UrlManager.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\web;
  8. use Yii;
  9. use yii\base\Component;
  10. use yii\base\InvalidConfigException;
  11. use yii\caching\Cache;
  12. use yii\helpers\Url;
  13. /**
  14. * UrlManager handles HTTP request parsing and creation of URLs based on a set of rules.
  15. *
  16. * UrlManager is configured as an application component in [[\yii\base\Application]] by default.
  17. * You can access that instance via `Yii::$app->urlManager`.
  18. *
  19. * You can modify its configuration by adding an array to your application config under `components`
  20. * as it is shown in the following example:
  21. *
  22. * ```php
  23. * 'urlManager' => [
  24. * 'enablePrettyUrl' => true,
  25. * 'rules' => [
  26. * // your rules go here
  27. * ],
  28. * // ...
  29. * ]
  30. * ```
  31. *
  32. * Rules are classes implementing the [[UrlRuleInterface]], by default that is [[UrlRule]].
  33. * For nesting rules, there is also a [[GroupUrlRule]] class.
  34. *
  35. * For more details and usage information on UrlManager, see the [guide article on routing](guide:runtime-routing).
  36. *
  37. * @property string $baseUrl The base URL that is used by [[createUrl()]] to prepend to created URLs.
  38. * @property string $hostInfo The host info (e.g. `http://www.example.com`) that is used by
  39. * [[createAbsoluteUrl()]] to prepend to created URLs.
  40. * @property string $scriptUrl The entry script URL that is used by [[createUrl()]] to prepend to created
  41. * URLs.
  42. *
  43. * @author Qiang Xue <qiang.xue@gmail.com>
  44. * @since 2.0
  45. */
  46. class UrlManager extends Component
  47. {
  48. /**
  49. * @var bool whether to enable pretty URLs. Instead of putting all parameters in the query
  50. * string part of a URL, pretty URLs allow using path info to represent some of the parameters
  51. * and can thus produce more user-friendly URLs, such as "/news/Yii-is-released", instead of
  52. * "/index.php?r=news%2Fview&id=100".
  53. */
  54. public $enablePrettyUrl = false;
  55. /**
  56. * @var bool whether to enable strict parsing. If strict parsing is enabled, the incoming
  57. * requested URL must match at least one of the [[rules]] in order to be treated as a valid request.
  58. * Otherwise, the path info part of the request will be treated as the requested route.
  59. * This property is used only when [[enablePrettyUrl]] is `true`.
  60. */
  61. public $enableStrictParsing = false;
  62. /**
  63. * @var array the rules for creating and parsing URLs when [[enablePrettyUrl]] is `true`.
  64. * This property is used only if [[enablePrettyUrl]] is `true`. Each element in the array
  65. * is the configuration array for creating a single URL rule. The configuration will
  66. * be merged with [[ruleConfig]] first before it is used for creating the rule object.
  67. *
  68. * A special shortcut format can be used if a rule only specifies [[UrlRule::pattern|pattern]]
  69. * and [[UrlRule::route|route]]: `'pattern' => 'route'`. That is, instead of using a configuration
  70. * array, one can use the key to represent the pattern and the value the corresponding route.
  71. * For example, `'post/<id:\d+>' => 'post/view'`.
  72. *
  73. * For RESTful routing the mentioned shortcut format also allows you to specify the
  74. * [[UrlRule::verb|HTTP verb]] that the rule should apply for.
  75. * You can do that by prepending it to the pattern, separated by space.
  76. * For example, `'PUT post/<id:\d+>' => 'post/update'`.
  77. * You may specify multiple verbs by separating them with comma
  78. * like this: `'POST,PUT post/index' => 'post/create'`.
  79. * The supported verbs in the shortcut format are: GET, HEAD, POST, PUT, PATCH and DELETE.
  80. * Note that [[UrlRule::mode|mode]] will be set to PARSING_ONLY when specifying verb in this way
  81. * so you normally would not specify a verb for normal GET request.
  82. *
  83. * Here is an example configuration for RESTful CRUD controller:
  84. *
  85. * ```php
  86. * [
  87. * 'dashboard' => 'site/index',
  88. *
  89. * 'POST <controller:[\w-]+>s' => '<controller>/create',
  90. * '<controller:[\w-]+>s' => '<controller>/index',
  91. *
  92. * 'PUT <controller:[\w-]+>/<id:\d+>' => '<controller>/update',
  93. * 'DELETE <controller:[\w-]+>/<id:\d+>' => '<controller>/delete',
  94. * '<controller:[\w-]+>/<id:\d+>' => '<controller>/view',
  95. * ];
  96. * ```
  97. *
  98. * Note that if you modify this property after the UrlManager object is created, make sure
  99. * you populate the array with rule objects instead of rule configurations.
  100. */
  101. public $rules = [];
  102. /**
  103. * @var string the URL suffix used when [[enablePrettyUrl]] is `true`.
  104. * For example, ".html" can be used so that the URL looks like pointing to a static HTML page.
  105. * This property is used only if [[enablePrettyUrl]] is `true`.
  106. */
  107. public $suffix;
  108. /**
  109. * @var bool whether to show entry script name in the constructed URL. Defaults to `true`.
  110. * This property is used only if [[enablePrettyUrl]] is `true`.
  111. */
  112. public $showScriptName = true;
  113. /**
  114. * @var string the GET parameter name for route. This property is used only if [[enablePrettyUrl]] is `false`.
  115. */
  116. public $routeParam = 'r';
  117. /**
  118. * @var Cache|string the cache object or the application component ID of the cache object.
  119. * Compiled URL rules will be cached through this cache object, if it is available.
  120. *
  121. * After the UrlManager object is created, if you want to change this property,
  122. * you should only assign it with a cache object.
  123. * Set this property to `false` if you do not want to cache the URL rules.
  124. */
  125. public $cache = 'cache';
  126. /**
  127. * @var array the default configuration of URL rules. Individual rule configurations
  128. * specified via [[rules]] will take precedence when the same property of the rule is configured.
  129. */
  130. public $ruleConfig = ['class' => 'yii\web\UrlRule'];
  131. /**
  132. * @var UrlNormalizer|array|string|false the configuration for [[UrlNormalizer]] used by this UrlManager.
  133. * The default value is `false`, which means normalization will be skipped.
  134. * If you wish to enable URL normalization, you should configure this property manually.
  135. * For example:
  136. *
  137. * ```php
  138. * [
  139. * 'class' => 'yii\web\UrlNormalizer',
  140. * 'collapseSlashes' => true,
  141. * 'normalizeTrailingSlash' => true,
  142. * ]
  143. * ```
  144. *
  145. * @since 2.0.10
  146. */
  147. public $normalizer = false;
  148. /**
  149. * @var string the cache key for cached rules
  150. * @since 2.0.8
  151. */
  152. protected $cacheKey = __CLASS__;
  153. private $_baseUrl;
  154. private $_scriptUrl;
  155. private $_hostInfo;
  156. private $_ruleCache;
  157. /**
  158. * Initializes UrlManager.
  159. */
  160. public function init()
  161. {
  162. parent::init();
  163. if ($this->normalizer !== false) {
  164. $this->normalizer = Yii::createObject($this->normalizer);
  165. if (!$this->normalizer instanceof UrlNormalizer) {
  166. throw new InvalidConfigException('`' . get_class($this) . '::normalizer` should be an instance of `' . UrlNormalizer::className() . '` or its DI compatible configuration.');
  167. }
  168. }
  169. if (!$this->enablePrettyUrl || empty($this->rules)) {
  170. return;
  171. }
  172. if (is_string($this->cache)) {
  173. $this->cache = Yii::$app->get($this->cache, false);
  174. }
  175. if ($this->cache instanceof Cache) {
  176. $cacheKey = $this->cacheKey;
  177. $hash = md5(json_encode($this->rules));
  178. if (($data = $this->cache->get($cacheKey)) !== false && isset($data[1]) && $data[1] === $hash) {
  179. $this->rules = $data[0];
  180. } else {
  181. $this->rules = $this->buildRules($this->rules);
  182. $this->cache->set($cacheKey, [$this->rules, $hash]);
  183. }
  184. } else {
  185. $this->rules = $this->buildRules($this->rules);
  186. }
  187. }
  188. /**
  189. * Adds additional URL rules.
  190. *
  191. * This method will call [[buildRules()]] to parse the given rule declarations and then append or insert
  192. * them to the existing [[rules]].
  193. *
  194. * Note that if [[enablePrettyUrl]] is `false`, this method will do nothing.
  195. *
  196. * @param array $rules the new rules to be added. Each array element represents a single rule declaration.
  197. * Please refer to [[rules]] for the acceptable rule format.
  198. * @param bool $append whether to add the new rules by appending them to the end of the existing rules.
  199. */
  200. public function addRules($rules, $append = true)
  201. {
  202. if (!$this->enablePrettyUrl) {
  203. return;
  204. }
  205. $rules = $this->buildRules($rules);
  206. if ($append) {
  207. $this->rules = array_merge($this->rules, $rules);
  208. } else {
  209. $this->rules = array_merge($rules, $this->rules);
  210. }
  211. }
  212. /**
  213. * Builds URL rule objects from the given rule declarations.
  214. * @param array $rules the rule declarations. Each array element represents a single rule declaration.
  215. * Please refer to [[rules]] for the acceptable rule formats.
  216. * @return UrlRuleInterface[] the rule objects built from the given rule declarations
  217. * @throws InvalidConfigException if a rule declaration is invalid
  218. */
  219. protected function buildRules($rules)
  220. {
  221. $compiledRules = [];
  222. $verbs = 'GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS';
  223. foreach ($rules as $key => $rule) {
  224. if (is_string($rule)) {
  225. $rule = ['route' => $rule];
  226. if (preg_match("/^((?:($verbs),)*($verbs))\\s+(.*)$/", $key, $matches)) {
  227. $rule['verb'] = explode(',', $matches[1]);
  228. // rules that do not apply for GET requests should not be use to create urls
  229. if (!in_array('GET', $rule['verb'])) {
  230. $rule['mode'] = UrlRule::PARSING_ONLY;
  231. }
  232. $key = $matches[4];
  233. }
  234. $rule['pattern'] = $key;
  235. }
  236. if (is_array($rule)) {
  237. $rule = Yii::createObject(array_merge($this->ruleConfig, $rule));
  238. }
  239. if (!$rule instanceof UrlRuleInterface) {
  240. throw new InvalidConfigException('URL rule class must implement UrlRuleInterface.');
  241. }
  242. $compiledRules[] = $rule;
  243. }
  244. return $compiledRules;
  245. }
  246. /**
  247. * Parses the user request.
  248. * @param Request $request the request component
  249. * @return array|bool the route and the associated parameters. The latter is always empty
  250. * if [[enablePrettyUrl]] is `false`. `false` is returned if the current request cannot be successfully parsed.
  251. */
  252. public function parseRequest($request)
  253. {
  254. if ($this->enablePrettyUrl) {
  255. /* @var $rule UrlRule */
  256. foreach ($this->rules as $rule) {
  257. $result = $rule->parseRequest($this, $request);
  258. if (YII_DEBUG) {
  259. Yii::trace([
  260. 'rule' => method_exists($rule, '__toString') ? $rule->__toString() : get_class($rule),
  261. 'match' => $result !== false,
  262. 'parent' => null
  263. ], __METHOD__);
  264. }
  265. if ($result !== false) {
  266. return $result;
  267. }
  268. }
  269. if ($this->enableStrictParsing) {
  270. return false;
  271. }
  272. Yii::trace('No matching URL rules. Using default URL parsing logic.', __METHOD__);
  273. $suffix = (string) $this->suffix;
  274. $pathInfo = $request->getPathInfo();
  275. $normalized = false;
  276. if ($this->normalizer !== false) {
  277. $pathInfo = $this->normalizer->normalizePathInfo($pathInfo, $suffix, $normalized);
  278. }
  279. if ($suffix !== '' && $pathInfo !== '') {
  280. $n = strlen($this->suffix);
  281. if (substr_compare($pathInfo, $this->suffix, -$n, $n) === 0) {
  282. $pathInfo = substr($pathInfo, 0, -$n);
  283. if ($pathInfo === '') {
  284. // suffix alone is not allowed
  285. return false;
  286. }
  287. } else {
  288. // suffix doesn't match
  289. return false;
  290. }
  291. }
  292. if ($normalized) {
  293. // pathInfo was changed by normalizer - we need also normalize route
  294. return $this->normalizer->normalizeRoute([$pathInfo, []]);
  295. } else {
  296. return [$pathInfo, []];
  297. }
  298. } else {
  299. Yii::trace('Pretty URL not enabled. Using default URL parsing logic.', __METHOD__);
  300. $route = $request->getQueryParam($this->routeParam, '');
  301. if (is_array($route)) {
  302. $route = '';
  303. }
  304. return [(string) $route, []];
  305. }
  306. }
  307. /**
  308. * Creates a URL using the given route and query parameters.
  309. *
  310. * You may specify the route as a string, e.g., `site/index`. You may also use an array
  311. * if you want to specify additional query parameters for the URL being created. The
  312. * array format must be:
  313. *
  314. * ```php
  315. * // generates: /index.php?r=site%2Findex&param1=value1&param2=value2
  316. * ['site/index', 'param1' => 'value1', 'param2' => 'value2']
  317. * ```
  318. *
  319. * If you want to create a URL with an anchor, you can use the array format with a `#` parameter.
  320. * For example,
  321. *
  322. * ```php
  323. * // generates: /index.php?r=site%2Findex&param1=value1#name
  324. * ['site/index', 'param1' => 'value1', '#' => 'name']
  325. * ```
  326. *
  327. * The URL created is a relative one. Use [[createAbsoluteUrl()]] to create an absolute URL.
  328. *
  329. * Note that unlike [[\yii\helpers\Url::toRoute()]], this method always treats the given route
  330. * as an absolute route.
  331. *
  332. * @param string|array $params use a string to represent a route (e.g. `site/index`),
  333. * or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`).
  334. * @return string the created URL
  335. */
  336. public function createUrl($params)
  337. {
  338. $params = (array) $params;
  339. $anchor = isset($params['#']) ? '#' . $params['#'] : '';
  340. unset($params['#'], $params[$this->routeParam]);
  341. $route = trim($params[0], '/');
  342. unset($params[0]);
  343. $baseUrl = $this->showScriptName || !$this->enablePrettyUrl ? $this->getScriptUrl() : $this->getBaseUrl();
  344. if ($this->enablePrettyUrl) {
  345. $cacheKey = $route . '?';
  346. foreach ($params as $key => $value) {
  347. if ($value !== null) {
  348. $cacheKey .= $key . '&';
  349. }
  350. }
  351. $url = $this->getUrlFromCache($cacheKey, $route, $params);
  352. if ($url === false) {
  353. $cacheable = true;
  354. foreach ($this->rules as $rule) {
  355. /* @var $rule UrlRule */
  356. if (!empty($rule->defaults) && $rule->mode !== UrlRule::PARSING_ONLY) {
  357. // if there is a rule with default values involved, the matching result may not be cached
  358. $cacheable = false;
  359. }
  360. if (($url = $rule->createUrl($this, $route, $params)) !== false) {
  361. if ($cacheable) {
  362. $this->setRuleToCache($cacheKey, $rule);
  363. }
  364. break;
  365. }
  366. }
  367. }
  368. if ($url !== false) {
  369. if (strpos($url, '://') !== false) {
  370. if ($baseUrl !== '' && ($pos = strpos($url, '/', 8)) !== false) {
  371. return substr($url, 0, $pos) . $baseUrl . substr($url, $pos) . $anchor;
  372. } else {
  373. return $url . $baseUrl . $anchor;
  374. }
  375. } elseif (strpos($url, '//') === 0) {
  376. if ($baseUrl !== '' && ($pos = strpos($url, '/', 2)) !== false) {
  377. return substr($url, 0, $pos) . $baseUrl . substr($url, $pos) . $anchor;
  378. } else {
  379. return $url . $baseUrl . $anchor;
  380. }
  381. } else {
  382. return "$baseUrl/{$url}{$anchor}";
  383. }
  384. }
  385. if ($this->suffix !== null) {
  386. $route .= $this->suffix;
  387. }
  388. if (!empty($params) && ($query = http_build_query($params)) !== '') {
  389. $route .= '?' . $query;
  390. }
  391. return "$baseUrl/{$route}{$anchor}";
  392. } else {
  393. $url = "$baseUrl?{$this->routeParam}=" . urlencode($route);
  394. if (!empty($params) && ($query = http_build_query($params)) !== '') {
  395. $url .= '&' . $query;
  396. }
  397. return $url . $anchor;
  398. }
  399. }
  400. /**
  401. * Get URL from internal cache if exists
  402. * @param string $cacheKey generated cache key to store data.
  403. * @param string $route the route (e.g. `site/index`).
  404. * @param array $params rule params.
  405. * @return bool|string the created URL
  406. * @see createUrl()
  407. * @since 2.0.8
  408. */
  409. protected function getUrlFromCache($cacheKey, $route, $params)
  410. {
  411. if (!empty($this->_ruleCache[$cacheKey])) {
  412. foreach ($this->_ruleCache[$cacheKey] as $rule) {
  413. /* @var $rule UrlRule */
  414. if (($url = $rule->createUrl($this, $route, $params)) !== false) {
  415. return $url;
  416. }
  417. }
  418. } else {
  419. $this->_ruleCache[$cacheKey] = [];
  420. }
  421. return false;
  422. }
  423. /**
  424. * Store rule (e.g. [[UrlRule]]) to internal cache
  425. * @param $cacheKey
  426. * @param UrlRuleInterface $rule
  427. * @since 2.0.8
  428. */
  429. protected function setRuleToCache($cacheKey, UrlRuleInterface $rule)
  430. {
  431. $this->_ruleCache[$cacheKey][] = $rule;
  432. }
  433. /**
  434. * Creates an absolute URL using the given route and query parameters.
  435. *
  436. * This method prepends the URL created by [[createUrl()]] with the [[hostInfo]].
  437. *
  438. * Note that unlike [[\yii\helpers\Url::toRoute()]], this method always treats the given route
  439. * as an absolute route.
  440. *
  441. * @param string|array $params use a string to represent a route (e.g. `site/index`),
  442. * or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`).
  443. * @param string|null $scheme the scheme to use for the URL (either `http`, `https` or empty string
  444. * for protocol-relative URL).
  445. * If not specified the scheme of the current request will be used.
  446. * @return string the created URL
  447. * @see createUrl()
  448. */
  449. public function createAbsoluteUrl($params, $scheme = null)
  450. {
  451. $params = (array) $params;
  452. $url = $this->createUrl($params);
  453. if (strpos($url, '://') === false) {
  454. $hostInfo = $this->getHostInfo();
  455. if (strpos($url, '//') === 0) {
  456. $url = substr($hostInfo, 0, strpos($hostInfo, '://')) . ':' . $url;
  457. } else {
  458. $url = $hostInfo . $url;
  459. }
  460. }
  461. return Url::ensureScheme($url, $scheme);
  462. }
  463. /**
  464. * Returns the base URL that is used by [[createUrl()]] to prepend to created URLs.
  465. * It defaults to [[Request::baseUrl]].
  466. * This is mainly used when [[enablePrettyUrl]] is `true` and [[showScriptName]] is `false`.
  467. * @return string the base URL that is used by [[createUrl()]] to prepend to created URLs.
  468. * @throws InvalidConfigException if running in console application and [[baseUrl]] is not configured.
  469. */
  470. public function getBaseUrl()
  471. {
  472. if ($this->_baseUrl === null) {
  473. $request = Yii::$app->getRequest();
  474. if ($request instanceof Request) {
  475. $this->_baseUrl = $request->getBaseUrl();
  476. } else {
  477. throw new InvalidConfigException('Please configure UrlManager::baseUrl correctly as you are running a console application.');
  478. }
  479. }
  480. return $this->_baseUrl;
  481. }
  482. /**
  483. * Sets the base URL that is used by [[createUrl()]] to prepend to created URLs.
  484. * This is mainly used when [[enablePrettyUrl]] is `true` and [[showScriptName]] is `false`.
  485. * @param string $value the base URL that is used by [[createUrl()]] to prepend to created URLs.
  486. */
  487. public function setBaseUrl($value)
  488. {
  489. $this->_baseUrl = $value === null ? null : rtrim($value, '/');
  490. }
  491. /**
  492. * Returns the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
  493. * It defaults to [[Request::scriptUrl]].
  494. * This is mainly used when [[enablePrettyUrl]] is `false` or [[showScriptName]] is `true`.
  495. * @return string the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
  496. * @throws InvalidConfigException if running in console application and [[scriptUrl]] is not configured.
  497. */
  498. public function getScriptUrl()
  499. {
  500. if ($this->_scriptUrl === null) {
  501. $request = Yii::$app->getRequest();
  502. if ($request instanceof Request) {
  503. $this->_scriptUrl = $request->getScriptUrl();
  504. } else {
  505. throw new InvalidConfigException('Please configure UrlManager::scriptUrl correctly as you are running a console application.');
  506. }
  507. }
  508. return $this->_scriptUrl;
  509. }
  510. /**
  511. * Sets the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
  512. * This is mainly used when [[enablePrettyUrl]] is `false` or [[showScriptName]] is `true`.
  513. * @param string $value the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
  514. */
  515. public function setScriptUrl($value)
  516. {
  517. $this->_scriptUrl = $value;
  518. }
  519. /**
  520. * Returns the host info that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
  521. * @return string the host info (e.g. `http://www.example.com`) that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
  522. * @throws InvalidConfigException if running in console application and [[hostInfo]] is not configured.
  523. */
  524. public function getHostInfo()
  525. {
  526. if ($this->_hostInfo === null) {
  527. $request = Yii::$app->getRequest();
  528. if ($request instanceof \yii\web\Request) {
  529. $this->_hostInfo = $request->getHostInfo();
  530. } else {
  531. throw new InvalidConfigException('Please configure UrlManager::hostInfo correctly as you are running a console application.');
  532. }
  533. }
  534. return $this->_hostInfo;
  535. }
  536. /**
  537. * Sets the host info that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
  538. * @param string $value the host info (e.g. "http://www.example.com") that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
  539. */
  540. public function setHostInfo($value)
  541. {
  542. $this->_hostInfo = $value === null ? null : rtrim($value, '/');
  543. }
  544. }