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

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