Author: Fabien Potencier (fabien@symfony.com)
Inheritance: extends Response
Exemplo n.º 1
1
 public function postAction(Request $request)
 {
     $form = new ConfigurationForm($request);
     try {
         $configForm = $this->validateForm($form);
         $data = $configForm->getData();
         $paylineConfig = new PaylineConfig();
         $paylineConfig->merge($data);
         // Redirect to the success URL,
         if ($this->getRequest()->get('save_mode') == 'stay') {
             // If we have to stay on the same page, redisplay the configuration page/
             $route = '/admin/module/Payline';
         } else {
             // If we have to close the page, go back to the module back-office page.
             $route = '/admin/modules';
         }
         return RedirectResponse::create(URL::getInstance()->absoluteUrl($route));
     } catch (FormValidationException $e) {
         $error = $this->createStandardFormValidationErrorMessage($e);
     } catch (\Exception $e) {
         $error = $e->getMessage();
     }
     $this->setupFormErrorContext('Payline Configuration', $error, $form, $e);
     return $this->render('module-configure', ['module_code' => 'Payline']);
 }
 /**
  * Returns a 301/302 redirect response based on content parameters.
  *
  * @param  \Raindrop\RoutingBundle\Routing\Base\ExternalRouteInterface $content
  * @return \Symfony\Component\HttpFoundation\RedirectResponse
  */
 public function redirectRouteAction($content)
 {
     $routeParams = $this->get('request')->query->all();
     // do not lose eventual get parameters
     if ($content instanceof ExternalRouteInterface) {
         /**
          * External redirect
          */
         $http_status = $content->getPermanent() ? 301 : 302;
         $uri = $content->getUri();
         if (count($routeParams)) {
             $uri .= (strpos($uri, '?') === false ? '?' : '&') . http_build_query($routeParams);
         }
     } else {
         /**
          * Inner redirect
          */
         $current_route = $this->get('router')->getRouteCollection()->get($this->getRequest()->get('_route'));
         $http_status = $current_route->getPermanent() ? 301 : 302;
         $uri = $this->get('router')->generate($content->getName(), $routeParams, true);
     }
     $response = new RedirectResponse($uri, $http_status);
     $response->setVary('accept-language');
     return $response;
 }
 public function onKernelException(GetResponseForExceptionEvent $event)
 {
     if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
         return;
     }
     $request = $event->getRequest();
     if ('' !== rtrim($request->getPathInfo(), '/')) {
         return;
     }
     $ex = $event->getException();
     if (!$ex instanceof NotFoundHttpException || !$ex->getPrevious() instanceof ResourceNotFoundException) {
         return;
     }
     $locale = $this->localeResolver->resolveLocale($request, $this->locales) ?: $this->defaultLocale;
     $request->setLocale($locale);
     $params = $request->query->all();
     unset($params['hl']);
     $response = new RedirectResponse($request->getBaseUrl() . '/' . $locale . '/' . ($params ? '?' . http_build_query($params) : ''));
     $response->setPrivate();
     $response->setMaxAge(0);
     $response->setSharedMaxAge(0);
     $response->headers->addCacheControlDirective('must-revalidate', true);
     $response->headers->addCacheControlDirective('no-store', true);
     $event->setResponse($response);
 }
Exemplo n.º 4
0
 /**
  * Tries to match a URL path with a set of routes.
  *
  * If the matcher can not find information, it must throw one of the
  * exceptions documented below.
  *
  * @param string $pathinfo The path info to be parsed (raw format, i.e. not
  *                         urldecoded)
  *
  * @return array An array of parameters
  *
  * @throws ResourceNotFoundException If the resource could not be found
  * @throws MethodNotAllowedException If the resource was found but the
  *                                   request method is not allowed
  */
 public function match($pathinfo)
 {
     $urlMatcher = new UrlMatcher($this->routeCollection, $this->getContext());
     $result = $urlMatcher->match($pathinfo);
     if (!empty($result)) {
         try {
             // The route matches, now check if it actually exists
             $result['content'] = $this->contentManager->findActiveBySlug($result['slug']);
         } catch (NoResultException $e) {
             try {
                 //is it directory index
                 if (substr($result['slug'], -1) == '/' || $result['slug'] == '') {
                     $result['content'] = $this->contentManager->findActiveBySlug($result['slug'] . 'index');
                 } else {
                     if ($this->contentManager->findActiveBySlug($result['slug'] . '/index')) {
                         $redirect = new RedirectResponse($this->request->getBaseUrl() . "/" . $result['slug'] . '/');
                         $redirect->sendHeaders();
                         exit;
                     }
                 }
             } catch (NoResultException $ex) {
                 try {
                     $result['content'] = $this->contentManager->findActiveByAlias($result['slug']);
                 } catch (NoResultException $ex) {
                     throw new ResourceNotFoundException('No page found for slug ' . $pathinfo);
                 }
             }
         }
     }
     return $result;
 }
