PageRenderTime 51ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/yii/framework/web/CHttpRequest.php

https://github.com/joshuaswarren/weatherhub
PHP | 999 lines | 820 code | 22 blank | 157 comment | 39 complexity | 0c5c36d4905ab3097a49fde820aada1b MD5 | raw file
  1. <?php
  2. /**
  3. * CHttpRequest and CCookieCollection 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. * CHttpRequest encapsulates the $_SERVER variable and resolves its inconsistency among different Web servers.
  12. *
  13. * CHttpRequest also manages the cookies sent from and sent to the user.
  14. * By setting {@link enableCookieValidation} to true,
  15. * cookies sent from the user will be validated to see if they are tampered.
  16. * The property {@link getCookies cookies} returns the collection of cookies.
  17. * For more details, see {@link CCookieCollection}.
  18. *
  19. * CHttpRequest is a default application component loaded by {@link CWebApplication}. It can be
  20. * accessed via {@link CWebApplication::getRequest()}.
  21. *
  22. * @author Qiang Xue <qiang.xue@gmail.com>
  23. * @version $Id: CHttpRequest.php 3050 2011-03-12 13:22:11Z qiang.xue $
  24. * @package system.web
  25. * @since 1.0
  26. */
  27. class CHttpRequest extends CApplicationComponent
  28. {
  29. /**
  30. * @var boolean whether cookies should be validated to ensure they are not tampered. Defaults to false.
  31. */
  32. public $enableCookieValidation=false;
  33. /**
  34. * @var boolean whether to enable CSRF (Cross-Site Request Forgery) validation. Defaults to false.
  35. * By setting this property to true, forms submitted to an Yii Web application must be originated
  36. * from the same application. If not, a 400 HTTP exception will be raised.
  37. * Note, this feature requires that the user client accepts cookie.
  38. * You also need to use {@link CHtml::form} or {@link CHtml::statefulForm} to generate
  39. * the needed HTML forms in your pages.
  40. * @see http://seclab.stanford.edu/websec/csrf/csrf.pdf
  41. */
  42. public $enableCsrfValidation=false;
  43. /**
  44. * @var string the name of the token used to prevent CSRF. Defaults to 'YII_CSRF_TOKEN'.
  45. * This property is effectively only when {@link enableCsrfValidation} is true.
  46. */
  47. public $csrfTokenName='YII_CSRF_TOKEN';
  48. /**
  49. * @var array the property values (in name-value pairs) used to initialize the CSRF cookie.
  50. * Any property of {@link CHttpCookie} may be initialized.
  51. * This property is effective only when {@link enableCsrfValidation} is true.
  52. */
  53. public $csrfCookie;
  54. private $_requestUri;
  55. private $_pathInfo;
  56. private $_scriptFile;
  57. private $_scriptUrl;
  58. private $_hostInfo;
  59. private $_baseUrl;
  60. private $_cookies;
  61. private $_preferredLanguage;
  62. private $_csrfToken;
  63. private $_deleteParams;
  64. private $_putParams;
  65. /**
  66. * Initializes the application component.
  67. * This method overrides the parent implementation by preprocessing
  68. * the user request data.
  69. */
  70. public function init()
  71. {
  72. parent::init();
  73. $this->normalizeRequest();
  74. }
  75. /**
  76. * Normalizes the request data.
  77. * This method strips off slashes in request data if get_magic_quotes_gpc() returns true.
  78. * It also performs CSRF validation if {@link enableCsrfValidation} is true.
  79. */
  80. protected function normalizeRequest()
  81. {
  82. // normalize request
  83. if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
  84. {
  85. if(isset($_GET))
  86. $_GET=$this->stripSlashes($_GET);
  87. if(isset($_POST))
  88. $_POST=$this->stripSlashes($_POST);
  89. if(isset($_REQUEST))
  90. $_REQUEST=$this->stripSlashes($_REQUEST);
  91. if(isset($_COOKIE))
  92. $_COOKIE=$this->stripSlashes($_COOKIE);
  93. }
  94. if($this->enableCsrfValidation)
  95. Yii::app()->attachEventHandler('onBeginRequest',array($this,'validateCsrfToken'));
  96. }
  97. /**
  98. * Strips slashes from input data.
  99. * This method is applied when magic quotes is enabled.
  100. * @param mixed $data input data to be processed
  101. * @return mixed processed data
  102. */
  103. public function stripSlashes(&$data)
  104. {
  105. return is_array($data)?array_map(array($this,'stripSlashes'),$data):stripslashes($data);
  106. }
  107. /**
  108. * Returns the named GET or POST parameter value.
  109. * If the GET or POST parameter does not exist, the second parameter to this method will be returned.
  110. * If both GET and POST contains such a named parameter, the GET parameter takes precedence.
  111. * @param string $name the GET parameter name
  112. * @param mixed $defaultValue the default parameter value if the GET parameter does not exist.
  113. * @return mixed the GET parameter value
  114. * @since 1.0.4
  115. * @see getQuery
  116. * @see getPost
  117. */
  118. public function getParam($name,$defaultValue=null)
  119. {
  120. return isset($_GET[$name]) ? $_GET[$name] : (isset($_POST[$name]) ? $_POST[$name] : $defaultValue);
  121. }
  122. /**
  123. * Returns the named GET parameter value.
  124. * If the GET parameter does not exist, the second parameter to this method will be returned.
  125. * @param string $name the GET parameter name
  126. * @param mixed $defaultValue the default parameter value if the GET parameter does not exist.
  127. * @return mixed the GET parameter value
  128. * @since 1.0.4
  129. * @see getPost
  130. * @see getParam
  131. */
  132. public function getQuery($name,$defaultValue=null)
  133. {
  134. return isset($_GET[$name]) ? $_GET[$name] : $defaultValue;
  135. }
  136. /**
  137. * Returns the named POST parameter value.
  138. * If the POST parameter does not exist, the second parameter to this method will be returned.
  139. * @param string $name the POST parameter name
  140. * @param mixed $defaultValue the default parameter value if the POST parameter does not exist.
  141. * @return mixed the POST parameter value
  142. * @since 1.0.4
  143. * @see getParam
  144. * @see getQuery
  145. */
  146. public function getPost($name,$defaultValue=null)
  147. {
  148. return isset($_POST[$name]) ? $_POST[$name] : $defaultValue;
  149. }
  150. /**
  151. * Returns the named DELETE parameter value.
  152. * If the DELETE parameter does not exist or if the current request is not a DELETE request,
  153. * the second parameter to this method will be returned.
  154. * @param string $name the DELETE parameter name
  155. * @param mixed $defaultValue the default parameter value if the DELETE parameter does not exist.
  156. * @return mixed the DELETE parameter value
  157. * @since 1.1.7
  158. */
  159. public function getDelete($name,$defaultValue=null)
  160. {
  161. if($this->_deleteParams===null)
  162. $this->_deleteParams=$this->getIsDeleteRequest() ? $this->getRestParams() : array();
  163. return isset($this->_deleteParams[$name]) ? $this->_deleteParams[$name] : $defaultValue;
  164. }
  165. /**
  166. * Returns the named PUT parameter value.
  167. * If the PUT parameter does not exist or if the current request is not a PUT request,
  168. * the second parameter to this method will be returned.
  169. * @param string $name the PUT parameter name
  170. * @param mixed $defaultValue the default parameter value if the PUT parameter does not exist.
  171. * @return mixed the PUT parameter value
  172. * @since 1.1.7
  173. */
  174. public function getPut($name,$defaultValue=null)
  175. {
  176. if($this->_putParams===null)
  177. $this->_putParams=$this->getIsPutRequest() ? $this->getRestParams() : array();
  178. return isset($this->_putParams[$name]) ? $this->_putParams[$name] : $defaultValue;
  179. }
  180. /**
  181. * Returns the PUT or DELETE request parameters.
  182. * @return array the request parameters
  183. * @since 1.1.7
  184. */
  185. protected function getRestParams()
  186. {
  187. $result=array();
  188. if(function_exists('mb_parse_str'))
  189. mb_parse_str(file_get_contents('php://input'), $result);
  190. else
  191. parse_str(file_get_contents('php://input'), $result);
  192. return $result;
  193. }
  194. /**
  195. * Returns the currently requested URL.
  196. * This is the same as {@link getRequestUri}.
  197. * @return string part of the request URL after the host info.
  198. */
  199. public function getUrl()
  200. {
  201. return $this->getRequestUri();
  202. }
  203. /**
  204. * Returns the schema and host part of the application URL.
  205. * The returned URL does not have an ending slash.
  206. * By default this is determined based on the user request information.
  207. * You may explicitly specify it by setting the {@link setHostInfo hostInfo} property.
  208. * @param string $schema schema to use (e.g. http, https). If empty, the schema used for the current request will be used.
  209. * @return string schema and hostname part (with port number if needed) of the request URL (e.g. http://www.yiiframework.com)
  210. * @see setHostInfo
  211. */
  212. public function getHostInfo($schema='')
  213. {
  214. if($this->_hostInfo===null)
  215. {
  216. if($secure=$this->getIsSecureConnection())
  217. $http='https';
  218. else
  219. $http='http';
  220. if(isset($_SERVER['HTTP_HOST']))
  221. $this->_hostInfo=$http.'://'.$_SERVER['HTTP_HOST'];
  222. else
  223. {
  224. $this->_hostInfo=$http.'://'.$_SERVER['SERVER_NAME'];
  225. $port=$secure ? $this->getSecurePort() : $this->getPort();
  226. if(($port!==80 && !$secure) || ($port!==443 && $secure))
  227. $this->_hostInfo.=':'.$port;
  228. }
  229. }
  230. if($schema!=='')
  231. {
  232. $secure=$this->getIsSecureConnection();
  233. if($secure && $schema==='https' || !$secure && $schema==='http')
  234. return $this->_hostInfo;
  235. $port=$schema==='https' ? $this->getSecurePort() : $this->getPort();
  236. if($port!==80 && $schema==='http' || $port!==443 && $schema==='https')
  237. $port=':'.$port;
  238. else
  239. $port='';
  240. $pos=strpos($this->_hostInfo,':');
  241. return $schema.substr($this->_hostInfo,$pos,strcspn($this->_hostInfo,':',$pos+1)+1).$port;
  242. }
  243. else
  244. return $this->_hostInfo;
  245. }
  246. /**
  247. * Sets the schema and host part of the application URL.
  248. * This setter is provided in case the schema and hostname cannot be determined
  249. * on certain Web servers.
  250. * @param string $value the schema and host part of the application URL.
  251. */
  252. public function setHostInfo($value)
  253. {
  254. $this->_hostInfo=rtrim($value,'/');
  255. }
  256. /**
  257. * Returns the relative URL for the application.
  258. * This is similar to {@link getScriptUrl scriptUrl} except that
  259. * it does not have the script file name, and the ending slashes are stripped off.
  260. * @param boolean $absolute whether to return an absolute URL. Defaults to false, meaning returning a relative one.
  261. * This parameter has been available since 1.0.2.
  262. * @return string the relative URL for the application
  263. * @see setScriptUrl
  264. */
  265. public function getBaseUrl($absolute=false)
  266. {
  267. if($this->_baseUrl===null)
  268. $this->_baseUrl=rtrim(dirname($this->getScriptUrl()),'\\/');
  269. return $absolute ? $this->getHostInfo() . $this->_baseUrl : $this->_baseUrl;
  270. }
  271. /**
  272. * Sets the relative URL for the application.
  273. * By default the URL is determined based on the entry script URL.
  274. * This setter is provided in case you want to change this behavior.
  275. * @param string $value the relative URL for the application
  276. */
  277. public function setBaseUrl($value)
  278. {
  279. $this->_baseUrl=$value;
  280. }
  281. /**
  282. * Returns the relative URL of the entry script.
  283. * The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.
  284. * @return string the relative URL of the entry script.
  285. */
  286. public function getScriptUrl()
  287. {
  288. if($this->_scriptUrl===null)
  289. {
  290. $scriptName=basename($_SERVER['SCRIPT_FILENAME']);
  291. if(basename($_SERVER['SCRIPT_NAME'])===$scriptName)
  292. $this->_scriptUrl=$_SERVER['SCRIPT_NAME'];
  293. else if(basename($_SERVER['PHP_SELF'])===$scriptName)
  294. $this->_scriptUrl=$_SERVER['PHP_SELF'];
  295. else if(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME'])===$scriptName)
  296. $this->_scriptUrl=$_SERVER['ORIG_SCRIPT_NAME'];
  297. else if(($pos=strpos($_SERVER['PHP_SELF'],'/'.$scriptName))!==false)
  298. $this->_scriptUrl=substr($_SERVER['SCRIPT_NAME'],0,$pos).'/'.$scriptName;
  299. else if(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT'])===0)
  300. $this->_scriptUrl=str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER['SCRIPT_FILENAME']));
  301. else
  302. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the entry script URL.'));
  303. }
  304. return $this->_scriptUrl;
  305. }
  306. /**
  307. * Sets the relative URL for the application entry script.
  308. * This setter is provided in case the entry script URL cannot be determined
  309. * on certain Web servers.
  310. * @param string $value the relative URL for the application entry script.
  311. */
  312. public function setScriptUrl($value)
  313. {
  314. $this->_scriptUrl='/'.trim($value,'/');
  315. }
  316. /**
  317. * Returns the path info of the currently requested URL.
  318. * This refers to the part that is after the entry script and before the question mark.
  319. * The starting and ending slashes are stripped off.
  320. * @return string part of the request URL that is after the entry script and before the question mark.
  321. * Note, the returned pathinfo is decoded starting from 1.1.4.
  322. * Prior to 1.1.4, whether it is decoded or not depends on the server configuration
  323. * (in most cases it is not decoded).
  324. * @throws CException if the request URI cannot be determined due to improper server configuration
  325. */
  326. public function getPathInfo()
  327. {
  328. if($this->_pathInfo===null)
  329. {
  330. $pathInfo=$this->getRequestUri();
  331. if(($pos=strpos($pathInfo,'?'))!==false)
  332. $pathInfo=substr($pathInfo,0,$pos);
  333. $pathInfo=urldecode($pathInfo);
  334. $scriptUrl=$this->getScriptUrl();
  335. $baseUrl=$this->getBaseUrl();
  336. if(strpos($pathInfo,$scriptUrl)===0)
  337. $pathInfo=substr($pathInfo,strlen($scriptUrl));
  338. else if($baseUrl==='' || strpos($pathInfo,$baseUrl)===0)
  339. $pathInfo=substr($pathInfo,strlen($baseUrl));
  340. else if(strpos($_SERVER['PHP_SELF'],$scriptUrl)===0)
  341. $pathInfo=substr($_SERVER['PHP_SELF'],strlen($scriptUrl));
  342. else
  343. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the path info of the request.'));
  344. $this->_pathInfo=trim($pathInfo,'/');
  345. }
  346. return $this->_pathInfo;
  347. }
  348. /**
  349. * Returns the request URI portion for the currently requested URL.
  350. * This refers to the portion that is after the {@link hostInfo host info} part.
  351. * It includes the {@link queryString query string} part if any.
  352. * The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.
  353. * @return string the request URI portion for the currently requested URL.
  354. * @throws CException if the request URI cannot be determined due to improper server configuration
  355. * @since 1.0.1
  356. */
  357. public function getRequestUri()
  358. {
  359. if($this->_requestUri===null)
  360. {
  361. if(isset($_SERVER['HTTP_X_REWRITE_URL'])) // IIS
  362. $this->_requestUri=$_SERVER['HTTP_X_REWRITE_URL'];
  363. else if(isset($_SERVER['REQUEST_URI']))
  364. {
  365. $this->_requestUri=$_SERVER['REQUEST_URI'];
  366. if(isset($_SERVER['HTTP_HOST']))
  367. {
  368. if(strpos($this->_requestUri,$_SERVER['HTTP_HOST'])!==false)
  369. $this->_requestUri=preg_replace('/^\w+:\/\/[^\/]+/','',$this->_requestUri);
  370. }
  371. else
  372. $this->_requestUri=preg_replace('/^(http|https):\/\/[^\/]+/i','',$this->_requestUri);
  373. }
  374. else if(isset($_SERVER['ORIG_PATH_INFO'])) // IIS 5.0 CGI
  375. {
  376. $this->_requestUri=$_SERVER['ORIG_PATH_INFO'];
  377. if(!empty($_SERVER['QUERY_STRING']))
  378. $this->_requestUri.='?'.$_SERVER['QUERY_STRING'];
  379. }
  380. else
  381. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the request URI.'));
  382. }
  383. return $this->_requestUri;
  384. }
  385. /**
  386. * Returns part of the request URL that is after the question mark.
  387. * @return string part of the request URL that is after the question mark
  388. */
  389. public function getQueryString()
  390. {
  391. return isset($_SERVER['QUERY_STRING'])?$_SERVER['QUERY_STRING']:'';
  392. }
  393. /**
  394. * Return if the request is sent via secure channel (https).
  395. * @return boolean if the request is sent via secure channel (https)
  396. */
  397. public function getIsSecureConnection()
  398. {
  399. return isset($_SERVER['HTTPS']) && !strcasecmp($_SERVER['HTTPS'],'on');
  400. }
  401. /**
  402. * Returns the request type, such as GET, POST, HEAD, PUT, DELETE.
  403. * @return string request type, such as GET, POST, HEAD, PUT, DELETE.
  404. */
  405. public function getRequestType()
  406. {
  407. return strtoupper(isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:'GET');
  408. }
  409. /**
  410. * Returns whether this is a POST request.
  411. * @return boolean whether this is a POST request.
  412. */
  413. public function getIsPostRequest()
  414. {
  415. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'POST');
  416. }
  417. /**
  418. * Returns whether this is a DELETE request.
  419. * @return boolean whether this is a DELETE request.
  420. * @since 1.1.7
  421. */
  422. public function getIsDeleteRequest()
  423. {
  424. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'DELETE');
  425. }
  426. /**
  427. * Returns whether this is a PUT request.
  428. * @return boolean whether this is a PUT request.
  429. * @since 1.1.7
  430. */
  431. public function getIsPutRequest()
  432. {
  433. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'PUT');
  434. }
  435. /**
  436. * Returns whether this is an AJAX (XMLHttpRequest) request.
  437. * @return boolean whether this is an AJAX (XMLHttpRequest) request.
  438. */
  439. public function getIsAjaxRequest()
  440. {
  441. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
  442. }
  443. /**
  444. * Returns the server name.
  445. * @return string server name
  446. */
  447. public function getServerName()
  448. {
  449. return $_SERVER['SERVER_NAME'];
  450. }
  451. /**
  452. * Returns the server port number.
  453. * @return integer server port number
  454. */
  455. public function getServerPort()
  456. {
  457. return $_SERVER['SERVER_PORT'];
  458. }
  459. /**
  460. * Returns the URL referrer, null if not present
  461. * @return string URL referrer, null if not present
  462. */
  463. public function getUrlReferrer()
  464. {
  465. return isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:null;
  466. }
  467. /**
  468. * Returns the user agent, null if not present.
  469. * @return string user agent, null if not present
  470. */
  471. public function getUserAgent()
  472. {
  473. return isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:null;
  474. }
  475. /**
  476. * Returns the user IP address.
  477. * @return string user IP address
  478. */
  479. public function getUserHostAddress()
  480. {
  481. return isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'127.0.0.1';
  482. }
  483. /**
  484. * Returns the user host name, null if it cannot be determined.
  485. * @return string user host name, null if cannot be determined
  486. */
  487. public function getUserHost()
  488. {
  489. return isset($_SERVER['REMOTE_HOST'])?$_SERVER['REMOTE_HOST']:null;
  490. }
  491. /**
  492. * Returns entry script file path.
  493. * @return string entry script file path (processed w/ realpath())
  494. */
  495. public function getScriptFile()
  496. {
  497. if($this->_scriptFile!==null)
  498. return $this->_scriptFile;
  499. else
  500. return $this->_scriptFile=realpath($_SERVER['SCRIPT_FILENAME']);
  501. }
  502. /**
  503. * Returns information about the capabilities of user browser.
  504. * @param string $userAgent the user agent to be analyzed. Defaults to null, meaning using the
  505. * current User-Agent HTTP header information.
  506. * @return array user browser capabilities.
  507. * @see http://www.php.net/manual/en/function.get-browser.php
  508. */
  509. public function getBrowser($userAgent=null)
  510. {
  511. return get_browser($userAgent,true);
  512. }
  513. /**
  514. * Returns user browser accept types, null if not present.
  515. * @return string user browser accept types, null if not present
  516. */
  517. public function getAcceptTypes()
  518. {
  519. return isset($_SERVER['HTTP_ACCEPT'])?$_SERVER['HTTP_ACCEPT']:null;
  520. }
  521. private $_port;
  522. /**
  523. * Returns the port to use for insecure requests.
  524. * Defaults to 80, or the port specified by the server if the current
  525. * request is insecure.
  526. * You may explicitly specify it by setting the {@link setPort port} property.
  527. * @return integer port number for insecure requests.
  528. * @see setPort
  529. * @since 1.1.3
  530. */
  531. public function getPort()
  532. {
  533. if($this->_port===null)
  534. $this->_port=!$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 80;
  535. return $this->_port;
  536. }
  537. /**
  538. * Sets the port to use for insecure requests.
  539. * This setter is provided in case a custom port is necessary for certain
  540. * server configurations.
  541. * @param integer $value port number.
  542. * @since 1.1.3
  543. */
  544. public function setPort($value)
  545. {
  546. $this->_port=(int)$value;
  547. $this->_hostInfo=null;
  548. }
  549. private $_securePort;
  550. /**
  551. * Returns the port to use for secure requests.
  552. * Defaults to 443, or the port specified by the server if the current
  553. * request is secure.
  554. * You may explicitly specify it by setting the {@link setSecurePort securePort} property.
  555. * @return integer port number for secure requests.
  556. * @see setSecurePort
  557. * @since 1.1.3
  558. */
  559. public function getSecurePort()
  560. {
  561. if($this->_securePort===null)
  562. $this->_securePort=$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 443;
  563. return $this->_securePort;
  564. }
  565. /**
  566. * Sets the port to use for secure requests.
  567. * This setter is provided in case a custom port is necessary for certain
  568. * server configurations.
  569. * @param integer $value port number.
  570. * @since 1.1.3
  571. */
  572. public function setSecurePort($value)
  573. {
  574. $this->_securePort=(int)$value;
  575. $this->_hostInfo=null;
  576. }
  577. /**
  578. * Returns the cookie collection.
  579. * The result can be used like an associative array. Adding {@link CHttpCookie} objects
  580. * to the collection will send the cookies to the client; and removing the objects
  581. * from the collection will delete those cookies on the client.
  582. * @return CCookieCollection the cookie collection.
  583. */
  584. public function getCookies()
  585. {
  586. if($this->_cookies!==null)
  587. return $this->_cookies;
  588. else
  589. return $this->_cookies=new CCookieCollection($this);
  590. }
  591. /**
  592. * Redirects the browser to the specified URL.
  593. * @param string $url URL to be redirected to. If the URL is a relative one, the base URL of
  594. * the application will be inserted at the beginning.
  595. * @param boolean $terminate whether to terminate the current application
  596. * @param integer $statusCode the HTTP status code. Defaults to 302. See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html}
  597. * for details about HTTP status code. This parameter has been available since version 1.0.4.
  598. */
  599. public function redirect($url,$terminate=true,$statusCode=302)
  600. {
  601. if(strpos($url,'/')===0)
  602. $url=$this->getHostInfo().$url;
  603. header('Location: '.$url, true, $statusCode);
  604. if($terminate)
  605. Yii::app()->end();
  606. }
  607. /**
  608. * Returns the user preferred language.
  609. * The returned language ID will be canonicalized using {@link CLocale::getCanonicalID}.
  610. * This method returns false if the user does not have language preference.
  611. * @return string the user preferred language.
  612. */
  613. public function getPreferredLanguage()
  614. {
  615. if($this->_preferredLanguage===null)
  616. {
  617. if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && ($n=preg_match_all('/([\w\-_]+)\s*(;\s*q\s*=\s*(\d*\.\d*))?/',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches))>0)
  618. {
  619. $languages=array();
  620. for($i=0;$i<$n;++$i)
  621. $languages[$matches[1][$i]]=empty($matches[3][$i]) ? 1.0 : floatval($matches[3][$i]);
  622. arsort($languages);
  623. foreach($languages as $language=>$pref)
  624. return $this->_preferredLanguage=CLocale::getCanonicalID($language);
  625. }
  626. return $this->_preferredLanguage=false;
  627. }
  628. return $this->_preferredLanguage;
  629. }
  630. /**
  631. * Sends a file to user.
  632. * @param string $fileName file name
  633. * @param string $content content to be set.
  634. * @param string $mimeType mime type of the content. If null, it will be guessed automatically based on the given file name.
  635. * @param boolean $terminate whether to terminate the current application after calling this method
  636. */
  637. public function sendFile($fileName,$content,$mimeType=null,$terminate=true)
  638. {
  639. if($mimeType===null)
  640. {
  641. if(($mimeType=CFileHelper::getMimeTypeByExtension($fileName))===null)
  642. $mimeType='text/plain';
  643. }
  644. header('Pragma: public');
  645. header('Expires: 0');
  646. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  647. header("Content-type: $mimeType");
  648. if(ini_get("output_handler")=='')
  649. header('Content-Length: '.(function_exists('mb_strlen') ? mb_strlen($content,'8bit') : strlen($content)));
  650. header("Content-Disposition: attachment; filename=\"$fileName\"");
  651. header('Content-Transfer-Encoding: binary');
  652. if($terminate)
  653. {
  654. // clean up the application first because the file downloading could take long time
  655. // which may cause timeout of some resources (such as DB connection)
  656. Yii::app()->end(0,false);
  657. echo $content;
  658. exit(0);
  659. }
  660. else
  661. echo $content;
  662. }
  663. /**
  664. * Sends existing file to a browser as a download using x-sendfile.
  665. *
  666. * X-Sendfile is a feature allowing a web application to redirect the request for a file to the webserver
  667. * that in turn processes the request, this way eliminating the need to perform tasks like reading the file
  668. * and sending it to the user. When dealing with a lot of files (or very big files) this can lead to a great
  669. * increase in performance as the web application is allowed to terminate earlier while the webserver is
  670. * handling the request.
  671. *
  672. * The request is sent to the server through a special non-standard HTTP-header.
  673. * When the web server encounters the presence of such header it will discard all output and send the file
  674. * specified by that header using web server internals including all optimizations like caching-headers.
  675. *
  676. * As this header directive is non-standard different directives exists for different web servers applications:
  677. * <ul>
  678. * <li>Apache: {@link http://tn123.org/mod_xsendfile X-Sendfile}</li>
  679. * <li>Lighttpd v1.4: {@link http://redmine.lighttpd.net/wiki/lighttpd/X-LIGHTTPD-send-file X-LIGHTTPD-send-file}</li>
  680. * <li>Lighttpd v1.5: X-Sendfile {@link http://redmine.lighttpd.net/wiki/lighttpd/X-LIGHTTPD-send-file X-Sendfile}</li>
  681. * <li>Nginx: {@link http://wiki.nginx.org/XSendfile X-Accel-Redirect}</li>
  682. * <li>Cherokee: {@link http://www.cherokee-project.com/doc/other_goodies.html#x-sendfile X-Sendfile and X-Accel-Redirect}</li>
  683. * </ul>
  684. * So for this method to work the X-SENDFILE option/module should be enabled by the web server and
  685. * a proper xHeader should be sent.
  686. *
  687. * <b>Note:</b>
  688. * This option allows to download files that are not under web folders, and even files that are otherwise protected (deny from all) like .htaccess
  689. *
  690. * <b>Side effects</b>:
  691. * If this option is disabled by the web server, when this method is called a download configuration dialog
  692. * will open but the downloaded file will have 0 bytes.
  693. *
  694. * <b>Example</b>:
  695. * <pre>
  696. * <?php
  697. * Yii::app()->request->xSendFile('/home/user/Pictures/picture1.jpg',array(
  698. * 'saveName'=>'image1.jpg',
  699. * 'mimeType'=>'image/jpeg',
  700. * 'terminate'=>false,
  701. * ));
  702. * ?>
  703. * </pre>
  704. * @param string $filePath file name with full path
  705. * @param array $options additional options:
  706. * <ul>
  707. * <li>saveName: file name shown to the user, if not set real file name will be used</li>
  708. * <li>mimeType: mime type of the file, if not set it will be guessed automatically based on the file name.</li>
  709. * <li>xHeader: appropriate x-sendfile header, defaults to "X-Sendfile"</li>
  710. * <li>terminate: whether to terminate the current application after calling this method, defaults to true</li>
  711. * </ul>
  712. * @return boolean false if file not found, true otherwise.
  713. */
  714. public function xSendFile($filePath, $options=array())
  715. {
  716. if(!is_file($filePath))
  717. return false;
  718. if(!isset($options['saveName']))
  719. $options['saveName']=basename($filePath);
  720. if(!isset($options['mimeType']))
  721. {
  722. if(($options['mimeType']=CFileHelper::getMimeTypeByExtension($filePath))===null)
  723. $options['mimeType']='text/plain';
  724. }
  725. if(!isset($options['xHeader']))
  726. $options['xHeader']='X-Sendfile';
  727. header('Content-type: '.$options['mimeType']);
  728. header('Content-Disposition: attachment; filename="'.$options['saveName'].'"');
  729. header(trim($options['xHeader']).': '.$filePath);
  730. if(!isset($options['terminate']) || $options['terminate'])
  731. Yii::app()->end();
  732. return true;
  733. }
  734. /**
  735. * Returns the random token used to perform CSRF validation.
  736. * The token will be read from cookie first. If not found, a new token
  737. * will be generated.
  738. * @return string the random token for CSRF validation.
  739. * @see enableCsrfValidation
  740. */
  741. public function getCsrfToken()
  742. {
  743. if($this->_csrfToken===null)
  744. {
  745. $cookie=$this->getCookies()->itemAt($this->csrfTokenName);
  746. if(!$cookie || ($this->_csrfToken=$cookie->value)==null)
  747. {
  748. $cookie=$this->createCsrfCookie();
  749. $this->_csrfToken=$cookie->value;
  750. $this->getCookies()->add($cookie->name,$cookie);
  751. }
  752. }
  753. return $this->_csrfToken;
  754. }
  755. /**
  756. * Creates a cookie with a randomly generated CSRF token.
  757. * Initial values specified in {@link csrfCookie} will be applied
  758. * to the generated cookie.
  759. * @return CHttpCookie the generated cookie
  760. * @see enableCsrfValidation
  761. */
  762. protected function createCsrfCookie()
  763. {
  764. $cookie=new CHttpCookie($this->csrfTokenName,sha1(uniqid(mt_rand(),true)));
  765. if(is_array($this->csrfCookie))
  766. {
  767. foreach($this->csrfCookie as $name=>$value)
  768. $cookie->$name=$value;
  769. }
  770. return $cookie;
  771. }
  772. /**
  773. * Performs the CSRF validation.
  774. * This is the event handler responding to {@link CApplication::onBeginRequest}.
  775. * The default implementation will compare the CSRF token obtained
  776. * from a cookie and from a POST field. If they are different, a CSRF attack is detected.
  777. * @param CEvent $event event parameter
  778. * @throws CHttpException if the validation fails
  779. * @since 1.0.4
  780. */
  781. public function validateCsrfToken($event)
  782. {
  783. if($this->getIsPostRequest())
  784. {
  785. // only validate POST requests
  786. $cookies=$this->getCookies();
  787. if($cookies->contains($this->csrfTokenName) && isset($_POST[$this->csrfTokenName]))
  788. {
  789. $tokenFromCookie=$cookies->itemAt($this->csrfTokenName)->value;
  790. $tokenFromPost=$_POST[$this->csrfTokenName];
  791. $valid=$tokenFromCookie===$tokenFromPost;
  792. }
  793. else
  794. $valid=false;
  795. if(!$valid)
  796. throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.'));
  797. }
  798. }
  799. }
  800. /**
  801. * CCookieCollection implements a collection class to store cookies.
  802. *
  803. * You normally access it via {@link CHttpRequest::getCookies()}.
  804. *
  805. * Since CCookieCollection extends from {@link CMap}, it can be used
  806. * like an associative array as follows:
  807. * <pre>
  808. * $cookies[$name]=new CHttpCookie($name,$value); // sends a cookie
  809. * $value=$cookies[$name]->value; // reads a cookie value
  810. * unset($cookies[$name]); // removes a cookie
  811. * </pre>
  812. *
  813. * @author Qiang Xue <qiang.xue@gmail.com>
  814. * @version $Id: CHttpRequest.php 3050 2011-03-12 13:22:11Z qiang.xue $
  815. * @package system.web
  816. * @since 1.0
  817. */
  818. class CCookieCollection extends CMap
  819. {
  820. private $_request;
  821. private $_initialized=false;
  822. /**
  823. * Constructor.
  824. * @param CHttpRequest $request owner of this collection.
  825. */
  826. public function __construct(CHttpRequest $request)
  827. {
  828. $this->_request=$request;
  829. $this->copyfrom($this->getCookies());
  830. $this->_initialized=true;
  831. }
  832. /**
  833. * @return CHttpRequest the request instance
  834. */
  835. public function getRequest()
  836. {
  837. return $this->_request;
  838. }
  839. /**
  840. * @return array list of validated cookies
  841. */
  842. protected function getCookies()
  843. {
  844. $cookies=array();
  845. if($this->_request->enableCookieValidation)
  846. {
  847. $sm=Yii::app()->getSecurityManager();
  848. foreach($_COOKIE as $name=>$value)
  849. {
  850. if(is_string($value) && ($value=$sm->validateData($value))!==false)
  851. $cookies[$name]=new CHttpCookie($name,@unserialize($value));
  852. }
  853. }
  854. else
  855. {
  856. foreach($_COOKIE as $name=>$value)
  857. $cookies[$name]=new CHttpCookie($name,$value);
  858. }
  859. return $cookies;
  860. }
  861. /**
  862. * Adds a cookie with the specified name.
  863. * This overrides the parent implementation by performing additional
  864. * operations for each newly added CHttpCookie object.
  865. * @param mixed $name Cookie name.
  866. * @param CHttpCookie $cookie Cookie object.
  867. * @throws CException if the item to be inserted is not a CHttpCookie object.
  868. */
  869. public function add($name,$cookie)
  870. {
  871. if($cookie instanceof CHttpCookie)
  872. {
  873. $this->remove($name);
  874. parent::add($name,$cookie);
  875. if($this->_initialized)
  876. $this->addCookie($cookie);
  877. }
  878. else
  879. throw new CException(Yii::t('yii','CHttpCookieCollection can only hold CHttpCookie objects.'));
  880. }
  881. /**
  882. * Removes a cookie with the specified name.
  883. * This overrides the parent implementation by performing additional
  884. * cleanup work when removing a CHttpCookie object.
  885. * @param mixed $name Cookie name.
  886. * @return CHttpCookie The removed cookie object.
  887. */
  888. public function remove($name)
  889. {
  890. if(($cookie=parent::remove($name))!==null)
  891. {
  892. if($this->_initialized)
  893. $this->removeCookie($cookie);
  894. }
  895. return $cookie;
  896. }
  897. /**
  898. * Sends a cookie.
  899. * @param CHttpCookie $cookie cook to be sent
  900. */
  901. protected function addCookie($cookie)
  902. {
  903. $value=$cookie->value;
  904. if($this->_request->enableCookieValidation)
  905. $value=Yii::app()->getSecurityManager()->hashData(serialize($value));
  906. if(version_compare(PHP_VERSION,'5.2.0','>='))
  907. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  908. else
  909. setcookie($cookie->name,$value,$cookie->expire,$cookie->path,$cookie->domain,$cookie->secure);
  910. }
  911. /**
  912. * Deletes a cookie.
  913. * @param CHttpCookie $cookie cook to be deleted
  914. */
  915. protected function removeCookie($cookie)
  916. {
  917. if(version_compare(PHP_VERSION,'5.2.0','>='))
  918. setcookie($cookie->name,null,0,$cookie->path,$cookie->domain,$cookie->secure,$cookie->httpOnly);
  919. else
  920. setcookie($cookie->name,null,0,$cookie->path,$cookie->domain,$cookie->secure);
  921. }
  922. }