Request.php 33 KB

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