Exemple #1
0
 /**
  * Sets the cache key on the alias manager cache decorator.
  *
  * KernelEvents::CONTROLLER is used in order to be executed after routing.
  *
  * @param \Symfony\Component\HttpKernel\Event\FilterControllerEvent $event
  *   The Event to process.
  */
 public function onKernelController(FilterControllerEvent $event)
 {
     // Set the cache key on the alias manager cache decorator.
     if ($event->getRequestType() == HttpKernelInterface::MASTER_REQUEST) {
         $this->aliasManager->setCacheKey(rtrim($this->currentPath->getPath($event->getRequest()), '/'));
     }
 }
Exemple #2
0
 /**
  * Test the getArgument() method.
  *
  * @see \Drupal\views\Plugin\views\argument_default\Raw::getArgument()
  */
 public function testGetArgument()
 {
     $view = $this->getMockBuilder('Drupal\\views\\ViewExecutable')->disableOriginalConstructor()->getMock();
     $display_plugin = $this->getMockBuilder('Drupal\\views\\Plugin\\views\\display\\DisplayPluginBase')->disableOriginalConstructor()->getMock();
     $current_path = new CurrentPathStack(new RequestStack());
     $request = new Request();
     $current_path->setPath('/test/example', $request);
     $view->expects($this->any())->method('getRequest')->will($this->returnValue($request));
     $alias_manager = $this->getMock('Drupal\\Core\\Path\\AliasManagerInterface');
     $alias_manager->expects($this->never())->method('getAliasByPath');
     // Don't use aliases.
     $raw = new Raw(array(), 'raw', array(), $alias_manager, $current_path);
     $options = array('use_alias' => FALSE, 'index' => 0);
     $raw->init($view, $display_plugin, $options);
     $this->assertEquals('test', $raw->getArgument());
     $raw = new Raw(array(), 'raw', array(), $alias_manager, $current_path);
     $options = array('use_alias' => FALSE, 'index' => 1);
     $raw->init($view, $display_plugin, $options);
     $this->assertEquals('example', $raw->getArgument());
     // Setup an alias manager with a path alias.
     $alias_manager = $this->getMock('Drupal\\Core\\Path\\AliasManagerInterface');
     $alias_manager->expects($this->any())->method('getAliasByPath')->with($this->equalTo('test/example'))->will($this->returnValue('other/example'));
     $raw = new Raw(array(), 'raw', array(), $alias_manager, $current_path);
     $options = array('use_alias' => TRUE, 'index' => 0);
     $raw->init($view, $display_plugin, $options);
     $this->assertEquals('other', $raw->getArgument());
     $raw = new Raw(array(), 'raw', array(), $alias_manager, $current_path);
     $options = array('use_alias' => TRUE, 'index' => 1);
     $raw->init($view, $display_plugin, $options);
     $this->assertEquals('example', $raw->getArgument());
 }
Exemple #3
0
 public function finalMatch(RouteCollection $collection, Request $request)
 {
     $this->routes = $collection;
     $context = new RequestContext();
     $context->fromRequest($request);
     $this->setContext($context);
     return $this->match($this->currentPath->getPath($request));
 }
Exemple #4
0
 public function getArgument()
 {
     $path = trim($this->currentPath->getPath($this->view->getRequest()), '/');
     if ($this->options['use_alias']) {
         $path = $this->aliasManager->getAliasByPath($path);
     }
     $args = explode('/', $path);
     if (isset($args[$this->options['index']])) {
         return $args[$this->options['index']];
     }
 }
