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 1s
Test Integration on MySQL / Test on PHP 8.5 (push) Failing after 1s
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,44 @@
<?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\EntityManager;
readonly class CreateParams
{
/**
* @param array<string, string> $replaceData
*/
public function __construct(
public bool $forceCreate = false,
public array $replaceData = [],
public bool $skipCustomPrefix = false,
public bool $isNotRemovable = false,
public bool $addTab = true,
) {}
}

View File

@@ -0,0 +1,42 @@
<?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\EntityManager;
class DeleteParams
{
public function __construct(
private bool $forceRemove = false
) {}
public function forceRemove(): bool
{
return $this->forceRemove;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,41 @@
<?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\EntityManager\Hook;
use Espo\Core\Exceptions\Error;
use Espo\Tools\EntityManager\Params;
interface CreateHook
{
/**
* @throws Error
*/
public function process(Params $params): void;
}

View File

@@ -0,0 +1,41 @@
<?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\EntityManager\Hook;
use Espo\Core\Exceptions\Error;
use Espo\Tools\EntityManager\Params;
interface DeleteHook
{
/**
* @throws Error
*/
public function process(Params $params): void;
}

View File

@@ -0,0 +1,143 @@
<?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\EntityManager\Hook\Hooks;
use Espo\Core\Name\Field;
use Espo\Core\ORM\Type\FieldType;
use Espo\Core\Utils\Log;
use Espo\Core\Utils\Metadata;
use Espo\Entities\User;
use Espo\ORM\Type\RelationType;
use Espo\Tools\EntityManager\Hook\UpdateHook;
use Espo\Tools\EntityManager\Params;
/**
* @noinspection PhpUnused
*/
class AssignedUsersUpdateHook implements UpdateHook
{
private const PARAM = 'assignedUsers';
private const FIELD = Field::ASSIGNED_USERS;
private const RELATION_NAME = 'entityUser';
private const FIELD_ASSIGNED_USER = Field::ASSIGNED_USER;
private const DEFAULT_MAX_COUNT = 10;
public function __construct(
private Metadata $metadata,
private Log $log,
) {}
public function process(Params $params, Params $previousParams): void
{
if ($params->get(self::PARAM) && !$previousParams->get(self::PARAM)) {
$this->add($params->getName());
} else if (!$params->get(self::PARAM) && $previousParams->get(self::PARAM)) {
$this->remove($params->getName());
}
}
private function add(string $entityType): void
{
if ($this->metadata->get("entityDefs.$entityType.links." . self::FIELD . ".isCustom")) {
$this->log->warning("Cannot enable multiple assigned users for $entityType as the link already exists.");
return;
}
$this->metadata->set('entityDefs', $entityType, [
'fields' => [
self::FIELD => [
'type' => FieldType::LINK_MULTIPLE,
'view' => 'views/fields/assigned-users',
'maxCount' => self::DEFAULT_MAX_COUNT,
],
],
'links' => [
self::FIELD => [
'type' => RelationType::HAS_MANY,
'entity' => User::ENTITY_TYPE,
'relationName' => self::RELATION_NAME,
'layoutRelationshipsDisabled' => true,
],
],
]);
$this->metadata->set('entityAcl', $entityType, [
'links' => [
self::FIELD => [
'readOnly' => true,
],
],
]);
if ($this->metadata->get("entityDefs.$entityType.fields.assignedUser")) {
$this->metadata->set('entityDefs', $entityType, [
'fields' => [
self::FIELD_ASSIGNED_USER => [
'disabled' => true,
],
],
'links' => [
self::FIELD_ASSIGNED_USER => [
'disabled' => true,
],
],
]);
}
$this->metadata->save();
}
private function remove(string $entityType): void
{
$field = self::FIELD;
if (
$this->metadata->get("entityDefs.$entityType.links.$field.isCustom") &&
$this->metadata->get("entityDefs.$entityType.links.$field.relationName") !== self::RELATION_NAME
) {
return;
}
$this->metadata->delete('entityDefs', $entityType, [
'fields.' . self::FIELD,
'links.' . self::FIELD,
'fields.' . self::FIELD_ASSIGNED_USER . '.disabled',
'links.' . self::FIELD_ASSIGNED_USER . '.disabled',
]);
$this->metadata->delete('entityAcl', $entityType, [
'links.' . self::FIELD,
]);
$this->metadata->save();
}
}

View File

@@ -0,0 +1,53 @@
<?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\EntityManager\Hook\Hooks;
use Espo\Core\Exceptions\Conflict;
use Espo\Core\Exceptions\Error\Body;
use Espo\Tools\EntityManager\Hook\UpdateHook;
use Espo\Tools\EntityManager\Params;
/**
* @noinspection PhpUnused
*/
class CategoriesBeforeUpdateHook implements UpdateHook
{
private const string PARAM = 'categories';
public function process(Params $params, Params $previousParams): void
{
if ($params->get(self::PARAM) && $params->get('kanbanViewMode')) {
throw Conflict::createWithBody(
'cannotEnableCategoriesWithKanbanViewMode',
Body::create()->withMessageTranslation('cannotEnableCategoriesWithKanbanViewMode', 'EntityManager')
);
}
}
}

View File

@@ -0,0 +1,66 @@
<?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\EntityManager\Hook\Hooks;
use Espo\Core\Exceptions\Error;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Templates\Entities\Base;
use Espo\Core\Templates\Entities\BasePlus;
use Espo\Tools\EntityManager\Hook\DeleteHook;
use Espo\Tools\EntityManager\Params;
/**
* @noinspection PhpUnused
*/
class CategoriesDeleteHook implements DeleteHook
{
private const string PARAM = 'categories';
public function __construct(
private CategoriesUpdateHook $categoriesUpdateHook,
) {}
/**
* @throws Forbidden
* @throws Error
*/
public function process(Params $params): void
{
if (!in_array($params->getType(), [BasePlus::TEMPLATE_TYPE, Base::TEMPLATE_TYPE])) {
return;
}
if (!$params->get(self::PARAM)) {
return;
}
$this->categoriesUpdateHook->remove($params->getName());
}
}

View File

@@ -0,0 +1,207 @@
<?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\EntityManager\Hook\Hooks;
use Espo\Core\Binding\Attributes\Qualify;
use Espo\Core\DataManager;
use Espo\Core\Exceptions\BadRequest;
use Espo\Core\Exceptions\Conflict;
use Espo\Core\Exceptions\Error;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\InjectableFactory;
use Espo\Core\ORM\Type\FieldType;
use Espo\Core\Templates\Entities\Base;
use Espo\Core\Templates\Entities\BasePlus;
use Espo\Core\Templates\Entities\CategoryTree;
use Espo\Core\Utils\Language;
use Espo\Core\Utils\Log;
use Espo\Core\Utils\Metadata;
use Espo\ORM\Defs\Params\FieldParam;
use Espo\ORM\Defs\Params\RelationParam;
use Espo\ORM\Type\RelationType;
use Espo\Tools\EntityManager\CreateParams;
use Espo\Tools\EntityManager\DeleteParams;
use Espo\Tools\EntityManager\EntityManager;
use Espo\Tools\EntityManager\Hook\UpdateHook;
use Espo\Tools\EntityManager\Params;
use Espo\Tools\LayoutManager\LayoutCustomizer;
use Espo\Tools\LayoutManager\LayoutName;
/**
* @noinspection PhpUnused
*/
class CategoriesUpdateHook implements UpdateHook
{
private const string PARAM = 'categories';
private const string FIELD = 'category';
public function __construct(
private InjectableFactory $injectableFactory,
#[Qualify(Language::QUALIFIER_DEFAULT)]
private Language $defaultLanguage,
private Metadata $metadata,
private DataManager $dataManager,
private LayoutCustomizer $layoutCustomizer,
private Log $log,
) {}
/**
* @throws BadRequest
* @throws Forbidden
* @throws Error
* @throws Conflict
*/
public function process(Params $params, Params $previousParams): void
{
if (!in_array($params->getType(), [BasePlus::TEMPLATE_TYPE, Base::TEMPLATE_TYPE])) {
return;
}
if ($params->get(self::PARAM) && !$previousParams->get(self::PARAM)) {
$this->add($params->getName());
} else if (!$params->get(self::PARAM) && $previousParams->get(self::PARAM)) {
$this->remove($params->getName());
}
}
/**
* @throws BadRequest
* @throws Conflict
* @throws Error
*/
private function add(string $name): void
{
$entityType = $this->composeEntityType($name);
if ($this->metadata->get("scopes.$entityType")) {
$message = "Could not create category entity type $entityType as the same entity type exists";
$this->log->warning($message);
return;
}
$createParams = new CreateParams(
forceCreate: true,
replaceData: [
'subjectEntityType' => $name,
],
skipCustomPrefix: true,
isNotRemovable: true,
addTab: false,
);
$this->getEntityManagerTool()->create(
name: $entityType,
type: CategoryTree::TEMPLATE_TYPE,
params: [
'labelSingular' => $this->defaultLanguage->translateLabel($name, 'scopeNames') . ' ' .
$this->defaultLanguage->translateLabel('Category', 'entityNameParts', 'EntityManager'),
'labelPlural' => $this->defaultLanguage->translateLabel($name, 'scopeNames') . ' ' .
$this->defaultLanguage->translateLabel('Category', 'entityNamePartsPlural', 'EntityManager')
],
createParams: $createParams,
);
$this->metadata->set('entityDefs', $name, [
'fields' => [
self::FIELD => [
FieldParam::TYPE => FieldType::LINK,
'audited' => true,
'view' => 'views/fields/link-category-tree'
]
],
'links' => [
self::FIELD => [
RelationParam::TYPE => RelationType::BELONGS_TO,
RelationParam::ENTITY => $entityType,
]
],
]);
$this->metadata->set('clientDefs', $name, [
'views' => [
'list' => 'views/list-with-categories',
],
'modalViews' => [
'select' => 'views/modals/select-records-with-categories',
],
]);
$this->metadata->save();
$this->dataManager->rebuild([$entityType]);
$this->dataManager->rebuild([$name]);
$this->layoutCustomizer->addDetailField($name, self::FIELD, LayoutName::DETAIL);
$this->layoutCustomizer->addDetailField($name, self::FIELD, LayoutName::DETAIL_SMALL);
}
/**
* @throws Forbidden
* @throws Error
*/
public function remove(string $name): void
{
$entityType = $this->composeEntityType($name);
$deleteParams = new DeleteParams(
forceRemove: true,
);
$this->getEntityManagerTool()->delete($entityType, $deleteParams);
$this->metadata->delete('entityDefs', $name, [
'fields.' . self::FIELD,
'links.' . self::FIELD,
]);
$this->metadata->delete('clientDefs', $name, [
'views.list',
'modalViews.select',
]);
$this->metadata->save();
$this->dataManager->rebuild([$entityType]);
$this->dataManager->rebuild([$name]);
$this->layoutCustomizer->removeInDetail($name, self::FIELD, LayoutName::DETAIL);
$this->layoutCustomizer->removeInDetail($name, self::FIELD, LayoutName::DETAIL_SMALL);
}
private function getEntityManagerTool(): EntityManager
{
return $this->injectableFactory->create(EntityManager::class);
}
private function composeEntityType(string $name): string
{
return $name . 'Category';
}
}

View File

@@ -0,0 +1,201 @@
<?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\EntityManager\Hook\Hooks;
use Espo\Core\DataManager;
use Espo\Core\Exceptions\Error;
use Espo\Core\Name\Field;
use Espo\Core\ORM\Type\FieldType;
use Espo\Core\Utils\Log;
use Espo\Core\Utils\Metadata;
use Espo\Entities\User;
use Espo\Modules\Crm\Entities\CaseObj;
use Espo\Modules\Crm\Entities\Task;
use Espo\ORM\Defs\Params\FieldParam;
use Espo\ORM\Defs\Params\RelationParam;
use Espo\ORM\Type\RelationType;
use Espo\Tools\EntityManager\Hook\UpdateHook;
use Espo\Tools\EntityManager\Params;
/**
* @noinspection PhpUnused
*/
class CollaboratorsUpdateHook implements UpdateHook
{
private const PARAM = 'collaborators';
private const FIELD = Field::COLLABORATORS;
private const RELATION_NAME = 'entityCollaborator';
private const DEFAULT_MAX_COUNT = 30;
/**
* @var string[]
*/
private array $enabledByDefaultEntityTypeList = [
CaseObj::ENTITY_TYPE,
Task::ENTITY_TYPE,
];
public function __construct(
private Metadata $metadata,
private Log $log,
private DataManager $dataManager,
) {}
/**
* @throws Error
*/
public function process(Params $params, Params $previousParams): void
{
if ($params->get(self::PARAM) && !$previousParams->get(self::PARAM)) {
$this->add($params->getName());
} else if (!$params->get(self::PARAM) && $previousParams->get(self::PARAM)) {
$this->remove($params->getName());
}
}
/**
* @throws Error
*/
private function add(string $entityType): void
{
if ($this->metadata->get("entityDefs.$entityType.links." . self::FIELD . ".isCustom")) {
$this->log->warning("Cannot enable collaborators for $entityType as the link already exists.");
return;
}
if ($this->isEnabledByDefault($entityType)) {
$this->addEnabledByDefault($entityType);
} else {
$this->addInternal($entityType);
}
$this->metadata->save();
$this->dataManager->rebuild([$entityType]);
}
private function remove(string $entityType): void
{
$field = self::FIELD;
if (
$this->metadata->get("entityDefs.$entityType.links.$field.isCustom") &&
$this->metadata->get("entityDefs.$entityType.links.$field.relationName") !== self::RELATION_NAME
) {
return;
}
$this->metadata->delete('entityDefs', $entityType, [
'fields.' . self::FIELD,
'links.' . self::FIELD,
]);
$this->metadata->delete('entityAcl', $entityType, [
'links.' . self::FIELD,
]);
$this->metadata->save();
// Must be after metadata is saved.
if ($this->isEnabledByDefault($entityType)) {
$this->metadata->set('entityDefs', $entityType, [
'fields' => [
self::FIELD => [
FieldParam::DISABLED => true,
],
],
'links' => [
self::FIELD => [
RelationParam::DISABLED => true,
],
],
]);
$this->metadata->save();
}
}
private function addInternal(string $entityType): void
{
$this->metadata->set('entityDefs', $entityType, [
'fields' => [
self::FIELD => [
'type' => FieldType::LINK_MULTIPLE,
'view' => 'views/fields/collaborators',
'maxCount' => self::DEFAULT_MAX_COUNT,
'fieldManagerParamList' => [
'readOnly',
'readOnlyAfterCreate',
'audited',
'autocompleteOnEmpty',
'maxCount',
'inlineEditDisabled',
'tooltipText',
]
],
],
'links' => [
self::FIELD => [
'type' => RelationType::HAS_MANY,
'entity' => User::ENTITY_TYPE,
RelationParam::RELATION_NAME => self::RELATION_NAME,
'layoutRelationshipsDisabled' => true,
RelationParam::READ_ONLY => true,
],
],
]);
$this->metadata->set('entityAcl', $entityType, [
'links' => [
self::FIELD => [
'readOnly' => true,
],
],
]);
}
private function addEnabledByDefault(string $entityType): void
{
$this->metadata->delete('entityDefs', $entityType, [
'fields.' . self::FIELD,
'links.' . self::FIELD,
]);
}
/**
* @param string $entityType
* @return bool
*/
private function isEnabledByDefault(string $entityType): bool
{
return in_array($entityType, $this->enabledByDefaultEntityTypeList);
}
}

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\EntityManager\Hook\Hooks;
use Espo\Core\Utils\Metadata;
use Espo\ORM\Defs\Params\RelationParam;
use Espo\ORM\Type\RelationType;
use Espo\Tools\EntityManager\Hook\DeleteHook;
use Espo\Tools\EntityManager\Params;
/**
* @noinspection PhpUnused
*/
class DeleteHasChildrenLinks implements DeleteHook
{
public function __construct(
private Metadata $metadata,
) {}
public function process(Params $params): void
{
/** @var array<string, array<string, mixed>> $entityDefs */
$entityDefs = $this->metadata->get('entityDefs', []);
foreach ($entityDefs as $entityType => $defs) {
/** @var array<string, array<string, mixed>> $links */
$links = $defs['links'] ?? [];
foreach ($links as $link => $linkDefs) {
$isCustom = $linkDefs['isCustom'] ?? false;
$foreignEntityType = $linkDefs[RelationParam::ENTITY] ?? null;
$type = $linkDefs[RelationParam::TYPE] ?? null;
if (
!$isCustom ||
$foreignEntityType !== $params->getName() ||
$type !== RelationType::HAS_CHILDREN
) {
continue;
}
$this->metadata->delete('entityDefs', $entityType, "links.$link");
}
}
$this->metadata->save();
}
}

View File

@@ -0,0 +1,78 @@
<?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\EntityManager\Hook\Hooks;
use Espo\Core\Binding\Attributes\Qualify;
use Espo\Core\Templates\Entities\Event;
use Espo\Core\Utils\Language;
use Espo\Tools\EntityManager\Hook\CreateHook;
use Espo\Tools\EntityManager\Params;
class EventCreateHook implements CreateHook
{
public function __construct(
#[Qualify(Language::QUALIFIER_BASE)]
private Language $baseLanguage,
private Language $language
) {}
public function process(Params $params): void
{
if ($params->getType() !== Event::TEMPLATE_TYPE) {
return;
}
$this->translate($this->baseLanguage, $params);
if ($this->baseLanguage->getLanguage() === $this->language->getLanguage()) {
return;
}
$this->translate($this->language, $params);
}
private function translate(Language $language, Params $params): void
{
$name = $params->getName();
$label1 = 'Schedule ' . $name;
$label2 = 'Log ' . $name;
$translatedName = $params->get('labelSingular') ?? $name;
$translation1 = $language->translateLabel('Schedule') . ' ' . $translatedName;
$translation2 = $language->translateLabel('Log') . ' ' . $translatedName;
$language->set('Global', 'labels', $label1, $translation1);
$language->set('Global', 'labels', $label2, $translation2);
$language->save();
}
}

View File

@@ -0,0 +1,68 @@
<?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\EntityManager\Hook\Hooks;
use Espo\Core\Binding\Attributes\Qualify;
use Espo\Core\Templates\Entities\Event;
use Espo\Core\Utils\Language;
use Espo\Tools\EntityManager\Hook\DeleteHook;
use Espo\Tools\EntityManager\Params;
class EventDeleteHook implements DeleteHook
{
public function __construct(
#[Qualify(Language::QUALIFIER_BASE)]
private Language $baseLanguage,
private Language $language
) {}
public function process(Params $params): void
{
if (
$params->getType() !== Event::TEMPLATE_TYPE
) {
return;
}
$name = $params->getName();
$label1 = 'Schedule ' . $name;
$label2 = 'Log ' . $name;
$this->baseLanguage->delete('Global', 'labels', $label1);
$this->baseLanguage->delete('Global', 'labels', $label2);
$this->language->delete('Global', 'labels', $label1);
$this->language->delete('Global', 'labels', $label2);
$this->baseLanguage->save();
$this->language->save();
}
}

View File

@@ -0,0 +1,148 @@
<?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\EntityManager\Hook\Hooks;
use Espo\Core\DataManager;
use Espo\Core\Exceptions\Error;
use Espo\Core\Name\Field;
use Espo\Core\ORM\Type\FieldType;
use Espo\Core\Utils\Log;
use Espo\Core\Utils\Metadata;
use Espo\Modules\Crm\Entities\Account;
use Espo\ORM\Defs\Params\FieldParam;
use Espo\Tools\EntityManager\Hook\UpdateHook;
use Espo\Tools\EntityManager\Params;
/**
* @noinspection PhpUnused
*/
class LockableUpdateHook implements UpdateHook
{
private const string PARAM = 'lockable';
private const string FIELD = Field::IS_LOCKED;
/** @var string[] */
private array $enabledByDefaultEntityTypeList = [
Account::ENTITY_TYPE,
];
public function __construct(
private Metadata $metadata,
private Log $log,
private DataManager $dataManager,
) {}
public function process(Params $params, Params $previousParams): void
{
if ($params->get(self::PARAM) && !$previousParams->get(self::PARAM)) {
$this->add($params->getName());
} else if (!$params->get(self::PARAM) && $previousParams->get(self::PARAM)) {
$this->remove($params->getName());
}
}
/**
* @throws Error
*/
private function add(string $entityType): void
{
if ($this->metadata->get("entityDefs.$entityType.fields." . self::FIELD . ".isCustom")) {
$this->log->warning("Cannot enable lockable for $entityType as the field already exists.");
return;
}
if ($this->isEnabledByDefault($entityType)) {
$this->addEnabledByDefault($entityType);
} else {
$this->addInternal($entityType);
}
$this->metadata->save();
$this->dataManager->rebuild([$entityType]);
}
private function addEnabledByDefault(string $entityType): void
{
$this->metadata->delete('entityDefs', $entityType, [
'fields.' . self::FIELD,
]);
}
private function addInternal(string $entityType): void
{
$this->metadata->set('entityDefs', $entityType, [
'fields' => [
self::FIELD => [
FieldParam::TYPE => FieldType::BOOL,
FieldParam::READ_ONLY => true,
'audited' => true,
'fieldManagerParamList' => [
'audited',
'tooltipText',
],
'layoutAvailabilityList' => [
'filters',
'list',
],
],
]
]);
}
private function remove(string $entityType): void
{
$this->metadata->delete('entityDefs', $entityType, [
'fields.' . self::FIELD,
]);
$this->metadata->save();
// Must be after metadata is saved.
if ($this->isEnabledByDefault($entityType)) {
$this->metadata->set('entityDefs', $entityType, [
'fields' => [
self::FIELD => [
FieldParam::DISABLED => true,
],
],
]);
$this->metadata->save();
}
}
private function isEnabledByDefault(string $entityType): bool
{
return in_array($entityType, $this->enabledByDefaultEntityTypeList);
}
}

View File

@@ -0,0 +1,53 @@
<?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\EntityManager\Hook\Hooks;
use Espo\Core\Exceptions\Conflict;
use Espo\Core\Exceptions\Error\Body;
use Espo\Tools\EntityManager\Hook\UpdateHook;
use Espo\Tools\EntityManager\Params;
/**
* @noinspection PhpUnused
*/
class PipelinesBeforeUpdateHook implements UpdateHook
{
private const string PARAM = 'pipelines';
public function process(Params $params, Params $previousParams): void
{
if ($params->get(self::PARAM) && !$params->get('statusField')) {
throw Conflict::createWithBody(
'cannotEnablePipelinesWithNoStatusField',
Body::create()->withMessageTranslation('cannotEnablePipelinesWithNoStatusField', 'EntityManager')
);
}
}
}

View File

@@ -0,0 +1,201 @@
<?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\EntityManager\Hook\Hooks;
use Espo\Classes\Acl\Common\Pipeline\PipelineLinkChecker;
use Espo\Classes\Acl\Common\Pipeline\PipelineStageLinkChecker;
use Espo\Classes\FieldValidators\Common\PipelineStage\Valid;
use Espo\Core\DataManager;
use Espo\Core\Exceptions\Error;
use Espo\Core\Name\Field;
use Espo\Core\ORM\Type\FieldType;
use Espo\Core\Utils\Log;
use Espo\Core\Utils\Metadata;
use Espo\Entities\Pipeline;
use Espo\Entities\PipelineStage;
use Espo\ORM\Defs\Params\FieldParam;
use Espo\ORM\Type\RelationType;
use Espo\Tools\EntityManager\Hook\UpdateHook;
use Espo\Tools\EntityManager\Params;
use Espo\Tools\LayoutManager\LayoutCustomizer;
use Espo\Tools\LayoutManager\LayoutName;
/**
* @noinspection PhpUnused
*/
class PipelinesUpdateHook implements UpdateHook
{
private const string PARAM = 'pipelines';
public function __construct(
private Metadata $metadata,
private DataManager $dataManager,
private LayoutCustomizer $layoutCustomizer,
private Log $log,
) {}
public function process(Params $params, Params $previousParams): void
{
if ($params->get(self::PARAM) && !$previousParams->get(self::PARAM)) {
$this->add($params->getName());
} else if (!$params->get(self::PARAM) && $previousParams->get(self::PARAM)) {
$this->remove($params->getName());
}
}
/**
* @throws Error
*/
private function add(string $entityType): void
{
if ($this->metadata->get("entityDefs.$entityType.links." . Field::PIPELINE . ".isCustom")) {
$this->log->warning("Cannot enable pipelines for $entityType as the link already exists.");
return;
}
$this->metadata->set('entityDefs', $entityType, [
'fields' => [
Field::PIPELINE => [
FieldParam::TYPE => FieldType::LINK,
FieldParam::REQUIRED => true,
'audited' => true,
'inlineEditDisabled' => true,
'fieldManagerParamList' => [
FieldParam::READ_ONLY_AFTER_CREATE,
'audited',
'tooltipText',
],
'view' => 'views/fields/extra/pipeline',
],
Field::PIPELINE_STAGE => [
FieldParam::TYPE => FieldType::LINK,
FieldParam::REQUIRED => true,
'audited' => true,
'validationDependsOnFieldList' => [
Field::PIPELINE,
],
'validatorClassNameList' => [
Valid::class,
],
'fieldManagerParamList' => [
'audited',
'tooltipText',
'inlineEditDisabled',
],
'view' => 'views/fields/extra/pipeline-stage',
'dynamicLogicConditionTypeList' => [
'isEmpty',
'isNotEmpty',
]
],
],
'links' => [
Field::PIPELINE => [
'type' => RelationType::BELONGS_TO,
'entity' => Pipeline::ENTITY_TYPE,
],
Field::PIPELINE_STAGE => [
'type' => RelationType::BELONGS_TO,
'entity' => PipelineStage::ENTITY_TYPE,
],
],
]);
$this->metadata->set('aclDefs', $entityType, [
'linkCheckerClassNameMap' => [
Field::PIPELINE => PipelineLinkChecker::class,
Field::PIPELINE_STAGE => PipelineStageLinkChecker::class,
],
]);
$this->metadata->set('selectDefs', $entityType, [
'selectAttributesDependencyMap' => [
Field::PIPELINE_STAGE . 'Id' => [
Field::PIPELINE . 'Id',
]
]
]);
$this->metadata->save();
$this->dataManager->rebuild([$entityType]);
$this->layoutCustomizer->addDetailField($entityType, Field::PIPELINE, LayoutName::DETAIL);
$this->layoutCustomizer->addDetailField($entityType, Field::PIPELINE_STAGE, LayoutName::DETAIL);
$this->layoutCustomizer->addDetailField($entityType, Field::PIPELINE, LayoutName::DETAIL_SMALL);
$this->layoutCustomizer->addDetailField($entityType, Field::PIPELINE_STAGE, LayoutName::DETAIL_SMALL);
}
/**
* @throws Error
*/
private function remove(string $entityType): void
{
$field = Field::PIPELINE;
if (
$this->metadata->get("entityDefs.$entityType.links.$field.isCustom") &&
$this->metadata->get("entityDefs.$entityType.links.$field.entityType") !== Pipeline::ENTITY_TYPE
) {
return;
}
$this->metadata->delete('entityDefs', $entityType, [
'fields.' . Field::PIPELINE,
'fields.' . Field::PIPELINE_STAGE,
'links.' . Field::PIPELINE,
'links.' . Field::PIPELINE_STAGE,
]);
$this->metadata->delete('entityAcl', $entityType, [
'links.' . Field::PIPELINE,
'links.' . Field::PIPELINE_STAGE,
]);
$this->metadata->delete('aclDefs', $entityType, [
'linkCheckerClassNameMap.' . Field::PIPELINE,
'linkCheckerClassNameMap.' . Field::PIPELINE_STAGE,
]);
$this->metadata->delete('selectDefs', $entityType, [
'selectAttributesDependencyMap.' . Field::PIPELINE_STAGE . 'Id',
]);
$this->metadata->save();
$this->dataManager->rebuild([$entityType]);
$this->layoutCustomizer->removeInDetail($entityType, Field::PIPELINE, LayoutName::DETAIL);
$this->layoutCustomizer->removeInDetail($entityType, Field::PIPELINE_STAGE, LayoutName::DETAIL);
$this->layoutCustomizer->removeInDetail($entityType, Field::PIPELINE, LayoutName::DETAIL_SMALL);
$this->layoutCustomizer->removeInDetail($entityType, Field::PIPELINE_STAGE, LayoutName::DETAIL_SMALL);
}
}

View File

@@ -0,0 +1,92 @@
<?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\EntityManager\Hook\Hooks;
use Espo\Core\Name\Field;
use Espo\Core\Templates\Entities\BasePlus;
use Espo\Core\Templates\Entities\Company;
use Espo\Core\Templates\Entities\Person;
use Espo\Core\Utils\Config;
use Espo\Core\Utils\Metadata;
use Espo\Modules\Crm\Entities\Task;
use Espo\Tools\EntityManager\Hook\CreateHook;
use Espo\Tools\EntityManager\Params;
class PlusCreateHook implements CreateHook
{
public function __construct(
private Config $config,
private Metadata $metadata
) {}
public function process(Params $params): void
{
if (
!in_array($params->getType(), [
BasePlus::TEMPLATE_TYPE,
Company::TEMPLATE_TYPE,
Person::TEMPLATE_TYPE,
])
) {
return;
}
$name = $params->getName();
$activitiesEntityTypeList = $this->config->get('activitiesEntityList', []);
$historyEntityTypeList = $this->config->get('historyEntityList', []);
$entityTypeList = array_merge($activitiesEntityTypeList, $historyEntityTypeList);
$entityTypeList[] = Task::ENTITY_TYPE;
$entityTypeList = array_unique($entityTypeList);
foreach ($entityTypeList as $entityType) {
if (!$this->metadata->get(['entityDefs', $entityType, 'fields', Field::PARENT, 'entityList'])) {
continue;
}
$list = $this->metadata->get(['entityDefs', $entityType, 'fields', Field::PARENT, 'entityList'], []);
if (!in_array($name, $list)) {
$list[] = $name;
$data = [
'fields' => [
Field::PARENT => ['entityList' => $list]
]
];
$this->metadata->set('entityDefs', $entityType, $data);
}
}
$this->metadata->save();
}
}

View File

@@ -0,0 +1,96 @@
<?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\EntityManager\Hook\Hooks;
use Espo\Core\Name\Field;
use Espo\Core\Templates\Entities\BasePlus;
use Espo\Core\Templates\Entities\Company;
use Espo\Core\Templates\Entities\Person;
use Espo\Core\Utils\Config;
use Espo\Core\Utils\Metadata;
use Espo\Modules\Crm\Entities\Task;
use Espo\Tools\EntityManager\Hook\CreateHook;
use Espo\Tools\EntityManager\Params;
class PlusDeleteHook implements CreateHook
{
public function __construct(
private Config $config,
private Metadata $metadata
) {}
public function process(Params $params): void
{
if (
!in_array($params->getType(), [
BasePlus::TEMPLATE_TYPE,
Company::TEMPLATE_TYPE,
Person::TEMPLATE_TYPE,
])
) {
return;
}
$name = $params->getName();
$activitiesEntityTypeList = $this->config->get('activitiesEntityList', []);
$historyEntityTypeList = $this->config->get('historyEntityList', []);
$entityTypeList = array_merge($activitiesEntityTypeList, $historyEntityTypeList);
$entityTypeList[] = Task::ENTITY_TYPE;
$entityTypeList = array_unique($entityTypeList);
foreach ($entityTypeList as $entityType) {
if (!$this->metadata->get(['entityDefs', $entityType, 'fields', Field::PARENT, 'entityList'])) {
continue;
}
$list = $this->metadata->get(['entityDefs', $entityType, 'fields', Field::PARENT, 'entityList'], []);
if (in_array($name, $list)) {
$key = array_search($name, $list);
unset($list[$key]);
$list = array_values($list);
$data = [
'fields' => [
'parent' => ['entityList' => $list]
]
];
$this->metadata->set('entityDefs', $entityType, $data);
}
}
$this->metadata->save();
}
}

View File

@@ -0,0 +1,57 @@
<?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\EntityManager\Hook\Hooks;
use Espo\Core\DataManager;
use Espo\Core\Exceptions\Error;
use Espo\Tools\EntityManager\Hook\UpdateHook;
use Espo\Tools\EntityManager\Params;
/**
* @noinspection PhpUnused
*/
class StreamUpdateHook implements UpdateHook
{
private const PARAM = 'stream';
public function __construct(
private DataManager $dataManager,
) {}
/**
* @throws Error
*/
public function process(Params $params, Params $previousParams): void
{
if ($params->get(self::PARAM) && !$previousParams->get(self::PARAM)) {
$this->dataManager->rebuild([$params->getName()]);
}
}
}

View File

@@ -0,0 +1,43 @@
<?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\EntityManager\Hook;
use Espo\Core\Exceptions\Conflict;
use Espo\Core\Exceptions\Error;
use Espo\Tools\EntityManager\Params;
interface UpdateHook
{
/**
* @throws Error
* @throws Conflict
*/
public function process(Params $params, Params $previousParams): void;
}

View File

@@ -0,0 +1,402 @@
<?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\EntityManager;
use Espo\Core\Exceptions\Error;
use Espo\Core\Name\Field;
use Espo\Core\Utils\Config;
use Espo\Core\Utils\Metadata;
use Espo\Core\Utils\Route;
use Espo\Core\Utils\Util;
use Espo\Core\ServiceFactory;
use Espo\ORM\Defs\Params\EntityParam;
use Espo\ORM\EntityManager;
use Espo\ORM\Entity;
use Espo\ORM\Name\Attribute;
class NameUtil
{
public const MAX_ENTITY_NAME_LENGTH = 64;
public const MIN_ENTITY_NAME_LENGTH = 3;
/**
* @var string[]
*/
public const RESERVED_WORLD_LIST = [
'__halt_compiler',
'abstract',
'and',
'array',
'as',
'break',
'callable',
'case',
'catch',
'class',
'clone',
'const',
'continue',
'declare',
'default',
'die',
'do',
'echo',
'else',
'elseif',
'empty',
'enddeclare',
'endfor',
'endforeach',
'endif',
'endswitch',
'endwhile',
'eval',
'exit',
'extends',
'final',
'for',
'foreach',
'function',
'global',
'goto',
'if',
'implements',
'include',
'include_once',
'instanceof',
'insteadof',
'interface',
'isset',
'list',
'namespace',
'new',
'or',
'print',
'private',
'protected',
'public',
'require',
'require_once',
'return',
'static',
'switch',
'throw',
'trait',
'try',
'unset',
'use',
'var',
'while',
'xor',
'common',
'fn',
'parent',
'int',
'float',
'bool',
'string',
'true',
'false',
'null',
'void',
'iterable',
'object',
'mixed',
'never',
];
/**
* @var string[]
*/
public const FIELD_FORBIDDEN_NAME_LIST = [
Attribute::ID,
Attribute::DELETED,
'deleteId',
'skipDuplicateCheck',
'null',
'false',
'true',
Field::VERSION_NUMBER,
Field::IS_STARRED,
Field::IS_FOLLOWED,
Field::FOLLOWERS,
Field::TEAMS,
Field::ASSIGNED_USER,
Field::ASSIGNED_USERS,
Field::COLLABORATORS,
Field::STREAM_UPDATED_AT,
Field::CREATED_BY,
Field::CREATED_AT,
Field::MODIFIED_BY,
Field::MODIFIED_AT,
Field::IS_LOCKED,
Field::PIPELINE,
Field::PIPELINE_STAGE,
'emailAddressList',
'userEmailAddressList',
'excludeFromReplyEmailAddressList',
];
/**
* @var string[]
*/
public const LINK_FORBIDDEN_NAME_LIST = [
'posts',
'stream',
'streamAttachments',
'subscription',
'starSubscription',
'action',
'null',
'false',
'true',
'layout',
'system',
Field::FOLLOWERS,
Field::TEAMS,
Field::ASSIGNED_USER,
Field::ASSIGNED_USERS,
Field::COLLABORATORS,
Field::CREATED_BY,
Field::MODIFIED_BY,
];
/**
* @var string[]
*/
public const ENTITY_TYPE_FORBIDDEN_NAME_LIST = [
'Common',
'PortalUser',
'ApiUser',
'Timeline',
'About',
'Admin',
'Null',
'False',
'True',
'Base',
'Layout',
'Home',
];
public function __construct(
private Metadata $metadata,
private ServiceFactory $serviceFactory,
private EntityManager $entityManager,
private Route $routeUtil,
private Config $config
) {}
public function nameIsBad(string $name): bool
{
if (!$name) {
return true;
}
if (preg_match('/[^a-zA-Z\d]/', $name)) {
return true;
}
if (preg_match('/[^A-Z]/', $name[0])) {
return true;
}
return false;
}
public function nameIsTooShort(string $name): bool
{
return strlen($name) < NameUtil::MIN_ENTITY_NAME_LENGTH;
}
public function nameIsTooLong(string $name): bool
{
return strlen(Util::camelCaseToUnderscore($name)) > NameUtil::MAX_ENTITY_NAME_LENGTH;
}
public function nameIsNotAllowed(string $name): bool
{
if (in_array($name, self::ENTITY_TYPE_FORBIDDEN_NAME_LIST)) {
return true;
}
if (in_array(strtolower($name), NameUtil::RESERVED_WORLD_LIST)) {
return true;
}
if ($name !== Util::normalizeScopeName($name)) {
return true;
}
return false;
}
public function nameIsUsed(string $name): bool
{
if ($this->metadata->get(['scopes', $name])) {
return true;
}
if ($this->metadata->get(['entityDefs', $name])) {
return true;
}
if ($this->metadata->get(['clientDefs', $name])) {
return true;
}
if ($this->relationshipExists($name)) {
return true;
}
if ($this->controllerExists($name)) {
return true;
}
if ($this->serviceFactory->checkExists($name)) {
return true;
}
if ($this->routeExists($name)) {
return true;
}
return false;
}
private function routeExists(string $name): bool
{
foreach ($this->routeUtil->getFullList() as $route) {
if (
$route->getRoute() === '/' . $name ||
str_starts_with($route->getRoute(), '/' . $name . '/')
) {
return true;
}
}
return false;
}
private function controllerExists(string $name): bool
{
$controllerClassName = 'Espo\\Custom\\Controllers\\' . Util::normalizeClassName($name);
if (class_exists($controllerClassName)) {
return true;
}
foreach ($this->metadata->getModuleList() as $moduleName) {
$controllerClassName =
'Espo\\Modules\\' . $moduleName . '\\Controllers\\' . Util::normalizeClassName($name);
if (class_exists($controllerClassName)) {
return true;
}
}
$controllerClassName = 'Espo\\Controllers\\' . Util::normalizeClassName($name);
if (class_exists($controllerClassName)) {
return true;
}
return false;
}
public function relationshipExists(string $name): bool
{
/** @var string[] $scopeList */
$scopeList = array_keys($this->metadata->get(['scopes'], []));
foreach ($scopeList as $entityType) {
$relationsDefs = $this->entityManager
->getMetadata()
->get($entityType, EntityParam::RELATIONS);
if (empty($relationsDefs)) {
continue;
}
foreach ($relationsDefs as $item) {
if (empty($item['type']) || empty($item['relationName'])) {
continue;
}
if (
$item['type'] === Entity::MANY_MANY &&
ucfirst($item['relationName']) === ucfirst($name)
) {
return true;
}
}
}
return false;
}
public function addCustomPrefix(string $name, bool $ucFirst = false): string
{
if ($this->config->get('customPrefixDisabled')) {
return $name;
}
$prefix = $ucFirst ? 'C' : 'c';
return $prefix . ucfirst($name);
}
public function fieldExists(string $entityType, string $name): bool
{
return (bool) $this->metadata->get("entityDefs.$entityType.fields.$name");
}
public function linkExists(string $entityType, string $name): bool
{
return (bool) $this->metadata->get("entityDefs.$entityType.links.$name");
}
/**
* @since 9.2.4
*/
public function linkNameIsBad(string $name): bool
{
if ($name === '') {
return true;
}
if (preg_match('/[^a-z]/', $name[0])) {
return true;
}
return $this->nameIsBad(ucfirst($name));
}
}

View File

@@ -0,0 +1,57 @@
<?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\EntityManager;
class Params
{
/**
* @param array<string, mixed> $params
*/
public function __construct(
private string $name,
private ?string $type,
private array $params,
) {}
public function get(string $name): mixed
{
return $this->params[$name] ?? null;
}
public function getType(): ?string
{
return $this->type;
}
public function getName(): string
{
return $this->name;
}
}

View File

@@ -0,0 +1,41 @@
<?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\EntityManager\Rename;
class ClassType
{
public const ENTITY = 'Entities';
public const CONTROLLER = 'Controllers';
public const REPOSITORY = 'Repositories';
public const SERVICE = 'Services';
}

View File

@@ -0,0 +1,53 @@
<?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\EntityManager\Rename;
class FailReason
{
public const ENV_NOT_SUPPORTED = 'envNotSupported';
public const TABLE_EXISTS = 'tableExists';
public const DOES_NOT_EXIST = 'doesNotExist';
public const NOT_CUSTOM = 'notCustom';
public const NAME_USED = 'nameUsed';
public const NAME_NOT_ALLOWED = 'nameIsNotAllosed';
public const NAME_BAD = 'nameBad';
public const NAME_TOO_LONG = 'nameTooLong';
public const NAME_TOO_SHORT = 'nameTooShort';
public const ERROR = 'error';
}

View File

@@ -0,0 +1,55 @@
<?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\EntityManager\Rename;
class MetadataType
{
public const ENTITY_DEFS = 'entityDefs';
public const SCOPES = 'scopes';
public const ACL_DEFS = 'aclDefs';
public const ENTITY_ACL = 'entityAcl';
public const CLIENT_DEFS = 'clientDefs';
public const SELECT_DEFS = 'selectDefs';
public const RECORD_DEFS = 'recordDefs';
public const NOTIFICATION_DEFS = 'notificationDefs';
public const PDF_DEFS = 'pdfDefs';
public const FORMULA = 'formula';
public const LOGIC_DEFS = 'logicDefs';
}

View File

@@ -0,0 +1,668 @@
<?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\EntityManager\Rename;
use Espo\Core\Console\IO;
use Espo\Core\ORM\Type\FieldType;
use Espo\Core\Utils\Metadata;
use Espo\Core\Utils\File\Manager as FileManager;
use Espo\Core\Utils\Util;
use Espo\Core\DataManager;
use Espo\Core\Utils\Config;
use Espo\Core\Utils\Config\ConfigWriter;
use Espo\Core\Utils\Language;
use Espo\Core\Utils\Log;
use Espo\Entities\PortalRole;
use Espo\Entities\Role;
use Espo\ORM\EntityManager;
use Espo\Tools\EntityManager\NameUtil;
use RuntimeException;
use Throwable;
class Renamer
{
/**
* @var array<int,ClassType::*>
*/
private $classTypeList = [
ClassType::ENTITY,
ClassType::CONTROLLER,
ClassType::REPOSITORY,
ClassType::SERVICE,
];
/**
* @var array<int,MetadataType::*>
*/
private $metadataTypeList = [
MetadataType::ACL_DEFS,
MetadataType::CLIENT_DEFS,
MetadataType::ENTITY_DEFS,
MetadataType::ENTITY_ACL,
MetadataType::FORMULA,
MetadataType::NOTIFICATION_DEFS,
MetadataType::PDF_DEFS,
MetadataType::RECORD_DEFS,
MetadataType::SCOPES,
MetadataType::SELECT_DEFS,
MetadataType::LOGIC_DEFS,
];
private NameUtil $nameUtil;
private Metadata $metadata;
private FileManager $fileManager;
private EntityManager $entityManager;
private DataManager $dataManager;
private Config $config;
private ConfigWriter $configWriter;
private Language $language;
private Log $log;
public function __construct(
NameUtil $nameUtil,
Metadata $metadata,
FileManager $fileManager,
EntityManager $entityManager,
DataManager $dataManager,
Config $config,
ConfigWriter $configWriter,
Language $language,
Log $log
) {
$this->nameUtil = $nameUtil;
$this->metadata = $metadata;
$this->fileManager = $fileManager;
$this->entityManager = $entityManager;
$this->dataManager = $dataManager;
$this->config = $config;
$this->configWriter = $configWriter;
$this->language = $language;
$this->log = $log;
}
public function process(string $entityType, string $newName, IO $io): Result
{
$failResult = $this->validate($entityType, $newName);
if ($failResult) {
return $failResult;
}
$io->writeLine(' DB table...');
$this->renameDbTable($entityType, $newName);
$io->writeLine(' DB many-to-many tables...');
$this->renameDbManyToMany($entityType, $newName);
$io->writeLine(' metadata relationships...');
$this->renameInRelationships($entityType, $newName);
$io->writeLine(' metadata fields...');
$this->renameInFields($entityType, $newName);
$io->writeLine(' php classes...');
foreach ($this->classTypeList as $classType) {
$this->renameClass($classType, $entityType, $newName);
}
$io->writeLine(' metadata files...');
foreach ($this->metadataTypeList as $metadataType) {
$this->renameMetadata($metadataType, $entityType, $newName);
}
$io->writeLine(' layouts...');
$this->renameLayouts($entityType, $newName);
$io->writeLine(' values in DB...');
$this->changeValuesInDb($entityType, $newName);
$io->writeLine(' language...');
$this->renameLanguage($entityType, $newName);
$io->writeLine(' config parameters...');
$this->renameInConfig($entityType, $newName);
$io->writeLine(' rebuild...');
$this->dataManager->rebuild();
return Result::createSuccess();
}
private function validate(string $entityType, string $newName): ?Result
{
if (!$this->metadata->get(['scopes', $entityType, 'entity'])) {
return Result::createFail(FailReason::DOES_NOT_EXIST);
}
if (!$this->metadata->get(['scopes', $entityType, 'isCustom'])) {
return Result::createFail(FailReason::NOT_CUSTOM);
}
if ($this->nameUtil->nameIsBad($newName)) {
return Result::createFail(FailReason::NAME_BAD);
}
/** @var non-empty-string $newName */
if ($this->nameUtil->nameIsTooLong($newName)) {
return Result::createFail(FailReason::NAME_TOO_LONG);
}
if ($this->nameUtil->nameIsTooShort($newName)) {
return Result::createFail(FailReason::NAME_TOO_SHORT);
}
if ($this->nameUtil->nameIsNotAllowed($newName)) {
return Result::createFail(FailReason::NAME_NOT_ALLOWED);
}
if ($this->nameUtil->nameIsUsed($newName)) {
return Result::createFail(FailReason::NAME_USED);
}
if (!$this->fileManager->isFile($this->getClassFilePath(ClassType::CONTROLLER, $entityType))) {
return Result::createFail(FailReason::NOT_CUSTOM);
}
if (!$this->fileManager->isFile($this->getMetadataFilePath(MetadataType::ENTITY_DEFS, $entityType))) {
return Result::createFail(FailReason::NOT_CUSTOM);
}
if (!$this->fileManager->isFile($this->getMetadataFilePath(MetadataType::SCOPES, $entityType))) {
return Result::createFail(FailReason::NOT_CUSTOM);
}
if ($this->tableExists($newName)) {
return Result::createFail(FailReason::TABLE_EXISTS);
}
return null;
}
private function renameDbManyToMany(string $entityType, string $newName): void
{
$relationList = $this->entityManager
->getDefs()
->getEntity($entityType)
->getRelationList();
foreach ($relationList as $relation) {
if (!$relation->isManyToMany()) {
continue;
}
if (lcfirst($relation->getRelationshipName()) === 'entityTeam') {
continue;
}
$this->renameDbRelationshipTableColumn(
$relation->getRelationshipName(),
$entityType . 'Id',
$newName . 'Id'
);
}
}
/**
* @param ClassType::* $classType
*/
private function renameClass(string $classType, string $name, string $newName): void
{
$path = $this->getClassFilePath($classType, $name);
$newPath = $this->getClassFilePath($classType, $newName);
if (!$this->fileManager->isFile($path)) {
return;
}
$contents = $this->fileManager->getContents($path);
$replaceFrom = [
"class {$name}",
"'{$name}'",
];
$replaceTo = [
"class {$newName}",
"'{$newName}'",
];
$newContents = str_replace($replaceFrom, $replaceTo, $contents);
$this->fileManager->putContents($newPath, $newContents);
$this->fileManager->removeFile($path);
}
/**
* @param MetadataType::* $metadataType
*/
private function renameMetadata(string $metadataType, string $name, string $newName): void
{
$path = $this->getMetadataFilePath($metadataType, $name);
$newPath = $this->getMetadataFilePath($metadataType, $newName);
if (!$this->fileManager->isFile($path)) {
return;
}
$contents = $this->fileManager->getContents($path);
$replaceFrom = [];
$replaceTo = [];
$newContents = str_replace($replaceFrom, $replaceTo, $contents);
$this->fileManager->putContents($newPath, $newContents);
$this->fileManager->removeFile($path);
}
/**
* @param ClassType::* $classType
*/
private function getClassFilePath(string $classType, string $name): string
{
return "custom/Espo/Custom/{$classType}/{$name}.php";
}
/**
* @param MetadataType::* $metadataType
*/
private function getMetadataFilePath(string $metadataType, string $name): string
{
return "custom/Espo/Custom/Resources/metadata/{$metadataType}/{$name}.json";
}
private function renameLayouts(string $name, string $newName): void
{
$fromPath = "custom/Espo/Custom/Resources/layouts/{$name}";
$toPath = "custom/Espo/Custom/Resources/layouts/{$newName}";
rename($fromPath, $toPath);
}
private function tableExists(string $newName): bool
{
$table = Util::camelCaseToUnderscore($newName);
if (self::dbNameSanitize($table) !== $table) {
throw new RuntimeException();
}
$sql = "SHOW TABLES LIKE '{$table}'";
$sth = $this->entityManager->getSqlExecutor()->execute($sql);
if ($sth->fetch()) {
return true;
}
return false;
}
private function renameDbTable(string $name, string $newName): void
{
$table = Util::camelCaseToUnderscore($name);
$newTable = Util::camelCaseToUnderscore($newName);
if (self::dbNameSanitize($table) !== $table) {
throw new RuntimeException();
}
if (self::dbNameSanitize($newTable) !== $newTable) {
throw new RuntimeException();
}
$sql = "RENAME TABLE `{$table}` TO `{$newTable}`";
$this->entityManager->getSqlExecutor()->execute($sql);
}
private function renameDbRelationshipTableColumn(string $entityType, string $name, string $newName): void
{
$table = Util::camelCaseToUnderscore($entityType);
$column = Util::camelCaseToUnderscore($name);
$newColumn = Util::camelCaseToUnderscore($newName);
if (self::dbNameSanitize($table) !== $table) {
throw new RuntimeException();
}
if (self::dbNameSanitize($column) !== $column) {
throw new RuntimeException();
}
if (self::dbNameSanitize($newColumn) !== $newColumn) {
throw new RuntimeException();
}
$sql = "ALTER TABLE `{$table}` CHANGE `{$column}` `{$newColumn}` VARCHAR(24)";
try {
$this->entityManager->getSqlExecutor()->execute($sql);
} catch (Throwable $e) {
$msg = $e->getMessage();
$this->log->error("Entity-rename: Rename relationship column failed: {$msg}.");
}
}
private static function dbNameSanitize(string $name): string
{
return preg_replace('/[^A-Za-z0-9_]+/', '', $name) ?? '';
}
private function renameLanguage(string $entityType, string $newName): void
{
$label = $this->language->translateLabel($entityType, 'scopeNames');
$labelPlural = $this->language->translateLabel($entityType, 'scopeNamesPlural');
$this->language->delete('Global', 'scopeNames', $entityType);
$this->language->delete('Global', 'scopeNamesPlural', $entityType);
$this->language->set('Global', 'scopeNames', $newName, $label);
$this->language->set('Global', 'scopeNamesPlural', $newName, $labelPlural);
$this->language->save();
$langList = $this->fileManager->getDirList('custom/Espo/Custom/Resources/i18n');
foreach ($langList as $lang) {
$fromPath = "custom/Espo/Custom/Resources/i18n/{$lang}/{$entityType}.json";
$toPath = "custom/Espo/Custom/Resources/i18n/{$lang}/{$newName}.json";
if (!$this->fileManager->isFile($fromPath)) {
continue;
}
$contents = $this->fileManager->getContents($fromPath);
$this->fileManager->putContents($toPath, $contents);
$this->fileManager->removeFile($fromPath);
}
}
private function renameInConfig(string $entityType, string $newName): void
{
/** @var string[] $entityTypeListParamList */
$entityTypeListParamList = $this->metadata->get(['app', 'config', 'entityTypeListParamList']) ?? [];
foreach ($entityTypeListParamList as $param) {
/** @var ?string[] $list */
$list = $this->config->get($param);
if ($list === null) {
continue;
}
$index = array_search($entityType, $list, true);
if ($index === false) {
continue;
}
$list[$index] = $newName;
$this->configWriter->set($param, $list);
}
$this->configWriter->save();
}
private function renameInRelationships(string $entityType, string $newName): void
{
/** @var string[] $entityTypeList */
$entityTypeList = array_keys($this->metadata->get(['entityDefs']) ?? []);
foreach ($entityTypeList as $itemEntityType) {
$this->renameInRelationshipsEntity($itemEntityType, $entityType, $newName);
}
$this->metadata->save();
}
private function renameInRelationshipsEntity(string $entityType, string $fromEntityType, string $toEntityType): void
{
/** @var array<string, array<string, mixed>> $linkDefs */
$linkDefs = $this->metadata->get(['entityDefs', $entityType, 'links']) ?? [];
foreach ($linkDefs as $link => $defs) {
$itemEntityType = $defs['entity'] ?? null;
if ($itemEntityType !== $fromEntityType) {
continue;
}
$this->metadata->set('entityDefs', $entityType, [
'links' => [
$link => [
'entity' => $toEntityType,
]
]
]);
}
}
private function renameInFields(string $entityType, string $newName): void
{
$entityList = $this->entityManager
->getDefs()
->getEntityList();
foreach ($entityList as $entityDefs) {
foreach ($entityDefs->getFieldNameList() as $field) {
$this->renameInFieldsField($entityDefs->getName(), $field, $entityType, $newName);
}
}
$this->metadata->save();
}
private function renameInFieldsField(string $entityType, string $field, string $from, string $to): void
{
$defs = $this->entityManager
->getDefs()
->getEntity($entityType)
->getField($field);
if ($defs->getType() === FieldType::LINK_PARENT) {
$this->renameInLinkParentField($entityType, $defs->getName(), $from, $to);
}
}
private function renameInLinkParentField(string $entityType, string $field, string $from, string $to): void
{
/** @var string[] $list */
$list = $this->metadata->get(['entityDefs', $entityType, 'fields', $field, 'entityList']) ?? [];
$index = array_search($from, $list, true);
if ($index === false) {
return;
}
$list[$index] = $to;
$this->metadata->set('entityDefs', $entityType, [
'fields' => [
$field => ['entityList' => $list]
]
]);
}
private function changeValuesInDb(string $from, string $to): void
{
$this->changeValuesInDbFields($from, $to);
$this->changeValuesInDbRoles($from, $to);
$query1 = $this->entityManager
->getQueryBuilder()
->update()
->in('EntityTeam')
->set(['entityType' => $to])
->where(['entityType' => $from])
->build();
$this->entityManager->getQueryExecutor()->execute($query1);
$query2 = $this->entityManager
->getQueryBuilder()
->update()
->in('EntityEmailAddress')
->set(['entityType' => $to])
->where(['entityType' => $from])
->build();
$this->entityManager->getQueryExecutor()->execute($query2);
$query3 = $this->entityManager
->getQueryBuilder()
->update()
->in('EntityPhoneNumber')
->set(['entityType' => $to])
->where(['entityType' => $from])
->build();
$this->entityManager->getQueryExecutor()->execute($query3);
}
private function changeValuesInDbFields(string $from, string $to): void
{
$entityList = $this->entityManager
->getDefs()
->getEntityList();
foreach ($entityList as $entityDefs) {
foreach ($entityDefs->getFieldNameList() as $field) {
$this->changeValuesInDbFieldsField($entityDefs->getName(), $field, $from, $to);
}
}
}
private function changeValuesInDbFieldsField(string $entityType, string $field, string $from, string $to): void
{
$defs = $this->entityManager
->getDefs()
->getEntity($entityType)
->getField($field);
if ($defs->getType() === FieldType::LINK_PARENT) {
$this->changeValuesInDbFieldsFieldLinkParent($entityType, $defs->getName(), $from, $to);
}
}
private function changeValuesInDbFieldsFieldLinkParent(
string $entityType,
string $field,
string $from,
string $to
): void {
$typeAttribute = $field . 'Type';
$query = $this->entityManager
->getQueryBuilder()
->update()
->in($entityType)
->set([$typeAttribute => $to])
->where([$typeAttribute => $from])
->build();
try {
$this->entityManager->getQueryExecutor()->execute($query);
} catch (Throwable $e) {
$msg = $e->getMessage();
$this->log->error("Entity-rename: Update values in link-parent field {$entityType}.{$field}: {$msg}.");
}
}
private function changeValuesInDbRoles(string $from, string $to): void
{
$roleList = $this->entityManager
->getRDBRepositoryByClass(Role::class)
->find();
foreach ($roleList as $role) {
$data = $role->getRawData();
$fieldData = $role->getRawFieldData();
if (isset($data->$from)) {
$data->$to = $data->$from;
unset($data->$from);
$role->setRawData($data);
}
if (isset($fieldData->$from)) {
$fieldData->$to = $fieldData->$from;
unset($fieldData->$from);
$role->setRawFieldData($fieldData);
}
$this->entityManager->saveEntity($role);
}
/** @var iterable<PortalRole> $portalRoleList */
$portalRoleList = $this->entityManager
->getRDBRepositoryByClass(PortalRole::class)
->find();
foreach ($portalRoleList as $role) {
$data = $role->getRawData();
$fieldData = $role->getRawFieldData();
if (isset($data->$from)) {
$data->$to = $data->$from;
unset($data->$from);
$role->setRawData($data);
}
if (isset($fieldData->$from)) {
$fieldData->$to = $fieldData->$from;
unset($fieldData->$from);
$role->setRawFieldData($fieldData);
}
$this->entityManager->saveEntity($role);
}
}
}

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\EntityManager\Rename;
class Result
{
private bool $isFail = false;
/**
* @var FailReason::*|null
*/
private ?string $failReason = null;
public static function createSuccess(): self
{
return new self();
}
/**
* @param FailReason::* $reason
*/
public static function createFail(string $reason): self
{
$obj = new self();
$obj->isFail = true;
$obj->failReason = $reason;
return $obj;
}
public function isFail(): bool
{
return $this->isFail;
}
/**
* @return FailReason::*|null
*/
public function getFailReason(): ?string
{
return $this->failReason;
}
}