/** * {@inheritdoc} */ public function getResponse() { if (!$this->response) { $this->response = new TrustedRedirectResponse($this->url->toString()); } return $this->response; }
/** * Performs a HTTP request with Basic authentication. * * We do not use \Drupal\simpletest\WebTestBase::drupalGet because we need to * set curl settings for basic authentication. * * @param \Drupal\Core\Url $url * A Url object. * @param string $username * The user name to authenticate with. * @param string $password * The password. * @param string $mime_type * The MIME type for the Accept header. * * @return string * Curl output. */ protected function basicAuthGet(Url $url, $username, $password, $mime_type = NULL) { if (!isset($mime_type)) { $mime_type = $this->defaultMimeType; } $out = $this->curlExec(array(CURLOPT_HTTPGET => TRUE, CURLOPT_URL => $url->setAbsolute()->toString(), CURLOPT_NOBODY => FALSE, CURLOPT_HTTPAUTH => CURLAUTH_BASIC, CURLOPT_USERPWD => $username . ':' . $password, CURLOPT_HTTPHEADER => array('Accept: ' . $mime_type))); $this->verbose('GET request to: ' . $url->toString() . '<hr />' . $out); return $out; }
/** * Tests bubbling of cacheable metadata for URLs. * * @param bool $collect_bubbleable_metadata * Whether bubbleable metadata should be collected. * @param int $invocations * The expected amount of invocations for the ::bubble() method. * @param array $options * The URL options. * * @covers ::bubble * * @dataProvider providerUrlBubbleableMetadataBubbling */ public function testUrlBubbleableMetadataBubbling($collect_bubbleable_metadata, $invocations, array $options) { $self = $this; $this->renderer->expects($this->exactly($invocations))->method('render')->willReturnCallback(function ($build) use($self) { $self->assertTrue(!empty($build['#cache'])); }); $url = new Url('test_1', [], $options); $url->setUrlGenerator($this->generator); $url->toString($collect_bubbleable_metadata); }
/** * {@inheritdoc} */ public function save(array $form, array &$form_state) { $sirenMapper = $this->entity; $status = $sirenMapper->save(); if ($status) { // Setting the success message. drupal_set_message($this->t('Saved the siren mapper: @name.', array('@name' => $sirenMapper->name))); } else { drupal_set_message($this->t('The @name siren mapper was not saved.', array('@name' => $sirenMapper->name))); } $url = new Url('siren_mapper.list'); $form_state['redirect'] = $url->toString(); }
/** * {@inheritdoc} */ public function save(array $form, array &$form_state) { $brand = $this->entity; $status = $brand->save(); if ($status) { // Setting the success message. drupal_set_message($this->t('Saved the brand: @name.', array('@name' => $brand->name))); } else { drupal_set_message($this->t('The @name brand was not saved.', array('@name' => $brand->name))); } $url = new Url('brandConfig.list'); $form_state['redirect'] = $url->toString(); }
/** * Checks whether a give path matches the ng-lightbox path rules. * This function checks both internal paths and aliased paths. * * @param \Drupal\Core\Url $url * The Url object. * * @return bool * TRUE if it matches the given rules. */ public function isNgLightboxEnabledPath(Url $url) { // No lightbox on external Urls. if ($url->isExternal()) { return FALSE; } // If we don't want to enable the Lightbox on admin pages. if ($this->config->get('skip_admin_paths') && $this->adminContext->isAdminRoute()) { return FALSE; } // @TODO, decide whether we want to try and support paths or to adopt routes // like core is trying to force us into. $path = strtolower($url->toString()); // We filter out empty paths because some modules (such as Media) use // theme_link() to generate links with empty paths. if (empty($path)) { return FALSE; } // Remove the base path. if ($base_path = \Drupal::request()->getBasePath()) { $path = substr($path, strlen($base_path)); } // Check the cache, see if we've handled this before. if (isset($this->matches[$path])) { return $this->matches[$path]; } // Normalise the patterns as well so they match the normalised paths. $patterns = strtolower($this->config->get('patterns')); // Check for internal paths first which is much quicker than the alias lookup. if ($this->pathMatcher->matchPath($path, $patterns)) { $this->matches[$path] = TRUE; } else { // Now check for aliases paths. $aliased_path = strtolower($this->aliasManager->getAliasByPath($path)); if ($path != $aliased_path && $this->pathMatcher->matchPath($aliased_path, $patterns)) { $this->matches[$path] = TRUE; } else { // No match. $this->matches[$path] = FALSE; } } return $this->matches[$path]; }
/** * {@inheritdoc} */ public function blockForm($form, FormStateInterface $form_state) { // Get the theme. $theme = $form_state->get('block_theme'); // Get permissions. $url_system_theme_settings = new Url('system.theme_settings'); $url_system_theme_settings_theme = new Url('system.theme_settings_theme', array('theme' => $theme)); if ($url_system_theme_settings->access() && $url_system_theme_settings_theme->access()) { // Provide links to the Appearance Settings and Theme Settings pages // if the user has access to administer themes. $site_logo_description = $this->t('Defined on the <a href="@appearance">Appearance Settings</a> or <a href="@theme">Theme Settings</a> page.', array('@appearance' => $url_system_theme_settings->toString(), '@theme' => $url_system_theme_settings_theme->toString())); } else { // Explain that the user does not have access to the Appearance and Theme // Settings pages. $site_logo_description = $this->t('Defined on the Appearance or Theme Settings page. You do not have the appropriate permissions to change the site logo.'); } $url_system_site_information_settings = new Url('system.site_information_settings'); if ($url_system_site_information_settings->access()) { // Get paths to settings pages. $site_information_url = $url_system_site_information_settings->toString(); // Provide link to Site Information page if the user has access to // administer site configuration. $site_name_description = $this->t('Defined on the <a href="@information">Site Information</a> page.', array('@information' => $site_information_url)); $site_slogan_description = $this->t('Defined on the <a href="@information">Site Information</a> page.', array('@information' => $site_information_url)); } else { // Explain that the user does not have access to the Site Information // page. $site_name_description = $this->t('Defined on the Site Information page. You do not have the appropriate permissions to change the site logo.'); $site_slogan_description = $this->t('Defined on the Site Information page. You do not have the appropriate permissions to change the site logo.'); } $form['block_branding'] = array('#type' => 'fieldset', '#title' => $this->t('Toggle branding elements'), '#description' => $this->t('Choose which branding elements you want to show in this block instance.')); $form['block_branding']['use_site_logo'] = array('#type' => 'checkbox', '#title' => $this->t('Site logo'), '#description' => $site_logo_description, '#default_value' => $this->configuration['use_site_logo']); $form['block_branding']['use_site_name'] = array('#type' => 'checkbox', '#title' => $this->t('Site name'), '#description' => $site_name_description, '#default_value' => $this->configuration['use_site_name']); $form['block_branding']['use_site_slogan'] = array('#type' => 'checkbox', '#title' => $this->t('Site slogan'), '#description' => $site_slogan_description, '#default_value' => $this->configuration['use_site_slogan']); return $form; }
/** * Asserts that a cancel link is present pointing to the provided URL. * * @param \Drupal\Core\Url $url * The url to check for. * @param string $message * The assert message. * @param string $group * The assertion group. * * @return bool * Result of the assertion. */ public function assertCancelLinkUrl(Url $url, $message = '', $group = 'Other') { $links = $this->xpath('//a[@href=:url]', [':url' => $url->toString()]); $message = $message ? $message : SafeMarkup::format('Cancel link with url %url found.', ['%url' => $url->toString()]); return $this->assertTrue(isset($links[0]), $message, $group); }
/** * Prior to set the response it check if we can redirect. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The event object. * @param \Drupal\Core\Url $url * The Url where we want to redirect. */ protected function setResponse(GetResponseEvent $event, Url $url) { $request = $event->getRequest(); $this->context->fromRequest($request); parse_str($request->getQueryString(), $query); $url->setOption('query', $query); $url->setAbsolute(TRUE); // We can only check access for routed URLs. if (!$url->isRouted() || $this->redirectChecker->canRedirect($url->getRouteName(), $request)) { // Add the 'rendered' cache tag, so that we can invalidate all responses // when settings are changed. $headers = ['X-Drupal-Cache-Tags' => 'rendered']; $event->setResponse(new RedirectResponse($url->toString(), 301, $headers)); } }
/** * Tests that the given path provides the correct alternate hreflang links. * * @param \Drupal\Core\Url $url * The path to be tested. */ protected function doTestAlternateHreflangLinks(Url $url) { $languages = $this->container->get('language_manager')->getLanguages(); $url->setAbsolute(); $urls = []; foreach ($this->langcodes as $langcode) { $language_url = clone $url; $urls[$langcode] = $language_url->setOption('language', $languages[$langcode]); } foreach ($this->langcodes as $langcode) { $this->drupalGet($urls[$langcode]); foreach ($urls as $alternate_langcode => $language_url) { // Retrieve desired link elements from the HTML head. $links = $this->xpath('head/link[@rel = "alternate" and @href = :href and @hreflang = :hreflang]', array(':href' => $language_url->toString(), ':hreflang' => $alternate_langcode)); $this->assert(isset($links[0]), format_string('The %langcode node translation has the correct alternate hreflang link for %alternate_langcode: %link.', array('%langcode' => $langcode, '%alternate_langcode' => $alternate_langcode, '%link' => $url->toString()))); } } }
/** * {@inheritdoc} * * For anonymous users, the "active" class will be calculated on the server, * because most sites serve each anonymous user the same cached page anyway. * For authenticated users, the "active" class will be calculated on the * client (through JavaScript), only data- attributes are added to links to * prevent breaking the render cache. The JavaScript is added in * system_page_attachments(). * * @see system_page_attachments() */ public function generate($text, Url $url) { // Performance: avoid Url::toString() needing to retrieve the URL generator // service from the container. $url->setUrlGenerator($this->urlGenerator); if (is_array($text)) { $text = $this->renderer->render($text); } // Start building a structured representation of our link to be altered later. $variables = array('text' => $text, 'url' => $url, 'options' => $url->getOptions()); // Merge in default options. $variables['options'] += array('attributes' => array(), 'query' => array(), 'language' => NULL, 'set_active_class' => FALSE, 'absolute' => FALSE); // Add a hreflang attribute if we know the language of this link's url and // hreflang has not already been set. if (!empty($variables['options']['language']) && !isset($variables['options']['attributes']['hreflang'])) { $variables['options']['attributes']['hreflang'] = $variables['options']['language']->getId(); } // Ensure that query values are strings. array_walk($variables['options']['query'], function (&$value) { if ($value instanceof MarkupInterface) { $value = (string) $value; } }); // Set the "active" class if the 'set_active_class' option is not empty. if (!empty($variables['options']['set_active_class']) && !$url->isExternal()) { // Add a "data-drupal-link-query" attribute to let the // drupal.active-link library know the query in a standardized manner. if (!empty($variables['options']['query'])) { $query = $variables['options']['query']; ksort($query); $variables['options']['attributes']['data-drupal-link-query'] = Json::encode($query); } // Add a "data-drupal-link-system-path" attribute to let the // drupal.active-link library know the path in a standardized manner. if ($url->isRouted() && !isset($variables['options']['attributes']['data-drupal-link-system-path'])) { // @todo System path is deprecated - use the route name and parameters. $system_path = $url->getInternalPath(); // Special case for the front page. $variables['options']['attributes']['data-drupal-link-system-path'] = $system_path == '' ? '<front>' : $system_path; } } // Remove all HTML and PHP tags from a tooltip, calling expensive strip_tags() // only when a quick strpos() gives suspicion tags are present. if (isset($variables['options']['attributes']['title']) && strpos($variables['options']['attributes']['title'], '<') !== FALSE) { $variables['options']['attributes']['title'] = strip_tags($variables['options']['attributes']['title']); } // Allow other modules to modify the structure of the link. $this->moduleHandler->alter('link', $variables); // Move attributes out of options since generateFromRoute() doesn't need // them. Include a placeholder for the href. $attributes = array('href' => '') + $variables['options']['attributes']; unset($variables['options']['attributes']); $url->setOptions($variables['options']); // External URLs can not have cacheable metadata. if ($url->isExternal()) { $generated_link = new GeneratedLink(); $attributes['href'] = $url->toString(FALSE); } else { $generated_url = $url->toString(TRUE); $generated_link = GeneratedLink::createFromObject($generated_url); // The result of the URL generator is a plain-text URL to use as the href // attribute, and it is escaped by \Drupal\Core\Template\Attribute. $attributes['href'] = $generated_url->getGeneratedUrl(); } if (!SafeMarkup::isSafe($variables['text'])) { $variables['text'] = Html::escape($variables['text']); } $attributes = new Attribute($attributes); // This is safe because Attribute does escaping and $variables['text'] is // either rendered or escaped. return $generated_link->setGeneratedLink('<a' . $attributes . '>' . $variables['text'] . '</a>'); }
public function ajaxSave(array &$form, FormStateInterface $form_state) { $response = new AjaxResponse(); $cached_values = $this->tempstore->get($this->tempstore_id)->get($this->machine_name); list($route_name, $route_parameters) = $this->getParentRouteInfo($cached_values); $url = new Url($route_name, $route_parameters); $response->addCommand(new RedirectCommand($url->toString())); $response->addCommand(new CloseModalDialogCommand()); return $response; }
public function generateUrl(Url $url) { return $url->toString(); }
/** * Adds a contextual tab to entities. * * @param RouteMatchInterface $route_match * * @return RedirectResponse */ public function contextualTab(RouteMatchInterface $route_match) { $parameter_name = $route_match->getRouteObject()->getOption('_ds_entity_type_id'); $entity = $route_match->getParameter($parameter_name); $entity_type_id = $entity->getEntityTypeId(); $destination = $entity->toUrl(); if (!empty($entity->ds_switch->value)) { $view_mode = $entity->ds_switch->value; } else { $view_mode = 'full'; } // Get the manage display URI. $route = FieldUI::getOverviewRouteInfo($entity_type_id, $entity->bundle()); /** @var $entity_display EntityDisplayBase */ $entity_display = EntityViewDisplay::load($entity_type_id . '.' . $entity->bundle() . '.' . $view_mode); $route_parameters = $route->getRouteParameters(); if ($entity_display && $entity_display->getThirdPartySetting('ds', 'layout')) { $route_parameters['view_mode_name'] = $view_mode; $admin_route_name = "entity.entity_view_display.{$entity_type_id}.view_mode"; } else { $admin_route_name = "entity.entity_view_display.{$entity_type_id}.default"; } $route->setOption('query', array('destination' => $destination->toString())); $url = new Url($admin_route_name, $route_parameters, $route->getOptions()); return new RedirectResponse($url->toString()); }
/** * Adds a contextual tab to entities. */ public function contextualTab($entity_type, $entity_id) { /** @var $entity EntityInterface */ $entity = entity_load($entity_type, $entity_id); $destination = $entity->urlInfo(); if (!empty($entity->ds_switch->value)) { $view_mode = $entity->ds_switch->value; } else { $view_mode = 'full'; } // Get the manage display URI. $route = FieldUI::getOverviewRouteInfo($entity_type, $entity->bundle()); /** @var $entity_display EntityDisplayBase */ $entity_display = entity_get_display($entity_type, $entity->bundle(), $view_mode); $route_parameters = $route->getRouteParameters(); if ($entity_display->getThirdPartySetting('ds', 'layout')) { $route_parameters['view_mode_name'] = $view_mode; $admin_route_name = "entity.entity_view_display.$entity_type.view_mode"; } else { $admin_route_name = "entity.entity_view_display.$entity_type.default"; } $route->setOption('query', array('destination' => $destination->toString())); $url = new Url($admin_route_name, $route_parameters, $route->getOptions()); return new RedirectResponse($url->toString()); }
/** * Tests the toString() method. * * @depends testCreateFromPath * * @covers ::toString() */ public function testToString(Url $url) { $this->assertSame($this->path, $url->toString()); }
/** * Load and render a help topic. * * @param string $module * Name of the module. * @param string $topic * Name of the topic. * @todo port the drupal_alter functionality. * * @return string * Returns formatted topic. */ public function viewTopic($module, $topic, $is_modal = false) { $file_info = $this->advanced_help->getTopicFileInfo($module, $topic); if ($file_info) { $info = $this->advanced_help->getTopic($module, $topic); $file = "{$file_info['path']}/{$file_info['file']}"; $build = [ '#type' => 'markup', ]; if (!empty($info['css'])) { $build['#attached']['library'][] = $info['module'] . '/' . $info['css']; } $build['#markup'] = file_get_contents($file); if (isset($info['readme file']) && $info['readme file']) { $ext = pathinfo($file, PATHINFO_EXTENSION); if ('md' == $ext && $this->advanced_help->isMarkdownFilterEnabled()) { libraries_load('php-markdown', 'markdown-extra'); $build['#markup'] = '<div class="advanced-help-topic">' . Xss::filterAdmin(\Michelf\MarkdownExtra::defaultTransform($build['#markup'])) . '</div>'; } else { $readme = ''; if ('md' == $ext) { $readme .= '<p>' . $this->t('If you install the !module module, the text below will be filtered by the module, producing rich text.', [ '!module' => $this->l($this->t('Markdown filter'), Url::fromUri('https://www.drupal.org/project/markdown'), ['attributes' => ['title' => $this->t('Link to project.')]]) ]) . '</p>'; } $readme .= '<div class="advanced-help-topic"><pre class="readme">' . SafeMarkup::checkPlain($build['#markup']) . '</pre></div>'; $build['#markup'] = $readme; } return $build['#markup']; } // Change 'topic:' to the URL for another help topic. preg_match('/&topic:([^"]+)&/', $build['#markup'], $matches); if (isset($matches[1]) && preg_match('/[\w\-]\/[\w\-]+/', $matches[1])) { list($umodule, $utopic) = explode('/', $matches[1]); $path = new Url('advanced_help.help', ['module' => $umodule, 'topic' => $utopic]); $build['#markup'] = preg_replace('/&topic:([^"]+)&/', $path->toString(), $build['#markup']); } global $base_path; // Change 'path:' to the URL to the base help directory. $build['#markup'] = str_replace('&path&', $base_path . $info['path'] . '/', $build['#markup']); // Change 'trans_path:' to the URL to the actual help directory. $build['#markup'] = str_replace('&trans_path&', $base_path . $file_info['path'] . '/', $build['#markup']); // Change 'base_url:' to the URL to the site. $build['#markup'] = preg_replace('/&base_url&([^"]+)"/', $base_path . '$1' . '"', $build['#markup']); // Run the line break filter if requested. if (!empty($info['line break'])) { // Remove the header since it adds an extra <br /> to the filter. $build['#markup'] = preg_replace('/^<!--[^\n]*-->\n/', '', $build['#markup']); $build['#markup'] = _filter_autop($build['#markup']); } if (!empty($info['navigation']) && !$is_modal) { $topics = $this->advanced_help->getTopics(); $topics = $this->getTopicHierarchy($topics); if (!empty($topics[$module][$topic]['children'])) { $items = $this->getTree($topics, $topics[$module][$topic]['children']); $links = [ '#theme' => 'item_list', '#items' => $items ]; $build['#markup'] .= \Drupal::service('renderer')->render($links, FALSE); } list($parent_module, $parent_topic) = $topics[$module][$topic]['_parent']; if ($parent_topic) { $parent = $topics[$module][$topic]['_parent']; $up = new Url('advanced_help.help', ['module' => $parent[0], 'topic' => $parent[1]]); } else { $up = new Url('advanced_help.module_index', ['module' => $module]); } $siblings = $topics[$parent_module][$parent_topic]['children']; uasort($siblings, [$this, 'helpUasort']); $prev = $next = NULL; $found = FALSE; foreach ($siblings as $sibling) { list($sibling_module, $sibling_topic) = $sibling; if ($found) { $next = $sibling; break; } if ($sibling_module == $module && $sibling_topic == $topic) { $found = TRUE; continue; } $prev = $sibling; } if ($prev || $up || $next) { $navigation = '<div class="help-navigation clear-block">'; if ($prev) { $navigation .= $this->l('«« ' . $topics[$prev[0]][$prev[1]]['title'], new Url('advanced_help.help', ['module' => $prev[0], 'topic' => $prev[1]], ['attributes' => ['class' => 'help-left']])); } if ($up) { $navigation .= $this->l($this->t('Up'), $up->setOption('attributes', ['class' => ($prev) ? 'help-up' : 'help-up-noleft'])); } if ($next) { $navigation .= $this->l($topics[$next[0]][$next[1]]['title'] . ' »»', new Url('advanced_help.help', ['module' => $next[0], 'topic' => $next[1]], ['attributes' => ['class' => 'help-right']])); } $navigation .= '</div>'; $build['#markup'] .= $navigation; } } $build['#markup'] = '<div class="advanced-help-topic">' . $build['#markup'] . '</div>'; // drupal_alter('advanced_help_topic', $output, $popup); return $build; } }
/** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $config = $this->config('ds.settings'); $form['additional_settings'] = array( '#type' => 'vertical_tabs', '#attached' => array( 'library' => array('ds/admin'), ), ); $form['fs1'] = array( '#type' => 'details', '#title' => t('Field Templates'), '#group' => 'additional_settings', '#tree' => TRUE, '#collapsed' => FALSE, ); $form['fs1']['field_template'] = array( '#type' => 'checkbox', '#title' => t('Enable Field Templates'), '#description' => t('Customize the labels and the HTML output of your fields.'), '#default_value' => $config->get('field_template'), ); $theme_functions = Ds::getFieldLayoutOptions(); $url = new Url('ds.classes'); $form['fs1']['ft-default'] = array( '#type' => 'select', '#title' => t('Default Field Template'), '#options' => $theme_functions, '#default_value' => $config->get('ft-default'), '#description' => t('Default will output the field as defined in Drupal Core.<br />Reset will strip all HTML.<br />Minimal adds a simple wrapper around the field.<br/>There is also an Expert Field Template that gives full control over the HTML, but can only be set per field.<br /><br />You can override this setting per field on the "Manage display" screens or when creating fields on the instance level.<br /><br /><strong>Template suggestions</strong><br />You can create .html.twig files as well for these field theme functions, e.g. field--reset.html.twig, field--minimal.html.twig<br /><br /><label>CSS classes</label>You can add custom CSS classes on the <a href=":url">classes form</a>. These classes can be added to fields using the Default Field Template.<br /><br /><label>Advanced</label>You can create your own custom field templates which need to be defined with hook_ds_field_theme_functions_info(). See ds.api.php for an example.', array(':url' => $url->toString())), '#states' => array( 'visible' => array( 'input[name="fs1[field_template]"]' => array('checked' => TRUE), ), ), ); $form['fs1']['ft-show-colon'] = array( '#type' => 'checkbox', '#title' => t('Show colon'), '#default_value' => $config->get('ft-show-colon'), '#description' => t('Show the colon on the reset field template.'), '#states' => array( 'visible' => array( 'select[name="fs1[ft-default]"]' => array('value' => 'reset'), 'input[name="fs1[field_template]"]' => array('checked' => TRUE), ), ), ); return parent::buildForm($form, $form_state); }
/** * Redirect to the correct manage callback. */ public function manageRedirect($field_key) { $config = $this->config('ds.field.' . $field_key); if ($field = $config->get()) { $url = new Url('ds.manage_' . $field['type'] . '_field', array('field_key' => $field_key)); if ($url->toString()) { return new RedirectResponse($url->toString()); } } drupal_set_message($this->t('Field not found')); $url = new Url('ds.fields_list'); return new RedirectResponse($url->toString()); }
/** * Prior to set the response it check if we can redirect. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The event object. * @param \Drupal\Core\Url $url * The Url where we want to redirect. */ protected function setResponse(GetResponseEvent $event, Url $url) { $request = $event->getRequest(); $this->context->fromRequest($request); parse_str($request->getQueryString(), $query); $url->setOption('query', $query); $url->setAbsolute(TRUE); // We can only check access for routed URLs. if (!$url->isRouted() || $this->checker->canRedirect($request, $url->getRouteName())) { // Add the 'rendered' cache tag, so that we can invalidate all responses // when settings are changed. $response = new TrustedRedirectResponse($url->toString(), 301); $response->addCacheableDependency(CacheableMetadata::createFromRenderArray([])->addCacheTags(['rendered'])); $event->setResponse($response); } }