This commit is contained in:
Paula Quispe
2017-08-02 16:06:56 -04:00
committed by davidcallizaya
parent 8359e30998
commit 9eb7d6cac2
2289 changed files with 204853 additions and 80064 deletions

80
thirdparty/pear/Net/CheckIP.php vendored Normal file
View File

@@ -0,0 +1,80 @@
<?php
/*
* Copyright (c) 2002-2006 Martin Jansen
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* $Id: CheckIP.php,v 1.8 2006/12/15 17:42:26 mj Exp $
*/
/**
* Class to validate the syntax of IPv4 adresses
*
* Usage:
* <?php
* require_once "Net/CheckIP.php";
*
* if (Net_CheckIP::check_ip("your_ip_goes_here")) {
* // Syntax of the IP is ok
* }
* ?>
*
* @author Martin Jansen <mj@php.net>
* @author Guido Haeger <gh-lists@ecora.de>
* @package Net_CheckIP
* @version 1.1
* @access public
*/
class Net_CheckIP
{
/**
* Validate the syntax of the given IP adress
*
* This function splits the IP address in 4 pieces
* (separated by ".") and checks for each piece
* if it's an integer value between 0 and 255.
* If all 4 parameters pass this test, the function
* returns true.
*
* @param string $ip IP adress
* @return bool true if syntax is valid, otherwise false
*/
function check_ip($ip)
{
$oct = explode('.', $ip);
if (count($oct) != 4) {
return false;
}
for ($i = 0; $i < 4; $i++) {
if (!preg_match("/^[0-9]+$/", $oct[$i])) {
return false;
}
if ($oct[$i] < 0 || $oct[$i] > 255) {
return false;
}
}
return true;
}
}
?>

876
thirdparty/pear/Net/Curl.php vendored Normal file
View File

@@ -0,0 +1,876 @@
<?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;
}
}
// }}}
// {{{ Net_Curl($url = '', $userAgent = '')
/**
* Net_Curl
*
* PHP 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
* @return void
*/
function Net_Curl($url = '', $userAgent = '')
{
$this->__construct($url, $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)) {
$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
$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 (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 === true) {
$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)) {
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)) {
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)) {
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)) {
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();
}
// }}}
}
?>

647
thirdparty/pear/Net/DIME.php vendored Normal file
View File

