PageRenderTime 67ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/Framework/framework/web/CHttpRequest.php

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