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

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