@@ -0,0 +1,647 @@
<?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 Net_DIME_Record($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()
{
if(!class_exists('G')){
$realdocuroot = str_replace( '\\', '/', $_SERVER['DOCUMENT_ROOT'] );
$docuroot = explode( '/', $realdocuroot );
array_pop( $docuroot );
$pathhome = implode( '/', $docuroot ) . '/';
array_pop( $docuroot );
$pathTrunk = implode( '/', $docuroot ) . '/';
require_once($pathTrunk.'gulliver/system/class.g.php');
}
$id = G::encryptOld(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 Net_DIME_Message($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)
{
if(!class_exists('G')){
$realdocuroot = str_replace( '\\', '/', $_SERVER['DOCUMENT_ROOT'] );
$docuroot = explode( '/', $realdocuroot );
array_pop( $docuroot );
$pathhome = implode( '/', $docuroot ) . '/';
array_pop( $docuroot );
$pathTrunk = implode( '/', $docuroot ) . '/';
require_once($pathTrunk.'gulliver/system/class.g.php');
}
$this->me = 0;
$this->cf = 1;
$this->type = $type;
$this->typestr = $typestr;
if ($id) {
$this->id = $id;
} else {
$this->id = G::encryptOld(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;
}
}
?>

2346
thirdparty/pear/Net/FTP.php vendored Normal file

File diff suppressed because it is too large Load Diff

116
thirdparty/pear/Net/FTP/Observer.php vendored Normal file
View File

@@ -0,0 +1,116 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Net_FTP observer.
*
* This class implements the Observer part of a Subject-Observer
* design pattern. It listens to the events sent by a Net_FTP instance.
* This module had many influences from the Log_observer code.
*
* PHP versions 4 and 5
*
* LICENSE: This source file is subject to version 3.0 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_0.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 Networking
* @package FTP
* @author Tobias Schlitt <toby@php.net>
* @author Laurent Laville <pear@laurent-laville.org>
* @author Chuck Hagenbuch <chuck@horde.org>
* @copyright 1997-2008 The PHP Group
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version CVS: $Id: Observer.php,v 1.4.2.1 2008/01/07 14:21:22 jschippers Exp $
* @link http://pear.php.net/package/Net_FTP
* @since File available since Release 0.0.1
*/
/**
* This class implements the Observer part of a Subject-Observer
* design pattern. It listens to the events sent by a Net_FTP instance.
* This module had many influences from the Log_observer code.
*
* @category Networking
* @package FTP
* @author Laurent Laville <pear@laurent-laville.org>
* @author Chuck Hagenbuch <chuck@horde.org>
* @author Tobias Schlitt <toby@php.net>
* @copyright 1997-2008 The PHP Group
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version Release: 1.3.7
* @link http://pear.php.net/package/Net_FTP
* @since 1.3.0.0
* @access public
*
* @example observer_upload.php An example of Net_FTP_Observer implementation.
*/
class Net_FTP_Observer
{
/**
* Instance-specific unique identification number.
*
* @var integer
* @since 1.3.0
* @access private
*/
var $_id;
/**
* Creates a new basic Net_FTP_Observer instance.
*
* @since 1.3.0
* @access public
*/
function Net_FTP_Observer()
{
$this->_id = $this->encryptOld(microtime());
}
/**
* Returns the listener's identifier
*
* @return string The listener's identifier
* @since 1.3.0
* @access public
*/
function getId()
{
return $this->_id;
}
/**
* This is a stub method to make sure that Net_FTP_Observer classes do
* something when they are notified of a message. The default behavior
* is to just do nothing.
* You should override this method.
*
* @param mixed $event A hash describing the net event.
*
* @since 1.3.0
* @access public
* @return void
*/
function notify($event)
{
return;
}
public function encryptOld($string)
{
if (!class_exists('G')) {
$realdocuroot = str_replace( '\\', '/', $_SERVER['DOCUMENT_ROOT'] );
$docuroot = explode( '/', $realdocuroot );
array_pop( $docuroot );
$pathhome = implode( '/', $docuroot ) . '/';
array_pop( $docuroot );
$pathTrunk = implode( '/', $docuroot ) . '/';
require_once($pathTrunk.'gulliver/system/class.g.php');
}
return G::encryptOld($string);
}
}
?>

800
thirdparty/pear/Net/FTP/Socket.php vendored Normal file
View File

@@ -0,0 +1,800 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Net_FTP socket implementation of FTP functions.
*
* The functions in this file emulate the ext/FTP functions through
* ext/Socket.
*
* PHP versions 4 and 5
*
* LICENSE: This source file is subject to version 3.0 of the PHP license
* that is available through the world-wide-web at the following URI:
* http://www.php.net/license/3_0.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 Networking
* @package FTP
* @author Tobias Schlitt <toby@php.net>
* @copyright 1997-2008 The PHP Group
* @license http://www.php.net/license/3_0.txt PHP License 3.0
* @version CVS: $Id: Socket.php,v 1.5.2.2 2008/04/22 19:47:08 jschippers Exp $
* @link http://pear.php.net/package/Net_FTP
* @since File available since Release 0.0.1
*/
error_reporting(E_ALL);
/**
* Default FTP extension constants
*/
define('FTP_ASCII', 0);
define('FTP_TEXT', 0);
define('FTP_BINARY', 1);
define('FTP_IMAGE', 1);
define('FTP_TIMEOUT_SEC', 0);
/**
* What needs to be done overall?
* #1 Install the rest of these functions
* #2 Document better
* #3 Alot of other things I don't remember
*/
/*
* !!! NOTE !!!
* Most of the comment's are "not working",
* meaning they are not all up-to-date
* !!! NOTE !!!
*/
/**
* &resource ftp_connect ( string host [, int port [, int timeout ] ] );
*
* Opens an FTP connection and return resource or false on failure.
*
* FTP Success respons code: 220
*
* @param string $host Host to connect to
* @param int $port Optional, port to connect to
* @param int $timeout Optional, seconds until function timeouts
*
* @todo The FTP extension has ftp_get_option() function which returns the
* timeout variable. This function needs to be created and contain it as
* static variable.
* @todo The FTP extension has ftp_set_option() function which sets the
* timeout variable. This function needs to be created and called here.
* @access public
* @return &resource
*/
function &ftp_connect($host, $port = 21, $timeout = 90)
{
$false = false; // We are going to return refrence (E_STRICT)
if (!is_string($host) || !is_integer($port) || !is_integer($timeout)) {
return $false;
}
$control = @fsockopen($host, $port, $iError, $sError,
$timeout);
$GLOBALS['_NET_FTP']['timeout'] = $timeout;
if (!is_resource($control)) {
return $false;
}
stream_set_blocking($control, true);
stream_set_timeout($control, $timeout);
do {
$content[] = fgets($control, 8129);
$array = socket_get_status($control);
} while ($array['unread_bytes'] > 0);
if (substr($content[count($content)-1], 0, 3) == 220) {
return $control;
}
return $false;
}
/**
* boolean ftp_login ( resource stream, string username, string password );
*
* Logs in to an given FTP connection stream.
* Returns TRUE on success or FALSE on failure.
*
* NOTE:
* Username and password are *not* optional. Function will *not*
* assume "anonymous" if username and/or password is empty
*
* FTP Success respons code: 230
*
* @param resource &$control FTP resource to login to
* @param string $username FTP Username to be used
* @param string $password FTP Password to be used
*
* @access public
* @return boolean
*/
function ftp_login(&$control, $username, $password)
{
if (!is_resource($control) || is_null($username)) {
return false;
}
fputs($control, 'USER '.$username."\r\n");
$contents = array();
do {
$contents[] = fgets($control, 8192);
$array = socket_get_status($control);
} while ($array['unread_bytes'] > 0);
if (substr($contents[count($contents)-1], 0, 3) != 331) {
return false;
}
fputs($control, 'PASS '.$password."\r\n");
$contents = array();
do {
$contents[] = fgets($control, 8192);
$array = socket_get_status($control);
} while ($array['unread_bytes']);
if (substr($contents[count($contents)-1], 0, 3) == 230) {
return true;
}
trigger_error('ftp_login() [<a href="function.ftp-login">function.ftp-login'.
'</a>]: '.$contents[count($contents)-1], E_USER_WARNING);
return false;
}
/**
* boolean ftp_quit ( resource stream );
*
* Closes FTP connection.
* Returns TRUE or FALSE on error.
*
* NOTE: The PHP function ftp_quit is *alias* to ftp_close, here it is
* the *other-way-around* ( ftp_close() is alias to ftp_quit() ).
*
* NOTE:
* resource is set to null since unset() can't unset the variable.
*
* @param resource &$control FTP resource
*
* @access public
* @return boolean
*/
function ftp_quit(&$control)
{
if (!is_resource($control)) {
return false;
}
fputs($control, 'QUIT'."\r\n");
fclose($control);
$control = null;
return true;
}
/**
* Alias to ftp_quit()
*
* @param resource &$control FTP resource
*
* @see ftp_quit()
* @access public
* @return boolean
*/
function ftp_close(&$control)
{
return ftp_quit($control);
}
/**
* string ftp_pwd ( resource stream );
*
* Gets the current directory name.
* Returns the current directory.
*
* Needs data connection: NO
* Success response code: 257
*
* @param resource &$control FTP resource
*
* @access public
* @return string
*/
function ftp_pwd(&$control)
{
if (!is_resource($control)) {
return $control;
}
fputs($control, 'PWD'."\r\n");
$content = array();
do {
$content[] = fgets($control, 8192);
$array = socket_get_status($control);
} while ($array['unread_bytes'] > 0);
if (substr($cont = $content[count($content)-1], 0, 3) == 257) {
$pos = strpos($cont, '"')+1;
$pos2 = strrpos($cont, '"') - $pos;
$path = substr($cont, $pos, $pos2);
return $path;
}
return false;
}
/**
* boolean ftp_chdir ( resource stream, string directory );
*
* Changes the current directory to the specified directory.
* Returns TRUE on success or FALSE on failure.
*
* FTP success response code: 250
* Needs data connection: NO
*
* @param resource &$control FTP stream
* @param string $pwd Directory name
*
* @access public
* @return boolean
*/
function ftp_chdir(&$control, $pwd)
{
if (!is_resource($control) || !is_string($pwd)) {
return false;
}
fputs($control, 'CWD '.$pwd."\r\n");
$content = array();
do {
$content[] = fgets($control, 8192);
$array = socket_get_status($control);
} while ($array['unread_bytes'] > 0);
if (substr($content[count($content)-1], 0, 3) == 250) {
return true;
}
trigger_error('ftp_chdir() [<a
href="function.ftp-chdir">function.ftp-chdir</a>]:
' .$content[count($content)-1], E_USER_WARNING);
return false;
}
$_NET_FTP = array();
$_NET_FTP['USE_PASSIVE'] = false;
$_NET_FTP['DATA'] = null;
/**
* boolean ftp_pasv ( resource stream, boolean passive );
*
* Toggles passive mode ON/OFF.
* Returns TRUE on success or FALSE on failure.
*
* Comment:
* Although my lack of C knowlege I checked how the PHP FTP extension
* do things here. Seems like they create the data connection and store
* it in object for other functions to use.
* This is now done here.
*
* FTP success response code: 227
*
* @param stream &$control FTP stream
* @param boolean $pasv True to switch to passive, false for active mode
*
* @access public
* @return boolean
*/
function ftp_pasv(&$control, $pasv)
{
if (!is_resource($control) || !is_bool($pasv)) {
return false;
}
// If data connection exists, destroy it
if (isset($GLOBALS['_NET_FTP']['DATA'])) {
fclose($GLOBALS['_NET_FTP']['DATA']);
$GLOBALS['_NET_FTP']['DATA'] = null;
do {
fgets($control, 16);
$array = socket_get_status($control);
} while ($array['unread_bytes'] > 0);
}
// Are we suppost to create active or passive connection?
if (!$pasv) {
$GLOBALS['_NET_FTP']['USE_PASSIVE'] = false;
// Pick random "low bit"
$low = rand(39, 250);
// Pick random "high bit"
$high = rand(39, 250);
// Lowest possible port would be; 10023
// Highest possible port would be; 64246
$port = ($low<<8)+$high;
$ip = str_replace('.', ',', $_SERVER['SERVER_ADDR']);
$s = $ip.','.$low.','.$high;
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (is_resource($socket)) {
if (socket_bind($socket, '0.0.0.0', $port)) {
if (socket_listen($socket)) {
$GLOBALS['_NET_FTP']['DATA'] = &$socket;
fputs($control, 'PORT '.$s."\r\n");
$line = fgets($control, 512);
if (substr($line, 0, 3) == 200) {
return true;
}
}
}
}
return false;
}
// Since we are here, we are suppost to create passive data connection.
$i = fputs($control, 'PASV' ."\r\n");
$content = array();
do {
$content[] = fgets($control, 128);
$array = socket_get_status($control);
} while ($array['unread_bytes']);
if (substr($cont = $content[count($content)-1], 0, 3) != 227) {
return false;
}
$pos = strpos($cont, '(')+1;
$pos2 = strrpos($cont, ')')-$pos;
$string = substr($cont, $pos, $pos2);
$array = explode(',', $string);
// IP we are connecting to
$ip = $array[0]. '.' .$array[1]. '.' .$array[2]. '.' .$array[3];
// Port ( 256*lowbit + highbit
$port = ($array[4] << 8)+$array[5];
// Our data connection
$data = fsockopen($ip, $port, $iError, $sError,
$GLOBALS['_NET_FTP']['timeout']);
if (is_resource($data)) {
$GLOBALS['_NET_FTP']['USE_PASSIVE'] = true;
$GLOBALS['_NET_FTP']['DATA'] = &$data;
stream_set_blocking($data, true);
stream_set_timeout($data, $GLOBALS['_NET_FTP']['timeout']);
return true;
}
return false;
}
/**
* array ftp_rawlist ( resource stream, string directory [,bool recursive] );
*
* Returns a detailed list of files in the given directory.
*
* Needs data connection: YES
*
* @param integer &$control FTP resource
* @param string $pwd Path to retrieve
* @param boolean $recursive Optional, retrieve recursive listing
*
* @todo Enable the recursive feature.
* @access public
* @return array
*/
function ftp_rawlist(&$control, $pwd, $recursive = false)
{
if (!is_resource($control) || !is_string($pwd)) {
return false;
}
if (!isset($GLOBALS['_NET_FTP']['DATA']) ||
!is_resource($GLOBALS['_NET_FTP']['DATA'])) {
ftp_pasv($control, $GLOBALS['_NET_FTP']['USE_PASSIVE']);
}
fputs($control, 'LIST '.$pwd."\r\n");
$msg = fgets($control, 512);
if (substr($msg, 0, 3) == 425) {
return false;
}
$data = &$GLOBALS['_NET_FTP']['DATA'];
if (!$GLOBALS['_NET_FTP']['USE_PASSIVE']) {
$data = &socket_accept($data);
}
$content = array();
switch ($GLOBALS['_NET_FTP']['USE_PASSIVE']) {
case true:
while (true) {
$string = rtrim(fgets($data, 1024));
if ($string=='') {
break;
}
$content[] = $string;
}
fclose($data);
break;
case false:
$string = socket_read($data, 1024, PHP_BINARY_READ);
$content = explode("\n", $string);
unset($content[count($content)-1]);
socket_close($GLOBALS['_NET_FTP']['DATA']);
socket_close($data);
break;
}
$data = $GLOBALS['_NET_FTP']['DATA'] = null;
$f = fgets($control, 1024);
return $content;
}
/**
* string ftp_systype ( resource stream );
*
* Gets system type identifier of remote FTP server
* Returns the remote system type
*
* @param resource &$control FTP resource
*
* @access public
* @return string
*/
function ftp_systype(&$control)
{
if (!is_resource($control)) {
return false;
}
fputs($control, 'SYST'."\r\n");
$line = fgets($control, 256);
if (substr($line, 0, 3) != 215) {
return false;
}
$os = substr($line, 4, strpos($line, ' ', 4)-4);
return $os;
}
/**
* boolean ftp_alloc ( resource stream, integer bytes [, string &message ] );
*
* Allocates space for a file to be uploaded
* Return TRUE on success or FALSE on failure
*
* NOTE; Many FTP servers do not support this command and/or don't need it.
*
* FTP success respons key: Belive it's 200
* Needs data connection: NO
*
* @param resource &$control FTP stream
* @param integer $int Space to allocate
* @param string &$msg Optional, textual representation of the servers response
* will be returned by reference
*
* @access public
* @return boolean
*/
function ftp_alloc(&$control, $int, &$msg = null)
{
if (!is_resource($control) || !is_integer($int)) {
return false;
}
fputs($control, 'ALLO '.$int.' R '.$int."\r\n");
$msg = rtrim(fgets($control, 256));
$code = substr($msg, 0, 3);
if ($code == 200 || $code == 202) {
return true;
}
return false;
}
/**
* bool ftp_put ( resource stream, string remote_file, string local_file,
* int mode [, int startpos ] );
*
* Uploads a file to the FTP server
* Returns TRUE on success or FALSE on failure.
*
* NOTE:
* The transfer mode specified must be either FTP_ASCII or FTP_BINARY.
*
* @param resource &$control FTP stream
* @param string $remote Remote file to write
* @param string $local Local file to upload
* @param integer $mode Upload mode, FTP_ASCI || FTP_BINARY
* @param integer $pos Optional, start upload at position
*
* @access public
* @return boolean
*/
function ftp_put(&$control, $remote, $local, $mode, $pos = 0)
{
if (!is_resource($control) || !is_readable($local) ||
!is_integer($mode) || !is_integer($pos)) {
return false;
}
$types = array (
0 => 'A',
1 => 'I'
);
$windows = array (
0 => 't',
1 => 'b'
);
/**
* TYPE values:
* A ( ASCII )
* I ( BINARY )
* E ( EBCDIC )
* L ( BYTE )
*/
if (!isset($GLOBALS['_NET_FTP']['DATA']) ||
!is_resource($GLOBALS['_NET_FTP']['DATA'])) {
ftp_pasv($control, $GLOBALS['_NET_FTP']['USE_PASSIVE']);
}
// Establish data connection variable
$data = &$GLOBALS['_NET_FTP']['DATA'];
// Decide TYPE to use
fputs($control, 'TYPE '.$types[$mode]."\r\n");
$line = fgets($control, 256); // "Type set to TYPE"
if (substr($line, 0, 3) != 200) {
return false;
}
fputs($control, 'STOR '.$remote."\r\n");
sleep(1);
$line = fgets($control, 256); // "Opening TYPE mode data connect."
if (substr($line, 0, 3) != 150) {
return false;
}
// Creating resource to $local file
$fp = fopen($local, 'r'. $windows[$mode]);
if (!is_resource($fp)) {
$fp = null;
return false;
}
// Loop throu that file and echo it to the data socket
$i = 0;
switch ($GLOBALS['_NET_FTP']['USE_PASSIVE']) {
case false:
$data = &socket_accept($data);
while (!feof($fp)) {
$i += socket_write($data, fread($fp, 10240), 10240);
}
socket_close($data);
break;
case true:
while (!feof($fp)) {
$i += fputs($data, fread($fp, 10240), 10240);
}
fclose($data);
break;
}
$data = null;
do {
$line = fgets($control, 256);
} while (substr($line, 0, 4) != "226 ");
return true;
}
/**
* Retrieve a remote file to a local file
* Returns TRUE on success or FALSE on failure
*
* @param integer &$control Stream ID
* @param string $local Local filename
* @param string $remote Remote filename
* @param integer $mode Transfer mode (FTP_ASCII or FTP_BINARY)
* @param integer $resume Resume the file transfer or not
*
* @access public
* @return boolean
*/
function ftp_get(&$control, $local, $remote, $mode, $resume = 0, $wr='w')
{
if (!class_exists('G')) {
$realdocuroot = str_replace('\\', '/', $_SERVER['DOCUMENT_ROOT']);
$docuroot = explode('/', $realdocuroot);
array_pop($docuroot);
$pathhome = implode('/', $docuroot) . '/';
array_pop($docuroot);
$pathTrunk = implode('/', $docuroot) . '/';
require_once($pathTrunk . 'gulliver/system/class.g.php');
}
G::LoadSystem('inputfilter');
$filter = new InputFilter();
if (!is_resource($control) || !is_writable(dirname($local)) ||
!is_integer($mode) || !is_integer($resume)) {
return false;
}
$types = array (
0 => 'A',
1 => 'I'
);
$windows = array (
0 => 't',
1 => 'b'
);
if (!isset($GLOBALS['_NET_FTP']['DATA']) ||
!is_resource($GLOBALS['_NET_FTP'][ 'DATA'])) {
ftp_pasv($control, $GLOBALS['_NET_FTP']['USE_PASSIVE']);
}
$data = &$GLOBALS['NET_FTP']['DATA'];
fputs($control, 'TYPE '.$types[$mode]."\r\n");
$line = fgets($control, 256);
if (substr($line, 0, 3) != 200) {
return false;
}
if(is_file($filter->validatePath($local))) {
$var = $wr.$windows[$mode];
$fp = fopen($filter->validatePath($local), $var);
} else {
$fp = false;
}
if (!is_resource($fp)) {
$fp = null;
return false;
}
}
/**
* Changes to the parent directory
* Returns TRUE on success or FALSE on failure
*
* @param integer &$control Stream ID
*
* @access public
* @return boolean
*/
function ftp_cdup(&$control)
{
fputs($control, 'CDUP'."\r\n");
$line = fgets($control, 256);
if (substr($line, 0, 3) != 250) {
return false;
}
return true;
}
/**
* Set permissions on a file via FTP
* Returns the new file permission on success or false on error
*
* NOTE: This command is *not* supported by the standard
* NOTE: This command not ready!
*
* @param integer &$control Stream ID
* @param integer $mode Octal value
* @param string $file File to change permissions on
*
* @todo Figure out a way to chmod files via FTP
* @access public
* @return integer
*/
function ftp_chmod(&$control, $mode, $file)
{
if (!is_resource($control) || !is_integer($mode) || !is_string($file)) {
return false;
}
// chmod not in the standard, proftpd doesn't recognize it
// use SITE CHMOD?
fputs($control, 'SITE CHMOD '.$mode. ' ' .$file."\r\n");
$line = fgets($control, 256);
if (substr($line, 0, 3) == 200) {
return $mode;
}
trigger_error('ftp_chmod() [<a
href="function.ftp-chmod">function.ftp-chmod</a>]: ' .
rtrim($line), E_USER_WARNING);
return false;
}
/**
* Deletes a file on the FTP server
* Returns TRUE on success or FALSE on failure
*
* @param integer &$control Stream ID
* @param string $path File to delete
*
* @access public
* @return boolean
*/
function ftp_delete(&$control, $path)
{
if (!is_resource($control) || !is_string($path)) {
return false;
}
fputs($control, 'DELE '.$path."\r\n");
$line = fgets($control, 256);
if (substr($line, 0, 3) == 250) {
return true;
}
return false;
}
/**
* Requests execution of a program on the FTP server
* NOTE; SITE EXEC is *not* supported by the standart
* Returns TRUE on success or FALSE on error
*
* @param integer &$control Stream ID
* @param string $cmd Command to send
*
* @access public
* @todo Look a littlebit better into this
* @return boolean
*/
function ftp_exec(&$control, $cmd)
{
if (!is_resource($control) || !is_string($cmd)) {
return false;
}
// Command not defined in the standart
// proftpd doesn't recognize SITE EXEC (only help,chgrp,chmod and ratio)
fputs($control, 'SITE EXEC '.$cmd."\r\n");
$line = fgets($control, 256);
// php.net/ftp_exec uses respons code 200 to verify if command was sent
// successfully or not, so we'll just do the same
if (substr($line, 0, 3) == 200) {
return true;
}
return false;
}
?>

101
thirdparty/pear/Net/IDNA.php vendored Normal file
View File

@@ -0,0 +1,101 @@
<?php
// {{{ license
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4 foldmethod=marker: */
//
// +----------------------------------------------------------------------+
// | This library is free software; you can redistribute it and/or modify |
// | it under the terms of the GNU Lesser General Public License as |
// | published by the Free Software Foundation; either version 2.1 of the |
// | License, or (at your option) any later version. |
// | |
// | This library is distributed in the hope that it will be useful, but |
// | WITHOUT ANY WARRANTY; without even the implied warranty of |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
// | Lesser General Public License for more details. |
// | |
// | You should have received a copy of the GNU Lesser General Public |
// | License along with this library; if not, write to the Free Software |
// | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 |
// | USA. |
// +----------------------------------------------------------------------+
//
// }}}
/**
* Encode/decode Internationalized Domain Names.
* Factory class to get correct implementation either for php4 or php5.
*
* @author Markus Nix <mnix@docuverse.de>
* @author Matthias Sommerfeld <mso@phlylabs.de>
* @package Net
* @version $Id: IDNA.php,v 1.1 2008/03/22 12:39:37 neufeind Exp $
*/
class Net_IDNA
{
// {{{ factory
/**
* Attempts to return a concrete IDNA instance for either php4 or php5.
*
* @param array $params Set of paramaters
* @return object IDNA The newly created concrete Log instance, or an
* false on an error.
* @access public
*/
function &getInstance($params = array())
{
$version = explode( '.', phpversion() );
$handler = ((int)$version[0] > 4) ? 'php5' : 'php4';
$class = 'Net_IDNA_' . $handler;
$classfile = 'Net/IDNA/' . $handler . '.php';
/*
* Attempt to include our version of the named class, but don't treat
* a failure as fatal. The caller may have already included their own
* version of the named class.
*/
@include_once $classfile;
/* If the class exists, return a new instance of it. */
if (class_exists($class)) {
$instance = &new $class($params);
return $instance;
}
return false;
}
// }}}
// {{{ singleton
/**
* Attempts to return a concrete IDNA instance for either php4 or php5,
* only creating a new instance if no IDNA instance with the same
* parameters currently exists.
*
* @param array $params Set of paramaters
* @return object IDNA The newly created concrete Log instance, or an
* false on an error.
* @access public
*/
function &singleton($params = array())
{
static $instances;
if (!isset($instances)) {
$instances = array();
}
$signature = serialize($params);
if (!isset($instances[$signature])) {
$instances[$signature] = &Net_IDNA::getInstance($params);
}
return $instances[$signature];
}
// }}}
}
?>

3011
thirdparty/pear/Net/IDNA/php4.php vendored Normal file

File diff suppressed because it is too large Load Diff

3233
thirdparty/pear/Net/IDNA/php5.php vendored Normal file

File diff suppressed because it is too large Load Diff

458
thirdparty/pear/Net/IPv4.php vendored Normal file
View File

@@ -0,0 +1,458 @@
<?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: 1.3.0
* @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
*/
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
*/
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 (preg_match("/([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/", $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 (preg_match("/([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})/",
$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
*/
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
*/
function ipInNetwork($ip, $network)
{
if (! is_object($network) || strcasecmp(get_class($network), 'net_ipv4') <> 0) {
$network = Net_IPv4::parseAddress($network);
}
$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
*/
?>

218
thirdparty/pear/Net/IPv6.php vendored Normal file
View File

@@ -0,0 +1,218 @@
<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 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: Alexander Merz <alexander.merz@web.de> |
// +----------------------------------------------------------------------+
//
// $Id: IPv6.php,v 1.12 2005/09/01 12:42:00 alexmerz Exp $
/**
* Class to validate and to work with IPv6
*
* @author Alexander Merz <alexander.merz@t-online.de>
* @author elfrink at introweb dot nl
* @package Net_IPv6
* @version $Id: IPv6.php,v 1.12 2005/09/01 12:42:00 alexmerz Exp $
* @access public
*/
class Net_IPv6 {
// {{{ Uncompress()
/**
* Uncompresses an IPv6 adress
*
* RFC 2373 allows you to compress zeros in an adress to '::'. This
* function expects an valid IPv6 adress and expands the '::' to
* the required zeros.
*
* Example: FF01::101 -> FF01:0:0:0:0:0:0:101
* ::1 -> 0:0:0:0:0:0:0:1
*
* @access public
* @see Compress()
* @static
* @param string $ip a valid IPv6-adress (hex format)
* @return string the uncompressed IPv6-adress (hex format)
*/
function Uncompress($ip) {
$uip = $ip;
$c1 = -1;
$c2 = -1;
if (false !== strpos($ip, '::') ) {
list($ip1, $ip2) = explode('::', $ip);
if(""==$ip1) {
$c1 = -1;
} else {
$pos = 0;
if(0 < ($pos = substr_count($ip1, ':'))) {
$c1 = $pos;
} else {
$c1 = 0;
}
}
if(""==$ip2) {
$c2 = -1;
} else {
$pos = 0;
if(0 < ($pos = substr_count($ip2, ':'))) {
$c2 = $pos;
} else {
$c2 = 0;
}
}
if(strstr($ip2, '.')) {
$c2++;
}
if(-1 == $c1 && -1 == $c2) { // ::
$uip = "0:0:0:0:0:0:0:0";
} else if(-1==$c1) { // ::xxx
$fill = str_repeat('0:', 7-$c2);
$uip = str_replace('::', $fill, $uip);
} else if(-1==$c2) { // xxx::
$fill = str_repeat(':0', 7-$c1);
$uip = str_replace('::', $fill, $uip);
} else { // xxx::xxx
$fill = str_repeat(':0:', 6-$c2-$c1);
$uip = str_replace('::', $fill, $uip);
$uip = str_replace('::', ':', $uip);
}
}
return $uip;
}
// }}}
// {{{ Compress()
/**
* Compresses an IPv6 adress
*
* RFC 2373 allows you to compress zeros in an adress to '::'. This
* function expects an valid IPv6 adress and compresses successive zeros
* to '::'
*
* Example: FF01:0:0:0:0:0:0:101 -> FF01::101
* 0:0:0:0:0:0:0:1 -> ::1
*
* @access public
* @see Uncompress()
* @static
* @param string $ip a valid IPv6-adress (hex format)
* @return string the compressed IPv6-adress (hex format)
* @author elfrink at introweb dot nl
*/
function Compress($ip) {
$cip = $ip;
if (!strstr($ip, '::')) {
$ipp = explode(':',$ip);
for($i=0; $i<count($ipp); $i++) {
$ipp[$i] = dechex(hexdec($ipp[$i]));
}
$cip = ':' . join(':',$ipp) . ':';
preg_match_all("/(:0)+/", $cip, $zeros);
if (count($zeros[0])>0) {
$match = '';
foreach($zeros[0] as $zero) {
if (strlen($zero) > strlen($match))
$match = $zero;
}
$cip = preg_replace('/' . $match . '/', ':', $cip, 1);
}
$cip = preg_replace('/((^:)|(:$))/', '' ,$cip);
$cip = preg_replace('/((^:)|(:$))/', '::' ,$cip);
}
return $cip;
}
// }}}
// {{{ SplitV64()
/**
* Splits an IPv6 adress into the IPv6 and a possible IPv4 part
*
* RFC 2373 allows you to note the last two parts of an IPv6 adress as
* an IPv4 compatible adress
*
* Example: 0:0:0:0:0:0:13.1.68.3
* 0:0:0:0:0:FFFF:129.144.52.38
*
* @access public
* @static
* @param string $ip a valid IPv6-adress (hex format)
* @return array [0] contains the IPv6 part, [1] the IPv4 part (hex format)
*/
function SplitV64($ip) {
$ip = Net_IPv6::Uncompress($ip);
if (strstr($ip, '.')) {
$pos = strrpos($ip, ':');
$ip{$pos} = '_';
$ipPart = explode('_', $ip);
return $ipPart;
} else {
return array($ip, "");
}
}
// }}}
// {{{ checkIPv6
/**
* Checks an IPv6 adress
*
* Checks if the given IP is IPv6-compatible
*
* @access public
* @static
* @param string $ip a valid IPv6-adress
* @return boolean true if $ip is an IPv6 adress
*/
function checkIPv6($ip) {
$ipPart = Net_IPv6::SplitV64($ip);
$count = 0;
if (!empty($ipPart[0])) {
$ipv6 =explode(':', $ipPart[0]);
for ($i = 0; $i < count($ipv6); $i++) {
$dec = hexdec($ipv6[$i]);
$hex = strtoupper(preg_replace("/^[0]{1,3}(.*[0-9a-fA-F])$/", "\\1", $ipv6[$i]));
if ($ipv6[$i] >= 0 && $dec <= 65535 && $hex == strtoupper(dechex($dec))) {
$count++;
}
}
if (8 == $count) {
return true;
} elseif (6 == $count and !empty($ipPart[1])) {
$ipv4 = explode('.',$ipPart[1]);
$count = 0;
for ($i = 0; $i < count($ipv4); $i++) {
if ($ipv4[$i] >= 0 && (integer)$ipv4[$i] <= 255 && preg_match("/^\d{1,3}$/", $ipv4[$i])) {
$count++;
}
}
if (4 == $count) {
return true;
}
} else {
return false;
}
} else {
return false;
}
}
// }}}
}
?>

806
thirdparty/pear/Net/JSON.php vendored Normal file
View File

@@ -0,0 +1,806 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Converts to and from JSON format.
*
* JSON (JavaScript Object Notation) is a lightweight data-interchange
* format. It is easy for humans to read and write. It is easy for machines
* to parse and generate. It is based on a subset of the JavaScript
* Programming Language, Standard ECMA-262 3rd Edition - December 1999.
* This feature can also be found in Python. JSON is a text format that is
* completely language independent but uses conventions that are familiar
* to programmers of the C-family of languages, including C, C++, C#, Java,
* JavaScript, Perl, TCL, and many others. These properties make JSON an
* ideal data-interchange language.
*
* This package provides a simple encoder and decoder for JSON notation. It
* is intended for use with client-side Javascript applications that make
* use of HTTPRequest to perform server communication functions - data can
* be encoded into JSON notation for use in a client-side javascript, or
* decoded from incoming Javascript requests. JSON format is native to
* Javascript, and can be directly eval()'ed with no further parsing
* overhead
*
* All strings should be in ASCII or UTF-8 format!
*
* LICENSE: 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.
*
* THIS SOFTWARE IS PROVIDED ``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 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
* @package Services_JSON
* @author Michal Migurski <mike-json@teczno.com>
* @author Matt Knapp <mdknapp[at]gmail[dot]com>
* @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
* @copyright 2005 Michal Migurski
* @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
* @license http://www.opensource.org/licenses/bsd-license.php
* @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
*/
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_SLICE', 1);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_STR', 2);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_ARR', 3);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_OBJ', 4);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_CMT', 5);
/**
* Behavior switch for Services_JSON::decode()
*/
define('SERVICES_JSON_LOOSE_TYPE', 16);
/**
* Behavior switch for Services_JSON::decode()
*/
define('SERVICES_JSON_SUPPRESS_ERRORS', 32);
/**
* Converts to and from JSON format.
*
* Brief example of use:
*
* <code>
* // create a new instance of Services_JSON
* $json = new Services_JSON();
*
* // convert a complexe value to JSON notation, and send it to the browser
* $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
* $output = $json->encode($value);
*
* print($output);
* // prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
*
* // accept incoming POST data, assumed to be in JSON notation
* $input = file_get_contents('php://input', 1000000);
* $value = $json->decode($input);
* </code>
*/
class Services_JSON
{
/**
* constructs a new JSON instance
*
* @param int $use object behavior flags; combine with boolean-OR
*
* possible values:
* - SERVICES_JSON_LOOSE_TYPE: loose typing.
* "{...}" syntax creates associative arrays
* instead of objects in decode().
* - SERVICES_JSON_SUPPRESS_ERRORS: error suppression.
* Values which can't be encoded (e.g. resources)
* appear as NULL instead of throwing errors.
* By default, a deeply-nested resource will
* bubble up with an error, so all return values
* from encode() should be checked with isError()
*/
function Services_JSON($use = 0)
{
$this->use = $use;
}
/**
* convert a string from one UTF-16 char to one UTF-8 char
*
* Normally should be handled by mb_convert_encoding, but
* provides a slower PHP-only method for installations
* that lack the multibye string extension.
*
* @param string $utf16 UTF-16 character
* @return string UTF-8 character
* @access private
*/
function utf162utf8($utf16)
{
// oh please oh please oh please oh please oh please
if(function_exists('mb_convert_encoding')) {
return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
}
$bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
switch(true) {
case ((0x7F & $bytes) == $bytes):
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x7F & $bytes);
case (0x07FF & $bytes) == $bytes:
// return a 2-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xC0 | (($bytes >> 6) & 0x1F))
. chr(0x80 | ($bytes & 0x3F));
case (0xFFFF & $bytes) == $bytes:
// return a 3-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xE0 | (($bytes >> 12) & 0x0F))
. chr(0x80 | (($bytes >> 6) & 0x3F))
. chr(0x80 | ($bytes & 0x3F));
}
// ignoring UTF-32 for now, sorry
return '';
}
/**
* convert a string from one UTF-8 char to one UTF-16 char
*
* Normally should be handled by mb_convert_encoding, but
* provides a slower PHP-only method for installations
* that lack the multibye string extension.
*
* @param string $utf8 UTF-8 character
* @return string UTF-16 character
* @access private
*/
function utf82utf16($utf8)
{
// oh please oh please oh please oh please oh please
if(function_exists('mb_convert_encoding')) {
return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
}
switch(strlen($utf8)) {
case 1:
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return $utf8;
case 2:
// return a UTF-16 character from a 2-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x07 & (ord($utf8{0}) >> 2))
. chr((0xC0 & (ord($utf8{0}) << 6))
| (0x3F & ord($utf8{1})));
case 3:
// return a UTF-16 character from a 3-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr((0xF0 & (ord($utf8{0}) << 4))
| (0x0F & (ord($utf8{1}) >> 2)))
. chr((0xC0 & (ord($utf8{1}) << 6))
| (0x7F & ord($utf8{2})));
}
// ignoring UTF-32 for now, sorry
return '';
}
/**
* encodes an arbitrary variable into JSON format
*
* @param mixed $var any number, boolean, string, array, or object to be encoded.
* see argument 1 to Services_JSON() above for array-parsing behavior.
* if var is a strng, note that encode() always expects it
* to be in ASCII or UTF-8 format!
*
* @return mixed JSON string representation of input var or an error if a problem occurs
* @access public
*/
function encode($var)
{
switch (gettype($var)) {
case 'boolean':
return $var ? 'true' : 'false';
case 'NULL':
return 'null';
case 'integer':
return (int) $var;
case 'double':
case 'float':
return (float) $var;
case 'string':
// STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
$ascii = '';
$strlen_var = strlen($var);
/*
* Iterate over every character in the string,
* escaping with a slash or encoding to UTF-8 where necessary
*/
for ($c = 0; $c < $strlen_var; ++$c) {
$ord_var_c = ord($var{$c});
switch (true) {
case $ord_var_c == 0x08:
$ascii .= '\b';
break;
case $ord_var_c == 0x09:
$ascii .= '\t';
break;
case $ord_var_c == 0x0A:
$ascii .= '\n';
break;
case $ord_var_c == 0x0C:
$ascii .= '\f';
break;
case $ord_var_c == 0x0D:
$ascii .= '\r';
break;
case $ord_var_c == 0x22:
case $ord_var_c == 0x2F:
case $ord_var_c == 0x5C:
// double quote, slash, slosh
$ascii .= '\\'.$var{$c};
break;
case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
// characters U-00000000 - U-0000007F (same as ASCII)
$ascii .= $var{$c};
break;
case (($ord_var_c & 0xE0) == 0xC0):
// characters U-00000080 - U-000007FF, mask 110XXXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c, ord($var{$c + 1}));
$c += 1;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xF0) == 0xE0):
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}));
$c += 2;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xF8) == 0xF0):
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}));
$c += 3;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xFC) == 0xF8):
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}),
ord($var{$c + 4}));
$c += 4;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xFE) == 0xFC):
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}),
ord($var{$c + 4}),
ord($var{$c + 5}));
$c += 5;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
}
}
return '"'.$ascii.'"';
case 'array':
/*
* As per JSON spec if any array key is not an integer
* we must treat the the whole array as an object. We
* also try to catch a sparsely populated associative
* array with numeric keys here because some JS engines
* will create an array with empty indexes up to
* max_index which can cause memory issues and because
* the keys, which may be relevant, will be remapped
* otherwise.
*
* As per the ECMA and JSON specification an object may
* have any string as a property. Unfortunately due to
* a hole in the ECMA specification if the key is a
* ECMA reserved word or starts with a digit the
* parameter is only accessible using ECMAScript's
* bracket notation.
*/
// treat as a JSON object
if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
$properties = array_map(array($this, 'name_value'),
array_keys($var),
array_values($var));
foreach($properties as $property) {
if(Services_JSON::isError($property)) {
return $property;
}
}
return '{' . join(',', $properties) . '}';
}
// treat it like a regular array
$elements = array_map(array($this, 'encode'), $var);
foreach($elements as $element) {
if(Services_JSON::isError($element)) {
return $element;
}
}
return '[' . join(',', $elements) . ']';
case 'object':
$vars = get_object_vars($var);
$properties = array_map(array($this, 'name_value'),
array_keys($vars),
array_values($vars));
foreach($properties as $property) {
if(Services_JSON::isError($property)) {
return $property;
}
}
return '{' . join(',', $properties) . '}';
default:
return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
? 'null'
: new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
}
}
/**
* array-walking function for use in generating JSON-formatted name-value pairs
*
* @param string $name name of key to use
* @param mixed $value reference to an array element to be encoded
*
* @return string JSON-formatted name-value pair, like '"name":value'
* @access private
*/
function name_value($name, $value)
{
$encoded_value = $this->encode($value);
if(Services_JSON::isError($encoded_value)) {
return $encoded_value;
}
return $this->encode(strval($name)) . ':' . $encoded_value;
}
/**
* reduce a string by removing leading and trailing comments and whitespace
*
* @param $str string string value to strip of comments and whitespace
*
* @return string string value stripped of comments and whitespace
* @access private
*/
function reduce_string($str)
{
$str = preg_replace(array(
// eliminate single line comments in '// ...' form
'#^\s*//(.+)$#m',
// eliminate multi-line comments in '/* ... */' form, at start of string
'#^\s*/\*(.+)\*/#Us',
// eliminate multi-line comments in '/* ... */' form, at end of string
'#/\*(.+)\*/\s*$#Us'
), '', $str);
// eliminate extraneous space
return trim($str);
}
/**
* decodes a JSON string into appropriate variable
*
* @param string $str JSON-formatted string
*
* @return mixed number, boolean, string, array, or object
* corresponding to given JSON input string.
* See argument 1 to Services_JSON() above for object-output behavior.
* Note that decode() always returns strings
* in ASCII or UTF-8 format!
* @access public
*/
function decode($str)
{
$str = $this->reduce_string($str);
switch (strtolower($str)) {
case 'true':
return true;
case 'false':
return false;
case 'null':
return null;
default:
$m = array();
if (is_numeric($str)) {
// Lookie-loo, it's a number
// This would work on its own, but I'm trying to be
// good about returning integers where appropriate:
// return (float)$str;
// Return float or int, as appropriate
return ((float)$str == (integer)$str)
? (integer)$str
: (float)$str;
} elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) {
// STRINGS RETURNED IN UTF-8 FORMAT
$delim = substr($str, 0, 1);
$chrs = substr($str, 1, -1);
$utf8 = '';
$strlen_chrs = strlen($chrs);
for ($c = 0; $c < $strlen_chrs; ++$c) {
$substr_chrs_c_2 = substr($chrs, $c, 2);
$ord_chrs_c = ord($chrs{$c});
switch (true) {
case $substr_chrs_c_2 == '\b':
$utf8 .= chr(0x08);
++$c;
break;
case $substr_chrs_c_2 == '\t':
$utf8 .= chr(0x09);
++$c;
break;
case $substr_chrs_c_2 == '\n':
$utf8 .= chr(0x0A);
++$c;
break;
case $substr_chrs_c_2 == '\f':
$utf8 .= chr(0x0C);
++$c;
break;
case $substr_chrs_c_2 == '\r':
$utf8 .= chr(0x0D);
++$c;
break;
case $substr_chrs_c_2 == '\\"':
case $substr_chrs_c_2 == '\\\'':
case $substr_chrs_c_2 == '\\\\':
case $substr_chrs_c_2 == '\\/':
if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
($delim == "'" && $substr_chrs_c_2 != '\\"')) {
$utf8 .= $chrs{++$c};
}
break;
case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)):
// single, escaped unicode character
$utf16 = chr(hexdec(substr($chrs, ($c + 2), 2)))
. chr(hexdec(substr($chrs, ($c + 4), 2)));
$utf8 .= $this->utf162utf8($utf16);
$c += 5;
break;
case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
$utf8 .= $chrs{$c};
break;
case ($ord_chrs_c & 0xE0) == 0xC0:
// characters U-00000080 - U-000007FF, mask 110XXXXX
//see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 2);
++$c;
break;
case ($ord_chrs_c & 0xF0) == 0xE0:
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 3);
$c += 2;
break;
case ($ord_chrs_c & 0xF8) == 0xF0:
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 4);
$c += 3;
break;
case ($ord_chrs_c & 0xFC) == 0xF8:
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 5);
$c += 4;
break;
case ($ord_chrs_c & 0xFE) == 0xFC:
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 6);
$c += 5;
break;
}
}
return $utf8;
} elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
// array, or object notation
if ($str{0} == '[') {
$stk = array(SERVICES_JSON_IN_ARR);
$arr = array();
} else {
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
$stk = array(SERVICES_JSON_IN_OBJ);
$obj = array();
} else {
$stk = array(SERVICES_JSON_IN_OBJ);
$obj = new stdClass();
}
}
array_push($stk, array('what' => SERVICES_JSON_SLICE,
'where' => 0,
'delim' => false));
$chrs = substr($str, 1, -1);
$chrs = $this->reduce_string($chrs);
if ($chrs == '') {
if (reset($stk) == SERVICES_JSON_IN_ARR) {
return $arr;
} else {
return $obj;
}
}
//print("\nparsing {$chrs}\n");
$strlen_chrs = strlen($chrs);
for ($c = 0; $c <= $strlen_chrs; ++$c) {
$top = end($stk);
$substr_chrs_c_2 = substr($chrs, $c, 2);
if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) {
// found a comma that is not inside a string, array, etc.,
// OR we've reached the end of the character list
$slice = substr($chrs, $top['where'], ($c - $top['where']));
array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
//print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
if (reset($stk) == SERVICES_JSON_IN_ARR) {
// we are in an array, so just push an element onto the stack
array_push($arr, $this->decode($slice));
} elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
// we are in an object, so figure
// out the property name and set an
// element in an associative array,
// for now
$parts = array();
if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
// "name":value pair
$key = $this->decode($parts[1]);
$val = $this->decode($parts[2]);
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
$obj[$key] = $val;
} else {
$obj->$key = $val;
}
} elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
// name:value pair, where name is unquoted
$key = $parts[1];
$val = $this->decode($parts[2]);
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
$obj[$key] = $val;
} else {
$obj->$key = $val;
}
}
}
} elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) {
// found a quote, and we are not inside a string
array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c}));
//print("Found start of string at {$c}\n");
} elseif (($chrs{$c} == $top['delim']) &&
($top['what'] == SERVICES_JSON_IN_STR) &&
((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) {
// found a quote, we're in a string, and it's not escaped
// we know that it's not escaped becase there is _not_ an
// odd number of backslashes at the end of the string so far
array_pop($stk);
//print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
} elseif (($chrs{$c} == '[') &&
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
// found a left-bracket, and we are in an array, object, or slice
array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false));
//print("Found start of array at {$c}\n");
} elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) {
// found a right-bracket, and we're in an array
array_pop($stk);
//print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
} elseif (($chrs{$c} == '{') &&
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
// found a left-brace, and we are in an array, object, or slice
array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false));
//print("Found start of object at {$c}\n");
} elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) {
// found a right-brace, and we're in an object
array_pop($stk);
//print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
} elseif (($substr_chrs_c_2 == '/*') &&
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
// found a comment start, and we are in an array, object, or slice
array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false));
$c++;
//print("Found start of comment at {$c}\n");
} elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) {
// found a comment end, and we're in one now
array_pop($stk);
$c++;
for ($i = $top['where']; $i <= $c; ++$i)
$chrs = substr_replace($chrs, ' ', $i, 1);
//print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
}
}
if (reset($stk) == SERVICES_JSON_IN_ARR) {
return $arr;
} elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
return $obj;
}
}
}
}
/**
* @todo Ultimately, this should just call PEAR::isError()
*/
function isError($data, $code = null)
{
if (class_exists('pear')) {
return PEAR::isError($data, $code);
} elseif (is_object($data) && (get_class($data) == 'services_json_error' ||
is_subclass_of($data, 'services_json_error'))) {
return true;
}
return false;
}
}
if (class_exists('PEAR_Error')) {
class Services_JSON_Error extends PEAR_Error
{
function Services_JSON_Error($message = 'unknown error', $code = null,
$mode = null, $options = null, $userinfo = null)
{
parent::PEAR_Error($message, $code, $mode, $options, $userinfo);
}
}
} else {
/**
* @todo Ultimately, this class shall be descended from PEAR_Error
*/
class Services_JSON_Error
{
function Services_JSON_Error($message = 'unknown error', $code = null,
$mode = null, $options = null, $userinfo = null)
{
}
}
}
?>

