Request.php 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069
  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. * @return string The request method
  562. */
  563. public function getMethod()
  564. {
  565. if (null === $this->method) {
  566. $this->method = strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
  567. if ('POST' === $this->method) {
  568. $this->method = strtoupper($this->server->get('X-HTTP-METHOD-OVERRIDE', $this->request->get('_method', 'POST')));
  569. }
  570. }
  571. return $this->method;
  572. }
  573. /**
  574. * Gets the mime type associated with the format.
  575. *
  576. * @param string $format The format
  577. *
  578. * @return string The associated mime type (null if not found)
  579. */
  580. public function getMimeType($format)
  581. {
  582. if (null === static::$formats) {
  583. static::initializeFormats();
  584. }
  585. return isset(static::$formats[$format]) ? static::$formats[$format][0] : null;
  586. }
  587. /**
  588. * Gets the format associated with the mime type.
  589. *
  590. * @param string $mimeType The associated mime type
  591. *
  592. * @return string The format (null if not found)
  593. */
  594. public function getFormat($mimeType)
  595. {
  596. if (null === static::$formats) {
  597. static::initializeFormats();
  598. }
  599. foreach (static::$formats as $format => $mimeTypes) {
  600. if (in_array($mimeType, (array) $mimeTypes)) {
  601. return $format;
  602. }
  603. }
  604. return null;
  605. }
  606. /**
  607. * Associates a format with mime types.
  608. *
  609. * @param string $format The format
  610. * @param string|array $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type)
  611. */
  612. public function setFormat($format, $mimeTypes)
  613. {
  614. if (null === static::$formats) {
  615. static::initializeFormats();
  616. }
  617. static::$formats[$format] = is_array($mimeTypes) ? $mimeTypes : array($mimeTypes);
  618. }
  619. /**
  620. * Gets the request format.
  621. *
  622. * Here is the process to determine the format:
  623. *
  624. * * format defined by the user (with setRequestFormat())
  625. * * _format request parameter
  626. * * $default
  627. *
  628. * @param string $default The default format
  629. *
  630. * @return string The request format
  631. */
  632. public function getRequestFormat($default = 'html')
  633. {
  634. if (null === $this->format) {
  635. $this->format = $this->get('_format', $default);
  636. }
  637. return $this->format;
  638. }
  639. public function setRequestFormat($format)
  640. {
  641. $this->format = $format;
  642. }
  643. /**
  644. * Checks whether the method is safe or not.
  645. *
  646. * @return Boolean
  647. */
  648. public function isMethodSafe()
  649. {
  650. return in_array($this->getMethod(), array('GET', 'HEAD'));
  651. }
  652. /**
  653. * Returns the request body content.
  654. *
  655. * @param Boolean $asResource If true, a resource will be returned
  656. *
  657. * @return string|resource The request body content or a resource to read the body stream.
  658. */
  659. public function getContent($asResource = false)
  660. {
  661. if (false === $this->content || (true === $asResource && null !== $this->content)) {
  662. throw new \LogicException('getContent() can only be called once when using the resource return type.');
  663. }
  664. if (true === $asResource) {
  665. $this->content = false;
  666. return fopen('php://input', 'rb');
  667. }
  668. if (null === $this->content) {
  669. $this->content = file_get_contents('php://input');
  670. }
  671. return $this->content;
  672. }
  673. /**
  674. * Gets the Etags.
  675. *
  676. * @return array The entity tags
  677. */
  678. public function getETags()
  679. {
  680. return preg_split('/\s*,\s*/', $this->headers->get('if_none_match'), null, PREG_SPLIT_NO_EMPTY);
  681. }
  682. public function isNoCache()
  683. {
  684. return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma');
  685. }
  686. /**
  687. * Returns the preferred language.
  688. *
  689. * @param array $locales An array of ordered available locales
  690. *
  691. * @return string The preferred locale
  692. */
  693. public function getPreferredLanguage(array $locales = null)
  694. {
  695. $preferredLanguages = $this->getLanguages();
  696. if (null === $locales) {
  697. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null;
  698. }
  699. if (!$preferredLanguages) {
  700. return $locales[0];
  701. }
  702. $preferredLanguages = array_values(array_intersect($preferredLanguages, $locales));
  703. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : $locales[0];
  704. }
  705. /**
  706. * Gets a list of languages acceptable by the client browser.
  707. *
  708. * @return array Languages ordered in the user browser preferences
  709. */
  710. public function getLanguages()
  711. {
  712. if (null !== $this->languages) {
  713. return $this->languages;
  714. }
  715. $languages = $this->splitHttpAcceptHeader($this->headers->get('Accept-Language'));
  716. $this->languages = array();
  717. foreach ($languages as $lang => $q) {
  718. if (strstr($lang, '-')) {
  719. $codes = explode('-', $lang);
  720. if ($codes[0] == 'i') {
  721. // Language not listed in ISO 639 that are not variants
  722. // of any listed language, which can be registered with the
  723. // i-prefix, such as i-cherokee
  724. if (count($codes) > 1) {
  725. $lang = $codes[1];
  726. }
  727. } else {
  728. for ($i = 0, $max = count($codes); $i < $max; $i++) {
  729. if ($i == 0) {
  730. $lang = strtolower($codes[0]);
  731. } else {
  732. $lang .= '_'.strtoupper($codes[$i]);
  733. }
  734. }
  735. }
  736. }
  737. $this->languages[] = $lang;
  738. }
  739. return $this->languages;
  740. }
  741. /**
  742. * Gets a list of charsets acceptable by the client browser.
  743. *
  744. * @return array List of charsets in preferable order
  745. */
  746. public function getCharsets()
  747. {
  748. if (null !== $this->charsets) {
  749. return $this->charsets;
  750. }
  751. return $this->charsets = array_keys($this->splitHttpAcceptHeader($this->headers->get('Accept-Charset')));
  752. }
  753. /**
  754. * Gets a list of content types acceptable by the client browser
  755. *
  756. * @return array Languages ordered in the user browser preferences
  757. */
  758. public function getAcceptableContentTypes()
  759. {
  760. if (null !== $this->acceptableContentTypes) {
  761. return $this->acceptableContentTypes;
  762. }
  763. return $this->acceptableContentTypes = array_keys($this->splitHttpAcceptHeader($this->headers->get('Accept')));
  764. }
  765. /**
  766. * Returns true if the request is a XMLHttpRequest.
  767. *
  768. * It works if your JavaScript library set an X-Requested-With HTTP header.
  769. * It is known to work with Prototype, Mootools, jQuery.
  770. *
  771. * @return Boolean true if the request is an XMLHttpRequest, false otherwise
  772. */
  773. public function isXmlHttpRequest()
  774. {
  775. return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
  776. }
  777. /**
  778. * Splits an Accept-* HTTP header.
  779. *
  780. * @param string $header Header to split
  781. */
  782. public function splitHttpAcceptHeader($header)
  783. {
  784. if (!$header) {
  785. return array();
  786. }
  787. $values = array();
  788. foreach (array_filter(explode(',', $header)) as $value) {
  789. // Cut off any q-value that might come after a semi-colon
  790. if ($pos = strpos($value, ';')) {
  791. $q = (float) trim(substr($value, strpos($value, '=') + 1));
  792. $value = trim(substr($value, 0, $pos));
  793. } else {
  794. $q = 1;
  795. }
  796. if (0 < $q) {
  797. $values[trim($value)] = $q;
  798. }
  799. }
  800. arsort($values);
  801. reset($values);
  802. return $values;
  803. }
  804. /*
  805. * The following methods are derived from code of the Zend Framework (1.10dev - 2010-01-24)
  806. *
  807. * Code subject to the new BSD license (http://framework.zend.com/license/new-bsd).
  808. *
  809. * Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  810. */
  811. protected function prepareRequestUri()
  812. {
  813. $requestUri = '';
  814. if ($this->headers->has('X_REWRITE_URL')) {
  815. // check this first so IIS will catch
  816. $requestUri = $this->headers->get('X_REWRITE_URL');
  817. } elseif ($this->server->get('IIS_WasUrlRewritten') == '1' && $this->server->get('UNENCODED_URL') != '') {
  818. // IIS7 with URL Rewrite: make sure we get the unencoded url (double slash problem)
  819. $requestUri = $this->server->get('UNENCODED_URL');
  820. } elseif ($this->server->has('REQUEST_URI')) {
  821. $requestUri = $this->server->get('REQUEST_URI');
  822. // HTTP proxy reqs setup request uri with scheme and host [and port] + the url path, only use url path
  823. $schemeAndHttpHost = $this->getScheme().'://'.$this->getHttpHost();
  824. if (strpos($requestUri, $schemeAndHttpHost) === 0) {
  825. $requestUri = substr($requestUri, strlen($schemeAndHttpHost));
  826. }
  827. } elseif ($this->server->has('ORIG_PATH_INFO')) {
  828. // IIS 5.0, PHP as CGI
  829. $requestUri = $this->server->get('ORIG_PATH_INFO');
  830. if ($this->server->get('QUERY_STRING')) {
  831. $requestUri .= '?'.$this->server->get('QUERY_STRING');
  832. }
  833. }
  834. return $requestUri;
  835. }
  836. protected function prepareBaseUrl()
  837. {
  838. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  839. if (basename($this->server->get('SCRIPT_NAME')) === $filename) {
  840. $baseUrl = $this->server->get('SCRIPT_NAME');
  841. } elseif (basename($this->server->get('PHP_SELF')) === $filename) {
  842. $baseUrl = $this->server->get('PHP_SELF');
  843. } elseif (basename($this->server->get('ORIG_SCRIPT_NAME')) === $filename) {
  844. $baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); // 1and1 shared hosting compatibility
  845. } else {
  846. // Backtrack up the script_filename to find the portion matching
  847. // php_self
  848. $path = $this->server->get('PHP_SELF', '');
  849. $file = $this->server->get('SCRIPT_FILENAME', '');
  850. $segs = explode('/', trim($file, '/'));
  851. $segs = array_reverse($segs);
  852. $index = 0;
  853. $last = count($segs);
  854. $baseUrl = '';
  855. do {
  856. $seg = $segs[$index];
  857. $baseUrl = '/'.$seg.$baseUrl;
  858. ++$index;
  859. } while (($last > $index) && (false !== ($pos = strpos($path, $baseUrl))) && (0 != $pos));
  860. }
  861. // Does the baseUrl have anything in common with the request_uri?
  862. $requestUri = $this->getRequestUri();
  863. if ($baseUrl && 0 === strpos($requestUri, $baseUrl)) {
  864. // full $baseUrl matches
  865. return $baseUrl;
  866. }
  867. if ($baseUrl && 0 === strpos($requestUri, dirname($baseUrl))) {
  868. // directory portion of $baseUrl matches
  869. return rtrim(dirname($baseUrl), '/');
  870. }
  871. $truncatedRequestUri = $requestUri;
  872. if (($pos = strpos($requestUri, '?')) !== false) {
  873. $truncatedRequestUri = substr($requestUri, 0, $pos);
  874. }
  875. $basename = basename($baseUrl);
  876. if (empty($basename) || !strpos($truncatedRequestUri, $basename)) {
  877. // no match whatsoever; set it blank
  878. return '';
  879. }
  880. // If using mod_rewrite or ISAPI_Rewrite strip the script filename
  881. // out of baseUrl. $pos !== 0 makes sure it is not matching a value
  882. // from PATH_INFO or QUERY_STRING
  883. if ((strlen($requestUri) >= strlen($baseUrl)) && ((false !== ($pos = strpos($requestUri, $baseUrl))) && ($pos !== 0))) {
  884. $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));
  885. }
  886. return rtrim($baseUrl, '/');
  887. }
  888. protected function prepareBasePath()
  889. {
  890. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  891. $baseUrl = $this->getBaseUrl();
  892. if (empty($baseUrl)) {
  893. return '';
  894. }
  895. if (basename($baseUrl) === $filename) {
  896. $basePath = dirname($baseUrl);
  897. } else {
  898. $basePath = $baseUrl;
  899. }
  900. if ('\\' === DIRECTORY_SEPARATOR) {
  901. $basePath = str_replace('\\', '/', $basePath);
  902. }
  903. return rtrim($basePath, '/');
  904. }
  905. protected function preparePathInfo()
  906. {
  907. $baseUrl = $this->getBaseUrl();
  908. if (null === ($requestUri = $this->getRequestUri())) {
  909. return '/';
  910. }
  911. $pathInfo = '/';
  912. // Remove the query string from REQUEST_URI
  913. if ($pos = strpos($requestUri, '?')) {
  914. $requestUri = substr($requestUri, 0, $pos);
  915. }
  916. if ((null !== $baseUrl) && (false === ($pathInfo = substr($requestUri, strlen($baseUrl))))) {
  917. // If substr() returns false then PATH_INFO is set to an empty string
  918. return '/';
  919. } elseif (null === $baseUrl) {
  920. return $requestUri;
  921. }
  922. return (string) $pathInfo;
  923. }
  924. static protected function initializeFormats()
  925. {
  926. static::$formats = array(
  927. 'html' => array('text/html', 'application/xhtml+xml'),
  928. 'txt' => array('text/plain'),
  929. 'js' => array('application/javascript', 'application/x-javascript', 'text/javascript'),
  930. 'css' => array('text/css'),
  931. 'json' => array('application/json', 'application/x-json'),
  932. 'xml' => array('text/xml', 'application/xml', 'application/x-xml'),
  933. 'rdf' => array('application/rdf+xml'),
  934. 'atom' => array('application/atom+xml'),
  935. );
  936. }
  937. }