PageRenderTime 1451ms CodeModel.GetById 70ms RepoModel.GetById 7ms app.codeStats 1ms

/framework/web/CHttpRequest.php

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