1065
thirdparty/pear/Net/LDAP.php vendored Normal file

File diff suppressed because it is too large Load Diff

524
thirdparty/pear/Net/LDAP/Entry.php vendored Normal file
View File

@@ -0,0 +1,524 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +--------------------------------------------------------------------------+
// | Net_LDAP |
// +--------------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +--------------------------------------------------------------------------+
// | This library is free software; you can redistribute it and/or |
// | modify it under the terms of the GNU Lesser General Public |
// | License as published by the Free Software Foundation; either |
// | version 2.1 of the License, or (at your option) any later version. |
// | |
// | This library is distributed in the hope that it will be useful, |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
// | Lesser General Public License for more details. |
// | |
// | You should have received a copy of the GNU Lesser General Public |
// | License along with this library; if not, write to the Free Software |
// | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
// +--------------------------------------------------------------------------+
// | Authors: Tarjej Huse |
// +--------------------------------------------------------------------------+
//
// $Id: Entry.php 4831 2006-02-06 09:59:09Z nbm $
/**
* This class represents an LDAP entry
*
* @package Net_LDAP
* @author Tarjei Huse
* @version $Revision: 4831 $
*/
class Net_LDAP_Entry extends PEAR
{
/**#@+
* Array of the attributes
*
* @access private
* @var array
*/
var $_attrs = array();
/**
* Array of attributes to be deleted upon update()
*/
var $_delAttrs = array();
/**
* Array of attributes to be modified upon update()
*/
var $_modAttrs = array();
/**
* Array of attributes to be added upon update()
*/
var $_addAttrs = array();
/**#@-*/
/**
* The distinguished name of the entry
*
* @access private
* @var string
*/
var $_dn = '';
/**
* LDAP resource link
*
* @access private
* @var resource
*/
var $_link = null;
/**
* Value of old DN if DN has changed
*
* @access private
* @var string
*/
var $_olddn = '';
/**#@+
* Array of errors for debugging class
*
* @access private
*/
var $_error = array();
/**
* updatechecks
*/
var $updateCheck = array('newdn' => false,
'modify' => false,
'newEntry' => true
); // since the entry is not changed before the update();
/**
* Net_LDAP_Schema object TO BE REMOVED
*/
var $_schema;
/**#@-*/
/** Constructor
*
* @param - link - ldap_resource_link, dn = string entry dn, attributes - array entry attributes array.
* @return - none
**/
function Net_LDAP_Entry($link = null, $dn = null, $attributes = null)
{
if (!is_null($link)) {
$this->_link = $link;
}
if (!is_null($dn)) {
$this->_set_dn($dn);
}
if (is_array($attributes) && count($attributes) > 0) {
$this->_set_attributes($attributes);
} else {
$this->updateCheck['newEntry'] = true;
}
}
/**
* Set the reasourcelink to the ldapserver.
*
* @access private
* @param resource LDAP link
*/
function _set_link(&$link)
{
$this->_link = $link;
}
/**
* set the entrys DN
*
* @access private
* @param string
*/
function _set_dn($dn)
{
$this->_dn = $dn;
}
/**
* sets the internal array of the entrys attributes.
*
* @access private
* @param array
*/
function _set_attributes($attributes= array())
{
$this->_attrs = $attributes;
// this is the sign that the entry exists in the first place:
$this->updateCheck['newEntry'] = false;
}
/**
* removes [count] entries from the array.
*
* remove all the count elements in the array:
* Used before ldap_modify, ldap_add
*
* @access private
* @return array Cleaned array of attributes
*/
function _clean_entry()
{
$attributes = array();
for ($i=0; $i < $this->_attrs['count'] ; $i++) {
$attr = $this->_attrs[$i];
if ($this->_attrs[$attr]['count'] == 1) {
$attributes[$this->_attrs[$i]] = $this->_attrs[$attr][0];
} else {
$attributes[$attr] = $this->_attrs[$attr];
unset ($attributes[ $attr ]['count']);
}
}
return $attributes;
}
/**
* returns an assosiative array of all the attributes in the array
*
* attributes - returns an assosiative array of all the attributes in the array
* of the form array ('attributename'=>'singelvalue' , 'attribute'=>array('multiple','values'))
*
* @param none
* @return array Array of attributes and values.
*/
function attributes()
{
return $this->_clean_entry();
}
/**
* Add one or more attribute to the entry
*
* The values given will be added to the values which already exist for the given attributes.
* usage:
* $entry->add ( array('sn'=>'huse',objectclass=>array(top,posixAccount)))
*
* @param array Array of attributes
* @return mixed Net_Ldap_Error if error, else true.
*/
function add($attr = array())
{
if (!isset($this->_attrs['count'])) {
$this->_attrs['count'] = 0;
}
if (!is_array($attr)) {
return $this->raiseError("Net_LDAP::add : the parameter supplied is not an array, $attr", 1000);
}
/* if you passed an empty array, that is your problem! */
if (count ($attr)==0) {
return true;
}
foreach ($attr as $k => $v ) {
// empty entrys should not be added to the entry.
if ($v == '') {
continue;
}
if ($this->exists($k)) {
if (!is_array($this->_attrs[$k])) {
return $this->raiseError("Possible malformed array as parameter to Net_LDAP::add().");
}
array_push($this->_attrs[$k],$v);
$this->_attrs[$k]['count']++;
} else {
$this->_attrs[$k][0] = $v;
$this->_attrs[$k]['count'] = 1;
$this->_attrs[$this->_attrs['count']] = $k;
$this->_attrs['count']++;
}
// Fix for bug #952
if (empty($this->_addAttrs[$k])) {
$this->_addAttrs[$k] = array();
}
if (false == is_array($v)) {
$v = array($v);
}
foreach ($v as $value) {
array_push($this->_addAttrs[$k], $value);
}
}
return true;
}
/**
* Set or get the DN for the object
*
* If a new dn is supplied, this will move the object when running $obj->update();
*
* @param string DN
*/
function dn($newdn = '')
{
if ($newdn == '') {
return $this->_dn;
}
$this->_olddn = $this->_dn;
$this->_dn = $newdn;
$this->updateCheck['newdn'] = true;
}
/**
* check if a certain attribute exists in the directory
*
* @param string attribute name.
* @return boolean
*/
function exists($attr)
{
if (array_key_exists($attr, $this->_attrs)) {
return true;
}
return false;
}
/**
* get_value get the values for a attribute
*
* returns either an array or a string
* possible values for option:
* alloptions - returns an array with the values + a countfield.
* i.e.: array (count=>1, 'sn'=>'huse');
* single - returns the, first value in the array as a string.
*
* @param $attr string attribute name
* @param $options array
*/
function get_value($attr = '', $options = '')
{
if (array_key_exists($attr, $this->_attrs)) {
if ($options == 'single') {
if (is_array($this->_attrs[$attr])) {
return $this->_attrs[$attr][0];
} else {
return $this->_attrs[$attr];
}
}
$value = $this->_attrs[$attr];
if (!$options == 'alloptions') {
unset ($value['count']);
}
return $value;
} else {
return '';
}
}
/**
* add/delete/modify attributes
*
* this function tries to do all the things that replace(),delete() and add() does on an object.
* Syntax:
* array ( 'attribute' => newval, 'delattribute' => '', newattrivute => newval);
* Note: You cannot use this function to modify parts of an attribute. You must modify the whole attribute.
* You may call the function many times before running $entry->update();
*
* @param array attributes to be modified
* @return mixed errorObject if failure, true if success.
*/
function modify($attrs = array()) {
if (!is_array($attrs) || count ($attrs) < 1 ) {
return $this->raiseError("You did not supply an array as expected",1000);
}
foreach ($attrs as $k => $v) {
// empty values are deleted (ldap v3 handling is in update() )
if ($v == '' && $this->exists($k)) {
$this->_delAttrs[$k] = '';
continue;
}
/* existing attributes are modified*/
if ($this->exists($k) ) {
if (is_array($v)) {
$this->_modAttrs[$k] = $v;
} else {
$this->_modAttrs[$k][0] = $v;
}
} else {
/* new ones are created */
if (is_array($v) ) {
// an empty array is deleted...
if (count($v) == 0 ) {
$this->_delAttrs[$k] = '';
} else {
$this->_addAttrs[$k] = $v;
}
} else {
// dont't add empty attributes
if ($v != null) $this->_addAttrs[$k][0] = $v;
}
}
}
return true;
}
/**
* replace a certain attributes value
*
* replace - replace a certain attributes value
* example:
* $entry->replace(array('uid'=>array('tarjei')));
*
* @param array attributes to be replaced
* @return mixed error if failure, true if sucess.
*/
function replace($attrs = array() )
{
foreach ($attrs as $k => $v) {
if ($this->exists($k)) {
if (is_array($v)) {
$this->_attrs[$k] = $v;
$this->_attrs[$k]['count'] = count($v);
$this->_modAttrs[$k] = $v;
} else {
$this->_attrs[$k]['count'] = 1;
$this->_attrs[$k][0] = $v;
$this->_modAttrs[$k][0] = $v;
}
} else {
return $this->raiseError("Attribute $k does not exist",16); // 16 = no such attribute exists.
}
}
return true;
}
/**
* delete attributes
*
* Use this function to delete certain attributes from an object.
*
* @param - array of attributes to be deleted
* @return mixed Net_Ldap_Error if failure, true if success.
*/
function delete($attrs = array())
{
foreach ($attrs as $k => $v) {
if ($this->exists ($k)) {
// if v is a null, then remove the whole attribute, else only the value.
if ($v == '') {
unset($this->_attrs[$k]);
$this->_delAttrs[$k] = "";
// else we remove only the correct value.
} else {
for ($i = 0;$i< $this->_attrs[$k]['count'];$i++) {
if ($this->_attrs[$k][$i] == $v ) {
unset ($this->_attrs[$k][$i]);
$this->_delAttrs[$k] = $v;
continue;
}
}
}
} else {
$this->raiseError("You tried to delete a nonexisting attribute!",16);
}
}
return true;
}
/**
* update the Entry in LDAP
*
* After modifying an object, you must run update() to
* make the updates on the ldap server. Before that, they only exists in the object.
*
* @param object Net_LDAP
* @return mixed Net_LDAP_Error object on failure or true on success
*/
function update ($ldapObject = null)
{
if ($ldapObject == null && $this->_link == null ) {
$this->raiseError("No link to database");
}
if ($ldapObject != null) {
$this->_link =& $ldapObject->_link;
}
//if it's a new
if ($this->updateCheck['newdn'] && !$this->updateCheck['newEntry']) {
if (@ldap_get_option( $this->_link, LDAP_OPT_PROTOCOL_VERSION, $version) && $version != 3) {
return $this->raiseError("Moving or renaming an dn is only supported in LDAP V3!", 80);
}
$newparent = ldap_explode_dn($this->_dn, 0);
unset($newparent['count']);
$relativeDn = array_shift($newparent);
$newparent = join(',', $newparent);
if (!@ldap_rename($this->_link, $this->_olddn, $relativeDn, $newparent, true)) {
return $this->raiseError("DN not renamed: " . ldap_error($this->_link), ldap_errno($this->_link));
}
}
if ($this->updateCheck['newEntry']) {
//print "<br>"; print_r($this->_clean_entry());
if (!@ldap_add($this->_link, $this->dn(), $this->_clean_entry()) ) {
return $this->raiseError("Entry" . $this->dn() . " not added!" .
ldap_error($this->_link), ldap_errno($this->_link));
} else {
return true;
}
// update existing entry
} else {
$this->_error['first'] = $this->_modAttrs;
$this->_error['count'] = count($this->_modAttrs);
// modified attributes
if (( count($this->_modAttrs)>0) &&
!ldap_modify($this->_link, $this->dn(), $this->_modAttrs))
{
return $this->raiseError("Entry " . $this->dn() . " not modified(attribs not modified): " .
ldap_error($this->_link),ldap_errno($this->_link));
}
// attributes to be deleted
if (( count($this->_delAttrs) > 0 ))
{
// in ldap v3 we need to supply the old attribute values for deleting
if (@ldap_get_option( $this->_link, LDAP_OPT_PROTOCOL_VERSION, $version) && $version == 3) {
foreach ( $this->_delAttrs as $k => $v ) {
if ( $v == '' && $this->exists($k) ) {
$this->_delAttrs[$k] = $this->get_value( $k );
}
}
}
if ( !ldap_mod_del($this->_link, $this->dn(), $this->_delAttrs) ) {
return $this->raiseError("Entry " . $this->dn() . " not modified (attributes not deleted): " .
ldap_error($this->_link),ldap_errno($this->_link));
}
}
// new attributes
if ((count($this->_addAttrs)) > 0 && !ldap_modify($this->_link, $this->dn(), $this->_addAttrs)) {
return $this->raiseError( "Entry " . $this->dn() . " not modified (attributes not added): " .
ldap_error($this->_link),ldap_errno($this->_link));
}
return true;
}
}
}
?>

