CUrlManager.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851
  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. $tr['.']='\\.';
  637. if(strpos($route,'<')!==false && preg_match_all('/<(\w+)>/',$route,$matches2))
  638. {
  639. foreach($matches2[1] as $name)
  640. $this->references[$name]="<$name>";
  641. }
  642. $this->hasHostInfo=!strncasecmp($pattern,'http://',7) || !strncasecmp($pattern,'https://',8);
  643. if($this->verb!==null)
  644. $this->verb=preg_split('/[\s,]+/',strtoupper($this->verb),-1,PREG_SPLIT_NO_EMPTY);
  645. if(preg_match_all('/<(\w+):?(.*?)?>/',$pattern,$matches))
  646. {
  647. $tokens=array_combine($matches[1],$matches[2]);
  648. foreach($tokens as $name=>$value)
  649. {
  650. if($value==='')
  651. $value='[^\/]+';
  652. $tr["<$name>"]="(?P<$name>$value)";
  653. if(isset($this->references[$name]))
  654. $tr2["<$name>"]=$tr["<$name>"];
  655. else
  656. $this->params[$name]=$value;
  657. }
  658. }
  659. $p=rtrim($pattern,'*');
  660. $this->append=$p!==$pattern;
  661. $p=trim($p,'/');
  662. $this->template=preg_replace('/<(\w+):?.*?>/','<$1>',$p);
  663. $this->pattern='/^'.strtr($this->template,$tr).'\/';
  664. if($this->append)
  665. $this->pattern.='/u';
  666. else
  667. $this->pattern.='$/u';
  668. if($this->references!==array())
  669. $this->routePattern='/^'.strtr($this->route,$tr2).'$/u';
  670. if(YII_DEBUG && @preg_match($this->pattern,'test')===false)
  671. throw new CException(Yii::t('yii','The URL pattern "{pattern}" for route "{route}" is not a valid regular expression.',
  672. array('{route}'=>$route,'{pattern}'=>$pattern)));
  673. }
  674. /**
  675. * Creates a URL based on this rule.
  676. * @param CUrlManager $manager the manager
  677. * @param string $route the route
  678. * @param array $params list of parameters
  679. * @param string $ampersand the token separating name-value pairs in the URL.
  680. * @return mixed the constructed URL or false on error
  681. */
  682. public function createUrl($manager,$route,$params,$ampersand)
  683. {
  684. if($this->parsingOnly)
  685. return false;
  686. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  687. $case='';
  688. else
  689. $case='i';
  690. $tr=array();
  691. if($route!==$this->route)
  692. {
  693. if($this->routePattern!==null && preg_match($this->routePattern.$case,$route,$matches))
  694. {
  695. foreach($this->references as $key=>$name)
  696. $tr[$name]=$matches[$key];
  697. }
  698. else
  699. return false;
  700. }
  701. foreach($this->defaultParams as $key=>$value)
  702. {
  703. if(isset($params[$key]))
  704. {
  705. if($params[$key]==$value)
  706. unset($params[$key]);
  707. else
  708. return false;
  709. }
  710. }
  711. foreach($this->params as $key=>$value)
  712. if(!isset($params[$key]))
  713. return false;
  714. if($manager->matchValue && $this->matchValue===null || $this->matchValue)
  715. {
  716. foreach($this->params as $key=>$value)
  717. {
  718. if(!preg_match('/\A'.$value.'\z/u'.$case,$params[$key]))
  719. return false;
  720. }
  721. }
  722. foreach($this->params as $key=>$value)
  723. {
  724. $tr["<$key>"]=urlencode($params[$key]);
  725. unset($params[$key]);
  726. }
  727. $suffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  728. $url=strtr($this->template,$tr);
  729. if($this->hasHostInfo)
  730. {
  731. $hostInfo=Yii::app()->getRequest()->getHostInfo();
  732. if(stripos($url,$hostInfo)===0)
  733. $url=substr($url,strlen($hostInfo));
  734. }
  735. if(empty($params))
  736. return $url!=='' ? $url.$suffix : $url;
  737. if($this->append)
  738. $url.='/'.$manager->createPathInfo($params,'/','/').$suffix;
  739. else
  740. {
  741. if($url!=='')
  742. $url.=$suffix;
  743. $url.='?'.$manager->createPathInfo($params,'=',$ampersand);
  744. }
  745. return $url;
  746. }
  747. /**
  748. * Parses a URL based on this rule.
  749. * @param CUrlManager $manager the URL manager
  750. * @param CHttpRequest $request the request object
  751. * @param string $pathInfo path info part of the URL
  752. * @param string $rawPathInfo path info that contains the potential URL suffix
  753. * @return mixed the route that consists of the controller ID and action ID or false on error
  754. */
  755. public function parseUrl($manager,$request,$pathInfo,$rawPathInfo)
  756. {
  757. if($this->verb!==null && !in_array($request->getRequestType(), $this->verb, true))
  758. return false;
  759. if($manager->caseSensitive && $this->caseSensitive===null || $this->caseSensitive)
  760. $case='';
  761. else
  762. $case='i';
  763. if($this->urlSuffix!==null)
  764. $pathInfo=$manager->removeUrlSuffix($rawPathInfo,$this->urlSuffix);
  765. // URL suffix required, but not found in the requested URL
  766. if($manager->useStrictParsing && $pathInfo===$rawPathInfo)
  767. {
  768. $urlSuffix=$this->urlSuffix===null ? $manager->urlSuffix : $this->urlSuffix;
  769. if($urlSuffix!='' && $urlSuffix!=='/')
  770. return false;
  771. }
  772. if($this->hasHostInfo)
  773. $pathInfo=strtolower($request->getHostInfo()).rtrim('/'.$pathInfo,'/');
  774. $pathInfo.='/';
  775. if(preg_match($this->pattern.$case,$pathInfo,$matches))
  776. {
  777. foreach($this->defaultParams as $name=>$value)
  778. {
  779. if(!isset($_GET[$name]))
  780. $_REQUEST[$name]=$_GET[$name]=$value;
  781. }
  782. $tr=array();
  783. foreach($matches as $key=>$value)
  784. {
  785. if(isset($this->references[$key]))
  786. $tr[$this->references[$key]]=$value;
  787. elseif(isset($this->params[$key]))
  788. $_REQUEST[$key]=$_GET[$key]=$value;
  789. }
  790. if($pathInfo!==$matches[0]) // there're additional GET params
  791. $manager->parsePathInfo(ltrim(substr($pathInfo,strlen($matches[0])),'/'));
  792. if($this->routePattern!==null)
  793. return strtr($this->route,$tr);
  794. else
  795. return $this->route;
  796. }
  797. else
  798. return false;
  799. }
  800. }