UrlGenerator.php 17 KB

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