snapshot of https://github.com/espocrm/espocrm.git (master, 2026-09-18; blobs > 131072B omitted)
Some checks failed
Test / Test on PHP 8.3 (push) Failing after 5s
Test / Test on PHP 8.4 (push) Failing after 4s
Test / Test on PHP 8.5 (push) Failing after 3s
TypeScript static analysis / TypeScript check (push) Failing after 14s
Test Integration on MySQL / Test on PHP 8.3 (push) Failing after 2s
Test Integration on MySQL / Test on PHP 8.5 (push) Failing after 0s
Test Integration on PostgreSQL / Test on PHP 8.4 fix (push) Failing after 1s
Test Integration on PostgreSQL / Test on PHP 8.4 master (push) Failing after 1s

This commit is contained in:
upstream-mirror
2026-09-18 04:19:15 +05:00
commit 7cc7e6b4f3
10077 changed files with 900756 additions and 0 deletions

View File

@@ -0,0 +1,125 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Attachment;
use Espo\Core\Acl;
use Espo\Core\Acl\Table;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Utils\Metadata;
use Espo\Entities\Attachment;
use Espo\Entities\Settings;
use Espo\Entities\User;
use Espo\Core\ORM\Type\FieldType;
class AccessChecker
{
/** @var string[] */
private $adminOnlyHavingInlineAttachmentsEntityTypeList = ['TemplateManager'];
/** @var string[] */
private $attachmentFieldTypeList = [
FieldType::FILE,
FieldType::IMAGE,
FieldType::ATTACHMENT_MULTIPLE,
];
/** @var string[] */
private $inlineAttachmentFieldTypeList = [
FieldType::WYSIWYG,
];
/** @var string[] */
private $allowedRoleList = [
Attachment::ROLE_ATTACHMENT,
Attachment::ROLE_INLINE_ATTACHMENT,
];
public function __construct(
private User $user,
private Acl $acl,
private Metadata $metadata
) {}
/**
* Check access to a field and role allowance.
*
* @throws Forbidden
*/
public function check(FieldData $fieldData, string $role = Attachment::ROLE_ATTACHMENT): void
{
if (!in_array($role, $this->allowedRoleList)) {
throw new Forbidden("Role not allowed.");
}
$relatedEntityType = $fieldData->getParentType() ?? $fieldData->getRelatedType();
$field = $fieldData->getField();
if (!$relatedEntityType) {
throw new Forbidden();
}
if (
$this->user->isEffectiveAdmin() &&
$role === Attachment::ROLE_INLINE_ATTACHMENT &&
in_array($relatedEntityType, $this->adminOnlyHavingInlineAttachmentsEntityTypeList)
) {
return;
}
$fieldType = $this->metadata->get(['entityDefs', $relatedEntityType, 'fields', $field, 'type']);
if (!$fieldType) {
throw new Forbidden("Field '$field' does not exist.");
}
$fieldTypeList = $role === Attachment::ROLE_INLINE_ATTACHMENT ?
$this->inlineAttachmentFieldTypeList :
$this->attachmentFieldTypeList;
if (!in_array($fieldType, $fieldTypeList)) {
throw new Forbidden("Field type '$fieldType' is not allowed for $role.");
}
if ($this->user->isEffectiveAdmin() && $relatedEntityType === Settings::ENTITY_TYPE) {
return;
}
if (
!$this->acl->checkScope($relatedEntityType, Table::ACTION_CREATE) &&
!$this->acl->checkScope($relatedEntityType, Table::ACTION_EDIT)
) {
throw new Forbidden("No access to " . $relatedEntityType . ".");
}
if (!$this->acl->checkField($relatedEntityType, $field, Table::ACTION_EDIT)) {
throw new Forbidden("No access to field '$field'.");
}
}
}

View File

