Request.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation;
  11. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  12. /**
  13. * Request represents an HTTP request.
  14. *
  15. * @author Fabien Potencier <fabien@symfony.com>
  16. *
  17. * @api
  18. */
  19. class Request
  20. {
  21. static protected $trustProxy = false;
  22. /**
  23. * @var \Symfony\Component\HttpFoundation\ParameterBag
  24. *
  25. * @api
  26. */
  27. public $attributes;
  28. /**
  29. * @var \Symfony\Component\HttpFoundation\ParameterBag
  30. *
  31. * @api
  32. */
  33. public $request;
  34. /**
  35. * @var \Symfony\Component\HttpFoundation\ParameterBag
  36. *
  37. * @api
  38. */
  39. public $query;
  40. /**
  41. * @var \Symfony\Component\HttpFoundation\ServerBag
  42. *
  43. * @api
  44. */
  45. public $server;
  46. /**
  47. * @var \Symfony\Component\HttpFoundation\FileBag
  48. *
  49. * @api
  50. */
  51. public $files;
  52. /**
  53. * @var \Symfony\Component\HttpFoundation\ParameterBag
  54. *
  55. * @api
  56. */
  57. public $cookies;
  58. /**
  59. * @var \Symfony\Component\HttpFoundation\HeaderBag
  60. *
  61. * @api
  62. */
  63. public $headers;
  64. /**
  65. * @var string
  66. */
  67. protected $content;
  68. /**
  69. * @var string
  70. */
  71. protected $languages;
  72. /**
  73. * @var string
  74. */
  75. protected $charsets;
  76. /**
  77. * @var string
  78. */
  79. protected $acceptableContentTypes;
  80. /**
  81. * @var string
  82. */
  83. protected $pathInfo;
  84. /**
  85. * @var string
  86. */
  87. protected $requestUri;
  88. /**
  89. * @var string
  90. */
  91. protected $baseUrl;
  92. /**
  93. * @var string
  94. */
  95. protected $basePath;
  96. /**
  97. * @var string
  98. */
  99. protected $method;
  100. /**
  101. * @var string
  102. */
  103. protected $format;
  104. /**
  105. * @var \Symfony\Component\HttpFoundation\Session\SessionInterface
  106. */
  107. protected $session;
  108. /**
  109. * @var string
  110. */
  111. protected $locale;
  112. /**
  113. * @var string
  114. */
  115. protected $defaultLocale = 'en';
  116. /**
  117. * @var string
  118. */
  119. static protected $formats;
  120. /**
  121. * Constructor.
  122. *
  123. * @param array $query The GET parameters
  124. * @param array $request The POST parameters
  125. * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
  126. * @param array $cookies The COOKIE parameters
  127. * @param array $files The FILES parameters
  128. * @param array $server The SERVER parameters
  129. * @param string $content The raw body data
  130. *
  131. * @api
  132. */
  133. public function __construct(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
  134. {
  135. $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content);
  136. }
  137. /**
  138. * Sets the parameters for this request.
  139. *
  140. * This method also re-initializes all properties.
  141. *
  142. * @param array $query The GET parameters
  143. * @param array $request The POST parameters
  144. * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
  145. * @param array $cookies The COOKIE parameters
  146. * @param array $files The FILES parameters
  147. * @param array $server The SERVER parameters
  148. * @param string $content The raw body data
  149. *
  150. * @api
  151. */
  152. public function initialize(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
  153. {
  154. $this->request = new ParameterBag($request);
  155. $this->query = new ParameterBag($query);
  156. $this->attributes = new ParameterBag($attributes);
  157. $this->cookies = new ParameterBag($cookies);
  158. $this->files = new FileBag($files);
  159. $this->server = new ServerBag($server);
  160. $this->headers = new HeaderBag($this->server->getHeaders());
  161. $this->content = $content;
  162. $this->languages = null;
  163. $this->charsets = null;
  164. $this->acceptableContentTypes = null;
  165. $this->pathInfo = null;
  166. $this->requestUri = null;
  167. $this->baseUrl = null;
  168. $this->basePath = null;
  169. $this->method = null;
  170. $this->format = null;
  171. }
  172. /**
  173. * Creates a new request with values from PHP's super globals.
  174. *
  175. * @return Request A new request
  176. *
  177. * @api
  178. */
  179. static public function createFromGlobals()
  180. {
  181. $request = new static($_GET, $_POST, array(), $_COOKIE, $_FILES, $_SERVER);
  182. if (0 === strpos($request->server->get('CONTENT_TYPE'), 'application/x-www-form-urlencoded')
  183. && in_array(strtoupper($request->server->get('REQUEST_METHOD', 'GET')), array('PUT', 'DELETE', 'PATCH'))
  184. ) {
  185. parse_str($request->getContent(), $data);
  186. $request->request = new ParameterBag($data);
  187. }
  188. return $request;
  189. }
  190. /**
  191. * Creates a Request based on a given URI and configuration.
  192. *
  193. * @param string $uri The URI
  194. * @param string $method The HTTP method
  195. * @param array $parameters The request (GET) or query (POST) parameters
  196. * @param array $cookies The request cookies ($_COOKIE)
  197. * @param array $files The request files ($_FILES)
  198. * @param array $server The server parameters ($_SERVER)
  199. * @param string $content The raw body data
  200. *
  201. * @return Request A Request instance
  202. *
  203. * @api
  204. */
  205. static public function create($uri, $method = 'GET', $parameters = array(), $cookies = array(), $files = array(), $server = array(), $content = null)
  206. {
  207. $defaults = array(
  208. 'SERVER_NAME' => 'localhost',
  209. 'SERVER_PORT' => 80,
  210. 'HTTP_HOST' => 'localhost',
  211. 'HTTP_USER_AGENT' => 'Symfony/2.X',
  212. 'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  213. 'HTTP_ACCEPT_LANGUAGE' => 'en-us,en;q=0.5',
  214. 'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  215. 'REMOTE_ADDR' => '127.0.0.1',
  216. 'SCRIPT_NAME' => '',
  217. 'SCRIPT_FILENAME' => '',
  218. 'SERVER_PROTOCOL' => 'HTTP/1.1',
  219. 'REQUEST_TIME' => time(),
  220. );
  221. $components = parse_url($uri);
  222. if (isset($components['host'])) {
  223. $defaults['SERVER_NAME'] = $components['host'];
  224. $defaults['HTTP_HOST'] = $components['host'];
  225. }
  226. if (isset($components['scheme'])) {
  227. if ('https' === $components['scheme']) {
  228. $defaults['HTTPS'] = 'on';
  229. $defaults['SERVER_PORT'] = 443;
  230. }
  231. }
  232. if (isset($components['port'])) {
  233. $defaults['SERVER_PORT'] = $components['port'];
  234. $defaults['HTTP_HOST'] = $defaults['HTTP_HOST'].':'.$components['port'];
  235. }
  236. if (isset($components['user'])) {
  237. $defaults['PHP_AUTH_USER'] = $components['user'];
  238. }
  239. if (isset($components['pass'])) {
  240. $defaults['PHP_AUTH_PW'] = $components['pass'];
  241. }
  242. if (!isset($components['path'])) {
  243. $components['path'] = '';
  244. }
  245. switch (strtoupper($method)) {
  246. case 'POST':
  247. case 'PUT':
  248. case 'DELETE':
  249. $defaults['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
  250. case 'PATCH':
  251. $request = $parameters;
  252. $query = array();
  253. break;
  254. default:
  255. $request = array();
  256. $query = $parameters;
  257. break;
  258. }
  259. if (isset($components['query'])) {
  260. $queryString = html_entity_decode($components['query']);
  261. parse_str($queryString, $qs);
  262. if (is_array($qs)) {
  263. $query = array_replace($qs, $query);
  264. }
  265. }
  266. $queryString = http_build_query($query);
  267. $uri = $components['path'].($queryString ? '?'.$queryString : '');
  268. $server = array_replace($defaults, $server, array(
  269. 'REQUEST_METHOD' => strtoupper($method),
  270. 'PATH_INFO' => '',
  271. 'REQUEST_URI' => $uri,
  272. 'QUERY_STRING' => $queryString,
  273. ));
  274. return new static($query, $request, array(), $cookies, $files, $server, $content);
  275. }
  276. /**
  277. * Clones a request and overrides some of its parameters.
  278. *
  279. * @param array $query The GET parameters
  280. * @param array $request The POST parameters
  281. * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
  282. * @param array $cookies The COOKIE parameters
  283. * @param array $files The FILES parameters
  284. * @param array $server The SERVER parameters
  285. *
  286. * @api
  287. */
  288. public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null)
  289. {
  290. $dup = clone $this;
  291. if ($query !== null) {
  292. $dup->query = new ParameterBag($query);
  293. }
  294. if ($request !== null) {
  295. $dup->request = new ParameterBag($request);
  296. }
  297. if ($attributes !== null) {
  298. $dup->attributes = new ParameterBag($attributes);
  299. }
  300. if ($cookies !== null) {
  301. $dup->cookies = new ParameterBag($cookies);
  302. }
  303. if ($files !== null) {
  304. $dup->files = new FileBag($files);
  305. }
  306. if ($server !== null) {
  307. $dup->server = new ServerBag($server);
  308. $dup->headers = new HeaderBag($dup->server->getHeaders());
  309. }
  310. $dup->languages = null;
  311. $dup->charsets = null;
  312. $dup->acceptableContentTypes = null;
  313. $dup->pathInfo = null;
  314. $dup->requestUri = null;
  315. $dup->baseUrl = null;
  316. $dup->basePath = null;
  317. $dup->method = null;
  318. $dup->format = null;
  319. return $dup;
  320. }
  321. /**
  322. * Clones the current request.
  323. *
  324. * Note that the session is not cloned as duplicated requests
  325. * are most of the time sub-requests of the main one.
  326. */
  327. public function __clone()
  328. {
  329. $this->query = clone $this->query;
  330. $this->request = clone $this->request;
  331. $this->attributes = clone $this->attributes;
  332. $this->cookies = clone $this->cookies;
  333. $this->files = clone $this->files;
  334. $this->server = clone $this->server;
  335. $this->headers = clone $this->headers;
  336. }
  337. /**
  338. * Returns the request as a string.
  339. *
  340. * @return string The request
  341. */
  342. public function __toString()
  343. {
  344. return
  345. sprintf('%s %s %s', $this->getMethod(), $this->getRequestUri(), $this->server->get('SERVER_PROTOCOL'))."\r\n".
  346. $this->headers."\r\n".
  347. $this->getContent();
  348. }
  349. /**
  350. * Overrides the PHP global variables according to this request instance.
  351. *
  352. * It overrides $_GET, $_POST, $_REQUEST, $_SERVER, $_COOKIE, and $_FILES.
  353. *
  354. * @api
  355. */
  356. public function overrideGlobals()
  357. {
  358. $_GET = $this->query->all();
  359. $_POST = $this->request->all();
  360. $_SERVER = $this->server->all();
  361. $_COOKIE = $this->cookies->all();
  362. // FIXME: populate $_FILES
  363. foreach ($this->headers->all() as $key => $value) {
  364. $key = strtoupper(str_replace('-', '_', $key));
  365. if (in_array($key, array('CONTENT_TYPE', 'CONTENT_LENGTH'))) {
  366. $_SERVER[$key] = implode(', ', $value);
  367. } else {
  368. $_SERVER['HTTP_'.$key] = implode(', ', $value);
  369. }
  370. }
  371. // FIXME: should read variables_order and request_order
  372. // to know which globals to merge and in which order
  373. $_REQUEST = array_merge($_GET, $_POST);
  374. }
  375. /**
  376. * Trusts $_SERVER entries coming from proxies.
  377. *
  378. * You should only call this method if your application
  379. * is hosted behind a reverse proxy that you manage.
  380. *
  381. * @api
  382. */
  383. static public function trustProxyData()
  384. {
  385. self::$trustProxy = true;
  386. }
  387. /**
  388. * Returns true if $_SERVER entries coming from proxies are trusted,
  389. * false otherwise.
  390. *
  391. * @return boolean
  392. */
  393. static public function isProxyTrusted()
  394. {
  395. return self::$trustProxy;
  396. }
  397. /**
  398. * Gets a "parameter" value.
  399. *
  400. * This method is mainly useful for libraries that want to provide some flexibility.
  401. *
  402. * Order of precedence: GET, PATH, POST, COOKIE
  403. *
  404. * Avoid using this method in controllers:
  405. *
  406. * * slow
  407. * * prefer to get from a "named" source
  408. *
  409. * It is better to explicity get request parameters from the appropriate
  410. * public property instead (query, request, attributes, ...).
  411. *
  412. * @param string $key the key
  413. * @param mixed $default the default value
  414. * @param type $deep is parameter deep in multidimensional array
  415. *
  416. * @return mixed
  417. */
  418. public function get($key, $default = null, $deep = false)
  419. {
  420. return $this->query->get($key, $this->attributes->get($key, $this->request->get($key, $default, $deep), $deep), $deep);
  421. }
  422. /**
  423. * Gets the Session.
  424. *
  425. * @return SessionInterface|null The session
  426. *
  427. * @api
  428. */
  429. public function getSession()
  430. {
  431. return $this->session;
  432. }
  433. /**
  434. * Whether the request contains a Session which was started in one of the
  435. * previous requests.
  436. *
  437. * @return boolean
  438. *
  439. * @api
  440. */
  441. public function hasPreviousSession()
  442. {
  443. // the check for $this->session avoids malicious users trying to fake a session cookie with proper name
  444. $sessionName = $this->hasSession() ? $this->session->getName() : null;
  445. return $this->cookies->has($sessionName) && $this->hasSession();
  446. }
  447. /**
  448. * Whether the request contains a Session object.
  449. *
  450. * @return boolean
  451. *
  452. * @api
  453. */
  454. public function hasSession()
  455. {
  456. return null !== $this->session;
  457. }
  458. /**
  459. * Sets the Session.
  460. *
  461. * @param SessionInterface $session The Session
  462. *
  463. * @api
  464. */
  465. public function setSession(SessionInterface $session)
  466. {
  467. $this->session = $session;
  468. }
  469. /**
  470. * Returns the client IP address.
  471. *
  472. * @return string The client IP address
  473. *
  474. * @api
  475. */
  476. public function getClientIp()
  477. {
  478. if (self::$trustProxy) {
  479. if ($this->server->has('HTTP_CLIENT_IP')) {
  480. return $this->server->get('HTTP_CLIENT_IP');
  481. } elseif ($this->server->has('HTTP_X_FORWARDED_FOR')) {
  482. $clientIp = explode(',', $this->server->get('HTTP_X_FORWARDED_FOR'), 2);
  483. return isset($clientIp[0]) ? trim($clientIp[0]) : '';
  484. }
  485. }
  486. return $this->server->get('REMOTE_ADDR');
  487. }
  488. /**
  489. * Returns current script name.
  490. *
  491. * @return string
  492. *
  493. * @api
  494. */
  495. public function getScriptName()
  496. {
  497. return $this->server->get('SCRIPT_NAME', $this->server->get('ORIG_SCRIPT_NAME', ''));
  498. }
  499. /**
  500. * Returns the path being requested relative to the executed script.
  501. *
  502. * The path info always starts with a /.
  503. *
  504. * Suppose this request is instantiated from /mysite on localhost:
  505. *
  506. * * http://localhost/mysite returns an empty string
  507. * * http://localhost/mysite/about returns '/about'
  508. * * http://localhost/mysite/about?var=1 returns '/about'
  509. *
  510. * @return string
  511. *
  512. * @api
  513. */
  514. public function getPathInfo()
  515. {
  516. if (null === $this->pathInfo) {
  517. $this->pathInfo = $this->preparePathInfo();
  518. }
  519. return $this->pathInfo;
  520. }
  521. /**
  522. * Returns the root path from which this request is executed.
  523. *
  524. * Suppose that an index.php file instantiates this request object:
  525. *
  526. * * http://localhost/index.php returns an empty string
  527. * * http://localhost/index.php/page returns an empty string
  528. * * http://localhost/web/index.php return '/web'
  529. *
  530. * @return string
  531. *
  532. * @api
  533. */
  534. public function getBasePath()
  535. {
  536. if (null === $this->basePath) {
  537. $this->basePath = $this->prepareBasePath();
  538. }
  539. return $this->basePath;
  540. }
  541. /**
  542. * Returns the root url from which this request is executed.
  543. *
  544. * The base URL never ends with a /.
  545. *
  546. * This is similar to getBasePath(), except that it also includes the
  547. * script filename (e.g. index.php) if one exists.
  548. *
  549. * @return string
  550. *
  551. * @api
  552. */
  553. public function getBaseUrl()
  554. {
  555. if (null === $this->baseUrl) {
  556. $this->baseUrl = $this->prepareBaseUrl();
  557. }
  558. return $this->baseUrl;
  559. }
  560. /**
  561. * Gets the request's scheme.
  562. *
  563. * @return string
  564. *
  565. * @api
  566. */
  567. public function getScheme()
  568. {
  569. return $this->isSecure() ? 'https' : 'http';
  570. }
  571. /**
  572. * Returns the port on which the request is made.
  573. *
  574. * @return string
  575. *
  576. * @api
  577. */
  578. public function getPort()
  579. {
  580. if (self::$trustProxy && $this->headers->has('X-Forwarded-Port')) {
  581. return $this->headers->get('X-Forwarded-Port');
  582. } else {
  583. return $this->server->get('SERVER_PORT');
  584. }
  585. }
  586. /**
  587. * Returns the user.
  588. *
  589. * @return string|null
  590. */
  591. public function getUser()
  592. {
  593. return $this->server->get('PHP_AUTH_USER');
  594. }
  595. /**
  596. * Returns the password.
  597. *
  598. * @return string|null
  599. */
  600. public function getPassword()
  601. {
  602. return $this->server->get('PHP_AUTH_PW');
  603. }
  604. /**
  605. * Returns the HTTP host being requested.
  606. *
  607. * The port name will be appended to the host if it's non-standard.
  608. *
  609. * @return string
  610. *
  611. * @api
  612. */
  613. public function getHttpHost()
  614. {
  615. $scheme = $this->getScheme();
  616. $port = $this->getPort();
  617. if (('http' == $scheme && $port == 80) || ('https' == $scheme && $port == 443)) {
  618. return $this->getHost();
  619. }
  620. return $this->getHost().':'.$port;
  621. }
  622. /**
  623. * Returns the requested URI.
  624. *
  625. * @return string
  626. *
  627. * @api
  628. */
  629. public function getRequestUri()
  630. {
  631. if (null === $this->requestUri) {
  632. $this->requestUri = $this->prepareRequestUri();
  633. }
  634. return $this->requestUri;
  635. }
  636. /**
  637. * Generates a normalized URI for the Request.
  638. *
  639. * @return string A normalized URI for the Request
  640. *
  641. * @see getQueryString()
  642. *
  643. * @api
  644. */
  645. public function getUri()
  646. {
  647. $qs = $this->getQueryString();
  648. if (null !== $qs) {
  649. $qs = '?'.$qs;
  650. }
  651. $auth = '';
  652. if ($user = $this->getUser()) {
  653. $auth = $user;
  654. }
  655. if ($pass = $this->getPassword()) {
  656. $auth .= ":$pass";
  657. }
  658. if ('' !== $auth) {
  659. $auth .= '@';
  660. }
  661. return $this->getScheme().'://'.$auth.$this->getHttpHost().$this->getBaseUrl().$this->getPathInfo().$qs;
  662. }
  663. /**
  664. * Generates a normalized URI for the given path.
  665. *
  666. * @param string $path A path to use instead of the current one
  667. *
  668. * @return string The normalized URI for the path
  669. *
  670. * @api
  671. */
  672. public function getUriForPath($path)
  673. {
  674. return $this->getScheme().'://'.$this->getHttpHost().$this->getBaseUrl().$path;
  675. }
  676. /**
  677. * Generates the normalized query string for the Request.
  678. *
  679. * It builds a normalized query string, where keys/value pairs are alphabetized
  680. * and have consistent escaping.
  681. *
  682. * @return string|null A normalized query string for the Request
  683. *
  684. * @api
  685. */
  686. public function getQueryString()
  687. {
  688. if (!$qs = $this->server->get('QUERY_STRING')) {
  689. return null;
  690. }
  691. $parts = array();
  692. $order = array();
  693. foreach (explode('&', $qs) as $segment) {
  694. if (false === strpos($segment, '=')) {
  695. $parts[] = $segment;
  696. $order[] = $segment;
  697. } else {
  698. $tmp = explode('=', rawurldecode($segment), 2);
  699. $parts[] = rawurlencode($tmp[0]).'='.rawurlencode($tmp[1]);
  700. $order[] = $tmp[0];
  701. }
  702. }
  703. array_multisort($order, SORT_ASC, $parts);
  704. return implode('&', $parts);
  705. }
  706. /**
  707. * Checks whether the request is secure or not.
  708. *
  709. * @return Boolean
  710. *
  711. * @api
  712. */
  713. public function isSecure()
  714. {
  715. return (
  716. (strtolower($this->server->get('HTTPS')) == 'on' || $this->server->get('HTTPS') == 1)
  717. ||
  718. (self::$trustProxy && strtolower($this->headers->get('SSL_HTTPS')) == 'on' || $this->headers->get('SSL_HTTPS') == 1)
  719. ||
  720. (self::$trustProxy && strtolower($this->headers->get('X_FORWARDED_PROTO')) == 'https')
  721. );
  722. }
  723. /**
  724. * Returns the host name.
  725. *
  726. * @return string
  727. *
  728. * @api
  729. */
  730. public function getHost()
  731. {
  732. if (self::$trustProxy && $host = $this->headers->get('X_FORWARDED_HOST')) {
  733. $elements = explode(',', $host);
  734. $host = trim($elements[count($elements) - 1]);
  735. } else {
  736. if (!$host = $this->headers->get('HOST')) {
  737. if (!$host = $this->server->get('SERVER_NAME')) {
  738. $host = $this->server->get('SERVER_ADDR', '');
  739. }
  740. }
  741. }
  742. // Remove port number from host
  743. $host = preg_replace('/:\d+$/', '', $host);
  744. return trim($host);
  745. }
  746. /**
  747. * Sets the request method.
  748. *
  749. * @param string $method
  750. *
  751. * @api
  752. */
  753. public function setMethod($method)
  754. {
  755. $this->method = null;
  756. $this->server->set('REQUEST_METHOD', $method);
  757. }
  758. /**
  759. * Gets the request method.
  760. *
  761. * The method is always an uppercased string.
  762. *
  763. * @return string The request method
  764. *
  765. * @api
  766. */
  767. public function getMethod()
  768. {
  769. if (null === $this->method) {
  770. $this->method = strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
  771. if ('POST' === $this->method) {
  772. $this->method = strtoupper($this->headers->get('X-HTTP-METHOD-OVERRIDE', $this->request->get('_method', 'POST')));
  773. }
  774. }
  775. return $this->method;
  776. }
  777. /**
  778. * Gets the mime type associated with the format.
  779. *
  780. * @param string $format The format
  781. *
  782. * @return string The associated mime type (null if not found)
  783. *
  784. * @api
  785. */
  786. public function getMimeType($format)
  787. {
  788. if (null === static::$formats) {
  789. static::initializeFormats();
  790. }
  791. return isset(static::$formats[$format]) ? static::$formats[$format][0] : null;
  792. }
  793. /**
  794. * Gets the format associated with the mime type.
  795. *
  796. * @param string $mimeType The associated mime type
  797. *
  798. * @return string The format (null if not found)
  799. *
  800. * @api
  801. */
  802. public function getFormat($mimeType)
  803. {
  804. if (false !== $pos = strpos($mimeType, ';')) {
  805. $mimeType = substr($mimeType, 0, $pos);
  806. }
  807. if (null === static::$formats) {
  808. static::initializeFormats();
  809. }
  810. foreach (static::$formats as $format => $mimeTypes) {
  811. if (in_array($mimeType, (array) $mimeTypes)) {
  812. return $format;
  813. }
  814. }
  815. return null;
  816. }
  817. /**
  818. * Associates a format with mime types.
  819. *
  820. * @param string $format The format
  821. * @param string|array $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type)
  822. *
  823. * @api
  824. */
  825. public function setFormat($format, $mimeTypes)
  826. {
  827. if (null === static::$formats) {
  828. static::initializeFormats();
  829. }
  830. static::$formats[$format] = is_array($mimeTypes) ? $mimeTypes : array($mimeTypes);
  831. }
  832. /**
  833. * Gets the request format.
  834. *
  835. * Here is the process to determine the format:
  836. *
  837. * * format defined by the user (with setRequestFormat())
  838. * * _format request parameter
  839. * * $default
  840. *
  841. * @param string $default The default format
  842. *
  843. * @return string The request format
  844. *
  845. * @api
  846. */
  847. public function getRequestFormat($default = 'html')
  848. {
  849. if (null === $this->format) {
  850. $this->format = $this->get('_format', $default);
  851. }
  852. return $this->format;
  853. }
  854. /**
  855. * Sets the request format.
  856. *
  857. * @param string $format The request format.
  858. *
  859. * @api
  860. */
  861. public function setRequestFormat($format)
  862. {
  863. $this->format = $format;
  864. }
  865. /**
  866. * Gets the format associated with the request.
  867. *
  868. * @return string The format (null if no content type is present)
  869. *
  870. * @api
  871. */
  872. public function getContentType()
  873. {
  874. return $this->getFormat($this->server->get('CONTENT_TYPE'));
  875. }
  876. /**
  877. * Sets the default locale.
  878. *
  879. * @param string $locale
  880. *
  881. * @api
  882. */
  883. public function setDefaultLocale($locale)
  884. {
  885. $this->setPhpDefaultLocale($this->defaultLocale = $locale);
  886. }
  887. /**
  888. * Sets the locale.
  889. *
  890. * @param string $locale
  891. *
  892. * @api
  893. */
  894. public function setLocale($locale)
  895. {
  896. $this->setPhpDefaultLocale($this->locale = $locale);
  897. }
  898. /**
  899. * Get the locale.
  900. *
  901. * @return string
  902. */
  903. public function getLocale()
  904. {
  905. return null === $this->locale ? $this->defaultLocale : $this->locale;
  906. }
  907. /**
  908. * Checks whether the method is safe or not.
  909. *
  910. * @return Boolean
  911. *
  912. * @api
  913. */
  914. public function isMethodSafe()
  915. {
  916. return in_array($this->getMethod(), array('GET', 'HEAD'));
  917. }
  918. /**
  919. * Returns the request body content.
  920. *
  921. * @param Boolean $asResource If true, a resource will be returned
  922. *
  923. * @return string|resource The request body content or a resource to read the body stream.
  924. */
  925. public function getContent($asResource = false)
  926. {
  927. if (false === $this->content || (true === $asResource && null !== $this->content)) {
  928. throw new \LogicException('getContent() can only be called once when using the resource return type.');
  929. }
  930. if (true === $asResource) {
  931. $this->content = false;
  932. return fopen('php://input', 'rb');
  933. }
  934. if (null === $this->content) {
  935. $this->content = file_get_contents('php://input');
  936. }
  937. return $this->content;
  938. }
  939. /**
  940. * Gets the Etags.
  941. *
  942. * @return array The entity tags
  943. */
  944. public function getETags()
  945. {
  946. return preg_split('/\s*,\s*/', $this->headers->get('if_none_match'), null, PREG_SPLIT_NO_EMPTY);
  947. }
  948. public function isNoCache()
  949. {
  950. return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma');
  951. }
  952. /**
  953. * Returns the preferred language.
  954. *
  955. * @param array $locales An array of ordered available locales
  956. *
  957. * @return string|null The preferred locale
  958. *
  959. * @api
  960. */
  961. public function getPreferredLanguage(array $locales = null)
  962. {
  963. $preferredLanguages = $this->getLanguages();
  964. if (empty($locales)) {
  965. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null;
  966. }
  967. if (!$preferredLanguages) {
  968. return $locales[0];
  969. }
  970. $preferredLanguages = array_values(array_intersect($preferredLanguages, $locales));
  971. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : $locales[0];
  972. }
  973. /**
  974. * Gets a list of languages acceptable by the client browser.
  975. *
  976. * @return array Languages ordered in the user browser preferences
  977. *
  978. * @api
  979. */
  980. public function getLanguages()
  981. {
  982. if (null !== $this->languages) {
  983. return $this->languages;
  984. }
  985. $languages = $this->splitHttpAcceptHeader($this->headers->get('Accept-Language'));
  986. $this->languages = array();
  987. foreach ($languages as $lang => $q) {
  988. if (strstr($lang, '-')) {
  989. $codes = explode('-', $lang);
  990. if ($codes[0] == 'i') {
  991. // Language not listed in ISO 639 that are not variants
  992. // of any listed language, which can be registered with the
  993. // i-prefix, such as i-cherokee
  994. if (count($codes) > 1) {
  995. $lang = $codes[1];
  996. }
  997. } else {
  998. for ($i = 0, $max = count($codes); $i < $max; $i++) {
  999. if ($i == 0) {
  1000. $lang = strtolower($codes[0]);
  1001. } else {
  1002. $lang .= '_'.strtoupper($codes[$i]);
  1003. }
  1004. }
  1005. }
  1006. }
  1007. $this->languages[] = $lang;
  1008. }
  1009. return $this->languages;
  1010. }
  1011. /**
  1012. * Gets a list of charsets acceptable by the client browser.
  1013. *
  1014. * @return array List of charsets in preferable order
  1015. *
  1016. * @api
  1017. */
  1018. public function getCharsets()
  1019. {
  1020. if (null !== $this->charsets) {
  1021. return $this->charsets;
  1022. }
  1023. return $this->charsets = array_keys($this->splitHttpAcceptHeader($this->headers->get('Accept-Charset')));
  1024. }
  1025. /**
  1026. * Gets a list of content types acceptable by the client browser
  1027. *
  1028. * @return array List of content types in preferable order
  1029. *
  1030. * @api
  1031. */
  1032. public function getAcceptableContentTypes()
  1033. {
  1034. if (null !== $this->acceptableContentTypes) {
  1035. return $this->acceptableContentTypes;
  1036. }
  1037. return $this->acceptableContentTypes = array_keys($this->splitHttpAcceptHeader($this->headers->get('Accept')));
  1038. }
  1039. /**
  1040. * Returns true if the request is a XMLHttpRequest.
  1041. *
  1042. * It works if your JavaScript library set an X-Requested-With HTTP header.
  1043. * It is known to work with Prototype, Mootools, jQuery.
  1044. *
  1045. * @return Boolean true if the request is an XMLHttpRequest, false otherwise
  1046. *
  1047. * @api
  1048. */
  1049. public function isXmlHttpRequest()
  1050. {
  1051. return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
  1052. }
  1053. /**
  1054. * Splits an Accept-* HTTP header.
  1055. *
  1056. * @param string $header Header to split
  1057. *
  1058. * @return array Array indexed by the values of the Accept-* header in preferred order
  1059. */
  1060. public function splitHttpAcceptHeader($header)
  1061. {
  1062. if (!$header) {
  1063. return array();
  1064. }
  1065. $values = array();
  1066. foreach (array_filter(explode(',', $header)) as $value) {
  1067. // Cut off any q-value that might come after a semi-colon
  1068. if (preg_match('/;\s*(q=.*$)/', $value, $match)) {
  1069. $q = (float) substr(trim($match[1]), 2);
  1070. $value = trim(substr($value, 0, -strlen($match[0])));
  1071. } else {
  1072. $q = 1;
  1073. }
  1074. if (0 < $q) {
  1075. $values[trim($value)] = $q;
  1076. }
  1077. }
  1078. arsort($values);
  1079. reset($values);
  1080. return $values;
  1081. }
  1082. /*
  1083. * The following methods are derived from code of the Zend Framework (1.10dev - 2010-01-24)
  1084. *
  1085. * Code subject to the new BSD license (http://framework.zend.com/license/new-bsd).
  1086. *
  1087. * Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  1088. */
  1089. protected function prepareRequestUri()
  1090. {
  1091. $requestUri = '';
  1092. if ($this->headers->has('X_REWRITE_URL') && false !== stripos(PHP_OS, 'WIN')) {
  1093. // check this first so IIS will catch
  1094. $requestUri = $this->headers->get('X_REWRITE_URL');
  1095. } elseif ($this->server->get('IIS_WasUrlRewritten') == '1' && $this->server->get('UNENCODED_URL') != '') {
  1096. // IIS7 with URL Rewrite: make sure we get the unencoded url (double slash problem)
  1097. $requestUri = $this->server->get('UNENCODED_URL');
  1098. } elseif ($this->server->has('REQUEST_URI')) {
  1099. $requestUri = $this->server->get('REQUEST_URI');
  1100. // HTTP proxy reqs setup request uri with scheme and host [and port] + the url path, only use url path
  1101. $schemeAndHttpHost = $this->getScheme().'://'.$this->getHttpHost();
  1102. if (strpos($requestUri, $schemeAndHttpHost) === 0) {
  1103. $requestUri = substr($requestUri, strlen($schemeAndHttpHost));
  1104. }
  1105. } elseif ($this->server->has('ORIG_PATH_INFO')) {
  1106. // IIS 5.0, PHP as CGI
  1107. $requestUri = $this->server->get('ORIG_PATH_INFO');
  1108. if ($this->server->get('QUERY_STRING')) {
  1109. $requestUri .= '?'.$this->server->get('QUERY_STRING');
  1110. }
  1111. }
  1112. return $requestUri;
  1113. }
  1114. /**
  1115. * Prepares the base URL.
  1116. *
  1117. * @return string
  1118. */
  1119. protected function prepareBaseUrl()
  1120. {
  1121. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  1122. if (basename($this->server->get('SCRIPT_NAME')) === $filename) {
  1123. $baseUrl = $this->server->get('SCRIPT_NAME');
  1124. } elseif (basename($this->server->get('PHP_SELF')) === $filename) {
  1125. $baseUrl = $this->server->get('PHP_SELF');
  1126. } elseif (basename($this->server->get('ORIG_SCRIPT_NAME')) === $filename) {
  1127. $baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); // 1and1 shared hosting compatibility
  1128. } else {
  1129. // Backtrack up the script_filename to find the portion matching
  1130. // php_self
  1131. $path = $this->server->get('PHP_SELF', '');
  1132. $file = $this->server->get('SCRIPT_FILENAME', '');
  1133. $segs = explode('/', trim($file, '/'));
  1134. $segs = array_reverse($segs);
  1135. $index = 0;
  1136. $last = count($segs);
  1137. $baseUrl = '';
  1138. do {
  1139. $seg = $segs[$index];
  1140. $baseUrl = '/'.$seg.$baseUrl;
  1141. ++$index;
  1142. } while (($last > $index) && (false !== ($pos = strpos($path, $baseUrl))) && (0 != $pos));
  1143. }
  1144. // Does the baseUrl have anything in common with the request_uri?
  1145. $requestUri = $this->getRequestUri();
  1146. if ($baseUrl && 0 === strpos($requestUri, $baseUrl)) {
  1147. // full $baseUrl matches
  1148. return $baseUrl;
  1149. }
  1150. if ($baseUrl && 0 === strpos($requestUri, dirname($baseUrl))) {
  1151. // directory portion of $baseUrl matches
  1152. return rtrim(dirname($baseUrl), '/');
  1153. }
  1154. $truncatedRequestUri = $requestUri;
  1155. if (($pos = strpos($requestUri, '?')) !== false) {
  1156. $truncatedRequestUri = substr($requestUri, 0, $pos);
  1157. }
  1158. $basename = basename($baseUrl);
  1159. if (empty($basename) || !strpos($truncatedRequestUri, $basename)) {
  1160. // no match whatsoever; set it blank
  1161. return '';
  1162. }
  1163. // If using mod_rewrite or ISAPI_Rewrite strip the script filename
  1164. // out of baseUrl. $pos !== 0 makes sure it is not matching a value
  1165. // from PATH_INFO or QUERY_STRING
  1166. if ((strlen($requestUri) >= strlen($baseUrl)) && ((false !== ($pos = strpos($requestUri, $baseUrl))) && ($pos !== 0))) {
  1167. $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));
  1168. }
  1169. return rtrim($baseUrl, '/');
  1170. }
  1171. /**
  1172. * Prepares the base path.
  1173. *
  1174. * @return string base path
  1175. */
  1176. protected function prepareBasePath()
  1177. {
  1178. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  1179. $baseUrl = $this->getBaseUrl();
  1180. if (empty($baseUrl)) {
  1181. return '';
  1182. }
  1183. if (basename($baseUrl) === $filename) {
  1184. $basePath = dirname($baseUrl);
  1185. } else {
  1186. $basePath = $baseUrl;
  1187. }
  1188. if ('\\' === DIRECTORY_SEPARATOR) {
  1189. $basePath = str_replace('\\', '/', $basePath);
  1190. }
  1191. return rtrim($basePath, '/');
  1192. }
  1193. /**
  1194. * Prepares the path info.
  1195. *
  1196. * @return string path info
  1197. */
  1198. protected function preparePathInfo()
  1199. {
  1200. $baseUrl = $this->getBaseUrl();
  1201. if (null === ($requestUri = $this->getRequestUri())) {
  1202. return '/';
  1203. }
  1204. $pathInfo = '/';
  1205. // Remove the query string from REQUEST_URI
  1206. if ($pos = strpos($requestUri, '?')) {
  1207. $requestUri = substr($requestUri, 0, $pos);
  1208. }
  1209. if ((null !== $baseUrl) && (false === ($pathInfo = substr(urldecode($requestUri), strlen(urldecode($baseUrl)))))) {
  1210. // If substr() returns false then PATH_INFO is set to an empty string
  1211. return '/';
  1212. } elseif (null === $baseUrl) {
  1213. return $requestUri;
  1214. }
  1215. return (string) $pathInfo;
  1216. }
  1217. /**
  1218. * Initializes HTTP request formats.
  1219. */
  1220. static protected function initializeFormats()
  1221. {
  1222. static::$formats = array(
  1223. 'html' => array('text/html', 'application/xhtml+xml'),
  1224. 'txt' => array('text/plain'),
  1225. 'js' => array('application/javascript', 'application/x-javascript', 'text/javascript'),
  1226. 'css' => array('text/css'),
  1227. 'json' => array('application/json', 'application/x-json'),
  1228. 'xml' => array('text/xml', 'application/xml', 'application/x-xml'),
  1229. 'rdf' => array('application/rdf+xml'),
  1230. 'atom' => array('application/atom+xml'),
  1231. 'rss' => array('application/rss+xml'),
  1232. );
  1233. }
  1234. /**
  1235. * Sets the default PHP locale.
  1236. *
  1237. * @param string $locale
  1238. */
  1239. private function setPhpDefaultLocale($locale)
  1240. {
  1241. // if either the class Locale doesn't exist, or an exception is thrown when
  1242. // setting the default locale, the intl module is not installed, and
  1243. // the call can be ignored:
  1244. try {
  1245. if (class_exists('Locale', false)) {
  1246. \Locale::setDefault($locale);
  1247. }
  1248. } catch (\Exception $e) {
  1249. }
  1250. }
  1251. }