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