Request.php 30 KB

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