TimeTrex Community Edition v16.2.0

This commit is contained in:
2022-12-13 07:10:06 +01:00
commit 472f000c1b
6810 changed files with 2636142 additions and 0 deletions

864
classes/pear/Net/Curl.php Normal file
View File

@ -0,0 +1,864 @@
<?php
/**
* An Object Oriented interface to PHP's cURL extension
*
* PHP version 5.1.0+
*
* Copyright (c) 2007, The PEAR Group
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the The PEAR Group nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* @category Net
* @package Net_Curl
* @author David Costa <gurugeek@php.net>
* @author Sterling Hughes <sterling@php.net>
* @author Joe Stump <joe@joestump.net>
* @author Philippe Jausions <jausions@php.net>
* @copyright 1997-2008 The PHP Group
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
* @version CVS: $Revision: 1.15 $
* @link http://pear.php.net/package/Net_Curl
*/
/**
* Include PEAR package for error handling
*/
require_once 'PEAR.php';
/**
* Object-oriented implementation of the Curl extension
*
* @category Net
* @package Net_Curl
* @author David Costa <gurugeek@php.net>
* @author Sterling Hughes <sterling@php.net>
* @author Joe Stump <joe@joestump.net>
* @author Philippe Jausions <jausions@php.net>
* @license http://www.opensource.org/licenses/bsd-license.php New BSD License
* @link http://pear.php.net/package/Net_Curl
*/
class Net_Curl
{
// {{{ Public Properties
/**
* The URL for cURL to work with
*
* @var string $url
* @access public
*/
var $url;
/**
* The Username for standard HTTP Authentication
*
* @var string $username
* @access public
*/
var $username = '';
/**
* The Password for standard HTTP Authentication
*
* @var string $password
* @access public
*/
var $password = '';
/**
* The SSL version for the transfer
*
* @var integer $sslVersion
* @access public
*/
var $sslVersion;
/**
* The filename of the SSL certificate
*
* @var string $sslCert
* @access public
*/
var $sslCert;
/**
* The password corresponding to the certificate
* in the $sslCert property
*
* @var string $sslCertPasswd
* @access public
*/
var $sslCertPasswd;
/**
* User Agent string when making an HTTP request
*
* @var string $userAgent
* @access public
*/
var $userAgent;
/**
* Whether or not to include the header in the results
* of the CURL transfer
*
* @var boolean $header
*/
var $header = false;
/**
* Whether or not to output debug information while executing a
* curl transfer
*
* @var boolean $verbose
* @access public
*/
var $verbose = false;
/**
* Whether or not to display a progress meter for the current transfer
*
* @var boolean $progress
* @access public
*/
var $progress = false;
/**
* Whether or not to suppress error messages
*
* @var boolean $mute
* @access public
*/
var $mute = false;
/**
* Whether or not to follow HTTP Location headers.
*
* @var boolean $followLocation
* @access public
*/
var $followLocation = true;
/**
* Whether or not to follow HTTP Location headers.
*
* @var boolean $follow_location
* @access public
* @deprecated
*/
var $follow_location = false;
/**
* Time allowed for current transfer, in seconds. 0 means no limit
*
* @var int $timeout
* @access public
*/
var $timeout = 0;
/**
* Whether or not to return the results of the
* current transfer
*
* @var boolean $returnTransfer
* @access public
*/
var $returnTransfer = true;
/**
* Whether or not to return the results of the
* current transfer
*
* @var boolean $return_transfer
* @access public
* @deprecated
*/
var $return_transfer = false;
/**
* The type of transfer to perform (ie. 'POST', 'GET', 'PUT', etc)
*
* @var string $type
* @access public
*/
var $type;
/**
* The file to upload (PUT, or FTP methods)
*
* @var string $file
* @access public
*/
var $file;
/**
* The file size of the file pointed to by the $file
* property
*
* @var integer $fileSize
* @access public
*/
var $fileSize;
/**
* The file size of the file pointed to by the $file
* property
*
* @var integer $file_size
* @access public
* @deprecated
*/
var $file_size = false;
/**
* The cookies to send to the remote site
*
* @var array $cookies
* @access public
*/
var $cookies = array();
/**
* Additional HTTP headers to send to the remote site
*
* @var array $httpHeaders
* @access public
*/
var $httpHeaders = null;
/**
* Additional HTTP headers to send to the remote site
*
* @var array $http_headers
* @access public
* @deprecated
*/
var $http_headers = false;
/**
* The fields to send in a 'POST' request
*
* @var array $fields
* @access public
*/
var $fields;
/**
* The proxy server to go through
*
* @var string $proxy
* @access public
*/
var $proxy;
/**
* The username for the Proxy server
*
* @var string $proxyUser
* @access public
*/
var $proxyUser;
/**
* The password for the Proxy server
*
* @var string $proxyPassword
* @access public
*/
var $proxyPassword;
/**
* $verifyPeer
*
* FALSE to stop CURL from verifying the peer's certificate.
* Alternate certificates to verify against can be specified
* with the CURLOPT_CAINFO option or a certificate directory
* can be specified with the CURLOPT_CAPATH option.
* CURLOPT_SSL_VERIFYHOST may also need to be TRUE or FALSE
* if CURLOPT_SSL_VERIFYPEER is disabled (it defaults to 2).
*
* @var boolean $verifyPeer
* @access public
*/
var $verifyPeer = true;
/**
* $verifyHost
*
* 0 : to stop CURL from verifying the host's certificate.
* 1 : to check the existence of a common name in the SSL peer certificate.
* 2 : to check the existence of a common name and also verify that it
* matches the hostname provided.
*
* @var bool $verifyHost
* @access public
*/
var $verifyHost = 2;
/**
* $caInfo
*
* Set value for CURLOPT_CAINFO. The name of a file holding one or more
* certificates to verify the peer with. This only makes sense when used
* in combination with CURLOPT_SSL_VERIFYPEER. curl-ca-bundle.crt is
* avaible on the Curl website http://curl.haxx.se/ for download inside
* the packages.
*
* @var string $caInfo
* @access public
*/
var $caInfo = '';
/**
* $caPath
*
* Set value for CURLOPT_CAPATH. A directory that holds multiple CA
* certificates. Use this option alongside CURLOPT_SSL_VERIFYPEER.
*
* @var string $caPath
* @access public
*/
var $caPath;
// }}}
// {{{ Private Properties
/**
* The current curl handle
*
* @var resource $_ch
* @access private
* @see Net_Curl::create()
*/
var $_ch = null;
/**
* The file upload resource
*
* The CURLOPT_INFILE requires a file resource and not just a file name.
* This is used by execute to open the file.
*
* @var resource $_fp
* @access private
* @see Net_Curl::execute()
*/
var $_fp = null;
// }}}
// {{{ __construct($url = '', $userAgent = '')
/**
* The Net_Curl PHP 5.x constructor, called when a new Net_Curl object
* is initialized (also called via 4.x constructor)
*
* @param string $url The URL to fetch (can be set using the $url
* property as well)
* @param string $userAgent The userAgent string (can be set using the
* $userAgent property as well)
*
* @access public
* @author Joe Stump <joe@joestump.net>
* @return void
*/
function __construct($url = '', $userAgent = '')
{
if (is_string($url) && strlen($url)) {
$this->url = $url;
}
if (is_string($userAgent) && strlen($userAgent)) {
$this->userAgent = $userAgent;
}
}
// }}}
// {{{ execute()
/**
* Executes a prepared CURL transfer
*
* Run this function to execute your cURL request. If all goes well you
* should get a string (the output from the remote host regarding your
* request) or true (if you choose to output directly to the browser). If
* something fails then PEAR_Error is returned.
*
* <code>
* <?php
* require_once 'Net/Curl.php';
*
* $curl = new Net_Curl('http://www.example.com');
* $curl->fields = array('foo' => '1', 'bar' => 'apple');
* $result = $curl->execute();
* if (!PEAR::isError($result)) {
* echo $result;
* }
* ?>
* </code>
*
* @access public
* @author Sterling Hughes <sterling@php.net>
* @author Joe Stump <joe@joestump.net>
* @return PEAR_Error on failure, true/result on success
* @since PHP 4.0.5
*/
function execute()
{
// Create cURL handle if it hasn't already been created
if (!is_resource($this->_ch) && !( ( is_object( $this->_ch ) && $this->_ch instanceOf CurlHandle ) ) ) {
$result = $this->create();
if (PEAR::isError($result)) {
return $result;
}
}
// Map the deprecated variables and throw a bunch of errors
$this->_mapDeprecatedVariables();
// Default return value is true.
$ret = true;
// Basic stuff
if ( class_exists('\CURLFile') ) {
$ret = curl_setopt( $this->_ch, CURLOPT_SAFE_UPLOAD, TRUE ); //Fixes change in PHP v5.6 that prevents @$file_name uploading.
} else {
$ret = curl_setopt( $this->_ch, CURLOPT_SAFE_UPLOAD, FALSE ); //Fixes change in PHP v5.6 that prevents @$file_name uploading.
}
$ret = curl_setopt($this->_ch, CURLOPT_URL, $this->url);
$ret = curl_setopt($this->_ch, CURLOPT_HEADER, $this->header);
// Whether or not to return the transfer contents
if ($this->returnTransfer === true || $this->mute === true) {
$ret = curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, true);
}
// HTTP Authentication
if ($this->username != '') {
$ret = curl_setopt($this->_ch,
CURLOPT_USERPWD,
$this->username . ':' . $this->password);
}
// SSL Checks
if (isset($this->sslVersion)) {
$ret = curl_setopt($this->_ch,
CURLOPT_SSLVERSION,
$this->sslVersion);
}
if (isset($this->sslCert)) {
$ret = curl_setopt($this->_ch, CURLOPT_SSLCERT, $this->sslCert);
}
if (isset($this->sslCertPasswd)) {
$ret = curl_setopt($this->_ch,
CURLOPT_SSLCERTPASSWD,
$this->sslCertPasswd);
}
// Proxy Related checks
if (isset($this->proxy)) {
$ret = curl_setopt($this->_ch, CURLOPT_PROXY, $this->proxy);
}
if (isset($this->proxyUser) || isset($this->proxyPassword)) {
$ret = curl_setopt($this->_ch,
CURLOPT_PROXYUSERPWD,
$this->proxyUser . ':' . $this->proxyPassword);
}
if (is_bool($this->verifyPeer)) {
if (!$this->setOption(CURLOPT_SSL_VERIFYPEER, $this->verifyPeer)) {
return PEAR::raiseError('Error setting CURLOPT_SSL_VERIFYPEER');
}
}
if (is_numeric($this->verifyHost) && $this->verifyHost >= 0 &&
$this->verifyHost <= 2) {
if (!$this->setOption(CURLOPT_SSL_VERIFYHOST, $this->verifyHost)) {
return PEAR::raiseError('Error setting CURLOPT_SSL_VERIFYPEER');
}
}
if (is_bool($this->verifyPeer) && $this->verifyPeer == true) {
if (isset($this->caInfo) && strlen($this->caInfo)) {
if (file_exists($this->caInfo)) {
if (!$this->setOption(CURLOPT_CAINFO, $this->caInfo)) {
return PEAR::raiseError('Error setting CURLOPT_CAINFO');
}
} else {
return PEAR::raiseError('Could not find CA info: '.
$this->caInfo);
}
}
if (isset($this->caPath) && is_string($this->caPath)) {
if (!$this->setOption(CURLOPT_CAPATH, $this->caPath)) {
return PEAR::raiseError('Error setting CURLOPT_CAPATH');
}
}
}
// Transfer type
if (isset($this->type)) {
switch (strtolower($this->type)) {
case 'post':
$ret = curl_setopt($this->_ch, CURLOPT_POST, true);
break;
case 'put':
$ret = curl_setopt($this->_ch, CURLOPT_PUT, true);
break;
}
}
// Transfer upload, etc. related
if (isset($this->file)) {
if (!file_exists($this->file)) {
return PEAR::raiseError('File does not exist: '.$this->file);
}
$this->_fp = fopen($this->file, 'r');
if (!is_resource($this->_fp)) {
return PEAR::raiseError('Could not open file: '.$this->file);
}
if (!isset($this->fileSize)) {
$this->fileSize = filesize($this->file);
}
$ret = curl_setopt($this->_ch, CURLOPT_INFILE, $this->_fp);
$ret = curl_setopt($this->_ch, CURLOPT_INFILESIZE, $this->fileSize);
$ret = curl_setopt($this->_ch, CURLOPT_UPLOAD, true);
}
if (isset($this->fields)) {
$sets = null;
if (!isset($this->type)) {
$this->type = 'post';
$ret = curl_setopt($this->_ch, CURLOPT_POST, true);
}
// If fields is an array then turn it into a string. Sometimes
// cURL doesn't like fields as an array.
// Exception: if a value is prefixed with "@" and the rest of the
// value resolves to an existing file, then pass
// the values as the original array.
if (is_array($this->fields)) {
$sets = array();
foreach ($this->fields as $key => $val) {
if ( class_exists('\CURLFile') AND is_object($val) ) {
$sets = null;
break;
} elseif ( strlen($val) > 1 && $val[0] == '@') {
$file = substr($val, 1);
if (is_file($file) && is_readable($file)) {
$sets = null;
break;
}
}
$sets[] = urlencode($key) . '=' . urlencode($val);
}
}
if (!is_null($sets)) {
$fields = implode('&', $sets);
} else {
$fields = $this->fields;
}
$ret = curl_setopt($this->_ch, CURLOPT_POSTFIELDS, $fields);
}
// Error related
if ($this->progress === 9999) { //Disable because CURLOPT_PROGRESS is not a defined constant
$ret = curl_setopt($this->_ch, CURLOPT_PROGRESS, true);
}
if ($this->verbose === true) {
$ret = curl_setopt($this->_ch, CURLOPT_VERBOSE, true);
}
// If a Location: header is passed then follow it
$ret = curl_setopt($this->_ch,
CURLOPT_FOLLOWLOCATION,
$this->followLocation);
// If a timeout is set and is greater then zero then set it
if (is_numeric($this->timeout) && $this->timeout > 0) {
$ret = curl_setopt($this->_ch, CURLOPT_TIMEOUT, $this->timeout);
}
if (isset($this->userAgent)) {
$ret = curl_setopt($this->_ch, CURLOPT_USERAGENT, $this->userAgent);
}
// Cookies
if (is_array($this->cookies) && count($this->cookies)) {
$cookieData = '';
foreach ($this->cookies as $name => $value) {
$cookieData .= $name . '=' . $value . ';';
}
$ret = curl_setopt($this->_ch, CURLOPT_COOKIE, $cookieData);
}
// Other HTTP headers
if ($this->httpHeaders !== null) {
if (is_array($this->httpHeaders)) {
$ret = curl_setopt($this->_ch,
CURLOPT_HTTPHEADER,
$this->httpHeaders);
} else {
return PEAR::raiseError('Net_Curl::$httpHeaders must be an array');
}
}
$ret = curl_exec($this->_ch);
// Close the file before we return anything
if (is_resource($this->_fp)) {
fclose($this->_fp);
}
if (curl_errno($this->_ch)) {
return PEAR::raiseError(curl_error($this->_ch), curl_errno($this->_ch));
}
// Check to make sure we get a 2XX/3XX code and not a 404 or something.
$info = $this->getInfo();
if (!isset($info['http_code'])) {
return PEAR::raiseError('Unknown or invalid HTTP response');
} else {
$type = substr($info['http_code'], 0, 1);
if ($type != 2 && $type != 3) {
return PEAR::raiseError('Unexpected HTTP code: ' .
$info['http_code']);
}
}
return $ret;
}
// }}}
// {{{ setOption($option, $value)
/**
* Sets an option for your cURL session. Please note that the cURL handler
* is NOT created before execute(). This is for error checking purposes.
* You should use setOption() in the following manner:
*
* <code>
* <?php
*
* require_once 'Net/Curl.php';
* $curl = new Net_Curl('http://www.example.com');
* $check = $curl->create();
* if (!PEAR::isError($check)) {
* $curl->setOption(CURLOPT_FOO, 'bar');
* $result = $curl->execute();
* if (!PEAR::isError($result)) {
* echo $result;
* }
* }
*
* ?>
* </code>
*
* @param int $option cURL constant (ie. CURLOPT_URL)
* @param mixed $value The option's value
*
* @author Joe Stump <joe@joestump.net>
* @access public
* @return boolean
*/
function setOption($option, $value)
{
if ( is_resource($this->_ch) || ( ( is_object( $this->_ch ) && $this->_ch instanceOf CurlHandle ) ) ) {
return curl_setopt($this->_ch, $option, $value);
}
return false;
}
// }}}
// {{{ getInfo()
/**
* Returns the info from the cURL session. PEAR_Error if you try and run
* this before you execute the session.
*
* @author Joe Stump <joe@joestump.net>
* @access public
* @return mixed PEAR_Error if there is no resource, info on success
*/
function getInfo()
{
if ( is_resource($this->_ch) || ( ( is_object( $this->_ch ) && $this->_ch instanceOf CurlHandle ) ) ) {
return curl_getinfo($this->_ch);
}
return PEAR::isError('cURL handler does not exist!');
}
// }}}
// {{{ create()
/**
* Creates a cURL resource. If curl_init() doesn't exist or we could not
* create a resource it will error out.
*
* @author Joe Stump <joe@joestump.net>
* @return boolean TRUE on success, PEAR_Error on failure
*/
function create()
{
if (!PEAR::loadExtension('curl')) {
return PEAR::raiseError('CURL extension is not available');
}
if (!function_exists('curl_init')) {
return PEAR::raiseError('Function curl_init() not found');
}
$this->_ch = curl_init();
if (!is_resource($this->_ch) && !( ( is_object( $this->_ch ) && $this->_ch instanceOf CurlHandle ) ) ) {
return PEAR::raiseError('Could not initialize cURL handler');
}
return true;
}
// }}}
// {{{ verboseAll()
/**
* Sets verbose output
*
* Turns on super debugging mode by not suppressing errors, turning on
* verbose mode, showing headers and displaying progress.
*
* @access public
* @author David Costa <gurugeek@php.net>
* @return void
*/
function verboseAll()
{
$this->verbose = true;
$this->mute = false;
$this->header = true;
$this->progress = true;
}
// }}}
// {{{ verbose_all()
/**
* Sets verbose output
*
* @access public
* @author David Costa <gurugeek@php.net>
* @return void
* @deprecated
*/
function verbose_all()
{
$this->verboseAll();
PEAR::raiseError('Net_Curl::verbose_all() is deprecated! Please use Net_Curl::verboseAll()'." <br />\n", null, PEAR_ERROR_PRINT);
}
// }}}
// {{{ close()
/**
* Closes the curl transfer and finishes the object (kinda ;)
*
* @access public
* @author Sterling Hughes <sterling@php.net>
* @return void
* @since PHP 4.0.5
*/
function close()
{
if ( is_resource($this->_ch) || ( ( is_object( $this->_ch ) && $this->_ch instanceOf CurlHandle ) ) ) {
curl_close($this->_ch);
}
}
// }}}
// {{{ _mapDeprecatedVariables()
/**
* Maps deprecated variables into the appropriate places. It also throws
* the necessary notices.
*
* @author Joe Stump <joe@joestump.net>
* @access private
* @return void
*/
function _mapDeprecatedVariables()
{
$bad = array();
if ($this->follow_location !== false) {
if ($this->follow_location > 0) {
$this->followLocation = true;
} else {
$this->followLocation = false;
}
$bad[] = array('follow_location', 'followLocation');
}
if ($this->return_transfer !== false) {
if ($this->return_transfer > 0) {
$this->returnTransfer = true;
} else {
$this->returnTransfer = false;
}
$bad[] = array('return_transfer', 'returnTransfer');
}
if ($this->file_size !== false) {
$this->fileSize = $this->file_size;
$bad[] = array('file_size', 'fileSize');
}
if ($this->http_headers !== false) {
$this->httpHeaders = $this->http_headers;
$bad[] = array('http_headers', 'httpHeaders');
}
foreach ($bad as $map) {
PEAR::raiseError('Net_Curl::$'. $map[0]. ' is deprecated! Please use Net_Curl::$'.$map[1]." instead! <br />\n", null, PEAR_ERROR_PRINT);
}
}
// }}}
// {{{ __destruct()
/**
* PHP 5.x destructor.
*
* Runs Net_Curl::close() to make sure we close our cURL connection.
*
* @author Joe Stump <joe@joestump.net>
* @see Net_Curl::close()
*/
function __destruct()
{
$this->close();
}
// }}}
}
?>

