Request.php 31 KB

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