@@ -0,0 +1,69 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Attachment\Api;
use Espo\Core\Api\Action as ActionAlias;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Tools\Attachment\Service;
/**
* Download a file.
*/
class GetFile implements ActionAlias
{
public function __construct(private Service $service) {}
public function process(Request $request): Response
{
$id = $request->getRouteParam('id');
if (!$id) {
throw new BadRequest();
}
$fileData = $this->service->getFileData($id);
$fileName = str_replace("\"", "\\\"", $fileData->getName() ?? '');
$response = ResponseComposer::empty()
->setHeader('Content-Disposition', 'attachment; filename="' . $fileName . '"')
->setHeader('Content-Length', (string) $fileData->getSize())
->setBody($fileData->getStream());
if ($fileData->getType()) {
$response->setHeader('Content-Type', $fileData->getType());
}
return $response;
}
}

View File

@@ -0,0 +1,59 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Attachment\Api;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Tools\Attachment\UploadService;
/**
* Uploads attachment chunks.
*/
class PostChunk implements Action
{
public function __construct(private UploadService $uploadService) {}
public function process(Request $request): Response
{
$id = $request->getRouteParam('id');
$body = $request->getBodyContents();
if (!$id || !$body) {
throw new BadRequest();
}
$this->uploadService->uploadChunk($id, $body);
return ResponseComposer::json(true);
}
}

View File

@@ -0,0 +1,76 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Attachment\Api;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Error;
use Espo\Tools\Attachment\FieldData;
use Espo\Tools\Attachment\Service;
/**
* Copies attachments.
*/
class PostCopy implements Action
{
public function __construct(private Service $service) {}
public function process(Request $request): Response
{
$id = $request->getRouteParam('id');
if (!$id) {
throw new BadRequest();
}
$data = $request->getParsedBody();
$field = $data->field ?? null;
$parentType = $data->parentType ?? null;
$relatedType = $data->relatedType ?? null;
if (!$field) {
throw new BadRequest("No `field`.");
}
try {
$fieldData = new FieldData($field, $parentType, $relatedType);
} catch (Error $e) {
throw new BadRequest($e->getMessage());
}
$attachment = $this->service->copy($id, $fieldData);
return ResponseComposer::json($attachment->getValueMap());
}
}

View File

@@ -0,0 +1,71 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Attachment\Api;
use Espo\Core\Api\Action;
use Espo\Core\Api\Request;
use Espo\Core\Api\Response;
use Espo\Core\Api\ResponseComposer;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Error;
use Espo\Tools\Attachment\FieldData;
use Espo\Tools\Attachment\UploadUrlService;
/**
* Crates attachments from image URLs.
*/
class PostFromImageUrl implements Action
{
public function __construct(private UploadUrlService $uploadUrlService) {}
public function process(Request $request): Response
{
$data = $request->getParsedBody();
$url = $data->url ?? null;
$field = $data->field ?? null;
$parentType = $data->parentType ?? null;
$relatedType = $data->relatedType ?? null;
if (!$url || !$field) {
throw new BadRequest("No `url` or `field`.");
}
try {
$fieldData = new FieldData($field, $parentType, $relatedType);
} catch (Error $e) {
throw new BadRequest($e->getMessage());
}
$attachment = $this->uploadUrlService->uploadImage($url, $fieldData);
return ResponseComposer::json($attachment->getValueMap());
}
}

View File