629
classes/pear/Net/DIME.php Normal file
View File

@ -0,0 +1,629 @@
<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2002 The PHP Group |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license, |
// | that is bundled with this package in the file LICENSE, and is |
// | available at through the world-wide-web at |
// | http://www.php.net/license/2_02.txt. |
// | If you did not receive a copy of the PHP license and are unable to |
// | obtain it through the world-wide-web, please send a note to |
// | license@php.net so we can mail you a copy immediately. |
// +----------------------------------------------------------------------+
// | Authors: Shane Caraveo <shane@caraveo.com> |
// | Ralf Hofmann <ralf.hofmann@verdisoft.com> |
// +----------------------------------------------------------------------+
//
// $Id: DIME.php,v 1.5 2002/09/29 01:55:16 shane Exp $
//
require_once 'PEAR.php';
/**
*
* DIME Encoding/Decoding
*
* What is it?
* This class enables you to manipulate and build
* a DIME encapsulated message.
*
* http://www.ietf.org/internet-drafts/draft-nielsen-dime-02.txt
*
* 09/18/02 Ralf - A huge number of changes to be compliant
* with the DIME Specification Release 17 June 2002
*
* TODO: lots of stuff needs to be tested.
* Definitily have to go through DIME spec and
* make things work right, most importantly, sec 3.3
* make examples, document
*
* see test/dime_mesage_test.php for example of usage
*
* @author Shane Caraveo <shane@caraveo.com>,
* Ralf Hofmann <ralf.hofmann@verdisoft.com>
* @version $Revision: 1.5 $
* @package Net_DIME
*/
define('NET_DIME_TYPE_UNCHANGED',0x00);
define('NET_DIME_TYPE_MEDIA',0x01);
define('NET_DIME_TYPE_URI',0x02);
define('NET_DIME_TYPE_UNKNOWN',0x03);
define('NET_DIME_TYPE_NONE',0x04);
define('NET_DIME_VERSION',0x0001);
define('NET_DIME_RECORD_HEADER',12);
define('NET_DIME_FLAGS', 0);
define('NET_DIME_OPTS_LEN', 1);
define('NET_DIME_ID_LEN', 2);
define('NET_DIME_TYPE_LEN', 3);
define('NET_DIME_DATA_LEN', 4);
define('NET_DIME_OPTS', 5);
define('NET_DIME_ID', 6);
define('NET_DIME_TYPE', 7);
define('NET_DIME_DATA', 8);
class Net_DIME_Record extends PEAR
{
// these are used to hold the padded length
var $OPTS_LENGTH = 0;
var $ID_LENGTH = 0;
var $TYPE_LENGTH = 0;
var $DATA_LENGTH = 0;
var $_haveOpts = FALSE;
var $_haveID = FALSE;
var $_haveType = FALSE;
var $_haveData = FALSE;
var $debug = FALSE;
var $padstr = "\0";
/**
* Elements
* [NET_DIME_FLAGS], 16 bits: VERSION:MB:ME:CF:TYPE_T
* [NET_DIME_OPTS_LEN], 16 bits: OPTIONS_LENGTH
* [NET_DIME_ID_LEN], 16 bits: ID_LENGTH
* [NET_DIME_TYPE_LEN], 16 bits: TYPE_LENGTH
* [NET_DIME_DATA_LEN], 32 bits: DATA_LENGTH
* [NET_DIME_OPTS] : OPTIONS
* [NET_DIME_ID] : ID
* [NET_DIME_TYPE] : TYPE
* [NET_DIME_DATA] : DATA
*/
var $Elements = array(NET_DIME_FLAGS => 0, NET_DIME_OPTS_LEN => 0,
NET_DIME_ID_LEN => 0, NET_DIME_TYPE_LEN => 0,
NET_DIME_DATA_LEN => 0,
NET_DIME_OPTS => '',
NET_DIME_ID => '',
NET_DIME_TYPE => '',
NET_DIME_DATA => '');
function __construct($debug = FALSE)
{
$this->debug = $debug;
if ($debug) $this->padstr = '*';
}
function setMB()
{
$this->Elements[NET_DIME_FLAGS] |= 0x0400;
}
function setME()
{
$this->Elements[NET_DIME_FLAGS] |= 0x0200;
}
function setCF()
{
$this->Elements[NET_DIME_FLAGS] |= 0x0100;
}
function isChunk()
{
return $this->Elements[NET_DIME_FLAGS] & 0x0100;
}
function isEnd()
{
return $this->Elements[NET_DIME_FLAGS] & 0x0200;
}
function isStart()
{
return $this->Elements[NET_DIME_FLAGS] & 0x0400;
}
function getID()
{
return $this->Elements[NET_DIME_ID];
}
function getType()
{
return $this->Elements[NET_DIME_TYPE];
}
function getData()
{
return $this->Elements[NET_DIME_DATA];
}
function getDataLength()
{
return $this->Elements[NET_DIME_DATA_LEN];
}
function setType($typestring, $type=NET_DIME_TYPE_UNKNOWN)
{
$typelen = strlen($typestring) & 0xFFFF;
$type = $type << 4;
$this->Elements[NET_DIME_FLAGS] = ($this->Elements[NET_DIME_FLAGS] & 0xFF0F) | $type;
$this->Elements[NET_DIME_TYPE_LEN] = $typelen;
$this->TYPE_LENGTH = $this->_getPadLength($typelen);
$this->Elements[NET_DIME_TYPE] = $typestring;
}
function generateID()
{
$id = md5(time());
$this->setID($id);
return $id;
}
function setID($id)
{
$idlen = strlen($id) & 0xFFFF;
$this->Elements[NET_DIME_ID_LEN] = $idlen;
$this->ID_LENGTH = $this->_getPadLength($idlen);
$this->Elements[NET_DIME_ID] = $id;
}
function setData($data, $size=0)
{
$datalen = $size?$size:strlen($data);
$this->Elements[NET_DIME_DATA_LEN] = $datalen;
$this->DATA_LENGTH = $this->_getPadLength($datalen);
$this->Elements[NET_DIME_DATA] = $data;
}
function encode()
{
// insert version
$this->Elements[NET_DIME_FLAGS] = ($this->Elements[NET_DIME_FLAGS] & 0x07FF) | (NET_DIME_VERSION << 11);
// the real dime encoding
$format = '%c%c%c%c%c%c%c%c%c%c%c%c'.
'%'.$this->OPTS_LENGTH.'s'.
'%'.$this->ID_LENGTH.'s'.
'%'.$this->TYPE_LENGTH.'s'.
'%'.$this->DATA_LENGTH.'s';
return sprintf($format,
($this->Elements[NET_DIME_FLAGS]&0x0000FF00)>>8,
($this->Elements[NET_DIME_FLAGS]&0x000000FF),
($this->Elements[NET_DIME_OPTS_LEN]&0x0000FF00)>>8,
($this->Elements[NET_DIME_OPTS_LEN]&0x000000FF),
($this->Elements[NET_DIME_ID_LEN]&0x0000FF00)>>8,
($this->Elements[NET_DIME_ID_LEN]&0x000000FF),
($this->Elements[NET_DIME_TYPE_LEN]&0x0000FF00)>>8,
($this->Elements[NET_DIME_TYPE_LEN]&0x000000FF),
($this->Elements[NET_DIME_DATA_LEN]&0xFF000000)>>24,
($this->Elements[NET_DIME_DATA_LEN]&0x00FF0000)>>16,
($this->Elements[NET_DIME_DATA_LEN]&0x0000FF00)>>8,
($this->Elements[NET_DIME_DATA_LEN]&0x000000FF),
str_pad($this->Elements[NET_DIME_OPTS], $this->OPTS_LENGTH, $this->padstr),
str_pad($this->Elements[NET_DIME_ID], $this->ID_LENGTH, $this->padstr),
str_pad($this->Elements[NET_DIME_TYPE], $this->TYPE_LENGTH, $this->padstr),
str_pad($this->Elements[NET_DIME_DATA], $this->DATA_LENGTH, $this->padstr));
}
function _getPadLength($len)
{
$pad = 0;
if ($len) {
$pad = $len % 4;
if ($pad) $pad = 4 - $pad;
}
return $len + $pad;
}
function decode(&$data)
{
// REAL DIME decoding
$this->Elements[NET_DIME_FLAGS] = (hexdec(bin2hex($data[0]))<<8) + hexdec(bin2hex($data[1]));
$this->Elements[NET_DIME_OPTS_LEN] = (hexdec(bin2hex($data[2]))<<8) + hexdec(bin2hex($data[3]));
$this->Elements[NET_DIME_ID_LEN] = (hexdec(bin2hex($data[4]))<<8) + hexdec(bin2hex($data[5]));
$this->Elements[NET_DIME_TYPE_LEN] = (hexdec(bin2hex($data[6]))<<8) + hexdec(bin2hex($data[7]));
$this->Elements[NET_DIME_DATA_LEN] = (hexdec(bin2hex($data[8]))<<24) +
(hexdec(bin2hex($data[9]))<<16) +
(hexdec(bin2hex($data[10]))<<8) +
hexdec(bin2hex($data[11]));
$p = 12;
$version = (($this->Elements[NET_DIME_FLAGS]>>11) & 0x001F);
if ($version == NET_DIME_VERSION)
{
$this->OPTS_LENGTH = $this->_getPadLength($this->Elements[NET_DIME_OPTS_LEN]);
$this->ID_LENGTH = $this->_getPadLength($this->Elements[NET_DIME_ID_LEN]);
$this->TYPE_LENGTH = $this->_getPadLength($this->Elements[NET_DIME_TYPE_LEN]);
$this->DATA_LENGTH = $this->_getPadLength($this->Elements[NET_DIME_DATA_LEN]);
$datalen = strlen($data);
$this->Elements[NET_DIME_OPTS] = substr($data,$p,$this->Elements[NET_DIME_OPTS_LEN]);
$this->_haveOpts = (strlen($this->Elements[NET_DIME_OPTS]) == $this->Elements[NET_DIME_OPTS_LEN]);
if ($this->_haveOpts) {
$p += $this->OPTS_LENGTH;
$this->Elements[NET_DIME_ID] = substr($data,$p,$this->Elements[NET_DIME_ID_LEN]);
$this->_haveID = (strlen($this->Elements[NET_DIME_ID]) == $this->Elements[NET_DIME_ID_LEN]);
if ($this->_haveID) {
$p += $this->ID_LENGTH;
$this->Elements[NET_DIME_TYPE] = substr($data,$p,$this->Elements[NET_DIME_TYPE_LEN]);
$this->_haveType = (strlen($this->Elements[NET_DIME_TYPE]) == $this->Elements[NET_DIME_TYPE_LEN]);
if ($this->_haveType) {
$p += $this->TYPE_LENGTH;
$this->Elements[NET_DIME_DATA] = substr($data,$p,$this->Elements[NET_DIME_DATA_LEN]);
$this->_haveData = (strlen($this->Elements[NET_DIME_DATA]) == $this->Elements[NET_DIME_DATA_LEN]);
if ($this->_haveData) {
$p += $this->DATA_LENGTH;
} else {
$p += strlen($this->Elements[NET_DIME_DATA]);
}
} else {
$p += strlen($this->Elements[NET_DIME_TYPE]);
}
} else {
$p += strlen($this->Elements[NET_DIME_ID]);
}
} else {
$p += strlen($this->Elements[NET_DIME_OPTS]);
}
}
return substr($data, $p);
}
function addData(&$data)
{
$datalen = strlen($data);
$p = 0;
if (!$this->_haveOpts) {
$have = strlen($this->Elements[NET_DIME_OPTS]);
$this->Elements[NET_DIME_OPTS] .= substr($data,$p,$this->Elements[NET_DIME_OPTS_LEN]-$have);
$this->_haveOpts = (strlen($this->Elements[NET_DIME_OPTS]) == $this->Elements[DIME_OTPS_LEN]);
if (!$this->_haveOpts) return NULL;
$p += $this->OPTS_LENGTH-$have;
}
if (!$this->_haveID) {
$have = strlen($this->Elements[NET_DIME_ID]);
$this->Elements[NET_DIME_ID] .= substr($data,$p,$this->Elements[NET_DIME_ID_LEN]-$have);
$this->_haveID = (strlen($this->Elements[NET_DIME_ID]) == $this->Elements[NET_DIME_ID_LEN]);
if (!$this->_haveID) return NULL;
$p += $this->ID_LENGTH-$have;
}
if (!$this->_haveType && $p < $datalen) {
$have = strlen($this->Elements[NET_DIME_TYPE]);
$this->Elements[NET_DIME_TYPE] .= substr($data,$p,$this->Elements[NET_DIME_TYPE_LEN]-$have);
$this->_haveType = (strlen($this->Elements[NET_DIME_TYPE]) == $this->Elements[NET_DIME_TYPE_LEN]);
if (!$this->_haveType) return NULL;
$p += $this->TYPE_LENGTH-$have;
}
if (!$this->_haveData && $p < $datalen) {
$have = strlen($this->Elements[NET_DIME_DATA]);
$this->Elements[NET_DIME_DATA] .= substr($data,$p,$this->Elements[NET_DIME_DATA_LEN]-$have);
$this->_haveData = (strlen($this->Elements[NET_DIME_DATA]) == $this->Elements[NET_DIME_DATA_LEN]);
if (!$this->_haveData) return NULL;
$p += $this->DATA_LENGTH-$have;
}
return substr($data,$p);
}
}
class Net_DIME_Message extends PEAR
{
var $record_size = 4096;
#var $records =array();
var $parts = array();
var $currentPart = -1;
var $stream = NULL;
var $_currentRecord;
var $_proc = array();
var $type;
var $typestr;
var $mb = 1;
var $me = 0;
var $cf = 0;
var $id = NULL;
var $debug = FALSE;
/**
* constructor
*
* this currently takes a file pointer as provided
* by fopen
*
* TODO: integrate with the php streams stuff
*/
function __construct($stream=NULL, $record_size = 4096, $debug = FALSE)
{
$this->stream = $stream;
$this->record_size = $record_size;
$this->debug = $debug;
}
function _makeRecord(&$data, $typestr='', $id=NULL, $type=NET_DIME_TYPE_UNKNOWN)
{
$record = new Net_DIME_Record($this->debug);
if ($this->mb) {
$record->setMB();
// all subsequent records are not message begin!
$this->mb = 0;
}
if ($this->me) $record->setME();
if ($this->cf) $record->setCF();
$record->setData($data);
$record->setType($typestr,$type);
if ($id) $record->setID($id);
#if ($this->debug) {
# print str_replace('\0','*',$record->encode());
#}
return $record->encode();
}
function startChunk(&$data, $typestr='', $id=NULL, $type=NET_DIME_TYPE_UNKNOWN)
{
$this->me = 0;
$this->cf = 1;
$this->type = $type;
$this->typestr = $typestr;
if ($id) {
$this->id = $id;
} else {
$this->id = md5(time());
}
return $this->_makeRecord($data, $this->typestr, $this->id, $this->type);
}
function doChunk(&$data)
{
$this->me = 0;
$this->cf = 1;
return $this->_makeRecord($data, NULL, NULL, NET_DIME_TYPE_UNCHANGED);
}
function endChunk()
{
$this->cf = 0;
$data = NULL;
$rec = $this->_makeRecord($data, NULL, NULL, NET_DIME_TYPE_UNCHANGED);
$this->id = 0;
$this->cf = 0;
$this->id = 0;
$this->type = NET_DIME_TYPE_UNKNOWN;
$this->typestr = NULL;
return $rec;
}
function endMessage()
{
$this->me = 1;
$data = NULL;
$rec = $this->_makeRecord($data, NULL, NULL, NET_DIME_TYPE_NONE);
$this->me = 0;
$this->mb = 1;
$this->id = 0;
return $rec;
}
/**
* sendRecord
*
* given a chunk of data, it creates DIME records
* and writes them to the stream
*
*/
function sendData(&$data, $typestr='', $id=NULL, $type=NET_DIME_TYPE_UNKNOWN)
{
$len = strlen($data);
if ($len > $this->record_size) {
$chunk = substr($data, 0, $this->record_size);
$p = $this->record_size;
$rec = $this->startChunk($chunk,$typestr,$id,$type);
fwrite($this->stream, $rec);
while ($p < $len) {
$chunk = substr($data, $p, $this->record_size);
$p += $this->record_size;
$rec = $this->doChunk($chunk);
fwrite($this->stream, $rec);
}
$rec = $this->endChunk();
fwrite($this->stream, $rec);
return;
}
$rec = $this->_makeRecord($data, $typestr,$id,$type);
fwrite($this->stream, $rec);
}
function sendEndMessage()
{
$rec = $this->endMessage();
fwrite($this->stream, $rec);
}
/**
* sendFile
*
* given a filename, it reads the file,
* creates records and writes them to the stream
*
*/
function sendFile($filename, $typestr='', $id=NULL, $type=NET_DIME_TYPE_UNKNOWN)
{
$f = fopen($filename, "rb");
if ($f) {
if ($data = fread($f, $this->record_size)) {
$this->startChunk($data,$typestr,$id,$type);
}
while ($data = fread($f, $this->record_size)) {
$this->doChunk($data,$typestr,$id,$type);
}
$this->endChunk();
fclose($f);
}
}
/**
* encodeData
*
* given data, encode it in DIME
*
*/
function encodeData($data, $typestr='', $id=NULL, $type=NET_DIME_TYPE_UNKNOWN)
{
$len = strlen($data);
$resp = '';
if ($len > $this->record_size) {
$chunk = substr($data, 0, $this->record_size);
$p = $this->record_size;
$resp .= $this->startChunk($chunk,$typestr,$id,$type);
while ($p < $len) {
$chunk = substr($data, $p, $this->record_size);
$p += $this->record_size;
$resp .= $this->doChunk($chunk);
}
$resp .= $this->endChunk();
} else {
$resp .= $this->_makeRecord($data, $typestr,$id,$type);
}
return $resp;
}
/**
* sendFile
*
* given a filename, it reads the file,
* creates records and writes them to the stream
*
*/
function encodeFile($filename, $typestr='', $id=NULL, $type=NET_DIME_TYPE_UNKNOWN)
{
$f = fopen($filename, "rb");
if ($f) {
if ($data = fread($f, $this->record_size)) {
$resp = $this->startChunk($data,$typestr,$id,$type);
}
while ($data = fread($f, $this->record_size)) {
$resp = $this->doChunk($data,$typestr,$id,$type);
}
$resp = $this->endChunk();
fclose($f);
}
return $resp;
}
/**
* _processData
*
* creates Net_DIME_Records from provided data
*
*/
function _processData(&$data)
{
$leftover = NULL;
if (!$this->_currentRecord) {
$this->_currentRecord = new Net_DIME_Record($this->debug);
$data = $this->_currentRecord->decode($data);
} else {
$data = $this->_currentRecord->addData($data);
}
if ($this->_currentRecord->_haveData) {
if (count($this->parts)==0 && !$this->_currentRecord->isStart()) {
// raise an error!
return PEAR::raiseError('First Message is not a DIME begin record!');
}
if ($this->_currentRecord->isEnd() && $this->_currentRecord->getDataLength()==0) {
return NULL;
}
if ($this->currentPart < 0 && !$this->_currentRecord->isChunk()) {
$this->parts[] = array();
$this->currentPart = count($this->parts)-1;
$this->parts[$this->currentPart]['id'] = $this->_currentRecord->getID();
$this->parts[$this->currentPart]['type'] = $this->_currentRecord->getType();
$this->parts[$this->currentPart]['data'] = $this->_currentRecord->getData();
$this->currentPart = -1;
} else {
if ($this->currentPart < 0) {
$this->parts[] = array();
$this->currentPart = count($this->parts)-1;
$this->parts[$this->currentPart]['id'] = $this->_currentRecord->getID();
$this->parts[$this->currentPart]['type'] = $this->_currentRecord->getType();
$this->parts[$this->currentPart]['data'] = $this->_currentRecord->getData();
} else {
$this->parts[$this->currentPart]['data'] .= $this->_currentRecord->getData();
if (!$this->_currentRecord->isChunk()) {
// we reached the end of the chunk
$this->currentPart = -1;
}
}
}
#$this->records[] = $this->_currentRecord;
if (!$this->_currentRecord->isEnd()) $this->_currentRecord = NULL;
}
return NULL;
}
/**
* decodeData
*
* decodes a DIME encrypted string of data
*
*/
function decodeData(&$data) {
while (strlen($data) >= NET_DIME_RECORD_HEADER) {
$err = $this->_processData($data);
if (PEAR::isError($err)) {
return $err;
}
}
}
/**
* read
*
* reads the stream and creates
* an array of records
*
* it can accept the start of a previously read buffer
* this is usefull in situations where you need to read
* headers before discovering that the data is DIME encoded
* such as in the case of reading an HTTP response.
*/
function read($buf=NULL)
{
while ($data = fread($this->stream, 8192)) {
if ($buf) {
$data = $buf.$data;
$buf = NULL;
}
if ($this->debug)
echo "read: ".strlen($data)." bytes\n";
$err = $this->decodeData($data);
if (PEAR::isError($err)) {
return $err;
}
// store any leftover data to be used again
// should be < NET_DIME_RECORD_HEADER bytes
$buf = $data;
}
if (!$this->_currentRecord || !$this->_currentRecord->isEnd()) {
return PEAR::raiseError('reached stream end without end record');
}
return NULL;
}
}
?>