192
thirdparty/pear/Net/LDAP/RootDSE.php vendored Normal file
View File

@@ -0,0 +1,192 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +--------------------------------------------------------------------------+
// | Net_LDAP |
// +--------------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +--------------------------------------------------------------------------+
// | This library is free software; you can redistribute it and/or |
// | modify it under the terms of the GNU Lesser General Public |
// | License as published by the Free Software Foundation; either |
// | version 2.1 of the License, or (at your option) any later version. |
// | |
// | This library is distributed in the hope that it will be useful, |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
// | Lesser General Public License for more details. |
// | |
// | You should have received a copy of the GNU Lesser General Public |
// | License along with this library; if not, write to the Free Software |
// | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
// +--------------------------------------------------------------------------+
// | Authors: Jan Wagner |
// +--------------------------------------------------------------------------+
//
// $Id: RootDSE.php 4831 2006-02-06 09:59:09Z nbm $
/**
* Getting the rootDSE entry of a LDAP server
*
* @package Net_LDAP
* @author Jan Wagner <wagner@netsols.de>
* @version $Revision: 4831 $
*/
class Net_LDAP_RootDSE extends PEAR
{
/**
* @access private
* @var object Net_LDAP_Entry
**/
var $_entry;
/**
* class constructor
*
* @param object Net_LDAP_Entry
*/
function Net_LDAP_RootDSE(&$entry)
{
$this->_entry = $entry;
}
/**
* Gets the requested attribute value
*
* Same usuage as Net_LDAP_Entry::get_value()
*
* @access public
* @param string Attribute name
* @param array Array of options
* @return mixed Net_LDAP_Error object or attribute values
* @see Net_LDAP_Entry::get_value()
*/
function getValue($attr = '', $options = '')
{
return $this->_entry->get_value($attr, $options);
}
/**
* alias function of getValue() for perl-ldap interface
*
* @see getValue()
*/
function get_value()
{
$args = func_get_args();
return call_user_func_array(array($this, 'getValue' ), $args);
}
/**
* Determines if the extension is supported
*
* @access public
* @param array Array of oids to check
* @return boolean
*/
function supportedExtension($oids)
{
return $this->_checkAttr($oids, 'supportedExtension');
}
/**
* alias function of supportedExtension() for perl-ldap interface
*
* @see supportedExtension()
*/
function supported_extension()
{
$args = func_get_args();
return call_user_func_array(array($this, 'supportedExtension'), $args);
}
/**
* Determines if the version is supported
*
* @access public
* @param array Versions to check
* @return boolean
*/
function supportedVersion($versions)
{
return $this->_checkAttr($versions, 'supportedLDAPVersion');
}
/**
* alias function of supportedVersion() for perl-ldap interface
*
* @see supportedVersion()
*/
function supported_version()
{
$args = func_get_args();
return call_user_func_array(array($this, 'supportedVersion'), $args);
}
/**
* Determines if the control is supported
*
* @access public
* @param array Control oids to check
* @return boolean
*/
function supportedControl($oids)
{
return $this->_checkAttr($oids, 'supportedControl');
}
/**
* alias function of supportedControl() for perl-ldap interface
*
* @see supportedControl()
*/
function supported_control()
{
$args = func_get_args();
return call_user_func_array(array($this, 'supportedControl' ), $args);
}
/**
* Determines if the sasl mechanism is supported
*
* @access public
* @param array SASL mechanisms to check
* @return boolean
*/
function supportedSASLMechanism($mechlist)
{
return $this->_checkAttr($mechlist, 'supportedSASLMechanisms');
}
/**
* alias function of supportedSASLMechanism() for perl-ldap interface
*
* @see supportedSASLMechanism()
*/
function supported_sasl_mechanism()
{
$args = func_get_args();
return call_user_func_array(array($this, 'supportedSASLMechanism'), $args);
}
/**
* Checks for existance of value in attribute
*
* @access private
* @param array $values values to check
* @param attr $attr attribute name
* @return boolean
*/
function _checkAttr($values, $attr)
{
if (!is_array($values)) $values = array($values);
foreach ($values as $value) {
if (!@in_array($value, $this->get_value($attr))) {
return false;
}
}
return true;
}
}
?>

355
thirdparty/pear/Net/LDAP/Schema.php vendored Normal file
View File

@@ -0,0 +1,355 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +--------------------------------------------------------------------------+
// | Net_LDAP |
// +--------------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +--------------------------------------------------------------------------+
// | This library is free software; you can redistribute it and/or |
// | modify it under the terms of the GNU Lesser General Public |
// | License as published by the Free Software Foundation; either |
// | version 2.1 of the License, or (at your option) any later version. |
// | |
// | This library is distributed in the hope that it will be useful, |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
// | Lesser General Public License for more details. |
// | |
// | You should have received a copy of the GNU Lesser General Public |
// | License along with this library; if not, write to the Free Software |
// | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
// +--------------------------------------------------------------------------+
// | Authors: Jan Wagner |
// +--------------------------------------------------------------------------+
//
// $Id: Schema.php 4831 2006-02-06 09:59:09Z nbm $
/**
* Load an LDAP Schema and provide information
*
* This class takes a Subschema entry, parses this information
* and makes it available in an array. Most of the code has been
* inspired by perl-ldap( http://perl-ldap.sourceforge.net).
* You will find portions of their implementation in here.
*
* @package Net_LDAP
* @author Jan Wagner <wagner@netsols.de>
* @version $Revision: 4831 $
*/
class Net_LDAP_Schema extends PEAR
{
/**
* Map of entry types to ldap attributes of subschema entry
*
* @access public
* @var array
*/
var $types = array('attribute' => 'attributeTypes',
'ditcontentrule' => 'dITContentRules',
'ditstructurerule' => 'dITStructureRules',
'matchingrule' => 'matchingRules',
'matchingruleuse' => 'matchingRuleUse',
'nameform' => 'nameForms',
'objectclass' => 'objectClasses',
'syntax' => 'ldapSyntaxes');
/**#@+
* Array of entries belonging to this type
*
* @access private
* @var array
*/
var $_attributeTypes = array();
var $_matchingRules = array();
var $_matchingRuleUse = array();
var $_ldapSyntaxes = array();
var $_objectClasses = array();
var $_dITContentRules = array();
var $_dITStructureRules = array();
var $_nameForms = array();
/**#@-*/
/**
* hash of all fetched oids
*
* @access private
* @var array
*/
var $_oids = array();
/**
* constructor of the class
*
* @access protected
*/
function Net_LDAP_Schema()
{
$this->PEAR('Net_LDAP_Error'); // default error class
}
/**
* Return a hash of entries for the given type
*
* Returns a hash of entry for th givene type. Types may be:
* objectclasses, attributes, ditcontentrules, ditstructurerules, matchingrules,
* matchingruleuses, nameforms, syntaxes
*
* @access public
* @param string Type to fetch
* @return mixed Array or Net_LDAP_Error
*/
function &getAll($type)
{
$map = array('objectclasses' => &$this->_objectClasses,
'attributes' => &$this->_attributeTypes,
'ditcontentrules' => &$this->_dITContentRules,
'ditstructurerules' => &$this->_dITStructureRules,
'matchingrules' => &$this->_matchingRules,
'matchingruleuses' => &$this->_matchingRuleUse,
'nameforms' => &$this->_nameForms,
'syntaxes' => &$this->_ldapSyntaxes );
$key = strtolower($type);
return ((key_exists($key, $map)) ? $map[$key] : $this->raiseError("Unknown type $type"));
}
/**
* Return a specific entry
*
* @access public
* @param string Type of name
* @param string Name or OID to fetch
* @return mixed Entry or Net_LDAP_Error
*/
function &get($type, $name)
{
$type = strtolower($type);
if (false == key_exists($type, $this->types)) {
return $this->raiseError("No such type $type");
}
$name = strtolower($name);
$type_var = &$this->{'_' . $this->types[$type]};
if( key_exists($name, $type_var)) {
return $type_var[$name];
} elseif(key_exists($name, $this->_oids) && $this->_oids[$name]['type'] == $type) {
return $this->_oids[$name];
} else {
return $this->raiseError("Could not find $type $name");
}
}
/**
* Fetches attributes that MAY be present in the given objectclass
*
* @access public
* @param string Name or OID of objectclass
* @return mixed Array with attributes or Net_LDAP_Error
*/
function may($oc)
{
return $this->_getAttr($oc, 'may');
}
/**
* Fetches attributes that MUST be present in the given objectclass
*
* @access public
* @param string Name or OID of objectclass
* @return mixed Array with attributes or Net_LDAP_Error
*/
function must($oc)
{
return $this->_getAttr($oc, 'must');
}
/**
* Fetches the given attribute from the given objectclass
*
* @access private
* @param string Name or OID of objectclass
* @param string Name of attribute to fetch
* @return mixed The attribute or Net_LDAP_Error
*/
function _getAttr($oc, $attr)
{
$oc = strtolower($oc);
if (key_exists($oc, $this->_objectClasses) && key_exists($attr, $this->_objectClasses[$oc])) {
return $this->_objectClasses[$oc][$attr];
}
elseif (key_exists($oc, $this->_oids) &&
$this->_oids[$oc]['type'] == 'objectclass' &&
key_exists($attr, $this->_oids[$oc])) {
return $this->_oids[$oc][$attr];
} else {
return $this->raiseError("Could not find $attr attributes for $oc ");
}
}
/**
* Returns the name(s) of the immediate superclass(es)
*
* @param string Name or OID of objectclass
* @return mixed Array of names or Net_LDAP_Error
*/
function superclass($oc)
{
$o = $this->get('objectclass', $oc);
if (Net_LDAP::isError($o)) {
return $o;
}
return (key_exists('sup', $o) ? $o['sup'] : array());
}
/**
* Parses the schema of the given Subschema entry
*
* @access public
* @param object Net_LDAP_Entry Subschema entry
*/
function parse(&$entry)
{
foreach ($this->types as $type => $attr)
{
// initialize map type to entry
$type_var = '_' . $attr;
$this->{$type_var} = array();
// get values for this type
$values = $entry->get_value($attr);
if (is_array($values))
{
foreach ($values as $value) {
unset($schema_entry); // this was a real mess without it
// get the schema entry
$schema_entry = $this->_parse_entry($value);
// set the type
$schema_entry['type'] = $type;
// save a ref in $_oids
$this->_oids[$schema_entry['oid']] =& $schema_entry;
// save refs for all names in type map
$names = $schema_entry['aliases'];
array_push($names, $schema_entry['name']);
foreach ($names as $name) {
$this->{$type_var}[strtolower($name)] =& $schema_entry;
}
}
}
}
}
/**
* parses an attribute value into a schema entry
*
* @access private
* @param string Attribute value
* @return mixed Schema entry array or false
*/
function &_parse_entry($value)
{
// tokens that have no value associated
$noValue = array('single-value',
'obsolete',
'collective',
'no-user-modification',
'abstract',
'structural',
'auxiliary');
// tokens that can have multiple values
$multiValue = array('must', 'may', 'sup');
$schema_entry = array('aliases' => array()); // initilization
$tokens = $this->_tokenize($value); // get an array of tokens
// remove surrounding brackets
if ($tokens[0] == '(') array_shift($tokens);
if ($tokens[count($tokens) - 1] == ')') array_pop($tokens); // -1 doesnt work on arrays :-(
$schema_entry['oid'] = array_shift($tokens); // first token is the oid
// cycle over the tokens until none are left
while (count($tokens) > 0) {
$token = strtolower(array_shift($tokens));
if (in_array($token, $noValue)) {
$schema_entry[$token] = 1; // single value token
} else {
// this one follows a string or a list if it is multivalued
if (($schema_entry[$token] = array_shift($tokens)) == '(') {
// this creates the list of values and cycles through the tokens
// until the end of the list is reached ')'
$schema_entry[$token] = array();
while ($tmp = array_shift($tokens)) {
if ($tmp == ')') break;
if ($tmp != '$') array_push($schema_entry[$token], $tmp);
}
}
// create a array if the value should be multivalued but was not
if (in_array($token, $multiValue ) && !is_array($schema_entry[$token])) {
$schema_entry[$token] = array($schema_entry[$token]);
}
}
}
// get max length from syntax
if (key_exists('syntax', $schema_entry)) {
if (preg_match('/{(\d+)}/', $schema_entry['syntax'], $matches)) {
$schema_entry['max_length'] = $matches[1];
}
}
// force a name
if (empty($schema_entry['name'])) {
$schema_entry['name'] = $schema_entry['oid'];
}
// make one name the default and put the other ones into aliases
if (is_array($schema_entry['name'])) {
$aliases = $schema_entry['name'];
$schema_entry['name'] = array_shift($aliases);
$schema_entry['aliases'] = $aliases;
}
return $schema_entry;
}
/**
* tokenizes the given value into an array of tokens
*
* @access private
* @param string String to parse
* @return array Array of tokens
*/
function _tokenize($value)
{
$tokens = array(); // array of tokens
$matches = array(); // matches[0] full pattern match, [1,2,3] subpatterns
// this one is taken from perl-ldap, modified for php
$pattern = "/\s* (?:([()]) | ([^'\s()]+) | '((?:[^']+|'[^\s)])*)') \s*/x";
/**
* This one matches one big pattern wherin only one of the three subpatterns matched
* We are interested in the subpatterns that matched. If it matched its value will be
* non-empty and so it is a token. Tokens may be round brackets, a string, or a string
* enclosed by '
*/
preg_match_all($pattern, $value, $matches);
for ($i = 0; $i < count($matches[0]); $i++) { // number of tokens (full pattern match)
for ($j = 1; $j < 4; $j++) { // each subpattern
if (null != trim($matches[$j][$i])) { // pattern match in this subpattern
$tokens[$i] = trim($matches[$j][$i]); // this is the token
}
}
}
return $tokens;
}
}
?>