Exemplo n.º 5
0
 public static function listener(RequestEvent $requestEvent)
 {
     $request = $requestEvent->getRequest();
     $pathInfo = $request->getPathInfo();
     $session = $requestEvent->getSession();
     $configSecurity = $requestEvent->getSecurityConfig();
     $routes = $requestEvent->getRoutes();
     $context = new RequestContext();
     $matcher = new UrlMatcher($routes, $context);
     $context->fromRequest($request);
     $matching = $matcher->match($pathInfo);
     $matchedRoute = $matching['_route'];
     if (isset($configSecurity['protected'])) {
         $protected = $configSecurity['protected'];
         $protectedRoutes = $protected['routes'];
         $sessionKey = $protected['session'];
         $notLoggedRoute = $protected['not_logged'];
         $loggedRoute = $protected['logged'];
         $redirectRoute = null;
         if ($session->get($sessionKey) && $matchedRoute === $notLoggedRoute) {
             $redirectRoute = $routes->get($loggedRoute);
         }
         if (!$session->get($sessionKey) && in_array($matchedRoute, $protectedRoutes)) {
             $redirectRoute = $routes->get($notLoggedRoute);
         }
         if ($redirectRoute) {
             $redirectResponse = new RedirectResponse($request->getBaseUrl() . $redirectRoute->getPath());
             $redirectResponse->send();
         }
     }
 }
 /**
  * @Route("/admin/asset/location-type/save")
  * @Method("POST")
  */
 public function saveAction(Request $request)
 {
     $this->denyAccessUnlessGranted('ROLE_SUPER_ADMIN', null, 'Unable to access this page!');
     $em = $this->getDoctrine()->getManager();
     $response = new Response();
     $locationTypes = [];
     $locationTypes['types'] = $em->getRepository('AppBundle\\Entity\\Asset\\LocationType')->findAll();
     $form = $this->createForm(LocationTypesType::class, $locationTypes, ['allow_extra_fields' => true]);
     $form->handleRequest($request);
     if ($form->isSubmitted() && $form->isValid()) {
         $locationTypes = $form->getData();
         foreach ($locationTypes['types'] as $type) {
             $em->persist($type);
         }
         $em->flush();
         $this->addFlash('notice', 'common.success');
         $response = new RedirectResponse($this->generateUrl('app_admin_asset_locationtype_index', [], UrlGeneratorInterface::ABSOLUTE_URL));
         $response->prepare($request);
         return $response->send();
     } else {
         $errorMessages = [];
         $formData = $form->all();
         foreach ($formData as $name => $item) {
             if (!$item->isValid()) {
                 $errorMessages[] = $name . ' - ' . $item->getErrors(true);
             }
         }
         return $this->render('admin/asset/location_types.html.twig', array('location_types_form' => $form->createView(), 'base_dir' => realpath($this->container->getParameter('kernel.root_dir') . '/..')));
     }
 }
Exemplo n.º 7
0
 /**
  * Переключение активной темы
  * @Route("/theme/{theme}", name="theme", defaults={"theme"="web"}, requirements={"theme"="web|phone"})
  */
 public function themeAction(Request $request, $theme)
 {
     $referer = $request->headers->get('referer');
     $response = new RedirectResponse($referer);
     $cookie = new Cookie('theme', $theme, 0, '/', null, false, false);
     $response->headers->setCookie($cookie);
     $response->send();
 }