464
classes/pear/Net/IPv4.php Normal file
View File

@ -0,0 +1,464 @@
<?php
/**
* Class to provide IPv4 calculations
*
* PHP versions 4 and 5
*
* LICENSE: This source file is subject to version 3.01 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_01.txt. If you did not receive a copy of
* the PHP License and are unable to obtain it through the web, please
* send a note to license@php.net so we can mail you a copy immediately.
*
* @category Net
* @package Net_IPv4
* @author Eric Kilfoil <edk@ypass.net>
* @author Marco Kaiser <bate@php.net>
* @author Florian Anderiasch <fa@php.net>
* @copyright 1997-2005 The PHP Group
* @license http://www.php.net/license/3_01.txt PHP License 3.01
* @version CVS: $Id: IPv4.php,v 1.11 2005/11/29 12:56:35 fa Exp $
* @link http://pear.php.net/package/Net_IPv4
*/
require_once 'PEAR.php';
// {{{ GLOBALS
/**
* Map of bitmasks to subnets
*
* This array contains every valid netmask. The index of the dot quad
* netmask value is the corresponding CIDR notation (bitmask).
*
* @global array $GLOBALS['Net_IPv4_Netmask_Map']
*/
$GLOBALS['Net_IPv4_Netmask_Map'] = array(
0 => "0.0.0.0",
1 => "128.0.0.0",
2 => "192.0.0.0",
3 => "224.0.0.0",
4 => "240.0.0.0",
5 => "248.0.0.0",
6 => "252.0.0.0",
7 => "254.0.0.0",
8 => "255.0.0.0",
9 => "255.128.0.0",
10 => "255.192.0.0",
11 => "255.224.0.0",
12 => "255.240.0.0",
13 => "255.248.0.0",
14 => "255.252.0.0",
15 => "255.254.0.0",
16 => "255.255.0.0",
17 => "255.255.128.0",
18 => "255.255.192.0",
19 => "255.255.224.0",
20 => "255.255.240.0",
21 => "255.255.248.0",
22 => "255.255.252.0",
23 => "255.255.254.0",
24 => "255.255.255.0",
25 => "255.255.255.128",
26 => "255.255.255.192",
27 => "255.255.255.224",
28 => "255.255.255.240",
29 => "255.255.255.248",
30 => "255.255.255.252",
31 => "255.255.255.254",
32 => "255.255.255.255"
);
// }}}
// {{{ Net_IPv4
/**
* Class to provide IPv4 calculations
*
* Provides methods for validating IP addresses, calculating netmasks,
* broadcast addresses, network addresses, conversion routines, etc.
*
* @category Net
* @package Net_IPv4
* @author Eric Kilfoil <edk@ypass.net>
* @author Marco Kaiser <bate@php.net>
* @author Florian Anderiasch <fa@php.net>
* @copyright 1997-2005 The PHP Group
* @license http://www.php.net/license/3_01.txt PHP License 3.01
* @version CVS: @package_version@
* @link http://pear.php.net/package/Net_IPv4
* @access public
*/
class Net_IPv4
{
// {{{ properties
var $ip = "";
var $bitmask = false;
var $netmask = "";
var $network = "";
var $broadcast = "";
var $long = 0;
// }}}
// {{{ validateIP()
/**
* Validate the syntax of the given IP adress
*
* Using the PHP long2ip() and ip2long() functions, convert the IP
* address from a string to a long and back. If the original still
* matches the converted IP address, it's a valid address. This
* function does not allow for IP addresses to be formatted as long
* integers.
*
* @param string $ip IP address in the format x.x.x.x
* @return bool true if syntax is valid, otherwise false
*/
static function validateIP($ip)
{
if ($ip == long2ip(ip2long($ip))) {
return true;
} else {
return false;
}
}
// }}}
// {{{ check_ip()
/**
* Validate the syntax of the given IP address (compatibility)
*
* This function is identical to Net_IPv4::validateIP(). It is included
* merely for compatibility reasons.
*
* @param string $ip IP address
* @return bool true if syntax is valid, otherwise false
*/
function check_ip($ip)
{
return $this->validateIP($ip);
}
// }}}
// {{{ validateNetmask()
/**
* Validate the syntax of a four octet netmask
*
* There are 33 valid netmask values. This function will compare the
* string passed as $netmask to the predefined 33 values and return
* true or false. This is most likely much faster than performing the
* calculation to determine the validity of the netmask.
*
* @param string $netmask Netmask
* @return bool true if syntax is valid, otherwise false
*/
function validateNetmask($netmask)
{
if (! in_array($netmask, $GLOBALS['Net_IPv4_Netmask_Map'])) {
return false;
}
return true;
}
// }}}
// {{{ parseAddress()
/**
* Parse a formatted IP address
*
* Given a network qualified IP address, attempt to parse out the parts
* and calculate qualities of the address.
*
* The following formats are possible:
*
* [dot quad ip]/[ bitmask ]
* [dot quad ip]/[ dot quad netmask ]
* [dot quad ip]/[ hex string netmask ]
*
* The first would be [IP Address]/[BitMask]:
* 192.168.0.0/16
*
* The second would be [IP Address] [Subnet Mask in dot quad notation]:
* 192.168.0.0/255.255.0.0
*
* The third would be [IP Address] [Subnet Mask as Hex string]
* 192.168.0.0/ffff0000
*
* Usage:
*
* $cidr = '192.168.0.50/16';
* $net = Net_IPv4::parseAddress($cidr);
* echo $net->network; // 192.168.0.0
* echo $net->ip; // 192.168.0.50
* echo $net->broadcast; // 192.168.255.255
* echo $net->bitmask; // 16
* echo $net->long; // 3232235520 (long/double version of 192.168.0.50)
* echo $net->netmask; // 255.255.0.0
*
* @param string $ip IP address netmask combination
* @return object true if syntax is valid, otherwise false
*/
static function parseAddress($address)
{
$myself = new Net_IPv4;
if (strchr($address, "/")) {
$parts = explode("/", $address);
if (! $myself->validateIP($parts[0])) {
return PEAR::raiseError("invalid IP address");
}
$myself->ip = $parts[0];
// Check the style of netmask that was entered
/*
* a hexadecimal string was entered
*/
//if (eregi("^([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$", $parts[1], $regs)) {
if (preg_match("/^([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i", $parts[1], $regs)) {
// hexadecimal string
$myself->netmask = hexdec($regs[1]) . "." . hexdec($regs[2]) . "." .
hexdec($regs[3]) . "." . hexdec($regs[4]);
/*
* a standard dot quad netmask was entered.
*/
} else if (strchr($parts[1], ".")) {
if (! $myself->validateNetmask($parts[1])) {
return PEAR::raiseError("invalid netmask value");
}
$myself->netmask = $parts[1];
/*
* a CIDR bitmask type was entered
*/
} else if ($parts[1] >= 0 && $parts[1] <= 32) {
// bitmask was entered
$myself->bitmask = $parts[1];
/*
* Some unknown format of netmask was entered
*/
} else {
return PEAR::raiseError("invalid netmask value");
}
$myself->calculate();
return $myself;
} else if ($myself->validateIP($address)) {
$myself->ip = $address;
return $myself;
} else {
return PEAR::raiseError("invalid IP address");
}
}
// }}}
// {{{ calculate()
/**
* Calculates network information based on an IP address and netmask.
*
* Fully populates the object properties based on the IP address and
* netmask/bitmask properties. Once these two fields are populated,
* calculate() will perform calculations to determine the network and
* broadcast address of the network.
*
* @return mixed true if no errors occured, otherwise PEAR_Error object
*/
function calculate()
{
$validNM = $GLOBALS['Net_IPv4_Netmask_Map'];
if (! is_a($this, "net_ipv4")) {
$myself = new Net_IPv4;
return PEAR::raiseError("cannot calculate on uninstantiated Net_IPv4 class");
}
/* Find out if we were given an ip address in dot quad notation or
* a network long ip address. Whichever was given, populate the
* other field
*/
if (strlen($this->ip)) {
if (! $this->validateIP($this->ip)) {
return PEAR::raiseError("invalid IP address");
}
$this->long = $this->ip2double($this->ip);
} else if (is_numeric($this->long)) {
$this->ip = long2ip($this->long);
} else {
return PEAR::raiseError("ip address not specified");
}
/*
* Check to see if we were supplied with a bitmask or a netmask.
* Populate the other field as needed.
*/
if (strlen($this->bitmask)) {
$this->netmask = $validNM[$this->bitmask];
} else if (strlen($this->netmask)) {
$validNM_rev = array_flip($validNM);
$this->bitmask = $validNM_rev[$this->netmask];
} else {
return PEAR::raiseError("netmask or bitmask are required for calculation");
}
$this->network = long2ip(ip2long($this->ip) & ip2long($this->netmask));
$this->broadcast = long2ip(ip2long($this->ip) |
(ip2long($this->netmask) ^ ip2long("255.255.255.255")));
return true;
}
// }}}
// {{{ getNetmask()
function getNetmask($length)
{
if (! PEAR::isError($ipobj = Net_IPv4::parseAddress("0.0.0.0/" . $length))) {
$mask = $ipobj->netmask;
unset($ipobj);
return $mask;
}
return false;
}
// }}}
// {{{ getNetLength()
function getNetLength($netmask)
{
if (! PEAR::isError($ipobj = Net_IPv4::parseAddress("0.0.0.0/" . $netmask))) {
$bitmask = $ipobj->bitmask;
unset($ipobj);
return $bitmask;
}
return false;
}
// }}}
// {{{ getSubnet()
function getSubnet($ip, $netmask)
{
if (! PEAR::isError($ipobj = Net_IPv4::parseAddress($ip . "/" . $netmask))) {
$net = $ipobj->network;
unset($ipobj);
return $net;
}
return false;
}
// }}}
// {{{ inSameSubnet()
function inSameSubnet($ip1, $ip2)
{
if (! is_object($ip1) || strcasecmp(get_class($ip1), 'net_ipv4') <> 0) {
$ipobj1 = Net_IPv4::parseAddress($ip1);
if (PEAR::isError($ipobj)) {
return PEAR::raiseError("IP addresses must be an understood format or a Net_IPv4 object");
}
}
if (! is_object($ip2) || strcasecmp(get_class($ip2), 'net_ipv4') <> 0) {
$ipobj2 = Net_IPv4::parseAddress($ip2);
if (PEAR::isError($ipobj)) {
return PEAR::raiseError("IP addresses must be an understood format or a Net_IPv4 object");
}
}
if ($ipobj1->network == $ipobj2->network &&
$ipobj1->bitmask == $ipobj2->bitmask) {
return true;
}
return false;
}
// }}}
// {{{ atoh()
/**
* Converts a dot-quad formatted IP address into a hexadecimal string
* @param string $addr IP-adress in dot-quad format
* @return mixed false if invalid IP and hexadecimal representation as string if valid
*/
function atoh($addr)
{
if (! Net_IPv4::validateIP($addr)) {
return false;
}
$ap = explode(".", $addr);
return sprintf("%02x%02x%02x%02x", $ap[0], $ap[1], $ap[2], $ap[3]);
}
// }}}
// {{{ htoa()
/**
* Converts a hexadecimal string into a dot-quad formatted IP address
* @param string $addr IP-adress in hexadecimal format
* @return mixed false if invalid IP and dot-quad formatted IP as string if valid
*/
function htoa($addr)
{
//if (eregi("^([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$",
if (preg_match("/^([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i",
$addr, $regs)) {
return hexdec($regs[1]) . "." . hexdec($regs[2]) . "." .
hexdec($regs[3]) . "." . hexdec($regs[4]);
}
return false;
}
// }}}
// {{{ ip2double()
/**
* Converts an IP address to a PHP double. Better than ip2long because
* a long in PHP is a signed integer.
* @param string $ip dot-quad formatted IP adress
* @return float IP adress as double - positive value unlike ip2long
*/
static function ip2double($ip)
{
return (double)(sprintf("%u", ip2long($ip)));
}
// }}}
// {{{ ipInNetwork()
/**
* Determines whether or not the supplied IP is within the supplied network.
*
* This function determines whether an IP address is within a network.
* The IP address ($ip) must be supplied in dot-quad format, and the
* network ($network) may be either a string containing a CIDR
* formatted network definition, or a Net_IPv4 object.
*
* @param string $ip A dot quad representation of an IP address
* @param string $network A string representing the network in CIDR format or a Net_IPv4 object.
* @return bool true if the IP address exists within the network
*/
static function ipInNetwork($ip, $network)
{
if (! is_object($network) || strcasecmp(get_class($network), 'net_ipv4') <> 0) {
$network = Net_IPv4::parseAddress($network);
}
if ( !is_object($network) OR ( is_object($network) AND ( !isset($network->network) OR !isset($network->broadcast) ) ) ) {
return false;
}
$net = Net_IPv4::ip2double($network->network);
$bcast = Net_IPv4::ip2double($network->broadcast);
$ip = Net_IPv4::ip2double($ip);
unset($network);
if ($ip >= $net && $ip <= $bcast) {
return true;
}
return false;
}
// }}}
}
// }}}
/*
* vim: sts=4 ts=4 sw=4 cindent fdm=marker
*/
?>

