Request.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983
  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. use Symfony\Component\HttpFoundation\File\UploadedFile;
  13. /**
  14. * Request represents an HTTP request.
  15. *
  16. * @author Fabien Potencier <fabien@symfony.com>
  17. */
  18. class Request
  19. {
  20. /**
  21. * @var \Symfony\Component\HttpFoundation\ParameterBag
  22. */
  23. public $attributes;
  24. /**
  25. * @var \Symfony\Component\HttpFoundation\ParameterBag
  26. */
  27. public $request;
  28. /**
  29. * @var \Symfony\Component\HttpFoundation\ParameterBag
  30. */
  31. public $query;
  32. /**
  33. * @var \Symfony\Component\HttpFoundation\ParameterBag
  34. */
  35. public $server;
  36. /**
  37. * @var \Symfony\Component\HttpFoundation\ParameterBag
  38. */
  39. public $files;
  40. /**
  41. * @var \Symfony\Component\HttpFoundation\ParameterBag
  42. */
  43. public $cookies;
  44. /**
  45. * @var \Symfony\Component\HttpFoundation\HeaderBag
  46. */
  47. public $headers;
  48. protected $content;
  49. protected $languages;
  50. protected $charsets;
  51. protected $acceptableContentTypes;
  52. protected $pathInfo;
  53. protected $requestUri;
  54. protected $baseUrl;
  55. protected $basePath;
  56. protected $method;
  57. protected $format;
  58. protected $session;
  59. static protected $formats;
  60. /**
  61. * Constructor.
  62. *
  63. * @param array $query The GET parameters
  64. * @param array $request The POST parameters
  65. * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
  66. * @param array $cookies The COOKIE parameters
  67. * @param array $files The FILES parameters
  68. * @param array $server The SERVER parameters
  69. * @param string $content The raw body data
  70. */
  71. public function __construct(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
  72. {
  73. $this->initialize($query, $request, $attributes, $cookies, $files, $server, $content);
  74. }
  75. /**
  76. * Sets the parameters for this request.
  77. *
  78. * This method also re-initializes all properties.
  79. *
  80. * @param array $query The GET parameters
  81. * @param array $request The POST parameters
  82. * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
  83. * @param array $cookies The COOKIE parameters
  84. * @param array $files The FILES parameters
  85. * @param array $server The SERVER parameters
  86. * @param string $content The raw body data
  87. */
  88. public function initialize(array $query = array(), array $request = array(), array $attributes = array(), array $cookies = array(), array $files = array(), array $server = array(), $content = null)
  89. {
  90. $this->request = new ParameterBag($request);
  91. $this->query = new ParameterBag($query);
  92. $this->attributes = new ParameterBag($attributes);
  93. $this->cookies = new ParameterBag($cookies);
  94. $this->files = new FileBag($files);
  95. $this->server = new ServerBag($server);
  96. $this->headers = new HeaderBag($this->server->getHeaders());
  97. $this->content = $content;
  98. $this->languages = null;
  99. $this->charsets = null;
  100. $this->acceptableContentTypes = null;
  101. $this->pathInfo = null;
  102. $this->requestUri = null;
  103. $this->baseUrl = null;
  104. $this->basePath = null;
  105. $this->method = null;
  106. $this->format = null;
  107. }
  108. /**
  109. * Creates a new request with values from PHP's super globals.
  110. *
  111. * @return Request A new request
  112. */
  113. static public function createfromGlobals()
  114. {
  115. return new static($_GET, $_POST, array(), $_COOKIE, $_FILES, $_SERVER);
  116. }
  117. /**
  118. * Creates a Request based on a given URI and configuration.
  119. *
  120. * @param string $uri The URI
  121. * @param string $method The HTTP method
  122. * @param array $parameters The request (GET) or query (POST) parameters
  123. * @param array $cookies The request cookies ($_COOKIE)
  124. * @param array $files The request files ($_FILES)
  125. * @param array $server The server parameters ($_SERVER)
  126. * @param string $content The raw body data
  127. *
  128. * @return Request A Request instance
  129. */
  130. static public function create($uri, $method = 'GET', $parameters = array(), $cookies = array(), $files = array(), $server = array(), $content = null)
  131. {
  132. $defaults = array(
  133. 'SERVER_NAME' => 'localhost',
  134. 'SERVER_PORT' => 80,
  135. 'HTTP_HOST' => 'localhost',
  136. 'HTTP_USER_AGENT' => 'Symfony/2.X',
  137. 'HTTP_ACCEPT' => 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
  138. 'HTTP_ACCEPT_LANGUAGE' => 'en-us,en;q=0.5',
  139. 'HTTP_ACCEPT_CHARSET' => 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  140. 'REMOTE_ADDR' => '127.0.0.1',
  141. 'SCRIPT_NAME' => '',
  142. 'SCRIPT_FILENAME' => '',
  143. );
  144. $components = parse_url($uri);
  145. if (isset($components['host'])) {
  146. $defaults['SERVER_NAME'] = $components['host'];
  147. $defaults['HTTP_HOST'] = $components['host'];
  148. }
  149. if (isset($components['scheme'])) {
  150. if ('https' === $components['scheme']) {
  151. $defaults['HTTPS'] = 'on';
  152. $defaults['SERVER_PORT'] = 443;
  153. }
  154. }
  155. if (isset($components['port'])) {
  156. $defaults['SERVER_PORT'] = $components['port'];
  157. $defaults['HTTP_HOST'] = $defaults['HTTP_HOST'].':'.$components['port'];
  158. }
  159. if (in_array(strtoupper($method), array('POST', 'PUT', 'DELETE'))) {
  160. $request = $parameters;
  161. $query = array();
  162. $defaults['CONTENT_TYPE'] = 'application/x-www-form-urlencoded';
  163. } else {
  164. $request = array();
  165. $query = $parameters;
  166. if (false !== $pos = strpos($uri, '?')) {
  167. $qs = substr($uri, $pos + 1);
  168. parse_str($qs, $params);
  169. $query = array_merge($params, $query);
  170. }
  171. }
  172. $queryString = isset($components['query']) ? html_entity_decode($components['query']) : '';
  173. parse_str($queryString, $qs);
  174. if (is_array($qs)) {
  175. $query = array_replace($qs, $query);
  176. }
  177. $uri = $components['path'] . ($queryString ? '?'.$queryString : '');
  178. $server = array_replace($defaults, $server, array(
  179. 'REQUEST_METHOD' => strtoupper($method),
  180. 'PATH_INFO' => '',
  181. 'REQUEST_URI' => $uri,
  182. 'QUERY_STRING' => $queryString,
  183. ));
  184. return new static($query, $request, array(), $cookies, $files, $server, $content);
  185. }
  186. /**
  187. * Clones a request and overrides some of its parameters.
  188. *
  189. * @param array $query The GET parameters
  190. * @param array $request The POST parameters
  191. * @param array $attributes The request attributes (parameters parsed from the PATH_INFO, ...)
  192. * @param array $cookies The COOKIE parameters
  193. * @param array $files The FILES parameters
  194. * @param array $server The SERVER parameters
  195. */
  196. public function duplicate(array $query = null, array $request = null, array $attributes = null, array $cookies = null, array $files = null, array $server = null)
  197. {
  198. $dup = clone $this;
  199. if ($query !== null) {
  200. $dup->query = new ParameterBag($query);
  201. }
  202. if ($request !== null) {
  203. $dup->request = new ParameterBag($request);
  204. }
  205. if ($attributes !== null) {
  206. $dup->attributes = new ParameterBag($attributes);
  207. }
  208. if ($cookies !== null) {
  209. $dup->cookies = new ParameterBag($cookies);
  210. }
  211. if ($files !== null) {
  212. $dup->files = new FileBag($files);
  213. }
  214. if ($server !== null) {
  215. $dup->server = new ServerBag($server);
  216. $dup->headers = new HeaderBag($dup->server->getHeaders());
  217. }
  218. $this->languages = null;
  219. $this->charsets = null;
  220. $this->acceptableContentTypes = null;
  221. $this->pathInfo = null;
  222. $this->requestUri = null;
  223. $this->baseUrl = null;
  224. $this->basePath = null;
  225. $this->method = null;
  226. $this->format = null;
  227. return $dup;
  228. }
  229. /**
  230. * Clones the current request.
  231. *
  232. * Note that the session is not cloned as duplicated requests
  233. * are most of the time sub-requests of the main one.
  234. */
  235. public function __clone()
  236. {
  237. $this->query = clone $this->query;
  238. $this->request = clone $this->request;
  239. $this->attributes = clone $this->attributes;
  240. $this->cookies = clone $this->cookies;
  241. $this->files = clone $this->files;
  242. $this->server = clone $this->server;
  243. $this->headers = clone $this->headers;
  244. }
  245. /**
  246. * Overrides the PHP global variables according to this request instance.
  247. *
  248. * It overrides $_GET, $_POST, $_REQUEST, $_SERVER, $_COOKIE, and $_FILES.
  249. */
  250. public function overrideGlobals()
  251. {
  252. $_GET = $this->query->all();
  253. $_POST = $this->request->all();
  254. $_SERVER = $this->server->all();
  255. $_COOKIE = $this->cookies->all();
  256. // FIXME: populate $_FILES
  257. foreach ($this->headers->all() as $key => $value) {
  258. $_SERVER['HTTP_'.strtoupper(str_replace('-', '_', $key))] = implode(', ', $value);
  259. }
  260. // FIXME: should read variables_order and request_order
  261. // to know which globals to merge and in which order
  262. $_REQUEST = array_merge($_GET, $_POST);
  263. }
  264. // Order of precedence: GET, PATH, POST, COOKIE
  265. // Avoid using this method in controllers:
  266. // * slow
  267. // * prefer to get from a "named" source
  268. // This method is mainly useful for libraries that want to provide some flexibility
  269. public function get($key, $default = null)
  270. {
  271. return $this->query->get($key, $this->attributes->get($key, $this->request->get($key, $default)));
  272. }
  273. public function getSession()
  274. {
  275. return $this->session;
  276. }
  277. public function hasSession()
  278. {
  279. return $this->cookies->has(session_name());
  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->server->get('HTTPS') == 'on') ? '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('=', urldecode($segment), 2);
  446. $parts[] = urlencode($tmp[0]).'='.urlencode($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. $elements = explode(':', $host);
  482. return trim($elements[0]);
  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. * * null
  558. *
  559. * @return string The request format
  560. */
  561. public function getRequestFormat()
  562. {
  563. if (null === $this->format) {
  564. $this->format = $this->get('_format', 'html');
  565. }
  566. return $this->format;
  567. }
  568. public function setRequestFormat($format)
  569. {
  570. $this->format = $format;
  571. }
  572. public function isMethodSafe()
  573. {
  574. return in_array($this->getMethod(), array('GET', 'HEAD'));
  575. }
  576. /**
  577. * Returns the request body content.
  578. *
  579. * @param Boolean $asResource If true, a resource will be returned
  580. *
  581. * @return string|resource The request body content or a resource to read the body stream.
  582. */
  583. public function getContent($asResource = false)
  584. {
  585. if (false === $this->content || (true === $asResource && null !== $this->content)) {
  586. throw new \LogicException('getContent() can only be called once when using the resource return type.');
  587. }
  588. if (true === $asResource) {
  589. $this->content = false;
  590. return fopen('php://input', 'rb');
  591. }
  592. if (null === $this->content) {
  593. $this->content = file_get_contents('php://input');
  594. }
  595. return $this->content;
  596. }
  597. public function getETags()
  598. {
  599. return preg_split('/\s*,\s*/', $this->headers->get('if_none_match'), null, PREG_SPLIT_NO_EMPTY);
  600. }
  601. public function isNoCache()
  602. {
  603. return $this->headers->hasCacheControlDirective('no-cache') || 'no-cache' == $this->headers->get('Pragma');
  604. }
  605. /**
  606. * Returns the preferred language.
  607. *
  608. * @param array $locales An array of ordered available locales
  609. *
  610. * @return string The preferred locale
  611. */
  612. public function getPreferredLanguage(array $locales = null)
  613. {
  614. $preferredLanguages = $this->getLanguages();
  615. if (null === $locales) {
  616. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : null;
  617. }
  618. if (!$preferredLanguages) {
  619. return $locales[0];
  620. }
  621. $preferredLanguages = array_values(array_intersect($preferredLanguages, $locales));
  622. return isset($preferredLanguages[0]) ? $preferredLanguages[0] : $locales[0];
  623. }
  624. /**
  625. * Gets a list of languages acceptable by the client browser.
  626. *
  627. * @return array Languages ordered in the user browser preferences
  628. */
  629. public function getLanguages()
  630. {
  631. if (null !== $this->languages) {
  632. return $this->languages;
  633. }
  634. $languages = $this->splitHttpAcceptHeader($this->headers->get('Accept-Language'));
  635. $this->languages = array();
  636. foreach ($languages as $lang) {
  637. if (strstr($lang, '-')) {
  638. $codes = explode('-', $lang);
  639. if ($codes[0] == 'i') {
  640. // Language not listed in ISO 639 that are not variants
  641. // of any listed language, which can be registered with the
  642. // i-prefix, such as i-cherokee
  643. if (count($codes) > 1) {
  644. $lang = $codes[1];
  645. }
  646. } else {
  647. for ($i = 0, $max = count($codes); $i < $max; $i++) {
  648. if ($i == 0) {
  649. $lang = strtolower($codes[0]);
  650. } else {
  651. $lang .= '_'.strtoupper($codes[$i]);
  652. }
  653. }
  654. }
  655. }
  656. $this->languages[] = $lang;
  657. }
  658. return $this->languages;
  659. }
  660. /**
  661. * Gets a list of charsets acceptable by the client browser.
  662. *
  663. * @return array List of charsets in preferable order
  664. */
  665. public function getCharsets()
  666. {
  667. if (null !== $this->charsets) {
  668. return $this->charsets;
  669. }
  670. return $this->charsets = $this->splitHttpAcceptHeader($this->headers->get('Accept-Charset'));
  671. }
  672. /**
  673. * Gets a list of content types acceptable by the client browser
  674. *
  675. * @return array Languages ordered in the user browser preferences
  676. */
  677. public function getAcceptableContentTypes()
  678. {
  679. if (null !== $this->acceptableContentTypes) {
  680. return $this->acceptableContentTypes;
  681. }
  682. return $this->acceptableContentTypes = $this->splitHttpAcceptHeader($this->headers->get('Accept'));
  683. }
  684. /**
  685. * Returns true if the request is a XMLHttpRequest.
  686. *
  687. * It works if your JavaScript library set an X-Requested-With HTTP header.
  688. * It is known to work with Prototype, Mootools, jQuery.
  689. *
  690. * @return Boolean true if the request is an XMLHttpRequest, false otherwise
  691. */
  692. public function isXmlHttpRequest()
  693. {
  694. return 'XMLHttpRequest' == $this->headers->get('X-Requested-With');
  695. }
  696. /**
  697. * Splits an Accept-* HTTP header.
  698. *
  699. * @param string $header Header to split
  700. */
  701. public function splitHttpAcceptHeader($header)
  702. {
  703. if (!$header) {
  704. return array();
  705. }
  706. $values = array();
  707. foreach (array_filter(explode(',', $header)) as $value) {
  708. // Cut off any q-value that might come after a semi-colon
  709. if ($pos = strpos($value, ';')) {
  710. $q = (float) trim(substr($value, strpos($value, '=') + 1));
  711. $value = trim(substr($value, 0, $pos));
  712. } else {
  713. $q = 1;
  714. }
  715. if (0 < $q) {
  716. $values[trim($value)] = $q;
  717. }
  718. }
  719. arsort($values);
  720. return array_keys($values);
  721. }
  722. /*
  723. * The following methods are derived from code of the Zend Framework (1.10dev - 2010-01-24)
  724. *
  725. * Code subject to the new BSD license (http://framework.zend.com/license/new-bsd).
  726. *
  727. * Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  728. */
  729. protected function prepareRequestUri()
  730. {
  731. $requestUri = '';
  732. if ($this->headers->has('X_REWRITE_URL')) {
  733. // check this first so IIS will catch
  734. $requestUri = $this->headers->get('X_REWRITE_URL');
  735. } elseif ($this->server->get('IIS_WasUrlRewritten') == '1' && $this->server->get('UNENCODED_URL') != '') {
  736. // IIS7 with URL Rewrite: make sure we get the unencoded url (double slash problem)
  737. $requestUri = $this->server->get('UNENCODED_URL');
  738. } elseif ($this->server->has('REQUEST_URI')) {
  739. $requestUri = $this->server->get('REQUEST_URI');
  740. // HTTP proxy reqs setup request uri with scheme and host [and port] + the url path, only use url path
  741. $schemeAndHttpHost = $this->getScheme().'://'.$this->getHttpHost();
  742. if (strpos($requestUri, $schemeAndHttpHost) === 0) {
  743. $requestUri = substr($requestUri, strlen($schemeAndHttpHost));
  744. }
  745. } elseif ($this->server->has('ORIG_PATH_INFO')) {
  746. // IIS 5.0, PHP as CGI
  747. $requestUri = $this->server->get('ORIG_PATH_INFO');
  748. if ($this->server->get('QUERY_STRING')) {
  749. $requestUri .= '?'.$this->server->get('QUERY_STRING');
  750. }
  751. }
  752. return $requestUri;
  753. }
  754. protected function prepareBaseUrl()
  755. {
  756. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  757. if (basename($this->server->get('SCRIPT_NAME')) === $filename) {
  758. $baseUrl = $this->server->get('SCRIPT_NAME');
  759. } elseif (basename($this->server->get('PHP_SELF')) === $filename) {
  760. $baseUrl = $this->server->get('PHP_SELF');
  761. } elseif (basename($this->server->get('ORIG_SCRIPT_NAME')) === $filename) {
  762. $baseUrl = $this->server->get('ORIG_SCRIPT_NAME'); // 1and1 shared hosting compatibility
  763. } else {
  764. // Backtrack up the script_filename to find the portion matching
  765. // php_self
  766. $path = $this->server->get('PHP_SELF', '');
  767. $file = $this->server->get('SCRIPT_FILENAME', '');
  768. $segs = explode('/', trim($file, '/'));
  769. $segs = array_reverse($segs);
  770. $index = 0;
  771. $last = count($segs);
  772. $baseUrl = '';
  773. do {
  774. $seg = $segs[$index];
  775. $baseUrl = '/'.$seg.$baseUrl;
  776. ++$index;
  777. } while (($last > $index) && (false !== ($pos = strpos($path, $baseUrl))) && (0 != $pos));
  778. }
  779. // Does the baseUrl have anything in common with the request_uri?
  780. $requestUri = $this->getRequestUri();
  781. if ($baseUrl && 0 === strpos($requestUri, $baseUrl)) {
  782. // full $baseUrl matches
  783. return $baseUrl;
  784. }
  785. if ($baseUrl && 0 === strpos($requestUri, dirname($baseUrl))) {
  786. // directory portion of $baseUrl matches
  787. return rtrim(dirname($baseUrl), '/');
  788. }
  789. $truncatedRequestUri = $requestUri;
  790. if (($pos = strpos($requestUri, '?')) !== false) {
  791. $truncatedRequestUri = substr($requestUri, 0, $pos);
  792. }
  793. $basename = basename($baseUrl);
  794. if (empty($basename) || !strpos($truncatedRequestUri, $basename)) {
  795. // no match whatsoever; set it blank
  796. return '';
  797. }
  798. // If using mod_rewrite or ISAPI_Rewrite strip the script filename
  799. // out of baseUrl. $pos !== 0 makes sure it is not matching a value
  800. // from PATH_INFO or QUERY_STRING
  801. if ((strlen($requestUri) >= strlen($baseUrl)) && ((false !== ($pos = strpos($requestUri, $baseUrl))) && ($pos !== 0))) {
  802. $baseUrl = substr($requestUri, 0, $pos + strlen($baseUrl));
  803. }
  804. return rtrim($baseUrl, '/');
  805. }
  806. protected function prepareBasePath()
  807. {
  808. $filename = basename($this->server->get('SCRIPT_FILENAME'));
  809. $baseUrl = $this->getBaseUrl();
  810. if (empty($baseUrl)) {
  811. return '';
  812. }
  813. if (basename($baseUrl) === $filename) {
  814. $basePath = dirname($baseUrl);
  815. } else {
  816. $basePath = $baseUrl;
  817. }
  818. if ('\\' === DIRECTORY_SEPARATOR) {
  819. $basePath = str_replace('\\', '/', $basePath);
  820. }
  821. return rtrim($basePath, '/');
  822. }
  823. protected function preparePathInfo()
  824. {
  825. $baseUrl = $this->getBaseUrl();
  826. if (null === ($requestUri = $this->getRequestUri())) {
  827. return '';
  828. }
  829. $pathInfo = '';
  830. // Remove the query string from REQUEST_URI
  831. if ($pos = strpos($requestUri, '?')) {
  832. $requestUri = substr($requestUri, 0, $pos);
  833. }
  834. if ((null !== $baseUrl) && (false === ($pathInfo = substr($requestUri, strlen($baseUrl))))) {
  835. // If substr() returns false then PATH_INFO is set to an empty string
  836. return '';
  837. } elseif (null === $baseUrl) {
  838. return $requestUri;
  839. }
  840. return (string) $pathInfo;
  841. }
  842. static protected function initializeFormats()
  843. {
  844. static::$formats = array(
  845. 'txt' => array('text/plain'),
  846. 'js' => array('application/javascript', 'application/x-javascript', 'text/javascript'),
  847. 'css' => array('text/css'),
  848. 'json' => array('application/json', 'application/x-json'),
  849. 'xml' => array('text/xml', 'application/xml', 'application/x-xml'),
  850. 'rdf' => array('application/rdf+xml'),
  851. 'atom' => array('application/atom+xml'),
  852. );
  853. }
  854. }