Exemple #5
0
 /**
  * Converts the request path to a system path.
  *
  * @param Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  *   The Event to process.
  */
 public function onKernelRequestConvertPath(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $path = trim($request->getPathInfo(), '/');
     $path = $this->pathProcessor->processInbound($path, $request);
     $this->currentPath->setPath('/' . $path, $request);
     // Set the cache key on the alias manager cache decorator.
     if ($event->getRequestType() == HttpKernelInterface::MASTER_REQUEST) {
         $this->aliasManager->setCacheKey($path);
     }
 }
 /**
  * Sets the 'is-active' class on links.
  *
  * @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event
  *   The response event.
  */
 public function onResponse(FilterResponseEvent $event)
 {
     // Only care about HTML responses.
     if (stripos($event->getResponse()->headers->get('Content-Type'), 'text/html') === FALSE) {
         return;
     }
     // For authenticated users, the 'is-active' class is set in JavaScript.
     // @see system_page_attachments()
     if ($this->currentUser->isAuthenticated()) {
         return;
     }
     $response = $event->getResponse();
     $response->setContent(static::setLinkActiveClass($response->getContent(), ltrim($this->currentPath->getPath(), '/'), $this->pathMatcher->isFrontPage(), $this->languageManager->getCurrentLanguage(LanguageInterface::TYPE_URL)->getId(), $event->getRequest()->query->all()));
 }
 /**
  * Redirects login attempts on already-logged-in session to the destination.
  */
 public function onRespond(FilterResponseEvent $event)
 {
     // Return early in most cases.
     if ($event->getRequest()->getMethod() !== 'POST') {
         return;
     }
     if (!$this->currentUser->isAuthenticated()) {
         return;
     }
     if (!$event->isMasterRequest()) {
         return;
     }
     if (!$event->getRequest()->query->has('destination')) {
         return;
     }
     if ($event->getResponse() instanceof RedirectResponse) {
         return;
     }
     // There has to be a better way to figure out if we landed on the 403/404 page.
     $page_403 = $this->configFactory->get('system.site')->get('page.403');
     $page_404 = $this->configFactory->get('system.site')->get('page.404');
     $path = $this->currentPath->getPath();
     $route = $this->currentRouteMatch->getRouteName();
     if ($route == 'system.403' || $page_403 && $path == $page_403 || $route == 'system.404' || $page_404 && $path == $page_404) {
         // RedirectResponseSubscriber will convert to absolute URL for us.
         $event->setResponse(new RedirectResponse($this->redirectDestination->get(), RedirectResponse::HTTP_SEE_OTHER));
     }
 }
 /**
  * Tests unsuccessful redirection due to rules admin page location.
  *
  * @covers ::execute
  */
 public function testRedirectRulesAdminPage()
 {
     $this->currentPathStack->getPath()->willReturn('admin/config/workflow/rules');
     $this->action->setContextValue('url', '/test/url');
     $this->action->execute();
     $this->logger->warning('Skipped page redirect on a rules admin page.')->shouldHaveBeenCalled();
 }
 /**
  * Tests the request path condition.
  */
 public function testConditions()
 {
     // Get the request path condition and test and configure it to check against
     // different patterns and requests.
     $pages = "/my/pass/page\r\n/my/pass/page2\r\n/foo";
     $request = Request::create('/my/pass/page2');
     $this->requestStack->push($request);
     /* @var \Drupal\system\Plugin\Condition\RequestPath $condition */
     $condition = $this->pluginManager->createInstance('request_path');
     $condition->setConfig('pages', $pages);
     $this->aliasManager->addAlias('/my/pass/page2', '/my/pass/page2');
     $this->assertTrue($condition->execute(), 'The request path matches a standard path');
     $this->assertEqual($condition->summary(), 'Return true on the following pages: /my/pass/page, /my/pass/page2, /foo', 'The condition summary matches for a standard path');
     // Test an aliased path.
     $this->currentPath->setPath('/my/aliased/page', $request);
     $this->requestStack->pop();
     $this->requestStack->push($request);
     $this->aliasManager->addAlias('/my/aliased/page', '/my/pass/page');
     $this->assertTrue($condition->execute(), 'The request path matches an aliased path');
     $this->assertEqual($condition->summary(), 'Return true on the following pages: /my/pass/page, /my/pass/page2, /foo', 'The condition summary matches for an aliased path');
     // Test a wildcard path.
     $this->aliasManager->addAlias('/my/pass/page3', '/my/pass/page3');
     $this->currentPath->setPath('/my/pass/page3', $request);
     $this->requestStack->pop();
     $this->requestStack->push($request);
     $condition->setConfig('pages', '/my/pass/*');
     $this->assertTrue($condition->evaluate(), 'The system_path my/pass/page3 passes for wildcard paths.');
     $this->assertEqual($condition->summary(), 'Return true on the following pages: /my/pass/*', 'The condition summary matches for a wildcard path');
     // Test a missing path.
     $this->requestStack->pop();
     $this->requestStack->push($request);
     $this->currentPath->setPath('/my/fail/page4', $request);
     $condition->setConfig('pages', '/my/pass/*');
     $this->aliasManager->addAlias('/my/fail/page4', '/my/fail/page4');
     $this->assertFalse($condition->evaluate(), 'The system_path /my/pass/page4 fails for a missing path.');
     // Test a path of '/'.
     $this->aliasManager->addAlias('/', '/my/pass/page3');
     $this->currentPath->setPath('/', $request);
     $this->requestStack->pop();
     $this->requestStack->push($request);
     $this->assertTrue($condition->evaluate(), 'The system_path my/pass/page3 passes for wildcard paths.');
     $this->assertEqual($condition->summary(), 'Return true on the following pages: /my/pass/*', 'The condition summary matches for a wildcard path');
 }
