vendor/shopware/core/Framework/Webhook/WebhookDispatcher.php line 89

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Shopware\Core\Framework\Webhook;
  3. use Doctrine\DBAL\Connection;
  4. use GuzzleHttp\Client;
  5. use GuzzleHttp\Pool;
  6. use GuzzleHttp\Psr7\Request;
  7. use Shopware\Core\Framework\App\AppEntity;
  8. use Shopware\Core\Framework\App\Event\AppChangedEvent;
  9. use Shopware\Core\Framework\App\Event\AppDeletedEvent;
  10. use Shopware\Core\Framework\App\Exception\AppUrlChangeDetectedException;
  11. use Shopware\Core\Framework\App\Hmac\RequestSigner;
  12. use Shopware\Core\Framework\App\ShopId\ShopIdProvider;
  13. use Shopware\Core\Framework\Context;
  14. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  15. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  16. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  17. use Shopware\Core\Framework\Uuid\Uuid;
  18. use Shopware\Core\Framework\Webhook\EventLog\WebhookEventLogDefinition;
  19. use Shopware\Core\Framework\Webhook\Hookable\HookableEventFactory;
  20. use Shopware\Core\Framework\Webhook\Message\WebhookEventMessage;
  21. use Symfony\Component\DependencyInjection\ContainerInterface;
  22. use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
  23. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  24. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  25. use Symfony\Component\Messenger\MessageBusInterface;
  26. class WebhookDispatcher implements EventDispatcherInterface
  27. {
  28.     private EventDispatcherInterface $dispatcher;
  29.     private Connection $connection;
  30.     private ?WebhookCollection $webhooks null;
  31.     private Client $guzzle;
  32.     private string $shopUrl;
  33.     private ContainerInterface $container;
  34.     private array $privileges = [];
  35.     private HookableEventFactory $eventFactory;
  36.     private string $shopwareVersion;
  37.     private MessageBusInterface $bus;
  38.     private bool $isAdminWorkerEnabled;
  39.     /**
  40.      * @psalm-suppress ContainerDependency
  41.      */
  42.     public function __construct(
  43.         EventDispatcherInterface $dispatcher,
  44.         Connection $connection,
  45.         Client $guzzle,
  46.         string $shopUrl,
  47.         ContainerInterface $container,
  48.         HookableEventFactory $eventFactory,
  49.         string $shopwareVersion,
  50.         MessageBusInterface $bus,
  51.         bool $isAdminWorkerEnabled
  52.     ) {
  53.         $this->dispatcher $dispatcher;
  54.         $this->connection $connection;
  55.         $this->guzzle $guzzle;
  56.         $this->shopUrl $shopUrl;
  57.         // inject container, so we can later get the ShopIdProvider and the webhook repository
  58.         // ShopIdProvider and webhook repository can not be injected directly as it would lead to a circular reference
  59.         $this->container $container;
  60.         $this->eventFactory $eventFactory;
  61.         $this->shopwareVersion $shopwareVersion;
  62.         $this->bus $bus;
  63.         $this->isAdminWorkerEnabled $isAdminWorkerEnabled;
  64.     }
  65.     /**
  66.      * @template TEvent of object
  67.      *
  68.      * @param TEvent $event
  69.      *
  70.      * @return TEvent
  71.      */
  72.     public function dispatch($event, ?string $eventName null): object
  73.     {
  74.         $event $this->dispatcher->dispatch($event$eventName);
  75.         foreach ($this->eventFactory->createHookablesFor($event) as $hookable) {
  76.             $this->callWebhooks($hookable->getName(), $hookable);
  77.         }
  78.         // always return the original event and never our wrapped events
  79.         // this would lead to problems in the `BusinessEventDispatcher` from core
  80.         return $event;
  81.     }
  82.     /**
  83.      * @param string   $eventName
  84.      * @param callable $listener
  85.      * @param int      $priority
  86.      */
  87.     public function addListener($eventName$listener$priority 0): void
  88.     {
  89.         $this->dispatcher->addListener($eventName$listener$priority);
  90.     }
  91.     public function addSubscriber(EventSubscriberInterface $subscriber): void
  92.     {
  93.         $this->dispatcher->addSubscriber($subscriber);
  94.     }
  95.     /**
  96.      * @param string   $eventName
  97.      * @param callable $listener
  98.      */
  99.     public function removeListener($eventName$listener): void
  100.     {
  101.         $this->dispatcher->removeListener($eventName$listener);
  102.     }
  103.     public function removeSubscriber(EventSubscriberInterface $subscriber): void
  104.     {
  105.         $this->dispatcher->removeSubscriber($subscriber);
  106.     }
  107.     /**
  108.      * @param string|null $eventName
  109.      */
  110.     public function getListeners($eventName null): array
  111.     {
  112.         return $this->dispatcher->getListeners($eventName);
  113.     }
  114.     /**
  115.      * @param string   $eventName
  116.      * @param callable $listener
  117.      */
  118.     public function getListenerPriority($eventName$listener): ?int
  119.     {
  120.         return $this->dispatcher->getListenerPriority($eventName$listener);
  121.     }
  122.     /**
  123.      * @param string|null $eventName
  124.      */
  125.     public function hasListeners($eventName null): bool
  126.     {
  127.         return $this->dispatcher->hasListeners($eventName);
  128.     }
  129.     public function clearInternalWebhookCache(): void
  130.     {
  131.         $this->webhooks null;
  132.     }
  133.     public function clearInternalPrivilegesCache(): void
  134.     {
  135.         $this->privileges = [];
  136.     }
  137.     private function callWebhooks(string $eventNameHookable $event): void
  138.     {
  139.         /** @var WebhookCollection $webhooksForEvent */
  140.         $webhooksForEvent $this->getWebhooks()->filterForEvent($eventName);
  141.         if ($webhooksForEvent->count() === 0) {
  142.             return;
  143.         }
  144.         $payload $event->getWebhookPayload();
  145.         $affectedRoleIds $webhooksForEvent->getAclRoleIdsAsBinary();
  146.         $requests = [];
  147.         foreach ($webhooksForEvent as $webhook) {
  148.             if ($webhook->getApp() !== null && !$this->isEventDispatchingAllowed($webhook->getApp(), $event$affectedRoleIds)) {
  149.                 continue;
  150.             }
  151.             $payload = ['data' => ['payload' => $payload]];
  152.             $payload['source']['url'] = $this->shopUrl;
  153.             $payload['data']['event'] = $eventName;
  154.             if ($webhook->getApp() !== null) {
  155.                 $payload['source']['appVersion'] = $webhook->getApp()->getVersion();
  156.                 $shopIdProvider $this->getShopIdProvider();
  157.                 try {
  158.                     $shopId $shopIdProvider->getShopId();
  159.                 } catch (AppUrlChangeDetectedException $e) {
  160.                     continue;
  161.                 }
  162.                 $payload['source']['shopId'] = $shopId;
  163.             }
  164.             if ($this->isAdminWorkerEnabled) {
  165.                 /** @var string $jsonPayload */
  166.                 $jsonPayload json_encode($payload);
  167.                 $request = new Request(
  168.                     'POST',
  169.                     $webhook->getUrl(),
  170.                     [
  171.                         'Content-Type' => 'application/json',
  172.                         'sw-version' => $this->shopwareVersion,
  173.                     ],
  174.                     $jsonPayload
  175.                 );
  176.                 if ($webhook->getApp() !== null && $webhook->getApp()->getAppSecret() !== null) {
  177.                     $request $request->withHeader(
  178.                         RequestSigner::SHOPWARE_SHOP_SIGNATURE,
  179.                         (new RequestSigner())->signPayload($jsonPayload$webhook->getApp()->getAppSecret())
  180.                     );
  181.                 }
  182.                 $requests[] = $request;
  183.             } else {
  184.                 $webhookEventId Uuid::randomHex();
  185.                 $appId $webhook->getApp() !== null $webhook->getApp()->getId() : null;
  186.                 $secret $webhook->getApp() !== null $webhook->getApp()->getAppSecret() : null;
  187.                 $webhookEventMessage = new WebhookEventMessage($webhookEventId$payload$appId$webhook->getId(), $this->shopwareVersion$webhook->getUrl(), $secret);
  188.                 if (!$this->container->has('webhook_event_log.repository')) {
  189.                     throw new ServiceNotFoundException('webhook_event_log.repository');
  190.                 }
  191.                 /** @var EntityRepositoryInterface $webhookEventLogRepository */
  192.                 $webhookEventLogRepository $this->container->get('webhook_event_log.repository');
  193.                 $webhookEventLogRepository->create([
  194.                     [
  195.                         'id' => $webhookEventId,
  196.                         'appName' => $webhook->getApp() !== null $webhook->getApp()->getName() : null,
  197.                         'deliveryStatus' => WebhookEventLogDefinition::STATUS_QUEUED,
  198.                         'webhookName' => $webhook->getName(),
  199.                         'eventName' => $webhook->getEventName(),
  200.                         'appVersion' => $webhook->getApp() !== null $webhook->getApp()->getVersion() : null,
  201.                         'url' => $webhook->getUrl(),
  202.                         'serializedWebhookMessage' => serialize($webhookEventMessage),
  203.                     ],
  204.                 ], Context::createDefaultContext());
  205.                 $this->bus->dispatch($webhookEventMessage);
  206.             }
  207.         }
  208.         if ($this->isAdminWorkerEnabled) {
  209.             $pool = new Pool($this->guzzle$requests);
  210.             $pool->promise()->wait();
  211.         }
  212.     }
  213.     private function getWebhooks(): WebhookCollection
  214.     {
  215.         if ($this->webhooks) {
  216.             return $this->webhooks;
  217.         }
  218.         $criteria = new Criteria();
  219.         $criteria->addFilter(new EqualsFilter('active'true));
  220.         $criteria->addAssociation('app');
  221.         if (!$this->container->has('webhook.repository')) {
  222.             throw new ServiceNotFoundException('webhook.repository');
  223.         }
  224.         /** @var WebhookCollection $webhooks */
  225.         $webhooks $this->container->get('webhook.repository')->search($criteriaContext::createDefaultContext())->getEntities();
  226.         return $this->webhooks $webhooks;
  227.     }
  228.     private function isEventDispatchingAllowed(AppEntity $appHookable $event, array $affectedRoles): bool
  229.     {
  230.         // Only app lifecycle hooks can be received if app is deactivated
  231.         if (!$app->isActive() && !($event instanceof AppChangedEvent || $event instanceof AppDeletedEvent)) {
  232.             return false;
  233.         }
  234.         if (!($this->privileges[$event->getName()] ?? null)) {
  235.             $this->loadPrivileges($event->getName(), $affectedRoles);
  236.         }
  237.         $privileges $this->privileges[$event->getName()][$app->getAclRoleId()]
  238.             ?? new AclPrivilegeCollection([]);
  239.         if (!$event->isAllowed($app->getId(), $privileges)) {
  240.             return false;
  241.         }
  242.         return true;
  243.     }
  244.     private function loadPrivileges(string $eventName, array $affectedRoleIds): void
  245.     {
  246.         $roles $this->connection->fetchAll('
  247.             SELECT `id`, `privileges`
  248.             FROM `acl_role`
  249.             WHERE `id` IN (:aclRoleIds)
  250.         ', ['aclRoleIds' => $affectedRoleIds], ['aclRoleIds' => Connection::PARAM_STR_ARRAY]);
  251.         if (!$roles) {
  252.             $this->privileges[$eventName] = [];
  253.         }
  254.         foreach ($roles as $privilege) {
  255.             $this->privileges[$eventName][Uuid::fromBytesToHex($privilege['id'])]
  256.                 = new AclPrivilegeCollection(json_decode($privilege['privileges'], true));
  257.         }
  258.     }
  259.     private function getShopIdProvider(): ShopIdProvider
  260.     {
  261.         if (!$this->container->has(ShopIdProvider::class)) {
  262.             throw new ServiceNotFoundException(ShopIdProvider::class);
  263.         }
  264.         return $this->container->get(ShopIdProvider::class);
  265.     }
  266. }