/**
  * Converts a render array into an HtmlFragment object.
  *
  * @param array|string $page_content
  *   The page content area to display.
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The request object.
  *
  * @return \Drupal\Core\Page\HtmlPage
  *   A page object.
  */
 protected function createHtmlFragment($page_content, Request $request)
 {
     // Allow controllers to return a HtmlFragment or a Response object directly.
     if ($page_content instanceof HtmlFragment || $page_content instanceof Response) {
         return $page_content;
     }
     if (!is_array($page_content)) {
         $page_content = array('main' => array('#markup' => $page_content));
     }
     $content = $this->drupalRender($page_content);
     $cache = !empty($page_content['#cache']['tags']) ? array('tags' => $page_content['#cache']['tags']) : array();
     $fragment = new HtmlFragment($content, $cache);
     // A title defined in the return always wins.
     if (isset($page_content['#title'])) {
         $fragment->setTitle($page_content['#title'], Title::FILTER_XSS_ADMIN);
     } else {
         if ($route = $request->attributes->get(RouteObjectInterface::ROUTE_OBJECT)) {
             $fragment->setTitle($this->titleResolver->getTitle($request, $route), Title::PASS_THROUGH);
         }
     }
     // Add feed links from the page content.
     $attached = drupal_render_collect_attached($page_content, TRUE);
     if (!empty($attached['drupal_add_feed'])) {
         foreach ($attached['drupal_add_feed'] as $feed) {
             $feed_link = new FeedLinkElement($feed[1], $this->urlGenerator->generateFromPath($feed[0]));
             $fragment->addLinkElement($feed_link);
         }
     }
     return $fragment;
 }