Exemple #10
0
 /**
  * {@inheritdoc}
  */
 public function displayEntityBrowser()
 {
     $uuid = $this->getUuid();
     /** @var \Drupal\entity_browser\Events\RegisterJSCallbacks $event */
     // TODO - $uuid is unused in this event but we need to pass it as
     // constructor expects it. See https://www.drupal.org/node/2600706 for more
     // info.
     $event = $this->eventDispatcher->dispatch(Events::REGISTER_JS_CALLBACKS, new RegisterJSCallbacks($this->configuration['entity_browser_id'], $uuid));
     $original_path = $this->currentPath->getPath();
     return ['#theme_wrappers' => ['container'], 'path' => ['#type' => 'hidden', '#value' => Url::fromRoute('entity_browser.' . $this->configuration['entity_browser_id'], [], ['query' => ['uuid' => $uuid, 'original_path' => $original_path]])->toString()], 'open_modal' => ['#type' => 'submit', '#value' => $this->configuration['link_text'], '#limit_validation_errors' => [], '#submit' => [], '#name' => 'op_' . $this->configuration['entity_browser_id'], '#ajax' => ['callback' => [$this, 'openModal'], 'event' => 'click'], '#attributes' => ['data-uuid' => $uuid], '#attached' => ['library' => ['core/drupal.dialog.ajax', 'entity_browser/modal'], 'drupalSettings' => ['entity_browser' => ['modal' => [$uuid => ['uuid' => $uuid, 'js_callbacks' => $event->getCallbacks(), 'original_path' => $original_path]]]]]]];
 }
Exemple #11
0
 /**
  * {@inheritdoc}
  */
 public function displayEntityBrowser()
 {
     $uuid = $this->getUuid();
     /** @var \Drupal\entity_browser\Events\RegisterJSCallbacks $event */
     // TODO - $uuid is unused in this event but we need to pass it as
     // constructor expects it. See https://www.drupal.org/node/2600706 for more
     // info.
     $event = $this->eventDispatcher->dispatch(Events::REGISTER_JS_CALLBACKS, new RegisterJSCallbacks($this->configuration['entity_browser_id'], $uuid));
     $original_path = $this->currentPath->getPath();
     return ['#theme_wrappers' => ['container'], 'link' => ['#type' => 'html_tag', '#tag' => 'a', '#value' => $this->configuration['link_text'], '#attributes' => ['href' => '#browser', 'class' => ['entity-browser-handle', 'entity-browser-iframe'], 'data-uuid' => $uuid, 'data-original-path' => $original_path], '#attached' => ['library' => ['entity_browser/iframe'], 'drupalSettings' => ['entity_browser' => ['iframe' => [$uuid => ['src' => Url::fromRoute('entity_browser.' . $this->configuration['entity_browser_id'], [], ['query' => ['uuid' => $uuid, 'original_path' => $original_path]])->toString(), 'width' => $this->configuration['width'], 'height' => $this->configuration['height'], 'js_callbacks' => $event->getCallbacks(), 'entity_browser_id' => $this->configuration['entity_browser_id'], 'auto_open' => $this->configuration['auto_open']]]]]]]];
 }
