Request.php 30 KB

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