vendor/shopware/storefront/Framework/Routing/StorefrontSubscriber.php line 211

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace Shopware\Storefront\Framework\Routing;
  3. use Shopware\Core\Checkout\Cart\Exception\CustomerNotLoggedInException;
  4. use Shopware\Core\Checkout\Customer\Event\CustomerLoginEvent;
  5. use Shopware\Core\Checkout\Customer\Event\CustomerLogoutEvent;
  6. use Shopware\Core\Content\Seo\HreflangLoaderInterface;
  7. use Shopware\Core\Content\Seo\HreflangLoaderParameter;
  8. use Shopware\Core\Framework\App\ActiveAppsLoader;
  9. use Shopware\Core\Framework\App\Exception\AppUrlChangeDetectedException;
  10. use Shopware\Core\Framework\App\ShopId\ShopIdProvider;
  11. use Shopware\Core\Framework\Event\BeforeSendResponseEvent;
  12. use Shopware\Core\Framework\Feature;
  13. use Shopware\Core\Framework\Routing\Annotation\RouteScope;
  14. use Shopware\Core\Framework\Routing\Event\SalesChannelContextResolvedEvent;
  15. use Shopware\Core\Framework\Routing\KernelListenerPriorities;
  16. use Shopware\Core\Framework\Util\Random;
  17. use Shopware\Core\PlatformRequest;
  18. use Shopware\Core\SalesChannelRequest;
  19. use Shopware\Core\System\SalesChannel\SalesChannelContext;
  20. use Shopware\Core\System\SystemConfig\SystemConfigService;
  21. use Shopware\Storefront\Event\StorefrontRenderEvent;
  22. use Shopware\Storefront\Framework\Csrf\CsrfPlaceholderHandler;
  23. use Shopware\Storefront\Framework\Routing\NotFound\NotFoundSubscriber;
  24. use Shopware\Storefront\Theme\StorefrontPluginRegistryInterface;
  25. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  26. use Symfony\Component\HttpFoundation\RedirectResponse;
  27. use Symfony\Component\HttpFoundation\RequestStack;
  28. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  29. use Symfony\Component\HttpKernel\Event\ControllerEvent;
  30. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  31. use Symfony\Component\HttpKernel\Event\RequestEvent;
  32. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  33. use Symfony\Component\HttpKernel\KernelEvents;
  34. use Symfony\Component\Routing\RouterInterface;
  35. /**
  36.  * @deprecated tag:v6.5.0 - reason:becomes-internal - EventSubscribers will become internal in v6.5.0
  37.  */
  38. class StorefrontSubscriber implements EventSubscriberInterface
  39. {
  40.     private RequestStack $requestStack;
  41.     private RouterInterface $router;
  42.     private CsrfPlaceholderHandler $csrfPlaceholderHandler;
  43.     private MaintenanceModeResolver $maintenanceModeResolver;
  44.     private HreflangLoaderInterface $hreflangLoader;
  45.     private ShopIdProvider $shopIdProvider;
  46.     private ActiveAppsLoader $activeAppsLoader;
  47.     private SystemConfigService $systemConfigService;
  48.     private StorefrontPluginRegistryInterface $themeRegistry;
  49.     private NotFoundSubscriber $notFoundSubscriber;
  50.     /**
  51.      * @internal
  52.      */
  53.     public function __construct(
  54.         RequestStack $requestStack,
  55.         RouterInterface $router,
  56.         CsrfPlaceholderHandler $csrfPlaceholderHandler,
  57.         HreflangLoaderInterface $hreflangLoader,
  58.         MaintenanceModeResolver $maintenanceModeResolver,
  59.         ShopIdProvider $shopIdProvider,
  60.         ActiveAppsLoader $activeAppsLoader,
  61.         SystemConfigService $systemConfigService,
  62.         StorefrontPluginRegistryInterface $themeRegistry,
  63.         NotFoundSubscriber $notFoundSubscriber
  64.     ) {
  65.         $this->requestStack $requestStack;
  66.         $this->router $router;
  67.         $this->csrfPlaceholderHandler $csrfPlaceholderHandler;
  68.         $this->maintenanceModeResolver $maintenanceModeResolver;
  69.         $this->hreflangLoader $hreflangLoader;
  70.         $this->shopIdProvider $shopIdProvider;
  71.         $this->activeAppsLoader $activeAppsLoader;
  72.         $this->systemConfigService $systemConfigService;
  73.         $this->themeRegistry $themeRegistry;
  74.         $this->notFoundSubscriber $notFoundSubscriber;
  75.     }
  76.     public static function getSubscribedEvents(): array
  77.     {
  78.         if (Feature::isActive('v6.5.0.0')) {
  79.             return [
  80.                 KernelEvents::REQUEST => [
  81.                     ['startSession'40],
  82.                     ['maintenanceResolver'],
  83.                 ],
  84.                 KernelEvents::EXCEPTION => [
  85.                     ['customerNotLoggedInHandler'],
  86.                     ['maintenanceResolver'],
  87.                 ],
  88.                 KernelEvents::CONTROLLER => [
  89.                     ['preventPageLoadingFromXmlHttpRequest'KernelListenerPriorities::KERNEL_CONTROLLER_EVENT_SCOPE_VALIDATE],
  90.                 ],
  91.                 CustomerLoginEvent::class => [
  92.                     'updateSessionAfterLogin',
  93.                 ],
  94.                 CustomerLogoutEvent::class => [
  95.                     'updateSessionAfterLogout',
  96.                 ],
  97.                 BeforeSendResponseEvent::class => [
  98.                     ['replaceCsrfToken'],
  99.                     ['setCanonicalUrl'],
  100.                 ],
  101.                 StorefrontRenderEvent::class => [
  102.                     ['addHreflang'],
  103.                     ['addShopIdParameter'],
  104.                     ['addIconSetConfig'],
  105.                 ],
  106.                 SalesChannelContextResolvedEvent::class => [
  107.                     ['replaceContextToken'],
  108.                 ],
  109.             ];
  110.         }
  111.         return [
  112.             KernelEvents::REQUEST => [
  113.                 ['startSession'40],
  114.                 ['maintenanceResolver'],
  115.             ],
  116.             KernelEvents::EXCEPTION => [
  117.                 ['showHtmlExceptionResponse', -100],
  118.                 ['customerNotLoggedInHandler'],
  119.                 ['maintenanceResolver'],
  120.             ],
  121.             KernelEvents::CONTROLLER => [
  122.                 ['preventPageLoadingFromXmlHttpRequest'KernelListenerPriorities::KERNEL_CONTROLLER_EVENT_SCOPE_VALIDATE],
  123.             ],
  124.             CustomerLoginEvent::class => [
  125.                 'updateSessionAfterLogin',
  126.             ],
  127.             CustomerLogoutEvent::class => [
  128.                 'updateSessionAfterLogout',
  129.             ],
  130.             BeforeSendResponseEvent::class => [
  131.                 ['replaceCsrfToken'],
  132.                 ['setCanonicalUrl'],
  133.             ],
  134.             StorefrontRenderEvent::class => [
  135.                 ['addHreflang'],
  136.                 ['addShopIdParameter'],
  137.                 ['addIconSetConfig'],
  138.             ],
  139.             SalesChannelContextResolvedEvent::class => [
  140.                 ['replaceContextToken'],
  141.             ],
  142.         ];
  143.     }
  144.     public function startSession(): void
  145.     {
  146.         $master $this->requestStack->getMainRequest();
  147.         if (!$master) {
  148.             return;
  149.         }
  150.         if (!$master->attributes->get(SalesChannelRequest::ATTRIBUTE_IS_SALES_CHANNEL_REQUEST)) {
  151.             return;
  152.         }
  153.         if (!$master->hasSession()) {
  154.             return;
  155.         }
  156.         $session $master->getSession();
  157.         if (!$session->isStarted()) {
  158.             $session->setName('session-');
  159.             $session->start();
  160.             $session->set('sessionId'$session->getId());
  161.         }
  162.         $salesChannelId $master->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID);
  163.         if ($salesChannelId === null) {
  164.             /** @var SalesChannelContext|null $salesChannelContext */
  165.             $salesChannelContext $master->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT);
  166.             if ($salesChannelContext !== null) {
  167.                 $salesChannelId $salesChannelContext->getSalesChannel()->getId();
  168.             }
  169.         }
  170.         if ($this->shouldRenewToken($session$salesChannelId)) {
  171.             $token Random::getAlphanumericString(32);
  172.             $session->set(PlatformRequest::HEADER_CONTEXT_TOKEN$token);
  173.             $session->set(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID$salesChannelId);
  174.         }
  175.         $master->headers->set(
  176.             PlatformRequest::HEADER_CONTEXT_TOKEN,
  177.             $session->get(PlatformRequest::HEADER_CONTEXT_TOKEN)
  178.         );
  179.     }
  180.     public function updateSessionAfterLogin(CustomerLoginEvent $event): void
  181.     {
  182.         $token $event->getContextToken();
  183.         $this->updateSession($token);
  184.     }
  185.     public function updateSessionAfterLogout(): void
  186.     {
  187.         $newToken Random::getAlphanumericString(32);
  188.         $this->updateSession($newTokentrue);
  189.     }
  190.     public function updateSession(string $tokenbool $destroyOldSession false): void
  191.     {
  192.         $master $this->requestStack->getMainRequest();
  193.         if (!$master) {
  194.             return;
  195.         }
  196.         if (!$master->attributes->get(SalesChannelRequest::ATTRIBUTE_IS_SALES_CHANNEL_REQUEST)) {
  197.             return;
  198.         }
  199.         if (!$master->hasSession()) {
  200.             return;
  201.         }
  202.         $session $master->getSession();
  203.         $session->migrate($destroyOldSession);
  204.         $session->set('sessionId'$session->getId());
  205.         $session->set(PlatformRequest::HEADER_CONTEXT_TOKEN$token);
  206.         $master->headers->set(PlatformRequest::HEADER_CONTEXT_TOKEN$token);
  207.     }
  208.     /**
  209.      * @deprecated tag:v6.5.0 - reason:remove-subscriber - Use `NotFoundSubscriber::onError` instead
  210.      */
  211.     public function showHtmlExceptionResponse(ExceptionEvent $event): void
  212.     {
  213.         $this->notFoundSubscriber->onError($event);
  214.     }
  215.     public function customerNotLoggedInHandler(ExceptionEvent $event): void
  216.     {
  217.         if (!$event->getRequest()->attributes->has(SalesChannelRequest::ATTRIBUTE_IS_SALES_CHANNEL_REQUEST)) {
  218.             return;
  219.         }
  220.         if (!$event->getThrowable() instanceof CustomerNotLoggedInException) {
  221.             return;
  222.         }
  223.         $request $event->getRequest();
  224.         $parameters = [
  225.             'redirectTo' => $request->attributes->get('_route'),
  226.             'redirectParameters' => json_encode($request->attributes->get('_route_params')),
  227.         ];
  228.         $redirectResponse = new RedirectResponse($this->router->generate('frontend.account.login.page'$parameters));
  229.         $event->setResponse($redirectResponse);
  230.     }
  231.     public function maintenanceResolver(RequestEvent $event): void
  232.     {
  233.         if ($this->maintenanceModeResolver->shouldRedirect($event->getRequest())) {
  234.             $event->setResponse(
  235.                 new RedirectResponse(
  236.                     $this->router->generate('frontend.maintenance.page'),
  237.                     RedirectResponse::HTTP_TEMPORARY_REDIRECT
  238.                 )
  239.             );
  240.         }
  241.     }
  242.     public function preventPageLoadingFromXmlHttpRequest(ControllerEvent $event): void
  243.     {
  244.         if (!$event->getRequest()->isXmlHttpRequest()) {
  245.             return;
  246.         }
  247.         /** @var RouteScope|list<string> $scope */
  248.         $scope $event->getRequest()->attributes->get(PlatformRequest::ATTRIBUTE_ROUTE_SCOPE, []);
  249.         if ($scope instanceof RouteScope) {
  250.             $scope $scope->getScopes();
  251.         }
  252.         if (!\in_array(StorefrontRouteScope::ID$scopetrue)) {
  253.             return;
  254.         }
  255.         $controller $event->getController();
  256.         // happens if Controller is a closure
  257.         if (!\is_array($controller)) {
  258.             return;
  259.         }
  260.         $isAllowed $event->getRequest()->attributes->getBoolean('XmlHttpRequest'false);
  261.         if ($isAllowed) {
  262.             return;
  263.         }
  264.         throw new AccessDeniedHttpException('PageController can\'t be requested via XmlHttpRequest.');
  265.     }
  266.     // used to switch session token - when the context token expired
  267.     public function replaceContextToken(SalesChannelContextResolvedEvent $event): void
  268.     {
  269.         $context $event->getSalesChannelContext();
  270.         // only update session if token expired and switched
  271.         if ($event->getUsedToken() === $context->getToken()) {
  272.             return;
  273.         }
  274.         $this->updateSession($context->getToken());
  275.     }
  276.     public function setCanonicalUrl(BeforeSendResponseEvent $event): void
  277.     {
  278.         if (!$event->getResponse()->isSuccessful()) {
  279.             return;
  280.         }
  281.         if ($canonical $event->getRequest()->attributes->get(SalesChannelRequest::ATTRIBUTE_CANONICAL_LINK)) {
  282.             $canonical sprintf('<%s>; rel="canonical"'$canonical);
  283.             $event->getResponse()->headers->set('Link'$canonical);
  284.         }
  285.     }
  286.     public function replaceCsrfToken(BeforeSendResponseEvent $event): void
  287.     {
  288.         $event->setResponse(
  289.             $this->csrfPlaceholderHandler->replaceCsrfToken($event->getResponse(), $event->getRequest())
  290.         );
  291.     }
  292.     public function addHreflang(StorefrontRenderEvent $event): void
  293.     {
  294.         $request $event->getRequest();
  295.         $route $request->attributes->get('_route');
  296.         if ($route === null) {
  297.             return;
  298.         }
  299.         $routeParams $request->attributes->get('_route_params', []);
  300.         $salesChannelContext $request->attributes->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_CONTEXT_OBJECT);
  301.         $parameter = new HreflangLoaderParameter($route$routeParams$salesChannelContext);
  302.         $event->setParameter('hrefLang'$this->hreflangLoader->load($parameter));
  303.     }
  304.     public function addShopIdParameter(StorefrontRenderEvent $event): void
  305.     {
  306.         if (!$this->activeAppsLoader->getActiveApps()) {
  307.             return;
  308.         }
  309.         try {
  310.             $shopId $this->shopIdProvider->getShopId();
  311.         } catch (AppUrlChangeDetectedException $e) {
  312.             return;
  313.         }
  314.         $event->setParameter('appShopId'$shopId);
  315.     }
  316.     public function addIconSetConfig(StorefrontRenderEvent $event): void
  317.     {
  318.         $request $event->getRequest();
  319.         // get name if theme is not inherited
  320.         $theme $request->attributes->get(SalesChannelRequest::ATTRIBUTE_THEME_NAME);
  321.         if (!$theme) {
  322.             // get theme name from base theme because for inherited themes the name is always null
  323.             $theme $request->attributes->get(SalesChannelRequest::ATTRIBUTE_THEME_BASE_NAME);
  324.         }
  325.         if (!$theme) {
  326.             return;
  327.         }
  328.         $themeConfig $this->themeRegistry->getConfigurations()->getByTechnicalName($theme);
  329.         if (!$themeConfig) {
  330.             return;
  331.         }
  332.         $iconConfig = [];
  333.         foreach ($themeConfig->getIconSets() as $pack => $path) {
  334.             $iconConfig[$pack] = [
  335.                 'path' => $path,
  336.                 'namespace' => $theme,
  337.             ];
  338.         }
  339.         $event->setParameter('themeIconConfig'$iconConfig);
  340.     }
  341.     private function shouldRenewToken(SessionInterface $session, ?string $salesChannelId null): bool
  342.     {
  343.         if (!$session->has(PlatformRequest::HEADER_CONTEXT_TOKEN) || $salesChannelId === null) {
  344.             return true;
  345.         }
  346.         if ($this->systemConfigService->get('core.systemWideLoginRegistration.isCustomerBoundToSalesChannel')) {
  347.             return $session->get(PlatformRequest::ATTRIBUTE_SALES_CHANNEL_ID) !== $salesChannelId;
  348.         }
  349.         return false;
  350.     }
  351. }