Request.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963
  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. return trim($elements[count($elements) - 1]);
  385. } else {
  386. return $this->headers->get('HOST', $this->server->get('SERVER_NAME', $this->server->get('SERVER_ADDR', '')));
  387. }
  388. }
  389. public function setMethod($method)
  390. {
  391. $this->method = null;
  392. $this->server->set('REQUEST_METHOD', 'GET');
  393. }
  394. /**
  395. * Gets the request method.
  396. *
  397. * @return string The request method
  398. */
  399. public function getMethod()
  400. {
  401. if (null === $this->method) {
  402. switch ($this->server->get('REQUEST_METHOD', 'GET')) {
  403. case 'POST':
  404. $this->method = strtoupper($this->request->get('_method', 'POST'));
  405. break;
  406. case 'PUT':
  407. $this->method = 'PUT';
  408. break;
  409. case 'DELETE':
  410. $this->method = 'DELETE';
  411. break;
  412. case 'HEAD':
  413. $this->method = 'HEAD';
  414. break;
  415. default:
  416. $this->method = 'GET';
  417. }
  418. }
  419. return $this->method;
  420. }
  421. /**
  422. * Gets the mime type associated with the format.
  423. *
  424. * @param string $format The format
  425. *
  426. * @return string The associated mime type (null if not found)
  427. */
  428. public function getMimeType($format)
  429. {
  430. if (null === static::$formats) {
  431. static::initializeFormats();
  432. }
  433. return isset(static::$formats[$format]) ? static::$formats[$format][0] : null;
  434. }
  435. /**
  436. * Gets the format associated with the mime type.
  437. *
  438. * @param string $mimeType The associated mime type
  439. *
  440. * @return string The format (null if not found)
  441. */
  442. public function getFormat($mimeType)
  443. {
  444. if (null === static::$formats) {
  445. static::initializeFormats();
  446. }
  447. foreach (static::$formats as $format => $mimeTypes) {
  448. if (in_array($mimeType, (array) $mimeTypes)) {
  449. return $format;
  450. }
  451. }
  452. return null;
  453. }
  454. /**
  455. * Associates a format with mime types.
  456. *
  457. * @param string $format The format
  458. * @param string|array $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type)
  459. */
  460. public function setFormat($format, $mimeTypes)
  461. {
  462. if (null === static::$formats) {
  463. static::initializeFormats();
  464. }
  465. static::$formats[$format] = is_array($mimeTypes) ? $mimeTypes : array($mimeTypes);
  466. }
  467. /**
  468. * Gets the request format.
  469. *
  470. * Here is the process to determine the format:
  471. *
  472. * * format defined by the user (with setRequestFormat())
  473. * * _format request parameter
  474. * * null
  475. *
  476. * @return string The request format
  477. */
  478. public function getRequestFormat()
  479. {
  480. if (null === $this->format) {
  481. $this->format = $this->get('_format', 'html');
  482. }
  483. return $this->format;
  484. }
  485. public function setRequestFormat($format)
  486. {
  487. $this->format = $format;
  488. }
  489. public function isMethodSafe()
  490. {
  491. return in_array(strtolower($this->getMethod()), array('get', 'head'));
  492. }
  493. public function getETags()
  494. {
  495. return preg_split('/\s*,\s*/', $this->headers->get('if_none_match'), null, PREG_SPLIT_NO_EMPTY);
  496. }
  497. public function isNoCache()
  498. {
  499. return $this->headers->getCacheControl()->isNoCache() || 'no-cache' == $this->headers->get('Pragma');
  500. }
  501. /**
  502. * Returns the preferred language.
  503. *
  504. * @param array $locales An array of ordered available locales
  505. *
  506. * @return string The preferred locale
  507. */
  508. public function getPreferredLanguage(array $locales = null)
  509. {
  510. $preferredLanguages = $this->getLanguages();
  511. if (null === $locales) {
  512. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null;
  513. }
  514. if (!$preferredLanguages) {
  515. return $locales[0];
  516. }
  517. $preferredLanguages = array_values(array_intersect($preferredLanguages, $locales));
  518. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : $locales[0];
  519. }
  520. /**
  521. * Gets a list of languages acceptable by the client browser.
  522. *
  523. * @return array Languages ordered in the user browser preferences
  524. */
  525. public function getLanguages()
  526. {
  527. if (null !== $this->languages) {
  528. return $this->languages;
  529. }
  530. $languages = $this->splitHttpAcceptHeader($this->headers->get('Accept-Language'));
  531. foreach ($languages as $lang) {
  532. if (strstr($lang, '-')) {
  533. $codes = explode('-', $lang);
  534. if ($codes[0] == 'i') {
  535. // Language not listed in ISO 639 that are not variants
  536. // of any listed language, which can be registered with the
  537. // i-prefix, such as i-cherokee
  538. if (count($codes) > 1) {
  539. $lang = $codes[1];
  540. }
  541. } else {
  542. for ($i = 0, $max = count($codes); $i < $max; $i++) {
  543. if ($i == 0) {
  544. $lang = strtolower($codes[0]);
  545. } else {
  546. $lang .= '_'.strtoupper($codes[$i]);
  547. }
  548. }
  549. }
  550. }
  551. $this->languages[] = $lang;
  552. }
  553. return $this->languages;
  554. }
  555. /**
  556. * Gets a list of charsets acceptable by the client browser.
  557. *
  558. * @return array List of charsets in preferable order
  559. */
  560. public function getCharsets()
  561. {
  562. if (null !== $this->charsets) {
  563. return $this->charsets;
  564. }
  565. return $this->charsets = $this->splitHttpAcceptHeader($this->headers->get('Accept-Charset'));
  566. }
  567. /**
  568. * Gets a list of content types acceptable by the client browser
  569. *
  570. * @return array Languages ordered in the user browser preferences
  571. */
  572. public function getAcceptableContentTypes()
  573. {
  574. if (null !== $this->acceptableContentTypes) {
  575. return $this->acceptableContentTypes;
  576. }
  577. return $this->acceptableContentTypes = $this->splitHttpAcceptHeader($this->headers->get('Accept'));
  578. }
  579. /**
  580. * Returns true if the request is a XMLHttpRequest.
  581. *
  582. * It works if your JavaScript library set an X-Requested-With HTTP header.
  583. * It is known to work with Prototype, Mootools, jQuery.
  584. *
  585. * @return bool true if the request is an XMLHttpRequest, false otherwise
  586. */
  587. public function isXmlHttpRequest()
  588. {
  589. return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
  590. }
  591. /**
  592. * Splits an Accept-* HTTP header.
  593. *
  594. * @param string $header Header to split
  595. */
  596. public function splitHttpAcceptHeader($header)
  597. {
  598. if (!$header) {
  599. return array();
  600. }
  601. $values = array();
  602. foreach (array_filter(explode(',', $header)) as $value) {
  603. // Cut off any q-value that might come after a semi-colon
  604. if ($pos = strpos($value, ';')) {
  605. $q = (float) trim(substr($value, strpos($value, '=') + 1));
  606. $value = trim(substr($value, 0, $pos));
  607. } else {
  608. $q = 1;
  609. }
  610. if (0 < $q) {
  611. $values[trim($value)] = $q;
  612. }
  613. }
  614. arsort($values);
  615. return array_keys($values);
  616. }
  617. /*
  618. * The following methods are derived from code of the Zend Framework (1.10dev - 2010-01-24)
  619. *
  620. * Code subject to the new BSD license (http://framework.zend.com/license/new-bsd).
  621. *
  622. * Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  623. */
  624. protected function prepareRequestUri()
  625. {
  626. $requestUri = '';
  627. if ($this->headers->has('X_REWRITE_URL')) {
  628. // check this first so IIS will catch
  629. $requestUri = $this->headers->get('X_REWRITE_URL');
  630. } elseif ($this->server->get('IIS_WasUrlRewritten') == '1' && $this->server->get('UNENCODED_URL') != '') {
  631. // IIS7 with URL Rewrite: make sure we get the unencoded url (double slash problem)
  632. $requestUri = $this->server->get('UNENCODED_URL');
  633. } elseif ($this->server->has('REQUEST_URI')) {
  634. $requestUri = $this->server->get('REQUEST_URI');
  635. // HTTP proxy reqs setup request uri with scheme and host [and port] + the url path, only use url path
  636. $schemeAndHttpHost = $this->getScheme().'://'.$this->getHttpHost();
  637. if (strpos($requestUri, $schemeAndHttpHost) === 0) {
  638. $requestUri = substr($requestUri, strlen($schemeAndHttpHost));
  639. }
  640. } elseif ($this->server->has('ORIG_PATH_INFO')) {
  641. // IIS 5.0, PHP as CGI
  642. $requestUri = $this->server->get('ORIG_PATH_INFO');
  643. if ($this->server->get('QUERY_STRING')) {
  644. $requestUri .= '?'.$this->server->get('QUERY_STRING');
  645. }
  646. }
  647. return $requestUri;
  648. }
  649. protected function prepareBaseUrl()
  650. {
  651. $baseUrl = '';
  652. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  653. if (basename($this->server->get('SCRIPT_NAME')) === $filename) {
  654. $baseUrl = $this->server->get('SCRIPT_NAME');
  655. } elseif (basename($this->server->get('PHP_SELF')) === $filename) {
  656. $baseUrl = $this->server->get('PHP_SELF');
  657. } elseif (basename($this->server->get('ORIG_SCRIPT_NAME')) === $filename) {
  658. $baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); // 1and1 shared hosting compatibility
  659. } else {
  660. // Backtrack up the script_filename to find the portion matching
  661. // php_self
  662. $path = $this->server->get('PHP_SELF', '');
  663. $file = $this->server->get('SCRIPT_FILENAME', '');
  664. $segs = explode('/', trim($file, '/'));
  665. $segs = array_reverse($segs);
  666. $index = 0;
  667. $last = count($segs);
  668. $baseUrl = '';
  669. do {
  670. $seg = $segs[$index];
  671. $baseUrl = '/'.$seg.$baseUrl;
  672. ++$index;
  673. } while (($last > $index) && (false !== ($pos = strpos($path, $baseUrl))) && (0 != $pos));
  674. }
  675. // Does the baseUrl have anything in common with the request_uri?
  676. $requestUri = $this->getRequestUri();
  677. if ($baseUrl && 0 === strpos($requestUri, $baseUrl)) {
  678. // full $baseUrl matches
  679. return $baseUrl;
  680. }
  681. if ($baseUrl && 0 === strpos($requestUri, dirname($baseUrl))) {
  682. // directory portion of $baseUrl matches
  683. return rtrim(dirname($baseUrl), '/');
  684. }
  685. $truncatedRequestUri = $requestUri;
  686. if (($pos = strpos($requestUri, '?')) !== false) {
  687. $truncatedRequestUri = substr($requestUri, 0, $pos);
  688. }
  689. $basename = basename($baseUrl);
  690. if (empty($basename) || !strpos($truncatedRequestUri, $basename)) {
  691. // no match whatsoever; set it blank
  692. return '';
  693. }
  694. // If using mod_rewrite or ISAPI_Rewrite strip the script filename
  695. // out of baseUrl. $pos !== 0 makes sure it is not matching a value
  696. // from PATH_INFO or QUERY_STRING
  697. if ((strlen($requestUri) >= strlen($baseUrl)) && ((false !== ($pos = strpos($requestUri, $baseUrl))) && ($pos !== 0))) {
  698. $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));
  699. }
  700. return rtrim($baseUrl, '/');
  701. }
  702. protected function prepareBasePath()
  703. {
  704. $basePath = '';
  705. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  706. $baseUrl = $this->getBaseUrl();
  707. if (empty($baseUrl)) {
  708. return '';
  709. }
  710. if (basename($baseUrl) === $filename) {
  711. $basePath = dirname($baseUrl);
  712. } else {
  713. $basePath = $baseUrl;
  714. }
  715. if ('\\' === DIRECTORY_SEPARATOR) {
  716. $basePath = str_replace('\\', '/', $basePath);
  717. }
  718. return rtrim($basePath, '/');
  719. }
  720. protected function preparePathInfo()
  721. {
  722. $baseUrl = $this->getBaseUrl();
  723. if (null === ($requestUri = $this->getRequestUri())) {
  724. return '';
  725. }
  726. $pathInfo = '';
  727. // Remove the query string from REQUEST_URI
  728. if ($pos = strpos($requestUri, '?')) {
  729. $requestUri = substr($requestUri, 0, $pos);
  730. }
  731. if ((null !== $baseUrl) && (false === ($pathInfo = substr($requestUri, strlen($baseUrl))))) {
  732. // If substr() returns false then PATH_INFO is set to an empty string
  733. return '';
  734. } elseif (null === $baseUrl) {
  735. return $requestUri;
  736. }
  737. return (string) $pathInfo;
  738. }
  739. /**
  740. * Converts uploaded files to UploadedFile instances.
  741. *
  742. * @param array $files A (multi-dimensional) array of uploaded file information
  743. *
  744. * @return array A (multi-dimensional) array of UploadedFile instances
  745. */
  746. protected function convertFileInformation(array $files)
  747. {
  748. $fixedFiles = array();
  749. foreach ($files as $key => $data) {
  750. $fixedFiles[$key] = $this->fixPhpFilesArray($data);
  751. }
  752. $fileKeys = array('error', 'name', 'size', 'tmp_name', 'type');
  753. foreach ($fixedFiles as $key => $data) {
  754. if (is_array($data)) {
  755. $keys = array_keys($data);
  756. sort($keys);
  757. if ($keys == $fileKeys) {
  758. $fixedFiles[$key] = new UploadedFile($data['tmp_name'], $data['name'], $data['type'], $data['size'], $data['error']);
  759. } else {
  760. $fixedFiles[$key] = $this->convertFileInformation($data);
  761. }
  762. }
  763. }
  764. return $fixedFiles;
  765. }
  766. /**
  767. * Fixes a malformed PHP $_FILES array.
  768. *
  769. * PHP has a bug that the format of the $_FILES array differs, depending on
  770. * whether the uploaded file fields had normal field names or array-like
  771. * field names ("normal" vs. "parent[child]").
  772. *
  773. * This method fixes the array to look like the "normal" $_FILES array.
  774. *
  775. * It's safe to pass an already converted array, in which case this method
  776. * just returns the original array unmodified.
  777. *
  778. * @param array $data
  779. * @return array
  780. */
  781. protected function fixPhpFilesArray($data)
  782. {
  783. if (!is_array($data)) {
  784. return $data;
  785. }
  786. $fileKeys = array('error', 'name', 'size', 'tmp_name', 'type');
  787. $keys = array_keys($data);
  788. sort($keys);
  789. if ($fileKeys != $keys || !isset($data['name']) || !is_array($data['name'])) {
  790. return $data;
  791. }
  792. $files = $data;
  793. foreach ($fileKeys as $k) {
  794. unset($files[$k]);
  795. }
  796. foreach (array_keys($data['name']) as $key) {
  797. $files[$key] = $this->fixPhpFilesArray(array(
  798. 'error' => $data['error'][$key],
  799. 'name' => $data['name'][$key],
  800. 'type' => $data['type'][$key],
  801. 'tmp_name' => $data['tmp_name'][$key],
  802. 'size' => $data['size'][$key],
  803. ));
  804. }
  805. return $files;
  806. }
  807. protected function initializeHeaders()
  808. {
  809. $headers = array();
  810. foreach ($this->server->all() as $key => $value) {
  811. if ('http_' === strtolower(substr($key, 0, 5))) {
  812. $headers[substr($key, 5)] = $value;
  813. }
  814. }
  815. return $headers;
  816. }
  817. static protected function initializeFormats()
  818. {
  819. static::$formats = array(
  820. 'txt' => 'text/plain',
  821. 'js' => array('application/javascript', 'application/x-javascript', 'text/javascript'),
  822. 'css' => 'text/css',
  823. 'json' => array('application/json', 'application/x-json'),
  824. 'xml' => array('text/xml', 'application/xml', 'application/x-xml'),
  825. 'rdf' => 'application/rdf+xml',
  826. 'atom' => 'application/atom+xml',
  827. );
  828. }
  829. }