@@ -0,0 +1,161 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Attachment;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Exceptions\ForbiddenSilent;
use Espo\Core\Utils\File\MimeType;
use Espo\Core\Utils\Metadata;
use Espo\Entities\Attachment;
use Espo\Core\ORM\Type\FieldType;
class Checker
{
public function __construct(
private Metadata $metadata,
private MimeType $mimeType,
private DetailsObtainer $detailsObtainer
) {}
/**
* Check a mine-type for allowance.
*
* @throws Forbidden
*/
public function checkType(Attachment $attachment): void
{
$field = $attachment->getTargetField();
$entityType = $attachment->getParentType() ?? $attachment->getRelatedType();
if (!$field || !$entityType) {
return;
}
if (
$this->detailsObtainer->getFieldType($attachment) === FieldType::IMAGE ||
$attachment->getRole() === Attachment::ROLE_INLINE_ATTACHMENT
) {
$this->checkTypeImage($attachment);
return;
}
$extension = strtolower(DetailsObtainer::getFileExtension($attachment) ?? '');
$mimeType = $this->mimeType->getMimeTypeByExtension($extension) ??
$attachment->getType();
/** @var string[] $accept */
$accept = $this->metadata->get(['entityDefs', $entityType, 'fields', $field, 'accept']) ?? [];
if ($accept === []) {
return;
}
$found = false;
foreach ($accept as $token) {
if (strtolower($token) === '.' . $extension) {
$found = true;
break;
}
if ($mimeType && MimeType::matchMimeTypeToAcceptToken($mimeType, $token)) {
$found = true;
break;
}
}
if (!$found) {
throw new ForbiddenSilent("Not allowed file type.");
}
}
/**
* Check a mime-time for allowance for an image.
*
* @throws Forbidden
*/
public function checkTypeImage(Attachment $attachment, ?string $filePath = null): void
{
$extension = DetailsObtainer::getFileExtension($attachment) ?? '';
$mimeType = $this->mimeType->getMimeTypeByExtension($extension);
/** @var string[] $imageTypeList */
$imageTypeList = $this->metadata->get(['app', 'image', 'allowedFileTypeList']) ?? [];
if (!in_array($mimeType, $imageTypeList)) {
throw new ForbiddenSilent("Not allowed file type.");
}
$setMimeType = $attachment->getType();
if (strtolower($setMimeType ?? '') !== $mimeType) {
throw new ForbiddenSilent("Passed type does not correspond to extension.");
}
$this->checkDetectedMimeType($attachment, $filePath);
}
/**
* @throws Forbidden
*/
private function checkDetectedMimeType(Attachment $attachment, ?string $filePath = null): void
{
// ext-fileinfo required, otherwise bypass.
if (!class_exists('\finfo') || !defined('FILEINFO_MIME_TYPE')) {
return;
}
/** @var ?string $contents */
$contents = $attachment->get('contents');
if (!$contents && !$filePath) {
return;
}
$extension = DetailsObtainer::getFileExtension($attachment) ?? '';
$mimeTypeList = $this->mimeType->getMimeTypeListByExtension($extension);
$fileInfo = new \finfo(FILEINFO_MIME_TYPE);
$detectedMimeType = $filePath ?
$fileInfo->file($filePath) :
$fileInfo->buffer($contents);
if (!in_array($detectedMimeType, $mimeTypeList)) {
throw new ForbiddenSilent("Detected mime type does not correspond to extension.");
}
}
}

View File

@@ -0,0 +1,99 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Attachment;
use Espo\Core\Utils\Config;
use Espo\Core\Utils\Metadata;
use Espo\Entities\Attachment;
class DetailsObtainer
{
private Metadata $metadata;
private Config $config;
public function __construct(
Metadata $metadata,
Config $config
) {
$this->metadata = $metadata;
$this->config = $config;
}
/**
* Get a file extension.
*/
public static function getFileExtension(Attachment $attachment): ?string
{
$name = $attachment->getName() ?? '';
return array_slice(explode('.', $name), -1)[0] ?? null;
}
/**
* Get an upload max size allowed for an attachment (depending on a field it's related to).
*
* @return int A size in bytes.
*/
public function getUploadMaxSize(Attachment $attachment): int
{
if ($attachment->getRole() === Attachment::ROLE_INLINE_ATTACHMENT) {
return $this->config->get('inlineAttachmentUploadMaxSize') * 1024 * 1024;
}
$field = $attachment->getTargetField();
$parentType = $attachment->getParentType() ?? $attachment->getRelatedType();
if ($field && $parentType) {
$maxSize = ($this->metadata
->get(['entityDefs', $parentType, 'fields', $field, 'maxFileSize']) ?? 0) * 1024 * 1024;
if ($maxSize) {
return $maxSize;
}
}
return (int) $this->config->get('attachmentUploadMaxSize', 0) * 1024 * 1024;
}
/**
* Get a field type (an attachment if related to another record through the field).
*/
public function getFieldType(Attachment $attachment): ?string
{
$field = $attachment->getTargetField();
$entityType = $attachment->getParentType() ?? $attachment->getRelatedType();
if (!$field || !$entityType) {
return null;
}
return $this->metadata->get(['entityDefs', $entityType, 'fields', $field, 'type']);
}
}

