444 lines
16KB

  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\Object;
  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. * @author Qiang Xue <qiang.xue@gmail.com>
  25. * @since 2.0
  26. */
  27. class UrlRule extends Object implements UrlRuleInterface
  28. {
  29. /**
  30. * Set [[mode]] with this value to mark that this rule is for URL parsing only
  31. */
  32. const PARSING_ONLY = 1;
  33. /**
  34. * Set [[mode]] with this value to mark that this rule is for URL creation only
  35. */
  36. const CREATION_ONLY = 2;
  37. /**
  38. * @var string the name of this rule. If not set, it will use [[pattern]] as the name.
  39. */
  40. public $name;
  41. /**
  42. * On the rule initialization, the [[pattern]] matching parameters names will be replaced with [[placeholders]].
  43. * @var string the pattern used to parse and create the path info part of a URL.
  44. * @see host
  45. * @see placeholders
  46. */
  47. public $pattern;
  48. /**
  49. * @var string the pattern used to parse and create the host info part of a URL (e.g. `http://example.com`).
  50. * @see pattern
  51. */
  52. public $host;
  53. /**
  54. * @var string the route to the controller action
  55. */
  56. public $route;
  57. /**
  58. * @var array the default GET parameters (name => value) that this rule provides.
  59. * When this rule is used to parse the incoming request, the values declared in this property
  60. * will be injected into $_GET.
  61. */
  62. public $defaults = [];
  63. /**
  64. * @var string the URL suffix used for this rule.
  65. * For example, ".html" can be used so that the URL looks like pointing to a static HTML page.
  66. * If not, the value of [[UrlManager::suffix]] will be used.
  67. */
  68. public $suffix;
  69. /**
  70. * @var string|array the HTTP verb (e.g. GET, POST, DELETE) that this rule should match.
  71. * Use array to represent multiple verbs that this rule may match.
  72. * If this property is not set, the rule can match any verb.
  73. * Note that this property is only used when parsing a request. It is ignored for URL creation.
  74. */
  75. public $verb;
  76. /**
  77. * @var integer a value indicating if this rule should be used for both request parsing and URL creation,
  78. * parsing only, or creation only.
  79. * If not set or 0, it means the rule is both request parsing and URL creation.
  80. * If it is [[PARSING_ONLY]], the rule is for request parsing only.
  81. * If it is [[CREATION_ONLY]], the rule is for URL creation only.
  82. */
  83. public $mode;
  84. /**
  85. * @var boolean a value indicating if parameters should be url encoded.
  86. */
  87. public $encodeParams = true;
  88. /**
  89. * @var UrlNormalizer|array|false|null the configuration for [[UrlNormalizer]] used by this rule.
  90. * If `null`, [[UrlManager::normalizer]] will be used, if `false`, normalization will be skipped
  91. * for this rule.
  92. * @since 2.0.10
  93. */
  94. public $normalizer;
  95. /**
  96. * @var array list of placeholders for matching parameters names. Used in [[parseRequest()]], [[createUrl()]].
  97. * On the rule initialization, the [[pattern]] parameters names will be replaced with placeholders.
  98. * This array contains relations between the original parameters names and their placeholders.
  99. * The array keys are the placeholders and the values are the original names.
  100. *
  101. * @see parseRequest()
  102. * @see createUrl()
  103. * @since 2.0.7
  104. */
  105. protected $placeholders = [];
  106. /**
  107. * @var string the template for generating a new URL. This is derived from [[pattern]] and is used in generating URL.
  108. */
  109. private $_template;
  110. /**
  111. * @var string the regex for matching the route part. This is used in generating URL.
  112. */
  113. private $_routeRule;
  114. /**
  115. * @var array list of regex for matching parameters. This is used in generating URL.
  116. */
  117. private $_paramRules = [];
  118. /**
  119. * @var array list of parameters used in the route.
  120. */
  121. private $_routeParams = [];
  122. /**
  123. * Initializes this rule.
  124. */
  125. public function init()
  126. {
  127. if ($this->pattern === null) {
  128. throw new InvalidConfigException('UrlRule::pattern must be set.');
  129. }
  130. if ($this->route === null) {
  131. throw new InvalidConfigException('UrlRule::route must be set.');
  132. }
  133. if (is_array($this->normalizer)) {
  134. $normalizerConfig = array_merge(['class' => UrlNormalizer::className()], $this->normalizer);
  135. $this->normalizer = Yii::createObject($normalizerConfig);
  136. }
  137. if ($this->normalizer !== null && $this->normalizer !== false && !$this->normalizer instanceof UrlNormalizer) {
  138. throw new InvalidConfigException('Invalid config for UrlRule::normalizer.');
  139. }
  140. if ($this->verb !== null) {
  141. if (is_array($this->verb)) {
  142. foreach ($this->verb as $i => $verb) {
  143. $this->verb[$i] = strtoupper($verb);
  144. }
  145. } else {
  146. $this->verb = [strtoupper($this->verb)];
  147. }
  148. }
  149. if ($this->name === null) {
  150. $this->name = $this->pattern;
  151. }
  152. $this->pattern = trim($this->pattern, '/');
  153. $this->route = trim($this->route, '/');
  154. if ($this->host !== null) {
  155. $this->host = rtrim($this->host, '/');
  156. $this->pattern = rtrim($this->host . '/' . $this->pattern, '/');
  157. } elseif ($this->pattern === '') {
  158. $this->_template = '';
  159. $this->pattern = '#^$#u';
  160. return;
  161. } elseif (($pos = strpos($this->pattern, '://')) !== false) {
  162. if (($pos2 = strpos($this->pattern, '/', $pos + 3)) !== false) {
  163. $this->host = substr($this->pattern, 0, $pos2);
  164. } else {
  165. $this->host = $this->pattern;
  166. }
  167. } else {
  168. $this->pattern = '/' . $this->pattern . '/';
  169. }
  170. if (strpos($this->route, '<') !== false && preg_match_all('/<([\w._-]+)>/', $this->route, $matches)) {
  171. foreach ($matches[1] as $name) {
  172. $this->_routeParams[$name] = "<$name>";
  173. }
  174. }
  175. $tr = [
  176. '.' => '\\.',
  177. '*' => '\\*',
  178. '$' => '\\$',
  179. '[' => '\\[',
  180. ']' => '\\]',
  181. '(' => '\\(',
  182. ')' => '\\)',
  183. ];
  184. $tr2 = [];
  185. if (preg_match_all('/<([\w._-]+):?([^>]+)?>/', $this->pattern, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER)) {
  186. foreach ($matches as $match) {
  187. $name = $match[1][0];
  188. $pattern = isset($match[2][0]) ? $match[2][0] : '[^\/]+';
  189. $placeholder = 'a' . hash('crc32b', $name); // placeholder must begin with a letter
  190. $this->placeholders[$placeholder] = $name;
  191. if (array_key_exists($name, $this->defaults)) {
  192. $length = strlen($match[0][0]);
  193. $offset = $match[0][1];
  194. if ($offset > 1 && $this->pattern[$offset - 1] === '/' && (!isset($this->pattern[$offset + $length]) || $this->pattern[$offset + $length] === '/')) {
  195. $tr["/<$name>"] = "(/(?P<$placeholder>$pattern))?";
  196. } else {
  197. $tr["<$name>"] = "(?P<$placeholder>$pattern)?";
  198. }
  199. } else {
  200. $tr["<$name>"] = "(?P<$placeholder>$pattern)";
  201. }
  202. if (isset($this->_routeParams[$name])) {
  203. $tr2["<$name>"] = "(?P<$placeholder>$pattern)";
  204. } else {
  205. $this->_paramRules[$name] = $pattern === '[^\/]+' ? '' : "#^$pattern$#u";
  206. }
  207. }
  208. }
  209. $this->_template = preg_replace('/<([\w._-]+):?([^>]+)?>/', '<$1>', $this->pattern);
  210. $this->pattern = '#^' . trim(strtr($this->_template, $tr), '/') . '$#u';
  211. if (!empty($this->_routeParams)) {
  212. $this->_routeRule = '#^' . strtr($this->route, $tr2) . '$#u';
  213. }
  214. }
  215. /**
  216. * @param UrlManager $manager the URL manager
  217. * @return UrlNormalizer|null
  218. * @since 2.0.10
  219. */
  220. protected function getNormalizer($manager)
  221. {
  222. if ($this->normalizer === null) {
  223. return $manager->normalizer;
  224. } else {
  225. return $this->normalizer;
  226. }
  227. }
  228. /**
  229. * @param UrlManager $manager the URL manager
  230. * @return boolean
  231. * @since 2.0.10
  232. */
  233. protected function hasNormalizer($manager)
  234. {
  235. return $this->getNormalizer($manager) instanceof UrlNormalizer;
  236. }
  237. /**
  238. * Parses the given request and returns the corresponding route and parameters.
  239. * @param UrlManager $manager the URL manager
  240. * @param Request $request the request component
  241. * @return array|boolean the parsing result. The route and the parameters are returned as an array.
  242. * If `false`, it means this rule cannot be used to parse this path info.
  243. */
  244. public function parseRequest($manager, $request)
  245. {
  246. if ($this->mode === self::CREATION_ONLY) {
  247. return false;
  248. }
  249. if (!empty($this->verb) && !in_array($request->getMethod(), $this->verb, true)) {
  250. return false;
  251. }
  252. $suffix = (string)($this->suffix === null ? $manager->suffix : $this->suffix);
  253. $pathInfo = $request->getPathInfo();
  254. $normalized = false;
  255. if ($this->hasNormalizer($manager)) {
  256. $pathInfo = $this->getNormalizer($manager)->normalizePathInfo($pathInfo, $suffix, $normalized);
  257. }
  258. if ($suffix !== '' && $pathInfo !== '') {
  259. $n = strlen($suffix);
  260. if (substr_compare($pathInfo, $suffix, -$n, $n) === 0) {
  261. $pathInfo = substr($pathInfo, 0, -$n);
  262. if ($pathInfo === '') {
  263. // suffix alone is not allowed
  264. return false;
  265. }
  266. } else {
  267. return false;
  268. }
  269. }
  270. if ($this->host !== null) {
  271. $pathInfo = strtolower($request->getHostInfo()) . ($pathInfo === '' ? '' : '/' . $pathInfo);
  272. }
  273. if (!preg_match($this->pattern, $pathInfo, $matches)) {
  274. return false;
  275. }
  276. $matches = $this->substitutePlaceholderNames($matches);
  277. foreach ($this->defaults as $name => $value) {
  278. if (!isset($matches[$name]) || $matches[$name] === '') {
  279. $matches[$name] = $value;
  280. }
  281. }
  282. $params = $this->defaults;
  283. $tr = [];
  284. foreach ($matches as $name => $value) {
  285. if (isset($this->_routeParams[$name])) {
  286. $tr[$this->_routeParams[$name]] = $value;
  287. unset($params[$name]);
  288. } elseif (isset($this->_paramRules[$name])) {
  289. $params[$name] = $value;
  290. }
  291. }
  292. if ($this->_routeRule !== null) {
  293. $route = strtr($this->route, $tr);
  294. } else {
  295. $route = $this->route;
  296. }
  297. Yii::trace("Request parsed with URL rule: {$this->name}", __METHOD__);
  298. if ($normalized) {
  299. // pathInfo was changed by normalizer - we need also normalize route
  300. return $this->getNormalizer($manager)->normalizeRoute([$route, $params]);
  301. } else {
  302. return [$route, $params];
  303. }
  304. }
  305. /**
  306. * Creates a URL according to the given route and parameters.
  307. * @param UrlManager $manager the URL manager
  308. * @param string $route the route. It should not have slashes at the beginning or the end.
  309. * @param array $params the parameters
  310. * @return string|boolean the created URL, or `false` if this rule cannot be used for creating this URL.
  311. */
  312. public function createUrl($manager, $route, $params)
  313. {
  314. if ($this->mode === self::PARSING_ONLY) {
  315. return false;
  316. }
  317. $tr = [];
  318. // match the route part first
  319. if ($route !== $this->route) {
  320. if ($this->_routeRule !== null && preg_match($this->_routeRule, $route, $matches)) {
  321. $matches = $this->substitutePlaceholderNames($matches);
  322. foreach ($this->_routeParams as $name => $token) {
  323. if (isset($this->defaults[$name]) && strcmp($this->defaults[$name], $matches[$name]) === 0) {
  324. $tr[$token] = '';
  325. } else {
  326. $tr[$token] = $matches[$name];
  327. }
  328. }
  329. } else {
  330. return false;
  331. }
  332. }
  333. // match default params
  334. // if a default param is not in the route pattern, its value must also be matched
  335. foreach ($this->defaults as $name => $value) {
  336. if (isset($this->_routeParams[$name])) {
  337. continue;
  338. }
  339. if (!isset($params[$name])) {
  340. return false;
  341. } elseif (strcmp($params[$name], $value) === 0) { // strcmp will do string conversion automatically
  342. unset($params[$name]);
  343. if (isset($this->_paramRules[$name])) {
  344. $tr["<$name>"] = '';
  345. }
  346. } elseif (!isset($this->_paramRules[$name])) {
  347. return false;
  348. }
  349. }
  350. // match params in the pattern
  351. foreach ($this->_paramRules as $name => $rule) {
  352. if (isset($params[$name]) && !is_array($params[$name]) && ($rule === '' || preg_match($rule, $params[$name]))) {
  353. $tr["<$name>"] = $this->encodeParams ? urlencode($params[$name]) : $params[$name];
  354. unset($params[$name]);
  355. } elseif (!isset($this->defaults[$name]) || isset($params[$name])) {
  356. return false;
  357. }
  358. }
  359. $url = trim(strtr($this->_template, $tr), '/');
  360. if ($this->host !== null) {
  361. $pos = strpos($url, '/', 8);
  362. if ($pos !== false) {
  363. $url = substr($url, 0, $pos) . preg_replace('#/+#', '/', substr($url, $pos));
  364. }
  365. } elseif (strpos($url, '//') !== false) {
  366. $url = preg_replace('#/+#', '/', $url);
  367. }
  368. if ($url !== '') {
  369. $url .= ($this->suffix === null ? $manager->suffix : $this->suffix);
  370. }
  371. if (!empty($params) && ($query = http_build_query($params)) !== '') {
  372. $url .= '?' . $query;
  373. }
  374. return $url;
  375. }
  376. /**
  377. * Returns list of regex for matching parameter.
  378. * @return array parameter keys and regexp rules.
  379. *
  380. * @since 2.0.6
  381. */
  382. protected function getParamRules()
  383. {
  384. return $this->_paramRules;
  385. }
  386. /**
  387. * Iterates over [[placeholders]] and checks whether each placeholder exists as a key in $matches array.
  388. * When found - replaces this placeholder key with a appropriate name of matching parameter.
  389. * Used in [[parseRequest()]], [[createUrl()]].
  390. *
  391. * @param array $matches result of `preg_match()` call
  392. * @return array input array with replaced placeholder keys
  393. * @see placeholders
  394. * @since 2.0.7
  395. */
  396. protected function substitutePlaceholderNames(array $matches)
  397. {
  398. foreach ($this->placeholders as $placeholder => $name) {
  399. if (isset($matches[$placeholder])) {
  400. $matches[$name] = $matches[$placeholder];
  401. unset($matches[$placeholder]);
  402. }
  403. }
  404. return $matches;
  405. }
  406. }