Request.php 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  1. <?php
  2. namespace Symfony\Component\HttpFoundation;
  3. use Symfony\Component\HttpFoundation\SessionStorage\NativeSessionStorage;
  4. use Symfony\Component\HttpFoundation\File\UploadedFile;
  5. /*
  6. * This file is part of the Symfony package.
  7. *
  8. * (c) Fabien Potencier <fabien.potencier@symfony-project.com>
  9. *
  10. * For the full copyright and license information, please view the LICENSE
  11. * file that was distributed with this source code.
  12. */
  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 ParameterBag($this->convertFileInformation(null !== $files ? $files : $_FILES));
  93. $this->server = new ParameterBag(null !== $server ? $server : $_SERVER);
  94. $this->headers = new HeaderBag($this->initializeHeaders());
  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 (($scheme == 'http' && $port == 80) || ($scheme == 'https' && $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 bool $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 bool 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. /**
  807. * Converts uploaded files to UploadedFile instances.
  808. *
  809. * @param array $files A (multi-dimensional) array of uploaded file information
  810. *
  811. * @return array A (multi-dimensional) array of UploadedFile instances
  812. */
  813. protected function convertFileInformation(array $files)
  814. {
  815. $fixedFiles = array();
  816. foreach ($files as $key => $data) {
  817. $fixedFiles[$key] = $this->fixPhpFilesArray($data);
  818. }
  819. $fileKeys = array('error', 'name', 'size', 'tmp_name', 'type');
  820. foreach ($fixedFiles as $key => $data) {
  821. if (is_array($data)) {
  822. $keys = array_keys($data);
  823. sort($keys);
  824. if ($keys != $fileKeys) {
  825. $fixedFiles[$key] = $this->convertFileInformation($data);
  826. } else if ($data['error'] === UPLOAD_ERR_NO_FILE) {
  827. $fixedFiles[$key] = null;
  828. } else {
  829. $fixedFiles[$key] = new UploadedFile($data['tmp_name'], $data['name'], $data['type'], $data['size'], $data['error']);
  830. }
  831. }
  832. }
  833. return $fixedFiles;
  834. }
  835. /**
  836. * Fixes a malformed PHP $_FILES array.
  837. *
  838. * PHP has a bug that the format of the $_FILES array differs, depending on
  839. * whether the uploaded file fields had normal field names or array-like
  840. * field names ("normal" vs. "parent[child]").
  841. *
  842. * This method fixes the array to look like the "normal" $_FILES array.
  843. *
  844. * It's safe to pass an already converted array, in which case this method
  845. * just returns the original array unmodified.
  846. *
  847. * @param array $data
  848. * @return array
  849. */
  850. protected function fixPhpFilesArray($data)
  851. {
  852. if (!is_array($data)) {
  853. return $data;
  854. }
  855. $fileKeys = array('error', 'name', 'size', 'tmp_name', 'type');
  856. $keys = array_keys($data);
  857. sort($keys);
  858. if ($fileKeys != $keys || !isset($data['name']) || !is_array($data['name'])) {
  859. return $data;
  860. }
  861. $files = $data;
  862. foreach ($fileKeys as $k) {
  863. unset($files[$k]);
  864. }
  865. foreach (array_keys($data['name']) as $key) {
  866. $files[$key] = $this->fixPhpFilesArray(array(
  867. 'error' => $data['error'][$key],
  868. 'name' => $data['name'][$key],
  869. 'type' => $data['type'][$key],
  870. 'tmp_name' => $data['tmp_name'][$key],
  871. 'size' => $data['size'][$key],
  872. ));
  873. }
  874. return $files;
  875. }
  876. protected function initializeHeaders()
  877. {
  878. $headers = array();
  879. foreach ($this->server->all() as $key => $value) {
  880. if ('http_' === strtolower(substr($key, 0, 5))) {
  881. $headers[substr($key, 5)] = $value;
  882. }
  883. }
  884. return $headers;
  885. }
  886. static protected function initializeFormats()
  887. {
  888. static::$formats = array(
  889. 'txt' => 'text/plain',
  890. 'js' => array('application/javascript', 'application/x-javascript', 'text/javascript'),
  891. 'css' => 'text/css',
  892. 'json' => array('application/json', 'application/x-json'),
  893. 'xml' => array('text/xml', 'application/xml', 'application/x-xml'),
  894. 'rdf' => 'application/rdf+xml',
  895. 'atom' => 'application/atom+xml',
  896. );
  897. }
  898. }