View File

@@ -0,0 +1,74 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Attachment;
use Espo\Core\Exceptions\Error;
/**
* Immutable.
*/
class FieldData
{
private string $field;
private ?string $parentType;
private ?string $relatedType;
/**
* @throws Error
*/
public function __construct(
string $field,
?string $parentType,
?string $relatedType
) {
$this->field = $field;
$this->parentType = $parentType;
$this->relatedType = $relatedType;
if (!$parentType && !$relatedType) {
throw new Error("No parentType and relatedType.");
}
}
public function getField(): string
{
return $this->field;
}
public function getParentType(): ?string
{
return $this->parentType;
}
public function getRelatedType(): ?string
{
return $this->relatedType;
}
}

View File

@@ -0,0 +1,75 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Attachment;
use Psr\Http\Message\StreamInterface;
/**
* Immutable.
*/
class FileData
{
private ?string $name;
private ?string $type;
private StreamInterface $stream;
private int $size;
public function __construct(
?string $name,
?string $type,
StreamInterface $stream,
int $size
) {
$this->name = $name;
$this->type = $type;
$this->stream = $stream;
$this->size = $size;
}
public function getName(): ?string
{
return $this->name;
}
public function getType(): ?string
{
return $this->type;
}
public function getStream(): StreamInterface
{
return $this->stream;
}
public function getSize(): int
{
return $this->size;
}
}

View File

@@ -0,0 +1,118 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Attachment\Jobs;
use Espo\Core\Job\Job;
use Espo\Core\Job\Job\Data;
use Espo\Core\Job\JobSchedulerFactory;
use Espo\Core\Field\DateTime;
use Espo\Core\FileStorage\Storages\EspoUploadDir;
use Espo\Core\Utils\Config;
use Espo\Core\FileStorage\Manager as FileStorageManager;
use Espo\ORM\EntityManager;
use Espo\Entities\Attachment;
use LogicException;
class MoveToStorage implements Job
{
private const REMOVE_FILE_PERIOD = '3 hours';
private EntityManager $entityManager;
private Config $config;
private FileStorageManager $fileStorageManager;
private JobSchedulerFactory $jobSchedulerFactory;
public function __construct(
EntityManager $entityManager,
Config $config,
FileStorageManager $fileStorageManager,
JobSchedulerFactory $jobSchedulerFactory
) {
$this->entityManager = $entityManager;
$this->config = $config;
$this->fileStorageManager = $fileStorageManager;
$this->jobSchedulerFactory = $jobSchedulerFactory;
}
public function run(Data $data): void
{
$id = $data->getTargetId();
if (!$id) {
throw new LogicException();
}
/** @var Attachment|null $attachment */
$attachment = $this->entityManager->getEntityById(Attachment::ENTITY_TYPE, $id);
if (!$attachment) {
return;
}
if ($attachment->getStorage() !== EspoUploadDir::NAME) {
return;
}
$defaultFileStorage = $this->config->get('defaultFileStorage');
if (!$defaultFileStorage || $defaultFileStorage === EspoUploadDir::NAME) {
return;
}
$stream = $this->fileStorageManager->getStream($attachment);
$attachment->set('storage', $defaultFileStorage);
$this->fileStorageManager->putStream($attachment, $stream);
$this->entityManager->saveEntity($attachment);
$this->jobSchedulerFactory->create()
->setClassName(RemoveUploadDirFile::class)
->setData(
Data::create()
->withTargetId($attachment->getId())
)
->setTime(
DateTime::createNow()
->modify('+' . self::REMOVE_FILE_PERIOD)
->toDateTime()
)
->schedule();
}
}

View File

