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.

преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
преди 8 години
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  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 [[enablePrettyUrl]] is `true`.
  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 UrlNormalizer|array|string|false the configuration for [[UrlNormalizer]] used by this UrlManager.
  127. * The default value is `false`, which means normalization will be skipped.
  128. * If you wish to enable URL normalization, you should configure this property manually.
  129. * For example:
  130. *
  131. * ```php
  132. * [
  133. * 'class' => 'yii\web\UrlNormalizer',
  134. * 'collapseSlashes' => true,
  135. * 'normalizeTrailingSlash' => true,
  136. * ]
  137. * ```
  138. *
  139. * @since 2.0.10
  140. */
  141. public $normalizer = false;
  142. /**
  143. * @var string the cache key for cached rules
  144. * @since 2.0.8
  145. */
  146. protected $cacheKey = __CLASS__;
  147. private $_baseUrl;
  148. private $_scriptUrl;
  149. private $_hostInfo;
  150. private $_ruleCache;
  151. /**
  152. * Initializes UrlManager.
  153. */
  154. public function init()
  155. {
  156. parent::init();
  157. if ($this->normalizer !== false) {
  158. $this->normalizer = Yii::createObject($this->normalizer);
  159. if (!$this->normalizer instanceof UrlNormalizer) {
  160. throw new InvalidConfigException('`' . get_class($this) . '::normalizer` should be an instance of `' . UrlNormalizer::className() . '` or its DI compatible configuration.');
  161. }
  162. }
  163. if (!$this->enablePrettyUrl || empty($this->rules)) {
  164. return;
  165. }
  166. if (is_string($this->cache)) {
  167. $this->cache = Yii::$app->get($this->cache, false);
  168. }
  169. if ($this->cache instanceof Cache) {
  170. $cacheKey = $this->cacheKey;
  171. $hash = md5(json_encode($this->rules));
  172. if (($data = $this->cache->get($cacheKey)) !== false && isset($data[1]) && $data[1] === $hash) {
  173. $this->rules = $data[0];
  174. } else {
  175. $this->rules = $this->buildRules($this->rules);
  176. $this->cache->set($cacheKey, [$this->rules, $hash]);
  177. }
  178. } else {
  179. $this->rules = $this->buildRules($this->rules);
  180. }
  181. }
  182. /**
  183. * Adds additional URL rules.
  184. *
  185. * This method will call [[buildRules()]] to parse the given rule declarations and then append or insert
  186. * them to the existing [[rules]].
  187. *
  188. * Note that if [[enablePrettyUrl]] is `false`, this method will do nothing.
  189. *
  190. * @param array $rules the new rules to be added. Each array element represents a single rule declaration.
  191. * Please refer to [[rules]] for the acceptable rule format.
  192. * @param boolean $append whether to add the new rules by appending them to the end of the existing rules.
  193. */
  194. public function addRules($rules, $append = true)
  195. {
  196. if (!$this->enablePrettyUrl) {
  197. return;
  198. }
  199. $rules = $this->buildRules($rules);
  200. if ($append) {
  201. $this->rules = array_merge($this->rules, $rules);
  202. } else {
  203. $this->rules = array_merge($rules, $this->rules);
  204. }
  205. }
  206. /**
  207. * Builds URL rule objects from the given rule declarations.
  208. * @param array $rules the rule declarations. Each array element represents a single rule declaration.
  209. * Please refer to [[rules]] for the acceptable rule formats.
  210. * @return UrlRuleInterface[] the rule objects built from the given rule declarations
  211. * @throws InvalidConfigException if a rule declaration is invalid
  212. */
  213. protected function buildRules($rules)
  214. {
  215. $compiledRules = [];
  216. $verbs = 'GET|HEAD|POST|PUT|PATCH|DELETE|OPTIONS';
  217. foreach ($rules as $key => $rule) {
  218. if (is_string($rule)) {
  219. $rule = ['route' => $rule];
  220. if (preg_match("/^((?:($verbs),)*($verbs))\\s+(.*)$/", $key, $matches)) {
  221. $rule['verb'] = explode(',', $matches[1]);
  222. // rules that do not apply for GET requests should not be use to create urls
  223. if (!in_array('GET', $rule['verb'])) {
  224. $rule['mode'] = UrlRule::PARSING_ONLY;
  225. }
  226. $key = $matches[4];
  227. }
  228. $rule['pattern'] = $key;
  229. }
  230. if (is_array($rule)) {
  231. $rule = Yii::createObject(array_merge($this->ruleConfig, $rule));
  232. }
  233. if (!$rule instanceof UrlRuleInterface) {
  234. throw new InvalidConfigException('URL rule class must implement UrlRuleInterface.');
  235. }
  236. $compiledRules[] = $rule;
  237. }
  238. return $compiledRules;
  239. }
  240. /**
  241. * Parses the user request.
  242. * @param Request $request the request component
  243. * @return array|boolean the route and the associated parameters. The latter is always empty
  244. * if [[enablePrettyUrl]] is `false`. `false` is returned if the current request cannot be successfully parsed.
  245. */
  246. public function parseRequest($request)
  247. {
  248. if ($this->enablePrettyUrl) {
  249. /* @var $rule UrlRule */
  250. foreach ($this->rules as $rule) {
  251. if (($result = $rule->parseRequest($this, $request)) !== false) {
  252. return $result;
  253. }
  254. }
  255. if ($this->enableStrictParsing) {
  256. return false;
  257. }
  258. Yii::trace('No matching URL rules. Using default URL parsing logic.', __METHOD__);
  259. $suffix = (string) $this->suffix;
  260. $pathInfo = $request->getPathInfo();
  261. $normalized = false;
  262. if ($this->normalizer !== false) {
  263. $pathInfo = $this->normalizer->normalizePathInfo($pathInfo, $suffix, $normalized);
  264. }
  265. if ($suffix !== '' && $pathInfo !== '') {
  266. $n = strlen($this->suffix);
  267. if (substr_compare($pathInfo, $this->suffix, -$n, $n) === 0) {
  268. $pathInfo = substr($pathInfo, 0, -$n);
  269. if ($pathInfo === '') {
  270. // suffix alone is not allowed
  271. return false;
  272. }
  273. } else {
  274. // suffix doesn't match
  275. return false;
  276. }
  277. }
  278. if ($normalized) {
  279. // pathInfo was changed by normalizer - we need also normalize route
  280. return $this->normalizer->normalizeRoute([$pathInfo, []]);
  281. } else {
  282. return [$pathInfo, []];
  283. }
  284. } else {
  285. Yii::trace('Pretty URL not enabled. Using default URL parsing logic.', __METHOD__);
  286. $route = $request->getQueryParam($this->routeParam, '');
  287. if (is_array($route)) {
  288. $route = '';
  289. }
  290. return [(string) $route, []];
  291. }
  292. }
  293. /**
  294. * Creates a URL using the given route and query parameters.
  295. *
  296. * You may specify the route as a string, e.g., `site/index`. You may also use an array
  297. * if you want to specify additional query parameters for the URL being created. The
  298. * array format must be:
  299. *
  300. * ```php
  301. * // generates: /index.php?r=site%2Findex&param1=value1&param2=value2
  302. * ['site/index', 'param1' => 'value1', 'param2' => 'value2']
  303. * ```
  304. *
  305. * If you want to create a URL with an anchor, you can use the array format with a `#` parameter.
  306. * For example,
  307. *
  308. * ```php
  309. * // generates: /index.php?r=site%2Findex&param1=value1#name
  310. * ['site/index', 'param1' => 'value1', '#' => 'name']
  311. * ```
  312. *
  313. * The URL created is a relative one. Use [[createAbsoluteUrl()]] to create an absolute URL.
  314. *
  315. * Note that unlike [[\yii\helpers\Url::toRoute()]], this method always treats the given route
  316. * as an absolute route.
  317. *
  318. * @param string|array $params use a string to represent a route (e.g. `site/index`),
  319. * or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`).
  320. * @return string the created URL
  321. */
  322. public function createUrl($params)
  323. {
  324. $params = (array) $params;
  325. $anchor = isset($params['#']) ? '#' . $params['#'] : '';
  326. unset($params['#'], $params[$this->routeParam]);
  327. $route = trim($params[0], '/');
  328. unset($params[0]);
  329. $baseUrl = $this->showScriptName || !$this->enablePrettyUrl ? $this->getScriptUrl() : $this->getBaseUrl();
  330. if ($this->enablePrettyUrl) {
  331. $cacheKey = $route . '?';
  332. foreach ($params as $key => $value) {
  333. if ($value !== null) {
  334. $cacheKey .= $key . '&';
  335. }
  336. }
  337. $url = $this->getUrlFromCache($cacheKey, $route, $params);
  338. if ($url === false) {
  339. $cacheable = true;
  340. foreach ($this->rules as $rule) {
  341. /* @var $rule UrlRule */
  342. if (!empty($rule->defaults) && $rule->mode !== UrlRule::PARSING_ONLY) {
  343. // if there is a rule with default values involved, the matching result may not be cached
  344. $cacheable = false;
  345. }
  346. if (($url = $rule->createUrl($this, $route, $params)) !== false) {
  347. if ($cacheable) {
  348. $this->setRuleToCache($cacheKey, $rule);
  349. }
  350. break;
  351. }
  352. }
  353. }
  354. if ($url !== false) {
  355. if (strpos($url, '://') !== false) {
  356. if ($baseUrl !== '' && ($pos = strpos($url, '/', 8)) !== false) {
  357. return substr($url, 0, $pos) . $baseUrl . substr($url, $pos) . $anchor;
  358. } else {
  359. return $url . $baseUrl . $anchor;
  360. }
  361. } else {
  362. return "$baseUrl/{$url}{$anchor}";
  363. }
  364. }
  365. if ($this->suffix !== null) {
  366. $route .= $this->suffix;
  367. }
  368. if (!empty($params) && ($query = http_build_query($params)) !== '') {
  369. $route .= '?' . $query;
  370. }
  371. return "$baseUrl/{$route}{$anchor}";
  372. } else {
  373. $url = "$baseUrl?{$this->routeParam}=" . urlencode($route);
  374. if (!empty($params) && ($query = http_build_query($params)) !== '') {
  375. $url .= '&' . $query;
  376. }
  377. return $url . $anchor;
  378. }
  379. }
  380. /**
  381. * Get URL from internal cache if exists
  382. * @param string $cacheKey generated cache key to store data.
  383. * @param string $route the route (e.g. `site/index`).
  384. * @param array $params rule params.
  385. * @return boolean|string the created URL
  386. * @see createUrl()
  387. * @since 2.0.8
  388. */
  389. protected function getUrlFromCache($cacheKey, $route, $params)
  390. {
  391. if (!empty($this->_ruleCache[$cacheKey])) {
  392. foreach ($this->_ruleCache[$cacheKey] as $rule) {
  393. /* @var $rule UrlRule */
  394. if (($url = $rule->createUrl($this, $route, $params)) !== false) {
  395. return $url;
  396. }
  397. }
  398. } else {
  399. $this->_ruleCache[$cacheKey] = [];
  400. }
  401. return false;
  402. }
  403. /**
  404. * Store rule (e.g. [[UrlRule]]) to internal cache
  405. * @param $cacheKey
  406. * @param UrlRuleInterface $rule
  407. * @since 2.0.8
  408. */
  409. protected function setRuleToCache($cacheKey, UrlRuleInterface $rule)
  410. {
  411. $this->_ruleCache[$cacheKey][] = $rule;
  412. }
  413. /**
  414. * Creates an absolute URL using the given route and query parameters.
  415. *
  416. * This method prepends the URL created by [[createUrl()]] with the [[hostInfo]].
  417. *
  418. * Note that unlike [[\yii\helpers\Url::toRoute()]], this method always treats the given route
  419. * as an absolute route.
  420. *
  421. * @param string|array $params use a string to represent a route (e.g. `site/index`),
  422. * or an array to represent a route with query parameters (e.g. `['site/index', 'param1' => 'value1']`).
  423. * @param string $scheme the scheme to use for the url (either `http` or `https`). If not specified
  424. * the scheme of the current request will be used.
  425. * @return string the created URL
  426. * @see createUrl()
  427. */
  428. public function createAbsoluteUrl($params, $scheme = null)
  429. {
  430. $params = (array) $params;
  431. $url = $this->createUrl($params);
  432. if (strpos($url, '://') === false) {
  433. $url = $this->getHostInfo() . $url;
  434. }
  435. if (is_string($scheme) && ($pos = strpos($url, '://')) !== false) {
  436. $url = $scheme . substr($url, $pos);
  437. }
  438. return $url;
  439. }
  440. /**
  441. * Returns the base URL that is used by [[createUrl()]] to prepend to created URLs.
  442. * It defaults to [[Request::baseUrl]].
  443. * This is mainly used when [[enablePrettyUrl]] is `true` and [[showScriptName]] is `false`.
  444. * @return string the base URL that is used by [[createUrl()]] to prepend to created URLs.
  445. * @throws InvalidConfigException if running in console application and [[baseUrl]] is not configured.
  446. */
  447. public function getBaseUrl()
  448. {
  449. if ($this->_baseUrl === null) {
  450. $request = Yii::$app->getRequest();
  451. if ($request instanceof Request) {
  452. $this->_baseUrl = $request->getBaseUrl();
  453. } else {
  454. throw new InvalidConfigException('Please configure UrlManager::baseUrl correctly as you are running a console application.');
  455. }
  456. }
  457. return $this->_baseUrl;
  458. }
  459. /**
  460. * Sets the base URL that is used by [[createUrl()]] to prepend to created URLs.
  461. * This is mainly used when [[enablePrettyUrl]] is `true` and [[showScriptName]] is `false`.
  462. * @param string $value the base URL that is used by [[createUrl()]] to prepend to created URLs.
  463. */
  464. public function setBaseUrl($value)
  465. {
  466. $this->_baseUrl = $value === null ? null : rtrim($value, '/');
  467. }
  468. /**
  469. * Returns the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
  470. * It defaults to [[Request::scriptUrl]].
  471. * This is mainly used when [[enablePrettyUrl]] is `false` or [[showScriptName]] is `true`.
  472. * @return string the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
  473. * @throws InvalidConfigException if running in console application and [[scriptUrl]] is not configured.
  474. */
  475. public function getScriptUrl()
  476. {
  477. if ($this->_scriptUrl === null) {
  478. $request = Yii::$app->getRequest();
  479. if ($request instanceof Request) {
  480. $this->_scriptUrl = $request->getScriptUrl();
  481. } else {
  482. throw new InvalidConfigException('Please configure UrlManager::scriptUrl correctly as you are running a console application.');
  483. }
  484. }
  485. return $this->_scriptUrl;
  486. }
  487. /**
  488. * Sets the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
  489. * This is mainly used when [[enablePrettyUrl]] is `false` or [[showScriptName]] is `true`.
  490. * @param string $value the entry script URL that is used by [[createUrl()]] to prepend to created URLs.
  491. */
  492. public function setScriptUrl($value)
  493. {
  494. $this->_scriptUrl = $value;
  495. }
  496. /**
  497. * Returns the host info that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
  498. * @return string the host info (e.g. "http://www.example.com") that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
  499. * @throws InvalidConfigException if running in console application and [[hostInfo]] is not configured.
  500. */
  501. public function getHostInfo()
  502. {
  503. if ($this->_hostInfo === null) {
  504. $request = Yii::$app->getRequest();
  505. if ($request instanceof \yii\web\Request) {
  506. $this->_hostInfo = $request->getHostInfo();
  507. } else {
  508. throw new InvalidConfigException('Please configure UrlManager::hostInfo correctly as you are running a console application.');
  509. }
  510. }
  511. return $this->_hostInfo;
  512. }
  513. /**
  514. * Sets the host info that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
  515. * @param string $value the host info (e.g. "http://www.example.com") that is used by [[createAbsoluteUrl()]] to prepend to created URLs.
  516. */
  517. public function setHostInfo($value)
  518. {
  519. $this->_hostInfo = $value === null ? null : rtrim($value, '/');
  520. }
  521. }