PageRenderTime 47ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 0ms

/yii/framework/web/CUrlManager.php

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