Net_URL2
[ class tree: Net_URL2 ] [ index: Net_URL2 ] [ all elements ]

Source for file URL2.php

Documentation is available at URL2.php

  1. <?php
  2. // +-----------------------------------------------------------------------+
  3. // | Copyright (c) 2002-2004, Richard Heyes                                |
  4. // | All rights reserved.                                                  |
  5. // |                                                                       |
  6. // | Redistribution and use in source and binary forms, with or without    |
  7. // | modification, are permitted provided that the following conditions    |
  8. // | are met:                                                              |
  9. // |                                                                       |
  10. // | o Redistributions of source code must retain the above copyright      |
  11. // |   notice, this list of conditions and the following disclaimer.       |
  12. // | o Redistributions in binary form must reproduce the above copyright   |
  13. // |   notice, this list of conditions and the following disclaimer in the |
  14. // |   documentation and/or other materials provided with the distribution.|
  15. // | o The names of the authors may not be used to endorse or promote      |
  16. // |   products derived from this software without specific prior written  |
  17. // |   permission.                                                         |
  18. // |                                                                       |
  19. // | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS   |
  20. // | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT     |
  21. // | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
  22. // | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT  |
  23. // | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
  24. // | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT      |
  25. // | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
  26. // | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
  27. // | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT   |
  28. // | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
  29. // | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.  |
  30. // |                                                                       |
  31. // +-----------------------------------------------------------------------+
  32. // | Author: Richard Heyes <richard at php net>                            |
  33. // +-----------------------------------------------------------------------+
  34. //
  35. // $Id: URL2.php,v 1.2 2007/05/08 00:08:13 davidc Exp $
  36. //
  37. // Net_URL2 Class (PHP5 Only)
  38.  
  39. class Net_URL2
  40. {
  41.     /**
  42.      * Options
  43.      *
  44.      * This is the options available for the neturl
  45.      * options.
  46.      *
  47.      * @var array $options  The options of Net_URL2
  48.      */
  49.     public static $options = array(
  50.         'encode_query_keys' => false,
  51.     );
  52.  
  53.     /**
  54.     * Full url
  55.     * @var string 
  56.     */
  57.     public $url;
  58.  
  59.     /**
  60.     * Protocol
  61.     * @var string 
  62.     */
  63.     public $protocol;
  64.  
  65.     /**
  66.     * Username
  67.     * @var string 
  68.     */
  69.     public $user;
  70.  
  71.     /**
  72.     * Password
  73.     * @var string 
  74.     */
  75.     public $pass;
  76.  
  77.     /**
  78.     * Host
  79.     * @var string 
  80.     */
  81.     public $host;
  82.  
  83.     /**
  84.     * Port
  85.     * @var integer 
  86.     */
  87.     public $port;
  88.  
  89.     /**
  90.     * Path
  91.     * @var string 
  92.     */
  93.     public $path;
  94.  
  95.     /**
  96.     * Query string
  97.     * @var array 
  98.     */
  99.     public $querystring;
  100.  
  101.     /**
  102.     * Anchor
  103.     * @var string 
  104.     */
  105.     public $anchor;
  106.  
  107.     /**
  108.     * Whether to use [] in querystrings
  109.     * @var boolean 
  110.     */
  111.     public $useBrackets;
  112.  
  113.     /**
  114.     * Constructor
  115.     *
  116.     * Parses the given url and stores the various parts
  117.     * Defaults are used in certain cases
  118.     *
  119.     * @param string $url         Optional URL
  120.     * @param bool   $useBrackets Whether to use square brackets when
  121.     *                             multiple querystrings with the same name
  122.     *                             exist
  123.     */
  124.     public function __construct($url = null$useBrackets = true)
  125.     {
  126.         $this->useBrackets $useBrackets;
  127.         $this->url         $url;
  128.         $this->user        '';
  129.         $this->pass        '';
  130.         $this->host        '';
  131.         $this->port        = 80;
  132.         $this->path        '';
  133.         $this->querystring = array();
  134.         $this->anchor      '';
  135.  
  136.         // Only use defaults if not an absolute URL given
  137.         if (!preg_match('/^[a-z0-9]+:\/\//i'$url)) {
  138.  
  139.             $this->protocol (!empty($_SERVER['HTTPS']&& $_SERVER['HTTPS'== 'on' 'https' 'http');
  140.  
  141.             /**
  142.             * Figure out host/port
  143.             */
  144.             if (!empty($_SERVER['HTTP_HOST']AND preg_match('/^(.*)(:([0-9]+))?$/U'$_SERVER['HTTP_HOST']$matches)) {
  145.                 $host $matches[1];
  146.                 if (!empty($matches[3])) {
  147.                     $port $matches[3];
  148.                 else {
  149.                     $port $this->getStandardPort($this->protocol);
  150.                 }
  151.             }
  152.  
  153.             $this->user        '';
  154.             $this->pass        '';
  155.             $this->host        !empty($host$host (isset($_SERVER['SERVER_NAME']$_SERVER['SERVER_NAME''localhost');
  156.             $this->port        !empty($port$port (isset($_SERVER['SERVER_PORT']$_SERVER['SERVER_PORT'$this->getStandardPort($this->protocol));
  157.             $this->path        !empty($_SERVER['PHP_SELF']$_SERVER['PHP_SELF''/';
  158.             $this->querystring = isset($_SERVER['QUERY_STRING']$this->_parseRawQuerystring($_SERVER['QUERY_STRING']: null;
  159.             $this->anchor      '';
  160.         }
  161.  
  162.         // Parse the url and store the various parts
  163.         if (!empty($url)) {
  164.             $urlinfo parse_url($url);
  165.  
  166.             // Default querystring
  167.             $this->querystring = array();
  168.  
  169.             foreach ($urlinfo as $key => $value{
  170.                 switch ($key{
  171.                     case 'scheme':
  172.                         $this->protocol $value;
  173.                         $this->port     $this->getStandardPort($value);
  174.                         break;
  175.  
  176.                     case 'user':
  177.                     case 'pass':
  178.                     case 'host':
  179.                     case 'port':
  180.                         $this->$key $value;
  181.                         break;
  182.  
  183.                     case 'path':
  184.                         if ($value{0== '/'{
  185.                             $this->path $value;
  186.                         else {
  187.                             $path dirname($this->path== DIRECTORY_SEPARATOR ? '' dirname($this->path);
  188.                             $this->path sprintf('%s/%s'$path$value);
  189.                         }
  190.                         break;
  191.  
  192.                     case 'query':
  193.                         $this->querystring $this->_parseRawQueryString($value);
  194.                         break;
  195.  
  196.                     case 'fragment':
  197.                         $this->anchor $value;
  198.                         break;
  199.                 }
  200.             }
  201.         }
  202.     }
  203.  
  204.     /**
  205.     * Returns full url
  206.     *
  207.     * @return string Full url
  208.     */
  209.     public function getURL()
  210.     {
  211.         $querystring $this->getQueryString();
  212.  
  213.         $this->url $this->protocol '://'
  214.                    . $this->user (!empty($this->pass':' '')
  215.                    . $this->pass (!empty($this->user'@' '')
  216.                    . $this->host ($this->port == $this->getStandardPort($this->protocol'' ':' $this->port)
  217.                    . $this->path
  218.                    . (!empty($querystring'?' $querystring '')
  219.                    . (!empty($this->anchor'#' $this->anchor '');
  220.  
  221.         return $this->url;
  222.     }
  223.  
  224.     /**
  225.     * Adds a querystring item
  226.     *
  227.     * @param  string $name       Name of item
  228.     * @param  string $value      Value of item
  229.     * @param  bool   $preencoded Whether value is rawurlencoded or not, default = not
  230.     */
  231.     public function addQueryString($name$value$preencoded = false)
  232.     {
  233.         if ($this->getOption('encode_query_keys')) {
  234.             $name rawurlencode($name);
  235.         }
  236.  
  237.  
  238.         if ($preencoded{
  239.             $this->querystring[$name$value;
  240.         else {
  241.             $this->querystring[$nameis_array($valuearray_map('rawurlencode'$value)rawurlencode($value);
  242.         }
  243.     }
  244.  
  245.     /**
  246.     * Removes a querystring item
  247.     *
  248.     * @param  string $name Name of item
  249.     */
  250.     public function removeQueryString($name)
  251.     {
  252.         if ($this->getOption('encode_query_keys')) {
  253.             $name rawurlencode($name);
  254.         }
  255.         
  256.         if (isset($this->querystring[$name])) {
  257.             unset($this->querystring[$name]);
  258.         }
  259.     }
  260.  
  261.     /**
  262.     * Sets the querystring to literally what you supply
  263.     *
  264.     * @param  string $querystring The querystring data. Should be of the format foo=bar&x=y etc
  265.     */
  266.     public function addRawQueryString($querystring)
  267.     {
  268.         $this->querystring $this->_parseRawQueryString($querystring);
  269.     }
  270.  
  271.     /**
  272.     * Returns flat querystring
  273.     *
  274.     * @return string Querystring
  275.     */
  276.     public function getQueryString()
  277.     {
  278.         if (!empty($this->querystring)) {
  279.             foreach ($this->querystring as $name => $value{
  280.  
  281.                 // Encode var name
  282.                 $name rawurlencode($name);
  283.  
  284.                 if (is_array($value)) {
  285.                     foreach ($value as $k => $v{
  286.                         $querystring[$this->useBrackets sprintf('%s[%s]=%s'$name$k$v($name '=' $v);
  287.                     }
  288.                 elseif (!is_null($value)) {
  289.                     $querystring[$name '=' $value;
  290.                 else {
  291.                     $querystring[$name;
  292.                 }
  293.             }
  294.             $querystring implode(ini_get('arg_separator.output')$querystring);
  295.         else {
  296.             $querystring '';
  297.         }
  298.  
  299.         return $querystring;
  300.     }
  301.  
  302.     /**
  303.     * Forces the URL to a particular protocol
  304.     *
  305.     * @param string  $protocol Protocol to force the URL to
  306.     * @param integer $port     Optional port (standard port is used by default)
  307.     */
  308.     public function setProtocol($protocol$port = null)
  309.     {
  310.         $this->protocol $protocol;
  311.         $this->port     is_null($port$this->getStandardPort($protocol$port;
  312.     }
  313.  
  314.     /**
  315.     * Resolves //, ../ and ./ from a path and returns
  316.     * the result. Eg:
  317.     *
  318.     * /foo/bar/../boo.php    => /foo/boo.php
  319.     * /foo/bar/../../boo.php => /boo.php
  320.     * /foo/bar/.././/boo.php => /foo/boo.php
  321.     *
  322.     * @param  string $url URL path to resolve
  323.     * @return string      The result
  324.     */
  325.     public static function resolvePath($path)
  326.     {
  327.         $path explode('/'str_replace('//''/'$path));
  328.  
  329.         for ($i=0; $i<count($path)$i++{
  330.             if ($path[$i== '.'{
  331.                 unset($path[$i]);
  332.                 $path array_values($path);
  333.                 $i--;
  334.  
  335.             elseif ($path[$i== '..' AND ($i > 1 OR ($i == 1 AND $path[0!= '') ) ) {
  336.                 unset($path[$i]);
  337.                 unset($path[$i-1]);
  338.                 $path array_values($path);
  339.                 $i -= 2;
  340.  
  341.             elseif ($path[$i== '..' AND $i == 1 AND $path[0== ''{
  342.                 unset($path[$i]);
  343.                 $path array_values($path);
  344.                 $i--;
  345.  
  346.             else {
  347.                 continue;
  348.             }
  349.         }
  350.  
  351.         return implode('/'$path);
  352.     }
  353.  
  354.     /**
  355.     * Returns the standard port number for a protocol
  356.     *
  357.     * @param  string  $scheme The protocol to lookup
  358.     * @return integer         Port number or NULL if no scheme matches
  359.     *
  360.     * @author Philippe Jausions <Philippe.Jausions@11abacus.com>
  361.     */
  362.     public static function getStandardPort($scheme)
  363.     {
  364.         switch (strtolower($scheme)) {
  365.             case 'http':    return 80;
  366.             case 'https':   return 443;
  367.             case 'ftp':     return 21;
  368.             case 'imap':    return 143;
  369.             case 'imaps':   return 993;
  370.             case 'pop3':    return 110;
  371.             case 'pop3s':   return 995;
  372.             default:        return null;
  373.        }
  374.     }
  375.  
  376.     /**
  377.     * Parses raw querystring and returns an array of it
  378.     *
  379.     * @param  string  $querystring The querystring to parse
  380.     * @return array                An array of the querystring data
  381.     */
  382.     private function _parseRawQuerystring($querystring)
  383.     {
  384.         $parts  preg_split('/[' preg_quote(ini_get('arg_separator.input')'/'']/'$querystring-1PREG_SPLIT_NO_EMPTY);
  385.         $return = array();
  386.  
  387.         foreach ($parts as $part{
  388.             if (strpos($part'='!== false{
  389.                 
  390.                 $value substr($partstrpos($part'='+ 1);
  391.                 $key   substr($part0strpos($part'='));
  392.             else {
  393.                 $value = null;
  394.                 $key   $part;
  395.             }
  396.  
  397.             if (!$this->getOption('encode_query_keys')) {
  398.                 $key urldecode($key);
  399.             }
  400.  
  401.             if (preg_match('#^(.*)\[([0-9a-z_-]*)\]#i'$key$matches)) {
  402.                 $key $matches[1];
  403.                 $idx $matches[2];
  404.  
  405.                 // Ensure is an array
  406.                 if (empty($return[$key]|| !is_array($return[$key])) {
  407.                     $return[$key= array();
  408.                 }
  409.  
  410.                 // Add data
  411.                 if ($idx === ''{
  412.                     $return[$key][$value;
  413.  
  414.                 else {
  415.                     $return[$key][$idx$value;
  416.                 }
  417.  
  418.             elseif (!$this->useBrackets AND !empty($return[$key])) {
  419.                 $return[$key]   = (array)$return[$key];
  420.                 $return[$key][$value;
  421.             else {
  422.                 $return[$key$value;
  423.             }
  424.         }
  425.  
  426.         return $return;
  427.     }
  428.  
  429.     /**
  430.      * Set a private option
  431.      *
  432.      * This function sets a private option
  433.      *
  434.      * @param string $optionName   The option name
  435.      * @param string $value        The value of this option
  436.      */
  437.     public static function setOption($optionName$value)
  438.     {
  439.         self::$options[$optionName$value;
  440.     }
  441.  
  442.     /**
  443.      * Get an option
  444.      *
  445.      * This function will get an option
  446.      * from the options private variable.
  447.      *
  448.      * @see $this->options
  449.      * @return mixed   Bool false if the key doesn't exist and the value
  450.      *                  of the option if it exists.
  451.      */
  452.     public function getOption($optionName)
  453.     {
  454.         if (!isset(self::$options[$optionName])) {
  455.             return false;
  456.         }
  457.  
  458.         return self::$options[$optionName];
  459.     }
  460. }
  461. ?>

Documentation generated on Mon, 11 Mar 2019 15:01:42 -0400 by phpDocumentor 1.4.4. PEAR Logo Copyright © PHP Group 2004.