Exemple #12
0
 /**
  * {@inheritdoc}
  */
 public function evaluate()
 {
     // Convert path to lowercase. This allows comparison of the same path
     // with different case. Ex: /Page, /page, /PAGE.
     $pages = Unicode::strtolower($this->configuration['pages']);
     if (!$pages) {
         return TRUE;
     }
     $request = $this->requestStack->getCurrentRequest();
     // Compare the lowercase path alias (if any) and internal path.
     $path = rtrim($this->currentPath->getPath($request), '/');
     $path_alias = Unicode::strtolower($this->aliasManager->getAliasByPath($path));
     return $this->pathMatcher->matchPath($path_alias, $pages) || $path != $path_alias && $this->pathMatcher->matchPath($path, $pages);
 }
 /**
  * Prepares the request attributes for use by the selection process.
  *
  * This is be done because route filters run before request attributes are
  * populated.
  *
  * @param \Symfony\Component\Routing\Route $route
  *   The route.
  * @param string $name
  *   The route name.
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The current request.
  *
  * @return array
  *   An array of request attributes.
  */
 protected function getRequestAttributes(Route $route, $name, Request $request)
 {
     // Extract the raw attributes from the current path. This performs the same
     // functionality as \Drupal\Core\Routing\UrlMatcher::finalMatch().
     $path = $this->currentPath->getPath($request);
     $raw_attributes = RouteAttributes::extractRawAttributes($route, $name, $path);
     $attributes = $request->attributes->all();
     $attributes = NestedArray::mergeDeep($attributes, $raw_attributes);
     // Run the route enhancers on the raw attributes. This performs the same
     // functionality as \Symfony\Cmf\Component\Routing\DynamicRouter::match().
     foreach ($this->getRouteEnhancers() as $enhancer) {
         $attributes = $enhancer->enhance($attributes, $request);
     }
     return $attributes;
 }
Exemple #14
0
 /**
  * {@inheritdoc}
  */
 public function getArgument()
 {
     // Don't trim the leading slash since getAliasByPath() requires it.
     $path = rtrim($this->currentPath->getPath($this->view->getRequest()), '/');
     if ($this->options['use_alias']) {
         $path = $this->aliasManager->getAliasByPath($path);
     }
     $args = explode('/', $path);
     // Drop the empty first element created by the leading slash since the path
     // component index doesn't take it into account.
     array_shift($args);
     if (isset($args[$this->options['index']])) {
         return $args[$this->options['index']];
     }
 }
 /**
  * @covers ::getRequestAttributes
  */
 public function testGetRequestAttributes()
 {
     $request = new Request();
     $route = new Route('/path/with/{slug}');
     $route_name = 'a_route';
     $this->currentPath->getPath($request)->willReturn('/path/with/1');
     $expected_attributes = ['slug' => 1, '_route_object' => $route, '_route' => $route_name];
     $route_enhancer = $this->prophesize(RouteEnhancerInterface::class);
     $route_enhancer->enhance($expected_attributes, $request)->willReturn(['slug' => 'slug 1']);
     $this->routeFilter->addRouteEnhancer($route_enhancer->reveal());
     $this->assertSame([], $request->attributes->all());
     $method = new \ReflectionMethod($this->routeFilter, 'getRequestAttributes');
     $method->setAccessible(TRUE);
     $attributes = $method->invoke($this->routeFilter, $route, $route_name, $request);
     $this->assertSame(['slug' => 'slug 1'], $attributes);
 }
 /**
  * Ensures a path set on the current path services overrides the request one.
  */
 function testCurrentPath()
 {
     $connection = Database::getConnection();
     $provider = new RouteProvider($connection, $this->state, $this->currentPath, 'test_routes');
     $this->fixtures->createTables($connection);
     $dumper = new MatcherDumper($connection, $this->state, 'test_routes');
     $dumper->addRoutes($this->fixtures->sampleRouteCollection());
     $dumper->dump();
     $request = Request::create('/path/one', 'GET');
     $this->currentPath->setPath('/path/two', $request);
     $routes_by_pattern = $provider->getRoutesByPattern('/path/two');
     $routes = $provider->getRouteCollectionForRequest($request);
     $this->assertEqual(array_keys($routes_by_pattern->all()), array_keys($routes->all()), 'Ensure the expected routes are found.');
     foreach ($routes as $route) {
         $this->assertEqual($route->getPath(), '/path/two', 'Found path has correct pattern');
     }
 }
 /**
  * Redirect to a provided url at the end of the request.
  *
  * @param string $url
  *   Redirect destination url.
  */
 protected function doExecute($url)
 {
     $current_path = $this->currentPathStack->getPath();
     $is_rules_admin_page = strpos($current_path, 'admin/config/workflow/rules') !== FALSE;
     // Make sure we do not redirect away from the rules admin pages.
     if ($is_rules_admin_page) {
         $this->logger->warning('Skipped page redirect on a rules admin page.');
         return;
     }
     // Make sure we do not redirect during batch processing.
     $batch = batch_get();
     if (isset($batch['current_set'])) {
         $this->logger->warning('Skipped page redirect during batch processing.');
         return;
     }
     $this->request->attributes->set('_rules_redirect_action_url', $url);
 }