1102
classes/pear/Net/IPv6.php Normal file

File diff suppressed because it is too large Load Diff

1226
classes/pear/Net/POP3.php Normal file

File diff suppressed because it is too large Load Diff

1254
classes/pear/Net/SMTP.php Normal file

File diff suppressed because it is too large Load Diff

686
classes/pear/Net/Socket.php Normal file
View File

@ -0,0 +1,686 @@
<?php
/**
* Net_Socket
*
* PHP Version 4
*
* Copyright (c) 1997-2013 The PHP Group
*
* This source file is subject to version 2.0 of the PHP license,
* that is bundled with this package in the file LICENSE, and is
* available at through the world-wide-web at
* http://www.php.net/license/2_02.txt.
* If you did not receive a copy of the PHP license and are unable to
* obtain it through the world-wide-web, please send a note to
* license@php.net so we can mail you a copy immediately.
*
* Authors: Stig Bakken <ssb@php.net>
* Chuck Hagenbuch <chuck@horde.org>
*
* @category Net
* @package Net_Socket
* @author Stig Bakken <ssb@php.net>
* @author Chuck Hagenbuch <chuck@horde.org>
* @copyright 1997-2003 The PHP Group
* @license http://www.php.net/license/2_02.txt PHP 2.02
* @link http://pear.php.net/packages/Net_Socket
*/
require_once 'PEAR.php';
define('NET_SOCKET_READ', 1);
define('NET_SOCKET_WRITE', 2);
define('NET_SOCKET_ERROR', 4);
/**
* Generalized Socket class.
*
* @category Net
* @package Net_Socket
* @author Stig Bakken <ssb@php.net>
* @author Chuck Hagenbuch <chuck@horde.org>
* @copyright 1997-2003 The PHP Group
* @license http://www.php.net/license/2_02.txt PHP 2.02
* @link http://pear.php.net/packages/Net_Socket
*/
class Net_Socket extends PEAR
{
/**
* Socket file pointer.
* @var resource $fp
*/
var $fp = null;
/**
* Whether the socket is blocking. Defaults to true.
* @var boolean $blocking
*/
var $blocking = true;
/**
* Whether the socket is persistent. Defaults to false.
* @var boolean $persistent
*/
var $persistent = false;
/**
* The IP address to connect to.
* @var string $addr
*/
var $addr = '';
/**
* The port number to connect to.
* @var integer $port
*/
var $port = 0;
/**
* Number of seconds to wait on socket operations before assuming
* there's no more data. Defaults to no timeout.
* @var integer|float $timeout
*/
var $timeout = null;
/**
* Number of bytes to read at a time in readLine() and
* readAll(). Defaults to 2048.
* @var integer $lineLength
*/
var $lineLength = 2048;
/**
* The string to use as a newline terminator. Usually "\r\n" or "\n".
* @var string $newline
*/
var $newline = "\r\n";
/**
* Connect to the specified port. If called when the socket is
* already connected, it disconnects and connects again.
*
* @param string $addr IP address or host name (may be with protocol prefix).
* @param integer $port TCP port number.
* @param boolean $persistent (optional) Whether the connection is
* persistent (kept open between requests
* by the web server).
* @param integer $timeout (optional) Connection socket timeout.
* @param array $options See options for stream_context_create.
*
* @access public
*
* @return boolean|PEAR_Error True on success or a PEAR_Error on failure.
*/
function connect($addr, $port = 0, $persistent = null,
$timeout = null, $options = null)
{
if (is_resource($this->fp)) {
@fclose($this->fp);
$this->fp = null;
}
if (!$addr) {
return $this->raiseError('$addr cannot be empty');
} else if (strspn($addr, ':.0123456789') == strlen($addr)) {
$this->addr = strpos($addr, ':') !== false ? '['.$addr.']' : $addr;
} else {
$this->addr = $addr;
}
$this->port = $port % 65536;
if ($persistent !== null) {
$this->persistent = $persistent;
}
$openfunc = $this->persistent ? 'pfsockopen' : 'fsockopen';
$errno = 0;
$errstr = '';
$old_track_errors = @ini_set('track_errors', 1);
if ($timeout <= 0) {
$timeout = @ini_get('default_socket_timeout');
}
if ($options && function_exists('stream_context_create')) {
$context = stream_context_create($options);
// Since PHP 5 fsockopen doesn't allow context specification
if (function_exists('stream_socket_client')) {
$flags = STREAM_CLIENT_CONNECT;
if ($this->persistent) {
$flags = STREAM_CLIENT_PERSISTENT;
}
$addr = $this->addr . ':' . $this->port;
$fp = stream_socket_client($addr, $errno, $errstr,
$timeout, $flags, $context);
} else {
$fp = @$openfunc($this->addr, $this->port, $errno,
$errstr, $timeout, $context);
}
} else {
$fp = @$openfunc($this->addr, $this->port, $errno, $errstr, $timeout);
}
if (!$fp) {
if ($errno == 0 && !strlen($errstr) && isset($php_errormsg)) {
$errstr = $php_errormsg;
}
@ini_set('track_errors', $old_track_errors);
return $this->raiseError($errstr, $errno);
}
@ini_set('track_errors', $old_track_errors);
$this->fp = $fp;
$this->setTimeout();
return $this->setBlocking($this->blocking);
}
/**
* Disconnects from the peer, closes the socket.
*
* @access public
* @return mixed true on success or a PEAR_Error instance otherwise
*/
function disconnect()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
@fclose($this->fp);
$this->fp = null;
return true;
}
/**
* Set the newline character/sequence to use.
*
* @param string $newline Newline character(s)
* @return boolean True
*/
function setNewline($newline)
{
$this->newline = $newline;
return true;
}
/**
* Find out if the socket is in blocking mode.
*
* @access public
* @return boolean The current blocking mode.
*/
function isBlocking()
{
return $this->blocking;
}
/**
* Sets whether the socket connection should be blocking or
* not. A read call to a non-blocking socket will return immediately
* if there is no data available, whereas it will block until there
* is data for blocking sockets.
*
* @param boolean $mode True for blocking sockets, false for nonblocking.
*
* @access public
* @return mixed true on success or a PEAR_Error instance otherwise
*/
function setBlocking($mode)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$this->blocking = $mode;
stream_set_blocking($this->fp, (int)$this->blocking);
return true;
}
/**
* Sets the timeout value on socket descriptor,
* expressed in the sum of seconds and microseconds
*
* @param integer $seconds Seconds.
* @param integer $microseconds Microseconds, optional.
*
* @access public
* @return mixed True on success or false on failure or
* a PEAR_Error instance when not connected
*/
function setTimeout($seconds = null, $microseconds = null)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
if ($seconds === null && $microseconds === null) {
$seconds = (int) $this->timeout;
$microseconds = (int) (($this->timeout - $seconds) * 1000000);
} else {
$this->timeout = $seconds + $microseconds/1000000;
}
if ($this->timeout > 0) {
return stream_set_timeout($this->fp, (int) $seconds, (int) $microseconds);
}
else {
return false;
}
}
/**
* Sets the file buffering size on the stream.
* See php's stream_set_write_buffer for more information.
*
* @param integer $size Write buffer size.
*
* @access public
* @return mixed on success or an PEAR_Error object otherwise
*/
function setWriteBuffer($size)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$returned = stream_set_write_buffer($this->fp, $size);
if ($returned == 0) {
return true;
}
return $this->raiseError('Cannot set write buffer.');
}
/**
* Returns information about an existing socket resource.
* Currently returns four entries in the result array:
*
* <p>
* timed_out (bool) - The socket timed out waiting for data<br>
* blocked (bool) - The socket was blocked<br>
* eof (bool) - Indicates EOF event<br>
* unread_bytes (int) - Number of bytes left in the socket buffer<br>
* </p>
*
* @access public
* @return mixed Array containing information about existing socket
* resource or a PEAR_Error instance otherwise
*/
function getStatus()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return stream_get_meta_data($this->fp);
}
/**
* Get a specified line of data
*
* @param int $size Reading ends when size - 1 bytes have been read,
* or a newline or an EOF (whichever comes first).
* If no size is specified, it will keep reading from
* the stream until it reaches the end of the line.
*
* @access public
* @return mixed $size bytes of data from the socket, or a PEAR_Error if
* not connected. If an error occurs, FALSE is returned.
*/
function gets($size = null)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
if (is_null($size)) {
return @fgets($this->fp);
} else {
return @fgets($this->fp, $size);
}
}
/**
* Read a specified amount of data. This is guaranteed to return,
* and has the added benefit of getting everything in one fread()
* chunk; if you know the size of the data you're getting
* beforehand, this is definitely the way to go.
*
* @param integer $size The number of bytes to read from the socket.
*
* @access public
* @return $size bytes of data from the socket, or a PEAR_Error if
* not connected.
*/
function read($size)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return @fread($this->fp, $size);
}
/**
* Write a specified amount of data.
*
* @param string $data Data to write.
* @param integer $blocksize Amount of data to write at once.
* NULL means all at once.
*
* @access public
* @return mixed If the socket is not connected, returns an instance of
* PEAR_Error.
* If the write succeeds, returns the number of bytes written.
* If the write fails, returns false.
* If the socket times out, returns an instance of PEAR_Error.
*/
function write($data, $blocksize = null)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
if (is_null($blocksize) && !OS_WINDOWS) {
$written = @fwrite($this->fp, $data);
// Check for timeout or lost connection
if (!$written) {
$meta_data = $this->getStatus();
if (!is_array($meta_data)) {
return $meta_data; // PEAR_Error
}
if (!empty($meta_data['timed_out'])) {
return $this->raiseError('timed out');
}
}
return $written;
} else {
if (is_null($blocksize)) {
$blocksize = 1024;
}
$pos = 0;
$size = strlen($data);
while ($pos < $size) {
$written = @fwrite($this->fp, substr($data, $pos, $blocksize));
// Check for timeout or lost connection
if (!$written) {
$meta_data = $this->getStatus();
if (!is_array($meta_data)) {
return $meta_data; // PEAR_Error
}
if (!empty($meta_data['timed_out'])) {
return $this->raiseError('timed out');
}
return $written;
}
$pos += $written;
}
return $pos;
}
}
/**
* Write a line of data to the socket, followed by a trailing newline.
*
* @param string $data Data to write
*
* @access public
* @return mixed fwrite() result, or PEAR_Error when not connected
*/
function writeLine($data)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return fwrite($this->fp, $data . $this->newline);
}
/**
* Tests for end-of-file on a socket descriptor.
*
* Also returns true if the socket is disconnected.
*
* @access public
* @return bool
*/
function eof()
{
return (!is_resource($this->fp) || feof($this->fp));
}
/**
* Reads a byte of data
*
* @access public
* @return 1 byte of data from the socket, or a PEAR_Error if
* not connected.
*/
function readByte()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return ord(@fread($this->fp, 1));
}
/**
* Reads a word of data
*
* @access public
* @return 1 word of data from the socket, or a PEAR_Error if
* not connected.
*/
function readWord()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$buf = @fread($this->fp, 2);
return (ord($buf[0]) + (ord($buf[1]) << 8));
}
/**
* Reads an int of data
*
* @access public
* @return integer 1 int of data from the socket, or a PEAR_Error if
* not connected.
*/
function readInt()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$buf = @fread($this->fp, 4);
return (ord($buf[0]) + (ord($buf[1]) << 8) +
(ord($buf[2]) << 16) + (ord($buf[3]) << 24));
}
/**
* Reads a zero-terminated string of data
*
* @access public
* @return string, or a PEAR_Error if
* not connected.
*/
function readString()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$string = '';
while (($char = @fread($this->fp, 1)) != "\x00") {
$string .= $char;
}
return $string;
}
/**
* Reads an IP Address and returns it in a dot formatted string
*
* @access public
* @return Dot formatted string, or a PEAR_Error if
* not connected.
*/
function readIPAddress()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$buf = @fread($this->fp, 4);
return sprintf('%d.%d.%d.%d', ord($buf[0]), ord($buf[1]),
ord($buf[2]), ord($buf[3]));
}
/**
* Read until either the end of the socket or a newline, whichever
* comes first. Strips the trailing newline from the returned data.
*
* @access public
* @return All available data up to a newline, without that
* newline, or until the end of the socket, or a PEAR_Error if
* not connected.
*/
function readLine()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$line = '';
$timeout = time() + $this->timeout;
while (!feof($this->fp) && (!$this->timeout || time() < $timeout)) {
$line .= @fgets($this->fp, $this->lineLength);
if (substr($line, -1) == "\n") {
return rtrim($line, $this->newline);
}
}
return $line;
}
/**
* Read until the socket closes, or until there is no more data in
* the inner PHP buffer. If the inner buffer is empty, in blocking
* mode we wait for at least 1 byte of data. Therefore, in
* blocking mode, if there is no data at all to be read, this
* function will never exit (unless the socket is closed on the
* remote end).
*
* @access public
*
* @return string All data until the socket closes, or a PEAR_Error if
* not connected.
*/
function readAll()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$data = '';
while (!feof($this->fp)) {
$data .= @fread($this->fp, $this->lineLength);
}
return $data;
}
/**
* Runs the equivalent of the select() system call on the socket
* with a timeout specified by tv_sec and tv_usec.
*
* @param integer $state Which of read/write/error to check for.
* @param integer $tv_sec Number of seconds for timeout.
* @param integer $tv_usec Number of microseconds for timeout.
*
* @access public
* @return False if select fails, integer describing which of read/write/error
* are ready, or PEAR_Error if not connected.
*/
function select($state, $tv_sec, $tv_usec = 0)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$read = null;
$write = null;
$except = null;
if ($state & NET_SOCKET_READ) {
$read[] = $this->fp;
}
if ($state & NET_SOCKET_WRITE) {
$write[] = $this->fp;
}
if ($state & NET_SOCKET_ERROR) {
$except[] = $this->fp;
}
if (false === ($sr = stream_select($read, $write, $except,
$tv_sec, $tv_usec))) {
return false;
}
$result = 0;
if (count($read)) {
$result |= NET_SOCKET_READ;
}
if (count($write)) {
$result |= NET_SOCKET_WRITE;
}
if (count($except)) {
$result |= NET_SOCKET_ERROR;
}
return $result;
}
/**
* Turns encryption on/off on a connected socket.
*
* @param bool $enabled Set this parameter to true to enable encryption
* and false to disable encryption.
* @param integer $type Type of encryption. See stream_socket_enable_crypto()
* for values.
*
* @see http://se.php.net/manual/en/function.stream-socket-enable-crypto.php
* @access public
* @return false on error, true on success and 0 if there isn't enough data
* and the user should try again (non-blocking sockets only).
* A PEAR_Error object is returned if the socket is not
* connected
*/
function enableCrypto($enabled, $type)
{
if (version_compare(phpversion(), "5.1.0", ">=")) {
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return @stream_socket_enable_crypto($this->fp, $enabled, $type);
} else {
$msg = 'Net_Socket::enableCrypto() requires php version >= 5.1.0';
return $this->raiseError($msg);
}
}
}

