92326ec42a3f3d29d9fbf8a0525906e29418731c
[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 form 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     // The contexts base URL is already encoded
301     // (see Symfony\Component\HttpFoundation\Request).
302     $path = str_replace($this->decodedChars[0], $this->decodedChars[1], rawurlencode($path));
303
304     // Drupal paths rarely include dots, so skip this processing if possible.
305     if (strpos($path, '/.') !== FALSE) {
306       // the path segments "." and ".." are interpreted as relative reference when
307       // resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3
308       // so we need to encode them as they are not used for this purpose here
309       // otherwise we would generate a URI that, when followed by a user agent
310       // (e.g. browser), does not match this route
311       $path = strtr($path, ['/../' => '/%2E%2E/', '/./' => '/%2E/']);
312       if ('/..' === substr($path, -3)) {
313         $path = substr($path, 0, -2) . '%2E%2E';
314       }
315       elseif ('/.' === substr($path, -2)) {
316         $path = substr($path, 0, -1) . '%2E';
317       }
318     }
319
320     if (!empty($options['prefix'])) {
321       $path = ltrim($path, '/');
322       $prefix = empty($path) ? rtrim($options['prefix'], '/') : $options['prefix'];
323       $path = '/' . str_replace('%2F', '/', rawurlencode($prefix)) . $path;
324     }
325
326     $query = $options['query'] ? '?' . UrlHelper::buildQuery($options['query']) : '';
327
328     // The base_url might be rewritten from the language rewrite in domain mode.
329     if (isset($options['base_url'])) {
330       $base_url = $options['base_url'];
331
332       if (isset($options['https'])) {
333         if ($options['https'] === TRUE) {
334           $base_url = str_replace('http://', 'https://', $base_url);
335         }
336         elseif ($options['https'] === FALSE) {
337           $base_url = str_replace('https://', 'http://', $base_url);
338         }
339       }
340
341       $url = $base_url . $path . $query . $fragment;
342       return $collect_bubbleable_metadata ? $generated_url->setGeneratedUrl($url) : $url;
343     }
344
345     $base_url = $this->context->getBaseUrl();
346
347     $absolute = !empty($options['absolute']);
348     if (!$absolute || !$host = $this->context->getHost()) {
349       $url = $base_url . $path . $query . $fragment;
350       return $collect_bubbleable_metadata ? $generated_url->setGeneratedUrl($url) : $url;
351     }
352
353     // Prepare an absolute URL by getting the correct scheme, host and port from
354     // the request context.
355     if (isset($options['https'])) {
356       $scheme = $options['https'] ? 'https' : 'http';
357     }
358     else {
359       $scheme = $this->context->getScheme();
360     }
361     $scheme_req = $route->getSchemes();
362     if ($scheme_req && ($req = $scheme_req[0]) && $scheme !== $req) {
363       $scheme = $req;
364     }
365     $port = '';
366     if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
367       $port = ':' . $this->context->getHttpPort();
368     }
369     elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) {
370       $port = ':' . $this->context->getHttpsPort();
371     }
372     if ($collect_bubbleable_metadata) {
373       $generated_url->addCacheContexts(['url.site']);
374     }
375     $url = $scheme . '://' . $host . $port . $base_url . $path . $query . $fragment;
376     return $collect_bubbleable_metadata ? $generated_url->setGeneratedUrl($url) : $url;
377   }
378
379   /**
380    * Passes the path to a processor manager to allow alterations.
381    */
382   protected function processPath($path, &$options = [], BubbleableMetadata $bubbleable_metadata = NULL) {
383     $actual_path = $path === '/' ? $path : rtrim($path, '/');
384     return $this->pathProcessor->processOutbound($actual_path, $options, $this->requestStack->getCurrentRequest(), $bubbleable_metadata);
385   }
386
387   /**
388    * Passes the route to the processor manager for altering before compilation.
389    *
390    * @param string $name
391    *   The route name.
392    * @param \Symfony\Component\Routing\Route $route
393    *   The route object to process.
394    * @param array $parameters
395    *   An array of parameters to be passed to the route compiler.
396    * @param \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata
397    *   (optional) Object to collect route processors' bubbleable metadata.
398    */
399   protected function processRoute($name, SymfonyRoute $route, array &$parameters, BubbleableMetadata $bubbleable_metadata = NULL) {
400     $this->routeProcessor->processOutbound($name, $route, $parameters, $bubbleable_metadata);
401   }
402
403   /**
404    * Find the route using the provided route name.
405    *
406    * @param string|\Symfony\Component\Routing\Route $name
407    *   The route name or a route object.
408    *
409    * @return \Symfony\Component\Routing\Route
410    *   The found route.
411    *
412    * @throws \Symfony\Component\Routing\Exception\RouteNotFoundException
413    *   Thrown if there is no route with that name in this repository.
414    *
415    * @see \Drupal\Core\Routing\RouteProviderInterface
416    */
417   protected function getRoute($name) {
418     if ($name instanceof SymfonyRoute) {
419       $route = $name;
420     }
421     elseif (NULL === $route = clone $this->provider->getRouteByName($name)) {
422       throw new RouteNotFoundException(sprintf('Route "%s" does not exist.', $name));
423     }
424     return $route;
425   }
426
427   /**
428    * {@inheritdoc}
429    */
430   public function supports($name) {
431     // Support a route object and any string as route name.
432     return is_string($name) || $name instanceof SymfonyRoute;
433   }
434
435   /**
436    * {@inheritdoc}
437    */
438   public function getRouteDebugMessage($name, array $parameters = []) {
439     if (is_scalar($name)) {
440       return $name;
441     }
442
443     if ($name instanceof SymfonyRoute) {
444       return 'Route with pattern ' . $name->getPath();
445     }
446
447     return serialize($name);
448   }
449
450 }