@@ -0,0 +1,102 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Attachment\Jobs;
use Espo\Core\Job\Job;
use Espo\Core\Job\Job\Data;
use Espo\Core\Utils\File\Manager as FileManager;
use Espo\Core\FileStorage\Factory as FileStorageFactory;
use Espo\Core\FileStorage\Storages\EspoUploadDir;
use Espo\Core\FileStorage\Local;
use Espo\Entities\Attachment;
use Espo\Core\FileStorage\AttachmentEntityWrapper;
use Espo\ORM\EntityManager;
use LogicException;
class RemoveUploadDirFile implements Job
{
private FileManager $fileManager;
private FileStorageFactory $fileStorageFactory;
private EntityManager $entityManager;
public function __construct(
FileManager $fileManager,
FileStorageFactory $fileStorageFactory,
EntityManager $entityManager
) {
$this->fileManager = $fileManager;
$this->fileStorageFactory = $fileStorageFactory;
$this->entityManager = $entityManager;
}
public function run(Data $data): void
{
$id = $data->getTargetId();
if (!$id) {
throw new LogicException();
}
/** @var Attachment|null $attachment */
$attachment = $this->entityManager->getEntityById(Attachment::ENTITY_TYPE, $id);
if (!$attachment) {
return;
}
if ($attachment->getStorage() === EspoUploadDir::NAME) {
return;
}
$storage = $this->fileStorageFactory->create(EspoUploadDir::NAME);
if (!$storage instanceof Local) {
throw new LogicException();
}
$filePath = $storage->getLocalFilePath(
new AttachmentEntityWrapper($attachment)
);
if (!$this->fileManager->isFile($filePath)) {
return;
}
$this->fileManager->remove($filePath);
}
}

View File

@@ -0,0 +1,117 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Attachment;
use Espo\Core\Exceptions\Error;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Exceptions\NotFound;
use Espo\Core\Record\ServiceContainer;
use Espo\Entities\Attachment;
use Espo\ORM\EntityManager;
use Espo\Repositories\Attachment as AttachmentRepository;
class Service
{
private ServiceContainer $recordServiceContainer;
private EntityManager $entityManager;
private AccessChecker $accessChecker;
public function __construct(
ServiceContainer $recordServiceContainer,
EntityManager $entityManager,
AccessChecker $accessChecker
) {
$this->recordServiceContainer = $recordServiceContainer;
$this->entityManager = $entityManager;
$this->accessChecker = $accessChecker;
}
/**
* Get file data (for downloading).
*
* @throws NotFound
* @throws Forbidden
*/
public function getFileData(string $id): FileData
{
/** @var ?Attachment $attachment */
$attachment = $this->recordServiceContainer
->get(Attachment::ENTITY_TYPE)
->getEntity($id);
if (!$attachment) {
throw new NotFound();
}
return new FileData(
$attachment->getName(),
$attachment->getType(),
$this->getAttachmentRepository()->getStream($attachment),
$this->getAttachmentRepository()->getSize($attachment)
);
}
/**
* Copy an attachment record (to reuse the same file w/o copying it in the storage).
*
* @throws Forbidden
* @throws NotFound
*/
public function copy(string $id, FieldData $data): Attachment
{
$this->accessChecker->check($data);
/** @var ?Attachment $attachment */
$attachment = $this->recordServiceContainer
->get(Attachment::ENTITY_TYPE)
->getEntity($id);
if (!$attachment) {
throw new NotFound();
}
$copied = $this->getAttachmentRepository()->getCopiedAttachment($attachment);
$copied->set('parentType', $data->getParentType());
$copied->set('relatedType', $data->getRelatedType());
$copied->setTargetField($data->getField());
$copied->setRole(Attachment::ROLE_ATTACHMENT);
$this->getAttachmentRepository()->save($copied);
return $copied;
}
private function getAttachmentRepository(): AttachmentRepository
{
/** @var AttachmentRepository */
return $this->entityManager->getRepositoryByClass(Attachment::class);
}
}

View File