400
classes/pear/Net/URL.php Normal file
View File

@ -0,0 +1,400 @@
<?php
// +-----------------------------------------------------------------------+
// | Copyright (c) 2002-2004, Richard Heyes |
// | All rights reserved. |
// | |
// | Redistribution and use in source and binary forms, with or without |
// | modification, are permitted provided that the following conditions |
// | are met: |
// | |
// | o Redistributions of source code must retain the above copyright |
// | notice, this list of conditions and the following disclaimer. |
// | o Redistributions in binary form must reproduce the above copyright |
// | notice, this list of conditions and the following disclaimer in the |
// | documentation and/or other materials provided with the distribution.|
// | o The names of the authors may not be used to endorse or promote |
// | products derived from this software without specific prior written |
// | permission. |
// | |
// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
// | |
// +-----------------------------------------------------------------------+
// | Author: Richard Heyes <richard at php net> |
// +-----------------------------------------------------------------------+
//
// $Id: URL.php,v 1.36 2004/06/19 18:58:50 richard Exp $
//
// Net_URL Class
class Net_URL
{
/**
* Full url
* @var string
*/
var $url;
/**
* Protocol
* @var string
*/
var $protocol;
/**
* Username
* @var string
*/
var $username;
/**
* Password
* @var string
*/
var $password;
/**
* Host
* @var string
*/
var $host;
/**
* Port
* @var integer
*/
var $port;
/**
* Path
* @var string
*/
var $path;
/**
* Query string
* @var array
*/
var $querystring;
/**
* Anchor
* @var string
*/
var $anchor;
/**
* Whether to use []
* @var bool
*/
var $useBrackets;
/**
* PHP5 Constructor
*
* Parses the given url and stores the various parts
* Defaults are used in certain cases
*
* @param string $url Optional URL
* @param bool $useBrackets Whether to use square brackets when
* multiple querystrings with the same name
* exist
*/
function __construct($url = null, $useBrackets = true)
{
$HTTP_SERVER_VARS = !empty($_SERVER) ? $_SERVER : $GLOBALS['HTTP_SERVER_VARS'];
$this->useBrackets = $useBrackets;
$this->url = $url;
$this->user = '';
$this->pass = '';
$this->host = '';
$this->port = 80;
$this->path = '';
$this->querystring = array();
$this->anchor = '';
// Only use defaults if not an absolute URL given
if (!preg_match('/^[a-z0-9]+:\/\//i', $url)) {
$this->protocol = (@$HTTP_SERVER_VARS['HTTPS'] == 'on' ? 'https' : 'http');
/**
* Figure out host/port
*/
if (!empty($HTTP_SERVER_VARS['HTTP_HOST']) AND preg_match('/^(.*)(:([0-9]+))?$/U', $HTTP_SERVER_VARS['HTTP_HOST'], $matches)) {
$host = $matches[1];
if (!empty($matches[3])) {
$port = $matches[3];
} else {
$port = $this->getStandardPort($this->protocol);
}
}
$this->user = '';
$this->pass = '';
$this->host = !empty($host) ? $host : (isset($HTTP_SERVER_VARS['SERVER_NAME']) ? $HTTP_SERVER_VARS['SERVER_NAME'] : 'localhost');
$this->port = !empty($port) ? $port : (isset($HTTP_SERVER_VARS['SERVER_PORT']) ? $HTTP_SERVER_VARS['SERVER_PORT'] : $this->getStandardPort($this->protocol));
$this->path = !empty($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : '/';
$this->querystring = isset($HTTP_SERVER_VARS['QUERY_STRING']) ? $this->_parseRawQuerystring($HTTP_SERVER_VARS['QUERY_STRING']) : null;
$this->anchor = '';
}
// Parse the url and store the various parts
if (!empty($url)) {
$urlinfo = parse_url($url);
// Default querystring
$this->querystring = array();
foreach ($urlinfo as $key => $value) {
switch ($key) {
case 'scheme':
$this->protocol = $value;
$this->port = $this->getStandardPort($value);
break;
case 'user':
case 'pass':
case 'host':
case 'port':
$this->$key = $value;
break;
case 'path':
if ($value[0] == '/') {
$this->path = $value;
} else {
$path = dirname($this->path) == DIRECTORY_SEPARATOR ? '' : dirname($this->path);
$this->path = sprintf('%s/%s', $path, $value);
}
break;
case 'query':
$this->querystring = $this->_parseRawQueryString($value);
break;
case 'fragment':
$this->anchor = $value;
break;
}
}
}
}
/**
* Returns full url
*
* @return string Full url
* @access public
*/
function getURL()
{
$querystring = $this->getQueryString();
$this->url = $this->protocol . '://'
. $this->user . (!empty($this->pass) ? ':' : '')
. $this->pass . (!empty($this->user) ? '@' : '')
. $this->host . ($this->port == $this->getStandardPort($this->protocol) ? '' : ':' . $this->port)
. $this->path
. (!empty($querystring) ? '?' . $querystring : '')
. (!empty($this->anchor) ? '#' . $this->anchor : '');
return $this->url;
}
/**
* Adds a querystring item
*
* @param string $name Name of item
* @param string $value Value of item
* @param bool $preencoded Whether value is urlencoded or not, default = not
* @access public
*/
function addQueryString($name, $value, $preencoded = false)
{
if ($preencoded) {
$this->querystring[$name] = $value;
} else {
$this->querystring[$name] = is_array($value) ? array_map('rawurlencode', $value): rawurlencode($value);
}
}
/**
* Removes a querystring item
*
* @param string $name Name of item
* @access public
*/
function removeQueryString($name)
{
if (isset($this->querystring[$name])) {
unset($this->querystring[$name]);
}
}
/**
* Sets the querystring to literally what you supply
*
* @param string $querystring The querystring data. Should be of the format foo=bar&x=y etc
* @access public
*/
function addRawQueryString($querystring)
{
$this->querystring = $this->_parseRawQueryString($querystring);
}
/**
* Returns flat querystring
*
* @return string Querystring
* @access public
*/
function getQueryString()
{
if (!empty($this->querystring)) {
foreach ($this->querystring as $name => $value) {
if (is_array($value)) {
foreach ($value as $k => $v) {
$querystring[] = $this->useBrackets ? sprintf('%s[%s]=%s', $name, $k, $v) : ($name . '=' . $v);
}
} elseif (!is_null($value)) {
$querystring[] = $name . '=' . $value;
} else {
$querystring[] = $name;
}
}
$querystring = implode(ini_get('arg_separator.output'), $querystring);
} else {
$querystring = '';
}
return $querystring;
}
/**
* Parses raw querystring and returns an array of it
*
* @param string $querystring The querystring to parse
* @return array An array of the querystring data
* @access private
*/
function _parseRawQuerystring($querystring)
{
$parts = preg_split('/[' . preg_quote(ini_get('arg_separator.input'), '/') . ']/', $querystring, -1, PREG_SPLIT_NO_EMPTY);
$return = array();
foreach ($parts as $part) {
if (strpos($part, '=') !== false) {
$value = substr($part, strpos($part, '=') + 1);
$key = substr($part, 0, strpos($part, '='));
} else {
$value = null;
$key = $part;
}
if (substr($key, -2) == '[]') {
$key = substr($key, 0, -2);
if (@!is_array($return[$key])) {
$return[$key] = array();
$return[$key][] = $value;
} else {
$return[$key][] = $value;
}
} elseif (!$this->useBrackets AND !empty($return[$key])) {
$return[$key] = (array)$return[$key];
$return[$key][] = $value;
} else {
$return[$key] = $value;
}
}
return $return;
}
/**
* Resolves //, ../ and ./ from a path and returns
* the result. Eg:
*
* /foo/bar/../boo.php => /foo/boo.php
* /foo/bar/../../boo.php => /boo.php
* /foo/bar/.././/boo.php => /foo/boo.php
*
* This method can also be called statically.
*
* @param string $url URL path to resolve
* @return string The result
*/
static function resolvePath($path)
{
$path = explode('/', str_replace('//', '/', $path));
for ($i=0; $i<count($path); $i++) {
if ($path[$i] == '.') {
unset($path[$i]);
$path = array_values($path);
$i--;
} elseif ($path[$i] == '..' AND ($i > 1 OR ($i == 1 AND $path[0] != '') ) ) {
unset($path[$i]);
unset($path[$i-1]);
$path = array_values($path);
$i -= 2;
} elseif ($path[$i] == '..' AND $i == 1 AND $path[0] == '') {
unset($path[$i]);
$path = array_values($path);
$i--;
} else {
continue;
}
}
return implode('/', $path);
}
/**
* Returns the standard port number for a protocol
*
* @param string $scheme The protocol to lookup
* @return integer Port number or NULL if no scheme matches
*
* @author Philippe Jausions <Philippe.Jausions@11abacus.com>
*/
function getStandardPort($scheme)
{
switch (strtolower($scheme)) {
case 'http': return 80;
case 'https': return 443;
case 'ftp': return 21;
case 'imap': return 143;
case 'imaps': return 993;
case 'pop3': return 110;
case 'pop3s': return 995;
default: return null;
}
}
/**
* Forces the URL to a particular protocol
*
* @param string $protocol Protocol to force the URL to
* @param integer $port Optional port (standard port is used by default)
*/
function setProtocol($protocol, $port = null)
{
$this->protocol = $protocol;
$this->port = is_null($port) ? $this->getStandardPort() : $port;
}
}
?>