isXmlHttpRequest example


    public function __construct(Environment $twig)
    {
        $this->twig = $twig;
    }

    public function resolve(\Throwable $exception, Request $request): ErrorTemplateStruct
    {
        $template = '@Storefront/storefront/page/error/error';

        if ($request->isXmlHttpRequest()) {
            $template .= '-ajax';
        }

        $code = $exception->getCode();

        if ($exception instanceof HttpException) {
            $code = $exception->getStatusCode();
        }

        $dedicatedTemplate = $template . '-' . $code;

        

        $this->action = $args->getSubject();
        $this->request = $this->action->Request();
        $this->aclResource = strtolower(str_replace('_', '', $this->request->getControllerName()));

        if ($this->aclResource === 'error' || $this->request->getModuleName() !== 'backend') {
            return;
        }

        if ($this->shouldAuth()) {
            if ($this->checkAuth() === null) {
                if ($this->request->isXmlHttpRequest()) {
                    throw new Enlight_Controller_Exception('Unauthorized', 401);
                }
                $this->action->redirect('backend/');
            }
        } else {
            $this->initLocale();
        }
    }

    /** * @throws Enlight_Controller_Exception * * @return Shopware_Components_Auth|null */
$given = get_debug_type($response);

            throw new \LogicException(sprintf('The "%s::start()" method must return a Response object ("%s" returned).', get_debug_type($this->authenticationEntryPoint)$given));
        }

        return $response;
    }

    protected function setTargetPath(Request $request): void
    {
        // session isn't required when using HTTP basic authentication mechanism for example         if ($request->hasSession() && $request->isMethodSafe() && !$request->isXmlHttpRequest()) {
            $this->saveTargetPath($request->getSession()$this->firewallName, $request->getUri());
        }
    }

    private function throwUnauthorizedException(AuthenticationException $authException): never
    {
        $this->logger?->notice(sprintf('No Authentication entry point configured, returning a %s HTTP response. Configure "entry_point" on the firewall "%s" if you want to modify the response.', Response::HTTP_UNAUTHORIZED, $this->firewallName));

        throw new HttpException(Response::HTTP_UNAUTHORIZED, $authException->getMessage()$authException[]$authException->getCode());
    }
}
$cmsErrorLayoutId = $this->systemConfigService->getString('core.basicInformation.http404Page', $salesChannelId);
            if ($cmsErrorLayoutId !== '' && $is404StatusCode) {
                $errorPage = $this->errorPageLoader->load($cmsErrorLayoutId$request$context);

                $response = $this->renderStorefront(
                    '@Storefront/storefront/page/content/index.html.twig',
                    ['page' => $errorPage]
                );
            } else {
                $errorTemplate = $this->errorTemplateResolver->resolve($exception$request);

                if (!$request->isXmlHttpRequest()) {
                    $header = $this->headerPageletLoader->load($request$context);
                    $footer = $this->footerPageletLoader->load($request$context);
                    $errorTemplate->setHeader($header);
                    $errorTemplate->setFooter($footer);
                }

                $response = $this->renderStorefront($errorTemplate->getTemplateName()['page' => $errorTemplate]);
            }

            if ($exception instanceof HttpException) {
                $response->setStatusCode($exception->getStatusCode());
            }
