Request.php 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  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. * Return the request body content.
  543. *
  544. * @return string The request body content.
  545. */
  546. public function getContent()
  547. {
  548. if (null === $this->content) {
  549. $this->content = file_get_contents('php://input');
  550. }
  551. return $this->content;
  552. }
  553. public function getETags()
  554. {
  555. return preg_split('/\s*,\s*/', $this->headers->get('if_none_match'), null, PREG_SPLIT_NO_EMPTY);
  556. }
  557. public function isNoCache()
  558. {
  559. return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma');
  560. }
  561. /**
  562. * Returns the preferred language.
  563. *
  564. * @param array $locales An array of ordered available locales
  565. *
  566. * @return string The preferred locale
  567. */
  568. public function getPreferredLanguage(array $locales = null)
  569. {
  570. $preferredLanguages = $this->getLanguages();
  571. if (null === $locales) {
  572. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null;
  573. }
  574. if (!$preferredLanguages) {
  575. return $locales[0];
  576. }
  577. $preferredLanguages = array_values(array_intersect($preferredLanguages, $locales));
  578. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : $locales[0];
  579. }
  580. /**
  581. * Gets a list of languages acceptable by the client browser.
  582. *
  583. * @return array Languages ordered in the user browser preferences
  584. */
  585. public function getLanguages()
  586. {
  587. if (null !== $this->languages) {
  588. return $this->languages;
  589. }
  590. $languages = $this->splitHttpAcceptHeader($this->headers->get('Accept-Language'));
  591. foreach ($languages as $lang) {
  592. if (strstr($lang, '-')) {
  593. $codes = explode('-', $lang);
  594. if ($codes[0] == 'i') {
  595. // Language not listed in ISO 639 that are not variants
  596. // of any listed language, which can be registered with the
  597. // i-prefix, such as i-cherokee
  598. if (count($codes) > 1) {
  599. $lang = $codes[1];
  600. }
  601. } else {
  602. for ($i = 0, $max = count($codes); $i < $max; $i++) {
  603. if ($i == 0) {
  604. $lang = strtolower($codes[0]);
  605. } else {
  606. $lang .= '_'.strtoupper($codes[$i]);
  607. }
  608. }
  609. }
  610. }
  611. $this->languages[] = $lang;
  612. }
  613. return $this->languages;
  614. }
  615. /**
  616. * Gets a list of charsets acceptable by the client browser.
  617. *
  618. * @return array List of charsets in preferable order
  619. */
  620. public function getCharsets()
  621. {
  622. if (null !== $this->charsets) {
  623. return $this->charsets;
  624. }
  625. return $this->charsets = $this->splitHttpAcceptHeader($this->headers->get('Accept-Charset'));
  626. }
  627. /**
  628. * Gets a list of content types acceptable by the client browser
  629. *
  630. * @return array Languages ordered in the user browser preferences
  631. */
  632. public function getAcceptableContentTypes()
  633. {
  634. if (null !== $this->acceptableContentTypes) {
  635. return $this->acceptableContentTypes;
  636. }
  637. return $this->acceptableContentTypes = $this->splitHttpAcceptHeader($this->headers->get('Accept'));
  638. }
  639. /**
  640. * Returns true if the request is a XMLHttpRequest.
  641. *
  642. * It works if your JavaScript library set an X-Requested-With HTTP header.
  643. * It is known to work with Prototype, Mootools, jQuery.
  644. *
  645. * @return bool true if the request is an XMLHttpRequest, false otherwise
  646. */
  647. public function isXmlHttpRequest()
  648. {
  649. return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
  650. }
  651. /**
  652. * Splits an Accept-* HTTP header.
  653. *
  654. * @param string $header Header to split
  655. */
  656. public function splitHttpAcceptHeader($header)
  657. {
  658. if (!$header) {
  659. return array();
  660. }
  661. $values = array();
  662. foreach (array_filter(explode(',', $header)) as $value) {
  663. // Cut off any q-value that might come after a semi-colon
  664. if ($pos = strpos($value, ';')) {
  665. $q = (float) trim(substr($value, strpos($value, '=') + 1));
  666. $value = trim(substr($value, 0, $pos));
  667. } else {
  668. $q = 1;
  669. }
  670. if (0 < $q) {
  671. $values[trim($value)] = $q;
  672. }
  673. }
  674. arsort($values);
  675. return array_keys($values);
  676. }
  677. /*
  678. * The following methods are derived from code of the Zend Framework (1.10dev - 2010-01-24)
  679. *
  680. * Code subject to the new BSD license (http://framework.zend.com/license/new-bsd).
  681. *
  682. * Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  683. */
  684. protected function prepareRequestUri()
  685. {
  686. $requestUri = '';
  687. if ($this->headers->has('X_REWRITE_URL')) {
  688. // check this first so IIS will catch
  689. $requestUri = $this->headers->get('X_REWRITE_URL');
  690. } elseif ($this->server->get('IIS_WasUrlRewritten') == '1' && $this->server->get('UNENCODED_URL') != '') {
  691. // IIS7 with URL Rewrite: make sure we get the unencoded url (double slash problem)
  692. $requestUri = $this->server->get('UNENCODED_URL');
  693. } elseif ($this->server->has('REQUEST_URI')) {
  694. $requestUri = $this->server->get('REQUEST_URI');
  695. // HTTP proxy reqs setup request uri with scheme and host [and port] + the url path, only use url path
  696. $schemeAndHttpHost = $this->getScheme().'://'.$this->getHttpHost();
  697. if (strpos($requestUri, $schemeAndHttpHost) === 0) {
  698. $requestUri = substr($requestUri, strlen($schemeAndHttpHost));
  699. }
  700. } elseif ($this->server->has('ORIG_PATH_INFO')) {
  701. // IIS 5.0, PHP as CGI
  702. $requestUri = $this->server->get('ORIG_PATH_INFO');
  703. if ($this->server->get('QUERY_STRING')) {
  704. $requestUri .= '?'.$this->server->get('QUERY_STRING');
  705. }
  706. }
  707. return $requestUri;
  708. }
  709. protected function prepareBaseUrl()
  710. {
  711. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  712. if (basename($this->server->get('SCRIPT_NAME')) === $filename) {
  713. $baseUrl = $this->server->get('SCRIPT_NAME');
  714. } elseif (basename($this->server->get('PHP_SELF')) === $filename) {
  715. $baseUrl = $this->server->get('PHP_SELF');
  716. } elseif (basename($this->server->get('ORIG_SCRIPT_NAME')) === $filename) {
  717. $baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); // 1and1 shared hosting compatibility
  718. } else {
  719. // Backtrack up the script_filename to find the portion matching
  720. // php_self
  721. $path = $this->server->get('PHP_SELF', '');
  722. $file = $this->server->get('SCRIPT_FILENAME', '');
  723. $segs = explode('/', trim($file, '/'));
  724. $segs = array_reverse($segs);
  725. $index = 0;
  726. $last = count($segs);
  727. $baseUrl = '';
  728. do {
  729. $seg = $segs[$index];
  730. $baseUrl = '/'.$seg.$baseUrl;
  731. ++$index;
  732. } while (($last > $index) && (false !== ($pos = strpos($path, $baseUrl))) && (0 != $pos));
  733. }
  734. // Does the baseUrl have anything in common with the request_uri?
  735. $requestUri = $this->getRequestUri();
  736. if ($baseUrl && 0 === strpos($requestUri, $baseUrl)) {
  737. // full $baseUrl matches
  738. return $baseUrl;
  739. }
  740. if ($baseUrl && 0 === strpos($requestUri, dirname($baseUrl))) {
  741. // directory portion of $baseUrl matches
  742. return rtrim(dirname($baseUrl), '/');
  743. }
  744. $truncatedRequestUri = $requestUri;
  745. if (($pos = strpos($requestUri, '?')) !== false) {
  746. $truncatedRequestUri = substr($requestUri, 0, $pos);
  747. }
  748. $basename = basename($baseUrl);
  749. if (empty($basename) || !strpos($truncatedRequestUri, $basename)) {
  750. // no match whatsoever; set it blank
  751. return '';
  752. }
  753. // If using mod_rewrite or ISAPI_Rewrite strip the script filename
  754. // out of baseUrl. $pos !== 0 makes sure it is not matching a value
  755. // from PATH_INFO or QUERY_STRING
  756. if ((strlen($requestUri) >= strlen($baseUrl)) && ((false !== ($pos = strpos($requestUri, $baseUrl))) && ($pos !== 0))) {
  757. $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));
  758. }
  759. return rtrim($baseUrl, '/');
  760. }
  761. protected function prepareBasePath()
  762. {
  763. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  764. $baseUrl = $this->getBaseUrl();
  765. if (empty($baseUrl)) {
  766. return '';
  767. }
  768. if (basename($baseUrl) === $filename) {
  769. $basePath = dirname($baseUrl);
  770. } else {
  771. $basePath = $baseUrl;
  772. }
  773. if ('\\' === DIRECTORY_SEPARATOR) {
  774. $basePath = str_replace('\\', '/', $basePath);
  775. }
  776. return rtrim($basePath, '/');
  777. }
  778. protected function preparePathInfo()
  779. {
  780. $baseUrl = $this->getBaseUrl();
  781. if (null === ($requestUri = $this->getRequestUri())) {
  782. return '';
  783. }
  784. $pathInfo = '';
  785. // Remove the query string from REQUEST_URI
  786. if ($pos = strpos($requestUri, '?')) {
  787. $requestUri = substr($requestUri, 0, $pos);
  788. }
  789. if ((null !== $baseUrl) && (false === ($pathInfo = substr($requestUri, strlen($baseUrl))))) {
  790. // If substr() returns false then PATH_INFO is set to an empty string
  791. return '';
  792. } elseif (null === $baseUrl) {
  793. return $requestUri;
  794. }
  795. return (string) $pathInfo;
  796. }
  797. /**
  798. * Converts uploaded files to UploadedFile instances.
  799. *
  800. * @param array $files A (multi-dimensional) array of uploaded file information
  801. *
  802. * @return array A (multi-dimensional) array of UploadedFile instances
  803. */
  804. protected function convertFileInformation(array $files)
  805. {
  806. $fixedFiles = array();
  807. foreach ($files as $key => $data) {
  808. $fixedFiles[$key] = $this->fixPhpFilesArray($data);
  809. }
  810. $fileKeys = array('error', 'name', 'size', 'tmp_name', 'type');
  811. foreach ($fixedFiles as $key => $data) {
  812. if (is_array($data)) {
  813. $keys = array_keys($data);
  814. sort($keys);
  815. if ($keys != $fileKeys) {
  816. $fixedFiles[$key] = $this->convertFileInformation($data);
  817. } else if ($data['error'] === UPLOAD_ERR_NO_FILE) {
  818. $fixedFiles[$key] = null;
  819. } else {
  820. $fixedFiles[$key] = new UploadedFile($data['tmp_name'], $data['name'], $data['type'], $data['size'], $data['error']);
  821. }
  822. }
  823. }
  824. return $fixedFiles;
  825. }
  826. /**
  827. * Fixes a malformed PHP $_FILES array.
  828. *
  829. * PHP has a bug that the format of the $_FILES array differs, depending on
  830. * whether the uploaded file fields had normal field names or array-like
  831. * field names ("normal" vs. "parent[child]").
  832. *
  833. * This method fixes the array to look like the "normal" $_FILES array.
  834. *
  835. * It's safe to pass an already converted array, in which case this method
  836. * just returns the original array unmodified.
  837. *
  838. * @param array $data
  839. * @return array
  840. */
  841. protected function fixPhpFilesArray($data)
  842. {
  843. if (!is_array($data)) {
  844. return $data;
  845. }
  846. $fileKeys = array('error', 'name', 'size', 'tmp_name', 'type');
  847. $keys = array_keys($data);
  848. sort($keys);
  849. if ($fileKeys != $keys || !isset($data['name']) || !is_array($data['name'])) {
  850. return $data;
  851. }
  852. $files = $data;
  853. foreach ($fileKeys as $k) {
  854. unset($files[$k]);
  855. }
  856. foreach (array_keys($data['name']) as $key) {
  857. $files[$key] = $this->fixPhpFilesArray(array(
  858. 'error' => $data['error'][$key],
  859. 'name' => $data['name'][$key],
  860. 'type' => $data['type'][$key],
  861. 'tmp_name' => $data['tmp_name'][$key],
  862. 'size' => $data['size'][$key],
  863. ));
  864. }
  865. return $files;
  866. }
  867. protected function initializeHeaders()
  868. {
  869. $headers = array();
  870. foreach ($this->server->all() as $key => $value) {
  871. if ('http_' === strtolower(substr($key, 0, 5))) {
  872. $headers[substr($key, 5)] = $value;
  873. }
  874. }
  875. return $headers;
  876. }
  877. static protected function initializeFormats()
  878. {
  879. static::$formats = array(
  880. 'txt' => 'text/plain',
  881. 'js' => array('application/javascript', 'application/x-javascript', 'text/javascript'),
  882. 'css' => 'text/css',
  883. 'json' => array('application/json', 'application/x-json'),
  884. 'xml' => array('text/xml', 'application/xml', 'application/x-xml'),
  885. 'rdf' => 'application/rdf+xml',
  886. 'atom' => 'application/atom+xml',
  887. );
  888. }
  889. }