示例#2
0
 /**
  * {@inheritdoc}
  */
 public function render(array $render_array)
 {
     $content = $this->drupalRenderRoot($render_array);
     if (!empty($render_array)) {
         drupal_process_attached($render_array);
     }
     $cache = !empty($render_array['#cache']['tags']) ? ['tags' => $render_array['#cache']['tags']] : [];
     $fragment = new HtmlFragment($content, $cache);
     if (isset($render_array['#title'])) {
         $fragment->setTitle($render_array['#title'], Title::FILTER_XSS_ADMIN);
     }
     $attached = isset($render_array['#attached']) ? $render_array['#attached'] : [];
     $attached += ['feed' => [], 'html_head' => [], 'html_head_link' => []];
     // Add feed links from the page content.
     foreach ($attached['feed'] as $feed) {
         $fragment->addLinkElement(new FeedLinkElement($feed[1], $this->urlGenerator->generateFromPath($feed[0])));
     }
     // Add generic links from the page content.
     foreach ($attached['html_head_link'] as $link) {
         $fragment->addLinkElement(new LinkElement($this->urlGenerator->generateFromPath($link[0]['href']), $link[0]['rel']));
     }
     // @todo Also transfer the contents of "_drupal_add_html_head" once
     // https://www.drupal.org/node/2296951 lands.
     // @todo Transfer CSS and JS over to the fragment once those are supported
     // on the fragment object.
     return $fragment;
 }
 /**
  * {@inheritdoc}
  */
 public function collect(Request $request, Response $response, \Exception $exception = NULL)
 {
     if ($this->translation instanceof TranslationManagerWrapper) {
         /** \Drupal\webprofiler\StringTranslation\TranslationManagerWrapper $this->translation */
         $this->data['translations']['translated'] = $this->translation->getTranslated();
         $this->data['translations']['untranslated'] = $this->translation->getUntranslated();
     }
     $data['user_interface_translations_path'] = $this->urlGenerator->generateFromRoute('locale.translate_page');
 }
 /**
  * {@inheritdoc}
  */
 public function execute($object = NULL)
 {
     $url = $this->urlGenerator->generateFromPath($this->configuration['url'], array('absolute' => TRUE));
     $response = new RedirectResponse($url);
     $listener = function ($event) use($response) {
         $event->setResponse($response);
     };
     // Add the listener to the event dispatcher.
     $this->dispatcher->addListener(KernelEvents::RESPONSE, $listener);
 }
 protected function setupUrlGenerator()
 {
     $this->urlGenerator->expects($this->any())->method('generateFromRoute')->willReturnCallback(function ($route, $parameters, $options) {
         $query_string = '';
         if (!empty($options['query'])) {
             $query_string = '?' . $options['query'];
         }
         return '/current-path' . $query_string;
     });
 }
 /**
  * Tests the output process.
  */
 public function testProcessOutbound()
 {
     $expected_cacheability = (new BubbleableMetadata())->addCacheContexts(['route'])->setCacheMaxAge(Cache::PERMANENT);
     $request_stack = \Drupal::requestStack();
     /** @var \Symfony\Component\Routing\RequestContext $request_context */
     $request_context = \Drupal::service('router.request_context');
     // Test request with subdir on homepage.
     $server = ['SCRIPT_NAME' => '/subdir/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/subdir/', 'GET', [], [], [], $server);
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<front>');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/'));
     $request_stack->push($request);
     $request_context->fromRequest($request);
     $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('/subdir/');
     $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<current>', [], [], TRUE));
     // Test request with subdir on other page.
     $server = ['SCRIPT_NAME' => '/subdir/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/subdir/node/add', 'GET', [], [], [], $server);
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'node.add');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/node/add'));
     $request_stack->push($request);
     $request_context->fromRequest($request);
     $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('/subdir/node/add');
     $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<current>', [], [], TRUE));
     // Test request without subdir on the homepage.
     $server = ['SCRIPT_NAME' => '/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/', 'GET', [], [], [], $server);
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, '<front>');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/'));
     $request_stack->push($request);
     $request_context->fromRequest($request);
     $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('/');
     $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<current>', [], [], TRUE));
     // Test request without subdir on other page.
     $server = ['SCRIPT_NAME' => '/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/node/add', 'GET', [], [], [], $server);
     $request->attributes->set(RouteObjectInterface::ROUTE_NAME, 'node.add');
     $request->attributes->set(RouteObjectInterface::ROUTE_OBJECT, new Route('/node/add'));
     $request_stack->push($request);
     $request_context->fromRequest($request);
     $url = GeneratedUrl::createFromObject($expected_cacheability)->setGeneratedUrl('/node/add');
     $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<current>', [], [], TRUE));
     // Test request without a found route. This happens for example on an
     // not found exception page.
     $server = ['SCRIPT_NAME' => '/index.php', 'SCRIPT_FILENAME' => \Drupal::root() . '/index.php', 'SERVER_NAME' => 'http://www.example.com'];
     $request = Request::create('/invalid-path', 'GET', [], [], [], $server);
     $request_stack->push($request);
     $request_context->fromRequest($request);
     // In case we have no routing, the current route should point to the front,
     // and the cacheability does not depend on the 'route' cache context, since
     // no route was involved at all: this is fallback behavior.
     $url = GeneratedUrl::createFromObject((new BubbleableMetadata())->setCacheMaxAge(Cache::PERMANENT))->setGeneratedUrl('/');
     $this->assertEqual($url, $this->urlGenerator->generateFromRoute('<current>', [], [], TRUE));
 }
 /**
  * @covers ::execute
  */
 public function testExecute()
 {
     $url = $this->randomMachineName();
     $currency = $this->getMock(CurrencyInterface::class);
     $currency->expects($this->once())->method('enable');
     $currency->expects($this->once())->method('save');
     $this->urlGenerator->expects($this->once())->method('generateFromRoute')->with('entity.currency.collection')->willReturn($url);
     $response = $this->sut->execute($currency);
     $this->assertInstanceOf(RedirectResponse::class, $response);
     $this->assertSame($url, $response->getTargetUrl());
 }
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     $this->eventDispatcher = $this->getMock(EventDispatcherInterface::class);
     $this->entityManager = $this->getMock(EntityManagerInterface::class);
     $this->urlGenerator = $this->getMock(UrlGeneratorInterface::class);
     $this->urlGenerator->expects($this->any())->method('generateFromRoute')->willReturn('http://example.com');
     $this->stringTranslation = $this->getStringTranslationStub();
     $this->payment = $this->getMock(PaymentInterface::class);
     $this->sut = new PaymentReference([], 'payment_reference', [], $this->eventDispatcher, $this->urlGenerator, $this->entityManager, $this->stringTranslation);
     $this->sut->setPayment($this->payment);
 }