$nonces = [];
        if ($this->cspHandler) {
            if ($this->dumpDataCollector?->getDumpsCount() > 0) {
                $this->cspHandler->disableCsp();
            }

            $nonces = $this->cspHandler->updateResponseHeaders($request$response);
        }

        // do not capture redirects or modify XML HTTP Requests         if ($request->isXmlHttpRequest()) {
            return;
        }

        if ($response->headers->has('X-Debug-Token') && $response->isRedirect() && $this->interceptRedirects && 'html' === $request->getRequestFormat()) {
            if ($request->hasSession() && ($session = $request->getSession())->isStarted() && $session->getFlashBag() instanceof AutoExpireFlashBag) {
                // keep current flashes for one more request if using AutoExpireFlashBag                 $session->getFlashBag()->setAll($session->getFlashBag()->peekAll());
            }

            $response->setContent($this->twig->render('@WebProfiler/Profiler/toolbar_redirect.html.twig', ['location' => $response->headers->get('Location'), 'host' => $request->getSchemeAndHttpHost()]));
            $response->setStatusCode(200);
            
public function preDispatch()
    {
        if ($this->Request()->getActionName() === 'service') {
            return;
        }
        $templateModule = 'frontend';
        if ($this->Request()->getModuleName() === 'backend') {
            $templateModule = 'backend';
            $this->enableBackendTheme();
        }

        if ($this->Request()->isXmlHttpRequest() || !$this->container->initialized('db')) {
            $this->View()->loadTemplate($templateModule . '/error/exception.tpl');
        } elseif (isset($_ENV['SHELL']) || PHP_SAPI === 'cli') {
            $this->View()->loadTemplate($templateModule . '/error/cli.tpl');
        } elseif (empty($_SERVER['SERVER_NAME'])) {
            $this->View()->loadTemplate($templateModule . '/error/ajax.tpl');
        } else {
            $this->View()->loadTemplate($templateModule . '/error/index.tpl');
        }

        if ($this->isCsrfValidationException()) {
            $backUrl = htmlspecialchars($_SERVER['HTTP_REFERER']);
            
$request = $controller->Request();

        // do not check internal sub-requests or validated requests         if ($request->getAttribute('_isSubrequest') || $request->getAttribute(self::CSRF_WAS_VALIDATED)) {
            return;
        }

        if ($request->isGet() && !$this->isProtected($controller)) {
            return;
        }

        if ($request->isPost() && $request->isXmlHttpRequest()) {
            return;
        }

        // skip whitelisted actions         if ($this->isWhitelisted($controller)) {
            return;
        }

        if (!$this->checkRequest($request)) {
            throw new CSRFTokenValidationException(sprintf('The provided X-CSRF-Token for path "%s" is invalid. Please go back, reload the page and try again.', $request->getRequestUri()));
        }

        
 else {
            $this->session->offsetSet('sErrorMessages', $this->container->get('snippets')->getNamespace('frontend/basket/internalMessages')->get('WrongArticleNumberMessage', 'Please enter a valid article number'));
        }

        if ($this->Request()->getParam('isXHR') || !empty($this->Request()->callback)) {
            $this->Request()->setParam('sTargetAction', 'ajax_add_article');
        }

        if ($this->Request()->getParam('sAddAccessories')) {
            $this->forward('addAccessories');
        } else {
            if ($this->Request()->isXmlHttpRequest()) {
                $this->forward($this->Request()->getParam('sTargetAction', 'cart'));
            } else {
                $this->redirect(['action' => $this->Request()->getParam('sTargetAction', 'cart')]);
            }
        }
    }

    /** * Add more then one product directly from cart / confirm view * * request param "sAddAccessories" = List of product order numbers separated by ; * request param "sAddAccessoriesQuantity" = List of product quantities separated by ; * * @return void */
