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

Source for file URL.php

Documentation is available at URL.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: URL.php,v 1.46 2007/05/08 05:01:49 davidc Exp $
  36. //
  37. // Net_URL Class
  38.  
  39.  
  40. class Net_URL
  41. {
  42.     var $options = array('encode_query_keys' => false);
  43.     /**
  44.     * Full url
  45.     * @var string 
  46.     */
  47.     var $url;
  48.  
  49.     /**
  50.     * Protocol
  51.     * @var string 
  52.     */
  53.     var $protocol;
  54.  
  55.     /**
  56.     * Username
  57.     * @var string 
  58.     */
  59.     var $username;
  60.  
  61.     /**
  62.     * Password
  63.     * @var string 
  64.     */
  65.     var $password;
  66.  
  67.     /**
  68.     * Host
  69.     * @var string 
  70.     */
  71.     var $host;
  72.  
  73.     /**
  74.     * Port
  75.     * @var integer 
  76.     */
  77.     var $port;
  78.  
  79.     /**
  80.     * Path
  81.     * @var string 
  82.     */
  83.     var $path;
  84.  
  85.     /**
  86.     * Query string
  87.     * @var array 
  88.     */
  89.     var $querystring;
  90.  
  91.     /**
  92.     * Anchor
  93.     * @var string 
  94.     */
  95.     var $anchor;
  96.  
  97.     /**
  98.     * Whether to use []
  99.     * @var bool 
  100.     */
  101.     var $useBrackets;
  102.  
  103.     /**
  104.     * PHP4 Constructor
  105.     *
  106.     * @see __construct()
  107.     */
  108.     function Net_URL($url = null$useBrackets = true)
  109.     {
  110.         $this->__construct($url$useBrackets);
  111.     }
  112.  
  113.     /**
  114.     * PHP5 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.     function __construct($url = null$useBrackets = true)
  125.     {
  126.         $this->url $url;
  127.         $this->useBrackets $useBrackets;
  128.  
  129.         $this->initialize();
  130.     }
  131.  
  132.     function initialize($url = null$useBrackets = true)
  133.     {
  134.         $HTTP_SERVER_VARS  !empty($_SERVER$_SERVER $GLOBALS['HTTP_SERVER_VARS'];
  135.  
  136.         $this->useBrackets $useBrackets;
  137.         $this->url         $url;
  138.         $this->user        '';
  139.         $this->pass        '';
  140.         $this->host        '';
  141.         $this->port        = 80;
  142.         $this->path        '';
  143.         $this->querystring = array();
  144.         $this->anchor      '';
  145.  
  146.         // Only use defaults if not an absolute URL given
  147.         if (!preg_match('/^[a-z0-9]+:\/\//i'$url)) {
  148.             $this->protocol (!empty($_SERVER['HTTPS']&& $_SERVER['HTTPS'== 'on' 'https' 'http');
  149.  
  150.             /**
  151.             * Figure out host/port
  152.             */
  153.             if (!empty($HTTP_SERVER_VARS['HTTP_HOST']AND preg_match('/^(.*)(:([0-9]+))?$/U'$HTTP_SERVER_VARS['HTTP_HOST']$matches)) {
  154.                 $host $matches[1];
  155.                 if (!empty($matches[3])) {
  156.                     $port $matches[3];
  157.                 else {
  158.                     $port $this->getStandardPort($this->protocol);
  159.                 }
  160.             }
  161.  
  162.             $this->user        '';
  163.             $this->pass        '';
  164.             $this->host        !empty($host$host (isset($HTTP_SERVER_VARS['SERVER_NAME']$HTTP_SERVER_VARS['SERVER_NAME''localhost');
  165.             $this->port        !empty($port$port (isset($HTTP_SERVER_VARS['SERVER_PORT']$HTTP_SERVER_VARS['SERVER_PORT'$this->getStandardPort($this->protocol));
  166.             $this->path        !empty($HTTP_SERVER_VARS['PHP_SELF']$HTTP_SERVER_VARS['PHP_SELF''/';
  167.             $this->querystring = isset($HTTP_SERVER_VARS['QUERY_STRING']$this->_parseRawQuerystring($HTTP_SERVER_VARS['QUERY_STRING']: null;
  168.             $this->anchor      '';
  169.         }
  170.  
  171.         // Parse the url and store the various parts
  172.         if (!empty($url)) {
  173.             $urlinfo parse_url($url);
  174.  
  175.             // Default querystring
  176.             $this->querystring = array();
  177.  
  178.             foreach ($urlinfo as $key => $value{
  179.                 switch ($key{
  180.                     case 'scheme':
  181.                         $this->protocol $value;
  182.                         $this->port     $this->getStandardPort($value);
  183.                         break;
  184.  
  185.                     case 'user':
  186.                     case 'pass':
  187.                     case 'host':
  188.                     case 'port':
  189.                         $this->$key $value;
  190.                         break;
  191.  
  192.                     case 'path':
  193.                         if ($value{0== '/'{
  194.                             $this->path $value;
  195.                         else {
  196.                             $path dirname($this->path== DIRECTORY_SEPARATOR ? '' dirname($this->path);
  197.                             $this->path sprintf('%s/%s'$path$value);
  198.                         }
  199.                         break;
  200.  
  201.                     case 'query':
  202.                         $this->querystring $this->_parseRawQueryString($value);
  203.                         break;
  204.  
  205.                     case 'fragment':
  206.                         $this->anchor $value;
  207.                         break;
  208.                 }
  209.             }
  210.         }
  211.     }
  212.     /**
  213.     * Returns full url
  214.     *
  215.     * @return string Full url
  216.     * @access public
  217.     */
  218.     function getURL()
  219.     {
  220.         $querystring $this->getQueryString();
  221.  
  222.         $this->url $this->protocol '://'
  223.                    . $this->user (!empty($this->pass':' '')
  224.                    . $this->pass (!empty($this->user'@' '')
  225.                    . $this->host ($this->port == $this->getStandardPort($this->protocol'' ':' $this->port)
  226.                    . $this->path
  227.                    . (!empty($querystring'?' $querystring '')
  228.                    . (!empty($this->anchor'#' $this->anchor '');
  229.  
  230.         return $this->url;
  231.     }
  232.  
  233.     /**
  234.     * Adds a querystring item
  235.     *
  236.     * @param  string $name       Name of item
  237.     * @param  string $value      Value of item
  238.     * @param  bool   $preencoded Whether value is urlencoded or not, default = not
  239.     * @access public
  240.     */
  241.     function addQueryString($name$value$preencoded = false)
  242.     {
  243.         if ($this->getOption('encode_query_keys')) {
  244.             $name rawurlencode($name);
  245.         }
  246.  
  247.         if ($preencoded{
  248.             $this->querystring[$name$value;
  249.         else {
  250.             $this->querystring[$nameis_array($valuearray_map('rawurlencode'$value)rawurlencode($value);
  251.         }
  252.     }
  253.  
  254.     /**
  255.     * Removes a querystring item
  256.     *
  257.     * @param  string $name Name of item
  258.     * @access public
  259.     */
  260.     function removeQueryString($name)
  261.     {
  262.         if ($this->getOption('encode_query_keys')) {
  263.             $name rawurlencode($name);
  264.         }
  265.  
  266.         if (isset($this->querystring[$name])) {
  267.             unset($this->querystring[$name]);
  268.         }
  269.     }
  270.  
  271.     /**
  272.     * Sets the querystring to literally what you supply
  273.     *
  274.     * @param  string $querystring The querystring data. Should be of the format foo=bar&x=y etc
  275.     * @access public
  276.     */
  277.     function addRawQueryString($querystring)
  278.     {
  279.         $this->querystring $this->_parseRawQueryString($querystring);
  280.     }
  281.  
  282.     /**
  283.     * Returns flat querystring
  284.     *
  285.     * @return string Querystring
  286.     * @access public
  287.     */
  288.     function getQueryString()
  289.     {
  290.         if (!empty($this->querystring)) {
  291.             foreach ($this->querystring as $name => $value{
  292.                 // Encode var name
  293.                 $name rawurlencode($name);
  294.  
  295.                 if (is_array($value)) {
  296.                     foreach ($value as $k => $v{
  297.                         $querystring[$this->useBrackets sprintf('%s[%s]=%s'$name$k$v($name '=' $v);
  298.                     }
  299.                 elseif (!is_null($value)) {
  300.                     $querystring[$name '=' $value;
  301.                 else {
  302.                     $querystring[$name;
  303.                 }
  304.             }
  305.             $querystring implode(ini_get('arg_separator.output')$querystring);
  306.         else {
  307.             $querystring '';
  308.         }
  309.  
  310.         return $querystring;
  311.     }
  312.  
  313.     /**
  314.     * Parses raw querystring and returns an array of it
  315.     *
  316.     * @param  string  $querystring The querystring to parse
  317.     * @return array                An array of the querystring data
  318.     * @access private
  319.     */
  320.     function _parseRawQuerystring($querystring)
  321.     {
  322.         $parts  preg_split('/[' preg_quote(ini_get('arg_separator.input')'/'']/'$querystring-1PREG_SPLIT_NO_EMPTY);
  323.         $return = array();
  324.  
  325.         foreach ($parts as $part{
  326.             if (strpos($part'='!== false{
  327.                 $value substr($partstrpos($part'='+ 1);
  328.                 $key   substr($part0strpos($part'='));
  329.             else {
  330.                 $value = null;
  331.                 $key   $part;
  332.             }
  333.  
  334.             if (!$this->getOption('encode_query_keys')) {
  335.                 $key rawurldecode($key);
  336.             }
  337.  
  338.             if (preg_match('#^(.*)\[([0-9a-z_-]*)\]#i'$key$matches)) {
  339.                 $key $matches[1];
  340.                 $idx $matches[2];
  341.  
  342.                 // Ensure is an array
  343.                 if (empty($return[$key]|| !is_array($return[$key])) {
  344.                     $return[$key= array();
  345.                 }
  346.  
  347.                 // Add data
  348.                 if ($idx === ''{
  349.                     $return[$key][$value;
  350.                 else {
  351.                     $return[$key][$idx$value;
  352.                 }
  353.             elseif (!$this->useBrackets AND !empty($return[$key])) {
  354.                 $return[$key]   = (array)$return[$key];
  355.                 $return[$key][$value;
  356.             else {
  357.                 $return[$key$value;
  358.             }
  359.         }
  360.  
  361.         return $return;
  362.     }
  363.  
  364.     /**
  365.     * Resolves //, ../ and ./ from a path and returns
  366.     * the result. Eg:
  367.     *
  368.     * /foo/bar/../boo.php    => /foo/boo.php
  369.     * /foo/bar/../../boo.php => /boo.php
  370.     * /foo/bar/.././/boo.php => /foo/boo.php
  371.     *
  372.     * This method can also be called statically.
  373.     *
  374.     * @param  string $url URL path to resolve
  375.     * @return string      The result
  376.     */
  377.     function resolvePath($path)
  378.     {
  379.         $path explode('/'str_replace('//''/'$path));
  380.  
  381.         for ($i=0; $i<count($path)$i++{
  382.             if ($path[$i== '.'{
  383.                 unset($path[$i]);
  384.                 $path array_values($path);
  385.                 $i--;
  386.  
  387.             elseif ($path[$i== '..' AND ($i > 1 OR ($i == 1 AND $path[0!= '') ) ) {
  388.                 unset($path[$i]);
  389.                 unset($path[$i-1]);
  390.                 $path array_values($path);
  391.                 $i -= 2;
  392.  
  393.             elseif ($path[$i== '..' AND $i == 1 AND $path[0== ''{
  394.                 unset($path[$i]);
  395.                 $path array_values($path);
  396.                 $i--;
  397.  
  398.             else {
  399.                 continue;
  400.             }
  401.         }
  402.  
  403.         return implode('/'$path);
  404.     }
  405.  
  406.     /**
  407.     * Returns the standard port number for a protocol
  408.     *
  409.     * @param  string  $scheme The protocol to lookup
  410.     * @return integer         Port number or NULL if no scheme matches
  411.     *
  412.     * @author Philippe Jausions <Philippe.Jausions@11abacus.com>
  413.     */
  414.     function getStandardPort($scheme)
  415.     {
  416.         switch (strtolower($scheme)) {
  417.             case 'http':    return 80;
  418.             case 'https':   return 443;
  419.             case 'ftp':     return 21;
  420.             case 'imap':    return 143;
  421.             case 'imaps':   return 993;
  422.             case 'pop3':    return 110;
  423.             case 'pop3s':   return 995;
  424.             default:        return null;
  425.        }
  426.     }
  427.  
  428.     /**
  429.     * Forces the URL to a particular protocol
  430.     *
  431.     * @param string  $protocol Protocol to force the URL to
  432.     * @param integer $port     Optional port (standard port is used by default)
  433.     */
  434.     function setProtocol($protocol$port = null)
  435.     {
  436.         $this->protocol $protocol;
  437.         $this->port     is_null($port$this->getStandardPort($protocol$port;
  438.     }
  439.  
  440.     /**
  441.      * Set an option
  442.      *
  443.      * This function set an option
  444.      * to be used thorough the script.
  445.      *
  446.      * @access public
  447.      * @param  string $optionName  The optionname to set
  448.      * @param  string $value       The value of this option.
  449.      */
  450.     function setOption($optionName$value)
  451.     {
  452.         if (!array_key_exists($optionName$this->options)) {
  453.             return false;
  454.         }
  455.  
  456.         $this->options[$optionName$value;
  457.         $this->initialize();
  458.     }
  459.  
  460.     /**
  461.      * Get an option
  462.      *
  463.      * This function gets an option
  464.      * from the $this->options array
  465.      * and return it's value.
  466.      *
  467.      * @access public
  468.      * @param  string $opionName  The name of the option to retrieve
  469.      * @see    $this->options
  470.      */
  471.     function getOption($optionName)
  472.     {
  473.         if (!isset($this->options[$optionName])) {
  474.             return false;
  475.         }
  476.  
  477.         return $this->options[$optionName];
  478.     }
  479.  
  480. }
  481. ?>

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