UrlGenerator.php 13.9 KB
Newer Older
1 2 3 4
<?php

/**
 * @file
Crell's avatar
Crell committed
5
 * Contains Drupal\Core\Routing\UrlGenerator.
6 7 8 9
 */

namespace Drupal\Core\Routing;

10
use Psr\Log\LoggerInterface;
11
use Symfony\Component\HttpFoundation\Request;
12
use Symfony\Component\HttpFoundation\RequestStack;
13

14 15 16
use Symfony\Component\Routing\Route as SymfonyRoute;
use Symfony\Component\Routing\Exception\RouteNotFoundException;

17 18
use Symfony\Cmf\Component\Routing\ProviderBasedGenerator;

19
use Drupal\Component\Utility\UrlHelper;
20
use Drupal\Core\Config\ConfigFactoryInterface;
21
use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
22
use Drupal\Core\RouteProcessor\OutboundRouteProcessorInterface;
23
use Drupal\Core\Site\Settings;
24 25

/**
26
 * Generates URLs from route names and parameters.
27
 */
28
class UrlGenerator extends ProviderBasedGenerator implements UrlGeneratorInterface {
29 30

  /**
31
   * A request stack object.
32
   *
33
   * @var \Symfony\Component\HttpFoundation\RequestStack
34
   */
35
  protected $requestStack;
36 37 38 39 40 41 42 43

  /**
   * The path processor to convert the system path to one suitable for urls.
   *
   * @var \Drupal\Core\PathProcessor\OutboundPathProcessorInterface
   */
  protected $pathProcessor;

44 45 46
  /**
   * The route processor.
   *
47
   * @var \Drupal\Core\RouteProcessor\OutboundRouteProcessorInterface
48 49 50
   */
  protected $routeProcessor;

51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
  /**
   * The base path to use for urls.
   *
   * @var string
   */
  protected $basePath;

  /**
   * The base url to use for urls.
   *
   * @var string
   */
  protected $baseUrl;

  /**
   * The script path to use for urls.
   *
   * @var string
   */
  protected $scriptPath;
71 72

  /**
73
   * Whether both secure and insecure session cookies can be used simultaneously.
74
   *
75
   * @var bool
76
   */
77
  protected $mixedModeSessions;
78

79 80 81
  /**
   *  Constructs a new generator object.
   *
82
   * @param \Drupal\Core\Routing\RouteProviderInterface $provider
83
   *   The route provider to be searched for routes.
84 85 86 87 88 89
   * @param \Drupal\Core\PathProcessor\OutboundPathProcessorInterface $path_processor
   *   The path processor to convert the system path to one suitable for urls.
   * @param \Drupal\Core\RouteProcessor\OutboundRouteProcessorInterface $route_processor
   *   The route processor.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config
   *    The config factory.
90
   * @param \Drupal\Core\Site\Settings $settings
91
   *    The read only settings.
92
   * @param \Psr\Log\LoggerInterface $logger
93
   *   An optional logger for recording errors.
94 95
   * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
   *   A request stack object.
96
   */
97
  public function __construct(RouteProviderInterface $provider, OutboundPathProcessorInterface $path_processor, OutboundRouteProcessorInterface $route_processor, ConfigFactoryInterface $config, Settings $settings, LoggerInterface $logger = NULL, RequestStack $request_stack) {
98 99
    parent::__construct($provider, $logger);

100
    $this->pathProcessor = $path_processor;
101
    $this->routeProcessor = $route_processor;
102 103
    $this->mixedModeSessions = $settings->get('mixed_mode_sessions', FALSE);
    $allowed_protocols = $config->get('system.filter')->get('protocols') ?: array('http', 'https');
104
    UrlHelper::setAllowedProtocols($allowed_protocols);
105
    $this->requestStack = $request_stack;
106
    $this->updateFromRequest();
107 108 109
  }

