sfWebRequest.class.php 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174
  1. <?php
  2. /*
  3. * This file is part of the symfony package.
  4. * (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
  5. * (c) 2004-2006 Sean Kerr <sean@code-box.org>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. /**
  11. * sfWebRequest class.
  12. *
  13. * This class manages web requests. It parses input from the request and store them as parameters.
  14. *
  15. * @package symfony
  16. * @subpackage request
  17. * @author Fabien Potencier <fabien.potencier@symfony-project.com>
  18. * @author Sean Kerr <sean@code-box.org>
  19. * @version SVN: $Id: sfWebRequest.class.php 17975 2009-05-06 09:04:00Z fabien $
  20. */
  21. class sfWebRequest extends sfRequest
  22. {
  23. protected
  24. $languages = null,
  25. $charsets = null,
  26. $acceptableContentTypes = null,
  27. $pathInfoArray = null,
  28. $relativeUrlRoot = null,
  29. $getParameters = null,
  30. $postParameters = null,
  31. $requestParameters = null,
  32. $formats = array(),
  33. $format = null,
  34. $fixedFileArray = false;
  35. /**
  36. * Initializes this sfRequest.
  37. *
  38. * @param sfEventDispatcher $dispatcher An sfEventDispatcher instance
  39. * @param array $parameters An associative array of initialization parameters
  40. * @param array $attributes An associative array of initialization attributes
  41. *
  42. * @return bool true, if initialization completes successfully, otherwise false
  43. *
  44. * @throws <b>sfInitializationException</b> If an error occurs while initializing this sfRequest
  45. */
  46. public function initialize(sfEventDispatcher $dispatcher, $parameters = array(), $attributes = array())
  47. {
  48. parent::initialize($dispatcher, $parameters, $attributes);
  49. if (isset($_SERVER['REQUEST_METHOD']))
  50. {
  51. switch ($_SERVER['REQUEST_METHOD'])
  52. {
  53. case 'GET':
  54. $this->setMethod(self::GET);
  55. break;
  56. case 'POST':
  57. $this->setMethod(self::POST);
  58. break;
  59. case 'PUT':
  60. $this->setMethod(self::PUT);
  61. break;
  62. case 'DELETE':
  63. $this->setMethod(self::DELETE);
  64. break;
  65. case 'HEAD':
  66. $this->setMethod(self::HEAD);
  67. break;
  68. default:
  69. $this->setMethod(self::GET);
  70. }
  71. }
  72. else
  73. {
  74. // set the default method
  75. $this->setMethod(self::GET);
  76. }
  77. foreach ($this->getAttribute('formats', array()) as $format => $mimeTypes)
  78. {
  79. $this->setFormat($format, $mimeTypes);
  80. }
  81. // load parameters from GET/PATH_INFO/POST
  82. $this->loadParameters();
  83. }
  84. /**
  85. * Retrieves an array of file information.
  86. *
  87. * @param string $name A file name
  88. *
  89. * @return array An associative array of file information, if the file exists, otherwise null
  90. */
  91. public function getFile($name)
  92. {
  93. if (!sfConfig::get('sf_compat_10'))
  94. {
  95. throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
  96. }
  97. return $this->hasFile($name) ? $this->getFileValues($name) : null;
  98. }
  99. /**
  100. * Retrieves a file error.
  101. *
  102. * @param string $name A file name
  103. *
  104. * @return int One of the following error codes:
  105. *
  106. * - <b>UPLOAD_ERR_OK</b> (no error)
  107. * - <b>UPLOAD_ERR_INI_SIZE</b> (the uploaded file exceeds the
  108. * upload_max_filesize directive
  109. * in php.ini)
  110. * - <b>UPLOAD_ERR_FORM_SIZE</b> (the uploaded file exceeds the
  111. * MAX_FILE_SIZE directive that
  112. * was specified in the HTML form)
  113. * - <b>UPLOAD_ERR_PARTIAL</b> (the uploaded file was only
  114. * partially uploaded)
  115. * - <b>UPLOAD_ERR_NO_FILE</b> (no file was uploaded)
  116. */
  117. public function getFileError($name)
  118. {
  119. if (!sfConfig::get('sf_compat_10'))
  120. {
  121. throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
  122. }
  123. return $this->hasFile($name) ? $this->getFileValue($name, 'error') : UPLOAD_ERR_NO_FILE;
  124. }
  125. /**
  126. * Retrieves a file name.
  127. *
  128. * @param string $name A file nam.
  129. *
  130. * @return string A file name, if the file exists, otherwise null
  131. */
  132. public function getFileName($name)
  133. {
  134. if (!sfConfig::get('sf_compat_10'))
  135. {
  136. throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
  137. }
  138. return $this->hasFile($name) ? $this->getFileValue($name, 'name') : null;
  139. }
  140. /**
  141. * Retrieves an array of file names.
  142. *
  143. * @return array An indexed array of file names
  144. */
  145. public function getFileNames()
  146. {
  147. if (!sfConfig::get('sf_compat_10'))
  148. {
  149. throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
  150. }
  151. return array_keys($_FILES);
  152. }
  153. /**
  154. * Retrieves an array of files.
  155. *
  156. * @param string $key A key
  157. * @return array An associative array of files
  158. */
  159. public function getFiles($key = null)
  160. {
  161. if (false === $this->fixedFileArray)
  162. {
  163. $this->fixedFileArray = self::convertFileInformation($_FILES);
  164. }
  165. return is_null($key) ? $this->fixedFileArray : (isset($this->fixedFileArray[$key]) ? $this->fixedFileArray[$key] : array());
  166. }
  167. /**
  168. * Converts uploaded file array to a format following the $_GET and $POST naming convention.
  169. *
  170. * It's safe to pass an already converted array, in which case this method just returns the original array unmodified.
  171. *
  172. * @param array $taintedFiles An array representing uploaded file information
  173. *
  174. * @return array An array of re-ordered uploaded file information
  175. */
  176. static public function convertFileInformation(array $taintedFiles)
  177. {
  178. $files = array();
  179. foreach ($taintedFiles as $key => $data)
  180. {
  181. $files[$key] = self::fixPhpFilesArray($data);
  182. }
  183. return $files;
  184. }
  185. static protected function fixPhpFilesArray($data)
  186. {
  187. $fileKeys = array('error', 'name', 'size', 'tmp_name', 'type');
  188. $keys = array_keys($data);
  189. sort($keys);
  190. if ($fileKeys != $keys || !isset($data['name']) || !is_array($data['name']))
  191. {
  192. return $data;
  193. }
  194. $files = $data;
  195. foreach ($fileKeys as $k)
  196. {
  197. unset($files[$k]);
  198. }
  199. foreach (array_keys($data['name']) as $key)
  200. {
  201. $files[$key] = self::fixPhpFilesArray(array(
  202. 'error' => $data['error'][$key],
  203. 'name' => $data['name'][$key],
  204. 'type' => $data['type'][$key],
  205. 'tmp_name' => $data['tmp_name'][$key],
  206. 'size' => $data['size'][$key],
  207. ));
  208. }
  209. return $files;
  210. }
  211. /**
  212. * Retrieves a file path.
  213. *
  214. * @param string $name A file name
  215. *
  216. * @return string A file path, if the file exists, otherwise null
  217. */
  218. public function getFilePath($name)
  219. {
  220. if (!sfConfig::get('sf_compat_10'))
  221. {
  222. throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
  223. }
  224. return $this->hasFile($name) ? $this->getFileValue($name, 'tmp_name') : null;
  225. }
  226. /**
  227. * Retrieve a file size.
  228. *
  229. * @param string $name A file name
  230. *
  231. * @return int A file size, if the file exists, otherwise null
  232. */
  233. public function getFileSize($name)
  234. {
  235. if (!sfConfig::get('sf_compat_10'))
  236. {
  237. throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
  238. }
  239. return $this->hasFile($name) ? $this->getFileValue($name, 'size') : null;
  240. }
  241. /**
  242. * Retrieves a file type.
  243. *
  244. * This may not be accurate. This is the mime-type sent by the browser
  245. * during the upload.
  246. *
  247. * @param string $name A file name
  248. *
  249. * @return string A file type, if the file exists, otherwise null
  250. */
  251. public function getFileType($name)
  252. {
  253. if (!sfConfig::get('sf_compat_10'))
  254. {
  255. throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
  256. }
  257. return $this->hasFile($name) ? $this->getFileValue($name, 'type') : null;
  258. }
  259. /**
  260. * Indicates whether or not a file exists.
  261. *
  262. * @param string $name A file name
  263. *
  264. * @return bool true, if the file exists, otherwise false
  265. */
  266. public function hasFile($name)
  267. {
  268. if (!sfConfig::get('sf_compat_10'))
  269. {
  270. throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
  271. }
  272. if (preg_match('/^(.+?)\[(.+?)\]$/', $name, $match))
  273. {
  274. return isset($_FILES[$match[1]]['name'][$match[2]]);
  275. }
  276. else
  277. {
  278. return isset($_FILES[$name]);
  279. }
  280. }
  281. /**
  282. * Indicates whether or not a file error exists.
  283. *
  284. * @param string $name A file name
  285. *
  286. * @return bool true, if the file error exists, otherwise false
  287. */
  288. public function hasFileError($name)
  289. {
  290. if (!sfConfig::get('sf_compat_10'))
  291. {
  292. throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
  293. }
  294. return $this->hasFile($name) ? ($this->getFileValue($name, 'error') != UPLOAD_ERR_OK) : false;
  295. }
  296. /**
  297. * Indicates whether or not any file errors occured.
  298. *
  299. * @return bool true, if any file errors occured, otherwise false
  300. */
  301. public function hasFileErrors()
  302. {
  303. if (!sfConfig::get('sf_compat_10'))
  304. {
  305. throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
  306. }
  307. foreach ($this->getFileNames() as $name)
  308. {
  309. if ($this->hasFileError($name) === true)
  310. {
  311. return true;
  312. }
  313. }
  314. return false;
  315. }
  316. /**
  317. * Indicates whether or not any files exist.
  318. *
  319. * @return boolean true, if any files exist, otherwise false
  320. */
  321. public function hasFiles()
  322. {
  323. if (!sfConfig::get('sf_compat_10'))
  324. {
  325. throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
  326. }
  327. return (count($_FILES) > 0);
  328. }
  329. /**
  330. * Retrieves a file value.
  331. *
  332. * @param string $name A file name
  333. * @param string $key Value to search in the file
  334. *
  335. * @return string File value
  336. */
  337. public function getFileValue($name, $key)
  338. {
  339. if (!sfConfig::get('sf_compat_10'))
  340. {
  341. throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
  342. }
  343. if (preg_match('/^(.+?)\[(.+?)\]$/', $name, $match))
  344. {
  345. return $_FILES[$match[1]][$key][$match[2]];
  346. }
  347. else
  348. {
  349. return $_FILES[$name][$key];
  350. }
  351. }
  352. /**
  353. * Retrieves all the values from a file.
  354. *
  355. * @param string $name A file name
  356. *
  357. * @return array Associative list of the file values
  358. */
  359. public function getFileValues($name)
  360. {
  361. if (!sfConfig::get('sf_compat_10'))
  362. {
  363. throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
  364. }
  365. if (preg_match('/^(.+?)\[(.+?)\]$/', $name, $match))
  366. {
  367. return array(
  368. 'name' => $_FILES[$match[1]]['name'][$match[2]],
  369. 'type' => $_FILES[$match[1]]['type'][$match[2]],
  370. 'tmp_name' => $_FILES[$match[1]]['tmp_name'][$match[2]],
  371. 'error' => $_FILES[$match[1]]['error'][$match[2]],
  372. 'size' => $_FILES[$match[1]]['size'][$match[2]],
  373. );
  374. }
  375. else
  376. {
  377. return $_FILES[$name];
  378. }
  379. }
  380. /**
  381. * Retrieves an extension for a given file.
  382. *
  383. * @param string $name A file name
  384. *
  385. * @return string Extension for the file
  386. */
  387. public function getFileExtension($name)
  388. {
  389. if (!sfConfig::get('sf_compat_10'))
  390. {
  391. throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
  392. }
  393. static $mimeTypes = null;
  394. $fileType = $this->getFileType($name);
  395. if (!$fileType)
  396. {
  397. return '.bin';
  398. }
  399. if (is_null($mimeTypes))
  400. {
  401. $mimeTypes = unserialize(file_get_contents(sfConfig::get('sf_symfony_lib_dir').'/plugins/sfCompat10Plugin/data/mime_types.dat'));
  402. }
  403. return isset($mimeTypes[$fileType]) ? '.'.$mimeTypes[$fileType] : '.bin';
  404. }
  405. /**
  406. * Retrieves the uniform resource identifier for the current web request.
  407. *
  408. * @return string Unified resource identifier
  409. */
  410. public function getUri()
  411. {
  412. $pathArray = $this->getPathInfoArray();
  413. // for IIS with rewrite module (IIFR, ISAPI Rewrite, ...)
  414. if ('HTTP_X_REWRITE_URL' == sfConfig::get('sf_path_info_key'))
  415. {
  416. $uri = isset($pathArray['HTTP_X_REWRITE_URL']) ? $pathArray['HTTP_X_REWRITE_URL'] : '';
  417. }
  418. else
  419. {
  420. $uri = isset($pathArray['REQUEST_URI']) ? $pathArray['REQUEST_URI'] : '';
  421. }
  422. return $this->isAbsUri() ? $uri : $this->getUriPrefix().$uri;
  423. }
  424. /**
  425. * See if the client is using absolute uri
  426. *
  427. * @return boolean true, if is absolute uri otherwise false
  428. */
  429. public function isAbsUri()
  430. {
  431. $pathArray = $this->getPathInfoArray();
  432. return preg_match('/^http/', $pathArray['REQUEST_URI']);
  433. }
  434. /**
  435. * Returns Uri prefix, including protocol, hostname and server port.
  436. *
  437. * @return string Uniform resource identifier prefix
  438. */
  439. public function getUriPrefix()
  440. {
  441. $pathArray = $this->getPathInfoArray();
  442. if ($this->isSecure())
  443. {
  444. $standardPort = '443';
  445. $protocol = 'https';
  446. }
  447. else
  448. {
  449. $standardPort = '80';
  450. $protocol = 'http';
  451. }
  452. $host = explode(":", $this->getHost());
  453. if (count($host) == 1)
  454. {
  455. $host[] = isset($pathArray['SERVER_PORT']) ? $pathArray['SERVER_PORT'] : '';
  456. }
  457. if ($host[1] == $standardPort || empty($host[1]))
  458. {
  459. unset($host[1]);
  460. }
  461. return $protocol.'://'.implode(':', $host);;
  462. }
  463. /**
  464. * Retrieves the path info for the current web request.
  465. *
  466. * @return string Path info
  467. */
  468. public function getPathInfo()
  469. {
  470. $pathInfo = '';
  471. $pathArray = $this->getPathInfoArray();
  472. // simulate PATH_INFO if needed
  473. $sf_path_info_key = sfConfig::get('sf_path_info_key', 'PATH_INFO');
  474. if (!isset($pathArray[$sf_path_info_key]) || !$pathArray[$sf_path_info_key])
  475. {
  476. if (isset($pathArray['REQUEST_URI']))
  477. {
  478. $script_name = $this->getScriptName();
  479. $uri_prefix = $this->isAbsUri() ? $this->getUriPrefix() : '';
  480. $pathInfo = preg_replace('/^'.preg_quote($uri_prefix, '/').'/','',$pathArray['REQUEST_URI']);
  481. $pathInfo = preg_replace('/^'.preg_quote($script_name, '/').'/', '', $pathInfo);
  482. $prefix_name = preg_replace('#/[^/]+$#', '', $script_name);
  483. $pathInfo = preg_replace('/^'.preg_quote($prefix_name, '/').'/', '', $pathInfo);
  484. $pathInfo = preg_replace('/\??'.preg_quote($pathArray['QUERY_STRING'], '/').'$/', '', $pathInfo);
  485. }
  486. }
  487. else
  488. {
  489. $pathInfo = $pathArray[$sf_path_info_key];
  490. if ($sf_relative_url_root = $this->getRelativeUrlRoot())
  491. {
  492. $pathInfo = preg_replace('/^'.str_replace('/', '\\/', $sf_relative_url_root).'\//', '', $pathInfo);
  493. }
  494. }
  495. // for IIS
  496. if (isset($_SERVER['SERVER_SOFTWARE']) && false !== stripos($_SERVER['SERVER_SOFTWARE'], 'iis') && $pos = stripos($pathInfo, '.php'))
  497. {
  498. $pathInfo = substr($pathInfo, $pos + 4);
  499. }
  500. if (!$pathInfo)
  501. {
  502. $pathInfo = '/';
  503. }
  504. return $pathInfo;
  505. }
  506. public function getGetParameters()
  507. {
  508. return $this->getParameters;
  509. }
  510. public function getPostParameters()
  511. {
  512. return $this->postParameters;
  513. }
  514. public function getRequestParameters()
  515. {
  516. return $this->requestParameters;
  517. }
  518. /**
  519. * Moves an uploaded file.
  520. *
  521. * @param string $name A file name
  522. * @param string $file An absolute filesystem path to where you would like the
  523. * file moved. This includes the new filename as well, since
  524. * uploaded files are stored with random names
  525. * @param int $fileMode The octal mode to use for the new file
  526. * @param bool $create Indicates that we should make the directory before moving the file
  527. * @param int $dirMode The octal mode to use when creating the directory
  528. *
  529. * @return bool true, if the file was moved, otherwise false
  530. *
  531. * @throws <b>sfFileException</b> If a major error occurs while attempting to move the file
  532. */
  533. public function moveFile($name, $file, $fileMode = 0666, $create = true, $dirMode = 0777)
  534. {
  535. if (!sfConfig::get('sf_compat_10'))
  536. {
  537. throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
  538. }
  539. if ($this->hasFile($name) && $this->getFileValue($name, 'error') == UPLOAD_ERR_OK && $this->getFileValue($name, 'size') > 0)
  540. {
  541. // get our directory path from the destination filename
  542. $directory = dirname($file);
  543. if (!is_readable($directory))
  544. {
  545. $fmode = 0777;
  546. if ($create && !@mkdir($directory, $dirMode, true))
  547. {
  548. // failed to create the directory
  549. throw new sfFileException(sprintf('Failed to create file upload directory "%s".', $directory));
  550. }
  551. // chmod the directory since it doesn't seem to work on
  552. // recursive paths
  553. @chmod($directory, $dirMode);
  554. }
  555. else if (!is_dir($directory))
  556. {
  557. // the directory path exists but it's not a directory
  558. throw new sfFileException(sprintf('File upload path "%s" exists, but is not a directory.', $directory));
  559. }
  560. else if (!is_writable($directory))
  561. {
  562. // the directory isn't writable
  563. throw new sfFileException(sprintf('File upload path "%s" is not writable.', $directory));
  564. }
  565. if (@move_uploaded_file($this->getFileValue($name, 'tmp_name'), $file))
  566. {
  567. // chmod our file
  568. @chmod($file, $fileMode);
  569. return true;
  570. }
  571. }
  572. return false;
  573. }
  574. /**
  575. * Returns referer.
  576. *
  577. * @return string
  578. */
  579. public function getReferer()
  580. {
  581. $pathArray = $this->getPathInfoArray();
  582. return isset($pathArray['HTTP_REFERER']) ? $pathArray['HTTP_REFERER'] : '';
  583. }
  584. /**
  585. * Returns current host name.
  586. *
  587. * @return string
  588. */
  589. public function getHost()
  590. {
  591. $pathArray = $this->getPathInfoArray();
  592. return isset($pathArray['HTTP_X_FORWARDED_HOST']) ? $pathArray['HTTP_X_FORWARDED_HOST'] : (isset($pathArray['HTTP_HOST']) ? $pathArray['HTTP_HOST'] : '');
  593. }
  594. /**
  595. * Returns current script name.
  596. *
  597. * @return string
  598. */
  599. public function getScriptName()
  600. {
  601. $pathArray = $this->getPathInfoArray();
  602. return isset($pathArray['SCRIPT_NAME']) ? $pathArray['SCRIPT_NAME'] : (isset($pathArray['ORIG_SCRIPT_NAME']) ? $pathArray['ORIG_SCRIPT_NAME'] : '');
  603. }
  604. /**
  605. * Checks if the request method is the given one.
  606. *
  607. * @param string $method The method name
  608. *
  609. * @return bool true if the current method is the given one, false otherwise
  610. */
  611. public function isMethod($method)
  612. {
  613. $pathArray = $this->getPathInfoArray();
  614. return strtolower($method) == strtolower($this->getMethodName());
  615. }
  616. /**
  617. * Returns request method.
  618. *
  619. * @return string
  620. */
  621. public function getMethodName()
  622. {
  623. $pathArray = $this->getPathInfoArray();
  624. return isset($pathArray['REQUEST_METHOD']) ? $pathArray['REQUEST_METHOD'] : 'GET';
  625. }
  626. /**
  627. * Returns the preferred culture for the current request.
  628. *
  629. * @param array $cultures An array of ordered cultures available
  630. *
  631. * @return string The preferred culture
  632. */
  633. public function getPreferredCulture(array $cultures = null)
  634. {
  635. $preferredCultures = $this->getLanguages();
  636. if (is_null($cultures))
  637. {
  638. return isset($preferredCultures[0]) ? $preferredCultures[0] : null;
  639. }
  640. if (!$preferredCultures)
  641. {
  642. return $cultures[0];
  643. }
  644. $preferredCultures = array_values(array_intersect($preferredCultures, $cultures));
  645. return isset($preferredCultures[0]) ? $preferredCultures[0] : $cultures[0];
  646. }
  647. /**
  648. * Gets a list of languages acceptable by the client browser
  649. *
  650. * @return array Languages ordered in the user browser preferences
  651. */
  652. public function getLanguages()
  653. {
  654. if ($this->languages)
  655. {
  656. return $this->languages;
  657. }
  658. if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
  659. {
  660. return array();
  661. }
  662. $languages = $this->splitHttpAcceptHeader($_SERVER['HTTP_ACCEPT_LANGUAGE']);
  663. foreach ($languages as $lang)
  664. {
  665. if (strstr($lang, '-'))
  666. {
  667. $codes = explode('-', $lang);
  668. if ($codes[0] == 'i')
  669. {
  670. // Language not listed in ISO 639 that are not variants
  671. // of any listed language, which can be registerd with the
  672. // i-prefix, such as i-cherokee
  673. if (count($codes) > 1)
  674. {
  675. $lang = $codes[1];
  676. }
  677. }
  678. else
  679. {
  680. for ($i = 0, $max = count($codes); $i < $max; $i++)
  681. {
  682. if ($i == 0)
  683. {
  684. $lang = strtolower($codes[0]);
  685. }
  686. else
  687. {
  688. $lang .= '_'.strtoupper($codes[$i]);
  689. }
  690. }
  691. }
  692. }
  693. $this->languages[] = $lang;
  694. }
  695. return $this->languages;
  696. }
  697. /**
  698. * Gets a list of charsets acceptable by the client browser.
  699. *
  700. * @return array List of charsets in preferable order
  701. */
  702. public function getCharsets()
  703. {
  704. if ($this->charsets)
  705. {
  706. return $this->charsets;
  707. }
  708. if (!isset($_SERVER['HTTP_ACCEPT_CHARSET']))
  709. {
  710. return array();
  711. }
  712. $this->charsets = $this->splitHttpAcceptHeader($_SERVER['HTTP_ACCEPT_CHARSET']);
  713. return $this->charsets;
  714. }
  715. /**
  716. * Gets a list of content types acceptable by the client browser
  717. *
  718. * @return array Languages ordered in the user browser preferences
  719. */
  720. public function getAcceptableContentTypes()
  721. {
  722. if ($this->acceptableContentTypes)
  723. {
  724. return $this->acceptableContentTypes;
  725. }
  726. if (!isset($_SERVER['HTTP_ACCEPT']))
  727. {
  728. return array();
  729. }
  730. $this->acceptableContentTypes = $this->splitHttpAcceptHeader($_SERVER['HTTP_ACCEPT']);
  731. return $this->acceptableContentTypes;
  732. }
  733. /**
  734. * Returns true if the request is a XMLHttpRequest.
  735. *
  736. * It works if your JavaScript library set an X-Requested-With HTTP header.
  737. * Works with Prototype, Mootools, jQuery, and perhaps others.
  738. *
  739. * @return bool true if the request is an XMLHttpRequest, false otherwise
  740. */
  741. public function isXmlHttpRequest()
  742. {
  743. return ($this->getHttpHeader('X_REQUESTED_WITH') == 'XMLHttpRequest');
  744. }
  745. public function getHttpHeader($name, $prefix = 'http')
  746. {
  747. if ($prefix)
  748. {
  749. $prefix = strtoupper($prefix).'_';
  750. }
  751. $name = $prefix.strtoupper(strtr($name, '-', '_'));
  752. $pathArray = $this->getPathInfoArray();
  753. return isset($pathArray[$name]) ? sfToolkit::stripslashesDeep($pathArray[$name]) : null;
  754. }
  755. /**
  756. * Gets a cookie value.
  757. *
  758. * @param string $name Cookie name
  759. * @param string $defaultValue Default value returned when no cookie with given name is found
  760. *
  761. * @return mixed
  762. */
  763. public function getCookie($name, $defaultValue = null)
  764. {
  765. $retval = $defaultValue;
  766. if (isset($_COOKIE[$name]))
  767. {
  768. $retval = get_magic_quotes_gpc() ? sfToolkit::stripslashesDeep($_COOKIE[$name]) : $_COOKIE[$name];
  769. }
  770. return $retval;
  771. }
  772. /**
  773. * Returns true if the current request is secure (HTTPS protocol).
  774. *
  775. * @return boolean
  776. */
  777. public function isSecure()
  778. {
  779. $pathArray = $this->getPathInfoArray();
  780. return (
  781. (isset($pathArray['HTTPS']) && (strtolower($pathArray['HTTPS']) == 'on' || $pathArray['HTTPS'] == 1))
  782. ||
  783. (isset($pathArray['HTTP_SSL_HTTPS']) && (strtolower($pathArray['HTTP_SSL_HTTPS']) == 'on' || $pathArray['HTTP_SSL_HTTPS'] == 1))
  784. ||
  785. (isset($pathArray['HTTP_X_FORWARDED_PROTO']) && strtolower($pathArray['HTTP_X_FORWARDED_PROTO']) == 'https')
  786. );
  787. }
  788. /**
  789. * Retrieves relative root url.
  790. *
  791. * @return string URL
  792. */
  793. public function getRelativeUrlRoot()
  794. {
  795. if ($this->relativeUrlRoot === null)
  796. {
  797. $this->relativeUrlRoot = sfConfig::get('sf_relative_url_root', preg_replace('#/[^/]+\.php5?$#', '', $this->getScriptName()));
  798. }
  799. return $this->relativeUrlRoot;
  800. }
  801. /**
  802. * Sets the relative root url for the current web request.
  803. *
  804. * @param string $value Value for the url
  805. */
  806. public function setRelativeUrlRoot($value)
  807. {
  808. $this->relativeUrlRoot = $value;
  809. }
  810. /**
  811. * Splits an HTTP header for the current web request.
  812. *
  813. * @param string $header Header to split
  814. */
  815. public function splitHttpAcceptHeader($header)
  816. {
  817. $values = array();
  818. foreach (array_filter(explode(',', $header)) as $value)
  819. {
  820. // Cut off any q-value that might come after a semi-colon
  821. if ($pos = strpos($value, ';'))
  822. {
  823. $q = (float) trim(substr($value, $pos + 3));
  824. $value = trim(substr($value, 0, $pos));
  825. }
  826. else
  827. {
  828. $q = 1;
  829. }
  830. $values[$value] = $q;
  831. }
  832. arsort($values);
  833. return array_keys($values);
  834. }
  835. /**
  836. * Returns the array that contains all request information ($_SERVER or $_ENV).
  837. *
  838. * This information is stored in the [sf_path_info_array] constant.
  839. *
  840. * @return array Path information
  841. */
  842. protected function getPathInfoArray()
  843. {
  844. if (!$this->pathInfoArray)
  845. {
  846. // parse PATH_INFO
  847. switch (sfConfig::get('sf_path_info_array', 'SERVER'))
  848. {
  849. case 'SERVER':
  850. $this->pathInfoArray =& $_SERVER;
  851. break;
  852. case 'ENV':
  853. default:
  854. $this->pathInfoArray =& $_ENV;
  855. }
  856. }
  857. return $this->pathInfoArray;
  858. }
  859. /**
  860. * Gets the mime type associated with the format.
  861. *
  862. * @param string $format The format
  863. *
  864. * @return string The associated mime type (null if not found)
  865. */
  866. public function getMimeType($format)
  867. {
  868. return isset($this->formats[$format]) ? $this->formats[$format][0] : null;
  869. }
  870. /**
  871. * Gets the format associated with the mime type.
  872. *
  873. * @param string $mimeType The associated mime type
  874. *
  875. * @return string The format (null if not found)
  876. */
  877. public function getFormat($mimeType)
  878. {
  879. foreach ($this->formats as $format => $mimeTypes)
  880. {
  881. if (in_array($mimeType, $mimeTypes))
  882. {
  883. return $format;
  884. }
  885. }
  886. return null;
  887. }
  888. /**
  889. * Associates a format with mime types.
  890. *
  891. * @param string $format The format
  892. * @param string|array $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type)
  893. */
  894. public function setFormat($format, $mimeTypes)
  895. {
  896. $this->formats[$format] = is_array($mimeTypes) ? $mimeTypes : array($mimeTypes);
  897. }
  898. /**
  899. * Sets the request format.
  900. *
  901. * @param string $format The request format
  902. */
  903. public function setRequestFormat($format)
  904. {
  905. $this->format = $format;
  906. }
  907. /**
  908. * Gets the request format.
  909. *
  910. * If no format is defined by the user, it defaults to the sf_format request parameter if available.
  911. *
  912. * @return string The request format
  913. */
  914. public function getRequestFormat()
  915. {
  916. if (is_null($this->format))
  917. {
  918. if ($this->getParameter('sf_format'))
  919. {
  920. $this->setRequestFormat($this->getParameter('sf_format'));
  921. }
  922. else
  923. {
  924. $acceptableContentTypes = $this->getAcceptableContentTypes();
  925. // skip if no acceptable content types or browsers
  926. if (isset($acceptableContentTypes[0]) && ('text/xml' != $acceptableContentTypes[0] && 'application/xml' != $acceptableContentTypes[0]))
  927. {
  928. $this->setRequestFormat($this->getFormat($acceptableContentTypes[0]));
  929. }
  930. }
  931. }
  932. return $this->format;
  933. }
  934. /**
  935. * Returns the value of a GET parameter.
  936. *
  937. * @param string $name The GET parameter name
  938. * @param string $default The default value
  939. *
  940. * @return string The GET parameter value
  941. */
  942. public function getGetParameter($name, $default = null)
  943. {
  944. if (isset($this->getParameters[$name]))
  945. {
  946. return $this->getParameters[$name];
  947. }
  948. else
  949. {
  950. return sfToolkit::getArrayValueForPath($this->getParameters, $name, $default);
  951. }
  952. }
  953. /**
  954. * Returns the value of a POST parameter.
  955. *
  956. * @param string $name The POST parameter name
  957. * @param string $default The default value
  958. *
  959. * @return string The POST parameter value
  960. */
  961. public function getPostParameter($name, $default = null)
  962. {
  963. if (isset($this->postParameters[$name]))
  964. {
  965. return $this->postParameters[$name];
  966. }
  967. else
  968. {
  969. return sfToolkit::getArrayValueForPath($this->postParameters, $name, $default);
  970. }
  971. }
  972. /**
  973. * Returns the value of a parameter passed as a URL segment.
  974. *
  975. * @param string $name The parameter name
  976. * @param string $default The default value
  977. *
  978. * @return string The parameter value
  979. */
  980. public function getUrlParameter($name, $default = null)
  981. {
  982. if (isset($this->requestParameters[$name]))
  983. {
  984. return $this->requestParameters[$name];
  985. }
  986. else
  987. {
  988. return sfToolkit::getArrayValueForPath($this->requestParameters, $name, $default);
  989. }
  990. }
  991. /**
  992. * Parses the request parameters.
  993. *
  994. * This method notifies the request.filter_parameters event.
  995. *
  996. * @return array An array of request parameters.
  997. */
  998. protected function parseRequestParameters()
  999. {
  1000. return $this->dispatcher->filter(new sfEvent($this, 'request.filter_parameters', array('path_info' => $this->getPathInfo())), array())->getReturnValue();
  1001. }
  1002. /**
  1003. * Loads GET, PATH_INFO and POST data into the parameter list.
  1004. *
  1005. */
  1006. protected function loadParameters()
  1007. {
  1008. // GET parameters
  1009. $this->getParameters = get_magic_quotes_gpc() ? sfToolkit::stripslashesDeep($_GET) : $_GET;
  1010. $this->parameterHolder->add($this->getParameters);
  1011. // additional parameters
  1012. $this->requestParameters = $this->parseRequestParameters();
  1013. $this->parameterHolder->add($this->requestParameters);
  1014. // POST parameters
  1015. $this->postParameters = get_magic_quotes_gpc() ? sfToolkit::stripslashesDeep($_POST) : $_POST;
  1016. $this->parameterHolder->add($this->postParameters);
  1017. // move symfony parameters to attributes (parameters prefixed with _sf_)
  1018. foreach ($this->parameterHolder->getAll() as $key => $value)
  1019. {
  1020. if (0 === stripos($key, '_sf_'))
  1021. {
  1022. $this->parameterHolder->remove($key);
  1023. $this->setAttribute($key, $value);
  1024. }
  1025. }
  1026. if (sfConfig::get('sf_logging_enabled'))
  1027. {
  1028. $this->dispatcher->notify(new sfEvent($this, 'application.log', array(sprintf('Request parameters %s', str_replace("\n", '', var_export($this->getParameterHolder()->getAll(), true))))));
  1029. }
  1030. }
  1031. }