Exemplo n.º 8
0
 public function run()
 {
     $user = $this->getUser();
     if (empty($user)) {
         $response = new RedirectResponse($this->getApp()->generateUrl('home'));
         $response->send();
         exit;
     }
 }
Exemplo n.º 9
0
 /**
  * Fast redirect in web environment
  * @param string $to
  * @param bool $full
  */
 public function redirect($to, $full = false)
 {
     $to = trim($to, '/');
     if (false === $full && !Str::startsWith(App::$Alias->baseUrl, $to)) {
         $to = App::$Alias->baseUrl . '/' . $to;
     }
     $redirect = new FoundationRedirect($to);
     $redirect->send();
     exit('Redirecting to ' . $to . ' ...');
 }
Exemplo n.º 10
0
 /**
  * Handle the callback.
  *
  * @param OrderInterface $order
  * @param string         $action
  *
  * @return Response
  */
 public function processCallback(OrderInterface $order, $action)
 {
     $params = array('bank' => $this->getCode(), 'reference' => $order->getReference(), 'check' => $this->generateUrlCheck($order), 'action' => $action);
     $url = $this->router->generate($this->getOption('url_callback'), $params, true);
     $response = $this->browser->get($url);
     $routeName = 'ok' === $response->getContent() ? 'url_return_ok' : 'url_return_ko';
     $response = new RedirectResponse($this->router->generate($this->getOption($routeName), $params, true), 302, array('Content-Type' => 'text/plain'));
     $response->setPrivate();
     return $response;
 }
 public function onRegistrationCompleted(FilterUserResponseEvent $event)
 {
     $user = $event->getUser();
     $tenantName = $this->_form->get('tenantName')->getData();
     $tenantSubdomain = $this->_form->get('tenantSubdomain')->getData();
     $tenant = $this->registrationManager->createTenant($user, $tenantName, $tenantSubdomain);
     // this referenced redirect response will be used
     $this->redirectResponse->setTargetUrl($this->tenantAwareRouter->generateUrl($tenant));
     unset($this->_form);
 }
 /**
  * @return int
  */
 public function getStatusCode()
 {
     if (isset($this->exception)) {
         return $this->getExceptionStatusCode();
     } elseif (isset($this->redirect)) {
         return $this->redirect->getStatusCode();
     } elseif ($this->isEmpty()) {
         return Response::HTTP_NO_CONTENT;
     }
     return $this->statusCode;
 }
 public function authorize()
 {
     if ($this->request->has('code')) {
         $state = $this->request->get('state');
         // This was a callback request from linkedin, get the token
         return $this->wunderlistService->requestAccessToken($this->request->get('code'), $state);
     } else {
         $url = $this->wunderlistService->getAuthorizationUri();
         $response = new RedirectResponse($url);
         $response->send();
     }
 }
Exemplo n.º 14
0
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     if (isset($form)) {
         if (isset($form['#token'])) {
             $collection_name = Html::escape($form['searchblox_collection']['#value']);
             \Drupal::state()->set('searchblox_collection', $collection_name);
             $response = new RedirectResponse(\Drupal::url('searchblox.step3'));
             $response->send();
             return;
         }
     }
 }
Exemplo n.º 15
0
 /**
  * Handles an access denied failure redirecting to home page
  *
  * @param Request               $request
  * @param AccessDeniedException $accessDeniedException
  *
  * @return Response may return null
  */
 public function handle(Request $request, AccessDeniedException $accessDeniedException)
 {
     $this->logger->error('User tried to access: ' . $request->getUri());
     if ($request->isXmlHttpRequest()) {
         return new JsonResponse(['message' => $accessDeniedException->getMessage(), 'trace' => $accessDeniedException->getTraceAsString(), 'exception' => get_class($accessDeniedException)], Response::HTTP_SERVICE_UNAVAILABLE);
     } else {
         $url = $request->getBasePath() !== "" ? $request->getBasePath() : "/";
         $response = new RedirectResponse($url);
         $response->setStatusCode(Response::HTTP_FORBIDDEN);
         $response->prepare($request);
         return $response->send();
     }
 }
