Request.php 29 KB

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