Development

/branches/1.1/lib/request/sfWebRequest.class.php

You must first sign up to be able to contribute.

root/branches/1.1/lib/request/sfWebRequest.class.php

Revision 17975, 30.7 kB (checked in by fabien, 6 years ago)

[1.1, 1.2, 1.3] fixed sfWebRequest::getFiles() (closes #6389)

  • Property svn:mime-type set to text/x-php
  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Rev Date
Line 
1 <?php
2
3 /*
4  * This file is part of the symfony package.
5  * (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
6  * (c) 2004-2006 Sean Kerr <sean@code-box.org>
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 /**
13  * sfWebRequest class.
14  *
15  * This class manages web requests. It parses input from the request and store them as parameters.
16  *
17  * @package    symfony
18  * @subpackage request
19  * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
20  * @author     Sean Kerr <sean@code-box.org>
21  * @version    SVN: $Id$
22  */
23 class sfWebRequest extends sfRequest
24 {
25   protected
26     $languages              = null,
27     $charsets               = null,
28     $acceptableContentTypes = null,
29     $pathInfoArray          = null,
30     $relativeUrlRoot        = null,
31     $getParameters          = null,
32     $postParameters         = null,
33     $requestParameters      = null,
34     $formats                = array(),
35     $format                 = null,
36     $fixedFileArray         = false;
37
38   /**
39    * Initializes this sfRequest.
40    *
41    * @param  sfEventDispatcher $dispatcher  An sfEventDispatcher instance
42    * @param  array             $parameters  An associative array of initialization parameters
43    * @param  array             $attributes  An associative array of initialization attributes
44    *
45    * @return bool true, if initialization completes successfully, otherwise false
46    *
47    * @throws <b>sfInitializationException</b> If an error occurs while initializing this sfRequest
48    */
49   public function initialize(sfEventDispatcher $dispatcher, $parameters = array(), $attributes = array())
50   {
51     parent::initialize($dispatcher, $parameters, $attributes);
52
53     if (isset($_SERVER['REQUEST_METHOD']))
54     {
55       switch ($_SERVER['REQUEST_METHOD'])
56       {
57         case 'GET':
58           $this->setMethod(self::GET);
59           break;
60
61         case 'POST':
62           $this->setMethod(self::POST);
63           break;
64
65         case 'PUT':
66           $this->setMethod(self::PUT);
67           break;
68
69         case 'DELETE':
70           $this->setMethod(self::DELETE);
71           break;
72
73         case 'HEAD':
74           $this->setMethod(self::HEAD);
75           break;
76
77         default:
78           $this->setMethod(self::GET);
79       }
80     }
81     else
82     {
83       // set the default method
84       $this->setMethod(self::GET);
85     }
86
87     foreach ($this->getAttribute('formats', array()) as $format => $mimeTypes)
88     {
89       $this->setFormat($format, $mimeTypes);
90     }
91
92     // load parameters from GET/PATH_INFO/POST
93     $this->loadParameters();
94   }
95
96   /**
97    * Retrieves an array of file information.
98    *
99    * @param  string $name  A file name
100    *
101    * @return array An associative array of file information, if the file exists, otherwise null
102    */
103   public function getFile($name)
104   {
105     if (!sfConfig::get('sf_compat_10'))
106     {
107       throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
108     }
109
110     return $this->hasFile($name) ? $this->getFileValues($name) : null;
111   }
112
113   /**
114    * Retrieves a file error.
115    *
116    * @param  string $name  A file name
117    *
118    * @return int One of the following error codes:
119    *
120    *             - <b>UPLOAD_ERR_OK</b>        (no error)
121    *             - <b>UPLOAD_ERR_INI_SIZE</b>  (the uploaded file exceeds the
122    *                                           upload_max_filesize directive
123    *                                           in php.ini)
124    *             - <b>UPLOAD_ERR_FORM_SIZE</b> (the uploaded file exceeds the
125    *                                           MAX_FILE_SIZE directive that
126    *                                           was specified in the HTML form)
127    *             - <b>UPLOAD_ERR_PARTIAL</b>   (the uploaded file was only
128    *                                           partially uploaded)
129    *             - <b>UPLOAD_ERR_NO_FILE</b>   (no file was uploaded)
130    */
131   public function getFileError($name)
132   {
133     if (!sfConfig::get('sf_compat_10'))
134     {
135       throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
136     }
137
138     return $this->hasFile($name) ? $this->getFileValue($name, 'error') : UPLOAD_ERR_NO_FILE;
139   }
140
141   /**
142    * Retrieves a file name.
143    *
144    * @param  string $name  A file nam.
145    *
146    * @return string A file name, if the file exists, otherwise null
147    */
148   public function getFileName($name)
149   {
150     if (!sfConfig::get('sf_compat_10'))
151     {
152       throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
153     }
154
155     return $this->hasFile($name) ? $this->getFileValue($name, 'name') : null;
156   }
157
158   /**
159    * Retrieves an array of file names.
160    *
161    * @return array An indexed array of file names
162    */
163   public function getFileNames()
164   {
165     if (!sfConfig::get('sf_compat_10'))
166     {
167       throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
168     }
169
170     return array_keys($_FILES);
171   }
172
173   /**
174    * Retrieves an array of files.
175    *
176    * @param  string $key  A key
177    * @return array  An associative array of files
178    */
179   public function getFiles($key = null)
180   {
181     if (false === $this->fixedFileArray)
182     {
183       $this->fixedFileArray = self::convertFileInformation($_FILES);
184     }
185
186     return is_null($key) ? $this->fixedFileArray : (isset($this->fixedFileArray[$key]) ? $this->fixedFileArray[$key] : array());
187   }
188
189   /**
190    * Converts uploaded file array to a format following the $_GET and $POST naming convention.
191    *
192    * It's safe to pass an already converted array, in which case this method just returns the original array unmodified.
193    *
194    * @param  array $taintedFiles An array representing uploaded file information
195    *
196    * @return array An array of re-ordered uploaded file information
197    */
198   static public function convertFileInformation(array $taintedFiles)
199   {
200     $files = array();
201     foreach ($taintedFiles as $key => $data)
202     {
203       $files[$key] = self::fixPhpFilesArray($data);
204     }
205
206     return $files;
207   }
208
209   static protected function fixPhpFilesArray($data)
210   {
211     $fileKeys = array('error', 'name', 'size', 'tmp_name', 'type');
212     $keys = array_keys($data);
213     sort($keys);
214
215     if ($fileKeys != $keys || !isset($data['name']) || !is_array($data['name']))
216     {
217       return $data;
218     }
219
220     $files = $data;
221     foreach ($fileKeys as $k)
222     {
223       unset($files[$k]);
224     }
225     foreach (array_keys($data['name']) as $key)
226     {
227       $files[$key] = self::fixPhpFilesArray(array(
228         'error'    => $data['error'][$key],
229         'name'     => $data['name'][$key],
230         'type'     => $data['type'][$key],
231         'tmp_name' => $data['tmp_name'][$key],
232         'size'     => $data['size'][$key],
233       ));
234     }
235
236     return $files;
237   }
238
239   /**
240    * Retrieves a file path.
241    *
242    * @param  string $name  A file name
243    *
244    * @return string A file path, if the file exists, otherwise null
245    */
246   public function getFilePath($name)
247   {
248     if (!sfConfig::get('sf_compat_10'))
249     {
250       throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
251     }
252
253     return $this->hasFile($name) ? $this->getFileValue($name, 'tmp_name') : null;
254   }
255
256   /**
257    * Retrieve a file size.
258    *
259    * @param  string $name  A file name
260    *
261    * @return int A file size, if the file exists, otherwise null
262    */
263   public function getFileSize($name)
264   {
265     if (!sfConfig::get('sf_compat_10'))
266     {
267       throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
268     }
269
270     return $this->hasFile($name) ? $this->getFileValue($name, 'size') : null;
271   }
272
273   /**
274    * Retrieves a file type.
275    *
276    * This may not be accurate. This is the mime-type sent by the browser
277    * during the upload.
278    *
279    * @param  string $name  A file name
280    *
281    * @return string A file type, if the file exists, otherwise null
282    */
283   public function getFileType($name)
284   {
285     if (!sfConfig::get('sf_compat_10'))
286     {
287       throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
288     }
289
290     return $this->hasFile($name) ? $this->getFileValue($name, 'type') : null;
291   }
292
293   /**
294    * Indicates whether or not a file exists.
295    *
296    * @param  string $name  A file name
297    *
298    * @return bool true, if the file exists, otherwise false
299    */
300   public function hasFile($name)
301   {
302     if (!sfConfig::get('sf_compat_10'))
303     {
304       throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
305     }
306
307     if (preg_match('/^(.+?)\[(.+?)\]$/', $name, $match))
308     {
309       return isset($_FILES[$match[1]]['name'][$match[2]]);
310     }
311     else
312     {
313       return isset($_FILES[$name]);
314     }
315   }
316
317   /**
318    * Indicates whether or not a file error exists.
319    *
320    * @param  string $name  A file name
321    *
322    * @return bool true, if the file error exists, otherwise false
323    */
324   public function hasFileError($name)
325   {
326     if (!sfConfig::get('sf_compat_10'))
327     {
328       throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
329     }
330
331     return $this->hasFile($name) ? ($this->getFileValue($name, 'error') != UPLOAD_ERR_OK) : false;
332   }
333
334   /**
335    * Indicates whether or not any file errors occured.
336    *
337    * @return bool true, if any file errors occured, otherwise false
338    */
339   public function hasFileErrors()
340   {
341     if (!sfConfig::get('sf_compat_10'))
342     {
343       throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
344     }
345
346     foreach ($this->getFileNames() as $name)
347     {
348       if ($this->hasFileError($name) === true)
349       {
350         return true;
351       }
352     }
353
354     return false;
355   }
356
357   /**
358    * Indicates whether or not any files exist.
359    *
360    * @return boolean true, if any files exist, otherwise false
361    */
362   public function hasFiles()
363   {
364     if (!sfConfig::get('sf_compat_10'))
365     {
366       throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
367     }
368
369     return (count($_FILES) > 0);
370   }
371
372   /**
373    * Retrieves a file value.
374    *
375    * @param string $name A file name
376    * @param string $key Value to search in the file
377    *
378    * @return string File value
379    */
380   public function getFileValue($name, $key)
381   {
382     if (!sfConfig::get('sf_compat_10'))
383     {
384       throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
385     }
386
387     if (preg_match('/^(.+?)\[(.+?)\]$/', $name, $match))
388     {
389       return $_FILES[$match[1]][$key][$match[2]];
390     }
391     else
392     {
393       return $_FILES[$name][$key];
394     }
395   }
396
397   /**
398    * Retrieves all the values from a file.
399    *
400    * @param  string $name  A file name
401    *
402    * @return array Associative list of the file values
403    */
404   public function getFileValues($name)
405   {
406     if (!sfConfig::get('sf_compat_10'))
407     {
408       throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
409     }
410
411     if (preg_match('/^(.+?)\[(.+?)\]$/', $name, $match))
412     {
413       return array(
414         'name'     => $_FILES[$match[1]]['name'][$match[2]],
415         'type'     => $_FILES[$match[1]]['type'][$match[2]],
416         'tmp_name' => $_FILES[$match[1]]['tmp_name'][$match[2]],
417         'error'    => $_FILES[$match[1]]['error'][$match[2]],
418         'size'     => $_FILES[$match[1]]['size'][$match[2]],
419       );
420     }
421     else
422     {
423       return $_FILES[$name];
424     }
425   }
426
427   /**
428    * Retrieves an extension for a given file.
429    *
430    * @param  string $name  A file name
431    *
432    * @return string Extension for the file
433    */
434   public function getFileExtension($name)
435   {
436     if (!sfConfig::get('sf_compat_10'))
437     {
438       throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
439     }
440
441     static $mimeTypes = null;
442
443     $fileType = $this->getFileType($name);
444
445     if (!$fileType)
446     {
447       return '.bin';
448     }
449
450     if (is_null($mimeTypes))
451     {
452       $mimeTypes = unserialize(file_get_contents(sfConfig::get('sf_symfony_lib_dir').'/plugins/sfCompat10Plugin/data/mime_types.dat'));
453     }
454
455     return isset($mimeTypes[$fileType]) ? '.'.$mimeTypes[$fileType] : '.bin';
456   }
457
458   /**
459    * Retrieves the uniform resource identifier for the current web request.
460    *
461    * @return string Unified resource identifier
462    */
463   public function getUri()
464   {
465     $pathArray = $this->getPathInfoArray();
466
467     // for IIS with rewrite module (IIFR, ISAPI Rewrite, ...)
468     if ('HTTP_X_REWRITE_URL' == sfConfig::get('sf_path_info_key'))
469     {
470       $uri = isset($pathArray['HTTP_X_REWRITE_URL']) ? $pathArray['HTTP_X_REWRITE_URL'] : '';
471     }
472     else
473     {
474       $uri = isset($pathArray['REQUEST_URI']) ? $pathArray['REQUEST_URI'] : '';
475     }
476
477     return $this->isAbsUri() ? $uri : $this->getUriPrefix().$uri;
478   }
479
480   /**
481    * See if the client is using absolute uri
482    *
483    * @return boolean true, if is absolute uri otherwise false
484    */
485   public function isAbsUri()
486   {
487     $pathArray = $this->getPathInfoArray();
488
489     return preg_match('/^http/', $pathArray['REQUEST_URI']);
490   }
491
492   /**
493    * Returns Uri prefix, including protocol, hostname and server port.
494    *
495    * @return string Uniform resource identifier prefix
496    */
497   public function getUriPrefix()
498   {
499     $pathArray = $this->getPathInfoArray();
500     if ($this->isSecure())
501     {
502       $standardPort = '443';
503       $protocol = 'https';
504     }
505     else
506     {
507       $standardPort = '80';
508       $protocol = 'http';
509     }
510
511     $host = explode(":", $this->getHost());
512     if (count($host) == 1)
513     {
514       $host[] = isset($pathArray['SERVER_PORT']) ? $pathArray['SERVER_PORT'] : '';
515     }
516
517     if ($host[1] == $standardPort || empty($host[1]))
518     {
519       unset($host[1]);
520     }
521
522     return $protocol.'://'.implode(':', $host);;
523   }
524
525   /**
526    * Retrieves the path info for the current web request.
527    *
528    * @return string Path info
529    */
530   public function getPathInfo()
531   {
532     $pathInfo = '';
533
534     $pathArray = $this->getPathInfoArray();
535
536     // simulate PATH_INFO if needed
537     $sf_path_info_key = sfConfig::get('sf_path_info_key', 'PATH_INFO');
538     if (!isset($pathArray[$sf_path_info_key]) || !$pathArray[$sf_path_info_key])
539     {
540       if (isset($pathArray['REQUEST_URI']))
541       {
542         $script_name = $this->getScriptName();
543         $uri_prefix = $this->isAbsUri() ? $this->getUriPrefix() : '';
544         $pathInfo = preg_replace('/^'.preg_quote($uri_prefix, '/').'/','',$pathArray['REQUEST_URI']);
545         $pathInfo = preg_replace('/^'.preg_quote($script_name, '/').'/', '', $pathInfo);
546         $prefix_name = preg_replace('#/[^/]+$#', '', $script_name);
547         $pathInfo = preg_replace('/^'.preg_quote($prefix_name, '/').'/', '', $pathInfo);
548         $pathInfo = preg_replace('/\??'.preg_quote($pathArray['QUERY_STRING'], '/').'$/', '', $pathInfo);
549       }
550     }
551     else
552     {
553       $pathInfo = $pathArray[$sf_path_info_key];
554       if ($sf_relative_url_root = $this->getRelativeUrlRoot())
555       {
556         $pathInfo = preg_replace('/^'.str_replace('/', '\\/', $sf_relative_url_root).'\//', '', $pathInfo);
557       }
558     }
559
560     // for IIS
561     if (isset($_SERVER['SERVER_SOFTWARE']) && false !== stripos($_SERVER['SERVER_SOFTWARE'], 'iis') && $pos = stripos($pathInfo, '.php'))
562     {
563       $pathInfo = substr($pathInfo, $pos + 4);
564     }
565
566     if (!$pathInfo)
567     {
568       $pathInfo = '/';
569     }
570
571     return $pathInfo;
572   }
573
574   public function getGetParameters()
575   {
576     return $this->getParameters;
577   }
578
579   public function getPostParameters()
580   {
581     return $this->postParameters;
582   }
583
584   public function getRequestParameters()
585   {
586     return $this->requestParameters;
587   }
588
589   /**
590    * Moves an uploaded file.
591    *
592    * @param string $name      A file name
593    * @param string $file      An absolute filesystem path to where you would like the
594    *                          file moved. This includes the new filename as well, since
595    *                          uploaded files are stored with random names
596    * @param int    $fileMode  The octal mode to use for the new file
597    * @param bool   $create    Indicates that we should make the directory before moving the file
598    * @param int    $dirMode   The octal mode to use when creating the directory
599    *
600    * @return bool true, if the file was moved, otherwise false
601    *
602    * @throws <b>sfFileException</b> If a major error occurs while attempting to move the file
603    */
604   public function moveFile($name, $file, $fileMode = 0666, $create = true, $dirMode = 0777)
605   {
606     if (!sfConfig::get('sf_compat_10'))
607     {
608       throw new sfConfigurationException('You must set "compat_10" to true if you want to use this method which is deprecated.');
609     }
610
611     if ($this->hasFile($name) && $this->getFileValue($name, 'error') == UPLOAD_ERR_OK && $this->getFileValue($name, 'size') > 0)
612     {
613       // get our directory path from the destination filename
614       $directory = dirname($file);
615
616       if (!is_readable($directory))
617       {
618         $fmode = 0777;
619
620         if ($create && !@mkdir($directory, $dirMode, true))
621         {
622           // failed to create the directory
623           throw new sfFileException(sprintf('Failed to create file upload directory "%s".', $directory));
624         }
625
626         // chmod the directory since it doesn't seem to work on
627         // recursive paths
628         @chmod($directory, $dirMode);
629       }
630       else if (!is_dir($directory))
631       {
632         // the directory path exists but it's not a directory
633         throw new sfFileException(sprintf('File upload path "%s" exists, but is not a directory.', $directory));
634       }
635       else if (!is_writable($directory))
636       {
637         // the directory isn't writable
638         throw new sfFileException(sprintf('File upload path "%s" is not writable.', $directory));
639       }
640
641       if (@move_uploaded_file($this->getFileValue($name, 'tmp_name'), $file))
642       {
643         // chmod our file
644         @chmod($file, $fileMode);
645
646         return true;
647       }
648     }
649
650     return false;
651   }
652
653   /**
654    * Returns referer.
655    *
656    * @return string
657    */
658   public function getReferer()
659   {
660     $pathArray = $this->getPathInfoArray();
661
662     return isset($pathArray['HTTP_REFERER']) ? $pathArray['HTTP_REFERER'] : '';
663   }
664
665   /**
666    * Returns current host name.
667    *
668    * @return string
669    */
670   public function getHost()
671   {
672     $pathArray = $this->getPathInfoArray();
673
674     return isset($pathArray['HTTP_X_FORWARDED_HOST']) ? $pathArray['HTTP_X_FORWARDED_HOST'] : (isset($pathArray['HTTP_HOST']) ? $pathArray['HTTP_HOST'] : '');
675   }
676
677   /**
678    * Returns current script name.
679    *
680    * @return string
681    */
682   public function getScriptName()
683   {
684     $pathArray = $this->getPathInfoArray();
685
686     return isset($pathArray['SCRIPT_NAME']) ? $pathArray['SCRIPT_NAME'] : (isset($pathArray['ORIG_SCRIPT_NAME']) ? $pathArray['ORIG_SCRIPT_NAME'] : '');
687   }
688
689   /**
690    * Checks if the request method is the given one.
691    *
692    * @param  string $method  The method name
693    *
694    * @return bool true if the current method is the given one, false otherwise
695    */
696   public function isMethod($method)
697   {
698     $pathArray = $this->getPathInfoArray();
699
700     return strtolower($method) == strtolower($this->getMethodName());
701   }
702
703   /**
704    * Returns request method.
705    *
706    * @return string
707    */
708   public function getMethodName()
709   {
710     $pathArray = $this->getPathInfoArray();
711
712     return isset($pathArray['REQUEST_METHOD']) ? $pathArray['REQUEST_METHOD'] : 'GET';
713   }
714
715   /**
716    * Returns the preferred culture for the current request.
717    *
718    * @param  array  $cultures  An array of ordered cultures available
719    *
720    * @return string The preferred culture
721    */
722   public function getPreferredCulture(array $cultures = null)
723   {
724     $preferredCultures = $this->getLanguages();
725
726     if (is_null($cultures))
727     {
728       return isset($preferredCultures[0]) ? $preferredCultures[0] : null;
729     }
730
731     if (!$preferredCultures)
732     {
733       return $cultures[0];
734     }
735
736     $preferredCultures = array_values(array_intersect($preferredCultures, $cultures));
737
738     return isset($preferredCultures[0]) ? $preferredCultures[0] : $cultures[0];
739   }
740
741   /**
742    * Gets a list of languages acceptable by the client browser
743    *
744    * @return array Languages ordered in the user browser preferences
745    */
746   public function getLanguages()
747   {
748     if ($this->languages)
749     {
750       return $this->languages;
751     }
752
753     if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE']))
754     {
755       return array();
756     }
757
758     $languages = $this->splitHttpAcceptHeader($_SERVER['HTTP_ACCEPT_LANGUAGE']);
759     foreach ($languages as $lang)
760     {
761       if (strstr($lang, '-'))
762       {
763         $codes = explode('-', $lang);
764         if ($codes[0] == 'i')
765         {
766           // Language not listed in ISO 639 that are not variants
767           // of any listed language, which can be registerd with the
768           // i-prefix, such as i-cherokee
769           if (count($codes) > 1)
770           {
771             $lang = $codes[1];
772           }
773         }
774         else
775         {
776           for ($i = 0, $max = count($codes); $i < $max; $i++)
777           {
778             if ($i == 0)
779             {
780               $lang = strtolower($codes[0]);
781             }
782             else
783             {
784               $lang .= '_'.strtoupper($codes[$i]);
785             }
786           }
787         }
788       }
789
790       $this->languages[] = $lang;
791     }
792
793     return $this->languages;
794   }
795
796   /**
797    * Gets a list of charsets acceptable by the client browser.
798    *
799    * @return array List of charsets in preferable order
800    */
801   public function getCharsets()
802   {
803     if ($this->charsets)
804     {
805       return $this->charsets;
806     }
807
808     if (!isset($_SERVER['HTTP_ACCEPT_CHARSET']))
809     {
810       return array();
811     }
812
813     $this->charsets = $this->splitHttpAcceptHeader($_SERVER['HTTP_ACCEPT_CHARSET']);
814
815     return $this->charsets;
816   }
817
818   /**
819    * Gets a list of content types acceptable by the client browser
820    *
821    * @return array Languages ordered in the user browser preferences
822    */
823   public function getAcceptableContentTypes()
824   {
825     if ($this->acceptableContentTypes)
826     {
827       return $this->acceptableContentTypes;
828     }
829
830     if (!isset($_SERVER['HTTP_ACCEPT']))
831     {
832       return array();
833     }
834
835     $this->acceptableContentTypes = $this->splitHttpAcceptHeader($_SERVER['HTTP_ACCEPT']);
836
837     return $this->acceptableContentTypes;
838   }
839
840   /**
841    * Returns true if the request is a XMLHttpRequest.
842    *
843    * It works if your JavaScript library set an X-Requested-With HTTP header.
844    * Works with Prototype, Mootools, jQuery, and perhaps others.
845    *
846    * @return bool true if the request is an XMLHttpRequest, false otherwise
847    */
848   public function isXmlHttpRequest()
849   {
850     return ($this->getHttpHeader('X_REQUESTED_WITH') == 'XMLHttpRequest');
851   }
852
853   public function getHttpHeader($name, $prefix = 'http')
854   {
855     if ($prefix)
856     {
857       $prefix = strtoupper($prefix).'_';
858     }
859
860     $name = $prefix.strtoupper(strtr($name, '-', '_'));
861
862     $pathArray = $this->getPathInfoArray();
863
864     return isset($pathArray[$name]) ? sfToolkit::stripslashesDeep($pathArray[$name]) : null;
865   }
866
867   /**
868    * Gets a cookie value.
869    *
870    * @param  string $name          Cookie name
871    * @param  string $defaultValue  Default value returned when no cookie with given name is found
872    *
873    * @return mixed
874    */
875   public function getCookie($name, $defaultValue = null)
876   {
877     $retval = $defaultValue;
878
879     if (isset($_COOKIE[$name]))
880     {
881       $retval = get_magic_quotes_gpc() ? sfToolkit::stripslashesDeep($_COOKIE[$name]) : $_COOKIE[$name];
882     }
883
884     return $retval;
885   }
886
887   /**
888    * Returns true if the current request is secure (HTTPS protocol).
889    *
890    * @return boolean
891    */
892   public function isSecure()
893   {
894     $pathArray = $this->getPathInfoArray();
895
896     return (
897       (isset($pathArray['HTTPS']) && (strtolower($pathArray['HTTPS']) == 'on' || $pathArray['HTTPS'] == 1))
898       ||
899       (isset($pathArray['HTTP_SSL_HTTPS']) && (strtolower($pathArray['HTTP_SSL_HTTPS']) == 'on' || $pathArray['HTTP_SSL_HTTPS'] == 1))
900       ||
901       (isset($pathArray['HTTP_X_FORWARDED_PROTO']) && strtolower($pathArray['HTTP_X_FORWARDED_PROTO']) == 'https')
902     );
903   }
904
905   /**
906    * Retrieves relative root url.
907    *
908    * @return string URL
909    */
910   public function getRelativeUrlRoot()
911   {
912     if ($this->relativeUrlRoot === null)
913     {
914       $this->relativeUrlRoot = sfConfig::get('sf_relative_url_root', preg_replace('#/[^/]+\.php5?$#', '', $this->getScriptName()));
915     }
916
917     return $this->relativeUrlRoot;
918   }
919
920   /**
921    * Sets the relative root url for the current web request.
922    *
923    * @param string $value  Value for the url
924    */
925   public function setRelativeUrlRoot($value)
926   {
927     $this->relativeUrlRoot = $value;
928   }
929
930   /**
931    * Splits an HTTP header for the current web request.
932    *
933    * @param string $header  Header to split
934    */
935   public function splitHttpAcceptHeader($header)
936   {
937     $values = array();
938     foreach (array_filter(explode(',', $header)) as $value)
939     {
940       // Cut off any q-value that might come after a semi-colon
941       if ($pos = strpos($value, ';'))
942       {
943         $q     = (float) trim(substr($value, $pos + 3));
944         $value = trim(substr($value, 0, $pos));
945       }
946       else
947       {
948         $q = 1;
949       }
950
951       $values[$value] = $q;
952     }
953
954     arsort($values);
955
956     return array_keys($values);
957   }
958
959   /**
960    * Returns the array that contains all request information ($_SERVER or $_ENV).
961    *
962    * This information is stored in the [sf_path_info_array] constant.
963    *
964    * @return  array Path information
965    */
966   protected function getPathInfoArray()
967   {
968     if (!$this->pathInfoArray)
969     {
970       // parse PATH_INFO
971       switch (sfConfig::get('sf_path_info_array', 'SERVER'))
972       {
973         case 'SERVER':
974           $this->pathInfoArray =& $_SERVER;
975           break;
976
977         case 'ENV':
978         default:
979           $this->pathInfoArray =& $_ENV;
980       }
981     }
982
983     return $this->pathInfoArray;
984   }
985
986   /**
987    * Gets the mime type associated with the format.
988    *
989    * @param  string $format  The format
990    *
991    * @return string The associated mime type (null if not found)
992    */
993   public function getMimeType($format)
994   {
995     return isset($this->formats[$format]) ? $this->formats[$format][0] : null;
996   }
997
998   /**
999    * Gets the format associated with the mime type.
1000    *
1001    * @param  string $mimeType  The associated mime type
1002    *
1003    * @return string The format (null if not found)
1004    */
1005   public function getFormat($mimeType)
1006   {
1007     foreach ($this->formats as $format => $mimeTypes)
1008     {
1009       if (in_array($mimeType, $mimeTypes))
1010       {
1011         return $format;
1012       }
1013     }
1014
1015     return null;
1016   }
1017
1018   /**
1019    * Associates a format with mime types.
1020    *
1021    * @param string       $format     The format
1022    * @param string|array $mimeTypes  The associated mime types (the preferred one must be the first as it will be used as the content type)
1023    */
1024   public function setFormat($format, $mimeTypes)
1025   {
1026     $this->formats[$format] = is_array($mimeTypes) ? $mimeTypes : array($mimeTypes);
1027   }
1028
1029   /**
1030    * Sets the request format.
1031    *
1032    * @param string $format  The request format
1033    */
1034   public function setRequestFormat($format)
1035   {
1036     $this->format = $format;
1037   }
1038
1039   /**
1040    * Gets the request format.
1041    *
1042    * If no format is defined by the user, it defaults to the sf_format request parameter if available.
1043    *
1044    * @return string The request format
1045    */
1046   public function getRequestFormat()
1047   {
1048     if (is_null($this->format))
1049     {
1050       if ($this->getParameter('sf_format'))
1051       {
1052         $this->setRequestFormat($this->getParameter('sf_format'));
1053       }
1054       else
1055       {
1056         $acceptableContentTypes = $this->getAcceptableContentTypes();
1057
1058         // skip if no acceptable content types or browsers
1059         if (isset($acceptableContentTypes[0]) && ('text/xml' != $acceptableContentTypes[0] && 'application/xml' != $acceptableContentTypes[0]))
1060         {
1061           $this->setRequestFormat($this->getFormat($acceptableContentTypes[0]));
1062         }
1063       }
1064     }
1065
1066     return $this->format;
1067   }
1068
1069   /**
1070    * Returns the value of a GET parameter.
1071    *
1072    * @param  string $name     The GET parameter name
1073    * @param  string $default  The default value
1074    *
1075    * @return string The GET parameter value
1076    */
1077   public function getGetParameter($name, $default = null)
1078   {
1079     if (isset($this->getParameters[$name]))
1080     {
1081       return $this->getParameters[$name];
1082     }
1083     else
1084     {
1085       return sfToolkit::getArrayValueForPath($this->getParameters, $name, $default);
1086     }
1087   }
1088
1089   /**
1090    * Returns the value of a POST parameter.
1091    *
1092    * @param  string $name     The POST parameter name
1093    * @param  string $default  The default value
1094    *
1095    * @return string The POST parameter value
1096    */
1097   public function getPostParameter($name, $default = null)
1098   {
1099     if (isset($this->postParameters[$name]))
1100     {
1101       return $this->postParameters[$name];
1102     }
1103     else
1104     {
1105       return sfToolkit::getArrayValueForPath($this->postParameters, $name, $default);
1106     }
1107   }
1108
1109   /**
1110    * Returns the value of a parameter passed as a URL segment.
1111    *
1112    * @param  string $name     The parameter name
1113    * @param  string $default  The default value
1114    *
1115    * @return string The parameter value
1116    */
1117   public function getUrlParameter($name, $default = null)
1118   {
1119     if (isset($this->requestParameters[$name]))
1120     {
1121       return $this->requestParameters[$name];
1122     }
1123     else
1124     {
1125       return sfToolkit::getArrayValueForPath($this->requestParameters, $name, $default);
1126     }
1127   }
1128
1129   /**
1130    * Parses the request parameters.
1131    *
1132    * This method notifies the request.filter_parameters event.
1133    *
1134    * @return array An array of request parameters.
1135    */
1136   protected function parseRequestParameters()
1137   {
1138     return $this->dispatcher->filter(new sfEvent($this, 'request.filter_parameters', array('path_info' => $this->getPathInfo())), array())->getReturnValue();
1139   }
1140
1141   /**
1142    * Loads GET, PATH_INFO and POST data into the parameter list.
1143    *
1144    */
1145   protected function loadParameters()
1146   {
1147     // GET parameters
1148     $this->getParameters = get_magic_quotes_gpc() ? sfToolkit::stripslashesDeep($_GET) : $_GET;
1149     $this->parameterHolder->add($this->getParameters);
1150
1151     // additional parameters
1152     $this->requestParameters = $this->parseRequestParameters();
1153     $this->parameterHolder->add($this->requestParameters);
1154
1155     // POST parameters
1156     $this->postParameters = get_magic_quotes_gpc() ? sfToolkit::stripslashesDeep($_POST) : $_POST;
1157     $this->parameterHolder->add($this->postParameters);
1158
1159     // move symfony parameters to attributes (parameters prefixed with _sf_)
1160     foreach ($this->parameterHolder->getAll() as $key => $value)
1161     {
1162       if (0 === stripos($key, '_sf_'))
1163       {
1164         $this->parameterHolder->remove($key);
1165         $this->setAttribute($key, $value);
1166       }
1167     }
1168
1169     if (sfConfig::get('sf_logging_enabled'))
1170     {
1171       $this->dispatcher->notify(new sfEvent($this, 'application.log', array(sprintf('Request parameters %s', str_replace("\n", '', var_export($this->getParameterHolder()->getAll(), true))))));
1172     }
1173   }
1174 }
1175
Note: See TracBrowser for help on using the browser.