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') . '/..'))); } }
/** * Переключение активной темы * @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(); }
public function run() { $user = $this->getUser(); if (empty($user)) { $response = new RedirectResponse($this->getApp()->generateUrl('home')); $response->send(); exit; } }
/** * 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 . ' ...'); }
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; } } }
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(); } }
public function send() { $cleared = \Cookie::getClearedCookies(); foreach ($cleared as $cookie) { $this->headers->clearCookie($cookie); } // First, we see if we have any cookies to send along $cookies = \Cookie::getCookies(); foreach ($cookies as $cookie) { $this->headers->setCookie($cookie); } parent::send(); }
/** * 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(); } }
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(); } }
public function onKernelController(FilterControllerEvent $event) { $controller = $event->getController(); if (!is_array($controller)) { return; } //var_dump(get_class($controller[0])); //exit; if (!$controller[0] instanceof SecurityController) { $needRegister = $event->getRequest()->getSession()->get('needRegister'); if ($needRegister === true) { $url = $this->router->generate('register'); $redirect = new RedirectResponse($url); $redirect->send(); } } }
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; } } }
/** * Redirect to a url (safely) * * This function safely shuts down Symfony by making sure the * response and terminate kernel events are called. * * @param string $url The url to redirect to * @param int $response_code http response code (defaults to 302) */ function zen_redirect($url, $responseCode = 302) { // fix accidental ampersands $url = str_replace(array('&', '&&'), '&', $url); $container = Runtime::getContainer(); $request = $container->get('request'); if (ENABLE_SSL == 'true' && $request->isSecure()) { $url = str_replace('http://', 'https://', $url); } $response = new RedirectResponse($url, $responseCode); $httpKernel = $container->get('http_kernel'); $event = new FilterResponseEvent($httpKernel, $request, HttpKernelInterface::MASTER_REQUEST, $response); $dispatcher = $container->get('event_dispatcher'); $dispatcher->dispatch(KernelEvents::RESPONSE, $event); $response->send(); $httpKernel->terminate($request, $response); exit; }
public function submitForm(array &$form, FormStateInterface $form_state) { if (isset($form)) { if (isset($form['#token'])) { $collection_name = Html::escape($form['searchblox_collection']['#value']); $resp = searchblox_check_collection($collection_name); // check weather collection name is valid if ($resp !== true) { $form_state->setErrorByName($resp); } if ($resp) { \Drupal::state()->set('searchblox_collection', $collection_name); $response = new RedirectResponse(\Drupal::url('searchblox.step3')); $response->send(); return; } } } }
public function authorize() { $request = $this->getRequest(); $session = $request->getSession(); if (!$request->query->has('code')) { // If we don't have an authorization code then get one $authUrl = $this->provider->getAuthorizationUrl(); $session->set('oauth2state', $this->provider->state); $response = new RedirectResponse($authUrl); $response->send(); } elseif (empty($request->query->get('state')) || $request->query->get('state') !== $session->get('oauth2state')) { $session->remove('oauth2state'); throw new \InvalidArgumentException('Invalid State'); } else { // Try to get an access token (using the authorization code grant) $this->token = $this->provider->getAccessToken('authorization_code', ['code' => $this->request->query->get('code')]); } return $this->token->accessToken; }
public function onCoreInit(GenericEvent $event) { /** @var Request $request */ $request = $this->container->get('request'); // create several booleans to test condition of request regarding install/upgrade $installed = $this->container->getParameter('installed'); if ($installed) { VersionUtil::defineCurrentInstalledCoreVersion($this->container); } $requiresUpgrade = $installed && version_compare(ZIKULACORE_CURRENT_INSTALLED_VERSION, \Zikula_Core::VERSION_NUM, '<'); // can't use $request->get('_route') to get any of the following // all these routes are hard-coded in xml files $uriContainsInstall = strpos($request->getRequestUri(), '/install') !== false; $uriContainsUpgrade = strpos($request->getRequestUri(), '/upgrade') !== false; $uriContainsDoc = strpos($request->getRequestUri(), '/installdoc') !== false; $uriContainsWdt = strpos($request->getRequestUri(), '/_wdt') !== false; $uriContainsProfiler = strpos($request->getRequestUri(), '/_profiler') !== false; $uriContainsRouter = strpos($request->getRequestUri(), '/js/routing?callback=fos.Router.setData') !== false; $doNotRedirect = $uriContainsProfiler || $uriContainsWdt || $uriContainsRouter || $request->isXmlHttpRequest(); // check if Zikula Core is not installed if (!$installed && !$uriContainsDoc && !$uriContainsInstall && !$doNotRedirect) { $this->container->get('router')->getContext()->setBaseUrl($request->getBasePath()); // compensate for sub-directory installs $url = $this->container->get('router')->generate('install'); $response = new RedirectResponse($url); $response->send(); \System::shutDown(); } // check if Zikula Core requires upgrade if ($requiresUpgrade && !$uriContainsDoc && !$uriContainsUpgrade && !$doNotRedirect) { $this->container->get('router')->getContext()->setBaseUrl($request->getBasePath()); // compensate for sub-directory installs $url = $this->container->get('router')->generate('upgrade'); $response = new RedirectResponse($url); $response->send(); \System::shutDown(); } if (!$installed || $requiresUpgrade || $this->container->hasParameter('upgrading')) { \System::setInstalling(true); } }
public function exec() { $c = new ReflectionClass($this); if (!$c->hasMethod($this->actionName)) { throw new RuntimeException('"' . $this->actionName . '" action isn\'t defined for this module.'); } $method = $c->getMethod($this->actionName); $viewName = $method->invokeArgs($this, $this->app->getRoute()->getVars()); if ($viewName !== null) { if (str_starts_with($viewName, 'redirect:')) { $dest = substr($viewName, strlen('redirect:')); if ($dest[0] = '/') { $dest = WEB_ROOT . substr($dest, 1); } $response = new RedirectResponse($dest); $this->app['Symfony\\Response']->prepare($this->app['Symfony\\Request']); $response->send(); } else { $reflClass = new ReflectionClass($this); $this->view->setViewPath(dirname($reflClass->getFileName()) . '/view/' . $viewName); } } return $this->view; }
public function indexStep() { // Return If Settings not configured if (!\Drupal::state()->get('searchblox_apikey') || !\Drupal::state()->get('searchblox_location')) { $response = new RedirectResponse(\Drupal::url('searchblox.step1')); $response->send(); } elseif (!\Drupal::state()->get('searchblox_collection')) { $response = new RedirectResponse(\Drupal::url('searchblox.step2')); $response->send(); } if (isset($_POST['searchblox_re_configure'])) { $response = new RedirectResponse(\Drupal::url('searchblox.admin.config')); searchblox_clear_config(); $response->send(); } $searchblox_full_page = array('#theme' => 'searchblox_full_page'); // Attach PHP vars to js script $js_vars = searchblox_add_js_settings(); $searchblox_full_page['#attached']['drupalSettings']["searchblox"]["base_url"] = $js_vars["base_url"]; $searchblox_full_page['#attached']['drupalSettings']["searchblox"]["total_docs"] = $js_vars["total_docs"]; // Attach Library $searchblox_full_page['#attached']['library'][] = 'searchblox/searchblox-deps'; return $searchblox_full_page; }
/** * Decode the path string into a set of variable/value pairs. * * This API works in conjunction with the new short urls * system to extract a path based variable set into the Get, Post * and request superglobals. * A sample path is /modname/function/var1:value1. * * @return void */ public static function queryStringDecode() { if (self::isInstalling()) { return; } // get our base parameters to work out if we need to decode the url $module = FormUtil::getPassedValue('module', null, 'GETPOST', FILTER_SANITIZE_STRING); $func = FormUtil::getPassedValue('func', null, 'GETPOST', FILTER_SANITIZE_STRING); $type = FormUtil::getPassedValue('type', null, 'GETPOST', FILTER_SANITIZE_STRING); // check if we need to decode the url if (self::getVar('shorturls') && (empty($module) && empty($type) && empty($func))) { // user language is not set at this stage $lang = System::getVar('language_i18n', ''); $customentrypoint = self::getVar('entrypoint'); $expectEntrypoint = !self::getVar('shorturlsstripentrypoint'); $root = empty($customentrypoint) ? 'index.php' : $customentrypoint; // check if we hit baseurl, e.g. domain.com/ and if we require the language URL // then we should redirect to the language URL. if (ZLanguage::isRequiredLangParam() && self::getCurrentUrl() == self::getBaseUrl()) { $uri = $expectEntrypoint ? "{$root}/{$lang}" : "{$lang}"; self::redirect(self::getBaseUrl() . $uri); self::shutDown(); } // check if entry point is part of the URL expectation. If so throw error if it's not present // since this URL is technically invalid. if ($expectEntrypoint && strpos(self::getCurrentUrl(), self::getBaseUrl() . $root) !== 0) { $protocol = System::serverGetVar('SERVER_PROTOCOL'); header("{$protocol} 404 Not Found"); echo __('The requested URL cannot be found'); system::shutDown(); } if (!$expectEntrypoint && self::getCurrentUrl() == self::getBaseUrl() . $root) { self::redirect(self::getHomepageUrl()); self::shutDown(); } if (!$expectEntrypoint && strpos(self::getCurrentUrl(), self::getBaseUrl() . $root) === 0) { $protocol = System::serverGetVar('SERVER_PROTOCOL'); header("{$protocol} 404 Not Found"); echo __('The requested URL cannot be found'); system::shutDown(); } // get base path to work out our current url $parsedURL = parse_url(self::getCurrentUri()); // strip any unwanted content from the provided URL $tobestripped = array(self::getBaseUri(), "{$root}"); $path = str_replace($tobestripped, '', $parsedURL['path']); $path = trim($path, '/'); // split the path into a set of argument strings $args = explode('/', rtrim($path, '/')); // ensure that each argument is properly decoded foreach ($args as $k => $v) { $args[$k] = urldecode($v); } $modinfo = null; $frontController = $expectEntrypoint ? "{$root}/" : ''; // if no arguments present if (!$args[0] && !isset($_GET['lang']) && !isset($_GET['theme'])) { // we are in the homepage, checks if language code is forced if (ZLanguage::getLangUrlRule() && $lang) { // and redirect then $response = new RedirectResponse(self::getCurrentUrl() . "/{$lang}"); $respose->send(); System::shutDown(); } } else { // check the existing shortURL parameters // validation of the first parameter as language code if (ZLanguage::isLangParam($args[0]) && in_array($args[0], ZLanguage::getInstalledLanguages())) { // checks if the language is not enforced and this url is passing the default lang if (!ZLanguage::getLangUrlRule() && $lang == $args[0]) { // redirects the passed arguments without the default site language array_shift($args); foreach ($args as $k => $v) { $args[$k] = urlencode($v); } $response = new RedirectResponse(self::getBaseUrl() . $frontController . ($args ? implode('/', $args) : '')); $respose->send(); System::shutDown(); } self::queryStringSetVar('lang', $args[0]); array_shift($args); } elseif (ZLanguage::getLangUrlRule()) { // if the lang is forced, redirects the passed arguments plus the lang foreach ($args as $k => $v) { $args[$k] = urlencode($v); } $langTheme = isset($_GET['theme']) ? "{$lang}/{$_GET['theme']}" : $lang; $response = new RedirectResponse(self::getBaseUrl() . $frontController . $langTheme . '/' . implode('/', $args)); $response->send(); System::shutDown(); } // check if there are remaining arguments if ($args) { // try the first argument as a module $modinfo = ModUtil::getInfoFromName($args[0]); if ($modinfo) { array_shift($args); } } // if that fails maybe it's a theme if ($args && !$modinfo) { $themeinfo = ThemeUtil::getInfo(ThemeUtil::getIDFromName($args[0])); if ($themeinfo) { self::queryStringSetVar('theme', $themeinfo['name']); // now shift the vars and continue as before array_shift($args); if ($args) { $modinfo = ModUtil::getInfoFromName($args[0]); if ($modinfo) { array_shift($args); } } } } // if there are parameters (not homepage) // try to see if there's a default shortURLs module if ($args && !$modinfo) { // add the default module handler into the code $modinfo = ModUtil::getInfoFromName(self::getVar('shorturlsdefaultmodule')); } } // check if there is a module and a custom url handler for it // if not decode the url using the default handler if ($modinfo && $modinfo['type'] != 0) { // prepare the arguments to the module handler array_unshift($args, ''); // support for 1.2- empty parameter due the initial explode array_unshift($args, $modinfo['url']); // set the REQUEST parameters self::queryStringSetVar('module', $modinfo['name']); // the user.function name can be the second argument string, set a default // later the custom module handler (if exists) must setup a new one if needed self::queryStringSetVar('type', 'user'); if (isset($args[2])) { self::queryStringSetVar('func', $args[2]); } else { self::queryStringSetVar('func', 'index'); } if (!ModUtil::apiFunc($modinfo['name'], 'user', 'decodeurl', array('vars' => $args))) { // any remaining arguments are specific to the module $argscount = count($args); for ($i = 3; $i < $argscount; $i = $i + 2) { if (isset($args[$i]) && isset($args[$i + 1])) { self::queryStringSetVar($args[$i], urldecode($args[$i + 1])); } } } } } }
/** * @Route("/index_poll_check/{pollId}", name="index_poll_check") */ public function indexPollCheckAction(Request $request, $pollId) { $em = $this->getDoctrine()->getManager(); $poll = $em->getRepository('EvrikaMainBundle:Poll')->findOneById($pollId); $referer = $request->headers->get('referer'); $response = new RedirectResponse($referer); $cookies = $request->cookies; $session = $request->getSession(); $checkName = 'index_poll_voted_' . $poll->getId(); $alreadyVoted = $cookies->has($checkName) || $session->has($checkName); if (!$alreadyVoted && $request->isMethod('POST')) { $questions = $request->request->get('questions'); $questionsMultiple = $request->request->get('questions_multiple'); # добавляем голоса варианту и самому вопросу if (!empty($questions)) { foreach ($questions as $questionId => $choiceId) { $question = $em->getRepository('EvrikaMainBundle:PollQuestion')->findOneById($questionId); $choice = $em->getRepository('EvrikaMainBundle:PollChoice')->findOneById($choiceId); $question->addVote(); $choice->addVote(); } } # добавляем голоса множественным вариантам и самому вопросу if (!empty($questionsMultiple)) { foreach ($questionsMultiple as $questionId => $choices) { $question = $em->getRepository('EvrikaMainBundle:PollQuestion')->findOneById($questionId); $question->addVote(); foreach ($choices as $choiceId => $on) { $choice = $em->getRepository('EvrikaMainBundle:PollChoice')->findOneById($choiceId); $choice->addVote(); } } } $em->flush(); # сохраняем сессию, что голосовал\ $session->set($checkName, ''); # сохраняем печеньку, что голосовал $cookie = new Cookie($checkName, '', time() + 3600 * 24 * 90); $response->headers->setCookie($cookie); } $response->send(); }
public function redirectUser($variable_path = '') { $user = \Drupal::currentUser(); $config = \Drupal::config('hostedpage.settings'); //Advanced module LR Code Hook Start // Make sure at least one module implements our hook. if (count(\Drupal::moduleHandler()->getImplementations('before_user_redirect')) > 0) { // Call all modules that implement the hook, and let them make changes to $variables. $use_data = array('userprofile' => $userprofile, 'form' => $form, 'account' => $account); $data = \Drupal::moduleHandler()->invokeAll('before_user_redirect', $use_data); if (!empty($data) && $data != 'true') { return $data; } } //Advanced module LR Code Hook End $variable_path = !empty($variable_path) ? $variable_path : 'login_redirection'; $variable_custom_path = $variable_path == 'login_redirection' ? 'custom_login_url' : 'custom_register_url'; $request_uri = \Drupal::request()->getRequestUri(); if ($this->module_config->get($variable_path) == 1) { // Redirect to profile. $response = new RedirectResponse($user->id() . '/edit'); return $response->send(); } elseif ($this->module_config->get($variable_path) == 2) { // Redirect to custom page. $custom_url = $this->module_config->get($variable_custom_path); if (!empty($custom_url)) { $response = new RedirectResponse($custom_url); return $response->send(); } else { return new RedirectResponse(Url::fromRoute('<front>')->toString()); } } else { // Redirect to same page. $enablehosted = $config->get('lr_hosted_page_enable'); if (isset($enablehosted) && $enablehosted == '1') { return new RedirectResponse(Url::fromRoute('<front>')->toString()); } else { $destination = \Drupal::destination()->getAsArray(); $response = new RedirectResponse($destination['destination']); return $response->send(); } } }
public function lrClearLog() { db_delete('loginradius_log')->execute(); $response = new RedirectResponse('logs'); return $response->send(); }
/** * * This file is part of the phpBB Forum Software package. * * @copyright (c) phpBB Limited <https://www.phpbb.com> * @license GNU General Public License, version 2 (GPL-2.0) * * For full copyright and license information, please see * the docs/CREDITS.txt file. * */ use Symfony\Component\HttpFoundation\RedirectResponse; /** * @ignore */ define('IN_PHPBB', true); $phpbb_root_path = defined('PHPBB_ROOT_PATH') ? PHPBB_ROOT_PATH : './'; $phpEx = substr(strrchr(__FILE__, '.'), 1); include $phpbb_root_path . 'common.' . $phpEx; // Start session management $user->session_begin(); $auth->acl($user->data); $post_id = $request->variable('p', 0); $pm_id = $request->variable('pm', 0); $redirect_route_name = $pm_id === 0 ? 'phpbb_report_post_controller' : 'phpbb_report_pm_controller'; /** @var \phpbb\controller\helper $controller_helper */ $controller_helper = $phpbb_container->get('controller.helper'); $response = new RedirectResponse($controller_helper->route($redirect_route_name, array('id' => $pm_id === 0 ? $post_id : $pm_id)), 301); $response->send();
/** * Prepare static pathway aliasing for routing * @param array|null $map * @param string|null $pathway * @return string */ private function findStaticAliases(array $map = null, $pathway = null) { if ($map === null) { return $pathway; } // current pathway is found as "old path" (or alias target). Make redirect to new pathway. if (Arr::in($pathway, $map)) { // find "new path" as binding uri slug $binding = array_search($pathway, $map, true); // build url to redirection $url = $this->getSchemeAndHttpHost() . $this->getBasePath() . '/'; if (App::$Properties->get('multiLanguage')) { $url .= $this->language . '/'; } $url .= ltrim($binding, '/'); $redirect = new Redirect($url); $redirect->send(); exit; } // current pathway request is equal to path alias. Set alias to property. if (array_key_exists($pathway, $map)) { $pathway = $map[$pathway]; $this->aliasPathTarget = $pathway; } return $pathway; }
/** * Prepares the Response before it is sent to the client. * * This method tweaks the Response to ensure that it is * compliant with RFC 2616. Most of the changes are based on * the Request that is "associated" with this Response. * * @param object $request A Request instance * @return object The current response. */ public function send() { if ($this->request) { $url = $this->getContent(); // Check for relative internal links. if (preg_match('/^index2?\\.php/', $url)) { $url = $this->request->base() . $url; } // Strip out any line breaks. $url = preg_split("/[\r\n]/", $url); $url = $url[0]; // If we don't start with a http we need to fix this before we proceed. // We could validly start with something else (e.g. ftp), though this would // be unlikely and isn't supported by this API. if (!preg_match('/^http/i', $url)) { $prefix = $this->request->scheme() . $this->request->getUserInfo() . $this->request->host(); if ($url[0] == '/') { // We just need the prefix since we have a path relative to the root. $url = $prefix . $url; } else { // It's relative to where we are now, so lets add that. $parts = explode('/', $this->request->path()); array_pop($parts); $path = implode('/', $parts) . '/'; $url = $prefix . $path . $url; } } $this->setContent($url); } return parent::send(); //prepare($request); }
/** @Route("/vebinars-post/{vebId}", name="vebinars_post") */ public function vebinarsPostAction(Request $request, $vebId) { $referer = $request->headers->get('referer'); $response = new RedirectResponse($referer); $cookies = $request->cookies; $session = $request->getSession(); $checkName = 'veb_voted_' . $vebId; $alreadyVoted = $cookies->has($checkName) || $session->has($checkName); if (!$alreadyVoted && $request->isMethod('POST')) { $em = $this->getDoctrine()->getManager(); # сохраняем объект участия в вебинаре $vebinar = new Vebinar(); $firstName = $request->request->get('firstName', ''); $lastName = $request->request->get('lastName', ''); $surName = $request->request->get('surName', ''); $email = $request->request->get('email', ''); $company = $request->request->get('company', ''); $position = $request->request->get('position', ''); $comment = $request->request->get('comment', ''); $choice = $request->request->get('option', ''); $veb = $request->request->get('vebinar'); if (!empty($firstName)) { $vebinar->setFirstName($firstName); } if (!empty($lastName)) { $vebinar->setLastName($lastName); } if (!empty($surName)) { $vebinar->setSurName($surName); } if (!empty($email)) { $vebinar->setEmail($email); } if (!empty($company)) { $vebinar->setCompany($company); } if (!empty($position)) { $vebinar->setPosition($position); } if (!empty($comment)) { $vebinar->setComment($comment); } if (!empty($choice)) { $vebinar->setChoice($choice); } $vebinar->setVebinar($veb); $em->persist($vebinar); $em->flush(); # сохраняем сессию, что голосовал\ $session->set($checkName, ''); # сохраняем печеньку, что голосовал $cookie = new Cookie($checkName, '', time() + 3600 * 24 * 90); $response->headers->setCookie($cookie); } $response->send(); }
/** * Cause redirect by throwing exception which passes to front controller. * * @param string $url Url to redirect to. * @param integer $type Redirect code, 302 default. * * sends RedirectResponse Causing redirect. * @deprecated since 1.4.0 return a RedirectResponse instead! * * @return void */ protected function redirect($url, $type = 302) { $response = new RedirectResponse(System::normalizeUrl($url), $type); $response->send(); exit; }
/** * Redirect. * * @param Zikula\Core\ModUrl|string $url Url. * * @return boolean True if redirected successfully, otherwise false. */ public function redirect($url) { $this->redirected = true; if ($url instanceof Zikula\Core\ModUrl) { $this->redirectTarget = $url; // return and complete lifecycle events. redirect will complete in the `execute` method return true; } else { // for BC: if only url is provided, send redirect immediately, discarding all future lifecycle changes $response = new RedirectResponse(System::normalizeUrl($url)); $response->send(); exit; } }
/** * Perform the anonymous user redirection, if needed. * * This method is called whenever the KernelEvents::REQUEST event is * dispatched. * * @param GetResponseEvent $event */ public function redirect(GetResponseEvent $event) { // Skip if maintenance mode is enabled. if ($this->state->get('system.maintenance_mode')) { return; } // Skip if running from the command-line. if (PHP_SAPI === 'cli') { return; } // Skip if no paths are configured for redirecting. if (!($paths = $this->paths()) || empty($paths['include'])) { return; } // Skip if the user is not anonymous. if (!$this->current_user->isAnonymous()) { return; } // Determine the current path and alias. $current = [ 'path' => $this->path_current->getPath(), 'alias' => \Drupal::request()->getRequestUri(), ]; // Ignore PHP file requests. if (substr($current['path'], -4) == '.php') { return; } // Ignore the user login page. if ($current['path'] == '/user/login') { return; } // Convert the path to the front page token, if needed. $current['path'] = ($current['path'] != '/') ? $current['path'] : '<front>'; // Track if we should redirect. $redirect = FALSE; // Iterate the current path and alias. foreach ($current as &$check) { // Remove the leading slash. $check = substr($check, 1); // Check if there is a trailer slash. if (substr($check, -1) == '/') { // Remove it. $check = substr($check, 0, strlen($check) - 1); } // Redirect if the path is a match for included paths. if ($this->path_matcher->matchPath($check, implode("\n", $paths['include']))) { $redirect = TRUE; } // Do not redirect if the path is a match for excluded paths. if ($this->path_matcher->matchPath($check, implode("\n", $paths['exclude']))) { $redirect = FALSE; // Matching an excluded path is a hard-stop. break; } } // See if we're going to redirect. if ($redirect) { // See if we have a message to display. if ($message = $this->config_factory->get('anonymous_login.settings')->get('message')) { // @todo: translation? // @todo: This does not show after the redirect.. drupal_set_message($message); } // Redirect to the login, keeping the requested alias as the destination. $response = new RedirectResponse('/user/login?destination=' . $current['alias']); $response->send(); exit(); } }
public function documentation() { $response = new RedirectResponse("https://api.drupal.org/api/drupal/8"); $response->send(); return $response; }