Request.php 32 KB

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