UrlRule.php 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. <?php
  2. /**
  3. * @link https://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license https://www.yiiframework.com/license/
  6. */
  7. namespace yii\web;
  8. use Yii;
  9. use yii\base\BaseObject;
  10. use yii\base\InvalidConfigException;
  11. /**
  12. * UrlRule represents a rule used by [[UrlManager]] for parsing and generating URLs.
  13. *
  14. * To define your own URL parsing and creation logic you can extend from this class
  15. * and add it to [[UrlManager::rules]] like this:
  16. *
  17. * ```php
  18. * 'rules' => [
  19. * ['class' => 'MyUrlRule', 'pattern' => '...', 'route' => 'site/index', ...],
  20. * // ...
  21. * ]
  22. * ```
  23. *
  24. * @property-read int|null $createUrlStatus Status of the URL creation after the last [[createUrl()]] call.
  25. * `null` if rule does not provide info about create status.
  26. *
  27. * @author Qiang Xue <qiang.xue@gmail.com>
  28. * @since 2.0
  29. */
  30. class UrlRule extends BaseObject implements UrlRuleInterface
  31. {
  32. /**
  33. * Set [[mode]] with this value to mark that this rule is for URL parsing only.
  34. */
  35. const PARSING_ONLY = 1;
  36. /**
  37. * Set [[mode]] with this value to mark that this rule is for URL creation only.
  38. */
  39. const CREATION_ONLY = 2;
  40. /**
  41. * Represents the successful URL generation by last [[createUrl()]] call.
  42. * @see createStatus
  43. * @since 2.0.12
  44. */
  45. const CREATE_STATUS_SUCCESS = 0;
  46. /**
  47. * Represents the unsuccessful URL generation by last [[createUrl()]] call, because rule does not support
  48. * creating URLs.
  49. * @see createStatus
  50. * @since 2.0.12
  51. */
  52. const CREATE_STATUS_PARSING_ONLY = 1;
  53. /**
  54. * Represents the unsuccessful URL generation by last [[createUrl()]] call, because of mismatched route.
  55. * @see createStatus
  56. * @since 2.0.12
  57. */
  58. const CREATE_STATUS_ROUTE_MISMATCH = 2;
  59. /**
  60. * Represents the unsuccessful URL generation by last [[createUrl()]] call, because of mismatched
  61. * or missing parameters.
  62. * @see createStatus
  63. * @since 2.0.12
  64. */
  65. const CREATE_STATUS_PARAMS_MISMATCH = 4;
  66. /**
  67. * @var string|null the name of this rule. If not set, it will use [[pattern]] as the name.
  68. */
  69. public $name;
  70. /**
  71. * On the rule initialization, the [[pattern]] matching parameters names will be replaced with [[placeholders]].
  72. * @var string the pattern used to parse and create the path info part of a URL.
  73. * @see host
  74. * @see placeholders
  75. */
  76. public $pattern;
  77. /**
  78. * @var string|null the pattern used to parse and create the host info part of a URL (e.g. `https://example.com`).
  79. * @see pattern
  80. */
  81. public $host;
  82. /**
  83. * @var string the route to the controller action
  84. */
  85. public $route;
  86. /**
  87. * @var array the default GET parameters (name => value) that this rule provides.
  88. * When this rule is used to parse the incoming request, the values declared in this property
  89. * will be injected into $_GET.
  90. */
  91. public $defaults = [];
  92. /**
  93. * @var string|null the URL suffix used for this rule.
  94. * For example, ".html" can be used so that the URL looks like pointing to a static HTML page.
  95. * If not set, the value of [[UrlManager::suffix]] will be used.
  96. * Default values should be strings. Non-string values will be automatically converted to
  97. * strings for comparison with URL parameters.
  98. */
  99. public $suffix;
  100. /**
  101. * @var string|array|null the HTTP verb (e.g. GET, POST, DELETE) that this rule should match.
  102. * Use array to represent multiple verbs that this rule may match.
  103. * If this property is not set, the rule can match any verb.
  104. * Note that this property is only used when parsing a request. It is ignored for URL creation.
  105. */
  106. public $verb;
  107. /**
  108. * @var int|null a value indicating if this rule should be used for both request parsing and URL creation,
  109. * parsing only, or creation only.
  110. * If not set or 0, it means the rule is both request parsing and URL creation.
  111. * If it is [[PARSING_ONLY]], the rule is for request parsing only.
  112. * If it is [[CREATION_ONLY]], the rule is for URL creation only.
  113. */
  114. public $mode;
  115. /**
  116. * @var bool a value indicating if parameters should be url encoded.
  117. */
  118. public $encodeParams = true;
  119. /**
  120. * @var UrlNormalizer|array|false|null the configuration for [[UrlNormalizer]] used by this rule.
  121. * If `null`, [[UrlManager::normalizer]] will be used, if `false`, normalization will be skipped
  122. * for this rule.
  123. * @since 2.0.10
  124. */
  125. public $normalizer;
  126. /**
  127. * @var int|null status of the URL creation after the last [[createUrl()]] call.
  128. * @since 2.0.12
  129. */
  130. protected $createStatus;
  131. /**
  132. * @var array list of placeholders for matching parameters names. Used in [[parseRequest()]], [[createUrl()]].
  133. * On the rule initialization, the [[pattern]] parameters names will be replaced with placeholders.
  134. * This array contains relations between the original parameters names and their placeholders.
  135. * The array keys are the placeholders and the values are the original names.
  136. *
  137. * @see parseRequest()
  138. * @see createUrl()
  139. * @since 2.0.7
  140. */
  141. protected $placeholders = [];
  142. /**
  143. * @var string the template for generating a new URL. This is derived from [[pattern]] and is used in generating URL.
  144. */
  145. private $_template;
  146. /**
  147. * @var string the regex for matching the route part. This is used in generating URL.
  148. */
  149. private $_routeRule;
  150. /**
  151. * @var array list of regex for matching parameters. This is used in generating URL.
  152. */
  153. private $_paramRules = [];
  154. /**
  155. * @var array list of parameters used in the route.
  156. */
  157. private $_routeParams = [];
  158. /**
  159. * @return string
  160. * @since 2.0.11
  161. */
  162. public function __toString()
  163. {
  164. $str = '';
  165. if ($this->verb !== null) {
  166. $str .= implode(',', $this->verb) . ' ';
  167. }
  168. if ($this->host !== null && strrpos($this->name, $this->host) === false) {
  169. $str .= $this->host . '/';
  170. }
  171. $str .= $this->name;
  172. if ($str === '') {
  173. return '/';
  174. }
  175. return $str;
  176. }
  177. /**
  178. * Initializes this rule.
  179. */
  180. public function init()
  181. {
  182. if ($this->pattern === null) {
  183. throw new InvalidConfigException('UrlRule::pattern must be set.');
  184. }
  185. if ($this->route === null) {
  186. throw new InvalidConfigException('UrlRule::route must be set.');
  187. }
  188. if (is_array($this->normalizer)) {
  189. $normalizerConfig = array_merge(['class' => UrlNormalizer::className()], $this->normalizer);
  190. $this->normalizer = Yii::createObject($normalizerConfig);
  191. }
  192. if ($this->normalizer !== null && $this->normalizer !== false && !$this->normalizer instanceof UrlNormalizer) {
  193. throw new InvalidConfigException('Invalid config for UrlRule::normalizer.');
  194. }
  195. if ($this->verb !== null) {
  196. if (is_array($this->verb)) {
  197. foreach ($this->verb as $i => $verb) {
  198. $this->verb[$i] = strtoupper($verb);
  199. }
  200. } else {
  201. $this->verb = [strtoupper($this->verb)];
  202. }
  203. }
  204. if ($this->name === null) {
  205. $this->name = $this->pattern;
  206. }
  207. $this->preparePattern();
  208. }
  209. /**
  210. * Process [[$pattern]] on rule initialization.
  211. */
  212. private function preparePattern()
  213. {
  214. $this->pattern = $this->trimSlashes($this->pattern);
  215. $this->route = trim($this->route, '/');
  216. if ($this->host !== null) {
  217. $this->host = rtrim($this->host, '/');
  218. $this->pattern = rtrim($this->host . '/' . $this->pattern, '/');
  219. } elseif ($this->pattern === '') {
  220. $this->_template = '';
  221. $this->pattern = '#^$#u';
  222. return;
  223. } elseif (($pos = strpos($this->pattern, '://')) !== false) {
  224. if (($pos2 = strpos($this->pattern, '/', $pos + 3)) !== false) {
  225. $this->host = substr($this->pattern, 0, $pos2);
  226. } else {
  227. $this->host = $this->pattern;
  228. }
  229. } elseif (strncmp($this->pattern, '//', 2) === 0) {
  230. if (($pos2 = strpos($this->pattern, '/', 2)) !== false) {
  231. $this->host = substr($this->pattern, 0, $pos2);
  232. } else {
  233. $this->host = $this->pattern;
  234. }
  235. } else {
  236. $this->pattern = '/' . $this->pattern . '/';
  237. }
  238. if (strpos($this->route, '<') !== false && preg_match_all('/<([\w._-]+)>/', $this->route, $matches)) {
  239. foreach ($matches[1] as $name) {
  240. $this->_routeParams[$name] = "<$name>";
  241. }
  242. }
  243. $this->translatePattern(true);
  244. }
  245. /**
  246. * Prepares [[$pattern]] on rule initialization - replace parameter names by placeholders.
  247. *
  248. * @param bool $allowAppendSlash Defines position of slash in the param pattern in [[$pattern]].
  249. * If `false` slash will be placed at the beginning of param pattern. If `true` slash position will be detected
  250. * depending on non-optional pattern part.
  251. */
  252. private function translatePattern($allowAppendSlash)
  253. {
  254. $tr = [
  255. '.' => '\\.',
  256. '*' => '\\*',
  257. '$' => '\\$',
  258. '[' => '\\[',
  259. ']' => '\\]',
  260. '(' => '\\(',
  261. ')' => '\\)',
  262. ];
  263. $tr2 = [];
  264. $requiredPatternPart = $this->pattern;
  265. $oldOffset = 0;
  266. if (preg_match_all('/<([\w._-]+):?([^>]+)?>/', $this->pattern, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
  267. $appendSlash = false;
  268. foreach ($matches as $match) {
  269. $name = $match[1][0];
  270. $pattern = isset($match[2][0]) ? $match[2][0] : '[^\/]+';
  271. $placeholder = 'a' . hash('crc32b', $name); // placeholder must begin with a letter
  272. $this->placeholders[$placeholder] = $name;
  273. if (array_key_exists($name, $this->defaults)) {
  274. $length = strlen($match[0][0]);
  275. $offset = $match[0][1];
  276. $requiredPatternPart = str_replace("/{$match[0][0]}/", '//', $requiredPatternPart);
  277. if (
  278. $allowAppendSlash
  279. && ($appendSlash || $offset === 1)
  280. && (($offset - $oldOffset) === 1)
  281. && isset($this->pattern[$offset + $length])
  282. && $this->pattern[$offset + $length] === '/'
  283. && isset($this->pattern[$offset + $length + 1])
  284. ) {
  285. // if pattern starts from optional params, put slash at the end of param pattern
  286. // @see https://github.com/yiisoft/yii2/issues/13086
  287. $appendSlash = true;
  288. $tr["<$name>/"] = "((?P<$placeholder>$pattern)/)?";
  289. } elseif (
  290. $offset > 1
  291. && $this->pattern[$offset - 1] === '/'
  292. && (!isset($this->pattern[$offset + $length]) || $this->pattern[$offset + $length] === '/')
  293. ) {
  294. $appendSlash = false;
  295. $tr["/<$name>"] = "(/(?P<$placeholder>$pattern))?";
  296. }
  297. $tr["<$name>"] = "(?P<$placeholder>$pattern)?";
  298. $oldOffset = $offset + $length;
  299. } else {
  300. $appendSlash = false;
  301. $tr["<$name>"] = "(?P<$placeholder>$pattern)";
  302. }
  303. if (isset($this->_routeParams[$name])) {
  304. $tr2["<$name>"] = "(?P<$placeholder>$pattern)";
  305. } else {
  306. $this->_paramRules[$name] = $pattern === '[^\/]+' ? '' : "#^$pattern$#u";
  307. }
  308. }
  309. }
  310. // we have only optional params in route - ensure slash position on param patterns
  311. if ($allowAppendSlash && trim($requiredPatternPart, '/') === '') {
  312. $this->translatePattern(false);
  313. return;
  314. }
  315. $this->_template = preg_replace('/<([\w._-]+):?([^>]+)?>/', '<$1>', $this->pattern);
  316. $this->pattern = '#^' . trim(strtr($this->_template, $tr), '/') . '$#u';
  317. // if host starts with relative scheme, then insert pattern to match any
  318. if ($this->host !== null && strncmp($this->host, '//', 2) === 0) {
  319. $this->pattern = substr_replace($this->pattern, '[\w]+://', 2, 0);
  320. }
  321. if (!empty($this->_routeParams)) {
  322. $this->_routeRule = '#^' . strtr($this->route, $tr2) . '$#u';
  323. }
  324. }
  325. /**
  326. * @param UrlManager $manager the URL manager
  327. * @return UrlNormalizer|null
  328. * @since 2.0.10
  329. */
  330. protected function getNormalizer($manager)
  331. {
  332. if ($this->normalizer === null) {
  333. return $manager->normalizer;
  334. }
  335. return $this->normalizer;
  336. }
  337. /**
  338. * @param UrlManager $manager the URL manager
  339. * @return bool
  340. * @since 2.0.10
  341. */
  342. protected function hasNormalizer($manager)
  343. {
  344. return $this->getNormalizer($manager) instanceof UrlNormalizer;
  345. }
  346. /**
  347. * Parses the given request and returns the corresponding route and parameters.
  348. * @param UrlManager $manager the URL manager
  349. * @param Request $request the request component
  350. * @return array|bool the parsing result. The route and the parameters are returned as an array.
  351. * If `false`, it means this rule cannot be used to parse this path info.
  352. */
  353. public function parseRequest($manager, $request)
  354. {
  355. if ($this->mode === self::CREATION_ONLY) {
  356. return false;
  357. }
  358. if (!empty($this->verb) && !in_array($request->getMethod(), $this->verb, true)) {
  359. return false;
  360. }
  361. $suffix = (string) ($this->suffix === null ? $manager->suffix : $this->suffix);
  362. $pathInfo = $request->getPathInfo();
  363. $normalized = false;
  364. if ($this->hasNormalizer($manager)) {
  365. $pathInfo = $this->getNormalizer($manager)->normalizePathInfo($pathInfo, $suffix, $normalized);
  366. }
  367. if ($suffix !== '' && $pathInfo !== '') {
  368. $n = strlen($suffix);
  369. if (substr_compare($pathInfo, $suffix, -$n, $n) === 0) {
  370. $pathInfo = substr($pathInfo, 0, -$n);
  371. if ($pathInfo === '') {
  372. // suffix alone is not allowed
  373. return false;
  374. }
  375. } else {
  376. return false;
  377. }
  378. }
  379. if ($this->host !== null) {
  380. $pathInfo = strtolower($request->getHostInfo()) . ($pathInfo === '' ? '' : '/' . $pathInfo);
  381. }
  382. if (!preg_match($this->pattern, $pathInfo, $matches)) {
  383. return false;
  384. }
  385. $matches = $this->substitutePlaceholderNames($matches);
  386. foreach ($this->defaults as $name => $value) {
  387. if (!isset($matches[$name]) || $matches[$name] === '') {
  388. $matches[$name] = $value;
  389. }
  390. }
  391. $params = $this->defaults;
  392. $tr = [];
  393. foreach ($matches as $name => $value) {
  394. if (isset($this->_routeParams[$name])) {
  395. $tr[$this->_routeParams[$name]] = $value;
  396. unset($params[$name]);
  397. } elseif (isset($this->_paramRules[$name])) {
  398. $params[$name] = $value;
  399. }
  400. }
  401. if ($this->_routeRule !== null) {
  402. $route = strtr($this->route, $tr);
  403. } else {
  404. $route = $this->route;
  405. }
  406. Yii::debug("Request parsed with URL rule: {$this->name}", __METHOD__);
  407. if ($normalized) {
  408. // pathInfo was changed by normalizer - we need also normalize route
  409. return $this->getNormalizer($manager)->normalizeRoute([$route, $params]);
  410. }
  411. return [$route, $params];
  412. }
  413. /**
  414. * Creates a URL according to the given route and parameters.
  415. * @param UrlManager $manager the URL manager
  416. * @param string $route the route. It should not have slashes at the beginning or the end.
  417. * @param array $params the parameters
  418. * @return string|bool the created URL, or `false` if this rule cannot be used for creating this URL.
  419. */
  420. public function createUrl($manager, $route, $params)
  421. {
  422. if ($this->mode === self::PARSING_ONLY) {
  423. $this->createStatus = self::CREATE_STATUS_PARSING_ONLY;
  424. return false;
  425. }
  426. $tr = [];
  427. // match the route part first
  428. if ($route !== $this->route) {
  429. if ($this->_routeRule !== null && preg_match($this->_routeRule, $route, $matches)) {
  430. $matches = $this->substitutePlaceholderNames($matches);
  431. foreach ($this->_routeParams as $name => $token) {
  432. if (isset($this->defaults[$name]) && strcmp($this->defaults[$name], $matches[$name]) === 0) {
  433. $tr[$token] = '';
  434. } else {
  435. $tr[$token] = $matches[$name];
  436. }
  437. }
  438. } else {
  439. $this->createStatus = self::CREATE_STATUS_ROUTE_MISMATCH;
  440. return false;
  441. }
  442. }
  443. // match default params
  444. // if a default param is not in the route pattern, its value must also be matched
  445. foreach ($this->defaults as $name => $value) {
  446. if (isset($this->_routeParams[$name])) {
  447. continue;
  448. }
  449. if (!isset($params[$name])) {
  450. // allow omit empty optional params
  451. // @see https://github.com/yiisoft/yii2/issues/10970
  452. if (in_array($name, $this->placeholders) && strcmp($value, '') === 0) {
  453. $params[$name] = '';
  454. } else {
  455. $this->createStatus = self::CREATE_STATUS_PARAMS_MISMATCH;
  456. return false;
  457. }
  458. }
  459. if (strcmp($params[$name], (string) $value) === 0) {
  460. unset($params[$name]);
  461. if (isset($this->_paramRules[$name])) {
  462. $tr["<$name>"] = '';
  463. }
  464. } elseif (!isset($this->_paramRules[$name])) {
  465. $this->createStatus = self::CREATE_STATUS_PARAMS_MISMATCH;
  466. return false;
  467. }
  468. }
  469. // match params in the pattern
  470. foreach ($this->_paramRules as $name => $rule) {
  471. if (isset($params[$name]) && !is_array($params[$name]) && ($rule === '' || preg_match($rule, $params[$name]))) {
  472. $tr["<$name>"] = $this->encodeParams ? urlencode($params[$name]) : $params[$name];
  473. unset($params[$name]);
  474. } elseif (!isset($this->defaults[$name]) || isset($params[$name])) {
  475. $this->createStatus = self::CREATE_STATUS_PARAMS_MISMATCH;
  476. return false;
  477. }
  478. }
  479. $url = $this->trimSlashes(strtr($this->_template, $tr));
  480. if ($this->host !== null) {
  481. $pos = strpos($url, '/', 8);
  482. if ($pos !== false) {
  483. $url = substr($url, 0, $pos) . preg_replace('#/+#', '/', substr($url, $pos));
  484. }
  485. } elseif (strpos($url, '//') !== false) {
  486. $url = preg_replace('#/+#', '/', trim($url, '/'));
  487. }
  488. if ($url !== '') {
  489. $url .= ($this->suffix === null ? $manager->suffix : $this->suffix);
  490. }
  491. if (!empty($params) && ($query = http_build_query($params)) !== '') {
  492. $url .= '?' . $query;
  493. }
  494. $this->createStatus = self::CREATE_STATUS_SUCCESS;
  495. return $url;
  496. }
  497. /**
  498. * Returns status of the URL creation after the last [[createUrl()]] call.
  499. *
  500. * @return int|null Status of the URL creation after the last [[createUrl()]] call. `null` if rule does not provide
  501. * info about create status.
  502. * @see createStatus
  503. * @since 2.0.12
  504. */
  505. public function getCreateUrlStatus()
  506. {
  507. return $this->createStatus;
  508. }
  509. /**
  510. * Returns list of regex for matching parameter.
  511. * @return array parameter keys and regexp rules.
  512. *
  513. * @since 2.0.6
  514. */
  515. protected function getParamRules()
  516. {
  517. return $this->_paramRules;
  518. }
  519. /**
  520. * Iterates over [[placeholders]] and checks whether each placeholder exists as a key in $matches array.
  521. * When found - replaces this placeholder key with a appropriate name of matching parameter.
  522. * Used in [[parseRequest()]], [[createUrl()]].
  523. *
  524. * @param array $matches result of `preg_match()` call
  525. * @return array input array with replaced placeholder keys
  526. * @see placeholders
  527. * @since 2.0.7
  528. */
  529. protected function substitutePlaceholderNames(array $matches)
  530. {
  531. foreach ($this->placeholders as $placeholder => $name) {
  532. if (isset($matches[$placeholder])) {
  533. $matches[$name] = $matches[$placeholder];
  534. unset($matches[$placeholder]);
  535. }
  536. }
  537. return $matches;
  538. }
  539. /**
  540. * Trim slashes in passed string. If string begins with '//', two slashes are left as is
  541. * in the beginning of a string.
  542. *
  543. * @param string $string
  544. * @return string
  545. */
  546. private function trimSlashes($string)
  547. {
  548. if (strncmp($string, '//', 2) === 0) {
  549. return '//' . trim($string, '/');
  550. }
  551. return trim($string, '/');
  552. }
  553. }