Exemplo n.º 16
0
 public static function exec($url, $status = 302, $cookies = array())
 {
     trigger_error('deprecated since version 2.1 and will be removed in 2.3. A response can not be send before the end of the script. Please use RedirectResponse directly', E_USER_DEPRECATED);
     if (false == Tlog::getInstance()->showRedirect($url)) {
         $response = new RedirectResponse($url, $status);
         foreach ($cookies as $cookie) {
             if (!$cookie instanceof Cookie) {
                 throw new \InvalidArgumentException(sprintf('Third parameter is not a valid Cookie object.'));
             }
             $response->headers->setCookie($cookie);
         }
         $response->send();
     }
 }
Exemplo n.º 17
0
 /**
  * @Route("/{code}", name="short_url")
  */
 public function indexAction(Request $request, $code)
 {
     $shortCode = $this->get('short_url')->get($code);
     if ($shortCode) {
         $response = new RedirectResponse($shortCode->getUrl(), RedirectResponse::HTTP_FOUND);
         $response->setPublic();
         $response->setExpires(new DateTime('+1 year'));
         return $response;
     }
     $response = new Response();
     $response->setPublic();
     $response->setExpires(new DateTime('+1 hour'));
     return $this->render('notFound.html.twig', ['code' => $code], $response);
 }
Exemplo n.º 18
0
 public function create($request, $response)
 {
     $formFactory = Forms::createFormFactory();
     /* @var $form \Symfony\Component\Form\Form */
     $form = $formFactory->create(new BookType());
     $form->handleRequest();
     if ($form->isValid()) {
         $this->em->persist($form->getData());
         $this->em->flush();
         $this->session->getFlashBag()->add('notice', 'Book inserted');
         $response = new RedirectResponse('/book');
         return $response;
     }
     return $response->create($this->template->render('book/create.html.twig', ['title' => 'New Book', 'form' => $form->createView()]));
 }
Exemplo n.º 19
0
 /**
  *
  * Launch the parser defined on the constructor and get the result.
  *
  * The result is transform id needed into a Response object
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseForControllerResultEvent $event
  */
 public function onKernelView(GetResponseForControllerResultEvent $event)
 {
     $parser = $this->container->get('thelia.parser');
     $templateHelper = $this->container->get('thelia.template_helper');
     $parser->setTemplateDefinition($templateHelper->getActiveFrontTemplate(), true);
     $request = $this->container->get('request_stack')->getCurrentRequest();
     $response = null;
     try {
         $content = $parser->render($request->attributes->get('_view') . ".html");
         if ($content instanceof Response) {
             $response = $content;
         } else {
             $response = new Response($content, $parser->getStatus() ?: 200);
         }
     } catch (ResourceNotFoundException $e) {
         throw new NotFoundHttpException();
     } catch (OrderException $e) {
         switch ($e->getCode()) {
             case OrderException::CART_EMPTY:
                 // Redirect to the cart template
                 $response = RedirectResponse::create($this->container->get('router.chainRequest')->generate($e->cartRoute, $e->arguments, Router::ABSOLUTE_URL));
                 break;
             case OrderException::UNDEFINED_DELIVERY:
                 // Redirect to the delivery choice template
                 $response = RedirectResponse::create($this->container->get('router.chainRequest')->generate($e->orderDeliveryRoute, $e->arguments, Router::ABSOLUTE_URL));
                 break;
         }
         if (null === $response) {
             throw $e;
         }
     }
     $event->setResponse($response);
 }
