Request.php 35KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238
  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. return $this->headers->get('X-Forwarded-Port') ?: $this->server->get('SERVER_PORT');
  512. }
  513. /**
  514. * Returns the HTTP host being requested.
  515. *
  516. * The port name will be appended to the host if it's non-standard.
  517. *
  518. * @return string
  519. *
  520. * @api
  521. */
  522. public function getHttpHost()
  523. {
  524. $scheme = $this->getScheme();
  525. $port = $this->getPort();
  526. if (('http' == $scheme && $port == 80) || ('https' == $scheme && $port == 443)) {
  527. return $this->getHost();
  528. }
  529. return $this->getHost().':'.$port;
  530. }
  531. /**
  532. * Returns the requested URI.
  533. *
  534. * @return string
  535. *
  536. * @api
  537. */
  538. public function getRequestUri()
  539. {
  540. if (null === $this->requestUri) {
  541. $this->requestUri = $this->prepareRequestUri();
  542. }
  543. return $this->requestUri;
  544. }
  545. /**
  546. * Generates a normalized URI for the Request.
  547. *
  548. * @return string A normalized URI for the Request
  549. *
  550. * @see getQueryString()
  551. *
  552. * @api
  553. */
  554. public function getUri()
  555. {
  556. $qs = $this->getQueryString();
  557. if (null !== $qs) {
  558. $qs = '?'.$qs;
  559. }
  560. return $this->getScheme().'://'.$this->getHttpHost().$this->getBaseUrl().$this->getPathInfo().$qs;
  561. }
  562. /**
  563. * Generates a normalized URI for the given path.
  564. *
  565. * @param string $path A path to use instead of the current one
  566. *
  567. * @return string The normalized URI for the path
  568. *
  569. * @api
  570. */
  571. public function getUriForPath($path)
  572. {
  573. return $this->getScheme().'://'.$this->getHttpHost().$this->getBaseUrl().$path;
  574. }
  575. /**
  576. * Generates the normalized query string for the Request.
  577. *
  578. * It builds a normalized query string, where keys/value pairs are alphabetized
  579. * and have consistent escaping.
  580. *
  581. * @return string A normalized query string for the Request
  582. *
  583. * @api
  584. */
  585. public function getQueryString()
  586. {
  587. if (!$qs = $this->server->get('QUERY_STRING')) {
  588. return null;
  589. }
  590. $parts = array();
  591. $order = array();
  592. foreach (explode('&', $qs) as $segment) {
  593. if (false === strpos($segment, '=')) {
  594. $parts[] = $segment;
  595. $order[] = $segment;
  596. } else {
  597. $tmp = explode('=', rawurldecode($segment), 2);
  598. $parts[] = rawurlencode($tmp[0]).'='.rawurlencode($tmp[1]);
  599. $order[] = $tmp[0];
  600. }
  601. }
  602. array_multisort($order, SORT_ASC, $parts);
  603. return implode('&', $parts);
  604. }
  605. /**
  606. * Checks whether the request is secure or not.
  607. *
  608. * @return Boolean
  609. *
  610. * @api
  611. */
  612. public function isSecure()
  613. {
  614. return (
  615. (strtolower($this->server->get('HTTPS')) == 'on' || $this->server->get('HTTPS') == 1)
  616. ||
  617. (self::$trustProxy && strtolower($this->headers->get('SSL_HTTPS')) == 'on' || $this->headers->get('SSL_HTTPS') == 1)
  618. ||
  619. (self::$trustProxy && strtolower($this->headers->get('X_FORWARDED_PROTO')) == 'https')
  620. );
  621. }
  622. /**
  623. * Returns the host name.
  624. *
  625. * @return string
  626. *
  627. * @api
  628. */
  629. public function getHost()
  630. {
  631. if (self::$trustProxy && $host = $this->headers->get('X_FORWARDED_HOST')) {
  632. $elements = explode(',', $host);
  633. $host = trim($elements[count($elements) - 1]);
  634. } else {
  635. if (!$host = $this->headers->get('HOST')) {
  636. if (!$host = $this->server->get('SERVER_NAME')) {
  637. $host = $this->server->get('SERVER_ADDR', '');
  638. }
  639. }
  640. }
  641. // Remove port number from host
  642. $host = preg_replace('/:\d+$/', '', $host);
  643. return trim($host);
  644. }
  645. /**
  646. * Sets the request method.
  647. *
  648. * @param string $method
  649. *
  650. * @api
  651. */
  652. public function setMethod($method)
  653. {
  654. $this->method = null;
  655. $this->server->set('REQUEST_METHOD', $method);
  656. }
  657. /**
  658. * Gets the request method.
  659. *
  660. * The method is always an uppercased string.
  661. *
  662. * @return string The request method
  663. *
  664. * @api
  665. */
  666. public function getMethod()
  667. {
  668. if (null === $this->method) {
  669. $this->method = strtoupper($this->server->get('REQUEST_METHOD', 'GET'));
  670. if ('POST' === $this->method) {
  671. $this->method = strtoupper($this->headers->get('X-HTTP-METHOD-OVERRIDE', $this->request->get('_method', 'POST')));
  672. }
  673. }
  674. return $this->method;
  675. }
  676. /**
  677. * Gets the mime type associated with the format.
  678. *
  679. * @param string $format The format
  680. *
  681. * @return string The associated mime type (null if not found)
  682. *
  683. * @api
  684. */
  685. public function getMimeType($format)
  686. {
  687. if (null === static::$formats) {
  688. static::initializeFormats();
  689. }
  690. return isset(static::$formats[$format]) ? static::$formats[$format][0] : null;
  691. }
  692. /**
  693. * Gets the format associated with the mime type.
  694. *
  695. * @param string $mimeType The associated mime type
  696. *
  697. * @return string The format (null if not found)
  698. *
  699. * @api
  700. */
  701. public function getFormat($mimeType)
  702. {
  703. if (false !== $pos = strpos($mimeType, ';')) {
  704. $mimeType = substr($mimeType, 0, $pos);
  705. }
  706. if (null === static::$formats) {
  707. static::initializeFormats();
  708. }
  709. foreach (static::$formats as $format => $mimeTypes) {
  710. if (in_array($mimeType, (array) $mimeTypes)) {
  711. return $format;
  712. }
  713. }
  714. return null;
  715. }
  716. /**
  717. * Associates a format with mime types.
  718. *
  719. * @param string $format The format
  720. * @param string|array $mimeTypes The associated mime types (the preferred one must be the first as it will be used as the content type)
  721. *
  722. * @api
  723. */
  724. public function setFormat($format, $mimeTypes)
  725. {
  726. if (null === static::$formats) {
  727. static::initializeFormats();
  728. }
  729. static::$formats[$format] = is_array($mimeTypes) ? $mimeTypes : array($mimeTypes);
  730. }
  731. /**
  732. * Gets the request format.
  733. *
  734. * Here is the process to determine the format:
  735. *
  736. * * format defined by the user (with setRequestFormat())
  737. * * _format request parameter
  738. * * $default
  739. *
  740. * @param string $default The default format
  741. *
  742. * @return string The request format
  743. *
  744. * @api
  745. */
  746. public function getRequestFormat($default = 'html')
  747. {
  748. if (null === $this->format) {
  749. $this->format = $this->get('_format', $default);
  750. }
  751. return $this->format;
  752. }
  753. /**
  754. * Sets the request format.
  755. *
  756. * @param string $format The request format.
  757. *
  758. * @api
  759. */
  760. public function setRequestFormat($format)
  761. {
  762. $this->format = $format;
  763. }
  764. public function setLocale($locale)
  765. {
  766. if (!$this->hasSession()) {
  767. throw new \LogicException('Forward compatibility for Request::setLocale() requires the session to be set.');
  768. }
  769. $this->session->setLocale($locale);
  770. }
  771. public function getLocale()
  772. {
  773. if (!$this->hasSession()) {
  774. throw new \LogicException('Forward compatibility for Request::getLocale() requires the session to be set.');
  775. }
  776. return $this->session->getLocale();
  777. }
  778. /**
  779. * Checks whether the method is safe or not.
  780. *
  781. * @return Boolean
  782. *
  783. * @api
  784. */
  785. public function isMethodSafe()
  786. {
  787. return in_array($this->getMethod(), array('GET', 'HEAD'));
  788. }
  789. /**
  790. * Returns the request body content.
  791. *
  792. * @param Boolean $asResource If true, a resource will be returned
  793. *
  794. * @return string|resource The request body content or a resource to read the body stream.
  795. */
  796. public function getContent($asResource = false)
  797. {
  798. if (false === $this->content || (true === $asResource && null !== $this->content)) {
  799. throw new \LogicException('getContent() can only be called once when using the resource return type.');
  800. }
  801. if (true === $asResource) {
  802. $this->content = false;
  803. return fopen('php://input', 'rb');
  804. }
  805. if (null === $this->content) {
  806. $this->content = file_get_contents('php://input');
  807. }
  808. return $this->content;
  809. }
  810. /**
  811. * Gets the Etags.
  812. *
  813. * @return array The entity tags
  814. */
  815. public function getETags()
  816. {
  817. return preg_split('/\s*,\s*/', $this->headers->get('if_none_match'), null, PREG_SPLIT_NO_EMPTY);
  818. }
  819. public function isNoCache()
  820. {
  821. return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma');
  822. }
  823. /**
  824. * Returns the preferred language.
  825. *
  826. * @param array $locales An array of ordered available locales
  827. *
  828. * @return string The preferred locale
  829. *
  830. * @api
  831. */
  832. public function getPreferredLanguage(array $locales = null)
  833. {
  834. $preferredLanguages = $this->getLanguages();
  835. if (null === $locales) {
  836. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null;
  837. }
  838. if (!$preferredLanguages) {
  839. return $locales[0];
  840. }
  841. $preferredLanguages = array_values(array_intersect($preferredLanguages, $locales));
  842. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : $locales[0];
  843. }
  844. /**
  845. * Gets a list of languages acceptable by the client browser.
  846. *
  847. * @return array Languages ordered in the user browser preferences
  848. *
  849. * @api
  850. */
  851. public function getLanguages()
  852. {
  853. if (null !== $this->languages) {
  854. return $this->languages;
  855. }
  856. $languages = $this->splitHttpAcceptHeader($this->headers->get('Accept-Language'));
  857. $this->languages = array();
  858. foreach ($languages as $lang => $q) {
  859. if (strstr($lang, '-')) {
  860. $codes = explode('-', $lang);
  861. if ($codes[0] == 'i') {
  862. // Language not listed in ISO 639 that are not variants
  863. // of any listed language, which can be registered with the
  864. // i-prefix, such as i-cherokee
  865. if (count($codes) > 1) {
  866. $lang = $codes[1];
  867. }
  868. } else {
  869. for ($i = 0, $max = count($codes); $i < $max; $i++) {
  870. if ($i == 0) {
  871. $lang = strtolower($codes[0]);
  872. } else {
  873. $lang .= '_'.strtoupper($codes[$i]);
  874. }
  875. }
  876. }
  877. }
  878. $this->languages[] = $lang;
  879. }
  880. return $this->languages;
  881. }
  882. /**
  883. * Gets a list of charsets acceptable by the client browser.
  884. *
  885. * @return array List of charsets in preferable order
  886. *
  887. * @api
  888. */
  889. public function getCharsets()
  890. {
  891. if (null !== $this->charsets) {
  892. return $this->charsets;
  893. }
  894. return $this->charsets = array_keys($this->splitHttpAcceptHeader($this->headers->get('Accept-Charset')));
  895. }
  896. /**
  897. * Gets a list of content types acceptable by the client browser
  898. *
  899. * @return array List of content types in preferable order
  900. *
  901. * @api
  902. */
  903. public function getAcceptableContentTypes()
  904. {
  905. if (null !== $this->acceptableContentTypes) {
  906. return $this->acceptableContentTypes;
  907. }
  908. return $this->acceptableContentTypes = array_keys($this->splitHttpAcceptHeader($this->headers->get('Accept')));
  909. }
  910. /**
  911. * Returns true if the request is a XMLHttpRequest.
  912. *
  913. * It works if your JavaScript library set an X-Requested-With HTTP header.
  914. * It is known to work with Prototype, Mootools, jQuery.
  915. *
  916. * @return Boolean true if the request is an XMLHttpRequest, false otherwise
  917. *
  918. * @api
  919. */
  920. public function isXmlHttpRequest()
  921. {
  922. return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
  923. }
  924. /**
  925. * Splits an Accept-* HTTP header.
  926. *
  927. * @param string $header Header to split
  928. */
  929. public function splitHttpAcceptHeader($header)
  930. {
  931. if (!$header) {
  932. return array();
  933. }
  934. $values = array();
  935. foreach (array_filter(explode(',', $header)) as $value) {
  936. // Cut off any q-value that might come after a semi-colon
  937. if (preg_match('/;\s*(q=.*$)/', $value, $match)) {
  938. $q = (float) substr(trim($match[1]), 2);
  939. $value = trim(substr($value, 0, -strlen($match[0])));
  940. } else {
  941. $q = 1;
  942. }
  943. if (0 < $q) {
  944. $values[trim($value)] = $q;
  945. }
  946. }
  947. arsort($values);
  948. reset($values);
  949. return $values;
  950. }
  951. /*
  952. * The following methods are derived from code of the Zend Framework (1.10dev - 2010-01-24)
  953. *
  954. * Code subject to the new BSD license (http://framework.zend.com/license/new-bsd).
  955. *
  956. * Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  957. */
  958. protected function prepareRequestUri()
  959. {
  960. $requestUri = '';
  961. if ($this->headers->has('X_REWRITE_URL') && false !== stripos(PHP_OS, 'WIN')) {
  962. // check this first so IIS will catch
  963. $requestUri = $this->headers->get('X_REWRITE_URL');
  964. } elseif ($this->server->get('IIS_WasUrlRewritten') == '1' && $this->server->get('UNENCODED_URL') != '') {
  965. // IIS7 with URL Rewrite: make sure we get the unencoded url (double slash problem)
  966. $requestUri = $this->server->get('UNENCODED_URL');
  967. } elseif ($this->server->has('REQUEST_URI')) {
  968. $requestUri = $this->server->get('REQUEST_URI');
  969. // HTTP proxy reqs setup request uri with scheme and host [and port] + the url path, only use url path
  970. $schemeAndHttpHost = $this->getScheme().'://'.$this->getHttpHost();
  971. if (strpos($requestUri, $schemeAndHttpHost) === 0) {
  972. $requestUri = substr($requestUri, strlen($schemeAndHttpHost));
  973. }
  974. } elseif ($this->server->has('ORIG_PATH_INFO')) {
  975. // IIS 5.0, PHP as CGI
  976. $requestUri = $this->server->get('ORIG_PATH_INFO');
  977. if ($this->server->get('QUERY_STRING')) {
  978. $requestUri .= '?'.$this->server->get('QUERY_STRING');
  979. }
  980. }
  981. return $requestUri;
  982. }
  983. protected function prepareBaseUrl()
  984. {
  985. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  986. if (basename($this->server->get('SCRIPT_NAME')) === $filename) {
  987. $baseUrl = $this->server->get('SCRIPT_NAME');
  988. } elseif (basename($this->server->get('PHP_SELF')) === $filename) {
  989. $baseUrl = $this->server->get('PHP_SELF');
  990. } elseif (basename($this->server->get('ORIG_SCRIPT_NAME')) === $filename) {
  991. $baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); // 1and1 shared hosting compatibility
  992. } else {
  993. // Backtrack up the script_filename to find the portion matching
  994. // php_self
  995. $path = $this->server->get('PHP_SELF', '');
  996. $file = $this->server->get('SCRIPT_FILENAME', '');
  997. $segs = explode('/', trim($file, '/'));
  998. $segs = array_reverse($segs);
  999. $index = 0;
  1000. $last = count($segs);
  1001. $baseUrl = '';
  1002. do {
  1003. $seg = $segs[$index];
  1004. $baseUrl = '/'.$seg.$baseUrl;
  1005. ++$index;
  1006. } while (($last > $index) && (false !== ($pos = strpos($path, $baseUrl))) && (0 != $pos));
  1007. }
  1008. // Does the baseUrl have anything in common with the request_uri?
  1009. $requestUri = $this->getRequestUri();
  1010. if ($baseUrl && 0 === strpos($requestUri, $baseUrl)) {
  1011. // full $baseUrl matches
  1012. return $baseUrl;
  1013. }
  1014. if ($baseUrl && 0 === strpos($requestUri, dirname($baseUrl))) {
  1015. // directory portion of $baseUrl matches
  1016. return rtrim(dirname($baseUrl), '/');
  1017. }
  1018. $truncatedRequestUri = $requestUri;
  1019. if (($pos = strpos($requestUri, '?')) !== false) {
  1020. $truncatedRequestUri = substr($requestUri, 0, $pos);
  1021. }
  1022. $basename = basename($baseUrl);
  1023. if (empty($basename) || !strpos($truncatedRequestUri, $basename)) {
  1024. // no match whatsoever; set it blank
  1025. return '';
  1026. }
  1027. // If using mod_rewrite or ISAPI_Rewrite strip the script filename
  1028. // out of baseUrl. $pos !== 0 makes sure it is not matching a value
  1029. // from PATH_INFO or QUERY_STRING
  1030. if ((strlen($requestUri) >= strlen($baseUrl)) && ((false !== ($pos = strpos($requestUri, $baseUrl))) && ($pos !== 0))) {
  1031. $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));
  1032. }
  1033. return rtrim($baseUrl, '/');
  1034. }
  1035. /**
  1036. * Prepares base path.
  1037. *
  1038. * @return string base path
  1039. */
  1040. protected function prepareBasePath()
  1041. {
  1042. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  1043. $baseUrl = $this->getBaseUrl();
  1044. if (empty($baseUrl)) {
  1045. return '';
  1046. }
  1047. if (basename($baseUrl) === $filename) {
  1048. $basePath = dirname($baseUrl);
  1049. } else {
  1050. $basePath = $baseUrl;
  1051. }
  1052. if ('\\' === DIRECTORY_SEPARATOR) {
  1053. $basePath = str_replace('\\', '/', $basePath);
  1054. }
  1055. return rtrim($basePath, '/');
  1056. }
  1057. /**
  1058. * Prepares path info.
  1059. *
  1060. * @return string path info
  1061. */
  1062. protected function preparePathInfo()
  1063. {
  1064. $baseUrl = $this->getBaseUrl();
  1065. if (null === ($requestUri = $this->getRequestUri())) {
  1066. return '/';
  1067. }
  1068. $pathInfo = '/';
  1069. // Remove the query string from REQUEST_URI
  1070. if ($pos = strpos($requestUri, '?')) {
  1071. $requestUri = substr($requestUri, 0, $pos);
  1072. }
  1073. if ((null !== $baseUrl) && (false === ($pathInfo = substr(urldecode($requestUri), strlen(urldecode($baseUrl)))))) {
  1074. // If substr() returns false then PATH_INFO is set to an empty string
  1075. return '/';
  1076. } elseif (null === $baseUrl) {
  1077. return $requestUri;
  1078. }
  1079. return (string) $pathInfo;
  1080. }
  1081. /**
  1082. * Initializes HTTP request formats.
  1083. */
  1084. static protected function initializeFormats()
  1085. {
  1086. static::$formats = array(
  1087. 'html' => array('text/html', 'application/xhtml+xml'),
  1088. 'txt' => array('text/plain'),
  1089. 'js' => array('application/javascript', 'application/x-javascript', 'text/javascript'),
  1090. 'css' => array('text/css'),
  1091. 'json' => array('application/json', 'application/x-json'),
  1092. 'xml' => array('text/xml', 'application/xml', 'application/x-xml'),
  1093. 'rdf' => array('application/rdf+xml'),
  1094. 'atom' => array('application/atom+xml'),
  1095. );
  1096. }
  1097. }