  /**
110 111 112 113
   * Updates instance properties using the current request from the stack.
   *
   * @todo This should probably be inline in the constructor as this is only
   *   useful to get some current tests pass.
114
   */
115 116
  public function updateFromRequest() {
    $request = $this->requestStack->getCurrentRequest();
117 118 119 120 121 122 123 124 125 126 127
    // Set some properties, based on the request, that are used during path-based
    // url generation.
    $this->basePath = $request->getBasePath() . '/';
    $this->baseUrl = $request->getSchemeAndHttpHost() . $this->basePath;
    $this->scriptPath = '';
    $base_path_with_script = $request->getBaseUrl();
    $script_name = $request->getScriptName();
    if (!empty($base_path_with_script) && strpos($base_path_with_script, $script_name) !== FALSE) {
      $length = strlen($this->basePath);
      $this->scriptPath = ltrim(substr($script_name, $length), '/') . '/';
    }
128 129
  }

130
  /**
131
   * {@inheritdoc}
132
   */
133
  public function getPathFromRoute($name, $parameters = array()) {
134
    $route = $this->getRoute($name);
135 136 137 138 139 140 141
    $path = $this->getInternalPathFromRoute($route, $parameters);
    // Router-based paths may have a querystring on them but Drupal paths may
    // not have one, so remove any ? and anything after it. For generate() this
    // is handled in processPath().
    $path = preg_replace('/\?.*/', '', $path);
    return trim($path, '/');
  }
142

143 144 145 146 147 148 149 150 151 152 153 154 155
  /**
   * Gets the path of a route.
   *
   * @param \Symfony\Component\Routing\Route $route
   *  The route object.
   * @param array $parameters
   *  An array of parameters as passed to
   *  \Symfony\Component\Routing\Generator\UrlGeneratorInterface::generate().
   *
   * @return string
   *  The url path corresponding to the route, without the base path.
   */
  protected function getInternalPathFromRoute(SymfonyRoute $route, $parameters = array()) {
156 157 158 159 160 161 162 163 164 165 166
    // The Route has a cache of its own and is not recompiled as long as it does
    // not get modified.
    $compiledRoute = $route->compile();
    $hostTokens = $compiledRoute->getHostTokens();

    $route_requirements = $route->getRequirements();
    // We need to bypass the doGenerate() method's handling of absolute URLs as
    // we handle that ourselves after processing the path.
    if (isset($route_requirements['_scheme'])) {
      unset($route_requirements['_scheme']);
    }
167
    $path = $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $route_requirements, $compiledRoute->getTokens(), $parameters, $route->getPath(), FALSE, $hostTokens);
168 169 170 171 172 173 174 175

    // The URL returned from doGenerate() will include the base path if there is
    // one (i.e., if running in a subdirectory) so we need to strip that off
    // before processing the path.
    $base_url = $this->context->getBaseUrl();
    if (!empty($base_url) && strpos($path, $base_url) === 0) {
      $path = substr($path, strlen($base_url));
    }
176 177
    return $path;
  }
178

179 180 181 182
  /**
   * {@inheritdoc}
   */
  public function generate($name, $parameters = array(), $absolute = FALSE) {
183 184 185
    $options['absolute'] = $absolute;
    return $this->generateFromRoute($name, $parameters, $options);
  }
webchick's avatar
webchick committed
186

187 188 189 190
  /**
   * {@inheritdoc}
   */
  public function generateFromRoute($name, $parameters = array(), $options = array()) {
191
    $options += array('prefix' => '');
192 193
    $absolute = !empty($options['absolute']);
    $route = $this->getRoute($name);
194 195
    $this->processRoute($route, $parameters);

196 197 198 199
    // Symfony adds any parameters that are not path slugs as query strings.
    if (isset($options['query']) && is_array($options['query'])) {
      $parameters = (array) $parameters + $options['query'];
    }
200

201 202
    $path = $this->getInternalPathFromRoute($route, $parameters);
    $path = $this->processPath($path, $options);
203 204 205 206 207 208
    if (!empty($options['prefix'])) {
      $path = ltrim($path, '/');
      $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
      $path = '/' . str_replace('%2F', '/', rawurlencode($prefix)) . $path;
    }

209 210 211 212 213 214
    $fragment = '';
    if (isset($options['fragment'])) {
      if (($fragment = trim($options['fragment'])) != '') {
        $fragment = '#' . $fragment;
      }
    }
215

216
    $base_url = $this->context->getBaseUrl();
217
    if (!$absolute || !$host = $this->context->getHost()) {
218
      return $base_url . $path . $fragment;
219 220 221 222
    }

    // Prepare an absolute URL by getting the correct scheme, host and port from
    // the request context.
223 224 225 226 227 228
    if (isset($options['https']) && $this->mixedModeSessions) {
      $scheme = $options['https'] ? 'https' : 'http';
    }
    else {
      $scheme = $this->context->getScheme();
    }
229
    $scheme_req = $route->getRequirement('_scheme');
230 231 232 233 234 235 236 237 238
    if (isset($scheme_req) && ($req = strtolower($scheme_req)) && $scheme !== $req) {
      $scheme = $req;
    }
    $port = '';
    if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
      $port = ':' . $this->context->getHttpPort();
    } elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) {
      $port = ':' . $this->context->getHttpsPort();
    }
239
    return $scheme . '://' . $host . $port . $base_url . $path . $fragment;