Exemplo n.º 20
0
 public function handle(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $currentRoute = $request->attributes->get('_route');
     if (!$this->session->has('LDAP_LOGIN_CALLBACK')) {
         if (in_array($currentRoute, $this->allowedRoutes)) {
             $this->session->set('LDAP_LOGIN_CALLBACK', $this->kernel->getParameter('rheck_ldap_firewall.default_url'));
         } else {
             $this->session->set('LDAP_LOGIN_CALLBACK', $currentRoute);
         }
     }
     if (in_array($currentRoute, $this->allowedRoutes)) {
         return;
     }
     if (!$this->session->has('LDAP_LOGIN')) {
         $loginUrl = $this->router->generate($this->kernel->getParameter('rheck_ldap_firewall.login_url'));
         $event->setResponse(RedirectResponse::create($loginUrl));
         return;
     }
     $ldapUserCredentials = $this->session->get('LDAP_LOGIN');
     $token = new LDAPToken();
     $token->setUser('ldap_proxy_user');
     $token->setLDAPUserCredentials($ldapUserCredentials);
     try {
         $authToken = $this->authenticationManager->authenticate($token);
         $this->securityContext->setToken($authToken);
     } catch (AuthenticationException $failed) {
         $this->session->set('LDAP_LOGIN_ERROR', 'Some error was occurred! Can\'t connect to LDAP.');
         $event->setResponse(RedirectResponse::create($this->router->generate('_rheck_ldap_login')));
     } catch (\Exception $e) {
         $this->session->set('LDAP_LOGIN_ERROR', 'Invalid credentials.');
         $event->setResponse(RedirectResponse::create($this->router->generate('_rheck_ldap_login')));
     }
 }
Exemplo n.º 21
0
 /**
  * @param Request $request
  * @param View $view
  * @param Session $session
  * @param array|string $url
  * @param int $status
  * @param array $headers
  */
 public function __construct(Request $request, View $view, Session $session, $url = ROOT, $status = 302, $headers = array())
 {
     $this->request = $request;
     $this->view = $view;
     $this->session = $session;
     parent::__construct($url, $status, $headers);
 }
 /**
  * {@inheritdoc}
  */
 public function setTargetUrl($url)
 {
     if (!$this->isSafe($url)) {
         throw new \InvalidArgumentException(sprintf('It is not safe to redirect to %s', $url));
     }
     return parent::setTargetUrl($url);
 }
Exemplo n.º 23
0
 public function authenticationException(GetResponseForExceptionEvent $event)
 {
     $exception = $event->getException();
     if ($exception instanceof AuthenticationException) {
         $event->setResponse(RedirectResponse::create($exception->getLoginTemplate()));
     }
 }
Exemplo n.º 24
0
 public function loginAction()
 {
     $customerController = new BaseCustomerController();
     $customerController->setContainer($this->container);
     $response = $customerController->loginAction();
     if (!$this->getSecurityContext()->hasCustomerUser()) {
         $request = $this->getRequest();
         $customerLoginForm = new CustomerLogin($request);
         try {
             $form = $this->validateForm($customerLoginForm, "post");
             $request = CustomerTempQuery::create();
             $customerTemp = $request->where('`customer_temp`.email = ?', $form->get('email')->getData(), \PDO::PARAM_STR)->where('`customer_temp`.password = PASSWORD(?)', $form->get('password')->getData(), \PDO::PARAM_STR)->where('`customer_temp`.processed = 0')->findOne();
             if (null !== $customerTemp) {
                 $customer = CustomerQuery::create()->findOneByEmail($form->get('email')->getData());
                 $customer->setPassword($form->get('password')->getData())->save();
                 $customerTemp->setProcessed(true)->save();
                 $this->dispatch(TheliaEvents::CUSTOMER_LOGIN, new CustomerLoginEvent($customer));
                 $successUrl = $customerLoginForm->getSuccessUrl();
                 $response = RedirectResponse::create($successUrl);
             }
         } catch (\Exception $e) {
         }
     }
     return $response;
 }
Exemplo n.º 25
0
 /** {@inheritdoc} */
 public function showFront(Template $template = null)
 {
     if (is_array($this->languages) && count($this->languages)) {
         // allowed languages
         $allowedLanguages = array();
         foreach ($this->languages as $lang) {
             $allowedLanguages[$lang['code']] = $lang;
         }
         // find preferred language
         reset($this->languages);
         $language = current($this->languages);
         foreach ($this->getLanguage() as $lang => $quality) {
             if (array_key_exists($lang, $allowedLanguages)) {
                 $language = $allowedLanguages[$lang];
                 break;
             }
         }
         $page = \PageQuery::create()->findPk($language['page_id']);
         if ($page) {
             return RedirectResponse::create(url($page->getUrl(), $_GET));
         } else {
             $this->app->logger->notice('Redirect page not found');
         }
     } else {
         $this->app->logger->notice('No languages found');
     }
     return '';
 }
