Request.php 36KB

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