Request.php 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation;
  11. use Symfony\Component\HttpFoundation\SessionStorage\NativeSessionStorage;
  12. /**
  13. * Request represents an HTTP request.
  14. *
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. *
  17. * @api
  18. */
  19. class Request
  20. {
  21. static protected $trustProxy = false;
  22. /**
  23. * @var \Symfony\Component\HttpFoundation\ParameterBag
  24. *
  25. * @api
  26. */
  27. public $attributes;
  28. /**
  29. * @var \Symfony\Component\HttpFoundation\ParameterBag
  30. *
  31. * @api
  32. */
  33. public $request;
  34. /**
  35. * @var \Symfony\Component\HttpFoundation\ParameterBag
  36. *
  37. * @api
  38. */
  39. public $query;
  40. /**
  41. * @var \Symfony\Component\HttpFoundation\ParameterBag
  42. *
  43. * @api
  44. */
  45. public $server;
  46. /**
  47. * @var \Symfony\Component\HttpFoundation\ParameterBag
  48. *
  49. * @api
  50. */
  51. public $files;
  52. /**
  53. * @var \Symfony\Component\HttpFoundation\ParameterBag
  54. *
  55. * @api
  56. */
  57. public $cookies;
  58. /**
  59. * @var \Symfony\Component\HttpFoundation\HeaderBag
  60. *
  61. * @api
  62. */
  63. public $headers;
  64. protected $content;
  65. protected $languages;
  66. protected $charsets;
  67. protected $acceptableContentTypes;
  68. protected $pathInfo;
  69. protected $requestUri;
  70. protected $baseUrl;
  71. protected $basePath;
  72. protected $method;
  73. protected $format;
  74. protected $session;
  75. static protected $formats;
  76. /**
  77. * Constructor.
  78. *
  79. * @param array $query The GET parameters
  80. * @param array $request The POST parameters
  81. * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
  82. * @param array $cookies The COOKIE parameters
  83. * @param array $files The FILES parameters
  84. * @param array $server The SERVER parameters
  85. * @param string $content The raw body data
  86. *
  87. * @api
  88. */
  89. public function __construct(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
  90. {
  91. $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content);
  92. }
  93. /**
  94. * Sets the parameters for this request.
  95. *
  96. * This method also re-initializes all properties.
  97. *
  98. * @param array $query The GET parameters
  99. * @param array $request The POST parameters
  100. * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
  101. * @param array $cookies The COOKIE parameters
  102. * @param array $files The FILES parameters
  103. * @param array $server The SERVER parameters
  104. * @param string $content The raw body data
  105. *
  106. * @api
  107. */
  108. public function initialize(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
  109. {
  110. $this->request = new ParameterBag($request);
  111. $this->query = new ParameterBag($query);
  112. $this->attributes = new ParameterBag($attributes);
  113. $this->cookies = new ParameterBag($cookies);
  114. $this->files = new FileBag($files);
  115. $this->server = new ServerBag($server);
  116. $this->headers = new HeaderBag($this->server->getHeaders());
  117. $this->content = $content;
  118. $this->languages = null;
  119. $this->charsets = null;
  120. $this->acceptableContentTypes = null;
  121. $this->pathInfo = null;
  122. $this->requestUri = null;
  123. $this->baseUrl = null;
  124. $this->basePath = null;
  125. $this->method = null;
  126. $this->format = null;
  127. }
  128. /**
  129. * Creates a new request with values from PHP's super globals.
  130. *
  131. * @return Request A new request
  132. *
  133. * @api
  134. */
  135. static public function createFromGlobals()
  136. {
  137. $request = new static($_GET, $_POST, array(), $_COOKIE, $_FILES, $_SERVER);
  138. if (0 === strpos($request->server->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded')
  139. && in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), array('PUT', 'DELETE'))
  140. ) {
  141. parse_str($request->getContent(), $data);
  142. $request->request = new ParameterBag($data);
  143. }
  144. return $request;
  145. }
  146. /**
  147. * Creates a Request based on a given URI and configuration.
  148. *
  149. * @param string $uri The URI
  150. * @param string $method The HTTP method
  151. * @param array $parameters The request (GET) or query (POST) parameters
  152. * @param array $cookies The request cookies ($_COOKIE)
  153. * @param array $files The request files ($_FILES)
  154. * @param array $server The server parameters ($_SERVER)
  155. * @param string $content The raw body data
  156. *
  157. * @return Request A Request instance
  158. *
  159. * @api
  160. */
  161. static public function create($uri, $method = 'GET', $parameters = array(), $cookies = array(), $files = array(), $server = array(), $content = null)
  162. {
  163. $defaults = array(
  164. 'SERVER_NAME' => 'localhost',
  165. 'SERVER_PORT' => 80,
  166. 'HTTP_HOST' => 'localhost',
  167. 'HTTP_USER_AGENT' => 'Symfony/2.X',
  168. 'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  169. 'HTTP_ACCEPT_LANGUAGE' => 'en-us,en;q=0.5',
  170. 'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  171. 'REMOTE_ADDR' => '127.0.0.1',
  172. 'SCRIPT_NAME' => '',
  173. 'SCRIPT_FILENAME' => '',
  174. 'SERVER_PROTOCOL' => 'HTTP/1.1',
  175. 'REQUEST_TIME' => time(),
  176. );
  177. $components = parse_url($uri);
  178. if (isset($components['host'])) {
  179. $defaults['SERVER_NAME'] = $components['host'];
  180. $defaults['HTTP_HOST'] = $components['host'];
  181. }
  182. if (isset($components['scheme'])) {
  183. if ('https' === $components['scheme']) {
  184. $defaults['HTTPS'] = 'on';
  185. $defaults['SERVER_PORT'] = 443;
  186. }
  187. }
  188. if (isset($components['port'])) {
  189. $defaults['SERVER_PORT'] = $components['port'];
  190. $defaults['HTTP_HOST'] = $defaults['HTTP_HOST'].':'.$components['port'];
  191. }
  192. if (!isset($components['path'])) {
  193. $components['path'] = '';
  194. }
  195. if (in_array(strtoupper($method), array('POST', 'PUT', 'DELETE'))) {
  196. $request = $parameters;
  197. $query = array();
  198. $defaults['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
  199. } else {
  200. $request = array();
  201. $query = $parameters;
  202. if (false !== $pos = strpos($uri, '?')) {
  203. $qs = substr($uri, $pos + 1);
  204. parse_str($qs, $params);
  205. $query = array_merge($params, $query);
  206. }
  207. }
  208. $queryString = isset($components['query']) ? html_entity_decode($components['query']) : '';
  209. parse_str($queryString, $qs);
  210. if (is_array($qs)) {
  211. $query = array_replace($qs, $query);
  212. }
  213. $uri = $components['path'].($queryString ? '?'.$queryString : '');
  214. $server = array_replace($defaults, $server, array(
  215. 'REQUEST_METHOD' => strtoupper($method),
  216. 'PATH_INFO' => '',
  217. 'REQUEST_URI' => $uri,
  218. 'QUERY_STRING' => $queryString,
  219. ));
  220. return new static($query, $request, array(), $cookies, $files, $server, $content);
  221. }
  222. /**
  223. * Clones a request and overrides some of its parameters.
  224. *
  225. * @param array $query The GET parameters
  226. * @param array $request The POST parameters
  227. * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
  228. * @param array $cookies The COOKIE parameters
  229. * @param array $files The FILES parameters
  230. * @param array $server The SERVER parameters
  231. *
  232. * @api
  233. */
  234. public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null)
  235. {
  236. $dup = clone $this;
  237. if ($query !== null) {
  238. $dup->query = new ParameterBag($query);
  239. }
  240. if ($request !== null) {
  241. $dup->request = new ParameterBag($request);
  242. }
  243. if ($attributes !== null) {
  244. $dup->attributes = new ParameterBag($attributes);
  245. }
  246. if ($cookies !== null) {
  247. $dup->cookies = new ParameterBag($cookies);
  248. }
  249. if ($files !== null) {
  250. $dup->files = new FileBag($files);
  251. }
  252. if ($server !== null) {
  253. $dup->server = new ServerBag($server);
  254. $dup->headers = new HeaderBag($dup->server->getHeaders());
  255. }
  256. $dup->languages = null;
  257. $dup->charsets = null;
  258. $dup->acceptableContentTypes = null;
  259. $dup->pathInfo = null;
  260. $dup->requestUri = null;
  261. $dup->baseUrl = null;
  262. $dup->basePath = null;
  263. $dup->method = null;
  264. $dup->format = null;
  265. return $dup;
  266. }
  267. /**
  268. * Clones the current request.
  269. *
  270. * Note that the session is not cloned as duplicated requests
  271. * are most of the time sub-requests of the main one.
  272. */
  273. public function __clone()
  274. {
  275. $this->query = clone $this->query;
  276. $this->request = clone $this->request;
  277. $this->attributes = clone $this->attributes;
  278. $this->cookies = clone $this->cookies;
  279. $this->files = clone $this->files;
  280. $this->server = clone $this->server;
  281. $this->headers = clone $this->headers;
  282. }
  283. /**
  284. * Returns the request as a string.
  285. *
  286. * @return string The request
  287. */
  288. public function __toString()
  289. {
  290. return
  291. sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n".
  292. $this->headers."\r\n".
  293. $this->getContent();
  294. }
  295. /**
  296. * Overrides the PHP global variables according to this request instance.
  297. *
  298. * It overrides $_GET, $_POST, $_REQUEST, $_SERVER, $_COOKIE, and $_FILES.
  299. *
  300. * @api
  301. */
  302. public function overrideGlobals()
  303. {
  304. $_GET = $this->query->all();
  305. $_POST = $this->request->all();
  306. $_SERVER = $this->server->all();
  307. $_COOKIE = $this->cookies->all();
  308. // FIXME: populate $_FILES
  309. foreach ($this->headers->all() as $key => $value) {
  310. $key = strtoupper(str_replace('-', '_', $key));
  311. if (in_array($key, array('CONTENT_TYPE', 'CONTENT_LENGTH'))) {
  312. $_SERVER[$key] = implode(', ', $value);
  313. } else {
  314. $_SERVER['HTTP_'.$key] = implode(', ', $value);
  315. }
  316. }
  317. // FIXME: should read variables_order and request_order
  318. // to know which globals to merge and in which order
  319. $_REQUEST = array_merge($_GET, $_POST);
  320. }
  321. /**
  322. * Trusts $_SERVER entries coming from proxies.
  323. *
  324. * You should only call this method if your application
  325. * is hosted behind a reverse proxy that you manage.
  326. *
  327. * @api
  328. */
  329. static public function trustProxyData()
  330. {
  331. self::$trustProxy = true;
  332. }
  333. /**
  334. * Gets a "parameter" value.
  335. *
  336. * This method is mainly useful for libraries that want to provide some flexibility.
  337. *
  338. * Order of precedence: GET, PATH, POST, COOKIE
  339. * Avoid using this method in controllers:
  340. * * slow
  341. * * prefer to get from a "named" source
  342. *
  343. * @param string $key the key
  344. * @param mixed $default the default value
  345. * @param type $deep is parameter deep in multidimensional array
  346. *
  347. * @return mixed
  348. */
  349. public function get($key, $default = null, $deep = false)
  350. {
  351. return $this->query->get($key, $this->attributes->get($key, $this->request->get($key, $default, $deep), $deep), $deep);
  352. }
  353. /**
  354. * Gets the Session.
  355. *
  356. * @return Session|null The session
  357. *
  358. * @api
  359. */
  360. public function getSession()
  361. {
  362. return $this->session;
  363. }
  364. /**
  365. * Whether the request contains a Session which was started in one of the
  366. * previous requests.
  367. *
  368. * @return boolean
  369. *
  370. * @api
  371. */
  372. public function hasPreviousSession()
  373. {
  374. // the check for $this->session avoids malicious users trying to fake a session cookie with proper name
  375. return $this->cookies->has(session_name()) && null !== $this->session;
  376. }
  377. /**
  378. * Whether the request contains a Session object.
  379. *
  380. * @return boolean
  381. *
  382. * @api
  383. */
  384. public function hasSession()
  385. {
  386. return null !== $this->session;
  387. }
  388. /**
  389. * Sets the Session.
  390. *
  391. * @param Session $session The Session
  392. *
  393. * @api
  394. */
  395. public function setSession(Session $session)
  396. {
  397. $this->session = $session;
  398. }
  399. /**
  400. * Returns the client IP address.
  401. *
  402. * @param Boolean $proxy Whether the current request has been made behind a proxy or not
  403. *
  404. * @return string The client IP address
  405. *
  406. * @api
  407. */
  408. public function getClientIp($proxy = false)
  409. {
  410. if ($proxy) {
  411. if ($this->server->has('HTTP_CLIENT_IP')) {
  412. return $this->server->get('HTTP_CLIENT_IP');
  413. } elseif (self::$trustProxy && $this->server->has('HTTP_X_FORWARDED_FOR')) {
  414. return $this->server->get('HTTP_X_FORWARDED_FOR');
  415. }
  416. }
  417. return $this->server->get('REMOTE_ADDR');
  418. }
  419. /**
  420. * Returns current script name.
  421. *
  422. * @return string
  423. *
  424. * @api
  425. */
  426. public function getScriptName()
  427. {
  428. return $this->server->get('SCRIPT_NAME', $this->server->get('ORIG_SCRIPT_NAME', ''));
  429. }
  430. /**
  431. * Returns the path being requested relative to the executed script.
  432. *
  433. * The path info always starts with a /.
  434. *
  435. * Suppose this request is instantiated from /mysite on localhost:
  436. *
  437. * * http://localhost/mysite returns an empty string
  438. * * http://localhost/mysite/about returns '/about'
  439. * * http://localhost/mysite/about?var=1 returns '/about'
  440. *
  441. * @return string
  442. *
  443. * @api
  444. */
  445. public function getPathInfo()
  446. {
  447. if (null === $this->pathInfo) {
  448. $this->pathInfo = $this->preparePathInfo();
  449. }
  450. return $this->pathInfo;
  451. }
  452. /**
  453. * Returns the root path from which this request is executed.
  454. *
  455. * Suppose that an index.php file instantiates this request object:
  456. *
  457. * * http://localhost/index.php returns an empty string
  458. * * http://localhost/index.php/page returns an empty string
  459. * * http://localhost/web/index.php return '/web'
  460. *
  461. * @return string
  462. *
  463. * @api
  464. */
  465. public function getBasePath()
  466. {
  467. if (null === $this->basePath) {
  468. $this->basePath = $this->prepareBasePath();
  469. }
  470. return $this->basePath;
  471. }
  472. /**
  473. * Returns the root url from which this request is executed.
  474. *
  475. * The base URL never ends with a /.
  476. *
  477. * This is similar to getBasePath(), except that it also includes the
  478. * script filename (e.g. index.php) if one exists.
  479. *
  480. * @return string
  481. *
  482. * @api
  483. */
  484. public function getBaseUrl()
  485. {
  486. if (null === $this->baseUrl) {
  487. $this->baseUrl = $this->prepareBaseUrl();
  488. }
  489. return $this->baseUrl;
  490. }
  491. /**
  492. * Gets the request's scheme.
  493. *
  494. * @return string
  495. *
  496. * @api
  497. */
  498. public function getScheme()
  499. {
  500. return $this->isSecure() ? 'https' : 'http';
  501. }
  502. /**
  503. * Returns the port on which the request is made.
  504. *
  505. * @return string
  506. *
  507. * @api
  508. */
  509. public function getPort()
  510. {
  511. return $this->headers->get('X-Forwarded-Port') ?: $this->server->get('SERVER_PORT');
  512. }
  513. /**
  514. * Returns the HTTP host being requested.
  515. *
  516. * The port name will be appended to the host if it's non-standard.
  517. *
  518. * @return string
  519. *
  520. * @api
  521. */
  522. public function getHttpHost()
  523. {
  524. $scheme = $this->getScheme();
  525. $port = $this->getPort();
  526. if (('http' == $scheme && $port == 80) || ('https' == $scheme && $port == 443)) {
  527. return $this->getHost();
  528. }
  529. return $this->getHost().':'.$port;
  530. }
  531. /**
  532. * Returns the requested URI.
  533. *
  534. * @return string
  535. *
  536. * @api
  537. */
  538. public function getRequestUri()
  539. {
  540. if (null === $this->requestUri) {
  541. $this->requestUri = $this->prepareRequestUri();
  542. }
  543. return $this->requestUri;
  544. }
  545. /**
  546. * Generates a normalized URI for the Request.
  547. *
  548. * @return string A normalized URI for the Request
  549. *
  550. * @see getQueryString()
  551. *
  552. * @api
  553. */
  554. public function getUri()
  555. {
  556. $qs = $this->getQueryString();
  557. if (null !== $qs) {
  558. $qs = '?'.$qs;
  559. }
  560. return $this->getScheme().'://'.$this->getHttpHost().$this->getBaseUrl().$this->getPathInfo().$qs;
  561. }
  562. /**
  563. * Generates a normalized URI for the given path.
  564. *
  565. * @param string $path A path to use instead of the current one
  566. *
  567. * @return string The normalized URI for the path
  568. *
  569. * @api
  570. */
  571. public function getUriForPath($path)
  572. {
  573. return $this->getScheme().'://'.$this->getHttpHost().$this->getBaseUrl().$path;
  574. }
  575. /**
  576. * Generates the normalized query string for the Request.
  577. *
  578. * It builds a normalized query string, where keys/value pairs are alphabetized
  579. * and have consistent escaping.
  580. *
  581. * @return string A normalized query string for the Request
  582. *
  583. * @api
  584. */
  585. public function getQueryString()
  586. {
  587. if (!$qs = $this->server->get('QUERY_STRING')) {
  588. return null;
  589. }
  590. $parts = array();
  591. $order = array();
  592. foreach (explode('&', $qs) as $segment) {
  593. if (false === strpos($segment, '=')) {
  594. $parts[] = $segment;
  595. $order[] = $segment;
  596. } else {
  597. $tmp = explode('=', rawurldecode($segment), 2);
  598. $parts[] = rawurlencode($tmp[0]).'='.rawurlencode($tmp[1]);
  599. $order[] = $tmp[0];
  600. }
  601. }
  602. array_multisort($order, SORT_ASC, $parts);
  603. return implode('&', $parts);
  604. }
  605. /**
  606. * Checks whether the request is secure or not.
  607. *
  608. * @return Boolean
  609. *
  610. * @api
  611. */
  612. public function isSecure()
  613. {
  614. return (
  615. (strtolower($this->server->get('HTTPS')) == 'on' || $this->server->get('HTTPS') == 1)
  616. ||
  617. (self::$trustProxy && strtolower($this->headers->get('SSL_HTTPS')) == 'on' || $this->headers->get('SSL_HTTPS') == 1)
  618. ||
  619. (self::$trustProxy && strtolower($this->headers->get('X_FORWARDED_PROTO')) == 'https')
  620. );
  621. }
  622. /**
  623. * Returns the host name.
  624. *
  625. * @return string
  626. *
  627. * @api
  628. */
  629. public function getHost()
  630. {
  631. if (self::$trustProxy && $host = $this->headers->get('X_FORWARDED_HOST')) {
  632. $elements = explode(',', $host);
  633. $host = trim($elements[count($elements) - 1]);
  634. } else {
  635. if (!$host = $this->headers->get('HOST')) {
  636. if (!$host = $this->server->get('SERVER_NAME')) {
  637. $host = $this->server->get('SERVER_ADDR', '');
  638. }
  639. }
  640. }
  641. // Remove port number from host
  642. $host = preg_replace('/:\d+$/', '', $host);
  643. return trim($host);
  644. }
  645. /**
  646. * Sets the request method.
  647. *
  648. * @param string $method
  649. *
  650. * @api
  651. */
  652. public function setMethod($method)
  653. {
  654. $this->method = null;
  655. $this->server->set('REQUEST_METHOD', $method);
  656. }
  657. /**
  658. * Gets the request method.
  659. *
  660. * The method is always an uppercased string.
  661. *
  662. * @return string The request method
  663. *
  664. * @api
  665. */
  666. public function getMethod()
  667. {
  668. if (null === $this->method) {
  669. $this->method = strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
  670. if ('POST' === $this->method) {
  671. $this->method = strtoupper($this->headers->get('X-HTTP-METHOD-OVERRIDE', $this->request->get('_method', 'POST')));
  672. }
  673. }
  674. return $this->method;
  675. }
  676. /**
  677. * Gets the mime type associated with the format.
  678. *
  679. * @param string $format The format
  680. *
  681. * @return string The associated mime type (null if not found)
  682. *
  683. * @api
  684. */
  685. public function getMimeType($format)
  686. {
  687. if (null === static::$formats) {
  688. static::initializeFormats();
  689. }
  690. return isset(static::$formats[$format]) ? static::$formats[$format][0] : null;
  691. }
  692. /**
  693. * Gets the format associated with the mime type.
  694. *
  695. * @param string $mimeType The associated mime type
  696. *
  697. * @return string The format (null if not found)
  698. *
  699. * @api
  700. */
  701. public function getFormat($mimeType)
  702. {
  703. if (false !== $pos = strpos($mimeType, ';')) {
  704. $mimeType = substr($mimeType, 0, $pos);
  705. }
  706. if (null === static::$formats) {
  707. static::initializeFormats();
  708. }
  709. foreach (static::$formats as $format => $mimeTypes) {
  710. if (in_array($mimeType, (array) $mimeTypes)) {
  711. return $format;
  712. }
  713. }
  714. return null;
  715. }
  716. /**
  717. * Associates a format with mime types.
  718. *
  719. * @param string $format The format
  720. * @param string|array $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type)
  721. *
  722. * @api
  723. */
  724. public function setFormat($format, $mimeTypes)
  725. {
  726. if (null === static::$formats) {
  727. static::initializeFormats();
  728. }
  729. static::$formats[$format] = is_array($mimeTypes) ? $mimeTypes : array($mimeTypes);
  730. }
  731. /**
  732. * Gets the request format.
  733. *
  734. * Here is the process to determine the format:
  735. *
  736. * * format defined by the user (with setRequestFormat())
  737. * * _format request parameter
  738. * * $default
  739. *
  740. * @param string $default The default format
  741. *
  742. * @return string The request format
  743. *
  744. * @api
  745. */
  746. public function getRequestFormat($default = 'html')
  747. {
  748. if (null === $this->format) {
  749. $this->format = $this->get('_format', $default);
  750. }
  751. return $this->format;
  752. }
  753. /**
  754. * Sets the request format.
  755. *
  756. * @param string $format The request format.
  757. *
  758. * @api
  759. */
  760. public function setRequestFormat($format)
  761. {
  762. $this->format = $format;
  763. }
  764. /**
  765. * Checks whether the method is safe or not.
  766. *
  767. * @return Boolean
  768. *
  769. * @api
  770. */
  771. public function isMethodSafe()
  772. {
  773. return in_array($this->getMethod(), array('GET', 'HEAD'));
  774. }
  775. /**
  776. * Returns the request body content.
  777. *
  778. * @param Boolean $asResource If true, a resource will be returned
  779. *
  780. * @return string|resource The request body content or a resource to read the body stream.
  781. */
  782. public function getContent($asResource = false)
  783. {
  784. if (false === $this->content || (true === $asResource && null !== $this->content)) {
  785. throw new \LogicException('getContent() can only be called once when using the resource return type.');
  786. }
  787. if (true === $asResource) {
  788. $this->content = false;
  789. return fopen('php://input', 'rb');
  790. }
  791. if (null === $this->content) {
  792. $this->content = file_get_contents('php://input');
  793. }
  794. return $this->content;
  795. }
  796. /**
  797. * Gets the Etags.
  798. *
  799. * @return array The entity tags
  800. */
  801. public function getETags()
  802. {
  803. return preg_split('/\s*,\s*/', $this->headers->get('if_none_match'), null, PREG_SPLIT_NO_EMPTY);
  804. }
  805. public function isNoCache()
  806. {
  807. return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma');
  808. }
  809. /**
  810. * Returns the preferred language.
  811. *
  812. * @param array $locales An array of ordered available locales
  813. *
  814. * @return string The preferred locale
  815. *
  816. * @api
  817. */
  818. public function getPreferredLanguage(array $locales = null)
  819. {
  820. $preferredLanguages = $this->getLanguages();
  821. if (null === $locales) {
  822. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null;
  823. }
  824. if (!$preferredLanguages) {
  825. return $locales[0];
  826. }
  827. $preferredLanguages = array_values(array_intersect($preferredLanguages, $locales));
  828. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : $locales[0];
  829. }
  830. /**
  831. * Gets a list of languages acceptable by the client browser.
  832. *
  833. * @return array Languages ordered in the user browser preferences
  834. *
  835. * @api
  836. */
  837. public function getLanguages()
  838. {
  839. if (null !== $this->languages) {
  840. return $this->languages;
  841. }
  842. $languages = $this->splitHttpAcceptHeader($this->headers->get('Accept-Language'));
  843. $this->languages = array();
  844. foreach ($languages as $lang => $q) {
  845. if (strstr($lang, '-')) {
  846. $codes = explode('-', $lang);
  847. if ($codes[0] == 'i') {
  848. // Language not listed in ISO 639 that are not variants
  849. // of any listed language, which can be registered with the
  850. // i-prefix, such as i-cherokee
  851. if (count($codes) > 1) {
  852. $lang = $codes[1];
  853. }
  854. } else {
  855. for ($i = 0, $max = count($codes); $i < $max; $i++) {
  856. if ($i == 0) {
  857. $lang = strtolower($codes[0]);
  858. } else {
  859. $lang .= '_'.strtoupper($codes[$i]);
  860. }
  861. }
  862. }
  863. }
  864. $this->languages[] = $lang;
  865. }
  866. return $this->languages;
  867. }
  868. /**
  869. * Gets a list of charsets acceptable by the client browser.
  870. *
  871. * @return array List of charsets in preferable order
  872. *
  873. * @api
  874. */
  875. public function getCharsets()
  876. {
  877. if (null !== $this->charsets) {
  878. return $this->charsets;
  879. }
  880. return $this->charsets = array_keys($this->splitHttpAcceptHeader($this->headers->get('Accept-Charset')));
  881. }
  882. /**
  883. * Gets a list of content types acceptable by the client browser
  884. *
  885. * @return array List of content types in preferable order
  886. *
  887. * @api
  888. */
  889. public function getAcceptableContentTypes()
  890. {
  891. if (null !== $this->acceptableContentTypes) {
  892. return $this->acceptableContentTypes;
  893. }
  894. return $this->acceptableContentTypes = array_keys($this->splitHttpAcceptHeader($this->headers->get('Accept')));
  895. }
  896. /**
  897. * Returns true if the request is a XMLHttpRequest.
  898. *
  899. * It works if your JavaScript library set an X-Requested-With HTTP header.
  900. * It is known to work with Prototype, Mootools, jQuery.
  901. *
  902. * @return Boolean true if the request is an XMLHttpRequest, false otherwise
  903. *
  904. * @api
  905. */
  906. public function isXmlHttpRequest()
  907. {
  908. return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
  909. }
  910. /**
  911. * Splits an Accept-* HTTP header.
  912. *
  913. * @param string $header Header to split
  914. */
  915. public function splitHttpAcceptHeader($header)
  916. {
  917. if (!$header) {
  918. return array();
  919. }
  920. $values = array();
  921. foreach (array_filter(explode(',', $header)) as $value) {
  922. // Cut off any q-value that might come after a semi-colon
  923. if ($pos = strpos($value, ';')) {
  924. $q = (float) trim(substr($value, strpos($value, '=') + 1));
  925. $value = trim(substr($value, 0, $pos));
  926. } else {
  927. $q = 1;
  928. }
  929. if (0 < $q) {
  930. $values[trim($value)] = $q;
  931. }
  932. }
  933. arsort($values);
  934. reset($values);
  935. return $values;
  936. }
  937. /*
  938. * The following methods are derived from code of the Zend Framework (1.10dev - 2010-01-24)
  939. *
  940. * Code subject to the new BSD license (http://framework.zend.com/license/new-bsd).
  941. *
  942. * Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  943. */
  944. protected function prepareRequestUri()
  945. {
  946. $requestUri = '';
  947. if ($this->headers->has('X_REWRITE_URL')) {
  948. // check this first so IIS will catch
  949. $requestUri = $this->headers->get('X_REWRITE_URL');
  950. } elseif ($this->server->get('IIS_WasUrlRewritten') == '1' && $this->server->get('UNENCODED_URL') != '') {
  951. // IIS7 with URL Rewrite: make sure we get the unencoded url (double slash problem)
  952. $requestUri = $this->server->get('UNENCODED_URL');
  953. } elseif ($this->server->has('REQUEST_URI')) {
  954. $requestUri = $this->server->get('REQUEST_URI');
  955. // HTTP proxy reqs setup request uri with scheme and host [and port] + the url path, only use url path
  956. $schemeAndHttpHost = $this->getScheme().'://'.$this->getHttpHost();
  957. if (strpos($requestUri, $schemeAndHttpHost) === 0) {
  958. $requestUri = substr($requestUri, strlen($schemeAndHttpHost));
  959. }
  960. } elseif ($this->server->has('ORIG_PATH_INFO')) {
  961. // IIS 5.0, PHP as CGI
  962. $requestUri = $this->server->get('ORIG_PATH_INFO');
  963. if ($this->server->get('QUERY_STRING')) {
  964. $requestUri .= '?'.$this->server->get('QUERY_STRING');
  965. }
  966. }
  967. return $requestUri;
  968. }
  969. protected function prepareBaseUrl()
  970. {
  971. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  972. if (basename($this->server->get('SCRIPT_NAME')) === $filename) {
  973. $baseUrl = $this->server->get('SCRIPT_NAME');
  974. } elseif (basename($this->server->get('PHP_SELF')) === $filename) {
  975. $baseUrl = $this->server->get('PHP_SELF');
  976. } elseif (basename($this->server->get('ORIG_SCRIPT_NAME')) === $filename) {
  977. $baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); // 1and1 shared hosting compatibility
  978. } else {
  979. // Backtrack up the script_filename to find the portion matching
  980. // php_self
  981. $path = $this->server->get('PHP_SELF', '');
  982. $file = $this->server->get('SCRIPT_FILENAME', '');
  983. $segs = explode('/', trim($file, '/'));
  984. $segs = array_reverse($segs);
  985. $index = 0;
  986. $last = count($segs);
  987. $baseUrl = '';
  988. do {
  989. $seg = $segs[$index];
  990. $baseUrl = '/'.$seg.$baseUrl;
  991. ++$index;
  992. } while (($last > $index) && (false !== ($pos = strpos($path, $baseUrl))) && (0 != $pos));
  993. }
  994. // Does the baseUrl have anything in common with the request_uri?
  995. $requestUri = $this->getRequestUri();
  996. if ($baseUrl && 0 === strpos($requestUri, $baseUrl)) {
  997. // full $baseUrl matches
  998. return $baseUrl;
  999. }
  1000. if ($baseUrl && 0 === strpos($requestUri, dirname($baseUrl))) {
  1001. // directory portion of $baseUrl matches
  1002. return rtrim(dirname($baseUrl), '/');
  1003. }
  1004. $truncatedRequestUri = $requestUri;
  1005. if (($pos = strpos($requestUri, '?')) !== false) {
  1006. $truncatedRequestUri = substr($requestUri, 0, $pos);
  1007. }
  1008. $basename = basename($baseUrl);
  1009. if (empty($basename) || !strpos($truncatedRequestUri, $basename)) {
  1010. // no match whatsoever; set it blank
  1011. return '';
  1012. }
  1013. // If using mod_rewrite or ISAPI_Rewrite strip the script filename
  1014. // out of baseUrl. $pos !== 0 makes sure it is not matching a value
  1015. // from PATH_INFO or QUERY_STRING
  1016. if ((strlen($requestUri) >= strlen($baseUrl)) && ((false !== ($pos = strpos($requestUri, $baseUrl))) && ($pos !== 0))) {
  1017. $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));
  1018. }
  1019. return rtrim($baseUrl, '/');
  1020. }
  1021. /**
  1022. * Prepares base path.
  1023. *
  1024. * @return string base path
  1025. */
  1026. protected function prepareBasePath()
  1027. {
  1028. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  1029. $baseUrl = $this->getBaseUrl();
  1030. if (empty($baseUrl)) {
  1031. return '';
  1032. }
  1033. if (basename($baseUrl) === $filename) {
  1034. $basePath = dirname($baseUrl);
  1035. } else {
  1036. $basePath = $baseUrl;
  1037. }
  1038. if ('\\' === DIRECTORY_SEPARATOR) {
  1039. $basePath = str_replace('\\', '/', $basePath);
  1040. }
  1041. return rtrim($basePath, '/');
  1042. }
  1043. /**
  1044. * Prepares path info.
  1045. *
  1046. * @return string path info
  1047. */
  1048. protected function preparePathInfo()
  1049. {
  1050. $baseUrl = $this->getBaseUrl();
  1051. if (null === ($requestUri = $this->getRequestUri())) {
  1052. return '/';
  1053. }
  1054. $pathInfo = '/';
  1055. // Remove the query string from REQUEST_URI
  1056. if ($pos = strpos($requestUri, '?')) {
  1057. $requestUri = substr($requestUri, 0, $pos);
  1058. }
  1059. if ((null !== $baseUrl) && (false === ($pathInfo = substr($requestUri, strlen($baseUrl))))) {
  1060. // If substr() returns false then PATH_INFO is set to an empty string
  1061. return '/';
  1062. } elseif (null === $baseUrl) {
  1063. return $requestUri;
  1064. }
  1065. return (string) $pathInfo;
  1066. }
  1067. /**
  1068. * Initializes HTTP request formats.
  1069. */
  1070. static protected function initializeFormats()
  1071. {
  1072. static::$formats = array(
  1073. 'html' => array('text/html', 'application/xhtml+xml'),
  1074. 'txt' => array('text/plain'),
  1075. 'js' => array('application/javascript', 'application/x-javascript', 'text/javascript'),
  1076. 'css' => array('text/css'),
  1077. 'json' => array('application/json', 'application/x-json'),
  1078. 'xml' => array('text/xml', 'application/xml', 'application/x-xml'),
  1079. 'rdf' => array('application/rdf+xml'),
  1080. 'atom' => array('application/atom+xml'),
  1081. );
  1082. }
  1083. }