CHttpRequest.php 47 KB

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