PageRenderTime 55ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/framework/web/CHttpRequest.php

https://gitlab.com/zenfork/vektor
PHP | 1422 lines | 938 code | 69 blank | 415 comment | 97 complexity | 201f645cc2983f2ecac3721e052fdcfa 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 2008-2013 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, PATCH, 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 $isPatchRequest Whether this is a PATCH request.
  38. * @property boolean $isAjaxRequest Whether this is an AJAX (XMLHttpRequest) request.
  39. * @property boolean $isFlashRequest Whether this is an Adobe Flash or Adobe Flex request.
  40. * @property string $serverName Server name.
  41. * @property integer $serverPort Server port number.
  42. * @property string $urlReferrer URL referrer, null if not present.
  43. * @property string $userAgent User agent, null if not present.
  44. * @property string $userHostAddress User IP address.
  45. * @property string $userHost User host name, null if cannot be determined.
  46. * @property string $scriptFile Entry script file path (processed w/ realpath()).
  47. * @property array $browser User browser capabilities.
  48. * @property string $acceptTypes User browser accept types, null if not present.
  49. * @property integer $port Port number for insecure requests.
  50. * @property integer $securePort Port number for secure requests.
  51. * @property CCookieCollection|CHttpCookie[] $cookies The cookie collection.
  52. * @property array $preferredAcceptType The user preferred accept type as an array map, e.g. array('type' => 'application', 'subType' => 'xhtml', 'baseType' => 'xml', 'params' => array('q' => 0.9)).
  53. * @property array $preferredAcceptTypes An array of all user accepted types (as array maps like array('type' => 'application', 'subType' => 'xhtml', 'baseType' => 'xml', 'params' => array('q' => 0.9)) ) in order of preference.
  54. * @property string $preferredLanguage The user preferred language.
  55. * @property array $preferredLanguages An array of all user accepted languages in order of preference.
  56. * @property string $csrfToken The random token for CSRF validation.
  57. *
  58. * @author Qiang Xue <qiang.xue@gmail.com>
  59. * @package system.web
  60. * @since 1.0
  61. */
  62. class CHttpRequest extends CApplicationComponent
  63. {
  64. /**
  65. * @var boolean whether the parsing of JSON REST requests should return associative arrays for object data.
  66. * @see getRestParams
  67. * @since 1.1.17
  68. */
  69. public $jsonAsArray = true;
  70. /**
  71. * @var boolean whether cookies should be validated to ensure they are not tampered. Defaults to false.
  72. */
  73. public $enableCookieValidation=false;
  74. /**
  75. * @var boolean whether to enable CSRF (Cross-Site Request Forgery) validation. Defaults to false.
  76. * By setting this property to true, forms submitted to an Yii Web application must be originated
  77. * from the same application. If not, a 400 HTTP exception will be raised.
  78. * Note, this feature requires that the user client accepts cookie.
  79. * You also need to use {@link CHtml::form} or {@link CHtml::statefulForm} to generate
  80. * the needed HTML forms in your pages.
  81. * @see http://seclab.stanford.edu/websec/csrf/csrf.pdf
  82. */
  83. public $enableCsrfValidation=false;
  84. /**
  85. * @var string the name of the token used to prevent CSRF. Defaults to 'YII_CSRF_TOKEN'.
  86. * This property is effectively only when {@link enableCsrfValidation} is true.
  87. */
  88. public $csrfTokenName='YII_CSRF_TOKEN';
  89. /**
  90. * @var array the property values (in name-value pairs) used to initialize the CSRF cookie.
  91. * Any property of {@link CHttpCookie} may be initialized.
  92. * This property is effective only when {@link enableCsrfValidation} is true.
  93. */
  94. public $csrfCookie;
  95. private $_requestUri;
  96. private $_pathInfo;
  97. private $_scriptFile;
  98. private $_scriptUrl;
  99. private $_hostInfo;
  100. private $_baseUrl;
  101. private $_cookies;
  102. private $_preferredAcceptTypes;
  103. private $_preferredLanguages;
  104. private $_csrfToken;
  105. private $_restParams;
  106. private $_httpVersion;
  107. /**
  108. * Initializes the application component.
  109. * This method overrides the parent implementation by preprocessing
  110. * the user request data.
  111. */
  112. public function init()
  113. {
  114. parent::init();
  115. $this->normalizeRequest();
  116. }
  117. /**
  118. * Normalizes the request data.
  119. * This method strips off slashes in request data if get_magic_quotes_gpc() returns true.
  120. * It also performs CSRF validation if {@link enableCsrfValidation} is true.
  121. */
  122. protected function normalizeRequest()
  123. {
  124. // normalize request
  125. if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
  126. {
  127. if(isset($_GET))
  128. $_GET=$this->stripSlashes($_GET);
  129. if(isset($_POST))
  130. $_POST=$this->stripSlashes($_POST);
  131. if(isset($_REQUEST))
  132. $_REQUEST=$this->stripSlashes($_REQUEST);
  133. if(isset($_COOKIE))
  134. $_COOKIE=$this->stripSlashes($_COOKIE);
  135. }
  136. if($this->enableCsrfValidation)
  137. Yii::app()->attachEventHandler('onBeginRequest',array($this,'validateCsrfToken'));
  138. }
  139. /**
  140. * Strips slashes from input data.
  141. * This method is applied when magic quotes is enabled.
  142. * @param mixed $data input data to be processed
  143. * @return mixed processed data
  144. */
  145. public function stripSlashes(&$data)
  146. {
  147. if(is_array($data))
  148. {
  149. if(count($data) == 0)
  150. return $data;
  151. $keys=array_map('stripslashes',array_keys($data));
  152. $data=array_combine($keys,array_values($data));
  153. return array_map(array($this,'stripSlashes'),$data);
  154. }
  155. else
  156. return stripslashes($data);
  157. }
  158. /**
  159. * Returns the named GET or POST parameter value.
  160. * If the GET or POST parameter does not exist, the second parameter to this method will be returned.
  161. * If both GET and POST contains such a named parameter, the GET parameter takes precedence.
  162. * @param string $name the GET parameter name
  163. * @param mixed $defaultValue the default parameter value if the GET parameter does not exist.
  164. * @return mixed the GET parameter value
  165. * @see getQuery
  166. * @see getPost
  167. */
  168. public function getParam($name,$defaultValue=null)
  169. {
  170. return isset($_GET[$name]) ? $_GET[$name] : (isset($_POST[$name]) ? $_POST[$name] : $defaultValue);
  171. }
  172. /**
  173. * Returns the named GET parameter value.
  174. * If the GET parameter does not exist, the second parameter to this method will be returned.
  175. * @param string $name the GET parameter name
  176. * @param mixed $defaultValue the default parameter value if the GET parameter does not exist.
  177. * @return mixed the GET parameter value
  178. * @see getPost
  179. * @see getParam
  180. */
  181. public function getQuery($name,$defaultValue=null)
  182. {
  183. return isset($_GET[$name]) ? $_GET[$name] : $defaultValue;
  184. }
  185. /**
  186. * Returns the named POST parameter value.
  187. * If the POST parameter does not exist, the second parameter to this method will be returned.
  188. * @param string $name the POST parameter name
  189. * @param mixed $defaultValue the default parameter value if the POST parameter does not exist.
  190. * @return mixed the POST parameter value
  191. * @see getParam
  192. * @see getQuery
  193. */
  194. public function getPost($name,$defaultValue=null)
  195. {
  196. return isset($_POST[$name]) ? $_POST[$name] : $defaultValue;
  197. }
  198. /**
  199. * Returns the named DELETE parameter value.
  200. * If the DELETE parameter does not exist or if the current request is not a DELETE request,
  201. * the second parameter to this method will be returned.
  202. * If the DELETE 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 DELETE parameter name
  205. * @param mixed $defaultValue the default parameter value if the DELETE parameter does not exist.
  206. * @return mixed the DELETE parameter value
  207. * @since 1.1.7
  208. */
  209. public function getDelete($name,$defaultValue=null)
  210. {
  211. if($this->getIsDeleteViaPostRequest())
  212. return $this->getPost($name, $defaultValue);
  213. if($this->getIsDeleteRequest())
  214. {
  215. $restParams=$this->getRestParams();
  216. return isset($restParams[$name]) ? $restParams[$name] : $defaultValue;
  217. }
  218. else
  219. return $defaultValue;
  220. }
  221. /**
  222. * Returns the named PUT parameter value.
  223. * If the PUT parameter does not exist or if the current request is not a PUT request,
  224. * the second parameter to this method will be returned.
  225. * If the PUT request was tunneled through POST via _method parameter, the POST parameter
  226. * will be returned instead (available since version 1.1.11).
  227. * @param string $name the PUT parameter name
  228. * @param mixed $defaultValue the default parameter value if the PUT parameter does not exist.
  229. * @return mixed the PUT parameter value
  230. * @since 1.1.7
  231. */
  232. public function getPut($name,$defaultValue=null)
  233. {
  234. if($this->getIsPutViaPostRequest())
  235. return $this->getPost($name, $defaultValue);
  236. if($this->getIsPutRequest())
  237. {
  238. $restParams=$this->getRestParams();
  239. return isset($restParams[$name]) ? $restParams[$name] : $defaultValue;
  240. }
  241. else
  242. return $defaultValue;
  243. }
  244. /**
  245. * Returns the named PATCH parameter value.
  246. * If the PATCH parameter does not exist or if the current request is not a PATCH request,
  247. * the second parameter to this method will be returned.
  248. * If the PATCH request was tunneled through POST via _method parameter, the POST parameter
  249. * will be returned instead.
  250. * @param string $name the PATCH parameter name
  251. * @param mixed $defaultValue the default parameter value if the PATCH parameter does not exist.
  252. * @return mixed the PATCH parameter value
  253. * @since 1.1.16
  254. */
  255. public function getPatch($name,$defaultValue=null)
  256. {
  257. if($this->getIsPatchViaPostRequest())
  258. return $this->getPost($name, $defaultValue);
  259. if($this->getIsPatchRequest())
  260. {
  261. $restParams=$this->getRestParams();
  262. return isset($restParams[$name]) ? $restParams[$name] : $defaultValue;
  263. }
  264. else
  265. return $defaultValue;
  266. }
  267. /**
  268. * Returns request parameters. Typically PUT, PATCH or DELETE.
  269. * @return array the request parameters
  270. * @since 1.1.7
  271. * @since 1.1.13 method became public
  272. */
  273. public function getRestParams()
  274. {
  275. if($this->_restParams===null)
  276. {
  277. $result=array();
  278. if (strncmp($this->getContentType(), 'application/json', 16) === 0)
  279. $result = CJSON::decode($this->getRawBody(), $this->jsonAsArray);
  280. elseif(function_exists('mb_parse_str'))
  281. mb_parse_str($this->getRawBody(), $result);
  282. else
  283. parse_str($this->getRawBody(), $result);
  284. $this->_restParams=$result;
  285. }
  286. return $this->_restParams;
  287. }
  288. /**
  289. * Returns the raw HTTP request body.
  290. * @return string the request body
  291. * @since 1.1.13
  292. */
  293. public function getRawBody()
  294. {
  295. static $rawBody;
  296. if($rawBody===null)
  297. $rawBody=file_get_contents('php://input');
  298. return $rawBody;
  299. }
  300. /**
  301. * Returns the currently requested URL.
  302. * This is the same as {@link getRequestUri}.
  303. * @return string part of the request URL after the host info.
  304. */
  305. public function getUrl()
  306. {
  307. return $this->getRequestUri();
  308. }
  309. /**
  310. * Returns the schema and host part of the application URL.
  311. * The returned URL does not have an ending slash.
  312. * By default this is determined based on the user request information.
  313. * You may explicitly specify it by setting the {@link setHostInfo hostInfo} property.
  314. * @param string $schema schema to use (e.g. http, https). If empty, the schema used for the current request will be used.
  315. * @return string schema and hostname part (with port number if needed) of the request URL (e.g. http://www.yiiframework.com)
  316. * @see setHostInfo
  317. */
  318. public function getHostInfo($schema='')
  319. {
  320. if($this->_hostInfo===null)
  321. {
  322. if($secure=$this->getIsSecureConnection())
  323. $http='https';
  324. else
  325. $http='http';
  326. if(isset($_SERVER['HTTP_HOST']))
  327. $this->_hostInfo=$http.'://'.$_SERVER['HTTP_HOST'];
  328. else
  329. {
  330. $this->_hostInfo=$http.'://'.$_SERVER['SERVER_NAME'];
  331. $port=$secure ? $this->getSecurePort() : $this->getPort();
  332. if(($port!==80 && !$secure) || ($port!==443 && $secure))
  333. $this->_hostInfo.=':'.$port;
  334. }
  335. }
  336. if($schema!=='')
  337. {
  338. $secure=$this->getIsSecureConnection();
  339. if($secure && $schema==='https' || !$secure && $schema==='http')
  340. return $this->_hostInfo;
  341. $port=$schema==='https' ? $this->getSecurePort() : $this->getPort();
  342. if($port!==80 && $schema==='http' || $port!==443 && $schema==='https')
  343. $port=':'.$port;
  344. else
  345. $port='';
  346. $pos=strpos($this->_hostInfo,':');
  347. return $schema.substr($this->_hostInfo,$pos,strcspn($this->_hostInfo,':',$pos+1)+1).$port;
  348. }
  349. else
  350. return $this->_hostInfo;
  351. }
  352. /**
  353. * Sets the schema and host part of the application URL.
  354. * This setter is provided in case the schema and hostname cannot be determined
  355. * on certain Web servers.
  356. * @param string $value the schema and host part of the application URL.
  357. */
  358. public function setHostInfo($value)
  359. {
  360. $this->_hostInfo=rtrim($value,'/');
  361. }
  362. /**
  363. * Returns the relative URL for the application.
  364. * This is similar to {@link getScriptUrl scriptUrl} except that
  365. * it does not have the script file name, and the ending slashes are stripped off.
  366. * @param boolean $absolute whether to return an absolute URL. Defaults to false, meaning returning a relative one.
  367. * @return string the relative URL for the application
  368. * @see setScriptUrl
  369. */
  370. public function getBaseUrl($absolute=false)
  371. {
  372. if($this->_baseUrl===null)
  373. $this->_baseUrl=rtrim(dirname($this->getScriptUrl()),'\\/');
  374. return $absolute ? $this->getHostInfo() . $this->_baseUrl : $this->_baseUrl;
  375. }
  376. /**
  377. * Sets the relative URL for the application.
  378. * By default the URL is determined based on the entry script URL.
  379. * This setter is provided in case you want to change this behavior.
  380. * @param string $value the relative URL for the application
  381. */
  382. public function setBaseUrl($value)
  383. {
  384. $this->_baseUrl=$value;
  385. }
  386. /**
  387. * Returns the relative URL of the entry script.
  388. * The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.
  389. * @throws CException when it is unable to determine the entry script URL.
  390. * @return string the relative URL of the entry script.
  391. */
  392. public function getScriptUrl()
  393. {
  394. if($this->_scriptUrl===null)
  395. {
  396. $scriptName=basename($_SERVER['SCRIPT_FILENAME']);
  397. if(basename($_SERVER['SCRIPT_NAME'])===$scriptName)
  398. $this->_scriptUrl=$_SERVER['SCRIPT_NAME'];
  399. elseif(basename($_SERVER['PHP_SELF'])===$scriptName)
  400. $this->_scriptUrl=$_SERVER['PHP_SELF'];
  401. elseif(isset($_SERVER['ORIG_SCRIPT_NAME']) && basename($_SERVER['ORIG_SCRIPT_NAME'])===$scriptName)
  402. $this->_scriptUrl=$_SERVER['ORIG_SCRIPT_NAME'];
  403. elseif(($pos=strpos($_SERVER['PHP_SELF'],'/'.$scriptName))!==false)
  404. $this->_scriptUrl=substr($_SERVER['SCRIPT_NAME'],0,$pos).'/'.$scriptName;
  405. elseif(isset($_SERVER['DOCUMENT_ROOT']) && strpos($_SERVER['SCRIPT_FILENAME'],$_SERVER['DOCUMENT_ROOT'])===0)
  406. $this->_scriptUrl=str_replace('\\','/',str_replace($_SERVER['DOCUMENT_ROOT'],'',$_SERVER['SCRIPT_FILENAME']));
  407. else
  408. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the entry script URL.'));
  409. }
  410. return $this->_scriptUrl;
  411. }
  412. /**
  413. * Sets the relative URL for the application entry script.
  414. * This setter is provided in case the entry script URL cannot be determined
  415. * on certain Web servers.
  416. * @param string $value the relative URL for the application entry script.
  417. */
  418. public function setScriptUrl($value)
  419. {
  420. $this->_scriptUrl='/'.trim($value,'/');
  421. }
  422. /**
  423. * Returns the path info of the currently requested URL.
  424. * This refers to the part that is after the entry script and before the question mark.
  425. * The starting and ending slashes are stripped off.
  426. * @return string part of the request URL that is after the entry script and before the question mark.
  427. * Note, the returned pathinfo is decoded starting from 1.1.4.
  428. * Prior to 1.1.4, whether it is decoded or not depends on the server configuration
  429. * (in most cases it is not decoded).
  430. * @throws CException if the request URI cannot be determined due to improper server configuration
  431. */
  432. public function getPathInfo()
  433. {
  434. if($this->_pathInfo===null)
  435. {
  436. $pathInfo=$this->getRequestUri();
  437. if(($pos=strpos($pathInfo,'?'))!==false)
  438. $pathInfo=substr($pathInfo,0,$pos);
  439. $pathInfo=$this->decodePathInfo($pathInfo);
  440. $scriptUrl=$this->getScriptUrl();
  441. $baseUrl=$this->getBaseUrl();
  442. if(strpos($pathInfo,$scriptUrl)===0)
  443. $pathInfo=substr($pathInfo,strlen($scriptUrl));
  444. elseif($baseUrl==='' || strpos($pathInfo,$baseUrl)===0)
  445. $pathInfo=substr($pathInfo,strlen($baseUrl));
  446. elseif(strpos($_SERVER['PHP_SELF'],$scriptUrl)===0)
  447. $pathInfo=substr($_SERVER['PHP_SELF'],strlen($scriptUrl));
  448. else
  449. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the path info of the request.'));
  450. if($pathInfo==='/' || $pathInfo===false)
  451. $pathInfo='';
  452. elseif($pathInfo!=='' && $pathInfo[0]==='/')
  453. $pathInfo=substr($pathInfo,1);
  454. if(($posEnd=strlen($pathInfo)-1)>0 && $pathInfo[$posEnd]==='/')
  455. $pathInfo=substr($pathInfo,0,$posEnd);
  456. $this->_pathInfo=$pathInfo;
  457. }
  458. return $this->_pathInfo;
  459. }
  460. /**
  461. * Decodes the path info.
  462. * This method is an improved variant of the native urldecode() function and used in {@link getPathInfo getPathInfo()} to
  463. * decode the path part of the request URI. You may override this method to change the way the path info is being decoded.
  464. * @param string $pathInfo encoded path info
  465. * @return string decoded path info
  466. * @since 1.1.10
  467. */
  468. protected function decodePathInfo($pathInfo)
  469. {
  470. $pathInfo = urldecode($pathInfo);
  471. // is it UTF-8?
  472. // http://w3.org/International/questions/qa-forms-utf-8.html
  473. if(preg_match('%^(?:
  474. [\x09\x0A\x0D\x20-\x7E] # ASCII
  475. | [\xC2-\xDF][\x80-\xBF] # non-overlong 2-byte
  476. | \xE0[\xA0-\xBF][\x80-\xBF] # excluding overlongs
  477. | [\xE1-\xEC\xEE\xEF][\x80-\xBF]{2} # straight 3-byte
  478. | \xED[\x80-\x9F][\x80-\xBF] # excluding surrogates
  479. | \xF0[\x90-\xBF][\x80-\xBF]{2} # planes 1-3
  480. | [\xF1-\xF3][\x80-\xBF]{3} # planes 4-15
  481. | \xF4[\x80-\x8F][\x80-\xBF]{2} # plane 16
  482. )*$%xs', $pathInfo))
  483. {
  484. return $pathInfo;
  485. }
  486. else
  487. {
  488. return utf8_encode($pathInfo);
  489. }
  490. }
  491. /**
  492. * Returns the request URI portion for the currently requested URL.
  493. * This refers to the portion that is after the {@link hostInfo host info} part.
  494. * It includes the {@link queryString query string} part if any.
  495. * The implementation of this method referenced Zend_Controller_Request_Http in Zend Framework.
  496. * @return string the request URI portion for the currently requested URL.
  497. * @throws CException if the request URI cannot be determined due to improper server configuration
  498. */
  499. public function getRequestUri()
  500. {
  501. if($this->_requestUri===null)
  502. {
  503. if(isset($_SERVER['HTTP_X_REWRITE_URL'])) // IIS
  504. $this->_requestUri=$_SERVER['HTTP_X_REWRITE_URL'];
  505. elseif(isset($_SERVER['REQUEST_URI']))
  506. {
  507. $this->_requestUri=$_SERVER['REQUEST_URI'];
  508. if(!empty($_SERVER['HTTP_HOST']))
  509. {
  510. if(strpos($this->_requestUri,$_SERVER['HTTP_HOST'])!==false)
  511. $this->_requestUri=preg_replace('/^\w+:\/\/[^\/]+/','',$this->_requestUri);
  512. }
  513. else
  514. $this->_requestUri=preg_replace('/^(http|https):\/\/[^\/]+/i','',$this->_requestUri);
  515. }
  516. elseif(isset($_SERVER['ORIG_PATH_INFO'])) // IIS 5.0 CGI
  517. {
  518. $this->_requestUri=$_SERVER['ORIG_PATH_INFO'];
  519. if(!empty($_SERVER['QUERY_STRING']))
  520. $this->_requestUri.='?'.$_SERVER['QUERY_STRING'];
  521. }
  522. else
  523. throw new CException(Yii::t('yii','CHttpRequest is unable to determine the request URI.'));
  524. }
  525. return $this->_requestUri;
  526. }
  527. /**
  528. * Returns part of the request URL that is after the question mark.
  529. * @return string part of the request URL that is after the question mark
  530. */
  531. public function getQueryString()
  532. {
  533. return isset($_SERVER['QUERY_STRING'])?$_SERVER['QUERY_STRING']:'';
  534. }
  535. /**
  536. * Return if the request is sent via secure channel (https).
  537. * @return boolean if the request is sent via secure channel (https)
  538. */
  539. public function getIsSecureConnection()
  540. {
  541. return isset($_SERVER['HTTPS']) && (strcasecmp($_SERVER['HTTPS'],'on')===0 || $_SERVER['HTTPS']==1)
  542. || isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && strcasecmp($_SERVER['HTTP_X_FORWARDED_PROTO'],'https')===0;
  543. }
  544. /**
  545. * Returns the request type, such as GET, POST, HEAD, PUT, PATCH, DELETE.
  546. * Request type can be manually set in POST requests with a parameter named _method. Useful
  547. * for RESTful request from older browsers which do not support PUT, PATCH or DELETE
  548. * natively (available since version 1.1.11).
  549. * @return string request type, such as GET, POST, HEAD, PUT, PATCH, DELETE.
  550. */
  551. public function getRequestType()
  552. {
  553. if(isset($_POST['_method']))
  554. return strtoupper($_POST['_method']);
  555. elseif(isset($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']))
  556. return strtoupper($_SERVER['HTTP_X_HTTP_METHOD_OVERRIDE']);
  557. return strtoupper(isset($_SERVER['REQUEST_METHOD'])?$_SERVER['REQUEST_METHOD']:'GET');
  558. }
  559. /**
  560. * Returns whether this is a POST request.
  561. * @return boolean whether this is a POST request.
  562. */
  563. public function getIsPostRequest()
  564. {
  565. return isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'POST');
  566. }
  567. /**
  568. * Returns whether this is a DELETE request.
  569. * @return boolean whether this is a DELETE request.
  570. * @since 1.1.7
  571. */
  572. public function getIsDeleteRequest()
  573. {
  574. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'DELETE')) || $this->getIsDeleteViaPostRequest();
  575. }
  576. /**
  577. * Returns whether this is a DELETE request which was tunneled through POST.
  578. * @return boolean whether this is a DELETE request tunneled through POST.
  579. * @since 1.1.11
  580. */
  581. protected function getIsDeleteViaPostRequest()
  582. {
  583. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'DELETE');
  584. }
  585. /**
  586. * Returns whether this is a PUT request.
  587. * @return boolean whether this is a PUT request.
  588. * @since 1.1.7
  589. */
  590. public function getIsPutRequest()
  591. {
  592. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'PUT')) || $this->getIsPutViaPostRequest();
  593. }
  594. /**
  595. * Returns whether this is a PUT request which was tunneled through POST.
  596. * @return boolean whether this is a PUT request tunneled through POST.
  597. * @since 1.1.11
  598. */
  599. protected function getIsPutViaPostRequest()
  600. {
  601. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'PUT');
  602. }
  603. /**
  604. * Returns whether this is a PATCH request.
  605. * @return boolean whether this is a PATCH request.
  606. * @since 1.1.16
  607. */
  608. public function getIsPatchRequest()
  609. {
  610. return (isset($_SERVER['REQUEST_METHOD']) && !strcasecmp($_SERVER['REQUEST_METHOD'],'PATCH')) || $this->getIsPatchViaPostRequest();
  611. }
  612. /**
  613. * Returns whether this is a PATCH request which was tunneled through POST.
  614. * @return boolean whether this is a PATCH request tunneled through POST.
  615. * @since 1.1.16
  616. */
  617. protected function getIsPatchViaPostRequest()
  618. {
  619. return isset($_POST['_method']) && !strcasecmp($_POST['_method'],'PATCH');
  620. }
  621. /**
  622. * Returns whether this is an AJAX (XMLHttpRequest) request.
  623. * @return boolean whether this is an AJAX (XMLHttpRequest) request.
  624. */
  625. public function getIsAjaxRequest()
  626. {
  627. return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']==='XMLHttpRequest';
  628. }
  629. /**
  630. * Returns whether this is an Adobe Flash or Adobe Flex request.
  631. * @return boolean whether this is an Adobe Flash or Adobe Flex request.
  632. * @since 1.1.11
  633. */
  634. public function getIsFlashRequest()
  635. {
  636. return isset($_SERVER['HTTP_USER_AGENT']) && (stripos($_SERVER['HTTP_USER_AGENT'],'Shockwave')!==false || stripos($_SERVER['HTTP_USER_AGENT'],'Flash')!==false);
  637. }
  638. /**
  639. * Returns the server name.
  640. * @return string server name
  641. */
  642. public function getServerName()
  643. {
  644. return $_SERVER['SERVER_NAME'];
  645. }
  646. /**
  647. * Returns the server port number.
  648. * @return integer server port number
  649. */
  650. public function getServerPort()
  651. {
  652. return $_SERVER['SERVER_PORT'];
  653. }
  654. /**
  655. * Returns the URL referrer, null if not present
  656. * @return string URL referrer, null if not present
  657. */
  658. public function getUrlReferrer()
  659. {
  660. return isset($_SERVER['HTTP_REFERER'])?$_SERVER['HTTP_REFERER']:null;
  661. }
  662. /**
  663. * Returns the user agent, null if not present.
  664. * @return string user agent, null if not present
  665. */
  666. public function getUserAgent()
  667. {
  668. return isset($_SERVER['HTTP_USER_AGENT'])?$_SERVER['HTTP_USER_AGENT']:null;
  669. }
  670. /**
  671. * Returns the user IP address.
  672. * @return string user IP address
  673. */
  674. public function getUserHostAddress()
  675. {
  676. return isset($_SERVER['REMOTE_ADDR'])?$_SERVER['REMOTE_ADDR']:'127.0.0.1';
  677. }
  678. /**
  679. * Returns the user host name, null if it cannot be determined.
  680. * @return string user host name, null if cannot be determined
  681. */
  682. public function getUserHost()
  683. {
  684. return isset($_SERVER['REMOTE_HOST'])?$_SERVER['REMOTE_HOST']:null;
  685. }
  686. /**
  687. * Returns entry script file path.
  688. * @return string entry script file path (processed w/ realpath())
  689. */
  690. public function getScriptFile()
  691. {
  692. if($this->_scriptFile!==null)
  693. return $this->_scriptFile;
  694. else
  695. return $this->_scriptFile=realpath($_SERVER['SCRIPT_FILENAME']);
  696. }
  697. /**
  698. * Returns information about the capabilities of user browser.
  699. * @param string $userAgent the user agent to be analyzed. Defaults to null, meaning using the
  700. * current User-Agent HTTP header information.
  701. * @return array user browser capabilities.
  702. * @see http://www.php.net/manual/en/function.get-browser.php
  703. */
  704. public function getBrowser($userAgent=null)
  705. {
  706. return get_browser($userAgent,true);
  707. }
  708. /**
  709. * Returns user browser accept types, null if not present.
  710. * @return string user browser accept types, null if not present
  711. */
  712. public function getAcceptTypes()
  713. {
  714. return isset($_SERVER['HTTP_ACCEPT'])?$_SERVER['HTTP_ACCEPT']:null;
  715. }
  716. /**
  717. * Returns request content-type
  718. * The Content-Type header field indicates the MIME type of the data
  719. * contained in {@link getRawBody()} or, in the case of the HEAD method, the
  720. * media type that would have been sent had the request been a GET.
  721. * @return string request content-type. Null is returned if this information is not available.
  722. * @link http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.17
  723. * HTTP 1.1 header field definitions
  724. * @since 1.1.17
  725. */
  726. public function getContentType()
  727. {
  728. if (isset($_SERVER["CONTENT_TYPE"])) {
  729. return $_SERVER["CONTENT_TYPE"];
  730. } elseif (isset($_SERVER["HTTP_CONTENT_TYPE"])) {
  731. //fix bug https://bugs.php.net/bug.php?id=66606
  732. return $_SERVER["HTTP_CONTENT_TYPE"];
  733. }
  734. return null;
  735. }
  736. private $_port;
  737. /**
  738. * Returns the port to use for insecure requests.
  739. * Defaults to 80, or the port specified by the server if the current
  740. * request is insecure.
  741. * You may explicitly specify it by setting the {@link setPort port} property.
  742. * @return integer port number for insecure requests.
  743. * @see setPort
  744. * @since 1.1.3
  745. */
  746. public function getPort()
  747. {
  748. if($this->_port===null)
  749. $this->_port=!$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 80;
  750. return $this->_port;
  751. }
  752. /**
  753. * Sets the port to use for insecure requests.
  754. * This setter is provided in case a custom port is necessary for certain
  755. * server configurations.
  756. * @param integer $value port number.
  757. * @since 1.1.3
  758. */
  759. public function setPort($value)
  760. {
  761. $this->_port=(int)$value;
  762. $this->_hostInfo=null;
  763. }
  764. private $_securePort;
  765. /**
  766. * Returns the port to use for secure requests.
  767. * Defaults to 443, or the port specified by the server if the current
  768. * request is secure.
  769. * You may explicitly specify it by setting the {@link setSecurePort securePort} property.
  770. * @return integer port number for secure requests.
  771. * @see setSecurePort
  772. * @since 1.1.3
  773. */
  774. public function getSecurePort()
  775. {
  776. if($this->_securePort===null)
  777. $this->_securePort=$this->getIsSecureConnection() && isset($_SERVER['SERVER_PORT']) ? (int)$_SERVER['SERVER_PORT'] : 443;
  778. return $this->_securePort;
  779. }
  780. /**
  781. * Sets the port to use for secure requests.
  782. * This setter is provided in case a custom port is necessary for certain
  783. * server configurations.
  784. * @param integer $value port number.
  785. * @since 1.1.3
  786. */
  787. public function setSecurePort($value)
  788. {
  789. $this->_securePort=(int)$value;
  790. $this->_hostInfo=null;
  791. }
  792. /**
  793. * Returns the cookie collection.
  794. * The result can be used like an associative array. Adding {@link CHttpCookie} objects
  795. * to the collection will send the cookies to the client; and removing the objects
  796. * from the collection will delete those cookies on the client.
  797. * @return CCookieCollection the cookie collection.
  798. */
  799. public function getCookies()
  800. {
  801. if($this->_cookies!==null)
  802. return $this->_cookies;
  803. else
  804. return $this->_cookies=new CCookieCollection($this);
  805. }
  806. /**
  807. * Redirects the browser to the specified URL.
  808. * @param string $url URL to be redirected to. Note that when URL is not
  809. * absolute (not starting with "/") it will be relative to current request URL.
  810. * @param boolean $terminate whether to terminate the current application
  811. * @param integer $statusCode the HTTP status code. Defaults to 302. See {@link http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html}
  812. * for details about HTTP status code.
  813. */
  814. public function redirect($url,$terminate=true,$statusCode=302)
  815. {
  816. if(strpos($url,'/')===0 && strpos($url,'//')!==0)
  817. $url=$this->getHostInfo().$url;
  818. header('Location: '.$url, true, $statusCode);
  819. if($terminate)
  820. Yii::app()->end();
  821. }
  822. /**
  823. * Parses an HTTP Accept header, returning an array map with all parts of each entry.
  824. * Each array entry consists of a map with the type, subType, baseType and params, an array map of key-value parameters,
  825. * obligatorily including a `q` value (i.e. preference ranking) as a double.
  826. * For example, an Accept header value of <code>'application/xhtml+xml;q=0.9;level=1'</code> would give an array entry of
  827. * <pre>
  828. * array(
  829. * 'type' => 'application',
  830. * 'subType' => 'xhtml',
  831. * 'baseType' => 'xml',
  832. * 'params' => array(
  833. * 'q' => 0.9,
  834. * 'level' => '1',
  835. * ),
  836. * )
  837. * </pre>
  838. *
  839. * <b>Please note:</b>
  840. * To avoid great complexity, there are no steps taken to ensure that quoted strings are treated properly.
  841. * If the header text includes quoted strings containing space or the , or ; characters then the results may not be correct!
  842. *
  843. * See also {@link http://tools.ietf.org/html/rfc2616#section-14.1} for details on Accept header.
  844. * @param string $header the accept header value to parse
  845. * @return array the user accepted MIME types.
  846. */
  847. public static function parseAcceptHeader($header)
  848. {
  849. $matches=array();
  850. $accepts=array();
  851. // get individual entries with their type, subtype, basetype and params
  852. preg_match_all('/(?:\G\s?,\s?|^)(\w+|\*)\/(\w+|\*)(?:\+(\w+))?|(?<!^)\G(?:\s?;\s?(\w+)=([\w\.]+))/',$header,$matches);
  853. // the regexp should (in theory) always return an array of 6 arrays
  854. if(count($matches)===6)
  855. {
  856. $i=0;
  857. $itemLen=count($matches[1]);
  858. while($i<$itemLen)
  859. {
  860. // fill out a content type
  861. $accept=array(
  862. 'type'=>$matches[1][$i],
  863. 'subType'=>$matches[2][$i],
  864. 'baseType'=>null,
  865. 'params'=>array(),
  866. );
  867. // fill in the base type if it exists
  868. if($matches[3][$i]!==null && $matches[3][$i]!=='')
  869. $accept['baseType']=$matches[3][$i];
  870. // continue looping while there is no new content type, to fill in all accompanying params
  871. for($i++;$i<$itemLen;$i++)
  872. {
  873. // if the next content type is null, then the item is a param for the current content type
  874. if($matches[1][$i]===null || $matches[1][$i]==='')
  875. {
  876. // if this is the quality param, convert it to a double
  877. if($matches[4][$i]==='q')
  878. {
  879. // sanity check on q value
  880. $q=(double)$matches[5][$i];
  881. if($q>1)
  882. $q=(double)1;
  883. elseif($q<0)
  884. $q=(double)0;
  885. $accept['params'][$matches[4][$i]]=$q;
  886. }
  887. else
  888. $accept['params'][$matches[4][$i]]=$matches[5][$i];
  889. }
  890. else
  891. break;
  892. }
  893. // q defaults to 1 if not explicitly given
  894. if(!isset($accept['params']['q']))
  895. $accept['params']['q']=(double)1;
  896. $accepts[] = $accept;
  897. }
  898. }
  899. return $accepts;
  900. }
  901. /**
  902. * Compare function for determining the preference of accepted MIME type array maps
  903. * See {@link parseAcceptHeader()} for the format of $a and $b
  904. * @param array $a user accepted MIME type as an array map
  905. * @param array $b user accepted MIME type as an array map
  906. * @return integer -1, 0 or 1 if $a has respectively greater preference, equal preference or less preference than $b (higher preference comes first).
  907. */
  908. public static function compareAcceptTypes($a,$b)
  909. {
  910. // check for equal quality first
  911. if($a['params']['q']===$b['params']['q'])
  912. if(!($a['type']==='*' xor $b['type']==='*'))
  913. if (!($a['subType']==='*' xor $b['subType']==='*'))
  914. // finally, higher number of parameters counts as greater precedence
  915. if(count($a['params'])===count($b['params']))
  916. return 0;
  917. else
  918. return count($a['params'])<count($b['params']) ? 1 : -1;
  919. // more specific takes precedence - whichever one doesn't have a * subType
  920. else
  921. return $a['subType']==='*' ? 1 : -1;
  922. // more specific takes precedence - whichever one doesn't have a * type
  923. else
  924. return $a['type']==='*' ? 1 : -1;
  925. else
  926. return ($a['params']['q']<$b['params']['q']) ? 1 : -1;
  927. }
  928. /**
  929. * Returns an array of user accepted MIME types in order of preference.
  930. * Each array entry consists of a map with the type, subType, baseType and params, an array map of key-value parameters.
  931. * See {@link parseAcceptHeader()} for a description of the array map.
  932. * @return array the user accepted MIME types, as array maps, in the order of preference.
  933. */
  934. public function getPreferredAcceptTypes()
  935. {
  936. if($this->_preferredAcceptTypes===null)
  937. {
  938. $accepts=self::parseAcceptHeader($this->getAcceptTypes());
  939. usort($accepts,array(get_class($this),'compareAcceptTypes'));
  940. $this->_preferredAcceptTypes=$accepts;
  941. }
  942. return $this->_preferredAcceptTypes;
  943. }
  944. /**
  945. * Returns the user preferred accept MIME type.
  946. * The MIME type is returned as an array map (see {@link parseAcceptHeader()}).
  947. * @return array the user preferred accept MIME type or false if the user does not have any.
  948. */
  949. public function getPreferredAcceptType()
  950. {
  951. $preferredAcceptTypes=$this->getPreferredAcceptTypes();
  952. return empty($preferredAcceptTypes) ? false : $preferredAcceptTypes[0];
  953. }
  954. /**
  955. * Returns an array of user accepted languages in order of preference.
  956. * The returned language IDs will NOT be canonicalized using {@link CLocale::getCanonicalID}.
  957. * @return array the user accepted languages in the order of preference.
  958. * See {@link http://tools.ietf.org/html/rfc2616#section-14.4}
  959. */
  960. public function getPreferredLanguages()
  961. {
  962. if($this->_preferredLanguages===null)
  963. {
  964. $sortedLanguages=array();
  965. if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE']) && $n=preg_match_all('/([\w\-_]+)(?:\s*;\s*q\s*=\s*(\d*\.?\d*))?/',$_SERVER['HTTP_ACCEPT_LANGUAGE'],$matches))
  966. {
  967. $languages=array();
  968. for($i=0;$i<$n;++$i)
  969. {
  970. $q=$matches[2][$i];
  971. if($q==='')
  972. $q=1;
  973. if($q)
  974. $languages[]=array((float)$q,$matches[1][$i]);
  975. }
  976. usort($languages,create_function('$a,$b','if($a[0]==$b[0]) {return 0;} return ($a[0]<$b[0]) ? 1 : -1;'));
  977. foreach($languages as $language)
  978. $sortedLanguages[]=$language[1];
  979. }
  980. $this->_preferredLanguages=$sortedLanguages;
  981. }
  982. return $this->_preferredLanguages;
  983. }
  984. /**
  985. * Returns the user-preferred language that should be used by this application.
  986. * The language resolution is based on the user preferred languages and the languages
  987. * supported by the application. The method will try to find the best match.
  988. * @param array $languages a list of the languages supported by the application.
  989. * If empty, this method will return the first language returned by [[getPreferredLanguages()]].
  990. * @return string the language that the application should use. false is returned if both [[getPreferredLanguages()]]
  991. * and `$languages` are empty.
  992. */
  993. public function getPreferredLanguage($languages=array())
  994. {
  995. $preferredLanguages=$this->getPreferredLanguages();
  996. if(empty($languages)) {
  997. return !empty($preferredLanguages) ? CLocale::getCanonicalID($preferredLanguages[0]) : false;
  998. }
  999. foreach ($preferredLanguages as $preferredLanguage) {
  1000. $preferredLanguage=CLocale::getCanonicalID($preferredLanguage);
  1001. foreach ($languages as $language) {
  1002. $language=CLocale::getCanonicalID($language);
  1003. // en_us==en_us, en==en_us, en_us==en
  1004. if($language===$preferredLanguage || strpos($preferredLanguage,$language.'_')===0 || strpos($language,$preferredLanguage.'_')===0) {
  1005. return $language;
  1006. }
  1007. }
  1008. }
  1009. return reset($languages);
  1010. }
  1011. /**
  1012. * Sends a file to user.
  1013. * @param string $fileName file name
  1014. * @param string $content content to be set.
  1015. * @param string $mimeType mime type of the content. If null, it will be guessed automatically based on the given file name.
  1016. * @param boolean $terminate whether to terminate the current application after calling this method
  1017. */
  1018. public function sendFile($fileName,$content,$mimeType=null,$terminate=true)
  1019. {
  1020. if($mimeType===null)
  1021. {
  1022. if(($mimeType=CFileHelper::getMimeTypeByExtension($fileName))===null)
  1023. $mimeType='text/plain';
  1024. }
  1025. $fileSize=(function_exists('mb_strlen') ? mb_strlen($content,'8bit') : strlen($content));
  1026. $contentStart=0;
  1027. $contentEnd=$fileSize-1;
  1028. $httpVersion=$this->getHttpVersion();
  1029. if(isset($_SERVER['HTTP_RANGE']))
  1030. {
  1031. header('Accept-Ranges: bytes');
  1032. //client sent us a multibyte range, can not hold this one for now
  1033. if(strpos($_SERVER['HTTP_RANGE'],',')!==false)
  1034. {
  1035. header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
  1036. throw new CHttpException(416,'Requested Range Not Satisfiable');
  1037. }
  1038. $range=str_replace('bytes=','',$_SERVER['HTTP_RANGE']);
  1039. //range requests starts from "-", so it means that data must be dumped the end point.
  1040. if($range[0]==='-')
  1041. $contentStart=$fileSize-substr($range,1);
  1042. else
  1043. {
  1044. $range=explode('-',$range);
  1045. $contentStart=$range[0];
  1046. // check if the last-byte-pos presents in header
  1047. if((isset($range[1]) && is_numeric($range[1])))
  1048. $contentEnd=$range[1];
  1049. }
  1050. /* Check the range and make sure it's treated according to the specs.
  1051. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
  1052. */
  1053. // End bytes can not be larger than $end.
  1054. $contentEnd=($contentEnd > $fileSize) ? $fileSize-1 : $contentEnd;
  1055. // Validate the requested range and return an error if it's not correct.
  1056. $wrongContentStart=($contentStart>$contentEnd || $contentStart>$fileSize-1 || $contentStart<0);
  1057. if($wrongContentStart)
  1058. {
  1059. header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
  1060. throw new CHttpException(416,'Requested Range Not Satisfiable');
  1061. }
  1062. header("HTTP/$httpVersion 206 Partial Content");
  1063. header("Content-Range: bytes $contentStart-$contentEnd/$fileSize");
  1064. }
  1065. else
  1066. header("HTTP/$httpVersion 200 OK");
  1067. $length=$contentEnd-$contentStart+1; // Calculate new content length
  1068. header('Pragma: public');
  1069. header('Expires: 0');
  1070. header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
  1071. header("Content-Type: $mimeType");
  1072. header('Content-Length: '.$length);
  1073. header("Content-Disposition: attachment; filename=\"$fileName\"");
  1074. header('Content-Transfer-Encoding: binary');
  1075. $content=function_exists('mb_substr') ? mb_substr($content,$contentStart,$length,'8bit') : substr($content,$contentStart,$length);
  1076. if($terminate)
  1077. {
  1078. // clean up the application first because the file downloading could take long time
  1079. // which may cause timeout of some resources (such as DB connection)
  1080. ob_start();
  1081. Yii::app()->end(0,false);
  1082. ob_end_clean();
  1083. echo $content;
  1084. exit(0);
  1085. }
  1086. else
  1087. echo $content;
  1088. }
  1089. /**
  1090. * Sends existing file to a browser as a download using x-sendfile.
  1091. *
  1092. * X-Sendfile is a feature allowing a web application to redirect the request for a file to the webserver
  1093. * that in turn processes the request, this way eliminating the need to perform tasks like reading the file
  1094. * and sending it to the user. When dealing with a lot of files (or very big files) this can lead to a great
  1095. * increase in performance as the web application is allowed to terminate earlier while the webserver is
  1096. * handling the request.
  1097. *
  1098. * The request is sent to the server through a special non-standard HTTP-header.
  1099. * When the web server encounters the presence of such header it will discard all output and send the file
  1100. * specified by that header using web server internals including all optimizations like caching-headers.
  1101. *
  1102. * As this header directive is non-standard different directives exists for different web servers applications:
  1103. * <ul>
  1104. * <li>Apache: {@link http://tn123.org/mod_xsendfile X-Sendfile}</li>
  1105. * <li>Lighttpd v1.4: {@link http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file X-LIGHTTPD-send-file}</li>
  1106. * <li>Lighttpd v1.5: {@link http://redmine.lighttpd.net/projects/lighttpd/wiki/X-LIGHTTPD-send-file X-Sendfile}</li>
  1107. * <li>Nginx: {@link http://wiki.nginx.org/XSendfile X-Accel-Redirect}</li>
  1108. * <li>Cherokee: {@link http://www.cherokee-project.com/doc/other_goodies.html#x-sendfile X-Sendfile and X-Accel-Redirect}</li>
  1109. * </ul>
  1110. * So for this method to work the X-SENDFILE option/module should be enabled by the web server and
  1111. * a proper xHeader should be sent.
  1112. *
  1113. * <b>Note:</b>
  1114. * This option allows to download files that are not under web folders, and even files that are otherwise protected (deny from all) like .htaccess
  1115. *
  1116. * <b>Side effects</b>:
  1117. * If this option is disabled by the web server, when this method is called a download configuration dialog
  1118. * will open but the downloaded file will have 0 bytes.
  1119. *
  1120. * <b>Known issues</b>:
  1121. * There is a Bug with Internet Explorer 6, 7 and 8 when X-SENDFILE is used over an SSL connection, it will show
  1122. * 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.".
  1123. * You can work around this problem by removing the <code>Pragma</code>-header.
  1124. *
  1125. * <b>Example</b>:
  1126. * <pre>
  1127. * <?php
  1128. * Yii::app()->request->xSendFile('/home/user/Pictures/picture1.jpg',array(
  1129. * 'saveName'=>'image1.jpg',
  1130. * 'mimeType'=>'image/jpeg',
  1131. * 'terminate'=>false,
  1132. * ));
  1133. * ?>
  1134. * </pre>
  1135. * @param string $filePath file name with full path
  1136. * @param array $options additional options:
  1137. * <ul>
  1138. * <li>saveName: file name shown to the user, if not set real file name will be used</li>
  1139. * <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>
  1140. * <li>xHeader: appropriate x-sendfile header, defaults to "X-Sendfile"</li>
  1141. * <li>terminate: whether to terminate the current application after calling this method, defaults to true</li>
  1142. * <li>forceDownload: specifies whether the file will be downloaded or shown inline, defaults to true. (Since version 1.1.9.)</li>
  1143. * <li>addHeaders: an array of additional http headers in header-value pairs (available since version 1.1.10)</li>
  1144. * </ul>
  1145. */
  1146. public function xSendFile($filePath, $options=array())
  1147. {
  1148. if(!isset($options['forceDownload']) || $options['forceDownload'])
  1149. $disposition='attachment';
  1150. else
  1151. $disposition='inline';
  1152. if(!isset($options['saveName']))
  1153. $options['saveName']=basename($filePath);
  1154. if(!isset($options['mimeType']))
  1155. {
  1156. if(($options['mimeType']=CFileHelper::getMimeTypeByExtension($filePath))===null)
  1157. $options['mimeType']='text/plain';
  1158. }
  1159. if(!isset($options['xHeader']))
  1160. $options['xHeader']='X-Sendfile';
  1161. if($options['mimeType']!==null)
  1162. header('Content-Type: '.$options['mimeType']);
  1163. header('Content-Disposition: '.$disposition.'; filename="'.$options['saveName'].'"');
  1164. if(isset($options['addHeaders']))
  1165. {
  1166. foreach($options['addHeaders'] as $header=>$value)
  1167. header($header.': '.$value);
  1168. }
  1169. header(trim($options['xHeader']).': '.$filePath);
  1170. if(!isset($options['terminate']) || $options['terminate'])
  1171. Yii::app()->end();
  1172. }
  1173. /**
  1174. * Returns the random token used to perform CSRF validation.
  1175. * The token will be read from cookie first. If not found, a new token
  1176. * will be generated.
  1177. * @return string the random token for CSRF validation.
  1178. * @see enableCsrfValidation
  1179. */
  1180. public function getCsrfToken()
  1181. {
  1182. if($this->_csrfToken===null)
  1183. {
  1184. $cookie=$this->getCookies()->itemAt($this->csrfTokenName);
  1185. if(!$cookie || ($this->_csrfToken=$cookie->value)==null)
  1186. {
  1187. $cookie=$this->createCsrfCookie();
  1188. $this->_csrfToken=$cookie->value;
  1189. $this->getCookies()->add($cookie->name,$cookie);
  1190. }
  1191. }
  1192. return $this->_csrfToken;
  1193. }
  1194. /**
  1195. * Creates a cookie with a randomly generated CSRF token.
  1196. * Initial values specified in {@link csrfCookie} will be applied
  1197. * to the generated cookie.
  1198. * @return CHttpCookie the generated cookie
  1199. * @see enableCsrfValidation
  1200. */
  1201. protected function createCsrfCookie()
  1202. {
  1203. $cookie=new CHttpCookie($this->csrfTokenName,sha1(uniqid(mt_rand(),true)));
  1204. if(is_array($this->csrfCookie))
  1205. {
  1206. foreach($this->csrfCookie as $name=>$value)
  1207. $cookie->$name=$value;
  1208. }
  1209. return $cookie;
  1210. }
  1211. /**
  1212. * Performs the CSRF validation.
  1213. * This is the event handler responding to {@link CApplication::onBeginRequest}.
  1214. * The default implementation will compare the CSRF token obtained
  1215. * from a cookie and from a POST field. If they are different, a CSRF attack is detected.
  1216. * @param CEvent $event event parameter
  1217. * @throws CHttpException if the validation fails
  1218. */
  1219. public function validateCsrfToken($event)
  1220. {
  1221. if ($this->getIsPostRequest() ||
  1222. $this->getIsPutRequest() ||
  1223. $this->getIsPatchRequest() ||
  1224. $this->getIsDeleteRequest())
  1225. {
  1226. $cookies=$this->getCookies();
  1227. $method=$this->getRequestType();
  1228. switch($method)
  1229. {
  1230. case 'POST':
  1231. $userToken=$this->getPost($this->csrfTokenName);
  1232. break;
  1233. case 'PUT':
  1234. $userToken=$this->getPut($this->csrfTokenName);
  1235. break;
  1236. case 'PATCH':
  1237. $userToken=$this->getPatch($this->csrfTokenName);
  1238. break;
  1239. case 'DELETE':
  1240. $userToken=$this->getDelete($this->csrfTokenName);
  1241. }
  1242. if (!empty($userToken) && $cookies->contains($this->csrfTokenName))
  1243. {
  1244. $cookieToken=$cookies->itemAt($this->csrfTokenName)->value;
  1245. $valid=$cookieToken===$userToken;
  1246. }
  1247. else
  1248. $valid = false;
  1249. if (!$valid)
  1250. throw new CHttpException(400,Yii::t('yii','The CSRF token could not be verified.'));
  1251. }
  1252. }
  1253. /**
  1254. * Returns the version of the HTTP protocol used by client.
  1255. *
  1256. * @return string the version of the HTTP protocol.
  1257. * @since 1.1.16
  1258. */
  1259. public function getHttpVersion()
  1260. {
  1261. if($this->_httpVersion===null)
  1262. {
  1263. if(isset($_SERVER['SERVER_PROTOCOL']) && $_SERVER['SERVER_PROTOCOL']==='HTTP/1.0')
  1264. $this->_httpVersion='1.0';
  1265. else
  1266. $this->_httpVersion='1.1';
  1267. }
  1268. return $this->_httpVersion;
  1269. }
  1270. }
  1271. /**
  1272. * CCookieCollection implements a collection class to store cookies.
  1273. *
  1274. * You normally access it via {@link CHttpRequest::getCookies()}.
  1275. *
  1276. * Since CCookieCollection extends from {@link CMap}, it can be used
  1277. * like an associative array as follows:
  1278. * <pre>
  1279. * $cookies[$name]=new CHttpCookie($name,$value); // sends a cookie
  1280. * $value=$cookies[$name]->value; // reads a cookie value
  1281. * unset($cookies[$name]); // removes a cookie
  1282. * </pre>
  1283. *
  1284. * @author Qiang Xue <qiang.xue@gmail.com>
  1285. * @package system.web
  1286. * @since 1.0
  1287. */
  1288. class CCookieCollection extends CMap
  1289. {
  1290. private $_request;
  1291. private $_initialized=false;
  1292. /**
  1293. * Constructor.
  1294. * @param CHttpRequest $request owner of this collection.
  1295. */
  1296. public function __construct(CHttpRequest $request)
  1297. {
  1298. $this->_request=$request;
  1299. $this->copyfrom($this->getCookies());
  1300. $this->_initialized=true;
  1301. }
  1302. /**
  1303. * @return CHttpRequest the request instance
  1304. */
  1305. public function getRequest()
  1306. {
  1307. return $this->_request;
  1308. }
  1309. /**
  1310. * @retur