Source for file jRequest.class.php

Documentation is available at jRequest.class.php

  1. <?php
  2. /**
  3. * @package    jelix
  4. * @subpackage core
  5. * @author     Laurent Jouanneau
  6. * @contributor Yannick Le Guédart
  7. * @copyright  2005-2012 Laurent Jouanneau, 2010 Yannick Le Guédart
  8. * @link        http://www.jelix.org
  9. * @licence    GNU Lesser General Public Licence see LICENCE file or http://www.gnu.org/licenses/lgpl.html
  10. */
  11.  
  12.  
  13. /**
  14.  * base class for object which retrieve all parameters of an http request. The
  15.  * process depends on the type of request (ex: xmlrpc..)
  16.  *
  17.  * @package  jelix
  18.  * @subpackage core
  19.  */
  20. abstract class jRequest {
  21.  
  22.    /**
  23.     * request parameters
  24.     * could set from $_GET, $_POST, or from data processing of $HTTP_RAW_POST_DATA
  25.     * @var array 
  26.     */
  27.     public $params;
  28.  
  29.     /**
  30.      * the request type code
  31.      * @var string 
  32.      */
  33.     public $type;
  34.  
  35.     /**
  36.      * the type of the default response
  37.      * @var string 
  38.      */
  39.     public $defaultResponseType = '';
  40.  
  41.     /**
  42.      * the path of the entry point in the url
  43.      * if the url is /foo/index.php/bar, its value is /foo/
  44.      * @var string 
  45.      */
  46.     public $urlScriptPath;
  47.  
  48.     /**
  49.      * the name of the entry point
  50.      * if the url is /foo/index.php/bar, its value is index.php
  51.      * @var string 
  52.      */
  53.     public $urlScriptName;
  54.  
  55.     /**
  56.      * the path to the entry point in the url
  57.      * if the url is /foo/index.php/bar, its value is /foo/index.php
  58.      * @var string 
  59.      */
  60.     public $urlScript;
  61.  
  62.     /**
  63.      * the pathinfo part of the url
  64.      * if the url is /foo/index.php/bar, its value is /bar
  65.      * @var string 
  66.      */
  67.     public $urlPathInfo;
  68.  
  69.     function __construct(){  }
  70.  
  71.     /**
  72.      * initialize the request : analyse of http request etc..
  73.      */
  74.     public function init(){
  75.         $this->_initUrlData();
  76.         $this->_initParams();
  77.     }
  78.  
  79.     /**
  80.      * analyse the http request and sets the params property
  81.      */
  82.     abstract protected function _initParams();
  83.  
  84.     /**
  85.      * init the url* properties
  86.      */
  87.     protected function _initUrlData(){
  88.         global $gJConfig;
  89.  
  90.         $this->urlScript = $gJConfig->urlengine['urlScript'];
  91.         $this->urlScriptPath = $gJConfig->urlengine['urlScriptPath'];
  92.         $this->urlScriptName = $gJConfig->urlengine['urlScriptName'];
  93.  
  94.         $piiqp = $gJConfig->urlengine['pathInfoInQueryParameter'];
  95.         if ($piiqp) {
  96.             if (isset($_GET[$piiqp])) {
  97.                 $pathinfo = $_GET[$piiqp];
  98.                 unset($_GET[$piiqp]);
  99.             } else
  100.                 $pathinfo = '';
  101.         } else if(isset($_SERVER['PATH_INFO'])){
  102.             $pathinfo = $_SERVER['PATH_INFO'];
  103.         } else if(isset($_SERVER['ORIG_PATH_INFO'])){
  104.             $pathinfo = $_SERVER['ORIG_PATH_INFO'];
  105.         } else
  106.             $pathinfo = '';
  107.  
  108.         if($pathinfo == $this->urlScript) {
  109.             //when php is used as cgi and if there isn't pathinfo in the url
  110.             $pathinfo = '';
  111.         }
  112.  
  113.         if ($gJConfig->isWindows && $pathinfo && strpos($pathinfo, $this->urlScript) !== false){
  114.             //under IIS, we may get  /subdir/index.php/mypath/myaction as PATH_INFO, so we fix it
  115.             $pathinfo = substr ($pathinfo, strlen ($this->urlScript));
  116.         }
  117.  
  118.         $this->urlPathInfo = $pathinfo;
  119.     }
  120.  
  121.     /**
  122.     * Gets the value of a request parameter. If not defined, gets its default value.
  123.     * @param string  $name           the name of the request parameter
  124.     * @param mixed   $defaultValue   the default returned value if the parameter doesn't exists
  125.     * @param boolean $useDefaultIfEmpty true: says to return the default value if the parameter value is ""
  126.     * @return mixed the request parameter value
  127.     */
  128.     public function getParam($name, $defaultValue=null, $useDefaultIfEmpty=false){
  129.  
  130.         if(isset($this->params[$name])){
  131.             if($useDefaultIfEmpty && trim($this->params[$name]) == ''){
  132.                 return $defaultValue;
  133.             }else{
  134.                 return $this->params[$name];
  135.             }
  136.         }else{
  137.             return $defaultValue;
  138.         }
  139.     }
  140.  
  141.     /**
  142.      * @param string $respclass the name of a response class
  143.      */
  144.     public function isAllowedResponse($respclass){
  145.         return true;
  146.     }
  147.  
  148.     /**
  149.      * get a response object.
  150.      * @param string $name the name of the response type (ex: "html")
  151.      * @param boolean $useOriginal true:don't use the response object redefined by the application
  152.      * @return jResponse the response object
  153.      */
  154.     public function getResponse($type='', $useOriginal = false){
  155.         global $gJCoord, $gJConfig;
  156.         if($type == ''){
  157.             $type = $this->defaultResponseType;
  158.         }
  159.  
  160.         if($useOriginal){
  161.             if(!isset($gJConfig->_coreResponses[$type])){
  162.                 throw new jException('jelix~errors.ad.response.type.unknown',array($gJCoord->action->resource,$type,$gJCoord->action->getPath()));
  163.             }
  164.             $respclass = $gJConfig->_coreResponses[$type];
  165.             $path = $gJConfig->_coreResponses[$type.'.path'];
  166.         }else{
  167.             if(!isset($gJConfig->responses[$type])){
  168.                 throw new jException('jelix~errors.ad.response.type.unknown',array($gJCoord->action->resource,$type,$gJCoord->action->getPath()));
  169.             }
  170.             $respclass = $gJConfig->responses[$type];
  171.             $path = $gJConfig->responses[$type.'.path'];
  172.         }
  173.  
  174.         if(!$this->isAllowedResponse($respclass)){
  175.             throw new jException('jelix~errors.ad.response.type.notallowed',array($gJCoord->action->resource,$type,$gJCoord->action->getPath()));
  176.         }
  177.  
  178.         if(!class_exists($respclass,false))
  179.             require($path);
  180.  
  181.         $response = new $respclass();
  182.         $gJCoord->response = $response;
  183.  
  184.         return $response;
  185.     }
  186.  
  187.     /**
  188.      * return the ip address of the user
  189.      * @return string the ip
  190.      */
  191.     function getIP() {
  192.         if (isset ($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR']){
  193.             return $_SERVER['HTTP_X_FORWARDED_FOR'];
  194.         }else if (isset ($_SERVER['HTTP_CLIENT_IP']) && $_SERVER['HTTP_CLIENT_IP']){
  195.             return  $_SERVER['HTTP_CLIENT_IP'];
  196.         }else{
  197.             return $_SERVER['REMOTE_ADDR'];
  198.         }
  199.     }
  200.  
  201.     /**
  202.      * return the protocol
  203.      * @return string  http or https
  204.      * @since 1.2
  205.      */
  206.    function getProtocol() {
  207.       return (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] && $_SERVER['HTTPS'] != 'off' ? 'https://':'http://');
  208.    }
  209.  
  210.    /**
  211.     * return the application domain name
  212.     * @return string 
  213.     * @since 1.2.3
  214.     */
  215.    function getDomainName() {
  216.       global $gJConfig;
  217.       if ($gJConfig->domainName != '') {
  218.          return $gJConfig->domainName;
  219.       }
  220.       elseif (isset($_SERVER['SERVER_NAME'])) {
  221.          return $_SERVER['SERVER_NAME'];
  222.       }
  223.       elseif (isset($_SERVER['HTTP_HOST'])) {
  224.          if (($pos = strpos($_SERVER['HTTP_HOST'], ':')) !== false)
  225.             return substr($_SERVER['HTTP_HOST'],0, $pos);
  226.          return $_SERVER['HTTP_HOST'];
  227.       }
  228.       return '';
  229.    }
  230.  
  231.    /**
  232.     * return the server URI of the application (protocol + server name + port)
  233.     * @return string the serveur uri
  234.     * @since 1.2.4
  235.     */
  236.    function getServerURI($forceHttps = null) {
  237.       $isHttps = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] && $_SERVER['HTTPS'] != 'off');
  238.  
  239.       if ( ($forceHttps === null && $isHttps) || $forceHttps) {
  240.          $uri = 'https://';
  241.       }
  242.       else {
  243.          $uri = 'http://';
  244.       }
  245.  
  246.       $uri .= $this->getDomainName();
  247.       $uri .= $this->getPort($forceHttps);
  248.       return $uri;
  249.    }
  250.  
  251.    /**
  252.     * return the server port of the application
  253.     * @return string the ":port" or empty string
  254.     * @since 1.2.4
  255.     */
  256.    function getPort($forceHttps = null) {
  257.       $isHttps = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] && $_SERVER['HTTPS'] != 'off');
  258.  
  259.       if ($forceHttps === null)
  260.          $https = $isHttps;
  261.       else
  262.          $https = $forceHttps;
  263.  
  264.       global $gJConfig;
  265.       $forcePort = ($https ? $gJConfig->forceHTTPSPort : $gJConfig->forceHTTPPort);
  266.       if ($forcePort === true) {
  267.          return '';
  268.       }
  269.       else if ($forcePort) { // a number
  270.          $port = $forcePort;
  271.       }
  272.       else if($isHttps != $https || !isset($_SERVER['SERVER_PORT'])) {
  273.          // the asked protocol is different from the current protocol
  274.          // we use the standard port for the asked protocol
  275.          return '';
  276.       } else {
  277.          $port = $_SERVER['SERVER_PORT'];
  278.       }
  279.       if (($https && $port == '443' ) || (!$https && $port == '80' ))
  280.          return '';
  281.       return ':'.$port;
  282.    }
  283.  
  284.    /**
  285.     * call it when you want to read the content of the body of a request
  286.     * when the method is not GET or POST
  287.     * @return mixed    array of parameters or a single string when the content-type is unknown
  288.     * @since 1.2
  289.     */
  290.    public function readHttpBody() {
  291.       $input = file_get_contents("php://input");
  292.       $values = array();
  293.  
  294.       if (strpos($_SERVER["CONTENT_TYPE"], "application/x-www-url-encoded") == 0) {
  295.          parse_str($input, $values);
  296.          return $values;
  297.       }
  298.       else if (strpos($_SERVER["CONTENT_TYPE"], "multipart/form-data") == 0) {
  299.  
  300.          if (!preg_match("/boundary=([a-zA-Z0-9]+)/", $_SERVER["CONTENT_TYPE"], $m))
  301.             return $input;
  302.  
  303.          $parts = explode('--'.$m[1], $input);
  304.          foreach($parts as $part) {
  305.             if (trim($part) == '' || $part == '--')
  306.                continue;
  307.             list($header, $value) = explode("\r\n\r\n", $part);
  308.             if (preg_match('/content\-disposition\:(?: *)form\-data\;(?: *)name="([^"]+)"(\;(?: *)filename="([^"]+)")?/i', $header, $m)) {
  309.                if (isset($m[2]) && $m[3] != '')
  310.                   $return[$m[1]] = array( $m[3], $value);
  311.                else
  312.                   $return[$m[1]] = $value;
  313.             }
  314.          }
  315.          if (count($values))
  316.             return $values;
  317.          else
  318.             return $input;
  319.       }
  320.       else {
  321.          return $input;
  322.       }
  323.    }
  324.  
  325.    private $_headers = null;
  326.  
  327.    private function _generateHeaders() {
  328.       if (is_null($this->_headers)) {
  329.          if (function_exists('apache_response_headers')) {
  330.             $this->_headers = apache_request_headers();
  331.          }
  332.          else {
  333.             $this->_headers = array();
  334.  
  335.             foreach($_SERVER as $key => $value) {
  336.                if (substr($key,0,5) == "HTTP_") {
  337.                   $key = str_replace(" ", "-",
  338.                           ucwords(strtolower(str_replace('_', ' ', substr($key,5)))));
  339.                   $this->_headers[$key] = $value;
  340.                }
  341.             }
  342.          }
  343.       }
  344.    }
  345.  
  346.    public function header($name) {
  347.       $this->_generateHeaders();
  348.       if (isset($this->_headers[$name])) {
  349.          return $this->_headers[$name];
  350.       }
  351.       return null;
  352.    }
  353.  
  354.    public function headers() {
  355.       $this->_generateHeaders();
  356.       return $this->_headers;
  357.    }
  358.  
  359.  
  360. }

Documentation generated on Thu, 19 Sep 2013 00:06:28 +0200 by phpDocumentor 1.4.3