platform/src/Core/Framework/Webhook/WebhookDispatcher.php line 94

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\AppLocaleProvider;
  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\Guzzle\AuthMiddleware;
  12. use Shopware\Core\Framework\App\Hmac\RequestSigner;
  13. use Shopware\Core\Framework\App\ShopId\ShopIdProvider;
  14. use Shopware\Core\Framework\Context;
  15. use Shopware\Core\Framework\DataAbstractionLayer\EntityRepositoryInterface;
  16. use Shopware\Core\Framework\DataAbstractionLayer\Event\EntityWrittenContainerEvent;
  17. use Shopware\Core\Framework\DataAbstractionLayer\Search\Criteria;
  18. use Shopware\Core\Framework\DataAbstractionLayer\Search\Filter\EqualsFilter;
  19. use Shopware\Core\Framework\Event\BusinessEventInterface;
  20. use Shopware\Core\Framework\Event\FlowEventAware;
  21. use Shopware\Core\Framework\Feature;
  22. use Shopware\Core\Framework\Uuid\Uuid;
  23. use Shopware\Core\Framework\Webhook\EventLog\WebhookEventLogDefinition;
  24. use Shopware\Core\Framework\Webhook\Hookable\HookableEventFactory;
  25. use Shopware\Core\Framework\Webhook\Message\WebhookEventMessage;
  26. use Symfony\Component\DependencyInjection\ContainerInterface;
  27. use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
  28. use Symfony\Component\EventDispatcher\EventDispatcherInterface;
  29. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  30. use Symfony\Component\Messenger\MessageBusInterface;
  31. class WebhookDispatcher implements EventDispatcherInterface
  32. {
  33.     private EventDispatcherInterface $dispatcher;
  34.     private Connection $connection;
  35.     private ?WebhookCollection $webhooks null;
  36.     private Client $guzzle;
  37.     private string $shopUrl;
  38.     private ContainerInterface $container;
  39.     private array $privileges = [];
  40.     private HookableEventFactory $eventFactory;
  41.     private string $shopwareVersion;
  42.     private MessageBusInterface $bus;
  43.     private bool $isAdminWorkerEnabled;
  44.     /**
  45.      * @psalm-suppress ContainerDependency
  46.      */
  47.     public function __construct(
  48.         EventDispatcherInterface $dispatcher,
  49.         Connection $connection,
  50.         Client $guzzle,
  51.         string $shopUrl,
  52.         ContainerInterface $container,
  53.         HookableEventFactory $eventFactory,
  54.         string $shopwareVersion,
  55.         MessageBusInterface $bus,
  56.         bool $isAdminWorkerEnabled
  57.     ) {
  58.         $this->dispatcher $dispatcher;
  59.         $this->connection $connection;
  60.         $this->guzzle $guzzle;
  61.         $this->shopUrl $shopUrl;
  62.         // inject container, so we can later get the ShopIdProvider and the webhook repository
  63.         // ShopIdProvider, AppLocaleProvider and webhook repository can not be injected directly as it would lead to a circular reference
  64.         $this->container $container;
  65.         $this->eventFactory $eventFactory;
  66.         $this->shopwareVersion $shopwareVersion;
  67.         $this->bus $bus;
  68.         $this->isAdminWorkerEnabled $isAdminWorkerEnabled;
  69.     }
  70.     /**
  71.      * @template TEvent of object
  72.      *
  73.      * @param TEvent $event
  74.      *
  75.      * @return TEvent
  76.      */
  77.     public function dispatch($event, ?string $eventName null): object
  78.     {
  79.         $event $this->dispatcher->dispatch($event$eventName);
  80.         foreach ($this->eventFactory->createHookablesFor($event) as $hookable) {
  81.             $context Context::createDefaultContext();
  82.             if (Feature::isActive('FEATURE_NEXT_17858')) {
  83.                 if ($event instanceof FlowEventAware || $event instanceof AppChangedEvent || $event instanceof EntityWrittenContainerEvent) {
  84.                     $context $event->getContext();
  85.                 }
  86.             } else {
  87.                 if ($event instanceof BusinessEventInterface || $event instanceof AppChangedEvent || $event instanceof EntityWrittenContainerEvent) {
  88.                     $context $event->getContext();
  89.                 }
  90.             }
  91.             $this->callWebhooks($hookable$context);
  92.         }
  93.         // always return the original event and never our wrapped events
  94.         // this would lead to problems in the `BusinessEventDispatcher` from core
  95.         return $event;
  96.     }
  97.     /**
  98.      * @param string   $eventName
  99.      * @param callable $listener
  100.      * @param int      $priority
  101.      */
  102.     public function addListener($eventName$listener$priority 0): void
  103.     {
  104.         $this->dispatcher->addListener($eventName$listener$priority);
  105.     }
  106.     public function addSubscriber(EventSubscriberInterface $subscriber): void
  107.     {
  108.         $this->dispatcher->addSubscriber($subscriber);
  109.     }
  110.     /**
  111.      * @param string   $eventName
  112.      * @param callable $listener
  113.      */
  114.     public function removeListener($eventName$listener): void
  115.     {
  116.         $this->dispatcher->removeListener($eventName$listener);
  117.     }
  118.     public function removeSubscriber(EventSubscriberInterface $subscriber): void
  119.     {
  120.         $this->dispatcher->removeSubscriber($subscriber);
  121.     }
  122.     /**
  123.      * @param string|null $eventName
  124.      */
  125.     public function getListeners($eventName null): array
  126.     {
  127.         return $this->dispatcher->getListeners($eventName);
  128.     }
  129.     /**
  130.      * @param string   $eventName
  131.      * @param callable $listener
  132.      */
  133.     public function getListenerPriority($eventName$listener): ?int
  134.     {
  135.         return $this->dispatcher->getListenerPriority($eventName$listener);
  136.     }
  137.     /**
  138.      * @param string|null $eventName
  139.      */
  140.     public function hasListeners($eventName null): bool
  141.     {
  142.         return $this->dispatcher->hasListeners($eventName);
  143.     }
  144.     public function clearInternalWebhookCache(): void
  145.     {
  146.         $this->webhooks null;
  147.     }
  148.     public function clearInternalPrivilegesCache(): void
  149.     {
  150.         $this->privileges = [];
  151.     }
  152.     private function callWebhooks(Hookable $eventContext $context): void
  153.     {
  154.         /** @var WebhookCollection $webhooksForEvent */
  155.         $webhooksForEvent $this->getWebhooks()->filterForEvent($event->getName());
  156.         if ($webhooksForEvent->count() === 0) {
  157.             return;
  158.         }
  159.         $affectedRoleIds $webhooksForEvent->getAclRoleIdsAsBinary();
  160.         $languageId $context->getLanguageId();
  161.         $userLocale $this->getAppLocaleProvider()->getLocaleFromContext($context);
  162.         if ($this->isAdminWorkerEnabled) {
  163.             $this->callWebhooksSynchronous($webhooksForEvent$event$affectedRoleIds$languageId$userLocale);
  164.             return;
  165.         }
  166.         $this->dispatchWebhooksToQueue($webhooksForEvent$event$affectedRoleIds$languageId$userLocale);
  167.     }
  168.     private function getWebhooks(): WebhookCollection
  169.     {
  170.         if ($this->webhooks) {
  171.             return $this->webhooks;
  172.         }
  173.         $criteria = new Criteria();
  174.         $criteria->addFilter(new EqualsFilter('active'true));
  175.         $criteria->addAssociation('app');
  176.         if (!$this->container->has('webhook.repository')) {
  177.             throw new ServiceNotFoundException('webhook.repository');
  178.         }
  179.         /** @var WebhookCollection $webhooks */
  180.         $webhooks $this->container->get('webhook.repository')->search($criteriaContext::createDefaultContext())->getEntities();
  181.         return $this->webhooks $webhooks;
  182.     }
  183.     private function isEventDispatchingAllowed(WebhookEntity $webhookHookable $event, array $affectedRoles): bool
  184.     {
  185.         $app $webhook->getApp();
  186.         if ($app === null) {
  187.             return true;
  188.         }
  189.         // Only app lifecycle hooks can be received if app is deactivated
  190.         if (!$app->isActive() && !($event instanceof AppChangedEvent || $event instanceof AppDeletedEvent)) {
  191.             return false;
  192.         }
  193.         if (!($this->privileges[$event->getName()] ?? null)) {
  194.             $this->loadPrivileges($event->getName(), $affectedRoles);
  195.         }
  196.         $privileges $this->privileges[$event->getName()][$app->getAclRoleId()]
  197.             ?? new AclPrivilegeCollection([]);
  198.         if (!$event->isAllowed($app->getId(), $privileges)) {
  199.             return false;
  200.         }
  201.         return true;
  202.     }
  203.     /**
  204.      * @param string[] $affectedRoleIds
  205.      */
  206.     private function callWebhooksSynchronous(
  207.         WebhookCollection $webhooksForEvent,
  208.         Hookable $event,
  209.         array $affectedRoleIds,
  210.         string $languageId,
  211.         string $userLocale
  212.     ): void {
  213.         $requests = [];
  214.         foreach ($webhooksForEvent as $webhook) {
  215.             if (!$this->isEventDispatchingAllowed($webhook$event$affectedRoleIds)) {
  216.                 continue;
  217.             }
  218.             try {
  219.                 $webhookData $this->getPayloadForWebhook($webhook$event);
  220.             } catch (AppUrlChangeDetectedException $e) {
  221.                 // don't dispatch webhooks for apps if url changed
  222.                 continue;
  223.             }
  224.             $timestamp time();
  225.             $webhookData['timestamp'] = $timestamp;
  226.             /** @var string $jsonPayload */
  227.             $jsonPayload json_encode($webhookData);
  228.             $request = new Request(
  229.                 'POST',
  230.                 $webhook->getUrl(),
  231.                 [
  232.                     'Content-Type' => 'application/json',
  233.                     'sw-version' => $this->shopwareVersion,
  234.                     AuthMiddleware::SHOPWARE_CONTEXT_LANGUAGE => $languageId,
  235.                     AuthMiddleware::SHOPWARE_USER_LANGUAGE => $userLocale,
  236.                 ],
  237.                 $jsonPayload
  238.             );
  239.             if ($webhook->getApp() !== null && $webhook->getApp()->getAppSecret() !== null) {
  240.                 $request $request->withHeader(
  241.                     RequestSigner::SHOPWARE_SHOP_SIGNATURE,
  242.                     (new RequestSigner())->signPayload($jsonPayload$webhook->getApp()->getAppSecret())
  243.                 );
  244.             }
  245.             $requests[] = $request;
  246.         }
  247.         if (\count($requests) > 0) {
  248.             $pool = new Pool($this->guzzle$requests);
  249.             $pool->promise()->wait();
  250.         }
  251.     }
  252.     /**
  253.      * @param string[] $affectedRoleIds
  254.      */
  255.     private function dispatchWebhooksToQueue(
  256.         WebhookCollection $webhooksForEvent,
  257.         Hookable $event,
  258.         array $affectedRoleIds,
  259.         string $languageId,
  260.         string $userLocale
  261.     ): void {
  262.         foreach ($webhooksForEvent as $webhook) {
  263.             if (!$this->isEventDispatchingAllowed($webhook$event$affectedRoleIds)) {
  264.                 continue;
  265.             }
  266.             try {
  267.                 $webhookData $this->getPayloadForWebhook($webhook$event);
  268.             } catch (AppUrlChangeDetectedException $e) {
  269.                 // don't dispatch webhooks for apps if url changed
  270.                 continue;
  271.             }
  272.             $webhookEventId Uuid::randomHex();
  273.             $appId $webhook->getApp() !== null $webhook->getApp()->getId() : null;
  274.             $secret $webhook->getApp() !== null $webhook->getApp()->getAppSecret() : null;
  275.             $webhookEventMessage = new WebhookEventMessage(
  276.                 $webhookEventId,
  277.                 $webhookData,
  278.                 $appId,
  279.                 $webhook->getId(),
  280.                 $this->shopwareVersion,
  281.                 $webhook->getUrl(),
  282.                 $secret,
  283.                 $languageId,
  284.                 $userLocale
  285.             );
  286.             $this->logWebhookWithEvent($webhook$webhookEventMessage);
  287.             $this->bus->dispatch($webhookEventMessage);
  288.         }
  289.     }
  290.     private function getPayloadForWebhook(WebhookEntity $webhookHookable $event): array
  291.     {
  292.         $data = [
  293.             'payload' => $event->getWebhookPayload(),
  294.             'event' => $event->getName(),
  295.         ];
  296.         $source = [
  297.             'url' => $this->shopUrl,
  298.         ];
  299.         if ($webhook->getApp() !== null) {
  300.             $shopIdProvider $this->getShopIdProvider();
  301.             $source['appVersion'] = $webhook->getApp()->getVersion();
  302.             $source['shopId'] = $shopIdProvider->getShopId();
  303.         }
  304.         return [
  305.             'data' => $data,
  306.             'source' => $source,
  307.         ];
  308.     }
  309.     private function logWebhookWithEvent(WebhookEntity $webhookWebhookEventMessage $webhookEventMessage): void
  310.     {
  311.         if (!$this->container->has('webhook_event_log.repository')) {
  312.             throw new ServiceNotFoundException('webhook_event_log.repository');
  313.         }
  314.         /** @var EntityRepositoryInterface $webhookEventLogRepository */
  315.         $webhookEventLogRepository $this->container->get('webhook_event_log.repository');
  316.         $webhookEventLogRepository->create([
  317.             [
  318.                 'id' => $webhookEventMessage->getWebhookEventId(),
  319.                 'appName' => $webhook->getApp() !== null $webhook->getApp()->getName() : null,
  320.                 'deliveryStatus' => WebhookEventLogDefinition::STATUS_QUEUED,
  321.                 'webhookName' => $webhook->getName(),
  322.                 'eventName' => $webhook->getEventName(),
  323.                 'appVersion' => $webhook->getApp() !== null $webhook->getApp()->getVersion() : null,
  324.                 'url' => $webhook->getUrl(),
  325.                 'serializedWebhookMessage' => serialize($webhookEventMessage),
  326.             ],
  327.         ], Context::createDefaultContext());
  328.     }
  329.     private function loadPrivileges(string $eventName, array $affectedRoleIds): void
  330.     {
  331.         $roles $this->connection->fetchAll('
  332.             SELECT `id`, `privileges`
  333.             FROM `acl_role`
  334.             WHERE `id` IN (:aclRoleIds)
  335.         ', ['aclRoleIds' => $affectedRoleIds], ['aclRoleIds' => Connection::PARAM_STR_ARRAY]);
  336.         if (!$roles) {
  337.             $this->privileges[$eventName] = [];
  338.         }
  339.         foreach ($roles as $privilege) {
  340.             $this->privileges[$eventName][Uuid::fromBytesToHex($privilege['id'])]
  341.                 = new AclPrivilegeCollection(json_decode($privilege['privileges'], true));
  342.         }
  343.     }
  344.     private function getShopIdProvider(): ShopIdProvider
  345.     {
  346.         if (!$this->container->has(ShopIdProvider::class)) {
  347.             throw new ServiceNotFoundException(ShopIdProvider::class);
  348.         }
  349.         return $this->container->get(ShopIdProvider::class);
  350.     }
  351.     private function getAppLocaleProvider(): AppLocaleProvider
  352.     {
  353.         if (!$this->container->has(AppLocaleProvider::class)) {
  354.             throw new ServiceNotFoundException(AppLocaleProvider::class);
  355.         }
  356.         return $this->container->get(AppLocaleProvider::class);
  357.     }
  358. }