UnroutedUrlAssembler.php 6.98 KB
Newer Older
1 2 3 4
<?php

namespace Drupal\Core\Utility;

5
use Drupal\Component\Utility\NestedArray;
6
use Drupal\Component\Utility\UrlHelper;
7
use Drupal\Core\GeneratedUrl;
8
use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
use Symfony\Component\HttpFoundation\RequestStack;

/**
 * Provides a way to build external or non Drupal local domain URLs.
 *
 * It takes into account configured safe HTTP protocols.
 */
class UnroutedUrlAssembler implements UnroutedUrlAssemblerInterface {

  /**
   * A request stack object.
   *
   * @var \Symfony\Component\HttpFoundation\RequestStack
   */
  protected $requestStack;

25 26 27 28 29 30 31
  /**
   * The outbound path processor.
   *
   * @var \Drupal\Core\PathProcessor\OutboundPathProcessorInterface
   */
  protected $pathProcessor;

32
  /**
33
   * Constructs a new unroutedUrlAssembler object.
34 35 36
   *
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   *   A request stack object.
37 38
   * @param \Drupal\Core\PathProcessor\OutboundPathProcessorInterface $path_processor
   *   The output path processor.
39 40
   * @param string[] $filter_protocols
   *   (optional) An array of protocols allowed for URL generation.
41
   */
42 43
  public function __construct(RequestStack $request_stack, OutboundPathProcessorInterface $path_processor, array $filter_protocols = ['http', 'https']) {
    UrlHelper::setAllowedProtocols($filter_protocols);
44
    $this->requestStack = $request_stack;
45
    $this->pathProcessor = $path_processor;
46 47 48 49 50 51 52 53
  }

  /**
   * {@inheritdoc}
   *
   * This is a helper function that calls buildExternalUrl() or buildLocalUrl()
   * based on a check of whether the path is a valid external URL.
   */
54
  public function assemble($uri, array $options = [], $collect_bubbleable_metadata = FALSE) {
55 56 57
    // Note that UrlHelper::isExternal will return FALSE if the $uri has a
    // disallowed protocol.  This is later made safe since we always add at
    // least a leading slash.
58
    if (parse_url($uri, PHP_URL_SCHEME) === 'base') {
59
      return $this->buildLocalUrl($uri, $options, $collect_bubbleable_metadata);
60 61 62
    }
    elseif (UrlHelper::isExternal($uri)) {
      // UrlHelper::isExternal() only returns true for safe protocols.
63
      return $this->buildExternalUrl($uri, $options, $collect_bubbleable_metadata);
64
    }
65
    throw new \InvalidArgumentException("The URI '$uri' is invalid. You must use a valid URI scheme. Use base: for a path, e.g., to a Drupal file that needs the base path. Do not use this for internal paths controlled by Drupal.");
66 67 68 69 70
  }

  /**
   * {@inheritdoc}
   */
71
  protected function buildExternalUrl($uri, array $options = [], $collect_bubbleable_metadata = FALSE) {
72
    $this->addOptionDefaults($options);
73 74 75 76 77 78 79
    // Split off the query & fragment.
    $parsed = UrlHelper::parse($uri);
    $uri = $parsed['path'];

    $parsed += ['query' => []];
    $options += ['query' => []];

80
    $options['query'] = NestedArray::mergeDeepArray([$parsed['query'], $options['query']], TRUE);
81 82 83

    if ($parsed['fragment'] && !$options['fragment']) {
      $options['fragment'] = '#' . $parsed['fragment'];
84 85 86 87 88 89 90 91 92 93 94 95
    }

    if (isset($options['https'])) {
      if ($options['https'] === TRUE) {
        $uri = str_replace('http://', 'https://', $uri);
      }
      elseif ($options['https'] === FALSE) {
        $uri = str_replace('https://', 'http://', $uri);
      }
    }
    // Append the query.
    if ($options['query']) {
96
      $uri .= '?' . UrlHelper::buildQuery($options['query']);
97 98
    }
    // Reassemble.
99
    $url = $uri . $options['fragment'];
100
    return $collect_bubbleable_metadata ? (new GeneratedUrl())->setGeneratedUrl($url) : $url;
101 102 103 104 105
  }

