This commit is contained in:
Yuri Kuznetsov
2024-04-25 15:03:14 +03:00
parent 4aa4b17c9f
commit c1855e84a9
6 changed files with 358 additions and 219 deletions
@@ -567,8 +567,7 @@ class DefaultImporter implements Importer
->create()
->setClassName(ProcessNoteAcl::class)
->setData(
JobData
::create()
JobData::create(['notify' => true])
->withTargetId($duplicate->getId())
->withTargetType(Email::ENTITY_TYPE)
)
@@ -31,7 +31,7 @@ namespace Espo\Hooks\Common;
use Espo\Core\ORM\Repository\Option\SaveOption;
use Espo\ORM\Entity;
use Espo\Tools\Stream\Service as Service;
use Espo\Tools\Stream\NoteAcl\AccessModifier;
/**
* Notes having `related` or `superParent` are subjects to access control
@@ -46,7 +46,7 @@ class StreamNotesAcl
{
public static int $order = 10;
public function __construct(private Service $service)
public function __construct(private AccessModifier $processor)
{}
/**
@@ -70,8 +70,6 @@ class StreamNotesAcl
return;
}
$forceProcessNoteNotifications = !empty($options['forceProcessNoteNotifications']);
$this->service->processNoteAcl($entity, $forceProcessNoteNotifications);
$this->processor->process($entity);
}
}
@@ -31,14 +31,14 @@ namespace Espo\Tools\Stream\Jobs;
use Espo\Core\Job\Job;
use Espo\Core\Job\Job\Data;
use Espo\Core\ORM\Entity as CoreEntity;
use Espo\ORM\EntityManager;
use Espo\Tools\Stream\Service as Service;
use Espo\Tools\Stream\NoteAcl\Processor;
class ProcessNoteAcl implements Job
{
public function __construct(
private Service $service,
private Processor $processor,
private EntityManager $entityManager
) {}
@@ -46,6 +46,7 @@ class ProcessNoteAcl implements Job
{
$targetType = $data->getTargetType();
$targetId = $data->getTargetId();
$notify = $data->get('notify') === true;
if (!$targetType || !$targetId) {
return;
@@ -57,10 +58,10 @@ class ProcessNoteAcl implements Job
$entity = $this->entityManager->getEntityById($targetType, $targetId);
if (!$entity) {
if (!$entity instanceof CoreEntity) {
return;
}
$this->service->processNoteAcl($entity, true);
$this->processor->process($entity, $notify);
}
}
@@ -0,0 +1,100 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2024 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko
* 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\Stream\NoteAcl;
use Espo\Core\ORM\Entity as CoreEntity;
use Espo\Core\Utils\Metadata;
use Espo\ORM\Entity;
/**
* Changes users and teams of notes related to an entity according users and teams of the entity.
*
* Notes having `related` or `superParent` are subjects to access control
* through `users` and `teams` fields.
*
* When users or teams of `related` or `parent` record are changed
* the note record will be changed too.
*
* @internal
* @todo Job to process the rest, after the last ID.
*/
class AccessModifier
{
/** @var string[] */
private array $ignoreEntityTypeList = [
'Note',
'User',
'Team',
'Role',
'Portal',
'PortalRole',
];
public function __construct(
private Metadata $metadata,
private Processor $processor
) {}
/**
* @internal
* @param bool $notify Process notifications for notes.
*/
public function process(Entity $entity, bool $notify = false): void
{
if (!$entity instanceof CoreEntity) {
return;
}
if (!$this->toProcess($entity)) {
return;
}
$this->processor->process($entity, $notify);
}
private function toProcess(CoreEntity $entity): bool
{
$entityType = $entity->getEntityType();
if (in_array($entityType, $this->ignoreEntityTypeList)) {
return false;
}
if (!$this->metadata->get(['scopes', $entityType, 'acl'])) {
return false;
}
if (!$this->metadata->get(['scopes', $entityType, 'object'])) {
return false;
}
return true;
}
}
@@ -0,0 +1,248 @@
<?php
/************************************************************************
* This file is part of EspoCRM.
*
* EspoCRM Open Source CRM application.
* Copyright (C) 2014-2024 Yurii Kuznietsov, Taras Machyshyn, Oleksii Avramenko
* 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\Stream\NoteAcl;
use Espo\Core\AclManager;
use Espo\Core\ORM\Entity as CoreEntity;
use Espo\Core\ORM\Type\FieldType;
use Espo\Core\Utils\Config;
use Espo\Entities\Note;
use Espo\ORM\Collection;
use Espo\ORM\Entity;
use Espo\ORM\EntityManager;
use Espo\ORM\Query\Part\Order;
use DateTime;
use DateTimeInterface;
use LogicException;
/**
* @internal
*/
class Processor
{
/**
* When a record is re-assigned, ACL will be recalculated for related notes
* created within the period.
*/
private const NOTE_ACL_PERIOD = '3 days';
private const NOTE_ACL_LIMIT = 50;
private const NOTE_NOTIFICATION_PERIOD = '1 hour';
public function __construct(
private EntityManager $entityManager,
private Config $config,
private AclManager $aclManager,
) {}
public function process(CoreEntity $entity, bool $notify = false): void
{
$entityType = $entity->getEntityType();
$usersAttributeIsChanged = false;
$teamsAttributeIsChanged = false;
$ownerUserField = $this->aclManager->getReadOwnerUserField($entityType);
$defs = $this->entityManager->getDefs()->getEntity($entity->getEntityType());
$userIdList = [];
$teamIdList = [];
if ($ownerUserField) {
if (!$defs->hasField($ownerUserField)) {
throw new LogicException("Non-existing read-owner user field.");
}
$fieldDefs = $defs->getField($ownerUserField);
if ($fieldDefs->getType() === FieldType::LINK_MULTIPLE) {
$ownerUserIdAttribute = $ownerUserField . 'Ids';
}
else if ($fieldDefs->getType() === FieldType::LINK) {
$ownerUserIdAttribute = $ownerUserField . 'Id';
}
else {
throw new LogicException("Bad read-owner user field type.");
}
if ($entity->isAttributeChanged($ownerUserIdAttribute)) {
$usersAttributeIsChanged = true;
}
if ($usersAttributeIsChanged || $notify) {
if ($fieldDefs->getType() === FieldType::LINK_MULTIPLE) {
$userIdList = $entity->getLinkMultipleIdList($ownerUserField);
}
else {
$userId = $entity->get($ownerUserIdAttribute);
$userIdList = $userId ? [$userId] : [];
}
}
}
if ($entity->hasLinkMultipleField('teams')) {
if ($entity->isAttributeChanged('teamsIds')) {
$teamsAttributeIsChanged = true;
}
if ($teamsAttributeIsChanged || $notify) {
$teamIdList = $entity->getLinkMultipleIdList('teams');
}
}
if (!$usersAttributeIsChanged && !$teamsAttributeIsChanged && !$notify) {
return;
}
$notificationThreshold = $this->getNotificationThreshold();
$aclThreshold = $this->getAclThreshold();
foreach ($this->getNotes($entity) as $note) {
$this->processNoteAclItem($entity, $note, [
'teamsAttributeIsChanged' => $teamsAttributeIsChanged,
'usersAttributeIsChanged' => $usersAttributeIsChanged,
'notify' => $notify,
'teamIdList' => $teamIdList,
'userIdList' => $userIdList,
'notificationThreshold' => $notificationThreshold,
'aclThreshold' => $aclThreshold,
]);
}
}
/**
* @param array{
* teamsAttributeIsChanged: bool,
* usersAttributeIsChanged: bool,
* notify: bool,
* teamIdList: string[],
* userIdList: string[],
* notificationThreshold: DateTimeInterface,
* aclThreshold: DateTimeInterface,
* } $params
*/
private function processNoteAclItem(Entity $entity, Note $note, array $params): void
{
$teamsAttributeIsChanged = $params['teamsAttributeIsChanged'];
$usersAttributeIsChanged = $params['usersAttributeIsChanged'];
$notify = $params['notify'];
$teamIdList = $params['teamIdList'];
$userIdList = $params['userIdList'];
$notificationThreshold = $params['notificationThreshold'];
$aclThreshold = $params['aclThreshold'];
$createdAt = $note->getCreatedAt();
if (!$createdAt) {
return;
}
if (!$entity->isNew()) {
if ($createdAt->toTimestamp() < $notificationThreshold->getTimestamp()) {
$notify = false;
}
if ($createdAt->toTimestamp() < $aclThreshold->getTimestamp()) {
return;
}
}
if ($teamsAttributeIsChanged || $notify) {
$note->setTeamsIds($teamIdList);
}
if ($usersAttributeIsChanged || $notify) {
$note->setUsersIds($userIdList);
}
$this->entityManager->saveEntity($note, [
'forceProcessNotifications' => $notify,
]);
}
/**
* @return Collection<Note>
*/
private function getNotes(CoreEntity $entity): Collection
{
$entityType = $entity->getEntityType();
$limit = $this->config->get('noteAclLimit', self::NOTE_ACL_LIMIT);
return $this->entityManager
->getRDBRepository(Note::ENTITY_TYPE)
->sth()
->where([
'OR' => [
[
'relatedId' => $entity->getId(),
'relatedType' => $entityType,
],
[
'parentId' => $entity->getId(),
'parentType' => $entityType,
'superParentId!=' => null,
'relatedId' => null,
]
]
])
->select([
'id',
'parentType',
'parentId',
'superParentType',
'superParentId',
'isInternal',
'relatedType',
'relatedId',
'createdAt',
])
->order('number', Order::DESC)
->limit(0, $limit)
->find();
}
private function getNotificationThreshold(): DateTime
{
$notificationPeriod = '-' . $this->config->get('noteNotificationPeriod', self::NOTE_NOTIFICATION_PERIOD);
return (new DateTime())->modify($notificationPeriod);
}
private function getAclThreshold(): DateTime
{
$aclPeriod = '-' . $this->config->get('noteAclPeriod', self::NOTE_ACL_PERIOD);
return (new DateTime())->modify($aclPeriod);
}
}
-207
View File
@@ -66,9 +66,6 @@ use Espo\Core\Select\SearchParams;
use Espo\Core\Utils\Acl\UserAclManagerProvider;
use stdClass;
use DateTime;
use DateTimeInterface;
use LogicException;
class Service
{
@@ -105,17 +102,6 @@ class Service
*/
private $auditedFieldsCache = [];
/**
* When a record is re-assigned, ACL will be recalculated for related notes
* created within the period.
*/
private const NOTE_ACL_PERIOD = '3 days';
private const NOTE_ACL_LIMIT = 50;
/**
* Not used currently.
*/
private const NOTE_NOTIFICATION_PERIOD = '1 hour';
public function __construct(
private EntityManager $entityManager,
private Config $config,
@@ -1168,199 +1154,6 @@ class Service
->find();
}
/**
* Changes users and teams of notes related to an entity according users and teams of the entity.
*
* Notes having `related` or `superParent` are subjects to access control
* through `users` and `teams` fields.
*
* When users or teams of `related` or `parent` record are changed
* the note record will be changed too.
*
* @todo Job to process the rest, after the last ID.
*/
public function processNoteAcl(Entity $entity, bool $forceProcessNoteNotifications = false): void
{
if (!$entity instanceof CoreEntity) {
return;
}
$entityType = $entity->getEntityType();
if (in_array($entityType, ['Note', 'User', 'Team', 'Role', 'Portal', 'PortalRole'])) {
return;
}
if (!$this->metadata->get(['scopes', $entityType, 'acl'])) {
return;
}
if (!$this->metadata->get(['scopes', $entityType, 'object'])) {
return;
}
$usersAttributeIsChanged = false;
$teamsAttributeIsChanged = false;
$ownerUserField = $this->aclManager->getReadOwnerUserField($entityType);
$defs = $this->entityManager->getDefs()->getEntity($entity->getEntityType());
$userIdList = [];
$teamIdList = [];
if ($ownerUserField) {
if (!$defs->hasField($ownerUserField)) {
throw new LogicException("Non-existing read-owner user field.");
}
$fieldDefs = $defs->getField($ownerUserField);
if ($fieldDefs->getType() === 'linkMultiple') {
$ownerUserIdAttribute = $ownerUserField . 'Ids';
}
else if ($fieldDefs->getType() === 'link') {
$ownerUserIdAttribute = $ownerUserField . 'Id';
}
else {
throw new LogicException("Bad read-owner user field type.");
}
if ($entity->isAttributeChanged($ownerUserIdAttribute)) {
$usersAttributeIsChanged = true;
}
if ($usersAttributeIsChanged || $forceProcessNoteNotifications) {
if ($fieldDefs->getType() === 'linkMultiple') {
$userIdList = $entity->getLinkMultipleIdList($ownerUserField);
}
else {
$userId = $entity->get($ownerUserIdAttribute);
$userIdList = $userId ? [$userId] : [];
}
}
}
if ($entity->hasLinkMultipleField('teams')) {
if ($entity->isAttributeChanged('teamsIds')) {
$teamsAttributeIsChanged = true;
}
if ($teamsAttributeIsChanged || $forceProcessNoteNotifications) {
$teamIdList = $entity->getLinkMultipleIdList('teams');
}
}
if (!$usersAttributeIsChanged && !$teamsAttributeIsChanged && !$forceProcessNoteNotifications) {
return;
}
$limit = $this->config->get('noteAclLimit', self::NOTE_ACL_LIMIT);
$noteList = $this->entityManager
->getRDBRepository(Note::ENTITY_TYPE)
->where([
'OR' => [
[
'relatedId' => $entity->getId(),
'relatedType' => $entityType,
],
[
'parentId' => $entity->getId(),
'parentType' => $entityType,
'superParentId!=' => null,
'relatedId' => null,
]
]
])
->select([
'id',
'parentType',
'parentId',
'superParentType',
'superParentId',
'isInternal',
'relatedType',
'relatedId',
'createdAt',
])
->order('number', 'DESC')
->limit(0, $limit)
->find();
$notificationPeriod = '-' . $this->config->get('noteNotificationPeriod', self::NOTE_NOTIFICATION_PERIOD);
$aclPeriod = '-' . $this->config->get('noteAclPeriod', self::NOTE_ACL_PERIOD);
$notificationThreshold = (new DateTime())->modify($notificationPeriod);
$aclThreshold = (new DateTime())->modify($aclPeriod);
foreach ($noteList as $note) {
$this->processNoteAclItem($entity, $note, [
'teamsAttributeIsChanged' => $teamsAttributeIsChanged,
'usersAttributeIsChanged' => $usersAttributeIsChanged,
'forceProcessNoteNotifications' => $forceProcessNoteNotifications,
'teamIdList' => $teamIdList,
'userIdList' => $userIdList,
'notificationThreshold' => $notificationThreshold,
'aclThreshold' => $aclThreshold,
]);
}
}
/**
* @param array{
* teamsAttributeIsChanged: bool,
* usersAttributeIsChanged: bool,
* forceProcessNoteNotifications: bool,
* teamIdList: string[],
* userIdList: string[],
* notificationThreshold: DateTimeInterface,
* aclThreshold: DateTimeInterface,
* } $params
* @return void
*/
private function processNoteAclItem(Entity $entity, Note $note, array $params): void
{
$teamsAttributeIsChanged = $params['teamsAttributeIsChanged'];
$usersAttributeIsChanged = $params['usersAttributeIsChanged'];
$forceProcessNoteNotifications = $params['forceProcessNoteNotifications'];
$teamIdList = $params['teamIdList'];
$userIdList = $params['userIdList'];
$notificationThreshold = $params['notificationThreshold'];
$aclThreshold = $params['aclThreshold'];
$createdAt = $note->getCreatedAt();
if (!$createdAt) {
return;
}
if (!$entity->isNew()) {
if ($createdAt->toTimestamp() < $notificationThreshold->getTimestamp()) {
$forceProcessNoteNotifications = false;
}
if ($createdAt->toTimestamp() < $aclThreshold->getTimestamp()) {
return;
}
}
if ($teamsAttributeIsChanged || $forceProcessNoteNotifications) {
$note->setTeamsIds($teamIdList);
}
if ($usersAttributeIsChanged || $forceProcessNoteNotifications) {
$note->setUsersIds($userIdList);
}
$this->entityManager->saveEntity($note, [
'forceProcessNotifications' => $forceProcessNoteNotifications,
]);
}
private function getEmailAddressRepository(): EmailAddressRepository
{
/** @var EmailAddressRepository */