@@ -0,0 +1,179 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Attachment;
use Espo\Core\Acl;
use Espo\Core\Acl\Table;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Error;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Exceptions\ForbiddenSilent;
use Espo\Core\Exceptions\NotFound;
use Espo\Core\FileStorage\Storages\EspoUploadDir;
use Espo\Core\Job\Job\Data as JobData;
use Espo\Core\Job\JobSchedulerFactory;
use Espo\Core\Record\ServiceContainer;
use Espo\Core\Utils\File\Manager as FileManager;
use Espo\Entities\Attachment;
use Espo\ORM\EntityManager;
use Espo\Repositories\Attachment as AttachmentRepository;
use Espo\Tools\Attachment\Jobs\MoveToStorage;
use Espo\Core\ORM\Type\FieldType;
class UploadService
{
private JobSchedulerFactory $jobSchedulerFactory;
private ServiceContainer $recordServiceContainer;
private Acl $acl;
private EntityManager $entityManager;
private FileManager $fileManager;
private DetailsObtainer $detailsObtainer;
private Checker $checker;
public function __construct(
JobSchedulerFactory $jobSchedulerFactory,
ServiceContainer $recordServiceContainer,
Acl $acl,
EntityManager $entityManager,
FileManager $fileManager,
DetailsObtainer $detailsObtainer,
Checker $checker
) {
$this->jobSchedulerFactory = $jobSchedulerFactory;
$this->recordServiceContainer = $recordServiceContainer;
$this->acl = $acl;
$this->entityManager = $entityManager;
$this->fileManager = $fileManager;
$this->detailsObtainer = $detailsObtainer;
$this->checker = $checker;
}
/**
* Upload a chunk.
*
* @throws BadRequest
* @throws Forbidden
* @throws Error
* @throws NotFound
*/
public function uploadChunk(string $id, string $fileData): void
{
if (!$this->acl->checkScope(Attachment::ENTITY_TYPE, Table::ACTION_CREATE)) {
throw new Forbidden();
}
/** @var ?Attachment $attachment */
$attachment = $this->recordServiceContainer
->get(Attachment::ENTITY_TYPE)
->getEntity($id);
if (!$attachment) {
throw new NotFound();
}
if (!$attachment->isBeingUploaded()) {
throw new Forbidden("Attachment is not being-uploaded.");
}
if ($attachment->getStorage() !== EspoUploadDir::NAME) {
throw new Forbidden("Attachment storage is not 'EspoUploadDir'.");
}
$arr = explode(';base64,', $fileData);
if (count($arr) < 2) {
throw new BadRequest("Bad file data.");
}
$contents = base64_decode($arr[1]);
$filePath = $this->getAttachmentRepository()->getFilePath($attachment);
$chunkSize = strlen($contents);
$actualFileSize = 0;
if ($this->fileManager->isFile($filePath)) {
$actualFileSize = $this->fileManager->getSize($filePath);
}
$maxFileSize = $this->detailsObtainer->getUploadMaxSize($attachment);
if ($actualFileSize + $chunkSize > $maxFileSize) {
throw new Forbidden("Max attachment size exceeded.");
}
$this->fileManager->appendContents($filePath, $contents);
if ($actualFileSize + $chunkSize > $attachment->getSize()) {
throw new Error("File size mismatch.");
}
$isLastChunk = $actualFileSize + $chunkSize === $attachment->getSize();
if (!$isLastChunk) {
return;
}
if ($this->detailsObtainer->getFieldType($attachment) === FieldType::IMAGE) {
try {
$this->checker->checkTypeImage($attachment, $filePath);
} catch (Forbidden $e) {
$this->entityManager->removeEntity($attachment);
throw new ForbiddenSilent($e->getMessage());
}
}
$attachment->set('isBeingUploaded', false);
$this->entityManager->saveEntity($attachment);
$this->createJobMoveToStorage($attachment);
}
private function getAttachmentRepository(): AttachmentRepository
{
/** @var AttachmentRepository */
return $this->entityManager->getRepositoryByClass(Attachment::class);
}
private function createJobMoveToStorage(Attachment $attachment): void
{
$this->jobSchedulerFactory
->create()
->setClassName(MoveToStorage::class)
->setData(
JobData::create()
->withTargetId($attachment->getId())
)
->schedule();
}
}