示例#9
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $this->urlGenerator = $this->getMock('Drupal\\Core\\Routing\\UrlGeneratorInterface');
     $this->urlGenerator->expects($this->any())->method('generateFromPath')->will($this->returnArgument(0));
     $this->router = $this->getMock('Drupal\\Tests\\Core\\Routing\\TestRouterInterface');
     $container = new ContainerBuilder();
     $container->set('router', $this->router);
     $container->set('url_generator', $this->urlGenerator);
     \Drupal::setContainer($container);
 }
 /**
  * @param \Symfony\Component\HttpFoundation\Response $response
  */
 protected function injectToolbar(Response $response)
 {
     $content = $response->getContent();
     $pos = mb_strripos($content, '</body>');
     if (FALSE !== $pos) {
         if ($token = $response->headers->get('X-Debug-Token')) {
             $loader = ['#theme' => 'webprofiler_loader', '#token' => $token, '#profiler_url' => $this->urlGenerator->generate('webprofiler.toolbar', ['profile' => $token])];
             $content = mb_substr($content, 0, $pos) . $this->renderer->renderRoot($loader) . mb_substr($content, $pos);
             $response->setContent($content);
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function listAttribute($content)
 {
     $this->crawler->addContent($content);
     $this->links = array();
     $this->crawler->filter('a')->each(function (HtmlPageCrawler $anchor, $uri) {
         $href = $anchor->attr('href');
         // @todo deprecated method.
         $this->links[] = $this->urlGenerator->generateFromPath($href, array('absolute' => TRUE));
     });
     $this->crawler->remove();
     return implode(',', $this->links);
 }
 /**
  * {@inheritdoc}
  */
 public function buildForm(array $form, FormStateInterface $form_state)
 {
     $config = $this->config('ckeditor_media_embed.settings');
     $form['embed_provider'] = array('#type' => 'textfield', '#title' => $this->t('Provider URL'), '#default_value' => $config->get('embed_provider'), '#description' => $this->t('A template for the URL of the provider endpoint.
     This URL will be queried for each resource to be embedded. By default CKEditor uses the Iframely service.<br />
     <strong>Example</strong> <code>//example.com/api/oembed-proxy?resource-url={url}&callback={callback}</code><br />
     <strong>Default</strong> <code>//ckeditor.iframe.ly/api/oembed?url={url}&callback={callback}</code><br />
   '));
     if ($this->moduleHandler->moduleExists('help')) {
         $form['embed_provider']['#description'] .= $this->t('Check out the <a href=":help">help</a> page for more information.<br />', array(':help' => $this->urlGenerator->generateFromRoute('help.page', array('name' => 'ckeditor_media_embed'))));
     }
     return parent::buildForm($form, $form_state);
 }
示例#13
0
 /**
  * {@inheritdoc}
  */
 public function get()
 {
     if (!isset($this->destination)) {
         $query = $this->requestStack->getCurrentRequest()->query;
         if (UrlHelper::isExternal($query->get('destination'))) {
             $this->destination = '/';
         } elseif ($query->has('destination')) {
             $this->destination = $query->get('destination');
         } else {
             $this->destination = $this->urlGenerator->generateFromRoute('<current>', [], ['query' => UrlHelper::buildQuery(UrlHelper::filterQueryParameters($query->all()))]);
         }
     }
     return $this->destination;
 }
 /**
  * {@inheritdoc}
  */
 public function render() {
   $build = parent::render();
   $build['#empty'] = t('No eform types available. <a href="@link">Add EForm type</a>.', array(
     '@link' => $this->urlGenerator->generateFromRoute('eform.type_add'),
   ));
   return $build;
 }
 /**
  * {@inheritdoc}
  */
 public function render() {
   $build = parent::render();
   $build['#empty'] = $this->t('There are currently no blocktabs. <a href=":url">Add a new one</a>.', array(
     ':url' => $this->urlGenerator->generateFromRoute('blocktabs.add'),
   ));
   return $build;
 }
 /**
  * Returns the site maintenance page if the site is offline.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  *   The event to process.
  */
 public function onKernelRequestMaintenance(GetResponseEvent $event)
 {
     $route_match = RouteMatch::createFromRequest($event->getRequest());
     if ($this->maintenanceMode->applies($route_match)) {
         if (!$this->maintenanceMode->exempt($this->account)) {
             // Deliver the 503 page if the site is in maintenance mode and the
             // logged in user is not allowed to bypass it.
             drupal_maintenance_theme();
             $content = Xss::filterAdmin(String::format($this->config->get('system.maintenance')->get('message'), array('@site' => $this->config->get('system.site')->get('name'))));
             // @todo Break the dependency on DefaultHtmlPageRenderer, see:
             //   https://www.drupal.org/node/2295609
             $content = DefaultHtmlPageRenderer::renderPage($content, $this->t('Site under maintenance'));
             $response = new Response('Service unavailable', 503);
             $response->setContent($content);
             $event->setResponse($response);
         } else {
             // Display a message if the logged in user has access to the site in
             // maintenance mode. However, suppress it on the maintenance mode
             // settings page.
             if ($route_match->getRouteName() != 'system.site_maintenance_mode') {
                 if ($this->account->hasPermission('administer site configuration')) {
                     $this->drupalSetMessage($this->t('Operating in maintenance mode. <a href="@url">Go online.</a>', array('@url' => $this->urlGenerator->generate('system.site_maintenance_mode'))), 'status', FALSE);
                 } else {
                     $this->drupalSetMessage($this->t('Operating in maintenance mode.'), 'status', FALSE);
                 }
             }
         }
     }
 }
示例#17
0
 /**
  * Assert user redirected to homepage when controller invoked.
  */
 private function assertRedirectedToFrontPageOnHandle()
 {
     // URL Generator will generate a path to the homepage.
     $this->urlGenerator->expects($this->once())->method('generate')->with('<front>')->will($this->returnValue('http://example.com/front'));
     $response = $this->serviceController->handle();
     $this->assertTrue($response->isRedirect('http://example.com/front'));
 }
示例#18
0
 /**
  * {@inheritdoc}
  */
 public function render() {
   $build = parent::render();
   $build['table']['#empty'] = t('No crop types available. <a href="@link">Add crop type</a>.', [
     '@link' => $this->urlGenerator->generateFromRoute('crop.type_add'),
   ]);
   return $build;
 }
 /**
  * Returns the site maintenance page if the site is offline.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  *   The event to process.
  */
 public function onKernelRequestMaintenance(GetResponseEvent $event)
 {
     $request = $event->getRequest();
     $route_match = RouteMatch::createFromRequest($request);
     if ($this->maintenanceMode->applies($route_match)) {
         // Don't cache maintenance mode pages.
         \Drupal::service('page_cache_kill_switch')->trigger();
         if (!$this->maintenanceMode->exempt($this->account)) {
             // Deliver the 503 page if the site is in maintenance mode and the
             // logged in user is not allowed to bypass it.
             // If the request format is not 'html' then show default maintenance
             // mode page else show a text/plain page with maintenance message.
             if ($request->getRequestFormat() !== 'html') {
                 $response = new Response($this->getSiteMaintenanceMessage(), 503, array('Content-Type' => 'text/plain'));
                 $event->setResponse($response);
                 return;
             }
             drupal_maintenance_theme();
             $response = $this->bareHtmlPageRenderer->renderBarePage(['#markup' => $this->getSiteMaintenanceMessage()], $this->t('Site under maintenance'), 'maintenance_page');
             $response->setStatusCode(503);
             $event->setResponse($response);
         } else {
             // Display a message if the logged in user has access to the site in
             // maintenance mode. However, suppress it on the maintenance mode
             // settings page.
             if ($route_match->getRouteName() != 'system.site_maintenance_mode') {
                 if ($this->account->hasPermission('administer site configuration')) {
                     $this->drupalSetMessage($this->t('Operating in maintenance mode. <a href=":url">Go online.</a>', array(':url' => $this->urlGenerator->generate('system.site_maintenance_mode'))), 'status', FALSE);
                 } else {
                     $this->drupalSetMessage($this->t('Operating in maintenance mode.'), 'status', FALSE);
                 }
             }
         }
     }
 }
 /**
  * {@inheritdoc}
  */
 public function forbiddenMessage(EntityInterface $entity, $field_name)
 {
     if (!isset($this->authenticatedCanPostComments)) {
         // We only output a link if we are certain that users will get the
         // permission to post comments by logging in.
         $this->authenticatedCanPostComments = $this->entityManager->getStorage('user_role')->load(DRUPAL_AUTHENTICATED_RID)->hasPermission('post comments');
     }
     if ($this->authenticatedCanPostComments) {
         // We cannot use drupal_get_destination() because these links
         // sometimes appear on /node and taxonomy listing pages.
         if ($entity->get($field_name)->getFieldDefinition()->getSetting('form_location') == CommentItemInterface::FORM_SEPARATE_PAGE) {
             $destination = array('destination' => 'comment/reply/' . $entity->getEntityTypeId() . '/' . $entity->id() . '/' . $field_name . '#comment-form');
         } else {
             $destination = array('destination' => $entity->getSystemPath() . '#comment-form');
         }
         if ($this->userConfig->get('register') != USER_REGISTER_ADMINISTRATORS_ONLY) {
             // Users can register themselves.
             return $this->t('<a href="@login">Log in</a> or <a href="@register">register</a> to post comments', array('@login' => $this->urlGenerator->generateFromRoute('user.login', array(), array('query' => $destination)), '@register' => $this->urlGenerator->generateFromRoute('user.register', array(), array('query' => $destination))));
         } else {
             // Only admins can add new users, no public registration.
             return $this->t('<a href="@login">Log in</a> to post comments', array('@login' => $this->urlGenerator->generateFromRoute('user.login', array(), array('query' => $destination))));
         }
     }
     return '';
 }
 /**
  * Returns the site maintenance page if the site is offline.
  *
  * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
  *   The event to process.
  */
 public function onKernelRequestMaintenance(GetResponseEvent $event)
 {
     $route_match = RouteMatch::createFromRequest($event->getRequest());
     if ($this->maintenanceMode->applies($route_match)) {
         // Don't cache maintenance mode pages.
         \Drupal::service('page_cache_kill_switch')->trigger();
         if (!$this->maintenanceMode->exempt($this->account)) {
             // Deliver the 503 page if the site is in maintenance mode and the
             // logged in user is not allowed to bypass it.
             drupal_maintenance_theme();
             $content = Xss::filterAdmin(SafeMarkup::format($this->config->get('system.maintenance')->get('message'), array('@site' => $this->config->get('system.site')->get('name'))));
             $output = $this->bareHtmlPageRenderer->renderBarePage(['#markup' => $content], $this->t('Site under maintenance'), 'maintenance_page');
             $response = new Response($output, 503);
             $event->setResponse($response);
         } else {
             // Display a message if the logged in user has access to the site in
             // maintenance mode. However, suppress it on the maintenance mode
             // settings page.
             if ($route_match->getRouteName() != 'system.site_maintenance_mode') {
                 if ($this->account->hasPermission('administer site configuration')) {
                     $this->drupalSetMessage($this->t('Operating in maintenance mode. <a href="@url">Go online.</a>', array('@url' => $this->urlGenerator->generate('system.site_maintenance_mode'))), 'status', FALSE);
                 } else {
                     $this->drupalSetMessage($this->t('Operating in maintenance mode.'), 'status', FALSE);
                 }
             }
         }
     }
 }
示例#22
0
 /**
  * {@inheritdoc}
  */
 protected function setUp()
 {
     parent::setUp();
     $map = array();
     $map[] = array('view.frontpage.page_1', array(), array(), '/node');
     $map[] = array('node_view', array('node' => '1'), array(), '/node/1');
     $map[] = array('node_edit', array('node' => '2'), array(), '/node/2/edit');
     $this->map = $map;
     $this->urlGenerator = $this->getMock('Drupal\\Core\\Routing\\UrlGeneratorInterface');
     $this->urlGenerator->expects($this->any())->method('generateFromRoute')->will($this->returnValueMap($this->map));
     $this->router = $this->getMock('Drupal\\Tests\\Core\\Routing\\TestRouterInterface');
     $container = new ContainerBuilder();
     $container->set('router', $this->router);
     $container->set('url_generator', $this->urlGenerator);
     \Drupal::setContainer($container);
 }
示例#23
0
 /**
  * {@inheritdoc}
  */
 public function settingsForm(array $form, FormStateInterface $form_state)
 {
     $bundles = $this->mediaBundleStorage->loadMultiple();
     if (empty($bundles)) {
         $create_url = $this->urlGenerator->generateFromRoute('media.bundle_add');
         $this->setMessage($this->t('You do not have any media bundles that can be generated. <a href="@create-bundle">Go create a new media bundle</a>', ['@create-bundle' => $create_url]), 'error', FALSE);
         return [];
     }
     $options = [];
     foreach ($bundles as $bundle) {
         $options[$bundle->id()] = ['bundle' => ['#markup' => $bundle->label()]];
     }
     $form['media_bundles'] = ['#type' => 'tableselect', '#header' => ['bundle' => $this->t('Media bundle')], '#options' => $options];
     $form['kill'] = ['#type' => 'checkbox', '#title' => $this->t('<strong>Delete all media</strong> in these bundles before generating new media.'), '#default_value' => $this->getSetting('kill')];
     $form['num'] = ['#type' => 'number', '#title' => $this->t('How many media items would you like to generate?'), '#default_value' => $this->getSetting('num'), '#required' => TRUE, '#min' => 0];
     $options = [1 => $this->t('Now')];
     foreach ([3600, 86400, 604800, 2592000, 31536000] as $interval) {
         $options[$interval] = $this->dateFormatter->formatInterval($interval, 1) . ' ' . $this->t('ago');
     }
     $form['time_range'] = ['#type' => 'select', '#title' => $this->t('How far back in time should the media be dated?'), '#description' => $this->t('Media creation dates will be distributed randomly from the current time, back to the selected time.'), '#options' => $options, '#default_value' => 604800];
     $form['name_length'] = ['#type' => 'number', '#title' => $this->t('Maximum number of words in names'), '#default_value' => $this->getSetting('name_length'), '#required' => TRUE, '#min' => 1, '#max' => 255];
     $options = [];
     // We always need a language.
     $languages = $this->languageManager->getLanguages(LanguageInterface::STATE_ALL);
     foreach ($languages as $langcode => $language) {
         $options[$langcode] = $language->getName();
     }
     $form['add_language'] = ['#type' => 'select', '#title' => $this->t('Set language on media'), '#multiple' => TRUE, '#description' => $this->t('Requires locale.module'), '#options' => $options, '#default_value' => [$this->languageManager->getDefaultLanguage()->getId()]];
     $form['#redirect'] = FALSE;
     return $form;
 }
示例#24
0
 /**
  * {@inheritdoc}
  */
 public function build()
 {
     if ($block = $this->getEntity()) {
         return $this->entityManager->getViewBuilder($block->getEntityTypeId())->view($block, $this->configuration['view_mode']);
     } else {
         return array('#markup' => $this->t('Block with uuid %uuid does not exist. <a href=":url">Add custom block</a>.', array('%uuid' => $this->getDerivativeId(), ':url' => $this->urlGenerator->generate('block_content.add_page'))), '#access' => $this->account->hasPermission('administer blocks'));
     }
 }
示例#25
0
 /**
  * {@inheritdoc}
  */
 public function settingsForm(array $form, FormStateInterface $form_state)
 {
     $types = $this->nodeTypeStorage->loadMultiple();
     if (empty($types)) {
         $create_url = $this->urlGenerator->generateFromRoute('node.type_add');
         $this->setMessage($this->t('You do not have any content types that can be generated. <a href=":create-type">Go create a new content type</a>', array(':create-type' => $create_url)), 'error', FALSE);
         return;
     }
     $options = array();
     foreach ($types as $type) {
         $options[$type->id()] = array('type' => array('#markup' => $type->label()));
         if ($this->commentManager) {
             $comment_fields = $this->commentManager->getFields('node');
             $map = array($this->t('Hidden'), $this->t('Closed'), $this->t('Open'));
             $fields = array();
             foreach ($comment_fields as $field_name => $info) {
                 // Find all comment fields for the bundle.
                 if (in_array($type->id(), $info['bundles'])) {
                     $instance = FieldConfig::loadByName('node', $type->id(), $field_name);
                     $default_value = $instance->getDefaultValueLiteral();
                     $default_mode = reset($default_value);
                     $fields[] = new FormattableMarkup('@field: @state', array('@field' => $instance->label(), '@state' => $map[$default_mode['status']]));
                 }
             }
             // @todo Refactor display of comment fields.
             if (!empty($fields)) {
                 $options[$type->id()]['comments'] = array('data' => array('#theme' => 'item_list', '#items' => $fields));
             } else {
                 $options[$type->id()]['comments'] = $this->t('No comment fields');
             }
         }
     }
     $header = array('type' => $this->t('Content type'));
     if ($this->commentManager) {
         $header['comments'] = array('data' => $this->t('Comments'), 'class' => array(RESPONSIVE_PRIORITY_MEDIUM));
     }
     $form['node_types'] = array('#type' => 'tableselect', '#header' => $header, '#options' => $options);
     $form['kill'] = array('#type' => 'checkbox', '#title' => $this->t('<strong>Delete all content</strong> in these content types before generating new content.'), '#default_value' => $this->getSetting('kill'));
     $form['num'] = array('#type' => 'number', '#title' => $this->t('How many nodes would you like to generate?'), '#default_value' => $this->getSetting('num'), '#required' => TRUE, '#min' => 0);
     $options = array(1 => $this->t('Now'));
     foreach (array(3600, 86400, 604800, 2592000, 31536000) as $interval) {
         $options[$interval] = $this->dateFormatter->formatInterval($interval, 1) . ' ' . $this->t('ago');
     }
     $form['time_range'] = array('#type' => 'select', '#title' => $this->t('How far back in time should the nodes be dated?'), '#description' => $this->t('Node creation dates will be distributed randomly from the current time, back to the selected time.'), '#options' => $options, '#default_value' => 604800);
     $form['max_comments'] = array('#type' => $this->moduleHandler->moduleExists('comment') ? 'number' : 'value', '#title' => $this->t('Maximum number of comments per node.'), '#description' => $this->t('You must also enable comments for the content types you are generating. Note that some nodes will randomly receive zero comments. Some will receive the max.'), '#default_value' => $this->getSetting('max_comments'), '#min' => 0, '#access' => $this->moduleHandler->moduleExists('comment'));
     $form['title_length'] = array('#type' => 'number', '#title' => $this->t('Maximum number of words in titles'), '#default_value' => $this->getSetting('title_length'), '#required' => TRUE, '#min' => 1, '#max' => 255);
     $form['add_alias'] = array('#type' => 'checkbox', '#disabled' => !$this->moduleHandler->moduleExists('path'), '#description' => $this->t('Requires path.module'), '#title' => $this->t('Add an url alias for each node.'), '#default_value' => FALSE);
     $form['add_statistics'] = array('#type' => 'checkbox', '#title' => $this->t('Add statistics for each node (node_counter table).'), '#default_value' => TRUE, '#access' => $this->moduleHandler->moduleExists('statistics'));
     $options = array();
     // We always need a language.
     $languages = $this->languageManager->getLanguages(LanguageInterface::STATE_ALL);
     foreach ($languages as $langcode => $language) {
         $options[$langcode] = $language->getName();
     }
     $form['add_language'] = array('#type' => 'select', '#title' => $this->t('Set language on nodes'), '#multiple' => TRUE, '#description' => $this->t('Requires locale.module'), '#options' => $options, '#default_value' => array($this->languageManager->getDefaultLanguage()->getId()));
     $form['#redirect'] = FALSE;
     return $form;
 }
示例#26
0
  /**
   * Tests the fromUri() method with an invalid entity: URI.
   *
   * @covers ::fromUri
   * @expectedException \Symfony\Component\Routing\Exception\InvalidParameterException
   */
  public function testInvalidEntityUriParameter() {
    // Make the mocked URL generator behave like the actual one.
    $this->urlGenerator->expects($this->once())
      ->method('generateFromRoute')
      ->with('entity.test_entity.canonical', ['test_entity' => '1/blah'])
      ->willThrowException(new InvalidParameterException('Parameter "test_entity" for route "/test_entity/{test_entity}" must match "[^/]++" ("1/blah" given) to generate a corresponding URL..'));

    Url::fromUri('entity:test_entity/1/blah')->toString();
  }
示例#27
0
 /**
  * Tests the redirectForm() method when no redirect is expected.
  *
  * @covers ::redirectForm
  *
  * @dataProvider providerTestRedirectWithoutResult
  */
 public function testRedirectWithoutResult($form_state)
 {
     $form_submitter = $this->getFormSubmitter();
     $this->urlGenerator->expects($this->never())->method('generateFromPath');
     $this->urlGenerator->expects($this->never())->method('generateFromRoute');
     $form_state += $this->getFormStateDefaults();
     $redirect = $form_submitter->redirectForm($form_state);
     $this->assertNull($redirect);
 }
示例#28
0
 /**
  * Handles a request to either validate a user login or log a user out.
  *
  * The path that this controller/action handle are always set to the "service"
  * when authenticating with the CAS server, so CAS server communicates back to
  * the Drupal site using this controller.
  */
 public function handle()
 {
     $request = $this->requestStack->getCurrentRequest();
     // First, check if this is a single-log-out (SLO) request from the server.
     if ($request->request->has('logoutRequest')) {
         $this->casHelper->log("Logout request: passing to casLogout::handleSlo");
         $this->casLogout->handleSlo($request->request->get('logoutRequest'));
         // Always return a 200 code. CAS Server doesn’t care either way what
         // happens here, since it is a fire-and-forget approach taken.
         return Response::create('', 200);
     }
     // Our CAS Subscriber, which implements forced redirect and gateway, will
     // set this query string param which indicates we should disable the
     // subscriber on the next redirect. This prevents an infinite redirect loop.
     if ($request->query->has('cas_temp_disable')) {
         $this->casHelper->log("Temp disable flag set, set session flag.");
         $_SESSION['cas_temp_disable'] = TRUE;
     }
     // Check if there is a ticket parameter. If there isn't, we could be
     // returning from a gateway request and the user may not be logged into CAS.
     // Just redirect away from here.
     if (!$request->query->has('ticket')) {
         $this->casHelper->log("No ticket detected, move along.");
         $this->handleReturnToParameter($request);
         return RedirectResponse::create($this->urlGenerator->generate('<front>'));
     }
     $ticket = $request->query->get('ticket');
     // Our CAS service will need to reconstruct the original service URL
     // when validating the ticket. We always know what the base URL for
     // the service URL (it's this page), but there may be some query params
     // attached as well (like a destination param) that we need to pass in
     // as well. So, detach the ticket param, and pass the rest off.
     $service_params = $request->query->all();
     unset($service_params['ticket']);
     $cas_version = $this->casHelper->getCasProtocolVersion();
     $this->casHelper->log("Configured to use CAS protocol version: {$cas_version}");
     try {
         $cas_validation_info = $this->casValidator->validateTicket($cas_version, $ticket, $service_params);
     } catch (CasValidateException $e) {
         // Validation failed, redirect to homepage and set message.
         $this->setMessage(t('There was a problem validating your login, please contact a site administrator.'), 'error');
         $this->handleReturnToParameter($request);
         return RedirectResponse::create($this->urlGenerator->generate('<front>'));
     }
     try {
         $this->casLogin->loginToDrupal($cas_validation_info, $ticket);
         if ($this->casHelper->isProxy() && $cas_validation_info->getPgt()) {
             $this->casHelper->log("Storing PGT information for this session.");
             $this->casHelper->storePGTSession($cas_validation_info->getPgt());
         }
         $this->setMessage(t('You have been logged in.'));
     } catch (CasLoginException $e) {
         $this->setMessage(t('There was a problem logging in, please contact a site administrator.'), 'error');
     }
     $this->handleReturnToParameter($request);
     return RedirectResponse::create($this->urlGenerator->generate('<front>'));
 }
示例#29
0
 /**
  * Test generating the logout url with front page specified.
  *
  * @covers ::getServerLogoutUrl
  */
 public function testGetServerLogoutUrlFrontPage()
 {
     $config_factory = $this->getConfigFactoryStub(array('cas.settings' => array('logout.logout_destination' => '<front>')));
     $cas_helper = $this->getMockBuilder('\\Drupal\\cas\\Service\\CasHelper')->setConstructorArgs(array($config_factory, $this->urlGenerator, $this->connection, $this->loggerFactory, $this->session))->setMethods(array('getServerBaseUrl'))->getMock();
     $cas_helper->expects($this->once())->method('getServerBaseUrl')->will($this->returnValue('https://example.com/'));
     $request = $this->getMockBuilder('\\Symfony\\Component\\HttpFoundation\\Request')->disableOriginalConstructor()->getMock();
     $this->urlGenerator->expects($this->once())->method('generate')->will($this->returnValue('https://example.com/frontpage'));
     $this->assertEquals('https://example.com/logout?service=https%3A//example.com/frontpage', $cas_helper->getServerLogoutUrl($request));
 }
示例#30
0
 /**
  * Generates an absolute URL given a route name and parameters.
  *
  * @param $name
  *   The name of the route.
  * @param array $parameters
  *   An associative array of route parameter names and values.
  * @param array $options
  *   (optional) An associative array of additional options. The 'absolute'
  *   option is forced to be TRUE.
  *
  * @return string
  *   The generated absolute URL for the given route.
  *
  * @todo Add an option for scheme-relative URLs.
  */
 public function getUrl($name, $parameters = array(), $options = array())
 {
     // Generate URL.
     $options['absolute'] = TRUE;
     $generated_url = $this->urlGenerator->generateFromRoute($name, $parameters, $options, TRUE);
     // Return as render array, so we can bubble the bubbleable metadata.
     $build = ['#markup' => $generated_url->getGeneratedUrl()];
     $generated_url->applyTo($build);
     return $build;
 }