Request.php 32 KB

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