View File

@@ -0,0 +1,168 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM – Open Source CRM application.
* Copyright (C) 2014-2026 EspoCRM, Inc.
* Website: https://www.espocrm.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
namespace Espo\Tools\Attachment;
use Espo\Core\Exceptions\Error;
use Espo\Core\Exceptions\ErrorSilent;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Exceptions\ForbiddenSilent;
use Espo\Core\HttpClient\ClientFactory;
use Espo\Core\HttpClient\Options;
use Espo\Core\Utils\File\MimeType;
use Espo\Core\Utils\Metadata;
use Espo\Core\Utils\Security\UrlCheck;
use Espo\Entities\Attachment as Attachment;
use Espo\ORM\EntityManager;
use Espo\Repositories\Attachment as AttachmentRepository;
use Espo\Core\HttpClient;
use const PATHINFO_EXTENSION;
class UploadUrlService
{
public function __construct(
private AccessChecker $accessChecker,
private Metadata $metadata,
private EntityManager $entityManager,
private MimeType $mimeType,
private DetailsObtainer $detailsObtainer,
private UrlCheck $urlCheck,
private ClientFactory $clientFactory,
) {}
/**
* Upload an image from and URL and store as attachment.
*
* @param non-empty-string $url
* @throws Forbidden
* @throws Error
*/
public function uploadImage(string $url, FieldData $data): Attachment
{
if (!$this->urlCheck->isUrlAndNotInternal($url)) {
throw new ForbiddenSilent("Not allowed URL.");
}
$attachment = $this->getAttachmentRepository()->getNew();
$this->accessChecker->check($data);
[$type, $contents] = $this->getImageDataByUrl($url) ?? [null, null];
if (!$type || !$contents) {
throw new ErrorSilent("Bad image data.");
}
$attachment
->setName($url)
->setType($type)
->setContents($contents)
->setRole(Attachment::ROLE_ATTACHMENT)
->setTargetField($data->getField());
$attachment->set('parentType', $data->getParentType());
$attachment->set('relatedType', $data->getRelatedType());
$size = mb_strlen($contents, '8bit');
$maxSize = $this->detailsObtainer->getUploadMaxSize($attachment);
if ($maxSize && $size > $maxSize) {
throw new Error("File size should not exceed {$maxSize}Mb.");
}
$this->getAttachmentRepository()->save($attachment);
$attachment->clear('contents');
return $attachment;
}
/**
* @param non-empty-string $url
* @return ?array{string, string} A type and contents.
* @throws Error
*/
private function getImageDataByUrl(string $url): ?array
{
$client = $this->clientFactory->create(
new Options(
protocols: [HttpClient\Protocol::https, HttpClient\Protocol::http],
redirect: new HttpClient\Options\Redirect(
allow: false,
),
internalHostRestriction: new HttpClient\Options\InternalHostRestriction(
restrict: true,
),
)
);
$request = HttpClient\RequestCreator::create('GET', $url);
try {
$response = $client->send($request);
} catch (HttpClient\Exceptions\SendException $e) {
throw new Error(previous: $e);
}
$type = $response->getHeader('Content-Type')[0] ?? null;
if ($type) {
$type = trim(explode(';', $type)[0]);
}
if (!$type) {
/** @var string $extension */
$extension = preg_replace('#\?.*#', '', pathinfo($url, PATHINFO_EXTENSION));
$type = $this->mimeType->getMimeTypeByExtension($extension);
}
if (!$type) {
return null;
}
/** @var string[] $imageTypeList */
$imageTypeList = $this->metadata->get('app.image.allowedFileTypeList') ?? [];
if (!in_array($type, $imageTypeList)) {
return null;
}
return [$type, (string) $response->getBody()];
}
private function getAttachmentRepository(): AttachmentRepository
{
/** @var AttachmentRepository */
return $this->entityManager->getRepositoryByClass(Attachment::class);
}
}