245
thirdparty/pear/Net/LDAP/Search.php vendored Normal file
View File

@@ -0,0 +1,245 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +--------------------------------------------------------------------------+
// | Net_LDAP |
// +--------------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +--------------------------------------------------------------------------+
// | This library is free software; you can redistribute it and/or |
// | modify it under the terms of the GNU Lesser General Public |
// | License as published by the Free Software Foundation; either |
// | version 2.1 of the License, or (at your option) any later version. |
// | |
// | This library is distributed in the hope that it will be useful, |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
// | Lesser General Public License for more details. |
// | |
// | You should have received a copy of the GNU Lesser General Public |
// | License along with this library; if not, write to the Free Software |
// | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
// +--------------------------------------------------------------------------+
// | Authors: Tarjej Huse |
// +--------------------------------------------------------------------------+
//
// $Id: Search.php 4831 2006-02-06 09:59:09Z nbm $
/**
* Result set of an LDAP search
*
* @author Tarjei Huse
* @version $Revision: 4831 $
* @package Net_LDAP
*/
class Net_LDAP_Search extends PEAR
{
/**
* Search result identifier
*
* @access private
* @var resource
*/
var $_search;
/**
* LDAP resource link
*
* @access private
* @var resource
*/
var $_link;
/**
* Array of entries
*
* @access private
* @var array
*/
var $_entries = array();
/**
* Result entry identifier
*
* @access private
* @var resource
*/
var $_elink = null;
/**
* The errorcode the search got
*
* Some errorcodes might be of interest, but might not be best handled as errors.
* examples: 4 - LDAP_SIZELIMIT_EXCEEDED - indecates a huge search.
* Incomplete results are returned. If you just want to check if there's anything in the search.
* than this is a point to handle.
* 32 - no such object - search here returns a count of 0.
*
* @access private
* @var int
*/
var $_errorCode = 0; // if not set - sucess!
/**
* Constructor
*
* @access protected
* @param resource Search result identifier
* @param resource Link identifier
*/
function Net_LDAP_Search (&$search, &$link)
{
$this->_setSearch($search, $link);
$this->_errorCode = ldap_errno($link);
}
/**
* Returns an assosiative array of entry objects
*
* @return array Array of entry objects.
*/
function entries()
{
if ($this->count() == 0) {
return array();
}
$this->_elink = @ldap_first_entry( $this->_link,$this->_search);
$entry = new Net_LDAP_Entry($this->_link,
@ldap_get_dn($this->_link, $this->_elink),
@ldap_get_attributes($this->_link, $this->_elink));
array_push($this->_entries, $entry);
while ($this->_elink = @ldap_next_entry($this->_link,$this->_elink)) {
$entry = new Net_LDAP_Entry($this->_link,
@ldap_get_dn($this->_link, $this->_elink),
@ldap_get_attributes($this->_link, $this->_elink));
array_push($this->_entries, $entry);
}
return $this->_entries;
}
/**
* Get the next entry in the searchresult.
*
* @return mixed Net_LDAP_Entry object or false
*/
function shiftEntry()
{
if ($this->count() == 0 ) {
return false;
}
if (is_null($this->_elink)) {
$this->_elink = @ldap_first_entry($this->_link, $this->_search);
$entry = new Net_LDAP_Entry($this->_link,
ldap_get_dn($this->_link, $this->_elink),
ldap_get_attributes($this->_link, $this->_elink));
} else {
if (!$this->_elink = ldap_next_entry($this->_link, $this->_elink)) {
return false;
}
$entry = new Net_LDAP_Entry($this->_link,
ldap_get_dn($this->_link,$this->_elink),
ldap_get_attributes($this->_link,$this->_elink));
}
return $entry;
}
/**
* alias function of shiftEntry() for perl-ldap interface
*
* @see shiftEntry()
*/
function shift_entry()
{
$args = func_get_args();
return call_user_func_array(array($this, 'shiftEntry'), $args);
}
/**
* Retrieve the last entry of the searchset. NOT IMPLEMENTED
*
* @return object Net_LDAP_Error
*/
function pop_entry ()
{
$this->raiseError("Not implemented");
}
/**
* Return entries sorted NOT IMPLEMENTED
*
* @param array Array of sort attributes
* @return object Net_LDAP_Error
*/
function sorted ($attrs = array())
{
$this->raiseError("Not impelented");
}
/**
* Return entries as object NOT IMPLEMENTED
*
* @return object Net_LDAP_Error
*/
function as_struct ()
{
$this->raiseError("Not implemented");
}
/**
* Set the searchobjects resourcelinks
*
* @access private
* @param resource Search result identifier
* @param resource Resource link identifier
*/
function _setSearch(&$search,&$link)
{
$this->_search = $search;
$this->_link = $link;
}
/**
* Returns the number of entries in the searchresult
*
* @return int Number of entries in search.
*/
function count()
{
/* this catches the situation where OL returned errno 32 = no such object! */
if (!$this->_search) {
return 0;
}
return @ldap_count_entries($this->_link, $this->_search);
}
/**
* Get the errorcode the object got in its search.
*
* @return int The ldap error number.
*/
function getErrorCode()
{
return $this->_errorCode;
}
/** Destructor
*
* @access protected
*/
function _Net_LDAP_Search()
{
@ldap_free_result($this->_search);
}
/**
* Closes search result
*/
function done()
{
$this->_Net_LDAP_Search();
}
}
?>

132
thirdparty/pear/Net/LDAP/Util.php vendored Normal file
View File

@@ -0,0 +1,132 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +--------------------------------------------------------------------------+
// | Net_LDAP |
// +--------------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group |
// +--------------------------------------------------------------------------+
// | This library is free software; you can redistribute it and/or |
// | modify it under the terms of the GNU Lesser General Public |
// | License as published by the Free Software Foundation; either |
// | version 2.1 of the License, or (at your option) any later version. |
// | |
// | This library is distributed in the hope that it will be useful, |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
// | Lesser General Public License for more details. |
// | |
// | You should have received a copy of the GNU Lesser General Public |
// | License along with this library; if not, write to the Free Software |
// | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
// +--------------------------------------------------------------------------+
// | Authors: Jan Wagner |
// +--------------------------------------------------------------------------+
//
// $Id: Util.php 4831 2006-02-06 09:59:09Z nbm $
/**
* Utility Class for Net_LDAP
*
* @package Net_LDAP
* @author Jan Wagner <wagner@netsols.de>
* @version $Revision: 4831 $
*/
class Net_LDAP_Util extends PEAR
{
/**
* Reference to LDAP object
*
* @access private
* @var object Net_LDAP
*/
var $_ldap = null;
/**
* Net_LDAP_Schema object
*
* @access private
* @var object Net_LDAP_Schema
*/
var $_schema = null;
/**
* Constructur
*
* Takes an LDAP object by reference and saves it. Then the schema will be fetched.
*
* @access public
* @param object Net_LDAP
*/
function Net_LDAP_Util(&$ldap)
{
if (is_object($ldap) && (strtolower(get_class($ldap)) == 'net_ldap')) {
$this->_ldap = $ldap;
$this->_schema = $this->_ldap->schema();
if (Net_LDAP::isError($this->_schema)) $this->_schema = null;
}
}
/**
* Encodes given attributes to UTF8 if needed
*
* This function takes attributes in an array and then checks against the schema if they need
* UTF8 encoding. If that is so, they will be encoded. An encoded array will be returned and
* can be used for adding or modifying.
*
* @access public
* @param array Array of attributes
* @return array Array of UTF8 encoded attributes
*/
function utf8Encode($attributes)
{
return $this->_utf8($attributes, 'utf8_encode');
}
/**
* Decodes the given attribute values
*
* @access public
* @param array Array of attributes
* @return array Array with decoded attribute values
*/
function utf8Decode($attributes)
{
return $this->_utf8($attributes, 'utf8_decode');
}
/**
* Encodes or decodes attribute values if needed
*
* @access private
* @param array Array of attributes
* @param array Function to apply to attribute values
* @return array Array of attributes with function applied to values
*/
function _utf8($attributes, $function)
{
if (!$this->_ldap || !$this->_schema || !function_exists($function)) {
return $attributes;
}
if (is_array($attributes) && count($attributes) > 0) {
foreach( $attributes as $k => $v ) {
$attr = $this->_schema->get('attribute', $k);
if (Net_LDAP::isError($attr)) {
continue;
}
if (false !== strpos($attr['syntax'], '1.3.6.1.4.1.1466.115.121.1.15')) {
if (is_array($v)) {
foreach ($v as $ak => $av ) {
$v[$ak] = call_user_func($function, $av );
}
} else {
$v = call_user_func($function, $v);
}
}
$attributes[$k] = $v;
}
}
return $attributes;
}
}
?>

38
thirdparty/pear/Net/LDAP/fg.php vendored Normal file
View File

@@ -0,0 +1,38 @@
<?php
require_once('../../../../config/dmsDefaults.php');
require_once(KT_LIB_DIR . '/authentication/authenticationutil.inc.php');
require_once(KT_LIB_DIR . '/authentication/authenticationsource.inc.php');
require_once('Net/LDAP.php');
$oKTConfig =& KTConfig::getSingleton();
$oAuthenticator = KTAuthenticationUtil::getAuthenticatorForSource(2);
$config = array(
'dn' => $oAuthenticator->sSearchUser,
'password' => $oAuthenticator->sSearchPassword,
'host' => $oAuthenticator->sLdapServer,
'base' => $oAuthenticator->sBaseDN,
);
$oLdap =& Net_LDAP::connect($config);
if (PEAR::isError($oLdap)) {
var_dump($oLdap);
exit(0);
}
$aParams = array(
'scope' => 'sub',
'attributes' => array('cn', 'dn', 'displayClass'),
);
$rootDn = $oAuthenticator->sBaseDN;
if (is_array($rootDn)) {
$rootDn = join(",", $rootDn);
}
$oResults = $oLdap->search($rootDn, '(objectClass=group)', $aParams);
foreach ($oResults->entries() as $oEntry) {
var_dump($oEntry->dn());
}

1240
thirdparty/pear/Net/POP3.php vendored Normal file

File diff suppressed because it is too large Load Diff

1082
thirdparty/pear/Net/SMTP.php vendored Normal file

File diff suppressed because it is too large Load Diff

576
thirdparty/pear/Net/Socket.php vendored Normal file
View File