  /**
   * {@inheritdoc}
   */
106 107
  protected function buildLocalUrl($uri, array $options = [], $collect_bubbleable_metadata = FALSE) {
    $generated_url = $collect_bubbleable_metadata ? new GeneratedUrl() : NULL;
108

109 110 111
    $this->addOptionDefaults($options);
    $request = $this->requestStack->getCurrentRequest();

112 113 114 115
    // Remove the base: scheme.
    // @todo Consider using a class constant for this in
    //   https://www.drupal.org/node/2417459
    $uri = substr($uri, 5);
116 117 118 119 120

    // Allow (outbound) path processing, if needed. A valid use case is the path
    // alias overview form:
    // @see \Drupal\path\Controller\PathController::adminOverview().
    if (!empty($options['path_processing'])) {
121 122 123
      // Do not pass the request, since this is a special case and we do not
      // want to include e.g. the request language in the processing.
      $uri = $this->pathProcessor->processOutbound($uri, $options, NULL, $generated_url);
124
    }
125 126 127 128
    // Strip leading slashes from internal paths to prevent them becoming
    // external URLs without protocol. /example.com should not be turned into
    // //example.com.
    $uri = ltrim($uri, '/');
129

130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147
    // Add any subdirectory where Drupal is installed.
    $current_base_path = $request->getBasePath() . '/';

    if ($options['absolute']) {
      $current_base_url = $request->getSchemeAndHttpHost() . $current_base_path;
      if (isset($options['https'])) {
        if (!empty($options['https'])) {
          $base = str_replace('http://', 'https://', $current_base_url);
          $options['absolute'] = TRUE;
        }
        else {
          $base = str_replace('https://', 'http://', $current_base_url);
          $options['absolute'] = TRUE;
        }
      }
      else {
        $base = $current_base_url;
      }
148
      if ($collect_bubbleable_metadata) {
149 150
        $generated_url->addCacheContexts(['url.site']);
      }
151 152 153 154 155 156 157 158 159
    }
    else {
      $base = $current_base_path;
    }

    $prefix = empty($uri) ? rtrim($options['prefix'], '/') : $options['prefix'];

    $uri = str_replace('%2F', '/', rawurlencode($prefix . $uri));
    $query = $options['query'] ? ('?' . UrlHelper::buildQuery($options['query'])) : '';
160
    $url = $base . $options['script'] . $uri . $query . $options['fragment'];
161
    return $collect_bubbleable_metadata ? $generated_url->setGeneratedUrl($url) : $url;
162 163 164 165 166 167 168 169 170
  }

  /**
   * Merges in default defaults
   *
   * @param array $options
   *   The options to merge in the defaults.
   */
  protected function addOptionDefaults(array &$options) {
171 172 173 174 175 176 177
    $request = $this->requestStack->getCurrentRequest();
    $current_base_path = $request->getBasePath() . '/';
    $current_script_path = '';
    $base_path_with_script = $request->getBaseUrl();

    // If the current request was made with the script name (eg, index.php) in
    // it, then extract it, making sure the leading / is gone, and a trailing /
178
    // is added, to allow simple string concatenation with other parts.
179 180 181 182 183 184 185
    if (!empty($base_path_with_script)) {
      $script_name = $request->getScriptName();
      if (strpos($base_path_with_script, $script_name) !== FALSE) {
        $current_script_path = ltrim(substr($script_name, strlen($current_base_path)), '/') . '/';
      }
    }

186 187 188 189 190 191
    // Merge in defaults.
    $options += [
      'fragment' => '',
      'query' => [],
      'absolute' => FALSE,
      'prefix' => '',
192
      'script' => $current_script_path,
193 194 195 196 197 198 199 200
    ];

    if (isset($options['fragment']) && $options['fragment'] !== '') {
      $options['fragment'] = '#' . $options['fragment'];
    }
  }

}