Request.php 41KB

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