PageRenderTime 80ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/framework/web/CHttpRequest.php

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