240 241 242
  }

  /**
243
   * {@inheritdoc}
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
   */
  public function generateFromPath($path = NULL, $options = array()) {

    if (!$this->initialized()) {
      throw new GeneratorNotInitializedException();
    }

    // Merge in defaults.
    $options += array(
      'fragment' => '',
      'query' => array(),
      'absolute' => FALSE,
      'prefix' => '',
    );

    if (!isset($options['external'])) {
      // Return an external link if $path contains an allowed absolute URL. Only
261 262 263
      // call the slow
      // \Drupal\Component\Utility\UrlHelper::stripDangerousProtocols() if $path
      // contains a ':' before any / ? or #. Note: we could use
264 265 266
      // \Drupal\Component\Utility\UrlHelper::isExternal($path) here, but that
      // would require another function call, and performance inside url() is
      // critical.
267
      $colonpos = strpos($path, ':');
268
      $options['external'] = ($colonpos !== FALSE && !preg_match('![/?#]!', substr($path, 0, $colonpos)) && UrlHelper::stripDangerousProtocols($path) == $path);
269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
    }

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

    if ($options['external']) {
      // Split off the fragment.
      if (strpos($path, '#') !== FALSE) {
        list($path, $old_fragment) = explode('#', $path, 2);
        // If $options contains no fragment, take it over from the path.
        if (isset($old_fragment) && !$options['fragment']) {
          $options['fragment'] = '#' . $old_fragment;
        }
      }
      // Append the query.
      if ($options['query']) {
286
        $path .= (strpos($path, '?') !== FALSE ? '&' : '?') . UrlHelper::buildQuery($options['query']);
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328
      }
      if (isset($options['https']) && $this->mixedModeSessions) {
        if ($options['https'] === TRUE) {
          $path = str_replace('http://', 'https://', $path);
        }
        elseif ($options['https'] === FALSE) {
          $path = str_replace('https://', 'http://', $path);
        }
      }
      // Reassemble.
      return $path . $options['fragment'];
    }
    else {
      $path = ltrim($this->processPath($path, $options), '/');
    }

    if (!isset($options['script'])) {
      $options['script'] = $this->scriptPath;
    }
    // The base_url might be rewritten from the language rewrite in domain mode.
    if (!isset($options['base_url'])) {
      if (isset($options['https']) && $this->mixedModeSessions) {
        if ($options['https'] === TRUE) {
          $options['base_url'] = str_replace('http://', 'https://', $this->baseUrl);
          $options['absolute'] = TRUE;
        }
        elseif ($options['https'] === FALSE) {
          $options['base_url'] = str_replace('https://', 'http://', $this->baseUrl);
          $options['absolute'] = TRUE;
        }
      }
      else {
        $options['base_url'] = $this->baseUrl;
      }
    }
    elseif (rtrim($options['base_url'], '/') == $options['base_url']) {
      $options['base_url'] .= '/';
    }
    $base = $options['absolute'] ? $options['base_url'] : $this->basePath;
    $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];

    $path = str_replace('%2F', '/', rawurlencode($prefix . $path));
329
    $query = $options['query'] ? ('?' . UrlHelper::buildQuery($options['query'])) : '';
330 331 332 333
    return $base . $options['script'] . $path . $query . $options['fragment'];
  }

  /**
334
   * {@inheritdoc}
335 336 337 338 339 340
   */
  public function setBaseUrl($url) {
    $this->baseUrl = $url;
  }

  /**
341
   * {@inheritdoc}
342 343 344 345 346 347
   */
  public function setBasePath($path) {
    $this->basePath = $path;
  }

  /**
348
   * {@inheritdoc}
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
   */
  public function setScriptPath($path) {
    $this->scriptPath = $path;
  }

  /**
   * Passes the path to a processor manager to allow alterations.
   */
  protected function processPath($path, &$options = array()) {
    // Router-based paths may have a querystring on them.
    if ($query_pos = strpos($path, '?')) {
      // We don't need to do a strict check here because position 0 would mean we
      // have no actual path to work with.
      $actual_path = substr($path, 0, $query_pos);
      $query_string = substr($path, $query_pos);
    }
    else {
      $actual_path = $path;
      $query_string = '';
    }
369
    $path = '/' . $this->pathProcessor->processOutbound(trim($actual_path, '/'), $options, $this->requestStack->getCurrentRequest());
370
    $path .= $query_string;
371 372 373
    return $path;
  }

374
  /**
375
   * Passes the route to the processor manager for altering before compilation.
376 377 378 379 380 381 382 383 384 385 386
   *
   * @param \Symfony\Component\Routing\Route $route
   *   The route object to process.
   *
   * @param array $parameters
   *   An array of parameters to be passed to the route compiler.
   */
  protected function processRoute(SymfonyRoute $route, array &$parameters) {
    $this->routeProcessor->processOutbound($route, $parameters);
  }

387 388 389 390 391 392 393 394 395 396 397
  /**
   * Returns whether or not the url generator has been initialized.
   *
   * @return bool
   *   Returns TRUE if the basePath, baseUrl and scriptPath properties have been
   *   set, FALSE otherwise.
   */
  protected function initialized() {
    return isset($this->basePath) && isset($this->baseUrl) && isset($this->scriptPath);
  }

398
  /**
399
   * Find the route using the provided route name.
400 401 402 403 404 405 406 407 408 409 410 411
   *
   * @param string $name
   *   The route name to fetch
   *
   * @return \Symfony\Component\Routing\Route
   *   The found route.
   *
   * @throws \Symfony\Component\Routing\Exception\RouteNotFoundException
   *   Thrown if there is no route with that name in this repository.
   *
   * @see \Drupal\Core\Routing\RouteProviderInterface
   */
412
  protected function getRoute($name) {
413 414 415
    if ($name instanceof SymfonyRoute) {
      $route = $name;
    }
416
    elseif (NULL === $route = $this->provider->getRouteByName($name)) {
417 418 419 420 421
      throw new RouteNotFoundException(sprintf('Route "%s" does not exist.', $name));
    }
    return $route;
  }

422
}