PageRenderTime 62ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/yii/framework/web/CUrlManager.php

https://github.com/Mozght/Prdgrp00000001
PHP | 850 lines | 417 code | 51 blank | 382 comment | 92 complexity | 619d847622a43212972fd5554df33816 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-2.1, BSD-2-Clause, LGPL-3.0, GPL-2.0, GPL-3.0
  1. <?php
  2. /**
  3. * CUrlManager class file
  4. *
  5. * @author Qiang Xue <qiang.xue@gmail.com>
  6. * @link http://www.yiiframework.com/
  7. * @copyright 2008-2013 Yii Software LLC
  8. * @license http://www.yiiframework.com/license/
  9. */
  10. /**
  11. * CUrlManager manages the URLs of Yii Web applications.
  12. *
  13. * It provides URL construction ({@link createUrl()}) as well as parsing ({@link parseUrl()}) functionality.
  14. *
  15. * URLs managed via CUrlManager can be in one of the following two formats,
  16. * by setting {@link setUrlFormat urlFormat} property:
  17. * <ul>
  18. * <li>'path' format: /path/to/EntryScript.php/name1/value1/name2/value2...</li>
  19. * <li>'get' format: /path/to/EntryScript.php?name1=value1&name2=value2...</li>
  20. * </ul>
  21. *
  22. * When using 'path' format, CUrlManager uses a set of {@link setRules rules} to:
  23. * <ul>
  24. * <li>parse the requested URL into a route ('ControllerID/ActionID') and GET parameters;</li>
  25. * <li>create URLs based on the given route and GET parameters.</li>
  26. * </ul>
  27. *
  28. * A rule consists of a route and a pattern. The latter is used by CUrlManager to determine
  29. * which rule is used for parsing/creating URLs. A pattern is meant to match the path info
  30. * part of a URL. It may contain named parameters using the syntax '&lt;ParamName:RegExp&gt;'.
  31. *
  32. * When parsing a URL, a matching rule will extract the named parameters from the path info
  33. * and put them into the $_GET variable; when creating a URL, a matching rule will extract
  34. * the named parameters from $_GET and put them into the path info part of the created URL.
  35. *
  36. * If a pattern ends with '/*', it means additional GET parameters may be appended to the path
  37. * info part of the URL; otherwise, the GET parameters can only appear in the query string part.
  38. *
  39. * To specify URL rules, set the {@link setRules rules} property as an array of rules (pattern=>route).
  40. * For example,
  41. * <pre>
  42. * array(
  43. * 'articles'=>'article/list',
  44. * 'article/<id:\d+>/*'=>'article/read',
  45. * )
  46. * </pre>
  47. * Two rules are specified in the above:
  48. * <ul>
  49. * <li>The first rule says that if the user requests the URL '/path/to/index.php/articles',
  50. * it should be treated as '/path/to/index.php/article/list'; and vice versa applies
  51. * when constructing such a URL.</li>
  52. * <li>The second rule contains a named parameter 'id' which is specified using
  53. * the &lt;ParamName:RegExp&gt; syntax. It says that if the user requests the URL
  54. * '/path/to/index.php/article/13', it should be treated as '/path/to/index.php/article/read?id=13';
  55. * and vice versa applies when constructing such a URL.</li>
  56. * </ul>
  57. *
  58. * The route part may contain references to named parameters defined in the pattern part.
  59. * This allows a rule to be applied to different routes based on matching criteria.
  60. * For example,
  61. * <pre>
  62. * array(
  63. * '<_c:(post|comment)>/<id:\d+>/<_a:(create|update|delete)>'=>'<_c>/<_a>',
  64. * '<_c:(post|comment)>/<id:\d+>'=>'<_c>/view',
  65. * '<_c:(post|comment)>s/*'=>'<_c>/list',
  66. * )
  67. * </pre>
  68. * In the above, we use two named parameters '<_c>' and '<_a>' in the route part. The '<_c>'
  69. * parameter matches either 'post' or 'comment', while the '<_a>' parameter matches an action ID.
  70. *
  71. * Like normal rules, these rules can be used for both parsing and creating URLs.
  72. * For example, using the rules above, the URL '/index.php/post/123/create'
  73. * would be parsed as the route 'post/create' with GET parameter 'id' being 123.
  74. * And given the route 'post/list' and GET parameter 'page' being 2, we should get a URL
  75. * '/index.php/posts/page/2'.
  76. *
  77. * It is also possible to include hostname into the rules for parsing and creating URLs.
  78. * One may extract part of the hostname to be a GET parameter.
  79. * For example, the URL <code>http://admin.example.com/en/profile</code> may be parsed into GET parameters
  80. * <code>user=admin</code> and <code>lang=en</code>. On the other hand, rules with hostname may also be used to
  81. * create URLs with parameterized hostnames.
  82. *
  83. * In order to use parameterized hostnames, simply declare URL rules with host info, e.g.:
  84. * <pre>
  85. * array(
  86. * 'http://<user:\w+>.example.com/<lang:\w+>/profile' => 'user/profile',
  87. * )
  88. * </pre>
  89. *
  90. * Starting from version 1.1.8, one can write custom URL rule classes and use them for one or several URL rules.
  91. * For example,
  92. * <pre>
  93. * array(
  94. * // a standard rule
  95. * '<action:(login|logout)>' => 'site/<action>',
  96. * // a custom rule using data in DB
  97. * array(
  98. * 'class' => 'application.components.MyUrlRule',
  99. * 'connectionID' => 'db',
  100. * ),
  101. * )
  102. * </pre>
  103. * Please note that the custom URL rule class should extend from {@link CBaseUrlRule} and
  104. * implement the following two methods,
  105. * <ul>
  106. * <li>{@link CBaseUrlRule::createUrl()}</li>
  107. * <li>{@link CBaseUrlRule::parseUrl()}</li>
  108. * </ul>
  109. *
  110. * CUrlManager is a default application component that may be accessed via
  111. * {@link CWebApplication::getUrlManager()}.
  112. *
  113. * @property string $baseUrl The base URL of the application (the part after host name and before query string).
  114. * If {@link showScriptName} is true, it will include the script name part.
  115. * Otherwise, it will not, and the ending slashes are stripped off.
  116. * @property string $urlFormat The URL format. Defaults to 'path'. Valid values include 'path' and 'get'.
  117. * Please refer to the guide for more details about the difference between these two formats.
  118. *
  119. * @author Qiang Xue <qiang.xue@gmail.com>
  120. * @package system.web
  121. * @since 1.0
  122. */
  123. class CUrlManager extends CApplicationComponent
  124. {
  125. const CACHE_KEY='Yii.CUrlManager.rules';
  126. const GET_FORMAT='get';
  127. const PATH_FORMAT='path';
  128. /**
  129. * @var array the URL rules (pattern=>route).
  130. */
  131. public $rules=array();
  132. /**
  133. * @var string the URL suffix used when in 'path' format.
  134. * For example, ".html" can be used so that the URL looks like pointing to a static HTML page. Defaults to empty.
  135. */
  136. public $urlSuffix='';
  137. /**
  138. * @var boolean whether to show entry script name in the constructed URL. Defaults to true.
  139. */
  140. public $showScriptName=true;
  141. /**
  142. * @var boolean whether to append GET parameters to the path info part. Defaults to true.
  143. * This property is only effective when {@link urlFormat} is 'path' and is mainly used when
  144. * creating URLs. When it is true, GET parameters will be appended to the path info and
  145. * separate from each other using slashes. If this is false, GET parameters will be in query part.
  146. */
  147. public $appendParams=true;
  148. /**
  149. * @var string the GET variable name for route. Defaults to 'r'.
  150. */
  151. public $routeVar='r';
  152. /**
  153. * @var boolean whether routes are case-sensitive. Defaults to true. By setting this to false,
  154. * the route in the incoming request will be turned to lower case first before further processing.
  155. * As a result, you should follow the convention that you use lower case when specifying
  156. * controller mapping ({@link CWebApplication::controllerMap}) and action mapping
  157. * ({@link CController::actions}). Also, the directory names for organizing controllers should
  158. * be in lower case.
  159. */
  160. public $caseSensitive=true;
  161. /**
  162. * @var boolean whether the GET parameter values should match the corresponding
  163. * sub-patterns in a rule before using it to create a URL. Defaults to false, meaning
  164. * a rule will be used for creating a URL only if its route and parameter names match the given ones.
  165. * If this property is set true, then the given parameter values must also match the corresponding
  166. * parameter sub-patterns. Note that setting this property to true will degrade performance.
  167. * @since 1.1.0
  168. */
  169. public $matchValue=false;
  170. /**
  171. * @var string the ID of the cache application component that is used to cache the parsed URL rules.
  172. * Defaults to 'cache' which refers to the primary cache application component.
  173. * Set this property to false if you want to disable caching URL rules.
  174. */
  175. public $cacheID='cache';
  176. /**
  177. * @var boolean whether to enable strict URL parsing.
  178. * This property is only effective when {@link urlFormat} is 'path'.
  179. * If it is set true, then an incoming URL must match one of the {@link rules URL rules}.
  180. * Otherwise, it will be treated as an invalid request and trigger a 404 HTTP exception.
  181. * Defaults to false.
  182. */
  183. public $useStrictParsing=false;
  184. /**
  185. * @var string the class name or path alias for the URL rule instances. Defaults to 'CUrlRule'.
  186. * If you change this to something else, please make sure that the new class must extend from
  187. * {@link CBaseUrlRule} and have the same constructor signature as {@link CUrlRule}.
  188. * It must also be serializable and autoloadable.
  189. * @since 1.1.8
  190. */
  191. public $urlRuleClass='CUrlRule';
  192. private $_urlFormat=self::GET_FORMAT;
  193. private $_rules=array();
  194. private $_baseUrl;
  195. /**
  196. * Initializes the application component.
  197. */
  198. public function init()
  199. {
  200. parent::init();
  201. $this->processRules();
  202. }
  203. /**
  204. * Processes the URL rules.
  205. */
  206. protected function processRules()
  207. {
  208. if(empty($this->rules) || $this->getUrlFormat()===self::GET_FORMAT)
  209. return;
  210. if($this->cacheID!==false && ($cache=Yii::app()->getComponent($this->cacheID))!==null)
  211. {
  212. $hash=md5(serialize($this->rules));
  213. if(($data=$cache->get(self::CACHE_KEY))!==false && isset($data[1]) && $data[1]===$hash)
  214. {
  215. $this->_rules=$data[0];
  216. return;
  217. }
  218. }
  219. foreach($this->rules as $pattern=>$route)
  220. $this->_rules[]=$this->createUrlRule($route,$pattern);
  221. if(isset($cache))
  222. $cache->set(self::CACHE_KEY,array($this->_rules,$hash));
  223. }
  224. /**
  225. * Adds new URL rules.
  226. * In order to make the new rules effective, this method must be called BEFORE
  227. * {@link CWebApplication::processRequest}.
  228. * @param array $rules new URL rules (pattern=>route).
  229. * @param boolean $append whether the new URL rules should be appended to the existing ones. If false,
  230. * they will be inserted at the beginning.
  231. * @since 1.1.4
  232. */
  233. public function addRules($rules,$append=true)
  234. {
  235. if ($append)
  236. {
  237. foreach($rules as $pattern=>$route)
  238. $this->_rules[]=$this->createUrlRule($route,$pattern);
  239. }
  240. else
  241. {
  242. $rules=array_reverse($rules);
  243. foreach($rules as $pattern=>$route)
  244. array_unshift($this->_rules, $this->createUrlRule($route,$pattern));
  245. }
  246. }
  247. /**
  248. * Creates a URL rule instance.
  249. * The default implementation returns a CUrlRule object.
  250. * @param mixed $route the route part of the rule. This could be a string or an array
  251. * @param string $pattern the pattern part of the rule
  252. * @return CUrlRule the URL rule instance
  253. * @since 1.1.0
  254. */
  255. protected function createUrlRule($route,$pattern)
  256. {
  257. if(is_array($route) && isset($route['class']))
  258. return $route;
  259. else
  260. {
  261. $urlRuleClass=Yii::import($this->urlRuleClass,true);
  262. return new $urlRuleClass($route,$pattern);
  263. }
  264. }
  265. /**
  266. * Constructs a URL.
  267. * @param string $route the controller and the action (e.g. article/read)
  268. * @param array $params list of GET parameters (name=>value). Both the name and value will be URL-encoded.
  269. * If the name is '#', the corresponding value will be treated as an anchor
  270. * and will be appended at the end of the URL.
  271. * @param string $ampersand the token separating name-value pairs in the URL. Defaults to '&'.
  272. * @return string the constructed URL
  273. */
  274. public function createUrl($route,$params=array(),$ampersand='&')
  275. {
  276. unset($params[$this->routeVar]);
  277. foreach($params as $i=>$param)
  278. if($param===null)
  279. $params[$i]='';
  280. if(isset($params['#']))
  281. {
  282. $anchor='#'.$params['#'];
  283. unset($params['#']);
  284. }
  285. else
  286. $anchor='';
  287. $route=trim($route,'/');
  288. foreach($this->_rules as $i=>$rule)
  289. {
  290. if(is_array($rule))
  291. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  292. if(($url=$rule->createUrl($this,$route,$params,$ampersand))!==false)
  293. {
  294. if($rule->hasHostInfo)
  295. return $url==='' ? '/'.$anchor : $url.$anchor;
  296. else
  297. return $this->getBaseUrl().'/'.$url.$anchor;
  298. }
  299. }
  300. return $this->createUrlDefault($route,$params,$ampersand).$anchor;
  301. }
  302. /**
  303. * Creates a URL based on default settings.
  304. * @param string $route the controller and the action (e.g. article/read)
  305. * @param array $params list of GET parameters
  306. * @param string $ampersand the token separating name-value pairs in the URL.
  307. * @return string the constructed URL
  308. */
  309. protected function createUrlDefault($route,$params,$ampersand)
  310. {
  311. if($this->getUrlFormat()===self::PATH_FORMAT)
  312. {
  313. $url=rtrim($this->getBaseUrl().'/'.$route,'/');
  314. if($this->appendParams)
  315. {
  316. $url=rtrim($url.'/'.$this->createPathInfo($params,'/','/'),'/');
  317. return $route==='' ? $url : $url.$this->urlSuffix;
  318. }
  319. else
  320. {
  321. if($route!=='')
  322. $url.=$this->urlSuffix;
  323. $query=$this->createPathInfo($params,'=',$ampersand);
  324. return $query==='' ? $url : $url.'?'.$query;
  325. }
  326. }
  327. else
  328. {
  329. $url=$this->getBaseUrl();
  330. if(!$this->showScriptName)
  331. $url.='/';
  332. if($route!=='')
  333. {
  334. $url.='?'.$this->routeVar.'='.$route;
  335. if(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  336. $url.=$ampersand.$query;
  337. }
  338. elseif(($query=$this->createPathInfo($params,'=',$ampersand))!=='')
  339. $url.='?'.$query;
  340. return $url;
  341. }
  342. }
  343. /**
  344. * Parses the user request.
  345. * @param CHttpRequest $request the request application component
  346. * @return string the route (controllerID/actionID) and perhaps GET parameters in path format.
  347. */
  348. public function parseUrl($request)
  349. {
  350. if($this->getUrlFormat()===self::PATH_FORMAT)
  351. {
  352. $rawPathInfo=$request->getPathInfo();
  353. $pathInfo=$this->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  354. foreach($this->_rules as $i=>$rule)
  355. {
  356. if(is_array($rule))
  357. $this->_rules[$i]=$rule=Yii::createComponent($rule);
  358. if(($r=$rule->parseUrl($this,$request,$pathInfo,$rawPathInfo))!==false)
  359. return isset($_GET[$this->routeVar]) ? $_GET[$this->routeVar] : $r;
  360. }
  361. if($this->useStrictParsing)
  362. throw new CHttpException(404,Yii::t('yii','Unable to resolve the request "{route}".',
  363. array('{route}'=>$pathInfo)));
  364. else
  365. return $pathInfo;
  366. }
  367. elseif(isset($_GET[$this->routeVar]))
  368. return $_GET[$this->routeVar];
  369. elseif(isset($_POST[$this->routeVar]))
  370. return $_POST[$this->routeVar];
  371. else
  372. return '';
  373. }
  374. /**
  375. * Parses a path info into URL segments and saves them to $_GET and $_REQUEST.
  376. * @param string $pathInfo path info
  377. */
  378. public function parsePathInfo($pathInfo)
  379. {
  380. if($pathInfo==='')
  381. return;
  382. $segs=explode('/',$pathInfo.'/');
  383. $n=count($segs);
  384. for($i=0;$i<$n-1;$i+=2)
  385. {
  386. $key=$segs[$i];
  387. if($key==='') continue;
  388. $value=$segs[$i+1];
  389. if(($pos=strpos($key,'['))!==false && ($m=preg_match_all('/\[(.*?)\]/',$key,$matches))>0)
  390. {
  391. $name=substr($key,0,$pos);
  392. for($j=$m-1;$j>=0;--$j)
  393. {
  394. if($matches[1][$j]==='')
  395. $value=array($value);
  396. else
  397. $value=array($matches[1][$j]=>$value);
  398. }
  399. if(isset($_GET[$name]) && is_array($_GET[$name]))
  400. $value=CMap::mergeArray($_GET[$name],$value);
  401. $_REQUEST[$name]=$_GET[$name]=$value;
  402. }
  403. else
  404. $_REQUEST[$key]=$_GET[$key]=$value;
  405. }
  406. }
  407. /**
  408. * Creates a path info based on the given parameters.
  409. * @param array $params list of GET parameters
  410. * @param string $equal the separator between name and value
  411. * @param string $ampersand the separator between name-value pairs
  412. * @param string $key this is used internally.
  413. * @return string the created path info
  414. */
  415. public function createPathInfo($params,$equal,$ampersand, $key=null)
  416. {
  417. $pairs = array();
  418. foreach($params as $k => $v)
  419. {
  420. if ($key!==null)
  421. $k = $key.'['.$k.']';
  422. if (is_array($v))
  423. $pairs[]=$this->createPathInfo($v,$equal,$ampersand, $k);
  424. else
  425. $pairs[]=urlencode($k).$equal.urlencode($v);
  426. }
  427. return implode($ampersand,$pairs);
  428. }
  429. /**
  430. * Removes the URL suffix from path info.
  431. * @param string $pathInfo path info part in the URL
  432. * @param string $urlSuffix the URL suffix to be removed
  433. * @return string path info with URL suffix removed.
  434. */
  435. public function removeUrlSuffix($pathInfo,$urlSuffix)
  436. {
  437. if($urlSuffix!=='' && substr($pathInfo,-strlen($urlSuffix))===$urlSuffix)
  438. return substr($pathInfo,0,-strlen($urlSuffix));
  439. else
  440. return $pathInfo;
  441. }
  442. /**
  443. * Returns the base URL of the application.
  444. * @return string the base URL of the application (the part after host name and before query string).
  445. * If {@link showScriptName} is true, it will include the script name part.
  446. * Otherwise, it will not, and the ending slashes are stripped off.
  447. */
  448. public function getBaseUrl()
  449. {
  450. if($this->_baseUrl!==null)
  451. return $this->_baseUrl;
  452. else
  453. {
  454. if($this->showScriptName)
  455. $this->_baseUrl=Yii::app()->getRequest()->getScriptUrl();
  456. else
  457. $this->_baseUrl=Yii::app()->getRequest()->getBaseUrl();
  458. return $this->_baseUrl;
  459. }
  460. }
  461. /**
  462. * Sets the base URL of the application (the part after host name and before query string).
  463. * This method is provided in case the {@link baseUrl} cannot be determined automatically.
  464. * The ending slashes should be stripped off. And you are also responsible to remove the script name
  465. * if you set {@link showScriptName} to be false.
  466. * @param string $value the base URL of the application
  467. * @since 1.1.1
  468. */
  469. public function setBaseUrl($value)
  470. {
  471. $this->_baseUrl=$value;
  472. }
  473. /**
  474. * Returns the URL format.
  475. * @return string the URL format. Defaults to 'path'. Valid values include 'path' and 'get'.
  476. * Please refer to the guide for more details about the difference between these two formats.
  477. */
  478. public function getUrlFormat()
  479. {
  480. return $this->_urlFormat;
  481. }
  482. /**
  483. * Sets the URL format.
  484. * @param string $value the URL format. It must be either 'path' or 'get'.
  485. */
  486. public function setUrlFormat($value)
  487. {
  488. if($value===self::PATH_FORMAT || $value===self::GET_FORMAT)
  489. $this->_urlFormat=$value;
  490. else
  491. throw new CException(Yii::t('yii','CUrlManager.UrlFormat must be either "path" or "get".'));
  492. }
  493. }
  494. /**
  495. * CBaseUrlRule is the base class for a URL rule class.
  496. *
  497. * Custom URL rule classes should extend from this class and implement two methods:
  498. * {@link createUrl} and {@link parseUrl}.
  499. *
  500. * @author Qiang Xue <qiang.xue@gmail.com>
  501. * @package system.web
  502. * @since 1.1.8
  503. */
  504. abstract class CBaseUrlRule extends CComponent
  505. {
  506. /**
  507. * @var boolean whether this rule will also parse the host info part. Defaults to false.
  508. */
  509. public $hasHostInfo=false;
  510. /**
  511. * Creates a URL based on this rule.
  512. * @param CUrlManager $manager the manager
  513. * @param string $route the route
  514. * @param array $params list of parameters (name=>value) associated with the route
  515. * @param string $ampersand the token separating name-value pairs in the URL.
  516. * @return mixed the constructed URL. False if this rule does not apply.
  517. */
  518. abstract public function createUrl($manager,$route,$params,$ampersand);
  519. /**
  520. * Parses a URL based on this rule.
  521. * @param CUrlManager $manager the URL manager
  522. * @param CHttpRequest $request the request object
  523. * @param string $pathInfo path info part of the URL (URL suffix is already removed based on {@link CUrlManager::urlSuffix})
  524. * @param string $rawPathInfo path info that contains the potential URL suffix
  525. * @return mixed the route that consists of the controller ID and action ID. False if this rule does not apply.
  526. */
  527. abstract public function parseUrl($manager,$request,$pathInfo,$rawPathInfo);
  528. }
  529. /**
  530. * CUrlRule represents a URL formatting/parsing rule.
  531. *
  532. * It mainly consists of two parts: route and pattern. The former classifies
  533. * the rule so that it only applies to specific controller-action route.
  534. * The latter performs the actual formatting and parsing role. The pattern
  535. * may have a set of named parameters.
  536. *
  537. * @author Qiang Xue <qiang.xue@gmail.com>
  538. * @package system.web
  539. * @since 1.0
  540. */
  541. class CUrlRule extends CBaseUrlRule
  542. {
  543. /**
  544. * @var string the URL suffix used for this rule.
  545. * For example, ".html" can be used so that the URL looks like pointing to a static HTML page.
  546. * Defaults to null, meaning using the value of {@link CUrlManager::urlSuffix}.
  547. */
  548. public $urlSuffix;
  549. /**
  550. * @var boolean whether the rule is case sensitive. Defaults to null, meaning
  551. * using the value of {@link CUrlManager::caseSensitive}.
  552. */
  553. public $caseSensitive;
  554. /**
  555. * @var array the default GET parameters (name=>value) that this rule provides.
  556. * When this rule is used to parse the incoming request, the values declared in this property
  557. * will be injected into $_GET.
  558. */
  559. public $defaultParams=array();
  560. /**
  561. * @var boolean whether the GET parameter values should match the corresponding
  562. * sub-patterns in the rule when creating a URL. Defaults to null, meaning using the value
  563. * of {@link CUrlManager::matchValue}. When this property is false, it means
  564. * a rule will be used for creating a URL if its route and parameter names match the given ones.
  565. * If this property is set true, then the given parameter values must also match the corresponding
  566. * parameter sub-patterns. Note that setting this property to true will degrade performance.
  567. * @since 1.1.0
  568. */
  569. public $matchValue;
  570. /**
  571. * @var string the HTTP verb (e.g. GET, POST, DELETE) that this rule should match.
  572. * If this rule can match multiple verbs, please separate them with commas.
  573. * If this property is not set, the rule can match any verb.
  574. * Note that this property is only used when parsing a request. It is ignored for URL creation.
  575. * @since 1.1.7
  576. */
  577. public $verb;
  578. /**
  579. * @var boolean whether this rule is only used for request parsing.
  580. * Defaults to false, meaning the rule is used for both URL parsing and creation.
  581. * @since 1.1.7
  582. */
  583. public $parsingOnly=false;
  584. /**
  585. * @var string the controller/action pair
  586. */
  587. public $route;
  588. /**
  589. * @var array the mapping from route param name to token name (e.g. _r1=><1>)
  590. */
  591. public $references=array();
  592. /**
  593. * @var string the pattern used to match route
  594. */
  595. public $routePattern;
  596. /**
  597. * @var string regular expression used to parse a URL
  598. */
  599. public $pattern;
  600. /**
  601. * @var string template used to construct a URL
  602. */
  603. public $template;
  604. /**
  605. * @var array list of parameters (name=>regular expression)
  606. */
  607. public $params=array();
  608. /**
  609. * @var boolean whether the URL allows additional parameters at the end of the path info.
  610. */
  611. public $append;
  612. /**
  613. * @var boolean whether host info should be considered for this rule
  614. */
  615. public $hasHostInfo;
  616. /**
  617. * Constructor.
  618. * @param string $route the route of the URL (controller/action)
  619. * @param string $pattern the pattern for matching the URL
  620. */
  621. public function __construct($route,$pattern)
  622. {
  623. if(is_array($route))
  624. {
  625. foreach(array('urlSuffix', 'caseSensitive', 'defaultParams', 'matchValue', 'verb', 'parsingOnly') as $name)
  626. {
  627. if(isset($route[$name]))
  628. $this->$name=$route[$name];
  629. }
  630. if(isset($route['pattern']))
  631. $pattern=$route['pattern'];
  632. $route=$route[0];
  633. }
  634. $this->route=trim($route,'/');
  635. $tr2['/']=$tr['/']='\\/';
  636. if(strpos($route,'<')!==false && preg_match_all('/<(\w+)>/',$route,$matches2))
  637. {
  638. foreach($matches2[1] as $name)
  639. $this->references[$name]="<$name>";
  640. }
  641. $this->hasHostInfo=!strncasecmp($pattern,'http://',7) || !strncasecmp($pattern,'https://',8);
  642. if($this->verb!==null)
  643. $this->verb=preg_split('/[\s,]+/',strtoupper($this->verb),-1,PREG_SPLIT_NO_EMPTY);
  644. if(preg_match_all('/<(\w+):?(.*?)?>/',$pattern,$matches))
  645. {
  646. $tokens=array_combine($matches[1],$matches[2]);
  647. foreach($tokens as $name=>$value)
  648. {
  649. if($value==='')
  650. $value='[^\/]+';
  651. $tr["<$name>"]="(?P<$name>$value)";
  652. if(isset($this->references[$name]))
  653. $tr2["<$name>"]=$tr["<$name>"];
  654. else
  655. $this->params[$name]=$value;
  656. }
  657. }
  658. $p=rtrim($pattern,'*');
  659. $this->append=$p!==$pattern;
  660. $p=trim($p,'/');
  661. $this->template=preg_replace('/<(\w+):?.*?>/','<$1>',$p);
  662. $this->pattern='/^'.strtr($this->template,$tr).'\/';
  663. if($this->append)
  664. $this->pattern.='/u';
  665. else
  666. $this->pattern.='$/u';
  667. if($this->references!==array())
  668. $this->routePattern='/^'.strtr($this->route,$tr2).'$/u';
  669. if(YII_DEBUG && @preg_match($this->pattern,'test')===false)
  670. throw new CException(Yii::t('yii','The URL pattern "{pattern}" for route "{route}" is not a valid regular expression.',
  671. array('{route}'=>$route,'{pattern}'=>$pattern)));
  672. }
  673. /**
  674. * Creates a URL based on this rule.
  675. * @param CUrlManager $manager the manager
  676. * @param string $route the route
  677. * @param array $params list of parameters
  678. * @param string $ampersand the token separating name-value pairs in the URL.
  679. * @return mixed the constructed URL or false on error
  680. */
  681. public function createUrl($manager,$route,$params,$ampersand)
  682. {
  683. if($this->parsingOnly)
  684. return false;
  685. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  686. $case='';
  687. else
  688. $case='i';
  689. $tr=array();
  690. if($route!==$this->route)
  691. {
  692. if($this->routePattern!==null && preg_match($this->routePattern.$case,$route,$matches))
  693. {
  694. foreach($this->references as $key=>$name)
  695. $tr[$name]=$matches[$key];
  696. }
  697. else
  698. return false;
  699. }
  700. foreach($this->defaultParams as $key=>$value)
  701. {
  702. if(isset($params[$key]))
  703. {
  704. if($params[$key]==$value)
  705. unset($params[$key]);
  706. else
  707. return false;
  708. }
  709. }
  710. foreach($this->params as $key=>$value)
  711. if(!isset($params[$key]))
  712. return false;
  713. if($manager->matchValue && $this->matchValue===null || $this->matchValue)
  714. {
  715. foreach($this->params as $key=>$value)
  716. {
  717. if(!preg_match('/\A'.$value.'\z/u'.$case,$params[$key]))
  718. return false;
  719. }
  720. }
  721. foreach($this->params as $key=>$value)
  722. {
  723. $tr["<$key>"]=urlencode($params[$key]);
  724. unset($params[$key]);
  725. }
  726. $suffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  727. $url=strtr($this->template,$tr);
  728. if($this->hasHostInfo)
  729. {
  730. $hostInfo=Yii::app()->getRequest()->getHostInfo();
  731. if(stripos($url,$hostInfo)===0)
  732. $url=substr($url,strlen($hostInfo));
  733. }
  734. if(empty($params))
  735. return $url!=='' ? $url.$suffix : $url;
  736. if($this->append)
  737. $url.='/'.$manager->createPathInfo($params,'/','/').$suffix;
  738. else
  739. {
  740. if($url!=='')
  741. $url.=$suffix;
  742. $url.='?'.$manager->createPathInfo($params,'=',$ampersand);
  743. }
  744. return $url;
  745. }
  746. /**
  747. * Parses a URL based on this rule.
  748. * @param CUrlManager $manager the URL manager
  749. * @param CHttpRequest $request the request object
  750. * @param string $pathInfo path info part of the URL
  751. * @param string $rawPathInfo path info that contains the potential URL suffix
  752. * @return mixed the route that consists of the controller ID and action ID or false on error
  753. */
  754. public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)
  755. {
  756. if($this->verb!==null && !in_array($request->getRequestType(), $this->verb, true))
  757. return false;
  758. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  759. $case='';
  760. else
  761. $case='i';
  762. if($this->urlSuffix!==null)
  763. $pathInfo=$manager->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  764. // URL suffix required, but not found in the requested URL
  765. if($manager->useStrictParsing && $pathInfo===$rawPathInfo)
  766. {
  767. $urlSuffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  768. if($urlSuffix!='' && $urlSuffix!=='/')
  769. return false;
  770. }
  771. if($this->hasHostInfo)
  772. $pathInfo=strtolower($request->getHostInfo()).rtrim('/'.$pathInfo,'/');
  773. $pathInfo.='/';
  774. if(preg_match($this->pattern.$case,$pathInfo,$matches))
  775. {
  776. foreach($this->defaultParams as $name=>$value)
  777. {
  778. if(!isset($_GET[$name]))
  779. $_REQUEST[$name]=$_GET[$name]=$value;
  780. }
  781. $tr=array();
  782. foreach($matches as $key=>$value)
  783. {
  784. if(isset($this->references[$key]))
  785. $tr[$this->references[$key]]=$value;
  786. elseif(isset($this->params[$key]))
  787. $_REQUEST[$key]=$_GET[$key]=$value;
  788. }
  789. if($pathInfo!==$matches[0]) // there're additional GET params
  790. $manager->parsePathInfo(ltrim(substr($pathInfo,strlen($matches[0])),'/'));
  791. if($this->routePattern!==null)
  792. return strtr($this->route,$tr);
  793. else
  794. return $this->route;
  795. }
  796. else
  797. return false;
  798. }
  799. }