You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

534 lines
21KB

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