Exemplo n.º 26
0
    /**
     * Automatically perform any required redirect
     *
     * This method is meant to be a helper for simple scenarios. If you want to customize the
     * redirection page, just call the getRedirectUrl() and getRedirectData() methods directly.
     */
    public function redirect()
    {
        if (!$this instanceof RedirectResponseInterface || !$this->isRedirect()) {
            throw new RuntimeException('This response does not support redirection.');
        }
        if ('GET' === $this->getRedirectMethod()) {
            HttpRedirectResponse::create($this->getRedirectUrl())->send();
            exit;
        } elseif ('POST' === $this->getRedirectMethod()) {
            $hiddenFields = '';
            foreach ($this->getRedirectData() as $key => $value) {
                $hiddenFields .= sprintf('<input type="hidden" name="%1$s" value="%2$s" />', htmlspecialchars($key, ENT_QUOTES, 'UTF-8'), htmlspecialchars($value, ENT_QUOTES, 'UTF-8')) . "\n";
            }
            $output = '<!DOCTYPE html>
<html>
    <head>
        <title>Redirecting...</title>
    </head>
    <body onload="document.forms[0].submit();">
        <form action="%1$s" method="post">
            <p>Redirecting to payment page...</p>
            <p>
                %2$s
                <input type="submit" value="Continue" />
            </p>
        </form>
    </body>
</html>';
            $output = sprintf($output, htmlspecialchars($this->redirectUrl, ENT_QUOTES, 'UTF-8'), $hiddenFields);
            HttpResponse::create($output)->send();
            exit;
        }
        throw new RuntimeException('Invalid redirect method "' . $this->getRedirectMethod() . '".');
    }
Exemplo n.º 27
0
 public function submitForm(array &$form, FormStateInterface $form_state)
 {
     if (isset($form)) {
         if (isset($form['#token'])) {
             $api = Html::escape($form['searchblox_api']['#value']);
             $location = rtrim(Html::escape($form['searchblox_location']['#value']), '/');
             $location = searchblox_addhttp($location);
             $port_no = intval(Html::escape($form['searchblox_portno']['#value']));
             \Drupal::state()->set('searchblox_apikey', $api);
             \Drupal::state()->set('searchblox_location', $location);
             \Drupal::state()->set('searchblox_portno', $port_no);
             $response = new RedirectResponse(\Drupal::url('searchblox.step2'));
             $response->send();
             return;
         }
     }
 }
Exemplo n.º 28
0
 public function setTargetUrl($url)
 {
     if ($url == '') {
         $url = '/';
     }
     return parent::setTargetUrl($url);
     // TODO: Change the autogenerated stub
 }
 /**
  * Creates a redirect response so that it conforms to the rules defined for a redirect status code.
  *
  * @param string  $url    The URL to redirect to
  * @param integer $status The status code (302 by default)
  * @param Cookie  $cookie An array of Cookie objects
  */
 public function __construct($url, $status = 302, $cookie = 'full')
 {
     parent::__construct($url, $status);
     if (!$cookie instanceof Cookie) {
         throw new \InvalidArgumentException(sprintf('Third parameter is not a valid Cookie object.'));
     }
     $this->headers->setCookie($cookie);
 }
Exemplo n.º 30
-1
 protected function canBeRedirected(Request $request, RedirectResponse $response)
 {
     $targetRequest = Request::create($response->getTargetUrl());
     $stripUrl = function ($path) {
         return preg_replace('/#.+$/', '', $path);
     };
     $targetPath = $stripUrl($targetRequest->getBaseUrl() . $targetRequest->getPathInfo());
     $currentPath = $stripUrl($request->getBaseUrl() . $request->getPathInfo());
     return $targetPath !== $currentPath;
 }