Exemple #18
0
 /**
  * {@inheritdoc}
  */
 public function buildEmbed(JuiceboxGalleryInterface $gallery, $settings, $xml_route_info, $add_js = TRUE, $add_xml = FALSE, $contextual = array())
 {
     // Merge all settings.
     $settings = $settings + $this->getGlobalSettings();
     // Set some defaults for the route info.
     $xml_route_info += array('route_name' => '', 'route_parameters' => array(), 'options' => array());
     // Prep the ids that may be used.
     $embed_id = $gallery->getId();
     $embed_xml_id = 'xml--' . $embed_id;
     // Construct the base render array for the gallery.
     $output = array('#gallery' => $gallery, '#theme' => 'juicebox_embed_markup', '#settings' => $settings, '#attached' => array(), '#contextual_links' => $contextual + array('juicebox_conf_global' => array('route_parameters' => array())), '#cache' => array('tags' => array('juicebox_gallery')), '#suffix' => '');
     // Process JS additions.
     if ($add_js) {
         // If we are also embedding the XML we want to set some query string
         // values on the XML URL that will allow the XML build methods to fetch
         // it later.
         $embed_query_additions = array();
         if ($add_xml) {
             $embed_query_additions['xml-source-path'] = trim($this->current_path_stack->getPath(), '/');
             $embed_query_additions['xml-source-id'] = $embed_xml_id;
         }
         // Add some query params that apply to all types of Juicebox galleries and
         // generate the final XML URL.
         $xml_query_additions = array_merge(array('checksum' => $gallery->getChecksum()), $embed_query_additions);
         $xml_options = array_merge_recursive(array('query' => $xml_query_additions), $xml_route_info['options']);
         $xml_url = $this->urlGenerator->generateFromRoute($xml_route_info['route_name'], $xml_route_info['route_parameters'], $xml_options);
         // Add the main library.
         $output['#attached']['library'][] = 'juicebox/juicebox';
         // Add the JS gallery details as Drupal.settings.
         $output['#attached']['drupalSettings']['juicebox'] = array($embed_id => $gallery->getJavascriptVars($xml_url));
         // Add some local JS (implementing Drupal.behaviors) that will process
         // the Drupal.settings above into a new client-side juicebox object.
         $output['#attached']['library'][] = 'juicebox/juicebox.local';
     }
     if ($add_xml) {
         $output['#suffix'] .= $gallery->renderXml($embed_xml_id);
     }
     // Ensure that our suffix is not further sanitized.
     $output['#suffix'] = SafeMarkup::format($output['#suffix'], array());
     return $output;
 }
