Version 1
[yaffs-website] / web / core / lib / Drupal / Core / Routing / UrlGenerator.php
1 <?php
2
3 namespace Drupal\Core\Routing;
4
5 use Drupal\Core\GeneratedUrl;
6 use Drupal\Core\Render\BubbleableMetadata;
7 use Symfony\Component\HttpFoundation\RequestStack;
8 use Symfony\Component\Routing\RequestContext as SymfonyRequestContext;
9 use Symfony\Component\Routing\Route as SymfonyRoute;
10 use Symfony\Component\Routing\Exception\RouteNotFoundException;
11 use Drupal\Component\Utility\UrlHelper;
12 use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
13 use Drupal\Core\RouteProcessor\OutboundRouteProcessorInterface;
14 use Symfony\Component\Routing\Exception\InvalidParameterException;
15 use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
16
17 /**
18  * Generates URLs from route names and parameters.
19  */
20 class UrlGenerator implements UrlGeneratorInterface {
21
22   /**
23    * The route provider.
24    *
25    * @var \Drupal\Core\Routing\RouteProviderInterface
26    */
27   protected $provider;
28
29   /**
30    * @var RequestContext
31    */
32   protected $context;
33
34   /**
35    * A request stack object.
36    *
37    * @var \Symfony\Component\HttpFoundation\RequestStack
38    */
39   protected $requestStack;
40
41   /**
42    * The path processor to convert the system path to one suitable for urls.
43    *
44    * @var \Drupal\Core\PathProcessor\OutboundPathProcessorInterface
45    */
46   protected $pathProcessor;
47
48   /**
49    * The route processor.
50    *
51    * @var \Drupal\Core\RouteProcessor\OutboundRouteProcessorInterface
52    */
53   protected $routeProcessor;
54
55   /**
56    * Overrides characters that will not be percent-encoded in the path segment.
57    *
58    * The first two elements are the first two parameters of str_replace(), so
59    * if you override this variable you can also use arrays for the encoded
60    * and decoded characters.
61    *
62    * @see \Symfony\Component\Routing\Generator\UrlGenerator
63    */
64   protected $decodedChars = [
65     // the slash can be used to designate a hierarchical structure and we want allow using it with this meaning
66     // some webservers don't allow the slash in encoded form in the path for security reasons anyway
67     // see http://stackoverflow.com/questions/4069002/http-400-if-2f-part-of-get-url-in-jboss
68     '%2F', // Map from these encoded characters.
69     '/', // Map to these decoded characters.
70   ];
71
72   /**
73    * Constructs a new generator object.
74    *
75    * @param \Drupal\Core\Routing\RouteProviderInterface $provider
76    *   The route provider to be searched for routes.
77    * @param \Drupal\Core\PathProcessor\OutboundPathProcessorInterface $path_processor
78    *   The path processor to convert the system path to one suitable for urls.
79    * @param \Drupal\Core\RouteProcessor\OutboundRouteProcessorInterface $route_processor
80    *   The route processor.
81    * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack
82    *   A request stack object.
83    * @param string[] $filter_protocols
84    *   (optional) An array of protocols allowed for URL generation.
85    */
86   public function __construct(RouteProviderInterface $provider, OutboundPathProcessorInterface $path_processor, OutboundRouteProcessorInterface $route_processor, RequestStack $request_stack, array $filter_protocols = ['http', 'https']) {
87     $this->provider = $provider;
88     $this->context = new RequestContext();
89
90     $this->pathProcessor = $path_processor;
91     $this->routeProcessor = $route_processor;
92     UrlHelper::setAllowedProtocols($filter_protocols);
93     $this->requestStack = $request_stack;
94   }
95
96   /**
97    * {@inheritdoc}
98    */
99   public function setContext(SymfonyRequestContext $context) {
100     $this->context = $context;
101   }
102
103   /**
104    * {@inheritdoc}
105    */
106   public function getContext() {
107     return $this->context;
108   }
109
110   /**
111    * {@inheritdoc}
112    */
113   public function setStrictRequirements($enabled) {
114     // Ignore changes to this.
115   }
116
117   /**
118    * {@inheritdoc}
119    */
120   public function isStrictRequirements() {
121     return TRUE;
122   }
123
124   /**
125    * {@inheritdoc}
126    */
127   public function getPathFromRoute($name, $parameters = []) {
128     $route = $this->getRoute($name);
129     $name = $this->getRouteDebugMessage($name);
130     $this->processRoute($name, $route, $parameters);
131     $path = $this->getInternalPathFromRoute($name, $route, $parameters);
132     // Router-based paths may have a querystring on them but Drupal paths may
133     // not have one, so remove any ? and anything after it. For generate() this
134     // is handled in processPath().
135     $path = preg_replace('/\?.*/', '', $path);
136     return trim($path, '/');
137   }
138
139   /**
140    * Substitute the route parameters into the route path.
141    *
142    * Note: This code was copied from
143    * \Symfony\Component\Routing\Generator\UrlGenerator::doGenerate() and
144    * shortened by removing code that is not relevant to Drupal or that is
145    * handled separately in ::generateFromRoute(). The Symfony version should be
146    * examined for changes in new Symfony releases.
147    *
148    * @param array $variables
149    *   The variables form the compiled route, corresponding to slugs in the
150    *   route path.
151    * @param array $defaults
152    *   The defaults from the route.
153    * @param array $tokens
154    *   The tokens from the compiled route.
155    * @param array $parameters
156    *   The route parameters passed to the generator. Parameters that do not
157    *   match any variables will be added to the result as query parameters.
158    * @param array $query_params
159    *   Query parameters passed to the generator as $options['query']. This may
160    *   be modified if there are extra parameters not used as route variables.
161    * @param string $name
162    *   The route name or other identifying string from ::getRouteDebugMessage().
163    *
164    * @return string
165    *   The url path, without any base path, without the query string, not URL
166    *   encoded.
167    *
168    * @throws MissingMandatoryParametersException
169    *   When some parameters are missing that are mandatory for the route.
170    * @throws InvalidParameterException
171    *   When a parameter value for a placeholder is not correct because it does
172    *   not match the requirement.
173    */
174   protected function doGenerate(array $variables, array $defaults, array $tokens, array $parameters, array &$query_params, $name) {
175     $variables = array_flip($variables);
176     $mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters);
177
178     // all params must be given
179     if ($diff = array_diff_key($variables, $mergedParams)) {
180       throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name));
181     }
182
183     $url = '';
184     // Tokens start from the end of the path and work to the beginning. The
185     // first one or several variable tokens may be optional, but once we find a
186     // supplied token or a static text portion of the path, all remaining
187     // variables up to the start of the path must be supplied to there is no gap.
188     $optional = TRUE;
189     // Structure of $tokens from the compiled route:
190     // If the path is /admin/config/user-interface/shortcut/manage/{shortcut_set}/add-link-inline
191     // [ [ 0 => 'text', 1 => '/add-link-inline' ], [ 0 => 'variable', 1 => '/', 2 => '[^/]++', 3 => 'shortcut_set' ], [ 0 => 'text', 1 => '/admin/config/user-interface/shortcut/manage' ] ]
192     //
193     // For a simple fixed path, there is just one token.
194     // If the path is /admin/config
195     // [ [ 0 => 'text', 1 => '/admin/config' ] ]
196     foreach ($tokens as $token) {
197       if ('variable' === $token[0]) {
198         if (!$optional || !array_key_exists($token[3], $defaults) || (isset($mergedParams[$token[3]]) && (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]])) {
199           // check requirement
200           if (!preg_match('#^' . $token[2] . '$#', $mergedParams[$token[3]])) {
201             $message = sprintf('Parameter "%s" for route "%s" must match "%s" ("%s" given) to generate a corresponding URL.', $token[3], $name, $token[2], $mergedParams[$token[3]]);
202             throw new InvalidParameterException($message);
203           }
204
205           $url = $token[1] . $mergedParams[$token[3]] . $url;
206           $optional = FALSE;
207         }
208       }
209       else {
210         // Static text
211         $url = $token[1] . $url;
212         $optional = FALSE;
213       }
214     }
215
216     if ('' === $url) {
217       $url = '/';
218     }
219
220     // Add extra parameters to the query parameters.
221     $query_params += array_diff_key($parameters, $variables, $defaults);
222
223     return $url;
224   }
225
226   /**
227    * Gets the path of a route.
228    *
229    * @param $name
230    *   The route name or other debug message.
231    * @param \Symfony\Component\Routing\Route $route
232    *   The route object.
233    * @param array $parameters
234    *   An array of parameters as passed to
235    *   \Symfony\Component\Routing\Generator\UrlGeneratorInterface::generate().
236    * @param array $query_params
237    *   An array of query string parameter, which will get any extra values from
238    *   $parameters merged in.
239    *
240    * @return string
241    *   The URL path corresponding to the route, without the base path, not URL
242    *   encoded.
243    */
244   protected function getInternalPathFromRoute($name, SymfonyRoute $route, $parameters = [], &$query_params = []) {
245     // The Route has a cache of its own and is not recompiled as long as it does
246     // not get modified.
247     $compiledRoute = $route->compile();
248
249     return $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $compiledRoute->getTokens(), $parameters, $query_params, $name);
250   }
251
252   /**
253    * {@inheritdoc}
254    */
255   public function generate($name, $parameters = [], $referenceType = self::ABSOLUTE_PATH) {
256     $options['absolute'] = is_bool($referenceType) ? $referenceType : $referenceType === self::ABSOLUTE_URL;
257     return $this->generateFromRoute($name, $parameters, $options);
258   }
259
260   /**
261    * {@inheritdoc}
262    */
263   public function generateFromRoute($name, $parameters = [], $options = [], $collect_bubbleable_metadata = FALSE) {
264     $options += ['prefix' => ''];
265     if (!isset($options['query']) || !is_array($options['query'])) {
266       $options['query'] = [];
267     }
268
269     $route = $this->getRoute($name);
270     $generated_url = $collect_bubbleable_metadata ? new GeneratedUrl() : NULL;
271
272     $fragment = '';
273     if (isset($options['fragment'])) {
274       if (($fragment = trim($options['fragment'])) != '') {
275         $fragment = '#' . $fragment;
276       }
277     }
278
279     // Generate a relative URL having no path, just query string and fragment.
280     if ($route->getOption('_no_path')) {
281       $query = $options['query'] ? '?' . UrlHelper::buildQuery($options['query']) : '';
282       $url = $query . $fragment;
283       return $collect_bubbleable_metadata ? $generated_url->setGeneratedUrl($url) : $url;
284     }
285
286     $options += $route->getOption('default_url_options') ?: [];
287     $options += ['prefix' => '', 'path_processing' => TRUE];
288
289     $name = $this->getRouteDebugMessage($name);
290     $this->processRoute($name, $route, $parameters, $generated_url);
291     $path = $this->getInternalPathFromRoute($name, $route, $parameters, $options['query']);
292     // Outbound path processors might need the route object for the path, e.g.
293     // to get the path pattern.
294     $options['route'] = $route;
295     if ($options['path_processing']) {
296       $path = $this->processPath($path, $options, $generated_url);
297     }
298     // The contexts base URL is already encoded
299     // (see Symfony\Component\HttpFoundation\Request).
300     $path = str_replace($this->decodedChars[0], $this->decodedChars[1], rawurlencode($path));
301
302     // Drupal paths rarely include dots, so skip this processing if possible.
303     if (strpos($path, '/.') !== FALSE) {
304       // the path segments "." and ".." are interpreted as relative reference when
305       // resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3
306       // so we need to encode them as they are not used for this purpose here
307       // otherwise we would generate a URI that, when followed by a user agent
308       // (e.g. browser), does not match this route
309       $path = strtr($path, ['/../' => '/%2E%2E/', '/./' => '/%2E/']);
310       if ('/..' === substr($path, -3)) {
311         $path = substr($path, 0, -2) . '%2E%2E';
312       }
313       elseif ('/.' === substr($path, -2)) {
314         $path = substr($path, 0, -1) . '%2E';
315       }
316     }
317
318     if (!empty($options['prefix'])) {
319       $path = ltrim($path, '/');
320       $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
321       $path = '/' . str_replace('%2F', '/', rawurlencode($prefix)) . $path;
322     }
323
324     $query = $options['query'] ? '?' . UrlHelper::buildQuery($options['query']) : '';
325
326     // The base_url might be rewritten from the language rewrite in domain mode.
327     if (isset($options['base_url'])) {
328       $base_url = $options['base_url'];
329
330       if (isset($options['https'])) {
331         if ($options['https'] === TRUE) {
332           $base_url = str_replace('http://', 'https://', $base_url);
333         }
334         elseif ($options['https'] === FALSE) {
335           $base_url = str_replace('https://', 'http://', $base_url);
336         }
337       }
338
339       $url = $base_url . $path . $query . $fragment;
340       return $collect_bubbleable_metadata ? $generated_url->setGeneratedUrl($url) : $url;
341     }
342
343     $base_url = $this->context->getBaseUrl();
344
345     $absolute = !empty($options['absolute']);
346     if (!$absolute || !$host = $this->context->getHost()) {
347       $url = $base_url . $path . $query . $fragment;
348       return $collect_bubbleable_metadata ? $generated_url->setGeneratedUrl($url) : $url;
349     }
350
351     // Prepare an absolute URL by getting the correct scheme, host and port from
352     // the request context.
353     if (isset($options['https'])) {
354       $scheme = $options['https'] ? 'https' : 'http';
355     }
356     else {
357       $scheme = $this->context->getScheme();
358     }
359     $scheme_req = $route->getSchemes();
360     if ($scheme_req && ($req = $scheme_req[0]) && $scheme !== $req) {
361       $scheme = $req;
362     }
363     $port = '';
364     if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
365       $port = ':' . $this->context->getHttpPort();
366     }
367     elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) {
368       $port = ':' . $this->context->getHttpsPort();
369     }
370     if ($collect_bubbleable_metadata) {
371       $generated_url->addCacheContexts(['url.site']);
372     }
373     $url = $scheme . '://' . $host . $port . $base_url . $path . $query . $fragment;
374     return $collect_bubbleable_metadata ? $generated_url->setGeneratedUrl($url) : $url;
375   }
376
377   /**
378    * Passes the path to a processor manager to allow alterations.
379    */
380   protected function processPath($path, &$options = [], BubbleableMetadata $bubbleable_metadata = NULL) {
381     $actual_path = $path === '/' ? $path : rtrim($path, '/');
382     return $this->pathProcessor->processOutbound($actual_path, $options, $this->requestStack->getCurrentRequest(), $bubbleable_metadata);
383   }
384
385   /**
386    * Passes the route to the processor manager for altering before compilation.
387    *
388    * @param string $name
389    *   The route name.
390    * @param \Symfony\Component\Routing\Route $route
391    *   The route object to process.
392    * @param array $parameters
393    *   An array of parameters to be passed to the route compiler.
394    * @param \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata
395    *   (optional) Object to collect route processors' bubbleable metadata.
396    */
397   protected function processRoute($name, SymfonyRoute $route, array &$parameters, BubbleableMetadata $bubbleable_metadata = NULL) {
398     $this->routeProcessor->processOutbound($name, $route, $parameters, $bubbleable_metadata);
399   }
400
401   /**
402    * Find the route using the provided route name.
403    *
404    * @param string|\Symfony\Component\Routing\Route $name
405    *   The route name or a route object.
406    *
407    * @return \Symfony\Component\Routing\Route
408    *   The found route.
409    *
410    * @throws \Symfony\Component\Routing\Exception\RouteNotFoundException
411    *   Thrown if there is no route with that name in this repository.
412    *
413    * @see \Drupal\Core\Routing\RouteProviderInterface
414    */
415   protected function getRoute($name) {
416     if ($name instanceof SymfonyRoute) {
417       $route = $name;
418     }
419     elseif (NULL === $route = clone $this->provider->getRouteByName($name)) {
420       throw new RouteNotFoundException(sprintf('Route "%s" does not exist.', $name));
421     }
422     return $route;
423   }
424
425   /**
426    * {@inheritdoc}
427    */
428   public function supports($name) {
429     // Support a route object and any string as route name.
430     return is_string($name) || $name instanceof SymfonyRoute;
431   }
432
433   /**
434    * {@inheritdoc}
435    */
436   public function getRouteDebugMessage($name, array $parameters = []) {
437     if (is_scalar($name)) {
438       return $name;
439     }
440
441     if ($name instanceof SymfonyRoute) {
442       return 'Route with pattern ' . $name->getPath();
443     }
444
445     return serialize($name);
446   }
447
448 }