Drupal investigation

UrlGenerator.php 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Routing\Generator;
  11. use Symfony\Component\Routing\RouteCollection;
  12. use Symfony\Component\Routing\RequestContext;
  13. use Symfony\Component\Routing\Exception\InvalidParameterException;
  14. use Symfony\Component\Routing\Exception\RouteNotFoundException;
  15. use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
  16. use Psr\Log\LoggerInterface;
  17. /**
  18. * UrlGenerator can generate a URL or a path for any route in the RouteCollection
  19. * based on the passed parameters.
  20. *
  21. * @author Fabien Potencier <fabien@symfony.com>
  22. * @author Tobias Schultze <http://tobion.de>
  23. */
  24. class UrlGenerator implements UrlGeneratorInterface, ConfigurableRequirementsInterface
  25. {
  26. /**
  27. * @var RouteCollection
  28. */
  29. protected $routes;
  30. /**
  31. * @var RequestContext
  32. */
  33. protected $context;
  34. /**
  35. * @var bool|null
  36. */
  37. protected $strictRequirements = true;
  38. /**
  39. * @var LoggerInterface|null
  40. */
  41. protected $logger;
  42. /**
  43. * This array defines the characters (besides alphanumeric ones) that will not be percent-encoded in the path segment of the generated URL.
  44. *
  45. * PHP's rawurlencode() encodes all chars except "a-zA-Z0-9-._~" according to RFC 3986. But we want to allow some chars
  46. * to be used in their literal form (reasons below). Other chars inside the path must of course be encoded, e.g.
  47. * "?" and "#" (would be interpreted wrongly as query and fragment identifier),
  48. * "'" and """ (are used as delimiters in HTML).
  49. */
  50. protected $decodedChars = array(
  51. // the slash can be used to designate a hierarchical structure and we want allow using it with this meaning
  52. // some webservers don't allow the slash in encoded form in the path for security reasons anyway
  53. // see http://stackoverflow.com/questions/4069002/http-400-if-2f-part-of-get-url-in-jboss
  54. '%2F' => '/',
  55. // the following chars are general delimiters in the URI specification but have only special meaning in the authority component
  56. // so they can safely be used in the path in unencoded form
  57. '%40' => '@',
  58. '%3A' => ':',
  59. // these chars are only sub-delimiters that have no predefined meaning and can therefore be used literally
  60. // so URI producing applications can use these chars to delimit subcomponents in a path segment without being encoded for better readability
  61. '%3B' => ';',
  62. '%2C' => ',',
  63. '%3D' => '=',
  64. '%2B' => '+',
  65. '%21' => '!',
  66. '%2A' => '*',
  67. '%7C' => '|',
  68. );
  69. /**
  70. * Constructor.
  71. *
  72. * @param RouteCollection $routes A RouteCollection instance
  73. * @param RequestContext $context The context
  74. * @param LoggerInterface|null $logger A logger instance
  75. */
  76. public function __construct(RouteCollection $routes, RequestContext $context, LoggerInterface $logger = null)
  77. {
  78. $this->routes = $routes;
  79. $this->context = $context;
  80. $this->logger = $logger;
  81. }
  82. /**
  83. * {@inheritdoc}
  84. */
  85. public function setContext(RequestContext $context)
  86. {
  87. $this->context = $context;
  88. }
  89. /**
  90. * {@inheritdoc}
  91. */
  92. public function getContext()
  93. {
  94. return $this->context;
  95. }
  96. /**
  97. * {@inheritdoc}
  98. */
  99. public function setStrictRequirements($enabled)
  100. {
  101. $this->strictRequirements = null === $enabled ? null : (bool) $enabled;
  102. }
  103. /**
  104. * {@inheritdoc}
  105. */
  106. public function isStrictRequirements()
  107. {
  108. return $this->strictRequirements;
  109. }
  110. /**
  111. * {@inheritdoc}
  112. */
  113. public function generate($name, $parameters = array(), $referenceType = self::ABSOLUTE_PATH)
  114. {
  115. if (null === $route = $this->routes->get($name)) {
  116. throw new RouteNotFoundException(sprintf('Unable to generate a URL for the named route "%s" as such route does not exist.', $name));
  117. }
  118. // the Route has a cache of its own and is not recompiled as long as it does not get modified
  119. $compiledRoute = $route->compile();
  120. return $this->doGenerate($compiledRoute->getVariables(), $route->getDefaults(), $route->getRequirements(), $compiledRoute->getTokens(), $parameters, $name, $referenceType, $compiledRoute->getHostTokens(), $route->getSchemes());
  121. }
  122. /**
  123. * @throws MissingMandatoryParametersException When some parameters are missing that are mandatory for the route
  124. * @throws InvalidParameterException When a parameter value for a placeholder is not correct because
  125. * it does not match the requirement
  126. */
  127. protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens, array $requiredSchemes = array())
  128. {
  129. if (is_bool($referenceType) || is_string($referenceType)) {
  130. @trigger_error('The hardcoded value you are using for the $referenceType argument of the '.__CLASS__.'::generate method is deprecated since version 2.8 and will not be supported anymore in 3.0. Use the constants defined in the UrlGeneratorInterface instead.', E_USER_DEPRECATED);
  131. if (true === $referenceType) {
  132. $referenceType = self::ABSOLUTE_URL;
  133. } elseif (false === $referenceType) {
  134. $referenceType = self::ABSOLUTE_PATH;
  135. } elseif ('relative' === $referenceType) {
  136. $referenceType = self::RELATIVE_PATH;
  137. } elseif ('network' === $referenceType) {
  138. $referenceType = self::NETWORK_PATH;
  139. }
  140. }
  141. $variables = array_flip($variables);
  142. $mergedParams = array_replace($defaults, $this->context->getParameters(), $parameters);
  143. // all params must be given
  144. if ($diff = array_diff_key($variables, $mergedParams)) {
  145. throw new MissingMandatoryParametersException(sprintf('Some mandatory parameters are missing ("%s") to generate a URL for route "%s".', implode('", "', array_keys($diff)), $name));
  146. }
  147. $url = '';
  148. $optional = true;
  149. foreach ($tokens as $token) {
  150. if ('variable' === $token[0]) {
  151. if (!$optional || !array_key_exists($token[3], $defaults) || null !== $mergedParams[$token[3]] && (string) $mergedParams[$token[3]] !== (string) $defaults[$token[3]]) {
  152. // check requirement
  153. if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#', $mergedParams[$token[3]])) {
  154. $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]]);
  155. if ($this->strictRequirements) {
  156. throw new InvalidParameterException($message);
  157. }
  158. if ($this->logger) {
  159. $this->logger->error($message);
  160. }
  161. return;
  162. }
  163. $url = $token[1].$mergedParams[$token[3]].$url;
  164. $optional = false;
  165. }
  166. } else {
  167. // static text
  168. $url = $token[1].$url;
  169. $optional = false;
  170. }
  171. }
  172. if ('' === $url) {
  173. $url = '/';
  174. }
  175. // the contexts base URL is already encoded (see Symfony\Component\HttpFoundation\Request)
  176. $url = strtr(rawurlencode($url), $this->decodedChars);
  177. // the path segments "." and ".." are interpreted as relative reference when resolving a URI; see http://tools.ietf.org/html/rfc3986#section-3.3
  178. // so we need to encode them as they are not used for this purpose here
  179. // otherwise we would generate a URI that, when followed by a user agent (e.g. browser), does not match this route
  180. $url = strtr($url, array('/../' => '/%2E%2E/', '/./' => '/%2E/'));
  181. if ('/..' === substr($url, -3)) {
  182. $url = substr($url, 0, -2).'%2E%2E';
  183. } elseif ('/.' === substr($url, -2)) {
  184. $url = substr($url, 0, -1).'%2E';
  185. }
  186. $schemeAuthority = '';
  187. if ($host = $this->context->getHost()) {
  188. $scheme = $this->context->getScheme();
  189. if ($requiredSchemes) {
  190. if (!in_array($scheme, $requiredSchemes, true)) {
  191. $referenceType = self::ABSOLUTE_URL;
  192. $scheme = current($requiredSchemes);
  193. }
  194. } elseif (isset($requirements['_scheme']) && ($req = strtolower($requirements['_scheme'])) && $scheme !== $req) {
  195. // We do this for BC; to be removed if _scheme is not supported anymore
  196. $referenceType = self::ABSOLUTE_URL;
  197. $scheme = $req;
  198. }
  199. if ($hostTokens) {
  200. $routeHost = '';
  201. foreach ($hostTokens as $token) {
  202. if ('variable' === $token[0]) {
  203. if (null !== $this->strictRequirements && !preg_match('#^'.$token[2].'$#i', $mergedParams[$token[3]])) {
  204. $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]]);
  205. if ($this->strictRequirements) {
  206. throw new InvalidParameterException($message);
  207. }
  208. if ($this->logger) {
  209. $this->logger->error($message);
  210. }
  211. return;
  212. }
  213. $routeHost = $token[1].$mergedParams[$token[3]].$routeHost;
  214. } else {
  215. $routeHost = $token[1].$routeHost;
  216. }
  217. }
  218. if ($routeHost !== $host) {
  219. $host = $routeHost;
  220. if (self::ABSOLUTE_URL !== $referenceType) {
  221. $referenceType = self::NETWORK_PATH;
  222. }
  223. }
  224. }
  225. if (self::ABSOLUTE_URL === $referenceType || self::NETWORK_PATH === $referenceType) {
  226. $port = '';
  227. if ('http' === $scheme && 80 != $this->context->getHttpPort()) {
  228. $port = ':'.$this->context->getHttpPort();
  229. } elseif ('https' === $scheme && 443 != $this->context->getHttpsPort()) {
  230. $port = ':'.$this->context->getHttpsPort();
  231. }
  232. $schemeAuthority = self::NETWORK_PATH === $referenceType ? '//' : "$scheme://";
  233. $schemeAuthority .= $host.$port;
  234. }
  235. }
  236. if (self::RELATIVE_PATH === $referenceType) {
  237. $url = self::getRelativePath($this->context->getPathInfo(), $url);
  238. } else {
  239. $url = $schemeAuthority.$this->context->getBaseUrl().$url;
  240. }
  241. // add a query string if needed
  242. $extra = array_udiff_assoc(array_diff_key($parameters, $variables), $defaults, function ($a, $b) {
  243. return $a == $b ? 0 : 1;
  244. });
  245. if ($extra && $query = http_build_query($extra, '', '&')) {
  246. // "/" and "?" can be left decoded for better user experience, see
  247. // http://tools.ietf.org/html/rfc3986#section-3.4
  248. $url .= '?'.strtr($query, array('%2F' => '/'));
  249. }
  250. return $url;
  251. }
  252. /**
  253. * Returns the target path as relative reference from the base path.
  254. *
  255. * Only the URIs path component (no schema, host etc.) is relevant and must be given, starting with a slash.
  256. * Both paths must be absolute and not contain relative parts.
  257. * Relative URLs from one resource to another are useful when generating self-contained downloadable document archives.
  258. * Furthermore, they can be used to reduce the link size in documents.
  259. *
  260. * Example target paths, given a base path of "/a/b/c/d":
  261. * - "/a/b/c/d" -> ""
  262. * - "/a/b/c/" -> "./"
  263. * - "/a/b/" -> "../"
  264. * - "/a/b/c/other" -> "other"
  265. * - "/a/x/y" -> "../../x/y"
  266. *
  267. * @param string $basePath The base path
  268. * @param string $targetPath The target path
  269. *
  270. * @return string The relative target path
  271. */
  272. public static function getRelativePath($basePath, $targetPath)
  273. {
  274. if ($basePath === $targetPath) {
  275. return '';
  276. }
  277. $sourceDirs = explode('/', isset($basePath[0]) && '/' === $basePath[0] ? substr($basePath, 1) : $basePath);
  278. $targetDirs = explode('/', isset($targetPath[0]) && '/' === $targetPath[0] ? substr($targetPath, 1) : $targetPath);
  279. array_pop($sourceDirs);
  280. $targetFile = array_pop($targetDirs);
  281. foreach ($sourceDirs as $i => $dir) {
  282. if (isset($targetDirs[$i]) && $dir === $targetDirs[$i]) {
  283. unset($sourceDirs[$i], $targetDirs[$i]);
  284. } else {
  285. break;
  286. }
  287. }
  288. $targetDirs[] = $targetFile;
  289. $path = str_repeat('../', count($sourceDirs)).implode('/', $targetDirs);
  290. // A reference to the same base directory or an empty subdirectory must be prefixed with "./".
  291. // This also applies to a segment with a colon character (e.g., "file:colon") that cannot be used
  292. // as the first segment of a relative-path reference, as it would be mistaken for a scheme name
  293. // (see http://tools.ietf.org/html/rfc3986#section-4.2).
  294. return '' === $path || '/' === $path[0]
  295. || false !== ($colonPos = strpos($path, ':')) && ($colonPos < ($slashPos = strpos($path, '/')) || false === $slashPos)
  296. ? "./$path" : $path;
  297. }
  298. }