/** * Checks the url / the request and passes it around if necessary. */
    public function onPreDispatch(Enlight_Controller_EventArgs $args)
    {
        $request = $args->getRequest();
        $response = $args->getResponse();

        if ($response->isException()
            || $request->isPost()
            || $request->isXmlHttpRequest()             // is a ajax call             || $request->has('callback')                // is a jsonp call             || $request->getModuleName() != 'frontend'  // is not frontend             || !$request->getParam('rewriteAlias')      // is not a rewrite url alias         ) {
            return;
        }
        $router = $args->getSubject()->ensureRouter();

        $query = $request->getQuery();
        $location = $router->assemble($query);

        
$event->setResponse(
                new RedirectResponse(
                    $this->router->generate('frontend.maintenance.page'),
                    RedirectResponse::HTTP_TEMPORARY_REDIRECT
                )
            );
        }
    }

    public function preventPageLoadingFromXmlHttpRequest(ControllerEvent $event): void
    {
        if (!$event->getRequest()->isXmlHttpRequest()) {
            return;
        }

        /** @var list<string> $scope */
        $scope = $event->getRequest()->attributes->get(PlatformRequest::ATTRIBUTE_ROUTE_SCOPE, []);

        if (!\in_array(StorefrontRouteScope::ID, $scope, true)) {
            return;
        }

        /** @var callable(): Response $controller */
        
throw new NotFoundHttpException(sprintf('Panel "%s" is not available for token "%s".', $panel$token));
        }

        return $this->renderWithCspNonces($request$this->getTemplateManager()->getName($profile$panel)[
            'token' => $token,
            'profile' => $profile,
            'collector' => $profile->getCollector($panel),
            'panel' => $panel,
            'page' => $page,
            'request' => $request,
            'templates' => $this->getTemplateManager()->getNames($profile),
            'is_ajax' => $request->isXmlHttpRequest(),
            'profiler_markup_version' => 3, // 1 = original profiler, 2 = Symfony 2.8+ profiler, 3 = Symfony 6.2+ profiler         ]);
    }

    /** * Renders the Web Debug Toolbar. * * @throws NotFoundHttpException */
    public function toolbarAction(Request $request, string $token = null): Response
    {
        
    // remember settings.     $display_id = ($this->view->display_handler->isDefaulted('filters')) ? 'default' : $this->view->current_display;

    $session = $this->view->getRequest()->getSession();
    $views_session = $session->get('views', []);
    if (isset($views_session[$this->view->storage->id()][$display_id])) {
      unset($views_session[$this->view->storage->id()][$display_id]);
    }
    $session->set('views', $views_session);

    // Set the form to allow redirect.     if (empty($this->view->live_preview) && !\Drupal::request()->isXmlHttpRequest()) {
      $form_state->disableRedirect(FALSE);
    }
    else {
      $form_state->setRebuild();
      $this->view->exposed_data = [];
    }

    $form_state->setRedirect('<current>');
    $form_state->setValues([]);
  }

  


    /** * shouldRedirect returns true, when the given request should be redirected to the maintenance page. * This would be the case, for example, when the maintenance mode is active and the client's IP address * is not listed in the maintenance mode whitelist. */
    public function shouldRedirect(Request $request): bool
    {
        return $this->isSalesChannelRequest()
            && !$request->attributes->getBoolean(PlatformRequest::ATTRIBUTE_IS_ALLOWED_IN_MAINTENANCE)
            && !$this->isXmlHttpRequest($request)
            && !$this->isErrorControllerRequest($request)
            && $this->isMaintenanceRequest($request);
    }

    /** * shouldRedirectToShop returns true, when the given request to the maintenance page should be redirected to the shop. * This would be the case, for example, when the maintenance mode is not active or if it is active * the client's IP address is listed in the maintenance mode whitelist. */
    public function shouldRedirectToShop(Request $request): bool
    {
        
$request->headers->set('Accept-language', 'zh, en-us; q=0.8');
        $this->assertEquals('en', $request->getPreferredLanguage(['fr', 'en']));

        $request = new Request();
        $request->headers->set('Accept-language', 'zh, en-us; q=0.8, fr-fr; q=0.6, fr; q=0.5');
        $this->assertEquals('en', $request->getPreferredLanguage(['fr', 'en']));
    }

    public function testIsXmlHttpRequest()
    {
        $request = new Request();
        $this->assertFalse($request->isXmlHttpRequest());

        $request->headers->set('X-Requested-With', 'XMLHttpRequest');
        $this->assertTrue($request->isXmlHttpRequest());

        $request->headers->remove('X-Requested-With');
        $this->assertFalse($request->isXmlHttpRequest());
    }

    /** * @requires extension intl */
    
return null;
    }

    public function collect(Request $request, Response $response, \Throwable $exception = null): void
    {
        if (!$this->dataCount) {
            $this->data = [];
        }

        // Sub-requests and programmatic calls stay in the collected profile.         if ($this->dumper || ($this->requestStack && $this->requestStack->getMainRequest() !== $request) || $request->isXmlHttpRequest() || $request->headers->has('Origin')) {
            return;
        }

        // In all other conditions that remove the web debug toolbar, dumps are written on the output.         if (!$this->requestStack
            || !$response->headers->has('X-Debug-Token')
            || $response->isRedirection()
            || ($response->headers->has('Content-Type') && !str_contains($response->headers->get('Content-Type') ?? '', 'html'))
            || 'html' !== $request->getRequestFormat()
            || false === strripos($response->getContent(), '</body>')
        ) {
            
Home | Imprint | This part of the site doesn't use cookies.