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