@@ -0,0 +1,576 @@
<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 4 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 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> |
// +----------------------------------------------------------------------+
//
// $Id: Socket.php,v 1.31 2007/05/04 04:30:29 chagenbu Exp $
require_once 'PEAR.php';
define('NET_SOCKET_READ', 1);
define('NET_SOCKET_WRITE', 2);
define('NET_SOCKET_ERROR', 4);
/**
* Generalized Socket class.
*
* @version 1.1
* @author Stig Bakken <ssb@php.net>
* @author Chuck Hagenbuch <chuck@horde.org>
*/
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 connections before assuming
* there's no more data. Defaults to no timeout.
* @var integer $timeout
*/
var $timeout = false;
/**
* Number of bytes to read at a time in readLine() and
* readAll(). Defaults to 2048.
* @var integer $lineLength
*/
var $lineLength = 2048;
/**
* 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.
* @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) How long to wait for data.
* @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');
} elseif (strspn($addr, '.0123456789') == strlen($addr) ||
strstr($addr, '/') !== false) {
$this->addr = $addr;
} else {
$this->addr = @gethostbyname($addr);
}
$this->port = $port % 65536;
if ($persistent !== null) {
$this->persistent = $persistent;
}
if ($timeout !== null) {
$this->timeout = $timeout;
}
$openfunc = $this->persistent ? 'pfsockopen' : 'fsockopen';
$errno = 0;
$errstr = '';
if ($options && function_exists('stream_context_create')) {
if ($this->timeout) {
$timeout = $this->timeout;
} else {
$timeout = 0;
}
$context = stream_context_create($options);
$fp = @$openfunc($this->addr, $this->port, $errno, $errstr, $timeout, $context);
} else {
if ($this->timeout) {
$fp = @$openfunc($this->addr, $this->port, $errno, $errstr, $this->timeout);
} else {
$fp = @$openfunc($this->addr, $this->port, $errno, $errstr);
}
}
if (!$fp) {
return $this->raiseError($errstr, $errno);
}
$this->fp = $fp;
return $this->setBlocking($this->blocking);
}
/**
* Disconnects from the peer, closes the socket.
*
* @access public
* @return mixed true on success or an error object otherwise
*/
function disconnect()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
@fclose($this->fp);
$this->fp = null;
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 an error object otherwise
*/
function setBlocking($mode)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
$this->blocking = $mode;
socket_set_blocking($this->fp, $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.
* @access public
* @return mixed true on success or an error object otherwise
*/
function setTimeout($seconds, $microseconds)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return socket_set_timeout($this->fp, $seconds, $microseconds);
}
/**
* 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, $code);
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 an error object otherwise
*/
function getStatus()
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return socket_get_status($this->fp);
}
/**
* Get a specified line of data
*
* @access public
* @return $size bytes of data from the socket, or a PEAR_Error if
* not connected.
*/
function gets($size)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
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 true on success or an error object otherwise
*/
function write($data, $blocksize = null)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
if (is_null($blocksize) && !OS_WINDOWS) {
return fwrite($this->fp, $data);
} else {
if (is_null($blocksize)) {
$blocksize = 1024;
}
$pos = 0;
$size = strlen($data);
while ($pos < $size) {
$written = @fwrite($this->fp, substr($data, $pos, $blocksize));
if ($written === false) {
return false;
}
$pos += $written;
}
return $pos;
}
}
/**
* Write a line of data to the socket, followed by a trailing "\r\n".
*
* @access public
* @return mixed fputs result, or an error
*/
function writeLine($data)
{
if (!is_resource($this->fp)) {
return $this->raiseError('not connected');
}
return fwrite($this->fp, $data . "\r\n");
}
/**
* 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 formated string
*
* @access public
* @return Dot formated 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("%s.%s.%s.%s", 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, "\r\n");
}
}
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
* http://se.php.net/manual/en/function.stream-socket-enable-crypto.php for values.
*
* @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 {
return $this->raiseError('Net_Socket::enableCrypto() requires php version >= 5.1.0');
}
}
}

485
thirdparty/pear/Net/URL.php vendored Normal file
View File

@@ -0,0 +1,485 @@
<?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.49 2007/06/28 14:43:07 davidc Exp $
//
// Net_URL Class
class Net_URL
{
var $options = array('encode_query_keys' => false);
/**
* 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;
/**
* PHP4 Constructor
*
* @see __construct()
*/
function Net_URL($url = null, $useBrackets = true)
{
$this->__construct($url, $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)
{
$this->url = $url;
$this->useBrackets = $useBrackets;
$this->initialize();
}
function initialize()
{
$HTTP_SERVER_VARS = !empty($_SERVER) ? $_SERVER : $GLOBALS['HTTP_SERVER_VARS'];
$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', $this->url)) {
$this->protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https' : 'http');
/**
* Figure out host/port
*/
if (!empty($HTTP_SERVER_VARS['HTTP_HOST']) &&
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($this->url)) {
$urlinfo = parse_url($this->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 or updates a querystring item (URL parameter).
* Automatically encodes parameters with rawurlencode() if $preencoded
* is false.
* You can pass an array to $value, it gets mapped via [] in the URL if
* $this->useBrackets is activated.
*
* @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 ($this->getOption('encode_query_keys')) {
$name = rawurlencode($name);
}
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 ($this->getOption('encode_query_keys')) {
$name = rawurlencode($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) {
// Encode var name
$name = rawurlencode($name);
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 (!$this->getOption('encode_query_keys')) {
$key = rawurldecode($key);
}
if (preg_match('#^(.*)\[([0-9a-z_-]*)\]#i', $key, $matches)) {
$key = $matches[1];
$idx = $matches[2];
// Ensure is an array
if (empty($return[$key]) || !is_array($return[$key])) {
$return[$key] = array();
}
// Add data
if ($idx === '') {
$return[$key][] = $value;
} else {
$return[$key][$idx] = $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 $path URL path to resolve
* @return string The result
*/
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($protocol) : $port;
}
/**
* Set an option
*
* This function set an option
* to be used thorough the script.
*
* @access public
* @param string $optionName The optionname to set
* @param string $value The value of this option.
*/
function setOption($optionName, $value)
{
if (!array_key_exists($optionName, $this->options)) {
return false;
}
$this->options[$optionName] = $value;
$this->initialize();
}
/**
* Get an option
*
* This function gets an option
* from the $this->options array
* and return it's value.
*
* @access public
* @param string $opionName The name of the option to retrieve
* @see $this->options
*/
function getOption($optionName)
{
if (!isset($this->options[$optionName])) {
return false;
}
return $this->options[$optionName];
}
}
?>

813
thirdparty/pear/Net/URL2.php vendored Normal file
View File

@@ -0,0 +1,813 @@
<?php
// +-----------------------------------------------------------------------+
// | Copyright (c) 2007-2008, Christian Schmidt, Peytz & Co. A/S |
// | 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: Christian Schmidt <schmidt at php dot net> |
// +-----------------------------------------------------------------------+
//
// $Id: URL2.php,v 1.10 2008/04/26 21:57:08 schmidt Exp $
//
// Net_URL2 Class (PHP5 Only)
// This code is released under the BSD License - http://www.opensource.org/licenses/bsd-license.php
/**
* @license BSD License
*/
class Net_URL2
{
/**
* Do strict parsing in resolve() (see RFC 3986, section 5.2.2). Default
* is true.
*/
const OPTION_STRICT = 'strict';
/**
* Represent arrays in query using PHP's [] notation. Default is true.
*/
const OPTION_USE_BRACKETS = 'use_brackets';
/**
* URL-encode query variable keys. Default is true.
*/
const OPTION_ENCODE_KEYS = 'encode_keys';
/**
* Query variable separators when parsing the query string. Every character
* is considered a separator. Default is specified by the
* arg_separator.input php.ini setting (this defaults to "&").
*/
const OPTION_SEPARATOR_INPUT = 'input_separator';
/**
* Query variable separator used when generating the query string. Default
* is specified by the arg_separator.output php.ini setting (this defaults
* to "&").
*/
const OPTION_SEPARATOR_OUTPUT = 'output_separator';
/**
* Default options corresponds to how PHP handles $_GET.
*/
private $options = array(
self::OPTION_STRICT => true,
self::OPTION_USE_BRACKETS => true,
self::OPTION_ENCODE_KEYS => true,
self::OPTION_SEPARATOR_INPUT => 'x&',
self::OPTION_SEPARATOR_OUTPUT => 'x&',
);
/**
* @var string|bool
*/
private $scheme = false;
/**
* @var string|bool
*/
private $userinfo = false;
/**
* @var string|bool
*/
private $host = false;
/**
* @var int|bool
*/
private $port = false;
/**
* @var string
*/
private $path = '';
/**
* @var string|bool
*/
private $query = false;
/**
* @var string|bool
*/
private $fragment = false;
/**
* @param string $url an absolute or relative URL
* @param array $options
*/
public function __construct($url, $options = null)
{
$this->setOption(self::OPTION_SEPARATOR_INPUT,
ini_get('arg_separator.input'));
$this->setOption(self::OPTION_SEPARATOR_OUTPUT,
ini_get('arg_separator.output'));
if (is_array($options)) {
foreach ($options as $optionName => $value) {
$this->setOption($optionName);
}
}
if (preg_match('@^([a-z][a-z0-9.+-]*):@i', $url, $reg)) {
$this->scheme = $reg[1];
$url = substr($url, strlen($reg[0]));
}
if (preg_match('@^//([^/#?]+)@', $url, $reg)) {
$this->setAuthority($reg[1]);
$url = substr($url, strlen($reg[0]));
}
$i = strcspn($url, '?#');
$this->path = substr($url, 0, $i);
$url = substr($url, $i);
if (preg_match('@^\?([^#]*)@', $url, $reg)) {
$this->query = $reg[1];
$url = substr($url, strlen($reg[0]));
}
if ($url) {
$this->fragment = substr($url, 1);
}
}
/**
* Returns the scheme, e.g. "http" or "urn", or false if there is no
* scheme specified, i.e. if this is a relative URL.
*
* @return string|bool
*/
public function getScheme()
{
return $this->scheme;
}
/**
* @param string|bool $scheme
*
* @return void
* @see getScheme()
*/
public function setScheme($scheme)
{
$this->scheme = $scheme;
}
/**
* Returns the user part of the userinfo part (the part preceding the first
* ":"), or false if there is no userinfo part.
*
* @return string|bool
*/
public function getUser()
{
return $this->userinfo !== false ? preg_replace('@:.*$@', '', $this->userinfo) : false;
}
/**
* Returns the password part of the userinfo part (the part after the first
* ":"), or false if there is no userinfo part (i.e. the URL does not
* contain "@" in front of the hostname) or the userinfo part does not
* contain ":".
*
* @return string|bool
*/
public function getPassword()
{
return $this->userinfo !== false ? substr(strstr($this->userinfo, ':'), 1) : false;
}
/**
* Returns the userinfo part, or false if there is none, i.e. if the
* authority part does not contain "@".
*
* @return string|bool
*/
public function getUserinfo()
{
return $this->userinfo;
}
/**
* Sets the userinfo part. If two arguments are passed, they are combined
* in the userinfo part as username ":" password.
*
* @param string|bool $userinfo userinfo or username
* @param string|bool $password
*
* @return void
*/
public function setUserinfo($userinfo, $password = false)
{
$this->userinfo = $userinfo;
if ($password !== false) {
$this->userinfo .= ':' . $password;
}
}
/**
* Returns the host part, or false if there is no authority part, e.g.
* relative URLs.
*
* @return string|bool
*/
public function getHost()
{
return $this->host;
}
/**
* @param string|bool $host
*
* @return void
*/
public function setHost($host)
{
$this->host = $host;
}
/**
* Returns the port number, or false if there is no port number specified,
* i.e. if the default port is to be used.
*
* @return int|bool
*/
public function getPort()
{
return $this->port;
}
/**
* @param int|bool $port
*
* @return void
*/
public function setPort($port)
{
$this->port = intval($port);
}
/**
* Returns the authority part, i.e. [ userinfo "@" ] host [ ":" port ], or
* false if there is no authority none.
*
* @return string|bool
*/
public function getAuthority()
{
if (!$this->host) {
return false;
}
$authority = '';
if ($this->userinfo !== false) {
$authority .= $this->userinfo . '@';
}
$authority .= $this->host;
if ($this->port !== false) {
$authority .= ':' . $this->port;
}
return $authority;
}
/**
* @param string|false $authority
*
* @return void
*/
public function setAuthority($authority)
{
$this->user = false;
$this->pass = false;
$this->host = false;
$this->port = false;
if (preg_match('@^(([^\@]+)\@)?([^:]+)(:(\d*))?$@', $authority, $reg)) {
if ($reg[1]) {
$this->userinfo = $reg[2];
}
$this->host = $reg[3];
if (isset($reg[5])) {
$this->port = intval($reg[5]);
}
}
}
/**
* Returns the path part (possibly an empty string).
*
* @return string
*/
public function getPath()
{
return $this->path;
}
/**
* @param string $path
*
* @return void
*/
public function setPath($path)
{
$this->path = $path;
}
/**
* Returns the query string (excluding the leading "?"), or false if "?"
* isn't present in the URL.
*
* @return string|bool
* @see self::getQueryVariables()
*/
public function getQuery()
{
return $this->query;
}
/**
* @param string|bool $query
*
* @return void
* @see self::setQueryVariables()
*/
public function setQuery($query)
{
$this->query = $query;
}
/**
* Returns the fragment name, or false if "#" isn't present in the URL.
*
* @return string|bool
*/
public function getFragment()
{
return $this->fragment;
}
/**
* @param string|bool $fragment
*
* @return void
*/
public function setFragment($fragment)
{
$this->fragment = $fragment;
}
/**
* Returns the query string like an array as the variables would appear in
* $_GET in a PHP script.
*
* @return array
*/
public function getQueryVariables()
{
$pattern = '/[' .
preg_quote($this->getOption(self::OPTION_SEPARATOR_INPUT), '/') .
']/';
$parts = preg_split($pattern, $this->query, -1, PREG_SPLIT_NO_EMPTY);
$return = array();
foreach ($parts as $part) {
if (strpos($part, '=') !== false) {
list($key, $value) = explode('=', $part, 2);
} else {
$key = $part;
$value = null;
}
if ($this->getOption(self::OPTION_ENCODE_KEYS)) {
$key = rawurldecode($key);
}
$value = rawurldecode($value);
if ($this->getOption(self::OPTION_USE_BRACKETS) &&
preg_match('#^(.*)\[([0-9a-z_-]*)\]#i', $key, $matches)) {
$key = $matches[1];
$idx = $matches[2];
// Ensure is an array
if (empty($return[$key]) || !is_array($return[$key])) {
$return[$key] = array();
}
// Add data
if ($idx === '') {
$return[$key][] = $value;
} else {
$return[$key][$idx] = $value;
}
} elseif (!$this->getOption(self::OPTION_USE_BRACKETS)
&& !empty($return[$key])
) {
$return[$key] = (array) $return[$key];
$return[$key][] = $value;
} else {
$return[$key] = $value;
}
}
return $return;
}
/**
* @param array $array (name => value) array
*
* @return void
*/
public function setQueryVariables(array $array)
{
if (!$array) {
$this->query = false;
} else {
foreach ($array as $name => $value) {
if ($this->getOption(self::OPTION_ENCODE_KEYS)) {
$name = rawurlencode($name);
}
if (is_array($value)) {
foreach ($value as $k => $v) {
$parts[] = $this->getOption(self::OPTION_USE_BRACKETS)
? sprintf('%s[%s]=%s', $name, $k, $v)
: ($name . '=' . $v);
}
} elseif (!is_null($value)) {
$parts[] = $name . '=' . $value;
} else {
$parts[] = $name;
}
}
$this->query = implode($this->getOption(self::OPTION_SEPARATOR_OUTPUT),
$parts);
}
}
/**
* @param string $name
* @param mixed $value
*
* @return array
*/
public function setQueryVariable($name, $value)
{
$array = $this->getQueryVariables();
$array[$name] = $value;
$this->setQueryVariables($array);
}
/**
* @param string $name
*
* @return void
*/
public function unsetQueryVariable($name)
{
$array = $this->getQueryVariables();
unset($array[$name]);
$this->setQueryVariables($array);
}
/**
* Returns a string representation of this URL.
*
* @return string
*/
public function getURL()
{
// See RFC 3986, section 5.3
$url = "";
if ($this->scheme !== false) {
$url .= $this->scheme . ':';
}
$authority = $this->getAuthority();
if ($authority !== false) {
$url .= '//' . $authority;
}
$url .= $this->path;
if ($this->query !== false) {
$url .= '?' . $this->query;
}
if ($this->fragment !== false) {
$url .= '#' . $this->fragment;
}
return $url;
}
/**
* Returns a normalized string representation of this URL. This is useful
* for comparison of URLs.
*
* @return string
*/
public function getNormalizedURL()
{
$url = clone $this;
$url->normalize();
return $url->getUrl();
}
/**
* Returns a normalized Net_URL2 instance.
*
* @return Net_URL2
*/
public function normalize()
{
// See RFC 3886, section 6
// Schemes are case-insensitive
if ($this->scheme) {
$this->scheme = strtolower($this->scheme);
}
// Hostnames are case-insensitive
if ($this->host) {
$this->host = strtolower($this->host);
}
// Remove default port number for known schemes (RFC 3986, section 6.2.3)
if ($this->port &&
$this->scheme &&
$this->port == getservbyname($this->scheme, 'tcp')) {
$this->port = false;
}
// Normalize case of %XX percentage-encodings (RFC 3986, section 6.2.2.1)
foreach (array('userinfo', 'host', 'path') as $part) {
if ($this->$part) {
$this->$part = preg_replace('/%[0-9a-f]{2}/ie', 'strtoupper("\0")', $this->$part);
}
}
// Path segment normalization (RFC 3986, section 6.2.2.3)
$this->path = self::removeDotSegments($this->path);
// Scheme based normalization (RFC 3986, section 6.2.3)
if ($this->host && !$this->path) {
$this->path = '/';
}
}
/**
* Returns whether this instance represents an absolute URL.
*
* @return bool
*/
public function isAbsolute()
{
return (bool) $this->scheme;
}
/**
* Returns an Net_URL2 instance representing an absolute URL relative to
* this URL.
*
* @param Net_URL2|string $reference relative URL
*
* @return Net_URL2
*/
public function resolve($reference)
{
if (is_string($reference)) {
$reference = new self($reference);
}
if (!$this->isAbsolute()) {
throw new Exception('Base-URL must be absolute');
}
// A non-strict parser may ignore a scheme in the reference if it is
// identical to the base URI's scheme.
if (!$this->getOption(self::OPTION_STRICT) && $reference->scheme == $this->scheme) {
$reference->scheme = false;
}
$target = new self('');
if ($reference->scheme !== false) {
$target->scheme = $reference->scheme;
$target->setAuthority($reference->getAuthority());
$target->path = self::removeDotSegments($reference->path);
$target->query = $reference->query;
} else {
$authority = $reference->getAuthority();
if ($authority !== false) {
$target->setAuthority($authority);
$target->path = self::removeDotSegments($reference->path);
$target->query = $reference->query;
} else {
if ($reference->path == '') {
$target->path = $this->path;
if ($reference->query !== false) {
$target->query = $reference->query;
} else {
$target->query = $this->query;
}
} else {
if (substr($reference->path, 0, 1) == '/') {
$target->path = self::removeDotSegments($reference->path);
} else {
// Merge paths (RFC 3986, section 5.2.3)
if ($this->host !== false && $this->path == '') {
$target->path = '/' . $this->path;
} else {
$i = strrpos($this->path, '/');
if ($i !== false) {
$target->path = substr($this->path, 0, $i + 1);
}
$target->path .= $reference->path;
}
$target->path = self::removeDotSegments($target->path);
}
$target->query = $reference->query;
}
$target->setAuthority($this->getAuthority());
}
$target->scheme = $this->scheme;
}
$target->fragment = $reference->fragment;
return $target;
}
/**
* Removes dots as described in RFC 3986, section 5.2.4, e.g.
* "/foo/../bar/baz" => "/bar/baz"
*
* @param string $path a path
*
* @return string a path
*/
private static function removeDotSegments($path)
{
$output = '';
// Make sure not to be trapped in an infinite loop due to a bug in this
// method
$j = 0;
while ($path && $j++ < 100) {
// Step A
if (substr($path, 0, 2) == './') {
$path = substr($path, 2);
} elseif (substr($path, 0, 3) == '../') {
$path = substr($path, 3);
// Step B
} elseif (substr($path, 0, 3) == '/./' || $path == '/.') {
$path = '/' . substr($path, 3);
// Step C
} elseif (substr($path, 0, 4) == '/../' || $path == '/..') {
$path = '/' . substr($path, 4);
$i = strrpos($output, '/');
$output = $i === false ? '' : substr($output, 0, $i);
// Step D
} elseif ($path == '.' || $path == '..') {
$path = '';
// Step E
} else {
$i = strpos($path, '/');
if ($i === 0) {
$i = strpos($path, '/', 1);
}
if ($i === false) {
$i = strlen($path);
}
$output .= substr($path, 0, $i);
$path = substr($path, $i);
}
}
return $output;
}
/**
* Returns a Net_URL2 instance representing the canonical URL of the
* currently executing PHP script.
*
* @return string
*/
public static function getCanonical()
{
if (!isset($_SERVER['REQUEST_METHOD'])) {
// ALERT - no current URL
throw new Exception('Script was not called through a webserver');
}
// Begin with a relative URL
$url = new self($_SERVER['PHP_SELF']);
$url->scheme = isset($_SERVER['HTTPS']) ? 'https' : 'http';
$url->host = $_SERVER['SERVER_NAME'];
$port = intval($_SERVER['SERVER_PORT']);
if ($url->scheme == 'http' && $port != 80 ||
$url->scheme == 'https' && $port != 443) {
$url->port = $port;
}
return $url;
}
/**
* Returns the URL used to retrieve the current request.
*
* @return string
*/
public static function getRequestedURL()
{
return self::getRequested()->getUrl();
}
/**
* Returns a Net_URL2 instance representing the URL used to retrieve the
* current request.
*
* @return Net_URL2
*/
public static function getRequested()
{
if (!isset($_SERVER['REQUEST_METHOD'])) {
// ALERT - no current URL
throw new Exception('Script was not called through a webserver');
}
// Begin with a relative URL
$url = new self($_SERVER['REQUEST_URI']);
$url->scheme = isset($_SERVER['HTTPS']) ? 'https' : 'http';
// Set host and possibly port
$url->setAuthority($_SERVER['HTTP_HOST']);
return $url;
}
/**
* Sets the specified option.
*
* @param string $optionName a self::OPTION_ constant
* @param mixed $value option value
*
* @return void
* @see self::OPTION_STRICT
* @see self::OPTION_USE_BRACKETS
* @see self::OPTION_ENCODE_KEYS
*/
function setOption($optionName, $value)
{
if (!array_key_exists($optionName, $this->options)) {
return false;
}
$this->options[$optionName] = $value;
}
/**
* Returns the value of the specified option.
*
* @param string $optionName The name of the option to retrieve
*
* @return mixed
*/
function getOption($optionName)
{
return isset($this->options[$optionName])
? $this->options[$optionName] : false;
}
}

967
thirdparty/pear/Net/UserAgent/Detect.php vendored Normal file
View File

@@ -0,0 +1,967 @@
<?php
// {{{ license
// +----------------------------------------------------------------------+
// | PHP version 4.2 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2007 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: Dan Allen <dan@mojavelinux.com> |
// | Jason Rust <jrust@php.net> |
// +----------------------------------------------------------------------+
// $Id: Detect.php,v 1.26 2007/09/19 21:31:54 jrust Exp $
// }}}
// {{{ constants
define('NET_USERAGENT_DETECT_BROWSER', 'browser');
define('NET_USERAGENT_DETECT_OS', 'os');
define('NET_USERAGENT_DETECT_FEATURES', 'features');
define('NET_USERAGENT_DETECT_QUIRKS', 'quirks');
define('NET_USERAGENT_DETECT_ACCEPT', 'accept');
define('NET_USERAGENT_DETECT_ALL', 'all');
// }}}
// {{{ class Net_UserAgent_Detect
/**
* The Net_UserAgent_Detect object does a number of tests on an HTTP user
* agent string. The results of these tests are available via methods of
* the object. Note that all methods in this class can be called
* statically. The constructor and singleton methods are only retained
* for BC.
*
* This module is based upon the JavaScript browser detection code
* available at http://www.mozilla.org/docs/web-developer/sniffer/browser_type.html.
* This module had many influences from the lib/Browser.php code in
* version 1.3 of Horde.
*
* @author Jason Rust <jrust@php.net>
* @author Dan Allen <dan@mojavelinux.com>
* @author Chuck Hagenbuch <chuck@horde.org>
* @author Jon Parise <jon@horde.org>
* @package Net_UserAgent
*/
// }}}
class Net_UserAgent_Detect {
// {{{ constructor
function Net_UserAgent_Detect($in_userAgent = null, $in_detect = null)
{
$this->detect($in_userAgent, $in_detect);
}
// }}}
// {{{ singleton
/**
* To be used in place of the contructor to return only open instance.
*
* @access public
* @return object Net_UserAgent_Detect instance
*/
function &singleton($in_userAgent = null, $in_detect = null)
{
static $instance;
if (!isset($instance)) {
$instance = new Net_UserAgent_Detect($in_userAgent, $in_detect);
}
return $instance;
}
// }}}
// {{{ detect()
/**
* Detect the user agent and prepare flags, features and quirks
* based on what is found
*
* This is the core of the Net_UserAgent_Detect class. It moves its
* way through the user agent string setting up the flags based on
* the vendors and versions of the browsers, determining the OS and
* setting up the features and quirks owned by each of the relevant
* clients. Note that if you are going to be calling methods of
* this class statically then set all the parameters using th
* setOption()
*
* @param string $in_userAgent (optional) User agent override.
* @param mixed $in_detect (optional) The level of checking to do.
*
* @access public
* @return void
*/
function detect($in_userAgent = null, $in_detect = null)
{
static $hasRun;
$options = &Net_UserAgent_Detect::_getStaticProperty('options');
if (!empty($hasRun) && empty($options['re-evaluate'])) {
return;
}
$hasRun = true;
// {{{ set up static properties
$in_userAgent = isset($options['userAgent']) && is_null($in_userAgent) ? $options['userAgent'] : $in_userAgent;
$in_detect = isset($options['detectOptions']) && is_null($in_detect) ? $options['detectOptions'] : $in_detect;
// User agent string that is being analyzed
$userAgent = &Net_UserAgent_Detect::_getStaticProperty('userAgent');
// Array that stores all of the flags for the vendor and version
// of the different browsers
$browser = &Net_UserAgent_Detect::_getStaticProperty('browser');
$browser = array_flip(array('ns', 'ns2', 'ns3', 'ns4', 'ns4up', 'nav', 'ns6', 'belowns6', 'ns6up', 'firefox', 'firefox0.x', 'firefox1.x', 'firefox1.5', 'firefox2.x', 'gecko', 'ie', 'ie3', 'ie4', 'ie4up', 'ie5', 'ie5_5', 'ie5up', 'ie6', 'belowie6', 'ie6up', 'ie7', 'ie7up', 'opera', 'opera2', 'opera3', 'opera4', 'opera5', 'opera6', 'opera7', 'opera8', 'opera9', 'opera5up', 'opera6up', 'opera7up', 'belowopera8', 'opera8up', 'opera9up', 'aol', 'aol3', 'aol4', 'aol5', 'aol6', 'aol7', 'aol8', 'webtv', 'aoltv', 'tvnavigator', 'hotjava', 'hotjava3', 'hotjava3up', 'konq', 'safari', 'netgem', 'webdav', 'icab'));
// Array that stores all of the flags for the operating systems,
// and in some cases the versions of those operating systems (windows)
$os = &Net_UserAgent_Detect::_getStaticProperty('os');
$os = array_flip(array('win', 'win95', 'win16', 'win31', 'win9x', 'win98', 'wince', 'winme', 'win2k', 'winxp', 'winnt', 'win2003', 'os2', 'mac', 'mac68k', 'macppc', 'linux', 'unix', 'vms', 'sun', 'sun4', 'sun5', 'suni86', 'irix', 'irix5', 'irix6', 'hpux', 'hpux9', 'hpux10', 'aix', 'aix1', 'aix2', 'aix3', 'aix4', 'sco', 'unixware', 'mpras', 'reliant', 'dec', 'sinix', 'freebsd', 'bsd'));
// Array which stores known issues with the given client that can
// be used for on the fly tweaking so that the client may recieve
// the proper handling of this quirk.
$quirks = &Net_UserAgent_Detect::_getStaticProperty('quirks');
$quirks = array(
'must_cache_forms' => false,
'popups_disabled' => false,
'empty_file_input_value' => false,
'cache_ssl_downloads' => false,
'scrollbar_in_way' => false,
'break_disposition_header' => false,
'nested_table_render_bug' => false);
// Array that stores credentials for each of the browser/os
// combinations. These allow quick access to determine if the
// current client has a feature that is going to be implemented
// in the script.
$features = &Net_UserAgent_Detect::_getStaticProperty('features');
$features = array(
'javascript' => false,
'dhtml' => false,
'dom' => false,
'sidebar' => false,
'gecko' => false,
'svg' => false,
'css2' => false,
'ajax' => false);
// The leading identifier is the very first term in the user
// agent string, which is used to identify clients which are not
// Mosaic-based browsers.
$leadingIdentifier = &Net_UserAgent_Detect::_getStaticProperty('leadingIdentifier');
// The full version of the client as supplied by the very first
// numbers in the user agent
$version = &Net_UserAgent_Detect::_getStaticProperty('version');
$version = 0;
// The major part of the client version, which is the integer
// value of the version.
$majorVersion = &Net_UserAgent_Detect::_getStaticProperty('majorVersion');
$majorVersion = 0;
// The minor part of the client version, which is the decimal
// parts of the version
$subVersion = &Net_UserAgent_Detect::_getStaticProperty('subVersion');
$subVersion = 0;
// }}}
// detemine what user agent we are using
if (is_null($in_userAgent)) {
if (isset($_SERVER['HTTP_USER_AGENT'])) {
$userAgent = $_SERVER['HTTP_USER_AGENT'];
}
elseif (isset($GLOBALS['HTTP_SERVER_VARS']['HTTP_USER_AGENT'])) {
$userAgent = $GLOBALS['HTTP_SERVER_VARS']['HTTP_USER_AGENT'];
}
else {
$userAgent = '';
}
}
else {
$userAgent = $in_userAgent;
}
// get the lowercase version for case-insensitive searching
$agt = strtolower($userAgent);
// figure out what we need to look for
$detectOptions = array(NET_USERAGENT_DETECT_BROWSER,
NET_USERAGENT_DETECT_OS, NET_USERAGENT_DETECT_FEATURES,
NET_USERAGENT_DETECT_QUIRKS, NET_USERAGENT_DETECT_ACCEPT,
NET_USERAGENT_DETECT_ALL);
$detect = is_null($in_detect) ? NET_USERAGENT_DETECT_ALL : $in_detect;
settype($detect, 'array');
foreach($detectOptions as $option) {
if (in_array($option, $detect)) {
$detectFlags[$option] = true;
}
else {
$detectFlags[$option] = false;
}
}
// initialize the arrays of browsers and operating systems
// Get the type and version of the client
if (preg_match(";^([[:alnum:]]+)[ /\(]*[[:alpha:]]*([\d]*)(\.[\d\.]*);", $agt, $matches)) {
list(, $leadingIdentifier, $majorVersion, $subVersion) = $matches;
}
if (empty($leadingIdentifier)) {
$leadingIdentifier = 'Unknown';
}
$version = $majorVersion . $subVersion;
// Browser type
if ($detectFlags[NET_USERAGENT_DETECT_ALL] || $detectFlags[NET_USERAGENT_DETECT_BROWSER]) {
$browser['webdav'] = ($agt == 'microsoft data access internet publishing provider dav' || $agt == 'microsoft data access internet publishing provider protocol discovery');
$browser['konq'] = $browser['safari'] = (strpos($agt, 'konqueror') !== false || strpos($agt, 'safari') !== false);
$browser['text'] = strpos($agt, 'links') !== false || strpos($agt, 'lynx') !== false || strpos($agt, 'w3m') !== false;
$browser['ns'] = strpos($agt, 'mozilla') !== false && !(strpos($agt, 'spoofer') !== false) && !(strpos($agt, 'compatible') !== false) && !(strpos($agt, 'hotjava') !== false) && !(strpos($agt, 'opera') !== false) && !(strpos($agt, 'webtv') !== false) ? 1 : 0;
$browser['netgem'] = strpos($agt, 'netgem') !== false;
$browser['icab'] = strpos($agt, 'icab') !== false;
$browser['ns2'] = $browser['ns'] && $majorVersion == 2;
$browser['ns3'] = $browser['ns'] && $majorVersion == 3;
$browser['ns4'] = $browser['ns'] && $majorVersion == 4;
$browser['ns4up'] = $browser['ns'] && $majorVersion >= 4;
// determine if this is a Netscape Navigator
$browser['nav'] = $browser['belowns6'] = $browser['ns'] && $majorVersion < 5;
$browser['ns6'] = !$browser['konq'] && $browser['ns'] && $majorVersion == 5;
$browser['ns6up'] = $browser['ns6'] && $majorVersion >= 5;
$browser['gecko'] = strpos($agt, 'gecko') !== false && !$browser['konq'];
$browser['firefox'] = $browser['gecko'] && strpos($agt, 'firefox') !== false;
$browser['firefox0.x'] = $browser['firefox'] && strpos($agt, 'firefox/0.') !== false;
$browser['firefox1.x'] = $browser['firefox'] && strpos($agt, 'firefox/1.') !== false;
$browser['firefox1.5'] = $browser['firefox'] && strpos($agt, 'firefox/1.5') !== false;
$browser['firefox2.x'] = $browser['firefox'] && strpos($agt, 'firefox/2.') !== false;
$browser['ie'] = strpos($agt, 'msie') !== false && !(strpos($agt, 'opera') !== false);
$browser['ie3'] = $browser['ie'] && $majorVersion < 4;
$browser['ie4'] = $browser['ie'] && $majorVersion == 4 && (strpos($agt, 'msie 4') !== false);
$browser['ie4up'] = $browser['ie'] && !$browser['ie3'];
$browser['ie5'] = $browser['ie4up'] && (strpos($agt, 'msie 5') !== false);
$browser['ie5_5'] = $browser['ie4up'] && (strpos($agt, 'msie 5.5') !== false);
$browser['ie5up'] = $browser['ie4up'] && !$browser['ie3'] && !$browser['ie4'];
$browser['ie5_5up'] = $browser['ie5up'] && !$browser['ie5'];
$browser['ie6'] = strpos($agt, 'msie 6') !== false;
$browser['ie6up'] = $browser['ie5up'] && !$browser['ie5'] && !$browser['ie5_5'];
$browser['ie7'] = strpos($agt, 'msie 7') !== false;
$browser['ie7up'] = $browser['ie6up'] && !$browser['ie6'];
$browser['belowie6']= $browser['ie'] && !$browser['ie6up'];
$browser['opera'] = strpos($agt, 'opera') !== false;
$browser['opera2'] = strpos($agt, 'opera 2') !== false || strpos($agt, 'opera/2') !== false;
$browser['opera3'] = strpos($agt, 'opera 3') !== false || strpos($agt, 'opera/3') !== false;
$browser['opera4'] = strpos($agt, 'opera 4') !== false || strpos($agt, 'opera/4') !== false;
$browser['opera5'] = strpos($agt, 'opera 5') !== false || strpos($agt, 'opera/5') !== false;
$browser['opera6'] = strpos($agt, 'opera 6') !== false || strpos($agt, 'opera/6') !== false;
$browser['opera7'] = strpos($agt, 'opera 7') !== false || strpos($agt, 'opera/7') !== false;
$browser['opera8'] = strpos($agt, 'opera 8') !== false || strpos($agt, 'opera/8') !== false;
$browser['opera9'] = strpos($agt, 'opera 9') !== false || strpos($agt, 'opera/9') !== false;
$browser['opera5up'] = $browser['opera'] && !$browser['opera2'] && !$browser['opera3'] && !$browser['opera4'];
$browser['opera6up'] = $browser['opera'] && !$browser['opera2'] && !$browser['opera3'] && !$browser['opera4'] && !$browser['opera5'];
$browser['opera7up'] = $browser['opera'] && !$browser['opera2'] && !$browser['opera3'] && !$browser['opera4'] && !$browser['opera5'] && !$browser['opera6'];
$browser['opera8up'] = $browser['opera'] && !$browser['opera2'] && !$browser['opera3'] && !$browser['opera4'] && !$browser['opera5'] && !$browser['opera6'] && !$browser['opera7'];
$browser['opera9up'] = $browser['opera'] && !$browser['opera2'] && !$browser['opera3'] && !$browser['opera4'] && !$browser['opera5'] && !$browser['opera6'] && !$browser['opera7'] && !$browser['opera8'];
$browser['belowopera8'] = $browser['opera'] && !$browser['opera8up'];
$browser['aol'] = strpos($agt, 'aol') !== false;
$browser['aol3'] = $browser['aol'] && $browser['ie3'];
$browser['aol4'] = $browser['aol'] && $browser['ie4'];
$browser['aol5'] = strpos($agt, 'aol 5') !== false;
$browser['aol6'] = strpos($agt, 'aol 6') !== false;
$browser['aol7'] = strpos($agt, 'aol 7') !== false || strpos($agt, 'aol7') !== false;
$browser['aol8'] = strpos($agt, 'aol 8') !== false || strpos($agt, 'aol8') !== false;
$browser['webtv'] = strpos($agt, 'webtv') !== false;
$browser['aoltv'] = $browser['tvnavigator'] = strpos($agt, 'navio') !== false || strpos($agt, 'navio_aoltv') !== false;
$browser['hotjava'] = strpos($agt, 'hotjava') !== false;
$browser['hotjava3'] = $browser['hotjava'] && $majorVersion == 3;
$browser['hotjava3up'] = $browser['hotjava'] && $majorVersion >= 3;
$browser['iemobile'] = strpos($agt, 'iemobile') !== false || strpos($agt, 'windows ce') !== false && (strpos($agt, 'ppc') !== false || strpos($agt, 'smartphone') !== false);
}
if ($detectFlags[NET_USERAGENT_DETECT_ALL] ||
($detectFlags[NET_USERAGENT_DETECT_BROWSER] && $detectFlags[NET_USERAGENT_DETECT_FEATURES])) {
// Javascript Check
if ($browser['ns2'] || $browser['ie3']) {
Net_UserAgent_Detect::setFeature('javascript', 1.0);
}
elseif ($browser['iemobile']) {
// no javascript
}
elseif ($browser['opera5up']) {
Net_UserAgent_Detect::setFeature('javascript', 1.3);
}
elseif ($browser['opera'] || $browser['ns3']) {
Net_UserAgent_Detect::setFeature('javascript', 1.1);
}
elseif (($browser['ns4'] && ($version <= 4.05)) || $browser['ie4']) {
Net_UserAgent_Detect::setFeature('javascript', 1.2);
}
elseif (($browser['ie5up'] && strpos($agt, 'mac') !== false) || $browser['konq']) {
Net_UserAgent_Detect::setFeature('javascript', 1.4);
}
// I can't believe IE6 still has javascript 1.3, what a shitty browser
elseif (($browser['ns4'] && ($version > 4.05)) || $browser['ie5up'] || $browser['hotjava3up']) {
Net_UserAgent_Detect::setFeature('javascript', 1.3);
}
elseif ($browser['ns6up'] || $browser['gecko'] || $browser['netgem']) {
Net_UserAgent_Detect::setFeature('javascript', 1.5);
}
}
/** OS Check **/
if ($detectFlags[NET_USERAGENT_DETECT_ALL] || $detectFlags[NET_USERAGENT_DETECT_OS]) {
$os['win'] = strpos($agt, 'win') !== false || strpos($agt, '16bit') !== false;
$os['win95'] = strpos($agt, 'win95') !== false || strpos($agt, 'windows 95') !== false;
$os['win16'] = strpos($agt, 'win16') !== false || strpos($agt, '16bit') !== false || strpos($agt, 'windows 3.1') !== false || strpos($agt, 'windows 16-bit') !== false;
$os['win31'] = strpos($agt, 'windows 3.1') !== false || strpos($agt, 'win16') !== false || strpos($agt, 'windows 16-bit') !== false;
$os['winme'] = strpos($agt, 'win 9x 4.90') !== false;
$os['wince'] = strpos($agt, 'windows ce') !== false;
$os['win2k'] = strpos($agt, 'windows nt 5.0') !== false;
$os['winxp'] = strpos($agt, 'windows nt 5.1') !== false;
$os['win2003'] = strpos($agt, 'windows nt 5.2') !== false;
$os['win98'] = strpos($agt, 'win98') !== false || strpos($agt, 'windows 98') !== false;
$os['win9x'] = $os['win95'] || $os['win98'];
$os['winnt'] = (strpos($agt, 'winnt') !== false || strpos($agt, 'windows nt') !== false) && strpos($agt, 'windows nt 5') === false;
$os['win32'] = $os['win95'] || $os['winnt'] || $os['win98'] || $majorVersion >= 4 && strpos($agt, 'win32') !== false || strpos($agt, '32bit') !== false;
$os['os2'] = strpos($agt, 'os/2') !== false || strpos($agt, 'ibm-webexplorer') !== false;
$os['mac'] = strpos($agt, 'mac') !== false;
$os['mac68k'] = $os['mac'] && (strpos($agt, '68k') !== false || strpos($agt, '68000') !== false);
$os['macppc'] = $os['mac'] && (strpos($agt, 'ppc') !== false || strpos($agt, 'powerpc') !== false);
$os['sun'] = strpos($agt, 'sunos') !== false;
$os['sun4'] = strpos($agt, 'sunos 4') !== false;
$os['sun5'] = strpos($agt, 'sunos 5') !== false;
$os['suni86'] = $os['sun'] && strpos($agt, 'i86') !== false;
$os['irix'] = strpos($agt, 'irix') !== false;
$os['irix5'] = strpos($agt, 'irix 5') !== false;
$os['irix6'] = strpos($agt, 'irix 6') !== false || strpos($agt, 'irix6') !== false;
$os['hpux'] = strpos($agt, 'hp-ux') !== false;
$os['hpux9'] = $os['hpux'] && strpos($agt, '09.') !== false;
$os['hpux10'] = $os['hpux'] && strpos($agt, '10.') !== false;
$os['aix'] = strpos($agt, 'aix') !== false;
$os['aix1'] = strpos($agt, 'aix 1') !== false;
$os['aix2'] = strpos($agt, 'aix 2') !== false;
$os['aix3'] = strpos($agt, 'aix 3') !== false;
$os['aix4'] = strpos($agt, 'aix 4') !== false;
$os['linux'] = strpos($agt, 'inux') !== false;
$os['sco'] = strpos($agt, 'sco') !== false || strpos($agt, 'unix_sv') !== false;
$os['unixware'] = strpos($agt, 'unix_system_v') !== false;
$os['mpras'] = strpos($agt, 'ncr') !== false;
$os['reliant'] = strpos($agt, 'reliant') !== false;
$os['dec'] = strpos($agt, 'dec') !== false || strpos($agt, 'osf1') !== false || strpos($agt, 'dec_alpha') !== false || strpos($agt, 'alphaserver') !== false || strpos($agt, 'ultrix') !== false || strpos($agt, 'alphastation') !== false;
$os['sinix'] = strpos($agt, 'sinix') !== false;
$os['freebsd'] = strpos($agt, 'freebsd') !== false;
$os['bsd'] = strpos($agt, 'bsd') !== false;
$os['unix'] = strpos($agt, 'x11') !== false || strpos($agt, 'unix') !== false || $os['sun'] || $os['irix'] || $os['hpux'] || $os['sco'] || $os['unixware'] || $os['mpras'] || $os['reliant'] || $os['dec'] || $os['sinix'] || $os['aix'] || $os['linux'] || $os['bsd'] || $os['freebsd'];
$os['vms'] = strpos($agt, 'vax') !== false || strpos($agt, 'openvms') !== false;
}
// Setup the quirks
if ($detectFlags[NET_USERAGENT_DETECT_ALL] ||
($detectFlags[NET_USERAGENT_DETECT_BROWSER] && $detectFlags[NET_USERAGENT_DETECT_QUIRKS])) {
if ($browser['konq']) {
Net_UserAgent_Detect::setQuirk('empty_file_input_value');
}
if ($browser['ie']) {
Net_UserAgent_Detect::setQuirk('cache_ssl_downloads');
}
if ($browser['ie6']) {
Net_UserAgent_Detect::setQuirk('scrollbar_in_way');
}
if ($browser['ie5']) {
Net_UserAgent_Detect::setQuirk('break_disposition_header');
}
if ($browser['ie7']) {
Net_UserAgent_Detect::setQuirk('popups_disabled');
}
if ($browser['ns6']) {
Net_UserAgent_Detect::setQuirk('popups_disabled');
Net_UserAgent_Detect::setQuirk('must_cache_forms');
}
if ($browser['nav'] && $subVersion < .79) {
Net_UserAgent_Detect::setQuirk('nested_table_render_bug');
}
}
// Set features
if ($detectFlags[NET_USERAGENT_DETECT_ALL] ||
($detectFlags[NET_USERAGENT_DETECT_BROWSER] && $detectFlags[NET_USERAGENT_DETECT_FEATURES])) {
if ($browser['gecko']) {
preg_match(';gecko/([\d]+)\b;i', $agt, $matches);
Net_UserAgent_Detect::setFeature('gecko', $matches[1]);
}
if ($browser['gecko'] || ($browser['ie5up'] && !$browser['iemobile']) || $browser['konq'] || $browser['opera8up'] && !$os['wince']) {
Net_UserAgent_Detect::setFeature('ajax');
}
if ($browser['ns6up'] || $browser['opera5up'] || $browser['konq'] || $browser['netgem']) {
Net_UserAgent_Detect::setFeature('dom');
}
if ($browser['ie4up'] || $browser['ns4up'] || $browser['opera5up'] || $browser['konq'] || $browser['netgem']) {
Net_UserAgent_Detect::setFeature('dhtml');
}
if ($browser['firefox1.5'] || $browser['firefox2.x'] || $browser['opera9up']) {
Net_UserAgent_Detect::setFeature('svg');
}
if ($browser['gecko'] || $browser['ns6up'] || $browser['ie5up'] || $browser['konq'] || $browser['opera7up']) {
Net_UserAgent_Detect::setFeature('css2');
}
}
if ($detectFlags[NET_USERAGENT_DETECT_ALL] || $detectFlags[NET_USERAGENT_DETECT_ACCEPT]) {
$mimetypes = preg_split(';[\s,]+;', substr(getenv('HTTP_ACCEPT'), 0, strpos(getenv('HTTP_ACCEPT') . ';', ';')), -1, PREG_SPLIT_NO_EMPTY);
Net_UserAgent_Detect::setAcceptType((array) $mimetypes, 'mimetype');
$languages = preg_split(';[\s,]+;', substr(getenv('HTTP_ACCEPT_LANGUAGE'), 0, strpos(getenv('HTTP_ACCEPT_LANGUAGE') . ';', ';')), -1, PREG_SPLIT_NO_EMPTY);
if (empty($languages)) {
$languages = 'en';
}
Net_UserAgent_Detect::setAcceptType((array) $languages, 'language');
$encodings = preg_split(';[\s,]+;', substr(getenv('HTTP_ACCEPT_ENCODING'), 0, strpos(getenv('HTTP_ACCEPT_ENCODING') . ';', ';')), -1, PREG_SPLIT_NO_EMPTY);
Net_UserAgent_Detect::setAcceptType((array) $encodings, 'encoding');
$charsets = preg_split(';[\s,]+;', substr(getenv('HTTP_ACCEPT_CHARSET'), 0, strpos(getenv('HTTP_ACCEPT_CHARSET') . ';', ';')), -1, PREG_SPLIT_NO_EMPTY);
Net_UserAgent_Detect::setAcceptType((array) $charsets, 'charset');
}
}
// }}}
// {{{ setOption()
/**
* Sets a class option. The available settings are:
* o 'userAgent' => The user agent string to detect (useful for
* checking a string manually).
* o 'detectOptions' => The level of checking to do. A single level
* or an array of options. Default is NET_USERAGENT_DETECT_ALL.
*
* @param string $in_field The option field (userAgent or detectOptions)
* @param mixed $in_value The value for the field
*/
function setOption($in_field, $in_value)
{
$options = &Net_UserAgent_Detect::_getStaticProperty('options');
$options[$in_field] = $in_value;
}
// }}}
// {{{ isBrowser()
/**
* Look up the provide browser flag and return a boolean value
*
* Given one of the flags listed in the properties, this function will return
* the value associated with that flag.
*
* @param string $in_match flag to lookup
*
* @access public
* @return boolean whether or not the browser satisfies this flag
*/
function isBrowser($in_match)
{
Net_UserAgent_Detect::detect();
$browser = &Net_UserAgent_Detect::_getStaticProperty('browser');
return isset($browser[strtolower($in_match)]) ? $browser[strtolower($in_match)] : false;
}
// }}}
// {{{ getBrowser()
/**
* Since simply returning the "browser" is somewhat ambiguous since there
* are different ways to classify the browser, this function works by taking
* an expect list and returning the string of the first match, so put the important
* ones first in the array.
*
* @param array $in_expectList the browser flags to search for
*
* @access public
* @return string first flag that matches
*/
function getBrowser($in_expectList)
{
Net_UserAgent_Detect::detect();
$browser = &Net_UserAgent_Detect::_getStaticProperty('browser');
foreach((array) $in_expectList as $brwsr) {
if (!empty($browser[strtolower($brwsr)])) {
return $brwsr;
}
}
}
// }}}
// {{{ getBrowserString()
/**
* This function returns the vendor string corresponding to the flag.
*
* Either use the default matches or pass in an associative array of
* flags and corresponding vendor strings. This function will find
* the highest version flag and return the vendor string corresponding
* to the appropriate flag. Be sure to pass in the flags in ascending order
* if you want a basic matches first, followed by more detailed matches.
*
* @param array $in_vendorStrings (optional) array of flags matched with vendor strings
*
* @access public
* @return string vendor string matches appropriate flag
*/
function getBrowserString($in_vendorStrings = null)
{
if (is_null($in_vendorStrings)) {
$in_vendorStrings = array (
'ie' => 'Microsoft Internet Explorer',
'ie4up' => 'Microsoft Internet Explorer 4.x',
'ie5up' => 'Microsoft Internet Explorer 5.x',
'ie6up' => 'Microsoft Internet Explorer 6.x',
'ie7up' => 'Microsoft Internet Explorer 7.x',
'opera4' => 'Opera 4.x',
'opera5up' => 'Opera 5.x',
'nav' => 'Netscape Navigator',
'ns4' => 'Netscape 4.x',
'ns6up' => 'Mozilla/Netscape 6.x',
'firefox0.x' => 'Firefox 0.x',
'firefox1.x' => 'Firefox 1.x',
'firefox1.5' => 'Firefox 1.5',
'firefox2.x' => 'Firefox 2.x',
'konq' => 'Konqueror/Safari',
'netgem' => 'Netgem/iPlayer');
}
Net_UserAgent_Detect::detect();
$browser = &Net_UserAgent_Detect::_getStaticProperty('browser');
foreach((array) $in_vendorStrings as $flag => $string) {
if (!empty($browser[$flag])) {
$vendorString = $string;
}
}
// if there are no matches just use the user agent leading idendifier (usually Mozilla)
if (!isset($vendorString)) {
$leadingIdentifier = &Net_UserAgent_Detect::_getStaticProperty('leadingIdentifier');
$vendorString = $leadingIdentifier;
}
return $vendorString;
}
// }}}
// {{{ isIE()
/**
* Determine if the browser is an Internet Explorer browser
*
* @access public
* @return bool whether or not this browser is an ie browser
*/
function isIE()
{
Net_UserAgent_Detect::detect();
$browser = &Net_UserAgent_Detect::_getStaticProperty('browser');
return !empty($browser['ie']);
}
// }}}
// {{{ isNavigator()
/**
* Determine if the browser is a Netscape Navigator browser
*
* @access public
* @return bool whether or not this browser is a Netscape Navigator browser
*/
function isNavigator()
{
Net_UserAgent_Detect::detect();
$browser = &Net_UserAgent_Detect::_getStaticProperty('browser');
return !empty($browser['nav']);
}
// }}}
// {{{ isNetscape()
/**
* Determine if the browser is a Netscape or Mozilla browser
*
* Note that this function is not the same as isNavigator, since the
* new Mozilla browsers are still sponsered by Netscape, and hence are
* Netscape products, but not the original Navigators
*
* @access public
* @return bool whether or not this browser is a Netscape product
*/
function isNetscape()
{
Net_UserAgent_Detect::detect();
$browser = &Net_UserAgent_Detect::_getStaticProperty('browser');
return !empty($browser['ns4up']);
}
// }}}
// {{{ isOS()
/**
* Look up the provide OS flag and return a boolean value
*
* Given one of the flags listed in the properties, this function will return
* the value associated with that flag for the operating system.
*
* @param string $in_match flag to lookup
*
* @access public
* @return boolean whether or not the OS satisfies this flag
*/
function isOS($in_match)
{
Net_UserAgent_Detect::detect();
$os = &Net_UserAgent_Detect::_getStaticProperty('os');
return isset($os[strtolower($in_match)]) ? $os[strtolower($in_match)] : false;
}
// }}}
// {{{ getOS()
/**
* Since simply returning the "os" is somewhat ambiguous since there
* are different ways to classify the browser, this function works by taking
* an expect list and returning the string of the first match, so put the important
* ones first in the array.
*
* @access public
* @return string first flag that matches
*/
function getOS($in_expectList)
{
Net_UserAgent_Detect::detect();
$os = &Net_UserAgent_Detect::_getStaticProperty('os');
foreach((array) $in_expectList as $expectOs) {
if (!empty($os[strtolower($expectOs)])) {
return $expectOs;
}
}
}
// }}}
// {{{ getOSString()
/**
* This function returns the os string corresponding to the flag.
*
* Either use the default matches or pass in an associative array of
* flags and corresponding os strings. This function will find
* the highest version flag and return the os string corresponding
* to the appropriate flag. Be sure to pass in the flags in ascending order
* if you want a basic matches first, followed by more detailed matches.
*
* @param array $in_osStrings (optional) array of flags matched with os strings
*
* @access public
* @return string os string matches appropriate flag
*/
function getOSString($in_osStrings = null)
{
if (is_null($in_osStrings)) {
$in_osStrings = array(
'win' => 'Microsoft Windows',
'wince' => 'Microsoft Windows CE',
'win9x' => 'Microsoft Windows 9x',
'winme' => 'Microsoft Windows Millenium',
'win2k' => 'Microsoft Windows 2000',
'winnt' => 'Microsoft Windows NT',
'winxp' => 'Microsoft Windows XP',
'win2003' => 'Microsoft Windows 2003',
'mac' => 'Macintosh',
'unix' => 'Linux/Unix');
}
Net_UserAgent_Detect::detect();
$osString = 'Unknown';
$os = &Net_UserAgent_Detect::_getStaticProperty('os');
foreach((array) $in_osStrings as $flag => $string) {
if (!empty($os[$flag])) {
$osString = $string;
}
}
return $osString;
}
// }}}
// {{{ setQuirk()
/**
* Set a unique behavior for the current browser.
*
* Many client browsers do some really funky things, and this
* mechanism allows the coder to determine if an excepetion must
* be made with the current client.
*
* @param string $in_quirk The quirk to set
* @param string $in_hasQuirk (optional) Does the browser have the quirk?
*
* @access public
* @return void
*/
function setQuirk($in_quirk, $in_hasQuirk = true)
{
$quirks = &Net_UserAgent_Detect::_getStaticProperty('quirks');
$hasQuirk = !empty($in_hasQuirk);
$quirks[strtolower($in_quirk)] = $hasQuirk;
}
// }}}
// {{{ hasQuirk()
/**
* Check a unique behavior for the current browser.
*
* Many client browsers do some really funky things, and this
* mechanism allows the coder to determine if an excepetion must
* be made with the current client.
*
* @param string $in_quirk The quirk to detect
*
* @access public
* @return bool whether or not browser has this quirk
*/
function hasQuirk($in_quirk)
{
return (bool) Net_UserAgent_Detect::getQuirk($in_quirk);
}
// }}}
// {{{ getQuirk()
/**
* Get the unique behavior for the current browser.
*
* Many client browsers do some really funky things, and this
* mechanism allows the coder to determine if an excepetion must
* be made with the current client.
*
* @param string $in_quirk The quirk to detect
*
* @access public
* @return string value of the quirk, in this case usually a boolean
*/
function getQuirk($in_quirk)
{
Net_UserAgent_Detect::detect();
$quirks = &Net_UserAgent_Detect::_getStaticProperty('quirks');
return isset($quirks[strtolower($in_quirk)]) ? $quirks[strtolower($in_quirk)] : null;
}
// }}}
// {{{ setFeature()
/**
* Set capabilities for the current browser.
*
* Since the capabilities of client browsers vary widly, this interface
* helps keep track of the core features of a client, such as if the client
* supports dhtml, dom, javascript, etc.
*
* @param string $in_feature The feature to set
* @param string $in_hasFeature (optional) Does the browser have the feature?
*
* @access public
* @return void
*/
function setFeature($in_feature, $in_hasFeature = true)
{
$features = &Net_UserAgent_Detect::_getStaticProperty('features');
$features[strtolower($in_feature)] = $in_hasFeature;
}
// }}}
// {{{ hasFeature()
/**
* Check the capabilities for the current browser.
*
* Since the capabilities of client browsers vary widly, this interface
* helps keep track of the core features of a client, such as if the client
* supports dhtml, dom, javascript, etc.
*
* @param string $in_feature The feature to detect
*
* @access public
* @return bool whether or not the current client has this feature
*/
function hasFeature($in_feature)
{
return (bool) Net_UserAgent_Detect::getFeature($in_feature);
}
// }}}
// {{{ getFeature()
/**
* Get the capabilities for the current browser.
*
* Since the capabilities of client browsers vary widly, this interface
* helps keep track of the core features of a client, such as if the client
* supports dhtml, dom, javascript, etc.
*
* @param string $in_feature The feature to detect
*
* @access public
* @return string value of the feature requested
*/
function getFeature($in_feature)
{
Net_UserAgent_Detect::detect();
$features = &Net_UserAgent_Detect::_getStaticProperty('features');
return isset($features[strtolower($in_feature)]) ? $features[strtolower($in_feature)] : null;
}
// }}}
// {{{ getAcceptType()
/**
* Retrive the accept type for the current browser.
*
* To keep track of the mime-types, languages, charsets and encodings
* that each browser accepts we use associative arrays for each type.
* This function works like getBrowser() as it takes an expect list
* and returns the first match. For instance, to find the language
* you would pass in your allowed languages and see if any of the
* languages set in the browser match.
*
* @param string $in_expectList values to check
* @param string $in_type type of accept
*
* @access public
* @return string the first matched value
*/
function getAcceptType($in_expectList, $in_type)
{
Net_UserAgent_Detect::detect();
$type = strtolower($in_type);
if ($type == 'mimetype' || $type == 'language' || $type == 'charset' || $type == 'encoding') {
$typeArray = &Net_UserAgent_Detect::_getStaticProperty($type);
foreach((array) $in_expectList as $match) {
if (!empty($typeArray[$match])) {
return $match;
}
}
}
return null;
}
// }}}
// {{{ setAcceptType()
/**
* Set the accept types for the current browser.
*
* To keep track of the mime-types, languages, charsets and encodings
* that each browser accepts we use associative arrays for each type.
* This function takes and array of accepted values for the type and
* records them for retrieval.
*
* @param array $in_values values of the accept type
* @param string $in_type type of accept
*
* @access public
* @return void
*/
function setAcceptType($in_values, $in_type)
{
$type = strtolower($in_type);
if ($type == 'mimetype' || $type == 'language' || $type == 'charset' || $type == 'encoding') {
$typeArray = &Net_UserAgent_Detect::_getStaticProperty($type);
foreach((array) $in_values as $value) {
$typeArray[$value] = true;
}
}
}
// }}}
// {{{ hasAcceptType()
/**
* Check the accept types for the current browser.
*
* To keep track of the mime-types, languages, charsets and encodings
* that each browser accepts we use associative arrays for each type.
* This function checks the array for the given type and determines if
* the browser accepts it.
*
* @param string $in_value values to check
* @param string $in_type type of accept
*
* @access public
* @return bool whether or not the value is accept for this type
*/
function hasAcceptType($in_value, $in_type)
{
return (bool) Net_UserAgent_Detect::getAcceptType((array) $in_value, $in_type);
}
// }}}
// {{{ getUserAgent()
/**
* Return the user agent string that is being worked on
*
* @access public
* @return string user agent
*/
function getUserAgent()
{
Net_UserAgent_Detect::detect();
$userAgent = &Net_UserAgent_Detect::_getStaticProperty('userAgent');
return $userAgent;
}
// }}}
// {{{ _getStaticProperty()
/**
* Copy of getStaticProperty() from PEAR.php to avoid having to
* include PEAR.php
*
* @access private
* @param string $var The variable to retrieve.
* @return mixed A reference to the variable. If not set it will be
* auto initialised to NULL.
*/
function &_getStaticProperty($var)
{
static $properties;
return $properties[$var];
}
// }}}
}
?>

View File

@@ -0,0 +1,123 @@
<?php
// +----------------------------------------------------------------------+
// | PHP version 4.2 |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 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: Lucas Nealan <lucas@facebook.com> |
// +----------------------------------------------------------------------+
// $Id: APC.php,v 1.1 2007/09/19 21:35:22 jrust Exp $
require_once 'Net_UserAgent/detect.php';
class Net_UserAgent_Detect_APC extends Net_UserAgent_Detect
{
var $key = '';
function Net_UserAgent_Detect_APC($in_userAgent = null, $in_detect = null, $ua_cache_window = 600)
{
$data = '';
$restored = false;
$ua_cache_timeout = apc_fetch('useragent:cache_timeout'); // don't cache after time period
if(!class_exists('G')){
$realdocuroot = str_replace( '\\', '/', $_SERVER['DOCUMENT_ROOT'] );
$docuroot = explode( '/', $realdocuroot );
array_pop( $docuroot );
$pathhome = implode( '/', $docuroot ) . '/';
array_pop( $docuroot );
$pathTrunk = implode( '/', $docuroot ) . '/';
require_once($pathTrunk.'gulliver/system/class.g.php');
}
if ($ua_cache_window > 0) {
if (!$ua_cache_timeout) {
// check apc uptime and disable after x mins
$apc_data = apc_cache_info('file', true);
if (isset($apc_data['start_time'])) {
$uptime = $apc_data['start_time'];
if (time() - $uptime > $ua_cache_window) { // timeout and disable after 10 minutes of uptime
apc_store('useragent:cache_timeout', true);
$ua_cache_timeout = true; // don't cache this one either
}
}
}
if (!$this->key) {
$key_flags = '';
if ($in_detect !== null) {
$key_flags = implode('-', $in_detect);
}
$this->key = 'useragent:'.G::encryptOld($in_userAgent.$key_flags);
}
if ($data = apc_fetch($this->key)) {
$success = null;
$data = unserialize($data);
if ($data) {
$restored = $this->cache_restore($data);
}
}
}
if (!$data) {
$this->detect($in_userAgent, $in_detect);
if ($ua_cache_window > 0 && !$ua_cache_timeout) {
$this->cache_save();
}
}
}
function &singleton($in_userAgent = null, $in_detect = null)
{
static $instance;
if (!isset($instance)) {
$instance = new Net_UserAgent_Detect_APC($in_userAgent, $in_detect);
}
return $instance;
}
function cache_restore($cache)
{
if (is_array($cache)) {
foreach($cache as $prop => $value) {
$ptr = Net_UserAgent_Detect::_getStaticProperty($prop);
$ptr = $value;
}
return true;
}
return false;
}
function cache_save()
{
if ($this->key) {
$data = array('browser' => Net_UserAgent_Detect::_getStaticProperty('browser'),
'features' => Net_UserAgent_Detect::_getStaticProperty('features'),
'leadingIdentifier' => Net_UserAgent_Detect::_getStaticProperty('leadingIdentifier'),
'majorVersion' => Net_UserAgent_Detect::_getStaticProperty('majorVersion'),
'options' => Net_UserAgent_Detect::_getStaticProperty('options'),
'os' => Net_UserAgent_Detect::_getStaticProperty('os'),
'quirks' => Net_UserAgent_Detect::_getStaticProperty('quirks'),
'subVersion' => Net_UserAgent_Detect::_getStaticProperty('subVersion'),
'userAgent' => Net_UserAgent_Detect::_getStaticProperty('userAgent'),
'version' => Net_UserAgent_Detect::_getStaticProperty('version'),
);
apc_store($this->key, serialize($data));
}
}
}
?>