Request.php 31 KB

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