Exemple #19
0
 /**
  * Finds routes that may potentially match the request.
  *
  * This may return a mixed list of class instances, but all routes returned
  * must extend the core symfony route. The classes may also implement
  * RouteObjectInterface to link to a content document.
  *
  * This method may not throw an exception based on implementation specific
  * restrictions on the url. That case is considered a not found - returning
  * an empty array. Exceptions are only used to abort the whole request in
  * case something is seriously broken, like the storage backend being down.
  *
  * Note that implementations may not implement an optimal matching
  * algorithm, simply a reasonable first pass.  That allows for potentially
  * very large route sets to be filtered down to likely candidates, which
  * may then be filtered in memory more completely.
  *
  * @param Request $request A request against which to match.
  *
  * @return \Symfony\Component\Routing\RouteCollection with all urls that
  *      could potentially match $request. Empty collection if nothing can
  *      match.
  */
 public function getRouteCollectionForRequest(Request $request)
 {
     // Cache both the system path as well as route parameters and matching
     // routes.
     $cid = 'route:' . $request->getPathInfo() . ':' . $request->getQueryString();
     if ($cached = $this->cache->get($cid)) {
         $this->currentPath->setPath($cached->data['path'], $request);
         $request->query->replace($cached->data['query']);
         return $cached->data['routes'];
     } else {
         // Just trim on the right side.
         $path = $request->getPathInfo();
         $path = $path === '/' ? $path : rtrim($request->getPathInfo(), '/');
         $path = $this->pathProcessor->processInbound($path, $request);
         $this->currentPath->setPath($path, $request);
         // Incoming path processors may also set query parameters.
         $query_parameters = $request->query->all();
         $routes = $this->getRoutesByPath(rtrim($path, '/'));
         $cache_value = ['path' => $path, 'query' => $query_parameters, 'routes' => $routes];
         $this->cache->set($cid, $cache_value, CacheBackendInterface::CACHE_PERMANENT, ['route_match']);
         return $routes;
     }
 }
 /**
  * Loads and renders a view via AJAX.
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The current request object.
  *
  * @return \Drupal\views\Ajax\ViewAjaxResponse
  *   The view response as ajax response.
  *
  * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  *   Thrown when the view was not found.
  */
 public function ajaxView(Request $request)
 {
     $name = $request->request->get('view_name');
     $display_id = $request->request->get('view_display_id');
     if (isset($name) && isset($display_id)) {
         $args = $request->request->get('view_args');
         $args = isset($args) && $args !== '' ? explode('/', $args) : array();
         // Arguments can be empty, make sure they are passed on as NULL so that
         // argument validation is not triggered.
         $args = array_map(function ($arg) {
             return $arg == '' ? NULL : $arg;
         }, $args);
         $path = $request->request->get('view_path');
         $dom_id = $request->request->get('view_dom_id');
         $dom_id = isset($dom_id) ? preg_replace('/[^a-zA-Z0-9_-]+/', '-', $dom_id) : NULL;
         $pager_element = $request->request->get('pager_element');
         $pager_element = isset($pager_element) ? intval($pager_element) : NULL;
         $response = new ViewAjaxResponse();
         // Remove all of this stuff from the query of the request so it doesn't
         // end up in pagers and tablesort URLs.
         foreach (array('view_name', 'view_display_id', 'view_args', 'view_path', 'view_dom_id', 'pager_element', 'view_base_path', AjaxResponseSubscriber::AJAX_REQUEST_PARAMETER) as $key) {
             $request->query->remove($key);
             $request->request->remove($key);
         }
         // Load the view.
         if (!($entity = $this->storage->load($name))) {
             throw new NotFoundHttpException();
         }
         $view = $this->executableFactory->get($entity);
         if ($view && $view->access($display_id)) {
             $response->setView($view);
             // Fix the current path for paging.
             if (!empty($path)) {
                 $this->currentPath->setPath('/' . $path, $request);
             }
             // Add all POST data, because AJAX is always a post and many things,
             // such as tablesorts, exposed filters and paging assume GET.
             $request_all = $request->request->all();
             $query_all = $request->query->all();
             $request->query->replace($request_all + $query_all);
             // Overwrite the destination.
             // @see the redirect.destination service.
             $origin_destination = $path;
             // Remove some special parameters you never want to have part of the
             // destination query.
             $used_query_parameters = $request->query->all();
             // @todo Remove this parsing once these are removed from the request in
             //   https://www.drupal.org/node/2504709.
             unset($used_query_parameters[FormBuilderInterface::AJAX_FORM_REQUEST], $used_query_parameters[MainContentViewSubscriber::WRAPPER_FORMAT], $used_query_parameters['ajax_page_state']);
             $query = UrlHelper::buildQuery($used_query_parameters);
             if ($query != '') {
                 $origin_destination .= '?' . $query;
             }
             $this->redirectDestination->set($origin_destination);
             // Override the display's pager_element with the one actually used.
             if (isset($pager_element)) {
                 $response->addCommand(new ScrollTopCommand(".js-view-dom-id-{$dom_id}"));
                 $view->displayHandlers->get($display_id)->setOption('pager_element', $pager_element);
             }
             // Reuse the same DOM id so it matches that in drupalSettings.
             $view->dom_id = $dom_id;
             $context = new RenderContext();
             $preview = $this->renderer->executeInRenderContext($context, function () use($view, $display_id, $args) {
                 return $view->preview($display_id, $args);
             });
             if (!$context->isEmpty()) {
                 $bubbleable_metadata = $context->pop();
                 BubbleableMetadata::createFromRenderArray($preview)->merge($bubbleable_metadata)->applyTo($preview);
             }
             $response->addCommand(new ReplaceCommand(".js-view-dom-id-{$dom_id}", $preview));
             return $response;
         } else {
             throw new AccessDeniedHttpException();
         }
     } else {
         throw new NotFoundHttpException();
     }
 }
 /**
  * Finds routes that may potentially match the request.
  *
  * This may return a mixed list of class instances, but all routes returned
  * must extend the core symfony route. The classes may also implement
  * RouteObjectInterface to link to a content document.
  *
  * This method may not throw an exception based on implementation specific
  * restrictions on the url. That case is considered a not found - returning
  * an empty array. Exceptions are only used to abort the whole request in
  * case something is seriously broken, like the storage backend being down.
  *
  * Note that implementations may not implement an optimal matching
  * algorithm, simply a reasonable first pass.  That allows for potentially
  * very large route sets to be filtered down to likely candidates, which
  * may then be filtered in memory more completely.
  *
  * @param Request $request A request against which to match.
  *
  * @return \Symfony\Component\Routing\RouteCollection with all urls that
  *      could potentially match $request. Empty collection if nothing can
  *      match.
  *
  * @todo Should this method's found routes also be included in the cache?
  */
 public function getRouteCollectionForRequest(Request $request)
 {
     $path = $this->currentPath->getPath($request);
     return $this->getRoutesByPath(rtrim($path, '/'));
 }
  /**
   * 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();
    }
  }
Exemple #23
0
 /**
  * Loads and renders a view via AJAX.
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *  The current request object.
  *
  * @return \Drupal\views\Ajax\ViewAjaxResponse
  *  The view response as ajax response.
  *
  * @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
  *   Thrown when the view was not found.
  */
 public function ajaxView(Request $request)
 {
     $name = $request->request->get('view_name');
     $display_id = $request->request->get('view_display_id');
     if (isset($name) && isset($display_id)) {
         $args = $request->request->get('view_args');
         $args = isset($args) && $args !== '' ? explode('/', $args) : array();
         // Arguments can be empty, make sure they are passed on as NULL so that
         // argument validation is not triggered.
         $args = array_map(function ($arg) {
             return $arg == '' ? NULL : $arg;
         }, $args);
         $path = $request->request->get('view_path');
         $dom_id = $request->request->get('view_dom_id');
         $dom_id = isset($dom_id) ? preg_replace('/[^a-zA-Z0-9_-]+/', '-', $dom_id) : NULL;
         $pager_element = $request->request->get('pager_element');
         $pager_element = isset($pager_element) ? intval($pager_element) : NULL;
         $response = new ViewAjaxResponse();
         // Remove all of this stuff from the query of the request so it doesn't
         // end up in pagers and tablesort URLs.
         foreach (array('view_name', 'view_display_id', 'view_args', 'view_path', 'view_dom_id', 'pager_element', 'view_base_path', 'ajax_html_ids') as $key) {
             $request->query->remove($key);
             $request->request->remove($key);
         }
         // Load the view.
         if (!($entity = $this->storage->load($name))) {
             throw new NotFoundHttpException();
         }
         $view = $this->executableFactory->get($entity);
         if ($view && $view->access($display_id)) {
             $response->setView($view);
             // Fix the current path for paging.
             if (!empty($path)) {
                 $this->currentPath->setPath('/' . $path, $request);
             }
             // Add all POST data, because AJAX is always a post and many things,
             // such as tablesorts, exposed filters and paging assume GET.
             $request_all = $request->request->all();
             $query_all = $request->query->all();
             $request->query->replace($request_all + $query_all);
             // Overwrite the destination.
             // @see the redirect.destination service.
             $origin_destination = $path;
             $query = UrlHelper::buildQuery($request->query->all());
             if ($query != '') {
                 $origin_destination .= '?' . $query;
             }
             $this->redirectDestination->set($origin_destination);
             // Override the display's pager_element with the one actually used.
             if (isset($pager_element)) {
                 $response->addCommand(new ScrollTopCommand(".view-dom-id-{$dom_id}"));
                 $view->displayHandlers->get($display_id)->setOption('pager_element', $pager_element);
             }
             // Reuse the same DOM id so it matches that in drupalSettings.
             $view->dom_id = $dom_id;
             if ($preview = $view->preview($display_id, $args)) {
                 $response->addCommand(new ReplaceCommand(".view-dom-id-{$dom_id}", $this->renderer->render($preview)));
                 $response->setAttachments($preview['#attached']);
             }
             return $response;
         } else {
             throw new AccessDeniedHttpException();
         }
     } else {
         throw new NotFoundHttpException();
     }
 }