This commit is contained in:
Yuri Kuznetsov
2024-02-22 10:50:11 +02:00
parent 231bd7699a
commit 1edc3ead8d
13 changed files with 506 additions and 286 deletions
@@ -0,0 +1,62 @@
<?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\Classes\RecordHooks\Webhook;
use Espo\Core\Record\DeleteParams;
use Espo\Core\Record\Hook\DeleteHook;
use Espo\Core\Webhook\Manager;
use Espo\Entities\Webhook;
use Espo\ORM\Entity;
/**
* @implements DeleteHook<Webhook>
* @noinspection PhpUnused
*/
class AfterDelete implements DeleteHook
{
public function __construct(
private Manager $webhookManager
) {}
public function process(Entity $entity, DeleteParams $params): void
{
$event = $entity->getEvent();
if (!$event) {
return;
}
if (!$entity->isActive()) {
return;
}
$this->webhookManager->removeEvent($event);
}
}
@@ -0,0 +1,75 @@
<?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\Classes\RecordHooks\Webhook;
use Espo\Core\Record\Hook\SaveHook;
use Espo\Core\Webhook\Manager;
use Espo\Entities\Webhook;
use Espo\ORM\Entity;
use RuntimeException;
/**
* @implements SaveHook<Webhook>
*/
class AfterSave implements SaveHook
{
public function __construct(
private Manager $webhookManager
) {}
public function process(Entity $entity): void
{
$event = $entity->getEvent();
if (!$event) {
throw new RuntimeException("No 'event'.");
}
if ($entity->isNew()) {
if ($entity->isActive()) {
$this->webhookManager->addEvent($event);
}
return;
}
if (!$entity->isAttributeChanged('isActive')) {
return;
}
if ($entity->isActive()) {
$this->webhookManager->addEvent($event);
return;
}
$this->webhookManager->removeEvent($event);
}
}
@@ -0,0 +1,186 @@
<?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\Classes\RecordHooks\Webhook;
use Espo\Core\Acl;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Record\Hook\SaveHook;
use Espo\Core\Utils\Config;
use Espo\Core\Utils\Metadata;
use Espo\Entities\User;
use Espo\Entities\Webhook;
use Espo\ORM\Entity;
use Espo\ORM\EntityManager;
/**
* @implements SaveHook<Webhook>
*/
class BeforeSave implements SaveHook
{
private const WEBHOOK_MAX_COUNT_PER_USER = 50;
/** @var string[] */
private $eventTypeList = [
'create',
'update',
'delete',
'fieldUpdate',
];
public function __construct(
private User $user,
private EntityManager $entityManager,
private Acl $acl,
private Metadata $metadata,
private Config $config
) {}
public function process(Entity $entity): void
{
$this->checkEntityUserIsApi($entity);
$this->processEntityEventData($entity);
if ($entity->isNew() && !$this->user->isAdmin()) {
$this->checkMaxCount();
}
}
/**
* @throws Forbidden
*/
private function checkEntityUserIsApi(Webhook $entity): void
{
$userId = $entity->getUserId();
if (!$userId) {
return;
}
$user = $this->entityManager->getRDBRepositoryByClass(User::class)->getById($userId);
if ($user && $user->isApi()) {
return;
}
throw new Forbidden("User must be an API User.");
}
/**
* @throws Forbidden
*/
private function processEntityEventData(Webhook $entity): void
{
$event = $entity->get('event');
if (!$event) {
throw new Forbidden("Event is empty.");
}
if (!$entity->isNew() && $entity->isAttributeChanged('event')) {
throw new Forbidden("Event can't be changed.");
}
$arr = explode('.', $event);
if (count($arr) !== 2 && count($arr) !== 3) {
throw new Forbidden("Not supported event.");
}
$entityType = $arr[0];
$type = $arr[1];
$entity->set('entityType', $entityType);
$entity->set('type', $type);
$field = null;
if (!$entityType) {
throw new Forbidden("Entity Type is empty.");
}
if (!$this->metadata->get(['scopes', $entityType, 'object'])) {
throw new Forbidden("Entity type is not available for Webhooks.");
}
if (!$this->entityManager->hasRepository($entityType)) {
throw new Forbidden("Not existing Entity Type.");
}
if (!$this->acl->checkScope($entityType, Acl\Table::ACTION_READ)) {
throw new Forbidden("Entity type is forbidden.");
}
if (!in_array($type, $this->eventTypeList)) {
throw new Forbidden("Not supported event.");
}
if ($type === 'fieldUpdate') {
if (count($arr) == 3) {
$field = $arr[2];
}
$entity->set('field', $field);
if (!$field) {
throw new Forbidden("Field is empty.");
}
if (!$this->acl->checkField($entityType, $field)) {
throw new Forbidden("Field is forbidden.");
}
if (!$this->metadata->get(['entityDefs', $entityType, 'fields', $field])) {
throw new Forbidden("Field does not exist.");
}
return;
}
/** @noinspection PhpRedundantOptionalArgumentInspection */
$entity->set('field', null);
}
/**
* @throws Forbidden
*/
private function checkMaxCount(): void
{
$maxCount = $this->config->get('webhookMaxCountPerUser', self::WEBHOOK_MAX_COUNT_PER_USER);
$count = $this->entityManager
->getRDBRepositoryByClass(Webhook::class)
->where(['userId' => $this->user->getId()])
->count();
if ($maxCount && $count >= $maxCount) {
throw new Forbidden("Webhook number per user exceeded the limit.");
}
}
}
+6 -6
View File
@@ -1960,7 +1960,7 @@ class Service implements Crud,
* @return void
* @noinspection PhpDocSignatureInspection
* @deprecated As of v8.2.
* @todo Remove in v10.0.
* @todo Remove (or add types) in v10.0.
*/
protected function beforeCreateEntity(Entity $entity, $data)
{}
@@ -1971,7 +1971,7 @@ class Service implements Crud,
* @return void
* @noinspection PhpDocSignatureInspection
* @deprecated As of v8.2.
* @todo Remove in v10.0.
* @todo Remove (or add types) in v10.0.
*/
protected function afterCreateEntity(Entity $entity, $data)
{}
@@ -1982,7 +1982,7 @@ class Service implements Crud,
* @return void
* @noinspection PhpDocSignatureInspection
* @deprecated As of v8.2.
* @todo Remove in v10.0.
* @todo Remove (or add types) in v10.0.
*/
protected function beforeUpdateEntity(Entity $entity, $data)
{}
@@ -1993,7 +1993,7 @@ class Service implements Crud,
* @return void
* @noinspection PhpDocSignatureInspection
* @deprecated As of v8.2.
* @todo Remove in v10.0.
* @todo Remove (or add types) in v10.0.
*/
protected function afterUpdateEntity(Entity $entity, $data)
{}
@@ -2003,7 +2003,7 @@ class Service implements Crud,
* @return void
* @noinspection PhpDocSignatureInspection
* @deprecated As of v8.2.
* @todo Remove in v10.0.
* @todo Remove (or add types) in v10.0.
*/
protected function beforeDeleteEntity(Entity $entity)
{}
@@ -2013,7 +2013,7 @@ class Service implements Crud,
* @return void
* @noinspection PhpDocSignatureInspection
* @deprecated As of v8.2.
* @todo Remove in v10.0.
* @todo Remove (or add types) in v10.0.
*/
protected function afterDeleteEntity(Entity $entity)
{}
@@ -0,0 +1,70 @@
<?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\Modules\Crm\Classes\RecordHooks\Case;
use Espo\Core\Acl;
use Espo\Core\Field\LinkParent;
use Espo\Core\Record\Hook\SaveHook;
use Espo\Entities\Email;
use Espo\Modules\Crm\Entities\CaseObj;
use Espo\ORM\Entity;
use Espo\ORM\EntityManager;
/**
* @implements SaveHook<CaseObj>
* @noinspection PhpUnused
*/
class AfterCreate implements SaveHook
{
public function __construct(
private EntityManager $entityManager,
private Acl $acl
) {}
public function process(Entity $entity): void
{
/** @var ?string $emailId */
$emailId = $entity->get('originalEmailId');
if (!$emailId) {
return;
}
$email = $this->entityManager->getRDBRepositoryByClass(Email::class)->getById($emailId);
if (!$email || $email->getParentId() || !$this->acl->check($email)) {
return;
}
$email->setParent(LinkParent::createFromEntity($entity));
$this->entityManager->saveEntity($email);
}
}
@@ -0,0 +1,69 @@
<?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\Modules\Crm\Classes\RecordHooks\Case;
use Espo\Core\Record\Hook\SaveHook;
use Espo\Entities\User;
use Espo\Modules\Crm\Entities\CaseObj;
use Espo\Modules\Crm\Entities\Contact;
use Espo\ORM\Entity;
use Espo\ORM\EntityManager;
/**
* @implements SaveHook<CaseObj>
* @noinspection PhpUnused
*/
class BeforeCreate implements SaveHook
{
public function __construct(
private EntityManager $entityManager,
private User $user
) {}
public function process(Entity $entity): void
{
if (!$this->user->isPortal()) {
return;
}
if (!$entity->has('accountId') && $this->user->getContactId()) {
/** @var ?Contact $contact */
$contact = $this->entityManager->getEntityById(Contact::ENTITY_TYPE, $this->user->getContactId());
if ($contact && $contact->getAccount()) {
$entity->set('accountId', $contact->getAccount()->getId());
}
}
if (!$entity->has('contactId') && $this->user->getContactId()) {
$entity->set('contactId', $this->user->getContactId());
}
}
}
@@ -11,7 +11,8 @@
"description": "Description",
"inboundEmail": "Group Email Account",
"lead": "Lead",
"attachments": "Attachments"
"attachments": "Attachments",
"originalEmail": "Original Email"
},
"links": {
"inboundEmail": "Group Email Account",
@@ -69,6 +69,14 @@
"type": "link",
"readOnly": true
},
"originalEmail": {
"type": "link",
"notStorable": true,
"entity": "Email",
"customizationDisabled": true,
"layoutAvailabilityList": [],
"directAccessDisabled": true
},
"createdAt": {
"type": "datetime",
"readOnly": true,
@@ -7,5 +7,11 @@
"emails": {
"linkRequiredForeignAccess": "read"
}
}
},
"beforeCreateHookClassNameList": [
"Espo\\Modules\\Crm\\Classes\\RecordHooks\\Case\\BeforeCreate"
],
"afterCreateHookClassNameList": [
"Espo\\Modules\\Crm\\Classes\\RecordHooks\\Case\\AfterCreate"
]
}
@@ -0,0 +1,17 @@
{
"beforeCreateHookClassNameList": [
"Espo\\Classes\\RecordHooks\\Webhook\\BeforeSave"
],
"beforeUpdateHookClassNameList": [
"Espo\\Classes\\RecordHooks\\Webhook\\BeforeSave"
],
"afterCreateHookClassNameList": [
"Espo\\Classes\\RecordHooks\\Webhook\\AfterSave"
],
"afterUpdateHookClassNameList": [
"Espo\\Classes\\RecordHooks\\Webhook\\AfterSave"
],
"afterDeleteHookClassNameList": [
"Espo\\Classes\\RecordHooks\\Webhook\\AfterDelete"
]
}
@@ -1,89 +0,0 @@
<?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\Modules\Crm\Services;
use Espo\Entities\Email;
use Espo\Modules\Crm\Entities\CaseObj as CaseEntity;
use Espo\Modules\Crm\Entities\Contact as ContactEntity;
use Espo\ORM\Entity;
use Espo\Services\Record;
/**
* @extends Record<CaseEntity>
*/
class CaseObj extends Record
{
/**
* @param CaseEntity $entity
*/
public function beforeCreateEntity(Entity $entity, $data)
{
parent::beforeCreateEntity($entity, $data);
if ($this->user->isPortal()) {
if (!$entity->has('accountId')) {
if ($this->user->getContactId()) {
/** @var ?ContactEntity $contact */
$contact = $this->entityManager
->getEntityById(ContactEntity::ENTITY_TYPE, $this->user->getContactId());
if ($contact && $contact->getAccount()) {
$entity->set('accountId', $contact->getAccount()->getId());
}
}
}
if (!$entity->has('contactId')) {
if ($this->user->getContactId()) {
$entity->set('contactId', $this->user->getContactId());
}
}
}
}
public function afterCreateEntity(Entity $entity, $data)
{
parent::afterCreateEntity($entity, $data);
if (!empty($data->emailId)) {
/** @var ?Email $email */
$email = $this->entityManager->getEntityById(Email::ENTITY_TYPE, $data->emailId);
if ($email && !$email->getParentId() && $this->acl->check($email)) {
$email->set([
'parentType' => CaseEntity::ENTITY_TYPE,
'parentId' => $entity->getId(),
]);
$this->entityManager->saveEntity($email);
}
}
}
}
+3 -188
View File
@@ -31,41 +31,17 @@ namespace Espo\Services;
use Espo\Entities\Webhook as WebhookEntity;
use Espo\ORM\Entity;
use Espo\Core\Exceptions\Forbidden;
use Espo\Core\Di;
use Espo\Entities\User;
use stdClass;
/**
* @extends Record<WebhookEntity>
*/
class Webhook extends Record implements
Di\WebhookManagerAware
class Webhook extends Record
{
use Di\WebhookManagerSetter;
const WEBHOOK_MAX_COUNT_PER_USER = 50;
/**
* @var string[]
*/
protected $eventTypeList = [
'create',
'update',
'delete',
'fieldUpdate',
];
/**
* @var string[]
*/
/** @var string[] */
protected $onlyAdminAttributeList = ['userId', 'userName'];
/**
* @var string[]
*/
/** @var string[] */
protected $readOnlyAttributeList = ['secretKey'];
public function populateDefaults(Entity $entity, stdClass $data): void
@@ -94,165 +70,4 @@ class Webhook extends Record implements
parent::filterUpdateInput($data);
}
/**
* @throws Forbidden
*/
protected function beforeCreateEntity(Entity $entity, $data)
{
$this->checkEntityUserIsApi($entity);
$this->processEntityEventData($entity);
if (!$this->user->isAdmin()) {
$this->checkMaxCount();
}
}
/**
* @throws Forbidden
*/
protected function checkMaxCount(): void
{
$maxCount = $this->config->get('webhookMaxCountPerUser', self::WEBHOOK_MAX_COUNT_PER_USER);
$count = $this->entityManager
->getRDBRepository(WebhookEntity::ENTITY_TYPE)
->where([
'userId' => $this->user->getId(),
])
->count();
if ($maxCount && $count >= $maxCount) {
throw new Forbidden("Webhook number per user exceeded the limit.");
}
}
/**
* @throws Forbidden
*/
protected function beforeUpdateEntity(Entity $entity, $data)
{
$this->checkEntityUserIsApi($entity);
$this->processEntityEventData($entity);
}
/**
* @throws Forbidden
*/
protected function checkEntityUserIsApi(Entity $entity): void
{
$userId = $entity->get('userId');
if (!$userId) {
return;
}
/** @var User|null $user */
$user = $this->entityManager->getEntity(User::ENTITY_TYPE, $userId);
if (!$user || !$user->isApi()) {
throw new Forbidden("User must be an API User.");
}
}
/**
* @throws Forbidden
*/
protected function processEntityEventData(Entity $entity): void
{
$event = $entity->get('event');
if (!$event) {
throw new Forbidden("Event is empty.");
}
if (!$entity->isNew()) {
if ($entity->isAttributeChanged('event')) {
throw new Forbidden("Event can't be changed.");
}
}
$arr = explode('.', $event);
if (count($arr) !== 2 && count($arr) !== 3) {
throw new Forbidden("Not supported event.");
}
$entityType = $arr[0];
$type = $arr[1];
$entity->set('entityType', $entityType);
$entity->set('type', $type);
$field = null;
if (!$entityType) {
throw new Forbidden("Entity Type is empty.");
}
if (!$this->metadata->get(['scopes', $entityType, 'object'])) {
throw new Forbidden("Entity type is not available for Webhooks.");
}
if (!$this->entityManager->hasRepository($entityType)) {
throw new Forbidden("Not existing Entity Type.");
}
if (!$this->acl->checkScope($entityType, 'read')) {
throw new Forbidden("Entity type is forbidden.");
}
if (!in_array($type, $this->eventTypeList)) {
throw new Forbidden("Not supported event.");
}
if ($type === 'fieldUpdate') {
if (count($arr) == 3) {
$field = $arr[2];
}
$entity->set('field', $field);
if (!$field) {
throw new Forbidden("Field is empty.");
}
if (!$this->acl->checkField($entityType, $field)) {
throw new Forbidden("Field is forbidden.");
}
if (!$this->metadata->get(['entityDefs', $entityType, 'fields', $field])) {
throw new Forbidden("Field does not exist.");
}
} else {
/** @noinspection PhpRedundantOptionalArgumentInspection */
$entity->set('field', null);
}
}
protected function afterCreateEntity(Entity $entity, $data)
{
if ($entity->get('isActive')) {
$this->webhookManager->addEvent($entity->get('event'));
}
}
protected function afterDeleteEntity(Entity $entity)
{
if ($entity->get('isActive')) {
$this->webhookManager->removeEvent($entity->get('event'));
}
}
protected function afterUpdateEntity(Entity $entity, $data)
{
if (isset($data->isActive)) {
if ($entity->get('isActive')) {
$this->webhookManager->addEvent($entity->get('event'));
}
else {
$this->webhookManager->removeEvent($entity->get('event'));
}
}
}
}
+1 -1
View File
@@ -291,7 +291,7 @@ class EmailDetailView extends DetailView {
}
attributes.emailsIds = [this.model.id];
attributes.emailId = this.model.id;
attributes.originalEmailId = this.model.id;
attributes.name = this.model.get('name');
attributes.description = this.model.get('bodyPlain') || '';