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

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