diff --git a/framework/src/Maveriks/WebApplication.php b/framework/src/Maveriks/WebApplication.php index e6308a748..2ffab8d90 100644 --- a/framework/src/Maveriks/WebApplication.php +++ b/framework/src/Maveriks/WebApplication.php @@ -285,7 +285,7 @@ class WebApplication Services\Api::setWorkspace(SYS_SYS); $cacheDir = defined("PATH_WORKSPACE") ? PATH_WORKSPACE : (defined("PATH_C")? PATH_C: sys_get_temp_dir()); - $sysConfig = \System::getSystemConfiguration(); + $sysConfig = \PMSystem::getSystemConfiguration(); \Luracast\Restler\Defaults::$cacheDirectory = $cacheDir; $productionMode = (bool) !(isset($sysConfig["service_api_debug"]) && $sysConfig["service_api_debug"]); @@ -449,7 +449,7 @@ class WebApplication \Bootstrap::initVendors(); \Bootstrap::LoadSystem( 'monologProvider' ); - $arraySystemConfiguration = \System::getSystemConfiguration(); + $arraySystemConfiguration = \PMSystem::getSystemConfiguration(); ini_set('date.timezone', $arraySystemConfiguration['time_zone']); //Set Time Zone @@ -497,7 +497,7 @@ class WebApplication exit(0); } - $arraySystemConfiguration = \System::getSystemConfiguration('', '', SYS_SYS); + $arraySystemConfiguration = \PMSystem::getSystemConfiguration('', '', SYS_SYS); //Do not change any of these settings directly, use env.ini instead ini_set('display_errors', $arraySystemConfiguration['display_errors']); diff --git a/gulliver/system/class.bootstrap.php b/gulliver/system/class.bootstrap.php index 2ef7e1ac6..d05379ae4 100644 --- a/gulliver/system/class.bootstrap.php +++ b/gulliver/system/class.bootstrap.php @@ -20,12 +20,7 @@ class Bootstrap public static function getSystemConfiguration($globalIniFile = '', $wsIniFile = '', $wsName = '') { - // (!) Backward compatibility, the original function is in System class - if (! class_exists("System")) { - - } - - return System::getSystemConfiguration($globalIniFile, $wsIniFile, $wsName); + return PMSystem::getSystemConfiguration($globalIniFile, $wsIniFile, $wsName); } //below this line, still not approved methods @@ -988,7 +983,7 @@ class Bootstrap */ public function getCheckSum($files) { - $key = System::getVersion(); + $key = PMSystem::getVersion(); if (!is_array($files)) { $tmp = $files; @@ -1881,7 +1876,7 @@ class Bootstrap /* Fix to prevent use uxs skin outside siplified interface, because that skin is not compatible with others interfaces */ if ($args['SYS_SKIN'] == 'uxs' && $args['SYS_COLLECTION'] != 'home' && $args['SYS_COLLECTION'] != 'cases') { - $config = System::getSystemConfiguration(); + $config = PMSystem::getSystemConfiguration(); $args['SYS_SKIN'] = $config['default_skin']; } diff --git a/gulliver/system/class.codeScanner.php b/gulliver/system/class.codeScanner.php index 1b59367ac..affd4826d 100644 --- a/gulliver/system/class.codeScanner.php +++ b/gulliver/system/class.codeScanner.php @@ -29,7 +29,7 @@ class CodeScanner $workspace = new workspaceTools($option); if ($workspace->workspaceExists()) { - $arraySystemConfiguration = System::getSystemConfiguration('', '', $workspace->name); + $arraySystemConfiguration = PMSystem::getSystemConfiguration('', '', $workspace->name); $flag = (int)($arraySystemConfiguration['enable_blacklist']) == 1; } break; diff --git a/gulliver/system/class.g.php b/gulliver/system/class.g.php index ccdc5dbc1..8563fc5aa 100644 --- a/gulliver/system/class.g.php +++ b/gulliver/system/class.g.php @@ -798,7 +798,7 @@ class G /* Fix to prevent use uxs skin outside siplified interface, because that skin is not compatible with others interfaces*/ if ($args['SYS_SKIN'] == 'uxs' && $args['SYS_COLLECTION'] != 'home' && $args['SYS_COLLECTION'] != 'cases') { - $config = System::getSystemConfiguration(); + $config = PMSystem::getSystemConfiguration(); $args['SYS_SKIN'] = $config['default_skin']; } @@ -4551,7 +4551,7 @@ class G */ public function getCheckSum ($files) { - $key = System::getVersion(); + $key = PMSystem::getVersion(); if (! is_array( $files )) { $tmp = $files; @@ -5182,7 +5182,7 @@ class G public static function browserCacheFilesGetUid() { - $sysConf = System::getSystemConfiguration(PATH_CONFIG . "env.ini"); + $sysConf = PMSystem::getSystemConfiguration(PATH_CONFIG . "env.ini"); return (isset($sysConf["browser_cache_files_uid"]))? $sysConf["browser_cache_files_uid"] : null; } @@ -5307,7 +5307,7 @@ class G */ public static function log($message, $pathData = PATH_DATA, $file = 'cron.log') { - $config = System::getSystemConfiguration(); + $config = PMSystem::getSystemConfiguration(); $oLogger = Logger::getSingleton($pathData, PATH_SEP, $file); diff --git a/gulliver/system/class.soapNtlm.php b/gulliver/system/class.soapNtlm.php index 988568c75..131d9f5f5 100644 --- a/gulliver/system/class.soapNtlm.php +++ b/gulliver/system/class.soapNtlm.php @@ -200,7 +200,7 @@ class soapNtlm curl_setopt( $this->ch, CURLOPT_USERPWD, $this->getuser() . ':' . $this->getpassword() ); // Ankit's code //Apply proxy settings if (class_exists( 'System' )) { - $sysConf = System::getSystemConfiguration(); + $sysConf = PMSystem::getSystemConfiguration(); $sysConf = $filter->xssFilterHard($sysConf); if ($sysConf['proxy_host'] != '') { curl_setopt( $this->ch, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '') ); @@ -243,7 +243,7 @@ class NTLMSoapClient extends SoapClient //Apply proxy settings if (class_exists( 'System' )) { - $sysConf = System::getSystemConfiguration(); + $sysConf = PMSystem::getSystemConfiguration(); if ($sysConf['proxy_host'] != '') { curl_setopt( $ch, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '') ); if ($sysConf['proxy_port'] != '') { diff --git a/gulliver/thirdparty/pear/Archive/Tar.php b/gulliver/thirdparty/pear/Archive/Tar.php deleted file mode 100644 index 8197d94aa..000000000 --- a/gulliver/thirdparty/pear/Archive/Tar.php +++ /dev/null @@ -1,1993 +0,0 @@ - - * 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. - * - * 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 File_Formats - * @package Archive_Tar - * @author Vincent Blavet - * @copyright 1997-2010 The Authors - * @license http://www.opensource.org/licenses/bsd-license.php New BSD License - * @version CVS: $Id$ - * @link http://pear.php.net/package/Archive_Tar - */ - -require_once 'PEAR.php'; - -define('ARCHIVE_TAR_ATT_SEPARATOR', 90001); -define('ARCHIVE_TAR_END_BLOCK', pack("a512", '')); - -/** - * Creates a (compressed) Tar archive - * - * @package Archive_Tar - * @author Vincent Blavet - * @license http://www.opensource.org/licenses/bsd-license.php New BSD License - * @version $Revision$ - */ -class Archive_Tar extends PEAR -{ - /** - * @var string Name of the Tar - */ - var $_tarname=''; - - /** - * @var boolean if true, the Tar file will be gzipped - */ - var $_compress=false; - - /** - * @var string Type of compression : 'none', 'gz' or 'bz2' - */ - var $_compress_type='none'; - - /** - * @var string Explode separator - */ - var $_separator=' '; - - /** - * @var file descriptor - */ - var $_file=0; - - /** - * @var string Local Tar name of a remote Tar (http:// or ftp://) - */ - var $_temp_tarname=''; - - /** - * @var string regular expression for ignoring files or directories - */ - var $_ignore_regexp=''; - - /** - * @var object PEAR_Error object - */ - var $error_object=null; - - // {{{ constructor - /** - * Archive_Tar Class constructor. This flavour of the constructor only - * declare a new Archive_Tar object, identifying it by the name of the - * tar file. - * If the compress argument is set the tar will be read or created as a - * gzip or bz2 compressed TAR file. - * - * @param string $p_tarname The name of the tar archive to create - * @param string $p_compress can be null, 'gz' or 'bz2'. This - * parameter indicates if gzip or bz2 compression - * is required. For compatibility reason the - * boolean value 'true' means 'gz'. - * - * @access public - */ - function Archive_Tar($p_tarname, $p_compress = null) - { - $this->PEAR(); - $this->_compress = false; - $this->_compress_type = 'none'; - if (($p_compress === null) || ($p_compress == '')) { - if (@file_exists($p_tarname)) { - if ($fp = @fopen($p_tarname, "rb")) { - // look for gzip magic cookie - $data = fread($fp, 2); - fclose($fp); - if ($data == "\37\213") { - $this->_compress = true; - $this->_compress_type = 'gz'; - // No sure it's enought for a magic code .... - } elseif ($data == "BZ") { - $this->_compress = true; - $this->_compress_type = 'bz2'; - } - } - } else { - // probably a remote file or some file accessible - // through a stream interface - if (substr($p_tarname, -2) == 'gz') { - $this->_compress = true; - $this->_compress_type = 'gz'; - } elseif ((substr($p_tarname, -3) == 'bz2') || - (substr($p_tarname, -2) == 'bz')) { - $this->_compress = true; - $this->_compress_type = 'bz2'; - } - } - } else { - if (($p_compress === true) || ($p_compress == 'gz')) { - $this->_compress = true; - $this->_compress_type = 'gz'; - } else if ($p_compress == 'bz2') { - $this->_compress = true; - $this->_compress_type = 'bz2'; - } else { - $this->_error("Unsupported compression type '$p_compress'\n". - "Supported types are 'gz' and 'bz2'.\n"); - return false; - } - } - $this->_tarname = $p_tarname; - if ($this->_compress) { // assert zlib or bz2 extension support - if ($this->_compress_type == 'gz') - $extname = 'zlib'; - else if ($this->_compress_type == 'bz2') - $extname = 'bz2'; - - if (!extension_loaded($extname)) { - PEAR::loadExtension($extname); - } - if (!extension_loaded($extname)) { - $this->_error("The extension '$extname' couldn't be found.\n". - "Please make sure your version of PHP was built ". - "with '$extname' support.\n"); - return false; - } - } - } - // }}} - - // {{{ destructor - function _Archive_Tar() - { - $this->_close(); - // ----- Look for a local copy to delete - if ($this->_temp_tarname != '') - @unlink($this->_temp_tarname); - $this->_PEAR(); - } - // }}} - - // {{{ create() - /** - * This method creates the archive file and add the files / directories - * that are listed in $p_filelist. - * If a file with the same name exist and is writable, it is replaced - * by the new tar. - * The method return false and a PEAR error text. - * The $p_filelist parameter can be an array of string, each string - * representing a filename or a directory name with their path if - * needed. It can also be a single string with names separated by a - * single blank. - * For each directory added in the archive, the files and - * sub-directories are also added. - * See also createModify() method for more details. - * - * @param array $p_filelist An array of filenames and directory names, or a - * single string with names separated by a single - * blank space. - * - * @return true on success, false on error. - * @see createModify() - * @access public - */ - function create($p_filelist) - { - return $this->createModify($p_filelist, '', ''); - } - // }}} - - // {{{ add() - /** - * This method add the files / directories that are listed in $p_filelist in - * the archive. If the archive does not exist it is created. - * The method return false and a PEAR error text. - * The files and directories listed are only added at the end of the archive, - * even if a file with the same name is already archived. - * See also createModify() method for more details. - * - * @param array $p_filelist An array of filenames and directory names, or a - * single string with names separated by a single - * blank space. - * - * @return true on success, false on error. - * @see createModify() - * @access public - */ - function add($p_filelist) - { - return $this->addModify($p_filelist, '', ''); - } - // }}} - - // {{{ extract() - function extract($p_path='', $p_preserve=false) - { - return $this->extractModify($p_path, '', $p_preserve); - } - // }}} - - // {{{ listContent() - function listContent() - { - $v_list_detail = array(); - - if ($this->_openRead()) { - if (!$this->_extractList('', $v_list_detail, "list", '', '')) { - unset($v_list_detail); - $v_list_detail = 0; - } - $this->_close(); - } - - return $v_list_detail; - } - // }}} - - // {{{ createModify() - /** - * This method creates the archive file and add the files / directories - * that are listed in $p_filelist. - * If the file already exists and is writable, it is replaced by the - * new tar. It is a create and not an add. If the file exists and is - * read-only or is a directory it is not replaced. The method return - * false and a PEAR error text. - * The $p_filelist parameter can be an array of string, each string - * representing a filename or a directory name with their path if - * needed. It can also be a single string with names separated by a - * single blank. - * The path indicated in $p_remove_dir will be removed from the - * memorized path of each file / directory listed when this path - * exists. By default nothing is removed (empty path '') - * The path indicated in $p_add_dir will be added at the beginning of - * the memorized path of each file / directory listed. However it can - * be set to empty ''. The adding of a path is done after the removing - * of path. - * The path add/remove ability enables the user to prepare an archive - * for extraction in a different path than the origin files are. - * See also addModify() method for file adding properties. - * - * @param array $p_filelist An array of filenames and directory names, - * or a single string with names separated by - * a single blank space. - * @param string $p_add_dir A string which contains a path to be added - * to the memorized path of each element in - * the list. - * @param string $p_remove_dir A string which contains a path to be - * removed from the memorized path of each - * element in the list, when relevant. - * - * @return boolean true on success, false on error. - * @access public - * @see addModify() - */ - function createModify($p_filelist, $p_add_dir, $p_remove_dir='') - { - $v_result = true; - - if (!$this->_openWrite()) - return false; - - if ($p_filelist != '') { - if (is_array($p_filelist)) - $v_list = $p_filelist; - elseif (is_string($p_filelist)) - $v_list = explode($this->_separator, $p_filelist); - else { - $this->_cleanFile(); - $this->_error('Invalid file list'); - return false; - } - - $v_result = $this->_addList($v_list, $p_add_dir, $p_remove_dir); - } - - if ($v_result) { - $this->_writeFooter(); - $this->_close(); - } else - $this->_cleanFile(); - - return $v_result; - } - // }}} - - // {{{ addModify() - /** - * This method add the files / directories listed in $p_filelist at the - * end of the existing archive. If the archive does not yet exists it - * is created. - * The $p_filelist parameter can be an array of string, each string - * representing a filename or a directory name with their path if - * needed. It can also be a single string with names separated by a - * single blank. - * The path indicated in $p_remove_dir will be removed from the - * memorized path of each file / directory listed when this path - * exists. By default nothing is removed (empty path '') - * The path indicated in $p_add_dir will be added at the beginning of - * the memorized path of each file / directory listed. However it can - * be set to empty ''. The adding of a path is done after the removing - * of path. - * The path add/remove ability enables the user to prepare an archive - * for extraction in a different path than the origin files are. - * If a file/dir is already in the archive it will only be added at the - * end of the archive. There is no update of the existing archived - * file/dir. However while extracting the archive, the last file will - * replace the first one. This results in a none optimization of the - * archive size. - * If a file/dir does not exist the file/dir is ignored. However an - * error text is send to PEAR error. - * If a file/dir is not readable the file/dir is ignored. However an - * error text is send to PEAR error. - * - * @param array $p_filelist An array of filenames and directory - * names, or a single string with names - * separated by a single blank space. - * @param string $p_add_dir A string which contains a path to be - * added to the memorized path of each - * element in the list. - * @param string $p_remove_dir A string which contains a path to be - * removed from the memorized path of - * each element in the list, when - * relevant. - * - * @return true on success, false on error. - * @access public - */ - function addModify($p_filelist, $p_add_dir, $p_remove_dir='') - { - $v_result = true; - - if (!$this->_isArchive()) - $v_result = $this->createModify($p_filelist, $p_add_dir, - $p_remove_dir); - else { - if (is_array($p_filelist)) - $v_list = $p_filelist; - elseif (is_string($p_filelist)) - $v_list = explode($this->_separator, $p_filelist); - else { - $this->_error('Invalid file list'); - return false; - } - - $v_result = $this->_append($v_list, $p_add_dir, $p_remove_dir); - } - - return $v_result; - } - // }}} - - // {{{ addString() - /** - * This method add a single string as a file at the - * end of the existing archive. If the archive does not yet exists it - * is created. - * - * @param string $p_filename A string which contains the full - * filename path that will be associated - * with the string. - * @param string $p_string The content of the file added in - * the archive. - * @param int $p_datetime A custom date/time (unix timestamp) - * for the file (optional). - * - * @return true on success, false on error. - * @access public - */ - function addString($p_filename, $p_string, $p_datetime = false) - { - $v_result = true; - - if (!$this->_isArchive()) { - if (!$this->_openWrite()) { - return false; - } - $this->_close(); - } - - if (!$this->_openAppend()) - return false; - - // Need to check the get back to the temporary file ? .... - $v_result = $this->_addString($p_filename, $p_string, $p_datetime); - - $this->_writeFooter(); - - $this->_close(); - - return $v_result; - } - // }}} - - // {{{ extractModify() - /** - * This method extract all the content of the archive in the directory - * indicated by $p_path. When relevant the memorized path of the - * files/dir can be modified by removing the $p_remove_path path at the - * beginning of the file/dir path. - * While extracting a file, if the directory path does not exists it is - * created. - * While extracting a file, if the file already exists it is replaced - * without looking for last modification date. - * While extracting a file, if the file already exists and is write - * protected, the extraction is aborted. - * While extracting a file, if a directory with the same name already - * exists, the extraction is aborted. - * While extracting a directory, if a file with the same name already - * exists, the extraction is aborted. - * While extracting a file/directory if the destination directory exist - * and is write protected, or does not exist but can not be created, - * the extraction is aborted. - * If after extraction an extracted file does not show the correct - * stored file size, the extraction is aborted. - * When the extraction is aborted, a PEAR error text is set and false - * is returned. However the result can be a partial extraction that may - * need to be manually cleaned. - * - * @param string $p_path The path of the directory where the - * files/dir need to by extracted. - * @param string $p_remove_path Part of the memorized path that can be - * removed if present at the beginning of - * the file/dir path. - * @param boolean $p_preserve Preserve user/group ownership of files - * - * @return boolean true on success, false on error. - * @access public - * @see extractList() - */ - function extractModify($p_path, $p_remove_path, $p_preserve=false) - { - $v_result = true; - $v_list_detail = array(); - - if ($v_result = $this->_openRead()) { - $v_result = $this->_extractList($p_path, $v_list_detail, - "complete", 0, $p_remove_path, $p_preserve); - $this->_close(); - } - - return $v_result; - } - // }}} - - // {{{ extractInString() - /** - * This method extract from the archive one file identified by $p_filename. - * The return value is a string with the file content, or NULL on error. - * - * @param string $p_filename The path of the file to extract in a string. - * - * @return a string with the file content or NULL. - * @access public - */ - function extractInString($p_filename) - { - if ($this->_openRead()) { - $v_result = $this->_extractInString($p_filename); - $this->_close(); - } else { - $v_result = null; - } - - return $v_result; - } - // }}} - - // {{{ extractList() - /** - * This method extract from the archive only the files indicated in the - * $p_filelist. These files are extracted in the current directory or - * in the directory indicated by the optional $p_path parameter. - * If indicated the $p_remove_path can be used in the same way as it is - * used in extractModify() method. - * - * @param array $p_filelist An array of filenames and directory names, - * or a single string with names separated - * by a single blank space. - * @param string $p_path The path of the directory where the - * files/dir need to by extracted. - * @param string $p_remove_path Part of the memorized path that can be - * removed if present at the beginning of - * the file/dir path. - * @param boolean $p_preserve Preserve user/group ownership of files - * - * @return true on success, false on error. - * @access public - * @see extractModify() - */ - function extractList($p_filelist, $p_path='', $p_remove_path='', $p_preserve=false) - { - $v_result = true; - $v_list_detail = array(); - - if (is_array($p_filelist)) - $v_list = $p_filelist; - elseif (is_string($p_filelist)) - $v_list = explode($this->_separator, $p_filelist); - else { - $this->_error('Invalid string list'); - return false; - } - - if ($v_result = $this->_openRead()) { - $v_result = $this->_extractList($p_path, $v_list_detail, "partial", - $v_list, $p_remove_path, $p_preserve); - $this->_close(); - } - - return $v_result; - } - // }}} - - // {{{ setAttribute() - /** - * This method set specific attributes of the archive. It uses a variable - * list of parameters, in the format attribute code + attribute values : - * $arch->setAttribute(ARCHIVE_TAR_ATT_SEPARATOR, ','); - * - * @param mixed $argv variable list of attributes and values - * - * @return true on success, false on error. - * @access public - */ - function setAttribute() - { - $v_result = true; - - // ----- Get the number of variable list of arguments - if (($v_size = func_num_args()) == 0) { - return true; - } - - // ----- Get the arguments - $v_att_list = &func_get_args(); - - // ----- Read the attributes - $i=0; - while ($i<$v_size) { - - // ----- Look for next option - switch ($v_att_list[$i]) { - // ----- Look for options that request a string value - case ARCHIVE_TAR_ATT_SEPARATOR : - // ----- Check the number of parameters - if (($i+1) >= $v_size) { - $this->_error('Invalid number of parameters for ' - .'attribute ARCHIVE_TAR_ATT_SEPARATOR'); - return false; - } - - // ----- Get the value - $this->_separator = $v_att_list[$i+1]; - $i++; - break; - - default : - $this->_error('Unknow attribute code '.$v_att_list[$i].''); - return false; - } - - // ----- Next attribute - $i++; - } - - return $v_result; - } - // }}} - - // {{{ setIgnoreRegexp() - /** - * This method sets the regular expression for ignoring files and directories - * at import, for example: - * $arch->setIgnoreRegexp("#CVS|\.svn#"); - * - * @param string $regexp regular expression defining which files or directories to ignore - * - * @access public - */ - function setIgnoreRegexp($regexp) - { - $this->_ignore_regexp = $regexp; - } - // }}} - - // {{{ setIgnoreList() - /** - * This method sets the regular expression for ignoring all files and directories - * matching the filenames in the array list at import, for example: - * $arch->setIgnoreList(array('CVS', '.svn', 'bin/tool')); - * - * @param array $list a list of file or directory names to ignore - * - * @access public - */ - function setIgnoreList($list) - { - $regexp = str_replace(array('#', '.', '^', '$'), array('\#', '\.', '\^', '\$'), $list); - $regexp = '#/'.join('$|/', $list).'#'; - $this->setIgnoreRegexp($regexp); - } - // }}} - - // {{{ _error() - function _error($p_message) - { - $this->error_object = &$this->raiseError($p_message); - } - // }}} - - // {{{ _warning() - function _warning($p_message) - { - $this->error_object = &$this->raiseError($p_message); - } - // }}} - - // {{{ _isArchive() - function _isArchive($p_filename=null) - { - if ($p_filename == null) { - $p_filename = $this->_tarname; - } - clearstatcache(); - return @is_file($p_filename) && !@is_link($p_filename); - } - // }}} - - // {{{ _openWrite() - function _openWrite() - { - if ($this->_compress_type == 'gz' && function_exists('gzopen')) - $this->_file = @gzopen($this->_tarname, "wb9"); - else if ($this->_compress_type == 'bz2' && function_exists('bzopen')) - $this->_file = @bzopen($this->_tarname, "w"); - else if ($this->_compress_type == 'none') - $this->_file = @fopen($this->_tarname, "wb"); - else { - $this->_error('Unknown or missing compression type (' - .$this->_compress_type.')'); - return false; - } - - if ($this->_file == 0) { - $this->_error('Unable to open in write mode \'' - .$this->_tarname.'\''); - return false; - } - - return true; - } - // }}} - - // {{{ _openRead() - function _openRead() - { - if (strtolower(substr($this->_tarname, 0, 7)) == 'http://') { - - // ----- Look if a local copy need to be done - if ($this->_temp_tarname == '') { - $this->_temp_tarname = uniqid('tar').'.tmp'; - if (!$v_file_from = @fopen($this->_tarname, 'rb')) { - $this->_error('Unable to open in read mode \'' - .$this->_tarname.'\''); - $this->_temp_tarname = ''; - return false; - } - if (!$v_file_to = @fopen($this->_temp_tarname, 'wb')) { - $this->_error('Unable to open in write mode \'' - .$this->_temp_tarname.'\''); - $this->_temp_tarname = ''; - return false; - } - while ($v_data = @fread($v_file_from, 1024)) - @fwrite($v_file_to, $v_data); - @fclose($v_file_from); - @fclose($v_file_to); - } - - // ----- File to open if the local copy - $v_filename = $this->_temp_tarname; - - } else - // ----- File to open if the normal Tar file - $v_filename = $this->_tarname; - - if ($this->_compress_type == 'gz' && function_exists('gzopen')) - $this->_file = @gzopen($v_filename, "rb"); - else if ($this->_compress_type == 'bz2' && function_exists('bzopen')) - $this->_file = @bzopen($v_filename, "r"); - else if ($this->_compress_type == 'none') - $this->_file = @fopen($v_filename, "rb"); - else { - $this->_error('Unknown or missing compression type (' - .$this->_compress_type.')'); - return false; - } - - if ($this->_file == 0) { - $this->_error('Unable to open in read mode \''.$v_filename.'\''); - return false; - } - - return true; - } - // }}} - - // {{{ _openReadWrite() - function _openReadWrite() - { - if ($this->_compress_type == 'gz') - $this->_file = @gzopen($this->_tarname, "r+b"); - else if ($this->_compress_type == 'bz2') { - $this->_error('Unable to open bz2 in read/write mode \'' - .$this->_tarname.'\' (limitation of bz2 extension)'); - return false; - } else if ($this->_compress_type == 'none') - $this->_file = @fopen($this->_tarname, "r+b"); - else { - $this->_error('Unknown or missing compression type (' - .$this->_compress_type.')'); - return false; - } - - if ($this->_file == 0) { - $this->_error('Unable to open in read/write mode \'' - .$this->_tarname.'\''); - return false; - } - - return true; - } - // }}} - - // {{{ _close() - function _close() - { - //if (isset($this->_file)) { - if (is_resource($this->_file)) { - if ($this->_compress_type == 'gz') - @gzclose($this->_file); - else if ($this->_compress_type == 'bz2') - @bzclose($this->_file); - else if ($this->_compress_type == 'none') - @fclose($this->_file); - else - $this->_error('Unknown or missing compression type (' - .$this->_compress_type.')'); - - $this->_file = 0; - } - - // ----- Look if a local copy need to be erase - // Note that it might be interesting to keep the url for a time : ToDo - if ($this->_temp_tarname != '') { - @unlink($this->_temp_tarname); - $this->_temp_tarname = ''; - } - - return true; - } - // }}} - - // {{{ _cleanFile() - function _cleanFile() - { - $this->_close(); - - // ----- Look for a local copy - if ($this->_temp_tarname != '') { - // ----- Remove the local copy but not the remote tarname - @unlink($this->_temp_tarname); - $this->_temp_tarname = ''; - } else { - // ----- Remove the local tarname file - @unlink($this->_tarname); - } - $this->_tarname = ''; - - return true; - } - // }}} - - // {{{ _writeBlock() - function _writeBlock($p_binary_data, $p_len=null) - { - if (is_resource($this->_file)) { - if ($p_len === null) { - if ($this->_compress_type == 'gz') - @gzputs($this->_file, $p_binary_data); - else if ($this->_compress_type == 'bz2') - @bzwrite($this->_file, $p_binary_data); - else if ($this->_compress_type == 'none') - @fputs($this->_file, $p_binary_data); - else - $this->_error('Unknown or missing compression type (' - .$this->_compress_type.')'); - } else { - if ($this->_compress_type == 'gz') - @gzputs($this->_file, $p_binary_data, $p_len); - else if ($this->_compress_type == 'bz2') - @bzwrite($this->_file, $p_binary_data, $p_len); - else if ($this->_compress_type == 'none') - @fputs($this->_file, $p_binary_data, $p_len); - else - $this->_error('Unknown or missing compression type (' - .$this->_compress_type.')'); - - } - } - return true; - } - // }}} - - // {{{ _readBlock() - function _readBlock() - { - $v_block = null; - if (is_resource($this->_file)) { - if ($this->_compress_type == 'gz') - $v_block = @gzread($this->_file, 512); - else if ($this->_compress_type == 'bz2') - $v_block = @bzread($this->_file, 512); - else if ($this->_compress_type == 'none') - $v_block = @fread($this->_file, 512); - else - $this->_error('Unknown or missing compression type (' - .$this->_compress_type.')'); - } - return $v_block; - } - // }}} - - // {{{ _jumpBlock() - function _jumpBlock($p_len=null) - { - if (is_resource($this->_file)) { - if ($p_len === null) - $p_len = 1; - - if ($this->_compress_type == 'gz') { - @gzseek($this->_file, gztell($this->_file)+($p_len*512)); - } - else if ($this->_compress_type == 'bz2') { - // ----- Replace missing bztell() and bzseek() - for ($i=0; $i<$p_len; $i++) - $this->_readBlock(); - } else if ($this->_compress_type == 'none') - @fseek($this->_file, $p_len*512, SEEK_CUR); - else - $this->_error('Unknown or missing compression type (' - .$this->_compress_type.')'); - - } - return true; - } - // }}} - - // {{{ _writeFooter() - function _writeFooter() - { - if (is_resource($this->_file)) { - // ----- Write the last 0 filled block for end of archive - $v_binary_data = pack('a1024', ''); - $this->_writeBlock($v_binary_data); - } - return true; - } - // }}} - - // {{{ _addList() - function _addList($p_list, $p_add_dir, $p_remove_dir) - { - $v_result=true; - $v_header = array(); - - // ----- Remove potential windows directory separator - $p_add_dir = $this->_translateWinPath($p_add_dir); - $p_remove_dir = $this->_translateWinPath($p_remove_dir, false); - - if (!$this->_file) { - $this->_error('Invalid file descriptor'); - return false; - } - - if (sizeof($p_list) == 0) - return true; - - foreach ($p_list as $v_filename) { - if (!$v_result) { - break; - } - - // ----- Skip the current tar name - if ($v_filename == $this->_tarname) - continue; - - if ($v_filename == '') - continue; - - // ----- ignore files and directories matching the ignore regular expression - if ($this->_ignore_regexp && preg_match($this->_ignore_regexp, '/'.$v_filename)) { - $this->_warning("File '$v_filename' ignored"); - continue; - } - - if (!file_exists($v_filename) && !is_link($v_filename)) { - $this->_warning("File '$v_filename' does not exist"); - continue; - } - - // ----- Add the file or directory header - if (!$this->_addFile($v_filename, $v_header, $p_add_dir, $p_remove_dir)) - return false; - - if (@is_dir($v_filename) && !@is_link($v_filename)) { - if (!($p_hdir = opendir($v_filename))) { - $this->_warning("Directory '$v_filename' can not be read"); - continue; - } - while (false !== ($p_hitem = readdir($p_hdir))) { - if (($p_hitem != '.') && ($p_hitem != '..')) { - if ($v_filename != ".") - $p_temp_list[0] = $v_filename.'/'.$p_hitem; - else - $p_temp_list[0] = $p_hitem; - - $v_result = $this->_addList($p_temp_list, - $p_add_dir, - $p_remove_dir); - } - } - - unset($p_temp_list); - unset($p_hdir); - unset($p_hitem); - } - } - - return $v_result; - } - // }}} - - // {{{ _addFile() - function _addFile($p_filename, &$p_header, $p_add_dir, $p_remove_dir) - { - if (!$this->_file) { - $this->_error('Invalid file descriptor'); - return false; - } - - if ($p_filename == '') { - $this->_error('Invalid file name'); - return false; - } - - // ----- Calculate the stored filename - $p_filename = $this->_translateWinPath($p_filename, false);; - $v_stored_filename = $p_filename; - if (strcmp($p_filename, $p_remove_dir) == 0) { - return true; - } - if ($p_remove_dir != '') { - if (substr($p_remove_dir, -1) != '/') - $p_remove_dir .= '/'; - - if (substr($p_filename, 0, strlen($p_remove_dir)) == $p_remove_dir) - $v_stored_filename = substr($p_filename, strlen($p_remove_dir)); - } - $v_stored_filename = $this->_translateWinPath($v_stored_filename); - if ($p_add_dir != '') { - if (substr($p_add_dir, -1) == '/') - $v_stored_filename = $p_add_dir.$v_stored_filename; - else - $v_stored_filename = $p_add_dir.'/'.$v_stored_filename; - } - - $v_stored_filename = $this->_pathReduction($v_stored_filename); - - if ($this->_isArchive($p_filename)) { - if (($v_file = @fopen($p_filename, "rb")) == 0) { - $this->_warning("Unable to open file '".$p_filename - ."' in binary read mode"); - return true; - } - - if (!$this->_writeHeader($p_filename, $v_stored_filename)) - return false; - - while (($v_buffer = fread($v_file, 512)) != '') { - $v_binary_data = pack("a512", "$v_buffer"); - $this->_writeBlock($v_binary_data); - } - - fclose($v_file); - - } else { - // ----- Only header for dir - if (!$this->_writeHeader($p_filename, $v_stored_filename)) - return false; - } - - return true; - } - // }}} - - // {{{ _addString() - function _addString($p_filename, $p_string, $p_datetime = false) - { - if (!$this->_file) { - $this->_error('Invalid file descriptor'); - return false; - } - - if ($p_filename == '') { - $this->_error('Invalid file name'); - return false; - } - - // ----- Calculate the stored filename - $p_filename = $this->_translateWinPath($p_filename, false);; - - // ----- If datetime is not specified, set current time - if ($p_datetime === false) { - $p_datetime = time(); - } - - if (!$this->_writeHeaderBlock($p_filename, strlen($p_string), - $p_datetime, 384, "", 0, 0)) - return false; - - $i=0; - while (($v_buffer = substr($p_string, (($i++)*512), 512)) != '') { - $v_binary_data = pack("a512", $v_buffer); - $this->_writeBlock($v_binary_data); - } - - return true; - } - // }}} - - // {{{ _writeHeader() - function _writeHeader($p_filename, $p_stored_filename) - { - if ($p_stored_filename == '') - $p_stored_filename = $p_filename; - $v_reduce_filename = $this->_pathReduction($p_stored_filename); - - if (strlen($v_reduce_filename) > 99) { - if (!$this->_writeLongHeader($v_reduce_filename)) - return false; - } - - $v_info = lstat($p_filename); - $v_uid = sprintf("%07s", DecOct($v_info[4])); - $v_gid = sprintf("%07s", DecOct($v_info[5])); - $v_perms = sprintf("%07s", DecOct($v_info['mode'] & 000777)); - - $v_mtime = sprintf("%011s", DecOct($v_info['mtime'])); - - $v_linkname = ''; - - if (@is_link($p_filename)) { - $v_typeflag = '2'; - $v_linkname = readlink($p_filename); - $v_size = sprintf("%011s", DecOct(0)); - } elseif (@is_dir($p_filename)) { - $v_typeflag = "5"; - $v_size = sprintf("%011s", DecOct(0)); - } else { - $v_typeflag = '0'; - clearstatcache(); - $v_size = sprintf("%011s", DecOct($v_info['size'])); - } - - $v_magic = 'ustar '; - - $v_version = ' '; - - if (function_exists('posix_getpwuid')) - { - $userinfo = posix_getpwuid($v_info[4]); - $groupinfo = posix_getgrgid($v_info[5]); - - $v_uname = $userinfo['name']; - $v_gname = $groupinfo['name']; - } - else - { - $v_uname = ''; - $v_gname = ''; - } - - $v_devmajor = ''; - - $v_devminor = ''; - - $v_prefix = ''; - - $v_binary_data_first = pack("a100a8a8a8a12a12", - $v_reduce_filename, $v_perms, $v_uid, - $v_gid, $v_size, $v_mtime); - $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12", - $v_typeflag, $v_linkname, $v_magic, - $v_version, $v_uname, $v_gname, - $v_devmajor, $v_devminor, $v_prefix, ''); - - // ----- Calculate the checksum - $v_checksum = 0; - // ..... First part of the header - for ($i=0; $i<148; $i++) - $v_checksum += ord(substr($v_binary_data_first,$i,1)); - // ..... Ignore the checksum value and replace it by ' ' (space) - for ($i=148; $i<156; $i++) - $v_checksum += ord(' '); - // ..... Last part of the header - for ($i=156, $j=0; $i<512; $i++, $j++) - $v_checksum += ord(substr($v_binary_data_last,$j,1)); - - // ----- Write the first 148 bytes of the header in the archive - $this->_writeBlock($v_binary_data_first, 148); - - // ----- Write the calculated checksum - $v_checksum = sprintf("%06s ", DecOct($v_checksum)); - $v_binary_data = pack("a8", $v_checksum); - $this->_writeBlock($v_binary_data, 8); - - // ----- Write the last 356 bytes of the header in the archive - $this->_writeBlock($v_binary_data_last, 356); - - return true; - } - // }}} - - // {{{ _writeHeaderBlock() - function _writeHeaderBlock($p_filename, $p_size, $p_mtime=0, $p_perms=0, - $p_type='', $p_uid=0, $p_gid=0) - { - $p_filename = $this->_pathReduction($p_filename); - - if (strlen($p_filename) > 99) { - if (!$this->_writeLongHeader($p_filename)) - return false; - } - - if ($p_type == "5") { - $v_size = sprintf("%011s", DecOct(0)); - } else { - $v_size = sprintf("%011s", DecOct($p_size)); - } - - $v_uid = sprintf("%07s", DecOct($p_uid)); - $v_gid = sprintf("%07s", DecOct($p_gid)); - $v_perms = sprintf("%07s", DecOct($p_perms & 000777)); - - $v_mtime = sprintf("%11s", DecOct($p_mtime)); - - $v_linkname = ''; - - $v_magic = 'ustar '; - - $v_version = ' '; - - if (function_exists('posix_getpwuid')) - { - $userinfo = posix_getpwuid($p_uid); - $groupinfo = posix_getgrgid($p_gid); - - $v_uname = $userinfo['name']; - $v_gname = $groupinfo['name']; - } - else - { - $v_uname = ''; - $v_gname = ''; - } - - $v_devmajor = ''; - - $v_devminor = ''; - - $v_prefix = ''; - - $v_binary_data_first = pack("a100a8a8a8a12A12", - $p_filename, $v_perms, $v_uid, $v_gid, - $v_size, $v_mtime); - $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12", - $p_type, $v_linkname, $v_magic, - $v_version, $v_uname, $v_gname, - $v_devmajor, $v_devminor, $v_prefix, ''); - - // ----- Calculate the checksum - $v_checksum = 0; - // ..... First part of the header - for ($i=0; $i<148; $i++) - $v_checksum += ord(substr($v_binary_data_first,$i,1)); - // ..... Ignore the checksum value and replace it by ' ' (space) - for ($i=148; $i<156; $i++) - $v_checksum += ord(' '); - // ..... Last part of the header - for ($i=156, $j=0; $i<512; $i++, $j++) - $v_checksum += ord(substr($v_binary_data_last,$j,1)); - - // ----- Write the first 148 bytes of the header in the archive - $this->_writeBlock($v_binary_data_first, 148); - - // ----- Write the calculated checksum - $v_checksum = sprintf("%06s ", DecOct($v_checksum)); - $v_binary_data = pack("a8", $v_checksum); - $this->_writeBlock($v_binary_data, 8); - - // ----- Write the last 356 bytes of the header in the archive - $this->_writeBlock($v_binary_data_last, 356); - - return true; - } - // }}} - - // {{{ _writeLongHeader() - function _writeLongHeader($p_filename) - { - $v_size = sprintf("%11s ", DecOct(strlen($p_filename))); - - $v_typeflag = 'L'; - - $v_linkname = ''; - - $v_magic = ''; - - $v_version = ''; - - $v_uname = ''; - - $v_gname = ''; - - $v_devmajor = ''; - - $v_devminor = ''; - - $v_prefix = ''; - - $v_binary_data_first = pack("a100a8a8a8a12a12", - '././@LongLink', 0, 0, 0, $v_size, 0); - $v_binary_data_last = pack("a1a100a6a2a32a32a8a8a155a12", - $v_typeflag, $v_linkname, $v_magic, - $v_version, $v_uname, $v_gname, - $v_devmajor, $v_devminor, $v_prefix, ''); - - // ----- Calculate the checksum - $v_checksum = 0; - // ..... First part of the header - for ($i=0; $i<148; $i++) - $v_checksum += ord(substr($v_binary_data_first,$i,1)); - // ..... Ignore the checksum value and replace it by ' ' (space) - for ($i=148; $i<156; $i++) - $v_checksum += ord(' '); - // ..... Last part of the header - for ($i=156, $j=0; $i<512; $i++, $j++) - $v_checksum += ord(substr($v_binary_data_last,$j,1)); - - // ----- Write the first 148 bytes of the header in the archive - $this->_writeBlock($v_binary_data_first, 148); - - // ----- Write the calculated checksum - $v_checksum = sprintf("%06s ", DecOct($v_checksum)); - $v_binary_data = pack("a8", $v_checksum); - $this->_writeBlock($v_binary_data, 8); - - // ----- Write the last 356 bytes of the header in the archive - $this->_writeBlock($v_binary_data_last, 356); - - // ----- Write the filename as content of the block - $i=0; - while (($v_buffer = substr($p_filename, (($i++)*512), 512)) != '') { - $v_binary_data = pack("a512", "$v_buffer"); - $this->_writeBlock($v_binary_data); - } - - return true; - } - // }}} - - // {{{ _readHeader() - function _readHeader($v_binary_data, &$v_header) - { - if (strlen($v_binary_data)==0) { - $v_header['filename'] = ''; - return true; - } - - if (strlen($v_binary_data) != 512) { - $v_header['filename'] = ''; - $this->_error('Invalid block size : '.strlen($v_binary_data)); - return false; - } - - if (!is_array($v_header)) { - $v_header = array(); - } - // ----- Calculate the checksum - $v_checksum = 0; - // ..... First part of the header - for ($i=0; $i<148; $i++) - $v_checksum+=ord(substr($v_binary_data,$i,1)); - // ..... Ignore the checksum value and replace it by ' ' (space) - for ($i=148; $i<156; $i++) - $v_checksum += ord(' '); - // ..... Last part of the header - for ($i=156; $i<512; $i++) - $v_checksum+=ord(substr($v_binary_data,$i,1)); - - if (version_compare(PHP_VERSION,"5.5.0-dev")<0) { - $fmt = "a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/" . - "a8checksum/a1typeflag/a100link/a6magic/a2version/" . - "a32uname/a32gname/a8devmajor/a8devminor/a131prefix"; - } else { - $fmt = "Z100filename/Z8mode/Z8uid/Z8gid/Z12size/Z12mtime/" . - "Z8checksum/Z1typeflag/Z100link/Z6magic/Z2version/" . - "Z32uname/Z32gname/Z8devmajor/Z8devminor/Z131prefix"; - } - $v_data = unpack($fmt, $v_binary_data); - - if (strlen($v_data["prefix"]) > 0) { - $v_data["filename"] = "$v_data[prefix]/$v_data[filename]"; - } - - // ----- Extract the checksum - $v_header['checksum'] = OctDec(trim($v_data['checksum'])); - if ($v_header['checksum'] != $v_checksum) { - $v_header['filename'] = ''; - - // ----- Look for last block (empty block) - if (($v_checksum == 256) && ($v_header['checksum'] == 0)) - return true; - - $this->_error('Invalid checksum for file "'.$v_data['filename'] - .'" : '.$v_checksum.' calculated, ' - .$v_header['checksum'].' expected'); - return false; - } - - // ----- Extract the properties - $v_header['filename'] = $v_data['filename']; - if ($this->_maliciousFilename($v_header['filename'])) { - $this->_error('Malicious .tar detected, file "' . $v_header['filename'] . - '" will not install in desired directory tree'); - return false; - } - $v_header['mode'] = OctDec(trim($v_data['mode'])); - $v_header['uid'] = OctDec(trim($v_data['uid'])); - $v_header['gid'] = OctDec(trim($v_data['gid'])); - $v_header['size'] = OctDec(trim($v_data['size'])); - $v_header['mtime'] = OctDec(trim($v_data['mtime'])); - if (($v_header['typeflag'] = $v_data['typeflag']) == "5") { - $v_header['size'] = 0; - } - $v_header['link'] = trim($v_data['link']); - /* ----- All these fields are removed form the header because - they do not carry interesting info - $v_header[magic] = trim($v_data[magic]); - $v_header[version] = trim($v_data[version]); - $v_header[uname] = trim($v_data[uname]); - $v_header[gname] = trim($v_data[gname]); - $v_header[devmajor] = trim($v_data[devmajor]); - $v_header[devminor] = trim($v_data[devminor]); - */ - - return true; - } - // }}} - - // {{{ _maliciousFilename() - /** - * Detect and report a malicious file name - * - * @param string $file - * - * @return bool - * @access private - */ - function _maliciousFilename($file) - { - if (strpos($file, '/../') !== false) { - return true; - } - if (strpos($file, '../') === 0) { - return true; - } - return false; - } - // }}} - - // {{{ _readLongHeader() - function _readLongHeader(&$v_header) - { - $v_filename = ''; - $n = floor($v_header['size']/512); - for ($i=0; $i<$n; $i++) { - $v_content = $this->_readBlock(); - $v_filename .= $v_content; - } - if (($v_header['size'] % 512) != 0) { - $v_content = $this->_readBlock(); - $v_filename .= trim($v_content); - } - - // ----- Read the next header - $v_binary_data = $this->_readBlock(); - - if (!$this->_readHeader($v_binary_data, $v_header)) - return false; - - $v_filename = trim($v_filename); - $v_header['filename'] = $v_filename; - if ($this->_maliciousFilename($v_filename)) { - $this->_error('Malicious .tar detected, file "' . $v_filename . - '" will not install in desired directory tree'); - return false; - } - - return true; - } - // }}} - - // {{{ _extractInString() - /** - * This method extract from the archive one file identified by $p_filename. - * The return value is a string with the file content, or null on error. - * - * @param string $p_filename The path of the file to extract in a string. - * - * @return a string with the file content or null. - * @access private - */ - function _extractInString($p_filename) - { - $v_result_str = ""; - - While (strlen($v_binary_data = $this->_readBlock()) != 0) - { - if (!$this->_readHeader($v_binary_data, $v_header)) - return null; - - if ($v_header['filename'] == '') - continue; - - // ----- Look for long filename - if ($v_header['typeflag'] == 'L') { - if (!$this->_readLongHeader($v_header)) - return null; - } - - if ($v_header['filename'] == $p_filename) { - if ($v_header['typeflag'] == "5") { - $this->_error('Unable to extract in string a directory ' - .'entry {'.$v_header['filename'].'}'); - return null; - } else { - $n = floor($v_header['size']/512); - for ($i=0; $i<$n; $i++) { - $v_result_str .= $this->_readBlock(); - } - if (($v_header['size'] % 512) != 0) { - $v_content = $this->_readBlock(); - $v_result_str .= substr($v_content, 0, - ($v_header['size'] % 512)); - } - return $v_result_str; - } - } else { - $this->_jumpBlock(ceil(($v_header['size']/512))); - } - } - - return null; - } - // }}} - - // {{{ _extractList() - function _extractList($p_path, &$p_list_detail, $p_mode, - $p_file_list, $p_remove_path, $p_preserve=false) - { - $v_result=true; - $v_nb = 0; - $v_extract_all = true; - $v_listing = false; - - $p_path = $this->_translateWinPath($p_path, false); - if ($p_path == '' || (substr($p_path, 0, 1) != '/' - && substr($p_path, 0, 3) != "../" && !strpos($p_path, ':'))) { - $p_path = "./".$p_path; - } - $p_remove_path = $this->_translateWinPath($p_remove_path); - - // ----- Look for path to remove format (should end by /) - if (($p_remove_path != '') && (substr($p_remove_path, -1) != '/')) - $p_remove_path .= '/'; - $p_remove_path_size = strlen($p_remove_path); - - switch ($p_mode) { - case "complete" : - $v_extract_all = true; - $v_listing = false; - break; - case "partial" : - $v_extract_all = false; - $v_listing = false; - break; - case "list" : - $v_extract_all = false; - $v_listing = true; - break; - default : - $this->_error('Invalid extract mode ('.$p_mode.')'); - return false; - } - - clearstatcache(); - - while (strlen($v_binary_data = $this->_readBlock()) != 0) - { - $v_extract_file = FALSE; - $v_extraction_stopped = 0; - - if (!$this->_readHeader($v_binary_data, $v_header)) - return false; - - if ($v_header['filename'] == '') { - continue; - } - - // ----- Look for long filename - if ($v_header['typeflag'] == 'L') { - if (!$this->_readLongHeader($v_header)) - return false; - } - - if ((!$v_extract_all) && (is_array($p_file_list))) { - // ----- By default no unzip if the file is not found - $v_extract_file = false; - - for ($i=0; $i strlen($p_file_list[$i])) - && (substr($v_header['filename'], 0, strlen($p_file_list[$i])) - == $p_file_list[$i])) { - $v_extract_file = true; - break; - } - } - - // ----- It is a file, so compare the file names - elseif ($p_file_list[$i] == $v_header['filename']) { - $v_extract_file = true; - break; - } - } - } else { - $v_extract_file = true; - } - - // ----- Look if this file need to be extracted - if (($v_extract_file) && (!$v_listing)) - { - if (($p_remove_path != '') - && (substr($v_header['filename'].'/', 0, $p_remove_path_size) - == $p_remove_path)) { - $v_header['filename'] = substr($v_header['filename'], - $p_remove_path_size); - if( $v_header['filename'] == '' ){ - continue; - } - } - if (($p_path != './') && ($p_path != '/')) { - while (substr($p_path, -1) == '/') - $p_path = substr($p_path, 0, strlen($p_path)-1); - - if (substr($v_header['filename'], 0, 1) == '/') - $v_header['filename'] = $p_path.$v_header['filename']; - else - $v_header['filename'] = $p_path.'/'.$v_header['filename']; - } - if (file_exists($v_header['filename'])) { - if ( (@is_dir($v_header['filename'])) - && ($v_header['typeflag'] == '')) { - $this->_error('File '.$v_header['filename'] - .' already exists as a directory'); - return false; - } - if ( ($this->_isArchive($v_header['filename'])) - && ($v_header['typeflag'] == "5")) { - $this->_error('Directory '.$v_header['filename'] - .' already exists as a file'); - return false; - } - if (!is_writeable($v_header['filename'])) { - $this->_error('File '.$v_header['filename'] - .' already exists and is write protected'); - return false; - } - if (filemtime($v_header['filename']) > $v_header['mtime']) { - // To be completed : An error or silent no replace ? - } - } - - // ----- Check the directory availability and create it if necessary - elseif (($v_result - = $this->_dirCheck(($v_header['typeflag'] == "5" - ?$v_header['filename'] - :dirname($v_header['filename'])))) != 1) { - $this->_error('Unable to create path for '.$v_header['filename']); - return false; - } - - if ($v_extract_file) { - if ($v_header['typeflag'] == "5") { - if (!@file_exists($v_header['filename'])) { - if (!@mkdir($v_header['filename'], 0777)) { - $this->_error('Unable to create directory {' - .$v_header['filename'].'}'); - return false; - } - } - } elseif ($v_header['typeflag'] == "2") { - if (@file_exists($v_header['filename'])) { - @unlink($v_header['filename']); - } - if (!@symlink($v_header['link'], $v_header['filename'])) { - $this->_error('Unable to extract symbolic link {' - .$v_header['filename'].'}'); - return false; - } - } else { - if (($v_dest_file = @fopen($v_header['filename'], "wb")) == 0) { - $this->_error('Error while opening {'.$v_header['filename'] - .'} in write binary mode'); - return false; - } else { - $n = floor($v_header['size']/512); - for ($i=0; $i<$n; $i++) { - $v_content = $this->_readBlock(); - fwrite($v_dest_file, $v_content, 512); - } - if (($v_header['size'] % 512) != 0) { - $v_content = $this->_readBlock(); - fwrite($v_dest_file, $v_content, ($v_header['size'] % 512)); - } - - @fclose($v_dest_file); - - if ($p_preserve) { - @chown($v_header['filename'], $v_header['uid']); - @chgrp($v_header['filename'], $v_header['gid']); - } - - // ----- Change the file mode, mtime - @touch($v_header['filename'], $v_header['mtime']); - if ($v_header['mode'] & 0111) { - // make file executable, obey umask - $mode = fileperms($v_header['filename']) | (~umask() & 0111); - @chmod($v_header['filename'], $mode); - } - } - - // ----- Check the file size - clearstatcache(); - if (!is_file($v_header['filename'])) { - $this->_error('Extracted file '.$v_header['filename'] - .'does not exist. Archive may be corrupted.'); - return false; - } - - $filesize = filesize($v_header['filename']); - if ($filesize != $v_header['size']) { - $this->_error('Extracted file '.$v_header['filename'] - .' does not have the correct file size \'' - .$filesize - .'\' ('.$v_header['size'] - .' expected). Archive may be corrupted.'); - return false; - } - } - } else { - $this->_jumpBlock(ceil(($v_header['size']/512))); - } - } else { - $this->_jumpBlock(ceil(($v_header['size']/512))); - } - - /* TBC : Seems to be unused ... - if ($this->_compress) - $v_end_of_file = @gzeof($this->_file); - else - $v_end_of_file = @feof($this->_file); - */ - - if ($v_listing || $v_extract_file || $v_extraction_stopped) { - // ----- Log extracted files - if (($v_file_dir = dirname($v_header['filename'])) - == $v_header['filename']) - $v_file_dir = ''; - if ((substr($v_header['filename'], 0, 1) == '/') && ($v_file_dir == '')) - $v_file_dir = '/'; - - $p_list_detail[$v_nb++] = $v_header; - if (is_array($p_file_list) && (count($p_list_detail) == count($p_file_list))) { - return true; - } - } - } - - return true; - } - // }}} - - // {{{ _openAppend() - function _openAppend() - { - if (filesize($this->_tarname) == 0) - return $this->_openWrite(); - - if ($this->_compress) { - $this->_close(); - - if (!@rename($this->_tarname, $this->_tarname.".tmp")) { - $this->_error('Error while renaming \''.$this->_tarname - .'\' to temporary file \''.$this->_tarname - .'.tmp\''); - return false; - } - - if ($this->_compress_type == 'gz') - $v_temp_tar = @gzopen($this->_tarname.".tmp", "rb"); - elseif ($this->_compress_type == 'bz2') - $v_temp_tar = @bzopen($this->_tarname.".tmp", "r"); - - if ($v_temp_tar == 0) { - $this->_error('Unable to open file \''.$this->_tarname - .'.tmp\' in binary read mode'); - @rename($this->_tarname.".tmp", $this->_tarname); - return false; - } - - if (!$this->_openWrite()) { - @rename($this->_tarname.".tmp", $this->_tarname); - return false; - } - - if ($this->_compress_type == 'gz') { - $end_blocks = 0; - - while (!@gzeof($v_temp_tar)) { - $v_buffer = @gzread($v_temp_tar, 512); - if ($v_buffer == ARCHIVE_TAR_END_BLOCK || strlen($v_buffer) == 0) { - $end_blocks++; - // do not copy end blocks, we will re-make them - // after appending - continue; - } elseif ($end_blocks > 0) { - for ($i = 0; $i < $end_blocks; $i++) { - $this->_writeBlock(ARCHIVE_TAR_END_BLOCK); - } - $end_blocks = 0; - } - $v_binary_data = pack("a512", $v_buffer); - $this->_writeBlock($v_binary_data); - } - - @gzclose($v_temp_tar); - } - elseif ($this->_compress_type == 'bz2') { - $end_blocks = 0; - - while (strlen($v_buffer = @bzread($v_temp_tar, 512)) > 0) { - if ($v_buffer == ARCHIVE_TAR_END_BLOCK || strlen($v_buffer) == 0) { - $end_blocks++; - // do not copy end blocks, we will re-make them - // after appending - continue; - } elseif ($end_blocks > 0) { - for ($i = 0; $i < $end_blocks; $i++) { - $this->_writeBlock(ARCHIVE_TAR_END_BLOCK); - } - $end_blocks = 0; - } - $v_binary_data = pack("a512", $v_buffer); - $this->_writeBlock($v_binary_data); - } - - @bzclose($v_temp_tar); - } - - if (!@unlink($this->_tarname.".tmp")) { - $this->_error('Error while deleting temporary file \'' - .$this->_tarname.'.tmp\''); - } - - } else { - // ----- For not compressed tar, just add files before the last - // one or two 512 bytes block - if (!$this->_openReadWrite()) - return false; - - clearstatcache(); - $v_size = filesize($this->_tarname); - - // We might have zero, one or two end blocks. - // The standard is two, but we should try to handle - // other cases. - fseek($this->_file, $v_size - 1024); - if (fread($this->_file, 512) == ARCHIVE_TAR_END_BLOCK) { - fseek($this->_file, $v_size - 1024); - } - elseif (fread($this->_file, 512) == ARCHIVE_TAR_END_BLOCK) { - fseek($this->_file, $v_size - 512); - } - } - - return true; - } - // }}} - - // {{{ _append() - function _append($p_filelist, $p_add_dir='', $p_remove_dir='') - { - if (!$this->_openAppend()) - return false; - - if ($this->_addList($p_filelist, $p_add_dir, $p_remove_dir)) - $this->_writeFooter(); - - $this->_close(); - - return true; - } - // }}} - - // {{{ _dirCheck() - - /** - * Check if a directory exists and create it (including parent - * dirs) if not. - * - * @param string $p_dir directory to check - * - * @return bool true if the directory exists or was created - */ - function _dirCheck($p_dir) - { - clearstatcache(); - if ((@is_dir($p_dir)) || ($p_dir == '')) - return true; - - $p_parent_dir = dirname($p_dir); - - if (($p_parent_dir != $p_dir) && - ($p_parent_dir != '') && - (!$this->_dirCheck($p_parent_dir))) - return false; - - if (!@mkdir($p_dir, 0777)) { - $this->_error("Unable to create directory '$p_dir'"); - return false; - } - - return true; - } - - // }}} - - // {{{ _pathReduction() - - /** - * Compress path by changing for example "/dir/foo/../bar" to "/dir/bar", - * rand emove double slashes. - * - * @param string $p_dir path to reduce - * - * @return string reduced path - * - * @access private - * - */ - function _pathReduction($p_dir) - { - $v_result = ''; - - // ----- Look for not empty path - if ($p_dir != '') { - // ----- Explode path by directory names - $v_list = explode('/', $p_dir); - - // ----- Study directories from last to first - for ($i=sizeof($v_list)-1; $i>=0; $i--) { - // ----- Look for current path - if ($v_list[$i] == ".") { - // ----- Ignore this directory - // Should be the first $i=0, but no check is done - } - else if ($v_list[$i] == "..") { - // ----- Ignore it and ignore the $i-1 - $i--; - } - else if ( ($v_list[$i] == '') - && ($i!=(sizeof($v_list)-1)) - && ($i!=0)) { - // ----- Ignore only the double '//' in path, - // but not the first and last / - } else { - $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?'/' - .$v_result:''); - } - } - } - - if (defined('OS_WINDOWS') && OS_WINDOWS) { - $v_result = strtr($v_result, '\\', '/'); - } - - return $v_result; - } - - // }}} - - // {{{ _translateWinPath() - function _translateWinPath($p_path, $p_remove_disk_letter=true) - { - if (defined('OS_WINDOWS') && OS_WINDOWS) { - // ----- Look for potential disk letter - if ( ($p_remove_disk_letter) - && (($v_position = strpos($p_path, ':')) != false)) { - $p_path = substr($p_path, $v_position+1); - } - // ----- Change potential windows directory separator - if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) { - $p_path = strtr($p_path, '\\', '/'); - } - } - return $p_path; - } - // }}} - -} -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/Archive/Zip.php b/gulliver/thirdparty/pear/Archive/Zip.php deleted file mode 100644 index e96111080..000000000 --- a/gulliver/thirdparty/pear/Archive/Zip.php +++ /dev/null @@ -1,3620 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Zip.php,v 1.2 2005/11/21 06:51:57 vblavet Exp $ - - require_once 'PEAR.php'; - - // ----- Constants - define( 'ARCHIVE_ZIP_READ_BLOCK_SIZE', 2048 ); - - // ----- File list separator - define( 'ARCHIVE_ZIP_SEPARATOR', ',' ); - - // ----- Optional static temporary directory - // By default temporary files are generated in the script current - // path. - // If defined : - // - MUST BE terminated by a '/'. - // - MUST be a valid, already created directory - // Samples : - // define( 'ARCHIVE_ZIP_TEMPORARY_DIR', '/temp/' ); - // define( 'ARCHIVE_ZIP_TEMPORARY_DIR', 'C:/Temp/' ); - define( 'ARCHIVE_ZIP_TEMPORARY_DIR', '' ); - - // ----- Error codes - define( 'ARCHIVE_ZIP_ERR_NO_ERROR', 0 ); - define( 'ARCHIVE_ZIP_ERR_WRITE_OPEN_FAIL', -1 ); - define( 'ARCHIVE_ZIP_ERR_READ_OPEN_FAIL', -2 ); - define( 'ARCHIVE_ZIP_ERR_INVALID_PARAMETER', -3 ); - define( 'ARCHIVE_ZIP_ERR_MISSING_FILE', -4 ); - define( 'ARCHIVE_ZIP_ERR_FILENAME_TOO_LONG', -5 ); - define( 'ARCHIVE_ZIP_ERR_INVALID_ZIP', -6 ); - define( 'ARCHIVE_ZIP_ERR_BAD_EXTRACTED_FILE', -7 ); - define( 'ARCHIVE_ZIP_ERR_DIR_CREATE_FAIL', -8 ); - define( 'ARCHIVE_ZIP_ERR_BAD_EXTENSION', -9 ); - define( 'ARCHIVE_ZIP_ERR_BAD_FORMAT', -10 ); - define( 'ARCHIVE_ZIP_ERR_DELETE_FILE_FAIL', -11 ); - define( 'ARCHIVE_ZIP_ERR_RENAME_FILE_FAIL', -12 ); - define( 'ARCHIVE_ZIP_ERR_BAD_CHECKSUM', -13 ); - define( 'ARCHIVE_ZIP_ERR_INVALID_ARCHIVE_ZIP', -14 ); - define( 'ARCHIVE_ZIP_ERR_MISSING_OPTION_VALUE', -15 ); - define( 'ARCHIVE_ZIP_ERR_INVALID_PARAM_VALUE', -16 ); - - // ----- Warning codes - define( 'ARCHIVE_ZIP_WARN_NO_WARNING', 0 ); - define( 'ARCHIVE_ZIP_WARN_FILE_EXIST', 1 ); - - // ----- Methods parameters - define( 'ARCHIVE_ZIP_PARAM_PATH', 'path' ); - define( 'ARCHIVE_ZIP_PARAM_ADD_PATH', 'add_path' ); - define( 'ARCHIVE_ZIP_PARAM_REMOVE_PATH', 'remove_path' ); - define( 'ARCHIVE_ZIP_PARAM_REMOVE_ALL_PATH', 'remove_all_path' ); - define( 'ARCHIVE_ZIP_PARAM_SET_CHMOD', 'set_chmod' ); - define( 'ARCHIVE_ZIP_PARAM_EXTRACT_AS_STRING', 'extract_as_string' ); - define( 'ARCHIVE_ZIP_PARAM_NO_COMPRESSION', 'no_compression' ); - define( 'ARCHIVE_ZIP_PARAM_BY_NAME', 'by_name' ); - define( 'ARCHIVE_ZIP_PARAM_BY_INDEX', 'by_index' ); - define( 'ARCHIVE_ZIP_PARAM_BY_EREG', 'by_ereg' ); - define( 'ARCHIVE_ZIP_PARAM_BY_PREG', 'by_preg' ); - - define( 'ARCHIVE_ZIP_PARAM_PRE_EXTRACT', 'callback_pre_extract' ); - define( 'ARCHIVE_ZIP_PARAM_POST_EXTRACT', 'callback_post_extract' ); - define( 'ARCHIVE_ZIP_PARAM_PRE_ADD', 'callback_pre_add' ); - define( 'ARCHIVE_ZIP_PARAM_POST_ADD', 'callback_post_add' ); - - - -/** -* Class for manipulating zip archive files -* -* A class which provided common methods to manipulate ZIP formatted -* archive files. -* It provides creation, extraction, deletion and add features. -* -* @author Vincent Blavet -* @version $Revision: 1.2 $ -* @package Archive_Zip -* @category Archive -*/ -class Archive_Zip -{ - /** - * The filename of the zip archive. - * - * @var string Name of the Zip file - */ - var $_zipname=''; - - /** - * File descriptor of the opened Zip file. - * - * @var int Internal zip file descriptor - */ - var $_zip_fd=0; - - /** - * @var int last error code - */ - var $_error_code=1; - - /** - * @var string Last error description - */ - var $_error_string=''; - - // {{{ constructor - /** - * Archive_Zip Class constructor. This flavour of the constructor only - * declare a new Archive_Zip object, identifying it by the name of the - * zip file. - * - * @param string $p_zipname The name of the zip archive to create - * @access public - */ - function Archive_Zip($p_zipname) - { - - // ----- Check the zlib - if (!extension_loaded('zlib')) { - PEAR::loadExtension('zlib'); - } - if (!extension_loaded('zlib')) { - die("The extension 'zlib' couldn't be found.\n". - "Please make sure your version of PHP was built ". - "with 'zlib' support.\n"); - return false; - } - - // ----- Set the attributes - $this->_zipname = $p_zipname; - $this->_zip_fd = 0; - - return; - } - // }}} - - // {{{ create() - /** - * This method creates a Zip Archive with the filename set with - * the constructor. - * The files and directories indicated in $p_filelist - * are added in the archive. - * When a directory is in the list, the directory and its content is added - * in the archive. - * The methods takes a variable list of parameters in $p_params. - * The supported parameters for this method are : - * 'add_path' : Add a path to the archived files. - * 'remove_path' : Remove the specified 'root' path of the archived files. - * 'remove_all_path' : Remove all the path of the archived files. - * 'no_compression' : The archived files will not be compressed. - * - * @access public - * @param mixed $p_filelist The list of the files or folders to add. - * It can be a string with filenames separated - * by a comma, or an array of filenames. - * @param mixed $p_params An array of variable parameters and values. - * @return mixed An array of file description on success, - * an error code on error - */ - function create($p_filelist, $p_params=0) - { - $this->_errorReset(); - - // ----- Set default values - if ($p_params === 0) { - $p_params = array(); - } - if ($this->_check_parameters($p_params, - array('no_compression' => false, - 'add_path' => "", - 'remove_path' => "", - 'remove_all_path' => false)) != 1) { - return 0; - } - - // ----- Look if the $p_filelist is really an array - $p_result_list = array(); - if (is_array($p_filelist)) { - $v_result = $this->_create($p_filelist, $p_result_list, $p_params); - } - - // ----- Look if the $p_filelist is a string - else if (is_string($p_filelist)) { - // ----- Create a list with the elements from the string - $v_list = explode(ARCHIVE_ZIP_SEPARATOR, $p_filelist); - - $v_result = $this->_create($v_list, $p_result_list, $p_params); - } - - // ----- Invalid variable - else { - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, - 'Invalid variable type p_filelist'); - $v_result = ARCHIVE_ZIP_ERR_INVALID_PARAMETER; - } - - if ($v_result != 1) { - return 0; - } - - return $p_result_list; - } - // }}} - - // {{{ add() - /** - * This method add files or directory in an existing Zip Archive. - * If the Zip Archive does not exist it is created. - * The files and directories to add are indicated in $p_filelist. - * When a directory is in the list, the directory and its content is added - * in the archive. - * The methods takes a variable list of parameters in $p_params. - * The supported parameters for this method are : - * 'add_path' : Add a path to the archived files. - * 'remove_path' : Remove the specified 'root' path of the archived files. - * 'remove_all_path' : Remove all the path of the archived files. - * 'no_compression' : The archived files will not be compressed. - * 'callback_pre_add' : A callback function that will be called before - * each entry archiving. - * 'callback_post_add' : A callback function that will be called after - * each entry archiving. - * - * @access public - * @param mixed $p_filelist The list of the files or folders to add. - * It can be a string with filenames separated - * by a comma, or an array of filenames. - * @param mixed $p_params An array of variable parameters and values. - * @return mixed An array of file description on success, - * 0 on an unrecoverable failure, an error code is logged. - */ - function add($p_filelist, $p_params=0) - { - $this->_errorReset(); - - // ----- Set default values - if ($p_params === 0) { - $p_params = array(); - } - if ($this->_check_parameters($p_params, - array ('no_compression' => false, - 'add_path' => '', - 'remove_path' => '', - 'remove_all_path' => false, - 'callback_pre_add' => '', - 'callback_post_add' => '')) != 1) { - return 0; - } - - // ----- Look if the $p_filelist is really an array - $p_result_list = array(); - if (is_array($p_filelist)) { - // ----- Call the create fct - $v_result = $this->_add($p_filelist, $p_result_list, $p_params); - } - - // ----- Look if the $p_filelist is a string - else if (is_string($p_filelist)) { - // ----- Create a list with the elements from the string - $v_list = explode(ARCHIVE_ZIP_SEPARATOR, $p_filelist); - - // ----- Call the create fct - $v_result = $this->_add($v_list, $p_result_list, $p_params); - } - - // ----- Invalid variable - else { - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, - "add() : Invalid variable type p_filelist"); - $v_result = ARCHIVE_ZIP_ERR_INVALID_PARAMETER; - } - - if ($v_result != 1) { - return 0; - } - - // ----- Return the result list - return $p_result_list; - } - // }}} - - // {{{ listContent() - /** - * This method gives the names and properties of the files and directories - * which are present in the zip archive. - * The properties of each entries in the list are : - * filename : Name of the file. - * For create() or add() it's the filename given by the user. - * For an extract() it's the filename of the extracted file. - * stored_filename : Name of the file / directory stored in the archive. - * size : Size of the stored file. - * compressed_size : Size of the file's data compressed in the archive - * (without the zip headers overhead) - * mtime : Last known modification date of the file (UNIX timestamp) - * comment : Comment associated with the file - * folder : true | false (indicates if the entry is a folder) - * index : index of the file in the archive (-1 when not available) - * status : status of the action on the entry (depending of the action) : - * Values are : - * ok : OK ! - * filtered : the file/dir was not extracted (filtered by user) - * already_a_directory : the file can't be extracted because a - * directory with the same name already - * exists - * write_protected : the file can't be extracted because a file - * with the same name already exists and is - * write protected - * newer_exist : the file was not extracted because a newer - * file already exists - * path_creation_fail : the file is not extracted because the - * folder does not exists and can't be - * created - * write_error : the file was not extracted because there was a - * error while writing the file - * read_error : the file was not extracted because there was a - * error while reading the file - * invalid_header : the file was not extracted because of an - * archive format error (bad file header) - * Note that each time a method can continue operating when there - * is an error on a single file, the error is only logged in the file status. - * - * @access public - * @return mixed An array of file description on success, - * 0 on an unrecoverable failure, an error code is logged. - */ - function listContent() - { - $this->_errorReset(); - - // ----- Check archive - if (!$this->_checkFormat()) { - return(0); - } - - $v_list = array(); - if ($this->_list($v_list) != 1) { - unset($v_list); - return(0); - } - - return $v_list; - } - // }}} - - // {{{ extract() - /** - * This method extract the files and folders which are in the zip archive. - * It can extract all the archive or a part of the archive by using filter - * feature (extract by name, by index, by ereg, by preg). The extraction - * can occur in the current path or an other path. - * All the advanced features are activated by the use of variable - * parameters. - * The return value is an array of entry descriptions which gives - * information on extracted files (See listContent()). - * The method may return a success value (an array) even if some files - * are not correctly extracted (see the file status in listContent()). - * The supported variable parameters for this method are : - * 'add_path' : Path where the files and directories are to be extracted - * 'remove_path' : First part ('root' part) of the memorized path - * (if similar) to remove while extracting. - * 'remove_all_path' : Remove all the memorized path while extracting. - * 'extract_as_string' : - * 'set_chmod' : After the extraction of the file the indicated mode - * will be set. - * 'by_name' : It can be a string with file/dir names separated by ',', - * or an array of file/dir names to extract from the archive. - * 'by_index' : A string with range of indexes separated by ',', - * (sample "1,3-5,12"). - * 'by_ereg' : A regular expression (ereg) that must match the extracted - * filename. - * 'by_preg' : A regular expression (preg) that must match the extracted - * filename. - * 'callback_pre_extract' : A callback function that will be called before - * each entry extraction. - * 'callback_post_extract' : A callback function that will be called after - * each entry extraction. - * - * @access public - * @param mixed $p_params An array of variable parameters and values. - * @return mixed An array of file description on success, - * 0 on an unrecoverable failure, an error code is logged. - */ - function extract($p_params=0) - { - - $this->_errorReset(); - - // ----- Check archive - if (!$this->_checkFormat()) { - return(0); - } - - // ----- Set default values - if ($p_params === 0) { - $p_params = array(); - } - if ($this->_check_parameters($p_params, - array ('extract_as_string' => false, - 'add_path' => '', - 'remove_path' => '', - 'remove_all_path' => false, - 'callback_pre_extract' => '', - 'callback_post_extract' => '', - 'set_chmod' => 0, - 'by_name' => '', - 'by_index' => '', - 'by_ereg' => '', - 'by_preg' => '') ) != 1) { - return 0; - } - - // ----- Call the extracting fct - $v_list = array(); - if ($this->_extractByRule($v_list, $p_params) != 1) { - unset($v_list); - return(0); - } - - return $v_list; - } - // }}} - - - // {{{ delete() - /** - * This methods delete archive entries in the zip archive. - * Notice that at least one filtering rule (set by the variable parameter - * list) must be set. - * Also notice that if you delete a folder entry, only the folder entry - * is deleted, not all the files bellonging to this folder. - * The supported variable parameters for this method are : - * 'by_name' : It can be a string with file/dir names separated by ',', - * or an array of file/dir names to delete from the archive. - * 'by_index' : A string with range of indexes separated by ',', - * (sample "1,3-5,12"). - * 'by_ereg' : A regular expression (ereg) that must match the extracted - * filename. - * 'by_preg' : A regular expression (preg) that must match the extracted - * filename. - * - * @access public - * @param mixed $p_params An array of variable parameters and values. - * @return mixed An array of file description on success, - * 0 on an unrecoverable failure, an error code is logged. - */ - function delete($p_params) - { - $this->_errorReset(); - - // ----- Check archive - if (!$this->_checkFormat()) { - return(0); - } - - // ----- Set default values - if ($this->_check_parameters($p_params, - array ('by_name' => '', - 'by_index' => '', - 'by_ereg' => '', - 'by_preg' => '') ) != 1) { - return 0; - } - - // ----- Check that at least one rule is set - if ( ($p_params['by_name'] == '') - && ($p_params['by_index'] == '') - && ($p_params['by_ereg'] == '') - && ($p_params['by_preg'] == '')) { - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, - 'At least one filtering rule must' - .' be set as parameter'); - return 0; - } - - // ----- Call the delete fct - $v_list = array(); - if ($this->_deleteByRule($v_list, $p_params) != 1) { - unset($v_list); - return(0); - } - - return $v_list; - } - // }}} - - // {{{ properties() - /** - * This method gives the global properties of the archive. - * The properties are : - * nb : Number of files in the archive - * comment : Comment associated with the archive file - * status : not_exist, ok - * - * @access public - * @param mixed $p_params {Description} - * @return mixed An array with the global properties or 0 on error. - */ - function properties() - { - $this->_errorReset(); - - // ----- Check archive - if (!$this->_checkFormat()) { - return(0); - } - - // ----- Default properties - $v_prop = array(); - $v_prop['comment'] = ''; - $v_prop['nb'] = 0; - $v_prop['status'] = 'not_exist'; - - // ----- Look if file exists - if (@is_file($this->_zipname)) { - // ----- Open the zip file - if (($this->_zip_fd = @fopen($this->_zipname, 'rb')) == 0) { - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, - 'Unable to open archive \''.$this->_zipname - .'\' in binary read mode'); - return 0; - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->_readEndCentralDir($v_central_dir)) != 1) { - return 0; - } - - $this->_closeFd(); - - // ----- Set the user attributes - $v_prop['comment'] = $v_central_dir['comment']; - $v_prop['nb'] = $v_central_dir['entries']; - $v_prop['status'] = 'ok'; - } - - return $v_prop; - } - // }}} - - - // {{{ duplicate() - /** - * This method creates an archive by copying the content of an other one. - * If the archive already exist, it is replaced by the new one without - * any warning. - * - * @access public - * @param mixed $p_archive It can be a valid Archive_Zip object or - * the filename of a valid zip archive. - * @return integer 1 on success, 0 on failure. - */ - function duplicate($p_archive) - { - $this->_errorReset(); - - // ----- Look if the $p_archive is a Archive_Zip object - if ( (is_object($p_archive)) - && (strtolower(get_class($p_archive)) == 'archive_zip')) { - $v_result = $this->_duplicate($p_archive->_zipname); - } - - // ----- Look if the $p_archive is a string (so a filename) - else if (is_string($p_archive)) { - // ----- Check that $p_archive is a valid zip file - // TBC : Should also check the archive format - if (!is_file($p_archive)) { - $this->_errorLog(ARCHIVE_ZIP_ERR_MISSING_FILE, - "No file with filename '".$p_archive."'"); - $v_result = ARCHIVE_ZIP_ERR_MISSING_FILE; - } - else { - $v_result = $this->_duplicate($p_archive); - } - } - - // ----- Invalid variable - else { - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, - "Invalid variable type p_archive_to_add"); - $v_result = ARCHIVE_ZIP_ERR_INVALID_PARAMETER; - } - - return $v_result; - } - // }}} - - // {{{ merge() - /** - * This method merge a valid zip archive at the end of the - * archive identified by the Archive_Zip object. - * If the archive ($this) does not exist, the merge becomes a duplicate. - * If the archive to add does not exist, the merge is a success. - * - * @access public - * @param mixed $p_archive_to_add It can be a valid Archive_Zip object or - * the filename of a valid zip archive. - * @return integer 1 on success, 0 on failure. - */ - function merge($p_archive_to_add) - { - $v_result = 1; - $this->_errorReset(); - - // ----- Check archive - if (!$this->_checkFormat()) { - return(0); - } - - // ----- Look if the $p_archive_to_add is a Archive_Zip object - if ( (is_object($p_archive_to_add)) - && (strtolower(get_class($p_archive_to_add)) == 'archive_zip')) { - $v_result = $this->_merge($p_archive_to_add); - } - - // ----- Look if the $p_archive_to_add is a string (so a filename) - else if (is_string($p_archive_to_add)) { - // ----- Create a temporary archive - $v_object_archive = new Archive_Zip($p_archive_to_add); - - // ----- Merge the archive - $v_result = $this->_merge($v_object_archive); - } - - // ----- Invalid variable - else { - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, - "Invalid variable type p_archive_to_add"); - $v_result = ARCHIVE_ZIP_ERR_INVALID_PARAMETER; - } - - return $v_result; - } - // }}} - - // {{{ errorCode() - /** - * Method that gives the lastest error code. - * - * @access public - * @return integer The error code value. - */ - function errorCode() - { - return($this->_error_code); - } - // }}} - - // {{{ errorName() - /** - * This method gives the latest error code name. - * - * @access public - * @param boolean $p_with_code If true, gives the name and the int value. - * @return string The error name. - */ - function errorName($p_with_code=false) - { - $v_const_list = get_defined_constants(); - - // ----- Extract error constants from all const. - for (reset($v_const_list); - list($v_key, $v_value) = each($v_const_list);) { - if (substr($v_key, 0, strlen('ARCHIVE_ZIP_ERR_')) - =='ARCHIVE_ZIP_ERR_') { - $v_error_list[$v_key] = $v_value; - } - } - - // ----- Search the name form the code value - $v_key=array_search($this->_error_code, $v_error_list, true); - if ($v_key!=false) { - $v_value = $v_key; - } - else { - $v_value = 'NoName'; - } - - if ($p_with_code) { - return($v_value.' ('.$this->_error_code.')'); - } - else { - return($v_value); - } - } - // }}} - - // {{{ errorInfo() - /** - * This method returns the description associated with the latest error. - * - * @access public - * @param boolean $p_full If set to true gives the description with the - * error code, the name and the description. - * If set to false gives only the description - * and the error code. - * @return string The error description. - */ - function errorInfo($p_full=false) - { - if ($p_full) { - return($this->errorName(true)." : ".$this->_error_string); - } - else { - return($this->_error_string." [code ".$this->_error_code."]"); - } - } - // }}} - - -// ----------------------------------------------------------------------------- -// ***** UNDER THIS LINE ARE DEFINED PRIVATE INTERNAL FUNCTIONS ***** -// ***** ***** -// ***** THESES FUNCTIONS MUST NOT BE USED DIRECTLY ***** -// ----------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _checkFormat() - // Description : - // This method check that the archive exists and is a valid zip archive. - // Several level of check exists. (futur) - // Parameters : - // $p_level : Level of check. Default 0. - // 0 : Check the first bytes (magic codes) (default value)) - // 1 : 0 + Check the central directory (futur) - // 2 : 1 + Check each file header (futur) - // Return Values : - // true on success, - // false on error, the error code is set. - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_checkFormat() - * - * { Description } - * - * @param integer $p_level - */ - function _checkFormat($p_level=0) - { - $v_result = true; - - // ----- Reset the error handler - $this->_errorReset(); - - // ----- Look if the file exits - if (!is_file($this->_zipname)) { - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_MISSING_FILE, - "Missing archive file '".$this->_zipname."'"); - return(false); - } - - // ----- Check that the file is readeable - if (!is_readable($this->_zipname)) { - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, - "Unable to read archive '".$this->_zipname."'"); - return(false); - } - - // ----- Check the magic code - // TBC - - // ----- Check the central header - // TBC - - // ----- Check each file header - // TBC - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _create() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_create() - * - * { Description } - * - */ - function _create($p_list, &$p_result_list, &$p_params) - { - $v_result=1; - $v_list_detail = array(); - - $p_add_dir = $p_params['add_path']; - $p_remove_dir = $p_params['remove_path']; - $p_remove_all_dir = $p_params['remove_all_path']; - - // ----- Open the file in write mode - if (($v_result = $this->_openFd('wb')) != 1) - { - // ----- Return - return $v_result; - } - - // ----- Add the list of files - $v_result = $this->_addList($p_list, $p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, $p_params); - - // ----- Close - $this->_closeFd(); - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _add() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_add() - * - * { Description } - * - */ - function _add($p_list, &$p_result_list, &$p_params) - { - $v_result=1; - $v_list_detail = array(); - - $p_add_dir = $p_params['add_path']; - $p_remove_dir = $p_params['remove_path']; - $p_remove_all_dir = $p_params['remove_all_path']; - - // ----- Look if the archive exists or is empty and need to be created - if ((!is_file($this->_zipname)) || (filesize($this->_zipname) == 0)) { - $v_result = $this->_create($p_list, $p_result_list, $p_params); - return $v_result; - } - - // ----- Open the zip file - if (($v_result=$this->_openFd('rb')) != 1) { - return $v_result; - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->_readEndCentralDir($v_central_dir)) != 1) - { - $this->_closeFd(); - return $v_result; - } - - // ----- Go to beginning of File - @rewind($this->_zip_fd); - - // ----- Creates a temporay file - $v_zip_temp_name = ARCHIVE_ZIP_TEMPORARY_DIR.uniqid('archive_zip-').'.tmp'; - - // ----- Open the temporary file in write mode - if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) - { - $this->_closeFd(); - - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, - 'Unable to open temporary file \'' - .$v_zip_temp_name.'\' in binary write mode'); - return Archive_Zip::errorCode(); - } - - // ----- Copy the files from the archive to the temporary file - // TBC : Here I should better append the file and go back to erase the - // central dir - $v_size = $v_central_dir['offset']; - while ($v_size != 0) - { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = fread($this->_zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Swap the file descriptor - // Here is a trick : I swap the temporary fd with the zip fd, in order to - // use the following methods on the temporary fil and not the real archive - $v_swap = $this->_zip_fd; - $this->_zip_fd = $v_zip_temp_fd; - $v_zip_temp_fd = $v_swap; - - // ----- Add the files - $v_header_list = array(); - if (($v_result = $this->_addFileList($p_list, $v_header_list, - $p_add_dir, $p_remove_dir, - $p_remove_all_dir, $p_params)) != 1) - { - fclose($v_zip_temp_fd); - $this->_closeFd(); - @unlink($v_zip_temp_name); - - // ----- Return - return $v_result; - } - - // ----- Store the offset of the central dir - $v_offset = @ftell($this->_zip_fd); - - // ----- Copy the block of file headers from the old archive - $v_size = $v_central_dir['size']; - while ($v_size != 0) - { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($v_zip_temp_fd, $v_read_size); - @fwrite($this->_zip_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Create the Central Dir files header - for ($i=0, $v_count=0; $i_writeCentralFileHeader($v_header_list[$i]))!=1) { - fclose($v_zip_temp_fd); - $this->_closeFd(); - @unlink($v_zip_temp_name); - - // ----- Return - return $v_result; - } - $v_count++; - } - - // ----- Transform the header to a 'usable' info - $this->_convertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); - } - - // ----- Zip file comment - $v_comment = ''; - - // ----- Calculate the size of the central header - $v_size = @ftell($this->_zip_fd)-$v_offset; - - // ----- Create the central dir footer - if (($v_result = $this->_writeCentralHeader($v_count - +$v_central_dir['entries'], - $v_size, $v_offset, - $v_comment)) != 1) { - // ----- Reset the file list - unset($v_header_list); - - // ----- Return - return $v_result; - } - - // ----- Swap back the file descriptor - $v_swap = $this->_zip_fd; - $this->_zip_fd = $v_zip_temp_fd; - $v_zip_temp_fd = $v_swap; - - // ----- Close - $this->_closeFd(); - - // ----- Close the temporary file - @fclose($v_zip_temp_fd); - - // ----- Delete the zip file - // TBC : I should test the result ... - @unlink($this->_zipname); - - // ----- Rename the temporary file - // TBC : I should test the result ... - //@rename($v_zip_temp_name, $this->_zipname); - $this->_tool_Rename($v_zip_temp_name, $this->_zipname); - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _openFd() - // Description : - // Parameters : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_openFd() - * - * { Description } - * - */ - function _openFd($p_mode) - { - $v_result=1; - - // ----- Look if already open - if ($this->_zip_fd != 0) - { - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, - 'Zip file \''.$this->_zipname.'\' already open'); - return Archive_Zip::errorCode(); - } - - // ----- Open the zip file - if (($this->_zip_fd = @fopen($this->_zipname, $p_mode)) == 0) - { - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, - 'Unable to open archive \''.$this->_zipname - .'\' in '.$p_mode.' mode'); - return Archive_Zip::errorCode(); - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _closeFd() - // Description : - // Parameters : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_closeFd() - * - * { Description } - * - */ - function _closeFd() - { - $v_result=1; - - if ($this->_zip_fd != 0) - @fclose($this->_zip_fd); - $this->_zip_fd = 0; - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _addList() - // Description : - // $p_add_dir and $p_remove_dir will give the ability to memorize a path which is - // different from the real path of the file. This is usefull if you want to have PclTar - // running in any directory, and memorize relative path from an other directory. - // Parameters : - // $p_list : An array containing the file or directory names to add in the tar - // $p_result_list : list of added files with their properties (specially the status field) - // $p_add_dir : Path to add in the filename path archived - // $p_remove_dir : Path to remove in the filename path archived - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_addList() - * - * { Description } - * - */ - function _addList($p_list, &$p_result_list, - $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_params) - { - $v_result=1; - - // ----- Add the files - $v_header_list = array(); - if (($v_result = $this->_addFileList($p_list, $v_header_list, - $p_add_dir, $p_remove_dir, - $p_remove_all_dir, $p_params)) != 1) { - return $v_result; - } - - // ----- Store the offset of the central dir - $v_offset = @ftell($this->_zip_fd); - - // ----- Create the Central Dir files header - for ($i=0,$v_count=0; $i_writeCentralFileHeader($v_header_list[$i])) != 1) { - return $v_result; - } - $v_count++; - } - - // ----- Transform the header to a 'usable' info - $this->_convertHeader2FileInfo($v_header_list[$i], $p_result_list[$i]); - } - - // ----- Zip file comment - $v_comment = ''; - - // ----- Calculate the size of the central header - $v_size = @ftell($this->_zip_fd)-$v_offset; - - // ----- Create the central dir footer - if (($v_result = $this->_writeCentralHeader($v_count, $v_size, $v_offset, - $v_comment)) != 1) - { - // ----- Reset the file list - unset($v_header_list); - - // ----- Return - return $v_result; - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _addFileList() - // Description : - // $p_add_dir and $p_remove_dir will give the ability to memorize a path which is - // different from the real path of the file. This is usefull if you want to - // run the lib in any directory, and memorize relative path from an other directory. - // Parameters : - // $p_list : An array containing the file or directory names to add in the tar - // $p_result_list : list of added files with their properties (specially the status field) - // $p_add_dir : Path to add in the filename path archived - // $p_remove_dir : Path to remove in the filename path archived - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_addFileList() - * - * { Description } - * - */ - function _addFileList($p_list, &$p_result_list, - $p_add_dir, $p_remove_dir, $p_remove_all_dir, - &$p_params) - { - $v_result=1; - $v_header = array(); - - // ----- Recuperate the current number of elt in list - $v_nb = sizeof($p_result_list); - - // ----- Loop on the files - for ($j=0; ($j_tool_TranslateWinPath($p_list[$j], false); - - // ----- Skip empty file names - if ($p_filename == "") - { - continue; - } - - // ----- Check the filename - if (!file_exists($p_filename)) - { - $this->_errorLog(ARCHIVE_ZIP_ERR_MISSING_FILE, - "File '$p_filename' does not exists"); - return Archive_Zip::errorCode(); - } - - // ----- Look if it is a file or a dir with no all pathnre move - if ((is_file($p_filename)) || ((is_dir($p_filename)) && !$p_remove_all_dir)) { - // ----- Add the file - if (($v_result = $this->_addFile($p_filename, $v_header, $p_add_dir, $p_remove_dir, $p_remove_all_dir, $p_params)) != 1) - { - // ----- Return status - return $v_result; - } - - // ----- Store the file infos - $p_result_list[$v_nb++] = $v_header; - } - - // ----- Look for directory - if (is_dir($p_filename)) - { - - // ----- Look for path - if ($p_filename != ".") - $v_path = $p_filename."/"; - else - $v_path = ""; - - // ----- Read the directory for files and sub-directories - $p_hdir = opendir($p_filename); - $p_hitem = readdir($p_hdir); // '.' directory - $p_hitem = readdir($p_hdir); // '..' directory - while ($p_hitem = readdir($p_hdir)) - { - - // ----- Look for a file - if (is_file($v_path.$p_hitem)) - { - - // ----- Add the file - if (($v_result = $this->_addFile($v_path.$p_hitem, $v_header, $p_add_dir, $p_remove_dir, $p_remove_all_dir, $p_params)) != 1) - { - // ----- Return status - return $v_result; - } - - // ----- Store the file infos - $p_result_list[$v_nb++] = $v_header; - } - - // ----- Recursive call to _addFileList() - else - { - - // ----- Need an array as parameter - $p_temp_list[0] = $v_path.$p_hitem; - $v_result = $this->_addFileList($p_temp_list, $p_result_list, $p_add_dir, $p_remove_dir, $p_remove_all_dir, $p_params); - - // ----- Update the number of elements of the list - $v_nb = sizeof($p_result_list); - } - } - - // ----- Free memory for the recursive loop - unset($p_temp_list); - unset($p_hdir); - unset($p_hitem); - } - } - - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _addFile() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_addFile() - * - * { Description } - * - */ - function _addFile($p_filename, &$p_header, $p_add_dir, $p_remove_dir, $p_remove_all_dir, &$p_params) - { - $v_result=1; - - if ($p_filename == "") - { - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, "Invalid file list parameter (invalid or empty list)"); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Calculate the stored filename - $v_stored_filename = $p_filename; - - // ----- Look for all path to remove - if ($p_remove_all_dir) { - $v_stored_filename = basename($p_filename); - } - // ----- Look for partial path remove - else if ($p_remove_dir != "") - { - if (substr($p_remove_dir, -1) != '/') - $p_remove_dir .= "/"; - - if ((substr($p_filename, 0, 2) == "./") || (substr($p_remove_dir, 0, 2) == "./")) - { - if ((substr($p_filename, 0, 2) == "./") && (substr($p_remove_dir, 0, 2) != "./")) - $p_remove_dir = "./".$p_remove_dir; - if ((substr($p_filename, 0, 2) != "./") && (substr($p_remove_dir, 0, 2) == "./")) - $p_remove_dir = substr($p_remove_dir, 2); - } - - $v_compare = $this->_tool_PathInclusion($p_remove_dir, $p_filename); - if ($v_compare > 0) -// if (substr($p_filename, 0, strlen($p_remove_dir)) == $p_remove_dir) - { - - if ($v_compare == 2) { - $v_stored_filename = ""; - } - else { - $v_stored_filename = substr($p_filename, strlen($p_remove_dir)); - } - } - } - // ----- Look for path to add - if ($p_add_dir != "") - { - if (substr($p_add_dir, -1) == "/") - $v_stored_filename = $p_add_dir.$v_stored_filename; - else - $v_stored_filename = $p_add_dir."/".$v_stored_filename; - } - - // ----- Filename (reduce the path of stored name) - $v_stored_filename = $this->_tool_PathReduction($v_stored_filename); - - - /* filename length moved after call-back in release 1.3 - // ----- Check the path length - if (strlen($v_stored_filename) > 0xFF) - { - // ----- Error log - $this->_errorLog(-5, "Stored file name is too long (max. 255) : '$v_stored_filename'"); - - // ----- Return - return Archive_Zip::errorCode(); - } - */ - - // ----- Set the file properties - clearstatcache(); - $p_header['version'] = 20; - $p_header['version_extracted'] = 10; - $p_header['flag'] = 0; - $p_header['compression'] = 0; - $p_header['mtime'] = filemtime($p_filename); - $p_header['crc'] = 0; - $p_header['compressed_size'] = 0; - $p_header['size'] = filesize($p_filename); - $p_header['filename_len'] = strlen($p_filename); - $p_header['extra_len'] = 0; - $p_header['comment_len'] = 0; - $p_header['disk'] = 0; - $p_header['internal'] = 0; - $p_header['external'] = (is_file($p_filename)?0xFE49FFE0:0x41FF0010); - $p_header['offset'] = 0; - $p_header['filename'] = $p_filename; - $p_header['stored_filename'] = $v_stored_filename; - $p_header['extra'] = ''; - $p_header['comment'] = ''; - $p_header['status'] = 'ok'; - $p_header['index'] = -1; - - // ----- Look for pre-add callback - if ( (isset($p_params[ARCHIVE_ZIP_PARAM_PRE_ADD])) - && ($p_params[ARCHIVE_ZIP_PARAM_PRE_ADD] != '')) { - - // ----- Generate a local information - $v_local_header = array(); - $this->_convertHeader2FileInfo($p_header, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. - eval('$v_result = '.$p_params[ARCHIVE_ZIP_PARAM_PRE_ADD].'(ARCHIVE_ZIP_PARAM_PRE_ADD, $v_local_header);'); - if ($v_result == 0) { - // ----- Change the file status - $p_header['status'] = "skipped"; - $v_result = 1; - } - - // ----- Update the informations - // Only some fields can be modified - if ($p_header['stored_filename'] != $v_local_header['stored_filename']) { - $p_header['stored_filename'] = $this->_tool_PathReduction($v_local_header['stored_filename']); - } - } - - // ----- Look for empty stored filename - if ($p_header['stored_filename'] == "") { - $p_header['status'] = "filtered"; - } - - // ----- Check the path length - if (strlen($p_header['stored_filename']) > 0xFF) { - $p_header['status'] = 'filename_too_long'; - } - - // ----- Look if no error, or file not skipped - if ($p_header['status'] == 'ok') { - - // ----- Look for a file - if (is_file($p_filename)) - { - // ----- Open the source file - if (($v_file = @fopen($p_filename, "rb")) == 0) { - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, "Unable to open file '$p_filename' in binary read mode"); - return Archive_Zip::errorCode(); - } - - if ($p_params['no_compression']) { - // ----- Read the file content - $v_content_compressed = @fread($v_file, $p_header['size']); - - // ----- Calculate the CRC - $p_header['crc'] = $this->encryptCrc32($v_content_compressed); - } - else { - // ----- Read the file content - $v_content = @fread($v_file, $p_header['size']); - - // ----- Calculate the CRC - $p_header['crc'] = $this->encryptCrc32($v_content); - - // ----- Compress the file - $v_content_compressed = gzdeflate($v_content); - } - - // ----- Set header parameters - $p_header['compressed_size'] = strlen($v_content_compressed); - $p_header['compression'] = 8; - - // ----- Call the header generation - if (($v_result = $this->_writeFileHeader($p_header)) != 1) { - @fclose($v_file); - return $v_result; - } - - // ----- Write the compressed content - $v_binary_data = pack('a'.$p_header['compressed_size'], $v_content_compressed); - @fwrite($this->_zip_fd, $v_binary_data, $p_header['compressed_size']); - - // ----- Close the file - @fclose($v_file); - } - - // ----- Look for a directory - else - { - // ----- Set the file properties - $p_header['filename'] .= '/'; - $p_header['filename_len']++; - $p_header['size'] = 0; - $p_header['external'] = 0x41FF0010; // Value for a folder : to be checked - - // ----- Call the header generation - if (($v_result = $this->_writeFileHeader($p_header)) != 1) - { - return $v_result; - } - } - } - - // ----- Look for pre-add callback - if ( (isset($p_params[ARCHIVE_ZIP_PARAM_POST_ADD])) - && ($p_params[ARCHIVE_ZIP_PARAM_POST_ADD] != '')) { - - // ----- Generate a local information - $v_local_header = array(); - $this->_convertHeader2FileInfo($p_header, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. - eval('$v_result = '.$p_params[ARCHIVE_ZIP_PARAM_POST_ADD].'(ARCHIVE_ZIP_PARAM_POST_ADD, $v_local_header);'); - if ($v_result == 0) { - // ----- Ignored - $v_result = 1; - } - - // ----- Update the informations - // Nothing can be modified - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _writeFileHeader() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_writeFileHeader() - * - * { Description } - * - */ - function _writeFileHeader(&$p_header) - { - $v_result=1; - - // TBC - //for(reset($p_header); $key = key($p_header); next($p_header)) { - //} - - // ----- Store the offset position of the file - $p_header['offset'] = ftell($this->_zip_fd); - - // ----- Transform UNIX mtime to DOS format mdate/mtime - $v_date = getdate($p_header['mtime']); - $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; - $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; - - // ----- Packed data - $v_binary_data = pack("VvvvvvVVVvv", 0x04034b50, $p_header['version'], $p_header['flag'], - $p_header['compression'], $v_mtime, $v_mdate, - $p_header['crc'], $p_header['compressed_size'], $p_header['size'], - strlen($p_header['stored_filename']), $p_header['extra_len']); - - // ----- Write the first 148 bytes of the header in the archive - fputs($this->_zip_fd, $v_binary_data, 30); - - // ----- Write the variable fields - if (strlen($p_header['stored_filename']) != 0) - { - fputs($this->_zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); - } - if ($p_header['extra_len'] != 0) - { - fputs($this->_zip_fd, $p_header['extra'], $p_header['extra_len']); - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _writeCentralFileHeader() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_writeCentralFileHeader() - * - * { Description } - * - */ - function _writeCentralFileHeader(&$p_header) - { - $v_result=1; - - // TBC - //for(reset($p_header); $key = key($p_header); next($p_header)) { - //} - - // ----- Transform UNIX mtime to DOS format mdate/mtime - $v_date = getdate($p_header['mtime']); - $v_mtime = ($v_date['hours']<<11) + ($v_date['minutes']<<5) + $v_date['seconds']/2; - $v_mdate = (($v_date['year']-1980)<<9) + ($v_date['mon']<<5) + $v_date['mday']; - - // ----- Packed data - $v_binary_data = pack("VvvvvvvVVVvvvvvVV", 0x02014b50, $p_header['version'], $p_header['version_extracted'], - $p_header['flag'], $p_header['compression'], $v_mtime, $v_mdate, $p_header['crc'], - $p_header['compressed_size'], $p_header['size'], - strlen($p_header['stored_filename']), $p_header['extra_len'], $p_header['comment_len'], - $p_header['disk'], $p_header['internal'], $p_header['external'], $p_header['offset']); - - // ----- Write the 42 bytes of the header in the zip file - fputs($this->_zip_fd, $v_binary_data, 46); - - // ----- Write the variable fields - if (strlen($p_header['stored_filename']) != 0) - { - fputs($this->_zip_fd, $p_header['stored_filename'], strlen($p_header['stored_filename'])); - } - if ($p_header['extra_len'] != 0) - { - fputs($this->_zip_fd, $p_header['extra'], $p_header['extra_len']); - } - if ($p_header['comment_len'] != 0) - { - fputs($this->_zip_fd, $p_header['comment'], $p_header['comment_len']); - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _writeCentralHeader() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_writeCentralHeader() - * - * { Description } - * - */ - function _writeCentralHeader($p_nb_entries, $p_size, $p_offset, $p_comment) - { - $v_result=1; - - // ----- Packed data - $v_binary_data = pack("VvvvvVVv", 0x06054b50, 0, 0, $p_nb_entries, $p_nb_entries, $p_size, $p_offset, strlen($p_comment)); - - // ----- Write the 22 bytes of the header in the zip file - fputs($this->_zip_fd, $v_binary_data, 22); - - // ----- Write the variable fields - if (strlen($p_comment) != 0) - { - fputs($this->_zip_fd, $p_comment, strlen($p_comment)); - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _list() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_list() - * - * { Description } - * - */ - function _list(&$p_list) - { - $v_result=1; - - // ----- Open the zip file - if (($this->_zip_fd = @fopen($this->_zipname, 'rb')) == 0) - { - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, 'Unable to open archive \''.$this->_zipname.'\' in binary read mode'); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->_readEndCentralDir($v_central_dir)) != 1) - { - return $v_result; - } - - // ----- Go to beginning of Central Dir - @rewind($this->_zip_fd); - if (@fseek($this->_zip_fd, $v_central_dir['offset'])) - { - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Read each entry - for ($i=0; $i<$v_central_dir['entries']; $i++) - { - // ----- Read the file header - if (($v_result = $this->_readCentralFileHeader($v_header)) != 1) - { - return $v_result; - } - $v_header['index'] = $i; - - // ----- Get the only interesting attributes - $this->_convertHeader2FileInfo($v_header, $p_list[$i]); - unset($v_header); - } - - // ----- Close the zip file - $this->_closeFd(); - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _convertHeader2FileInfo() - // Description : - // This function takes the file informations from the central directory - // entries and extract the interesting parameters that will be given back. - // The resulting file infos are set in the array $p_info - // $p_info['filename'] : Filename with full path. Given by user (add), - // extracted in the filesystem (extract). - // $p_info['stored_filename'] : Stored filename in the archive. - // $p_info['size'] = Size of the file. - // $p_info['compressed_size'] = Compressed size of the file. - // $p_info['mtime'] = Last modification date of the file. - // $p_info['comment'] = Comment associated with the file. - // $p_info['folder'] = true/false : indicates if the entry is a folder or not. - // $p_info['status'] = status of the action on the file. - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_convertHeader2FileInfo() - * - * { Description } - * - */ - function _convertHeader2FileInfo($p_header, &$p_info) - { - $v_result=1; - - // ----- Get the interesting attributes - $p_info['filename'] = $p_header['filename']; - $p_info['stored_filename'] = $p_header['stored_filename']; - $p_info['size'] = $p_header['size']; - $p_info['compressed_size'] = $p_header['compressed_size']; - $p_info['mtime'] = $p_header['mtime']; - $p_info['comment'] = $p_header['comment']; - $p_info['folder'] = (($p_header['external']&0x00000010)==0x00000010); - $p_info['index'] = $p_header['index']; - $p_info['status'] = $p_header['status']; - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _extractByRule() - // Description : - // Extract a file or directory depending of rules (by index, by name, ...) - // Parameters : - // $p_file_list : An array where will be placed the properties of each - // extracted file - // $p_path : Path to add while writing the extracted files - // $p_remove_path : Path to remove (from the file memorized path) while writing the - // extracted files. If the path does not match the file path, - // the file is extracted with its memorized path. - // $p_remove_path does not apply to 'list' mode. - // $p_path and $p_remove_path are commulative. - // Return Values : - // 1 on success,0 or less on error (see error code list) - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_extractByRule() - * - * { Description } - * - */ - function _extractByRule(&$p_file_list, &$p_params) - { - $v_result=1; - - $p_path = $p_params['add_path']; - $p_remove_path = $p_params['remove_path']; - $p_remove_all_path = $p_params['remove_all_path']; - - // ----- Check the path - if (($p_path == "") - || ((substr($p_path, 0, 1) != "/") - && (substr($p_path, 0, 3) != "../") && (substr($p_path,1,2)!=":/"))) - $p_path = "./".$p_path; - - // ----- Reduce the path last (and duplicated) '/' - if (($p_path != "./") && ($p_path != "/")) { - // ----- Look for the path end '/' - while (substr($p_path, -1) == "/") { - $p_path = substr($p_path, 0, strlen($p_path)-1); - } - } - - // ----- Look for path to remove format (should end by /) - if (($p_remove_path != "") && (substr($p_remove_path, -1) != '/')) { - $p_remove_path .= '/'; - } - $p_remove_path_size = strlen($p_remove_path); - - // ----- Open the zip file - if (($v_result = $this->_openFd('rb')) != 1) - { - return $v_result; - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->_readEndCentralDir($v_central_dir)) != 1) - { - // ----- Close the zip file - $this->_closeFd(); - - return $v_result; - } - - // ----- Start at beginning of Central Dir - $v_pos_entry = $v_central_dir['offset']; - - // ----- Read each entry - $j_start = 0; - for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) { - // ----- Read next Central dir entry - @rewind($this->_zip_fd); - if (@fseek($this->_zip_fd, $v_pos_entry)) { - $this->_closeFd(); - - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_ARCHIVE_ZIP, - 'Invalid archive size'); - - return Archive_Zip::errorCode(); - } - - // ----- Read the file header - $v_header = array(); - if (($v_result = $this->_readCentralFileHeader($v_header)) != 1) { - $this->_closeFd(); - - return $v_result; - } - - // ----- Store the index - $v_header['index'] = $i; - - // ----- Store the file position - $v_pos_entry = ftell($this->_zip_fd); - - // ----- Look for the specific extract rules - $v_extract = false; - - // ----- Look for extract by name rule - if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_NAME])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_NAME] != 0)) { - - // ----- Look if the filename is in the list - for ($j=0; - ($j strlen($p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j])) - && (substr($v_header['stored_filename'], 0, strlen($p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j])) == $p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j])) { - $v_extract = true; - } - } - // ----- Look for a filename - elseif ($v_header['stored_filename'] == $p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j]) { - $v_extract = true; - } - } - } - - // ----- Look for extract by ereg rule - else if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_EREG])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_EREG] != "")) { - - if (ereg($p_params[ARCHIVE_ZIP_PARAM_BY_EREG], $v_header['stored_filename'])) { - $v_extract = true; - } - } - - // ----- Look for extract by preg rule - else if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_PREG])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_PREG] != "")) { - - if (preg_match($p_params[ARCHIVE_ZIP_PARAM_BY_PREG], $v_header['stored_filename'])) { - $v_extract = true; - } - } - - // ----- Look for extract by index rule - else if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_INDEX])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_INDEX] != 0)) { - - // ----- Look if the index is in the list - for ($j=$j_start; ($j=$p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['start']) && ($i<=$p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['end'])) { - $v_extract = true; - } - if ($i>=$p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['end']) { - $j_start = $j+1; - } - - if ($p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['start']>$i) { - break; - } - } - } - - // ----- Look for no rule, which means extract all the archive - else { - $v_extract = true; - } - - - // ----- Look for real extraction - if ($v_extract) - { - - // ----- Go to the file position - @rewind($this->_zip_fd); - if (@fseek($this->_zip_fd, $v_header['offset'])) - { - // ----- Close the zip file - $this->_closeFd(); - - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_ARCHIVE_ZIP, 'Invalid archive size'); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Look for extraction as string - if ($p_params[ARCHIVE_ZIP_PARAM_EXTRACT_AS_STRING]) { - - // ----- Extracting the file - if (($v_result = $this->_extractFileAsString($v_header, $v_string)) != 1) - { - // ----- Close the zip file - $this->_closeFd(); - - return $v_result; - } - - // ----- Get the only interesting attributes - if (($v_result = $this->_convertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted])) != 1) - { - // ----- Close the zip file - $this->_closeFd(); - - return $v_result; - } - - // ----- Set the file content - $p_file_list[$v_nb_extracted]['content'] = $v_string; - - // ----- Next extracted file - $v_nb_extracted++; - } - else { - // ----- Extracting the file - if (($v_result = $this->_extractFile($v_header, $p_path, $p_remove_path, $p_remove_all_path, $p_params)) != 1) - { - // ----- Close the zip file - $this->_closeFd(); - - return $v_result; - } - - // ----- Get the only interesting attributes - if (($v_result = $this->_convertHeader2FileInfo($v_header, $p_file_list[$v_nb_extracted++])) != 1) - { - // ----- Close the zip file - $this->_closeFd(); - - return $v_result; - } - } - } - } - - // ----- Close the zip file - $this->_closeFd(); - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _extractFile() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_extractFile() - * - * { Description } - * - */ - function _extractFile(&$p_entry, $p_path, $p_remove_path, $p_remove_all_path, &$p_params) - { - $v_result=1; - - // ----- Read the file header - if (($v_result = $this->_readFileHeader($v_header)) != 1) - { - // ----- Return - return $v_result; - } - - - // ----- Check that the file header is coherent with $p_entry info - // TBC - - // ----- Look for all path to remove - if ($p_remove_all_path == true) { - // ----- Get the basename of the path - $p_entry['filename'] = basename($p_entry['filename']); - } - - // ----- Look for path to remove - else if ($p_remove_path != "") - { - //if (strcmp($p_remove_path, $p_entry['filename'])==0) - if ($this->_tool_PathInclusion($p_remove_path, $p_entry['filename']) == 2) - { - - // ----- Change the file status - $p_entry['status'] = "filtered"; - - // ----- Return - return $v_result; - } - - $p_remove_path_size = strlen($p_remove_path); - if (substr($p_entry['filename'], 0, $p_remove_path_size) == $p_remove_path) - { - - // ----- Remove the path - $p_entry['filename'] = substr($p_entry['filename'], $p_remove_path_size); - - } - } - - // ----- Add the path - if ($p_path != '') - { - $p_entry['filename'] = $p_path."/".$p_entry['filename']; - } - - // ----- Look for pre-extract callback - if ( (isset($p_params[ARCHIVE_ZIP_PARAM_PRE_EXTRACT])) - && ($p_params[ARCHIVE_ZIP_PARAM_PRE_EXTRACT] != '')) { - - // ----- Generate a local information - $v_local_header = array(); - $this->_convertHeader2FileInfo($p_entry, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. - eval('$v_result = '.$p_params[ARCHIVE_ZIP_PARAM_PRE_EXTRACT].'(ARCHIVE_ZIP_PARAM_PRE_EXTRACT, $v_local_header);'); - if ($v_result == 0) { - // ----- Change the file status - $p_entry['status'] = "skipped"; - $v_result = 1; - } - - // ----- Update the informations - // Only some fields can be modified - $p_entry['filename'] = $v_local_header['filename']; - } - - // ----- Trace - - // ----- Look if extraction should be done - if ($p_entry['status'] == 'ok') { - - // ----- Look for specific actions while the file exist - if (file_exists($p_entry['filename'])) - { - - // ----- Look if file is a directory - if (is_dir($p_entry['filename'])) - { - - // ----- Change the file status - $p_entry['status'] = "already_a_directory"; - - // ----- Return - //return $v_result; - } - // ----- Look if file is write protected - else if (!is_writeable($p_entry['filename'])) - { - - // ----- Change the file status - $p_entry['status'] = "write_protected"; - - // ----- Return - //return $v_result; - } - - // ----- Look if the extracted file is older - else if (filemtime($p_entry['filename']) > $p_entry['mtime']) - { - - // ----- Change the file status - $p_entry['status'] = "newer_exist"; - - // ----- Return - //return $v_result; - } - } - - // ----- Check the directory availability and create it if necessary - else { - if ((($p_entry['external']&0x00000010)==0x00000010) || (substr($p_entry['filename'], -1) == '/')) - $v_dir_to_check = $p_entry['filename']; - else if (!strstr($p_entry['filename'], "/")) - $v_dir_to_check = ""; - else - $v_dir_to_check = dirname($p_entry['filename']); - - if (($v_result = $this->_dirCheck($v_dir_to_check, (($p_entry['external']&0x00000010)==0x00000010))) != 1) { - - // ----- Change the file status - $p_entry['status'] = "path_creation_fail"; - - // ----- Return - //return $v_result; - $v_result = 1; - } - } - } - - // ----- Look if extraction should be done - if ($p_entry['status'] == 'ok') { - - // ----- Do the extraction (if not a folder) - if (!(($p_entry['external']&0x00000010)==0x00000010)) - { - - // ----- Look for not compressed file - if ($p_entry['compressed_size'] == $p_entry['size']) - { - - // ----- Opening destination file - if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) - { - - // ----- Change the file status - $p_entry['status'] = "write_error"; - - // ----- Return - return $v_result; - } - - - // ----- Read the file by ARCHIVE_ZIP_READ_BLOCK_SIZE octets blocks - $v_size = $p_entry['compressed_size']; - while ($v_size != 0) - { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = fread($this->_zip_fd, $v_read_size); - $v_binary_data = pack('a'.$v_read_size, $v_buffer); - @fwrite($v_dest_file, $v_binary_data, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Closing the destination file - fclose($v_dest_file); - - // ----- Change the file mtime - touch($p_entry['filename'], $p_entry['mtime']); - } - else - { - // ----- Trace - - // ----- Opening destination file - if (($v_dest_file = @fopen($p_entry['filename'], 'wb')) == 0) { - - // ----- Change the file status - $p_entry['status'] = "write_error"; - - return $v_result; - } - - - // ----- Read the compressed file in a buffer (one shot) - $v_buffer = @fread($this->_zip_fd, $p_entry['compressed_size']); - - // ----- Decompress the file - $v_file_content = gzinflate($v_buffer); - unset($v_buffer); - - // ----- Write the uncompressed data - @fwrite($v_dest_file, $v_file_content, $p_entry['size']); - unset($v_file_content); - - // ----- Closing the destination file - @fclose($v_dest_file); - - // ----- Change the file mtime - touch($p_entry['filename'], $p_entry['mtime']); - } - - // ----- Look for chmod option - if ( (isset($p_params[ARCHIVE_ZIP_PARAM_SET_CHMOD])) - && ($p_params[ARCHIVE_ZIP_PARAM_SET_CHMOD] != 0)) { - - // ----- Change the mode of the file - chmod($p_entry['filename'], $p_params[ARCHIVE_ZIP_PARAM_SET_CHMOD]); - } - - } - } - - // ----- Look for post-extract callback - if ( (isset($p_params[ARCHIVE_ZIP_PARAM_POST_EXTRACT])) - && ($p_params[ARCHIVE_ZIP_PARAM_POST_EXTRACT] != '')) { - - // ----- Generate a local information - $v_local_header = array(); - $this->_convertHeader2FileInfo($p_entry, $v_local_header); - - // ----- Call the callback - // Here I do not use call_user_func() because I need to send a reference to the - // header. - eval('$v_result = '.$p_params[ARCHIVE_ZIP_PARAM_POST_EXTRACT].'(ARCHIVE_ZIP_PARAM_POST_EXTRACT, $v_local_header);'); - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _extractFileAsString() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_extractFileAsString() - * - * { Description } - * - */ - function _extractFileAsString(&$p_entry, &$p_string) - { - $v_result=1; - - // ----- Read the file header - $v_header = array(); - if (($v_result = $this->_readFileHeader($v_header)) != 1) - { - // ----- Return - return $v_result; - } - - - // ----- Check that the file header is coherent with $p_entry info - // TBC - - // ----- Trace - - // ----- Do the extraction (if not a folder) - if (!(($p_entry['external']&0x00000010)==0x00000010)) - { - // ----- Look for not compressed file - if ($p_entry['compressed_size'] == $p_entry['size']) - { - // ----- Trace - - // ----- Reading the file - $p_string = fread($this->_zip_fd, $p_entry['compressed_size']); - } - else - { - // ----- Trace - - // ----- Reading the file - $v_data = fread($this->_zip_fd, $p_entry['compressed_size']); - - // ----- Decompress the file - $p_string = gzinflate($v_data); - } - - // ----- Trace - } - else { - // TBC : error : can not extract a folder in a string - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _readFileHeader() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_readFileHeader() - * - * { Description } - * - */ - function _readFileHeader(&$p_header) - { - $v_result=1; - - // ----- Read the 4 bytes signature - $v_binary_data = @fread($this->_zip_fd, 4); - $v_data = unpack('Vid', $v_binary_data); - - // ----- Check signature - if ($v_data['id'] != 0x04034b50) - { - - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Read the first 42 bytes of the header - $v_binary_data = fread($this->_zip_fd, 26); - - // ----- Look for invalid block size - if (strlen($v_binary_data) != 26) - { - $p_header['filename'] = ""; - $p_header['status'] = "invalid_header"; - - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Extract the values - $v_data = unpack('vversion/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len', $v_binary_data); - - // ----- Get filename - $p_header['filename'] = fread($this->_zip_fd, $v_data['filename_len']); - - // ----- Get extra_fields - if ($v_data['extra_len'] != 0) { - $p_header['extra'] = fread($this->_zip_fd, $v_data['extra_len']); - } - else { - $p_header['extra'] = ''; - } - - // ----- Extract properties - $p_header['compression'] = $v_data['compression']; - $p_header['size'] = $v_data['size']; - $p_header['compressed_size'] = $v_data['compressed_size']; - $p_header['crc'] = $v_data['crc']; - $p_header['flag'] = $v_data['flag']; - - // ----- Recuperate date in UNIX format - $p_header['mdate'] = $v_data['mdate']; - $p_header['mtime'] = $v_data['mtime']; - if ($p_header['mdate'] && $p_header['mtime']) - { - // ----- Extract time - $v_hour = ($p_header['mtime'] & 0xF800) >> 11; - $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; - $v_seconde = ($p_header['mtime'] & 0x001F)*2; - - // ----- Extract date - $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; - $v_month = ($p_header['mdate'] & 0x01E0) >> 5; - $v_day = $p_header['mdate'] & 0x001F; - - // ----- Get UNIX date format - $p_header['mtime'] = mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); - - } - else - { - $p_header['mtime'] = time(); - } - - // ----- Other informations - - // TBC - //for(reset($v_data); $key = key($v_data); next($v_data)) { - //} - - // ----- Set the stored filename - $p_header['stored_filename'] = $p_header['filename']; - - // ----- Set the status field - $p_header['status'] = "ok"; - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _readCentralFileHeader() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_readCentralFileHeader() - * - * { Description } - * - */ - function _readCentralFileHeader(&$p_header) - { - $v_result=1; - - // ----- Read the 4 bytes signature - $v_binary_data = @fread($this->_zip_fd, 4); - $v_data = unpack('Vid', $v_binary_data); - - // ----- Check signature - if ($v_data['id'] != 0x02014b50) - { - - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, 'Invalid archive structure'); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Read the first 42 bytes of the header - $v_binary_data = fread($this->_zip_fd, 42); - - // ----- Look for invalid block size - if (strlen($v_binary_data) != 42) - { - $p_header['filename'] = ""; - $p_header['status'] = "invalid_header"; - - // ----- Error log - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, "Invalid block size : ".strlen($v_binary_data)); - - // ----- Return - return Archive_Zip::errorCode(); - } - - // ----- Extract the values - $p_header = unpack('vversion/vversion_extracted/vflag/vcompression/vmtime/vmdate/Vcrc/Vcompressed_size/Vsize/vfilename_len/vextra_len/vcomment_len/vdisk/vinternal/Vexternal/Voffset', $v_binary_data); - - // ----- Get filename - if ($p_header['filename_len'] != 0) - $p_header['filename'] = fread($this->_zip_fd, $p_header['filename_len']); - else - $p_header['filename'] = ''; - - // ----- Get extra - if ($p_header['extra_len'] != 0) - $p_header['extra'] = fread($this->_zip_fd, $p_header['extra_len']); - else - $p_header['extra'] = ''; - - // ----- Get comment - if ($p_header['comment_len'] != 0) - $p_header['comment'] = fread($this->_zip_fd, $p_header['comment_len']); - else - $p_header['comment'] = ''; - - // ----- Extract properties - - // ----- Recuperate date in UNIX format - if ($p_header['mdate'] && $p_header['mtime']) - { - // ----- Extract time - $v_hour = ($p_header['mtime'] & 0xF800) >> 11; - $v_minute = ($p_header['mtime'] & 0x07E0) >> 5; - $v_seconde = ($p_header['mtime'] & 0x001F)*2; - - // ----- Extract date - $v_year = (($p_header['mdate'] & 0xFE00) >> 9) + 1980; - $v_month = ($p_header['mdate'] & 0x01E0) >> 5; - $v_day = $p_header['mdate'] & 0x001F; - - // ----- Get UNIX date format - $p_header['mtime'] = mktime($v_hour, $v_minute, $v_seconde, $v_month, $v_day, $v_year); - - } - else - { - $p_header['mtime'] = time(); - } - - // ----- Set the stored filename - $p_header['stored_filename'] = $p_header['filename']; - - // ----- Set default status to ok - $p_header['status'] = 'ok'; - - // ----- Look if it is a directory - if (substr($p_header['filename'], -1) == '/') - { - $p_header['external'] = 0x41FF0010; - } - - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _readEndCentralDir() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_readEndCentralDir() - * - * { Description } - * - */ - function _readEndCentralDir(&$p_central_dir) - { - $v_result=1; - - // ----- Go to the end of the zip file - $v_size = filesize($this->_zipname); - @fseek($this->_zip_fd, $v_size); - if (@ftell($this->_zip_fd) != $v_size) { - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, - 'Unable to go to the end of the archive \'' - .$this->_zipname.'\''); - return Archive_Zip::errorCode(); - } - - // ----- First try : look if this is an archive with no commentaries - // (most of the time) - // in this case the end of central dir is at 22 bytes of the file end - $v_found = 0; - if ($v_size > 26) { - @fseek($this->_zip_fd, $v_size-22); - if (($v_pos = @ftell($this->_zip_fd)) != ($v_size-22)) { - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, - 'Unable to seek back to the middle of the archive \'' - .$this->_zipname.'\''); - return Archive_Zip::errorCode(); - } - - // ----- Read for bytes - $v_binary_data = @fread($this->_zip_fd, 4); - $v_data = unpack('Vid', $v_binary_data); - - // ----- Check signature - if ($v_data['id'] == 0x06054b50) { - $v_found = 1; - } - - $v_pos = ftell($this->_zip_fd); - } - - // ----- Go back to the maximum possible size of the Central Dir End Record - if (!$v_found) { - $v_maximum_size = 65557; // 0xFFFF + 22; - if ($v_maximum_size > $v_size) - $v_maximum_size = $v_size; - @fseek($this->_zip_fd, $v_size-$v_maximum_size); - if (@ftell($this->_zip_fd) != ($v_size-$v_maximum_size)) { - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, - 'Unable to seek back to the middle of the archive \'' - .$this->_zipname.'\''); - return Archive_Zip::errorCode(); - } - - // ----- Read byte per byte in order to find the signature - $v_pos = ftell($this->_zip_fd); - $v_bytes = 0x00000000; - while ($v_pos < $v_size) { - // ----- Read a byte - $v_byte = @fread($this->_zip_fd, 1); - - // ----- Add the byte - $v_bytes = ($v_bytes << 8) | Ord($v_byte); - - // ----- Compare the bytes - if ($v_bytes == 0x504b0506) { - $v_pos++; - break; - } - - $v_pos++; - } - - // ----- Look if not found end of central dir - if ($v_pos == $v_size) { - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, - "Unable to find End of Central Dir Record signature"); - return Archive_Zip::errorCode(); - } - } - - // ----- Read the first 18 bytes of the header - $v_binary_data = fread($this->_zip_fd, 18); - - // ----- Look for invalid block size - if (strlen($v_binary_data) != 18) { - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, - "Invalid End of Central Dir Record size : " - .strlen($v_binary_data)); - return Archive_Zip::errorCode(); - } - - // ----- Extract the values - $v_data = unpack('vdisk/vdisk_start/vdisk_entries/ventries/Vsize/Voffset/vcomment_size', $v_binary_data); - - // ----- Check the global size - if (($v_pos + $v_data['comment_size'] + 18) != $v_size) { - $this->_errorLog(ARCHIVE_ZIP_ERR_BAD_FORMAT, - "Fail to find the right signature"); - return Archive_Zip::errorCode(); - } - - // ----- Get comment - if ($v_data['comment_size'] != 0) - $p_central_dir['comment'] = fread($this->_zip_fd, $v_data['comment_size']); - else - $p_central_dir['comment'] = ''; - - $p_central_dir['entries'] = $v_data['entries']; - $p_central_dir['disk_entries'] = $v_data['disk_entries']; - $p_central_dir['offset'] = $v_data['offset']; - $p_central_dir['size'] = $v_data['size']; - $p_central_dir['disk'] = $v_data['disk']; - $p_central_dir['disk_start'] = $v_data['disk_start']; - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _deleteByRule() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_deleteByRule() - * - * { Description } - * - */ - function _deleteByRule(&$p_result_list, &$p_params) - { - $v_result=1; - $v_list_detail = array(); - - // ----- Open the zip file - if (($v_result=$this->_openFd('rb')) != 1) - { - // ----- Return - return $v_result; - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->_readEndCentralDir($v_central_dir)) != 1) - { - $this->_closeFd(); - return $v_result; - } - - // ----- Go to beginning of File - @rewind($this->_zip_fd); - - // ----- Scan all the files - // ----- Start at beginning of Central Dir - $v_pos_entry = $v_central_dir['offset']; - @rewind($this->_zip_fd); - if (@fseek($this->_zip_fd, $v_pos_entry)) { - // ----- Clean - $this->_closeFd(); - - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_ARCHIVE_ZIP, - 'Invalid archive size'); - return Archive_Zip::errorCode(); - } - - // ----- Read each entry - $v_header_list = array(); - $j_start = 0; - for ($i=0, $v_nb_extracted=0; $i<$v_central_dir['entries']; $i++) { - - // ----- Read the file header - $v_header_list[$v_nb_extracted] = array(); - $v_result - = $this->_readCentralFileHeader($v_header_list[$v_nb_extracted]); - if ($v_result != 1) { - // ----- Clean - $this->_closeFd(); - - return $v_result; - } - - // ----- Store the index - $v_header_list[$v_nb_extracted]['index'] = $i; - - // ----- Look for the specific extract rules - $v_found = false; - - // ----- Look for extract by name rule - if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_NAME])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_NAME] != 0)) { - - // ----- Look if the filename is in the list - for ($j=0; - ($j strlen($p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j])) - && (substr($v_header_list[$v_nb_extracted]['stored_filename'], 0, strlen($p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j])) == $p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j])) { - $v_found = true; - } - elseif ( (($v_header_list[$v_nb_extracted]['external']&0x00000010)==0x00000010) /* Indicates a folder */ - && ($v_header_list[$v_nb_extracted]['stored_filename'].'/' == $p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j])) { - $v_found = true; - } - } - // ----- Look for a filename - elseif ($v_header_list[$v_nb_extracted]['stored_filename'] - == $p_params[ARCHIVE_ZIP_PARAM_BY_NAME][$j]) { - $v_found = true; - } - } - } - - // ----- Look for extract by ereg rule - else if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_EREG])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_EREG] != "")) { - - if (ereg($p_params[ARCHIVE_ZIP_PARAM_BY_EREG], - $v_header_list[$v_nb_extracted]['stored_filename'])) { - $v_found = true; - } - } - - // ----- Look for extract by preg rule - else if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_PREG])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_PREG] != "")) { - - if (preg_match($p_params[ARCHIVE_ZIP_PARAM_BY_PREG], - $v_header_list[$v_nb_extracted]['stored_filename'])) { - $v_found = true; - } - } - - // ----- Look for extract by index rule - else if ( (isset($p_params[ARCHIVE_ZIP_PARAM_BY_INDEX])) - && ($p_params[ARCHIVE_ZIP_PARAM_BY_INDEX] != 0)) { - - // ----- Look if the index is in the list - for ($j=$j_start; - ($j=$p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['start']) - && ($i<=$p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['end'])) { - $v_found = true; - } - if ($i>=$p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['end']) { - $j_start = $j+1; - } - - if ($p_params[ARCHIVE_ZIP_PARAM_BY_INDEX][$j]['start']>$i) { - break; - } - } - } - - // ----- Look for deletion - if ($v_found) { - unset($v_header_list[$v_nb_extracted]); - } - else { - $v_nb_extracted++; - } - } - - // ----- Look if something need to be deleted - if ($v_nb_extracted > 0) { - - // ----- Creates a temporay file - $v_zip_temp_name = ARCHIVE_ZIP_TEMPORARY_DIR.uniqid('archive_zip-') - .'.tmp'; - - // ----- Creates a temporary zip archive - $v_temp_zip = new Archive_Zip($v_zip_temp_name); - - // ----- Open the temporary zip file in write mode - if (($v_result = $v_temp_zip->_openFd('wb')) != 1) { - $this->_closeFd(); - - // ----- Return - return $v_result; - } - - // ----- Look which file need to be kept - for ($i=0; $i_zip_fd); - if (@fseek($this->_zip_fd, $v_header_list[$i]['offset'])) { - // ----- Clean - $this->_closeFd(); - $v_temp_zip->_closeFd(); - @unlink($v_zip_temp_name); - - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_ARCHIVE_ZIP, - 'Invalid archive size'); - return Archive_Zip::errorCode(); - } - - // ----- Read the file header - if (($v_result = $this->_readFileHeader($v_header_list[$i])) != 1) { - // ----- Clean - $this->_closeFd(); - $v_temp_zip->_closeFd(); - @unlink($v_zip_temp_name); - - return $v_result; - } - - // ----- Write the file header - $v_result = $v_temp_zip->_writeFileHeader($v_header_list[$i]); - if ($v_result != 1) { - // ----- Clean - $this->_closeFd(); - $v_temp_zip->_closeFd(); - @unlink($v_zip_temp_name); - - return $v_result; - } - - // ----- Read/write the data block - $v_result = $this->_tool_CopyBlock($this->_zip_fd, - $v_temp_zip->_zip_fd, - $v_header_list[$i]['compressed_size']); - if ($v_result != 1) { - // ----- Clean - $this->_closeFd(); - $v_temp_zip->_closeFd(); - @unlink($v_zip_temp_name); - - return $v_result; - } - } - - // ----- Store the offset of the central dir - $v_offset = @ftell($v_temp_zip->_zip_fd); - - // ----- Re-Create the Central Dir files header - for ($i=0; $i_writeCentralFileHeader($v_header_list[$i]); - if ($v_result != 1) { - // ----- Clean - $v_temp_zip->_closeFd(); - $this->_closeFd(); - @unlink($v_zip_temp_name); - - return $v_result; - } - - // ----- Transform the header to a 'usable' info - $v_temp_zip->_convertHeader2FileInfo($v_header_list[$i], - $p_result_list[$i]); - } - - - // ----- Zip file comment - $v_comment = ''; - - // ----- Calculate the size of the central header - $v_size = @ftell($v_temp_zip->_zip_fd)-$v_offset; - - // ----- Create the central dir footer - $v_result = $v_temp_zip->_writeCentralHeader(sizeof($v_header_list), - $v_size, $v_offset, - $v_comment); - if ($v_result != 1) { - // ----- Clean - unset($v_header_list); - $v_temp_zip->_closeFd(); - $this->_closeFd(); - @unlink($v_zip_temp_name); - - return $v_result; - } - - // ----- Close - $v_temp_zip->_closeFd(); - $this->_closeFd(); - - // ----- Delete the zip file - // TBC : I should test the result ... - @unlink($this->_zipname); - - // ----- Rename the temporary file - // TBC : I should test the result ... - //@rename($v_zip_temp_name, $this->_zipname); - $this->_tool_Rename($v_zip_temp_name, $this->_zipname); - - // ----- Destroy the temporary archive - unset($v_temp_zip); - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _dirCheck() - // Description : - // Check if a directory exists, if not it creates it and all the parents directory - // which may be useful. - // Parameters : - // $p_dir : Directory path to check. - // Return Values : - // 1 : OK - // -1 : Unable to create directory - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_dirCheck() - * - * { Description } - * - * @param [type] $p_is_dir - */ - function _dirCheck($p_dir, $p_is_dir=false) - { - $v_result = 1; - - // ----- Remove the final '/' - if (($p_is_dir) && (substr($p_dir, -1)=='/')) { - $p_dir = substr($p_dir, 0, strlen($p_dir)-1); - } - - // ----- Check the directory availability - if ((is_dir($p_dir)) || ($p_dir == "")) { - return 1; - } - - // ----- Extract parent directory - $p_parent_dir = dirname($p_dir); - - // ----- Just a check - if ($p_parent_dir != $p_dir) { - // ----- Look for parent directory - if ($p_parent_dir != "") { - if (($v_result = $this->_dirCheck($p_parent_dir)) != 1) { - return $v_result; - } - } - } - - // ----- Create the directory - if (!@mkdir($p_dir, 0777)) { - $this->_errorLog(ARCHIVE_ZIP_ERR_DIR_CREATE_FAIL, - "Unable to create directory '$p_dir'"); - return Archive_Zip::errorCode(); - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _merge() - // Description : - // If $p_archive_to_add does not exist, the function exit with a success result. - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_merge() - * - * { Description } - * - */ - function _merge(&$p_archive_to_add) - { - $v_result=1; - - // ----- Look if the archive_to_add exists - if (!is_file($p_archive_to_add->_zipname)) { - // ----- Nothing to merge, so merge is a success - return 1; - } - - // ----- Look if the archive exists - if (!is_file($this->_zipname)) { - // ----- Do a duplicate - $v_result = $this->_duplicate($p_archive_to_add->_zipname); - - return $v_result; - } - - // ----- Open the zip file - if (($v_result=$this->_openFd('rb')) != 1) { - return $v_result; - } - - // ----- Read the central directory informations - $v_central_dir = array(); - if (($v_result = $this->_readEndCentralDir($v_central_dir)) != 1) { - $this->_closeFd(); - return $v_result; - } - - // ----- Go to beginning of File - @rewind($this->_zip_fd); - - // ----- Open the archive_to_add file - if (($v_result=$p_archive_to_add->_openFd('rb')) != 1) { - $this->_closeFd(); - return $v_result; - } - - // ----- Read the central directory informations - $v_central_dir_to_add = array(); - $v_result = $p_archive_to_add->_readEndCentralDir($v_central_dir_to_add); - if ($v_result != 1) { - $this->_closeFd(); - $p_archive_to_add->_closeFd(); - return $v_result; - } - - // ----- Go to beginning of File - @rewind($p_archive_to_add->_zip_fd); - - // ----- Creates a temporay file - $v_zip_temp_name = ARCHIVE_ZIP_TEMPORARY_DIR.uniqid('archive_zip-').'.tmp'; - - // ----- Open the temporary file in write mode - if (($v_zip_temp_fd = @fopen($v_zip_temp_name, 'wb')) == 0) { - $this->_closeFd(); - $p_archive_to_add->_closeFd(); - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, - 'Unable to open temporary file \'' - .$v_zip_temp_name.'\' in binary write mode'); - return Archive_Zip::errorCode(); - } - - // ----- Copy the files from the archive to the temporary file - // TBC : Here I should better append the file and go back to erase the - // central dir - $v_size = $v_central_dir['offset']; - while ($v_size != 0) { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = fread($this->_zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Copy the files from the archive_to_add into the temporary file - $v_size = $v_central_dir_to_add['offset']; - while ($v_size != 0) { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = fread($p_archive_to_add->_zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Store the offset of the central dir - $v_offset = @ftell($v_zip_temp_fd); - - // ----- Copy the block of file headers from the old archive - $v_size = $v_central_dir['size']; - while ($v_size != 0) { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($this->_zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Copy the block of file headers from the archive_to_add - $v_size = $v_central_dir_to_add['size']; - while ($v_size != 0) { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($p_archive_to_add->_zip_fd, $v_read_size); - @fwrite($v_zip_temp_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Zip file comment - // TBC : I should merge the two comments - $v_comment = ''; - - // ----- Calculate the size of the (new) central header - $v_size = @ftell($v_zip_temp_fd)-$v_offset; - - // ----- Swap the file descriptor - // Here is a trick : I swap the temporary fd with the zip fd, in order to use - // the following methods on the temporary fil and not the real archive fd - $v_swap = $this->_zip_fd; - $this->_zip_fd = $v_zip_temp_fd; - $v_zip_temp_fd = $v_swap; - - // ----- Create the central dir footer - if (($v_result = $this->_writeCentralHeader($v_central_dir['entries'] - +$v_central_dir_to_add['entries'], - $v_size, $v_offset, - $v_comment)) != 1) { - $this->_closeFd(); - $p_archive_to_add->_closeFd(); - @fclose($v_zip_temp_fd); - $this->_zip_fd = null; - - // ----- Reset the file list - unset($v_header_list); - - // ----- Return - return $v_result; - } - - // ----- Swap back the file descriptor - $v_swap = $this->_zip_fd; - $this->_zip_fd = $v_zip_temp_fd; - $v_zip_temp_fd = $v_swap; - - // ----- Close - $this->_closeFd(); - $p_archive_to_add->_closeFd(); - - // ----- Close the temporary file - @fclose($v_zip_temp_fd); - - // ----- Delete the zip file - // TBC : I should test the result ... - @unlink($this->_zipname); - - // ----- Rename the temporary file - // TBC : I should test the result ... - //@rename($v_zip_temp_name, $this->_zipname); - $this->_tool_Rename($v_zip_temp_name, $this->_zipname); - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _duplicate() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_duplicate() - * - * { Description } - * - */ - function _duplicate($p_archive_filename) - { - $v_result=1; - - // ----- Look if the $p_archive_filename exists - if (!is_file($p_archive_filename)) { - - // ----- Nothing to duplicate, so duplicate is a success. - $v_result = 1; - - // ----- Return - return $v_result; - } - - // ----- Open the zip file - if (($v_result=$this->_openFd('wb')) != 1) { - // ----- Return - return $v_result; - } - - // ----- Open the temporary file in write mode - if (($v_zip_temp_fd = @fopen($p_archive_filename, 'rb')) == 0) { - $this->_closeFd(); - $this->_errorLog(ARCHIVE_ZIP_ERR_READ_OPEN_FAIL, - 'Unable to open archive file \'' - .$p_archive_filename.'\' in binary write mode'); - return Archive_Zip::errorCode(); - } - - // ----- Copy the files from the archive to the temporary file - // TBC : Here I should better append the file and go back to erase the - // central dir - $v_size = filesize($p_archive_filename); - while ($v_size != 0) { - $v_read_size = ($v_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $v_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = fread($v_zip_temp_fd, $v_read_size); - @fwrite($this->_zip_fd, $v_buffer, $v_read_size); - $v_size -= $v_read_size; - } - - // ----- Close - $this->_closeFd(); - - // ----- Close the temporary file - @fclose($v_zip_temp_fd); - - return $v_result; - } - // --------------------------------------------------------------------------- - - /** - * Archive_Zip::_check_parameters() - * - * { Description } - * - * @param integer $p_error_code - * @param string $p_error_string - */ - function _check_parameters(&$p_params, $p_default) - { - - // ----- Check that param is an array - if (!is_array($p_params)) { - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, - 'Unsupported parameter, waiting for an array'); - return Archive_Zip::errorCode(); - } - - // ----- Check that all the params are valid - for (reset($p_params); list($v_key, $v_value) = each($p_params); ) { - if (!isset($p_default[$v_key])) { - $this->_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAMETER, - 'Unsupported parameter with key \''.$v_key.'\''); - - return Archive_Zip::errorCode(); - } - } - - // ----- Set the default values - for (reset($p_default); list($v_key, $v_value) = each($p_default); ) { - if (!isset($p_params[$v_key])) { - $p_params[$v_key] = $p_default[$v_key]; - } - } - - // ----- Check specific parameters - $v_callback_list = array ('callback_pre_add','callback_post_add', - 'callback_pre_extract','callback_post_extract'); - for ($i=0; $i_errorLog(ARCHIVE_ZIP_ERR_INVALID_PARAM_VALUE, - "Callback '".$p_params[$v_key] - ."()' is not an existing function for " - ."parameter '".$v_key."'"); - return Archive_Zip::errorCode(); - } - } - } - - return(1); - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _errorLog() - // Description : - // Parameters : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_errorLog() - * - * { Description } - * - * @param integer $p_error_code - * @param string $p_error_string - */ - function _errorLog($p_error_code=0, $p_error_string='') - { - $this->_error_code = $p_error_code; - $this->_error_string = $p_error_string; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : _errorReset() - // Description : - // Parameters : - // --------------------------------------------------------------------------- - /** - * Archive_Zip::_errorReset() - * - * { Description } - * - */ - function _errorReset() - { - $this->_error_code = 1; - $this->_error_string = ''; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : $this->_tool_PathReduction() - // Description : - // Parameters : - // Return Values : - // --------------------------------------------------------------------------- - /** - * _tool_PathReduction() - * - * { Description } - * - */ - function _tool_PathReduction($p_dir) - { - $v_result = ""; - - // ----- Look for not empty path - if ($p_dir != "") - { - // ----- Explode path by directory names - $v_list = explode("/", $p_dir); - - // ----- Study directories from last to first - for ($i=sizeof($v_list)-1; $i>=0; $i--) - { - // ----- Look for current path - if ($v_list[$i] == ".") - { - // ----- Ignore this directory - // Should be the first $i=0, but no check is done - } - else if ($v_list[$i] == "..") - { - // ----- Ignore it and ignore the $i-1 - $i--; - } - else if (($v_list[$i] == "") && ($i!=(sizeof($v_list)-1)) && ($i!=0)) - { - // ----- Ignore only the double '//' in path, - // but not the first and last '/' - } - else - { - $v_result = $v_list[$i].($i!=(sizeof($v_list)-1)?"/".$v_result:""); - } - } - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : $this->_tool_PathInclusion() - // Description : - // This function indicates if the path $p_path is under the $p_dir tree. Or, - // said in an other way, if the file or sub-dir $p_path is inside the dir - // $p_dir. - // The function indicates also if the path is exactly the same as the dir. - // This function supports path with duplicated '/' like '//', but does not - // support '.' or '..' statements. - // Parameters : - // Return Values : - // 0 if $p_path is not inside directory $p_dir - // 1 if $p_path is inside directory $p_dir - // 2 if $p_path is exactly the same as $p_dir - // --------------------------------------------------------------------------- - /** - * _tool_PathInclusion() - * - * { Description } - * - */ - function _tool_PathInclusion($p_dir, $p_path) - { - $v_result = 1; - - // ----- Explode dir and path by directory separator - $v_list_dir = explode("/", $p_dir); - $v_list_dir_size = sizeof($v_list_dir); - $v_list_path = explode("/", $p_path); - $v_list_path_size = sizeof($v_list_path); - - // ----- Study directories paths - $i = 0; - $j = 0; - while (($i < $v_list_dir_size) && ($j < $v_list_path_size) && ($v_result)) { - - // ----- Look for empty dir (path reduction) - if ($v_list_dir[$i] == '') { - $i++; - continue; - } - if ($v_list_path[$j] == '') { - $j++; - continue; - } - - // ----- Compare the items - if ( ($v_list_dir[$i] != $v_list_path[$j]) - && ($v_list_dir[$i] != '') - && ( $v_list_path[$j] != '')) { - $v_result = 0; - } - - // ----- Next items - $i++; - $j++; - } - - // ----- Look if everything seems to be the same - if ($v_result) { - // ----- Skip all the empty items - while (($j < $v_list_path_size) && ($v_list_path[$j] == '')) $j++; - while (($i < $v_list_dir_size) && ($v_list_dir[$i] == '')) $i++; - - if (($i >= $v_list_dir_size) && ($j >= $v_list_path_size)) { - // ----- There are exactly the same - $v_result = 2; - } - else if ($i < $v_list_dir_size) { - // ----- The path is shorter than the dir - $v_result = 0; - } - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : $this->_tool_CopyBlock() - // Description : - // Parameters : - // $p_mode : read/write compression mode - // 0 : src & dest normal - // 1 : src gzip, dest normal - // 2 : src normal, dest gzip - // 3 : src & dest gzip - // Return Values : - // --------------------------------------------------------------------------- - /** - * _tool_CopyBlock() - * - * { Description } - * - * @param integer $p_mode - */ - function _tool_CopyBlock($p_src, $p_dest, $p_size, $p_mode=0) - { - $v_result = 1; - - if ($p_mode==0) - { - while ($p_size != 0) - { - $v_read_size = ($p_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $p_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($p_src, $v_read_size); - @fwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } - } - else if ($p_mode==1) - { - while ($p_size != 0) - { - $v_read_size = ($p_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $p_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = @gzread($p_src, $v_read_size); - @fwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } - } - else if ($p_mode==2) - { - while ($p_size != 0) - { - $v_read_size = ($p_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $p_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = @fread($p_src, $v_read_size); - @gzwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } - } - else if ($p_mode==3) - { - while ($p_size != 0) - { - $v_read_size = ($p_size < ARCHIVE_ZIP_READ_BLOCK_SIZE - ? $p_size : ARCHIVE_ZIP_READ_BLOCK_SIZE); - $v_buffer = @gzread($p_src, $v_read_size); - @gzwrite($p_dest, $v_buffer, $v_read_size); - $p_size -= $v_read_size; - } - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : $this->_tool_Rename() - // Description : - // This function tries to do a simple rename() function. If it fails, it - // tries to copy the $p_src file in a new $p_dest file and then unlink the - // first one. - // Parameters : - // $p_src : Old filename - // $p_dest : New filename - // Return Values : - // 1 on success, 0 on failure. - // --------------------------------------------------------------------------- - /** - * _tool_Rename() - * - * { Description } - * - */ - function _tool_Rename($p_src, $p_dest) - { - $v_result = 1; - - // ----- Try to rename the files - if (!@rename($p_src, $p_dest)) { - - // ----- Try to copy & unlink the src - if (!@copy($p_src, $p_dest)) { - $v_result = 0; - } - else if (!@unlink($p_src)) { - $v_result = 0; - } - } - - // ----- Return - return $v_result; - } - // --------------------------------------------------------------------------- - - // --------------------------------------------------------------------------- - // Function : $this->_tool_TranslateWinPath() - // Description : - // Translate windows path by replacing '\' by '/' and optionally removing - // drive letter. - // Parameters : - // $p_path : path to translate. - // $p_remove_disk_letter : true | false - // Return Values : - // The path translated. - // --------------------------------------------------------------------------- - /** - * _tool_TranslateWinPath() - * - * { Description } - * - * @param [type] $p_remove_disk_letter - */ - function _tool_TranslateWinPath($p_path, $p_remove_disk_letter=true) - { - if (stristr(php_uname(), 'windows')) { - // ----- Look for potential disk letter - if ( ($p_remove_disk_letter) - && (($v_position = strpos($p_path, ':')) != false)) { - $p_path = substr($p_path, $v_position+1); - } - // ----- Change potential windows directory separator - if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0,1) == '\\')) { - $p_path = strtr($p_path, '\\', '/'); - } - } - return $p_path; - } - // --------------------------------------------------------------------------- - - public function encryptCrc32($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::encryptCrc32($string); - } - - } - // End of class - -?> diff --git a/gulliver/thirdparty/pear/Benchmark/Iterate.php b/gulliver/thirdparty/pear/Benchmark/Iterate.php deleted file mode 100644 index 159b43416..000000000 --- a/gulliver/thirdparty/pear/Benchmark/Iterate.php +++ /dev/null @@ -1,167 +0,0 @@ -. | -// +------------------------------------------------------------------------+ -// | This source file is subject to the New BSD license, That is bundled | -// | with this package in the file LICENSE, and is available through | -// | the world-wide-web at | -// | http://www.opensource.org/licenses/bsd-license.php | -// | If you did not receive a copy of the new BSDlicense 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. | -// +------------------------------------------------------------------------+ -// -// $Id: Iterate.php,v 1.1 2007/05/24 05:17:56 anant Exp $ -// - -require_once 'Benchmark/Timer.php'; - -/** - * Provides timing and profiling information. - * - * Example 1 - * - * - * '; - * } - * - * $benchmark->run(100, 'foo', 'test'); - * $result = $benchmark->get(); - * ?> - * - * - * Example 2 - * - * - * '; - * } - * } - * - * $benchmark->run(100, 'myclass::foo', 'test'); - * $result = $benchmark->get(); - * ?> - * - * - * Example 3 - * - * - * '; - * } - * } - * - * $o = new MyClass(); - * - * $benchmark->run(100, 'o->foo', 'test'); - * $result = $benchmark->get(); - * ?> - * - * - * @author Sebastian Bergmann - * @copyright Copyright © 2002-2005 Sebastian Bergmann - * @license http://www.php.net/license/3_0.txt The PHP License, Version 3.0 - * @category Benchmarking - * @package Benchmark - */ -class Benchmark_Iterate extends Benchmark_Timer { - /** - * Benchmarks a function or method. - * - * @access public - */ - function run() { - $arguments = func_get_args(); - $iterations = array_shift($arguments); - $function_name = array_shift($arguments); - - if (strstr($function_name, '::')) { - $function_name = explode('::', $function_name); - $objectmethod = $function_name[1]; - } - - if (strstr($function_name, '->')) { - $function_name = explode('->', $function_name); - $objectname = $function_name[0]; - - $object = $GLOBALS[$objectname]; - $objectmethod = $function_name[1]; - - for ($i = 1; $i <= $iterations; $i++) { - $this->setMarker('start_' . $i); - call_user_func_array(array($object, $function_name[1]), $arguments); - $this->setMarker('end_' . $i); - } - - return(0); - } - - for ($i = 1; $i <= $iterations; $i++) { - $this->setMarker('start_' . $i); - call_user_func_array($function_name, $arguments); - $this->setMarker('end_' . $i); - } - } - - /** - * Returns benchmark result. - * - * $result[x ] = execution time of iteration x - * $result['mean' ] = mean execution time - * $result['iterations'] = number of iterations - * - * @return array - * @access public - */ - function get($simple_output = false) { - $result = array(); - $total = 0; - - $iterations = count($this->markers)/2; - - for ($i = 1; $i <= $iterations; $i++) { - $time = $this->timeElapsed('start_'.$i , 'end_'.$i); - - if (extension_loaded('bcmath')) { - $total = bcadd($total, $time, 6); - } else { - $total = $total + $time; - } - - if (!$simple_output) { - $result[$i] = $time; - } - } - - if (extension_loaded('bcmath')) { - $result['mean'] = bcdiv($total, $iterations, 6); - } else { - $result['mean'] = $total / $iterations; - } - - $result['iterations'] = $iterations; - - return $result; - } -} diff --git a/gulliver/thirdparty/pear/Benchmark/Profiler.php b/gulliver/thirdparty/pear/Benchmark/Profiler.php deleted file mode 100644 index a91b34477..000000000 --- a/gulliver/thirdparty/pear/Benchmark/Profiler.php +++ /dev/null @@ -1,447 +0,0 @@ -. | -// +----------------------------------------------------------------------+ -// | This source file is subject to the New BSD license, That is bundled | -// | with this package in the file LICENSE, and is available through | -// | the world-wide-web at | -// | http://www.opensource.org/licenses/bsd-license.php | -// | If you did not receive a copy of the new BSDlicense 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. | -// +----------------------------------------------------------------------+ -// -// $Id: Profiler.php,v 1.2 2007/05/24 05:23:20 anant Exp $ -// - -require_once 'PEAR.php'; - -/** - * Provides timing and profiling information. - * - * Example 1: Automatic profiling start, stop, and output. - * - * - * enterSection('myFunction'); - * //do something - * $profiler->leaveSection('myFunction'); - * return; - * } - * - * //do something - * myFunction(); - * //do more - * ?> - * - * - * Example 2: Manual profiling start, stop, and output. - * - * - * enterSection('myFunction'); - * //do something - * $profiler->leaveSection('myFunction'); - * return; - * } - * - * $profiler->start(); - * //do something - * myFunction(); - * //do more - * $profiler->stop(); - * $profiler->display(); - * ?> - * - * - * @author Matthias Englert - * @copyright Copyright © 2002-2005 Matthias Englert - * @license http://www.php.net/license/3_0.txt The PHP License, Version 3.0 - * @category Benchmarking - * @package Benchmark - * @since 1.2.0 - */ -class Benchmark_Profiler extends PEAR { - /** - * Contains the total ex. time of each section - * - * @var array - * @access private - */ - var $_sections = array(); - - /** - * Calling stack - * - * @var array - * @access private - */ - var $_stack = array(); - - /** - * Notes how often a section was entered - * - * @var array - * @access private - */ - var $_numberOfCalls = array(); - - /** - * Notes for each section how much time is spend in sub-sections - * - * @var array - * @access private - */ - var $_subSectionsTime = array(); - - /** - * Notes for each section how often it calls which section - * - * @var array - * @access private - */ - var $_calls = array(); - - /** - * Notes for each section how often it was called by which section - * - * @var array - * @access private - */ - var $_callers = array(); - - /** - * Auto-starts and stops profiler - * - * @var boolean - * @access private - */ - var $_auto = FALSE; - - /** - * Max marker name length for non-html output - * - * @var integer - * @access private - */ - var $_maxStringLength = 0; - - /** - * Constructor, starts profiling recording - * - * @access public - */ - function Benchmark_Profiler($auto = FALSE) { - $this->_auto = $auto; - - if ($this->_auto) { - $this->start(); - } - - $this->PEAR(); - } - - /** - * Close method, stop profiling recording and display output. - * - * @access public - */ - function close() { - if (isset($this->_auto) && $this->_auto) { - $this->stop(); - $this->display(); - } - } - - /** - * Returns profiling informations for a given section. - * - * @param string $section - * @return array - * @access public - */ - function getSectionInformations($section = 'Global') { - if (isset($this->_sections[$section])) { - $calls = array(); - - if (isset($this->_calls[$section])) { - $calls = $this->_calls[$section]; - } - - $callers = array(); - - if (isset($this->_callers[$section])) { - $callers = $this->_callers[$section]; - } - - $informations = array(); - - $informations['time'] = $this->_sections[$section]; - if (isset($this->_sections['Global'])) { - $informations['percentage'] = number_format(100 * $this->_sections[$section] / $this->_sections['Global'], 2, '.', ''); - } else { - $informations['percentage'] = 'N/A'; - } - $informations['calls'] = $calls; - $informations['num_calls'] = $this->_numberOfCalls[$section]; - $informations['callers'] = $callers; - - if (isset($this->_subSectionsTime[$section])) { - $informations['netto_time'] = $this->_sections[$section] - $this->_subSectionsTime[$section]; - } else { - $informations['netto_time'] = $this->_sections[$section]; - } - - return $informations; - } else { - $this->raiseError("The section '$section' does not exists.\n", NULL, PEAR_ERROR_TRIGGER, E_USER_WARNING); - } - } - - /** - * Returns profiling informations for all sections. - * - * @return array - * @access public - */ - function getAllSectionsInformations() { - $informations = array(); - - foreach($this->_sections as $section => $time) { - $informations[$section] = $this->getSectionInformations($section); - } - - return $informations; - } - - /** - * Returns formatted profiling information. - * - * @param string output format (auto, plain or html), default auto - * @see display() - * @access private - */ - function _getOutput($format) { - - /* Quickly find out the maximun length: Ineffecient, but will do for now! */ - $informations = $this->getAllSectionsInformations(); - $names = array_keys($informations); - - $maxLength = 0; - foreach ($names as $name) - { - if ($maxLength < strlen($name)) { - $maxLength = strlen($name); - } - } - $this->_maxStringLength = $maxLength; - - if ($format == 'auto') { - if (function_exists('version_compare') && - version_compare(phpversion(), '4.1', 'ge')) { - $format = isset($_SERVER['SERVER_PROTOCOL']) ? 'html' : 'plain'; - } else { - global $HTTP_SERVER_VARS; - $format = isset($HTTP_SERVER_VARS['SERVER_PROTOCOL']) ? 'html' : 'plain'; - } - } - - if ($format == 'html') { - $out = ''."\n"; - $out .= - ''. - ''. - ''. - ''. - "\n"; - } else { - $dashes = $out = str_pad("\n", ($this->_maxStringLength + 75), '-', STR_PAD_LEFT); - $out .= str_pad('Section', $this->_maxStringLength + 10); - $out .= str_pad("Total Ex Time", 22); - $out .= str_pad("Netto Ex Time", 22); - $out .= str_pad("#Calls", 10); - $out .= "Percentage\n"; - $out .= $dashes; - } - - foreach($informations as $name => $values) { - $percentage = $values['percentage']; - $calls_str = ""; - - foreach($values['calls'] as $key => $val) { - if ($calls_str) { - $calls_str .= ", "; - } - - $calls_str .= "$key ($val)"; - } - - $callers_str = ""; - - foreach($values['callers'] as $key => $val) { - if ($callers_str) { - $callers_str .= ", "; - } - - $callers_str .= "$key ($val)"; - } - - if ($format == 'html') { - $out .= ""; - if (is_numeric($values['percentage'])) { - $out .= "\n"; - } else { - $out .= "\n"; - } - $out .= ""; - } else { - $out .= str_pad($name, $this->_maxStringLength + 10); - $out .= str_pad($values['time'], 22); - $out .= str_pad($values['netto_time'], 22); - $out .= str_pad($values['num_calls'], 10); - if (is_numeric($values['percentage'])) { - $out .= str_pad($values['percentage']."%\n", 8, ' ', STR_PAD_LEFT); - } else { - $out .= str_pad($values['percentage']."\n", 8, ' ', STR_PAD_LEFT); - } - } - } - - if ($format == 'html') { - return $out . '
 total ex. timenetto ex. time#calls%callscallers
$name{$values['time']}{$values['netto_time']}{$values['num_calls']}{$values['percentage']}%{$values['percentage']}$calls_str$callers_str
'; - } else { - return $out; - } - } - - /** - * Returns formatted profiling information. - * - * @param string output format (auto, plain or html), default auto - * @access public - */ - function display($format = 'auto') { - echo $this->_getOutput($format); - } - - /** - * Enters "Global" section. - * - * @see enterSection(), stop() - * @access public - */ - function start() { - $this->enterSection('Global'); - } - - /** - * Leaves "Global" section. - * - * @see leaveSection(), start() - * @access public - */ - function stop() { - $this->leaveSection('Global'); - } - - /** - * Enters code section. - * - * @param string name of the code section - * @see start(), leaveSection() - * @access public - */ - function enterSection($name) { - if (count($this->_stack)) { - if (isset($this->_callers[$name][$this->_stack[count($this->_stack) - 1]["name"]])) { - $this->_callers[$name][$this->_stack[count($this->_stack) - 1]["name"]]++; - } else { - $this->_callers[$name][$this->_stack[count($this->_stack) - 1]["name"]] = 1; - } - - if (isset($this->_calls[$this->_stack[count($this->_stack) - 1]["name"]][$name])) { - $this->_calls[$this->_stack[count($this->_stack) - 1]["name"]][$name]++; - } else { - $this->_calls[$this->_stack[count($this->_stack) - 1]["name"]][$name] = 1; - } - } else { - if ($name != 'Global') { - $this->raiseError("tried to enter section ".$name." but profiling was not started\n", NULL, PEAR_ERROR_DIE); - } - } - - if (isset($this->_numberOfCalls[$name])) { - $this->_numberOfCalls[$name]++; - } else { - $this->_numberOfCalls[$name] = 1; - } - - array_push($this->_stack, array("name" => $name, "time" => $this->_getMicrotime())); - } - - /** - * Leaves code section. - * - * @param string name of the marker to be set - * @see stop(), enterSection() - * @access public - */ - function leaveSection($name) { - $microtime = $this->_getMicrotime(); - - if (!count($this->_stack)) { - $this->raiseError("tried to leave section ".$name." but profiling was not started\n", NULL, PEAR_ERROR_DIE); - } - - $x = array_pop($this->_stack); - - if ($x["name"] != $name) { - $this->raiseError("reached end of section $name but expecting end of " . $x["name"]."\n", NULL, PEAR_ERROR_DIE); - } - - if (isset($this->_sections[$name])) { - $this->_sections[$name] += $microtime - $x["time"]; - } else { - $this->_sections[$name] = $microtime - $x["time"]; - } - - $parent = array_pop($this->_stack); - - if (isset($parent)) { - if (isset($this->_subSectionsTime[$parent['name']])) { - $this->_subSectionsTime[$parent['name']] += $microtime - $x['time']; - } else { - $this->_subSectionsTime[$parent['name']] = $microtime - $x['time']; - } - - array_push($this->_stack, $parent); - } - } - - /** - * Wrapper for microtime(). - * - * @return float - * @access private - * @since 1.3.0 - */ - function _getMicrotime() { - $microtime = explode(' ', microtime()); - return $microtime[1] . substr($microtime[0], 1); - } -} diff --git a/gulliver/thirdparty/pear/Benchmark/Timer.php b/gulliver/thirdparty/pear/Benchmark/Timer.php deleted file mode 100644 index 093f46129..000000000 --- a/gulliver/thirdparty/pear/Benchmark/Timer.php +++ /dev/null @@ -1,321 +0,0 @@ -. | -// +------------------------------------------------------------------------+ -// | This source file is subject to the New BSD license, That is bundled | -// | with this package in the file LICENSE, and is available through | -// | the world-wide-web at | -// | http://www.opensource.org/licenses/bsd-license.php | -// | If you did not receive a copy of the new BSDlicense 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. | -// +------------------------------------------------------------------------+ -// -// $Id: Timer.php,v 1.2 2007/05/24 05:23:20 anant Exp $ -// - -require_once 'PEAR.php'; - -/** - * Provides timing and profiling information. - * - * Example 1: Automatic profiling start, stop, and output. - * - * - * setMarker('Marker 1'); - * ?> - * - * - * Example 2: Manual profiling start, stop, and output. - * - * - * start(); - * $timer->setMarker('Marker 1'); - * $timer->stop(); - * - * $timer->display(); // to output html formated - * // AND/OR : - * $profiling = $timer->getProfiling(); // get the profiler info as an associative array - * ?> - * - * - * @author Sebastian Bergmann - * @author Ludovico Magnocavallo - * @copyright Copyright © 2002-2005 Sebastian Bergmann - * @license http://www.php.net/license/3_0.txt The PHP License, Version 3.0 - * @category Benchmarking - * @package Benchmark - */ -class Benchmark_Timer extends PEAR { - /** - * Contains the markers. - * - * @var array - * @access private - */ - var $markers = array(); - - /** - * Auto-start and stop timer. - * - * @var boolean - * @access private - */ - var $auto = FALSE; - - /** - * Max marker name length for non-html output. - * - * @var integer - * @access private - */ - var $maxStringLength = 0; - - /** - * Constructor. - * - * @param boolean $auto - * @access public - */ - function Benchmark_Timer($auto = FALSE) { - $this->auto = $auto; - - if ($this->auto) { - $this->start(); - } - - $this->PEAR(); - } - - /** - * Close method. Stop timer and display output. - * - * @access public - */ - function close() { - if ($this->auto) { - $this->stop(); - $this->display(); - } - } - - /** - * Set "Start" marker. - * - * @see setMarker(), stop() - * @access public - */ - function start() { - $this->setMarker('Start'); - } - - /** - * Set "Stop" marker. - * - * @see setMarker(), start() - * @access public - */ - function stop() { - $this->setMarker('Stop'); - } - - /** - * Set marker. - * - * @param string $name Name of the marker to be set. - * @see start(), stop() - * @access public - */ - function setMarker($name) { - $this->markers[$name] = $this->_getMicrotime(); - } - - /** - * Returns the time elapsed betweens two markers. - * - * @param string $start start marker, defaults to "Start" - * @param string $end end marker, defaults to "Stop" - * @return double $time_elapsed time elapsed between $start and $end - * @access public - */ - function timeElapsed($start = 'Start', $end = 'Stop') { - if ($end == 'Stop' && !isset($this->markers['Stop'])) { - $this->markers['Stop'] = $this->_getMicrotime(); - } - $end = isset($this->markers[$end]) ? $this->markers[$end] : 0; - $start = isset($this->markers[$start]) ? $this->markers[$start] : 0; - - if (extension_loaded('bcmath')) { - return bcsub($end, $start, 6); - } else { - return $end - $start; - } - } - - /** - * Returns profiling information. - * - * $profiling[x]['name'] = name of marker x - * $profiling[x]['time'] = time index of marker x - * $profiling[x]['diff'] = execution time from marker x-1 to this marker x - * $profiling[x]['total'] = total execution time up to marker x - * - * @return array - * @access public - */ - function getProfiling() { - $i = $total = 0; - $result = array(); - $temp = reset($this->markers); - $this->maxStringLength = 0; - - foreach ($this->markers as $marker => $time) { - if (extension_loaded('bcmath')) { - $diff = bcsub($time, $temp, 6); - $total = bcadd($total, $diff, 6); - } else { - $diff = $time - $temp; - $total = $total + $diff; - } - - $result[$i]['name'] = $marker; - $result[$i]['time'] = $time; - $result[$i]['diff'] = $diff; - $result[$i]['total'] = $total; - - $this->maxStringLength = (strlen($marker) > $this->maxStringLength ? strlen($marker) + 1 : $this->maxStringLength); - - $temp = $time; - $i++; - } - - $result[0]['diff'] = '-'; - $result[0]['total'] = '-'; - $this->maxStringLength = (strlen('total') > $this->maxStringLength ? strlen('total') : $this->maxStringLength); - $this->maxStringLength += 2; - - return $result; - } - - /** - * Return formatted profiling information. - * - * @param boolean $showTotal Optionnaly includes total in output, default no - * @param string $format output format (auto, plain or html), default auto - * @return string - * @see getProfiling() - * @access public - */ - function getOutput($showTotal = FALSE, $format = 'auto') { - if ($format == 'auto') { - if (function_exists('version_compare') && - version_compare(phpversion(), '4.1', 'ge')) - { - $format = isset($_SERVER['SERVER_PROTOCOL']) ? 'html' : 'plain'; - } else { - global $HTTP_SERVER_VARS; - $format = isset($HTTP_SERVER_VARS['SERVER_PROTOCOL']) ? 'html' : 'plain'; - } - } - - $total = $this->TimeElapsed(); - $result = $this->getProfiling(); - $dashes = ''; - - if ($format == 'html') { - $out = ''."\n"; - $out .= ''. - ($showTotal ? - '' - : '')."\n"; - } else { - $dashes = $out = str_pad("\n", - $this->maxStringLength + ($showTotal ? 70 : 45), '-', STR_PAD_LEFT); - $out .= str_pad('marker', $this->maxStringLength) . - str_pad("time index", 22) . - str_pad("ex time", 16) . - str_pad("perct ", 8) . - ($showTotal ? ' '.str_pad("elapsed", 16)."perct" : '')."\n" . - $dashes; - } - - foreach ($result as $k => $v) { - $perc = (($v['diff'] * 100) / $total); - $tperc = (($v['total'] * 100) / $total); - - if ($format == 'html') { - $out .= "". - ($showTotal ? - "" : ''). - "\n"; - } else { - $out .= str_pad($v['name'], $this->maxStringLength, ' ') . - str_pad($v['time'], 22) . - str_pad($v['diff'], 14) . - str_pad(number_format($perc, 2, '.', '')."%",8, ' ', STR_PAD_LEFT) . - ($showTotal ? ' '. - str_pad($v['total'], 14) . - str_pad(number_format($tperc, 2, '.', '')."%", - 8, ' ', STR_PAD_LEFT) : ''). - "\n"; - } - - $out .= $dashes; - } - - if ($format == 'html') { - $out .= "".($showTotal ? "" : "")."\n"; - $out .= "
 time indexex time%elapsed%
" . $v['name'] . - "" . $v['time'] . - "" . $v['diff'] . - "" . number_format($perc, 2, '.', '') . - "%" . $v['total'] . - "" . - number_format($tperc, 2, '.', '') . - "%
total-${total}100.00%--
\n"; - } else { - $out .= str_pad('total', $this->maxStringLength); - $out .= str_pad('-', 22); - $out .= str_pad($total, 15); - $out .= "100.00%\n"; - $out .= $dashes; - } - - return $out; - } - - /** - * Prints the information returned by getOutput(). - * - * @param boolean $showTotal Optionnaly includes total in output, default no - * @param string $format output format (auto, plain or html), default auto - * @see getOutput() - * @access public - */ - function display($showTotal = FALSE, $format = 'auto') { - print $this->getOutput($showTotal, $format); - } - - /** - * Wrapper for microtime(). - * - * @return float - * @access private - * @since 1.3.0 - */ - function _getMicrotime() { - $microtime = explode(' ', microtime()); - return $microtime[1] . substr($microtime[0], 1); - } -} diff --git a/gulliver/thirdparty/pear/CMD.php b/gulliver/thirdparty/pear/CMD.php deleted file mode 100644 index f65de96c3..000000000 --- a/gulliver/thirdparty/pear/CMD.php +++ /dev/null @@ -1,285 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -define('CMD_RCSID', '$Id: CMD.php,v 1.5 2002/12/31 16:18:22 sebastian Exp $'); - -/** - * The Cmd:: class implements an abstraction for various ways - * of executing commands (directly using the backtick operator, - * as a background task after the script has terminated using - * register_shutdown_function() or as a detached process using nohup). - * - * @author Anders Johannsen - * @version $Revision: 1.5 $ - **/ - -require_once 'PEAR.php'; - - -class Cmd extends PEAR -{ - var $arrSetting = array(); - var $arrConstant = array(); - var $arrCommand = array(); - - /** - * Class constructor - * - * Defines all necessary constants and sets defaults - * - * @author Anders Johannsen - * - * @access public - * - **/ - - function Cmd () - { - // Defining constants - $this->arrConstant = array ("CMD_SEQUENCE", - "CMD_SHUTDOWN", - "CMD_SHELL", - "CMD_OUTPUT", - "CMD_NOHUP", - "CMD_VERBOSE" - ); - - foreach ($this->arrConstant as $key => $value) { - if (!defined($value)) { - define($value, $key); - } - } - - // Setting default values - $this->arrSetting[CMD_SEQUENCE] = true; - $this->arrSetting[CMD_SHUTDOWN] = false; - $this->arrSetting[CMD_OUTPUT] = false; - $this->arrSetting[CMD_NOHUP] = false; - $this->arrSetting[CMD_VERBOSE] = false; - - $arrShell = array ("sh", "bash", "zsh", "tcsh", "csh", "ash", "sash", "esh", "ksh"); - - foreach ($arrShell as $shell) { - if ($this->arrSetting[CMD_SHELL] = $this->which($shell)) { - break; - } - } - - if (empty($this->arrSetting[CMD_SHELL])) { - $this->raiseError("No shell found"); - } - } - - /** - * Sets any option - * - * The options are currently: - * CMD_SHUTDOWN : Execute commands via a shutdown function - * CMD_SHELL : Path to shell - * CMD_OUTPUT : Output stdout from process - * CMD_NOHUP : Use nohup to detach process - * CMD_VERBOSE : Print errors to stdout - * - * @param $option is a constant, which corresponds to the - * option that should be changed - * - * @param $setting is the value of the option currently - * being toggled. - * - * @return bool true if succes, else false - * - * @access public - * - * @author Anders Johannsen - * - **/ - - function setOption ($option, $setting) - { - if (empty($this->arrConstant[$option])) { - $this->raiseError("No such option: $option"); - return false; - } - - - switch ($option) { - case CMD_OUTPUT: - case CMD_SHUTDOWN: - case CMD_VERBOSE: - case CMD_SEQUENCE: - $this->arrSetting[$option] = $setting; - return true; - break; - - case CMD_SHELL: - if (is_executable($setting)) { - $this->arrSetting[$option] = $setting; - return true; - } else { - $this->raiseError("No such shell: $setting"); - return false; - } - break; - - - case CMD_NOHUP: - if (empty($setting)) { - $this->arrSetting[$option] = false; - - } else if ($location = $this->which("nohup")) { - $this->arrSetting[$option] = true; - - } else { - $this->raiseError("Nohup was not found on your system"); - return false; - } - break; - - } - } - - /** - * Add command for execution - * - * @param $command accepts both arrays and regular strings - * - * @return bool true if succes, else false - * - * @access public - * - * @author Anders Johannsen - * - **/ - - function command($command) - { - if (is_array($command)) { - foreach ($command as $key => $value) { - $this->arrCommand[] = $value; - } - return true; - - } else if (is_string($command)) { - $this->arrCommand[] = $command; - return true; - } - - $this->raiseError("Argument not valid"); - return false; - } - - /** - * Executes the code according to given options - * - * @return bool true if succes, else false - * - * @access public - * - * @author Anders Johannsen - * - **/ - - function exec() - { - // Warning about impossible mix of options - if (!empty($this->arrSetting[CMD_OUTPUT])) { - if (!empty($this->arrSetting[CMD_SHUTDOWN]) || !empty($this->arrSetting[CMD_NOHUP])) { - $this->raiseError("Error: Commands executed via shutdown functions or nohup cannot return output"); - return false; - } - } - - // Building command - $strCommand = implode(";", $this->arrCommand); - - $strExec = "echo '$strCommand' | ".$this->arrSetting[CMD_SHELL]; - - if (empty($this->arrSetting[CMD_OUTPUT])) { - $strExec = $strExec . ' > /dev/null'; - } - - if (!empty($this->arrSetting[CMD_NOHUP])) { - $strExec = 'nohup ' . $strExec; - } - - // Executing - if (!empty($this->arrSetting[CMD_SHUTDOWN])) { - $line = "system(\"$strExec\");"; - $function = create_function('', $line); - register_shutdown_function($function); - return true; - } else { - return `$strExec`; - } - } - - /** - * Errorhandler. If option CMD_VERBOSE is true, - * the error is printed to stdout, otherwise it - * is avaliable in lastError - * - * @return bool always returns true - * - * @access private - * - * @author Anders Johannsen - **/ - - function raiseError($strError) - { - if (!empty($this->arrSetting[CMD_VERBOSE])) { - echo $strError; - } else { - $this->lastError = $strError; - } - - return true; - } - - /** - * Functionality similiar to unix 'which'. Searches the path - * for the specified program. - * - * @param $cmd name of the executable to search for - * - * @return string returns the full path if found, - * false if not - * - * @access private - * - * @author Anders Johannsen - **/ - - function which($cmd) - { - global $HTTP_ENV_VARS; - - $arrPath = explode(":", $HTTP_ENV_VARS['PATH']); - - foreach ($arrPath as $path) { - $location = $path . "/" . $cmd; - - if (is_executable($location)) { - return $location; - } - } - return false; - } -} - -?> diff --git a/gulliver/thirdparty/pear/CODING_STANDARDS b/gulliver/thirdparty/pear/CODING_STANDARDS deleted file mode 100644 index 5687c9a9d..000000000 --- a/gulliver/thirdparty/pear/CODING_STANDARDS +++ /dev/null @@ -1,8 +0,0 @@ -=========================================================================== -|| PEAR Coding Standards || -=========================================================================== - -$Id: CODING_STANDARDS,v 1.14 2002/01/24 15:02:05 cox Exp $ - -This document is no longer maintained, see -http://pear.php.net/manual/ instead. diff --git a/gulliver/thirdparty/pear/Console/Getopt.php b/gulliver/thirdparty/pear/Console/Getopt.php deleted file mode 100644 index f6b281378..000000000 --- a/gulliver/thirdparty/pear/Console/Getopt.php +++ /dev/null @@ -1,251 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Getopt.php 6820 2007-06-20 13:35:30Z kevin_fourie $ - -require_once 'PEAR.php'; - -/** - * Command-line options parsing class. - * - * @author Andrei Zmievski - * - */ -class Console_Getopt { - /** - * Parses the command-line options. - * - * The first parameter to this function should be the list of command-line - * arguments without the leading reference to the running program. - * - * The second parameter is a string of allowed short options. Each of the - * option letters can be followed by a colon ':' to specify that the option - * requires an argument, or a double colon '::' to specify that the option - * takes an optional argument. - * - * The third argument is an optional array of allowed long options. The - * leading '--' should not be included in the option name. Options that - * require an argument should be followed by '=', and options that take an - * option argument should be followed by '=='. - * - * The return value is an array of two elements: the list of parsed - * options and the list of non-option command-line arguments. Each entry in - * the list of parsed options is a pair of elements - the first one - * specifies the option, and the second one specifies the option argument, - * if there was one. - * - * Long and short options can be mixed. - * - * Most of the semantics of this function are based on GNU getopt_long(). - * - * @param array $args an array of command-line arguments - * @param string $short_options specifies the list of allowed short options - * @param array $long_options specifies the list of allowed long options - * - * @return array two-element array containing the list of parsed options and - * the non-option arguments - * - * @access public - * - */ - function getopt2($args, $short_options, $long_options = null) - { - return Console_Getopt::doGetopt(2, $args, $short_options, $long_options); - } - - /** - * This function expects $args to start with the script name (POSIX-style). - * Preserved for backwards compatibility. - * @see getopt2() - */ - function getopt($args, $short_options, $long_options = null) - { - return Console_Getopt::doGetopt(1, $args, $short_options, $long_options); - } - - /** - * The actual implementation of the argument parsing code. - */ - function doGetopt($version, $args, $short_options, $long_options = null) - { - // in case you pass directly readPHPArgv() as the first arg - if (PEAR::isError($args)) { - return $args; - } - if (empty($args)) { - return array(array(), array()); - } - $opts = array(); - $non_opts = array(); - - settype($args, 'array'); - - if ($long_options) { - sort($long_options); - } - - /* - * Preserve backwards compatibility with callers that relied on - * erroneous POSIX fix. - */ - if ($version < 2) { - if (isset($args[0]{0}) && $args[0]{0} != '-') { - array_shift($args); - } - } - - reset($args); - while (list($i, $arg) = each($args)) { - - /* The special element '--' means explicit end of - options. Treat the rest of the arguments as non-options - and end the loop. */ - if ($arg == '--') { - $non_opts = array_merge($non_opts, array_slice($args, $i + 1)); - break; - } - - if ($arg{0} != '-' || (strlen($arg) > 1 && $arg{1} == '-' && !$long_options)) { - $non_opts = array_merge($non_opts, array_slice($args, $i)); - break; - } elseif (strlen($arg) > 1 && $arg{1} == '-') { - $error = Console_Getopt::_parseLongOption(substr($arg, 2), $long_options, $opts, $args); - if (PEAR::isError($error)) - return $error; - } else { - $error = Console_Getopt::_parseShortOption(substr($arg, 1), $short_options, $opts, $args); - if (PEAR::isError($error)) - return $error; - } - } - - return array($opts, $non_opts); - } - - /** - * @access private - * - */ - function _parseShortOption($arg, $short_options, &$opts, &$args) - { - for ($i = 0; $i < strlen($arg); $i++) { - $opt = $arg{$i}; - $opt_arg = null; - - /* Try to find the short option in the specifier string. */ - if (($spec = strstr($short_options, $opt)) === false || $arg{$i} == ':') - { - return PEAR::raiseError("Console_Getopt: unrecognized option -- $opt"); - } - - if (strlen($spec) > 1 && $spec{1} == ':') { - if (strlen($spec) > 2 && $spec{2} == ':') { - if ($i + 1 < strlen($arg)) { - /* Option takes an optional argument. Use the remainder of - the arg string if there is anything left. */ - $opts[] = array($opt, substr($arg, $i + 1)); - break; - } - } else { - /* Option requires an argument. Use the remainder of the arg - string if there is anything left. */ - if ($i + 1 < strlen($arg)) { - $opts[] = array($opt, substr($arg, $i + 1)); - break; - } else if (list(, $opt_arg) = each($args)) - /* Else use the next argument. */; - else - return PEAR::raiseError("Console_Getopt: option requires an argument -- $opt"); - } - } - - $opts[] = array($opt, $opt_arg); - } - } - - /** - * @access private - * - */ - function _parseLongOption($arg, $long_options, &$opts, &$args) - { - @list($opt, $opt_arg) = explode('=', $arg); - $opt_len = strlen($opt); - - for ($i = 0; $i < count($long_options); $i++) { - $long_opt = $long_options[$i]; - $opt_start = substr($long_opt, 0, $opt_len); - - /* Option doesn't match. Go on to the next one. */ - if ($opt_start != $opt) - continue; - - $opt_rest = substr($long_opt, $opt_len); - - /* Check that the options uniquely matches one of the allowed - options. */ - if ($opt_rest != '' && $opt{0} != '=' && - $i + 1 < count($long_options) && - $opt == substr($long_options[$i+1], 0, $opt_len)) { - return PEAR::raiseError("Console_Getopt: option --$opt is ambiguous"); - } - - if (substr($long_opt, -1) == '=') { - if (substr($long_opt, -2) != '==') { - /* Long option requires an argument. - Take the next argument if one wasn't specified. */; - if (!strlen($opt_arg) && !(list(, $opt_arg) = each($args))) { - return PEAR::raiseError("Console_Getopt: option --$opt requires an argument"); - } - } - } else if ($opt_arg) { - return PEAR::raiseError("Console_Getopt: option --$opt doesn't allow an argument"); - } - - $opts[] = array('--' . $opt, $opt_arg); - return; - } - - return PEAR::raiseError("Console_Getopt: unrecognized option --$opt"); - } - - /** - * Safely read the $argv PHP array across different PHP configurations. - * Will take care on register_globals and register_argc_argv ini directives - * - * @access public - * @return mixed the $argv PHP array or PEAR error if not registered - */ - function readPHPArgv() - { - global $argv; - if (!is_array($argv)) { - if (!@is_array($_SERVER['argv'])) { - if (!@is_array($GLOBALS['HTTP_SERVER_VARS']['argv'])) { - return PEAR::raiseError("Console_Getopt: Could not read cmd args (register_argc_argv=Off?)"); - } - return $GLOBALS['HTTP_SERVER_VARS']['argv']; - } - return $_SERVER['argv']; - } - return $argv; - } - -} - -?> diff --git a/gulliver/thirdparty/pear/DB.php b/gulliver/thirdparty/pear/DB.php deleted file mode 100644 index d866c4d25..000000000 --- a/gulliver/thirdparty/pear/DB.php +++ /dev/null @@ -1,1114 +0,0 @@ - | -// | Tomas V.V.Cox | -// | Maintainer: Daniel Convissor | -// +----------------------------------------------------------------------+ -// -// $Id: DB.php 3355 2005-06-11 22:14:40Z nbm $ -// -// Database independent query interface. - - -require_once 'PEAR.php'; - -// {{{ constants -// {{{ error codes - -/* - * The method mapErrorCode in each DB_dbtype implementation maps - * native error codes to one of these. - * - * If you add an error code here, make sure you also add a textual - * version of it in DB::errorMessage(). - */ -define('DB_OK', 1); -define('DB_ERROR', -1); -define('DB_ERROR_SYNTAX', -2); -define('DB_ERROR_CONSTRAINT', -3); -define('DB_ERROR_NOT_FOUND', -4); -define('DB_ERROR_ALREADY_EXISTS', -5); -define('DB_ERROR_UNSUPPORTED', -6); -define('DB_ERROR_MISMATCH', -7); -define('DB_ERROR_INVALID', -8); -define('DB_ERROR_NOT_CAPABLE', -9); -define('DB_ERROR_TRUNCATED', -10); -define('DB_ERROR_INVALID_NUMBER', -11); -define('DB_ERROR_INVALID_DATE', -12); -define('DB_ERROR_DIVZERO', -13); -define('DB_ERROR_NODBSELECTED', -14); -define('DB_ERROR_CANNOT_CREATE', -15); -define('DB_ERROR_CANNOT_DELETE', -16); -define('DB_ERROR_CANNOT_DROP', -17); -define('DB_ERROR_NOSUCHTABLE', -18); -define('DB_ERROR_NOSUCHFIELD', -19); -define('DB_ERROR_NEED_MORE_DATA', -20); -define('DB_ERROR_NOT_LOCKED', -21); -define('DB_ERROR_VALUE_COUNT_ON_ROW', -22); -define('DB_ERROR_INVALID_DSN', -23); -define('DB_ERROR_CONNECT_FAILED', -24); -define('DB_ERROR_EXTENSION_NOT_FOUND',-25); -define('DB_ERROR_ACCESS_VIOLATION', -26); -define('DB_ERROR_NOSUCHDB', -27); -define('DB_ERROR_CONSTRAINT_NOT_NULL',-29); - - -// }}} -// {{{ prepared statement-related - - -/* - * These constants are used when storing information about prepared - * statements (using the "prepare" method in DB_dbtype). - * - * The prepare/execute model in DB is mostly borrowed from the ODBC - * extension, in a query the "?" character means a scalar parameter. - * There are two extensions though, a "&" character means an opaque - * parameter. An opaque parameter is simply a file name, the real - * data are in that file (useful for putting uploaded files into your - * database and such). The "!" char means a parameter that must be - * left as it is. - * They modify the quote behavoir: - * DB_PARAM_SCALAR (?) => 'original string quoted' - * DB_PARAM_OPAQUE (&) => 'string from file quoted' - * DB_PARAM_MISC (!) => original string - */ -define('DB_PARAM_SCALAR', 1); -define('DB_PARAM_OPAQUE', 2); -define('DB_PARAM_MISC', 3); - - -// }}} -// {{{ binary data-related - - -/* - * These constants define different ways of returning binary data - * from queries. Again, this model has been borrowed from the ODBC - * extension. - * - * DB_BINMODE_PASSTHRU sends the data directly through to the browser - * when data is fetched from the database. - * DB_BINMODE_RETURN lets you return data as usual. - * DB_BINMODE_CONVERT returns data as well, only it is converted to - * hex format, for example the string "123" would become "313233". - */ -define('DB_BINMODE_PASSTHRU', 1); -define('DB_BINMODE_RETURN', 2); -define('DB_BINMODE_CONVERT', 3); - - -// }}} -// {{{ fetch modes - - -/** - * This is a special constant that tells DB the user hasn't specified - * any particular get mode, so the default should be used. - */ -define('DB_FETCHMODE_DEFAULT', 0); - -/** - * Column data indexed by numbers, ordered from 0 and up - */ -define('DB_FETCHMODE_ORDERED', 1); - -/** - * Column data indexed by column names - */ -define('DB_FETCHMODE_ASSOC', 2); - -/** - * Column data as object properties - */ -define('DB_FETCHMODE_OBJECT', 3); - -/** - * For multi-dimensional results: normally the first level of arrays - * is the row number, and the second level indexed by column number or name. - * DB_FETCHMODE_FLIPPED switches this order, so the first level of arrays - * is the column name, and the second level the row number. - */ -define('DB_FETCHMODE_FLIPPED', 4); - -/* for compatibility */ -define('DB_GETMODE_ORDERED', DB_FETCHMODE_ORDERED); -define('DB_GETMODE_ASSOC', DB_FETCHMODE_ASSOC); -define('DB_GETMODE_FLIPPED', DB_FETCHMODE_FLIPPED); - - -// }}} -// {{{ tableInfo() && autoPrepare()-related - - -/** - * these are constants for the tableInfo-function - * they are bitwised or'ed. so if there are more constants to be defined - * in the future, adjust DB_TABLEINFO_FULL accordingly - */ -define('DB_TABLEINFO_ORDER', 1); -define('DB_TABLEINFO_ORDERTABLE', 2); -define('DB_TABLEINFO_FULL', 3); - -/* - * Used by autoPrepare() - */ -define('DB_AUTOQUERY_INSERT', 1); -define('DB_AUTOQUERY_UPDATE', 2); - - -// }}} -// {{{ portability modes - - -/** - * Portability: turn off all portability features. - * @see DB_common::setOption() - */ -define('DB_PORTABILITY_NONE', 0); - -/** - * Portability: convert names of tables and fields to lower case - * when using the get*(), fetch*() and tableInfo() methods. - * @see DB_common::setOption() - */ -define('DB_PORTABILITY_LOWERCASE', 1); - -/** - * Portability: right trim the data output by get*() and fetch*(). - * @see DB_common::setOption() - */ -define('DB_PORTABILITY_RTRIM', 2); - -/** - * Portability: force reporting the number of rows deleted. - * @see DB_common::setOption() - */ -define('DB_PORTABILITY_DELETE_COUNT', 4); - -/** - * Portability: enable hack that makes numRows() work in Oracle. - * @see DB_common::setOption() - */ -define('DB_PORTABILITY_NUMROWS', 8); - -/** - * Portability: makes certain error messages in certain drivers compatible - * with those from other DBMS's. - * - * + mysql, mysqli: change unique/primary key constraints - * DB_ERROR_ALREADY_EXISTS -> DB_ERROR_CONSTRAINT - * - * + odbc(access): MS's ODBC driver reports 'no such field' as code - * 07001, which means 'too few parameters.' When this option is on - * that code gets mapped to DB_ERROR_NOSUCHFIELD. - * - * @see DB_common::setOption() - */ -define('DB_PORTABILITY_ERRORS', 16); - -/** - * Portability: convert null values to empty strings in data output by - * get*() and fetch*(). - * @see DB_common::setOption() - */ -define('DB_PORTABILITY_NULL_TO_EMPTY', 32); - -/** - * Portability: turn on all portability features. - * @see DB_common::setOption() - */ -define('DB_PORTABILITY_ALL', 63); - -// }}} - - -// }}} -// {{{ class DB - -/** - * The main "DB" class is simply a container class with some static - * methods for creating DB objects as well as some utility functions - * common to all parts of DB. - * - * The object model of DB is as follows (indentation means inheritance): - * - * DB The main DB class. This is simply a utility class - * with some "static" methods for creating DB objects as - * well as common utility functions for other DB classes. - * - * DB_common The base for each DB implementation. Provides default - * | implementations (in OO lingo virtual methods) for - * | the actual DB implementations as well as a bunch of - * | query utility functions. - * | - * +-DB_mysql The DB implementation for MySQL. Inherits DB_common. - * When calling DB::factory or DB::connect for MySQL - * connections, the object returned is an instance of this - * class. - * - * @package DB - * @author Stig Bakken - * @author Tomas V.V.Cox - * @since PHP 4.0 - * @version $Id: DB.php 3355 2005-06-11 22:14:40Z nbm $ - * @category Database - */ -class DB -{ - // {{{ &factory() - - /** - * Create a new DB object for the specified database type. - * - * Allows creation of a DB_ object from which the object's - * methods can be utilized without actually connecting to a database. - * - * @param string $type database type, for example "mysql" - * @param array $options associative array of option names and values - * - * @return object a new DB object. On error, an error object. - * - * @see DB_common::setOption() - * @access public - */ - function &factory($type, $options = false) - { - if (!is_array($options)) { - $options = array('persistent' => $options); - } - - if (isset($options['debug']) && $options['debug'] >= 2) { - // expose php errors with sufficient debug level - include_once "DB/{$type}.php"; - } else { - @include_once "DB/{$type}.php"; - } - - $classname = "DB_${type}"; - - if (!class_exists($classname)) { - $tmp = PEAR::raiseError(null, DB_ERROR_NOT_FOUND, null, null, - "Unable to include the DB/{$type}.php file", - 'DB_Error', true); - return $tmp; - } - - $obj = new $classname; - - foreach ($options as $option => $value) { - $test = $obj->setOption($option, $value); - if (DB::isError($test)) { - return $test; - } - } - - return $obj; - } - - // }}} - // {{{ &connect() - - /** - * Create a new DB object and connect to the specified database. - * - * Example 1. - * 2, - * 'portability' => DB_PORTABILITY_ALL, - * ); - * - * $dbh =& DB::connect($dsn, $options); - * if (DB::isError($dbh)) { - * die($dbh->getMessage()); - * } - * ?> - * - * @param mixed $dsn string "data source name" or an array in the - * format returned by DB::parseDSN() - * - * @param array $options an associative array of option names and - * their values - * - * @return object a newly created DB connection object, or a DB - * error object on error - * - * @see DB::parseDSN(), DB_common::setOption(), DB::isError() - * @access public - */ - function &connect($dsn, $options = array()) - { - $dsninfo = DB::parseDSN($dsn); - $type = $dsninfo['phptype']; - - if (!is_array($options)) { - /* - * For backwards compatibility. $options used to be boolean, - * indicating whether the connection should be persistent. - */ - $options = array('persistent' => $options); - } - - if (isset($options['debug']) && $options['debug'] >= 2) { - // expose php errors with sufficient debug level - include_once "DB/${type}.php"; - } else { - @include_once "DB/${type}.php"; - } - - $classname = "DB_${type}"; - if (!class_exists($classname)) { - $tmp = PEAR::raiseError(null, DB_ERROR_NOT_FOUND, null, null, - "Unable to include the DB/{$type}.php file for `$dsn'", - 'DB_Error', true); - return $tmp; - } - - $obj = new $classname; - - foreach ($options as $option => $value) { - $test = $obj->setOption($option, $value); - if (DB::isError($test)) { - return $test; - } - } - - $err = $obj->connect($dsninfo, $obj->getOption('persistent')); - if (DB::isError($err)) { - $err->addUserInfo($dsn); - return $err; - } - - return $obj; - } - - // }}} - // {{{ apiVersion() - - /** - * Return the DB API version - * - * @return int the DB API version number - * - * @access public - */ - function apiVersion() - { - return 2; - } - - // }}} - // {{{ isError() - - /** - * Tell whether a result code from a DB method is an error - * - * @param int $value result code - * - * @return bool whether $value is an error - * - * @access public - */ - function isError($value) - { - return is_a($value, 'DB_Error'); - } - - // }}} - // {{{ isConnection() - - /** - * Tell whether a value is a DB connection - * - * @param mixed $value value to test - * - * @return bool whether $value is a DB connection - * - * @access public - */ - function isConnection($value) - { - return (is_object($value) && - is_subclass_of($value, 'db_common') && - method_exists($value, 'simpleQuery')); - } - - // }}} - // {{{ isManip() - - /** - * Tell whether a query is a data manipulation query (insert, - * update or delete) or a data definition query (create, drop, - * alter, grant, revoke). - * - * @access public - * - * @param string $query the query - * - * @return boolean whether $query is a data manipulation query - */ - function isManip($query) - { - $manips = 'INSERT|UPDATE|DELETE|LOAD DATA|'.'REPLACE|CREATE|DROP|'. - 'ALTER|GRANT|REVOKE|'.'LOCK|UNLOCK'; - if (preg_match('/^\s*"?('.$manips.')\s+/i', $query)) { - return true; - } - return false; - } - - // }}} - // {{{ errorMessage() - - /** - * Return a textual error message for a DB error code - * - * @param integer $value error code - * - * @return string error message, or false if the error code was - * not recognized - */ - function errorMessage($value) - { - static $errorMessages; - if (!isset($errorMessages)) { - $errorMessages = array( - DB_ERROR => 'unknown error', - DB_ERROR_ALREADY_EXISTS => 'already exists', - DB_ERROR_CANNOT_CREATE => 'can not create', - DB_ERROR_CANNOT_DELETE => 'can not delete', - DB_ERROR_CANNOT_DROP => 'can not drop', - DB_ERROR_CONSTRAINT => 'constraint violation', - DB_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint', - DB_ERROR_DIVZERO => 'division by zero', - DB_ERROR_INVALID => 'invalid', - DB_ERROR_INVALID_DATE => 'invalid date or time', - DB_ERROR_INVALID_NUMBER => 'invalid number', - DB_ERROR_MISMATCH => 'mismatch', - DB_ERROR_NODBSELECTED => 'no database selected', - DB_ERROR_NOSUCHFIELD => 'no such field', - DB_ERROR_NOSUCHTABLE => 'no such table', - DB_ERROR_NOT_CAPABLE => 'DB backend not capable', - DB_ERROR_NOT_FOUND => 'not found', - DB_ERROR_NOT_LOCKED => 'not locked', - DB_ERROR_SYNTAX => 'syntax error', - DB_ERROR_UNSUPPORTED => 'not supported', - DB_ERROR_VALUE_COUNT_ON_ROW => 'value count on row', - DB_ERROR_INVALID_DSN => 'invalid DSN', - DB_ERROR_CONNECT_FAILED => 'connect failed', - DB_OK => 'no error', - DB_ERROR_NEED_MORE_DATA => 'insufficient data supplied', - DB_ERROR_EXTENSION_NOT_FOUND=> 'extension not found', - DB_ERROR_NOSUCHDB => 'no such database', - DB_ERROR_ACCESS_VIOLATION => 'insufficient permissions', - DB_ERROR_TRUNCATED => 'truncated' - ); - } - - if (DB::isError($value)) { - $value = $value->getCode(); - } - - return isset($errorMessages[$value]) ? $errorMessages[$value] : $errorMessages[DB_ERROR]; - } - - // }}} - // {{{ parseDSN() - - /** - * Parse a data source name. - * - * Additional keys can be added by appending a URI query string to the - * end of the DSN. - * - * The format of the supplied DSN is in its fullest form: - * - * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true - * - * - * Most variations are allowed: - * - * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644 - * phptype://username:password@hostspec/database_name - * phptype://username:password@hostspec - * phptype://username@hostspec - * phptype://hostspec/database - * phptype://hostspec - * phptype(dbsyntax) - * phptype - * - * - * @param string $dsn Data Source Name to be parsed - * - * @return array an associative array with the following keys: - * + phptype: Database backend used in PHP (mysql, odbc etc.) - * + dbsyntax: Database used with regards to SQL syntax etc. - * + protocol: Communication protocol to use (tcp, unix etc.) - * + hostspec: Host specification (hostname[:port]) - * + database: Database to use on the DBMS server - * + username: User name for login - * + password: Password for login - * - * @author Tomas V.V.Cox - */ - function parseDSN($dsn) - { - $parsed = array( - 'phptype' => false, - 'dbsyntax' => false, - 'username' => false, - 'password' => false, - 'protocol' => false, - 'hostspec' => false, - 'port' => false, - 'socket' => false, - 'database' => false, - ); - - if (is_array($dsn)) { - $dsn = array_merge($parsed, $dsn); - if (!$dsn['dbsyntax']) { - $dsn['dbsyntax'] = $dsn['phptype']; - } - return $dsn; - } - - // Find phptype and dbsyntax - if (($pos = strpos($dsn, '://')) !== false) { - $str = substr($dsn, 0, $pos); - $dsn = substr($dsn, $pos + 3); - } else { - $str = $dsn; - $dsn = null; - } - - // Get phptype and dbsyntax - // $str => phptype(dbsyntax) - if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) { - $parsed['phptype'] = $arr[1]; - $parsed['dbsyntax'] = !$arr[2] ? $arr[1] : $arr[2]; - } else { - $parsed['phptype'] = $str; - $parsed['dbsyntax'] = $str; - } - - if (!count($dsn)) { - return $parsed; - } - - // Get (if found): username and password - // $dsn => username:password@protocol+hostspec/database - if (($at = strrpos($dsn,'@')) !== false) { - $str = substr($dsn, 0, $at); - $dsn = substr($dsn, $at + 1); - if (($pos = strpos($str, ':')) !== false) { - $parsed['username'] = rawurldecode(substr($str, 0, $pos)); - $parsed['password'] = rawurldecode(substr($str, $pos + 1)); - } else { - $parsed['username'] = rawurldecode($str); - } - } - - // Find protocol and hostspec - - // $dsn => proto(proto_opts)/database - if (preg_match('|^([^(]+)\((.*?)\)/?(.*?)$|', $dsn, $match)) { - $proto = $match[1]; - $proto_opts = $match[2] ? $match[2] : false; - $dsn = $match[3]; - - // $dsn => protocol+hostspec/database (old format) - } else { - if (strpos($dsn, '+') !== false) { - list($proto, $dsn) = explode('+', $dsn, 2); - } - if (strpos($dsn, '/') !== false) { - list($proto_opts, $dsn) = explode('/', $dsn, 2); - } else { - $proto_opts = $dsn; - $dsn = null; - } - } - - // process the different protocol options - $parsed['protocol'] = (!empty($proto)) ? $proto : 'tcp'; - $proto_opts = rawurldecode($proto_opts); - if ($parsed['protocol'] == 'tcp') { - if (strpos($proto_opts, ':') !== false) { - list($parsed['hostspec'], $parsed['port']) = explode(':', $proto_opts); - } else { - $parsed['hostspec'] = $proto_opts; - } - } elseif ($parsed['protocol'] == 'unix') { - $parsed['socket'] = $proto_opts; - } - - // Get dabase if any - // $dsn => database - if ($dsn) { - // /database - if (($pos = strpos($dsn, '?')) === false) { - $parsed['database'] = rawurldecode($dsn); - // /database?param1=value1¶m2=value2 - } else { - $parsed['database'] = rawurldecode(substr($dsn, 0, $pos)); - $dsn = substr($dsn, $pos + 1); - if (strpos($dsn, '&') !== false) { - $opts = explode('&', $dsn); - } else { // database?param1=value1 - $opts = array($dsn); - } - foreach ($opts as $opt) { - list($key, $value) = explode('=', $opt); - if (!isset($parsed[$key])) { - // don't allow params overwrite - $parsed[$key] = rawurldecode($value); - } - } - } - } - - return $parsed; - } - - // }}} - // {{{ assertExtension() - - /** - * Load a PHP database extension if it is not loaded already. - * - * @access public - * - * @param string $name the base name of the extension (without the .so or - * .dll suffix) - * - * @return boolean true if the extension was already or successfully - * loaded, false if it could not be loaded - */ - function assertExtension($name) - { - if (!extension_loaded($name)) { - $dlext = OS_WINDOWS ? '.dll' : '.so'; - $dlprefix = OS_WINDOWS ? 'php_' : ''; - @dl($dlprefix . $name . $dlext); - return extension_loaded($name); - } - return true; - } - // }}} -} - -// }}} -// {{{ class DB_Error - -/** - * DB_Error implements a class for reporting portable database error - * messages. - * - * @package DB - * @author Stig Bakken - */ -class DB_Error extends PEAR_Error -{ - // {{{ constructor - - /** - * DB_Error constructor. - * - * @param mixed $code DB error code, or string with error message. - * @param integer $mode what "error mode" to operate in - * @param integer $level what error level to use for $mode & PEAR_ERROR_TRIGGER - * @param mixed $debuginfo additional debug info, such as the last query - * - * @access public - * - * @see PEAR_Error - */ - function DB_Error($code = DB_ERROR, $mode = PEAR_ERROR_RETURN, - $level = E_USER_NOTICE, $debuginfo = null) - { - if (is_int($code)) { - $this->PEAR_Error('DB Error: ' . DB::errorMessage($code), $code, $mode, $level, $debuginfo); - } else { - $this->PEAR_Error("DB Error: $code", DB_ERROR, $mode, $level, $debuginfo); - } - } - // }}} -} - -// }}} -// {{{ class DB_result - -/** - * This class implements a wrapper for a DB result set. - * A new instance of this class will be returned by the DB implementation - * after processing a query that returns data. - * - * @package DB - * @author Stig Bakken - */ -class DB_result -{ - // {{{ properties - - var $dbh; - var $result; - var $row_counter = null; - - /** - * for limit queries, the row to start fetching - * @var integer - */ - var $limit_from = null; - - /** - * for limit queries, the number of rows to fetch - * @var integer - */ - var $limit_count = null; - - // }}} - // {{{ constructor - - /** - * DB_result constructor. - * @param resource &$dbh DB object reference - * @param resource $result result resource id - * @param array $options assoc array with optional result options - */ - function DB_result(&$dbh, $result, $options = array()) - { - $this->dbh = &$dbh; - $this->result = $result; - foreach ($options as $key => $value) { - $this->setOption($key, $value); - } - $this->limit_type = $dbh->features['limit']; - $this->autofree = $dbh->options['autofree']; - $this->fetchmode = $dbh->fetchmode; - $this->fetchmode_object_class = $dbh->fetchmode_object_class; - } - - function setOption($key, $value = null) - { - switch ($key) { - case 'limit_from': - $this->limit_from = $value; break; - case 'limit_count': - $this->limit_count = $value; break; - } - } - - // }}} - // {{{ fetchRow() - - /** - * Fetch a row of data and return it by reference into an array. - * - * The type of array returned can be controlled either by setting this - * method's $fetchmode parameter or by changing the default - * fetch mode setFetchMode() before calling this method. - * - * There are two options for standardizing the information returned - * from databases, ensuring their values are consistent when changing - * DBMS's. These portability options can be turned on when creating a - * new DB object or by using setOption(). - * - * + DB_PORTABILITY_LOWERCASE - * convert names of fields to lower case - * - * + DB_PORTABILITY_RTRIM - * right trim the data - * - * @param int $fetchmode how the resulting array should be indexed - * @param int $rownum the row number to fetch - * - * @return array a row of data, null on no more rows or PEAR_Error - * object on error - * - * @see DB_common::setOption(), DB_common::setFetchMode() - * @access public - */ - function &fetchRow($fetchmode = DB_FETCHMODE_DEFAULT, $rownum=null) - { - if ($fetchmode === DB_FETCHMODE_DEFAULT) { - $fetchmode = $this->fetchmode; - } - if ($fetchmode === DB_FETCHMODE_OBJECT) { - $fetchmode = DB_FETCHMODE_ASSOC; - $object_class = $this->fetchmode_object_class; - } - if ($this->limit_from !== null) { - if ($this->row_counter === null) { - $this->row_counter = $this->limit_from; - // Skip rows - if ($this->limit_type == false) { - $i = 0; - while ($i++ < $this->limit_from) { - $this->dbh->fetchInto($this->result, $arr, $fetchmode); - } - } - } - if ($this->row_counter >= ( - $this->limit_from + $this->limit_count)) - { - if ($this->autofree) { - $this->free(); - } - $tmp = null; - return $tmp; - } - if ($this->limit_type == 'emulate') { - $rownum = $this->row_counter; - } - $this->row_counter++; - } - $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum); - if ($res === DB_OK) { - if (isset($object_class)) { - // default mode specified in DB_common::fetchmode_object_class property - if ($object_class == 'stdClass') { - $arr = (object) $arr; - } else { - $arr = new $object_class($arr); - } - } - return $arr; - } - if ($res == null && $this->autofree) { - $this->free(); - } - return $res; - } - - // }}} - // {{{ fetchInto() - - /** - * Fetch a row of data into an array which is passed by reference. - * - * The type of array returned can be controlled either by setting this - * method's $fetchmode parameter or by changing the default - * fetch mode setFetchMode() before calling this method. - * - * There are two options for standardizing the information returned - * from databases, ensuring their values are consistent when changing - * DBMS's. These portability options can be turned on when creating a - * new DB object or by using setOption(). - * - * + DB_PORTABILITY_LOWERCASE - * convert names of fields to lower case - * - * + DB_PORTABILITY_RTRIM - * right trim the data - * - * @param array &$arr (reference) array where data from the row - * should be placed - * @param int $fetchmode how the resulting array should be indexed - * @param int $rownum the row number to fetch - * - * @return mixed DB_OK on success, null on no more rows or - * a DB_Error object on error - * - * @see DB_common::setOption(), DB_common::setFetchMode() - * @access public - */ - function fetchInto(&$arr, $fetchmode = DB_FETCHMODE_DEFAULT, $rownum=null) - { - if ($fetchmode === DB_FETCHMODE_DEFAULT) { - $fetchmode = $this->fetchmode; - } - if ($fetchmode === DB_FETCHMODE_OBJECT) { - $fetchmode = DB_FETCHMODE_ASSOC; - $object_class = $this->fetchmode_object_class; - } - if ($this->limit_from !== null) { - if ($this->row_counter === null) { - $this->row_counter = $this->limit_from; - // Skip rows - if ($this->limit_type == false) { - $i = 0; - while ($i++ < $this->limit_from) { - $this->dbh->fetchInto($this->result, $arr, $fetchmode); - } - } - } - if ($this->row_counter >= ( - $this->limit_from + $this->limit_count)) - { - if ($this->autofree) { - $this->free(); - } - return null; - } - if ($this->limit_type == 'emulate') { - $rownum = $this->row_counter; - } - - $this->row_counter++; - } - $res = $this->dbh->fetchInto($this->result, $arr, $fetchmode, $rownum); - if ($res === DB_OK) { - if (isset($object_class)) { - // default mode specified in DB_common::fetchmode_object_class property - if ($object_class == 'stdClass') { - $arr = (object) $arr; - } else { - $arr = new $object_class($arr); - } - } - return DB_OK; - } - if ($res == null && $this->autofree) { - $this->free(); - } - return $res; - } - - // }}} - // {{{ numCols() - - /** - * Get the the number of columns in a result set. - * - * @return int the number of columns, or a DB error - * - * @access public - */ - function numCols() - { - return $this->dbh->numCols($this->result); - } - - // }}} - // {{{ numRows() - - /** - * Get the number of rows in a result set. - * - * @return int the number of rows, or a DB error - * - * @access public - */ - function numRows() - { - return $this->dbh->numRows($this->result); - } - - // }}} - // {{{ nextResult() - - /** - * Get the next result if a batch of queries was executed. - * - * @return bool true if a new result is available or false if not. - * - * @access public - */ - function nextResult() - { - return $this->dbh->nextResult($this->result); - } - - // }}} - // {{{ free() - - /** - * Frees the resources allocated for this result set. - * @return int error code - * - * @access public - */ - function free() - { - $err = $this->dbh->freeResult($this->result); - if (DB::isError($err)) { - return $err; - } - $this->result = false; - return true; - } - - // }}} - // {{{ tableInfo() - - /** - * @deprecated - * @internal - * @see DB_common::tableInfo() - */ - function tableInfo($mode = null) - { - if (is_string($mode)) { - return $this->dbh->raiseError(DB_ERROR_NEED_MORE_DATA); - } - return $this->dbh->tableInfo($this, $mode); - } - - // }}} - // {{{ getRowCounter() - - /** - * returns the actual row number - * @return integer - */ - function getRowCounter() - { - return $this->row_counter; - } - // }}} -} - -// }}} -// {{{ class DB_row - -/** - * Pear DB Row Object - * @see DB_common::setFetchMode() - */ -class DB_row -{ - // {{{ constructor - - /** - * constructor - * - * @param resource row data as array - */ - function DB_row(&$arr) - { - foreach ($arr as $key => $value) { - $this->$key = &$arr[$key]; - } - } - - // }}} -} - -// }}} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - */ - -?> diff --git a/gulliver/thirdparty/pear/DB/common.php b/gulliver/thirdparty/pear/DB/common.php deleted file mode 100644 index 13bb1df8c..000000000 --- a/gulliver/thirdparty/pear/DB/common.php +++ /dev/null @@ -1,2042 +0,0 @@ - | -// | Tomas V.V.Cox | -// | Maintainer: Daniel Convissor | -// +----------------------------------------------------------------------+ -// -// $Id: common.php 3355 2005-06-11 22:14:40Z nbm $ - -require_once 'PEAR.php'; - -/** - * DB_common is a base class for DB implementations, and must be - * inherited by all such - * - * @package DB - * @version $Id: common.php 3355 2005-06-11 22:14:40Z nbm $ - * @category Database - * @author Stig Bakken - * @author Tomas V.V.Cox - */ -class DB_common extends PEAR -{ - // {{{ properties - - /** - * assoc of capabilities for this DB implementation - * $features['limit'] => 'emulate' => emulate with fetch row by number - * 'alter' => alter the query - * false => skip rows - * @var array - */ - var $features = array(); - - /** - * assoc mapping native error codes to DB ones - * @var array - */ - var $errorcode_map = array(); - - /** - * DB type (mysql, oci8, odbc etc.) - * @var string - */ - var $phptype; - - /** - * @var string - */ - var $prepare_tokens; - - /** - * @var string - */ - var $prepare_types; - - /** - * @var string - */ - var $prepared_queries; - - /** - * @var integer - */ - var $prepare_maxstmt = 0; - - /** - * @var string - */ - var $last_query = ''; - - /** - * @var integer - */ - var $fetchmode = DB_FETCHMODE_ORDERED; - - /** - * @var string - */ - var $fetchmode_object_class = 'stdClass'; - - /** - * Run-time configuration options. - * - * The 'optimize' option has been deprecated. Use the 'portability' - * option instead. - * - * @see DB_common::setOption() - * @var array - */ - var $options = array( - 'persistent' => false, - 'ssl' => false, - 'debug' => 0, - 'seqname_format' => '%s_seq', - 'autofree' => false, - 'portability' => DB_PORTABILITY_NONE, - 'optimize' => 'performance', // Deprecated. Use 'portability'. - ); - - /** - * DB handle - * @var resource - */ - var $dbh; - - // }}} - // {{{ toString() - - /** - * String conversation - * - * @return string - * @access private - */ - function toString() - { - $info = strtolower(get_class($this)); - $info .= ': (phptype=' . $this->phptype . - ', dbsyntax=' . $this->dbsyntax . - ')'; - - if ($this->connection) { - $info .= ' [connected]'; - } - - return $info; - } - - // }}} - // {{{ constructor - - /** - * Constructor - */ - function DB_common() - { - $this->PEAR('DB_Error'); - } - - // }}} - // {{{ quoteString() - - /** - * DEPRECATED: Quotes a string so it can be safely used within string - * delimiters in a query - * - * @return string quoted string - * - * @see DB_common::quoteSmart(), DB_common::escapeSimple() - * @deprecated Deprecated in release 1.2 or lower - * @internal - */ - function quoteString($string) - { - $string = $this->quote($string); - if ($string{0} == "'") { - return substr($string, 1, -1); - } - return $string; - } - - // }}} - // {{{ quote() - - /** - * DEPRECATED: Quotes a string so it can be safely used in a query - * - * @param string $string the input string to quote - * - * @return string The NULL string or the string quotes - * in magic_quote_sybase style - * - * @see DB_common::quoteSmart(), DB_common::escapeSimple() - * @deprecated Deprecated in release 1.6.0 - * @internal - */ - function quote($string = null) - { - return ($string === null) ? 'NULL' : "'".str_replace("'", "''", $string)."'"; - } - - // }}} - // {{{ quoteIdentifier() - - /** - * Quote a string so it can be safely used as a table or column name - * - * Delimiting style depends on which database driver is being used. - * - * NOTE: just because you CAN use delimited identifiers doesn't mean - * you SHOULD use them. In general, they end up causing way more - * problems than they solve. - * - * Portability is broken by using the following characters inside - * delimited identifiers: - * + backtick (`) -- due to MySQL - * + double quote (") -- due to Oracle - * + brackets ([ or ]) -- due to Access - * - * Delimited identifiers are known to generally work correctly under - * the following drivers: - * + mssql - * + mysql - * + mysqli - * + oci8 - * + odbc(access) - * + odbc(db2) - * + pgsql - * + sqlite - * + sybase - * - * InterBase doesn't seem to be able to use delimited identifiers - * via PHP 4. They work fine under PHP 5. - * - * @param string $str identifier name to be quoted - * - * @return string quoted identifier string - * - * @since 1.6.0 - * @access public - */ - function quoteIdentifier($str) - { - return '"' . str_replace('"', '""', $str) . '"'; - } - - // }}} - // {{{ quoteSmart() - - /** - * Format input so it can be safely used in a query - * - * The output depends on the PHP data type of input and the database - * type being used. - * - * @param mixed $in data to be quoted - * - * @return mixed the format of the results depends on the input's - * PHP type: - * - *
    - *
  • - * input -> returns - *
  • - *
  • - * null -> the string NULL - *
  • - *
  • - * integer or double -> the unquoted number - *
  • - *
  • - * &type.bool; -> output depends on the driver in use - * Most drivers return integers: 1 if - * true or 0 if - * false. - * Some return strings: TRUE if - * true or FALSE if - * false. - * Finally one returns strings: T if - * true or F if - * false. Here is a list of each DBMS, - * the values returned and the suggested column type: - *
      - *
    • - * dbase -> T/F - * (Logical) - *
    • - *
    • - * fbase -> TRUE/FALSE - * (BOOLEAN) - *
    • - *
    • - * ibase -> 1/0 - * (SMALLINT) [1] - *
    • - *
    • - * ifx -> 1/0 - * (SMALLINT) [1] - *
    • - *
    • - * msql -> 1/0 - * (INTEGER) - *
    • - *
    • - * mssql -> 1/0 - * (BIT) - *
    • - *
    • - * mysql -> 1/0 - * (TINYINT(1)) - *
    • - *
    • - * mysqli -> 1/0 - * (TINYINT(1)) - *
    • - *
    • - * oci8 -> 1/0 - * (NUMBER(1)) - *
    • - *
    • - * odbc -> 1/0 - * (SMALLINT) [1] - *
    • - *
    • - * pgsql -> TRUE/FALSE - * (BOOLEAN) - *
    • - *
    • - * sqlite -> 1/0 - * (INTEGER) - *
    • - *
    • - * sybase -> 1/0 - * (TINYINT(1)) - *
    • - *
    - * [1] Accommodate the lowest common denominator because not all - * versions of have BOOLEAN. - *
  • - *
  • - * other (including strings and numeric strings) -> - * the data with single quotes escaped by preceeding - * single quotes, backslashes are escaped by preceeding - * backslashes, then the whole string is encapsulated - * between single quotes - *
  • - *
- * - * @since 1.6.0 - * @see DB_common::escapeSimple() - * @access public - */ - function quoteSmart($in) - { - if (is_int($in) || is_double($in)) { - return $in; - } elseif (is_bool($in)) { - return $in ? 1 : 0; - } elseif (is_null($in)) { - return 'NULL'; - } else { - return "'" . $this->escapeSimple($in) . "'"; - } - } - - // }}} - // {{{ escapeSimple() - - /** - * Escape a string according to the current DBMS's standards - * - * In SQLite, this makes things safe for inserts/updates, but may - * cause problems when performing text comparisons against columns - * containing binary data. See the - * {@link http://php.net/sqlite_escape_string PHP manual} for more info. - * - * @param string $str the string to be escaped - * - * @return string the escaped string - * - * @since 1.6.0 - * @see DB_common::quoteSmart() - * @access public - */ - function escapeSimple($str) { - return str_replace("'", "''", $str); - } - - // }}} - // {{{ provides() - - /** - * Tell whether a DB implementation or its backend extension - * supports a given feature - * - * @param array $feature name of the feature (see the DB class doc) - * @return bool whether this DB implementation supports $feature - * @access public - */ - function provides($feature) - { - return $this->features[$feature]; - } - - // }}} - // {{{ errorCode() - - /** - * Map native error codes to DB's portable ones - * - * Requires that the DB implementation's constructor fills - * in the $errorcode_map property. - * - * @param mixed $nativecode the native error code, as returned by the - * backend database extension (string or integer) - * - * @return int a portable DB error code, or DB_ERROR if this DB - * implementation has no mapping for the given error code. - * - * @access public - */ - function errorCode($nativecode) - { - if (isset($this->errorcode_map[$nativecode])) { - return $this->errorcode_map[$nativecode]; - } - // Fall back to DB_ERROR if there was no mapping. - return DB_ERROR; - } - - // }}} - // {{{ errorMessage() - - /** - * Map a DB error code to a textual message. This is actually - * just a wrapper for DB::errorMessage() - * - * @param integer $dbcode the DB error code - * - * @return string the corresponding error message, of false - * if the error code was unknown - * - * @access public - */ - function errorMessage($dbcode) - { - return DB::errorMessage($this->errorcode_map[$dbcode]); - } - - // }}} - // {{{ raiseError() - - /** - * Communicate an error and invoke error callbacks, etc - * - * Basically a wrapper for PEAR::raiseError without the message string. - * - * @param mixed integer error code, or a PEAR error object (all - * other parameters are ignored if this parameter is - * an object - * - * @param int error mode, see PEAR_Error docs - * - * @param mixed If error mode is PEAR_ERROR_TRIGGER, this is the - * error level (E_USER_NOTICE etc). If error mode is - * PEAR_ERROR_CALLBACK, this is the callback function, - * either as a function name, or as an array of an - * object and method name. For other error modes this - * parameter is ignored. - * - * @param string Extra debug information. Defaults to the last - * query and native error code. - * - * @param mixed Native error code, integer or string depending the - * backend. - * - * @return object a PEAR error object - * - * @access public - * @see PEAR_Error - */ - function &raiseError($code = DB_ERROR, $mode = null, $options = null, - $userinfo = null, $nativecode = null) - { - // The error is yet a DB error object - if (is_object($code)) { - // because we the static PEAR::raiseError, our global - // handler should be used if it is set - if ($mode === null && !empty($this->_default_error_mode)) { - $mode = $this->_default_error_mode; - $options = $this->_default_error_options; - } - $tmp = PEAR::raiseError($code, null, $mode, $options, null, null, true); - return $tmp; - } - - if ($userinfo === null) { - $userinfo = $this->last_query; - } - - if ($nativecode) { - $userinfo .= ' [nativecode=' . trim($nativecode) . ']'; - } - - $tmp = PEAR::raiseError(null, $code, $mode, $options, $userinfo, - 'DB_Error', true); - return $tmp; - } - - // }}} - // {{{ setFetchMode() - - /** - * Sets which fetch mode should be used by default on queries - * on this connection - * - * @param integer $fetchmode DB_FETCHMODE_ORDERED or - * DB_FETCHMODE_ASSOC, possibly bit-wise OR'ed with - * DB_FETCHMODE_FLIPPED. - * - * @param string $object_class The class of the object - * to be returned by the fetch methods when - * the DB_FETCHMODE_OBJECT mode is selected. - * If no class is specified by default a cast - * to object from the assoc array row will be done. - * There is also the posibility to use and extend the - * 'DB_row' class. - * - * @see DB_FETCHMODE_ORDERED - * @see DB_FETCHMODE_ASSOC - * @see DB_FETCHMODE_FLIPPED - * @see DB_FETCHMODE_OBJECT - * @see DB_row::DB_row() - * @access public - */ - function setFetchMode($fetchmode, $object_class = 'stdClass') - { - switch ($fetchmode) { - case DB_FETCHMODE_OBJECT: - $this->fetchmode_object_class = $object_class; - case DB_FETCHMODE_ORDERED: - case DB_FETCHMODE_ASSOC: - $this->fetchmode = $fetchmode; - break; - default: - return $this->raiseError('invalid fetchmode mode'); - } - } - - // }}} - // {{{ setOption() - - /** - * Set run-time configuration options for PEAR DB - * - * Options, their data types, default values and description: - *
    - *
  • - * autofree boolean = false - *
    should results be freed automatically when there are no - * more rows? - *
  • - * debug integer = 0 - *
    debug level - *
  • - * persistent boolean = false - *
    should the connection be persistent? - *
  • - * portability integer = DB_PORTABILITY_NONE - *
    portability mode constant (see below) - *
  • - * seqname_format string = %s_seq - *
    the sprintf() format string used on sequence names. This - * format is applied to sequence names passed to - * createSequence(), nextID() and dropSequence(). - *
  • - * ssl boolean = false - *
    use ssl to connect? - *
  • - *
- * - * ----------------------------------------- - * - * PORTABILITY MODES - * - * These modes are bitwised, so they can be combined using | - * and removed using ^. See the examples section below on how - * to do this. - * - * DB_PORTABILITY_NONE - * turn off all portability features - * - * This mode gets automatically turned on if the deprecated - * optimize option gets set to performance. - * - * - * DB_PORTABILITY_LOWERCASE - * convert names of tables and fields to lower case when using - * get*(), fetch*() and tableInfo() - * - * This mode gets automatically turned on in the following databases - * if the deprecated option optimize gets set to - * portability: - * + oci8 - * - * - * DB_PORTABILITY_RTRIM - * right trim the data output by get*() fetch*() - * - * - * DB_PORTABILITY_DELETE_COUNT - * force reporting the number of rows deleted - * - * Some DBMS's don't count the number of rows deleted when performing - * simple DELETE FROM tablename queries. This portability - * mode tricks such DBMS's into telling the count by adding - * WHERE 1=1 to the end of DELETE queries. - * - * This mode gets automatically turned on in the following databases - * if the deprecated option optimize gets set to - * portability: - * + fbsql - * + mysql - * + mysqli - * + sqlite - * - * - * DB_PORTABILITY_NUMROWS - * enable hack that makes numRows() work in Oracle - * - * This mode gets automatically turned on in the following databases - * if the deprecated option optimize gets set to - * portability: - * + oci8 - * - * - * DB_PORTABILITY_ERRORS - * makes certain error messages in certain drivers compatible - * with those from other DBMS's - * - * + mysql, mysqli: change unique/primary key constraints - * DB_ERROR_ALREADY_EXISTS -> DB_ERROR_CONSTRAINT - * - * + odbc(access): MS's ODBC driver reports 'no such field' as code - * 07001, which means 'too few parameters.' When this option is on - * that code gets mapped to DB_ERROR_NOSUCHFIELD. - * DB_ERROR_MISMATCH -> DB_ERROR_NOSUCHFIELD - * - * - * DB_PORTABILITY_NULL_TO_EMPTY - * convert null values to empty strings in data output by get*() and - * fetch*(). Needed because Oracle considers empty strings to be null, - * while most other DBMS's know the difference between empty and null. - * - * - * DB_PORTABILITY_ALL - * turn on all portability features - * - * ----------------------------------------- - * - * Example 1. Simple setOption() example - * setOption('autofree', true); - * ?> - * - * Example 2. Portability for lowercasing and trimming - * setOption('portability', - * DB_PORTABILITY_LOWERCASE | DB_PORTABILITY_RTRIM); - * ?> - * - * Example 3. All portability options except trimming - * setOption('portability', - * DB_PORTABILITY_ALL ^ DB_PORTABILITY_RTRIM); - * ?> - * - * @param string $option option name - * @param mixed $value value for the option - * - * @return int DB_OK on success. DB_Error object on failure. - * - * @see DB_common::$options - */ - function setOption($option, $value) - { - if (isset($this->options[$option])) { - $this->options[$option] = $value; - - /* - * Backwards compatibility check for the deprecated 'optimize' - * option. Done here in case settings change after connecting. - */ - if ($option == 'optimize') { - if ($value == 'portability') { - switch ($this->phptype) { - case 'oci8': - $this->options['portability'] = - DB_PORTABILITY_LOWERCASE | - DB_PORTABILITY_NUMROWS; - break; - case 'fbsql': - case 'mysql': - case 'mysqli': - case 'sqlite': - $this->options['portability'] = - DB_PORTABILITY_DELETE_COUNT; - break; - } - } else { - $this->options['portability'] = DB_PORTABILITY_NONE; - } - } - - return DB_OK; - } - return $this->raiseError("unknown option $option"); - } - - // }}} - // {{{ getOption() - - /** - * Returns the value of an option - * - * @param string $option option name - * - * @return mixed the option value - */ - function getOption($option) - { - if (isset($this->options[$option])) { - return $this->options[$option]; - } - return $this->raiseError("unknown option $option"); - } - - // }}} - // {{{ prepare() - - /** - * Prepares a query for multiple execution with execute() - * - * Creates a query that can be run multiple times. Each time it is run, - * the placeholders, if any, will be replaced by the contents of - * execute()'s $data argument. - * - * Three types of placeholders can be used: - * + ? scalar value (i.e. strings, integers). The system - * will automatically quote and escape the data. - * + ! value is inserted 'as is' - * + & requires a file name. The file's contents get - * inserted into the query (i.e. saving binary - * data in a db) - * - * Example 1. - * prepare('INSERT INTO tbl (a, b, c) VALUES (?, !, &)'); - * $data = array( - * "John's text", - * "'it''s good'", - * 'filename.txt' - * ); - * $res = $dbh->execute($sth, $data); - * ?> - * - * Use backslashes to escape placeholder characters if you don't want - * them to be interpreted as placeholders: - *
-     *    "UPDATE foo SET col=? WHERE col='over \& under'"
-     * 
- * - * With some database backends, this is emulated. - * - * {@internal ibase and oci8 have their own prepare() methods.}} - * - * @param string $query query to be prepared - * - * @return mixed DB statement resource on success. DB_Error on failure. - * - * @see DB_common::execute() - * @access public - */ - function prepare($query) - { - $tokens = preg_split('/((?prepare_tokens[] = &$newtokens; - end($this->prepare_tokens); - - $k = key($this->prepare_tokens); - $this->prepare_types[$k] = $types; - $this->prepared_queries[$k] = implode(' ', $newtokens); - - return $k; - } - - // }}} - // {{{ autoPrepare() - - /** - * Automaticaly generate an insert or update query and pass it to prepare() - * - * @param string $table name of the table - * @param array $table_fields ordered array containing the fields names - * @param int $mode type of query to make (DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE) - * @param string $where in case of update queries, this string will be put after the sql WHERE statement - * @return resource handle for the query - * @see DB_common::prepare(), DB_common::buildManipSQL() - * @access public - */ - function autoPrepare($table, $table_fields, $mode = DB_AUTOQUERY_INSERT, $where = false) - { - $query = $this->buildManipSQL($table, $table_fields, $mode, $where); - return $this->prepare($query); - } - - // }}} - // {{{ autoExecute() - - /** - * Automaticaly generate an insert or update query and call prepare() - * and execute() with it - * - * @param string $table name of the table - * @param array $fields_values assoc ($key=>$value) where $key is a field name and $value its value - * @param int $mode type of query to make (DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE) - * @param string $where in case of update queries, this string will be put after the sql WHERE statement - * @return mixed a new DB_Result or a DB_Error when fail - * @see DB_common::autoPrepare(), DB_common::buildManipSQL() - * @access public - */ - function autoExecute($table, $fields_values, $mode = DB_AUTOQUERY_INSERT, $where = false) - { - $sth = $this->autoPrepare($table, array_keys($fields_values), $mode, $where); - $ret =& $this->execute($sth, array_values($fields_values)); - $this->freePrepared($sth); - return $ret; - - } - - // }}} - // {{{ buildManipSQL() - - /** - * Make automaticaly an sql query for prepare() - * - * Example : buildManipSQL('table_sql', array('field1', 'field2', 'field3'), DB_AUTOQUERY_INSERT) - * will return the string : INSERT INTO table_sql (field1,field2,field3) VALUES (?,?,?) - * NB : - This belongs more to a SQL Builder class, but this is a simple facility - * - Be carefull ! If you don't give a $where param with an UPDATE query, all - * the records of the table will be updated ! - * - * @param string $table name of the table - * @param array $table_fields ordered array containing the fields names - * @param int $mode type of query to make (DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE) - * @param string $where in case of update queries, this string will be put after the sql WHERE statement - * @return string sql query for prepare() - * @access public - */ - function buildManipSQL($table, $table_fields, $mode, $where = false) - { - if (count($table_fields) == 0) { - $this->raiseError(DB_ERROR_NEED_MORE_DATA); - } - $first = true; - switch ($mode) { - case DB_AUTOQUERY_INSERT: - $values = ''; - $names = ''; - foreach ($table_fields as $value) { - if ($first) { - $first = false; - } else { - $names .= ','; - $values .= ','; - } - $names .= $value; - $values .= '?'; - } - return "INSERT INTO $table ($names) VALUES ($values)"; - case DB_AUTOQUERY_UPDATE: - $set = ''; - foreach ($table_fields as $value) { - if ($first) { - $first = false; - } else { - $set .= ','; - } - $set .= "$value = ?"; - } - $sql = "UPDATE $table SET $set"; - if ($where) { - $sql .= " WHERE $where"; - } - return $sql; - default: - $this->raiseError(DB_ERROR_SYNTAX); - } - } - - // }}} - // {{{ execute() - - /** - * Executes a DB statement prepared with prepare() - * - * Example 1. - * prepare('INSERT INTO tbl (a, b, c) VALUES (?, !, &)'); - * $data = array( - * "John's text", - * "'it''s good'", - * 'filename.txt' - * ); - * $res =& $dbh->execute($sth, $data); - * ?> - * - * @param resource $stmt a DB statement resource returned from prepare() - * @param mixed $data array, string or numeric data to be used in - * execution of the statement. Quantity of items - * passed must match quantity of placeholders in - * query: meaning 1 placeholder for non-array - * parameters or 1 placeholder per array element. - * - * @return object a new DB_Result or a DB_Error when fail - * - * {@internal ibase and oci8 have their own execute() methods.}} - * - * @see DB_common::prepare() - * @access public - */ - function &execute($stmt, $data = array()) - { - $realquery = $this->executeEmulateQuery($stmt, $data); - if (DB::isError($realquery)) { - return $realquery; - } - $result = $this->simpleQuery($realquery); - - if (DB::isError($result) || $result === DB_OK) { - return $result; - } else { - $tmp =& new DB_result($this, $result); - return $tmp; - } - } - - // }}} - // {{{ executeEmulateQuery() - - /** - * Emulates the execute statement, when not supported - * - * @param resource $stmt a DB statement resource returned from execute() - * @param mixed $data array, string or numeric data to be used in - * execution of the statement. Quantity of items - * passed must match quantity of placeholders in - * query: meaning 1 placeholder for non-array - * parameters or 1 placeholder per array element. - * - * @return mixed a string containing the real query run when emulating - * prepare/execute. A DB error code is returned on failure. - * - * @see DB_common::execute() - * @access private - */ - function executeEmulateQuery($stmt, $data = array()) - { - $stmt = (int)$stmt; - if (!is_array($data)) { - $data = array($data); - } - - if (count($this->prepare_types[$stmt]) != count($data)) { - $this->last_query = $this->prepared_queries[$stmt]; - return $this->raiseError(DB_ERROR_MISMATCH); - } - - $realquery = $this->prepare_tokens[$stmt][0]; - - $i = 0; - foreach ($data as $value) { - if ($this->prepare_types[$stmt][$i] == DB_PARAM_SCALAR) { - $realquery .= $this->quoteSmart($value); - } elseif ($this->prepare_types[$stmt][$i] == DB_PARAM_OPAQUE) { - $fp = @fopen($value, 'rb'); - if (!$fp) { - return $this->raiseError(DB_ERROR_ACCESS_VIOLATION); - } - $realquery .= $this->quoteSmart(fread($fp, filesize($value))); - fclose($fp); - } else { - $realquery .= $value; - } - - $realquery .= $this->prepare_tokens[$stmt][++$i]; - } - - return $realquery; - } - - // }}} - // {{{ executeMultiple() - - /** - * This function does several execute() calls on the same - * statement handle - * - * $data must be an array indexed numerically - * from 0, one execute call is done for every "row" in the array. - * - * If an error occurs during execute(), executeMultiple() does not - * execute the unfinished rows, but rather returns that error. - * - * @param resource $stmt query handle from prepare() - * @param array $data numeric array containing the - * data to insert into the query - * - * @return mixed DB_OK or DB_Error - * - * @see DB_common::prepare(), DB_common::execute() - * @access public - */ - function executeMultiple($stmt, $data) - { - foreach ($data as $value) { - $res =& $this->execute($stmt, $value); - if (DB::isError($res)) { - return $res; - } - } - return DB_OK; - } - - // }}} - // {{{ freePrepared() - - /** - * Free the resource used in a prepared query - * - * @param $stmt The resurce returned by the prepare() function - * @see DB_common::prepare() - */ - function freePrepared($stmt) - { - $stmt = (int)$stmt; - // Free the internal prepared vars - if (isset($this->prepare_tokens[$stmt])) { - unset($this->prepare_tokens[$stmt]); - unset($this->prepare_types[$stmt]); - unset($this->prepared_queries[$stmt]); - return true; - } - return false; - } - - // }}} - // {{{ modifyQuery() - - /** - * This method is used by backends to alter queries for various - * reasons - * - * It is defined here to assure that all implementations - * have this method defined. - * - * @param string $query query to modify - * - * @return the new (modified) query - * - * @access private - */ - function modifyQuery($query) { - return $query; - } - - // }}} - // {{{ modifyLimitQuery() - - /** - * This method is used by backends to alter limited queries - * - * @param string $query query to modify - * @param integer $from the row to start to fetching - * @param integer $count the numbers of rows to fetch - * - * @return the new (modified) query - * - * @access private - */ - function modifyLimitQuery($query, $from, $count, $params = array()) - { - return $query; - } - - // }}} - // {{{ query() - - /** - * Send a query to the database and return any results with a - * DB_result object - * - * The query string can be either a normal statement to be sent directly - * to the server OR if $params are passed the query can have - * placeholders and it will be passed through prepare() and execute(). - * - * @param string $query the SQL query or the statement to prepare - * @param mixed $params array, string or numeric data to be used in - * execution of the statement. Quantity of items - * passed must match quantity of placeholders in - * query: meaning 1 placeholder for non-array - * parameters or 1 placeholder per array element. - * - * @return mixed a DB_result object or DB_OK on success, a DB - * error on failure - * - * @see DB_result, DB_common::prepare(), DB_common::execute() - * @access public - */ - function &query($query, $params = array()) - { - if (sizeof($params) > 0) { - $sth = $this->prepare($query); - if (DB::isError($sth)) { - return $sth; - } - $ret =& $this->execute($sth, $params); - $this->freePrepared($sth); - return $ret; - } else { - $result = $this->simpleQuery($query); - if (DB::isError($result) || $result === DB_OK) { - return $result; - } else { - $tmp =& new DB_result($this, $result); - return $tmp; - } - } - } - - // }}} - // {{{ limitQuery() - - /** - * Generates a limited query - * - * @param string $query query - * @param integer $from the row to start to fetching - * @param integer $count the numbers of rows to fetch - * @param mixed $params array, string or numeric data to be used in - * execution of the statement. Quantity of items - * passed must match quantity of placeholders in - * query: meaning 1 placeholder for non-array - * parameters or 1 placeholder per array element. - * - * @return mixed a DB_Result object, DB_OK or a DB_Error - * - * @access public - */ - function &limitQuery($query, $from, $count, $params = array()) - { - $query = $this->modifyLimitQuery($query, $from, $count, $params); - if (DB::isError($query)){ - return $query; - } - $result =& $this->query($query, $params); - if (is_a($result, 'DB_result')) { - $result->setOption('limit_from', $from); - $result->setOption('limit_count', $count); - } - return $result; - } - - // }}} - // {{{ getOne() - - /** - * Fetch the first column of the first row of data returned from - * a query - * - * Takes care of doing the query and freeing the results when finished. - * - * @param string $query the SQL query - * @param mixed $params array, string or numeric data to be used in - * execution of the statement. Quantity of items - * passed must match quantity of placeholders in - * query: meaning 1 placeholder for non-array - * parameters or 1 placeholder per array element. - * - * @return mixed the returned value of the query. DB_Error on failure. - * - * @access public - */ - function &getOne($query, $params = array()) - { - settype($params, 'array'); - if (sizeof($params) > 0) { - $sth = $this->prepare($query); - if (DB::isError($sth)) { - return $sth; - } - $res =& $this->execute($sth, $params); - $this->freePrepared($sth); - } else { - $res =& $this->query($query); - } - - if (DB::isError($res)) { - return $res; - } - - $err = $res->fetchInto($row, DB_FETCHMODE_ORDERED); - $res->free(); - - if ($err !== DB_OK) { - return $err; - } - - return $row[0]; - } - - // }}} - // {{{ getRow() - - /** - * Fetch the first row of data returned from a query - * - * Takes care of doing the query and freeing the results when finished. - * - * @param string $query the SQL query - * @param array $params array to be used in execution of the statement. - * Quantity of array elements must match quantity - * of placeholders in query. This function does - * NOT support scalars. - * @param int $fetchmode the fetch mode to use - * - * @return array the first row of results as an array indexed from - * 0, or a DB error code. - * - * @access public - */ - function &getRow($query, - $params = array(), - $fetchmode = DB_FETCHMODE_DEFAULT) - { - // compat check, the params and fetchmode parameters used to - // have the opposite order - if (!is_array($params)) { - if (is_array($fetchmode)) { - if ($params === null) { - $tmp = DB_FETCHMODE_DEFAULT; - } else { - $tmp = $params; - } - $params = $fetchmode; - $fetchmode = $tmp; - } elseif ($params !== null) { - $fetchmode = $params; - $params = array(); - } - } - - if (sizeof($params) > 0) { - $sth = $this->prepare($query); - if (DB::isError($sth)) { - return $sth; - } - $res =& $this->execute($sth, $params); - $this->freePrepared($sth); - } else { - $res =& $this->query($query); - } - - if (DB::isError($res)) { - return $res; - } - - $err = $res->fetchInto($row, $fetchmode); - - $res->free(); - - if ($err !== DB_OK) { - return $err; - } - - return $row; - } - - // }}} - // {{{ getCol() - - /** - * Fetch a single column from a result set and return it as an - * indexed array - * - * @param string $query the SQL query - * @param mixed $col which column to return (integer [column number, - * starting at 0] or string [column name]) - * @param mixed $params array, string or numeric data to be used in - * execution of the statement. Quantity of items - * passed must match quantity of placeholders in - * query: meaning 1 placeholder for non-array - * parameters or 1 placeholder per array element. - * - * @return array an indexed array with the data from the first - * row at index 0, or a DB error code - * - * @see DB_common::query() - * @access public - */ - function &getCol($query, $col = 0, $params = array()) - { - settype($params, 'array'); - if (sizeof($params) > 0) { - $sth = $this->prepare($query); - - if (DB::isError($sth)) { - return $sth; - } - - $res =& $this->execute($sth, $params); - $this->freePrepared($sth); - } else { - $res =& $this->query($query); - } - - if (DB::isError($res)) { - return $res; - } - - $fetchmode = is_int($col) ? DB_FETCHMODE_ORDERED : DB_FETCHMODE_ASSOC; - - if (!is_array($row = $res->fetchRow($fetchmode))) { - $ret = array(); - } else { - if (!array_key_exists($col, $row)) { - $ret =& $this->raiseError(DB_ERROR_NOSUCHFIELD); - } else { - $ret = array($row[$col]); - while (is_array($row = $res->fetchRow($fetchmode))) { - $ret[] = $row[$col]; - } - } - } - - $res->free(); - - if (DB::isError($row)) { - $ret = $row; - } - - return $ret; - } - - // }}} - // {{{ getAssoc() - - /** - * Fetch the entire result set of a query and return it as an - * associative array using the first column as the key - * - * If the result set contains more than two columns, the value - * will be an array of the values from column 2-n. If the result - * set contains only two columns, the returned value will be a - * scalar with the value of the second column (unless forced to an - * array with the $force_array parameter). A DB error code is - * returned on errors. If the result set contains fewer than two - * columns, a DB_ERROR_TRUNCATED error is returned. - * - * For example, if the table "mytable" contains: - * - *
-     *  ID      TEXT       DATE
-     * --------------------------------
-     *  1       'one'      944679408
-     *  2       'two'      944679408
-     *  3       'three'    944679408
-     * 
- * - * Then the call getAssoc('SELECT id,text FROM mytable') returns: - *
-     *   array(
-     *     '1' => 'one',
-     *     '2' => 'two',
-     *     '3' => 'three',
-     *   )
-     * 
- * - * ...while the call getAssoc('SELECT id,text,date FROM mytable') returns: - *
-     *   array(
-     *     '1' => array('one', '944679408'),
-     *     '2' => array('two', '944679408'),
-     *     '3' => array('three', '944679408')
-     *   )
-     * 
- * - * If the more than one row occurs with the same value in the - * first column, the last row overwrites all previous ones by - * default. Use the $group parameter if you don't want to - * overwrite like this. Example: - * - *
-     * getAssoc('SELECT category,id,name FROM mytable', false, null,
-     *          DB_FETCHMODE_ASSOC, true) returns:
-     *
-     *   array(
-     *     '1' => array(array('id' => '4', 'name' => 'number four'),
-     *                  array('id' => '6', 'name' => 'number six')
-     *            ),
-     *     '9' => array(array('id' => '4', 'name' => 'number four'),
-     *                  array('id' => '6', 'name' => 'number six')
-     *            )
-     *   )
-     * 
- * - * Keep in mind that database functions in PHP usually return string - * values for results regardless of the database's internal type. - * - * @param string $query the SQL query - * @param boolean $force_array used only when the query returns - * exactly two columns. If true, the values - * of the returned array will be one-element - * arrays instead of scalars. - * @param mixed $params array, string or numeric data to be used in - * execution of the statement. Quantity of items - * passed must match quantity of placeholders in - * query: meaning 1 placeholder for non-array - * parameters or 1 placeholder per array element. - * @param int $fetchmode the fetch mode to use - * @param boolean $group if true, the values of the returned array - * is wrapped in another array. If the same - * key value (in the first column) repeats - * itself, the values will be appended to - * this array instead of overwriting the - * existing values. - * - * @return array associative array with results from the query. - * DB Error on failure. - * - * @access public - */ - function &getAssoc($query, $force_array = false, $params = array(), - $fetchmode = DB_FETCHMODE_DEFAULT, $group = false) - { - settype($params, 'array'); - if (sizeof($params) > 0) { - $sth = $this->prepare($query); - - if (DB::isError($sth)) { - return $sth; - } - - $res =& $this->execute($sth, $params); - $this->freePrepared($sth); - } else { - $res =& $this->query($query); - } - - if (DB::isError($res)) { - return $res; - } - if ($fetchmode == DB_FETCHMODE_DEFAULT) { - $fetchmode = $this->fetchmode; - } - $cols = $res->numCols(); - - if ($cols < 2) { - $tmp =& $this->raiseError(DB_ERROR_TRUNCATED); - return $tmp; - } - - $results = array(); - - if ($cols > 2 || $force_array) { - // return array values - // XXX this part can be optimized - if ($fetchmode == DB_FETCHMODE_ASSOC) { - while (is_array($row = $res->fetchRow(DB_FETCHMODE_ASSOC))) { - reset($row); - $key = current($row); - unset($row[key($row)]); - if ($group) { - $results[$key][] = $row; - } else { - $results[$key] = $row; - } - } - } elseif ($fetchmode == DB_FETCHMODE_OBJECT) { - while ($row = $res->fetchRow(DB_FETCHMODE_OBJECT)) { - $arr = get_object_vars($row); - $key = current($arr); - if ($group) { - $results[$key][] = $row; - } else { - $results[$key] = $row; - } - } - } else { - while (is_array($row = $res->fetchRow(DB_FETCHMODE_ORDERED))) { - // we shift away the first element to get - // indices running from 0 again - $key = array_shift($row); - if ($group) { - $results[$key][] = $row; - } else { - $results[$key] = $row; - } - } - } - if (DB::isError($row)) { - $results = $row; - } - } else { - // return scalar values - while (is_array($row = $res->fetchRow(DB_FETCHMODE_ORDERED))) { - if ($group) { - $results[$row[0]][] = $row[1]; - } else { - $results[$row[0]] = $row[1]; - } - } - if (DB::isError($row)) { - $results = $row; - } - } - - $res->free(); - - return $results; - } - - // }}} - // {{{ getAll() - - /** - * Fetch all the rows returned from a query - * - * @param string $query the SQL query - * @param array $params array to be used in execution of the statement. - * Quantity of array elements must match quantity - * of placeholders in query. This function does - * NOT support scalars. - * @param int $fetchmode the fetch mode to use - * - * @return array an nested array. DB error on failure. - * - * @access public - */ - function &getAll($query, - $params = array(), - $fetchmode = DB_FETCHMODE_DEFAULT) - { - // compat check, the params and fetchmode parameters used to - // have the opposite order - if (!is_array($params)) { - if (is_array($fetchmode)) { - if ($params === null) { - $tmp = DB_FETCHMODE_DEFAULT; - } else { - $tmp = $params; - } - $params = $fetchmode; - $fetchmode = $tmp; - } elseif ($params !== null) { - $fetchmode = $params; - $params = array(); - } - } - - if (sizeof($params) > 0) { - $sth = $this->prepare($query); - - if (DB::isError($sth)) { - return $sth; - } - - $res =& $this->execute($sth, $params); - $this->freePrepared($sth); - } else { - $res =& $this->query($query); - } - - if (DB::isError($res) || $res === DB_OK) { - return $res; - } - - $results = array(); - while (DB_OK === $res->fetchInto($row, $fetchmode)) { - if ($fetchmode & DB_FETCHMODE_FLIPPED) { - foreach ($row as $key => $val) { - $results[$key][] = $val; - } - } else { - $results[] = $row; - } - } - - $res->free(); - - if (DB::isError($row)) { - $tmp =& $this->raiseError($row); - return $tmp; - } - return $results; - } - - // }}} - // {{{ autoCommit() - - /** - * enable automatic Commit - * - * @param boolean $onoff - * @return mixed DB_Error - * - * @access public - */ - function autoCommit($onoff=false) - { - return $this->raiseError(DB_ERROR_NOT_CAPABLE); - } - - // }}} - // {{{ commit() - - /** - * starts a Commit - * - * @return mixed DB_Error - * - * @access public - */ - function commit() - { - return $this->raiseError(DB_ERROR_NOT_CAPABLE); - } - - // }}} - // {{{ rollback() - - /** - * starts a rollback - * - * @return mixed DB_Error - * - * @access public - */ - function rollback() - { - return $this->raiseError(DB_ERROR_NOT_CAPABLE); - } - - // }}} - // {{{ numRows() - - /** - * Returns the number of rows in a result object - * - * @param object DB_Result the result object to check - * - * @return mixed DB_Error or the number of rows - * - * @access public - */ - function numRows($result) - { - return $this->raiseError(DB_ERROR_NOT_CAPABLE); - } - - // }}} - // {{{ affectedRows() - - /** - * Returns the affected rows of a query - * - * @return mixed DB_Error or number of rows - * - * @access public - */ - function affectedRows() - { - return $this->raiseError(DB_ERROR_NOT_CAPABLE); - } - - // }}} - // {{{ errorNative() - - /** - * Returns an errormessage, provides by the database - * - * @return mixed DB_Error or message - * - * @access public - */ - function errorNative() - { - return $this->raiseError(DB_ERROR_NOT_CAPABLE); - } - - // }}} - // {{{ getSequenceName() - - /** - * Generate the name used inside the database for a sequence - * - * The createSequence() docblock contains notes about storing sequence - * names. - * - * @param string $sqn the sequence's public name - * - * @return string the sequence's name in the backend - * - * @see DB_common::createSequence(), DB_common::dropSequence(), - * DB_common::nextID(), DB_common::setOption() - * @access private - */ - function getSequenceName($sqn) - { - return sprintf($this->getOption('seqname_format'), - preg_replace('/[^a-z0-9_.]/i', '_', $sqn)); - } - - // }}} - // {{{ nextId() - - /** - * Returns the next free id in a sequence - * - * @param string $seq_name name of the sequence - * @param boolean $ondemand when true, the seqence is automatically - * created if it does not exist - * - * @return int the next id number in the sequence. DB_Error if problem. - * - * @see DB_common::createSequence(), DB_common::dropSequence(), - * DB_common::getSequenceName() - * @access public - */ - function nextId($seq_name, $ondemand = true) - { - return $this->raiseError(DB_ERROR_NOT_CAPABLE); - } - - // }}} - // {{{ createSequence() - - /** - * Creates a new sequence - * - * The name of a given sequence is determined by passing the string - * provided in the $seq_name argument through PHP's sprintf() - * function using the value from the seqname_format option as - * the sprintf()'s format argument. - * - * seqname_format is set via setOption(). - * - * @param string $seq_name name of the new sequence - * - * @return int DB_OK on success. A DB_Error object is returned if - * problems arise. - * - * @see DB_common::dropSequence(), DB_common::getSequenceName(), - * DB_common::nextID() - * @access public - */ - function createSequence($seq_name) - { - return $this->raiseError(DB_ERROR_NOT_CAPABLE); - } - - // }}} - // {{{ dropSequence() - - /** - * Deletes a sequence - * - * @param string $seq_name name of the sequence to be deleted - * - * @return int DB_OK on success. DB_Error if problems. - * - * @see DB_common::createSequence(), DB_common::getSequenceName(), - * DB_common::nextID() - * @access public - */ - function dropSequence($seq_name) - { - return $this->raiseError(DB_ERROR_NOT_CAPABLE); - } - - // }}} - // {{{ tableInfo() - - /** - * Returns information about a table or a result set - * - * The format of the resulting array depends on which $mode - * you select. The sample output below is based on this query: - *
-     *    SELECT tblFoo.fldID, tblFoo.fldPhone, tblBar.fldId
-     *    FROM tblFoo
-     *    JOIN tblBar ON tblFoo.fldId = tblBar.fldId
-     * 
- * - *
    - *
  • - * - * null (default) - *
    -     *   [0] => Array (
    -     *       [table] => tblFoo
    -     *       [name] => fldId
    -     *       [type] => int
    -     *       [len] => 11
    -     *       [flags] => primary_key not_null
    -     *   )
    -     *   [1] => Array (
    -     *       [table] => tblFoo
    -     *       [name] => fldPhone
    -     *       [type] => string
    -     *       [len] => 20
    -     *       [flags] =>
    -     *   )
    -     *   [2] => Array (
    -     *       [table] => tblBar
    -     *       [name] => fldId
    -     *       [type] => int
    -     *       [len] => 11
    -     *       [flags] => primary_key not_null
    -     *   )
    -     *   
    - * - *
  • - * - * DB_TABLEINFO_ORDER - * - *

    In addition to the information found in the default output, - * a notation of the number of columns is provided by the - * num_fields element while the order - * element provides an array with the column names as the keys and - * their location index number (corresponding to the keys in the - * the default output) as the values.

    - * - *

    If a result set has identical field names, the last one is - * used.

    - * - *
    -     *   [num_fields] => 3
    -     *   [order] => Array (
    -     *       [fldId] => 2
    -     *       [fldTrans] => 1
    -     *   )
    -     *   
    - * - *
  • - * - * DB_TABLEINFO_ORDERTABLE - * - *

    Similar to DB_TABLEINFO_ORDER but adds more - * dimensions to the array in which the table names are keys and - * the field names are sub-keys. This is helpful for queries that - * join tables which have identical field names.

    - * - *
    -     *   [num_fields] => 3
    -     *   [ordertable] => Array (
    -     *       [tblFoo] => Array (
    -     *           [fldId] => 0
    -     *           [fldPhone] => 1
    -     *       )
    -     *       [tblBar] => Array (
    -     *           [fldId] => 2
    -     *       )
    -     *   )
    -     *   
    - * - *
  • - *
- * - * The flags element contains a space separated list - * of extra information about the field. This data is inconsistent - * between DBMS's due to the way each DBMS works. - * + primary_key - * + unique_key - * + multiple_key - * + not_null - * - * Most DBMS's only provide the table and flags - * elements if $result is a table name. The following DBMS's - * provide full information from queries: - * + fbsql - * + mysql - * - * If the 'portability' option has DB_PORTABILITY_LOWERCASE - * turned on, the names of tables and fields will be lowercased. - * - * @param object|string $result DB_result object from a query or a - * string containing the name of a table. - * While this also accepts a query result - * resource identifier, this behavior is - * deprecated. - * @param int $mode either unused or one of the tableInfo modes: - * DB_TABLEINFO_ORDERTABLE, - * DB_TABLEINFO_ORDER or - * DB_TABLEINFO_FULL (which does both). - * These are bitwise, so the first two can be - * combined using |. - * @return array an associative array with the information requested. - * If something goes wrong an error object is returned. - * - * @see DB_common::setOption() - * @access public - */ - function tableInfo($result, $mode = null) - { - /* - * If the DB_ class has a tableInfo() method, that one - * overrides this one. But, if the driver doesn't have one, - * this method runs and tells users about that fact. - */ - return $this->raiseError(DB_ERROR_NOT_CAPABLE); - } - - // }}} - // {{{ getTables() - - /** - * @deprecated Deprecated in release 1.2 or lower - */ - function getTables() - { - return $this->getListOf('tables'); - } - - // }}} - // {{{ getListOf() - - /** - * list internal DB info - * valid values for $type are db dependent, - * often: databases, users, view, functions - * - * @param string $type type of requested info - * - * @return mixed DB_Error or the requested data - * - * @access public - */ - function getListOf($type) - { - $sql = $this->getSpecialQuery($type); - if ($sql === null) { // No support - return $this->raiseError(DB_ERROR_UNSUPPORTED); - } elseif (is_int($sql) || DB::isError($sql)) { // Previous error - return $this->raiseError($sql); - } elseif (is_array($sql)) { // Already the result - return $sql; - } - return $this->getCol($sql); // Launch this query - } - - // }}} - // {{{ getSpecialQuery() - - /** - * Returns the query needed to get some backend info - * - * @param string $type What kind of info you want to retrieve - * - * @return string The SQL query string - * - * @access public - */ - function getSpecialQuery($type) - { - return $this->raiseError(DB_ERROR_UNSUPPORTED); - } - - // }}} - // {{{ _rtrimArrayValues() - - /** - * Right trim all strings in an array - * - * @param array $array the array to be trimmed (passed by reference) - * @return void - * @access private - */ - function _rtrimArrayValues(&$array) - { - foreach ($array as $key => $value) { - if (is_string($value)) { - $array[$key] = rtrim($value); - } - } - } - - // }}} - // {{{ _convertNullArrayValuesToEmpty() - - /** - * Convert all null values in an array to empty strings - * - * @param array $array the array to be de-nullified (passed by reference) - * @return void - * @access private - */ - function _convertNullArrayValuesToEmpty(&$array) - { - foreach ($array as $key => $value) { - if (is_null($value)) { - $array[$key] = ''; - } - } - } - - // }}} -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - */ - -?> diff --git a/gulliver/thirdparty/pear/DB/dbase.php b/gulliver/thirdparty/pear/DB/dbase.php deleted file mode 100644 index 89b27a16d..000000000 --- a/gulliver/thirdparty/pear/DB/dbase.php +++ /dev/null @@ -1,225 +0,0 @@ - | -// | Maintainer: Daniel Convissor | -// +----------------------------------------------------------------------+ -// -// $Id: dbase.php 3355 2005-06-11 22:14:40Z nbm $ - - -// XXX legend: -// You have to compile your PHP with the --enable-dbase option - - -require_once 'DB/common.php'; - -/** - * Database independent query interface definition for PHP's dbase - * extension. - * - * @package DB - * @version $Id: dbase.php 3355 2005-06-11 22:14:40Z nbm $ - * @category Database - * @author Stig Bakken - */ -class DB_dbase extends DB_common -{ - // {{{ properties - - var $connection; - var $phptype, $dbsyntax; - var $prepare_tokens = array(); - var $prepare_types = array(); - var $res_row = array(); - var $result = 0; - - // }}} - // {{{ constructor - - /** - * DB_mysql constructor. - * - * @access public - */ - function DB_dbase() - { - $this->DB_common(); - $this->phptype = 'dbase'; - $this->dbsyntax = 'dbase'; - $this->features = array( - 'prepare' => false, - 'pconnect' => false, - 'transactions' => false, - 'limit' => false - ); - $this->errorcode_map = array(); - } - - // }}} - // {{{ connect() - - function connect($dsninfo, $persistent = false) - { - if (!DB::assertExtension('dbase')) { - return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND); - } - $this->dsn = $dsninfo; - - $ini = ini_get('track_errors'); - if ($ini) { - $conn = @dbase_open($dsninfo['database'], 0); - } else { - ini_set('track_errors', 1); - $conn = @dbase_open($dsninfo['database'], 0); - ini_set('track_errors', $ini); - } - if (!$conn) { - return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, - null, null, strip_tags($php_errormsg)); - } - $this->connection = $conn; - return DB_OK; - } - - // }}} - // {{{ disconnect() - - function disconnect() - { - $ret = @dbase_close($this->connection); - $this->connection = null; - return $ret; - } - - // }}} - // {{{ &query() - - function &query($query = null) - { - // emulate result resources - $this->res_row[(int)$this->result] = 0; - $tmp =& new DB_result($this, $this->result++); - return $tmp; - } - - // }}} - // {{{ fetchInto() - - /** - * Fetch a row and insert the data into an existing array. - * - * Formating of the array and the data therein are configurable. - * See DB_result::fetchInto() for more information. - * - * @param resource $result query result identifier - * @param array $arr (reference) array where data from the row - * should be placed - * @param int $fetchmode how the resulting array should be indexed - * @param int $rownum the row number to fetch - * - * @return mixed DB_OK on success, null when end of result set is - * reached or on failure - * - * @see DB_result::fetchInto() - * @access private - */ - function fetchInto($result, &$arr, $fetchmode, $rownum=null) - { - if ($rownum === null) { - $rownum = $this->res_row[(int)$result]++; - } - if ($fetchmode & DB_FETCHMODE_ASSOC) { - $arr = @dbase_get_record_with_names($this->connection, $rownum); - if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) { - $arr = array_change_key_case($arr, CASE_LOWER); - } - } else { - $arr = @dbase_get_record($this->connection, $rownum); - } - if (!$arr) { - return null; - } - if ($this->options['portability'] & DB_PORTABILITY_RTRIM) { - $this->_rtrimArrayValues($arr); - } - if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) { - $this->_convertNullArrayValuesToEmpty($arr); - } - return DB_OK; - } - - // }}} - // {{{ numCols() - - function numCols($foo) - { - return @dbase_numfields($this->connection); - } - - // }}} - // {{{ numRows() - - function numRows($foo) - { - return @dbase_numrecords($this->connection); - } - - // }}} - // {{{ quoteSmart() - - /** - * Format input so it can be safely used in a query - * - * @param mixed $in data to be quoted - * - * @return mixed Submitted variable's type = returned value: - * + null = the string NULL - * + boolean = T if true or - * F if false. Use the Logical - * data type. - * + integer or double = the unquoted number - * + other (including strings and numeric strings) = - * the data with single quotes escaped by preceeding - * single quotes then the whole string is encapsulated - * between single quotes - * - * @internal - */ - function quoteSmart($in) - { - if (is_int($in) || is_double($in)) { - return $in; - } elseif (is_bool($in)) { - return $in ? 'T' : 'F'; - } elseif (is_null($in)) { - return 'NULL'; - } else { - return "'" . $this->escapeSimple($in) . "'"; - } - } - - // }}} - -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - */ - -?> diff --git a/gulliver/thirdparty/pear/DB/fbsql.php b/gulliver/thirdparty/pear/DB/fbsql.php deleted file mode 100644 index 540580a79..000000000 --- a/gulliver/thirdparty/pear/DB/fbsql.php +++ /dev/null @@ -1,655 +0,0 @@ - | -// | Maintainer: Daniel Convissor | -// +----------------------------------------------------------------------+ -// -// $Id: fbsql.php 3355 2005-06-11 22:14:40Z nbm $ - - -// XXX legend: -// -// XXX ERRORMSG: The error message from the fbsql function should -// be registered here. -// -// TODO/wishlist: -// longReadlen -// binmode - - -require_once 'DB/common.php'; - -/** - * Database independent query interface definition for PHP's FrontBase - * extension. - * - * @package DB - * @version $Id: fbsql.php 3355 2005-06-11 22:14:40Z nbm $ - * @category Database - * @author Frank M. Kromann - */ -class DB_fbsql extends DB_common -{ - // {{{ properties - - var $connection; - var $phptype, $dbsyntax; - var $prepare_tokens = array(); - var $prepare_types = array(); - var $num_rows = array(); - var $fetchmode = DB_FETCHMODE_ORDERED; /* Default fetch mode */ - - // }}} - // {{{ constructor - - /** - * DB_fbsql constructor. - * - * @access public - */ - function DB_fbsql() - { - $this->DB_common(); - $this->phptype = 'fbsql'; - $this->dbsyntax = 'fbsql'; - $this->features = array( - 'prepare' => false, - 'pconnect' => true, - 'transactions' => true, - 'limit' => 'emulate' - ); - $this->errorcode_map = array( - 1004 => DB_ERROR_CANNOT_CREATE, - 1005 => DB_ERROR_CANNOT_CREATE, - 1006 => DB_ERROR_CANNOT_CREATE, - 1007 => DB_ERROR_ALREADY_EXISTS, - 1008 => DB_ERROR_CANNOT_DROP, - 1046 => DB_ERROR_NODBSELECTED, - 1050 => DB_ERROR_ALREADY_EXISTS, - 1051 => DB_ERROR_NOSUCHTABLE, - 1054 => DB_ERROR_NOSUCHFIELD, - 1062 => DB_ERROR_ALREADY_EXISTS, - 1064 => DB_ERROR_SYNTAX, - 1100 => DB_ERROR_NOT_LOCKED, - 1136 => DB_ERROR_VALUE_COUNT_ON_ROW, - 1146 => DB_ERROR_NOSUCHTABLE, - ); - } - - // }}} - // {{{ connect() - - /** - * Connect to a database and log in as the specified user. - * - * @param $dsn the data source name (see DB::parseDSN for syntax) - * @param $persistent (optional) whether the connection should - * be persistent - * @access public - * @return int DB_OK on success, a DB error on failure - */ - function connect($dsninfo, $persistent = false) - { - if (!DB::assertExtension('fbsql')) { - return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND); - } - - $this->dsn = $dsninfo; - $dbhost = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost'; - - $php_errormsg = ''; - $connect_function = $persistent ? 'fbsql_pconnect' : 'fbsql_connect'; - - if ($dbhost && $dsninfo['username'] && $dsninfo['password']) { - $conn = @$connect_function($dbhost, $dsninfo['username'], - $dsninfo['password']); - } elseif ($dbhost && $dsninfo['username']) { - $conn = @$connect_function($dbhost, $dsninfo['username']); - } elseif ($dbhost) { - $conn = @$connect_function($dbhost); - } else { - $conn = false; - } - if (!$conn) { - if (empty($php_errormsg)) { - return $this->raiseError(DB_ERROR_CONNECT_FAILED); - } else { - return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null, - null, $php_errormsg); - } - } - - if ($dsninfo['database']) { - if (!fbsql_select_db($dsninfo['database'], $conn)) { - return $this->fbsqlRaiseError(); - } - } - - $this->connection = $conn; - return DB_OK; - } - - // }}} - // {{{ disconnect() - - /** - * Log out and disconnect from the database. - * - * @access public - * - * @return bool true on success, false if not connected. - */ - function disconnect() - { - $ret = @fbsql_close($this->connection); - $this->connection = null; - return $ret; - } - - // }}} - // {{{ simpleQuery() - - /** - * Send a query to fbsql and return the results as a fbsql resource - * identifier. - * - * @param the SQL query - * - * @access public - * - * @return mixed returns a valid fbsql result for successful SELECT - * queries, DB_OK for other successful queries. A DB error is - * returned on failure. - */ - function simpleQuery($query) - { - $this->last_query = $query; - $query = $this->modifyQuery($query); - $result = @fbsql_query("$query;", $this->connection); - if (!$result) { - return $this->fbsqlRaiseError(); - } - // Determine which queries that should return data, and which - // should return an error code only. - if (DB::isManip($query)) { - return DB_OK; - } - $numrows = $this->numrows($result); - if (is_object($numrows)) { - return $numrows; - } - $this->num_rows[(int)$result] = $numrows; - return $result; - } - - // }}} - // {{{ nextResult() - - /** - * Move the internal fbsql result pointer to the next available result - * - * @param a valid fbsql result resource - * - * @access public - * - * @return true if a result is available otherwise return false - */ - function nextResult($result) - { - return @fbsql_next_result($result); - } - - // }}} - // {{{ fetchInto() - - /** - * Fetch a row and insert the data into an existing array. - * - * Formating of the array and the data therein are configurable. - * See DB_result::fetchInto() for more information. - * - * @param resource $result query result identifier - * @param array $arr (reference) array where data from the row - * should be placed - * @param int $fetchmode how the resulting array should be indexed - * @param int $rownum the row number to fetch - * - * @return mixed DB_OK on success, null when end of result set is - * reached or on failure - * - * @see DB_result::fetchInto() - * @access private - */ - function fetchInto($result, &$arr, $fetchmode, $rownum=null) - { - if ($rownum !== null) { - if (!@fbsql_data_seek($result, $rownum)) { - return null; - } - } - if ($fetchmode & DB_FETCHMODE_ASSOC) { - $arr = @fbsql_fetch_array($result, FBSQL_ASSOC); - if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) { - $arr = array_change_key_case($arr, CASE_LOWER); - } - } else { - $arr = @fbsql_fetch_row($result); - } - if (!$arr) { - $errno = @fbsql_errno($this->connection); - if (!$errno) { - return null; - } - return $this->fbsqlRaiseError($errno); - } - if ($this->options['portability'] & DB_PORTABILITY_RTRIM) { - $this->_rtrimArrayValues($arr); - } - if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) { - $this->_convertNullArrayValuesToEmpty($arr); - } - return DB_OK; - } - - // }}} - // {{{ freeResult() - - /** - * Free the internal resources associated with $result. - * - * @param $result fbsql result identifier - * - * @access public - * - * @return bool true on success, false if $result is invalid - */ - function freeResult($result) - { - return @fbsql_free_result($result); - } - - // }}} - // {{{ autoCommit() - - function autoCommit($onoff=false) - { - if ($onoff) { - $this->query("SET COMMIT TRUE"); - } else { - $this->query("SET COMMIT FALSE"); - } - } - - // }}} - // {{{ commit() - - function commit() - { - @fbsql_commit(); - } - - // }}} - // {{{ rollback() - - function rollback() - { - @fbsql_rollback(); - } - - // }}} - // {{{ numCols() - - /** - * Get the number of columns in a result set. - * - * @param $result fbsql result identifier - * - * @access public - * - * @return int the number of columns per row in $result - */ - function numCols($result) - { - $cols = @fbsql_num_fields($result); - - if (!$cols) { - return $this->fbsqlRaiseError(); - } - - return $cols; - } - - // }}} - // {{{ numRows() - - /** - * Get the number of rows in a result set. - * - * @param $result fbsql result identifier - * - * @access public - * - * @return int the number of rows in $result - */ - function numRows($result) - { - $rows = @fbsql_num_rows($result); - if ($rows === null) { - return $this->fbsqlRaiseError(); - } - return $rows; - } - - // }}} - // {{{ affectedRows() - - /** - * Gets the number of rows affected by the data manipulation - * query. For other queries, this function returns 0. - * - * @return number of rows affected by the last query - */ - function affectedRows() - { - if (DB::isManip($this->last_query)) { - $result = @fbsql_affected_rows($this->connection); - } else { - $result = 0; - } - return $result; - } - - // }}} - // {{{ errorNative() - - /** - * Get the native error code of the last error (if any) that - * occured on the current connection. - * - * @access public - * - * @return int native fbsql error code - */ - function errorNative() - { - return @fbsql_errno($this->connection); - } - - // }}} - // {{{ nextId() - - /** - * Returns the next free id in a sequence - * - * @param string $seq_name name of the sequence - * @param boolean $ondemand when true, the seqence is automatically - * created if it does not exist - * - * @return int the next id number in the sequence. DB_Error if problem. - * - * @internal - * @see DB_common::nextID() - * @access public - */ - function nextId($seq_name, $ondemand = true) - { - $seqname = $this->getSequenceName($seq_name); - $repeat = 0; - do { - $result = $this->query("INSERT INTO ${seqname} (id) VALUES (NULL)"); - if ($ondemand && DB::isError($result) && - $result->getCode() == DB_ERROR_NOSUCHTABLE) { - $repeat = 1; - $result = $this->createSequence($seq_name); - if (DB::isError($result)) { - return $result; - } - } else { - $repeat = 0; - } - } while ($repeat); - if (DB::isError($result)) { - return $result; - } - return @fbsql_insert_id($this->connection); - } - - /** - * Creates a new sequence - * - * @param string $seq_name name of the new sequence - * - * @return int DB_OK on success. A DB_Error object is returned if - * problems arise. - * - * @internal - * @see DB_common::createSequence() - * @access public - */ - function createSequence($seq_name) - { - $seqname = $this->getSequenceName($seq_name); - return $this->query("CREATE TABLE ${seqname} ". - '(id INTEGER UNSIGNED AUTO_INCREMENT NOT NULL,'. - ' PRIMARY KEY(id))'); - } - - // }}} - // {{{ dropSequence() - - /** - * Deletes a sequence - * - * @param string $seq_name name of the sequence to be deleted - * - * @return int DB_OK on success. DB_Error if problems. - * - * @internal - * @see DB_common::dropSequence() - * @access public - */ - function dropSequence($seq_name) - { - $seqname = $this->getSequenceName($seq_name); - return $this->query("DROP TABLE ${seqname} RESTRICT"); - } - - // }}} - // {{{ modifyQuery() - - function modifyQuery($query) - { - if ($this->options['portability'] & DB_PORTABILITY_DELETE_COUNT) { - // "DELETE FROM table" gives 0 affected rows in fbsql. - // This little hack lets you know how many rows were deleted. - if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) { - $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/', - 'DELETE FROM \1 WHERE 1=1', $query); - } - } - return $query; - } - - // }}} - // {{{ quoteSmart() - - /** - * Format input so it can be safely used in a query - * - * @param mixed $in data to be quoted - * - * @return mixed Submitted variable's type = returned value: - * + null = the string NULL - * + boolean = string TRUE or FALSE - * + integer or double = the unquoted number - * + other (including strings and numeric strings) = - * the data escaped according to MySQL's settings - * then encapsulated between single quotes - * - * @internal - */ - function quoteSmart($in) - { - if (is_int($in) || is_double($in)) { - return $in; - } elseif (is_bool($in)) { - return $in ? 'TRUE' : 'FALSE'; - } elseif (is_null($in)) { - return 'NULL'; - } else { - return "'" . $this->escapeSimple($in) . "'"; - } - } - - // }}} - // {{{ fbsqlRaiseError() - - /** - * Gather information about an error, then use that info to create a - * DB error object and finally return that object. - * - * @param integer $errno PEAR error number (usually a DB constant) if - * manually raising an error - * @return object DB error object - * @see DB_common::errorCode() - * @see DB_common::raiseError() - */ - function fbsqlRaiseError($errno = null) - { - if ($errno === null) { - $errno = $this->errorCode(fbsql_errno($this->connection)); - } - return $this->raiseError($errno, null, null, null, - @fbsql_error($this->connection)); - } - - // }}} - // {{{ tableInfo() - - /** - * Returns information about a table or a result set. - * - * @param object|string $result DB_result object from a query or a - * string containing the name of a table - * @param int $mode a valid tableInfo mode - * @return array an associative array with the information requested - * or an error object if something is wrong - * @access public - * @internal - * @see DB_common::tableInfo() - */ - function tableInfo($result, $mode = null) { - if (isset($result->result)) { - /* - * Probably received a result object. - * Extract the result resource identifier. - */ - $id = $result->result; - $got_string = false; - } elseif (is_string($result)) { - /* - * Probably received a table name. - * Create a result resource identifier. - */ - $id = @fbsql_list_fields($this->dsn['database'], - $result, $this->connection); - $got_string = true; - } else { - /* - * Probably received a result resource identifier. - * Copy it. - * Deprecated. Here for compatibility only. - */ - $id = $result; - $got_string = false; - } - - if (!is_resource($id)) { - return $this->fbsqlRaiseError(DB_ERROR_NEED_MORE_DATA); - } - - if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) { - $case_func = 'strtolower'; - } else { - $case_func = 'strval'; - } - - $count = @fbsql_num_fields($id); - - // made this IF due to performance (one if is faster than $count if's) - if (!$mode) { - for ($i=0; $i<$count; $i++) { - $res[$i]['table'] = $case_func(@fbsql_field_table($id, $i)); - $res[$i]['name'] = $case_func(@fbsql_field_name($id, $i)); - $res[$i]['type'] = @fbsql_field_type($id, $i); - $res[$i]['len'] = @fbsql_field_len($id, $i); - $res[$i]['flags'] = @fbsql_field_flags($id, $i); - } - } else { // full - $res["num_fields"]= $count; - - for ($i=0; $i<$count; $i++) { - $res[$i]['table'] = $case_func(@fbsql_field_table($id, $i)); - $res[$i]['name'] = $case_func(@fbsql_field_name($id, $i)); - $res[$i]['type'] = @fbsql_field_type($id, $i); - $res[$i]['len'] = @fbsql_field_len($id, $i); - $res[$i]['flags'] = @fbsql_field_flags($id, $i); - - if ($mode & DB_TABLEINFO_ORDER) { - $res['order'][$res[$i]['name']] = $i; - } - if ($mode & DB_TABLEINFO_ORDERTABLE) { - $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i; - } - } - } - - // free the result only if we were called on a table - if ($got_string) { - @fbsql_free_result($id); - } - return $res; - } - - // }}} - // {{{ getSpecialQuery() - - /** - * Returns the query needed to get some backend info - * @param string $type What kind of info you want to retrieve - * @return string The SQL query string - */ - function getSpecialQuery($type) - { - switch ($type) { - case 'tables': - return 'select "table_name" from information_schema.tables'; - default: - return null; - } - } - - // }}} -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - */ - -?> diff --git a/gulliver/thirdparty/pear/DB/ibase.php b/gulliver/thirdparty/pear/DB/ibase.php deleted file mode 100644 index 7100975bf..000000000 --- a/gulliver/thirdparty/pear/DB/ibase.php +++ /dev/null @@ -1,784 +0,0 @@ - | -// | Maintainer: Daniel Convissor | -// +----------------------------------------------------------------------+ -// -// $Id: ibase.php 3355 2005-06-11 22:14:40Z nbm $ - - -// Bugs: -// - If dbsyntax is not firebird, the limitQuery may fail - - -require_once 'DB/common.php'; - -/** - * Database independent query interface definition for PHP's Interbase - * extension. - * - * @package DB - * @version $Id: ibase.php 3355 2005-06-11 22:14:40Z nbm $ - * @category Database - * @author Sterling Hughes - */ -class DB_ibase extends DB_common -{ - - // {{{ properties - - var $connection; - var $phptype, $dbsyntax; - var $autocommit = 1; - var $manip_query = array(); - - // }}} - // {{{ constructor - - function DB_ibase() - { - $this->DB_common(); - $this->phptype = 'ibase'; - $this->dbsyntax = 'ibase'; - $this->features = array( - 'prepare' => true, - 'pconnect' => true, - 'transactions' => true, - 'limit' => false - ); - // just a few of the tons of Interbase error codes listed in the - // Language Reference section of the Interbase manual - $this->errorcode_map = array( - -104 => DB_ERROR_SYNTAX, - -150 => DB_ERROR_ACCESS_VIOLATION, - -151 => DB_ERROR_ACCESS_VIOLATION, - -155 => DB_ERROR_NOSUCHTABLE, - 88 => DB_ERROR_NOSUCHTABLE, - -157 => DB_ERROR_NOSUCHFIELD, - -158 => DB_ERROR_VALUE_COUNT_ON_ROW, - -170 => DB_ERROR_MISMATCH, - -171 => DB_ERROR_MISMATCH, - -172 => DB_ERROR_INVALID, - -204 => DB_ERROR_INVALID, - -205 => DB_ERROR_NOSUCHFIELD, - -206 => DB_ERROR_NOSUCHFIELD, - -208 => DB_ERROR_INVALID, - -219 => DB_ERROR_NOSUCHTABLE, - -297 => DB_ERROR_CONSTRAINT, - -530 => DB_ERROR_CONSTRAINT, - -607 => DB_ERROR_NOSUCHTABLE, - -803 => DB_ERROR_CONSTRAINT, - -551 => DB_ERROR_ACCESS_VIOLATION, - -552 => DB_ERROR_ACCESS_VIOLATION, - -922 => DB_ERROR_NOSUCHDB, - -923 => DB_ERROR_CONNECT_FAILED, - -924 => DB_ERROR_CONNECT_FAILED - ); - } - - // }}} - // {{{ connect() - - function connect($dsninfo, $persistent = false) - { - if (!DB::assertExtension('interbase')) { - return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND); - } - $this->dsn = $dsninfo; - $dbhost = $dsninfo['hostspec'] ? - ($dsninfo['hostspec'] . ':' . $dsninfo['database']) : - $dsninfo['database']; - - $connect_function = $persistent ? 'ibase_pconnect' : 'ibase_connect'; - - $params = array(); - $params[] = $dbhost; - $params[] = $dsninfo['username'] ? $dsninfo['username'] : null; - $params[] = $dsninfo['password'] ? $dsninfo['password'] : null; - $params[] = isset($dsninfo['charset']) ? $dsninfo['charset'] : null; - $params[] = isset($dsninfo['buffers']) ? $dsninfo['buffers'] : null; - $params[] = isset($dsninfo['dialect']) ? $dsninfo['dialect'] : null; - $params[] = isset($dsninfo['role']) ? $dsninfo['role'] : null; - - $conn = @call_user_func_array($connect_function, $params); - if (!$conn) { - return $this->ibaseRaiseError(DB_ERROR_CONNECT_FAILED); - } - $this->connection = $conn; - if ($this->dsn['dbsyntax'] == 'firebird') { - $this->features['limit'] = 'alter'; - } - return DB_OK; - } - - // }}} - // {{{ disconnect() - - function disconnect() - { - $ret = @ibase_close($this->connection); - $this->connection = null; - return $ret; - } - - // }}} - // {{{ simpleQuery() - - function simpleQuery($query) - { - $ismanip = DB::isManip($query); - $this->last_query = $query; - $query = $this->modifyQuery($query); - $result = @ibase_query($this->connection, $query); - if (!$result) { - return $this->ibaseRaiseError(); - } - if ($this->autocommit && $ismanip) { - @ibase_commit($this->connection); - } - // Determine which queries that should return data, and which - // should return an error code only. - return $ismanip ? DB_OK : $result; - } - - // }}} - // {{{ modifyLimitQuery() - - /** - * This method is used by backends to alter limited queries - * Uses the new FIRST n SKIP n Firebird 1.0 syntax, so it is - * only compatible with Firebird 1.x - * - * @param string $query query to modify - * @param integer $from the row to start to fetching - * @param integer $count the numbers of rows to fetch - * - * @return the new (modified) query - * @author Ludovico Magnocavallo - * @access private - */ - function modifyLimitQuery($query, $from, $count, $params = array()) - { - if ($this->dsn['dbsyntax'] == 'firebird') { - //$from++; // SKIP starts from 1, ie SKIP 1 starts from the first record - // (cox) Seems that SKIP starts in 0 - $query = preg_replace('/^\s*select\s(.*)$/is', - "SELECT FIRST $count SKIP $from $1", $query); - } - return $query; - } - - // }}} - // {{{ nextResult() - - /** - * Move the internal ibase result pointer to the next available result - * - * @param a valid fbsql result resource - * - * @access public - * - * @return true if a result is available otherwise return false - */ - function nextResult($result) - { - return false; - } - - // }}} - // {{{ fetchInto() - - /** - * Fetch a row and insert the data into an existing array. - * - * Formating of the array and the data therein are configurable. - * See DB_result::fetchInto() for more information. - * - * @param resource $result query result identifier - * @param array $arr (reference) array where data from the row - * should be placed - * @param int $fetchmode how the resulting array should be indexed - * @param int $rownum the row number to fetch - * - * @return mixed DB_OK on success, null when end of result set is - * reached or on failure - * - * @see DB_result::fetchInto() - * @access private - */ - function fetchInto($result, &$arr, $fetchmode, $rownum=null) - { - if ($rownum !== null) { - return $this->ibaseRaiseError(DB_ERROR_NOT_CAPABLE); - } - if ($fetchmode & DB_FETCHMODE_ASSOC) { - if (function_exists('ibase_fetch_assoc')) { - $arr = @ibase_fetch_assoc($result); - } else { - $arr = get_object_vars(ibase_fetch_object($result)); - } - if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) { - $arr = array_change_key_case($arr, CASE_LOWER); - } - } else { - $arr = @ibase_fetch_row($result); - } - if (!$arr) { - if ($errmsg = @ibase_errmsg()) { - return $this->ibaseRaiseError(null, $errmsg); - } else { - return null; - } - } - if ($this->options['portability'] & DB_PORTABILITY_RTRIM) { - $this->_rtrimArrayValues($arr); - } - if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) { - $this->_convertNullArrayValuesToEmpty($arr); - } - return DB_OK; - } - - // }}} - // {{{ freeResult() - - function freeResult($result) - { - return @ibase_free_result($result); - } - - // }}} - // {{{ freeQuery() - - function freeQuery($query) - { - @ibase_free_query($query); - return true; - } - - // }}} - // {{{ numCols() - - function numCols($result) - { - $cols = @ibase_num_fields($result); - if (!$cols) { - return $this->ibaseRaiseError(); - } - return $cols; - } - - // }}} - // {{{ prepare() - - /** - * Prepares a query for multiple execution with execute(). - * - * prepare() requires a generic query as string like - * INSERT INTO numbers VALUES (?, ?, ?) - * . The ? characters are placeholders. - * - * Three types of placeholders can be used: - * + ? a quoted scalar value, i.e. strings, integers - * + ! value is inserted 'as is' - * + & requires a file name. The file's contents get - * inserted into the query (i.e. saving binary - * data in a db) - * - * Use backslashes to escape placeholder characters if you don't want - * them to be interpreted as placeholders. Example: - * "UPDATE foo SET col=? WHERE col='over \& under'" - * - * - * @param string $query query to be prepared - * @return mixed DB statement resource on success. DB_Error on failure. - */ - function prepare($query) - { - $tokens = preg_split('/((? $val) { - switch ($val) { - case '?': - $types[$token++] = DB_PARAM_SCALAR; - break; - case '&': - $types[$token++] = DB_PARAM_OPAQUE; - break; - case '!': - $types[$token++] = DB_PARAM_MISC; - break; - default: - $tokens[$key] = preg_replace('/\\\([&?!])/', "\\1", $val); - $newquery .= $tokens[$key] . '?'; - } - } - - $newquery = substr($newquery, 0, -1); - $this->last_query = $query; - $newquery = $this->modifyQuery($newquery); - $stmt = @ibase_prepare($this->connection, $newquery); - $this->prepare_types[(int)$stmt] = $types; - $this->manip_query[(int)$stmt] = DB::isManip($query); - return $stmt; - } - - // }}} - // {{{ execute() - - /** - * Executes a DB statement prepared with prepare(). - * - * @param resource $stmt a DB statement resource returned from prepare() - * @param mixed $data array, string or numeric data to be used in - * execution of the statement. Quantity of items - * passed must match quantity of placeholders in - * query: meaning 1 for non-array items or the - * quantity of elements in the array. - * @return object a new DB_Result or a DB_Error when fail - * @see DB_ibase::prepare() - * @access public - */ - function &execute($stmt, $data = array()) - { - if (!is_array($data)) { - $data = array($data); - } - - $types =& $this->prepare_types[(int)$stmt]; - if (count($types) != count($data)) { - $tmp =& $this->raiseError(DB_ERROR_MISMATCH); - return $tmp; - } - - $i = 0; - foreach ($data as $key => $value) { - if ($types[$i] == DB_PARAM_MISC) { - /* - * ibase doesn't seem to have the ability to pass a - * parameter along unchanged, so strip off quotes from start - * and end, plus turn two single quotes to one single quote, - * in order to avoid the quotes getting escaped by - * ibase and ending up in the database. - */ - $data[$key] = preg_replace("/^'(.*)'$/", "\\1", $data[$key]); - $data[$key] = str_replace("''", "'", $data[$key]); - } elseif ($types[$i] == DB_PARAM_OPAQUE) { - $fp = @fopen($data[$key], 'rb'); - if (!$fp) { - $tmp =& $this->raiseError(DB_ERROR_ACCESS_VIOLATION); - return $tmp; - } - $data[$key] = fread($fp, filesize($data[$key])); - fclose($fp); - } - $i++; - } - - array_unshift($data, $stmt); - - $res = call_user_func_array('ibase_execute', $data); - if (!$res) { - $tmp =& $this->ibaseRaiseError(); - return $tmp; - } - /* XXX need this? - if ($this->autocommit && $this->manip_query[(int)$stmt]) { - @ibase_commit($this->connection); - }*/ - if ($this->manip_query[(int)$stmt]) { - $tmp = DB_OK; - } else { - $tmp =& new DB_result($this, $res); - } - return $tmp; - } - - /** - * Free the internal resources associated with a prepared query. - * - * @param $stmt The interbase_query resource type - * - * @return bool true on success, false if $result is invalid - */ - function freePrepared($stmt) - { - if (!is_resource($stmt)) { - return false; - } - @ibase_free_query($stmt); - unset($this->prepare_tokens[(int)$stmt]); - unset($this->prepare_types[(int)$stmt]); - unset($this->manip_query[(int)$stmt]); - return true; - } - - // }}} - // {{{ autoCommit() - - function autoCommit($onoff = false) - { - $this->autocommit = $onoff ? 1 : 0; - return DB_OK; - } - - // }}} - // {{{ commit() - - function commit() - { - return @ibase_commit($this->connection); - } - - // }}} - // {{{ rollback() - - function rollback() - { - return @ibase_rollback($this->connection); - } - - // }}} - // {{{ transactionInit() - - function transactionInit($trans_args = 0) - { - return $trans_args ? @ibase_trans($trans_args, $this->connection) : @ibase_trans(); - } - - // }}} - // {{{ nextId() - - /** - * Returns the next free id in a sequence - * - * @param string $seq_name name of the sequence - * @param boolean $ondemand when true, the seqence is automatically - * created if it does not exist - * - * @return int the next id number in the sequence. DB_Error if problem. - * - * @internal - * @see DB_common::nextID() - * @access public - */ - function nextId($seq_name, $ondemand = true) - { - $sqn = strtoupper($this->getSequenceName($seq_name)); - $repeat = 0; - do { - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $result =& $this->query("SELECT GEN_ID(${sqn}, 1) " - . 'FROM RDB$GENERATORS ' - . "WHERE RDB\$GENERATOR_NAME='${sqn}'"); - $this->popErrorHandling(); - if ($ondemand && DB::isError($result)) { - $repeat = 1; - $result = $this->createSequence($seq_name); - if (DB::isError($result)) { - return $result; - } - } else { - $repeat = 0; - } - } while ($repeat); - if (DB::isError($result)) { - return $this->raiseError($result); - } - $arr = $result->fetchRow(DB_FETCHMODE_ORDERED); - $result->free(); - return $arr[0]; - } - - // }}} - // {{{ createSequence() - - /** - * Create the sequence - * - * @param string $seq_name the name of the sequence - * @return mixed DB_OK on success or DB error on error - * @access public - */ - function createSequence($seq_name) - { - $sqn = strtoupper($this->getSequenceName($seq_name)); - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $result = $this->query("CREATE GENERATOR ${sqn}"); - $this->popErrorHandling(); - - return $result; - } - - // }}} - // {{{ dropSequence() - - /** - * Drop a sequence - * - * @param string $seq_name the name of the sequence - * @return mixed DB_OK on success or DB error on error - * @access public - */ - function dropSequence($seq_name) - { - $sqn = strtoupper($this->getSequenceName($seq_name)); - return $this->query('DELETE FROM RDB$GENERATORS ' - . "WHERE RDB\$GENERATOR_NAME='${sqn}'"); - } - - // }}} - // {{{ _ibaseFieldFlags() - - /** - * get the Flags of a Field - * - * @param string $field_name the name of the field - * @param string $table_name the name of the table - * - * @return string The flags of the field ("primary_key", "unique_key", "not_null" - * "default", "computed" and "blob" are supported) - * @access private - */ - function _ibaseFieldFlags($field_name, $table_name) - { - $sql = 'SELECT R.RDB$CONSTRAINT_TYPE CTYPE' - .' FROM RDB$INDEX_SEGMENTS I' - .' JOIN RDB$RELATION_CONSTRAINTS R ON I.RDB$INDEX_NAME=R.RDB$INDEX_NAME' - .' WHERE I.RDB$FIELD_NAME=\'' . $field_name . '\'' - .' AND UPPER(R.RDB$RELATION_NAME)=\'' . strtoupper($table_name) . '\''; - - $result = @ibase_query($this->connection, $sql); - if (!$result) { - return $this->ibaseRaiseError(); - } - - $flags = ''; - if ($obj = @ibase_fetch_object($result)) { - @ibase_free_result($result); - if (isset($obj->CTYPE) && trim($obj->CTYPE) == 'PRIMARY KEY') { - $flags .= 'primary_key '; - } - if (isset($obj->CTYPE) && trim($obj->CTYPE) == 'UNIQUE') { - $flags .= 'unique_key '; - } - } - - $sql = 'SELECT R.RDB$NULL_FLAG AS NFLAG,' - .' R.RDB$DEFAULT_SOURCE AS DSOURCE,' - .' F.RDB$FIELD_TYPE AS FTYPE,' - .' F.RDB$COMPUTED_SOURCE AS CSOURCE' - .' FROM RDB$RELATION_FIELDS R ' - .' JOIN RDB$FIELDS F ON R.RDB$FIELD_SOURCE=F.RDB$FIELD_NAME' - .' WHERE UPPER(R.RDB$RELATION_NAME)=\'' . strtoupper($table_name) . '\'' - .' AND R.RDB$FIELD_NAME=\'' . $field_name . '\''; - - $result = @ibase_query($this->connection, $sql); - if (!$result) { - return $this->ibaseRaiseError(); - } - if ($obj = @ibase_fetch_object($result)) { - @ibase_free_result($result); - if (isset($obj->NFLAG)) { - $flags .= 'not_null '; - } - if (isset($obj->DSOURCE)) { - $flags .= 'default '; - } - if (isset($obj->CSOURCE)) { - $flags .= 'computed '; - } - if (isset($obj->FTYPE) && $obj->FTYPE == 261) { - $flags .= 'blob '; - } - } - - return trim($flags); - } - - // }}} - // {{{ tableInfo() - - /** - * Returns information about a table or a result set. - * - * NOTE: only supports 'table' and 'flags' if $result - * is a table name. - * - * @param object|string $result DB_result object from a query or a - * string containing the name of a table - * @param int $mode a valid tableInfo mode - * @return array an associative array with the information requested - * or an error object if something is wrong - * @access public - * @internal - * @see DB_common::tableInfo() - */ - function tableInfo($result, $mode = null) - { - if (isset($result->result)) { - /* - * Probably received a result object. - * Extract the result resource identifier. - */ - $id = $result->result; - $got_string = false; - } elseif (is_string($result)) { - /* - * Probably received a table name. - * Create a result resource identifier. - */ - $id = @ibase_query($this->connection, - "SELECT * FROM $result WHERE 1=0"); - $got_string = true; - } else { - /* - * Probably received a result resource identifier. - * Copy it. - * Deprecated. Here for compatibility only. - */ - $id = $result; - $got_string = false; - } - - if (!is_resource($id)) { - return $this->ibaseRaiseError(DB_ERROR_NEED_MORE_DATA); - } - - if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) { - $case_func = 'strtolower'; - } else { - $case_func = 'strval'; - } - - $count = @ibase_num_fields($id); - - // made this IF due to performance (one if is faster than $count if's) - if (!$mode) { - for ($i=0; $i<$count; $i++) { - $info = @ibase_field_info($id, $i); - $res[$i]['table'] = $got_string ? $case_func($result) : ''; - $res[$i]['name'] = $case_func($info['name']); - $res[$i]['type'] = $info['type']; - $res[$i]['len'] = $info['length']; - $res[$i]['flags'] = ($got_string) ? $this->_ibaseFieldFlags($info['name'], $result) : ''; - } - } else { // full - $res['num_fields']= $count; - - for ($i=0; $i<$count; $i++) { - $info = @ibase_field_info($id, $i); - $res[$i]['table'] = $got_string ? $case_func($result) : ''; - $res[$i]['name'] = $case_func($info['name']); - $res[$i]['type'] = $info['type']; - $res[$i]['len'] = $info['length']; - $res[$i]['flags'] = ($got_string) ? $this->_ibaseFieldFlags($info['name'], $result) : ''; - - if ($mode & DB_TABLEINFO_ORDER) { - $res['order'][$res[$i]['name']] = $i; - } - if ($mode & DB_TABLEINFO_ORDERTABLE) { - $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i; - } - } - } - - // free the result only if we were called on a table - if ($got_string) { - @ibase_free_result($id); - } - return $res; - } - - // }}} - // {{{ ibaseRaiseError() - - /** - * Gather information about an error, then use that info to create a - * DB error object and finally return that object. - * - * @param integer $db_errno PEAR error number (usually a DB constant) if - * manually raising an error - * @param string $native_errmsg text of error message if known - * @return object DB error object - * @see DB_common::errorCode() - * @see DB_common::raiseError() - */ - function &ibaseRaiseError($db_errno = null, $native_errmsg = null) - { - if ($native_errmsg === null) { - $native_errmsg = @ibase_errmsg(); - } - // memo for the interbase php module hackers: we need something similar - // to mysql_errno() to retrieve error codes instead of this ugly hack - if (preg_match('/^([^0-9\-]+)([0-9\-]+)\s+(.*)$/', $native_errmsg, $m)) { - $native_errno = (int)$m[2]; - } else { - $native_errno = null; - } - // try to map the native error to the DB one - if ($db_errno === null) { - if ($native_errno) { - // try to interpret Interbase error code (that's why we need ibase_errno() - // in the interbase module to return the real error code) - switch ($native_errno) { - case -204: - if (is_int(strpos($m[3], 'Table unknown'))) { - $db_errno = DB_ERROR_NOSUCHTABLE; - } - break; - default: - $db_errno = $this->errorCode($native_errno); - } - } else { - $error_regexps = array( - '/[tT]able not found/' => DB_ERROR_NOSUCHTABLE, - '/[tT]able .* already exists/' => DB_ERROR_ALREADY_EXISTS, - '/validation error for column .* value "\*\*\* null/' => DB_ERROR_CONSTRAINT_NOT_NULL, - '/violation of [\w ]+ constraint/' => DB_ERROR_CONSTRAINT, - '/conversion error from string/' => DB_ERROR_INVALID_NUMBER, - '/no permission for/' => DB_ERROR_ACCESS_VIOLATION, - '/arithmetic exception, numeric overflow, or string truncation/' => DB_ERROR_DIVZERO - ); - foreach ($error_regexps as $regexp => $code) { - if (preg_match($regexp, $native_errmsg)) { - $db_errno = $code; - $native_errno = null; - break; - } - } - } - } - $tmp =& $this->raiseError($db_errno, null, null, null, $native_errmsg); - return $tmp; - } - - // }}} - -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - */ - -?> diff --git a/gulliver/thirdparty/pear/DB/ifx.php b/gulliver/thirdparty/pear/DB/ifx.php deleted file mode 100644 index 89204a633..000000000 --- a/gulliver/thirdparty/pear/DB/ifx.php +++ /dev/null @@ -1,579 +0,0 @@ - | -// | Maintainer: Daniel Convissor | -// +----------------------------------------------------------------------+ -// -// $Id: ifx.php 3355 2005-06-11 22:14:40Z nbm $ - - -// Legend: -// For more info on Informix errors see: -// http://www.informix.com/answers/english/ierrors.htm -// -// TODO: -// - set needed env Informix vars on connect -// - implement native prepare/execute - - -require_once 'DB/common.php'; - -/** - * Database independent query interface definition for PHP's Informix - * extension. - * - * @package DB - * @version $Id: ifx.php 3355 2005-06-11 22:14:40Z nbm $ - * @category Database - * @author Tomas V.V.Cox - */ -class DB_ifx extends DB_common -{ - // {{{ properties - - var $connection; - var $affected = 0; - var $dsn = array(); - var $transaction_opcount = 0; - var $autocommit = true; - var $fetchmode = DB_FETCHMODE_ORDERED; /* Default fetch mode */ - - // }}} - // {{{ constructor - - function DB_ifx() - { - $this->phptype = 'ifx'; - $this->dbsyntax = 'ifx'; - $this->features = array( - 'prepare' => false, - 'pconnect' => true, - 'transactions' => true, - 'limit' => 'emulate' - ); - $this->errorcode_map = array( - '-201' => DB_ERROR_SYNTAX, - '-206' => DB_ERROR_NOSUCHTABLE, - '-217' => DB_ERROR_NOSUCHFIELD, - '-239' => DB_ERROR_CONSTRAINT, - '-253' => DB_ERROR_SYNTAX, - '-292' => DB_ERROR_CONSTRAINT_NOT_NULL, - '-310' => DB_ERROR_ALREADY_EXISTS, - '-329' => DB_ERROR_NODBSELECTED, - '-346' => DB_ERROR_CONSTRAINT, - '-386' => DB_ERROR_CONSTRAINT_NOT_NULL, - '-391' => DB_ERROR_CONSTRAINT_NOT_NULL, - '-554' => DB_ERROR_SYNTAX, - '-691' => DB_ERROR_CONSTRAINT, - '-703' => DB_ERROR_CONSTRAINT_NOT_NULL, - '-1204' => DB_ERROR_INVALID_DATE, - '-1205' => DB_ERROR_INVALID_DATE, - '-1206' => DB_ERROR_INVALID_DATE, - '-1209' => DB_ERROR_INVALID_DATE, - '-1210' => DB_ERROR_INVALID_DATE, - '-1212' => DB_ERROR_INVALID_DATE, - '-1213' => DB_ERROR_INVALID_NUMBER, - ); - } - - // }}} - // {{{ connect() - - /** - * Connect to a database and log in as the specified user. - * - * @param $dsn the data source name (see DB::parseDSN for syntax) - * @param $persistent (optional) whether the connection should - * be persistent - * - * @return int DB_OK on success, a DB error code on failure - */ - function connect($dsninfo, $persistent = false) - { - if (!DB::assertExtension('informix') && - !DB::assertExtension('Informix')) - { - return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND); - } - $this->dsn = $dsninfo; - $dbhost = $dsninfo['hostspec'] ? '@' . $dsninfo['hostspec'] : ''; - $dbname = $dsninfo['database'] ? $dsninfo['database'] . $dbhost : ''; - $user = $dsninfo['username'] ? $dsninfo['username'] : ''; - $pw = $dsninfo['password'] ? $dsninfo['password'] : ''; - - $connect_function = $persistent ? 'ifx_pconnect' : 'ifx_connect'; - - $this->connection = @$connect_function($dbname, $user, $pw); - if (!is_resource($this->connection)) { - return $this->ifxraiseError(DB_ERROR_CONNECT_FAILED); - } - return DB_OK; - } - - // }}} - // {{{ disconnect() - - /** - * Log out and disconnect from the database. - * - * @return bool true on success, false if not connected. - */ - function disconnect() - { - $ret = @ifx_close($this->connection); - $this->connection = null; - return $ret; - } - - // }}} - // {{{ simpleQuery() - - /** - * Send a query to Informix and return the results as a - * Informix resource identifier. - * - * @param $query the SQL query - * - * @return int returns a valid Informix result for successful SELECT - * queries, DB_OK for other successful queries. A DB error code - * is returned on failure. - */ - function simpleQuery($query) - { - $ismanip = DB::isManip($query); - $this->last_query = $query; - $this->affected = null; - if (preg_match('/(SELECT)/i', $query)) { //TESTME: Use !DB::isManip()? - // the scroll is needed for fetching absolute row numbers - // in a select query result - $result = @ifx_query($query, $this->connection, IFX_SCROLL); - } else { - if (!$this->autocommit && $ismanip) { - if ($this->transaction_opcount == 0) { - $result = @ifx_query('BEGIN WORK', $this->connection); - if (!$result) { - return $this->ifxraiseError(); - } - } - $this->transaction_opcount++; - } - $result = @ifx_query($query, $this->connection); - } - if (!$result) { - return $this->ifxraiseError(); - } - $this->affected = @ifx_affected_rows($result); - // Determine which queries should return data, and which - // should return an error code only. - if (preg_match('/(SELECT)/i', $query)) { - return $result; - } - // XXX Testme: free results inside a transaction - // may cause to stop it and commit the work? - - // Result has to be freed even with a insert or update - @ifx_free_result($result); - - return DB_OK; - } - - // }}} - // {{{ nextResult() - - /** - * Move the internal ifx result pointer to the next available result - * - * @param a valid fbsql result resource - * - * @access public - * - * @return true if a result is available otherwise return false - */ - function nextResult($result) - { - return false; - } - - // }}} - // {{{ affectedRows() - - /** - * Gets the number of rows affected by the last query. - * if the last query was a select, returns 0. - * - * @return number of rows affected by the last query - */ - function affectedRows() - { - if (DB::isManip($this->last_query)) { - return $this->affected; - } else { - return 0; - } - - } - - // }}} - // {{{ fetchInto() - - /** - * Fetch a row and insert the data into an existing array. - * - * Formating of the array and the data therein are configurable. - * See DB_result::fetchInto() for more information. - * - * @param resource $result query result identifier - * @param array $arr (reference) array where data from the row - * should be placed - * @param int $fetchmode how the resulting array should be indexed - * @param int $rownum the row number to fetch - * - * @return mixed DB_OK on success, null when end of result set is - * reached or on failure - * - * @see DB_result::fetchInto() - * @access private - */ - function fetchInto($result, &$arr, $fetchmode, $rownum=null) - { - if (($rownum !== null) && ($rownum < 0)) { - return null; - } - if ($rownum === null) { - /* - * Even though fetch_row() should return the next row if - * $rownum is null, it doesn't in all cases. Bug 598. - */ - $rownum = 'NEXT'; - } else { - // Index starts at row 1, unlike most DBMS's starting at 0. - $rownum++; - } - if (!$arr = @ifx_fetch_row($result, $rownum)) { - return null; - } - if ($fetchmode !== DB_FETCHMODE_ASSOC) { - $i=0; - $order = array(); - foreach ($arr as $val) { - $order[$i++] = $val; - } - $arr = $order; - } elseif ($fetchmode == DB_FETCHMODE_ASSOC && - $this->options['portability'] & DB_PORTABILITY_LOWERCASE) - { - $arr = array_change_key_case($arr, CASE_LOWER); - } - if ($this->options['portability'] & DB_PORTABILITY_RTRIM) { - $this->_rtrimArrayValues($arr); - } - if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) { - $this->_convertNullArrayValuesToEmpty($arr); - } - return DB_OK; - } - - // }}} - // {{{ numRows() - - function numRows($result) - { - return $this->raiseError(DB_ERROR_NOT_CAPABLE); - } - - // }}} - // {{{ numCols() - - /** - * Get the number of columns in a result set. - * - * @param $result Informix result identifier - * - * @return int the number of columns per row in $result - */ - function numCols($result) - { - if (!$cols = @ifx_num_fields($result)) { - return $this->ifxraiseError(); - } - return $cols; - } - - // }}} - // {{{ freeResult() - - /** - * Free the internal resources associated with $result. - * - * @param $result Informix result identifier - * - * @return bool true on success, false if $result is invalid - */ - function freeResult($result) - { - return @ifx_free_result($result); - } - - // }}} - // {{{ autoCommit() - - /** - * Enable/disable automatic commits - */ - function autoCommit($onoff = true) - { - // XXX if $this->transaction_opcount > 0, we should probably - // issue a warning here. - $this->autocommit = $onoff ? true : false; - return DB_OK; - } - - // }}} - // {{{ commit() - - /** - * Commit the current transaction. - */ - function commit() - { - if ($this->transaction_opcount > 0) { - $result = @ifx_query('COMMIT WORK', $this->connection); - $this->transaction_opcount = 0; - if (!$result) { - return $this->ifxRaiseError(); - } - } - return DB_OK; - } - - // }}} - // {{{ rollback() - - /** - * Roll back (undo) the current transaction. - */ - function rollback() - { - if ($this->transaction_opcount > 0) { - $result = @ifx_query('ROLLBACK WORK', $this->connection); - $this->transaction_opcount = 0; - if (!$result) { - return $this->ifxRaiseError(); - } - } - return DB_OK; - } - - // }}} - // {{{ ifxraiseError() - - /** - * Gather information about an error, then use that info to create a - * DB error object and finally return that object. - * - * @param integer $errno PEAR error number (usually a DB constant) if - * manually raising an error - * @return object DB error object - * @see errorNative() - * @see errorCode() - * @see DB_common::raiseError() - */ - function ifxraiseError($errno = null) - { - if ($errno === null) { - $errno = $this->errorCode(ifx_error()); - } - - return $this->raiseError($errno, null, null, null, - $this->errorNative()); - } - - // }}} - // {{{ errorCode() - - /** - * Map native error codes to DB's portable ones. - * - * Requires that the DB implementation's constructor fills - * in the $errorcode_map property. - * - * @param string $nativecode error code returned by the database - * @return int a portable DB error code, or DB_ERROR if this DB - * implementation has no mapping for the given error code. - */ - function errorCode($nativecode) - { - if (ereg('SQLCODE=(.*)]', $nativecode, $match)) { - $code = $match[1]; - if (isset($this->errorcode_map[$code])) { - return $this->errorcode_map[$code]; - } - } - return DB_ERROR; - } - - // }}} - // {{{ errorNative() - - /** - * Get the native error message of the last error (if any) that - * occured on the current connection. - * - * @return int native Informix error code - */ - function errorNative() - { - return @ifx_error() . ' ' . @ifx_errormsg(); - } - - // }}} - // {{{ getSpecialQuery() - - /** - * Returns the query needed to get some backend info - * @param string $type What kind of info you want to retrieve - * @return string The SQL query string - */ - function getSpecialQuery($type) - { - switch ($type) { - case 'tables': - return 'select tabname from systables where tabid >= 100'; - default: - return null; - } - } - - // }}} - // {{{ tableInfo() - - /** - * Returns information about a table or a result set. - * - * NOTE: only supports 'table' if $result is a table name. - * - * If analyzing a query result and the result has duplicate field names, - * an error will be raised saying - * can't distinguish duplicate field names. - * - * @param object|string $result DB_result object from a query or a - * string containing the name of a table - * @param int $mode a valid tableInfo mode - * @return array an associative array with the information requested - * or an error object if something is wrong - * @access public - * @internal - * @since 1.6.0 - * @see DB_common::tableInfo() - */ - function tableInfo($result, $mode = null) - { - if (isset($result->result)) { - /* - * Probably received a result object. - * Extract the result resource identifier. - */ - $id = $result->result; - $got_string = false; - } elseif (is_string($result)) { - /* - * Probably received a table name. - * Create a result resource identifier. - */ - $id = @ifx_query("SELECT * FROM $result WHERE 1=0", - $this->connection); - $got_string = true; - } else { - /* - * Probably received a result resource identifier. - * Copy it. - */ - $id = $result; - $got_string = false; - } - - if (!is_resource($id)) { - return $this->ifxRaiseError(DB_ERROR_NEED_MORE_DATA); - } - - $flds = @ifx_fieldproperties($id); - $count = @ifx_num_fields($id); - - if (count($flds) != $count) { - return $this->raiseError("can't distinguish duplicate field names"); - } - - if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) { - $case_func = 'strtolower'; - } else { - $case_func = 'strval'; - } - - $i = 0; - // made this IF due to performance (one if is faster than $count if's) - if (!$mode) { - foreach ($flds as $key => $value) { - $props = explode(';', $value); - - $res[$i]['table'] = $got_string ? $case_func($result) : ''; - $res[$i]['name'] = $case_func($key); - $res[$i]['type'] = $props[0]; - $res[$i]['len'] = $props[1]; - $res[$i]['flags'] = $props[4] == 'N' ? 'not_null' : ''; - $i++; - } - - } else { // full - $res['num_fields'] = $count; - - foreach ($flds as $key => $value) { - $props = explode(';', $value); - - $res[$i]['table'] = $got_string ? $case_func($result) : ''; - $res[$i]['name'] = $case_func($key); - $res[$i]['type'] = $props[0]; - $res[$i]['len'] = $props[1]; - $res[$i]['flags'] = $props[4] == 'N' ? 'not_null' : ''; - - if ($mode & DB_TABLEINFO_ORDER) { - $res['order'][$res[$i]['name']] = $i; - } - if ($mode & DB_TABLEINFO_ORDERTABLE) { - $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i; - } - $i++; - } - } - - // free the result only if we were called on a table - if ($got_string) { - @ifx_free_result($id); - } - return $res; - } - - // }}} - -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - */ - -?> diff --git a/gulliver/thirdparty/pear/DB/msql.php b/gulliver/thirdparty/pear/DB/msql.php deleted file mode 100644 index 8f87689ab..000000000 --- a/gulliver/thirdparty/pear/DB/msql.php +++ /dev/null @@ -1,242 +0,0 @@ - | -// | Maintainer: Daniel Convissor | -// +----------------------------------------------------------------------+ -// -// $Id: msql.php 3355 2005-06-11 22:14:40Z nbm $ - -require_once 'DB/common.php'; - -/** - * Database independent query interface definition for PHP's Mini-SQL - * extension. - * - * @package DB - * @version $Id: msql.php 3355 2005-06-11 22:14:40Z nbm $ - * @category Database - * @author Sterling Hughes - */ -class DB_msql extends DB_common -{ - // {{{ properties - - var $connection; - var $phptype, $dbsyntax; - var $prepare_tokens = array(); - var $prepare_types = array(); - - // }}} - // {{{ constructor - - function DB_msql() - { - $this->DB_common(); - $this->phptype = 'msql'; - $this->dbsyntax = 'msql'; - $this->features = array( - 'prepare' => false, - 'pconnect' => true, - 'transactions' => false, - 'limit' => 'emulate' - ); - } - - // }}} - // {{{ connect() - - function connect($dsninfo, $persistent = false) - { - if (!DB::assertExtension('msql')) { - return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND); - } - - $this->dsn = $dsninfo; - $dbhost = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost'; - - $connect_function = $persistent ? 'msql_pconnect' : 'msql_connect'; - - if ($dbhost && $dsninfo['username'] && $dsninfo['password']) { - $conn = $connect_function($dbhost, $dsninfo['username'], - $dsninfo['password']); - } elseif ($dbhost && $dsninfo['username']) { - $conn = $connect_function($dbhost, $dsninfo['username']); - } else { - $conn = $connect_function($dbhost); - } - if (!$conn) { - $this->raiseError(DB_ERROR_CONNECT_FAILED); - } - if (!@msql_select_db($dsninfo['database'], $conn)){ - return $this->raiseError(DB_ERROR_NODBSELECTED); - } - $this->connection = $conn; - return DB_OK; - } - - // }}} - // {{{ disconnect() - - function disconnect() - { - $ret = @msql_close($this->connection); - $this->connection = null; - return $ret; - } - - // }}} - // {{{ simpleQuery() - - function simpleQuery($query) - { - $this->last_query = $query; - $query = $this->modifyQuery($query); - $result = @msql_query($query, $this->connection); - if (!$result) { - return $this->raiseError(); - } - // Determine which queries that should return data, and which - // should return an error code only. - return DB::isManip($query) ? DB_OK : $result; - } - - - // }}} - // {{{ nextResult() - - /** - * Move the internal msql result pointer to the next available result - * - * @param a valid fbsql result resource - * - * @access public - * - * @return true if a result is available otherwise return false - */ - function nextResult($result) - { - return false; - } - - // }}} - // {{{ fetchInto() - - /** - * Fetch a row and insert the data into an existing array. - * - * Formating of the array and the data therein are configurable. - * See DB_result::fetchInto() for more information. - * - * @param resource $result query result identifier - * @param array $arr (reference) array where data from the row - * should be placed - * @param int $fetchmode how the resulting array should be indexed - * @param int $rownum the row number to fetch - * - * @return mixed DB_OK on success, null when end of result set is - * reached or on failure - * - * @see DB_result::fetchInto() - * @access private - */ - function fetchInto($result, &$arr, $fetchmode, $rownum=null) - { - if ($rownum !== null) { - if (!@msql_data_seek($result, $rownum)) { - return null; - } - } - if ($fetchmode & DB_FETCHMODE_ASSOC) { - $arr = @msql_fetch_array($result, MSQL_ASSOC); - if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) { - $arr = array_change_key_case($arr, CASE_LOWER); - } - } else { - $arr = @msql_fetch_row($result); - } - if (!$arr) { - if ($error = @msql_error()) { - return $this->raiseError($error); - } else { - return null; - } - } - if ($this->options['portability'] & DB_PORTABILITY_RTRIM) { - $this->_rtrimArrayValues($arr); - } - if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) { - $this->_convertNullArrayValuesToEmpty($arr); - } - return DB_OK; - } - - // }}} - // {{{ freeResult() - - function freeResult($result) - { - return @msql_free_result($result); - } - - // }}} - // {{{ numCols() - - function numCols($result) - { - $cols = @msql_num_fields($result); - if (!$cols) { - return $this->raiseError(); - } - return $cols; - } - - // }}} - // {{{ numRows() - - function numRows($result) - { - $rows = @msql_num_rows($result); - if (!$rows) { - return $this->raiseError(); - } - return $rows; - } - - // }}} - // {{{ affected() - - /** - * Gets the number of rows affected by a query. - * - * @return number of rows affected by the last query - */ - function affectedRows() - { - return @msql_affected_rows($this->connection); - } - - // }}} - -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - */ - -?> diff --git a/gulliver/thirdparty/pear/DB/mssql.php b/gulliver/thirdparty/pear/DB/mssql.php deleted file mode 100644 index 4c8516471..000000000 --- a/gulliver/thirdparty/pear/DB/mssql.php +++ /dev/null @@ -1,738 +0,0 @@ - | -// | Maintainer: Daniel Convissor | -// +----------------------------------------------------------------------+ -// -// $Id: mssql.php 3355 2005-06-11 22:14:40Z nbm $ - -require_once 'DB/common.php'; - -/** - * Database independent query interface definition for PHP's Microsoft SQL Server - * extension. - * - * @package DB - * @version $Id: mssql.php 3355 2005-06-11 22:14:40Z nbm $ - * @category Database - * @author Sterling Hughes - */ -class DB_mssql extends DB_common -{ - // {{{ properties - - var $connection; - var $phptype, $dbsyntax; - var $prepare_tokens = array(); - var $prepare_types = array(); - var $transaction_opcount = 0; - var $autocommit = true; - var $_db = null; - - // }}} - // {{{ constructor - - function DB_mssql() - { - $this->DB_common(); - $this->phptype = 'mssql'; - $this->dbsyntax = 'mssql'; - $this->features = array( - 'prepare' => false, - 'pconnect' => true, - 'transactions' => true, - 'limit' => 'emulate' - ); - // XXX Add here error codes ie: 'S100E' => DB_ERROR_SYNTAX - $this->errorcode_map = array( - 170 => DB_ERROR_SYNTAX, - 207 => DB_ERROR_NOSUCHFIELD, - 208 => DB_ERROR_NOSUCHTABLE, - 245 => DB_ERROR_INVALID_NUMBER, - 515 => DB_ERROR_CONSTRAINT_NOT_NULL, - 547 => DB_ERROR_CONSTRAINT, - 2627 => DB_ERROR_CONSTRAINT, - 2714 => DB_ERROR_ALREADY_EXISTS, - 3701 => DB_ERROR_NOSUCHTABLE, - 8134 => DB_ERROR_DIVZERO, - ); - } - - // }}} - // {{{ connect() - - function connect($dsninfo, $persistent = false) - { - if (!DB::assertExtension('mssql') && !DB::assertExtension('sybase') - && !DB::assertExtension('sybase_ct')) - { - return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND); - } - $this->dsn = $dsninfo; - $dbhost = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost'; - //$dbhost .= $dsninfo['port'] ? ',' . $dsninfo['port'] : ''; - - $dbhost .= $dsninfo['port'] ? ':' . $dsninfo['port'] : ':1433'; - $connect_function = $persistent ? 'mssql_pconnect' : 'mssql_connect'; - - if ($dbhost && $dsninfo['username'] && $dsninfo['password']) { - $conn = @$connect_function($dbhost, $dsninfo['username'], $dsninfo['password']); - }elseif ($dbhost && $dsninfo['username']){ - $conn = @$connect_function($dbhost, $dsninfo['username']); - } else { - $conn = @$connect_function($dbhost); - } - if (!$conn) { - return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null, - null, @mssql_get_last_message()); - } - if ($dsninfo['database']) { - if (!@mssql_select_db($dsninfo['database'], $conn)) { - return $this->raiseError(DB_ERROR_NODBSELECTED, null, null, - null, @mssql_get_last_message()); - } - $this->_db = $dsninfo['database']; - } - $this->connection = $conn; - return DB_OK; - } - - // }}} - // {{{ disconnect() - - function disconnect() - { - $ret = @mssql_close($this->connection); - $this->connection = null; - return $ret; - } - - // }}} - // {{{ simpleQuery() - - function simpleQuery($query) - { - $ismanip = DB::isManip($query); - $this->last_query = $query; - if (!@mssql_select_db($this->_db, $this->connection)) { - return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED); - } - $query = $this->modifyQuery($query); - if (!$this->autocommit && $ismanip) { - if ($this->transaction_opcount == 0) { - $result = @mssql_query('BEGIN TRAN', $this->connection); - if (!$result) { - return $this->mssqlRaiseError(); - } - } - $this->transaction_opcount++; - } - $result = @mssql_query($query, $this->connection); - if (!$result) { - return $this->mssqlRaiseError(); - } - // Determine which queries that should return data, and which - // should return an error code only. - return $ismanip ? DB_OK : $result; - } - - // }}} - // {{{ nextResult() - - /** - * Move the internal mssql result pointer to the next available result - * - * @param a valid fbsql result resource - * - * @access public - * - * @return true if a result is available otherwise return false - */ - function nextResult($result) - { - return @mssql_next_result($result); - } - - // }}} - // {{{ fetchInto() - - /** - * Fetch a row and insert the data into an existing array. - * - * Formating of the array and the data therein are configurable. - * See DB_result::fetchInto() for more information. - * - * @param resource $result query result identifier - * @param array $arr (reference) array where data from the row - * should be placed - * @param int $fetchmode how the resulting array should be indexed - * @param int $rownum the row number to fetch - * - * @return mixed DB_OK on success, null when end of result set is - * reached or on failure - * - * @see DB_result::fetchInto() - * @access private - */ - function fetchInto($result, &$arr, $fetchmode, $rownum=null) - { - if ($rownum !== null) { - if (!@mssql_data_seek($result, $rownum)) { - return null; - } - } - if ($fetchmode & DB_FETCHMODE_ASSOC) { - $arr = @mssql_fetch_array($result, MSSQL_ASSOC); - if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) { - $arr = array_change_key_case($arr, CASE_LOWER); - } - } else { - $arr = @mssql_fetch_row($result); - } - if (!$arr) { - /* This throws informative error messages, - don't use it for now - if ($msg = @mssql_get_last_message()) { - return $this->raiseError($msg); - } - */ - return null; - } - if ($this->options['portability'] & DB_PORTABILITY_RTRIM) { - $this->_rtrimArrayValues($arr); - } - if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) { - $this->_convertNullArrayValuesToEmpty($arr); - } - return DB_OK; - } - - // }}} - // {{{ freeResult() - - function freeResult($result) - { - return @mssql_free_result($result); - } - - // }}} - // {{{ numCols() - - function numCols($result) - { - $cols = @mssql_num_fields($result); - if (!$cols) { - return $this->mssqlRaiseError(); - } - return $cols; - } - - // }}} - // {{{ numRows() - - function numRows($result) - { - $rows = @mssql_num_rows($result); - if ($rows === false) { - return $this->mssqlRaiseError(); - } - return $rows; - } - - // }}} - // {{{ autoCommit() - - /** - * Enable/disable automatic commits - */ - function autoCommit($onoff = false) - { - // XXX if $this->transaction_opcount > 0, we should probably - // issue a warning here. - $this->autocommit = $onoff ? true : false; - return DB_OK; - } - - // }}} - // {{{ commit() - - /** - * Commit the current transaction. - */ - function commit() - { - if ($this->transaction_opcount > 0) { - if (!@mssql_select_db($this->_db, $this->connection)) { - return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED); - } - $result = @mssql_query('COMMIT TRAN', $this->connection); - $this->transaction_opcount = 0; - if (!$result) { - return $this->mssqlRaiseError(); - } - } - return DB_OK; - } - - // }}} - // {{{ rollback() - - /** - * Roll back (undo) the current transaction. - */ - function rollback() - { - if ($this->transaction_opcount > 0) { - if (!@mssql_select_db($this->_db, $this->connection)) { - return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED); - } - $result = @mssql_query('ROLLBACK TRAN', $this->connection); - $this->transaction_opcount = 0; - if (!$result) { - return $this->mssqlRaiseError(); - } - } - return DB_OK; - } - - // }}} - // {{{ affectedRows() - - /** - * Gets the number of rows affected by the last query. - * if the last query was a select, returns 0. - * - * @return number of rows affected by the last query or DB_ERROR - */ - function affectedRows() - { - if (DB::isManip($this->last_query)) { - $res = @mssql_query('select @@rowcount', $this->connection); - if (!$res) { - return $this->mssqlRaiseError(); - } - $ar = @mssql_fetch_row($res); - if (!$ar) { - $result = 0; - } else { - @mssql_free_result($res); - $result = $ar[0]; - } - } else { - $result = 0; - } - return $result; - } - - // }}} - // {{{ nextId() - - /** - * Returns the next free id in a sequence - * - * @param string $seq_name name of the sequence - * @param boolean $ondemand when true, the seqence is automatically - * created if it does not exist - * - * @return int the next id number in the sequence. DB_Error if problem. - * - * @internal - * @see DB_common::nextID() - * @access public - */ - function nextId($seq_name, $ondemand = true) - { - $seqname = $this->getSequenceName($seq_name); - if (!@mssql_select_db($this->_db, $this->connection)) { - return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED); - } - $repeat = 0; - do { - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $result = $this->query("INSERT INTO $seqname (vapor) VALUES (0)"); - $this->popErrorHandling(); - if ($ondemand && DB::isError($result) && - ($result->getCode() == DB_ERROR || $result->getCode() == DB_ERROR_NOSUCHTABLE)) - { - $repeat = 1; - $result = $this->createSequence($seq_name); - if (DB::isError($result)) { - return $this->raiseError($result); - } - } elseif (!DB::isError($result)) { - $result =& $this->query("SELECT @@IDENTITY FROM $seqname"); - $repeat = 0; - } else { - $repeat = false; - } - } while ($repeat); - if (DB::isError($result)) { - return $this->raiseError($result); - } - $result = $result->fetchRow(DB_FETCHMODE_ORDERED); - return $result[0]; - } - - /** - * Creates a new sequence - * - * @param string $seq_name name of the new sequence - * - * @return int DB_OK on success. A DB_Error object is returned if - * problems arise. - * - * @internal - * @see DB_common::createSequence() - * @access public - */ - function createSequence($seq_name) - { - $seqname = $this->getSequenceName($seq_name); - return $this->query("CREATE TABLE $seqname ". - '([id] [int] IDENTITY (1, 1) NOT NULL ,' . - '[vapor] [int] NULL)'); - } - - // }}} - // {{{ dropSequence() - - /** - * Deletes a sequence - * - * @param string $seq_name name of the sequence to be deleted - * - * @return int DB_OK on success. DB_Error if problems. - * - * @internal - * @see DB_common::dropSequence() - * @access public - */ - function dropSequence($seq_name) - { - $seqname = $this->getSequenceName($seq_name); - return $this->query("DROP TABLE $seqname"); - } - - // }}} - // {{{ errorNative() - - /** - * Determine MS SQL Server error code by querying @@ERROR. - * - * @return mixed mssql's native error code or DB_ERROR if unknown. - */ - function errorNative() - { - $res = @mssql_query('select @@ERROR as ErrorCode', $this->connection); - if (!$res) { - return DB_ERROR; - } - $row = @mssql_fetch_row($res); - return $row[0]; - } - - // }}} - // {{{ errorCode() - - /** - * Determine PEAR::DB error code from mssql's native codes. - * - * If $nativecode isn't known yet, it will be looked up. - * - * @param mixed $nativecode mssql error code, if known - * @return integer an error number from a DB error constant - * @see errorNative() - */ - function errorCode($nativecode = null) - { - if (!$nativecode) { - $nativecode = $this->errorNative(); - } - if (isset($this->errorcode_map[$nativecode])) { - return $this->errorcode_map[$nativecode]; - } else { - return DB_ERROR; - } - } - - // }}} - // {{{ mssqlRaiseError() - - /** - * Gather information about an error, then use that info to create a - * DB error object and finally return that object. - * - * @param integer $code PEAR error number (usually a DB constant) if - * manually raising an error - * @return object DB error object - * @see errorCode() - * @see errorNative() - * @see DB_common::raiseError() - */ - function mssqlRaiseError($code = null) - { - $message = @mssql_get_last_message(); - if (!$code) { - $code = $this->errorNative(); - } - return $this->raiseError($this->errorCode($code), null, null, null, - "$code - $message"); - } - - // }}} - // {{{ tableInfo() - - /** - * Returns information about a table or a result set. - * - * NOTE: only supports 'table' and 'flags' if $result - * is a table name. - * - * @param object|string $result DB_result object from a query or a - * string containing the name of a table - * @param int $mode a valid tableInfo mode - * @return array an associative array with the information requested - * or an error object if something is wrong - * @access public - * @internal - * @see DB_common::tableInfo() - */ - function tableInfo($result, $mode = null) - { - if (isset($result->result)) { - /* - * Probably received a result object. - * Extract the result resource identifier. - */ - $id = $result->result; - $got_string = false; - } elseif (is_string($result)) { - /* - * Probably received a table name. - * Create a result resource identifier. - */ - if (!@mssql_select_db($this->_db, $this->connection)) { - return $this->mssqlRaiseError(DB_ERROR_NODBSELECTED); - } - $id = @mssql_query("SELECT * FROM $result WHERE 1=0", - $this->connection); - $got_string = true; - } else { - /* - * Probably received a result resource identifier. - * Copy it. - * Deprecated. Here for compatibility only. - */ - $id = $result; - $got_string = false; - } - - if (!is_resource($id)) { - return $this->mssqlRaiseError(DB_ERROR_NEED_MORE_DATA); - } - - if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) { - $case_func = 'strtolower'; - } else { - $case_func = 'strval'; - } - - $count = @mssql_num_fields($id); - - // made this IF due to performance (one if is faster than $count if's) - if (!$mode) { - for ($i=0; $i<$count; $i++) { - $res[$i]['table'] = $got_string ? $case_func($result) : ''; - $res[$i]['name'] = $case_func(@mssql_field_name($id, $i)); - $res[$i]['type'] = @mssql_field_type($id, $i); - $res[$i]['len'] = @mssql_field_length($id, $i); - // We only support flags for tables - $res[$i]['flags'] = $got_string ? $this->_mssql_field_flags($result, $res[$i]['name']) : ''; - } - - } else { // full - $res['num_fields']= $count; - - for ($i=0; $i<$count; $i++) { - $res[$i]['table'] = $got_string ? $case_func($result) : ''; - $res[$i]['name'] = $case_func(@mssql_field_name($id, $i)); - $res[$i]['type'] = @mssql_field_type($id, $i); - $res[$i]['len'] = @mssql_field_length($id, $i); - // We only support flags for tables - $res[$i]['flags'] = $got_string ? $this->_mssql_field_flags($result, $res[$i]['name']) : ''; - - if ($mode & DB_TABLEINFO_ORDER) { - $res['order'][$res[$i]['name']] = $i; - } - if ($mode & DB_TABLEINFO_ORDERTABLE) { - $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i; - } - } - } - - // free the result only if we were called on a table - if ($got_string) { - @mssql_free_result($id); - } - return $res; - } - - // }}} - // {{{ getSpecialQuery() - - /** - * Returns the query needed to get some backend info - * @param string $type What kind of info you want to retrieve - * @return string The SQL query string - */ - function getSpecialQuery($type) - { - switch ($type) { - case 'tables': - return "select name from sysobjects where type = 'U' order by name"; - case 'views': - return "select name from sysobjects where type = 'V'"; - default: - return null; - } - } - - // }}} - // {{{ _mssql_field_flags() - - /** - * Get the flags for a field, currently supports "not_null", "primary_key", - * "auto_increment" (mssql identity), "timestamp" (mssql timestamp), - * "unique_key" (mssql unique index, unique check or primary_key) and - * "multiple_key" (multikey index) - * - * mssql timestamp is NOT similar to the mysql timestamp so this is maybe - * not useful at all - is the behaviour of mysql_field_flags that primary - * keys are alway unique? is the interpretation of multiple_key correct? - * - * @param string The table name - * @param string The field - * @author Joern Barthel - * @access private - */ - function _mssql_field_flags($table, $column) - { - static $tableName = null; - static $flags = array(); - - if ($table != $tableName) { - - $flags = array(); - $tableName = $table; - - // get unique and primary keys - $res = $this->getAll("EXEC SP_HELPINDEX[$table]", DB_FETCHMODE_ASSOC); - - foreach ($res as $val) { - $keys = explode(', ', $val['index_keys']); - - if (sizeof($keys) > 1) { - foreach ($keys as $key) { - $this->_add_flag($flags[$key], 'multiple_key'); - } - } - - if (strpos($val['index_description'], 'primary key')) { - foreach ($keys as $key) { - $this->_add_flag($flags[$key], 'primary_key'); - } - } elseif (strpos($val['index_description'], 'unique')) { - foreach ($keys as $key) { - $this->_add_flag($flags[$key], 'unique_key'); - } - } - } - - // get auto_increment, not_null and timestamp - $res = $this->getAll("EXEC SP_COLUMNS[$table]", DB_FETCHMODE_ASSOC); - - foreach ($res as $val) { - $val = array_change_key_case($val, CASE_LOWER); - if ($val['nullable'] == '0') { - $this->_add_flag($flags[$val['column_name']], 'not_null'); - } - if (strpos($val['type_name'], 'identity')) { - $this->_add_flag($flags[$val['column_name']], 'auto_increment'); - } - if (strpos($val['type_name'], 'timestamp')) { - $this->_add_flag($flags[$val['column_name']], 'timestamp'); - } - } - } - - if (array_key_exists($column, $flags)) { - return(implode(' ', $flags[$column])); - } - return ''; - } - - // }}} - // {{{ _add_flag() - - /** - * Adds a string to the flags array if the flag is not yet in there - * - if there is no flag present the array is created. - * - * @param reference Reference to the flag-array - * @param value The flag value - * @access private - * @author Joern Barthel - */ - function _add_flag(&$array, $value) - { - if (!is_array($array)) { - $array = array($value); - } elseif (!in_array($value, $array)) { - array_push($array, $value); - } - } - - // }}} - // {{{ quoteIdentifier() - - /** - * Quote a string so it can be safely used as a table / column name - * - * Quoting style depends on which database driver is being used. - * - * @param string $str identifier name to be quoted - * - * @return string quoted identifier string - * - * @since 1.6.0 - * @access public - */ - function quoteIdentifier($str) - { - return '[' . str_replace(']', ']]', $str) . ']'; - } - - // }}} -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - */ - -?> diff --git a/gulliver/thirdparty/pear/DB/mysql.php b/gulliver/thirdparty/pear/DB/mysql.php deleted file mode 100644 index f7f032c17..000000000 --- a/gulliver/thirdparty/pear/DB/mysql.php +++ /dev/null @@ -1,916 +0,0 @@ - | -// | Maintainer: Daniel Convissor | -// +----------------------------------------------------------------------+ -// -// $Id: mysql.php 3355 2005-06-11 22:14:40Z nbm $ - - -// XXX legend: -// -// XXX ERRORMSG: The error message from the mysql function should -// be registered here. -// -// TODO/wishlist: -// longReadlen -// binmode - - -require_once 'DB/common.php'; - -/** - * Database independent query interface definition for PHP's MySQL - * extension. - * - * This is for MySQL versions 4.0 and below. - * - * @package DB - * @version $Id: mysql.php 3355 2005-06-11 22:14:40Z nbm $ - * @category Database - * @author Stig Bakken - */ -class DB_mysql extends DB_common -{ - // {{{ properties - - var $connection; - var $phptype, $dbsyntax; - var $prepare_tokens = array(); - var $prepare_types = array(); - var $num_rows = array(); - var $transaction_opcount = 0; - var $autocommit = true; - var $fetchmode = DB_FETCHMODE_ORDERED; /* Default fetch mode */ - var $_db = false; - - // }}} - // {{{ constructor - - /** - * DB_mysql constructor. - * - * @access public - */ - function DB_mysql() - { - $this->DB_common(); - $this->phptype = 'mysql'; - $this->dbsyntax = 'mysql'; - $this->features = array( - 'prepare' => false, - 'pconnect' => true, - 'transactions' => true, - 'limit' => 'alter' - ); - $this->errorcode_map = array( - 1004 => DB_ERROR_CANNOT_CREATE, - 1005 => DB_ERROR_CANNOT_CREATE, - 1006 => DB_ERROR_CANNOT_CREATE, - 1007 => DB_ERROR_ALREADY_EXISTS, - 1008 => DB_ERROR_CANNOT_DROP, - 1022 => DB_ERROR_ALREADY_EXISTS, - 1046 => DB_ERROR_NODBSELECTED, - 1048 => DB_ERROR_CONSTRAINT, - 1050 => DB_ERROR_ALREADY_EXISTS, - 1051 => DB_ERROR_NOSUCHTABLE, - 1054 => DB_ERROR_NOSUCHFIELD, - 1062 => DB_ERROR_ALREADY_EXISTS, - 1064 => DB_ERROR_SYNTAX, - 1100 => DB_ERROR_NOT_LOCKED, - 1136 => DB_ERROR_VALUE_COUNT_ON_ROW, - 1146 => DB_ERROR_NOSUCHTABLE, - 1216 => DB_ERROR_CONSTRAINT, - 1217 => DB_ERROR_CONSTRAINT, - ); - } - - // }}} - // {{{ connect() - - /** - * Connect to a database and log in as the specified user. - * - * @param $dsn the data source name (see DB::parseDSN for syntax) - * @param $persistent (optional) whether the connection should - * be persistent - * @access public - * @return int DB_OK on success, a DB error on failure - */ - function connect($dsninfo, $persistent = false) - { - if (!DB::assertExtension('mysql')) { - return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND); - } - $this->dsn = $dsninfo; - if ($dsninfo['protocol'] && $dsninfo['protocol'] == 'unix') { - $dbhost = ':' . $dsninfo['socket']; - } else { - $dbhost = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost'; - if ($dsninfo['port']) { - $dbhost .= ':' . $dsninfo['port']; - } - } - - $connect_function = $persistent ? 'mysql_pconnect' : 'mysql_connect'; - - if ($dbhost && $dsninfo['username'] && isset($dsninfo['password'])) { - $conn = @$connect_function($dbhost, $dsninfo['username'], - $dsninfo['password']); - } elseif ($dbhost && $dsninfo['username']) { - $conn = @$connect_function($dbhost, $dsninfo['username']); - } elseif ($dbhost) { - $conn = @$connect_function($dbhost); - } else { - $conn = false; - } - if (!$conn) { - if (($err = @mysql_error()) != '') { - return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null, - null, $err); - } elseif (empty($php_errormsg)) { - return $this->raiseError(DB_ERROR_CONNECT_FAILED); - } else { - return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null, - null, $php_errormsg); - } - } - - if ($dsninfo['database']) { - if (!@mysql_select_db($dsninfo['database'], $conn)) { - switch(mysql_errno($conn)) { - case 1049: - return $this->raiseError(DB_ERROR_NOSUCHDB, null, null, - null, @mysql_error($conn)); - case 1044: - return $this->raiseError(DB_ERROR_ACCESS_VIOLATION, null, null, - null, @mysql_error($conn)); - default: - return $this->raiseError(DB_ERROR, null, null, - null, @mysql_error($conn)); - } - } - // fix to allow calls to different databases in the same script - $this->_db = $dsninfo['database']; - } - - $this->connection = $conn; - return DB_OK; - } - - // }}} - // {{{ disconnect() - - /** - * Log out and disconnect from the database. - * - * @access public - * - * @return bool true on success, false if not connected. - */ - function disconnect() - { - $ret = @mysql_close($this->connection); - $this->connection = null; - return $ret; - } - - // }}} - // {{{ simpleQuery() - - /** - * Send a query to MySQL and return the results as a MySQL resource - * identifier. - * - * @param the SQL query - * - * @access public - * - * @return mixed returns a valid MySQL result for successful SELECT - * queries, DB_OK for other successful queries. A DB error is - * returned on failure. - */ - function simpleQuery($query) - { - $ismanip = DB::isManip($query); - $this->last_query = $query; - $query = $this->modifyQuery($query); - if ($this->_db) { - if (!@mysql_select_db($this->_db, $this->connection)) { - return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED); - } - } - if (!$this->autocommit && $ismanip) { - if ($this->transaction_opcount == 0) { - $result = @mysql_query('SET AUTOCOMMIT=0', $this->connection); - $result = @mysql_query('BEGIN', $this->connection); - if (!$result) { - return $this->mysqlRaiseError(); - } - } - $this->transaction_opcount++; - } - $result = @mysql_query($query, $this->connection); - if (!$result) { - return $this->mysqlRaiseError(); - } - if (is_resource($result)) { - $numrows = $this->numrows($result); - if (is_object($numrows)) { - return $numrows; - } - $this->num_rows[(int)$result] = $numrows; - return $result; - } - return DB_OK; - } - - // }}} - // {{{ nextResult() - - /** - * Move the internal mysql result pointer to the next available result - * - * This method has not been implemented yet. - * - * @param a valid sql result resource - * - * @access public - * - * @return false - */ - function nextResult($result) - { - return false; - } - - // }}} - // {{{ fetchInto() - - /** - * Fetch a row and insert the data into an existing array. - * - * Formating of the array and the data therein are configurable. - * See DB_result::fetchInto() for more information. - * - * @param resource $result query result identifier - * @param array $arr (reference) array where data from the row - * should be placed - * @param int $fetchmode how the resulting array should be indexed - * @param int $rownum the row number to fetch - * - * @return mixed DB_OK on success, null when end of result set is - * reached or on failure - * - * @see DB_result::fetchInto() - * @access private - */ - function fetchInto($result, &$arr, $fetchmode, $rownum=null) - { - if ($rownum !== null) { - if (!@mysql_data_seek($result, $rownum)) { - return null; - } - } - if ($fetchmode & DB_FETCHMODE_ASSOC) { - $arr = @mysql_fetch_array($result, MYSQL_ASSOC); - if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) { - $arr = array_change_key_case($arr, CASE_LOWER); - } - } else { - $arr = @mysql_fetch_row($result); - } - if (!$arr) { - // See: http://bugs.php.net/bug.php?id=22328 - // for why we can't check errors on fetching - return null; - /* - $errno = @mysql_errno($this->connection); - if (!$errno) { - return null; - } - return $this->mysqlRaiseError($errno); - */ - } - if ($this->options['portability'] & DB_PORTABILITY_RTRIM) { - /* - * Even though this DBMS already trims output, we do this because - * a field might have intentional whitespace at the end that - * gets removed by DB_PORTABILITY_RTRIM under another driver. - */ - $this->_rtrimArrayValues($arr); - } - if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) { - $this->_convertNullArrayValuesToEmpty($arr); - } - return DB_OK; - } - - // }}} - // {{{ freeResult() - - /** - * Free the internal resources associated with $result. - * - * @param $result MySQL result identifier - * - * @access public - * - * @return bool true on success, false if $result is invalid - */ - function freeResult($result) - { - unset($this->num_rows[(int)$result]); - return @mysql_free_result($result); - } - - // }}} - // {{{ numCols() - - /** - * Get the number of columns in a result set. - * - * @param $result MySQL result identifier - * - * @access public - * - * @return int the number of columns per row in $result - */ - function numCols($result) - { - $cols = @mysql_num_fields($result); - - if (!$cols) { - return $this->mysqlRaiseError(); - } - - return $cols; - } - - // }}} - // {{{ numRows() - - /** - * Get the number of rows in a result set. - * - * @param $result MySQL result identifier - * - * @access public - * - * @return int the number of rows in $result - */ - function numRows($result) - { - $rows = @mysql_num_rows($result); - if ($rows === null) { - return $this->mysqlRaiseError(); - } - return $rows; - } - - // }}} - // {{{ autoCommit() - - /** - * Enable/disable automatic commits - */ - function autoCommit($onoff = false) - { - // XXX if $this->transaction_opcount > 0, we should probably - // issue a warning here. - $this->autocommit = $onoff ? true : false; - return DB_OK; - } - - // }}} - // {{{ commit() - - /** - * Commit the current transaction. - */ - function commit() - { - if ($this->transaction_opcount > 0) { - if ($this->_db) { - if (!@mysql_select_db($this->_db, $this->connection)) { - return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED); - } - } - $result = @mysql_query('COMMIT', $this->connection); - $result = @mysql_query('SET AUTOCOMMIT=1', $this->connection); - $this->transaction_opcount = 0; - if (!$result) { - return $this->mysqlRaiseError(); - } - } - return DB_OK; - } - - // }}} - // {{{ rollback() - - /** - * Roll back (undo) the current transaction. - */ - function rollback() - { - if ($this->transaction_opcount > 0) { - if ($this->_db) { - if (!@mysql_select_db($this->_db, $this->connection)) { - return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED); - } - } - $result = @mysql_query('ROLLBACK', $this->connection); - $result = @mysql_query('SET AUTOCOMMIT=1', $this->connection); - $this->transaction_opcount = 0; - if (!$result) { - return $this->mysqlRaiseError(); - } - } - return DB_OK; - } - - // }}} - // {{{ affectedRows() - - /** - * Gets the number of rows affected by the data manipulation - * query. For other queries, this function returns 0. - * - * @return number of rows affected by the last query - */ - function affectedRows() - { - if (DB::isManip($this->last_query)) { - return @mysql_affected_rows($this->connection); - } else { - return 0; - } - } - - // }}} - // {{{ errorNative() - - /** - * Get the native error code of the last error (if any) that - * occured on the current connection. - * - * @access public - * - * @return int native MySQL error code - */ - function errorNative() - { - return @mysql_errno($this->connection); - } - - // }}} - // {{{ nextId() - - /** - * Returns the next free id in a sequence - * - * @param string $seq_name name of the sequence - * @param boolean $ondemand when true, the seqence is automatically - * created if it does not exist - * - * @return int the next id number in the sequence. DB_Error if problem. - * - * @internal - * @see DB_common::nextID() - * @access public - */ - function nextId($seq_name, $ondemand = true) - { - $seqname = $this->getSequenceName($seq_name); - do { - $repeat = 0; - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $result = $this->query("UPDATE ${seqname} ". - 'SET id=LAST_INSERT_ID(id+1)'); - $this->popErrorHandling(); - if ($result === DB_OK) { - /** COMMON CASE **/ - $id = @mysql_insert_id($this->connection); - if ($id != 0) { - return $id; - } - /** EMPTY SEQ TABLE **/ - // Sequence table must be empty for some reason, so fill it and return 1 - // Obtain a user-level lock - $result = $this->getOne("SELECT GET_LOCK('${seqname}_lock',10)"); - if (DB::isError($result)) { - return $this->raiseError($result); - } - if ($result == 0) { - // Failed to get the lock, bail with a DB_ERROR_NOT_LOCKED error - return $this->mysqlRaiseError(DB_ERROR_NOT_LOCKED); - } - - // add the default value - $result = $this->query("REPLACE INTO ${seqname} (id) VALUES (0)"); - if (DB::isError($result)) { - return $this->raiseError($result); - } - - // Release the lock - $result = $this->getOne("SELECT RELEASE_LOCK('${seqname}_lock')"); - if (DB::isError($result)) { - return $this->raiseError($result); - } - // We know what the result will be, so no need to try again - return 1; - - /** ONDEMAND TABLE CREATION **/ - } elseif ($ondemand && DB::isError($result) && - $result->getCode() == DB_ERROR_NOSUCHTABLE) - { - $result = $this->createSequence($seq_name); - if (DB::isError($result)) { - return $this->raiseError($result); - } else { - $repeat = 1; - } - - /** BACKWARDS COMPAT **/ - } elseif (DB::isError($result) && - $result->getCode() == DB_ERROR_ALREADY_EXISTS) - { - // see _BCsequence() comment - $result = $this->_BCsequence($seqname); - if (DB::isError($result)) { - return $this->raiseError($result); - } - $repeat = 1; - } - } while ($repeat); - - return $this->raiseError($result); - } - - // }}} - // {{{ createSequence() - - /** - * Creates a new sequence - * - * @param string $seq_name name of the new sequence - * - * @return int DB_OK on success. A DB_Error object is returned if - * problems arise. - * - * @internal - * @see DB_common::createSequence() - * @access public - */ - function createSequence($seq_name) - { - $seqname = $this->getSequenceName($seq_name); - $res = $this->query("CREATE TABLE ${seqname} ". - '(id INTEGER UNSIGNED AUTO_INCREMENT NOT NULL,'. - ' PRIMARY KEY(id))'); - if (DB::isError($res)) { - return $res; - } - // insert yields value 1, nextId call will generate ID 2 - $res = $this->query("INSERT INTO ${seqname} (id) VALUES (0)"); - if (DB::isError($res)) { - return $res; - } - // so reset to zero - return $this->query("UPDATE ${seqname} SET id = 0;"); - } - - // }}} - // {{{ dropSequence() - - /** - * Deletes a sequence - * - * @param string $seq_name name of the sequence to be deleted - * - * @return int DB_OK on success. DB_Error if problems. - * - * @internal - * @see DB_common::dropSequence() - * @access public - */ - function dropSequence($seq_name) - { - return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name)); - } - - // }}} - // {{{ _BCsequence() - - /** - * Backwards compatibility with old sequence emulation implementation - * (clean up the dupes) - * - * @param string $seqname The sequence name to clean up - * @return mixed DB_Error or true - */ - function _BCsequence($seqname) - { - // Obtain a user-level lock... this will release any previous - // application locks, but unlike LOCK TABLES, it does not abort - // the current transaction and is much less frequently used. - $result = $this->getOne("SELECT GET_LOCK('${seqname}_lock',10)"); - if (DB::isError($result)) { - return $result; - } - if ($result == 0) { - // Failed to get the lock, can't do the conversion, bail - // with a DB_ERROR_NOT_LOCKED error - return $this->mysqlRaiseError(DB_ERROR_NOT_LOCKED); - } - - $highest_id = $this->getOne("SELECT MAX(id) FROM ${seqname}"); - if (DB::isError($highest_id)) { - return $highest_id; - } - // This should kill all rows except the highest - // We should probably do something if $highest_id isn't - // numeric, but I'm at a loss as how to handle that... - $result = $this->query("DELETE FROM ${seqname} WHERE id <> $highest_id"); - if (DB::isError($result)) { - return $result; - } - - // If another thread has been waiting for this lock, - // it will go thru the above procedure, but will have no - // real effect - $result = $this->getOne("SELECT RELEASE_LOCK('${seqname}_lock')"); - if (DB::isError($result)) { - return $result; - } - return true; - } - - // }}} - // {{{ quoteIdentifier() - - /** - * Quote a string so it can be safely used as a table or column name - * - * Quoting style depends on which database driver is being used. - * - * MySQL can't handle the backtick character (`) in - * table or column names. - * - * @param string $str identifier name to be quoted - * - * @return string quoted identifier string - * - * @since 1.6.0 - * @access public - * @internal - */ - function quoteIdentifier($str) - { - return '`' . $str . '`'; - } - - // }}} - // {{{ quote() - - /** - * @deprecated Deprecated in release 1.6.0 - * @internal - */ - function quote($str) { - return $this->quoteSmart($str); - } - - // }}} - // {{{ escapeSimple() - - /** - * Escape a string according to the current DBMS's standards - * - * @param string $str the string to be escaped - * - * @return string the escaped string - * - * @internal - */ - function escapeSimple($str) { - if (function_exists('mysql_real_escape_string')) { - return @mysql_real_escape_string($str, $this->connection); - } else { - return @mysql_escape_string($str); - } - } - - // }}} - // {{{ modifyQuery() - - function modifyQuery($query) - { - if ($this->options['portability'] & DB_PORTABILITY_DELETE_COUNT) { - // "DELETE FROM table" gives 0 affected rows in MySQL. - // This little hack lets you know how many rows were deleted. - if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) { - $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/', - 'DELETE FROM \1 WHERE 1=1', $query); - } - } - return $query; - } - - // }}} - // {{{ modifyLimitQuery() - - function modifyLimitQuery($query, $from, $count, $params = array()) - { - if (DB::isManip($query)) { - return $query . " LIMIT $count"; - } else { - return $query . " LIMIT $from, $count"; - } - } - - // }}} - // {{{ mysqlRaiseError() - - /** - * Gather information about an error, then use that info to create a - * DB error object and finally return that object. - * - * @param integer $errno PEAR error number (usually a DB constant) if - * manually raising an error - * @return object DB error object - * @see DB_common::errorCode() - * @see DB_common::raiseError() - */ - function mysqlRaiseError($errno = null) - { - if ($errno === null) { - if ($this->options['portability'] & DB_PORTABILITY_ERRORS) { - $this->errorcode_map[1022] = DB_ERROR_CONSTRAINT; - $this->errorcode_map[1048] = DB_ERROR_CONSTRAINT_NOT_NULL; - $this->errorcode_map[1062] = DB_ERROR_CONSTRAINT; - } else { - // Doing this in case mode changes during runtime. - $this->errorcode_map[1022] = DB_ERROR_ALREADY_EXISTS; - $this->errorcode_map[1048] = DB_ERROR_CONSTRAINT; - $this->errorcode_map[1062] = DB_ERROR_ALREADY_EXISTS; - } - $errno = $this->errorCode(mysql_errno($this->connection)); - } - return $this->raiseError($errno, null, null, null, - @mysql_errno($this->connection) . ' ** ' . - @mysql_error($this->connection)); - } - - // }}} - // {{{ tableInfo() - - /** - * Returns information about a table or a result set. - * - * @param object|string $result DB_result object from a query or a - * string containing the name of a table - * @param int $mode a valid tableInfo mode - * @return array an associative array with the information requested - * or an error object if something is wrong - * @access public - * @internal - * @see DB_common::tableInfo() - */ - function tableInfo($result, $mode = null) { - if (isset($result->result)) { - /* - * Probably received a result object. - * Extract the result resource identifier. - */ - $id = $result->result; - $got_string = false; - } elseif (is_string($result)) { - /* - * Probably received a table name. - * Create a result resource identifier. - */ - $id = @mysql_list_fields($this->dsn['database'], - $result, $this->connection); - $got_string = true; - } else { - /* - * Probably received a result resource identifier. - * Copy it. - * Deprecated. Here for compatibility only. - */ - $id = $result; - $got_string = false; - } - - if (!is_resource($id)) { - return $this->mysqlRaiseError(DB_ERROR_NEED_MORE_DATA); - } - - if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) { - $case_func = 'strtolower'; - } else { - $case_func = 'strval'; - } - - $count = @mysql_num_fields($id); - - // made this IF due to performance (one if is faster than $count if's) - if (!$mode) { - for ($i=0; $i<$count; $i++) { - $res[$i]['table'] = $case_func(@mysql_field_table($id, $i)); - $res[$i]['name'] = $case_func(@mysql_field_name($id, $i)); - $res[$i]['type'] = @mysql_field_type($id, $i); - $res[$i]['len'] = @mysql_field_len($id, $i); - $res[$i]['flags'] = @mysql_field_flags($id, $i); - } - } else { // full - $res['num_fields']= $count; - - for ($i=0; $i<$count; $i++) { - $res[$i]['table'] = $case_func(@mysql_field_table($id, $i)); - $res[$i]['name'] = $case_func(@mysql_field_name($id, $i)); - $res[$i]['type'] = @mysql_field_type($id, $i); - $res[$i]['len'] = @mysql_field_len($id, $i); - $res[$i]['flags'] = @mysql_field_flags($id, $i); - - if ($mode & DB_TABLEINFO_ORDER) { - $res['order'][$res[$i]['name']] = $i; - } - if ($mode & DB_TABLEINFO_ORDERTABLE) { - $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i; - } - } - } - - // free the result only if we were called on a table - if ($got_string) { - @mysql_free_result($id); - } - return $res; - } - - // }}} - // {{{ getSpecialQuery() - - /** - * Returns the query needed to get some backend info - * @param string $type What kind of info you want to retrieve - * @return string The SQL query string - */ - function getSpecialQuery($type) - { - switch ($type) { - case 'tables': - return 'SHOW TABLES'; - case 'views': - return DB_ERROR_NOT_CAPABLE; - case 'users': - $sql = 'select distinct User from user'; - if ($this->dsn['database'] != 'mysql') { - $dsn = $this->dsn; - $dsn['database'] = 'mysql'; - if (DB::isError($db = DB::connect($dsn))) { - return $db; - } - $sql = $db->getCol($sql); - $db->disconnect(); - // XXX Fixme the mysql driver should take care of this - if (!@mysql_select_db($this->dsn['database'], $this->connection)) { - return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED); - } - } - return $sql; - case 'databases': - return 'SHOW DATABASES'; - default: - return null; - } - } - - // }}} - -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - */ - -?> diff --git a/gulliver/thirdparty/pear/DB/mysqli.php b/gulliver/thirdparty/pear/DB/mysqli.php deleted file mode 100644 index 3c0fd1db4..000000000 --- a/gulliver/thirdparty/pear/DB/mysqli.php +++ /dev/null @@ -1,960 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: mysqli.php 3355 2005-06-11 22:14:40Z nbm $ - - -// EXPERIMENTAL - - -require_once 'DB/common.php'; - -/** - * Database independent query interface definition for PHP's mysqli - * extension. - * - * This is for MySQL versions 4.1 and above. Requires PHP 5. - * - * Note that persistent connections no longer exist. - * - * @package DB - * @version $Id: mysqli.php 3355 2005-06-11 22:14:40Z nbm $ - * @category Database - * @author Daniel Convissor - * @since Class functional since Release 1.6.3 - */ -class DB_mysqli extends DB_common -{ - // {{{ properties - - var $connection; - var $phptype, $dbsyntax; - var $prepare_tokens = array(); - var $prepare_types = array(); - var $num_rows = array(); - var $transaction_opcount = 0; - var $autocommit = true; - var $fetchmode = DB_FETCHMODE_ORDERED; /* Default fetch mode */ - var $_db = false; - - /** - * Array for converting MYSQLI_*_FLAG constants to text values - * @var array - * @access public - * @since Property available since Release 1.6.5 - */ - var $mysqli_flags = array( - MYSQLI_NOT_NULL_FLAG => 'not_null', - MYSQLI_PRI_KEY_FLAG => 'primary_key', - MYSQLI_UNIQUE_KEY_FLAG => 'unique_key', - MYSQLI_MULTIPLE_KEY_FLAG => 'multiple_key', - MYSQLI_BLOB_FLAG => 'blob', - MYSQLI_UNSIGNED_FLAG => 'unsigned', - MYSQLI_ZEROFILL_FLAG => 'zerofill', - MYSQLI_AUTO_INCREMENT_FLAG => 'auto_increment', - MYSQLI_TIMESTAMP_FLAG => 'timestamp', - MYSQLI_SET_FLAG => 'set', - // MYSQLI_NUM_FLAG => 'numeric', // unnecessary - // MYSQLI_PART_KEY_FLAG => 'multiple_key', // duplicatvie - MYSQLI_GROUP_FLAG => 'group_by' - ); - - /** - * Array for converting MYSQLI_TYPE_* constants to text values - * @var array - * @access public - * @since Property available since Release 1.6.5 - */ - var $mysqli_types = array( - MYSQLI_TYPE_DECIMAL => 'decimal', - MYSQLI_TYPE_TINY => 'tinyint', - MYSQLI_TYPE_SHORT => 'int', - MYSQLI_TYPE_LONG => 'int', - MYSQLI_TYPE_FLOAT => 'float', - MYSQLI_TYPE_DOUBLE => 'double', - // MYSQLI_TYPE_NULL => 'DEFAULT NULL', // let flags handle it - MYSQLI_TYPE_TIMESTAMP => 'timestamp', - MYSQLI_TYPE_LONGLONG => 'bigint', - MYSQLI_TYPE_INT24 => 'mediumint', - MYSQLI_TYPE_DATE => 'date', - MYSQLI_TYPE_TIME => 'time', - MYSQLI_TYPE_DATETIME => 'datetime', - MYSQLI_TYPE_YEAR => 'year', - MYSQLI_TYPE_NEWDATE => 'date', - MYSQLI_TYPE_ENUM => 'enum', - MYSQLI_TYPE_SET => 'set', - MYSQLI_TYPE_TINY_BLOB => 'tinyblob', - MYSQLI_TYPE_MEDIUM_BLOB => 'mediumblob', - MYSQLI_TYPE_LONG_BLOB => 'longblob', - MYSQLI_TYPE_BLOB => 'blob', - MYSQLI_TYPE_VAR_STRING => 'varchar', - MYSQLI_TYPE_STRING => 'char', - MYSQLI_TYPE_GEOMETRY => 'geometry', - ); - - // }}} - // {{{ constructor - - /** - * DB_mysql constructor. - * - * @access public - */ - function DB_mysqli() - { - $this->DB_common(); - $this->phptype = 'mysqli'; - $this->dbsyntax = 'mysqli'; - $this->features = array( - 'prepare' => false, - 'ssl' => true, - 'transactions' => true, - 'limit' => 'alter' - ); - $this->errorcode_map = array( - 1004 => DB_ERROR_CANNOT_CREATE, - 1005 => DB_ERROR_CANNOT_CREATE, - 1006 => DB_ERROR_CANNOT_CREATE, - 1007 => DB_ERROR_ALREADY_EXISTS, - 1008 => DB_ERROR_CANNOT_DROP, - 1022 => DB_ERROR_ALREADY_EXISTS, - 1046 => DB_ERROR_NODBSELECTED, - 1048 => DB_ERROR_CONSTRAINT, - 1050 => DB_ERROR_ALREADY_EXISTS, - 1051 => DB_ERROR_NOSUCHTABLE, - 1054 => DB_ERROR_NOSUCHFIELD, - 1062 => DB_ERROR_ALREADY_EXISTS, - 1064 => DB_ERROR_SYNTAX, - 1100 => DB_ERROR_NOT_LOCKED, - 1136 => DB_ERROR_VALUE_COUNT_ON_ROW, - 1146 => DB_ERROR_NOSUCHTABLE, - 1216 => DB_ERROR_CONSTRAINT, - 1217 => DB_ERROR_CONSTRAINT, - ); - } - - // }}} - // {{{ connect() - - /** - * Connect to a database and log in as the specified user. - * - * @param string $dsn the data source name (see DB::parseDSN for syntax) - * @param boolean $persistent (optional) whether the connection should - * be persistent - * @return mixed DB_OK on success, a DB error on failure - * @access public - */ - function connect($dsninfo, $persistent = false) - { - if (!DB::assertExtension('mysqli')) { - return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND); - } - - $this->dsn = $dsninfo; - $conn = false; - @ini_set('track_errors', true); - - if ($this->getOption('ssl') === true) { - $init = mysqli_init(); - mysqli_ssl_set( - $init, - empty($dsninfo['key']) ? null : $dsninfo['key'], - empty($dsninfo['cert']) ? null : $dsninfo['cert'], - empty($dsninfo['ca']) ? null : $dsninfo['ca'], - empty($dsninfo['capath']) ? null : $dsninfo['capath'], - empty($dsninfo['cipher']) ? null : $dsninfo['cipher'] - ); - if ($conn = @mysqli_real_connect($init, - $dsninfo['hostspec'], - $dsninfo['username'], - $dsninfo['password'], - $dsninfo['database'], - $dsninfo['port'], - $dsninfo['socket'])) - { - $conn = $init; - } - } else { - $conn = @mysqli_connect( - $dsninfo['hostspec'], - $dsninfo['username'], - $dsninfo['password'], - $dsninfo['database'], - $dsninfo['port'], - $dsninfo['socket'] - ); - } - - @ini_restore('track_errors'); - - if (!$conn) { - if (($err = @mysqli_connect_error()) != '') { - return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null, - null, $err); - } elseif (empty($php_errormsg)) { - return $this->raiseError(DB_ERROR_CONNECT_FAILED); - } else { - return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null, - null, $php_errormsg); - } - } - - if ($dsninfo['database']) { - $this->_db = $dsninfo['database']; - } - - $this->connection = $conn; - return DB_OK; - } - - // }}} - // {{{ disconnect() - - /** - * Log out and disconnect from the database. - * - * @return boolean true on success, false if not connected - * @access public - */ - function disconnect() - { - $ret = @mysqli_close($this->connection); - $this->connection = null; - return $ret; - } - - // }}} - // {{{ simpleQuery() - - /** - * Send a query to MySQL and return the results as a MySQL resource - * identifier. - * - * @param string $query the SQL query - * @return mixed a valid MySQL result for successful SELECT - * queries, DB_OK for other successful queries. - * A DB error is returned on failure. - * @access public - */ - function simpleQuery($query) - { - $ismanip = DB::isManip($query); - $this->last_query = $query; - $query = $this->modifyQuery($query); - if ($this->_db) { - if (!@mysqli_select_db($this->connection, $this->_db)) { - return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED); - } - } - if (!$this->autocommit && $ismanip) { - if ($this->transaction_opcount == 0) { - $result = @mysqli_query($this->connection, 'SET AUTOCOMMIT=0'); - $result = @mysqli_query($this->connection, 'BEGIN'); - if (!$result) { - return $this->mysqlRaiseError(); - } - } - $this->transaction_opcount++; - } - $result = @mysqli_query($this->connection, $query); - if (!$result) { - return $this->mysqlRaiseError(); - } -# this next block is still sketchy.. - if (is_object($result)) { - $numrows = $this->numrows($result); - if (is_object($numrows)) { - return $numrows; - } -# need to come up with different means for next line -# since $result is object (int)$result won't fly... -// $this->num_rows[(int)$result] = $numrows; - return $result; - } - return DB_OK; - } - - // }}} - // {{{ nextResult() - - /** - * Move the internal mysql result pointer to the next available result. - * - * This method has not been implemented yet. - * - * @param resource $result a valid sql result resource - * @return false - * @access public - */ - function nextResult($result) - { - return false; - } - - // }}} - // {{{ fetchInto() - - /** - * Fetch a row and insert the data into an existing array. - * - * Formating of the array and the data therein are configurable. - * See DB_result::fetchInto() for more information. - * - * @param resource $result query result identifier - * @param array $arr (reference) array where data from the row - * should be placed - * @param int $fetchmode how the resulting array should be indexed - * @param int $rownum the row number to fetch - * - * @return mixed DB_OK on success, null when end of result set is - * reached or on failure - * - * @see DB_result::fetchInto() - * @access private - */ - function fetchInto($result, &$arr, $fetchmode, $rownum=null) - { - if ($rownum !== null) { - if (!@mysqli_data_seek($result, $rownum)) { - return null; - } - } - if ($fetchmode & DB_FETCHMODE_ASSOC) { - $arr = @mysqli_fetch_array($result, MYSQLI_ASSOC); - if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) { - $arr = array_change_key_case($arr, CASE_LOWER); - } - } else { - $arr = @mysqli_fetch_row($result); - } - if (!$arr) { - $errno = @mysqli_errno($this->connection); - if (!$errno) { - return null; - } - return $this->mysqlRaiseError($errno); - } - if ($this->options['portability'] & DB_PORTABILITY_RTRIM) { - /* - * Even though this DBMS already trims output, we do this because - * a field might have intentional whitespace at the end that - * gets removed by DB_PORTABILITY_RTRIM under another driver. - */ - $this->_rtrimArrayValues($arr); - } - if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) { - $this->_convertNullArrayValuesToEmpty($arr); - } - return DB_OK; - } - - // }}} - // {{{ freeResult() - - /** - * Free the internal resources associated with $result. - * - * @param resource $result MySQL result identifier - * @return bool true on success, false if $result is invalid - * @access public - */ - function freeResult($result) - { -# need to come up with different means for next line -# since $result is object (int)$result won't fly... -// unset($this->num_rows[(int)$result]); - return @mysqli_free_result($result); - } - - // }}} - // {{{ numCols() - - /** - * Get the number of columns in a result set. - * - * @param $result MySQL result identifier - * - * @access public - * - * @return int the number of columns per row in $result - */ - function numCols($result) - { - $cols = @mysqli_num_fields($result); - - if (!$cols) { - return $this->mysqlRaiseError(); - } - - return $cols; - } - - // }}} - // {{{ numRows() - - /** - * Get the number of rows in a result set. - * - * @param resource $result MySQL result identifier - * @return int the number of rows in $result - * @access public - */ - function numRows($result) - { - $rows = @mysqli_num_rows($result); - if ($rows === null) { - return $this->mysqlRaiseError(); - } - return $rows; - } - - // }}} - // {{{ autoCommit() - - /** - * Enable/disable automatic commits. - */ - function autoCommit($onoff = false) - { - // XXX if $this->transaction_opcount > 0, we should probably - // issue a warning here. - $this->autocommit = $onoff ? true : false; - return DB_OK; - } - - // }}} - // {{{ commit() - - /** - * Commit the current transaction. - */ - function commit() - { - if ($this->transaction_opcount > 0) { - if ($this->_db) { - if (!@mysqli_select_db($this->connection, $this->_db)) { - return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED); - } - } - $result = @mysqli_query($this->connection, 'COMMIT'); - $result = @mysqli_query($this->connection, 'SET AUTOCOMMIT=1'); - $this->transaction_opcount = 0; - if (!$result) { - return $this->mysqlRaiseError(); - } - } - return DB_OK; - } - - // }}} - // {{{ rollback() - - /** - * Roll back (undo) the current transaction. - */ - function rollback() - { - if ($this->transaction_opcount > 0) { - if ($this->_db) { - if (!@mysqli_select_db($this->connection, $this->_db)) { - return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED); - } - } - $result = @mysqli_query($this->connection, 'ROLLBACK'); - $result = @mysqli_query($this->connection, 'SET AUTOCOMMIT=1'); - $this->transaction_opcount = 0; - if (!$result) { - return $this->mysqlRaiseError(); - } - } - return DB_OK; - } - - // }}} - // {{{ affectedRows() - - /** - * Gets the number of rows affected by the data manipulation - * query. For other queries, this function returns 0. - * - * @return integer number of rows affected by the last query - */ - function affectedRows() - { - if (DB::isManip($this->last_query)) { - return @mysqli_affected_rows($this->connection); - } else { - return 0; - } - } - - // }}} - // {{{ errorNative() - - /** - * Get the native error code of the last error (if any) that - * occured on the current connection. - * - * @return int native MySQL error code - * @access public - */ - function errorNative() - { - return @mysqli_errno($this->connection); - } - - // }}} - // {{{ nextId() - - /** - * Returns the next free id in a sequence - * - * @param string $seq_name name of the sequence - * @param boolean $ondemand when true, the seqence is automatically - * created if it does not exist - * - * @return int the next id number in the sequence. DB_Error if problem. - * - * @internal - * @see DB_common::nextID() - * @access public - */ - function nextId($seq_name, $ondemand = true) - { - $seqname = $this->getSequenceName($seq_name); - do { - $repeat = 0; - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $result = $this->query("UPDATE ${seqname} ". - 'SET id=LAST_INSERT_ID(id+1)'); - $this->popErrorHandling(); - if ($result === DB_OK) { - /** COMMON CASE **/ - $id = @mysqli_insert_id($this->connection); - if ($id != 0) { - return $id; - } - /** EMPTY SEQ TABLE **/ - // Sequence table must be empty for some reason, so fill it and return 1 - // Obtain a user-level lock - $result = $this->getOne("SELECT GET_LOCK('${seqname}_lock',10)"); - if (DB::isError($result)) { - return $this->raiseError($result); - } - if ($result == 0) { - // Failed to get the lock, bail with a DB_ERROR_NOT_LOCKED error - return $this->mysqlRaiseError(DB_ERROR_NOT_LOCKED); - } - - // add the default value - $result = $this->query("REPLACE INTO ${seqname} (id) VALUES (0)"); - if (DB::isError($result)) { - return $this->raiseError($result); - } - - // Release the lock - $result = $this->getOne("SELECT RELEASE_LOCK('${seqname}_lock')"); - if (DB::isError($result)) { - return $this->raiseError($result); - } - // We know what the result will be, so no need to try again - return 1; - - /** ONDEMAND TABLE CREATION **/ - } elseif ($ondemand && DB::isError($result) && - $result->getCode() == DB_ERROR_NOSUCHTABLE) - { - $result = $this->createSequence($seq_name); - // Since createSequence initializes the ID to be 1, - // we do not need to retrieve the ID again (or we will get 2) - if (DB::isError($result)) { - return $this->raiseError($result); - } else { - // First ID of a newly created sequence is 1 - return 1; - } - - /** BACKWARDS COMPAT **/ - } elseif (DB::isError($result) && - $result->getCode() == DB_ERROR_ALREADY_EXISTS) - { - // see _BCsequence() comment - $result = $this->_BCsequence($seqname); - if (DB::isError($result)) { - return $this->raiseError($result); - } - $repeat = 1; - } - } while ($repeat); - - return $this->raiseError($result); - } - - /** - * Creates a new sequence - * - * @param string $seq_name name of the new sequence - * - * @return int DB_OK on success. A DB_Error object is returned if - * problems arise. - * - * @internal - * @see DB_common::createSequence() - * @access public - */ - function createSequence($seq_name) - { - $seqname = $this->getSequenceName($seq_name); - $res = $this->query("CREATE TABLE ${seqname} ". - '(id INTEGER UNSIGNED AUTO_INCREMENT NOT NULL,'. - ' PRIMARY KEY(id))'); - if (DB::isError($res)) { - return $res; - } - // insert yields value 1, nextId call will generate ID 2 - return $this->query("INSERT INTO ${seqname} (id) VALUES (0)"); - } - - // }}} - // {{{ dropSequence() - - /** - * Deletes a sequence - * - * @param string $seq_name name of the sequence to be deleted - * - * @return int DB_OK on success. DB_Error if problems. - * - * @internal - * @see DB_common::dropSequence() - * @access public - */ - function dropSequence($seq_name) - { - return $this->query('DROP TABLE ' . $this->getSequenceName($seq_name)); - } - - // }}} - // {{{ _BCsequence() - - /** - * Backwards compatibility with old sequence emulation implementation - * (clean up the dupes). - * - * @param string $seqname The sequence name to clean up - * @return mixed DB_Error or true - */ - function _BCsequence($seqname) - { - // Obtain a user-level lock... this will release any previous - // application locks, but unlike LOCK TABLES, it does not abort - // the current transaction and is much less frequently used. - $result = $this->getOne("SELECT GET_LOCK('${seqname}_lock',10)"); - if (DB::isError($result)) { - return $result; - } - if ($result == 0) { - // Failed to get the lock, can't do the conversion, bail - // with a DB_ERROR_NOT_LOCKED error - return $this->mysqlRaiseError(DB_ERROR_NOT_LOCKED); - } - - $highest_id = $this->getOne("SELECT MAX(id) FROM ${seqname}"); - if (DB::isError($highest_id)) { - return $highest_id; - } - // This should kill all rows except the highest - // We should probably do something if $highest_id isn't - // numeric, but I'm at a loss as how to handle that... - $result = $this->query("DELETE FROM ${seqname} WHERE id <> $highest_id"); - if (DB::isError($result)) { - return $result; - } - - // If another thread has been waiting for this lock, - // it will go thru the above procedure, but will have no - // real effect - $result = $this->getOne("SELECT RELEASE_LOCK('${seqname}_lock')"); - if (DB::isError($result)) { - return $result; - } - return true; - } - - // }}} - // {{{ quoteIdentifier() - - /** - * Quote a string so it can be safely used as a table or column name - * - * Quoting style depends on which database driver is being used. - * - * MySQL can't handle the backtick character (`) in - * table or column names. - * - * @param string $str identifier name to be quoted - * - * @return string quoted identifier string - * - * @since 1.6.0 - * @access public - * @internal - */ - function quoteIdentifier($str) - { - return '`' . $str . '`'; - } - - // }}} - // {{{ escapeSimple() - - /** - * Escape a string according to the current DBMS's standards - * - * @param string $str the string to be escaped - * - * @return string the escaped string - * - * @internal - */ - function escapeSimple($str) { - return @mysqli_real_escape_string($this->connection, $str); - } - - // }}} - // {{{ modifyQuery() - - function modifyQuery($query) - { - return $query; - } - - // }}} - // {{{ modifyLimitQuery() - - function modifyLimitQuery($query, $from, $count, $params = array()) - { - if (DB::isManip($query)) { - return $query . " LIMIT $count"; - } else { - return $query . " LIMIT $from, $count"; - } - } - - // }}} - // {{{ mysqlRaiseError() - - /** - * Gather information about an error, then use that info to create a - * DB error object and finally return that object. - * - * @param integer $errno PEAR error number (usually a DB constant) if - * manually raising an error - * @return object DB error object - * @see DB_common::errorCode() - * @see DB_common::raiseError() - */ - function mysqlRaiseError($errno = null) - { - if ($errno === null) { - if ($this->options['portability'] & DB_PORTABILITY_ERRORS) { - $this->errorcode_map[1022] = DB_ERROR_CONSTRAINT; - $this->errorcode_map[1048] = DB_ERROR_CONSTRAINT_NOT_NULL; - $this->errorcode_map[1062] = DB_ERROR_CONSTRAINT; - } else { - // Doing this in case mode changes during runtime. - $this->errorcode_map[1022] = DB_ERROR_ALREADY_EXISTS; - $this->errorcode_map[1048] = DB_ERROR_CONSTRAINT; - $this->errorcode_map[1062] = DB_ERROR_ALREADY_EXISTS; - } - $errno = $this->errorCode(mysqli_errno($this->connection)); - } - return $this->raiseError($errno, null, null, null, - @mysqli_errno($this->connection) . ' ** ' . - @mysqli_error($this->connection)); - } - - // }}} - // {{{ tableInfo() - - /** - * Returns information about a table or a result set. - * - * WARNING: this method will probably not work because the mysqli_*() - * functions it relies upon may not exist. - * - * @param object|string $result DB_result object from a query or a - * string containing the name of a table - * @param int $mode a valid tableInfo mode - * @return array an associative array with the information requested - * or an error object if something is wrong - * @access public - * @internal - * @see DB_common::tableInfo() - */ - function tableInfo($result, $mode = null) { - if (isset($result->result)) { - /* - * Probably received a result object. - * Extract the result resource identifier. - */ - $id = $result->result; - $got_string = false; - } elseif (is_string($result)) { - /* - * Probably received a table name. - * Create a result resource identifier. - */ - $id = @mysqli_query($this->connection, - "SELECT * FROM $result LIMIT 0"); - $got_string = true; - } else { - /* - * Probably received a result resource identifier. - * Copy it. - * Deprecated. Here for compatibility only. - */ - $id = $result; - $got_string = false; - } - - if (!is_a($id, 'mysqli_result')) { - return $this->mysqlRaiseError(DB_ERROR_NEED_MORE_DATA); - } - - if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) { - $case_func = 'strtolower'; - } else { - $case_func = 'strval'; - } - - $count = @mysqli_num_fields($id); - - // made this IF due to performance (one if is faster than $count if's) - if (!$mode) { - for ($i=0; $i<$count; $i++) { - $tmp = @mysqli_fetch_field($id); - $res[$i]['table'] = $case_func($tmp->table); - $res[$i]['name'] = $case_func($tmp->name); - $res[$i]['type'] = isset($this->mysqli_types[$tmp->type]) ? - $this->mysqli_types[$tmp->type] : - 'unknown'; - $res[$i]['len'] = $tmp->max_length; - - $res[$i]['flags'] = ''; - foreach ($this->mysqli_flags as $const => $means) { - if ($tmp->flags & $const) { - $res[$i]['flags'] .= $means . ' '; - } - } - if ($tmp->def) { - $res[$i]['flags'] .= 'default_' . rawurlencode($tmp->def); - } - $res[$i]['flags'] = trim($res[$i]['flags']); - } - } else { // full - $res['num_fields']= $count; - - for ($i=0; $i<$count; $i++) { - $tmp = @mysqli_fetch_field($id); - $res[$i]['table'] = $case_func($tmp->table); - $res[$i]['name'] = $case_func($tmp->name); - $res[$i]['type'] = isset($this->mysqli_types[$tmp->type]) ? - $this->mysqli_types[$tmp->type] : - 'unknown'; - $res[$i]['len'] = $tmp->max_length; - - $res[$i]['flags'] = ''; - foreach ($this->mysqli_flags as $const => $means) { - if ($tmp->flags & $const) { - $res[$i]['flags'] .= $means . ' '; - } - } - if ($tmp->def) { - $res[$i]['flags'] .= 'default_' . rawurlencode($tmp->def); - } - $res[$i]['flags'] = trim($res[$i]['flags']); - - if ($mode & DB_TABLEINFO_ORDER) { - $res['order'][$res[$i]['name']] = $i; - } - if ($mode & DB_TABLEINFO_ORDERTABLE) { - $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i; - } - } - } - - // free the result only if we were called on a table - if ($got_string) { - @mysqli_free_result($id); - } - return $res; - } - - // }}} - // {{{ getSpecialQuery() - - /** - * Returns the query needed to get some backend info. - * - * @param string $type What kind of info you want to retrieve - * @return string The SQL query string - */ - function getSpecialQuery($type) - { - switch ($type) { - case 'tables': - return 'SHOW TABLES'; - case 'views': - return DB_ERROR_NOT_CAPABLE; - case 'users': - $sql = 'select distinct User from user'; - if ($this->dsn['database'] != 'mysql') { - $dsn = $this->dsn; - $dsn['database'] = 'mysql'; - if (DB::isError($db = DB::connect($dsn))) { - return $db; - } - $sql = $db->getCol($sql); - $db->disconnect(); - // XXX Fixme the mysql driver should take care of this - if (!@mysqli_select_db($this->connection, $this->dsn['database'])) { - return $this->mysqlRaiseError(DB_ERROR_NODBSELECTED); - } - } - return $sql; - case 'databases': - return 'SHOW DATABASES'; - default: - return null; - } - } - - // }}} - -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - */ - -?> diff --git a/gulliver/thirdparty/pear/DB/oci8.php b/gulliver/thirdparty/pear/DB/oci8.php deleted file mode 100644 index ad3fb69ae..000000000 --- a/gulliver/thirdparty/pear/DB/oci8.php +++ /dev/null @@ -1,899 +0,0 @@ - | -// | Maintainer: Daniel Convissor | -// +----------------------------------------------------------------------+ -// -// $Id: oci8.php 3355 2005-06-11 22:14:40Z nbm $ - - -// be aware... OCIError() only appears to return anything when given a -// statement, so functions return the generic DB_ERROR instead of more -// useful errors that have to do with feedback from the database. - - -require_once 'DB/common.php'; - -/** - * Database independent query interface definition for PHP's Oracle 8 - * call-interface extension. - * - * Definitely works with versions 8 and 9 of Oracle. - * - * @package DB - * @version $Id: oci8.php 3355 2005-06-11 22:14:40Z nbm $ - * @category Database - * @author James L. Pine - */ -class DB_oci8 extends DB_common -{ - // {{{ properties - - var $connection; - var $phptype, $dbsyntax; - var $manip_query = array(); - var $prepare_types = array(); - var $autoCommit = 1; - var $last_stmt = false; - - /** - * stores the $data passed to execute() in the oci8 driver - * - * Gets reset to array() when simpleQuery() is run. - * - * Needed in case user wants to call numRows() after prepare/execute - * was used. - * - * @var array - * @access private - */ - var $_data = array(); - - // }}} - // {{{ constructor - - function DB_oci8() - { - $this->DB_common(); - $this->phptype = 'oci8'; - $this->dbsyntax = 'oci8'; - $this->features = array( - 'prepare' => false, - 'pconnect' => true, - 'transactions' => true, - 'limit' => 'alter' - ); - $this->errorcode_map = array( - 1 => DB_ERROR_CONSTRAINT, - 900 => DB_ERROR_SYNTAX, - 904 => DB_ERROR_NOSUCHFIELD, - 921 => DB_ERROR_SYNTAX, - 923 => DB_ERROR_SYNTAX, - 942 => DB_ERROR_NOSUCHTABLE, - 955 => DB_ERROR_ALREADY_EXISTS, - 1400 => DB_ERROR_CONSTRAINT_NOT_NULL, - 1407 => DB_ERROR_CONSTRAINT_NOT_NULL, - 1476 => DB_ERROR_DIVZERO, - 1722 => DB_ERROR_INVALID_NUMBER, - 2289 => DB_ERROR_NOSUCHTABLE, - 2291 => DB_ERROR_CONSTRAINT, - 2292 => DB_ERROR_CONSTRAINT, - 2449 => DB_ERROR_CONSTRAINT, - ); - } - - // }}} - // {{{ connect() - - /** - * Connect to a database and log in as the specified user. - * - * @param $dsn the data source name (see DB::parseDSN for syntax) - * @param $persistent (optional) whether the connection should - * be persistent - * - * @return int DB_OK on success, a DB error code on failure - */ - function connect($dsninfo, $persistent = false) - { - if (!DB::assertExtension('oci8')) { - return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND); - } - $this->dsn = $dsninfo; - - $connect_function = $persistent ? 'OCIPLogon' : 'OCILogon'; - - if ($dsninfo['hostspec']) { - $conn = @$connect_function($dsninfo['username'], - $dsninfo['password'], - $dsninfo['hostspec']); - } elseif ($dsninfo['username'] || $dsninfo['password']) { - $conn = @$connect_function($dsninfo['username'], - $dsninfo['password']); - } else { - $conn = false; - } - if ($conn == false) { - $error = OCIError(); - $error = (is_array($error)) ? $error['message'] : null; - return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null, - null, $error); - } - $this->connection = $conn; - return DB_OK; - } - - // }}} - // {{{ disconnect() - - /** - * Log out and disconnect from the database. - * - * @return bool true on success, false if not connected. - */ - function disconnect() - { - $ret = @OCILogOff($this->connection); - $this->connection = null; - return $ret; - } - - // }}} - // {{{ simpleQuery() - - /** - * Send a query to oracle and return the results as an oci8 resource - * identifier. - * - * @param $query the SQL query - * - * @return int returns a valid oci8 result for successful SELECT - * queries, DB_OK for other successful queries. A DB error code - * is returned on failure. - */ - function simpleQuery($query) - { - $this->_data = array(); - $this->last_query = $query; - $query = $this->modifyQuery($query); - $result = @OCIParse($this->connection, $query); - if (!$result) { - return $this->oci8RaiseError(); - } - if ($this->autoCommit) { - $success = @OCIExecute($result,OCI_COMMIT_ON_SUCCESS); - } else { - $success = @OCIExecute($result,OCI_DEFAULT); - } - if (!$success) { - return $this->oci8RaiseError($result); - } - $this->last_stmt=$result; - // Determine which queries that should return data, and which - // should return an error code only. - return DB::isManip($query) ? DB_OK : $result; - } - - // }}} - // {{{ nextResult() - - /** - * Move the internal oracle result pointer to the next available result - * - * @param a valid oci8 result resource - * - * @access public - * - * @return true if a result is available otherwise return false - */ - function nextResult($result) - { - return false; - } - - // }}} - // {{{ fetchInto() - - /** - * Fetch a row and insert the data into an existing array. - * - * Formating of the array and the data therein are configurable. - * See DB_result::fetchInto() for more information. - * - * @param resource $result query result identifier - * @param array $arr (reference) array where data from the row - * should be placed - * @param int $fetchmode how the resulting array should be indexed - * @param int $rownum the row number to fetch - * - * @return mixed DB_OK on success, null when end of result set is - * reached or on failure - * - * @see DB_result::fetchInto() - * @access private - */ - function fetchInto($result, &$arr, $fetchmode, $rownum=null) - { - if ($rownum !== null) { - return $this->raiseError(DB_ERROR_NOT_CAPABLE); - } - if ($fetchmode & DB_FETCHMODE_ASSOC) { - $moredata = @OCIFetchInto($result,$arr,OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS); - if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && - $moredata) - { - $arr = array_change_key_case($arr, CASE_LOWER); - } - } else { - $moredata = OCIFetchInto($result,$arr,OCI_RETURN_NULLS+OCI_RETURN_LOBS); - } - if (!$moredata) { - return null; - } - if ($this->options['portability'] & DB_PORTABILITY_RTRIM) { - $this->_rtrimArrayValues($arr); - } - if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) { - $this->_convertNullArrayValuesToEmpty($arr); - } - return DB_OK; - } - - // }}} - // {{{ freeResult() - - /** - * Free the internal resources associated with $result. - * - * @param $result oci8 result identifier - * - * @return bool true on success, false if $result is invalid - */ - function freeResult($result) - { - return @OCIFreeStatement($result); - } - - /** - * Free the internal resources associated with a prepared query. - * - * @param $stmt oci8 statement identifier - * - * @return bool true on success, false if $result is invalid - */ - function freePrepared($stmt) - { - if (isset($this->prepare_types[(int)$stmt])) { - unset($this->prepare_types[(int)$stmt]); - unset($this->manip_query[(int)$stmt]); - } else { - return false; - } - return true; - } - - // }}} - // {{{ numRows() - - function numRows($result) - { - // emulate numRows for Oracle. yuck. - if ($this->options['portability'] & DB_PORTABILITY_NUMROWS && - $result === $this->last_stmt) - { - $countquery = 'SELECT COUNT(*) FROM ('.$this->last_query.')'; - $save_query = $this->last_query; - $save_stmt = $this->last_stmt; - - if (count($this->_data)) { - $smt = $this->prepare('SELECT COUNT(*) FROM ('.$this->last_query.')'); - $count = $this->execute($smt, $this->_data); - } else { - $count =& $this->query($countquery); - } - - if (DB::isError($count) || - DB::isError($row = $count->fetchRow(DB_FETCHMODE_ORDERED))) - { - $this->last_query = $save_query; - $this->last_stmt = $save_stmt; - return $this->raiseError(DB_ERROR_NOT_CAPABLE); - } - return $row[0]; - } - return $this->raiseError(DB_ERROR_NOT_CAPABLE); - } - - // }}} - // {{{ numCols() - - /** - * Get the number of columns in a result set. - * - * @param $result oci8 result identifier - * - * @return int the number of columns per row in $result - */ - function numCols($result) - { - $cols = @OCINumCols($result); - if (!$cols) { - return $this->oci8RaiseError($result); - } - return $cols; - } - - // }}} - // {{{ errorNative() - - /** - * Get the native error code of the last error (if any) that occured - * on the current connection. This does not work, as OCIError does - * not work unless given a statement. If OCIError does return - * something, so will this. - * - * @return int native oci8 error code - */ - function errorNative() - { - if (is_resource($this->last_stmt)) { - $error = @OCIError($this->last_stmt); - } else { - $error = @OCIError($this->connection); - } - if (is_array($error)) { - return $error['code']; - } - return false; - } - - // }}} - // {{{ prepare() - - /** - * Prepares a query for multiple execution with execute(). - * - * With oci8, this is emulated. - * - * prepare() requires a generic query as string like - * INSERT INTO numbers VALUES (?, ?, ?) - * . The ? characters are placeholders. - * - * Three types of placeholders can be used: - * + ? a quoted scalar value, i.e. strings, integers - * + ! value is inserted 'as is' - * + & requires a file name. The file's contents get - * inserted into the query (i.e. saving binary - * data in a db) - * - * Use backslashes to escape placeholder characters if you don't want - * them to be interpreted as placeholders. Example: - * "UPDATE foo SET col=? WHERE col='over \& under'" - * - * - * @param string $query query to be prepared - * @return mixed DB statement resource on success. DB_Error on failure. - */ - function prepare($query) - { - $tokens = preg_split('/((? $val) { - switch ($val) { - case '?': - $types[$token++] = DB_PARAM_SCALAR; - unset($tokens[$key]); - break; - case '&': - $types[$token++] = DB_PARAM_OPAQUE; - unset($tokens[$key]); - break; - case '!': - $types[$token++] = DB_PARAM_MISC; - unset($tokens[$key]); - break; - default: - $tokens[$key] = preg_replace('/\\\([&?!])/', "\\1", $val); - if ($key != $binds) { - $newquery .= $tokens[$key] . ':bind' . $token; - } else { - $newquery .= $tokens[$key]; - } - } - } - - $this->last_query = $query; - $newquery = $this->modifyQuery($newquery); - if (!$stmt = @OCIParse($this->connection, $newquery)) { - return $this->oci8RaiseError(); - } - $this->prepare_types[(int)$stmt] = $types; - $this->manip_query[(int)$stmt] = DB::isManip($query); - return $stmt; - } - - // }}} - // {{{ execute() - - /** - * Executes a DB statement prepared with prepare(). - * - * @param resource $stmt a DB statement resource returned from prepare() - * @param mixed $data array, string or numeric data to be used in - * execution of the statement. Quantity of items - * passed must match quantity of placeholders in - * query: meaning 1 for non-array items or the - * quantity of elements in the array. - * @return int returns an oci8 result resource for successful - * SELECT queries, DB_OK for other successful queries. A DB error - * code is returned on failure. - * @see DB_oci::prepare() - */ - function &execute($stmt, $data = array()) - { - if (!is_array($data)) { - $data = array($data); - } - - $this->_data = $data; - - $types =& $this->prepare_types[(int)$stmt]; - if (count($types) != count($data)) { - $tmp =& $this->raiseError(DB_ERROR_MISMATCH); - return $tmp; - } - - $i = 0; - foreach ($data as $key => $value) { - if ($types[$i] == DB_PARAM_MISC) { - /* - * Oracle doesn't seem to have the ability to pass a - * parameter along unchanged, so strip off quotes from start - * and end, plus turn two single quotes to one single quote, - * in order to avoid the quotes getting escaped by - * Oracle and ending up in the database. - */ - $data[$key] = preg_replace("/^'(.*)'$/", "\\1", $data[$key]); - $data[$key] = str_replace("''", "'", $data[$key]); - } elseif ($types[$i] == DB_PARAM_OPAQUE) { - $fp = @fopen($data[$key], 'rb'); - if (!$fp) { - $tmp =& $this->raiseError(DB_ERROR_ACCESS_VIOLATION); - return $tmp; - } - $data[$key] = fread($fp, filesize($data[$key])); - fclose($fp); - } - if (!@OCIBindByName($stmt, ':bind' . $i, $data[$key], -1)) { - $tmp = $this->oci8RaiseError($stmt); - return $tmp; - } - $i++; - } - if ($this->autoCommit) { - $success = @OCIExecute($stmt, OCI_COMMIT_ON_SUCCESS); - } else { - $success = @OCIExecute($stmt, OCI_DEFAULT); - } - if (!$success) { - $tmp = $this->oci8RaiseError($stmt); - return $tmp; - } - $this->last_stmt = $stmt; - if ($this->manip_query[(int)$stmt]) { - $tmp = DB_OK; - } else { - $tmp =& new DB_result($this, $stmt); - } - return $tmp; - } - - // }}} - // {{{ autoCommit() - - /** - * Enable/disable automatic commits - * - * @param $onoff true/false whether to autocommit - */ - function autoCommit($onoff = false) - { - $this->autoCommit = (bool)$onoff;; - return DB_OK; - } - - // }}} - // {{{ commit() - - /** - * Commit transactions on the current connection - * - * @return DB_ERROR or DB_OK - */ - function commit() - { - $result = @OCICommit($this->connection); - if (!$result) { - return $this->oci8RaiseError(); - } - return DB_OK; - } - - // }}} - // {{{ rollback() - - /** - * Roll back all uncommitted transactions on the current connection. - * - * @return DB_ERROR or DB_OK - */ - function rollback() - { - $result = @OCIRollback($this->connection); - if (!$result) { - return $this->oci8RaiseError(); - } - return DB_OK; - } - - // }}} - // {{{ affectedRows() - - /** - * Gets the number of rows affected by the last query. - * if the last query was a select, returns 0. - * - * @return number of rows affected by the last query or DB_ERROR - */ - function affectedRows() - { - if ($this->last_stmt === false) { - return $this->oci8RaiseError(); - } - $result = @OCIRowCount($this->last_stmt); - if ($result === false) { - return $this->oci8RaiseError($this->last_stmt); - } - return $result; - } - - // }}} - // {{{ modifyQuery() - - function modifyQuery($query) - { - // "SELECT 2+2" must be "SELECT 2+2 FROM dual" in Oracle - if (preg_match('/^\s*SELECT/i', $query) && - !preg_match('/\sFROM\s/i', $query)) { - $query .= ' FROM dual'; - } - return $query; - } - - // }}} - // {{{ modifyLimitQuery() - - /** - * Emulate the row limit support altering the query - * - * @param string $query The query to treat - * @param int $from The row to start to fetch from - * @param int $count The offset - * @return string The modified query - * - * @author Tomas V.V.Cox - */ - function modifyLimitQuery($query, $from, $count, $params = array()) - { - // Let Oracle return the name of the columns instead of - // coding a "home" SQL parser - - if (count($params)) { - $result = $this->prepare("SELECT * FROM ($query) " - . 'WHERE NULL = NULL'); - $tmp =& $this->execute($result, $params); - } else { - $q_fields = "SELECT * FROM ($query) WHERE NULL = NULL"; - - if (!$result = @OCIParse($this->connection, $q_fields)) { - $this->last_query = $q_fields; - return $this->oci8RaiseError(); - } - if (!@OCIExecute($result, OCI_DEFAULT)) { - $this->last_query = $q_fields; - return $this->oci8RaiseError($result); - } - } - - $ncols = OCINumCols($result); - $cols = array(); - for ( $i = 1; $i <= $ncols; $i++ ) { - $cols[] = '"' . OCIColumnName($result, $i) . '"'; - } - $fields = implode(', ', $cols); - // XXX Test that (tip by John Lim) - //if (preg_match('/^\s*SELECT\s+/is', $query, $match)) { - // // Introduce the FIRST_ROWS Oracle query optimizer - // $query = substr($query, strlen($match[0]), strlen($query)); - // $query = "SELECT /* +FIRST_ROWS */ " . $query; - //} - - // Construct the query - // more at: http://marc.theaimsgroup.com/?l=php-db&m=99831958101212&w=2 - // Perhaps this could be optimized with the use of Unions - $query = "SELECT $fields FROM". - " (SELECT rownum as linenum, $fields FROM". - " ($query)". - ' WHERE rownum <= '. ($from + $count) . - ') WHERE linenum >= ' . ++$from; - return $query; - } - - // }}} - // {{{ nextId() - - /** - * Returns the next free id in a sequence - * - * @param string $seq_name name of the sequence - * @param boolean $ondemand when true, the seqence is automatically - * created if it does not exist - * - * @return int the next id number in the sequence. DB_Error if problem. - * - * @internal - * @see DB_common::nextID() - * @access public - */ - function nextId($seq_name, $ondemand = true) - { - $seqname = $this->getSequenceName($seq_name); - $repeat = 0; - do { - $this->expectError(DB_ERROR_NOSUCHTABLE); - $result =& $this->query("SELECT ${seqname}.nextval FROM dual"); - $this->popExpect(); - if ($ondemand && DB::isError($result) && - $result->getCode() == DB_ERROR_NOSUCHTABLE) { - $repeat = 1; - $result = $this->createSequence($seq_name); - if (DB::isError($result)) { - return $this->raiseError($result); - } - } else { - $repeat = 0; - } - } while ($repeat); - if (DB::isError($result)) { - return $this->raiseError($result); - } - $arr = $result->fetchRow(DB_FETCHMODE_ORDERED); - return $arr[0]; - } - - /** - * Creates a new sequence - * - * @param string $seq_name name of the new sequence - * - * @return int DB_OK on success. A DB_Error object is returned if - * problems arise. - * - * @internal - * @see DB_common::createSequence() - * @access public - */ - function createSequence($seq_name) - { - $seqname = $this->getSequenceName($seq_name); - return $this->query("CREATE SEQUENCE ${seqname}"); - } - - // }}} - // {{{ dropSequence() - - /** - * Deletes a sequence - * - * @param string $seq_name name of the sequence to be deleted - * - * @return int DB_OK on success. DB_Error if problems. - * - * @internal - * @see DB_common::dropSequence() - * @access public - */ - function dropSequence($seq_name) - { - $seqname = $this->getSequenceName($seq_name); - return $this->query("DROP SEQUENCE ${seqname}"); - } - - // }}} - // {{{ oci8RaiseError() - - /** - * Gather information about an error, then use that info to create a - * DB error object and finally return that object. - * - * @param integer $errno PEAR error number (usually a DB constant) if - * manually raising an error - * @return object DB error object - * @see DB_common::errorCode() - * @see DB_common::raiseError() - */ - function oci8RaiseError($errno = null) - { - if ($errno === null) { - $error = @OCIError($this->connection); - return $this->raiseError($this->errorCode($error['code']), - null, null, null, $error['message']); - } elseif (is_resource($errno)) { - $error = @OCIError($errno); - return $this->raiseError($this->errorCode($error['code']), - null, null, null, $error['message']); - } - return $this->raiseError($this->errorCode($errno)); - } - - // }}} - // {{{ getSpecialQuery() - - /** - * Returns the query needed to get some backend info - * @param string $type What kind of info you want to retrieve - * @return string The SQL query string - */ - function getSpecialQuery($type) - { - switch ($type) { - case 'tables': - return 'SELECT table_name FROM user_tables'; - default: - return null; - } - } - - // }}} - // {{{ tableInfo() - - /** - * Returns information about a table or a result set. - * - * NOTE: only supports 'table' and 'flags' if $result - * is a table name. - * - * NOTE: flags won't contain index information. - * - * @param object|string $result DB_result object from a query or a - * string containing the name of a table - * @param int $mode a valid tableInfo mode - * @return array an associative array with the information requested - * or an error object if something is wrong - * @access public - * @internal - * @see DB_common::tableInfo() - */ - function tableInfo($result, $mode = null) - { - if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) { - $case_func = 'strtolower'; - } else { - $case_func = 'strval'; - } - - if (is_string($result)) { - /* - * Probably received a table name. - * Create a result resource identifier. - */ - $result = strtoupper($result); - $q_fields = 'SELECT column_name, data_type, data_length, ' - . 'nullable ' - . 'FROM user_tab_columns ' - . "WHERE table_name='$result' ORDER BY column_id"; - - $this->last_query = $q_fields; - - if (!$stmt = @OCIParse($this->connection, $q_fields)) { - return $this->oci8RaiseError(DB_ERROR_NEED_MORE_DATA); - } - if (!@OCIExecute($stmt, OCI_DEFAULT)) { - return $this->oci8RaiseError($stmt); - } - - $i = 0; - while (@OCIFetch($stmt)) { - $res[$i]['table'] = $case_func($result); - $res[$i]['name'] = $case_func(@OCIResult($stmt, 1)); - $res[$i]['type'] = @OCIResult($stmt, 2); - $res[$i]['len'] = @OCIResult($stmt, 3); - $res[$i]['flags'] = (@OCIResult($stmt, 4) == 'N') ? 'not_null' : ''; - - if ($mode & DB_TABLEINFO_ORDER) { - $res['order'][$res[$i]['name']] = $i; - } - if ($mode & DB_TABLEINFO_ORDERTABLE) { - $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i; - } - $i++; - } - - if ($mode) { - $res['num_fields'] = $i; - } - @OCIFreeStatement($stmt); - - } else { - if (isset($result->result)) { - /* - * Probably received a result object. - * Extract the result resource identifier. - */ - $result = $result->result; - } else { - /* - * ELSE, probably received a result resource identifier. - * Deprecated. Here for compatibility only. - */ - } - - if ($result === $this->last_stmt) { - $count = @OCINumCols($result); - - for ($i=0; $i<$count; $i++) { - $res[$i]['table'] = ''; - $res[$i]['name'] = $case_func(@OCIColumnName($result, $i+1)); - $res[$i]['type'] = @OCIColumnType($result, $i+1); - $res[$i]['len'] = @OCIColumnSize($result, $i+1); - $res[$i]['flags'] = ''; - - if ($mode & DB_TABLEINFO_ORDER) { - $res['order'][$res[$i]['name']] = $i; - } - if ($mode & DB_TABLEINFO_ORDERTABLE) { - $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i; - } - } - - if ($mode) { - $res['num_fields'] = $count; - } - - } else { - return $this->raiseError(DB_ERROR_NOT_CAPABLE); - } - } - return $res; - } - - // }}} - -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - */ - -?> diff --git a/gulliver/thirdparty/pear/DB/odbc.php b/gulliver/thirdparty/pear/DB/odbc.php deleted file mode 100644 index 0f0532769..000000000 --- a/gulliver/thirdparty/pear/DB/odbc.php +++ /dev/null @@ -1,585 +0,0 @@ - | -// | Maintainer: Daniel Convissor | -// +----------------------------------------------------------------------+ -// -// $Id: odbc.php 3355 2005-06-11 22:14:40Z nbm $ - - -// XXX legend: -// More info on ODBC errors could be found here: -// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/trblsql/tr_err_odbc_5stz.asp -// -// XXX ERRORMSG: The error message from the odbc function should -// be registered here. - - -require_once 'DB/common.php'; - -/** - * Database independent query interface definition for PHP's ODBC - * extension. - * - * @package DB - * @version $Id: odbc.php 3355 2005-06-11 22:14:40Z nbm $ - * @category Database - * @author Stig Bakken - */ -class DB_odbc extends DB_common -{ - // {{{ properties - - var $connection; - var $phptype, $dbsyntax; - var $row = array(); - - // }}} - // {{{ constructor - - function DB_odbc() - { - $this->DB_common(); - $this->phptype = 'odbc'; - $this->dbsyntax = 'sql92'; - $this->features = array( - 'prepare' => true, - 'pconnect' => true, - 'transactions' => false, - 'limit' => 'emulate' - ); - $this->errorcode_map = array( - '01004' => DB_ERROR_TRUNCATED, - '07001' => DB_ERROR_MISMATCH, - '21S01' => DB_ERROR_MISMATCH, - '21S02' => DB_ERROR_MISMATCH, - '22003' => DB_ERROR_INVALID_NUMBER, - '22005' => DB_ERROR_INVALID_NUMBER, - '22008' => DB_ERROR_INVALID_DATE, - '22012' => DB_ERROR_DIVZERO, - '23000' => DB_ERROR_CONSTRAINT, - '23502' => DB_ERROR_CONSTRAINT_NOT_NULL, - '23503' => DB_ERROR_CONSTRAINT, - '23505' => DB_ERROR_CONSTRAINT, - '24000' => DB_ERROR_INVALID, - '34000' => DB_ERROR_INVALID, - '37000' => DB_ERROR_SYNTAX, - '42000' => DB_ERROR_SYNTAX, - '42601' => DB_ERROR_SYNTAX, - 'IM001' => DB_ERROR_UNSUPPORTED, - 'S0000' => DB_ERROR_NOSUCHTABLE, - 'S0001' => DB_ERROR_ALREADY_EXISTS, - 'S0002' => DB_ERROR_NOSUCHTABLE, - 'S0011' => DB_ERROR_ALREADY_EXISTS, - 'S0012' => DB_ERROR_NOT_FOUND, - 'S0021' => DB_ERROR_ALREADY_EXISTS, - 'S0022' => DB_ERROR_NOSUCHFIELD, - 'S1000' => DB_ERROR_CONSTRAINT_NOT_NULL, - 'S1009' => DB_ERROR_INVALID, - 'S1090' => DB_ERROR_INVALID, - 'S1C00' => DB_ERROR_NOT_CAPABLE - ); - } - - // }}} - // {{{ connect() - - /** - * Connect to a database and log in as the specified user. - * - * @param $dsn the data source name (see DB::parseDSN for syntax) - * @param $persistent (optional) whether the connection should - * be persistent - * - * @return int DB_OK on success, a DB error code on failure - */ - function connect($dsninfo, $persistent = false) - { - if (!DB::assertExtension('odbc')) { - return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND); - } - - $this->dsn = $dsninfo; - if ($dsninfo['dbsyntax']) { - $this->dbsyntax = $dsninfo['dbsyntax']; - } - switch ($this->dbsyntax) { - case 'solid': - $this->features = array( - 'prepare' => true, - 'pconnect' => true, - 'transactions' => true - ); - break; - case 'navision': - // the Navision driver doesn't support fetch row by number - $this->features['limit'] = false; - } - - /* - * This is hear for backwards compatibility. - * Should have been using 'database' all along, but used hostspec. - */ - if ($dsninfo['database']) { - $odbcdsn = $dsninfo['database']; - } elseif ($dsninfo['hostspec']) { - $odbcdsn = $dsninfo['hostspec']; - } else { - $odbcdsn = 'localhost'; - } - - if ($this->provides('pconnect')) { - $connect_function = $persistent ? 'odbc_pconnect' : 'odbc_connect'; - } else { - $connect_function = 'odbc_connect'; - } - - if (empty($dsninfo['cursor'])) { - $conn = @$connect_function($odbcdsn, $dsninfo['username'], - $dsninfo['password']); - } else { - $conn = @$connect_function($odbcdsn, $dsninfo['username'], - $dsninfo['password'], - $dsninfo['cursor']); - } - - if (!is_resource($conn)) { - return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, null, - null, $this->errorNative()); - } - $this->connection = $conn; - return DB_OK; - } - - // }}} - // {{{ disconnect() - - function disconnect() - { - $err = @odbc_close($this->connection); - $this->connection = null; - return $err; - } - - // }}} - // {{{ simpleQuery() - - /** - * Send a query to ODBC and return the results as a ODBC resource - * identifier. - * - * @param $query the SQL query - * - * @return int returns a valid ODBC result for successful SELECT - * queries, DB_OK for other successful queries. A DB error code - * is returned on failure. - */ - function simpleQuery($query) - { - $this->last_query = $query; - $query = $this->modifyQuery($query); - $result = @odbc_exec($this->connection, $query); - if (!$result) { - return $this->odbcRaiseError(); // XXX ERRORMSG - } - // Determine which queries that should return data, and which - // should return an error code only. - if (DB::isManip($query)) { - $this->manip_result = $result; // For affectedRows() - return DB_OK; - } - $this->row[(int)$result] = 0; - $this->manip_result = 0; - return $result; - } - - // }}} - // {{{ nextResult() - - /** - * Move the internal odbc result pointer to the next available result - * - * @param a valid fbsql result resource - * - * @access public - * - * @return true if a result is available otherwise return false - */ - function nextResult($result) - { - return @odbc_next_result($result); - } - - // }}} - // {{{ fetchInto() - - /** - * Fetch a row and insert the data into an existing array. - * - * Formating of the array and the data therein are configurable. - * See DB_result::fetchInto() for more information. - * - * @param resource $result query result identifier - * @param array $arr (reference) array where data from the row - * should be placed - * @param int $fetchmode how the resulting array should be indexed - * @param int $rownum the row number to fetch - * - * @return mixed DB_OK on success, null when end of result set is - * reached or on failure - * - * @see DB_result::fetchInto() - * @access private - */ - function fetchInto($result, &$arr, $fetchmode, $rownum=null) - { - $arr = array(); - if ($rownum !== null) { - $rownum++; // ODBC first row is 1 - if (version_compare(phpversion(), '4.2.0', 'ge')) { - $cols = @odbc_fetch_into($result, $arr, $rownum); - } else { - $cols = @odbc_fetch_into($result, $rownum, $arr); - } - } else { - $cols = @odbc_fetch_into($result, $arr); - } - - if (!$cols) { - /* XXX FIXME: doesn't work with unixODBC and easysoft - (get corrupted $errno values) - if ($errno = @odbc_error($this->connection)) { - return $this->RaiseError($errno); - }*/ - return null; - } - if ($fetchmode !== DB_FETCHMODE_ORDERED) { - for ($i = 0; $i < count($arr); $i++) { - $colName = @odbc_field_name($result, $i+1); - $a[$colName] = $arr[$i]; - } - if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) { - $a = array_change_key_case($a, CASE_LOWER); - } - $arr = $a; - } - if ($this->options['portability'] & DB_PORTABILITY_RTRIM) { - $this->_rtrimArrayValues($arr); - } - if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) { - $this->_convertNullArrayValuesToEmpty($arr); - } - return DB_OK; - } - - // }}} - // {{{ freeResult() - - function freeResult($result) - { - unset($this->row[(int)$result]); - return @odbc_free_result($result); - } - - // }}} - // {{{ numCols() - - function numCols($result) - { - $cols = @odbc_num_fields($result); - if (!$cols) { - return $this->odbcRaiseError(); - } - return $cols; - } - - // }}} - // {{{ affectedRows() - - /** - * Returns the number of rows affected by a manipulative query - * (INSERT, DELETE, UPDATE) - * @return mixed int affected rows, 0 when non manip queries or - * DB error on error - */ - function affectedRows() - { - if (empty($this->manip_result)) { // In case of SELECT stms - return 0; - } - $nrows = @odbc_num_rows($this->manip_result); - if ($nrows == -1) { - return $this->odbcRaiseError(); - } - return $nrows; - } - - // }}} - // {{{ numRows() - - /** - * ODBC may or may not support counting rows in the result set of - * SELECTs. - * - * @param $result the odbc result resource - * @return the number of rows, or 0 - */ - function numRows($result) - { - $nrows = @odbc_num_rows($result); - if ($nrows == -1) { - return $this->odbcRaiseError(DB_ERROR_UNSUPPORTED); - } - return $nrows; - } - - // }}} - // {{{ quoteIdentifier() - - /** - * Quote a string so it can be safely used as a table / column name - * - * Quoting style depends on which dbsyntax was passed in the DSN. - * - * Use 'mssql' as the dbsyntax in the DB DSN only if you've unchecked - * "Use ANSI quoted identifiers" when setting up the ODBC data source. - * - * @param string $str identifier name to be quoted - * - * @return string quoted identifier string - * - * @since 1.6.0 - * @access public - */ - function quoteIdentifier($str) - { - switch ($this->dsn['dbsyntax']) { - case 'access': - return '[' . $str . ']'; - case 'mssql': - case 'sybase': - return '[' . str_replace(']', ']]', $str) . ']'; - case 'mysql': - case 'mysqli': - return '`' . $str . '`'; - default: - return '"' . str_replace('"', '""', $str) . '"'; - } - } - - // }}} - // {{{ quote() - - /** - * @deprecated Deprecated in release 1.6.0 - * @internal - */ - function quote($str) { - return $this->quoteSmart($str); - } - - // }}} - // {{{ errorNative() - - /** - * Get the native error code of the last error (if any) that - * occured on the current connection. - * - * @access public - * - * @return int ODBC error code - */ - function errorNative() - { - if (!isset($this->connection) || !is_resource($this->connection)) { - return @odbc_error() . ' ' . @odbc_errormsg(); - } - return @odbc_error($this->connection) . ' ' . @odbc_errormsg($this->connection); - } - - // }}} - // {{{ nextId() - - /** - * Returns the next free id in a sequence - * - * @param string $seq_name name of the sequence - * @param boolean $ondemand when true, the seqence is automatically - * created if it does not exist - * - * @return int the next id number in the sequence. DB_Error if problem. - * - * @internal - * @see DB_common::nextID() - * @access public - */ - function nextId($seq_name, $ondemand = true) - { - $seqname = $this->getSequenceName($seq_name); - $repeat = 0; - do { - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $result = $this->query("update ${seqname} set id = id + 1"); - $this->popErrorHandling(); - if ($ondemand && DB::isError($result) && - $result->getCode() == DB_ERROR_NOSUCHTABLE) { - $repeat = 1; - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $result = $this->createSequence($seq_name); - $this->popErrorHandling(); - if (DB::isError($result)) { - return $this->raiseError($result); - } - $result = $this->query("insert into ${seqname} (id) values(0)"); - } else { - $repeat = 0; - } - } while ($repeat); - - if (DB::isError($result)) { - return $this->raiseError($result); - } - - $result = $this->query("select id from ${seqname}"); - if (DB::isError($result)) { - return $result; - } - - $row = $result->fetchRow(DB_FETCHMODE_ORDERED); - if (DB::isError($row || !$row)) { - return $row; - } - - return $row[0]; - } - - /** - * Creates a new sequence - * - * @param string $seq_name name of the new sequence - * - * @return int DB_OK on success. A DB_Error object is returned if - * problems arise. - * - * @internal - * @see DB_common::createSequence() - * @access public - */ - function createSequence($seq_name) - { - $seqname = $this->getSequenceName($seq_name); - return $this->query("CREATE TABLE ${seqname} ". - '(id integer NOT NULL,'. - ' PRIMARY KEY(id))'); - } - - // }}} - // {{{ dropSequence() - - /** - * Deletes a sequence - * - * @param string $seq_name name of the sequence to be deleted - * - * @return int DB_OK on success. DB_Error if problems. - * - * @internal - * @see DB_common::dropSequence() - * @access public - */ - function dropSequence($seq_name) - { - $seqname = $this->getSequenceName($seq_name); - return $this->query("DROP TABLE ${seqname}"); - } - - // }}} - // {{{ autoCommit() - - function autoCommit($onoff = false) - { - if (!@odbc_autocommit($this->connection, $onoff)) { - return $this->odbcRaiseError(); - } - return DB_OK; - } - - // }}} - // {{{ commit() - - function commit() - { - if (!@odbc_commit($this->connection)) { - return $this->odbcRaiseError(); - } - return DB_OK; - } - - // }}} - // {{{ rollback() - - function rollback() - { - if (!@odbc_rollback($this->connection)) { - return $this->odbcRaiseError(); - } - return DB_OK; - } - - // }}} - // {{{ odbcRaiseError() - - /** - * Gather information about an error, then use that info to create a - * DB error object and finally return that object. - * - * @param integer $errno PEAR error number (usually a DB constant) if - * manually raising an error - * @return object DB error object - * @see errorNative() - * @see DB_common::errorCode() - * @see DB_common::raiseError() - */ - function odbcRaiseError($errno = null) - { - if ($errno === null) { - switch ($this->dbsyntax) { - case 'access': - if ($this->options['portability'] & DB_PORTABILITY_ERRORS) { - $this->errorcode_map['07001'] = DB_ERROR_NOSUCHFIELD; - } else { - // Doing this in case mode changes during runtime. - $this->errorcode_map['07001'] = DB_ERROR_MISMATCH; - } - } - $errno = $this->errorCode(odbc_error($this->connection)); - } - return $this->raiseError($errno, null, null, null, - $this->errorNative()); - } - - // }}} - -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - */ - -?> diff --git a/gulliver/thirdparty/pear/DB/pgsql.php b/gulliver/thirdparty/pear/DB/pgsql.php deleted file mode 100644 index 0a95eb132..000000000 --- a/gulliver/thirdparty/pear/DB/pgsql.php +++ /dev/null @@ -1,847 +0,0 @@ - | -// | Stig Bakken | -// | Maintainer: Daniel Convissor | -// +----------------------------------------------------------------------+ -// -// $Id: pgsql.php 3355 2005-06-11 22:14:40Z nbm $ - -require_once 'DB/common.php'; - -/** - * Database independent query interface definition for PHP's PostgreSQL - * extension. - * - * @package DB - * @version $Id: pgsql.php 3355 2005-06-11 22:14:40Z nbm $ - * @category Database - * @author Rui Hirokawa - * @author Stig Bakken - */ -class DB_pgsql extends DB_common -{ - // {{{ properties - - var $connection; - var $phptype, $dbsyntax; - var $prepare_tokens = array(); - var $prepare_types = array(); - var $transaction_opcount = 0; - var $dsn = array(); - var $row = array(); - var $num_rows = array(); - var $affected = 0; - var $autocommit = true; - var $fetchmode = DB_FETCHMODE_ORDERED; - - // }}} - // {{{ constructor - - function DB_pgsql() - { - $this->DB_common(); - $this->phptype = 'pgsql'; - $this->dbsyntax = 'pgsql'; - $this->features = array( - 'prepare' => false, - 'pconnect' => true, - 'transactions' => true, - 'limit' => 'alter' - ); - $this->errorcode_map = array( - ); - } - - // }}} - // {{{ connect() - - /** - * Connect to a database and log in as the specified user. - * - * @param $dsn the data source name (see DB::parseDSN for syntax) - * @param $persistent (optional) whether the connection should - * be persistent - * - * @return int DB_OK on success, a DB error code on failure. - */ - function connect($dsninfo, $persistent = false) - { - if (!DB::assertExtension('pgsql')) { - return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND); - } - - $this->dsn = $dsninfo; - $protocol = $dsninfo['protocol'] ? $dsninfo['protocol'] : 'tcp'; - $connstr = ''; - - if ($protocol == 'tcp') { - if ($dsninfo['hostspec']) { - $connstr .= 'host=' . $dsninfo['hostspec']; - } - if ($dsninfo['port']) { - $connstr .= ' port=' . $dsninfo['port']; - } - } elseif ($protocol == 'unix') { - // Allow for pg socket in non-standard locations. - if ($dsninfo['socket']) { - $connstr .= 'host=' . $dsninfo['socket']; - } - if ($dsninfo['port']) { - $connstr .= ' port=' . $dsninfo['port']; - } - } - - if ($dsninfo['database']) { - $connstr .= ' dbname=\'' . addslashes($dsninfo['database']) . '\''; - } - if ($dsninfo['username']) { - $connstr .= ' user=\'' . addslashes($dsninfo['username']) . '\''; - } - if ($dsninfo['password']) { - $connstr .= ' password=\'' . addslashes($dsninfo['password']) . '\''; - } - if (!empty($dsninfo['options'])) { - $connstr .= ' options=' . $dsninfo['options']; - } - if (!empty($dsninfo['tty'])) { - $connstr .= ' tty=' . $dsninfo['tty']; - } - - $connect_function = $persistent ? 'pg_pconnect' : 'pg_connect'; - - $ini = ini_get('track_errors'); - if ($ini) { - $conn = @$connect_function($connstr); - } else { - ini_set('track_errors', 1); - $conn = @$connect_function($connstr); - ini_set('track_errors', $ini); - } - if ($conn == false) { - return $this->raiseError(DB_ERROR_CONNECT_FAILED, null, - null, null, strip_tags($php_errormsg)); - } - $this->connection = $conn; - return DB_OK; - } - - // }}} - // {{{ disconnect() - - /** - * Log out and disconnect from the database. - * - * @return bool true on success, false if not connected. - */ - function disconnect() - { - $ret = @pg_close($this->connection); - $this->connection = null; - return $ret; - } - - // }}} - // {{{ simpleQuery() - - /** - * Send a query to PostgreSQL and return the results as a - * PostgreSQL resource identifier. - * - * @param $query the SQL query - * - * @return int returns a valid PostgreSQL result for successful SELECT - * queries, DB_OK for other successful queries. A DB error code - * is returned on failure. - */ - function simpleQuery($query) - { - $ismanip = DB::isManip($query); - $this->last_query = $query; - $query = $this->modifyQuery($query); - if (!$this->autocommit && $ismanip) { - if ($this->transaction_opcount == 0) { - $result = @pg_exec($this->connection, 'begin;'); - if (!$result) { - return $this->pgsqlRaiseError(); - } - } - $this->transaction_opcount++; - } - $result = @pg_exec($this->connection, $query); - if (!$result) { - return $this->pgsqlRaiseError(); - } - // Determine which queries that should return data, and which - // should return an error code only. - if ($ismanip) { - $this->affected = @pg_cmdtuples($result); - return DB_OK; - } elseif (preg_match('/^\s*\(?\s*(SELECT(?!\s+INTO)|EXPLAIN|SHOW)\s/si', $query)) { - /* PostgreSQL commands: - ABORT, ALTER, BEGIN, CLOSE, CLUSTER, COMMIT, COPY, - CREATE, DECLARE, DELETE, DROP TABLE, EXPLAIN, FETCH, - GRANT, INSERT, LISTEN, LOAD, LOCK, MOVE, NOTIFY, RESET, - REVOKE, ROLLBACK, SELECT, SELECT INTO, SET, SHOW, - UNLISTEN, UPDATE, VACUUM - */ - $this->row[(int)$result] = 0; // reset the row counter. - $numrows = $this->numrows($result); - if (is_object($numrows)) { - return $numrows; - } - $this->num_rows[(int)$result] = $numrows; - $this->affected = 0; - return $result; - } else { - $this->affected = 0; - return DB_OK; - } - } - - // }}} - // {{{ nextResult() - - /** - * Move the internal pgsql result pointer to the next available result - * - * @param a valid fbsql result resource - * - * @access public - * - * @return true if a result is available otherwise return false - */ - function nextResult($result) - { - return false; - } - - // }}} - // {{{ errorCode() - - /** - * Determine PEAR::DB error code from the database's text error message. - * - * @param string $errormsg error message returned from the database - * @return integer an error number from a DB error constant - */ - function errorCode($errormsg) - { - static $error_regexps; - if (!isset($error_regexps)) { - $error_regexps = array( - '/(([Rr]elation|[Ss]equence|[Tt]able)( [\"\'].*[\"\'])? does not exist|[Cc]lass ".+" not found)$/' => DB_ERROR_NOSUCHTABLE, - '/[Cc]olumn [\"\'].*[\"\'] .*does not exist/' => DB_ERROR_NOSUCHFIELD, - '/[Rr]elation [\"\'].*[\"\'] already exists|[Cc]annot insert a duplicate key into (a )?unique index.*/' => DB_ERROR_ALREADY_EXISTS, - '/(divide|division) by zero$/' => DB_ERROR_DIVZERO, - '/pg_atoi: error in .*: can\'t parse /' => DB_ERROR_INVALID_NUMBER, - '/invalid input syntax for integer/' => DB_ERROR_INVALID_NUMBER, - '/ttribute [\"\'].*[\"\'] not found$|[Rr]elation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/' => DB_ERROR_NOSUCHFIELD, - '/parser: parse error at or near \"/' => DB_ERROR_SYNTAX, - '/syntax error at/' => DB_ERROR_SYNTAX, - '/permission denied/' => DB_ERROR_ACCESS_VIOLATION, - '/violates not-null constraint/' => DB_ERROR_CONSTRAINT_NOT_NULL, - '/violates [\w ]+ constraint/' => DB_ERROR_CONSTRAINT, - '/referential integrity violation/' => DB_ERROR_CONSTRAINT - ); - } - foreach ($error_regexps as $regexp => $code) { - if (preg_match($regexp, $errormsg)) { - return $code; - } - } - // Fall back to DB_ERROR if there was no mapping. - return DB_ERROR; - } - - // }}} - // {{{ fetchInto() - - /** - * Fetch a row and insert the data into an existing array. - * - * Formating of the array and the data therein are configurable. - * See DB_result::fetchInto() for more information. - * - * @param resource $result query result identifier - * @param array $arr (reference) array where data from the row - * should be placed - * @param int $fetchmode how the resulting array should be indexed - * @param int $rownum the row number to fetch - * - * @return mixed DB_OK on success, null when end of result set is - * reached or on failure - * - * @see DB_result::fetchInto() - * @access private - */ - function fetchInto($result, &$arr, $fetchmode, $rownum=null) - { - $result_int = (int)$result; - $rownum = ($rownum !== null) ? $rownum : $this->row[$result_int]; - if ($rownum >= $this->num_rows[$result_int]) { - return null; - } - if ($fetchmode & DB_FETCHMODE_ASSOC) { - $arr = @pg_fetch_array($result, $rownum, PGSQL_ASSOC); - if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) { - $arr = array_change_key_case($arr, CASE_LOWER); - } - } else { - $arr = @pg_fetch_row($result, $rownum); - } - if (!$arr) { - $err = pg_errormessage($this->connection); - if (!$err) { - return null; - } - return $this->pgsqlRaiseError(); - } - if ($this->options['portability'] & DB_PORTABILITY_RTRIM) { - $this->_rtrimArrayValues($arr); - } - if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) { - $this->_convertNullArrayValuesToEmpty($arr); - } - $this->row[$result_int] = ++$rownum; - return DB_OK; - } - - // }}} - // {{{ freeResult() - - /** - * Free the internal resources associated with $result. - * - * @param $result int PostgreSQL result identifier - * - * @return bool true on success, false if $result is invalid - */ - function freeResult($result) - { - if (is_resource($result)) { - unset($this->row[(int)$result]); - unset($this->num_rows[(int)$result]); - $this->affected = 0; - return @pg_freeresult($result); - } - return false; - } - - // }}} - // {{{ quote() - - /** - * @deprecated Deprecated in release 1.6.0 - * @internal - */ - function quote($str) { - return $this->quoteSmart($str); - } - - // }}} - // {{{ quoteSmart() - - /** - * Format input so it can be safely used in a query - * - * @param mixed $in data to be quoted - * - * @return mixed Submitted variable's type = returned value: - * + null = the string NULL - * + boolean = string TRUE or FALSE - * + integer or double = the unquoted number - * + other (including strings and numeric strings) = - * the data escaped according to MySQL's settings - * then encapsulated between single quotes - * - * @internal - */ - function quoteSmart($in) - { - if (is_int($in) || is_double($in)) { - return $in; - } elseif (is_bool($in)) { - return $in ? 'TRUE' : 'FALSE'; - } elseif (is_null($in)) { - return 'NULL'; - } else { - return "'" . $this->escapeSimple($in) . "'"; - } - } - - // }}} - // {{{ escapeSimple() - - /** - * Escape a string according to the current DBMS's standards - * - * PostgreSQL treats a backslash as an escape character, so they are - * removed. - * - * Not using pg_escape_string() yet because it requires PostgreSQL - * to be at version 7.2 or greater. - * - * @param string $str the string to be escaped - * - * @return string the escaped string - * - * @internal - */ - function escapeSimple($str) { - return str_replace("'", "''", str_replace('\\', '\\\\', $str)); - } - - // }}} - // {{{ numCols() - - /** - * Get the number of columns in a result set. - * - * @param $result resource PostgreSQL result identifier - * - * @return int the number of columns per row in $result - */ - function numCols($result) - { - $cols = @pg_numfields($result); - if (!$cols) { - return $this->pgsqlRaiseError(); - } - return $cols; - } - - // }}} - // {{{ numRows() - - /** - * Get the number of rows in a result set. - * - * @param $result resource PostgreSQL result identifier - * - * @return int the number of rows in $result - */ - function numRows($result) - { - $rows = @pg_numrows($result); - if ($rows === null) { - return $this->pgsqlRaiseError(); - } - return $rows; - } - - // }}} - // {{{ errorNative() - - /** - * Get the native error code of the last error (if any) that - * occured on the current connection. - * - * @return int native PostgreSQL error code - */ - function errorNative() - { - return pg_errormessage($this->connection); - } - - // }}} - // {{{ autoCommit() - - /** - * Enable/disable automatic commits - */ - function autoCommit($onoff = false) - { - // XXX if $this->transaction_opcount > 0, we should probably - // issue a warning here. - $this->autocommit = $onoff ? true : false; - return DB_OK; - } - - // }}} - // {{{ commit() - - /** - * Commit the current transaction. - */ - function commit() - { - if ($this->transaction_opcount > 0) { - // (disabled) hack to shut up error messages from libpq.a - //@fclose(@fopen("php://stderr", "w")); - $result = @pg_exec($this->connection, 'end;'); - $this->transaction_opcount = 0; - if (!$result) { - return $this->pgsqlRaiseError(); - } - } - return DB_OK; - } - - // }}} - // {{{ rollback() - - /** - * Roll back (undo) the current transaction. - */ - function rollback() - { - if ($this->transaction_opcount > 0) { - $result = @pg_exec($this->connection, 'abort;'); - $this->transaction_opcount = 0; - if (!$result) { - return $this->pgsqlRaiseError(); - } - } - return DB_OK; - } - - // }}} - // {{{ affectedRows() - - /** - * Gets the number of rows affected by the last query. - * if the last query was a select, returns 0. - * - * @return int number of rows affected by the last query or DB_ERROR - */ - function affectedRows() - { - return $this->affected; - } - - // }}} - // {{{ nextId() - - /** - * Returns the next free id in a sequence - * - * @param string $seq_name name of the sequence - * @param boolean $ondemand when true, the seqence is automatically - * created if it does not exist - * - * @return int the next id number in the sequence. DB_Error if problem. - * - * @internal - * @see DB_common::nextID() - * @access public - */ - function nextId($seq_name, $ondemand = true) - { - $seqname = $this->getSequenceName($seq_name); - $repeat = false; - do { - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $result =& $this->query("SELECT NEXTVAL('${seqname}')"); - $this->popErrorHandling(); - if ($ondemand && DB::isError($result) && - $result->getCode() == DB_ERROR_NOSUCHTABLE) { - $repeat = true; - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $result = $this->createSequence($seq_name); - $this->popErrorHandling(); - if (DB::isError($result)) { - return $this->raiseError($result); - } - } else { - $repeat = false; - } - } while ($repeat); - if (DB::isError($result)) { - return $this->raiseError($result); - } - $arr = $result->fetchRow(DB_FETCHMODE_ORDERED); - $result->free(); - return $arr[0]; - } - - // }}} - // {{{ createSequence() - - /** - * Create the sequence - * - * @param string $seq_name the name of the sequence - * @return mixed DB_OK on success or DB error on error - * @access public - */ - function createSequence($seq_name) - { - $seqname = $this->getSequenceName($seq_name); - $result = $this->query("CREATE SEQUENCE ${seqname}"); - return $result; - } - - // }}} - // {{{ dropSequence() - - /** - * Drop a sequence - * - * @param string $seq_name the name of the sequence - * @return mixed DB_OK on success or DB error on error - * @access public - */ - function dropSequence($seq_name) - { - $seqname = $this->getSequenceName($seq_name); - return $this->query("DROP SEQUENCE ${seqname}"); - } - - // }}} - // {{{ modifyLimitQuery() - - function modifyLimitQuery($query, $from, $count, $params = array()) - { - $query = $query . " LIMIT $count OFFSET $from"; - return $query; - } - - // }}} - // {{{ pgsqlRaiseError() - - /** - * Gather information about an error, then use that info to create a - * DB error object and finally return that object. - * - * @param integer $errno PEAR error number (usually a DB constant) if - * manually raising an error - * @return object DB error object - * @see errorNative() - * @see errorCode() - * @see DB_common::raiseError() - */ - function pgsqlRaiseError($errno = null) - { - $native = $this->errorNative(); - if ($errno === null) { - $err = $this->errorCode($native); - } else { - $err = $errno; - } - return $this->raiseError($err, null, null, null, $native); - } - - // }}} - // {{{ _pgFieldFlags() - - /** - * Flags of a Field - * - * @param int $resource PostgreSQL result identifier - * @param int $num_field the field number - * - * @return string The flags of the field ("not_null", "default_value", - * "primary_key", "unique_key" and "multiple_key" - * are supported). The default value is passed - * through rawurlencode() in case there are spaces in it. - * @access private - */ - function _pgFieldFlags($resource, $num_field, $table_name) - { - $field_name = @pg_fieldname($resource, $num_field); - - $result = @pg_exec($this->connection, "SELECT f.attnotnull, f.atthasdef - FROM pg_attribute f, pg_class tab, pg_type typ - WHERE tab.relname = typ.typname - AND typ.typrelid = f.attrelid - AND f.attname = '$field_name' - AND tab.relname = '$table_name'"); - if (@pg_numrows($result) > 0) { - $row = @pg_fetch_row($result, 0); - $flags = ($row[0] == 't') ? 'not_null ' : ''; - - if ($row[1] == 't') { - $result = @pg_exec($this->connection, "SELECT a.adsrc - FROM pg_attribute f, pg_class tab, pg_type typ, pg_attrdef a - WHERE tab.relname = typ.typname AND typ.typrelid = f.attrelid - AND f.attrelid = a.adrelid AND f.attname = '$field_name' - AND tab.relname = '$table_name' AND f.attnum = a.adnum"); - $row = @pg_fetch_row($result, 0); - $num = preg_replace("/'(.*)'::\w+/", "\\1", $row[0]); - $flags .= 'default_' . rawurlencode($num) . ' '; - } - } else { - $flags = ''; - } - $result = @pg_exec($this->connection, "SELECT i.indisunique, i.indisprimary, i.indkey - FROM pg_attribute f, pg_class tab, pg_type typ, pg_index i - WHERE tab.relname = typ.typname - AND typ.typrelid = f.attrelid - AND f.attrelid = i.indrelid - AND f.attname = '$field_name' - AND tab.relname = '$table_name'"); - $count = @pg_numrows($result); - - for ($i = 0; $i < $count ; $i++) { - $row = @pg_fetch_row($result, $i); - $keys = explode(' ', $row[2]); - - if (in_array($num_field + 1, $keys)) { - $flags .= ($row[0] == 't' && $row[1] == 'f') ? 'unique_key ' : ''; - $flags .= ($row[1] == 't') ? 'primary_key ' : ''; - if (count($keys) > 1) - $flags .= 'multiple_key '; - } - } - - return trim($flags); - } - - // }}} - // {{{ tableInfo() - - /** - * Returns information about a table or a result set. - * - * NOTE: only supports 'table' and 'flags' if $result - * is a table name. - * - * @param object|string $result DB_result object from a query or a - * string containing the name of a table - * @param int $mode a valid tableInfo mode - * @return array an associative array with the information requested - * or an error object if something is wrong - * @access public - * @internal - * @see DB_common::tableInfo() - */ - function tableInfo($result, $mode = null) - { - if (isset($result->result)) { - /* - * Probably received a result object. - * Extract the result resource identifier. - */ - $id = $result->result; - $got_string = false; - } elseif (is_string($result)) { - /* - * Probably received a table name. - * Create a result resource identifier. - */ - $id = @pg_exec($this->connection, "SELECT * FROM $result LIMIT 0"); - $got_string = true; - } else { - /* - * Probably received a result resource identifier. - * Copy it. - * Deprecated. Here for compatibility only. - */ - $id = $result; - $got_string = false; - } - - if (!is_resource($id)) { - return $this->pgsqlRaiseError(DB_ERROR_NEED_MORE_DATA); - } - - if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) { - $case_func = 'strtolower'; - } else { - $case_func = 'strval'; - } - - $count = @pg_numfields($id); - - // made this IF due to performance (one if is faster than $count if's) - if (!$mode) { - - for ($i=0; $i<$count; $i++) { - $res[$i]['table'] = $got_string ? $case_func($result) : ''; - $res[$i]['name'] = $case_func(@pg_fieldname($id, $i)); - $res[$i]['type'] = @pg_fieldtype($id, $i); - $res[$i]['len'] = @pg_fieldsize($id, $i); - $res[$i]['flags'] = $got_string ? $this->_pgFieldflags($id, $i, $result) : ''; - } - - } else { // full - $res['num_fields']= $count; - - for ($i=0; $i<$count; $i++) { - $res[$i]['table'] = $got_string ? $case_func($result) : ''; - $res[$i]['name'] = $case_func(@pg_fieldname($id, $i)); - $res[$i]['type'] = @pg_fieldtype($id, $i); - $res[$i]['len'] = @pg_fieldsize($id, $i); - $res[$i]['flags'] = $got_string ? $this->_pgFieldFlags($id, $i, $result) : ''; - - if ($mode & DB_TABLEINFO_ORDER) { - $res['order'][$res[$i]['name']] = $i; - } - if ($mode & DB_TABLEINFO_ORDERTABLE) { - $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i; - } - } - } - - // free the result only if we were called on a table - if ($got_string) { - @pg_freeresult($id); - } - return $res; - } - - // }}} - // {{{ getTablesQuery() - - /** - * Returns the query needed to get some backend info - * @param string $type What kind of info you want to retrieve - * @return string The SQL query string - */ - function getSpecialQuery($type) - { - switch ($type) { - case 'tables': - return "SELECT c.relname as \"Name\" - FROM pg_class c, pg_user u - WHERE c.relowner = u.usesysid AND c.relkind = 'r' - AND not exists (select 1 from pg_views where viewname = c.relname) - AND c.relname !~ '^(pg_|sql_)' - UNION - SELECT c.relname as \"Name\" - FROM pg_class c - WHERE c.relkind = 'r' - AND not exists (select 1 from pg_views where viewname = c.relname) - AND not exists (select 1 from pg_user where usesysid = c.relowner) - AND c.relname !~ '^pg_'"; - case 'views': - // Table cols: viewname | viewowner | definition - return 'SELECT viewname FROM pg_views'; - case 'users': - // cols: usename |usesysid|usecreatedb|usetrace|usesuper|usecatupd|passwd |valuntil - return 'SELECT usename FROM pg_user'; - case 'databases': - return 'SELECT datname FROM pg_database'; - case 'functions': - return 'SELECT proname FROM pg_proc'; - default: - return null; - } - } - - // }}} - -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - */ - -?> diff --git a/gulliver/thirdparty/pear/DB/sqlite.php b/gulliver/thirdparty/pear/DB/sqlite.php deleted file mode 100644 index cd5a12ca3..000000000 --- a/gulliver/thirdparty/pear/DB/sqlite.php +++ /dev/null @@ -1,695 +0,0 @@ - | -// | Mika Tuupola | -// | Maintainer: Daniel Convissor | -// +----------------------------------------------------------------------+ -// -// $Id: sqlite.php 3355 2005-06-11 22:14:40Z nbm $ - -require_once 'DB/common.php'; - -/** - * Database independent query interface definition for the SQLite - * PECL extension. - * - * @package DB - * @version $Id: sqlite.php 3355 2005-06-11 22:14:40Z nbm $ - * @category Database - * @author Urs Gehrig - * @author Mika Tuupola - */ -class DB_sqlite extends DB_common -{ - // {{{ properties - - var $connection; - var $phptype, $dbsyntax; - var $prepare_tokens = array(); - var $prepare_types = array(); - var $_lasterror = ''; - - // }}} - // {{{ constructor - - /** - * Constructor for this class. - * - * Error codes according to sqlite_exec. Error Codes specification is - * in the {@link http://sqlite.org/c_interface.html online manual}. - * - * This errorhandling based on sqlite_exec is not yet implemented. - * - * @access public - */ - function DB_sqlite() - { - - $this->DB_common(); - $this->phptype = 'sqlite'; - $this->dbsyntax = 'sqlite'; - $this->features = array ( - 'prepare' => false, - 'pconnect' => true, - 'transactions' => false, - 'limit' => 'alter' - ); - - // SQLite data types, http://www.sqlite.org/datatypes.html - $this->keywords = array ( - 'BLOB' => '', - 'BOOLEAN' => '', - 'CHARACTER' => '', - 'CLOB' => '', - 'FLOAT' => '', - 'INTEGER' => '', - 'KEY' => '', - 'NATIONAL' => '', - 'NUMERIC' => '', - 'NVARCHAR' => '', - 'PRIMARY' => '', - 'TEXT' => '', - 'TIMESTAMP' => '', - 'UNIQUE' => '', - 'VARCHAR' => '', - 'VARYING' => '' - ); - $this->errorcode_map = array( - ); - } - - // }}} - // {{{ connect() - - /** - * Connect to a database represented by a file. - * - * @param $dsn the data source name; the file is taken as - * database; "sqlite://root:@host/test.db?mode=0644" - * @param $persistent (optional) whether the connection should - * be persistent - * @access public - * @return int DB_OK on success, a DB error on failure - */ - function connect($dsninfo, $persistent = false) - { - if (!DB::assertExtension('sqlite')) { - return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND); - } - - $this->dsn = $dsninfo; - - if ($dsninfo['database']) { - if (!file_exists($dsninfo['database'])) { - if (!touch($dsninfo['database'])) { - return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND); - } - if (!isset($dsninfo['mode']) || - !is_numeric($dsninfo['mode'])) - { - $mode = 0644; - } else { - $mode = octdec($dsninfo['mode']); - } - if (!chmod($dsninfo['database'], $mode)) { - return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND); - } - if (!file_exists($dsninfo['database'])) { - return $this->sqliteRaiseError(DB_ERROR_NOT_FOUND); - } - } - if (!is_file($dsninfo['database'])) { - return $this->sqliteRaiseError(DB_ERROR_INVALID); - } - if (!is_readable($dsninfo['database'])) { - return $this->sqliteRaiseError(DB_ERROR_ACCESS_VIOLATION); - } - } else { - return $this->sqliteRaiseError(DB_ERROR_ACCESS_VIOLATION); - } - - $connect_function = $persistent ? 'sqlite_popen' : 'sqlite_open'; - if (!($conn = @$connect_function($dsninfo['database']))) { - return $this->sqliteRaiseError(DB_ERROR_NODBSELECTED); - } - $this->connection = $conn; - - return DB_OK; - } - - // }}} - // {{{ disconnect() - - /** - * Log out and disconnect from the database. - * - * @access public - * @return bool true on success, false if not connected. - * @todo fix return values - */ - function disconnect() - { - $ret = @sqlite_close($this->connection); - $this->connection = null; - return $ret; - } - - // }}} - // {{{ simpleQuery() - - /** - * Send a query to SQLite and returns the results as a SQLite resource - * identifier. - * - * @param the SQL query - * @access public - * @return mixed returns a valid SQLite result for successful SELECT - * queries, DB_OK for other successful queries. A DB error is - * returned on failure. - */ - function simpleQuery($query) - { - $ismanip = DB::isManip($query); - $this->last_query = $query; - $query = $this->_modifyQuery($query); - ini_set('track_errors', true); - $result = @sqlite_query($query, $this->connection); - ini_restore('track_errors'); - $this->_lasterror = isset($php_errormsg) ? $php_errormsg : ''; - $this->result = $result; - if (!$this->result) { - return $this->sqliteRaiseError(null); - } - - /* sqlite_query() seems to allways return a resource */ - /* so cant use that. Using $ismanip instead */ - if (!$ismanip) { - $numRows = $this->numRows($result); - - /* if numRows() returned PEAR_Error */ - if (is_object($numRows)) { - return $numRows; - } - return $result; - } - return DB_OK; - } - - // }}} - // {{{ nextResult() - - /** - * Move the internal sqlite result pointer to the next available result. - * - * @param a valid sqlite result resource - * @access public - * @return true if a result is available otherwise return false - */ - function nextResult($result) - { - return false; - } - - // }}} - // {{{ fetchInto() - - /** - * Fetch a row and insert the data into an existing array. - * - * Formating of the array and the data therein are configurable. - * See DB_result::fetchInto() for more information. - * - * @param resource $result query result identifier - * @param array $arr (reference) array where data from the row - * should be placed - * @param int $fetchmode how the resulting array should be indexed - * @param int $rownum the row number to fetch - * - * @return mixed DB_OK on success, null when end of result set is - * reached or on failure - * - * @see DB_result::fetchInto() - * @access private - */ - function fetchInto($result, &$arr, $fetchmode, $rownum=null) - { - if ($rownum !== null) { - if (!@sqlite_seek($this->result, $rownum)) { - return null; - } - } - if ($fetchmode & DB_FETCHMODE_ASSOC) { - $arr = @sqlite_fetch_array($result, SQLITE_ASSOC); - if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) { - $arr = array_change_key_case($arr, CASE_LOWER); - } - } else { - $arr = @sqlite_fetch_array($result, SQLITE_NUM); - } - if (!$arr) { - /* See: http://bugs.php.net/bug.php?id=22328 */ - return null; - } - if ($this->options['portability'] & DB_PORTABILITY_RTRIM) { - /* - * Even though this DBMS already trims output, we do this because - * a field might have intentional whitespace at the end that - * gets removed by DB_PORTABILITY_RTRIM under another driver. - */ - $this->_rtrimArrayValues($arr); - } - if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) { - $this->_convertNullArrayValuesToEmpty($arr); - } - return DB_OK; - } - - // }}} - // {{{ freeResult() - - /** - * Free the internal resources associated with $result. - * - * @param $result SQLite result identifier - * @access public - * @return bool true on success, false if $result is invalid - */ - function freeResult(&$result) - { - // XXX No native free? - if (!is_resource($result)) { - return false; - } - $result = null; - return true; - } - - // }}} - // {{{ numCols() - - /** - * Gets the number of columns in a result set. - * - * @return number of columns in a result set - */ - function numCols($result) - { - $cols = @sqlite_num_fields($result); - if (!$cols) { - return $this->sqliteRaiseError(); - } - return $cols; - } - - // }}} - // {{{ numRows() - - /** - * Gets the number of rows affected by a query. - * - * @return number of rows affected by the last query - */ - function numRows($result) - { - $rows = @sqlite_num_rows($result); - if (!is_integer($rows)) { - return $this->raiseError(); - } - return $rows; - } - - // }}} - // {{{ affected() - - /** - * Gets the number of rows affected by a query. - * - * @return number of rows affected by the last query - */ - function affectedRows() - { - return @sqlite_changes($this->connection); - } - - // }}} - // {{{ errorNative() - - /** - * Get the native error string of the last error (if any) that - * occured on the current connection. - * - * This is used to retrieve more meaningfull error messages DB_pgsql - * way since sqlite_last_error() does not provide adequate info. - * - * @return string native SQLite error message - */ - function errorNative() - { - return($this->_lasterror); - } - - // }}} - // {{{ errorCode() - - /** - * Determine PEAR::DB error code from the database's text error message. - * - * @param string $errormsg error message returned from the database - * @return integer an error number from a DB error constant - */ - function errorCode($errormsg) - { - static $error_regexps; - if (!isset($error_regexps)) { - $error_regexps = array( - '/^no such table:/' => DB_ERROR_NOSUCHTABLE, - '/^table .* already exists$/' => DB_ERROR_ALREADY_EXISTS, - '/PRIMARY KEY must be unique/i' => DB_ERROR_CONSTRAINT, - '/is not unique/' => DB_ERROR_CONSTRAINT, - '/uniqueness constraint failed/' => DB_ERROR_CONSTRAINT, - '/may not be NULL/' => DB_ERROR_CONSTRAINT_NOT_NULL, - '/^no such column:/' => DB_ERROR_NOSUCHFIELD, - '/^near ".*": syntax error$/' => DB_ERROR_SYNTAX - ); - } - foreach ($error_regexps as $regexp => $code) { - if (preg_match($regexp, $errormsg)) { - return $code; - } - } - // Fall back to DB_ERROR if there was no mapping. - return DB_ERROR; - } - - // }}} - // {{{ dropSequence() - - /** - * Deletes a sequence - * - * @param string $seq_name name of the sequence to be deleted - * - * @return int DB_OK on success. DB_Error if problems. - * - * @internal - * @see DB_common::dropSequence() - * @access public - */ - function dropSequence($seq_name) - { - $seqname = $this->getSequenceName($seq_name); - return $this->query("DROP TABLE $seqname"); - } - - /** - * Creates a new sequence - * - * @param string $seq_name name of the new sequence - * - * @return int DB_OK on success. A DB_Error object is returned if - * problems arise. - * - * @internal - * @see DB_common::createSequence() - * @access public - */ - function createSequence($seq_name) - { - $seqname = $this->getSequenceName($seq_name); - $query = 'CREATE TABLE ' . $seqname . - ' (id INTEGER UNSIGNED PRIMARY KEY) '; - $result = $this->query($query); - if (DB::isError($result)) { - return($result); - } - $query = "CREATE TRIGGER ${seqname}_cleanup AFTER INSERT ON $seqname - BEGIN - DELETE FROM $seqname WHERE idquery($query); - if (DB::isError($result)) { - return($result); - } - } - - // }}} - // {{{ nextId() - - /** - * Returns the next free id in a sequence - * - * @param string $seq_name name of the sequence - * @param boolean $ondemand when true, the seqence is automatically - * created if it does not exist - * - * @return int the next id number in the sequence. DB_Error if problem. - * - * @internal - * @see DB_common::nextID() - * @access public - */ - function nextId($seq_name, $ondemand = true) - { - $seqname = $this->getSequenceName($seq_name); - - do { - $repeat = 0; - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $result = $this->query("INSERT INTO $seqname (id) VALUES (NULL)"); - $this->popErrorHandling(); - if ($result === DB_OK) { - $id = @sqlite_last_insert_rowid($this->connection); - if ($id != 0) { - return $id; - } - } elseif ($ondemand && DB::isError($result) && - $result->getCode() == DB_ERROR_NOSUCHTABLE) - { - $result = $this->createSequence($seq_name); - if (DB::isError($result)) { - return $this->raiseError($result); - } else { - $repeat = 1; - } - } - } while ($repeat); - - return $this->raiseError($result); - } - - // }}} - // {{{ getSpecialQuery() - - /** - * Returns the query needed to get some backend info. - * - * Refer to the online manual at http://sqlite.org/sqlite.html. - * - * @param string $type What kind of info you want to retrieve - * @return string The SQL query string - */ - function getSpecialQuery($type, $args=array()) - { - if (!is_array($args)) - return $this->raiseError('no key specified', null, null, null, - 'Argument has to be an array.'); - switch (strtolower($type)) { - case 'master': - return 'SELECT * FROM sqlite_master;'; - case 'tables': - return "SELECT name FROM sqlite_master WHERE type='table' " - . 'UNION ALL SELECT name FROM sqlite_temp_master ' - . "WHERE type='table' ORDER BY name;"; - case 'schema': - return 'SELECT sql FROM (SELECT * FROM sqlite_master UNION ALL ' - . 'SELECT * FROM sqlite_temp_master) ' - . "WHERE type!='meta' ORDER BY tbl_name, type DESC, name;"; - case 'schemax': - case 'schema_x': - /* - * Use like: - * $res = $db->query($db->getSpecialQuery('schema_x', array('table' => 'table3'))); - */ - return 'SELECT sql FROM (SELECT * FROM sqlite_master UNION ALL ' - . 'SELECT * FROM sqlite_temp_master) ' - . "WHERE tbl_name LIKE '{$args['table']}' AND type!='meta' " - . 'ORDER BY type DESC, name;'; - case 'alter': - /* - * SQLite does not support ALTER TABLE; this is a helper query - * to handle this. 'table' represents the table name, 'rows' - * the news rows to create, 'save' the row(s) to keep _with_ - * the data. - * - * Use like: - * $args = array( - * 'table' => $table, - * 'rows' => "id INTEGER PRIMARY KEY, firstname TEXT, surname TEXT, datetime TEXT", - * 'save' => "NULL, titel, content, datetime" - * ); - * $res = $db->query( $db->getSpecialQuery('alter', $args)); - */ - $rows = strtr($args['rows'], $this->keywords); - - $q = array( - 'BEGIN TRANSACTION', - "CREATE TEMPORARY TABLE {$args['table']}_backup ({$args['rows']})", - "INSERT INTO {$args['table']}_backup SELECT {$args['save']} FROM {$args['table']}", - "DROP TABLE {$args['table']}", - "CREATE TABLE {$args['table']} ({$args['rows']})", - "INSERT INTO {$args['table']} SELECT {$rows} FROM {$args['table']}_backup", - "DROP TABLE {$args['table']}_backup", - 'COMMIT', - ); - - // This is a dirty hack, since the above query will no get executed with a single - // query call; so here the query method will be called directly and return a select instead. - foreach ($q as $query) { - $this->query($query); - } - return "SELECT * FROM {$args['table']};"; - default: - return null; - } - } - - // }}} - // {{{ getDbFileStats() - - /** - * Get the file stats for the current database. - * - * Possible arguments are dev, ino, mode, nlink, uid, gid, rdev, size, - * atime, mtime, ctime, blksize, blocks or a numeric key between - * 0 and 12. - * - * @param string $arg Array key for stats() - * @return mixed array on an unspecified key, integer on a passed arg and - * false at a stats error. - */ - function getDbFileStats($arg = '') - { - $stats = stat($this->dsn['database']); - if ($stats == false) { - return false; - } - if (is_array($stats)) { - if (is_numeric($arg)) { - if (((int)$arg <= 12) & ((int)$arg >= 0)) { - return false; - } - return $stats[$arg ]; - } - if (array_key_exists(trim($arg), $stats)) { - return $stats[$arg ]; - } - } - return $stats; - } - - // }}} - // {{{ escapeSimple() - - /** - * Escape a string according to the current DBMS's standards - * - * In SQLite, this makes things safe for inserts/updates, but may - * cause problems when performing text comparisons against columns - * containing binary data. See the - * {@link http://php.net/sqlite_escape_string PHP manual} for more info. - * - * @param string $str the string to be escaped - * - * @return string the escaped string - * - * @since 1.6.1 - * @see DB_common::escapeSimple() - * @internal - */ - function escapeSimple($str) { - return @sqlite_escape_string($str); - } - - // }}} - // {{{ modifyLimitQuery() - - function modifyLimitQuery($query, $from, $count, $params = array()) - { - $query = $query . " LIMIT $count OFFSET $from"; - return $query; - } - - // }}} - // {{{ modifyQuery() - - /** - * "DELETE FROM table" gives 0 affected rows in SQLite. - * - * This little hack lets you know how many rows were deleted. - * - * @param string $query The SQL query string - * @return string The SQL query string - */ - function _modifyQuery($query) - { - if ($this->options['portability'] & DB_PORTABILITY_DELETE_COUNT) { - if (preg_match('/^\s*DELETE\s+FROM\s+(\S+)\s*$/i', $query)) { - $query = preg_replace('/^\s*DELETE\s+FROM\s+(\S+)\s*$/', - 'DELETE FROM \1 WHERE 1=1', $query); - } - } - return $query; - } - - // }}} - // {{{ sqliteRaiseError() - - /** - * Gather information about an error, then use that info to create a - * DB error object and finally return that object. - * - * @param integer $errno PEAR error number (usually a DB constant) if - * manually raising an error - * @return object DB error object - * @see errorNative() - * @see errorCode() - * @see DB_common::raiseError() - */ - function sqliteRaiseError($errno = null) - { - - $native = $this->errorNative(); - if ($errno === null) { - $errno = $this->errorCode($native); - } - - $errorcode = @sqlite_last_error($this->connection); - $userinfo = "$errorcode ** $this->last_query"; - - return $this->raiseError($errno, null, null, $userinfo, $native); - } - - // }}} -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - */ - -?> diff --git a/gulliver/thirdparty/pear/DB/storage.php b/gulliver/thirdparty/pear/DB/storage.php deleted file mode 100644 index 1e446d93f..000000000 --- a/gulliver/thirdparty/pear/DB/storage.php +++ /dev/null @@ -1,495 +0,0 @@ - | -// | Maintainer: Daniel Convissor | -// +----------------------------------------------------------------------+ -// -// $Id: storage.php 3355 2005-06-11 22:14:40Z nbm $ - -require_once 'DB.php'; - -/** - * Provides an object interface to a table row. - * - * It lets you add, delete and change rows using objects rather than SQL - * statements. - * - * @package DB - * @version $Id: storage.php 3355 2005-06-11 22:14:40Z nbm $ - * @category Database - * @author Stig Bakken - */ -class DB_storage extends PEAR -{ - // {{{ properties - - /** the name of the table (or view, if the backend database supports - updates in views) we hold data from */ - var $_table = null; - - /** which column(s) in the table contains primary keys, can be a - string for single-column primary keys, or an array of strings - for multiple-column primary keys */ - var $_keycolumn = null; - - /** DB connection handle used for all transactions */ - var $_dbh = null; - - /** an assoc with the names of database fields stored as properties - in this object */ - var $_properties = array(); - - /** an assoc with the names of the properties in this object that - have been changed since they were fetched from the database */ - var $_changes = array(); - - /** flag that decides if data in this object can be changed. - objects that don't have their table's key column in their - property lists will be flagged as read-only. */ - var $_readonly = false; - - /** function or method that implements a validator for fields that - are set, this validator function returns true if the field is - valid, false if not */ - var $_validator = null; - - // }}} - // {{{ constructor - - /** - * Constructor - * - * @param $table string the name of the database table - * - * @param $keycolumn mixed string with name of key column, or array of - * strings if the table has a primary key of more than one column - * - * @param $dbh object database connection object - * - * @param $validator mixed function or method used to validate - * each new value, called with three parameters: the name of the - * field/column that is changing, a reference to the new value and - * a reference to this object - * - */ - function DB_storage($table, $keycolumn, &$dbh, $validator = null) - { - $this->PEAR('DB_Error'); - $this->_table = $table; - $this->_keycolumn = $keycolumn; - $this->_dbh = $dbh; - $this->_readonly = false; - $this->_validator = $validator; - } - - // }}} - // {{{ _makeWhere() - - /** - * Utility method to build a "WHERE" clause to locate ourselves in - * the table. - * - * XXX future improvement: use rowids? - * - * @access private - */ - function _makeWhere($keyval = null) - { - if (is_array($this->_keycolumn)) { - if ($keyval === null) { - for ($i = 0; $i < sizeof($this->_keycolumn); $i++) { - $keyval[] = $this->{$this->_keycolumn[$i]}; - } - } - $whereclause = ''; - for ($i = 0; $i < sizeof($this->_keycolumn); $i++) { - if ($i > 0) { - $whereclause .= ' AND '; - } - $whereclause .= $this->_keycolumn[$i]; - if (is_null($keyval[$i])) { - // there's not much point in having a NULL key, - // but we support it anyway - $whereclause .= ' IS NULL'; - } else { - $whereclause .= ' = ' . $this->_dbh->quote($keyval[$i]); - } - } - } else { - if ($keyval === null) { - $keyval = @$this->{$this->_keycolumn}; - } - $whereclause = $this->_keycolumn; - if (is_null($keyval)) { - // there's not much point in having a NULL key, - // but we support it anyway - $whereclause .= ' IS NULL'; - } else { - $whereclause .= ' = ' . $this->_dbh->quote($keyval); - } - } - return $whereclause; - } - - // }}} - // {{{ setup() - - /** - * Method used to initialize a DB_storage object from the - * configured table. - * - * @param $keyval mixed the key[s] of the row to fetch (string or array) - * - * @return int DB_OK on success, a DB error if not - */ - function setup($keyval) - { - $whereclause = $this->_makeWhere($keyval); - $query = 'SELECT * FROM ' . $this->_table . ' WHERE ' . $whereclause; - $sth = $this->_dbh->query($query); - if (DB::isError($sth)) { - return $sth; - } - $row = $sth->fetchRow(DB_FETCHMODE_ASSOC); - if (DB::isError($row)) { - return $row; - } - if (!$row) { - return $this->raiseError(null, DB_ERROR_NOT_FOUND, null, null, - $query, null, true); - } - foreach ($row as $key => $value) { - $this->_properties[$key] = true; - $this->$key = $value; - } - return DB_OK; - } - - // }}} - // {{{ insert() - - /** - * Create a new (empty) row in the configured table for this - * object. - */ - function insert($newpk) - { - if (is_array($this->_keycolumn)) { - $primarykey = $this->_keycolumn; - } else { - $primarykey = array($this->_keycolumn); - } - settype($newpk, "array"); - for ($i = 0; $i < sizeof($primarykey); $i++) { - $pkvals[] = $this->_dbh->quote($newpk[$i]); - } - - $sth = $this->_dbh->query("INSERT INTO $this->_table (" . - implode(",", $primarykey) . ") VALUES(" . - implode(",", $pkvals) . ")"); - if (DB::isError($sth)) { - return $sth; - } - if (sizeof($newpk) == 1) { - $newpk = $newpk[0]; - } - $this->setup($newpk); - } - - // }}} - // {{{ toString() - - /** - * Output a simple description of this DB_storage object. - * @return string object description - */ - function toString() - { - $info = strtolower(get_class($this)); - $info .= " (table="; - $info .= $this->_table; - $info .= ", keycolumn="; - if (is_array($this->_keycolumn)) { - $info .= "(" . implode(",", $this->_keycolumn) . ")"; - } else { - $info .= $this->_keycolumn; - } - $info .= ", dbh="; - if (is_object($this->_dbh)) { - $info .= $this->_dbh->toString(); - } else { - $info .= "null"; - } - $info .= ")"; - if (sizeof($this->_properties)) { - $info .= " [loaded, key="; - $keyname = $this->_keycolumn; - if (is_array($keyname)) { - $info .= "("; - for ($i = 0; $i < sizeof($keyname); $i++) { - if ($i > 0) { - $info .= ","; - } - $info .= $this->$keyname[$i]; - } - $info .= ")"; - } else { - $info .= $this->$keyname; - } - $info .= "]"; - } - if (sizeof($this->_changes)) { - $info .= " [modified]"; - } - return $info; - } - - // }}} - // {{{ dump() - - /** - * Dump the contents of this object to "standard output". - */ - function dump() - { - foreach ($this->_properties as $prop => $foo) { - print "$prop = "; - print htmlentities($this->$prop); - print "
\n"; - } - } - - // }}} - // {{{ &create() - - /** - * Static method used to create new DB storage objects. - * @param $data assoc. array where the keys are the names - * of properties/columns - * @return object a new instance of DB_storage or a subclass of it - */ - function &create($table, &$data) - { - $classname = strtolower(get_class($this)); - $obj =& new $classname($table); - foreach ($data as $name => $value) { - $obj->_properties[$name] = true; - $obj->$name = &$value; - } - return $obj; - } - - // }}} - // {{{ loadFromQuery() - - /** - * Loads data into this object from the given query. If this - * object already contains table data, changes will be saved and - * the object re-initialized first. - * - * @param $query SQL query - * - * @param $params parameter list in case you want to use - * prepare/execute mode - * - * @return int DB_OK on success, DB_WARNING_READ_ONLY if the - * returned object is read-only (because the object's specified - * key column was not found among the columns returned by $query), - * or another DB error code in case of errors. - */ -// XXX commented out for now -/* - function loadFromQuery($query, $params = null) - { - if (sizeof($this->_properties)) { - if (sizeof($this->_changes)) { - $this->store(); - $this->_changes = array(); - } - $this->_properties = array(); - } - $rowdata = $this->_dbh->getRow($query, DB_FETCHMODE_ASSOC, $params); - if (DB::isError($rowdata)) { - return $rowdata; - } - reset($rowdata); - $found_keycolumn = false; - while (list($key, $value) = each($rowdata)) { - if ($key == $this->_keycolumn) { - $found_keycolumn = true; - } - $this->_properties[$key] = true; - $this->$key = &$value; - unset($value); // have to unset, or all properties will - // refer to the same value - } - if (!$found_keycolumn) { - $this->_readonly = true; - return DB_WARNING_READ_ONLY; - } - return DB_OK; - } - */ - - // }}} - // {{{ set() - - /** - * Modify an attriute value. - */ - function set($property, $newvalue) - { - // only change if $property is known and object is not - // read-only - if ($this->_readonly) { - return $this->raiseError(null, DB_WARNING_READ_ONLY, null, - null, null, null, true); - } - if (@isset($this->_properties[$property])) { - if (empty($this->_validator)) { - $valid = true; - } else { - $valid = @call_user_func($this->_validator, - $this->_table, - $property, - $newvalue, - $this->$property, - $this); - } - if ($valid) { - $this->$property = $newvalue; - if (empty($this->_changes[$property])) { - $this->_changes[$property] = 0; - } else { - $this->_changes[$property]++; - } - } else { - return $this->raiseError(null, DB_ERROR_INVALID, null, - null, "invalid field: $property", - null, true); - } - return true; - } - return $this->raiseError(null, DB_ERROR_NOSUCHFIELD, null, - null, "unknown field: $property", - null, true); - } - - // }}} - // {{{ &get() - - /** - * Fetch an attribute value. - * - * @param string attribute name - * - * @return attribute contents, or null if the attribute name is - * unknown - */ - function &get($property) - { - // only return if $property is known - if (isset($this->_properties[$property])) { - return $this->$property; - } - $tmp = null; - return $tmp; - } - - // }}} - // {{{ _DB_storage() - - /** - * Destructor, calls DB_storage::store() if there are changes - * that are to be kept. - */ - function _DB_storage() - { - if (sizeof($this->_changes)) { - $this->store(); - } - $this->_properties = array(); - $this->_changes = array(); - $this->_table = null; - } - - // }}} - // {{{ store() - - /** - * Stores changes to this object in the database. - * - * @return DB_OK or a DB error - */ - function store() - { - foreach ($this->_changes as $name => $foo) { - $params[] = &$this->$name; - $vars[] = $name . ' = ?'; - } - if ($vars) { - $query = 'UPDATE ' . $this->_table . ' SET ' . - implode(', ', $vars) . ' WHERE ' . - $this->_makeWhere(); - $stmt = $this->_dbh->prepare($query); - $res = $this->_dbh->execute($stmt, $params); - if (DB::isError($res)) { - return $res; - } - $this->_changes = array(); - } - return DB_OK; - } - - // }}} - // {{{ remove() - - /** - * Remove the row represented by this object from the database. - * - * @return mixed DB_OK or a DB error - */ - function remove() - { - if ($this->_readonly) { - return $this->raiseError(null, DB_WARNING_READ_ONLY, null, - null, null, null, true); - } - $query = 'DELETE FROM ' . $this->_table .' WHERE '. - $this->_makeWhere(); - $res = $this->_dbh->query($query); - if (DB::isError($res)) { - return $res; - } - foreach ($this->_properties as $prop => $foo) { - unset($this->$prop); - } - $this->_properties = array(); - $this->_changes = array(); - return DB_OK; - } - - // }}} -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - */ - -?> diff --git a/gulliver/thirdparty/pear/DB/sybase.php b/gulliver/thirdparty/pear/DB/sybase.php deleted file mode 100644 index 34451d2ce..000000000 --- a/gulliver/thirdparty/pear/DB/sybase.php +++ /dev/null @@ -1,835 +0,0 @@ - | -// | Antônio Carlos Venâncio Júnior | -// | Maintainer: Daniel Convissor | -// +----------------------------------------------------------------------+ -// -// $Id: sybase.php 3355 2005-06-11 22:14:40Z nbm $ - - -// TODO -// - This driver may fail with multiple connections under the same -// user/pass/host and different databases - - -require_once 'DB/common.php'; - -/** - * Database independent query interface definition for PHP's Sybase - * extension. - * - * @package DB - * @version $Id: sybase.php 3355 2005-06-11 22:14:40Z nbm $ - * @category Database - * @author Sterling Hughes - * @author Antônio Carlos Venâncio Júnior - */ -class DB_sybase extends DB_common -{ - // {{{ properties - - var $connection; - var $phptype, $dbsyntax; - var $prepare_tokens = array(); - var $prepare_types = array(); - var $transaction_opcount = 0; - var $autocommit = true; - - // }}} - // {{{ constructor - - /** - * DB_sybase constructor. - * - * @access public - */ - function DB_sybase() - { - $this->DB_common(); - $this->phptype = 'sybase'; - $this->dbsyntax = 'sybase'; - $this->features = array( - 'prepare' => false, - 'pconnect' => true, - 'transactions' => false, - 'limit' => 'emulate' - ); - $this->errorcode_map = array( - ); - } - - // }}} - // {{{ connect() - - /** - * Connect to a database and log in as the specified user. - * - * @param $dsn the data source name (see DB::parseDSN for syntax) - * @param $persistent (optional) whether the connection should - * be persistent - * @access public - * @return int DB_OK on success, a DB error on failure - */ - function connect($dsninfo, $persistent = false) - { - if (!DB::assertExtension('sybase') && - !DB::assertExtension('sybase_ct')) - { - return $this->raiseError(DB_ERROR_EXTENSION_NOT_FOUND); - } - - $this->dsn = $dsninfo; - - $interface = $dsninfo['hostspec'] ? $dsninfo['hostspec'] : 'localhost'; - $connect_function = $persistent ? 'sybase_pconnect' : 'sybase_connect'; - $dsninfo['password'] = !empty($dsninfo['password']) ? $dsninfo['password'] : false; - $dsninfo['charset'] = isset($dsninfo['charset']) ? $dsninfo['charset'] : false; - $dsninfo['appname'] = isset($dsninfo['appname']) ? $dsninfo['appname'] : false; - - if ($interface && $dsninfo['username']) { - $conn = @$connect_function($interface, $dsninfo['username'], - $dsninfo['password'], - $dsninfo['charset'], - $dsninfo['appname']); - } else { - $conn = false; - } - - if (!$conn) { - return $this->raiseError(DB_ERROR_CONNECT_FAILED); - } - - if ($dsninfo['database']) { - if (!@sybase_select_db($dsninfo['database'], $conn)) { - return $this->raiseError(DB_ERROR_NODBSELECTED, null, - null, null, @sybase_get_last_message()); - } - $this->_db = $dsninfo['database']; - } - - $this->connection = $conn; - return DB_OK; - } - - // }}} - // {{{ disconnect() - - /** - * Log out and disconnect from the database. - * - * @access public - * - * @return bool true on success, false if not connected. - */ - function disconnect() - { - $ret = @sybase_close($this->connection); - $this->connection = null; - return $ret; - } - - // }}} - // {{{ errorNative() - - /** - * Get the last server error messge (if any) - * - * @return string sybase last error message - */ - function errorNative() - { - return @sybase_get_last_message(); - } - - // }}} - // {{{ errorCode() - - /** - * Determine PEAR::DB error code from the database's text error message. - * - * @param string $errormsg error message returned from the database - * @return integer an error number from a DB error constant - */ - function errorCode($errormsg) - { - static $error_regexps; - if (!isset($error_regexps)) { - $error_regexps = array( - '/Incorrect syntax near/' - => DB_ERROR_SYNTAX, - '/^Unclosed quote before the character string [\"\'].*[\"\']\./' - => DB_ERROR_SYNTAX, - '/Implicit conversion from datatype [\"\'].+[\"\'] to [\"\'].+[\"\'] is not allowed\./' - => DB_ERROR_INVALID_NUMBER, - '/Cannot drop the table [\"\'].+[\"\'], because it doesn\'t exist in the system catalogs\./' - => DB_ERROR_NOSUCHTABLE, - '/Only the owner of object [\"\'].+[\"\'] or a user with System Administrator \(SA\) role can run this command\./' - => DB_ERROR_ACCESS_VIOLATION, - '/^.+ permission denied on object .+, database .+, owner .+/' - => DB_ERROR_ACCESS_VIOLATION, - '/^.* permission denied, database .+, owner .+/' - => DB_ERROR_ACCESS_VIOLATION, - '/[^.*] not found\./' - => DB_ERROR_NOSUCHTABLE, - '/There is already an object named/' - => DB_ERROR_ALREADY_EXISTS, - '/Invalid column name/' - => DB_ERROR_NOSUCHFIELD, - '/does not allow null values/' - => DB_ERROR_CONSTRAINT_NOT_NULL, - '/Command has been aborted/' - => DB_ERROR_CONSTRAINT, - ); - } - - foreach ($error_regexps as $regexp => $code) { - if (preg_match($regexp, $errormsg)) { - return $code; - } - } - return DB_ERROR; - } - - // }}} - // {{{ sybaseRaiseError() - - /** - * Gather information about an error, then use that info to create a - * DB error object and finally return that object. - * - * @param integer $errno PEAR error number (usually a DB constant) if - * manually raising an error - * @return object DB error object - * @see errorNative() - * @see errorCode() - * @see DB_common::raiseError() - */ - function sybaseRaiseError($errno = null) - { - $native = $this->errorNative(); - if ($errno === null) { - $errno = $this->errorCode($native); - } - return $this->raiseError($errno, null, null, null, $native); - } - - // }}} - // {{{ simpleQuery() - - /** - * Send a query to Sybase and return the results as a Sybase resource - * identifier. - * - * @param the SQL query - * - * @access public - * - * @return mixed returns a valid Sybase result for successful SELECT - * queries, DB_OK for other successful queries. A DB error is - * returned on failure. - */ - function simpleQuery($query) - { - $ismanip = DB::isManip($query); - $this->last_query = $query; - if (!@sybase_select_db($this->_db, $this->connection)) { - return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED); - } - $query = $this->modifyQuery($query); - if (!$this->autocommit && $ismanip) { - if ($this->transaction_opcount == 0) { - $result = @sybase_query('BEGIN TRANSACTION', $this->connection); - if (!$result) { - return $this->sybaseRaiseError(); - } - } - $this->transaction_opcount++; - } - $result = @sybase_query($query, $this->connection); - if (!$result) { - return $this->sybaseRaiseError(); - } - if (is_resource($result)) { - $numrows = $this->numRows($result); - if (is_object($numrows)) { - return $numrows; - } - $this->num_rows[(int)$result] = $numrows; - return $result; - } - // Determine which queries that should return data, and which - // should return an error code only. - return $ismanip ? DB_OK : $result; - } - - // }}} - // {{{ nextResult() - - /** - * Move the internal sybase result pointer to the next available result - * - * @param a valid sybase result resource - * - * @access public - * - * @return true if a result is available otherwise return false - */ - function nextResult($result) - { - return false; - } - - // }}} - // {{{ fetchInto() - - /** - * Fetch a row and insert the data into an existing array. - * - * Formating of the array and the data therein are configurable. - * See DB_result::fetchInto() for more information. - * - * @param resource $result query result identifier - * @param array $arr (reference) array where data from the row - * should be placed - * @param int $fetchmode how the resulting array should be indexed - * @param int $rownum the row number to fetch - * - * @return mixed DB_OK on success, null when end of result set is - * reached or on failure - * - * @see DB_result::fetchInto() - * @access private - */ - function fetchInto($result, &$arr, $fetchmode, $rownum=null) - { - if ($rownum !== null) { - if (!@sybase_data_seek($result, $rownum)) { - return null; - } - } - if ($fetchmode & DB_FETCHMODE_ASSOC) { - if (function_exists('sybase_fetch_assoc')) { - $arr = @sybase_fetch_assoc($result); - } else { - if ($arr = @sybase_fetch_array($result)) { - foreach ($arr as $key => $value) { - if (is_int($key)) { - unset($arr[$key]); - } - } - } - } - if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE && $arr) { - $arr = array_change_key_case($arr, CASE_LOWER); - } - } else { - $arr = @sybase_fetch_row($result); - } - if (!$arr) { - // reported not work as seems that sybase_get_last_message() - // always return a message here - //if ($errmsg = @sybase_get_last_message()) { - // return $this->sybaseRaiseError($errmsg); - //} else { - return null; - //} - } - if ($this->options['portability'] & DB_PORTABILITY_RTRIM) { - $this->_rtrimArrayValues($arr); - } - if ($this->options['portability'] & DB_PORTABILITY_NULL_TO_EMPTY) { - $this->_convertNullArrayValuesToEmpty($arr); - } - return DB_OK; - } - - // }}} - // {{{ freeResult() - - /** - * Free the internal resources associated with $result. - * - * @param $result Sybase result identifier - * - * @access public - * - * @return bool true on success, false if $result is invalid - */ - function freeResult($result) - { - unset($this->num_rows[(int)$result]); - return @sybase_free_result($result); - } - - // }}} - // {{{ numCols() - - /** - * Get the number of columns in a result set. - * - * @param $result Sybase result identifier - * - * @access public - * - * @return int the number of columns per row in $result - */ - function numCols($result) - { - $cols = @sybase_num_fields($result); - if (!$cols) { - return $this->sybaseRaiseError(); - } - return $cols; - } - - // }}} - // {{{ numRows() - - /** - * Get the number of rows in a result set. - * - * @param $result Sybase result identifier - * - * @access public - * - * @return int the number of rows in $result - */ - function numRows($result) - { - $rows = @sybase_num_rows($result); - if ($rows === false) { - return $this->sybaseRaiseError(); - } - return $rows; - } - - // }}} - // {{{ affectedRows() - - /** - * Gets the number of rows affected by the data manipulation - * query. For other queries, this function returns 0. - * - * @return number of rows affected by the last query - */ - function affectedRows() - { - if (DB::isManip($this->last_query)) { - $result = @sybase_affected_rows($this->connection); - } else { - $result = 0; - } - return $result; - } - - // }}} - // {{{ nextId() - - /** - * Returns the next free id in a sequence - * - * @param string $seq_name name of the sequence - * @param boolean $ondemand when true, the seqence is automatically - * created if it does not exist - * - * @return int the next id number in the sequence. DB_Error if problem. - * - * @internal - * @see DB_common::nextID() - * @access public - */ - function nextId($seq_name, $ondemand = true) - { - $seqname = $this->getSequenceName($seq_name); - if (!@sybase_select_db($this->_db, $this->connection)) { - return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED); - } - $repeat = 0; - do { - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $result = $this->query("INSERT INTO $seqname (vapor) VALUES (0)"); - $this->popErrorHandling(); - if ($ondemand && DB::isError($result) && - ($result->getCode() == DB_ERROR || $result->getCode() == DB_ERROR_NOSUCHTABLE)) - { - $repeat = 1; - $result = $this->createSequence($seq_name); - if (DB::isError($result)) { - return $this->raiseError($result); - } - } elseif (!DB::isError($result)) { - $result =& $this->query("SELECT @@IDENTITY FROM $seqname"); - $repeat = 0; - } else { - $repeat = false; - } - } while ($repeat); - if (DB::isError($result)) { - return $this->raiseError($result); - } - $result = $result->fetchRow(DB_FETCHMODE_ORDERED); - return $result[0]; - } - - /** - * Creates a new sequence - * - * @param string $seq_name name of the new sequence - * - * @return int DB_OK on success. A DB_Error object is returned if - * problems arise. - * - * @internal - * @see DB_common::createSequence() - * @access public - */ - function createSequence($seq_name) - { - $seqname = $this->getSequenceName($seq_name); - return $this->query("CREATE TABLE $seqname ". - '(id numeric(10,0) IDENTITY NOT NULL ,' . - 'vapor int NULL)'); - } - - // }}} - // {{{ dropSequence() - - /** - * Deletes a sequence - * - * @param string $seq_name name of the sequence to be deleted - * - * @return int DB_OK on success. DB_Error if problems. - * - * @internal - * @see DB_common::dropSequence() - * @access public - */ - function dropSequence($seq_name) - { - $seqname = $this->getSequenceName($seq_name); - return $this->query("DROP TABLE $seqname"); - } - - // }}} - // {{{ getSpecialQuery() - - /** - * Returns the query needed to get some backend info - * @param string $type What kind of info you want to retrieve - * @return string The SQL query string - */ - function getSpecialQuery($type) - { - switch ($type) { - case 'tables': - return "select name from sysobjects where type = 'U' order by name"; - case 'views': - return "select name from sysobjects where type = 'V'"; - default: - return null; - } - } - - // }}} - // {{{ autoCommit() - - /** - * Enable/disable automatic commits - */ - function autoCommit($onoff = false) - { - // XXX if $this->transaction_opcount > 0, we should probably - // issue a warning here. - $this->autocommit = $onoff ? true : false; - return DB_OK; - } - - // }}} - // {{{ commit() - - /** - * Commit the current transaction. - */ - function commit() - { - if ($this->transaction_opcount > 0) { - if (!@sybase_select_db($this->_db, $this->connection)) { - return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED); - } - $result = @sybase_query('COMMIT', $this->connection); - $this->transaction_opcount = 0; - if (!$result) { - return $this->sybaseRaiseError(); - } - } - return DB_OK; - } - - // }}} - // {{{ rollback() - - /** - * Roll back (undo) the current transaction. - */ - function rollback() - { - if ($this->transaction_opcount > 0) { - if (!@sybase_select_db($this->_db, $this->connection)) { - return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED); - } - $result = @sybase_query('ROLLBACK', $this->connection); - $this->transaction_opcount = 0; - if (!$result) { - return $this->sybaseRaiseError(); - } - } - return DB_OK; - } - - // }}} - // {{{ tableInfo() - - /** - * Returns information about a table or a result set. - * - * NOTE: only supports 'table' and 'flags' if $result - * is a table name. - * - * @param object|string $result DB_result object from a query or a - * string containing the name of a table - * @param int $mode a valid tableInfo mode - * @return array an associative array with the information requested - * or an error object if something is wrong - * @access public - * @internal - * @since 1.6.0 - * @see DB_common::tableInfo() - */ - function tableInfo($result, $mode = null) - { - if (isset($result->result)) { - /* - * Probably received a result object. - * Extract the result resource identifier. - */ - $id = $result->result; - $got_string = false; - } elseif (is_string($result)) { - /* - * Probably received a table name. - * Create a result resource identifier. - */ - if (!@sybase_select_db($this->_db, $this->connection)) { - return $this->sybaseRaiseError(DB_ERROR_NODBSELECTED); - } - $id = @sybase_query("SELECT * FROM $result WHERE 1=0", - $this->connection); - $got_string = true; - } else { - /* - * Probably received a result resource identifier. - * Copy it. - * Deprecated. Here for compatibility only. - */ - $id = $result; - $got_string = false; - } - - if (!is_resource($id)) { - return $this->sybaseRaiseError(DB_ERROR_NEED_MORE_DATA); - } - - if ($this->options['portability'] & DB_PORTABILITY_LOWERCASE) { - $case_func = 'strtolower'; - } else { - $case_func = 'strval'; - } - - $count = @sybase_num_fields($id); - - // made this IF due to performance (one if is faster than $count if's) - if (!$mode) { - - for ($i=0; $i<$count; $i++) { - $f = @sybase_fetch_field($id, $i); - - // column_source is often blank - if ($got_string) { - $res[$i]['table'] = $case_func($result); - } else { - $res[$i]['table'] = $case_func($f->column_source); - } - $res[$i]['name'] = $case_func($f->name); - $res[$i]['type'] = $f->type; - $res[$i]['len'] = $f->max_length; - if ($res[$i]['table']) { - $res[$i]['flags'] = $this->_sybase_field_flags( - $res[$i]['table'], $res[$i]['name']); - } else { - $res[$i]['flags'] = ''; - } - } - - } else { - // get full info - - $res['num_fields'] = $count; - - for ($i=0; $i<$count; $i++) { - $f = @sybase_fetch_field($id, $i); - - // column_source is often blank - if ($got_string) { - $res[$i]['table'] = $case_func($result); - } else { - $res[$i]['table'] = $case_func($f->column_source); - } - $res[$i]['name'] = $case_func($f->name); - $res[$i]['type'] = $f->type; - $res[$i]['len'] = $f->max_length; - if ($res[$i]['table']) { - $res[$i]['flags'] = $this->_sybase_field_flags( - $res[$i]['table'], $res[$i]['name']); - } else { - $res[$i]['flags'] = ''; - } - - if ($mode & DB_TABLEINFO_ORDER) { - $res['order'][$res[$i]['name']] = $i; - } - if ($mode & DB_TABLEINFO_ORDERTABLE) { - $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i; - } - } - } - - // free the result only if we were called on a table - if ($got_string) { - @sybase_free_result($id); - } - return $res; - } - - // }}} - // {{{ _sybase_field_flags() - - /** - * Get the flags for a field. - * - * Currently supports: - * + unique_key (unique index, unique check or primary_key) - * + multiple_key (multi-key index) - * - * @param string $table table name - * @param string $column field name - * @return string space delimited string of flags. Empty string if none. - * @access private - */ - function _sybase_field_flags($table, $column) - { - static $tableName = null; - static $flags = array(); - - if ($table != $tableName) { - $flags = array(); - $tableName = $table; - - // get unique/primary keys - $res = $this->getAll("sp_helpindex $table", DB_FETCHMODE_ASSOC); - - if (!isset($res[0]['index_description'])) { - return ''; - } - - foreach ($res as $val) { - $keys = explode(', ', trim($val['index_keys'])); - - if (sizeof($keys) > 1) { - foreach ($keys as $key) { - $this->_add_flag($flags[$key], 'multiple_key'); - } - } - - if (strpos($val['index_description'], 'unique')) { - foreach ($keys as $key) { - $this->_add_flag($flags[$key], 'unique_key'); - } - } - } - - } - - if (array_key_exists($column, $flags)) { - return(implode(' ', $flags[$column])); - } - - return ''; - } - - // }}} - // {{{ _add_flag() - - /** - * Adds a string to the flags array if the flag is not yet in there - * - if there is no flag present the array is created. - * - * @param array $array reference of flags array to add a value to - * @param mixed $value value to add to the flag array - * @access private - */ - function _add_flag(&$array, $value) - { - if (!is_array($array)) { - $array = array($value); - } elseif (!in_array($value, $array)) { - array_push($array, $value); - } - } - - // }}} - // {{{ quoteIdentifier() - - /** - * Quote a string so it can be safely used as a table / column name - * - * Quoting style depends on which database driver is being used. - * - * @param string $str identifier name to be quoted - * - * @return string quoted identifier string - * - * @since 1.6.0 - * @access public - */ - function quoteIdentifier($str) - { - return '[' . str_replace(']', ']]', $str) . ']'; - } - - // }}} - -} - -/* - * Local variables: - * tab-width: 4 - * c-basic-offset: 4 - * End: - */ - -?> diff --git a/gulliver/thirdparty/pear/HTTP/HTTP.php b/gulliver/thirdparty/pear/HTTP/HTTP.php deleted file mode 100644 index 98af71fad..000000000 --- a/gulliver/thirdparty/pear/HTTP/HTTP.php +++ /dev/null @@ -1,343 +0,0 @@ - | -// | Sterling Hughes | -// | Tomas V.V.Cox | -// | Richard Heyes | -// | Philippe Jausions | -// | Michael Wallner | -// +----------------------------------------------------------------------+ -// -// $Id: HTTP.php,v 1.35 2004/09/21 15:28:07 mike Exp $ - -/** - * HTTP - * - * HTTP utility functions - * - * @package HTTP - * @category HTTP - * @license PHP License - * @access public - * @version $Revision: 1.35 $ - */ -class HTTP -{ - /** - * Date - * - * Format a RFC compliant GMT date HTTP header. This function honors the - * "y2k_compliance" php.ini directive and formats the GMT date corresponding - * to either RFC850 or RFC822. - * - * @static - * @access public - * @return mixed GMT date string, or false for an invalid $time parameter - * @param mixed $time unix timestamp or date (default = current time) - */ - function Date($time = null) - { - if (!isset($time)) { - $time = time(); - } elseif (!is_numeric($time) && (-1 === $time = strtotime($time))) { - return false; - } - - // RFC822 or RFC850 - $format = ini_get('y2k_compliance') ? 'D, d M Y' : 'l, d-M-y'; - - return gmdate($format .' H:i:s \G\M\T', $time); - } - - /** - * Negotiate Language - * - * Negotiate language with the user's browser through the Accept-Language - * HTTP header or the user's host address. Language codes are generally in - * the form "ll" for a language spoken in only one country, or "ll-CC" for a - * language spoken in a particular country. For example, U.S. English is - * "en-US", while British English is "en-UK". Portugese as spoken in - * Portugal is "pt-PT", while Brazilian Portugese is "pt-BR". - * - * Quality factors in the Accept-Language: header are supported, e.g.: - * Accept-Language: en-UK;q=0.7, en-US;q=0.6, no, dk;q=0.8 - * - * - * require_once 'HTTP.php'; - * $langs = array( - * 'en' => 'locales/en', - * 'en-US'=> 'locales/en', - * 'en-UK'=> 'locales/en', - * 'de' => 'locales/de', - * 'de-DE'=> 'locales/de', - * 'de-AT'=> 'locales/de', - * ); - * $neg = HTTP::negotiateLanguage($langs); - * $dir = $langs[$neg]; - * - * - * @static - * @access public - * @return string The negotiated language result or the supplied default. - * @param array $supported An associative array of supported languages, - * whose values must evaluate to true. - * @param string $default The default language to use if none is found. - */ - function negotiateLanguage($supported, $default = 'en-US') - { - $supp = array(); - foreach ($supported as $lang => $isSupported) { - if ($isSupported) { - $supp[strToLower($lang)] = $lang; - } - } - - if (!count($supp)) { - return $default; - } - - $matches = array(); - if (isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { - foreach (explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']) as $lang) { - @list($l, $q) = array_map('strtolower', - array_map('trim', explode(';', $lang))); - if (isset($supp[$l])) { - if (isset($q)) { - $matches[$l] = (float) str_replace('q=', '', $q); - } else { - $matches[$l] = 1000 - count($matches); - } - } - } - } - - if (count($matches)) { - asort($matches, SORT_NUMERIC); - return $supp[array_pop(array_keys($matches))]; - } - - if (isset($_SERVER['REMOTE_HOST'])) { - $lang = strtolower(array_pop(explode('.', $_SERVER['REMOTE_HOST']))); - if (isset($supp[$lang])) { - return $supp[$lang]; - } - } - - return $default; - } - - /** - * Head - * - * Sends a "HEAD" HTTP command to a server and returns the headers - * as an associative array. Example output could be: - * - * Array - * ( - * [response_code] => 200 // The HTTP response code - * [response] => HTTP/1.1 200 OK // The full HTTP response string - * [Date] => Fri, 11 Jan 2002 01:41:44 GMT - * [Server] => Apache/1.3.20 (Unix) PHP/4.1.1 - * [X-Powered-By] => PHP/4.1.1 - * [Connection] => close - * [Content-Type] => text/html - * ) - * - * - * @see HTTP_Client::head() - * @see HTTP_Request - * - * @static - * @access public - * @return mixed Returns associative array of response headers on success - * or PEAR error on failure. - * @param string $url A valid URL, e.g.: http://pear.php.net/credits.php - * @param integer $timeout Timeout in seconds (default = 10) - */ - function head($url, $timeout = 10) - { - $p = parse_url($url); - if (!isset($p['scheme'])) { - $p = parse_url(HTTP::absoluteURI($url)); - } elseif ($p['scheme'] != 'http') { - return HTTP::raiseError('Unsupported protocol: '. $p['scheme']); - } - - $port = isset($p['port']) ? $p['port'] : 80; - - if (!$fp = @fsockopen($p['host'], $port, $eno, $estr, $timeout)) { - return HTTP::raiseError("Connection error: $estr ($eno)"); - } - - $path = !empty($p['path']) ? $p['path'] : '/'; - $path .= !empty($p['query']) ? '?' . $p['query'] : ''; - - fputs($fp, "HEAD $path HTTP/1.0\r\n"); - fputs($fp, 'Host: ' . $p['host'] . ':' . $port . "\r\n"); - fputs($fp, "Connection: close\r\n\r\n"); - - $response = rtrim(fgets($fp, 4096)); - if (preg_match("|^HTTP/[^\s]*\s(.*?)\s|", $response, $status)) { - $headers['response_code'] = $status[1]; - } - $headers['response'] = $response; - - while ($line = fgets($fp, 4096)) { - if (!trim($line)) { - break; - } - if (($pos = strpos($line, ':')) !== false) { - $header = substr($line, 0, $pos); - $value = trim(substr($line, $pos + 1)); - $headers[$header] = $value; - } - } - fclose($fp); - return $headers; - } - - /** - * Redirect - * - * This function redirects the client. This is done by issuing - * a "Location" header and exiting if wanted. If you set $rfc2616 to true - * HTTP will output a hypertext note with the location of the redirect. - * - * @static - * @access public - * @return mixed Returns true on succes (or exits) or false if headers - * have already been sent. - * @param string $url URL where the redirect should go to. - * @param bool $exit Whether to exit immediately after redirection. - * @param bool $rfc2616 Wheter to output a hypertext note where we're - * redirecting to (Redirecting to ....) - */ - function redirect($url, $exit = true, $rfc2616 = false) - { - if (headers_sent()) { - return false; - } - - $url = HTTP::absoluteURI($url); - header('Location: '. $url); - - if ($rfc2616 && @$_SERVER['REQUEST_METHOD'] != 'HEAD') { - printf('Redirecting to: %s.', $url, $url); - } - if ($exit) { - exit; - } - return true; - } - - /** - * Absolute URI - * - * This function returns the absolute URI for the partial URL passed. - * The current scheme (HTTP/HTTPS), host server, port, current script - * location are used if necessary to resolve any relative URLs. - * - * Offsets potentially created by PATH_INFO are taken care of to resolve - * relative URLs to the current script. - * - * You can choose a new protocol while resolving the URI. This is - * particularly useful when redirecting a web browser using relative URIs - * and to switch from HTTP to HTTPS, or vice-versa, at the same time. - * - * @author Philippe Jausions - * @static - * @access public - * @return string The absolute URI. - * @param string $url Absolute or relative URI the redirect should go to. - * @param string $protocol Protocol to use when redirecting URIs. - * @param integer $port A new port number. - */ - function absoluteURI($url = null, $protocol = null, $port = null) - { - // Mess around with already absolute URIs - if (preg_match('!^([a-z0-9]+)://!i', $url)) { - if (empty($protocol) && empty($port)) { - return $url; - } - if (!empty($protocol)) { - $url = $protocol .':'. array_pop(explode(':', $url, 2)); - } - if (!empty($port)) { - $url = preg_replace('!^(([a-z0-9]+)://[^/:]+)(:[\d]+)?!i', - '\1:'. $port, $url); - } - return $url; - } - - $host = 'localhost'; - if (!empty($_SERVER['HTTP_HOST'])) { - list($host) = explode(':', $_SERVER['HTTP_HOST']); - } elseif (!empty($_SERVER['SERVER_NAME'])) { - list($host) = explode(':', $_SERVER['SERVER_NAME']); - } - - if (empty($protocol)) { - $protocol = isset($_SERVER['HTTPS']) ? 'https' : 'http'; - if (!isset($port) || $port != intval($port)) { - $port = isset($_SERVER['SERVER_PORT']) ? $_SERVER['SERVER_PORT'] : 80; - } - } - - if ($protocol == 'http' && $port == 80) { - unset($port); - } - if ($protocol == 'https' && $port == 443) { - unset($port); - } - - $server = $protocol .'://'. $host . (isset($port) ? ':'. $port : ''); - - if (!strlen($url)) { - $url = isset($_SERVER['REQUEST_URI']) ? - $_SERVER['REQUEST_URI'] : $_SERVER['PHP_SELF']; - } - - if ($url{0} == '/') { - return $server . $url; - } - - // Check for PATH_INFO - if (isset($_SERVER['PATH_INFO'])) { - $path = dirname(substr($_SERVER['PHP_SELF'], 0, -strlen($_SERVER['PATH_INFO']))); - } else { - $path = dirname($_SERVER['PHP_SELF']); - } - - if (substr($path, -1) != '/') { - $path .= '/'; - } - - return $server . strtr($path, '\\', '/') . $url; - } - - /** - * Raise Error - * - * Lazy raising of PEAR_Errors. - * - * @static - * @access protected - * @return object PEAR_Error - * @param mixed $error - * @param int $code - */ - function raiseError($error = null, $code = null) - { - require_once 'PEAR.php'; - return PEAR::raiseError($error, $code); - } -} -?> diff --git a/gulliver/thirdparty/pear/HTTP/Request.php b/gulliver/thirdparty/pear/HTTP/Request.php deleted file mode 100644 index 6a4cd8688..000000000 --- a/gulliver/thirdparty/pear/HTTP/Request.php +++ /dev/null @@ -1,1205 +0,0 @@ - | -// +-----------------------------------------------------------------------+ -// -// $Id: Request.php 6820 2007-06-20 13:35:30Z kevin_fourie $ -// -// HTTP_Request Class -// -// Simple example, (Fetches yahoo.com and displays it): -// -// $a = &new HTTP_Request('http://www.yahoo.com/'); -// $a->sendRequest(); -// echo $a->getResponseBody(); -// - -require_once 'PEAR.php'; -require_once 'Net/Socket.php'; -require_once 'Net/URL.php'; - -define('HTTP_REQUEST_METHOD_GET', 'GET', true); -define('HTTP_REQUEST_METHOD_HEAD', 'HEAD', true); -define('HTTP_REQUEST_METHOD_POST', 'POST', true); -define('HTTP_REQUEST_METHOD_PUT', 'PUT', true); -define('HTTP_REQUEST_METHOD_DELETE', 'DELETE', true); -define('HTTP_REQUEST_METHOD_OPTIONS', 'OPTIONS', true); -define('HTTP_REQUEST_METHOD_TRACE', 'TRACE', true); - -define('HTTP_REQUEST_HTTP_VER_1_0', '1.0', true); -define('HTTP_REQUEST_HTTP_VER_1_1', '1.1', true); - -class HTTP_Request { - - /** - * Instance of Net_URL - * @var object Net_URL - */ - var $_url; - - /** - * Type of request - * @var string - */ - var $_method; - - /** - * HTTP Version - * @var string - */ - var $_http; - - /** - * Request headers - * @var array - */ - var $_requestHeaders; - - /** - * Basic Auth Username - * @var string - */ - var $_user; - - /** - * Basic Auth Password - * @var string - */ - var $_pass; - - /** - * Socket object - * @var object Net_Socket - */ - var $_sock; - - /** - * Proxy server - * @var string - */ - var $_proxy_host; - - /** - * Proxy port - * @var integer - */ - var $_proxy_port; - - /** - * Proxy username - * @var string - */ - var $_proxy_user; - - /** - * Proxy password - * @var string - */ - var $_proxy_pass; - - /** - * Post data - * @var array - */ - var $_postData; - - /** - * Request body - * @var string - */ - var $_body; - - /** - * A list of methods that MUST NOT have a request body, per RFC 2616 - * @var array - */ - var $_bodyDisallowed = array('TRACE'); - - /** - * Files to post - * @var array - */ - var $_postFiles = array(); - - /** - * Connection timeout. - * @var float - */ - var $_timeout; - - /** - * HTTP_Response object - * @var object HTTP_Response - */ - var $_response; - - /** - * Whether to allow redirects - * @var boolean - */ - var $_allowRedirects; - - /** - * Maximum redirects allowed - * @var integer - */ - var $_maxRedirects; - - /** - * Current number of redirects - * @var integer - */ - var $_redirects; - - /** - * Whether to append brackets [] to array variables - * @var bool - */ - var $_useBrackets = true; - - /** - * Attached listeners - * @var array - */ - var $_listeners = array(); - - /** - * Whether to save response body in response object property - * @var bool - */ - var $_saveBody = true; - - /** - * Timeout for reading from socket (array(seconds, microseconds)) - * @var array - */ - var $_readTimeout = null; - - /** - * Options to pass to Net_Socket::connect. See stream_context_create - * @var array - */ - var $_socketOptions = null; - - /** - * Constructor - * - * Sets up the object - * @param string The url to fetch/access - * @param array Associative array of parameters which can have the following keys: - *
    - *
  • method - Method to use, GET, POST etc (string)
  • - *
  • http - HTTP Version to use, 1.0 or 1.1 (string)
  • - *
  • user - Basic Auth username (string)
  • - *
  • pass - Basic Auth password (string)
  • - *
  • proxy_host - Proxy server host (string)
  • - *
  • proxy_port - Proxy server port (integer)
  • - *
  • proxy_user - Proxy auth username (string)
  • - *
  • proxy_pass - Proxy auth password (string)
  • - *
  • timeout - Connection timeout in seconds (float)
  • - *
  • allowRedirects - Whether to follow redirects or not (bool)
  • - *
  • maxRedirects - Max number of redirects to follow (integer)
  • - *
  • useBrackets - Whether to append [] to array variable names (bool)
  • - *
  • saveBody - Whether to save response body in response object property (bool)
  • - *
  • readTimeout - Timeout for reading / writing data over the socket (array (seconds, microseconds))
  • - *
  • socketOptions - Options to pass to Net_Socket object (array)
  • - *
- * @access public - */ - function HTTP_Request($url = '', $params = array()) - { - $this->_sock = new Net_Socket(); - $this->_method = HTTP_REQUEST_METHOD_GET; - $this->_http = HTTP_REQUEST_HTTP_VER_1_1; - $this->_requestHeaders = array(); - $this->_postData = array(); - $this->_body = null; - - $this->_user = null; - $this->_pass = null; - - $this->_proxy_host = null; - $this->_proxy_port = null; - $this->_proxy_user = null; - $this->_proxy_pass = null; - - $this->_allowRedirects = false; - $this->_maxRedirects = 3; - $this->_redirects = 0; - - $this->_timeout = null; - $this->_response = null; - - foreach ($params as $key => $value) { - $this->{'_' . $key} = $value; - } - - if (!empty($url)) { - $this->setURL($url); - } - - // Default useragent - $this->addHeader('User-Agent', 'PEAR HTTP_Request class ( http://pear.php.net/ )'); - - // Make sure keepalives dont knobble us - $this->addHeader('Connection', 'close'); - - // Basic authentication - if (!empty($this->_user)) { - $this->addHeader('Authorization', 'Basic ' . base64_encode($this->_user . ':' . $this->_pass)); - } - - // Use gzip encoding if possible - // Avoid gzip encoding if using multibyte functions (see #1781) - if (HTTP_REQUEST_HTTP_VER_1_1 == $this->_http && extension_loaded('zlib') && - 0 == (2 & ini_get('mbstring.func_overload'))) { - - $this->addHeader('Accept-Encoding', 'gzip'); - } - } - - /** - * Generates a Host header for HTTP/1.1 requests - * - * @access private - * @return string - */ - function _generateHostHeader() - { - if ($this->_url->port != 80 AND strcasecmp($this->_url->protocol, 'http') == 0) { - $host = $this->_url->host . ':' . $this->_url->port; - - } elseif ($this->_url->port != 443 AND strcasecmp($this->_url->protocol, 'https') == 0) { - $host = $this->_url->host . ':' . $this->_url->port; - - } elseif ($this->_url->port == 443 AND strcasecmp($this->_url->protocol, 'https') == 0 AND strpos($this->_url->url, ':443') !== false) { - $host = $this->_url->host . ':' . $this->_url->port; - - } else { - $host = $this->_url->host; - } - - return $host; - } - - /** - * Resets the object to its initial state (DEPRECATED). - * Takes the same parameters as the constructor. - * - * @param string $url The url to be requested - * @param array $params Associative array of parameters - * (see constructor for details) - * @access public - * @deprecated deprecated since 1.2, call the constructor if this is necessary - */ - function reset($url, $params = array()) - { - $this->HTTP_Request($url, $params); - } - - /** - * Sets the URL to be requested - * - * @param string The url to be requested - * @access public - */ - function setURL($url) - { - $this->_url = new Net_URL($url, $this->_useBrackets); - - if (!empty($this->_url->user) || !empty($this->_url->pass)) { - $this->setBasicAuth($this->_url->user, $this->_url->pass); - } - - if (HTTP_REQUEST_HTTP_VER_1_1 == $this->_http) { - $this->addHeader('Host', $this->_generateHostHeader()); - } - } - - /** - * Sets a proxy to be used - * - * @param string Proxy host - * @param int Proxy port - * @param string Proxy username - * @param string Proxy password - * @access public - */ - function setProxy($host, $port = 8080, $user = null, $pass = null) - { - $this->_proxy_host = $host; - $this->_proxy_port = $port; - $this->_proxy_user = $user; - $this->_proxy_pass = $pass; - - if (!empty($user)) { - $this->addHeader('Proxy-Authorization', 'Basic ' . base64_encode($user . ':' . $pass)); - } - } - - /** - * Sets basic authentication parameters - * - * @param string Username - * @param string Password - */ - function setBasicAuth($user, $pass) - { - $this->_user = $user; - $this->_pass = $pass; - - $this->addHeader('Authorization', 'Basic ' . base64_encode($user . ':' . $pass)); - } - - /** - * Sets the method to be used, GET, POST etc. - * - * @param string Method to use. Use the defined constants for this - * @access public - */ - function setMethod($method) - { - $this->_method = $method; - } - - /** - * Sets the HTTP version to use, 1.0 or 1.1 - * - * @param string Version to use. Use the defined constants for this - * @access public - */ - function setHttpVer($http) - { - $this->_http = $http; - } - - /** - * Adds a request header - * - * @param string Header name - * @param string Header value - * @access public - */ - function addHeader($name, $value) - { - $this->_requestHeaders[strtolower($name)] = $value; - } - - /** - * Removes a request header - * - * @param string Header name to remove - * @access public - */ - function removeHeader($name) - { - if (isset($this->_requestHeaders[strtolower($name)])) { - unset($this->_requestHeaders[strtolower($name)]); - } - } - - /** - * Adds a querystring parameter - * - * @param string Querystring parameter name - * @param string Querystring parameter value - * @param bool Whether the value is already urlencoded or not, default = not - * @access public - */ - function addQueryString($name, $value, $preencoded = false) - { - $this->_url->addQueryString($name, $value, $preencoded); - } - - /** - * Sets the querystring to literally what you supply - * - * @param string The querystring data. Should be of the format foo=bar&x=y etc - * @param bool Whether data is already urlencoded or not, default = already encoded - * @access public - */ - function addRawQueryString($querystring, $preencoded = true) - { - $this->_url->addRawQueryString($querystring, $preencoded); - } - - /** - * Adds postdata items - * - * @param string Post data name - * @param string Post data value - * @param bool Whether data is already urlencoded or not, default = not - * @access public - */ - function addPostData($name, $value, $preencoded = false) - { - if ($preencoded) { - $this->_postData[$name] = $value; - } else { - $this->_postData[$name] = $this->_arrayMapRecursive('urlencode', $value); - } - } - - /** - * Recursively applies the callback function to the value - * - * @param mixed Callback function - * @param mixed Value to process - * @access private - * @return mixed Processed value - */ - function _arrayMapRecursive($callback, $value) - { - if (!is_array($value)) { - return call_user_func($callback, $value); - } else { - $map = array(); - foreach ($value as $k => $v) { - $map[$k] = $this->_arrayMapRecursive($callback, $v); - } - return $map; - } - } - - /** - * Adds a file to upload - * - * This also changes content-type to 'multipart/form-data' for proper upload - * - * @access public - * @param string name of file-upload field - * @param mixed file name(s) - * @param mixed content-type(s) of file(s) being uploaded - * @return bool true on success - * @throws PEAR_Error - */ - function addFile($inputName, $fileName, $contentType = 'application/octet-stream') - { - if (!is_array($fileName) && !is_readable($fileName)) { - return PEAR::raiseError("File '{$fileName}' is not readable"); - } elseif (is_array($fileName)) { - foreach ($fileName as $name) { - if (!is_readable($name)) { - return PEAR::raiseError("File '{$name}' is not readable"); - } - } - } - $this->addHeader('Content-Type', 'multipart/form-data'); - $this->_postFiles[$inputName] = array( - 'name' => $fileName, - 'type' => $contentType - ); - return true; - } - - /** - * Adds raw postdata (DEPRECATED) - * - * @param string The data - * @param bool Whether data is preencoded or not, default = already encoded - * @access public - * @deprecated deprecated since 1.3.0, method addBody() should be used instead - */ - function addRawPostData($postdata, $preencoded = true) - { - $this->_body = $preencoded ? $postdata : urlencode($postdata); - } - - /** - * Sets the request body (for POST, PUT and similar requests) - * - * @param string Request body - * @access public - */ - function setBody($body) - { - $this->_body = $body; - } - - /** - * Clears any postdata that has been added (DEPRECATED). - * - * Useful for multiple request scenarios. - * - * @access public - * @deprecated deprecated since 1.2 - */ - function clearPostData() - { - $this->_postData = null; - } - - /** - * Appends a cookie to "Cookie:" header - * - * @param string $name cookie name - * @param string $value cookie value - * @access public - */ - function addCookie($name, $value) - { - $cookies = isset($this->_requestHeaders['cookie']) ? $this->_requestHeaders['cookie']. '; ' : ''; - $this->addHeader('Cookie', $cookies . $name . '=' . $value); - } - - /** - * Clears any cookies that have been added (DEPRECATED). - * - * Useful for multiple request scenarios - * - * @access public - * @deprecated deprecated since 1.2 - */ - function clearCookies() - { - $this->removeHeader('Cookie'); - } - - /** - * Sends the request - * - * @access public - * @param bool Whether to store response body in Response object property, - * set this to false if downloading a LARGE file and using a Listener - * @return mixed PEAR error on error, true otherwise - */ - function sendRequest($saveBody = true) - { - if (!is_a($this->_url, 'Net_URL')) { - return PEAR::raiseError('No URL given.'); - } - - $host = isset($this->_proxy_host) ? $this->_proxy_host : $this->_url->host; - $port = isset($this->_proxy_port) ? $this->_proxy_port : $this->_url->port; - - // 4.3.0 supports SSL connections using OpenSSL. The function test determines - // we running on at least 4.3.0 - if (strcasecmp($this->_url->protocol, 'https') == 0 AND function_exists('file_get_contents') AND extension_loaded('openssl')) { - if (isset($this->_proxy_host)) { - return PEAR::raiseError('HTTPS proxies are not supported.'); - } - $host = 'ssl://' . $host; - } - - // magic quotes may fuck up file uploads and chunked response processing - $magicQuotes = ini_get('magic_quotes_runtime'); - ini_set('magic_quotes_runtime', false); - - // If this is a second request, we may get away without - // re-connecting if they're on the same server - $err = $this->_sock->connect($host, $port, null, $this->_timeout, $this->_socketOptions); - PEAR::isError($err) or $err = $this->_sock->write($this->_buildRequest()); - - if (!PEAR::isError($err)) { - if (!empty($this->_readTimeout)) { - $this->_sock->setTimeout($this->_readTimeout[0], $this->_readTimeout[1]); - } - - $this->_notify('sentRequest'); - - // Read the response - $this->_response = new HTTP_Response($this->_sock, $this->_listeners); - $err = $this->_response->process($this->_saveBody && $saveBody); - } - - ini_set('magic_quotes_runtime', $magicQuotes); - - if (PEAR::isError($err)) { - return $err; - } - - - // Check for redirection - if ( $this->_allowRedirects - AND $this->_redirects <= $this->_maxRedirects - AND $this->getResponseCode() > 300 - AND $this->getResponseCode() < 399 - AND !empty($this->_response->_headers['location'])) { - - - $redirect = $this->_response->_headers['location']; - - // Absolute URL - if (preg_match('/^https?:\/\//i', $redirect)) { - $this->_url = new Net_URL($redirect); - $this->addHeader('Host', $this->_generateHostHeader()); - // Absolute path - } elseif ($redirect{0} == '/') { - $this->_url->path = $redirect; - - // Relative path - } elseif (substr($redirect, 0, 3) == '../' OR substr($redirect, 0, 2) == './') { - if (substr($this->_url->path, -1) == '/') { - $redirect = $this->_url->path . $redirect; - } else { - $redirect = dirname($this->_url->path) . '/' . $redirect; - } - $redirect = Net_URL::resolvePath($redirect); - $this->_url->path = $redirect; - - // Filename, no path - } else { - if (substr($this->_url->path, -1) == '/') { - $redirect = $this->_url->path . $redirect; - } else { - $redirect = dirname($this->_url->path) . '/' . $redirect; - } - $this->_url->path = $redirect; - } - - $this->_redirects++; - return $this->sendRequest($saveBody); - - // Too many redirects - } elseif ($this->_allowRedirects AND $this->_redirects > $this->_maxRedirects) { - return PEAR::raiseError('Too many redirects'); - } - - $this->_sock->disconnect(); - - return true; - } - - /** - * Returns the response code - * - * @access public - * @return mixed Response code, false if not set - */ - function getResponseCode() - { - return isset($this->_response->_code) ? $this->_response->_code : false; - } - - /** - * Returns either the named header or all if no name given - * - * @access public - * @param string The header name to return, do not set to get all headers - * @return mixed either the value of $headername (false if header is not present) - * or an array of all headers - */ - function getResponseHeader($headername = null) - { - if (!isset($headername)) { - return isset($this->_response->_headers)? $this->_response->_headers: array(); - } else { - $headername = strtolower($headername); - return isset($this->_response->_headers[$headername]) ? $this->_response->_headers[$headername] : false; - } - } - - /** - * Returns the body of the response - * - * @access public - * @return mixed response body, false if not set - */ - function getResponseBody() - { - return isset($this->_response->_body) ? $this->_response->_body : false; - } - - /** - * Returns cookies set in response - * - * @access public - * @return mixed array of response cookies, false if none are present - */ - function getResponseCookies() - { - return isset($this->_response->_cookies) ? $this->_response->_cookies : false; - } - - /** - * Builds the request string - * - * @access private - * @return string The request string - */ - function _buildRequest() - { - $separator = ini_get('arg_separator.output'); - ini_set('arg_separator.output', '&'); - $querystring = ($querystring = $this->_url->getQueryString()) ? '?' . $querystring : ''; - ini_set('arg_separator.output', $separator); - - $host = isset($this->_proxy_host) ? $this->_url->protocol . '://' . $this->_url->host : ''; - $port = (isset($this->_proxy_host) AND $this->_url->port != 80) ? ':' . $this->_url->port : ''; - $path = (empty($this->_url->path)? '/': $this->_url->path) . $querystring; - $url = $host . $port . $path; - - $request = $this->_method . ' ' . $url . ' HTTP/' . $this->_http . "\r\n"; - - if (in_array($this->_method, $this->_bodyDisallowed) || - (HTTP_REQUEST_METHOD_POST != $this->_method && empty($this->_body)) || - (HTTP_REQUEST_METHOD_POST != $this->_method && empty($this->_postData) && empty($this->_postFiles))) { - - $this->removeHeader('Content-Type'); - } else { - if (empty($this->_requestHeaders['content-type'])) { - // Add default content-type - $this->addHeader('Content-Type', 'application/x-www-form-urlencoded'); - } elseif ('multipart/form-data' == $this->_requestHeaders['content-type']) { - $boundary = 'HTTP_Request_' . $this->encryptOld(uniqid('request') . microtime()); - $this->addHeader('Content-Type', 'multipart/form-data; boundary=' . $boundary); - } - } - - // Request Headers - if (!empty($this->_requestHeaders)) { - foreach ($this->_requestHeaders as $name => $value) { - $canonicalName = implode('-', array_map('ucfirst', explode('-', $name))); - $request .= $canonicalName . ': ' . $value . "\r\n"; - } - } - - // No post data or wrong method, so simply add a final CRLF - if (in_array($this->_method, $this->_bodyDisallowed) || - (HTTP_REQUEST_METHOD_POST != $this->_method && empty($this->_body))) { - - $request .= "\r\n"; - - // Post data if it's an array - } elseif (HTTP_REQUEST_METHOD_POST == $this->_method && - (!empty($this->_postData) || !empty($this->_postFiles))) { - - // "normal" POST request - if (!isset($boundary)) { - $postdata = implode('&', array_map( - create_function('$a', 'return $a[0] . \'=\' . $a[1];'), - $this->_flattenArray('', $this->_postData) - )); - - // multipart request, probably with file uploads - } else { - $postdata = ''; - if (!empty($this->_postData)) { - $flatData = $this->_flattenArray('', $this->_postData); - foreach ($flatData as $item) { - $postdata .= '--' . $boundary . "\r\n"; - $postdata .= 'Content-Disposition: form-data; name="' . $item[0] . '"'; - $postdata .= "\r\n\r\n" . urldecode($item[1]) . "\r\n"; - } - } - foreach ($this->_postFiles as $name => $value) { - if (is_array($value['name'])) { - $varname = $name . ($this->_useBrackets? '[]': ''); - } else { - $varname = $name; - $value['name'] = array($value['name']); - } - foreach ($value['name'] as $key => $filename) { - $fp = fopen($filename, 'r'); - $data = fread($fp, filesize($filename)); - fclose($fp); - $basename = basename($filename); - $type = is_array($value['type'])? @$value['type'][$key]: $value['type']; - - $postdata .= '--' . $boundary . "\r\n"; - $postdata .= 'Content-Disposition: form-data; name="' . $varname . '"; filename="' . $basename . '"'; - $postdata .= "\r\nContent-Type: " . $type; - $postdata .= "\r\n\r\n" . $data . "\r\n"; - } - } - $postdata .= '--' . $boundary . "--\r\n"; - } - $request .= 'Content-Length: ' . strlen($postdata) . "\r\n\r\n"; - $request .= $postdata; - - // Explicitly set request body - } elseif (!empty($this->_body)) { - - $request .= 'Content-Length: ' . strlen($this->_body) . "\r\n\r\n"; - $request .= $this->_body; - } - - return $request; - } - - /** - * Helper function to change the (probably multidimensional) associative array - * into the simple one. - * - * @param string name for item - * @param mixed item's values - * @return array array with the following items: array('item name', 'item value'); - */ - function _flattenArray($name, $values) - { - if (!is_array($values)) { - return array(array($name, $values)); - } else { - $ret = array(); - foreach ($values as $k => $v) { - if (empty($name)) { - $newName = $k; - } elseif ($this->_useBrackets) { - $newName = $name . '[' . $k . ']'; - } else { - $newName = $name; - } - $ret = array_merge($ret, $this->_flattenArray($newName, $v)); - } - return $ret; - } - } - - - /** - * Adds a Listener to the list of listeners that are notified of - * the object's events - * - * @param object HTTP_Request_Listener instance to attach - * @return boolean whether the listener was successfully attached - * @access public - */ - function attach(&$listener) - { - if (!is_a($listener, 'HTTP_Request_Listener')) { - return false; - } - $this->_listeners[$listener->getId()] =& $listener; - return true; - } - - - /** - * Removes a Listener from the list of listeners - * - * @param object HTTP_Request_Listener instance to detach - * @return boolean whether the listener was successfully detached - * @access public - */ - function detach(&$listener) - { - if (!is_a($listener, 'HTTP_Request_Listener') || - !isset($this->_listeners[$listener->getId()])) { - return false; - } - unset($this->_listeners[$listener->getId()]); - return true; - } - - - /** - * Notifies all registered listeners of an event. - * - * Events sent by HTTP_Request object - * 'sentRequest': after the request was sent - * Events sent by HTTP_Response object - * 'gotHeaders': after receiving response headers (headers are passed in $data) - * 'tick': on receiving a part of response body (the part is passed in $data) - * 'gzTick': on receiving a gzip-encoded part of response body (ditto) - * 'gotBody': after receiving the response body (passes the decoded body in $data if it was gzipped) - * - * @param string Event name - * @param mixed Additional data - * @access private - */ - function _notify($event, $data = null) - { - foreach (array_keys($this->_listeners) as $id) { - $this->_listeners[$id]->update($this, $event, $data); - } - } - - 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); - } -} - - -/** -* Response class to complement the Request class -*/ -class HTTP_Response -{ - /** - * Socket object - * @var object - */ - var $_sock; - - /** - * Protocol - * @var string - */ - var $_protocol; - - /** - * Return code - * @var string - */ - var $_code; - - /** - * Response headers - * @var array - */ - var $_headers; - - /** - * Cookies set in response - * @var array - */ - var $_cookies; - - /** - * Response body - * @var string - */ - var $_body = ''; - - /** - * Used by _readChunked(): remaining length of the current chunk - * @var string - */ - var $_chunkLength = 0; - - /** - * Attached listeners - * @var array - */ - var $_listeners = array(); - - /** - * Constructor - * - * @param object Net_Socket socket to read the response from - * @param array listeners attached to request - * @return mixed PEAR Error on error, true otherwise - */ - function HTTP_Response(&$sock, &$listeners) - { - $this->_sock =& $sock; - $this->_listeners =& $listeners; - } - - - /** - * Processes a HTTP response - * - * This extracts response code, headers, cookies and decodes body if it - * was encoded in some way - * - * @access public - * @param bool Whether to store response body in object property, set - * this to false if downloading a LARGE file and using a Listener. - * This is assumed to be true if body is gzip-encoded. - * @throws PEAR_Error - * @return mixed true on success, PEAR_Error in case of malformed response - */ - function process($saveBody = true) - { - do { - $line = $this->_sock->readLine(); - if (sscanf($line, 'HTTP/%s %s', $http_version, $returncode) != 2) { - return PEAR::raiseError('Malformed response.'); - } else { - $this->_protocol = 'HTTP/' . $http_version; - $this->_code = intval($returncode); - } - while ('' !== ($header = $this->_sock->readLine())) { - $this->_processHeader($header); - } - } while (100 == $this->_code); - - $this->_notify('gotHeaders', $this->_headers); - - // If response body is present, read it and decode - $chunked = isset($this->_headers['transfer-encoding']) && ('chunked' == $this->_headers['transfer-encoding']); - $gzipped = isset($this->_headers['content-encoding']) && ('gzip' == $this->_headers['content-encoding']); - $hasBody = false; - if (!isset($this->_headers['content-length']) || 0 != $this->_headers['content-length']) { - while (!$this->_sock->eof()) { - if ($chunked) { - $data = $this->_readChunked(); - } else { - $data = $this->_sock->read(4096); - } - if ('' == $data) { - break; - } else { - $hasBody = true; - if ($saveBody || $gzipped) { - $this->_body .= $data; - } - $this->_notify($gzipped? 'gzTick': 'tick', $data); - } - } - } - if ($hasBody) { - // Uncompress the body if needed - if ($gzipped) { - $this->_body = gzinflate(substr($this->_body, 10)); - $this->_notify('gotBody', $this->_body); - } else { - $this->_notify('gotBody'); - } - } - return true; - } - - - /** - * Processes the response header - * - * @access private - * @param string HTTP header - */ - function _processHeader($header) - { - list($headername, $headervalue) = explode(':', $header, 2); - $headername = strtolower($headername); - $headervalue = ltrim($headervalue); - - if ('set-cookie' != $headername) { - if (isset($this->_headers[$headername])) { - $this->_headers[$headername] .= ',' . $headervalue; - } else { - $this->_headers[$headername] = $headervalue; - } - } else { - $this->_parseCookie($headervalue); - } - } - - - /** - * Parse a Set-Cookie header to fill $_cookies array - * - * @access private - * @param string value of Set-Cookie header - */ - function _parseCookie($headervalue) - { - $cookie = array( - 'expires' => null, - 'domain' => null, - 'path' => null, - 'secure' => false - ); - - // Only a name=value pair - if (!strpos($headervalue, ';')) { - $pos = strpos($headervalue, '='); - $cookie['name'] = trim(substr($headervalue, 0, $pos)); - $cookie['value'] = trim(substr($headervalue, $pos + 1)); - - // Some optional parameters are supplied - } else { - $elements = explode(';', $headervalue); - $pos = strpos($elements[0], '='); - $cookie['name'] = trim(substr($elements[0], 0, $pos)); - $cookie['value'] = trim(substr($elements[0], $pos + 1)); - - for ($i = 1; $i < count($elements); $i++) { - if (false === strpos($elements[$i], '=')) { - $elName = trim($elements[$i]); - $elValue = null; - } else { - list ($elName, $elValue) = array_map('trim', explode('=', $elements[$i])); - } - $elName = strtolower($elName); - if ('secure' == $elName) { - $cookie['secure'] = true; - } elseif ('expires' == $elName) { - $cookie['expires'] = str_replace('"', '', $elValue); - } elseif ('path' == $elName || 'domain' == $elName) { - $cookie[$elName] = urldecode($elValue); - } else { - $cookie[$elName] = $elValue; - } - } - } - $this->_cookies[] = $cookie; - } - - - /** - * Read a part of response body encoded with chunked Transfer-Encoding - * - * @access private - * @return string - */ - function _readChunked() - { - // at start of the next chunk? - if (0 == $this->_chunkLength) { - $line = $this->_sock->readLine(); - if (preg_match('/^([0-9a-f]+)/i', $line, $matches)) { - $this->_chunkLength = hexdec($matches[1]); - // Chunk with zero length indicates the end - if (0 == $this->_chunkLength) { - $this->_sock->readLine(); // make this an eof() - return ''; - } - } else { - return ''; - } - } - $data = $this->_sock->read($this->_chunkLength); - $this->_chunkLength -= strlen($data); - if (0 == $this->_chunkLength) { - $this->_sock->readLine(); // Trailing CRLF - } - return $data; - } - - - /** - * Notifies all registered listeners of an event. - * - * @param string Event name - * @param mixed Additional data - * @access private - * @see HTTP_Request::_notify() - */ - function _notify($event, $data = null) - { - foreach (array_keys($this->_listeners) as $id) { - $this->_listeners[$id]->update($this, $event, $data); - } - } -} // End class HTTP_Response -?> diff --git a/gulliver/thirdparty/pear/HTTP/WebDAV/Server.php b/gulliver/thirdparty/pear/HTTP/WebDAV/Server.php deleted file mode 100644 index 15188f91f..000000000 --- a/gulliver/thirdparty/pear/HTTP/WebDAV/Server.php +++ /dev/null @@ -1,2089 +0,0 @@ - | -// | Christian Stocker | -// +----------------------------------------------------------------------+ -// -// $Id: Server.php,v 1.46 2006/03/03 21:43:09 hholzgra Exp $ -// -require_once "HTTP/WebDAV/Tools/_parse_propfind.php"; -require_once "HTTP/WebDAV/Tools/_parse_proppatch.php"; -require_once "HTTP/WebDAV/Tools/_parse_lockinfo.php"; - - - -/** - * Virtual base class for implementing WebDAV servers - * - * WebDAV server base class, needs to be extended to do useful work - * - * @package HTTP_WebDAV_Server - * @author Hartmut Holzgraefe - * @version 0.99.1dev - */ -class HTTP_WebDAV_Server -{ - // {{{ Member Variables - - /** - * complete URI for this request - * - * @var string - */ - var $uri; - - - /** - * base URI for this request - * - * @var string - */ - var $base_uri; - - - /** - * URI path for this request - * - * @var string - */ - var $path; - - /** - * Realm string to be used in authentification popups - * - * @var string - */ - var $http_auth_realm = "PHP WebDAV"; - - /** - * String to be used in "X-Dav-Powered-By" header - * - * @var string - */ - var $dav_powered_by = ""; - - /** - * Remember parsed If: (RFC2518/9.4) header conditions - * - * @var array - */ - var $_if_header_uris = array(); - - /** - * HTTP response status/message - * - * @var string - */ - var $_http_status = "200 OK"; - - /** - * encoding of property values passed in - * - * @var string - */ - var $_prop_encoding = "utf-8"; - - // }}} - - // {{{ Constructor - - /** - * Constructor - * - * @param void - */ - function HTTP_WebDAV_Server() - { - // PHP messages destroy XML output -> switch them off - ini_set("display_errors", 0); - } - - // }}} - - // {{{ ServeRequest() - /** - * Serve WebDAV HTTP request - * - * dispatch WebDAV HTTP request to the apropriate method handler - * - * @param void - * @return void - */ - function ServeRequest() - { - // prevent warning in litmus check 'delete_fragment' - if (strstr($_SERVER["REQUEST_URI"], '#')) { - $this->http_status("400 Bad Request"); - return; - } - - // default uri is the complete request uri - $uri = (@$_SERVER["HTTPS"] === "on" ? "https:" : "http:"); - $messagePath = (@$_SERVER["HTTPS"] === "on" ? "https:" : "http:"); - $uri.= "//$_SERVER[HTTP_HOST]$_SERVER[SCRIPT_NAME]"; - - $path_info = empty($_SERVER["PATH_INFO"]) ? "/" : $_SERVER["PATH_INFO"]; - - $this->base_uri = $uri; - $this->uri = $uri . $path_info; - - $requestUri = $_SERVER['REQUEST_URI']; - if ( substr ( $requestUri, -1 ) == '/' ) $requestUri = substr ( $requestUri, 0, strlen ($requestUri) -1 ); - $paths = explode ( '/', $requestUri ); - $redirectPaths = $paths; - array_shift ( $paths ); - array_shift ( $paths ); - array_shift ( $paths ); - array_shift ( $paths ); - array_shift ( $paths ); - array_shift ( $paths ); - array_shift ( $redirectPaths ); - array_pop ( $redirectPaths ); - $this->paths = $paths; - - // set path - //$this->path = $this->_urldecode($path_info); - $this->path = implode ('/', $paths ); - - if (!strlen($this->path)) { - if ($_SERVER["REQUEST_METHOD"] == "GET") { - // redirect clients that try to GET a collection - // WebDAV clients should never try this while - // regular HTTP clients might ... - $redirectPaths = implode ('/', $redirectPaths ); - $messagePath .= '//'.$_SERVER['HTTP_HOST'].'/'.$redirectPaths.'/unavailableService'; - header("Location: ".$messagePath); -// header("Location: ".$this->base_uri."/"); - return; - } else { - // if a WebDAV client didn't give a path we just assume '/' - $this->path = "/"; - } - } - - if(ini_get("magic_quotes_gpc")) { - $this->path = stripslashes($this->path); - } - - - // identify ourselves - if (empty($this->dav_powered_by)) { - header("X-Dav-Powered-By: PHP class: ".get_class($this)); - } else { - header("X-Dav-Powered-By: ".$this->dav_powered_by ); - } - - // check authentication - // for the motivation for not checking OPTIONS requests on / see - // http://pear.php.net/bugs/bug.php?id=5363 - if ( ( !(($_SERVER['REQUEST_METHOD'] == 'OPTIONS') && ($this->path == "/"))) - && (!$this->_check_auth())) { - // RFC2518 says we must use Digest instead of Basic - // but Microsoft Clients do not support Digest - // and we don't support NTLM and Kerberos - // so we are stuck with Basic here - header('WWW-Authenticate: Basic realm="'.($this->http_auth_realm).'"'); - - // Windows seems to require this being the last header sent - // (changed according to PECL bug #3138) - $this->http_status('401 Unauthorized'); - - return; - } - - // check - if(! $this->_check_if_header_conditions()) { - return; - } - - // detect requested method names - $method = strtolower($_SERVER["REQUEST_METHOD"]); - $wrapper = "http_".$method; - - // activate HEAD emulation by GET if no HEAD method found - if ($method == "head" && !method_exists($this, "head")) { - $method = "get"; - } - - if (method_exists($this, $wrapper) && ($method == "options" || method_exists($this, $method))) { - $this->$wrapper(); // call method by name - } else { // method not found/implemented - if ($_SERVER["REQUEST_METHOD"] == "LOCK") { - $this->http_status("412 Precondition failed"); - } else { - $this->http_status("405 Method not allowed"); - header("Allow: ".join(", ", $this->_allow())); // tell client what's allowed - } - } - } - - // }}} - - // {{{ abstract WebDAV methods - - // {{{ GET() - /** - * GET implementation - * - * overload this method to retrieve resources from your server - *
- * - * - * @abstract - * @param array &$params Array of input and output parameters - *
input
    - *
  • path - - *
- *
output
    - *
  • size - - *
- * @returns int HTTP-Statuscode - */ - - /* abstract - function GET(&$params) - { - // dummy entry for PHPDoc - } - */ - - // }}} - - // {{{ PUT() - /** - * PUT implementation - * - * PUT implementation - * - * @abstract - * @param array &$params - * @returns int HTTP-Statuscode - */ - - /* abstract - function PUT() - { - // dummy entry for PHPDoc - } - */ - - // }}} - - // {{{ COPY() - - /** - * COPY implementation - * - * COPY implementation - * - * @abstract - * @param array &$params - * @returns int HTTP-Statuscode - */ - - /* abstract - function COPY() - { - // dummy entry for PHPDoc - } - */ - - // }}} - - // {{{ MOVE() - - /** - * MOVE implementation - * - * MOVE implementation - * - * @abstract - * @param array &$params - * @returns int HTTP-Statuscode - */ - - /* abstract - function MOVE() - { - // dummy entry for PHPDoc - } - */ - - // }}} - - // {{{ DELETE() - - /** - * DELETE implementation - * - * DELETE implementation - * - * @abstract - * @param array &$params - * @returns int HTTP-Statuscode - */ - - /* abstract - function DELETE() - { - // dummy entry for PHPDoc - } - */ - // }}} - - // {{{ PROPFIND() - - /** - * PROPFIND implementation - * - * PROPFIND implementation - * - * @abstract - * @param array &$params - * @returns int HTTP-Statuscode - */ - - /* abstract - function PROPFIND() - { - // dummy entry for PHPDoc - } - */ - - // }}} - - // {{{ PROPPATCH() - - /** - * PROPPATCH implementation - * - * PROPPATCH implementation - * - * @abstract - * @param array &$params - * @returns int HTTP-Statuscode - */ - - /* abstract - function PROPPATCH() - { - // dummy entry for PHPDoc - } - */ - // }}} - - // {{{ LOCK() - - /** - * LOCK implementation - * - * LOCK implementation - * - * @abstract - * @param array &$params - * @returns int HTTP-Statuscode - */ - - /* abstract - function LOCK() - { - // dummy entry for PHPDoc - } - */ - // }}} - - // {{{ UNLOCK() - - /** - * UNLOCK implementation - * - * UNLOCK implementation - * - * @abstract - * @param array &$params - * @returns int HTTP-Statuscode - */ - - /* abstract - function UNLOCK() - { - // dummy entry for PHPDoc - } - */ - // }}} - - // }}} - - // {{{ other abstract methods - - // {{{ check_auth() - - /** - * check authentication - * - * overload this method to retrieve and confirm authentication information - * - * @abstract - * @param string type Authentication type, e.g. "basic" or "digest" - * @param string username Transmitted username - * @param string passwort Transmitted password - * @returns bool Authentication status - */ - - /* abstract - function checkAuth($type, $username, $password) - { - // dummy entry for PHPDoc - } - */ - - // }}} - - // {{{ checklock() - - /** - * check lock status for a resource - * - * overload this method to return shared and exclusive locks - * active for this resource - * - * @abstract - * @param string resource Resource path to check - * @returns array An array of lock entries each consisting - * of 'type' ('shared'/'exclusive'), 'token' and 'timeout' - */ - - /* abstract - function checklock($resource) - { - // dummy entry for PHPDoc - } - */ - - // }}} - - // }}} - - // {{{ WebDAV HTTP method wrappers - - // {{{ http_OPTIONS() - - /** - * OPTIONS method handler - * - * The OPTIONS method handler creates a valid OPTIONS reply - * including Dav: and Allowed: heaers - * based on the implemented methods found in the actual instance - * - * @param void - * @return void - */ - function http_OPTIONS() - { - // Microsoft clients default to the Frontpage protocol - // unless we tell them to use WebDAV - header("MS-Author-Via: DAV"); - - // get allowed methods - $allow = $this->_allow(); - - // dav header - $dav = array(1); // assume we are always dav class 1 compliant - if (isset($allow['LOCK'])) { - $dav[] = 2; // dav class 2 requires that locking is supported - } - - // tell clients what we found - $this->http_status("200 OK"); - header("DAV: " .join("," , $dav)); - header("Allow: ".join(", ", $allow)); - - header("Content-length: 0"); - } - - // }}} - - - // {{{ http_PROPFIND() - - /** - * PROPFIND method handler - * - * @param void - * @return void - */ - function http_PROPFIND() - { - $options = Array(); - $options["path"] = $this->path; - - // search depth from header (default is "infinity) - if (isset($_SERVER['HTTP_DEPTH'])) { - $options["depth"] = $_SERVER["HTTP_DEPTH"]; - } else { - $options["depth"] = "infinity"; - } - - // analyze request payload - $propinfo = new _parse_propfind("php://input"); - if (!$propinfo->success) { - $this->http_status("400 Error"); - return; - } - $options['props'] = $propinfo->props; - - // call user handler - if (!$this->PROPFIND($options, $files)) { - $this->http_status("404 Not Found"); - return; - } - - // collect namespaces here - $ns_hash = array(); - - // Microsoft Clients need this special namespace for date and time values - $ns_defs = "xmlns:ns0=\"urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/\""; - - // now we loop over all returned file entries - foreach($files["files"] as $filekey => $file) { - - // nothing to do if no properties were returend for a file - if (!isset($file["props"]) || !is_array($file["props"])) { - continue; - } - - // now loop over all returned properties - foreach($file["props"] as $key => $prop) { - // as a convenience feature we do not require that user handlers - // restrict returned properties to the requested ones - // here we strip all unrequested entries out of the response - - switch($options['props']) { - case "all": - // nothing to remove - break; - - case "names": - // only the names of all existing properties were requested - // so we remove all values - unset($files["files"][$filekey]["props"][$key]["val"]); - break; - - default: - $found = false; - - // search property name in requested properties - foreach((array)$options["props"] as $reqprop) { - if ( $reqprop["name"] == $prop["name"] - && @$reqprop["xmlns"] == $prop["ns"]) { - $found = true; - break; - } - } - - // unset property and continue with next one if not found/requested - if (!$found) { - $files["files"][$filekey]["props"][$key]=""; - continue(2); - } - break; - } - - // namespace handling - if (empty($prop["ns"])) continue; // no namespace - $ns = $prop["ns"]; - if ($ns == "DAV:") continue; // default namespace - if (isset($ns_hash[$ns])) continue; // already known - - // register namespace - $ns_name = "ns".(count($ns_hash) + 1); - $ns_hash[$ns] = $ns_name; - $ns_defs .= " xmlns:$ns_name=\"$ns\""; - } - - // we also need to add empty entries for properties that were requested - // but for which no values where returned by the user handler - if (is_array($options['props'])) { - foreach($options["props"] as $reqprop) { - if($reqprop['name']=="") continue; // skip empty entries - - $found = false; - - // check if property exists in result - foreach($file["props"] as $prop) { - if ( $reqprop["name"] == $prop["name"] - && @$reqprop["xmlns"] == $prop["ns"]) { - $found = true; - break; - } - } - - if (!$found) { - if($reqprop["xmlns"]==="DAV:" && $reqprop["name"]==="lockdiscovery") { - // lockdiscovery is handled by the base class - $files["files"][$filekey]["props"][] - = $this->mkprop("DAV:", - "lockdiscovery" , - $this->lockdiscovery($files["files"][$filekey]['path'])); - } else { - // add empty value for this property - $files["files"][$filekey]["noprops"][] = - $this->mkprop($reqprop["xmlns"], $reqprop["name"], ""); - - // register property namespace if not known yet - if ($reqprop["xmlns"] != "DAV:" && !isset($ns_hash[$reqprop["xmlns"]])) { - $ns_name = "ns".(count($ns_hash) + 1); - $ns_hash[$reqprop["xmlns"]] = $ns_name; - $ns_defs .= " xmlns:$ns_name=\"$reqprop[xmlns]\""; - } - } - } - } - } - } - - // now we generate the reply header ... - $this->http_status("207 Multi-Status"); - header('Content-Type: text/xml; charset="utf-8"'); - - // ... and payload - echo "\n"; - echo "\n"; - - foreach($files["files"] as $file) { - // ignore empty or incomplete entries - if(!is_array($file) || empty($file) || !isset($file["path"])) continue; - $path = $file['path']; - if(!is_string($path) || $path==="") continue; - - 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(); - $ns_defs = $filter->xssFilterHard($ns_defs); - - echo ' \n"; - - /* TODO right now the user implementation has to make sure - collections end in a slash, this should be done in here - by checking the resource attribute */ - //$href = $this->_mergePathes($_SERVER['SCRIPT_NAME'], $path); - $href = $this->_mergePathes($this->uriBase, $path); - - echo " $href\n"; - - // report all found properties and their values (if any) - if (isset($file["props"]) && is_array($file["props"])) { - echo " \n"; - echo " \n"; - - foreach($file["props"] as $key => $prop) { - - if (!is_array($prop)) continue; - if (!isset($prop["name"])) continue; - - if (!isset($prop["val"]) || $prop["val"] === "" || $prop["val"] === false) { - // empty properties (cannot use empty() for check as "0" is a legal value here) - if($prop["ns"]=="DAV:") { - echo " \n"; - } else if(!empty($prop["ns"])) { - echo " <".$ns_hash[$prop["ns"]].":$prop[name]/>\n"; - } else { - echo " <$prop[name] xmlns=\"\"/>"; - } - } else if ($prop["ns"] == "DAV:") { - // some WebDAV properties need special treatment - switch ($prop["name"]) { - case "creationdate": - echo " " - . gmdate("Y-m-d\\TH:i:s\\Z",$prop['val']) - . "\n"; - break; - case "getlastmodified": - echo " " - . gmdate("D, d M Y H:i:s ", $prop['val']) - . "GMT\n"; - break; - case "lastaccessed": - echo " " - . gmdate("D, d M Y H:i:s ", $prop['val']) - . "GMT\n"; - break; - case "resourcetype": - echo " \n"; - break; - case "supportedlock": - echo " $prop[val]\n"; - break; - case "lockdiscovery": - echo " \n"; - echo $prop["val"]; - echo " \n"; - break; - default: - echo " " - . $this->_prop_encode(htmlspecialchars($prop['val'])) - . "\n"; - break; - } - } else { - // properties from namespaces != "DAV:" or without any namespace - if ($prop["ns"]) { - echo " <" . $ns_hash[$prop["ns"]] . ":$prop[name]>" - . $this->_prop_encode(htmlspecialchars($prop['val'])) - . "\n"; - } else { - echo " <$prop[name] xmlns=\"\">" - . $this->_prop_encode(htmlspecialchars($prop['val'])) - . "\n"; - } - } - } - - echo " \n"; - echo " HTTP/1.1 200 OK\n"; - echo " \n"; - } - /* commented by Onti. - // now report all properties requested but not found - if (isset($file["noprops"])) { - echo " \n"; - echo " \n"; - - foreach($file["noprops"] as $key => $prop) { - if ($prop["ns"] == "DAV:") { - echo " \n"; - } else if ($prop["ns"] == "") { - echo " <$prop[name] xmlns=\"\"/>\n"; - } else { - echo " <" . $ns_hash[$prop["ns"]] . ":$prop[name]/>\n"; - } - } - - echo " \n"; - echo " HTTP/1.1 404 Not Found\n"; - echo " \n"; - } - */ - echo " \n"; - } - - echo "\n"; - } - - - // }}} - - // {{{ http_PROPPATCH() - - /** - * PROPPATCH method handler - * - * @param void - * @return void - */ - function http_PROPPATCH() - { - if($this->_check_lock_status($this->path)) { - $options = Array(); - $options["path"] = $this->path; - - $propinfo = new _parse_proppatch("php://input"); - - if (!$propinfo->success) { - $this->http_status("400 Error"); - return; - } - - $options['props'] = $propinfo->props; - - $responsedescr = $this->PROPPATCH($options); - - $this->http_status("207 Multi-Status"); - header('Content-Type: text/xml; charset="utf-8"'); - - 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(); - $_mergePathes = $filter->xssFilterHard($this->_urlencode($this->_mergePathes($_SERVER["SCRIPT_NAME"], $this->path))); - - echo "\n"; - - echo "\n"; - echo " \n"; - echo " ".$_mergePathes."\n"; - - foreach($options["props"] as $prop) { - echo " \n"; - echo " <$prop[name] xmlns=\"$prop[ns]\"/>\n"; - echo " HTTP/1.1 $prop[status]\n"; - echo " \n"; - } - - if ($responsedescr) { - echo " ". - $this->_prop_encode(htmlspecialchars($responsedescr)). - "\n"; - } - - echo " \n"; - echo "\n"; - } else { - $this->http_status("423 Locked"); - } - } - - // }}} - - - // {{{ http_MKCOL() - - /** - * MKCOL method handler - * - * @param void - * @return void - */ - function http_MKCOL() - { - $options = Array(); - $options["path"] = $this->path; - - $stat = $this->MKCOL($options); - - $this->http_status($stat); - } - - // }}} - - - // {{{ http_GET() - - /** - * GET method handler - * - * @param void - * @returns void - */ - function http_GET() - { - // TODO check for invalid stream - $options = Array(); - $options["path"] = $this->path; - - $this->_get_ranges($options); - - if (true === ($status = $this->GET($options))) { - if (!headers_sent()) { - $status = "200 OK"; - - if (!isset($options['mimetype'])) { - $options['mimetype'] = "application/octet-stream"; - } - header("Content-type: $options[mimetype]"); - - if (isset($options['mtime'])) { - header("Last-modified:".gmdate("D, d M Y H:i:s ", $options['mtime'])."GMT"); - } - - if (isset($options['stream'])) { - // GET handler returned a stream - if (!empty($options['ranges']) && (0===fseek($options['stream'], 0, SEEK_SET))) { - // partial request and stream is seekable - - if (count($options['ranges']) === 1) { - $range = $options['ranges'][0]; - - if (isset($range['start'])) { - fseek($options['stream'], $range['start'], SEEK_SET); - if (feof($options['stream'])) { - $this->http_status("416 Requested range not satisfiable"); - return; - } - - if (isset($range['end'])) { - $size = $range['end']-$range['start']+1; - $this->http_status("206 partial"); - header("Content-length: $size"); - header("Content-range: $range[start]-$range[end]/" - . (isset($options['size']) ? $options['size'] : "*")); - while ($size && !feof($options['stream'])) { - $buffer = fread($options['stream'], 4096); - $size -= strlen($buffer); - echo $buffer; - } - } else { - $this->http_status("206 partial"); - if (isset($options['size'])) { - header("Content-length: ".($options['size'] - $range['start'])); - header("Content-range: $start-$end/" - . (isset($options['size']) ? $options['size'] : "*")); - } - fpassthru($options['stream']); - } - } else { - header("Content-length: ".$range['last']); - fseek($options['stream'], -$range['last'], SEEK_END); - fpassthru($options['stream']); - } - } else { - $this->_multipart_byterange_header(); // init multipart - foreach ($options['ranges'] as $range) { - // TODO what if size unknown? 500? - if (isset($range['start'])) { - $from = $range['start']; - $to = !empty($range['end']) ? $range['end'] : $options['size']-1; - } else { - $from = $options['size'] - $range['last']-1; - $to = $options['size'] -1; - } - $total = isset($options['size']) ? $options['size'] : "*"; - $size = $to - $from + 1; - $this->_multipart_byterange_header($options['mimetype'], $from, $to, $total); - - - fseek($options['stream'], $start, SEEK_SET); - while ($size && !feof($options['stream'])) { - $buffer = fread($options['stream'], 4096); - $size -= strlen($buffer); - echo $buffer; - } - } - $this->_multipart_byterange_header(); // end multipart - } - } else { - // normal request or stream isn't seekable, return full content - if (isset($options['size'])) { - header("Content-length: ".$options['size']); - } - fpassthru($options['stream']); - return; // no more headers - } - } elseif (isset($options['data'])) { - if (is_array($options['data'])) { - // reply to partial request - } else { - header("Content-length: ".strlen($options['data'])); - echo $options['data']; - } - } - } - } - - if (!headers_sent()) { - if (false === $status) { - $this->http_status("404 not found"); - } else { - // TODO: check setting of headers in various code pathes above - $this->http_status("$status"); - } - } - } - - - /** - * parse HTTP Range: header - * - * @param array options array to store result in - * @return void - */ - function _get_ranges(&$options) - { - // process Range: header if present - if (isset($_SERVER['HTTP_RANGE'])) { - - // we only support standard "bytes" range specifications for now - if (preg_match('/bytes\s*=\s*(.+)/', $_SERVER['HTTP_RANGE'], $matches)) { - $options["ranges"] = array(); - - // ranges are comma separated - foreach (explode(",", $matches[1]) as $range) { - // ranges are either from-to pairs or just end positions - list($start, $end) = explode("-", $range); - $options["ranges"][] = ($start==="") - ? array("last"=>$end) - : array("start"=>$start, "end"=>$end); - } - } - } - } - - /** - * generate separator headers for multipart response - * - * first and last call happen without parameters to generate - * the initial header and closing sequence, all calls inbetween - * require content mimetype, start and end byte position and - * optionaly the total byte length of the requested resource - * - * @param string mimetype - * @param int start byte position - * @param int end byte position - * @param int total resource byte size - */ - function _multipart_byterange_header($mimetype = false, $from = false, $to=false, $total=false) - { - if ($mimetype === false) { - if (!isset($this->multipart_separator)) { - // initial - - // a little naive, this sequence *might* be part of the content - // but it's really not likely and rather expensive to check - $this->multipart_separator = "SEPARATOR_".$this->encryptOld(microtime()); - - // generate HTTP header - header("Content-type: multipart/byteranges; boundary=".$this->multipart_separator); - } else { - // final - - // generate closing multipart sequence - echo "\n--{$this->multipart_separator}--"; - } - } else { - // generate separator and header for next part - echo "\n--{$this->multipart_separator}\n"; - echo "Content-type: $mimetype\n"; - echo "Content-range: $from-$to/". ($total === false ? "*" : $total); - echo "\n\n"; - } - } - - - - // }}} - - // {{{ http_HEAD() - - /** - * HEAD method handler - * - * @param void - * @return void - */ - function http_HEAD() - { - $status = false; - $options = Array(); - $options["path"] = $this->path; - - if (method_exists($this, "HEAD")) { - $status = $this->head($options); - } else if (method_exists($this, "GET")) { - ob_start(); - $status = $this->GET($options); - if (!isset($options['size'])) { - $options['size'] = ob_get_length(); - } - ob_end_clean(); - } - - if (isset($options['size'])) { - header("Content-length: ".$options['size']); - } - - if($status===true) $status = "200 OK"; - if($status===false) $status = "404 Not found"; - - $this->http_status($status); - } - - // }}} - - // {{{ http_PUT() - - /** - * PUT method handler - * - * @param void - * @return void - */ - function http_PUT() - { - if ($this->_check_lock_status($this->path)) { - $options = Array(); - $options["path"] = $this->path; - $options["content_length"] = $_SERVER["CONTENT_LENGTH"]; - - // get the Content-type - if (isset($_SERVER["CONTENT_TYPE"])) { - // for now we do not support any sort of multipart requests - if (!strncmp($_SERVER["CONTENT_TYPE"], "multipart/", 10)) { - $this->http_status("501 not implemented"); - echo "The service does not support mulipart PUT requests"; - return; - } - $options["content_type"] = $_SERVER["CONTENT_TYPE"]; - } else { - // default content type if none given - $options["content_type"] = "application/octet-stream"; - } - - /* RFC 2616 2.6 says: "The recipient of the entity MUST NOT - ignore any Content-* (e.g. Content-Range) headers that it - does not understand or implement and MUST return a 501 - (Not Implemented) response in such cases." - */ - foreach ($_SERVER as $key => $val) { - if (strncmp($key, "HTTP_CONTENT", 11)) continue; - switch ($key) { - case 'HTTP_CONTENT_ENCODING': // RFC 2616 14.11 - // TODO support this if ext/zlib filters are available - $this->http_status("501 not implemented"); - - 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(); - $val = $filter->xssFilterHard($val); - - echo 'The service does not support \''.$val.'\' content encoding'; - return; - - case 'HTTP_CONTENT_LANGUAGE': // RFC 2616 14.12 - // we assume it is not critical if this one is ignored - // in the actual PUT implementation ... - $options["content_language"] = $value; - break; - - case 'HTTP_CONTENT_LOCATION': // RFC 2616 14.14 - /* The meaning of the Content-Location header in PUT - or POST requests is undefined; servers are free - to ignore it in those cases. */ - break; - - case 'HTTP_CONTENT_RANGE': // RFC 2616 14.16 - // single byte range requests are supported - // the header format is also specified in RFC 2616 14.16 - // TODO we have to ensure that implementations support this or send 501 instead - if (!preg_match('@bytes\s+(\d+)-(\d+)/((\d+)|\*)@', $val, $matches)) { - $this->http_status("400 bad request"); - echo "The service does only support single byte ranges"; - return; - } - - $range = array("start"=>$matches[1], "end"=>$matches[2]); - if (is_numeric($matches[3])) { - $range["total_length"] = $matches[3]; - } - $option["ranges"][] = $range; - - // TODO make sure the implementation supports partial PUT - // this has to be done in advance to avoid data being overwritten - // on implementations that do not support this ... - break; - - case 'HTTP_CONTENT_MD5': // RFC 2616 14.15 - // TODO: maybe we can just pretend here? - $this->http_status("501 not implemented"); - echo "The service does not support content MD5 checksum verification"; - return; - - default: - // any other unknown Content-* headers - $this->http_status("501 not implemented"); - - 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(); - $key = $filter->xssFilterHard($key); - - echo 'The service does not support \''.$key.'\' '; - return; - } - } - - - $options["stream"] = fopen("php://input", "r"); - - $stat = $this->PUT($options); - - if ($stat === false) { - $stat = "403 Forbidden"; - } -/* - else if (is_resource($stat) && get_resource_type($stat) == "stream") { - $stream = $stat; - - $stat = $options["new"] ? "201 Created" : "204 No Content"; - if (!empty($options["ranges"])) { - // TODO multipart support is missing (see also above) - if (0 == fseek($stream, $range[0]["start"], SEEK_SET)) { - $length = $range[0]["end"]-$range[0]["start"]+1; - if (!fwrite($stream, fread($options["stream"], $length))) { - $stat = "403 Forbidden"; - } - } else { - $stat = "403 Forbidden"; - } - } else { - while (!feof($options["stream"])) { - if (false === fwrite($stream, fread($options["stream"], 4096))) { - $stat = "403 Forbidden"; - break; - } - } - } - - fclose($stream); - - } -*/ - $this->http_status($stat); - } else { - $this->http_status("423 Locked"); - } - } - - // }}} - - - // {{{ http_DELETE() - - /** - * DELETE method handler - * - * @param void - * @return void - */ - function http_DELETE() - { - // check RFC 2518 Section 9.2, last paragraph - if (isset($_SERVER["HTTP_DEPTH"])) { - if ($_SERVER["HTTP_DEPTH"] != "infinity") { - $this->http_status("400 Bad Request"); - return; - } - } - - // check lock status - if ($this->_check_lock_status($this->path)) { - // ok, proceed - $options = Array(); - $options["path"] = $this->path; - - $stat = $this->DELETE($options); - - $this->http_status($stat); - } else { - // sorry, its locked - $this->http_status("423 Locked"); - } - } - - // }}} - - // {{{ http_COPY() - - /** - * COPY method handler - * - * @param void - * @return void - */ - function http_COPY() - { - // no need to check source lock status here - // destination lock status is always checked by the helper method - $this->_copymove("copy"); - } - - // }}} - - // {{{ http_MOVE() - - /** - * MOVE method handler - * - * @param void - * @return void - */ - function http_MOVE() - { - if ($this->_check_lock_status($this->path)) { - // destination lock status is always checked by the helper method - $this->_copymove("move"); - } else { - $this->http_status("423 Locked"); - } - } - - // }}} - - - // {{{ http_LOCK() - - /** - * LOCK method handler - * - * @param void - * @return void - */ - function http_LOCK() - { - $options = Array(); - $options["path"] = $this->path; - - if (isset($_SERVER['HTTP_DEPTH'])) { - $options["depth"] = $_SERVER["HTTP_DEPTH"]; - } else { - $options["depth"] = "infinity"; - } - - if (isset($_SERVER["HTTP_TIMEOUT"])) { - $options["timeout"] = explode(",", $_SERVER["HTTP_TIMEOUT"]); - } - - if(empty($_SERVER['CONTENT_LENGTH']) && !empty($_SERVER['HTTP_IF'])) { - // check if locking is possible - if(!$this->_check_lock_status($this->path)) { - $this->http_status("423 Locked"); - return; - } - - // refresh lock - $options["update"] = substr($_SERVER['HTTP_IF'], 2, -2); - $stat = $this->LOCK($options); - } else { - // extract lock request information from request XML payload - $lockinfo = new _parse_lockinfo("php://input"); - if (!$lockinfo->success) { - $this->http_status("400 bad request"); - } - - // check if locking is possible - if(!$this->_check_lock_status($this->path, $lockinfo->lockscope === "shared")) { - $this->http_status("423 Locked"); - return; - } - - // new lock - $options["scope"] = $lockinfo->lockscope; - $options["type"] = $lockinfo->locktype; - $options["owner"] = $lockinfo->owner; - - $options["locktoken"] = $this->_new_locktoken(); - - $stat = $this->LOCK($options); - } - - if(is_bool($stat)) { - $http_stat = $stat ? "200 OK" : "423 Locked"; - } else { - $http_stat = $stat; - } - - $this->http_status($http_stat); - - if ($http_stat{0} == 2) { // 2xx states are ok - if($options["timeout"]) { - // more than a million is considered an absolute timestamp - // less is more likely a relative value - if($options["timeout"]>1000000) { - $timeout = "Second-".($options['timeout']-time()); - } else { - $timeout = "Second-$options[timeout]"; - } - } else { - $timeout = "Infinite"; - } - - 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(); - $options = $filter->xssFilterHard($options); - $timeout = $filter->xssFilterHard($timeout); - - header('Content-Type: text/xml; charset="utf-8"'); - header("Lock-Token: <$options[locktoken]>"); - echo "\n"; - echo "\n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " \n"; - echo " $options[depth]\n"; - echo " $options[owner]\n"; - echo " $timeout\n"; - echo " $options[locktoken]\n"; - echo " \n"; - echo " \n"; - echo "\n\n"; - } - } - - - // }}} - - // {{{ http_UNLOCK() - - /** - * UNLOCK method handler - * - * @param void - * @return void - */ - function http_UNLOCK() - { - $options = Array(); - $options["path"] = $this->path; - - if (isset($_SERVER['HTTP_DEPTH'])) { - $options["depth"] = $_SERVER["HTTP_DEPTH"]; - } else { - $options["depth"] = "infinity"; - } - - // strip surrounding <> - $options["token"] = substr(trim($_SERVER["HTTP_LOCK_TOKEN"]), 1, -1); - - // call user method - $stat = $this->UNLOCK($options); - - $this->http_status($stat); - } - - // }}} - - // }}} - - // {{{ _copymove() - - function _copymove($what) - { - $options = Array(); - $options["path"] = $this->path; - - if (isset($_SERVER["HTTP_DEPTH"])) { - $options["depth"] = $_SERVER["HTTP_DEPTH"]; - } else { - $options["depth"] = "infinity"; - } - - extract(parse_url($_SERVER["HTTP_DESTINATION"])); - $path = urldecode($path); - $http_host = $host; - if (isset($port) && $port != 80) - $http_host.= ":$port"; - - $http_header_host = preg_replace("/:80$/", "", $_SERVER["HTTP_HOST"]); - - if ($http_host == $http_header_host && - !strncmp($_SERVER["SCRIPT_NAME"], $path, - strlen($_SERVER["SCRIPT_NAME"]))) { - $options["dest"] = substr($path, strlen($_SERVER["SCRIPT_NAME"])); - if (!$this->_check_lock_status($options["dest"])) { - $this->http_status("423 Locked"); - return; - } - - } else { - $options["dest_url"] = $_SERVER["HTTP_DESTINATION"]; - } - - // see RFC 2518 Sections 9.6, 8.8.4 and 8.9.3 - if (isset($_SERVER["HTTP_OVERWRITE"])) { - $options["overwrite"] = $_SERVER["HTTP_OVERWRITE"] == "T"; - } else { - $options["overwrite"] = true; - } - - $stat = $this->$what($options); - $this->http_status($stat); - } - - // }}} - - // {{{ _allow() - - /** - * check for implemented HTTP methods - * - * @param void - * @return array something - */ - function _allow() - { - // OPTIONS is always there - $allow = array("OPTIONS" =>"OPTIONS"); - - // all other METHODS need both a http_method() wrapper - // and a method() implementation - // the base class supplies wrappers only - foreach(get_class_methods($this) as $method) { - if (!strncmp("http_", $method, 5)) { - $method = strtoupper(substr($method, 5)); - if (method_exists($this, $method)) { - $allow[$method] = $method; - } - } - } - - // we can emulate a missing HEAD implemetation using GET - if (isset($allow["GET"])) - $allow["HEAD"] = "HEAD"; - - // no LOCK without checklok() - if (!method_exists($this, "checklock")) { - unset($allow["LOCK"]); - unset($allow["UNLOCK"]); - } - - return $allow; - } - - // }}} - - /** - * helper for property element creation - * - * @param string XML namespace (optional) - * @param string property name - * @param string property value - * @return array property array - */ - function mkprop() - { - $args = func_get_args(); - if (count($args) == 3) { - return array("ns" => $args[0], - "name" => $args[1], - "val" => $args[2]); - } else { - return array("ns" => "DAV:", - "name" => $args[0], - "val" => $args[1]); - } - } - - // {{{ _check_auth - - /** - * check authentication if check is implemented - * - * @param void - * @return bool true if authentication succeded or not necessary - */ - function _check_auth() - { - if (method_exists($this, "checkAuth")) { - // PEAR style method name - return $this->checkAuth(@$_SERVER["AUTH_TYPE"], - @$_SERVER["PHP_AUTH_USER"], - @$_SERVER["PHP_AUTH_PW"]); - } else if (method_exists($this, "check_auth")) { - // old (pre 1.0) method name - return $this->check_auth(@$_SERVER["AUTH_TYPE"], - @$_SERVER["PHP_AUTH_USER"], - @$_SERVER["PHP_AUTH_PW"]); - } else { - // no method found -> no authentication required - return true; - } - } - - // }}} - - // {{{ UUID stuff - - /** - * generate Unique Universal IDentifier for lock token - * - * @param void - * @return string a new UUID - */ - function _new_uuid() - { - // use uuid extension from PECL if available - if (function_exists("uuid_create")) { - return uuid_create(); - } - - // fallback - $uuid = $this->encryptOld(microtime().getmypid()); // this should be random enough for now - - // set variant and version fields for 'true' random uuid - $uuid{12} = "4"; - $n = 8 + (ord($uuid{16}) & 3); - $hex = "0123456789abcdef"; - $uuid{16} = $hex{$n}; - - // return formated uuid - return substr($uuid, 0, 8)."-" - . substr($uuid, 8, 4)."-" - . substr($uuid, 12, 4)."-" - . substr($uuid, 16, 4)."-" - . substr($uuid, 20); - } - - /** - * create a new opaque lock token as defined in RFC2518 - * - * @param void - * @return string new RFC2518 opaque lock token - */ - function _new_locktoken() - { - return "opaquelocktoken:".$this->_new_uuid(); - } - - // }}} - - // {{{ WebDAV If: header parsing - - /** - * - * - * @param string header string to parse - * @param int current parsing position - * @return array next token (type and value) - */ - function _if_header_lexer($string, &$pos) - { - // skip whitespace - while (ctype_space($string{$pos})) { - ++$pos; - } - - // already at end of string? - if (strlen($string) <= $pos) { - return false; - } - - // get next character - $c = $string{$pos++}; - - // now it depends on what we found - switch ($c) { - case "<": - // URIs are enclosed in <...> - $pos2 = strpos($string, ">", $pos); - $uri = substr($string, $pos, $pos2 - $pos); - $pos = $pos2 + 1; - return array("URI", $uri); - - case "[": - //Etags are enclosed in [...] - if ($string{$pos} == "W") { - $type = "ETAG_WEAK"; - $pos += 2; - } else { - $type = "ETAG_STRONG"; - } - $pos2 = strpos($string, "]", $pos); - $etag = substr($string, $pos + 1, $pos2 - $pos - 2); - $pos = $pos2 + 1; - return array($type, $etag); - - case "N": - // "N" indicates negation - $pos += 2; - return array("NOT", "Not"); - - default: - // anything else is passed verbatim char by char - return array("CHAR", $c); - } - } - - /** - * parse If: header - * - * @param string header string - * @return array URIs and their conditions - */ - function _if_header_parser($str) - { - $pos = 0; - $len = strlen($str); - - $uris = array(); - - // parser loop - while ($pos < $len) { - // get next token - $token = $this->_if_header_lexer($str, $pos); - - // check for URI - if ($token[0] == "URI") { - $uri = $token[1]; // remember URI - $token = $this->_if_header_lexer($str, $pos); // get next token - } else { - $uri = ""; - } - - // sanity check - if ($token[0] != "CHAR" || $token[1] != "(") { - return false; - } - - $list = array(); - $level = 1; - $not = ""; - while ($level) { - $token = $this->_if_header_lexer($str, $pos); - if ($token[0] == "NOT") { - $not = "!"; - continue; - } - switch ($token[0]) { - case "CHAR": - switch ($token[1]) { - case "(": - $level++; - break; - case ")": - $level--; - break; - default: - return false; - } - break; - - case "URI": - $list[] = $not."<$token[1]>"; - break; - - case "ETAG_WEAK": - $list[] = $not."[W/'$token[1]']>"; - break; - - case "ETAG_STRONG": - $list[] = $not."['$token[1]']>"; - break; - - default: - return false; - } - $not = ""; - } - - if (@is_array($uris[$uri])) { - $uris[$uri] = array_merge($uris[$uri],$list); - } else { - $uris[$uri] = $list; - } - } - - return $uris; - } - - /** - * check if conditions from "If:" headers are meat - * - * the "If:" header is an extension to HTTP/1.1 - * defined in RFC 2518 section 9.4 - * - * @param void - * @return void - */ - function _check_if_header_conditions() - { - if (isset($_SERVER["HTTP_IF"])) { - $this->_if_header_uris = - $this->_if_header_parser($_SERVER["HTTP_IF"]); - - foreach($this->_if_header_uris as $uri => $conditions) { - if ($uri == "") { - $uri = $this->uri; - } - // all must match - $state = true; - foreach($conditions as $condition) { - // lock tokens may be free form (RFC2518 6.3) - // but if opaquelocktokens are used (RFC2518 6.4) - // we have to check the format (litmus tests this) - if (!strncmp($condition, "$/', $condition)) { - $this->http_status("423 Locked"); - return false; - } - } - if (!$this->_check_uri_condition($uri, $condition)) { - $this->http_status("412 Precondition failed"); - $state = false; - break; - } - } - - // any match is ok - if ($state == true) { - return true; - } - } - return false; - } - return true; - } - - /** - * Check a single URI condition parsed from an if-header - * - * Check a single URI condition parsed from an if-header - * - * @abstract - * @param string $uri URI to check - * @param string $condition Condition to check for this URI - * @returns bool Condition check result - */ - function _check_uri_condition($uri, $condition) - { - // not really implemented here, - // implementations must override - return true; - } - - - /** - * - * - * @param string path of resource to check - * @param bool exclusive lock? - */ - function _check_lock_status($path, $exclusive_only = false) - { - // FIXME depth -> ignored for now - if (method_exists($this, "checkLock")) { - // is locked? - $lock = $this->checkLock($path); - - // ... and lock is not owned? - if (is_array($lock) && count($lock)) { - // FIXME doesn't check uri restrictions yet - if (!isset($_SERVER["HTTP_IF"]) || !strstr($_SERVER["HTTP_IF"], $lock["token"])) { - if (!$exclusive_only || ($lock["scope"] !== "shared")) - return false; - } - } - } - return true; - } - - - // }}} - - - /** - * Generate lockdiscovery reply from checklock() result - * - * @param string resource path to check - * @return string lockdiscovery response - */ - function lockdiscovery($path) - { - // no lock support without checklock() method - if (!method_exists($this, "checklock")) { - return ""; - } - - // collect response here - $activelocks = ""; - - // get checklock() reply - $lock = $this->checklock($path); - - // generate block for returned data - if (is_array($lock) && count($lock)) { - // check for 'timeout' or 'expires' - if (!empty($lock["expires"])) { - $timeout = "Second-".($lock["expires"] - time()); - } else if (!empty($lock["timeout"])) { - $timeout = "Second-$lock[timeout]"; - } else { - $timeout = "Infinite"; - } - - // genreate response block - $activelocks.= " - - - - $lock[depth] - $lock[owner] - $timeout - $lock[token] - - "; - } - - // return generated response - return $activelocks; - } - - /** - * set HTTP return status and mirror it in a private header - * - * @param string status code and message - * @return void - */ - function http_status($status) - { - // simplified success case - if($status === true) { - $status = "200 OK"; - } - - // remember status - $this->_http_status = $status; - - // generate HTTP status response - header("HTTP/1.1 $status"); - header("X-WebDAV-Status: $status", true); - } - - /** - * private minimalistic version of PHP urlencode() - * - * only blanks and XML special chars must be encoded here - * full urlencode() encoding confuses some clients ... - * - * @param string URL to encode - * @return string encoded URL - */ - function _urlencode($url) - { - return strtr($url, array(" "=>"%20", - "&"=>"%26", - "<"=>"%3C", - ">"=>"%3E", - )); - } - - /** - * private version of PHP urldecode - * - * not really needed but added for completenes - * - * @param string URL to decode - * @return string decoded URL - */ - function _urldecode($path) - { - return urldecode($path); - } - - /** - * UTF-8 encode property values if not already done so - * - * @param string text to encode - * @return string utf-8 encoded text - */ - function _prop_encode($text) - { - switch (strtolower($this->_prop_encoding)) { - case "utf-8": - return $text; - case "iso-8859-1": - case "iso-8859-15": - case "latin-1": - default: - return utf8_encode($text); - } - } - - /** - * Slashify - make sure path ends in a slash - * - * @param string directory path - * @returns string directory path wiht trailing slash - */ - function _slashify($path) { - if ($path[strlen($path)-1] != '/') { - $path = $path."/"; - } - return $path; - } - - /** - * Unslashify - make sure path doesn't in a slash - * - * @param string directory path - * @returns string directory path wihtout trailing slash - */ - function _unslashify($path) { - if ($path[strlen($path)-1] == '/') { - $path = substr($path, 0, strlen($path, 0, -1)); - } - return $path; - } - - /** - * Merge two pathes, make sure there is exactly one slash between them - * - * @param string parent path - * @param string child path - * @return string merged path - */ - function _mergePathes($parent, $child) - { - if ($child{0} == '/') { - return $this->_unslashify($parent).$child; - } else { - return $this->_slashify($parent).$child; - } - } - - 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); - } -} diff --git a/gulliver/thirdparty/pear/HTTP/WebDAV/Server/Filesystem.php b/gulliver/thirdparty/pear/HTTP/WebDAV/Server/Filesystem.php deleted file mode 100644 index bc8d5e146..000000000 --- a/gulliver/thirdparty/pear/HTTP/WebDAV/Server/Filesystem.php +++ /dev/null @@ -1,721 +0,0 @@ - $value) { - if (stristr($key,"litmus")) { - error_log("Litmus test $value"); - header("X-Litmus-reply: ".$value); - } - } - } - - // set root directory, defaults to webserver document root if not set - if ($base) { - $this->base = realpath($base); // TODO throw if not a directory - } else if (!$this->base) { - $this->base = $_SERVER['DOCUMENT_ROOT']; - } - - // establish connection to property/locking db - //mysql_connect($this->db_host, $this->db_user, $this->db_passwd) or die(mysql_error()); - //mysql_select_db($this->db_name) or die(mysql_error()); - // TODO throw on connection problems - - // let the base class do all the work - parent::ServeRequest(); - } - - /** - * No authentication is needed here - * - * @access private - * @param string HTTP Authentication type (Basic, Digest, ...) - * @param string Username - * @param string Password - * @return bool true on successful authentication - */ - function check_auth($type, $user, $pass) - { - return true; - } - - - /** - * PROPFIND method handler - * - * @param array general parameter passing array - * @param array return array for file properties - * @return bool true on success - */ - function PROPFIND(&$options, &$files) - { - // get absolute fs path to requested resource - $fspath = $this->base . $options["path"]; - - // sanity check - if (!file_exists($fspath)) { - return false; - } - - // prepare property array - $files["files"] = array(); - - // store information for the requested path itself - $files["files"][] = $this->fileinfo($options["path"]); - - // information for contained resources requested? - if (!empty($options["depth"])) { // TODO check for is_dir() first? - - // make sure path ends with '/' - $options["path"] = $this->_slashify($options["path"]); - - // try to open directory - $handle = @opendir($fspath); - - if ($handle) { - // ok, now get all its contents - while ($filename = readdir($handle)) { - if ($filename != "." && $filename != "..") { - $files["files"][] = $this->fileinfo($options["path"].$filename); - } - } - // TODO recursion needed if "Depth: infinite" - } - } - - // ok, all done - return true; - } - - /** - * Get properties for a single file/resource - * - * @param string resource path - * @return array resource properties - */ - function fileinfo($path) - { - // map URI path to filesystem path - $fspath = $this->base . $path; - - // create result array - $info = array(); - // TODO remove slash append code when base clase is able to do it itself - $info["path"] = is_dir($fspath) ? $this->_slashify($path) : $path; - $info["props"] = array(); - - // no special beautified displayname here ... - $info["props"][] = $this->mkprop("displayname", strtoupper($path)); - - // creation and modification time - $info["props"][] = $this->mkprop("creationdate", filectime($fspath)); - $info["props"][] = $this->mkprop("getlastmodified", filemtime($fspath)); - - // type and size (caller already made sure that path exists) - if (is_dir($fspath)) { - // directory (WebDAV collection) - $info["props"][] = $this->mkprop("resourcetype", "collection"); - $info["props"][] = $this->mkprop("getcontenttype", "httpd/unix-directory"); - } else { - // plain file (WebDAV resource) - $info["props"][] = $this->mkprop("resourcetype", ""); - if (is_readable($fspath)) { - $info["props"][] = $this->mkprop("getcontenttype", $this->_mimetype($fspath)); - } else { - $info["props"][] = $this->mkprop("getcontenttype", "application/x-non-readable"); - } - $info["props"][] = $this->mkprop("getcontentlength", filesize($fspath)); - } - - // get additional properties from database - $query = "SELECT ns, name, value FROM properties WHERE path = '$path'"; - $res = mysql_query($query); - while ($row = mysql_fetch_assoc($res)) { - $info["props"][] = $this->mkprop($row["ns"], $row["name"], $row["value"]); - } - mysql_free_result($res); - - return $info; - } - - /** - * detect if a given program is found in the search PATH - * - * helper function used by _mimetype() to detect if the - * external 'file' utility is available - * - * @param string program name - * @param string optional search path, defaults to $PATH - * @return bool true if executable program found in path - */ - function _can_execute($name, $path = false) - { - // path defaults to PATH from environment if not set - if ($path === false) { - $path = getenv("PATH"); - } - - // check method depends on operating system - if (!strncmp(PHP_OS, "WIN", 3)) { - // on Windows an appropriate COM or EXE file needs to exist - $exts = array(".exe", ".com"); - $check_fn = "file_exists"; - } else { - // anywhere else we look for an executable file of that name - $exts = array(""); - $check_fn = "is_executable"; - } - - // now check the directories in the path for the program - foreach (explode(PATH_SEPARATOR, $path) as $dir) { - // skip invalid path entries - if (!file_exists($dir)) continue; - if (!is_dir($dir)) continue; - - // and now look for the file - foreach ($exts as $ext) { - if ($check_fn("$dir/$name".$ext)) return true; - } - } - - return false; - } - - - /** - * try to detect the mime type of a file - * - * @param string file path - * @return string guessed mime type - */ - function _mimetype($fspath) - { - if (@is_dir($fspath)) { - // directories are easy - return "httpd/unix-directory"; - } else if (function_exists("mime_content_type")) { - // use mime magic extension if available - $mime_type = mime_content_type($fspath); - } else if ($this->_can_execute("file")) { - // it looks like we have a 'file' command, - // lets see it it does have mime support - $fp = popen("file -i '$fspath' 2>/dev/null", "r"); - $reply = fgets($fp); - pclose($fp); - - // popen will not return an error if the binary was not found - // and find may not have mime support using "-i" - // so we test the format of the returned string - - // the reply begins with the requested filename - if (!strncmp($reply, "$fspath: ", strlen($fspath)+2)) { - $reply = substr($reply, strlen($fspath)+2); - // followed by the mime type (maybe including options) - if (preg_match('/^[[:alnum:]_-]+/[[:alnum:]_-]+;?.*/', $reply, $matches)) { - $mime_type = $matches[0]; - } - } - } - - if (empty($mime_type)) { - // Fallback solution: try to guess the type by the file extension - // TODO: add more ... - // TODO: it has been suggested to delegate mimetype detection - // to apache but this has at least three issues: - // - works only with apache - // - needs file to be within the document tree - // - requires apache mod_magic - // TODO: can we use the registry for this on Windows? - // OTOH if the server is Windos the clients are likely to - // be Windows, too, and tend do ignore the Content-Type - // anyway (overriding it with information taken from - // the registry) - // TODO: have a seperate PEAR class for mimetype detection? - switch (strtolower(strrchr(basename($fspath), "."))) { - case ".html": - $mime_type = "text/html"; - break; - case ".gif": - $mime_type = "image/gif"; - break; - case ".jpg": - $mime_type = "image/jpeg"; - break; - default: - $mime_type = "application/octet-stream"; - break; - } - } - - return $mime_type; - } - - /** - * GET method handler - * - * @param array parameter passing array - * @return bool true on success - */ - function GET(&$options) - { - // get absolute fs path to requested resource - $fspath = $this->base . $options["path"]; - - // sanity check - if (!file_exists($fspath)) return false; - - // is this a collection? - if (is_dir($fspath)) { - return $this->GetDir($fspath, $options); - } - - // detect resource type - $options['mimetype'] = $this->_mimetype($fspath); - - // detect modification time - // see rfc2518, section 13.7 - // some clients seem to treat this as a reverse rule - // requiering a Last-Modified header if the getlastmodified header was set - $options['mtime'] = filemtime($fspath); - - // detect resource size - $options['size'] = filesize($fspath); - - // no need to check result here, it is handled by the base class - $options['stream'] = fopen($fspath, "r"); - - return true; - } - - /** - * GET method handler for directories - * - * This is a very simple mod_index lookalike. - * See RFC 2518, Section 8.4 on GET/HEAD for collections - * - * @param string directory path - * @return void function has to handle HTTP response itself - */ - function GetDir($fspath, &$options) - { - $path = $this->_slashify($options["path"]); - if ($path != $options["path"]) { - header("Location: ".$this->base_uri.$path); - exit; - } - - // fixed width directory column format - $format = "%15s %-19s %-s\n"; - - $handle = @opendir($fspath); - if (!$handle) { - return false; - } - - echo "Index of ".htmlspecialchars($options['path'])."\n"; - - echo "

Index of ".htmlspecialchars($options['path'])."

\n"; - - echo "
";
-            printf($format, "Size", "Last modified", "Filename");
-            echo "
"; - - while ($filename = readdir($handle)) { - if ($filename != "." && $filename != "..") { - $fullpath = $fspath."/".$filename; - $name = htmlspecialchars($filename); - printf($format, - number_format(filesize($fullpath)), - strftime("%Y-%m-%d %H:%M:%S", filemtime($fullpath)), - "$name"); - } - } - - echo "
"; - - closedir($handle); - - echo "\n"; - - exit; - } - - /** - * PUT method handler - * - * @param array parameter passing array - * @return bool true on success - */ - function PUT(&$options) - { - $fspath = $this->base . $options["path"]; - - if (!@is_dir(dirname($fspath))) { - return "409 Conflict"; - } - - $options["new"] = ! file_exists($fspath); - - $fp = fopen($fspath, "w"); - - return $fp; - } - - - /** - * MKCOL method handler - * - * @param array general parameter passing array - * @return bool true on success - */ - function MKCOL($options) - { - $path = $this->base .$options["path"]; - $parent = dirname($path); - $name = basename($path); - - if (!file_exists($parent)) { - return "409 Conflict"; - } - - if (!is_dir($parent)) { - return "403 Forbidden"; - } - - if ( file_exists($parent."/".$name) ) { - return "405 Method not allowed"; - } - - if (!empty($_SERVER["CONTENT_LENGTH"])) { // no body parsing yet - return "415 Unsupported media type"; - } - - $stat = mkdir ($parent."/".$name,0777); - if (!$stat) { - return "403 Forbidden"; - } - - return ("201 Created"); - } - - - /** - * DELETE method handler - * - * @param array general parameter passing array - * @return bool true on success - */ - function DELETE($options) - { - $path = $this->base . "/" .$options["path"]; - - if (!file_exists($path)) { - return "404 Not found"; - } - - if (is_dir($path)) { - $query = "DELETE FROM properties WHERE path LIKE '".$this->_slashify($options["path"])."%'"; - mysql_query($query); - System::rm("-rf $path"); - } else { - unlink ($path); - } - $query = "DELETE FROM properties WHERE path = '$options[path]'"; - mysql_query($query); - - return "204 No Content"; - } - - - /** - * MOVE method handler - * - * @param array general parameter passing array - * @return bool true on success - */ - function MOVE($options) - { - return $this->COPY($options, true); - } - - /** - * COPY method handler - * - * @param array general parameter passing array - * @return bool true on success - */ - function COPY($options, $del=false) - { - // TODO Property updates still broken (Litmus should detect this?) - - if (!empty($_SERVER["CONTENT_LENGTH"])) { // no body parsing yet - return "415 Unsupported media type"; - } - - // no copying to different WebDAV Servers yet - if (isset($options["dest_url"])) { - return "502 bad gateway"; - } - - $source = $this->base .$options["path"]; - if (!file_exists($source)) return "404 Not found"; - - $dest = $this->base . $options["dest"]; - - $new = !file_exists($dest); - $existing_col = false; - - if (!$new) { - if ($del && is_dir($dest)) { - if (!$options["overwrite"]) { - return "412 precondition failed"; - } - $dest .= basename($source); - if (file_exists($dest)) { - $options["dest"] .= basename($source); - } else { - $new = true; - $existing_col = true; - } - } - } - - if (!$new) { - if ($options["overwrite"]) { - $stat = $this->DELETE(array("path" => $options["dest"])); - if (($stat{0} != "2") && (substr($stat, 0, 3) != "404")) { - return $stat; - } - } else { - return "412 precondition failed"; - } - } - - if (is_dir($source) && ($options["depth"] != "infinity")) { - // RFC 2518 Section 9.2, last paragraph - return "400 Bad request"; - } - - if ($del) { - if (!rename($source, $dest)) { - return "500 Internal server error"; - } - $destpath = $this->_unslashify($options["dest"]); - if (is_dir($source)) { - $query = "UPDATE properties - SET path = REPLACE(path, '".$options["path"]."', '".$destpath."') - WHERE path LIKE '".$this->_slashify($options["path"])."%'"; - mysql_query($query); - } - - $query = "UPDATE properties - SET path = '".$destpath."' - WHERE path = '".$options["path"]."'"; - mysql_query($query); - } else { - if (is_dir($source)) { - $files = System::find($source); - $files = array_reverse($files); - } else { - $files = array($source); - } - - if (!is_array($files) || empty($files)) { - return "500 Internal server error"; - } - - - foreach ($files as $file) { - if (is_dir($file)) { - $file = $this->_slashify($file); - } - - $destfile = str_replace($source, $dest, $file); - - if (is_dir($file)) { - if (!is_dir($destfile)) { - // TODO "mkdir -p" here? (only natively supported by PHP 5) - if (!mkdir($destfile)) { - return "409 Conflict"; - } - } else { - error_log("existing dir '$destfile'"); - } - } else { - if (!copy($file, $destfile)) { - return "409 Conflict"; - } - } - } - - $query = "INSERT INTO properties SELECT ... FROM properties WHERE path = '".$options['path']."'"; - } - - return ($new && !$existing_col) ? "201 Created" : "204 No Content"; - } - - - /** - * LOCK method handler - * - * @param array general parameter passing array - * @return bool true on success - */ - function LOCK(&$options) - { - if (isset($options["update"])) { // Lock Update - $query = "UPDATE locks SET expires = ".(time()+300); - mysql_query($query); - - if (mysql_affected_rows()) { - $options["timeout"] = 300; // 5min hardcoded - return true; - } else { - return false; - } - } - - $options["timeout"] = time()+300; // 5min. hardcoded - - $query = "INSERT INTO locks - SET token = '$options[locktoken]' - , path = '$options[path]' - , owner = '$options[owner]' - , expires = '$options[timeout]' - , exclusivelock = " .($options['scope'] === "exclusive" ? "1" : "0") - ; - mysql_query($query); - - return mysql_affected_rows() ? "200 OK" : "409 Conflict"; - } - - /** - * UNLOCK method handler - * - * @param array general parameter passing array - * @return bool true on success - */ - function UNLOCK(&$options) - { - $query = "DELETE FROM locks - WHERE path = '$options[path]' - AND token = '$options[token]'"; - mysql_query($query); - - return mysql_affected_rows() ? "204 No Content" : "409 Conflict"; - } - - /** - * checkLock() helper - * - * @param string resource path to check for locks - * @return bool true on success - */ - function checkLock($path) - { - $result = false; - - $query = "SELECT owner, token, expires, exclusivelock - FROM locks - WHERE path = '$path' - "; - $res = mysql_query($query); - - if ($res) { - $row = mysql_fetch_array($res); - mysql_free_result($res); - - if ($row) { - $result = array( "type" => "write", - "scope" => $row["exclusivelock"] ? "exclusive" : "shared", - "depth" => 0, - "owner" => $row['owner'], - "token" => $row['token'], - "expires" => $row['expires'] - ); - } - } - - return $result; - } - - - /** - * create database tables for property and lock storage - * - * @param void - * @return bool true on success - */ - function create_database() - { - // TODO - return false; - } - - } - - -?> diff --git a/gulliver/thirdparty/pear/HTTP/WebDAV/Tools/_parse_lockinfo.php b/gulliver/thirdparty/pear/HTTP/WebDAV/Tools/_parse_lockinfo.php deleted file mode 100644 index 3b32e2ff6..000000000 --- a/gulliver/thirdparty/pear/HTTP/WebDAV/Tools/_parse_lockinfo.php +++ /dev/null @@ -1,237 +0,0 @@ - | -// | Christian Stocker | -// +----------------------------------------------------------------------+ -// -// $Id: _parse_lockinfo.php,v 1.2 2004/01/05 12:32:40 hholzgra Exp $ -// - -/** - * helper class for parsing LOCK request bodies - * - * @package HTTP_WebDAV_Server - * @author Hartmut Holzgraefe - * @version 0.99.1dev - */ -class _parse_lockinfo -{ - /** - * success state flag - * - * @var bool - * @access public - */ - var $success = false; - - /** - * lock type, currently only "write" - * - * @var string - * @access public - */ - var $locktype = ""; - - /** - * lock scope, "shared" or "exclusive" - * - * @var string - * @access public - */ - var $lockscope = ""; - - /** - * lock owner information - * - * @var string - * @access public - */ - var $owner = ""; - - /** - * flag that is set during lock owner read - * - * @var bool - * @access private - */ - var $collect_owner = false; - - /** - * constructor - * - * @param string path of stream to read - * @access public - */ - function _parse_lockinfo($path) - { - // we assume success unless problems occur - $this->success = true; - - // remember if any input was parsed - $had_input = false; - - // open stream - $f_in = fopen($path, "r"); - if (!$f_in) { - $this->success = false; - return; - } - - // create namespace aware parser - $xml_parser = xml_parser_create_ns("UTF-8", " "); - - // set tag and data handlers - xml_set_element_handler($xml_parser, - array(&$this, "_startElement"), - array(&$this, "_endElement")); - xml_set_character_data_handler($xml_parser, - array(&$this, "_data")); - - // we want a case sensitive parser - xml_parser_set_option($xml_parser, - XML_OPTION_CASE_FOLDING, false); - - // parse input - while($this->success && !feof($f_in)) { - $line = fgets($f_in); - if (is_string($line)) { - $had_input = true; - $this->success &= xml_parse($xml_parser, $line, false); - } - } - - // finish parsing - if($had_input) { - $this->success &= xml_parse($xml_parser, "", true); - } - - // check if required tags where found - $this->success &= !empty($this->locktype); - $this->success &= !empty($this->lockscope); - - // free parser resource - xml_parser_free($xml_parser); - - // close input stream - fclose($f_in); - } - - - /** - * tag start handler - * - * @param resource parser - * @param string tag name - * @param array tag attributes - * @return void - * @access private - */ - function _startElement($parser, $name, $attrs) - { - // namespace handling - if (strstr($name, " ")) { - list($ns, $tag) = explode(" ", $name); - } else { - $ns = ""; - $tag = $name; - } - - - if ($this->collect_owner) { - // everything within the tag needs to be collected - $ns_short = ""; - $ns_attr = ""; - if ($ns) { - if ($ns == "DAV:") { - $ns_short = "D:"; - } else { - $ns_attr = " xmlns='$ns'"; - } - } - $this->owner .= "<$ns_short$tag$ns_attr>"; - } else if ($ns == "DAV:") { - // parse only the essential tags - switch ($tag) { - case "write": - $this->locktype = $tag; - break; - case "exclusive": - case "shared": - $this->lockscope = $tag; - break; - case "owner": - $this->collect_owner = true; - break; - } - } - } - - /** - * data handler - * - * @param resource parser - * @param string data - * @return void - * @access private - */ - function _data($parser, $data) - { - // only the tag has data content - if ($this->collect_owner) { - $this->owner .= $data; - } - } - - /** - * tag end handler - * - * @param resource parser - * @param string tag name - * @return void - * @access private - */ - function _endElement($parser, $name) - { - // namespace handling - if (strstr($name, " ")) { - list($ns, $tag) = explode(" ", $name); - } else { - $ns = ""; - $tag = $name; - } - - // finished? - if (($ns == "DAV:") && ($tag == "owner")) { - $this->collect_owner = false; - } - - // within we have to collect everything - if ($this->collect_owner) { - $ns_short = ""; - $ns_attr = ""; - if ($ns) { - if ($ns == "DAV:") { - $ns_short = "D:"; - } else { - $ns_attr = " xmlns='$ns'"; - } - } - $this->owner .= ""; - } - } -} - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/HTTP/WebDAV/Tools/_parse_propfind.php b/gulliver/thirdparty/pear/HTTP/WebDAV/Tools/_parse_propfind.php deleted file mode 100644 index 15234cb15..000000000 --- a/gulliver/thirdparty/pear/HTTP/WebDAV/Tools/_parse_propfind.php +++ /dev/null @@ -1,178 +0,0 @@ - | -// | Christian Stocker | -// +----------------------------------------------------------------------+ -// -// $Id: _parse_propfind.php,v 1.2 2004/01/05 12:33:22 hholzgra Exp $ -// - -/** - * helper class for parsing PROPFIND request bodies - * - * @package HTTP_WebDAV_Server - * @author Hartmut Holzgraefe - * @version 0.99.1dev - */ -class _parse_propfind -{ - /** - * success state flag - * - * @var bool - * @access public - */ - var $success = false; - - /** - * found properties are collected here - * - * @var array - * @access public - */ - var $props = false; - - /** - * internal tag nesting depth counter - * - * @var int - * @access private - */ - var $depth = 0; - - - /** - * constructor - * - * @access public - */ - function _parse_propfind($path) - { - // success state flag - $this->success = true; - - // property storage array - $this->props = array(); - - // internal tag depth counter - $this->depth = 0; - - // remember if any input was parsed - $had_input = false; - - // open input stream - $f_in = fopen($path, "r"); - if (!$f_in) { - $this->success = false; - return; - } - - // create XML parser - $xml_parser = xml_parser_create_ns("UTF-8", " "); - - // set tag and data handlers - xml_set_element_handler($xml_parser, - array(&$this, "_startElement"), - array(&$this, "_endElement")); - - // we want a case sensitive parser - xml_parser_set_option($xml_parser, - XML_OPTION_CASE_FOLDING, false); - - - // parse input - while($this->success && !feof($f_in)) { - $line = fgets($f_in); - if (is_string($line)) { - $had_input = true; - $this->success &= xml_parse($xml_parser, $line, false); - } - } - - // finish parsing - if($had_input) { - $this->success &= xml_parse($xml_parser, "", true); - } - - // free parser - xml_parser_free($xml_parser); - - // close input stream - fclose($f_in); - - // if no input was parsed it was a request - if(!count($this->props)) $this->props = "all"; // default - } - - - /** - * start tag handler - * - * @access private - * @param resource parser - * @param string tag name - * @param array tag attributes - */ - function _startElement($parser, $name, $attrs) - { - // name space handling - if (strstr($name, " ")) { - list($ns, $tag) = explode(" ", $name); - if ($ns == "") - $this->success = false; - } else { - $ns = ""; - $tag = $name; - } - - // special tags at level 1: and - if ($this->depth == 1) { - if ($tag == "allprop") - $this->props = "all"; - - if ($tag == "propname") - $this->props = "names"; - } - - // requested properties are found at level 2 - if ($this->depth == 2) { - $prop = array("name" => $tag); - if ($ns) - $prop["xmlns"] = $ns; - $this->props[] = $prop; - } - - // increment depth count - $this->depth++; - } - - - /** - * end tag handler - * - * @access private - * @param resource parser - * @param string tag name - */ - function _endElement($parser, $name) - { - // here we only need to decrement the depth count - $this->depth--; - } -} - - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/HTTP/WebDAV/Tools/_parse_proppatch.php b/gulliver/thirdparty/pear/HTTP/WebDAV/Tools/_parse_proppatch.php deleted file mode 100644 index 9836ab228..000000000 --- a/gulliver/thirdparty/pear/HTTP/WebDAV/Tools/_parse_proppatch.php +++ /dev/null @@ -1,214 +0,0 @@ - | -// | Christian Stocker | -// +----------------------------------------------------------------------+ -// -// $Id: _parse_proppatch.php,v 1.3 2004/01/05 12:41:34 hholzgra Exp $ -// - -/** - * helper class for parsing PROPPATCH request bodies - * - * @package HTTP_WebDAV_Server - * @author Hartmut Holzgraefe - * @version 0.99.1dev - */ -class _parse_proppatch -{ - /** - * - * - * @var - * @access - */ - var $success; - - /** - * - * - * @var - * @access - */ - var $props; - - /** - * - * - * @var - * @access - */ - var $depth; - - /** - * - * - * @var - * @access - */ - var $mode; - - /** - * - * - * @var - * @access - */ - var $current; - - /** - * constructor - * - * @param string path of input stream - * @access public - */ - function _parse_proppatch($path) - { - $this->success = true; - - $this->depth = 0; - $this->props = array(); - $had_input = false; - - $f_in = fopen($path, "r"); - if (!$f_in) { - $this->success = false; - return; - } - - $xml_parser = xml_parser_create_ns("UTF-8", " "); - - xml_set_element_handler($xml_parser, - array(&$this, "_startElement"), - array(&$this, "_endElement")); - - xml_set_character_data_handler($xml_parser, - array(&$this, "_data")); - - xml_parser_set_option($xml_parser, - XML_OPTION_CASE_FOLDING, false); - - while($this->success && !feof($f_in)) { - $line = fgets($f_in); - if (is_string($line)) { - $had_input = true; - $this->success &= xml_parse($xml_parser, $line, false); - } - } - - if($had_input) { - $this->success &= xml_parse($xml_parser, "", true); - } - - xml_parser_free($xml_parser); - - fclose($f_in); - } - - /** - * tag start handler - * - * @param resource parser - * @param string tag name - * @param array tag attributes - * @return void - * @access private - */ - function _startElement($parser, $name, $attrs) - { - if (strstr($name, " ")) { - list($ns, $tag) = explode(" ", $name); - if ($ns == "") - $this->success = false; - } else { - $ns = ""; - $tag = $name; - } - - if ($this->depth == 1) { - $this->mode = $tag; - } - - if ($this->depth == 3) { - $prop = array("name" => $tag); - $this->current = array("name" => $tag, "ns" => $ns, "status"=> 200); - if ($this->mode == "set") { - $this->current["val"] = ""; // default set val - } - } - - if ($this->depth >= 4) { - $this->current["val"] .= "<$tag"; - foreach ($attr as $key => $val) { - $this->current["val"] .= ' '.$key.'="'.str_replace('"','"', $val).'"'; - } - $this->current["val"] .= ">"; - } - - - - $this->depth++; - } - - /** - * tag end handler - * - * @param resource parser - * @param string tag name - * @return void - * @access private - */ - function _endElement($parser, $name) - { - if (strstr($name, " ")) { - list($ns, $tag) = explode(" ", $name); - if ($ns == "") - $this->success = false; - } else { - $ns = ""; - $tag = $name; - } - - $this->depth--; - - if ($this->depth >= 4) { - $this->current["val"] .= ""; - } - - if ($this->depth == 3) { - if (isset($this->current)) { - $this->props[] = $this->current; - unset($this->current); - } - } - } - - /** - * input data handler - * - * @param resource parser - * @param string data - * @return void - * @access private - */ - function _data($parser, $data) { - if (isset($this->current)) { - $this->current["val"] .= $data; - } - } -} - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/Log.php b/gulliver/thirdparty/pear/Log.php deleted file mode 100644 index 0e21b5eff..000000000 --- a/gulliver/thirdparty/pear/Log.php +++ /dev/null @@ -1,832 +0,0 @@ - - * @author Jon Parise - * @since Horde 1.3 - * @package Log - */ -class Log -{ - /** - * Indicates whether or not the log can been opened / connected. - * - * @var boolean - * @access protected - */ - var $_opened = false; - - /** - * Instance-specific unique identification number. - * - * @var integer - * @access protected - */ - var $_id = 0; - - /** - * The label that uniquely identifies this set of log messages. - * - * @var string - * @access protected - */ - var $_ident = ''; - - /** - * The default priority to use when logging an event. - * - * @var integer - * @access protected - */ - var $_priority = PEAR_LOG_INFO; - - /** - * The bitmask of allowed log levels. - * - * @var integer - * @access protected - */ - var $_mask = PEAR_LOG_ALL; - - /** - * Holds all Log_observer objects that wish to be notified of new messages. - * - * @var array - * @access protected - */ - var $_listeners = array(); - - /** - * Maps canonical format keys to position arguments for use in building - * "line format" strings. - * - * @var array - * @access protected - */ - var $_formatMap = array('%{timestamp}' => '%1$s', - '%{ident}' => '%2$s', - '%{priority}' => '%3$s', - '%{message}' => '%4$s', - '%{file}' => '%5$s', - '%{line}' => '%6$s', - '%{function}' => '%7$s', - '%\{' => '%%{'); - - - /** - * Attempts to return a concrete Log instance of type $handler. - * - * @param string $handler The type of concrete Log subclass to return. - * Attempt to dynamically include the code for - * this subclass. Currently, valid values are - * 'console', 'syslog', 'sql', 'file', and 'mcal'. - * - * @param string $name The name of the actually log file, table, or - * other specific store to use. Defaults to an - * empty string, with which the subclass will - * attempt to do something intelligent. - * - * @param string $ident The identity reported to the log system. - * - * @param array $conf A hash containing any additional configuration - * information that a subclass might need. - * - * @param int $level Log messages up to and including this level. - * - * @return object Log The newly created concrete Log instance, or - * null on an error. - * @access public - * @since Log 1.0 - */ - function &factory($handler, $name = '', $ident = '', $conf = array(), - $level = PEAR_LOG_DEBUG) - { - $handler = strtolower($handler); - $class = 'Log_' . $handler; - $classfile = 'Log/' . $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. - */ - if (!class_exists($class, false)) { - include_once $classfile; - } - - /* If the class exists, return a new instance of it. */ - if (class_exists($class, false)) { - $obj = new $class($name, $ident, $conf, $level); - return $obj; - } - - $null = null; - return $null; - } - - /** - * Attempts to return a reference to a concrete Log instance of type - * $handler, only creating a new instance if no log instance with the same - * parameters currently exists. - * - * You should use this if there are multiple places you might create a - * logger, you don't want to create multiple loggers, and you don't want to - * check for the existance of one each time. The singleton pattern does all - * the checking work for you. - * - * You MUST call this method with the $var = &Log::singleton() syntax. - * Without the ampersand (&) in front of the method name, you will not get - * a reference, you will get a copy. - * - * @param string $handler The type of concrete Log subclass to return. - * Attempt to dynamically include the code for - * this subclass. Currently, valid values are - * 'console', 'syslog', 'sql', 'file', and 'mcal'. - * - * @param string $name The name of the actually log file, table, or - * other specific store to use. Defaults to an - * empty string, with which the subclass will - * attempt to do something intelligent. - * - * @param string $ident The identity reported to the log system. - * - * @param array $conf A hash containing any additional configuration - * information that a subclass might need. - * - * @param int $level Log messages up to and including this level. - * - * @return object Log The newly created concrete Log instance, or - * null on an error. - * @access public - * @since Log 1.0 - */ - function &singleton($handler, $name = '', $ident = '', $conf = array(), - $level = PEAR_LOG_DEBUG) - { - static $instances; - if (!isset($instances)) $instances = array(); - - $signature = serialize(array($handler, $name, $ident, $conf, $level)); - if (!isset($instances[$signature])) { - $instances[$signature] = &Log::factory($handler, $name, $ident, - $conf, $level); - } - - return $instances[$signature]; - } - - /** - * Abstract implementation of the open() method. - * @since Log 1.0 - */ - function open() - { - return false; - } - - /** - * Abstract implementation of the close() method. - * @since Log 1.0 - */ - function close() - { - return false; - } - - /** - * Abstract implementation of the flush() method. - * @since Log 1.8.2 - */ - function flush() - { - return false; - } - - /** - * Abstract implementation of the log() method. - * @since Log 1.0 - */ - function log($message, $priority = null) - { - return false; - } - - /** - * A convenience function for logging a emergency event. It will log a - * message at the PEAR_LOG_EMERG log level. - * - * @param mixed $message String or object containing the message - * to log. - * - * @return boolean True if the message was successfully logged. - * - * @access public - * @since Log 1.7.0 - */ - function emerg($message) - { - return $this->log($message, PEAR_LOG_EMERG); - } - - /** - * A convenience function for logging an alert event. It will log a - * message at the PEAR_LOG_ALERT log level. - * - * @param mixed $message String or object containing the message - * to log. - * - * @return boolean True if the message was successfully logged. - * - * @access public - * @since Log 1.7.0 - */ - function alert($message) - { - return $this->log($message, PEAR_LOG_ALERT); - } - - /** - * A convenience function for logging a critical event. It will log a - * message at the PEAR_LOG_CRIT log level. - * - * @param mixed $message String or object containing the message - * to log. - * - * @return boolean True if the message was successfully logged. - * - * @access public - * @since Log 1.7.0 - */ - function crit($message) - { - return $this->log($message, PEAR_LOG_CRIT); - } - - /** - * A convenience function for logging a error event. It will log a - * message at the PEAR_LOG_ERR log level. - * - * @param mixed $message String or object containing the message - * to log. - * - * @return boolean True if the message was successfully logged. - * - * @access public - * @since Log 1.7.0 - */ - function err($message) - { - return $this->log($message, PEAR_LOG_ERR); - } - - /** - * A convenience function for logging a warning event. It will log a - * message at the PEAR_LOG_WARNING log level. - * - * @param mixed $message String or object containing the message - * to log. - * - * @return boolean True if the message was successfully logged. - * - * @access public - * @since Log 1.7.0 - */ - function warning($message) - { - return $this->log($message, PEAR_LOG_WARNING); - } - - /** - * A convenience function for logging a notice event. It will log a - * message at the PEAR_LOG_NOTICE log level. - * - * @param mixed $message String or object containing the message - * to log. - * - * @return boolean True if the message was successfully logged. - * - * @access public - * @since Log 1.7.0 - */ - function notice($message) - { - return $this->log($message, PEAR_LOG_NOTICE); - } - - /** - * A convenience function for logging a information event. It will log a - * message at the PEAR_LOG_INFO log level. - * - * @param mixed $message String or object containing the message - * to log. - * - * @return boolean True if the message was successfully logged. - * - * @access public - * @since Log 1.7.0 - */ - function info($message) - { - return $this->log($message, PEAR_LOG_INFO); - } - - /** - * A convenience function for logging a debug event. It will log a - * message at the PEAR_LOG_DEBUG log level. - * - * @param mixed $message String or object containing the message - * to log. - * - * @return boolean True if the message was successfully logged. - * - * @access public - * @since Log 1.7.0 - */ - function debug($message) - { - return $this->log($message, PEAR_LOG_DEBUG); - } - - /** - * Returns the string representation of the message data. - * - * If $message is an object, _extractMessage() will attempt to extract - * the message text using a known method (such as a PEAR_Error object's - * getMessage() method). If a known method, cannot be found, the - * serialized representation of the object will be returned. - * - * If the message data is already a string, it will be returned unchanged. - * - * @param mixed $message The original message data. This may be a - * string or any object. - * - * @return string The string representation of the message. - * - * @access protected - */ - function _extractMessage($message) - { - /* - * If we've been given an object, attempt to extract the message using - * a known method. If we can't find such a method, default to the - * "human-readable" version of the object. - * - * We also use the human-readable format for arrays. - */ - if (is_object($message)) { - if (method_exists($message, 'getmessage')) { - $message = $message->getMessage(); - } else if (method_exists($message, 'tostring')) { - $message = $message->toString(); - } else if (method_exists($message, '__tostring')) { - if (version_compare(PHP_VERSION, '5.0.0', 'ge')) { - $message = (string)$message; - } else { - $message = $message->__toString(); - } - } else { - $message = print_r($message, true); - } - } else if (is_array($message)) { - if (isset($message['message'])) { - $message = $message['message']; - } else { - $message = print_r($message, true); - } - } - - /* Otherwise, we assume the message is a string. */ - return $message; - } - - /** - * Using debug_backtrace(), returns the file, line, and enclosing function - * name of the source code context from which log() was invoked. - * - * @param int $depth The initial number of frames we should step - * back into the trace. - * - * @return array Array containing three strings: the filename, the line, - * and the function name from which log() was called. - * - * @access private - * @since Log 1.9.4 - */ - function _getBacktraceVars($depth) - { - /* Start by generating a backtrace from the current call (here). */ - $backtrace = debug_backtrace(); - - /* - * If we were ultimately invoked by the composite handler, we need to - * increase our depth one additional level to compensate. - */ - if (strcasecmp(@$backtrace[$depth+1]['class'], 'Log_composite') == 0) { - $depth++; - } - - /* - * We're interested in the frame which invoked the log() function, so - * we need to walk back some number of frames into the backtrace. The - * $depth parameter tells us where to start looking. We go one step - * further back to find the name of the encapsulating function from - * which log() was called. - */ - $file = @$backtrace[$depth]['file']; - $line = @$backtrace[$depth]['line']; - $func = @$backtrace[$depth + 1]['function']; - - /* - * However, if log() was called from one of our "shortcut" functions, - * we're going to need to go back an additional step. - */ - if (in_array($func, array('emerg', 'alert', 'crit', 'err', 'warning', - 'notice', 'info', 'debug'))) { - $file = @$backtrace[$depth + 1]['file']; - $line = @$backtrace[$depth + 1]['line']; - $func = @$backtrace[$depth + 2]['function']; - } - - /* - * If we couldn't extract a function name (perhaps because we were - * executed from the "main" context), provide a default value. - */ - if (is_null($func)) { - $func = '(none)'; - } - $functions = ''; - for ( $i = count(@$backtrace) -1 ; $i > 2 ; $i-- ) { - $parts = explode ( PATH_SEP, @$backtrace[$i]['file']); - $filename = $parts [ count($parts) -1] . ':' . @$backtrace[$i]['line'] . ':'; - $functions .= $filename. @$backtrace[$i]['function'] . '()->'; - } - - /* Return a 4-tuple containing (file, line, function). */ - return array($file, $line, $func, $functions); - } - - /** - * Produces a formatted log line based on a format string and a set of - * variables representing the current log record and state. - * - * @return string Formatted log string. - * - * @access protected - * @since Log 1.9.4 - */ - function _format($format, $timestamp, $priority, $message) - { - /* - * If the format string references any of the backtrace-driven - * variables (%5, %6, %7), generate the backtrace and fetch them. - */ - if (strpos($format, '%5') || strpos($format, '%6') || strpos($format, '%7')) { - list($file, $line, $func) = $this->_getBacktraceVars(2); - } - - /* - * Build the formatted string. We use the sprintf() function's - * "argument swapping" capability to dynamically select and position - * the variables which will ultimately appear in the log string. - */ - return sprintf($format, - $timestamp, - $this->_ident, - $this->priorityToString($priority), - $message, - isset($file) ? $file : '', - isset($line) ? $line : '', - isset($func) ? $func : ''); - } - - /** - * Returns the string representation of a PEAR_LOG_* integer constant. - * - * @param int $priority A PEAR_LOG_* integer constant. - * - * @return string The string representation of $level. - * - * @access public - * @since Log 1.0 - */ - function priorityToString($priority) - { - $levels = array( - PEAR_LOG_EMERG => 'emergency', - PEAR_LOG_ALERT => 'alert', - PEAR_LOG_CRIT => 'critical', - PEAR_LOG_ERR => 'error', - PEAR_LOG_WARNING => 'warning', - PEAR_LOG_NOTICE => 'notice', - PEAR_LOG_INFO => 'info', - PEAR_LOG_DEBUG => 'debug' - ); - - return (isset($priority) && $priority != '')? $levels[$priority]: ''; - } - - /** - * Returns the the PEAR_LOG_* integer constant for the given string - * representation of a priority name. This function performs a - * case-insensitive search. - * - * @param string $name String containing a priority name. - * - * @return string The PEAR_LOG_* integer contstant corresponding - * the the specified priority name. - * - * @access public - * @since Log 1.9.0 - */ - function stringToPriority($name) - { - $levels = array( - 'emergency' => PEAR_LOG_EMERG, - 'alert' => PEAR_LOG_ALERT, - 'critical' => PEAR_LOG_CRIT, - 'error' => PEAR_LOG_ERR, - 'warning' => PEAR_LOG_WARNING, - 'notice' => PEAR_LOG_NOTICE, - 'info' => PEAR_LOG_INFO, - 'debug' => PEAR_LOG_DEBUG - ); - - return $levels[strtolower($name)]; - } - - /** - * Calculate the log mask for the given priority. - * - * This method may be called statically. - * - * @param integer $priority The priority whose mask will be calculated. - * - * @return integer The calculated log mask. - * - * @access public - * @since Log 1.7.0 - */ - function MASK($priority) - { - return (1 << $priority); - } - - /** - * Calculate the log mask for all priorities up to the given priority. - * - * This method may be called statically. - * - * @param integer $priority The maximum priority covered by this mask. - * - * @return integer The resulting log mask. - * - * @access public - * @since Log 1.7.0 - * - * @deprecated deprecated since Log 1.9.4; use Log::MAX() instead - */ - function UPTO($priority) - { - return Log::MAX($priority); - } - - /** - * Calculate the log mask for all priorities greater than or equal to the - * given priority. In other words, $priority will be the lowest priority - * matched by the resulting mask. - * - * This method may be called statically. - * - * @param integer $priority The minimum priority covered by this mask. - * - * @return integer The resulting log mask. - * - * @access public - * @since Log 1.9.4 - */ - function MIN($priority) - { - return PEAR_LOG_ALL ^ ((1 << $priority) - 1); - } - - /** - * Calculate the log mask for all priorities less than or equal to the - * given priority. In other words, $priority will be the highests priority - * matched by the resulting mask. - * - * This method may be called statically. - * - * @param integer $priority The maximum priority covered by this mask. - * - * @return integer The resulting log mask. - * - * @access public - * @since Log 1.9.4 - */ - function MAX($priority) - { - return ((1 << ($priority + 1)) - 1); - } - - /** - * Set and return the level mask for the current Log instance. - * - * @param integer $mask A bitwise mask of log levels. - * - * @return integer The current level mask. - * - * @access public - * @since Log 1.7.0 - */ - function setMask($mask) - { - $this->_mask = $mask; - - return $this->_mask; - } - - /** - * Returns the current level mask. - * - * @return interger The current level mask. - * - * @access public - * @since Log 1.7.0 - */ - function getMask() - { - return $this->_mask; - } - - /** - * Check if the given priority is included in the current level mask. - * - * @param integer $priority The priority to check. - * - * @return boolean True if the given priority is included in the current - * log mask. - * - * @access protected - * @since Log 1.7.0 - */ - function _isMasked($priority) - { - return (Log::MASK($priority) & $this->_mask); - } - - /** - * Returns the current default priority. - * - * @return integer The current default priority. - * - * @access public - * @since Log 1.8.4 - */ - function getPriority() - { - return $this->_priority; - } - - /** - * Sets the default priority to the specified value. - * - * @param integer $priority The new default priority. - * - * @access public - * @since Log 1.8.4 - */ - function setPriority($priority) - { - $this->_priority = $priority; - } - - /** - * Adds a Log_observer instance to the list of observers that are listening - * for messages emitted by this Log instance. - * - * @param object $observer The Log_observer instance to attach as a - * listener. - * - * @param boolean True if the observer is successfully attached. - * - * @access public - * @since Log 1.0 - */ - function attach(&$observer) - { - if (!is_a($observer, 'Log_observer')) { - return false; - } - - $this->_listeners[$observer->_id] = &$observer; - - return true; - } - - /** - * Removes a Log_observer instance from the list of observers. - * - * @param object $observer The Log_observer instance to detach from - * the list of listeners. - * - * @param boolean True if the observer is successfully detached. - * - * @access public - * @since Log 1.0 - */ - function detach($observer) - { - if (!is_a($observer, 'Log_observer') || - !isset($this->_listeners[$observer->_id])) { - return false; - } - - unset($this->_listeners[$observer->_id]); - - return true; - } - - /** - * Informs each registered observer instance that a new message has been - * logged. - * - * @param array $event A hash describing the log event. - * - * @access protected - */ - function _announce($event) - { - foreach ($this->_listeners as $id => $listener) { - if ($event['priority'] <= $this->_listeners[$id]->_priority) { - $this->_listeners[$id]->notify($event); - } - } - } - - /** - * Indicates whether this is a composite class. - * - * @return boolean True if this is a composite class. - * - * @access public - * @since Log 1.0 - */ - function isComposite() - { - return false; - } - - /** - * Sets this Log instance's identification string. - * - * @param string $ident The new identification string. - * - * @access public - * @since Log 1.6.3 - */ - function setIdent($ident) - { - $this->_ident = $ident; - } - - /** - * Returns the current identification string. - * - * @return string The current Log instance's identification string. - * - * @access public - * @since Log 1.6.3 - */ - function getIdent() - { - return $this->_ident; - } -} diff --git a/gulliver/thirdparty/pear/Log/composite.php b/gulliver/thirdparty/pear/Log/composite.php deleted file mode 100644 index 98a1d814c..000000000 --- a/gulliver/thirdparty/pear/Log/composite.php +++ /dev/null @@ -1,231 +0,0 @@ - - * @author Jon Parise - * - * @since Horde 1.3 - * @since Log 1.0 - * @package Log - * - * @example composite.php Using the composite handler. - */ -class Log_composite extends Log -{ - /** - * Array holding all of the Log instances to which log events should be - * sent. - * - * @var array - * @access private - */ - var $_children = array(); - - - /** - * Constructs a new composite Log object. - * - * @param boolean $name This parameter is ignored. - * @param boolean $ident This parameter is ignored. - * @param boolean $conf This parameter is ignored. - * @param boolean $level This parameter is ignored. - * - * @access public - */ - function Log_composite($name, $ident = '', $conf = array(), - $level = PEAR_LOG_DEBUG) - { - $this->_ident = $ident; - } - - /** - * Opens all of the child instances. - * - * @return True if all of the child instances were successfully opened. - * - * @access public - */ - function open() - { - /* Attempt to open each of our children. */ - $this->_opened = true; - foreach ($this->_children as $id => $child) { - $this->_opened &= $this->_children[$id]->open(); - } - - /* If all children were opened, return success. */ - return $this->_opened; - } - - /** - * Closes all of the child instances. - * - * @return True if all of the child instances were successfully closed. - * - * @access public - */ - function close() - { - /* Attempt to close each of our children. */ - $closed = true; - foreach ($this->_children as $id => $child) { - $closed &= $this->_children[$id]->close(); - } - - /* Track the _opened state for consistency. */ - $this->_opened = false; - - /* If all children were closed, return success. */ - return $closed; - } - - /** - * Flushes all child instances. It is assumed that all of the children - * have been successfully opened. - * - * @return True if all of the child instances were successfully flushed. - * - * @access public - * @since Log 1.8.2 - */ - function flush() - { - /* Attempt to flush each of our children. */ - $flushed = true; - foreach ($this->_children as $id => $child) { - $flushed &= $this->_children[$id]->flush(); - } - - /* If all children were flushed, return success. */ - return $flushed; - } - - /** - * Sends $message and $priority to each child of this composite. If the - * children aren't already open, they will be opened here. - * - * @param mixed $message String or object containing the message - * to log. - * @param string $priority (optional) The priority of the message. - * Valid values are: PEAR_LOG_EMERG, - * PEAR_LOG_ALERT, PEAR_LOG_CRIT, - * PEAR_LOG_ERR, PEAR_LOG_WARNING, - * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and - * PEAR_LOG_DEBUG. - * - * @return boolean True if the entry is successfully logged. - * - * @access public - */ - function log($message, $priority = null) - { - /* If a priority hasn't been specified, use the default value. */ - if ($priority === null) { - $priority = $this->_priority; - } - - /* - * If the handlers haven't been opened, attempt to open them now. - * However, we don't treat failure to open all of the handlers as a - * fatal error. We defer that consideration to the success of calling - * each handler's log() method below. - */ - if (!$this->_opened) { - $this->open(); - } - - /* Attempt to log the event using each of the children. */ - $success = true; - foreach ($this->_children as $id => $child) { - $success &= $this->_children[$id]->log($message, $priority); - } - - $this->_announce(array('priority' => $priority, 'message' => $message)); - - /* Return success if all of the children logged the event. */ - return $success; - } - - /** - * Returns true if this is a composite. - * - * @return boolean True if this is a composite class. - * - * @access public - */ - function isComposite() - { - return true; - } - - /** - * Sets this identification string for all of this composite's children. - * - * @param string $ident The new identification string. - * - * @access public - * @since Log 1.6.7 - */ - function setIdent($ident) - { - /* Call our base class's setIdent() method. */ - parent::setIdent($ident); - - /* ... and then call setIdent() on all of our children. */ - foreach ($this->_children as $id => $child) { - $this->_children[$id]->setIdent($ident); - } - } - - /** - * Adds a Log instance to the list of children. - * - * @param object $child The Log instance to add. - * - * @return boolean True if the Log instance was successfully added. - * - * @access public - */ - function addChild(&$child) - { - /* Make sure this is a Log instance. */ - if (!is_a($child, 'Log')) { - return false; - } - - $this->_children[$child->_id] = &$child; - - return true; - } - - /** - * Removes a Log instance from the list of children. - * - * @param object $child The Log instance to remove. - * - * @return boolean True if the Log instance was successfully removed. - * - * @access public - */ - function removeChild($child) - { - if (!is_a($child, 'Log') || !isset($this->_children[$child->_id])) { - return false; - } - - unset($this->_children[$child->_id]); - - return true; - } - -} diff --git a/gulliver/thirdparty/pear/Log/console.php b/gulliver/thirdparty/pear/Log/console.php deleted file mode 100644 index a52c15a57..000000000 --- a/gulliver/thirdparty/pear/Log/console.php +++ /dev/null @@ -1,217 +0,0 @@ - - * @since Log 1.1 - * @package Log - * - * @example console.php Using the console handler. - */ -class Log_console extends Log -{ - /** - * Handle to the current output stream. - * @var resource - * @access private - */ - var $_stream = STDOUT; - - /** - * Should the output be buffered or displayed immediately? - * @var string - * @access private - */ - var $_buffering = false; - - /** - * String holding the buffered output. - * @var string - * @access private - */ - var $_buffer = ''; - - /** - * String containing the format of a log line. - * @var string - * @access private - */ - var $_lineFormat = '%1$s %2$s [%3$s] %4$s'; - - /** - * String containing the timestamp format. It will be passed directly to - * strftime(). Note that the timestamp string will generated using the - * current locale. - * @var string - * @access private - */ - var $_timeFormat = '%b %d %H:%M:%S'; - - /** - * Constructs a new Log_console object. - * - * @param string $name Ignored. - * @param string $ident The identity string. - * @param array $conf The configuration array. - * @param int $level Log messages up to and including this level. - * @access public - */ - function Log_console($name, $ident = '', $conf = array(), - $level = PEAR_LOG_DEBUG) - { - 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->_id = G::encryptOld(microtime()); - $this->_ident = $ident; - $this->_mask = Log::UPTO($level); - - if (!empty($conf['stream'])) { - $this->_stream = $conf['stream']; - } - - if (isset($conf['buffering'])) { - $this->_buffering = $conf['buffering']; - } - - if (!empty($conf['lineFormat'])) { - $this->_lineFormat = str_replace(array_keys($this->_formatMap), - array_values($this->_formatMap), - $conf['lineFormat']); - } - - if (!empty($conf['timeFormat'])) { - $this->_timeFormat = $conf['timeFormat']; - } - - /* - * If output buffering has been requested, we need to register a - * shutdown function that will dump the buffer upon termination. - */ - if ($this->_buffering) { - register_shutdown_function(array(&$this, '_Log_console')); - } - } - - /** - * Destructor - */ - function _Log_console() - { - $this->close(); - } - - /** - * Open the output stream. - * - * @access public - * @since Log 1.9.7 - */ - function open() - { - $this->_opened = true; - return true; - } - - /** - * Closes the output stream. - * - * This results in a call to flush(). - * - * @access public - * @since Log 1.9.0 - */ - function close() - { - $this->flush(); - $this->_opened = false; - return true; - } - - /** - * Flushes all pending ("buffered") data to the output stream. - * - * @access public - * @since Log 1.8.2 - */ - function flush() - { - /* - * If output buffering is enabled, dump the contents of the buffer to - * the output stream. - */ - if ($this->_buffering && (strlen($this->_buffer) > 0)) { - fwrite($this->_stream, $this->_buffer); - $this->_buffer = ''; - } - - if (is_resource($this->_stream)) { - return fflush($this->_stream); - } - - return false; - } - - /** - * Writes $message to the text console. Also, passes the message - * along to any Log_observer instances that are observing this Log. - * - * @param mixed $message String or object containing the message to log. - * @param string $priority The priority of the message. Valid - * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, - * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, - * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. - * @return boolean True on success or false on failure. - * @access public - */ - function log($message, $priority = null) - { - /* If a priority hasn't been specified, use the default value. */ - if ($priority === null) { - $priority = $this->_priority; - } - - /* Abort early if the priority is above the maximum logging level. */ - if (!$this->_isMasked($priority)) { - return false; - } - - /* Extract the string representation of the message. */ - $message = $this->_extractMessage($message); - - /* Build the string containing the complete log line. */ - $line = $this->_format($this->_lineFormat, - strftime($this->_timeFormat), - $priority, $message) . "\n"; - - /* - * If buffering is enabled, append this line to the output buffer. - * Otherwise, print the line to the output stream immediately. - */ - if ($this->_buffering) { - $this->_buffer .= $line; - } else { - fwrite($this->_stream, $line); - } - - /* Notify observers about this log message. */ - $this->_announce(array('priority' => $priority, 'message' => $message)); - - return true; - } - -} diff --git a/gulliver/thirdparty/pear/Log/daemon.php b/gulliver/thirdparty/pear/Log/daemon.php deleted file mode 100644 index 07ca7a832..000000000 --- a/gulliver/thirdparty/pear/Log/daemon.php +++ /dev/null @@ -1,239 +0,0 @@ - - * @version $Revision: 1.2 $ - * @package Log - */ -class Log_daemon extends Log -{ - /** - * Integer holding the log facility to use. - * @var string - */ - var $_name = LOG_DAEMON; - - /** - * Var holding the resource pointer to the socket - * @var resource - */ - var $_socket; - - /** - * The ip address or servername - * @see http://www.php.net/manual/en/transports.php - * @var string - */ - var $_ip = '127.0.0.1'; - - /** - * Protocol to use (tcp, udp, etc.) - * @see http://www.php.net/manual/en/transports.php - * @var string - */ - var $_proto = 'udp'; - - /** - * Port to connect to - * @var int - */ - var $_port = 514; - - /** - * Maximum message length in bytes - * @var int - */ - var $_maxsize = 4096; - - /** - * Socket timeout in seconds - * @var int - */ - var $_timeout = 1; - - - /** - * Constructs a new syslog object. - * - * @param string $name The syslog facility. - * @param string $ident The identity string. - * @param array $conf The configuration array. - * @param int $maxLevel Maximum level at which to log. - * @access public - */ - function Log_daemon($name, $ident = '', $conf = array(), - $level = PEAR_LOG_DEBUG) - { - /* Ensure we have a valid integer value for $name. */ - if (empty($name) || !is_int($name)) { - $name = LOG_SYSLOG; - } - - 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->_id = G::encryptOld(microtime()); - $this->_name = $name; - $this->_ident = $ident; - $this->_mask = Log::UPTO($level); - - if (isset($conf['ip'])) { - $this->_ip = $conf['ip']; - } - if (isset($conf['proto'])) { - $this->_proto = $conf['proto']; - } - if (isset($conf['port'])) { - $this->_port = $conf['port']; - } - if (isset($conf['maxsize'])) { - $this->_maxsize = $conf['maxsize']; - } - if (isset($conf['timeout'])) { - $this->_timeout = $conf['timeout']; - } - $this->_proto = $this->_proto . '://'; - - register_shutdown_function(array(&$this, '_Log_daemon')); - } - - /** - * Destructor. - * - * @access private - */ - function _Log_daemon() - { - $this->close(); - } - - /** - * Opens a connection to the system logger, if it has not already - * been opened. This is implicitly called by log(), if necessary. - * @access public - */ - function open() - { - if (!$this->_opened) { - $this->_opened = (bool)($this->_socket = @fsockopen( - $this->_proto . $this->_ip, - $this->_port, - $errno, - $errstr, - $this->_timeout)); - } - return $this->_opened; - } - - /** - * Closes the connection to the system logger, if it is open. - * @access public - */ - function close() - { - if ($this->_opened) { - $this->_opened = false; - return fclose($this->_socket); - } - return true; - } - - /** - * Sends $message to the currently open syslog connection. Calls - * open() if necessary. Also passes the message along to any Log_observer - * instances that are observing this Log. - * - * @param string $message The textual message to be logged. - * @param int $priority (optional) The priority of the message. Valid - * values are: LOG_EMERG, LOG_ALERT, LOG_CRIT, - * LOG_ERR, LOG_WARNING, LOG_NOTICE, LOG_INFO, - * and LOG_DEBUG. The default is LOG_INFO. - * @access public - */ - function log($message, $priority = null) - { - /* If a priority hasn't been specified, use the default value. */ - if ($priority === null) { - $priority = $this->_priority; - } - - /* Abort early if the priority is above the maximum logging level. */ - if (!$this->_isMasked($priority)) { - return false; - } - - /* If the connection isn't open and can't be opened, return failure. */ - if (!$this->_opened && !$this->open()) { - return false; - } - - /* Extract the string representation of the message. */ - $message = $this->_extractMessage($message); - - /* Set the facility level. */ - $facility_level = intval($this->_name) + - intval($this->_toSyslog($priority)); - - /* Prepend ident info. */ - if (!empty($this->_ident)) { - $message = $this->_ident . ' ' . $message; - } - - /* Check for message length. */ - if (strlen($message) > $this->_maxsize) { - $message = substr($message, 0, ($this->_maxsize) - 10) . ' [...]'; - } - - /* Write to socket. */ - fwrite($this->_socket, '<' . $facility_level . '>' . $message . "\n"); - - $this->_announce(array('priority' => $priority, 'message' => $message)); - } - - /** - * Converts a PEAR_LOG_* constant into a syslog LOG_* constant. - * - * This function exists because, under Windows, not all of the LOG_* - * constants have unique values. Instead, the PEAR_LOG_* were introduced - * for global use, with the conversion to the LOG_* constants kept local to - * to the syslog driver. - * - * @param int $priority PEAR_LOG_* value to convert to LOG_* value. - * - * @return The LOG_* representation of $priority. - * - * @access private - */ - function _toSyslog($priority) - { - static $priorities = array( - PEAR_LOG_EMERG => LOG_EMERG, - PEAR_LOG_ALERT => LOG_ALERT, - PEAR_LOG_CRIT => LOG_CRIT, - PEAR_LOG_ERR => LOG_ERR, - PEAR_LOG_WARNING => LOG_WARNING, - PEAR_LOG_NOTICE => LOG_NOTICE, - PEAR_LOG_INFO => LOG_INFO, - PEAR_LOG_DEBUG => LOG_DEBUG - ); - - /* If we're passed an unknown priority, default to LOG_INFO. */ - if (!is_int($priority) || !in_array($priority, $priorities)) { - return LOG_INFO; - } - - return $priorities[$priority]; - } - -} diff --git a/gulliver/thirdparty/pear/Log/display.php b/gulliver/thirdparty/pear/Log/display.php deleted file mode 100644 index fb3667e09..000000000 --- a/gulliver/thirdparty/pear/Log/display.php +++ /dev/null @@ -1,159 +0,0 @@ - - * @since Log 1.8.0 - * @package Log - * - * @example display.php Using the display handler. - */ -class Log_display extends Log -{ - /** - * String to output before an error message - * @var string - * @access private - */ - var $_error_prepend = ''; - - /** - * String to output after an error message - * @var string - * @access private - */ - var $_error_append = ''; - - /** - * String used to represent a line break. - * @var string - * @access private - */ - var $_linebreak = "
\n"; - - /** - * Constructs a new Log_display object. - * - * @param string $name Ignored. - * @param string $ident The identity string. - * @param array $conf The configuration array. - * @param int $level Log messages up to and including this level. - * @access public - */ - function Log_display($name = '', $ident = '', $conf = array(), - $level = PEAR_LOG_DEBUG) - { - 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->_id = G::encryptOld(microtime()); - $this->_ident = $ident; - $this->_mask = Log::UPTO($level); - - if (isset($conf['error_prepend'])) { - $this->_error_prepend = $conf['error_prepend']; - } else { - $this->_error_prepend = ini_get('error_prepend_string'); - } - - if (isset($conf['error_append'])) { - $this->_error_append = $conf['error_append']; - } else { - $this->_error_append = ini_get('error_append_string'); - } - - if (isset($conf['linebreak'])) { - $this->_linebreak = $conf['linebreak']; - } - } - - /** - * Opens the display handler. - * - * @access public - * @since Log 1.9.6 - */ - function open() - { - $this->_opened = true; - return true; - } - - /** - * Closes the display handler. - * - * @access public - * @since Log 1.9.6 - */ - function close() - { - $this->_opened = false; - return true; - } - - /** - * Writes $message to the text browser. Also, passes the message - * along to any Log_observer instances that are observing this Log. - * - * @param mixed $message String or object containing the message to log. - * @param string $priority The priority of the message. Valid - * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, - * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, - * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. - * @return boolean True on success or false on failure. - * @access public - */ - function log($message, $priority = null) - { - /* If a priority hasn't been specified, use the default value. */ - if ($priority === null) { - $priority = $this->_priority; - } - - /* Abort early if the priority is above the maximum logging level. */ - if (!$this->_isMasked($priority)) { - return false; - } - - /* Extract the string representation of the message. */ - $message = $this->_extractMessage($message); - - /* Build and output the complete log line. */ - $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.inputfilter.php'); - $filter = new InputFilter(); - $tag = $filter->xssFilterHard(ucfirst($this->priorityToString($priority))); - echo $this->_error_prepend . - '' . $tag . ': '. - nl2br(htmlspecialchars($message)) . - $this->_error_append . $this->_linebreak; - - /* Notify observers about this log message. */ - $this->_announce(array('priority' => $priority, 'message' => $message)); - - return true; - } - -} diff --git a/gulliver/thirdparty/pear/Log/error_log.php b/gulliver/thirdparty/pear/Log/error_log.php deleted file mode 100644 index 412f4cac9..000000000 --- a/gulliver/thirdparty/pear/Log/error_log.php +++ /dev/null @@ -1,136 +0,0 @@ - - * @since Log 1.7.0 - * @package Log - * - * @example error_log.php Using the error_log handler. - */ -class Log_error_log extends Log -{ - /** - * The error_log() log type. - * @var integer - * @access private - */ - var $_type = PEAR_LOG_TYPE_SYSTEM; - - /** - * The type-specific destination value. - * @var string - * @access private - */ - var $_destination = ''; - - /** - * Additional headers to pass to the mail() function when the - * PEAR_LOG_TYPE_MAIL type is used. - * @var string - * @access private - */ - var $_extra_headers = ''; - - /** - * Constructs a new Log_error_log object. - * - * @param string $name Ignored. - * @param string $ident The identity string. - * @param array $conf The configuration array. - * @param int $level Log messages up to and including this level. - * @access public - */ - function Log_error_log($name, $ident = '', $conf = array(), - $level = PEAR_LOG_DEBUG) - { - 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->_id = G::encryptOld(microtime()); - $this->_type = $name; - $this->_ident = $ident; - $this->_mask = Log::UPTO($level); - - if (!empty($conf['destination'])) { - $this->_destination = $conf['destination']; - } - if (!empty($conf['extra_headers'])) { - $this->_extra_headers = $conf['extra_headers']; - } - } - - /** - * Opens the handler. - * - * @access public - * @since Log 1.9.6 - */ - function open() - { - $this->_opened = true; - return true; - } - - /** - * Closes the handler. - * - * @access public - * @since Log 1.9.6 - */ - function close() - { - $this->_opened = false; - return true; - } - - /** - * Logs $message using PHP's error_log() function. The message is also - * passed along to any Log_observer instances that are observing this Log. - * - * @param mixed $message String or object containing the message to log. - * @param string $priority The priority of the message. Valid - * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, - * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, - * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. - * @return boolean True on success or false on failure. - * @access public - */ - function log($message, $priority = null) - { - /* If a priority hasn't been specified, use the default value. */ - if ($priority === null) { - $priority = $this->_priority; - } - - /* Abort early if the priority is above the maximum logging level. */ - if (!$this->_isMasked($priority)) { - return false; - } - - /* Extract the string representation of the message. */ - $message = $this->_extractMessage($message); - - $success = error_log($this->_ident . ': ' . $message, $this->_type, - $this->_destination, $this->_extra_headers); - - $this->_announce(array('priority' => $priority, 'message' => $message)); - - return $success; - } - -} diff --git a/gulliver/thirdparty/pear/Log/file.php b/gulliver/thirdparty/pear/Log/file.php deleted file mode 100644 index 89c14e1de..000000000 --- a/gulliver/thirdparty/pear/Log/file.php +++ /dev/null @@ -1,352 +0,0 @@ - - * @author Roman Neuhauser - * @since Log 1.0 - * @package Log - * - * @example file.php Using the file handler. - */ -class Log_file extends Log -{ - /** - * String containing the name of the log file. - * @var string - * @access private - */ - var $_filename = 'php.log'; - - /** - * Handle to the log file. - * @var resource - * @access private - */ - var $_fp = false; - - /** - * Should new log entries be append to an existing log file, or should the - * a new log file overwrite an existing one? - * @var boolean - * @access private - */ - var $_append = true; - - /** - * Should advisory file locking (i.e., flock()) be used? - * @var boolean - * @access private - */ - var $_locking = false; - - /** - * Integer (in octal) containing the log file's permissions mode. - * @var integer - * @access private - */ - var $_mode = 0644; - - /** - * Integer (in octal) specifying the file permission mode that will be - * used when creating directories that do not already exist. - * @var integer - * @access private - */ - var $_dirmode = 0755; - - /** - * String containing the format of a log line. - * @var string - * @access private - */ - var $_lineFormat = '%1$s %2$s [%3$s] %4$s'; - - /** - * String containing the timestamp format. It will be passed directly to - * strftime(). Note that the timestamp string will generated using the - * current locale. - * @var string - * @access private - */ - var $_timeFormat = '%b %d %H:%M:%S'; - - /** - * String containing the end-on-line character sequence. - * @var string - * @access private - */ - var $_eol = "\n"; - - /** - * Constructs a new Log_file object. - * - * @param string $name Ignored. - * @param string $ident The identity string. - * @param array $conf The configuration array. - * @param int $level Log messages up to and including this level. - * @access public - */ - function Log_file($name, $ident = '', $conf = array(), - $level = PEAR_LOG_DEBUG) - { - 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->_id = G::encryptOld(microtime()); - $this->_filename = $name; - $this->_ident = $ident; - $this->_mask = Log::UPTO($level); - - if (isset($conf['append'])) { - $this->_append = $conf['append']; - } - - if (isset($conf['locking'])) { - $this->_locking = $conf['locking']; - } - - if (!empty($conf['mode'])) { - if (is_string($conf['mode'])) { - $this->_mode = octdec($conf['mode']); - } else { - $this->_mode = $conf['mode']; - } - } - - if (!empty($conf['dirmode'])) { - if (is_string($conf['dirmode'])) { - $this->_dirmode = octdec($conf['dirmode']); - } else { - $this->_dirmode = $conf['dirmode']; - } - } - - if (!empty($conf['lineFormat'])) { - $this->_lineFormat = str_replace(array_keys($this->_formatMap), - array_values($this->_formatMap), - $conf['lineFormat']); - } - - if (!empty($conf['timeFormat'])) { - $this->_timeFormat = $conf['timeFormat']; - } - - if (!empty($conf['eol'])) { - $this->_eol = $conf['eol']; - } else { - $this->_eol = (strstr(PHP_OS, 'WIN')) ? "\r\n" : "\n"; - } - - register_shutdown_function(array(&$this, '_Log_file')); - } - - /** - * Destructor - */ - function _Log_file() - { - if ($this->_opened) { - $this->close(); - } - } - - /** - * Creates the given directory path. If the parent directories don't - * already exist, they will be created, too. - * - * This implementation is inspired by Python's os.makedirs function. - * - * @param string $path The full directory path to create. - * @param integer $mode The permissions mode with which the - * directories will be created. - * - * @return True if the full path is successfully created or already - * exists. - * - * @access private - */ - function _mkpath($path, $mode = 0700) - { - /* Separate the last pathname component from the rest of the path. */ - $head = dirname($path); - $tail = basename($path); - - /* Make sure we've split the path into two complete components. */ - if (empty($tail)) { - $head = dirname($path); - $tail = basename($path); - } - - /* Recurse up the path if our current segment does not exist. */ - if (!empty($head) && !empty($tail) && !is_dir($head)) { - $this->_mkpath($head, $mode); - } - - /* Create this segment of the path. */ - return @mkdir($head, $mode); - } - - /** - * Opens the log file for output. If the specified log file does not - * already exist, it will be created. By default, new log entries are - * appended to the end of the log file. - * - * This is implicitly called by log(), if necessary. - * - * @access public - */ - function open() - { - if (!$this->_opened) { - /* If the log file's directory doesn't exist, create it. */ - if (!is_dir(dirname($this->_filename))) { - $this->_mkpath($this->_filename, $this->_dirmode); - } - - /* Determine whether the log file needs to be created. */ - $creating = !file_exists($this->_filename); - - /* Obtain a handle to the log file. */ - $this->_fp = fopen($this->_filename, ($this->_append) ? 'a' : 'w'); - - /* We consider the file "opened" if we have a valid file pointer. */ - $this->_opened = ($this->_fp !== false); - - /* Attempt to set the file's permissions if we just created it. */ - if ($creating && $this->_opened) { - chmod($this->_filename, $this->_mode); - } - } - - return $this->_opened; - } - - /** - * Closes the log file if it is open. - * - * @access public - */ - function close() - { - /* If the log file is open, close it. */ - if ($this->_opened && fclose($this->_fp)) { - $this->_opened = false; - } - - return ($this->_opened === false); - } - - /** - * Flushes all pending data to the file handle. - * - * @access public - * @since Log 1.8.2 - */ - function flush() - { - if (is_resource($this->_fp)) { - return fflush($this->_fp); - } - - return false; - } - - /** - * Logs $message to the output window. The message is also passed along - * to any Log_observer instances that are observing this Log. - * - * @param mixed $message String or object containing the message to log. - * @param string $priority The priority of the message. Valid - * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, - * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, - * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. - * @return boolean True on success or false on failure. - * @access public - */ - function log($message, $priority = null) - { - // define constants, because there are times when the page is rendered outside a workspace - if ( !defined('PM_PID') ) { - define ('PM_PID', rand(0,1000) ); - } - if ( !defined('SYS_SYS') ) { - define ('SYS_SYS', '' ); - } - /* If a priority hasn't been specified, use the default value. */ - if ($priority === null) { - $priority = $this->_priority; - } - - /* Abort early if the priority is above the maximum logging level. */ - if (!$this->_isMasked($priority)) { - return false; - } - - /* If the log file isn't already open, open it now. */ - if (!$this->_opened && !$this->open()) { - return false; - } - - /* Extract the string representation of the message. */ - $message = $this->_extractMessage($message); - - /*********************** change here >> depth value *************/ - $uri = $_SERVER['REQUEST_URI']; - $backTrace = $this->_getBacktraceVars( 5 ); - $method = $_SERVER['REQUEST_METHOD']; - $ip = getenv('REMOTE_ADDR'); - $myPid = PM_PID; - //$request variable will have all the values in POST and GET - $request = ''; - foreach( $_POST as $k => $v ){ - if(is_string($v)){ - $request .= ($request!='' ? "\t" : '') . $k . '='.$v; - } - } - foreach( $_GET as $k => $v ) $request .= ($request!='' ? "\t" : '') . $k . '='.$v; - - //exact time with microseconds - $t = explode(' ',microtime(false)); - list($usec, $sec) = explode(' ', microtime()); - $micro = date('H:i:s.') . sprintf("%04d", floor($usec * 10000 )); - - /* Build the string containing the complete message */ - $msg = sprintf ( "%s|%s|%s|%05d|%s|%s|%s|%s|%s\n", $micro,SYS_SYS,$ip, $myPid, $message, $backTrace[3], $method, $uri, $request); - /* Build the string containing the complete log line. */ - $line = $this->_format('%4$s', $micro,'',$msg ); - - /* If locking is enabled, acquire an exclusive lock on the file. */ - if ($this->_locking) { - flock($this->_fp, LOCK_EX); - } - - /* Write the log line to the log file. */ - $success = (fwrite($this->_fp, $line) !== false); - - /* Unlock the file now that we're finished writing to it. */ - if ($this->_locking) { - flock($this->_fp, LOCK_UN); - } - - /* Notify observers about this log message. */ - $this->_announce(array('priority' => $priority, 'message' => $message)); - - return $success; - } - -} diff --git a/gulliver/thirdparty/pear/Log/firebug.php b/gulliver/thirdparty/pear/Log/firebug.php deleted file mode 100644 index 1dea4a7f5..000000000 --- a/gulliver/thirdparty/pear/Log/firebug.php +++ /dev/null @@ -1,223 +0,0 @@ - - * @since Log 1.x.x - * @package Log - * - * @example firebug.php Using the firebug handler. - */ -class Log_firebug extends Log -{ - /** - * Should the output be buffered or displayed immediately? - * @var string - * @access private - */ - var $_buffering = false; - - /** - * String holding the buffered output. - * @var string - * @access private - */ - var $_buffer = array(); - - /** - * String containing the format of a log line. - * @var string - * @access private - */ - var $_lineFormat = '%2$s [%3$s] %4$s'; - - /** - * String containing the timestamp format. It will be passed directly to - * strftime(). Note that the timestamp string will generated using the - * current locale. - * - * Note! Default lineFormat of this driver does not display time. - * - * @var string - * @access private - */ - var $_timeFormat = '%b %d %H:%M:%S'; - - /** - * Mapping of log priorities to Firebug methods. - * @var array - * @access private - */ - var $_methods = array( - PEAR_LOG_EMERG => 'error', - PEAR_LOG_ALERT => 'error', - PEAR_LOG_CRIT => 'error', - PEAR_LOG_ERR => 'error', - PEAR_LOG_WARNING => 'warn', - PEAR_LOG_NOTICE => 'info', - PEAR_LOG_INFO => 'info', - PEAR_LOG_DEBUG => 'debug' - ); - - /** - * Constructs a new Log_firebug object. - * - * @param string $name Ignored. - * @param string $ident The identity string. - * @param array $conf The configuration array. - * @param int $level Log messages up to and including this level. - * @access public - */ - function Log_firebug($name = '', $ident = 'PHP', $conf = array(), - $level = PEAR_LOG_DEBUG) - { - 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->_id = G::encryptOld(microtime()); - $this->_ident = $ident; - $this->_mask = Log::UPTO($level); - if (isset($conf['buffering'])) { - $this->_buffering = $conf['buffering']; - } - - if ($this->_buffering) { - register_shutdown_function(array(&$this, '_Log_firebug')); - } - - if (!empty($conf['lineFormat'])) { - $this->_lineFormat = str_replace(array_keys($this->_formatMap), - array_values($this->_formatMap), - $conf['lineFormat']); - } - - if (!empty($conf['timeFormat'])) { - $this->_timeFormat = $conf['timeFormat']; - } - } - - /** - * Opens the firebug handler. - * - * @access public - */ - function open() - { - $this->_opened = true; - return true; - } - - /** - * Destructor - */ - function _Log_firebug() - { - $this->close(); - } - - /** - * Closes the firebug handler. - * - * @access public - */ - function close() - { - $this->flush(); - $this->_opened = false; - return true; - } - - /** - * Flushes all pending ("buffered") data. - * - * @access public - */ - function flush() { - if (count($this->_buffer)) { - print '\n"; - }; - $this->_buffer = array(); - } - - /** - * Writes $message to Firebug console. Also, passes the message - * along to any Log_observer instances that are observing this Log. - * - * @param mixed $message String or object containing the message to log. - * @param string $priority The priority of the message. Valid - * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, - * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, - * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. - * @return boolean True on success or false on failure. - * @access public - */ - function log($message, $priority = null) - { - /* If a priority hasn't been specified, use the default value. */ - if ($priority === null) { - $priority = $this->_priority; - } - - /* Abort early if the priority is above the maximum logging level. */ - if (!$this->_isMasked($priority)) { - return false; - } - - /* Extract the string representation of the message. */ - $message = $this->_extractMessage($message); - $method = $this->_methods[$priority]; - - /* normalize line breaks */ - $message = str_replace("\r\n", "\n", $message); - - /* escape line breaks */ - $message = str_replace("\n", "\\n\\\n", $message); - - /* escape quotes */ - $message = str_replace('"', '\\"', $message); - - /* Build the string containing the complete log line. */ - $line = $this->_format($this->_lineFormat, - strftime($this->_timeFormat), - $priority, - $message); - - if ($this->_buffering) { - $this->_buffer[] = sprintf('console.%s("%s");', $method, $line); - } else { - print '\n"; - } - /* Notify observers about this log message. */ - $this->_announce(array('priority' => $priority, 'message' => $message)); - - return true; - } - -} diff --git a/gulliver/thirdparty/pear/Log/mail.php b/gulliver/thirdparty/pear/Log/mail.php deleted file mode 100644 index 51538ae52..000000000 --- a/gulliver/thirdparty/pear/Log/mail.php +++ /dev/null @@ -1,266 +0,0 @@ - - * @author Jon Parise - * @since Log 1.3 - * @package Log - * - * @example mail.php Using the mail handler. - */ -class Log_mail extends Log -{ - /** - * String holding the recipients' email addresses. Multiple addresses - * should be separated with commas. - * @var string - * @access private - */ - var $_recipients = ''; - - /** - * String holding the sender's email address. - * @var string - * @access private - */ - var $_from = ''; - - /** - * String holding the email's subject. - * @var string - * @access private - */ - var $_subject = '[Log_mail] Log message'; - - /** - * String holding an optional preamble for the log messages. - * @var string - * @access private - */ - var $_preamble = ''; - - /** - * String containing the format of a log line. - * @var string - * @access private - */ - var $_lineFormat = '%1$s %2$s [%3$s] %4$s'; - - /** - * String containing the timestamp format. It will be passed directly to - * strftime(). Note that the timestamp string will generated using the - * current locale. - * @var string - * @access private - */ - var $_timeFormat = '%b %d %H:%M:%S'; - - /** - * String holding the mail message body. - * @var string - * @access private - */ - var $_message = ''; - - /** - * Flag used to indicated that log lines have been written to the message - * body and the message should be sent on close(). - * @var boolean - * @access private - */ - var $_shouldSend = false; - - /** - * Constructs a new Log_mail object. - * - * Here is how you can customize the mail driver with the conf[] hash : - * $conf['from'] : the mail's "From" header line, - * $conf['subject'] : the mail's "Subject" line. - * - * @param string $name The message's recipients. - * @param string $ident The identity string. - * @param array $conf The configuration array. - * @param int $level Log messages up to and including this level. - * @access public - */ - function Log_mail($name, $ident = '', $conf = array(), - $level = PEAR_LOG_DEBUG) - { - 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->_id = G::encryptOld(microtime()); - $this->_recipients = $name; - $this->_ident = $ident; - $this->_mask = Log::UPTO($level); - - if (!empty($conf['from'])) { - $this->_from = $conf['from']; - } else { - $this->_from = ini_get('sendmail_from'); - } - - if (!empty($conf['subject'])) { - $this->_subject = $conf['subject']; - } - - if (!empty($conf['preamble'])) { - $this->_preamble = $conf['preamble']; - } - - if (!empty($conf['lineFormat'])) { - $this->_lineFormat = str_replace(array_keys($this->_formatMap), - array_values($this->_formatMap), - $conf['lineFormat']); - } - - if (!empty($conf['timeFormat'])) { - $this->_timeFormat = $conf['timeFormat']; - } - - /* register the destructor */ - register_shutdown_function(array(&$this, '_Log_mail')); - } - - /** - * Destructor. Calls close(). - * - * @access private - */ - function _Log_mail() - { - $this->close(); - } - - /** - * Starts a new mail message. - * This is implicitly called by log(), if necessary. - * - * @access public - */ - function open() - { - if (!$this->_opened) { - if (!empty($this->_preamble)) { - $this->_message = $this->_preamble . "\r\n\r\n"; - } - $this->_opened = true; - $_shouldSend = false; - } - - return $this->_opened; - } - - /** - * Closes the message, if it is open, and sends the mail. - * This is implicitly called by the destructor, if necessary. - * - * @access public - */ - function close() - { - if ($this->_opened) { - if ($this->_shouldSend && !empty($this->_message)) { - $headers = "From: $this->_from\r\n"; - $headers .= "User-Agent: Log_mail"; - - if (mail($this->_recipients, $this->_subject, $this->_message, - $headers) == false) { - error_log("Log_mail: Failure executing mail()", 0); - return false; - } - - /* Clear the message string now that the email has been sent. */ - $this->_message = ''; - $this->_shouldSend = false; - } - $this->_opened = false; - } - - return ($this->_opened === false); - } - - /** - * Flushes the log output by forcing the email message to be sent now. - * Events that are logged after flush() is called will be appended to a - * new email message. - * - * @access public - * @since Log 1.8.2 - */ - function flush() - { - /* - * It's sufficient to simply call close() to flush the output. - * The next call to log() will cause the handler to be reopened. - */ - return $this->close(); - } - - /** - * Writes $message to the currently open mail message. - * Calls open(), if necessary. - * - * @param mixed $message String or object containing the message to log. - * @param string $priority The priority of the message. Valid - * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, - * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, - * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. - * @return boolean True on success or false on failure. - * @access public - */ - function log($message, $priority = null) - { - /* If a priority hasn't been specified, use the default value. */ - if ($priority === null) { - $priority = $this->_priority; - } - - /* Abort early if the priority is above the maximum logging level. */ - if (!$this->_isMasked($priority)) { - return false; - } - - /* If the message isn't open and can't be opened, return failure. */ - if (!$this->_opened && !$this->open()) { - return false; - } - - /* Extract the string representation of the message. */ - $message = $this->_extractMessage($message); - - /* Append the string containing the complete log line. */ - $this->_message .= $this->_format($this->_lineFormat, - strftime($this->_timeFormat), - $priority, $message) . "\r\n"; - $this->_shouldSend = true; - - /* Notify observers about this log message. */ - $this->_announce(array('priority' => $priority, 'message' => $message)); - - return true; - } -} diff --git a/gulliver/thirdparty/pear/Log/mcal.php b/gulliver/thirdparty/pear/Log/mcal.php deleted file mode 100644 index f2832cf48..000000000 --- a/gulliver/thirdparty/pear/Log/mcal.php +++ /dev/null @@ -1,179 +0,0 @@ - - * @since Horde 1.3 - * @since Log 1.0 - * @package Log - */ -class Log_mcal extends Log -{ - /** - * holding the calendar specification to connect to. - * @var string - * @access private - */ - var $_calendar = '{localhost/mstore}'; - - /** - * holding the username to use. - * @var string - * @access private - */ - var $_username = ''; - - /** - * holding the password to use. - * @var string - * @access private - */ - var $_password = ''; - - /** - * holding the options to pass to the calendar stream. - * @var integer - * @access private - */ - var $_options = 0; - - /** - * ResourceID of the MCAL stream. - * @var string - * @access private - */ - var $_stream = ''; - - /** - * Integer holding the log facility to use. - * @var string - * @access private - */ - var $_name = LOG_SYSLOG; - - - /** - * Constructs a new Log_mcal object. - * - * @param string $name The category to use for our events. - * @param string $ident The identity string. - * @param array $conf The configuration array. - * @param int $level Log messages up to and including this level. - * @access public - */ - function Log_mcal($name, $ident = '', $conf = array(), - $level = PEAR_LOG_DEBUG) - { - 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->_id = G::encryptOld(microtime()); - $this->_name = $name; - $this->_ident = $ident; - $this->_mask = Log::UPTO($level); - $this->_calendar = $conf['calendar']; - $this->_username = $conf['username']; - $this->_password = $conf['password']; - $this->_options = $conf['options']; - } - - /** - * Opens a calendar stream, if it has not already been - * opened. This is implicitly called by log(), if necessary. - * @access public - */ - function open() - { - if (!$this->_opened) { - $this->_stream = mcal_open($this->_calendar, $this->_username, - $this->_password, $this->_options); - $this->_opened = true; - } - - return $this->_opened; - } - - /** - * Closes the calendar stream, if it is open. - * @access public - */ - function close() - { - if ($this->_opened) { - mcal_close($this->_stream); - $this->_opened = false; - } - - return ($this->_opened === false); - } - - /** - * Logs $message and associated information to the currently open - * calendar stream. Calls open() if necessary. Also passes the - * message along to any Log_observer instances that are observing - * this Log. - * - * @param mixed $message String or object containing the message to log. - * @param string $priority The priority of the message. Valid - * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, - * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, - * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. - * @return boolean True on success or false on failure. - * @access public - */ - function log($message, $priority = null) - { - /* If a priority hasn't been specified, use the default value. */ - if ($priority === null) { - $priority = $this->_priority; - } - - /* Abort early if the priority is above the maximum logging level. */ - if (!$this->_isMasked($priority)) { - return false; - } - - /* If the connection isn't open and can't be opened, return failure. */ - if (!$this->_opened && !$this->open()) { - return false; - } - - /* Extract the string representation of the message. */ - $message = $this->_extractMessage($message); - - $date_str = date('Y:n:j:G:i:s'); - $dates = explode(':', $date_str); - - mcal_event_init($this->_stream); - mcal_event_set_title($this->_stream, $this->_ident); - mcal_event_set_category($this->_stream, $this->_name); - mcal_event_set_description($this->_stream, $message); - mcal_event_add_attribute($this->_stream, 'priority', $priority); - mcal_event_set_start($this->_stream, $dates[0], $dates[1], $dates[2], - $dates[3], $dates[4], $dates[5]); - mcal_event_set_end($this->_stream, $dates[0], $dates[1], $dates[2], - $dates[3], $dates[4], $dates[5]); - mcal_append_event($this->_stream); - - $this->_announce(array('priority' => $priority, 'message' => $message)); - - return true; - } - -} diff --git a/gulliver/thirdparty/pear/Log/mdb2.php b/gulliver/thirdparty/pear/Log/mdb2.php deleted file mode 100644 index 34d35676b..000000000 --- a/gulliver/thirdparty/pear/Log/mdb2.php +++ /dev/null @@ -1,367 +0,0 @@ - - * @author Jon Parise - * @since Log 1.9.0 - * @package Log - */ -class Log_mdb2 extends Log -{ - /** - * Variable containing the DSN information. - * @var mixed - * @access private - */ - var $_dsn = ''; - - /** - * Array containing our set of DB configuration options. - * @var array - * @access private - */ - var $_options = array('persistent' => true); - - /** - * Object holding the database handle. - * @var object - * @access private - */ - var $_db = null; - - /** - * Resource holding the prepared statement handle. - * @var resource - * @access private - */ - var $_statement = null; - - /** - * Flag indicating that we're using an existing database connection. - * @var boolean - * @access private - */ - var $_existingConnection = false; - - /** - * String holding the database table to use. - * @var string - * @access private - */ - var $_table = 'log_table'; - - /** - * String holding the name of the ID sequence. - * @var string - * @access private - */ - var $_sequence = 'log_id'; - - /** - * Maximum length of the $ident string. This corresponds to the size of - * the 'ident' column in the SQL table. - * @var integer - * @access private - */ - var $_identLimit = 16; - - /** - * Set of field types used in the database table. - * @var array - * @access private - */ - var $_types = array( - 'id' => 'integer', - 'logtime' => 'timestamp', - 'ident' => 'text', - 'priority' => 'text', - 'message' => 'clob' - ); - - /** - * Constructs a new sql logging object. - * - * @param string $name The target SQL table. - * @param string $ident The identification field. - * @param array $conf The connection configuration array. - * @param int $level Log messages up to and including this level. - * @access public - */ - function Log_mdb2($name, $ident = '', $conf = array(), - $level = PEAR_LOG_DEBUG) - { - 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->_id = G::encryptOld(microtime()); - $this->_table = $name; - $this->_mask = Log::UPTO($level); - - /* If an options array was provided, use it. */ - if (isset($conf['options']) && is_array($conf['options'])) { - $this->_options = $conf['options']; - } - - /* If a specific sequence name was provided, use it. */ - if (!empty($conf['sequence'])) { - $this->_sequence = $conf['sequence']; - } - - /* If a specific sequence name was provided, use it. */ - if (isset($conf['identLimit'])) { - $this->_identLimit = $conf['identLimit']; - } - - /* Now that the ident limit is confirmed, set the ident string. */ - $this->setIdent($ident); - - /* If an existing database connection was provided, use it. */ - if (isset($conf['db'])) { - $this->_db = &$conf['db']; - $this->_existingConnection = true; - $this->_opened = true; - } elseif (isset($conf['singleton'])) { - $this->_db = &MDB2::singleton($conf['singleton'], $this->_options); - $this->_existingConnection = true; - $this->_opened = true; - } else { - $this->_dsn = $conf['dsn']; - } - } - - /** - * Opens a connection to the database, if it has not already - * been opened. This is implicitly called by log(), if necessary. - * - * @return boolean True on success, false on failure. - * @access public - */ - function open() - { - if (!$this->_opened) { - /* Use the DSN and options to create a database connection. */ - $this->_db = &MDB2::connect($this->_dsn, $this->_options); - if (PEAR::isError($this->_db)) { - return false; - } - - /* Create a prepared statement for repeated use in log(). */ - if (!$this->_prepareStatement()) { - return false; - } - - /* We now consider out connection open. */ - $this->_opened = true; - } - - return $this->_opened; - } - - /** - * Closes the connection to the database if it is still open and we were - * the ones that opened it. It is the caller's responsible to close an - * existing connection that was passed to us via $conf['db']. - * - * @return boolean True on success, false on failure. - * @access public - */ - function close() - { - /* If we have a statement object, free it. */ - if (is_object($this->_statement)) { - $this->_statement->free(); - $this->_statement = null; - } - - /* If we opened the database connection, disconnect it. */ - if ($this->_opened && !$this->_existingConnection) { - $this->_opened = false; - return $this->_db->disconnect(); - } - - return ($this->_opened === false); - } - - /** - * Sets this Log instance's identification string. Note that this - * SQL-specific implementation will limit the length of the $ident string - * to sixteen (16) characters. - * - * @param string $ident The new identification string. - * - * @access public - * @since Log 1.8.5 - */ - function setIdent($ident) - { - $this->_ident = substr($ident, 0, $this->_identLimit); - } - - /** - * Inserts $message to the currently open database. Calls open(), - * if necessary. Also passes the message along to any Log_observer - * instances that are observing this Log. - * - * @param mixed $message String or object containing the message to log. - * @param string $priority The priority of the message. Valid - * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, - * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, - * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. - * @return boolean True on success or false on failure. - * @access public - */ - function log($message, $priority = null) - { - /* If a priority hasn't been specified, use the default value. */ - if ($priority === null) { - $priority = $this->_priority; - } - - /* Abort early if the priority is above the maximum logging level. */ - if (!$this->_isMasked($priority)) { - return false; - } - - /* If the connection isn't open and can't be opened, return failure. */ - if (!$this->_opened && !$this->open()) { - return false; - } - - /* If we don't already have a statement object, create one. */ - if (!is_object($this->_statement) && !$this->_prepareStatement()) { - return false; - } - - /* Extract the string representation of the message. */ - $message = $this->_extractMessage($message); - - /* Build our set of values for this log entry. */ - $values = array( - 'id' => $this->_db->nextId($this->_sequence), - 'logtime' => MDB2_Date::mdbNow(), - 'ident' => $this->_ident, - 'priority' => $priority, - 'message' => $message - ); - - /* Execute the SQL query for this log entry insertion. */ - $this->_db->expectError(MDB2_ERROR_NOSUCHTABLE); - $result = &$this->_statement->execute($values); - $this->_db->popExpect(); - - /* Attempt to handle any errors. */ - if (PEAR::isError($result)) { - /* We can only handle MDB2_ERROR_NOSUCHTABLE errors. */ - if ($result->getCode() != MDB2_ERROR_NOSUCHTABLE) { - return false; - } - - /* Attempt to create the target table. */ - if (!$this->_createTable()) { - return false; - } - - /* Recreate our prepared statement resource. */ - $this->_statement->free(); - if (!$this->_prepareStatement()) { - return false; - } - - /* Attempt to re-execute the insertion query. */ - $result = $this->_statement->execute($values); - if (PEAR::isError($result)) { - return false; - } - } - - $this->_announce(array('priority' => $priority, 'message' => $message)); - - return true; - } - - /** - * Create the log table in the database. - * - * @return boolean True on success or false on failure. - * @access private - */ - function _createTable() - { - $this->_db->loadModule('Manager', null, true); - $result = $this->_db->manager->createTable( - $this->_table, - array( - 'id' => array('type' => $this->_types['id']), - 'logtime' => array('type' => $this->_types['logtime']), - 'ident' => array('type' => $this->_types['ident']), - 'priority' => array('type' => $this->_types['priority']), - 'message' => array('type' => $this->_types['message']) - ) - ); - if (PEAR::isError($result)) { - return false; - } - - $result = $this->_db->manager->createIndex( - $this->_table, - 'unique_id', - array('fields' => array('id' => true), 'unique' => true) - ); - if (PEAR::isError($result)) { - return false; - } - - return true; - } - - /** - * Prepare the SQL insertion statement. - * - * @return boolean True if the statement was successfully created. - * - * @access private - * @since Log 1.9.0 - */ - function _prepareStatement() - { - $this->_statement = &$this->_db->prepare( - 'INSERT INTO ' . $this->_table . - ' (id, logtime, ident, priority, message)' . - ' VALUES(:id, :logtime, :ident, :priority, :message)', - $this->_types, MDB2_PREPARE_MANIP); - - /* Return success if we didn't generate an error. */ - return (PEAR::isError($this->_statement) === false); - } -} diff --git a/gulliver/thirdparty/pear/Log/null.php b/gulliver/thirdparty/pear/Log/null.php deleted file mode 100644 index 20a510566..000000000 --- a/gulliver/thirdparty/pear/Log/null.php +++ /dev/null @@ -1,100 +0,0 @@ - - * @since Log 1.8.2 - * @package Log - * - * @example null.php Using the null handler. - */ -class Log_null extends Log -{ - /** - * Constructs a new Log_null object. - * - * @param string $name Ignored. - * @param string $ident The identity string. - * @param array $conf The configuration array. - * @param int $level Log messages up to and including this level. - * @access public - */ - function Log_null($name, $ident = '', $conf = array(), - $level = PEAR_LOG_DEBUG) - { - 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->_id = G::encryptOld(microtime()); - $this->_ident = $ident; - $this->_mask = Log::UPTO($level); - } - - /** - * Opens the handler. - * - * @access public - * @since Log 1.9.6 - */ - function open() - { - $this->_opened = true; - return true; - } - - /** - * Closes the handler. - * - * @access public - * @since Log 1.9.6 - */ - function close() - { - $this->_opened = false; - return true; - } - - /** - * Simply consumes the log event. The message will still be passed - * along to any Log_observer instances that are observing this Log. - * - * @param mixed $message String or object containing the message to log. - * @param string $priority The priority of the message. Valid - * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, - * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, - * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. - * @return boolean True on success or false on failure. - * @access public - */ - function log($message, $priority = null) - { - /* If a priority hasn't been specified, use the default value. */ - if ($priority === null) { - $priority = $this->_priority; - } - - /* Abort early if the priority is above the maximum logging level. */ - if (!$this->_isMasked($priority)) { - return false; - } - - $this->_announce(array('priority' => $priority, 'message' => $message)); - - return true; - } - -} diff --git a/gulliver/thirdparty/pear/Log/observer.php b/gulliver/thirdparty/pear/Log/observer.php deleted file mode 100644 index 7cbe26369..000000000 --- a/gulliver/thirdparty/pear/Log/observer.php +++ /dev/null @@ -1,143 +0,0 @@ - - * @since Horde 1.3 - * @since Log 1.0 - * @package Log - * - * @example observer_mail.php An example Log_observer implementation. - */ -class Log_observer -{ - /** - * Instance-specific unique identification number. - * - * @var integer - * @access private - */ - var $_id = 0; - - /** - * The minimum priority level of message that we want to hear about. - * PEAR_LOG_EMERG is the highest priority, so we will only hear messages - * with an integer priority value less than or equal to ours. It defaults - * to PEAR_LOG_INFO, which listens to everything except PEAR_LOG_DEBUG. - * - * @var string - * @access private - */ - var $_priority = PEAR_LOG_INFO; - - /** - * Creates a new basic Log_observer instance. - * - * @param integer $priority The highest priority at which to receive - * log event notifications. - * - * @access public - */ - function Log_observer($priority = PEAR_LOG_INFO) - { - $this->_id = $this->encryptOld(microtime()); - $this->_priority = $priority; - } - - /** - * Attempts to return a new concrete Log_observer instance of the requested - * type. - * - * @param string $type The type of concreate Log_observer subclass - * to return. - * @param integer $priority The highest priority at which to receive - * log event notifications. - * @param array $conf Optional associative array of additional - * configuration values. - * - * @return object The newly created concrete Log_observer - * instance, or null on an error. - */ - function &factory($type, $priority = PEAR_LOG_INFO, $conf = array()) - { - $type = strtolower($type); - $class = 'Log_observer_' . $type; - - /* - * If the desired class already exists (because the caller has supplied - * it from some custom location), simply instantiate and return a new - * instance. - */ - if (class_exists($class)) { - $object = &new $class($priority, $conf); - return $object; - } - - /* Support both the new-style and old-style file naming conventions. */ - $newstyle = true; - $classfile = dirname(__FILE__) . '/observer_' . $type . '.php'; - - if (!file_exists($classfile)) { - $classfile = 'Log/' . $type . '.php'; - $newstyle = false; - } - - /* - * 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)) { - /* Support both new-style and old-style construction. */ - if ($newstyle) { - $object = &new $class($priority, $conf); - } else { - $object = &new $class($priority); - } - return $object; - } - - $null = null; - return $null; - } - - /** - * This is a stub method to make sure that Log_Observer classes do - * something when they are notified of a message. The default behavior - * is to just print the message, which is obviously not desireable in - * practically any situation - which is why you need to override this - * method. :) - * - * @param array $event A hash describing the log event. - */ - function notify($event) - { - print_r($event); - } - - 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); - } -} diff --git a/gulliver/thirdparty/pear/Log/sql.php b/gulliver/thirdparty/pear/Log/sql.php deleted file mode 100644 index 9c6777ab2..000000000 --- a/gulliver/thirdparty/pear/Log/sql.php +++ /dev/null @@ -1,308 +0,0 @@ - - * @since Horde 1.3 - * @since Log 1.0 - * @package Log - * - * @example sql.php Using the SQL handler. - */ -class Log_sql extends Log -{ - /** - * Variable containing the DSN information. - * @var mixed - * @access private - */ - var $_dsn = ''; - - /** - * String containing the SQL insertion statement. - * - * @var string - * @access private - */ - var $_sql = ''; - - /** - * Array containing our set of DB configuration options. - * @var array - * @access private - */ - var $_options = array('persistent' => true); - - /** - * Object holding the database handle. - * @var object - * @access private - */ - var $_db = null; - - /** - * Resource holding the prepared statement handle. - * @var resource - * @access private - */ - var $_statement = null; - - /** - * Flag indicating that we're using an existing database connection. - * @var boolean - * @access private - */ - var $_existingConnection = false; - - /** - * String holding the database table to use. - * @var string - * @access private - */ - var $_table = 'log_table'; - - /** - * String holding the name of the ID sequence. - * @var string - * @access private - */ - var $_sequence = 'log_id'; - - /** - * Maximum length of the $ident string. This corresponds to the size of - * the 'ident' column in the SQL table. - * @var integer - * @access private - */ - var $_identLimit = 16; - - - /** - * Constructs a new sql logging object. - * - * @param string $name The target SQL table. - * @param string $ident The identification field. - * @param array $conf The connection configuration array. - * @param int $level Log messages up to and including this level. - * @access public - */ - function Log_sql($name, $ident = '', $conf = array(), - $level = PEAR_LOG_DEBUG) - { - $this->_id = $this->encryptOld(microtime()); - $this->_table = $name; - $this->_mask = Log::UPTO($level); - - /* Now that we have a table name, assign our SQL statement. */ - if (!empty($this->_sql)) { - $this->_sql = $conf['sql']; - } else { - $this->_sql = 'INSERT INTO ' . $this->_table . - ' (id, logtime, ident, priority, message)' . - ' VALUES(?, CURRENT_TIMESTAMP, ?, ?, ?)'; - } - - /* If an options array was provided, use it. */ - if (isset($conf['options']) && is_array($conf['options'])) { - $this->_options = $conf['options']; - } - - /* If a specific sequence name was provided, use it. */ - if (!empty($conf['sequence'])) { - $this->_sequence = $conf['sequence']; - } - - /* If a specific sequence name was provided, use it. */ - if (isset($conf['identLimit'])) { - $this->_identLimit = $conf['identLimit']; - } - - /* Now that the ident limit is confirmed, set the ident string. */ - $this->setIdent($ident); - - /* If an existing database connection was provided, use it. */ - if (isset($conf['db'])) { - $this->_db = &$conf['db']; - $this->_existingConnection = true; - $this->_opened = true; - } else { - $this->_dsn = $conf['dsn']; - } - } - - /** - * Opens a connection to the database, if it has not already - * been opened. This is implicitly called by log(), if necessary. - * - * @return boolean True on success, false on failure. - * @access public - */ - function open() - { - if (!$this->_opened) { - /* Use the DSN and options to create a database connection. */ - $this->_db = &DB::connect($this->_dsn, $this->_options); - if (DB::isError($this->_db)) { - return false; - } - - /* Create a prepared statement for repeated use in log(). */ - if (!$this->_prepareStatement()) { - return false; - } - - /* We now consider out connection open. */ - $this->_opened = true; - } - - return $this->_opened; - } - - /** - * Closes the connection to the database if it is still open and we were - * the ones that opened it. It is the caller's responsible to close an - * existing connection that was passed to us via $conf['db']. - * - * @return boolean True on success, false on failure. - * @access public - */ - function close() - { - if ($this->_opened && !$this->_existingConnection) { - $this->_opened = false; - $this->_db->freePrepared($this->_statement); - return $this->_db->disconnect(); - } - - return ($this->_opened === false); - } - - /** - * Sets this Log instance's identification string. Note that this - * SQL-specific implementation will limit the length of the $ident string - * to sixteen (16) characters. - * - * @param string $ident The new identification string. - * - * @access public - * @since Log 1.8.5 - */ - function setIdent($ident) - { - $this->_ident = substr($ident, 0, $this->_identLimit); - } - - /** - * Inserts $message to the currently open database. Calls open(), - * if necessary. Also passes the message along to any Log_observer - * instances that are observing this Log. - * - * @param mixed $message String or object containing the message to log. - * @param string $priority The priority of the message. Valid - * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, - * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, - * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. - * @return boolean True on success or false on failure. - * @access public - */ - function log($message, $priority = null) - { - /* If a priority hasn't been specified, use the default value. */ - if ($priority === null) { - $priority = $this->_priority; - } - - /* Abort early if the priority is above the maximum logging level. */ - if (!$this->_isMasked($priority)) { - return false; - } - - /* If the connection isn't open and can't be opened, return failure. */ - if (!$this->_opened && !$this->open()) { - return false; - } - - /* If we don't already have our statement object yet, create it. */ - if (!is_object($this->_statement) && !$this->_prepareStatement()) { - return false; - } - - /* Extract the string representation of the message. */ - $message = $this->_extractMessage($message); - - /* Build our set of values for this log entry. */ - $id = $this->_db->nextId($this->_sequence); - $values = array($id, $this->_ident, $priority, $message); - - /* Execute the SQL query for this log entry insertion. */ - $result =& $this->_db->execute($this->_statement, $values); - if (DB::isError($result)) { - return false; - } - - $this->_announce(array('priority' => $priority, 'message' => $message)); - - return true; - } - - /** - * Prepare the SQL insertion statement. - * - * @return boolean True if the statement was successfully created. - * - * @access private - * @since Log 1.9.1 - */ - function _prepareStatement() - { - $this->_statement = $this->_db->prepare($this->_sql); - - /* Return success if we didn't generate an error. */ - return (DB::isError($this->_statement) === false); - } - - 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); - } -} diff --git a/gulliver/thirdparty/pear/Log/sqlite.php b/gulliver/thirdparty/pear/Log/sqlite.php deleted file mode 100644 index 0473e069f..000000000 --- a/gulliver/thirdparty/pear/Log/sqlite.php +++ /dev/null @@ -1,239 +0,0 @@ - - * @author Jon Parise - * @since Log 1.8.3 - * @package Log - * - * @example sqlite.php Using the Sqlite handler. - */ -class Log_sqlite extends Log -{ - /** - * Array containing the connection defaults - * @var array - * @access private - */ - var $_options = array('mode' => 0666, - 'persistent' => false); - - /** - * Object holding the database handle. - * @var object - * @access private - */ - var $_db = null; - - /** - * Flag indicating that we're using an existing database connection. - * @var boolean - * @access private - */ - var $_existingConnection = false; - - /** - * String holding the database table to use. - * @var string - * @access private - */ - var $_table = 'log_table'; - - - /** - * Constructs a new sql logging object. - * - * @param string $name The target SQL table. - * @param string $ident The identification field. - * @param mixed $conf Can be an array of configuration options used - * to open a new database connection - * or an already opened sqlite connection. - * @param int $level Log messages up to and including this level. - * @access public - */ - function Log_sqlite($name, $ident = '', &$conf, $level = PEAR_LOG_DEBUG) - { - $this->_id = $this->encryptOld(microtime()); - $this->_table = $name; - $this->_ident = $ident; - $this->_mask = Log::UPTO($level); - - if (is_array($conf)) { - foreach ($conf as $k => $opt) { - $this->_options[$k] = $opt; - } - } else { - // If an existing database connection was provided, use it. - $this->_db =& $conf; - $this->_existingConnection = true; - } - } - - /** - * Opens a connection to the database, if it has not already - * been opened. This is implicitly called by log(), if necessary. - * - * @return boolean True on success, false on failure. - * @access public - */ - function open() - { - if (is_resource($this->_db)) { - $this->_opened = true; - return $this->_createTable(); - } else { - /* Set the connection function based on the 'persistent' option. */ - if (empty($this->_options['persistent'])) { - $connectFunction = 'sqlite_open'; - } else { - $connectFunction = 'sqlite_popen'; - } - - /* Attempt to connect to the database. */ - if ($this->_db = $connectFunction($this->_options['filename'], - (int)$this->_options['mode'], - $error)) { - $this->_opened = true; - return $this->_createTable(); - } - } - - return $this->_opened; - } - - /** - * Closes the connection to the database if it is still open and we were - * the ones that opened it. It is the caller's responsible to close an - * existing connection that was passed to us via $conf['db']. - * - * @return boolean True on success, false on failure. - * @access public - */ - function close() - { - /* We never close existing connections. */ - if ($this->_existingConnection) { - return false; - } - - if ($this->_opened) { - $this->_opened = false; - sqlite_close($this->_db); - } - - return ($this->_opened === false); - } - - /** - * Inserts $message to the currently open database. Calls open(), - * if necessary. Also passes the message along to any Log_observer - * instances that are observing this Log. - * - * @param mixed $message String or object containing the message to log. - * @param string $priority The priority of the message. Valid - * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, - * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, - * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. - * @return boolean True on success or false on failure. - * @access public - */ - function log($message, $priority = null) - { - /* If a priority hasn't been specified, use the default value. */ - if ($priority === null) { - $priority = $this->_priority; - } - - /* Abort early if the priority is above the maximum logging level. */ - if (!$this->_isMasked($priority)) { - return false; - } - - /* If the connection isn't open and can't be opened, return failure. */ - if (!$this->_opened && !$this->open()) { - return false; - } - - // Extract the string representation of the message. - $message = $this->_extractMessage($message); - - // Build the SQL query for this log entry insertion. - $q = sprintf('INSERT INTO [%s] (logtime, ident, priority, message) ' . - "VALUES ('%s', '%s', %d, '%s')", - $this->_table, - strftime('%Y-%m-%d %H:%M:%S', time()), - sqlite_escape_string($this->_ident), - $priority, - sqlite_escape_string($message)); - if (!($res = @sqlite_unbuffered_query($this->_db, $q))) { - return false; - } - $this->_announce(array('priority' => $priority, 'message' => $message)); - - return true; - } - - /** - * Checks whether the log table exists and creates it if necessary. - * - * @return boolean True on success or false on failure. - * @access private - */ - function _createTable() - { - $q = "SELECT name FROM sqlite_master WHERE name='" . $this->_table . - "' AND type='table'"; - - $res = sqlite_query($this->_db, $q); - - if (sqlite_num_rows($res) == 0) { - $q = 'CREATE TABLE [' . $this->_table . '] (' . - 'id INTEGER PRIMARY KEY NOT NULL, ' . - 'logtime NOT NULL, ' . - 'ident CHAR(16) NOT NULL, ' . - 'priority INT NOT NULL, ' . - 'message)'; - - if (!($res = sqlite_unbuffered_query($this->_db, $q))) { - return false; - } - } - - return true; - } - - 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); - } - -} diff --git a/gulliver/thirdparty/pear/Log/syslog.php b/gulliver/thirdparty/pear/Log/syslog.php deleted file mode 100644 index 93ce84efc..000000000 --- a/gulliver/thirdparty/pear/Log/syslog.php +++ /dev/null @@ -1,193 +0,0 @@ - - * @author Jon Parise - * @since Horde 1.3 - * @since Log 1.0 - * @package Log - * - * @example syslog.php Using the syslog handler. - */ -class Log_syslog extends Log -{ - /** - * Integer holding the log facility to use. - * @var integer - * @access private - */ - var $_name = LOG_SYSLOG; - - /** - * Should we inherit the current syslog connection for this process, or - * should we call openlog() to start a new syslog connection? - * @var boolean - * @access private - */ - var $_inherit = false; - - /** - * Constructs a new syslog object. - * - * @param string $name The syslog facility. - * @param string $ident The identity string. - * @param array $conf The configuration array. - * @param int $level Log messages up to and including this level. - * @access public - */ - function Log_syslog($name, $ident = '', $conf = array(), - $level = PEAR_LOG_DEBUG) - { - /* Ensure we have a valid integer value for $name. */ - if (empty($name) || !is_int($name)) { - $name = LOG_SYSLOG; - } - - if (isset($conf['inherit'])) { - $this->_inherit = $conf['inherit']; - $this->_opened = $this->_inherit; - } - - $this->_id = $this->encryptOld(microtime()); - $this->_name = $name; - $this->_ident = $ident; - $this->_mask = Log::UPTO($level); - } - - /** - * Opens a connection to the system logger, if it has not already - * been opened. This is implicitly called by log(), if necessary. - * @access public - */ - function open() - { - if (!$this->_opened) { - $this->_opened = openlog($this->_ident, LOG_PID, $this->_name); - } - - return $this->_opened; - } - - /** - * Closes the connection to the system logger, if it is open. - * @access public - */ - function close() - { - if ($this->_opened && !$this->_inherit) { - closelog(); - $this->_opened = false; - } - - return true; - } - - /** - * Sends $message to the currently open syslog connection. Calls - * open() if necessary. Also passes the message along to any Log_observer - * instances that are observing this Log. - * - * @param mixed $message String or object containing the message to log. - * @param int $priority (optional) The priority of the message. Valid - * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, - * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, - * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. - * @return boolean True on success or false on failure. - * @access public - */ - function log($message, $priority = null) - { - /* If a priority hasn't been specified, use the default value. */ - if ($priority === null) { - $priority = $this->_priority; - } - - /* Abort early if the priority is above the maximum logging level. */ - if (!$this->_isMasked($priority)) { - return false; - } - - /* If the connection isn't open and can't be opened, return failure. */ - if (!$this->_opened && !$this->open()) { - return false; - } - - /* Extract the string representation of the message. */ - $message = $this->_extractMessage($message); - - /* Build a syslog priority value based on our current configuration. */ - $priority = $this->_toSyslog($priority); - if ($this->_inherit) { - $priority |= $this->_name; - } - - if (!syslog($priority, $message)) { - return false; - } - - $this->_announce(array('priority' => $priority, 'message' => $message)); - - return true; - } - - /** - * Converts a PEAR_LOG_* constant into a syslog LOG_* constant. - * - * This function exists because, under Windows, not all of the LOG_* - * constants have unique values. Instead, the PEAR_LOG_* were introduced - * for global use, with the conversion to the LOG_* constants kept local to - * to the syslog driver. - * - * @param int $priority PEAR_LOG_* value to convert to LOG_* value. - * - * @return The LOG_* representation of $priority. - * - * @access private - */ - function _toSyslog($priority) - { - static $priorities = array( - PEAR_LOG_EMERG => LOG_EMERG, - PEAR_LOG_ALERT => LOG_ALERT, - PEAR_LOG_CRIT => LOG_CRIT, - PEAR_LOG_ERR => LOG_ERR, - PEAR_LOG_WARNING => LOG_WARNING, - PEAR_LOG_NOTICE => LOG_NOTICE, - PEAR_LOG_INFO => LOG_INFO, - PEAR_LOG_DEBUG => LOG_DEBUG - ); - - /* If we're passed an unknown priority, default to LOG_INFO. */ - if (!is_int($priority) || !in_array($priority, $priorities)) { - return LOG_INFO; - } - - return $priorities[$priority]; - } - - 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); - } - -} diff --git a/gulliver/thirdparty/pear/Log/win.php b/gulliver/thirdparty/pear/Log/win.php deleted file mode 100644 index 1f7d1ae62..000000000 --- a/gulliver/thirdparty/pear/Log/win.php +++ /dev/null @@ -1,283 +0,0 @@ - - * @since Log 1.7.0 - * @package Log - * - * @example win.php Using the window handler. - */ -class Log_win extends Log -{ - /** - * The name of the output window. - * @var string - * @access private - */ - var $_name = 'LogWindow'; - - /** - * The title of the output window. - * @var string - * @access private - */ - var $_title = 'Log Output Window'; - - /** - * Mapping of log priorities to styles. - * @var array - * @access private - */ - var $_styles = array( - PEAR_LOG_EMERG => 'color: red;', - PEAR_LOG_ALERT => 'color: orange;', - PEAR_LOG_CRIT => 'color: yellow;', - PEAR_LOG_ERR => 'color: green;', - PEAR_LOG_WARNING => 'color: blue;', - PEAR_LOG_NOTICE => 'color: indigo;', - PEAR_LOG_INFO => 'color: violet;', - PEAR_LOG_DEBUG => 'color: black;' - ); - - /** - * String buffer that holds line that are pending output. - * @var array - * @access private - */ - var $_buffer = array(); - - /** - * Constructs a new Log_win object. - * - * @param string $name Ignored. - * @param string $ident The identity string. - * @param array $conf The configuration array. - * @param int $level Log messages up to and including this level. - * @access public - */ - function Log_win($name, $ident = '', $conf = array(), - $level = PEAR_LOG_DEBUG) - { - $this->_id = $this->encryptOld(microtime()); - $this->_name = $name; - $this->_ident = $ident; - $this->_mask = Log::UPTO($level); - - if (isset($conf['title'])) { - $this->_title = $conf['title']; - } - if (isset($conf['styles']) && is_array($conf['styles'])) { - $this->_styles = $conf['styles']; - } - if (isset($conf['colors']) && is_array($conf['colors'])) { - foreach ($conf['colors'] as $level => $color) { - $this->_styles[$level] .= "color: $color;"; - } - } - - register_shutdown_function(array(&$this, '_Log_win')); - } - - /** - * Destructor - */ - function _Log_win() - { - if ($this->_opened || (count($this->_buffer) > 0)) { - $this->close(); - } - } - - /** - * The first time open() is called, it will open a new browser window and - * prepare it for output. - * - * This is implicitly called by log(), if necessary. - * - * @access public - */ - function open() - { - if (!$this->_opened) { - $win = $this->_name; - $styles = $this->_styles; - - if (!empty($this->_ident)) { - $identHeader = "$win.document.writeln('Ident')"; - } else { - $identHeader = ''; - } - - echo <<< EOT - -EOT; - $this->_opened = true; - } - - return $this->_opened; - } - - /** - * Closes the output stream if it is open. If there are still pending - * lines in the output buffer, the output window will be opened so that - * the buffer can be drained. - * - * @access public - */ - function close() - { - /* - * If there are still lines waiting to be written, open the output - * window so that we can drain the buffer. - */ - if (!$this->_opened && (count($this->_buffer) > 0)) { - $this->open(); - } - - if ($this->_opened) { - $this->_writeln(''); - $this->_writeln(''); - $this->_opened = false; - } - - return ($this->_opened === false); - } - - /** - * Writes a single line of text to the output window. - * - * @param string $line The line of text to write. - * - * @access private - */ - function _writeln($line) - { - /* Add this line to our output buffer. */ - $this->_buffer[] = $line; - - /* Buffer the output until this page's headers have been sent. */ - if (!headers_sent()) { - return; - } - - /* If we haven't already opened the output window, do so now. */ - if (!$this->_opened && !$this->open()) { - return false; - } - - /* Drain the buffer to the output window. */ - $win = $this->_name; - foreach ($this->_buffer as $line) { - echo "\n"; - } - - /* Now that the buffer has been drained, clear it. */ - $this->_buffer = array(); - } - - /** - * Logs $message to the output window. The message is also passed along - * to any Log_observer instances that are observing this Log. - * - * @param mixed $message String or object containing the message to log. - * @param string $priority The priority of the message. Valid - * values are: PEAR_LOG_EMERG, PEAR_LOG_ALERT, - * PEAR_LOG_CRIT, PEAR_LOG_ERR, PEAR_LOG_WARNING, - * PEAR_LOG_NOTICE, PEAR_LOG_INFO, and PEAR_LOG_DEBUG. - * @return boolean True on success or false on failure. - * @access public - */ - function log($message, $priority = null) - { - /* If a priority hasn't been specified, use the default value. */ - if ($priority === null) { - $priority = $this->_priority; - } - - /* Abort early if the priority is above the maximum logging level. */ - if (!$this->_isMasked($priority)) { - return false; - } - - /* Extract the string representation of the message. */ - $message = $this->_extractMessage($message); - $message = preg_replace('/\r\n|\n|\r/', '
', $message); - - list($usec, $sec) = explode(' ', microtime()); - - /* Build the output line that contains the log entry row. */ - $line = ''; - $line .= sprintf('%s.%s', - strftime('%H:%M:%S', $sec), substr($usec, 2, 2)); - if (!empty($this->_ident)) { - $line .= '' . $this->_ident . ''; - } - $line .= '' . ucfirst($this->priorityToString($priority)) . ''; - $line .= sprintf('%s', $priority, $message); - $line .= ''; - - $this->_writeln($line); - - $this->_announce(array('priority' => $priority, 'message' => $message)); - - return true; - } - - 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); - } - -} diff --git a/gulliver/thirdparty/pear/Net/CheckIP.php b/gulliver/thirdparty/pear/Net/CheckIP.php deleted file mode 100644 index e7309db67..000000000 --- a/gulliver/thirdparty/pear/Net/CheckIP.php +++ /dev/null @@ -1,80 +0,0 @@ - -* -* @author Martin Jansen -* @author Guido Haeger -* @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; - } -} -?> diff --git a/gulliver/thirdparty/pear/Net/Curl.php b/gulliver/thirdparty/pear/Net/Curl.php deleted file mode 100644 index ef9ceb5e2..000000000 --- a/gulliver/thirdparty/pear/Net/Curl.php +++ /dev/null @@ -1,876 +0,0 @@ - - * @author Sterling Hughes - * @author Joe Stump - * @author Philippe Jausions - * @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 - * @author Sterling Hughes - * @author Joe Stump - * @author Philippe Jausions - * @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 - * @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. - * - * - * fields = array('foo' => '1', 'bar' => 'apple'); - * $result = $curl->execute(); - * if (!PEAR::isError($result)) { - * echo $result; - * } - * ?> - * - * - * @access public - * @author Sterling Hughes - * @author Joe Stump - * @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: - * - * - * create(); - * if (!PEAR::isError($check)) { - * $curl->setOption(CURLOPT_FOO, 'bar'); - * $result = $curl->execute(); - * if (!PEAR::isError($result)) { - * echo $result; - * } - * } - * - * ?> - * - * - * @param int $option cURL constant (ie. CURLOPT_URL) - * @param mixed $value The option's value - * - * @author Joe Stump - * @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 - * @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 - * @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 - * @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 - * @return void - * @deprecated - */ - function verbose_all() - { - $this->verboseAll(); - PEAR::raiseError('Net_Curl::verbose_all() is deprecated! Please use Net_Curl::verboseAll()'."
\n", null, PEAR_ERROR_PRINT); - } - // }}} - - // {{{ close() - /** - * Closes the curl transfer and finishes the object (kinda ;) - * - * @access public - * @author Sterling Hughes - * @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 - * @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!
\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 - * @see Net_Curl::close() - */ - function __destruct() - { - $this->close(); - } - // }}} -} - -?> diff --git a/gulliver/thirdparty/pear/Net/DIME.php b/gulliver/thirdparty/pear/Net/DIME.php deleted file mode 100644 index 1eaf321b8..000000000 --- a/gulliver/thirdparty/pear/Net/DIME.php +++ /dev/null @@ -1,647 +0,0 @@ - | -// | Ralf Hofmann | -// +----------------------------------------------------------------------+ -// -// $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 , - * Ralf Hofmann - * @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; - } -} -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/Net/FTP.php b/gulliver/thirdparty/pear/Net/FTP.php deleted file mode 100644 index 851c1c905..000000000 --- a/gulliver/thirdparty/pear/Net/FTP.php +++ /dev/null @@ -1,2346 +0,0 @@ - - * @author Jorrit Schippers - * @copyright 1997-2008 The PHP Group - * @license http://www.php.net/license/3_0.txt PHP License 3.0 - * @version CVS: $Id: FTP.php,v 1.53.2.10 2008/05/19 18:01:08 jschippers Exp $ - * @link http://pear.php.net/package/Net_FTP - * @since File available since Release 0.0.1 - */ - -/** - * Include PEAR.php to obtain the PEAR base class - */ -require_once 'PEAR.php'; - -/** - * Option to let the ls() method return only files. - * - * @since 1.3 - * @name NET_FTP_FILES_ONLY - * @see Net_FTP::ls() - */ -define('NET_FTP_FILES_ONLY', 0, true); - -/** - * Option to let the ls() method return only directories. - * - * @since 1.3 - * @name NET_FTP_DIRS_ONLY - * @see Net_FTP::ls() - */ -define('NET_FTP_DIRS_ONLY', 1, true); - -/** - * Option to let the ls() method return directories and files (default). - * - * @since 1.3 - * @name NET_FTP_DIRS_FILES - * @see Net_FTP::ls() - */ -define('NET_FTP_DIRS_FILES', 2, true); - -/** - * Option to let the ls() method return the raw directory listing from ftp_rawlist() - * - * @since 1.3 - * @name NET_FTP_RAWLIST - * @see Net_FTP::ls() - */ -define('NET_FTP_RAWLIST', 3, true); - -/** - * Error code to indicate a failed connection - * This error code indicates, that the connection you tryed to set up - * could not be established. Check your connection settings (host & port)! - * - * @since 1.3 - * @name NET_FTP_ERR_CONNECT_FAILED - * @see Net_FTP::connect() - */ -define('NET_FTP_ERR_CONNECT_FAILED', -1); - -/** - * Error code to indicate a failed login - * This error code indicates, that the login to the FTP server failed. Check - * your user data (username & password). - * - * @since 1.3 - * @name NET_FTP_ERR_LOGIN_FAILED - * @see Net_FTP::login() - */ -define('NET_FTP_ERR_LOGIN_FAILED', -2); - -/** - * Error code to indicate a failed directory change - * The cd() method failed. Ensure that the directory you wanted to access exists. - * - * @since 1.3 - * @name NET_FTP_ERR_DIRCHANGE_FAILED - * @see Net_FTP::cd() - */ -define('NET_FTP_ERR_DIRCHANGE_FAILED', 2); // Compatibillity reasons! - -/** - * Error code to indicate that Net_FTP could not determine the current path - * The cwd() method failed and could not determine the path you currently reside - * in on the FTP server. - * - * @since 1.3 - * @name NET_FTP_ERR_DETERMINEPATH_FAILED - * @see Net_FTP::pwd() - */ -define('NET_FTP_ERR_DETERMINEPATH_FAILED', 4); // Compatibillity reasons! - -/** - * Error code to indicate that the creation of a directory failed - * The directory you tryed to create could not be created. Check the - * access rights on the parent directory! - * - * @since 1.3 - * @name NET_FTP_ERR_CREATEDIR_FAILED - * @see Net_FTP::mkdir() - */ -define('NET_FTP_ERR_CREATEDIR_FAILED', -4); - -/** - * Error code to indicate that the EXEC execution failed. - * The execution of a command using EXEC failed. Ensure, that your - * FTP server supports the EXEC command. - * - * @since 1.3 - * @name NET_FTP_ERR_EXEC_FAILED - * @see Net_FTP::execute() - */ -define('NET_FTP_ERR_EXEC_FAILED', -5); - -/** - * Error code to indicate that the SITE command failed. - * The execution of a command using SITE failed. Ensure, that your - * FTP server supports the SITE command. - * - * @since 1.3 - * @name NET_FTP_ERR_SITE_FAILED - * @see Net_FTP::site() - */ -define('NET_FTP_ERR_SITE_FAILED', -6); - -/** - * Error code to indicate that the CHMOD command failed. - * The execution of CHMOD failed. Ensure, that your - * FTP server supports the CHMOD command and that you have the appropriate - * access rights to use CHMOD. - * - * @since 1.3 - * @name NET_FTP_ERR_CHMOD_FAILED - * @see Net_FTP::chmod() - */ -define('NET_FTP_ERR_CHMOD_FAILED', -7); - -/** - * Error code to indicate that a file rename failed - * The renaming of a file on the server failed. Ensure that you have the - * appropriate access rights to rename the file. - * - * @since 1.3 - * @name NET_FTP_ERR_RENAME_FAILED - * @see Net_FTP::rename() - */ -define('NET_FTP_ERR_RENAME_FAILED', -8); - -/** - * Error code to indicate that the MDTM command failed - * The MDTM command is not supported for directories. Ensure that you gave - * a file path to the mdtm() method, not a directory path. - * - * @since 1.3 - * @name NET_FTP_ERR_MDTMDIR_UNSUPPORTED - * @see Net_FTP::mdtm() - */ -define('NET_FTP_ERR_MDTMDIR_UNSUPPORTED', -9); - -/** - * Error code to indicate that the MDTM command failed - * The MDTM command failed. Ensure that your server supports the MDTM command. - * - * @since 1.3 - * @name NET_FTP_ERR_MDTM_FAILED - * @see Net_FTP::mdtm() - */ -define('NET_FTP_ERR_MDTM_FAILED', -10); - -/** - * Error code to indicate that a date returned by the server was misformated - * A date string returned by your server seems to be missformated and could not be - * parsed. Check that the server is configured correctly. If you're sure, please - * send an email to the auhtor with a dumped output of - * $ftp->ls('./', NET_FTP_RAWLIST); to get the date format supported. - * - * @since 1.3 - * @name NET_FTP_ERR_DATEFORMAT_FAILED - * @see Net_FTP::mdtm(), Net_FTP::ls() - */ -define('NET_FTP_ERR_DATEFORMAT_FAILED', -11); - -/** - * Error code to indicate that the SIZE command failed - * The determination of the filesize of a file failed. Ensure that your server - * supports the SIZE command. - * - * @since 1.3 - * @name NET_FTP_ERR_SIZE_FAILED - * @see Net_FTP::size() - */ -define('NET_FTP_ERR_SIZE_FAILED', -12); - -/** - * Error code to indicate that a local file could not be overwritten - * You specified not to overwrite files. Therefore the local file has not been - * overwriten. If you want to get the file overwriten, please set the option to - * do so. - * - * @since 1.3 - * @name NET_FTP_ERR_OVERWRITELOCALFILE_FORBIDDEN - * @see Net_FTP::get(), Net_FTP::getRecursive() - */ -define('NET_FTP_ERR_OVERWRITELOCALFILE_FORBIDDEN', -13); - -/** - * Error code to indicate that a local file could not be overwritten - * Also you specified to overwrite the local file you want to download to, - * it has not been possible to do so. Check that you have the appropriate access - * rights on the local file to overwrite it. - * - * @since 1.3 - * @name NET_FTP_ERR_OVERWRITELOCALFILE_FAILED - * @see Net_FTP::get(), Net_FTP::getRecursive() - */ -define('NET_FTP_ERR_OVERWRITELOCALFILE_FAILED', -14); - -/** - * Error code to indicate that the file you wanted to upload does not exist - * The file you tried to upload does not exist. Ensure that it exists. - * - * @since 1.3 - * @name NET_FTP_ERR_LOCALFILENOTEXIST - * @see Net_FTP::put(), Net_FTP::putRecursive() - */ -define('NET_FTP_ERR_LOCALFILENOTEXIST', -15); - -/** - * Error code to indicate that a remote file could not be overwritten - * You specified not to overwrite files. Therefore the remote file has not been - * overwriten. If you want to get the file overwriten, please set the option to - * do so. - * - * @since 1.3 - * @name NET_FTP_ERR_OVERWRITEREMOTEFILE_FORBIDDEN - * @see Net_FTP::put(), Net_FTP::putRecursive() - */ -define('NET_FTP_ERR_OVERWRITEREMOTEFILE_FORBIDDEN', -16); - -/** - * Error code to indicate that the upload of a file failed - * The upload you tried failed. Ensure that you have appropriate access rights - * to upload the desired file. - * - * @since 1.3 - * @name NET_FTP_ERR_UPLOADFILE_FAILED - * @see Net_FTP::put(), Net_FTP::putRecursive() - */ -define('NET_FTP_ERR_UPLOADFILE_FAILED', -17); - -/** - * Error code to indicate that you specified an incorrect directory path - * The remote path you specified seems not to be a directory. Ensure that - * the path you specify is a directory and that the path string ends with - * a /. - * - * @since 1.3 - * @name NET_FTP_ERR_REMOTEPATHNODIR - * @see Net_FTP::putRecursive(), Net_FTP::getRecursive() - */ -define('NET_FTP_ERR_REMOTEPATHNODIR', -18); - -/** - * Error code to indicate that you specified an incorrect directory path - * The local path you specified seems not to be a directory. Ensure that - * the path you specify is a directory and that the path string ends with - * a /. - * - * @since 1.3 - * @name NET_FTP_ERR_LOCALPATHNODIR - * @see Net_FTP::putRecursive(), Net_FTP::getRecursive() - */ -define('NET_FTP_ERR_LOCALPATHNODIR', -19); - -/** - * Error code to indicate that a local directory failed to be created - * You tried to create a local directory through getRecursive() method, - * which has failed. Ensure that you have the appropriate access rights - * to create it. - * - * @since 1.3 - * @name NET_FTP_ERR_CREATELOCALDIR_FAILED - * @see Net_FTP::getRecursive() - */ -define('NET_FTP_ERR_CREATELOCALDIR_FAILED', -20); - -/** - * Error code to indicate that the provided hostname was incorrect - * The hostname you provided was invalid. Ensure to provide either a - * full qualified domain name or an IP address. - * - * @since 1.3 - * @name NET_FTP_ERR_HOSTNAMENOSTRING - * @see Net_FTP::setHostname() - */ -define('NET_FTP_ERR_HOSTNAMENOSTRING', -21); - -/** - * Error code to indicate that the provided port was incorrect - * The port number you provided was invalid. Ensure to provide either a - * a numeric port number greater zero. - * - * @since 1.3 - * @name NET_FTP_ERR_PORTLESSZERO - * @see Net_FTP::setPort() - */ -define('NET_FTP_ERR_PORTLESSZERO', -22); - -/** - * Error code to indicate that you provided an invalid mode constant - * The mode constant you provided was invalid. You may only provide - * FTP_ASCII or FTP_BINARY. - * - * @since 1.3 - * @name NET_FTP_ERR_NOMODECONST - * @see Net_FTP::setMode() - */ -define('NET_FTP_ERR_NOMODECONST', -23); - -/** - * Error code to indicate that you provided an invalid timeout - * The timeout you provided was invalid. You have to provide a timeout greater - * or equal to zero. - * - * @since 1.3 - * @name NET_FTP_ERR_TIMEOUTLESSZERO - * @see Net_FTP::Net_FTP(), Net_FTP::setTimeout() - */ -define('NET_FTP_ERR_TIMEOUTLESSZERO', -24); - -/** - * Error code to indicate that you provided an invalid timeout - * An error occured while setting the timeout. Ensure that you provide a - * valid integer for the timeount and that your PHP installation works - * correctly. - * - * @since 1.3 - * @name NET_FTP_ERR_SETTIMEOUT_FAILED - * @see Net_FTP::Net_FTP(), Net_FTP::setTimeout() - */ -define('NET_FTP_ERR_SETTIMEOUT_FAILED', -25); - -/** - * Error code to indicate that the provided extension file doesn't exist - * The provided extension file does not exist. Ensure to provided an - * existant extension file. - * - * @since 1.3 - * @name NET_FTP_ERR_EXTFILENOTEXIST - * @see Net_FTP::getExtensionsFile() - */ -define('NET_FTP_ERR_EXTFILENOTEXIST', -26); - -/** - * Error code to indicate that the provided extension file is not readable - * The provided extension file is not readable. Ensure to have sufficient - * access rights for it. - * - * @since 1.3 - * @name NET_FTP_ERR_EXTFILEREAD_FAILED - * @see Net_FTP::getExtensionsFile() - */ -define('NET_FTP_ERR_EXTFILEREAD_FAILED', -27); - -/** - * Error code to indicate that the deletion of a file failed - * The specified file could not be deleted. Ensure to have sufficient - * access rights to delete the file. - * - * @since 1.3 - * @name NET_FTP_ERR_EXTFILEREAD_FAILED - * @see Net_FTP::rm() - */ -define('NET_FTP_ERR_DELETEFILE_FAILED', -28); - -/** - * Error code to indicate that the deletion of a directory faild - * The specified file could not be deleted. Ensure to have sufficient - * access rights to delete the file. - * - * @since 1.3 - * @name NET_FTP_ERR_EXTFILEREAD_FAILED - * @see Net_FTP::rm() - */ -define('NET_FTP_ERR_DELETEDIR_FAILED', -29); - -/** - * Error code to indicate that the directory listing failed - * PHP could not list the directory contents on the server. Ensure - * that your server is configured appropriate. - * - * @since 1.3 - * @name NET_FTP_ERR_RAWDIRLIST_FAILED - * @see Net_FTP::ls() - */ -define('NET_FTP_ERR_RAWDIRLIST_FAILED', -30); - -/** - * Error code to indicate that the directory listing failed - * The directory listing format your server uses seems not to - * be supported by Net_FTP. Please send the output of the - * call ls('./', NET_FTP_RAWLIST); to the author of this - * class to get it supported. - * - * @since 1.3 - * @name NET_FTP_ERR_DIRLIST_UNSUPPORTED - * @see Net_FTP::ls() - */ -define('NET_FTP_ERR_DIRLIST_UNSUPPORTED', -31); - -/** - * Error code to indicate failed disconnecting - * This error code indicates, that disconnection was not possible. - * - * @since 1.3 - * @name NET_FTP_ERR_DISCONNECT_FAILED - * @see Net_FTP::disconnect() - */ -define('NET_FTP_ERR_DISCONNECT_FAILED', -32); - -/** - * Error code to indicate that the username you provided was invalid. - * Check that you provided a non-empty string as the username. - * - * @since 1.3 - * @name NET_FTP_ERR_USERNAMENOSTRING - * @see Net_FTP::setUsername() - */ -define('NET_FTP_ERR_USERNAMENOSTRING', -33); - -/** - * Error code to indicate that the username you provided was invalid. - * Check that you provided a non-empty string as the username. - * - * @since 1.3 - * @name NET_FTP_ERR_PASSWORDNOSTRING - * @see Net_FTP::setPassword() - */ -define('NET_FTP_ERR_PASSWORDNOSTRING', -34); - -/** - * Error code to indicate that the provided extension file is not loadable - * The provided extension file is not loadable. Ensure to have a correct file - * syntax. - * - * @since 1.3.3 - * @name NET_FTP_ERR_EXTFILELOAD_FAILED - * @see Net_FTP::getExtensionsFile() - */ -define('NET_FTP_ERR_EXTFILELOAD_FAILED', -35); - -/** - * Class for comfortable FTP-communication - * - * This class provides comfortable communication with FTP-servers. You may do - * everything enabled by the PHP-FTP-extension and further functionalities, like - * recursive-deletion, -up- and -download. Another feature is to create directories - * recursively. - * - * @category Networking - * @package FTP - * @author Tobias Schlitt - * @author Jorrit Schippers - * @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 0.0.1 - * @access public - */ -class Net_FTP extends PEAR -{ - const mkdir = 'mkdir'; - /** - * The host to connect to - * - * @access private - * @var string - */ - var $_hostname; - - /** - * The port for ftp-connection (standard is 21) - * - * @access private - * @var int - */ - var $_port = 21; - - /** - * The username for login - * - * @access private - * @var string - */ - var $_username; - - /** - * The password for login - * - * @access private - * @var string - */ - var $_password; - - /** - * Determine whether to use passive-mode (true) or active-mode (false) - * - * @access private - * @var bool - */ - var $_passv; - - /** - * The standard mode for ftp-transfer - * - * @access private - * @var int - */ - var $_mode = FTP_BINARY; - - /** - * This holds the handle for the ftp-connection - * - * @access private - * @var resource - */ - var $_handle; - - /** - * Contains the timeout for FTP operations - * - * @access private - * @var int - * @since 1.3 - */ - var $_timeout = 90; - - /** - * Saves file-extensions for ascii- and binary-mode - * - * The array contains 2 sub-arrays ("ascii" and "binary"), which both contain - * file-extensions without the "." (".php" = "php"). - * - * @access private - * @var array - */ - var $_file_extensions; - - /** - * ls match - * Matches the ls entries against a regex and maps the resulting array to - * speaking names - * - * The values are set in the constructor because of line length constaints. - * - * Typical lines for the Windows format: - * 07-05-07 08:40AM 4701 SomeFile.ext - * 04-29-07 10:28PM SomeDir - * - * @access private - * @var array - * @since 1.3 - */ - var $_ls_match = null; - - /** - * matcher - * Stores the matcher for the current connection - * - * @access private - * @var array - * @since 1.3 - */ - var $_matcher = null; - - /** - * Holds all Net_FTP_Observer objects - * that wish to be notified of new messages. - * - * @var array - * @access private - * @since 1.3 - */ - var $_listeners = array(); - - /** - * This generates a new FTP-Object. The FTP-connection will not be established, - * yet. - * You can leave $host and $port blank, if you want. The $host will not be set - * and the $port will be left at 21. You have to set the $host manualy before - * trying to connect or with the connect() method. - * - * @param string $host (optional) The hostname - * @param int $port (optional) The port - * @param int $timeout (optional) Sets the standard timeout - * - * @access public - * @return void - * @see Net_FTP::setHostname(), Net_FTP::setPort(), Net_FTP::connect() - */ - function Net_FTP($host = null, $port = null, $timeout = 90) - { - $this->PEAR(); - if (isset($host)) { - $this->setHostname($host); - } - if (isset($port)) { - $this->setPort($port); - } - $this->_timeout = $timeout; - $this->_file_extensions[FTP_ASCII] = array(); - $this->_file_extensions[FTP_BINARY] = array(); - - $this->_ls_match = array( - 'unix' => array( - 'pattern' => '/(?:(d)|.)([rwxts-]{9})\s+(\w+)\s+([\w\d-()?.]+)\s+'. - '([\w\d-()?.]+)\s+(\w+)\s+(\S+\s+\S+\s+\S+)\s+(.+)/', - 'map' => array( - 'is_dir' => 1, - 'rights' => 2, - 'files_inside' => 3, - 'user' => 4, - 'group' => 5, - 'size' => 6, - 'date' => 7, - 'name' => 8, - ) - ), - 'windows' => array( - 'pattern' => '/([0-9\-]+)\s+([0-9:APM]+)\s+(()|\d+)\s+(.+)/', - 'map' => array( - 'date' => 1, - 'time' => 2, - 'size' => 3, - 'is_dir' => 4, - 'name' => 5, - ) - ) - ); - } - - /** - * This function generates the FTP-connection. You can optionally define a - * hostname and/or a port. If you do so, this data is stored inside the object. - * - * @param string $host (optional) The Hostname - * @param int $port (optional) The Port - * - * @access public - * @return mixed True on success, otherwise PEAR::Error - * @see NET_FTP_ERR_CONNECT_FAILED - */ - function connect($host = null, $port = null) - { - $this->_matcher = null; - if (isset($host)) { - $this->setHostname($host); - } - if (isset($port)) { - $this->setPort($port); - } - $handle = @ftp_connect($this->getHostname(), $this->getPort(), - $this->_timeout); - if (!$handle) { - return $this->raiseError("Connection to host failed", - NET_FTP_ERR_CONNECT_FAILED); - } else { - $this->_handle =& $handle; - return true; - } - } - - /** - * This function close the FTP-connection - * - * @access public - * @return bool|PEAR_Error Returns true on success, PEAR_Error on failure - */ - function disconnect() - { - $res = @ftp_close($this->_handle); - if (!$res) { - return PEAR::raiseError('Disconnect failed.', - NET_FTP_ERR_DISCONNECT_FAILED); - } - return true; - } - - /** - * This logs you into the ftp-server. You are free to specify username and - * password in this method. If you specify it, the values will be taken into - * the corresponding attributes, if do not specify, the attributes are taken. - * - * @param string $username (optional) The username to use - * @param string $password (optional) The password to use - * - * @access public - * @return mixed True on success, otherwise PEAR::Error - * @see NET_FTP_ERR_LOGIN_FAILED - */ - function login($username = null, $password = null) - { - if (!isset($username)) { - $username = $this->getUsername(); - } else { - $this->setUsername($username); - } - - if (!isset($password)) { - $password = $this->getPassword(); - } else { - $this->setPassword($password); - } - - $res = @ftp_login($this->_handle, $username, $password); - - if (!$res) { - return $this->raiseError("Unable to login", NET_FTP_ERR_LOGIN_FAILED); - } else { - return true; - } - } - - /** - * This changes the currently used directory. You can use either an absolute - * directory-path (e.g. "/home/blah") or a relative one (e.g. "../test"). - * - * @param string $dir The directory to go to. - * - * @access public - * @return mixed True on success, otherwise PEAR::Error - * @see NET_FTP_ERR_DIRCHANGE_FAILED - */ - function cd($dir) - { - $erg = @ftp_chdir($this->_handle, $dir); - if (!$erg) { - return $this->raiseError("Directory change failed", - NET_FTP_ERR_DIRCHANGE_FAILED); - } else { - return true; - } - } - - /** - * Show's you the actual path on the server - * This function questions the ftp-handle for the actual selected path and - * returns it. - * - * @access public - * @return mixed The actual path or PEAR::Error - * @see NET_FTP_ERR_DETERMINEPATH_FAILED - */ - function pwd() - { - $res = @ftp_pwd($this->_handle); - if (!$res) { - return $this->raiseError("Could not determine the actual path.", - NET_FTP_ERR_DETERMINEPATH_FAILED); - } else { - return $res; - } - } - - /** - * This works similar to the mkdir-command on your local machine. You can either - * give it an absolute or relative path. The relative path will be completed - * with the actual selected server-path. (see: pwd()) - * - * @param string $dir Absolute or relative dir-path - * @param bool $recursive (optional) Create all needed directories - * - * @access public - * @return mixed True on success, otherwise PEAR::Error - * @see NET_FTP_ERR_CREATEDIR_FAILED - */ - function mkdir($dir, $recursive = false) - { - $dir = $this->_constructPath($dir); - $savedir = $this->pwd(); - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $e = $this->cd($dir); - $this->popErrorHandling(); - if ($e === true) { - $this->cd($savedir); - return true; - } - $this->cd($savedir); - if ($recursive === false) { - $res = @ftp_mkdir($this->_handle, $dir); - if (!$res) { - return $this->raiseError("Creation of '$dir' failed", - NET_FTP_ERR_CREATEDIR_FAILED); - } else { - return true; - } - } else { - // do not look at the first character, as $dir is absolute, - // it will always be a / - if (strpos(substr($dir, 1), '/') === false) { - return $this->mkdir($dir, false); - } - if (substr($dir, -1) == '/') { - $dir = substr($dir, 0, -1); - } - $parent = substr($dir, 0, strrpos($dir, '/')); - $res = $this->mkdir($parent, true); - if ($res === true) { - $res = $this->mkdir($dir, false); - } - if ($res !== true) { - return $res; - } - return true; - } - } - - /** - * This method tries executing a command on the ftp, using SITE EXEC. - * - * @param string $command The command to execute - * - * @access public - * @return mixed The result of the command (if successfull), otherwise - * PEAR::Error - * @see NET_FTP_ERR_EXEC_FAILED - */ - function execute($command) - { - $res = @ftp_exec($this->_handle, $command); - if (!$res) { - return $this->raiseError("Execution of command '$command' failed.", - NET_FTP_ERR_EXEC_FAILED); - } else { - return $res; - } - } - - /** - * Execute a SITE command on the server - * This method tries to execute a SITE command on the ftp server. - * - * @param string $command The command with parameters to execute - * - * @access public - * @return mixed True if successful, otherwise PEAR::Error - * @see NET_FTP_ERR_SITE_FAILED - */ - function site($command) - { - $res = @ftp_site($this->_handle, $command); - if (!$res) { - return $this->raiseError("Execution of SITE command '$command' failed.", - NET_FTP_ERR_SITE_FAILED); - } else { - return $res; - } - } - - /** - * This method will try to chmod the file specified on the server - * Currently, you must give a number as the the permission argument (777 or - * similar). The file can be either a relative or absolute path. - * NOTE: Some servers do not support this feature. In that case, you will - * get a PEAR error object returned. If successful, the method returns true - * - * @param mixed $target The file or array of files to set permissions for - * @param integer $permissions The mode to set the file permissions to - * - * @access public - * @return mixed True if successful, otherwise PEAR::Error - * @see NET_FTP_ERR_CHMOD_FAILED - */ - function chmod($target, $permissions) - { - // If $target is an array: Loop through it. - if (is_array($target)) { - - for ($i = 0; $i < count($target); $i++) { - $res = $this->chmod($target[$i], $permissions); - if (PEAR::isError($res)) { - return $res; - } // end if isError - } // end for i < count($target) - - } else { - - $res = $this->site("CHMOD " . $permissions . " " . $target); - if (!$res) { - return PEAR::raiseError("CHMOD " . $permissions . " " . $target . - " failed", NET_FTP_ERR_CHMOD_FAILED); - } else { - return $res; - } - - } // end if is_array - - } // end method chmod - - /** - * This method will try to chmod a folder and all of its contents - * on the server. The target argument must be a folder or an array of folders - * and the permissions argument have to be an integer (i.e. 777). - * The file can be either a relative or absolute path. - * NOTE: Some servers do not support this feature. In that case, you - * will get a PEAR error object returned. If successful, the method - * returns true - * - * @param mixed $target The folder or array of folders to - * set permissions for - * @param integer $permissions The mode to set the folder - * and file permissions to - * - * @access public - * @return mixed True if successful, otherwise PEAR::Error - * @see NET_FTP_ERR_CHMOD_FAILED, NET_FTP_ERR_DETERMINEPATH_FAILED, - * NET_FTP_ERR_RAWDIRLIST_FAILED, NET_FTP_ERR_DIRLIST_UNSUPPORTED - */ - function chmodRecursive($target, $permissions) - { - static $dir_permissions; - - if (!isset($dir_permissions)) { // Making directory specific permissions - $dir_permissions = $this->_makeDirPermissions($permissions); - } - - // If $target is an array: Loop through it - if (is_array($target)) { - - for ($i = 0; $i < count($target); $i++) { - $res = $this->chmodRecursive($target[$i], $permissions); - if (PEAR::isError($res)) { - return $res; - } // end if isError - } // end for i < count($target) - - } else { - - $remote_path = $this->_constructPath($target); - - // Chmod the directory itself - $result = $this->chmod($remote_path, $dir_permissions); - - if (PEAR::isError($result)) { - return $result; - } - - // If $remote_path last character is not a slash, add one - if (substr($remote_path, strlen($remote_path)-1) != "/") { - - $remote_path .= "/"; - } - - $dir_list = array(); - $mode = NET_FTP_DIRS_ONLY; - $dir_list = $this->ls($remote_path, $mode); - foreach ($dir_list as $dir_entry) { - if ($dir_entry['name'] == '.' || $dir_entry['name'] == '..') { - continue; - } - - $remote_path_new = $remote_path.$dir_entry["name"]."/"; - - // Chmod the directory we're about to enter - $result = $this->chmod($remote_path_new, $dir_permissions); - - if (PEAR::isError($result)) { - return $result; - } - - $result = $this->chmodRecursive($remote_path_new, $permissions); - - if (PEAR::isError($result)) { - return $result; - } - - } // end foreach dir_list as dir_entry - - $file_list = array(); - $mode = NET_FTP_FILES_ONLY; - $file_list = $this->ls($remote_path, $mode); - - foreach ($file_list as $file_entry) { - - $remote_file = $remote_path.$file_entry["name"]; - - $result = $this->chmod($remote_file, $permissions); - - if (PEAR::isError($result)) { - return $result; - } - - } // end foreach $file_list - - } // end if is_array - - return true; // No errors - - } // end method chmodRecursive - - /** - * Rename or move a file or a directory from the ftp-server - * - * @param string $remote_from The remote file or directory original to rename or - * move - * @param string $remote_to The remote file or directory final to rename or - * move - * - * @access public - * @return bool $res True on success, otherwise PEAR::Error - * @see NET_FTP_ERR_RENAME_FAILED - */ - function rename ($remote_from, $remote_to) - { - $res = @ftp_rename($this->_handle, $remote_from, $remote_to); - if (!$res) { - return $this->raiseError("Could not rename ".$remote_from." to ". - $remote_to." !", NET_FTP_ERR_RENAME_FAILED); - } - return true; - } - - /** - * This will return logical permissions mask for directory. - * if directory has to be readable it have also be executable - * - * @param string $permissions File permissions in digits for file (i.e. 666) - * - * @access private - * @return string File permissions in digits for directory (i.e. 777) - */ - function _makeDirPermissions($permissions) - { - $permissions = (string)$permissions; - - // going through (user, group, world) - for ($i = 0; $i < strlen($permissions); $i++) { - // Read permission is set but execute not yet - if ((int)$permissions{$i} & 4 and !((int)$permissions{$i} & 1)) { - // Adding execute flag - (int)$permissions{$i} = (int)$permissions{$i} + 1; - } - } - - return (string)$permissions; - } - - /** - * This will return the last modification-time of a file. You can either give - * this function a relative or an absolute path to the file to check. - * NOTE: Some servers will not support this feature and the function works - * only on files, not directories! When successful, - * it will return the last modification-time as a unix-timestamp or, when - * $format is specified, a preformated timestring. - * - * @param string $file The file to check - * @param string $format (optional) The format to give the date back - * if not set, it will return a Unix timestamp - * - * @access public - * @return mixed Unix timestamp, a preformated date-string or PEAR::Error - * @see NET_FTP_ERR_MDTMDIR_UNSUPPORTED, NET_FTP_ERR_MDTM_FAILED, - * NET_FTP_ERR_DATEFORMAT_FAILED - */ - function mdtm($file, $format = null) - { - $file = $this->_constructPath($file); - if ($this->_checkDir($file)) { - return $this->raiseError("Filename '$file' seems to be a directory.", - NET_FTP_ERR_MDTMDIR_UNSUPPORTED); - } - $res = @ftp_mdtm($this->_handle, $file); - if ($res == -1) { - return $this->raiseError("Could not get last-modification-date of '". - $file."'.", NET_FTP_ERR_MDTM_FAILED); - } - if (isset($format)) { - $res = date($format, $res); - if (!$res) { - return $this->raiseError("Date-format failed on timestamp '".$res. - "'.", NET_FTP_ERR_DATEFORMAT_FAILED); - } - } - return $res; - } - - /** - * This will return the size of a given file in bytes. You can either give this - * function a relative or an absolute file-path. NOTE: Some servers do not - * support this feature! - * - * @param string $file The file to check - * - * @access public - * @return mixed Size in bytes or PEAR::Error - * @see NET_FTP_ERR_SIZE_FAILED - */ - function size($file) - { - $file = $this->_constructPath($file); - $res = @ftp_size($this->_handle, $file); - if ($res == -1) { - return $this->raiseError("Could not determine filesize of '$file'.", - NET_FTP_ERR_SIZE_FAILED); - } else { - return $res; - } - } - - /** - * This method returns a directory-list of the current directory or given one. - * To display the current selected directory, simply set the first parameter to - * null - * or leave it blank, if you do not want to use any other parameters. - *

- * There are 4 different modes of listing directories. Either to list only - * the files (using NET_FTP_FILES_ONLY), to list only directories (using - * NET_FTP_DIRS_ONLY) or to show both (using NET_FTP_DIRS_FILES, which is - * default). - *

- * The 4th one is the NET_FTP_RAWLIST, which returns just the array created by - * the ftp_rawlist()-function build into PHP. - *

- * The other function-modes will return an array containing the requested data. - * The files and dirs are listed in human-sorted order, but if you select - * NET_FTP_DIRS_FILES the directories will be added above the files, - * but although both sorted. - *

- * All elements in the arrays are associative arrays themselves. They have the - * following structure: - *

- * Dirs:
- * ["name"] => string The name of the directory
- * ["rights"] => string The rights of the directory (in style - * "rwxr-xr-x")
- * ["user"] => string The owner of the directory
- * ["group"] => string The group-owner of the directory
- * ["files_inside"]=> string The number of files/dirs inside the - * directory excluding "." and ".."
- * ["date"] => int The creation-date as Unix timestamp
- * ["is_dir"] => bool true, cause this is a dir
- *

- * Files:
- * ["name"] => string The name of the file
- * ["size"] => int Size in bytes
- * ["rights"] => string The rights of the file (in style - * "rwxr-xr-x")
- * ["user"] => string The owner of the file
- * ["group"] => string The group-owner of the file
- * ["date"] => int The creation-date as Unix timestamp
- * ["is_dir"] => bool false, cause this is a file
- * - * @param string $dir (optional) The directory to list or null, when listing - * the current directory. - * @param int $mode (optional) The mode which types to list (files, - * directories or both). - * - * @access public - * @return mixed The directory list as described above or PEAR::Error on failure - * @see NET_FTP_DIRS_FILES, NET_FTP_DIRS_ONLY, NET_FTP_FILES_ONLY, - * NET_FTP_RAWLIST, NET_FTP_ERR_DETERMINEPATH_FAILED, - * NET_FTP_ERR_RAWDIRLIST_FAILED, NET_FTP_ERR_DIRLIST_UNSUPPORTED - */ - function ls($dir = null, $mode = NET_FTP_DIRS_FILES) - { - if (!isset($dir)) { - $dir = @ftp_pwd($this->_handle); - if (!$dir) { - return $this->raiseError("Could not retrieve current directory", - NET_FTP_ERR_DETERMINEPATH_FAILED); - } - } - if (($mode != NET_FTP_FILES_ONLY) && ($mode != NET_FTP_DIRS_ONLY) && - ($mode != NET_FTP_RAWLIST)) { - $mode = NET_FTP_DIRS_FILES; - } - - switch ($mode) { - case NET_FTP_DIRS_FILES: - $res = $this->_lsBoth($dir); - break; - case NET_FTP_DIRS_ONLY: - $res = $this->_lsDirs($dir); - break; - case NET_FTP_FILES_ONLY: - $res = $this->_lsFiles($dir); - break; - case NET_FTP_RAWLIST: - $res = @ftp_rawlist($this->_handle, $dir); - break; - } - - return $res; - } - - /** - * This method will delete the given file or directory ($path) from the server - * (maybe recursive). - * - * Whether the given string is a file or directory is only determined by the - * last sign inside the string ("/" or not). - * - * If you specify a directory, you can optionally specify $recursive as true, - * to let the directory be deleted recursive (with all sub-directories and files - * inherited). - * - * You can either give a absolute or relative path for the file / dir. If you - * choose to use the relative path, it will be automatically completed with the - * actual selected directory. - * - * @param string $path The absolute or relative path to the file/directory. - * @param bool $recursive (optional) - * - * @access public - * @return mixed True on success, otherwise PEAR::Error - * @see NET_FTP_ERR_DELETEFILE_FAILED, NET_FTP_ERR_DELETEDIR_FAILED, - * NET_FTP_ERR_REMOTEPATHNODIR - */ - function rm($path, $recursive = false) - { - $path = $this->_constructPath($path); - if ($this->_checkDir($path)) { - if ($recursive) { - return $this->_rmDirRecursive($path); - } else { - return $this->_rmDir($path); - } - } else { - return $this->_rmFile($path); - } - } - - /** - * This function will download a file from the ftp-server. You can either - * specify an absolute path to the file (beginning with "/") or a relative one, - * which will be completed with the actual directory you selected on the server. - * You can specify the path to which the file will be downloaded on the local - * machine, if the file should be overwritten if it exists (optionally, default - * is no overwriting) and in which mode (FTP_ASCII or FTP_BINARY) the file - * should be downloaded (if you do not specify this, the method tries to - * determine it automatically from the mode-directory or uses the default-mode, - * set by you). - * If you give a relative path to the local-file, the script-path is used as - * basepath. - * - * @param string $remote_file The absolute or relative path to the file to - * download - * @param string $local_file The local file to put the downloaded in - * @param bool $overwrite (optional) Whether to overwrite existing file - * @param int $mode (optional) Either FTP_ASCII or FTP_BINARY - * - * @access public - * @return mixed True on success, otherwise PEAR::Error - * @see NET_FTP_ERR_OVERWRITELOCALFILE_FORBIDDEN, - * NET_FTP_ERR_OVERWRITELOCALFILE_FAILED, - * NET_FTP_ERR_OVERWRITELOCALFILE_FAILED - */ - function get($remote_file, $local_file, $overwrite = false, $mode = null) - { - if (!isset($mode)) { - $mode = $this->checkFileExtension($remote_file); - } - - $remote_file = $this->_constructPath($remote_file); - - if (@file_exists($local_file) && !$overwrite) { - return $this->raiseError("Local file '".$local_file. - "' exists and may not be overwriten.", - NET_FTP_ERR_OVERWRITELOCALFILE_FORBIDDEN); - } - if (@file_exists($local_file) && - !@is_writeable($local_file) && $overwrite) { - return $this->raiseError("Local file '".$local_file. - "' is not writeable. Can not overwrite.", - NET_FTP_ERR_OVERWRITELOCALFILE_FAILED); - } - - if (@function_exists('ftp_nb_get')) { - $res = @ftp_nb_get($this->_handle, $local_file, $remote_file, $mode); - while ($res == FTP_MOREDATA) { - $this->_announce('nb_get'); - $res = @ftp_nb_continue($this->_handle); - } - } else { - $res = @ftp_get($this->_handle, $local_file, $remote_file, $mode); - } - if (!$res) { - return $this->raiseError("File '".$remote_file. - "' could not be downloaded to '$local_file'.", - NET_FTP_ERR_OVERWRITELOCALFILE_FAILED); - } else { - return true; - } - } - - /** - * This function will upload a file to the ftp-server. You can either specify a - * absolute path to the remote-file (beginning with "/") or a relative one, - * which will be completed with the actual directory you selected on the server. - * You can specify the path from which the file will be uploaded on the local - * maschine, if the file should be overwritten if it exists (optionally, default - * is no overwriting) and in which mode (FTP_ASCII or FTP_BINARY) the file - * should be downloaded (if you do not specify this, the method tries to - * determine it automatically from the mode-directory or uses the default-mode, - * set by you). - * If you give a relative path to the local-file, the script-path is used as - * basepath. - * - * @param string $local_file The local file to upload - * @param string $remote_file The absolute or relative path to the file to - * upload to - * @param bool $overwrite (optional) Whether to overwrite existing file - * @param int $mode (optional) Either FTP_ASCII or FTP_BINARY - * - * @access public - * @return mixed True on success, otherwise PEAR::Error - * @see NET_FTP_ERR_LOCALFILENOTEXIST, - * NET_FTP_ERR_OVERWRITEREMOTEFILE_FORBIDDEN, - * NET_FTP_ERR_UPLOADFILE_FAILED - */ - function put($local_file, $remote_file, $overwrite = false, $mode = null) - { - if (!isset($mode)) { - $mode = $this->checkFileExtension($local_file); - } - $remote_file = $this->_constructPath($remote_file); - - if (!@file_exists($local_file)) { - return $this->raiseError("Local file '$local_file' does not exist.", - NET_FTP_ERR_LOCALFILENOTEXIST); - } - if ((@ftp_size($this->_handle, $remote_file) != -1) && !$overwrite) { - return $this->raiseError("Remote file '".$remote_file. - "' exists and may not be overwriten.", - NET_FTP_ERR_OVERWRITEREMOTEFILE_FORBIDDEN); - } - - if (function_exists('ftp_alloc')) { - ftp_alloc($this->_handle, filesize($local_file)); - } - if (function_exists('ftp_nb_put')) { - $res = @ftp_nb_put($this->_handle, $remote_file, $local_file, $mode); - while ($res == FTP_MOREDATA) { - $this->_announce('nb_put'); - $res = @ftp_nb_continue($this->_handle); - } - - } else { - $res = @ftp_put($this->_handle, $remote_file, $local_file, $mode); - } - if (!$res) { - return $this->raiseError("File '$local_file' could not be uploaded to '" - .$remote_file."'.", - NET_FTP_ERR_UPLOADFILE_FAILED); - } else { - return true; - } - } - - /** - * This functionality allows you to transfer a whole directory-structure from - * the remote-ftp to your local host. You have to give a remote-directory - * (ending with '/') and the local directory (ending with '/') where to put the - * files you download. - * The remote path is automatically completed with the current-remote-dir, if - * you give a relative path to this function. You can give a relative path for - * the $local_path, too. Then the script-basedir will be used for comletion of - * the path. - * The parameter $overwrite will determine, whether to overwrite existing files - * or not. Standard for this is false. Fourth you can explicitly set a mode for - * all transfer actions done. If you do not set this, the method tries to - * determine the transfer mode by checking your mode-directory for the file - * extension. If the extension is not inside the mode-directory, it will get - * your default mode. - * - * @param string $remote_path The path to download - * @param string $local_path The path to download to - * @param bool $overwrite (optional) Whether to overwrite existing files - * (true) or not (false, standard). - * @param int $mode (optional) The transfermode (either FTP_ASCII or - * FTP_BINARY). - * - * @access public - * @return mixed True on succes, otherwise PEAR::Error - * @see NET_FTP_ERR_OVERWRITELOCALFILE_FORBIDDEN, - * NET_FTP_ERR_OVERWRITELOCALFILE_FAILED, NET_FTP_ERR_OVERWRITELOCALFILE_FAILED, - * NET_FTP_ERR_REMOTEPATHNODIR, NET_FTP_ERR_LOCALPATHNODIR, - * NET_FTP_ERR_CREATELOCALDIR_FAILED - */ - function getRecursive($remote_path, $local_p, $overwrite = false, - $mode = null) - { - 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(); - $remote_path = $this->_constructPath($remote_path); - if (!$this->_checkDir($remote_path)) { - return $this->raiseError("Given remote-path '".$remote_path. - "' seems not to be a directory.", - NET_FTP_ERR_REMOTEPATHNODIR); - } - if (!$this->_checkDir($local_p)) { - return $this->raiseError("Given local-path '".$local_p. - "' seems not to be a directory.", - NET_FTP_ERR_LOCALPATHNODIR); - } - - if (!@is_dir($filter->validatePath($local_p))) { - $sLocal_p = $filter->validatePath($local_p); - $mkdir = self::mkdir; - $res = $mkdir($sLocal_p); - if (!$res) { - return $this->raiseError("Could not create dir '$local_p'", - NET_FTP_ERR_CREATELOCALDIR_FAILED); - } - } - $dir_list = array(); - $dir_list = $this->ls($remote_path, NET_FTP_DIRS_ONLY); - if (PEAR::isError($dir_list)) { - return $dir_list; - } - foreach ($dir_list as $dir_entry) { - if ($dir_entry['name'] != '.' && $dir_entry['name'] != '..') { - $remote_path_new = $remote_path.$dir_entry["name"]."/"; - $local_p_new = $local_p.$dir_entry["name"]."/"; - $result = $this->getRecursive($remote_path_new, - $local_p_new, $overwrite, $mode); - if ($this->isError($result)) { - return $result; - } - } - } - $file_list = array(); - $file_list = $this->ls($remote_path, NET_FTP_FILES_ONLY); - if (PEAR::isError($file_list)) { - return $file_list; - } - foreach ($file_list as $file_entry) { - $remote_file = $remote_path.$file_entry["name"]; - $local_file = $local_p.$file_entry["name"]; - $result = $this->get($remote_file, $local_file, $overwrite, $mode); - if ($this->isError($result)) { - return $result; - } - } - return true; - } - - /** - * This functionality allows you to transfer a whole directory-structure from - * your local host to the remote-ftp. You have to give a remote-directory - * (ending with '/') and the local directory (ending with '/') where to put the - * files you download. The remote path is automatically completed with the - * current-remote-dir, if you give a relative path to this function. You can - * give a relative path for the $local_path, too. Then the script-basedir will - * be used for comletion of the path. - * The parameter $overwrite will determine, whether to overwrite existing files - * or not. - * Standard for this is false. Fourth you can explicitly set a mode for all - * transfer actions done. If you do not set this, the method tries to determine - * the transfer mode by checking your mode-directory for the file-extension. If - * the extension is not inside the mode-directory, it will get your default - * mode. - * - * @param string $local_path The path to download to - * @param string $remote_path The path to download - * @param bool $overwrite (optional) Whether to overwrite existing files - * (true) or not (false, standard). - * @param int $mode (optional) The transfermode (either FTP_ASCII or - * FTP_BINARY). - * - * @access public - * @return mixed True on succes, otherwise PEAR::Error - * @see NET_FTP_ERR_LOCALFILENOTEXIST, - * NET_FTP_ERR_OVERWRITEREMOTEFILE_FORBIDDEN, - * NET_FTP_ERR_UPLOADFILE_FAILED, NET_FTP_ERR_LOCALPATHNODIR, - * NET_FTP_ERR_REMOTEPATHNODIR - */ - function putRecursive($local_path, $remote_path, $overwrite = false, - $mode = null) - { - $remote_path = $this->_constructPath($remote_path); - if (!file_exists($local_path) || !is_dir($local_path)) { - return $this->raiseError("Given local-path '".$local_path. - "' seems not to be a directory.", - NET_FTP_ERR_LOCALPATHNODIR); - } - if (!$this->_checkDir($remote_path)) { - return $this->raiseError("Given remote-path '".$remote_path. - "' seems not to be a directory.", - NET_FTP_ERR_REMOTEPATHNODIR); - } - $old_path = $this->pwd(); - if ($this->isError($this->cd($remote_path))) { - $res = $this->mkdir($remote_path); - if ($this->isError($res)) { - return $res; - } - } - $this->cd($old_path); - $dir_list = $this->_lsLocal($local_path); - foreach ($dir_list["dirs"] as $dir_entry) { - // local directories do not have arrays as entry - $remote_path_new = $remote_path.$dir_entry."/"; - $local_path_new = $local_path.$dir_entry."/"; - $result = $this->putRecursive($local_path_new, - $remote_path_new, $overwrite, $mode); - if ($this->isError($result)) { - return $result; - } - } - - foreach ($dir_list["files"] as $file_entry) { - $remote_file = $remote_path.$file_entry; - $local_file = $local_path.$file_entry; - $result = $this->put($local_file, $remote_file, $overwrite, $mode); - if ($this->isError($result)) { - return $result; - } - } - return true; - } - - /** - * This checks, whether a file should be transfered in ascii- or binary-mode - * by it's file-extension. If the file-extension is not set or - * the extension is not inside one of the extension-dirs, the actual set - * transfer-mode is returned. - * - * @param string $filename The filename to be checked - * - * @access public - * @return int Either FTP_ASCII or FTP_BINARY - */ - function checkFileExtension($filename) - { - if (($pos = strrpos($filename, '.')) === false) { - return $this->_mode; - } else { - $ext = substr($filename, $pos + 1); - } - - if (isset($this->_file_extensions[$ext])) { - return $this->_file_extensions[$ext]; - } - - return $this->_mode; - } - - /** - * Set the hostname - * - * @param string $host The hostname to set - * - * @access public - * @return bool True on success, otherwise PEAR::Error - * @see NET_FTP_ERR_HOSTNAMENOSTRING - */ - function setHostname($host) - { - if (!is_string($host)) { - return PEAR::raiseError("Hostname must be a string.", - NET_FTP_ERR_HOSTNAMENOSTRING); - } - $this->_hostname = $host; - return true; - } - - /** - * Set the Port - * - * @param int $port The port to set - * - * @access public - * @return bool True on success, otherwise PEAR::Error - * @see NET_FTP_ERR_PORTLESSZERO - */ - function setPort($port) - { - if (!is_int($port) || ($port < 0)) { - PEAR::raiseError("Invalid port. Has to be integer >= 0", - NET_FTP_ERR_PORTLESSZERO); - } - $this->_port = $port; - return true; - } - - /** - * Set the Username - * - * @param string $user The username to set - * - * @access public - * @return mixed True on success, otherwise PEAR::Error - * @see NET_FTP_ERR_USERNAMENOSTRING - */ - function setUsername($user) - { - if (empty($user) || !is_string($user)) { - return PEAR::raiseError('Username $user invalid.', - NET_FTP_ERR_USERNAMENOSTRING); - } - $this->_username = $user; - } - - /** - * Set the password - * - * @param string $password The password to set - * - * @access private - * @return void - * @see NET_FTP_ERR_PASSWORDNOSTRING - */ - function setPassword($password) - { - if (empty($password) || !is_string($password)) { - return PEAR::raiseError('Password xxx invalid.', - NET_FTP_ERR_PASSWORDNOSTRING); - } - $this->_password = $password; - } - - /** - * Set the transfer-mode. You can use the predefined constants - * FTP_ASCII or FTP_BINARY. The mode will be stored for any further transfers. - * - * @param int $mode The mode to set - * - * @access public - * @return mixed True on success, otherwise PEAR::Error - * @see NET_FTP_ERR_NOMODECONST - */ - function setMode($mode) - { - if (($mode == FTP_ASCII) || ($mode == FTP_BINARY)) { - $this->_mode = $mode; - return true; - } else { - return $this->raiseError('FTP-Mode has either to be FTP_ASCII or'. - 'FTP_BINARY', NET_FTP_ERR_NOMODECONST); - } - } - - /** - * Set the transfer-method to passive mode - * - * @access public - * @return void - */ - function setPassive() - { - $this->_passv = true; - @ftp_pasv($this->_handle, true); - } - - /** - * Set the transfer-method to active mode - * - * @access public - * @return void - */ - function setActive() - { - $this->_passv = false; - @ftp_pasv($this->_handle, false); - } - - /** - * Set the timeout for FTP operations - * - * Use this method to set a timeout for FTP operation. Timeout has to be an - * integer. - * - * @param int $timeout the timeout to use - * - * @access public - * @return bool True on success, otherwise PEAR::Error - * @see NET_FTP_ERR_TIMEOUTLESSZERO, NET_FTP_ERR_SETTIMEOUT_FAILED - */ - function setTimeout ( $timeout = 0 ) - { - if (!is_int($timeout) || ($timeout < 0)) { - return PEAR::raiseError('Timeout '.$timeout. - ' is invalid, has to be an integer >= 0', - NET_FTP_ERR_TIMEOUTLESSZERO); - } - $this->_timeout = $timeout; - if (isset($this->_handle) && is_resource($this->_handle)) { - $res = @ftp_set_option($this->_handle, FTP_TIMEOUT_SEC, $timeout); - } else { - $res = true; - } - if (!$res) { - return PEAR::raiseError("Set timeout failed.", - NET_FTP_ERR_SETTIMEOUT_FAILED); - } - return true; - } - - /** - * Adds an extension to a mode-directory - * - * The mode-directory saves file-extensions coresponding to filetypes - * (ascii e.g.: 'php', 'txt', 'htm',...; binary e.g.: 'jpg', 'gif', 'exe',...). - * The extensions have to be saved without the '.'. And - * can be predefined in an external file (see: getExtensionsFile()). - * - * The array is build like this: 'php' => FTP_ASCII, 'png' => FTP_BINARY - * - * To change the mode of an extension, just add it again with the new mode! - * - * @param int $mode Either FTP_ASCII or FTP_BINARY - * @param string $ext Extension - * - * @access public - * @return void - */ - function addExtension($mode, $ext) - { - $this->_file_extensions[$ext] = $mode; - } - - /** - * This function removes an extension from the mode-directories - * (described above). - * - * @param string $ext The extension to remove - * - * @access public - * @return void - */ - function removeExtension($ext) - { - if (isset($this->_file_extensions[$ext])) { - unset($this->_file_extensions[$ext]); - } - } - - /** - * This get's both (ascii- and binary-mode-directories) from the given file. - * Beware, if you read a file into the mode-directory, all former set values - * will be unset! - * - * Example file contents: - * [ASCII] - * asc = 0 - * txt = 0 - * [BINARY] - * bin = 1 - * jpg = 1 - * - * @param string $filename The file to get from - * - * @access public - * @return mixed True on success, otherwise PEAR::Error - * @see NET_FTP_ERR_EXTFILENOTEXIST, NET_FTP_ERR_EXTFILEREAD_FAILED - */ - function getExtensionsFile($filename) - { - if (!file_exists($filename)) { - return $this->raiseError("Extensions-file '$filename' does not exist", - NET_FTP_ERR_EXTFILENOTEXIST); - } - - if (!is_readable($filename)) { - return $this->raiseError("Extensions-file '$filename' is not readable", - NET_FTP_ERR_EXTFILEREAD_FAILED); - } - - $exts = @parse_ini_file($filename, true); - if (!is_array($exts)) { - return $this->raiseError("Extensions-file '$filename' could not be". - "loaded", NET_FTP_ERR_EXTFILELOAD_FAILED); - } - - $this->_file_extensions = array(); - - if (isset($exts['ASCII'])) { - foreach ($exts['ASCII'] as $ext => $bogus) { - $this->_file_extensions[$ext] = FTP_ASCII; - } - } - - if (isset($exts['BINARY'])) { - foreach ($exts['BINARY'] as $ext => $bogus) { - $this->_file_extensions[$ext] = FTP_BINARY; - } - } - - return true; - } - - /** - * Returns the hostname - * - * @access public - * @return string The hostname - */ - function getHostname() - { - return $this->_hostname; - } - - /** - * Returns the port - * - * @access public - * @return int The port - */ - function getPort() - { - return $this->_port; - } - - /** - * Returns the username - * - * @access public - * @return string The username - */ - function getUsername() - { - return $this->_username; - } - - /** - * Returns the password - * - * @access public - * @return string The password - */ - function getPassword() - { - return $this->_password; - } - - /** - * Returns the transfermode - * - * @access public - * @return int The transfermode, either FTP_ASCII or FTP_BINARY. - */ - function getMode() - { - return $this->_mode; - } - - /** - * Returns, whether the connection is set to passive mode or not - * - * @access public - * @return bool True if passive-, false if active-mode - */ - function isPassive() - { - return $this->_passv; - } - - /** - * Returns the mode set for a file-extension - * - * @param string $ext The extension you wanna ask for - * - * @return int Either FTP_ASCII, FTP_BINARY or NULL (if not set a mode for it) - * @access public - */ - function getExtensionMode($ext) - { - return @$this->_file_extensions[$ext]; - } - - /** - * Get the currently set timeout. - * Returns the actual timeout set. - * - * @access public - * @return int The actual timeout - */ - function getTimeout() - { - return ftp_get_option($this->_handle, FTP_TIMEOUT_SEC); - } - - /** - * Adds a Net_FTP_Observer instance to the list of observers - * that are listening for messages emitted by this Net_FTP instance. - * - * @param object &$observer The Net_FTP_Observer instance to attach - * as a listener. - * - * @return boolean True if the observer is successfully attached. - * @access public - * @since 1.3 - */ - function attach(&$observer) - { - if (!is_a($observer, 'Net_FTP_Observer')) { - return false; - } - - $this->_listeners[$observer->getId()] = &$observer; - return true; - } - - /** - * Removes a Net_FTP_Observer instance from the list of observers. - * - * @param object $observer The Net_FTP_Observer instance to detach - * from the list of listeners. - * - * @return boolean True if the observer is successfully detached. - * @access public - * @since 1.3 - */ - function detach($observer) - { - if (!is_a($observer, 'Net_FTP_Observer') || - !isset($this->_listeners[$observer->getId()])) { - return false; - } - - unset($this->_listeners[$observer->getId()]); - return true; - } - - /** - * Informs each registered observer instance that a new message has been - * sent. - * - * @param mixed $event A hash describing the net event. - * - * @access private - * @since 1.3 - * @return void - */ - function _announce($event) - { - foreach ($this->_listeners as $id => $listener) { - $this->_listeners[$id]->notify($event); - } - } - - /** - * Rebuild the path, if given relative - * - * This method will make a relative path absolute by prepending the current - * remote directory in front of it. - * - * @param string $path The path to check and construct - * - * @access private - * @return string The build path - */ - function _constructPath($path) - { - if ((substr($path, 0, 1) != '/') && (substr($path, 0, 2) != './')) { - $actual_dir = @ftp_pwd($this->_handle); - if (substr($actual_dir, -1) != '/') { - $actual_dir .= '/'; - } - $path = $actual_dir.$path; - } - return $path; - } - - /** - * Checks, whether a given string is a directory-path (ends with "/") or not. - * - * @param string $path Path to check - * - * @access private - * @return bool True if $path is a directory, otherwise false - */ - function _checkDir($path) - { - if (!empty($path) && substr($path, (strlen($path) - 1), 1) == "/") { - return true; - } else { - return false; - } - } - - /** - * This will remove a file - * - * @param string $file The file to delete - * - * @access private - * @return mixed True on success, otherwise PEAR::Error - * @see NET_FTP_ERR_DELETEFILE_FAILED - */ - function _rmFile($file) - { - if (substr($file, 0, 1) != "/") { - $actual_dir = @ftp_pwd($this->_handle); - if (substr($actual_dir, (strlen($actual_dir) - 2), 1) != "/") { - $actual_dir .= "/"; - } - $file = $actual_dir.$file; - } - $res = @ftp_delete($this->_handle, $file); - - if (!$res) { - return $this->raiseError("Could not delete file '$file'.", - NET_FTP_ERR_DELETEFILE_FAILED); - } else { - return true; - } - } - - /** - * This will remove a dir - * - * @param string $dir The dir to delete - * - * @access private - * @return mixed True on success, otherwise PEAR::Error - * @see NET_FTP_ERR_REMOTEPATHNODIR, NET_FTP_ERR_DELETEDIR_FAILED - */ - function _rmDir($dir) - { - if (substr($dir, (strlen($dir) - 1), 1) != "/") { - return $this->raiseError("Directory name '".$dir. - "' is invalid, has to end with '/'", - NET_FTP_ERR_REMOTEPATHNODIR); - } - $res = @ftp_rmdir($this->_handle, $dir); - if (!$res) { - return $this->raiseError("Could not delete directory '$dir'.", - NET_FTP_ERR_DELETEDIR_FAILED); - } else { - return true; - } - } - - /** - * This will remove a dir and all subdirs and -files - * - * @param string $dir The dir to delete recursively - * - * @access private - * @return mixed True on success, otherwise PEAR::Error - * @see NET_FTP_ERR_REMOTEPATHNODIR, NET_FTP_ERR_DELETEDIR_FAILED - */ - function _rmDirRecursive($dir) - { - if (substr($dir, (strlen($dir) - 1), 1) != "/") { - return $this->raiseError("Directory name '".$dir. - "' is invalid, has to end with '/'", - NET_FTP_ERR_REMOTEPATHNODIR); - } - $file_list = $this->_lsFiles($dir); - foreach ($file_list as $file) { - $file = $dir.$file["name"]; - $res = $this->rm($file); - if ($this->isError($res)) { - return $res; - } - } - $dir_list = $this->_lsDirs($dir); - foreach ($dir_list as $new_dir) { - if ($new_dir["name"] == '.' || $new_dir["name"] == '..') { - continue; - } - $new_dir = $dir.$new_dir["name"]."/"; - $res = $this->_rmDirRecursive($new_dir); - if ($this->isError($res)) { - return $res; - } - } - $res = $this->_rmDir($dir); - if (PEAR::isError($res)) { - return $res; - } else { - return true; - } - } - - /** - * Lists up files and directories - * - * @param string $dir The directory to list up - * - * @access private - * @return array An array of dirs and files - */ - function _lsBoth($dir) - { - $list_splitted = $this->_listAndParse($dir); - if (PEAR::isError($list_splitted)) { - return $list_splitted; - } - if (!is_array($list_splitted["files"])) { - $list_splitted["files"] = array(); - } - if (!is_array($list_splitted["dirs"])) { - $list_splitted["dirs"] = array(); - } - $res = array(); - @array_splice($res, 0, 0, $list_splitted["files"]); - @array_splice($res, 0, 0, $list_splitted["dirs"]); - return $res; - } - - /** - * Lists up directories - * - * @param string $dir The directory to list up - * - * @access private - * @return array An array of dirs - */ - function _lsDirs($dir) - { - $list = $this->_listAndParse($dir); - if (PEAR::isError($list)) { - return $list; - } - return $list["dirs"]; - } - - /** - * Lists up files - * - * @param string $dir The directory to list up - * - * @access private - * @return array An array of files - */ - function _lsFiles($dir) - { - $list = $this->_listAndParse($dir); - if (PEAR::isError($list)) { - return $list; - } - return $list["files"]; - } - - /** - * This lists up the directory-content and parses the items into well-formated - * arrays. - * The results of this array are sorted (dirs on top, sorted by name; - * files below, sorted by name). - * - * @param string $dir The directory to parse - * - * @access private - * @return array Lists of dirs and files - * @see NET_FTP_ERR_RAWDIRLIST_FAILED - */ - function _listAndParse($dir) - { - $dirs_list = array(); - $files_list = array(); - $dir_list = @ftp_rawlist($this->_handle, $dir); - if (!is_array($dir_list)) { - return PEAR::raiseError('Could not get raw directory listing.', - NET_FTP_ERR_RAWDIRLIST_FAILED); - } - - foreach ($dir_list AS $k=>$v) { - if (strncmp($v, 'total: ', 7) == 0 && preg_match('/total: \d+/', $v)) { - unset($dir_list[$k]); - break; // usually there is just one line like this - } - } - - // Handle empty directories - if (count($dir_list) == 0) { - return array('dirs' => $dirs_list, 'files' => $files_list); - } - - // Exception for some FTP servers seem to return this wiered result instead - // of an empty list - if (count($dirs_list) == 1 && $dirs_list[0] == 'total 0') { - return array('dirs' => array(), 'files' => $files_list); - } - - if (!isset($this->_matcher) || PEAR::isError($this->_matcher)) { - $this->_matcher = $this->_determineOSMatch($dir_list); - if (PEAR::isError($this->_matcher)) { - return $this->_matcher; - } - } - foreach ($dir_list as $entry) { - if (!preg_match($this->_matcher['pattern'], $entry, $m)) { - continue; - } - $entry = array(); - foreach ($this->_matcher['map'] as $key=>$val) { - $entry[$key] = $m[$val]; - } - $entry['stamp'] = $this->_parseDate($entry['date']); - - if ($entry['is_dir']) { - $dirs_list[] = $entry; - } else { - $files_list[] = $entry; - } - } - @usort($dirs_list, array("Net_FTP", "_natSort")); - @usort($files_list, array("Net_FTP", "_natSort")); - $res["dirs"] = (is_array($dirs_list)) ? $dirs_list : array(); - $res["files"] = (is_array($files_list)) ? $files_list : array(); - return $res; - } - - /** - * Determine server OS - * This determines the server OS and returns a valid regex to parse - * ls() output. - * - * @param array &$dir_list The raw dir list to parse - * - * @access private - * @return mixed An array of 'pattern' and 'map' on success, otherwise - * PEAR::Error - * @see NET_FTP_ERR_DIRLIST_UNSUPPORTED - */ - function _determineOSMatch(&$dir_list) - { - foreach ($dir_list as $entry) { - foreach ($this->_ls_match as $os => $match) { - $matches = array(); - if (preg_match($match['pattern'], $entry, $matches)) { - return $match; - } - } - } - $error = 'The list style of your server seems not to be supported. Please'. - 'email a "$ftp->ls(NET_FTP_RAWLIST);" output plus info on the'. - 'server to the maintainer of this package to get it supported!'. - 'Thanks for your help!'; - return PEAR::raiseError($error, NET_FTP_ERR_DIRLIST_UNSUPPORTED); - } - - /** - * Lists a local directory - * - * @param string $dir_path The dir to list - * - * @access private - * @return array The list of dirs and files - */ - function _lsLocal($dir_path) - { - $dir = dir($dir_path); - $dir_list = array(); - $file_list = array(); - while (false !== ($entry = $dir->read())) { - if (($entry != '.') && ($entry != '..')) { - if (is_dir($dir_path.$entry)) { - $dir_list[] = $entry; - } else { - $file_list[] = $entry; - } - } - } - $dir->close(); - $res['dirs'] = $dir_list; - $res['files'] = $file_list; - return $res; - } - - /** - * Function for use with usort(). - * Compares the list-array-elements by name. - * - * @param string $item_1 first item to be compared - * @param string $item_2 second item to be compared - * - * @access private - * @return int < 0 if $item_1 is less than $item_2, 0 if equal and > 0 otherwise - */ - function _natSort($item_1, $item_2) - { - return strnatcmp($item_1['name'], $item_2['name']); - } - - /** - * Parse dates to timestamps - * - * @param string $date Date - * - * @access private - * @return int Timestamp - * @see NET_FTP_ERR_DATEFORMAT_FAILED - */ - function _parseDate($date) - { - // Sep 10 22:06 => Sep 10, 22:06 - if (preg_match('/([A-Za-z]+)[ ]+([0-9]+)[ ]+([0-9]+):([0-9]+)/', $date, - $res)) { - $year = date('Y'); - $month = $res[1]; - $day = $res[2]; - $hour = $res[3]; - $minute = $res[4]; - $date = "$month $day, $year $hour:$minute"; - $tmpDate = strtotime($date); - if ($tmpDate > time()) { - $year--; - $date = "$month $day, $year $hour:$minute"; - } - } elseif (preg_match('/^\d\d-\d\d-\d\d/', $date)) { - // 09-10-04 => 09/10/04 - $date = str_replace('-', '/', $date); - } - $res = strtotime($date); - if (!$res) { - return $this->raiseError('Dateconversion failed.', - NET_FTP_ERR_DATEFORMAT_FAILED); - } - return $res; - } -} -?> diff --git a/gulliver/thirdparty/pear/Net/FTP/Observer.php b/gulliver/thirdparty/pear/Net/FTP/Observer.php deleted file mode 100644 index 3069ec30d..000000000 --- a/gulliver/thirdparty/pear/Net/FTP/Observer.php +++ /dev/null @@ -1,116 +0,0 @@ - - * @author Laurent Laville - * @author Chuck Hagenbuch - * @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 - * @author Chuck Hagenbuch - * @author Tobias Schlitt - * @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); - } - -} -?> diff --git a/gulliver/thirdparty/pear/Net/FTP/Socket.php b/gulliver/thirdparty/pear/Net/FTP/Socket.php deleted file mode 100644 index 72665396b..000000000 --- a/gulliver/thirdparty/pear/Net/FTP/Socket.php +++ /dev/null @@ -1,800 +0,0 @@ - - * @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() [function.ftp-login'. - ']: '.$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() [function.ftp-chdir]: - ' .$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() [function.ftp-chmod]: ' . - 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; -} -?> diff --git a/gulliver/thirdparty/pear/Net/IDNA.php b/gulliver/thirdparty/pear/Net/IDNA.php deleted file mode 100644 index 14749d580..000000000 --- a/gulliver/thirdparty/pear/Net/IDNA.php +++ /dev/null @@ -1,101 +0,0 @@ - - * @author Matthias Sommerfeld - * @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]; - } - // }}} -} - -?> diff --git a/gulliver/thirdparty/pear/Net/IDNA/php4.php b/gulliver/thirdparty/pear/Net/IDNA/php4.php deleted file mode 100644 index 3e93bb474..000000000 --- a/gulliver/thirdparty/pear/Net/IDNA/php4.php +++ /dev/null @@ -1,3011 +0,0 @@ - - * @author Matthias Sommerfeld - * @author Stefan Neufeind - * @package Net - * @version $Id: php4.php,v 1.3 2008/03/22 15:24:17 neufeind Exp $ - */ - -class Net_IDNA_php4 -{ - // {{{ npdata - /** - * These Unicode codepoints are mapped to nothing, - * See RFC3454 for details - * - * @static - * @var array - * @access private - */ - var $_np_map_nothing = array( - 0xAD, - 0x34F, - 0x1806, - 0x180B, - 0x180C, - 0x180D, - 0x200B, - 0x200C, - 0x200D, - 0x2060, - 0xFE00, - 0xFE01, - 0xFE02, - 0xFE03, - 0xFE04, - 0xFE05, - 0xFE06, - 0xFE07, - 0xFE08, - 0xFE09, - 0xFE0A, - 0xFE0B, - 0xFE0C, - 0xFE0D, - 0xFE0E, - 0xFE0F, - 0xFEFF - ); - - /** - * @static - * @var array - * @access private - */ - var $_general_prohibited = array( - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 0xA, - 0xB, - 0xC, - 0xD, - 0xE, - 0xF, - 0x10, - 0x11, - 0x12, - 0x13, - 0x14, - 0x15, - 0x16, - 0x17, - 0x18, - 0x19, - 0x1A, - 0x1B, - 0x1C, - 0x1D, - 0x1E, - 0x1F, - 0x20, - 0x21, - 0x22, - 0x23, - 0x24, - 0x25, - 0x26, - 0x27, - 0x28, - 0x29, - 0x2A, - 0x2B, - 0x2C, - 0x2F, - 0x3B, - 0x3C, - 0x3D, - 0x3E, - 0x3F, - 0x40, - 0x5B, - 0x5C, - 0x5D, - 0x5E, - 0x5F, - 0x60, - 0x7B, - 0x7C, - 0x7D, - 0x7E, - 0x7F, - 0x3002 - ); - - /** - * @static - * @var array - * @access private - */ - var $_np_prohibit = array( - 0xA0, - 0x1680, - 0x2000, - 0x2001, - 0x2002, - 0x2003, - 0x2004, - 0x2005, - 0x2006, - 0x2007, - 0x2008, - 0x2009, - 0x200A, - 0x200B, - 0x202F, - 0x205F, - 0x3000, - 0x6DD, - 0x70F, - 0x180E, - 0x200C, - 0x200D, - 0x2028, - 0x2029, - 0xFEFF, - 0xFFF9, - 0xFFFA, - 0xFFFB, - 0xFFFC, - 0xFFFE, - 0xFFFF, - 0x1FFFE, - 0x1FFFF, - 0x2FFFE, - 0x2FFFF, - 0x3FFFE, - 0x3FFFF, - 0x4FFFE, - 0x4FFFF, - 0x5FFFE, - 0x5FFFF, - 0x6FFFE, - 0x6FFFF, - 0x7FFFE, - 0x7FFFF, - 0x8FFFE, - 0x8FFFF, - 0x9FFFE, - 0x9FFFF, - 0xAFFFE, - 0xAFFFF, - 0xBFFFE, - 0xBFFFF, - 0xCFFFE, - 0xCFFFF, - 0xDFFFE, - 0xDFFFF, - 0xEFFFE, - 0xEFFFF, - 0xFFFFE, - 0xFFFFF, - 0x10FFFE, - 0x10FFFF, - 0xFFF9, - 0xFFFA, - 0xFFFB, - 0xFFFC, - 0xFFFD, - 0x340, - 0x341, - 0x200E, - 0x200F, - 0x202A, - 0x202B, - 0x202C, - 0x202D, - 0x202E, - 0x206A, - 0x206B, - 0x206C, - 0x206D, - 0x206E, - 0x206F, - 0xE0001 - ); - - /** - * @static - * @var array - * @access private - */ - var $_np_prohibit_ranges = array( - array(0x80, 0x9F ), - array(0x2060, 0x206F ), - array(0x1D173, 0x1D17A ), - array(0xE000, 0xF8FF ), - array(0xF0000, 0xFFFFD ), - array(0x100000, 0x10FFFD), - array(0xFDD0, 0xFDEF ), - array(0xD800, 0xDFFF ), - array(0x2FF0, 0x2FFB ), - array(0xE0020, 0xE007F ) - ); - - /** - * @static - * @var array - * @access private - */ - var $_np_replacemaps = array( - 0x41 => array(0x61), - 0x42 => array(0x62), - 0x43 => array(0x63), - 0x44 => array(0x64), - 0x45 => array(0x65), - 0x46 => array(0x66), - 0x47 => array(0x67), - 0x48 => array(0x68), - 0x49 => array(0x69), - 0x4A => array(0x6A), - 0x4B => array(0x6B), - 0x4C => array(0x6C), - 0x4D => array(0x6D), - 0x4E => array(0x6E), - 0x4F => array(0x6F), - 0x50 => array(0x70), - 0x51 => array(0x71), - 0x52 => array(0x72), - 0x53 => array(0x73), - 0x54 => array(0x74), - 0x55 => array(0x75), - 0x56 => array(0x76), - 0x57 => array(0x77), - 0x58 => array(0x78), - 0x59 => array(0x79), - 0x5A => array(0x7A), - 0xB5 => array(0x3BC), - 0xC0 => array(0xE0), - 0xC1 => array(0xE1), - 0xC2 => array(0xE2), - 0xC3 => array(0xE3), - 0xC4 => array(0xE4), - 0xC5 => array(0xE5), - 0xC6 => array(0xE6), - 0xC7 => array(0xE7), - 0xC8 => array(0xE8), - 0xC9 => array(0xE9), - 0xCA => array(0xEA), - 0xCB => array(0xEB), - 0xCC => array(0xEC), - 0xCD => array(0xED), - 0xCE => array(0xEE), - 0xCF => array(0xEF), - 0xD0 => array(0xF0), - 0xD1 => array(0xF1), - 0xD2 => array(0xF2), - 0xD3 => array(0xF3), - 0xD4 => array(0xF4), - 0xD5 => array(0xF5), - 0xD6 => array(0xF6), - 0xD8 => array(0xF8), - 0xD9 => array(0xF9), - 0xDA => array(0xFA), - 0xDB => array(0xFB), - 0xDC => array(0xFC), - 0xDD => array(0xFD), - 0xDE => array(0xFE), - 0xDF => array(0x73, 0x73), - 0x100 => array(0x101), - 0x102 => array(0x103), - 0x104 => array(0x105), - 0x106 => array(0x107), - 0x108 => array(0x109), - 0x10A => array(0x10B), - 0x10C => array(0x10D), - 0x10E => array(0x10F), - 0x110 => array(0x111), - 0x112 => array(0x113), - 0x114 => array(0x115), - 0x116 => array(0x117), - 0x118 => array(0x119), - 0x11A => array(0x11B), - 0x11C => array(0x11D), - 0x11E => array(0x11F), - 0x120 => array(0x121), - 0x122 => array(0x123), - 0x124 => array(0x125), - 0x126 => array(0x127), - 0x128 => array(0x129), - 0x12A => array(0x12B), - 0x12C => array(0x12D), - 0x12E => array(0x12F), - 0x130 => array(0x69, 0x307), - 0x132 => array(0x133), - 0x134 => array(0x135), - 0x136 => array(0x137), - 0x139 => array(0x13A), - 0x13B => array(0x13C), - 0x13D => array(0x13E), - 0x13F => array(0x140), - 0x141 => array(0x142), - 0x143 => array(0x144), - 0x145 => array(0x146), - 0x147 => array(0x148), - 0x149 => array(0x2BC, 0x6E), - 0x14A => array(0x14B), - 0x14C => array(0x14D), - 0x14E => array(0x14F), - 0x150 => array(0x151), - 0x152 => array(0x153), - 0x154 => array(0x155), - 0x156 => array(0x157), - 0x158 => array(0x159), - 0x15A => array(0x15B), - 0x15C => array(0x15D), - 0x15E => array(0x15F), - 0x160 => array(0x161), - 0x162 => array(0x163), - 0x164 => array(0x165), - 0x166 => array(0x167), - 0x168 => array(0x169), - 0x16A => array(0x16B), - 0x16C => array(0x16D), - 0x16E => array(0x16F), - 0x170 => array(0x171), - 0x172 => array(0x173), - 0x174 => array(0x175), - 0x176 => array(0x177), - 0x178 => array(0xFF), - 0x179 => array(0x17A), - 0x17B => array(0x17C), - 0x17D => array(0x17E), - 0x17F => array(0x73), - 0x181 => array(0x253), - 0x182 => array(0x183), - 0x184 => array(0x185), - 0x186 => array(0x254), - 0x187 => array(0x188), - 0x189 => array(0x256), - 0x18A => array(0x257), - 0x18B => array(0x18C), - 0x18E => array(0x1DD), - 0x18F => array(0x259), - 0x190 => array(0x25B), - 0x191 => array(0x192), - 0x193 => array(0x260), - 0x194 => array(0x263), - 0x196 => array(0x269), - 0x197 => array(0x268), - 0x198 => array(0x199), - 0x19C => array(0x26F), - 0x19D => array(0x272), - 0x19F => array(0x275), - 0x1A0 => array(0x1A1), - 0x1A2 => array(0x1A3), - 0x1A4 => array(0x1A5), - 0x1A6 => array(0x280), - 0x1A7 => array(0x1A8), - 0x1A9 => array(0x283), - 0x1AC => array(0x1AD), - 0x1AE => array(0x288), - 0x1AF => array(0x1B0), - 0x1B1 => array(0x28A), - 0x1B2 => array(0x28B), - 0x1B3 => array(0x1B4), - 0x1B5 => array(0x1B6), - 0x1B7 => array(0x292), - 0x1B8 => array(0x1B9), - 0x1BC => array(0x1BD), - 0x1C4 => array(0x1C6), - 0x1C5 => array(0x1C6), - 0x1C7 => array(0x1C9), - 0x1C8 => array(0x1C9), - 0x1CA => array(0x1CC), - 0x1CB => array(0x1CC), - 0x1CD => array(0x1CE), - 0x1CF => array(0x1D0), - 0x1D1 => array(0x1D2), - 0x1D3 => array(0x1D4), - 0x1D5 => array(0x1D6), - 0x1D7 => array(0x1D8), - 0x1D9 => array(0x1DA), - 0x1DB => array(0x1DC), - 0x1DE => array(0x1DF), - 0x1E0 => array(0x1E1), - 0x1E2 => array(0x1E3), - 0x1E4 => array(0x1E5), - 0x1E6 => array(0x1E7), - 0x1E8 => array(0x1E9), - 0x1EA => array(0x1EB), - 0x1EC => array(0x1ED), - 0x1EE => array(0x1EF), - 0x1F0 => array(0x6A, 0x30C), - 0x1F1 => array(0x1F3), - 0x1F2 => array(0x1F3), - 0x1F4 => array(0x1F5), - 0x1F6 => array(0x195), - 0x1F7 => array(0x1BF), - 0x1F8 => array(0x1F9), - 0x1FA => array(0x1FB), - 0x1FC => array(0x1FD), - 0x1FE => array(0x1FF), - 0x200 => array(0x201), - 0x202 => array(0x203), - 0x204 => array(0x205), - 0x206 => array(0x207), - 0x208 => array(0x209), - 0x20A => array(0x20B), - 0x20C => array(0x20D), - 0x20E => array(0x20F), - 0x210 => array(0x211), - 0x212 => array(0x213), - 0x214 => array(0x215), - 0x216 => array(0x217), - 0x218 => array(0x219), - 0x21A => array(0x21B), - 0x21C => array(0x21D), - 0x21E => array(0x21F), - 0x220 => array(0x19E), - 0x222 => array(0x223), - 0x224 => array(0x225), - 0x226 => array(0x227), - 0x228 => array(0x229), - 0x22A => array(0x22B), - 0x22C => array(0x22D), - 0x22E => array(0x22F), - 0x230 => array(0x231), - 0x232 => array(0x233), - 0x345 => array(0x3B9), - 0x37A => array(0x20, 0x3B9), - 0x386 => array(0x3AC), - 0x388 => array(0x3AD), - 0x389 => array(0x3AE), - 0x38A => array(0x3AF), - 0x38C => array(0x3CC), - 0x38E => array(0x3CD), - 0x38F => array(0x3CE), - 0x390 => array(0x3B9, 0x308, 0x301), - 0x391 => array(0x3B1), - 0x392 => array(0x3B2), - 0x393 => array(0x3B3), - 0x394 => array(0x3B4), - 0x395 => array(0x3B5), - 0x396 => array(0x3B6), - 0x397 => array(0x3B7), - 0x398 => array(0x3B8), - 0x399 => array(0x3B9), - 0x39A => array(0x3BA), - 0x39B => array(0x3BB), - 0x39C => array(0x3BC), - 0x39D => array(0x3BD), - 0x39E => array(0x3BE), - 0x39F => array(0x3BF), - 0x3A0 => array(0x3C0), - 0x3A1 => array(0x3C1), - 0x3A3 => array(0x3C3), - 0x3A4 => array(0x3C4), - 0x3A5 => array(0x3C5), - 0x3A6 => array(0x3C6), - 0x3A7 => array(0x3C7), - 0x3A8 => array(0x3C8), - 0x3A9 => array(0x3C9), - 0x3AA => array(0x3CA), - 0x3AB => array(0x3CB), - 0x3B0 => array(0x3C5, 0x308, 0x301), - 0x3C2 => array(0x3C3), - 0x3D0 => array(0x3B2), - 0x3D1 => array(0x3B8), - 0x3D2 => array(0x3C5), - 0x3D3 => array(0x3CD), - 0x3D4 => array(0x3CB), - 0x3D5 => array(0x3C6), - 0x3D6 => array(0x3C0), - 0x3D8 => array(0x3D9), - 0x3DA => array(0x3DB), - 0x3DC => array(0x3DD), - 0x3DE => array(0x3DF), - 0x3E0 => array(0x3E1), - 0x3E2 => array(0x3E3), - 0x3E4 => array(0x3E5), - 0x3E6 => array(0x3E7), - 0x3E8 => array(0x3E9), - 0x3EA => array(0x3EB), - 0x3EC => array(0x3ED), - 0x3EE => array(0x3EF), - 0x3F0 => array(0x3BA), - 0x3F1 => array(0x3C1), - 0x3F2 => array(0x3C3), - 0x3F4 => array(0x3B8), - 0x3F5 => array(0x3B5), - 0x400 => array(0x450), - 0x401 => array(0x451), - 0x402 => array(0x452), - 0x403 => array(0x453), - 0x404 => array(0x454), - 0x405 => array(0x455), - 0x406 => array(0x456), - 0x407 => array(0x457), - 0x408 => array(0x458), - 0x409 => array(0x459), - 0x40A => array(0x45A), - 0x40B => array(0x45B), - 0x40C => array(0x45C), - 0x40D => array(0x45D), - 0x40E => array(0x45E), - 0x40F => array(0x45F), - 0x410 => array(0x430), - 0x411 => array(0x431), - 0x412 => array(0x432), - 0x413 => array(0x433), - 0x414 => array(0x434), - 0x415 => array(0x435), - 0x416 => array(0x436), - 0x417 => array(0x437), - 0x418 => array(0x438), - 0x419 => array(0x439), - 0x41A => array(0x43A), - 0x41B => array(0x43B), - 0x41C => array(0x43C), - 0x41D => array(0x43D), - 0x41E => array(0x43E), - 0x41F => array(0x43F), - 0x420 => array(0x440), - 0x421 => array(0x441), - 0x422 => array(0x442), - 0x423 => array(0x443), - 0x424 => array(0x444), - 0x425 => array(0x445), - 0x426 => array(0x446), - 0x427 => array(0x447), - 0x428 => array(0x448), - 0x429 => array(0x449), - 0x42A => array(0x44A), - 0x42B => array(0x44B), - 0x42C => array(0x44C), - 0x42D => array(0x44D), - 0x42E => array(0x44E), - 0x42F => array(0x44F), - 0x460 => array(0x461), - 0x462 => array(0x463), - 0x464 => array(0x465), - 0x466 => array(0x467), - 0x468 => array(0x469), - 0x46A => array(0x46B), - 0x46C => array(0x46D), - 0x46E => array(0x46F), - 0x470 => array(0x471), - 0x472 => array(0x473), - 0x474 => array(0x475), - 0x476 => array(0x477), - 0x478 => array(0x479), - 0x47A => array(0x47B), - 0x47C => array(0x47D), - 0x47E => array(0x47F), - 0x480 => array(0x481), - 0x48A => array(0x48B), - 0x48C => array(0x48D), - 0x48E => array(0x48F), - 0x490 => array(0x491), - 0x492 => array(0x493), - 0x494 => array(0x495), - 0x496 => array(0x497), - 0x498 => array(0x499), - 0x49A => array(0x49B), - 0x49C => array(0x49D), - 0x49E => array(0x49F), - 0x4A0 => array(0x4A1), - 0x4A2 => array(0x4A3), - 0x4A4 => array(0x4A5), - 0x4A6 => array(0x4A7), - 0x4A8 => array(0x4A9), - 0x4AA => array(0x4AB), - 0x4AC => array(0x4AD), - 0x4AE => array(0x4AF), - 0x4B0 => array(0x4B1), - 0x4B2 => array(0x4B3), - 0x4B4 => array(0x4B5), - 0x4B6 => array(0x4B7), - 0x4B8 => array(0x4B9), - 0x4BA => array(0x4BB), - 0x4BC => array(0x4BD), - 0x4BE => array(0x4BF), - 0x4C1 => array(0x4C2), - 0x4C3 => array(0x4C4), - 0x4C5 => array(0x4C6), - 0x4C7 => array(0x4C8), - 0x4C9 => array(0x4CA), - 0x4CB => array(0x4CC), - 0x4CD => array(0x4CE), - 0x4D0 => array(0x4D1), - 0x4D2 => array(0x4D3), - 0x4D4 => array(0x4D5), - 0x4D6 => array(0x4D7), - 0x4D8 => array(0x4D9), - 0x4DA => array(0x4DB), - 0x4DC => array(0x4DD), - 0x4DE => array(0x4DF), - 0x4E0 => array(0x4E1), - 0x4E2 => array(0x4E3), - 0x4E4 => array(0x4E5), - 0x4E6 => array(0x4E7), - 0x4E8 => array(0x4E9), - 0x4EA => array(0x4EB), - 0x4EC => array(0x4ED), - 0x4EE => array(0x4EF), - 0x4F0 => array(0x4F1), - 0x4F2 => array(0x4F3), - 0x4F4 => array(0x4F5), - 0x4F8 => array(0x4F9), - 0x500 => array(0x501), - 0x502 => array(0x503), - 0x504 => array(0x505), - 0x506 => array(0x507), - 0x508 => array(0x509), - 0x50A => array(0x50B), - 0x50C => array(0x50D), - 0x50E => array(0x50F), - 0x531 => array(0x561), - 0x532 => array(0x562), - 0x533 => array(0x563), - 0x534 => array(0x564), - 0x535 => array(0x565), - 0x536 => array(0x566), - 0x537 => array(0x567), - 0x538 => array(0x568), - 0x539 => array(0x569), - 0x53A => array(0x56A), - 0x53B => array(0x56B), - 0x53C => array(0x56C), - 0x53D => array(0x56D), - 0x53E => array(0x56E), - 0x53F => array(0x56F), - 0x540 => array(0x570), - 0x541 => array(0x571), - 0x542 => array(0x572), - 0x543 => array(0x573), - 0x544 => array(0x574), - 0x545 => array(0x575), - 0x546 => array(0x576), - 0x547 => array(0x577), - 0x548 => array(0x578), - 0x549 => array(0x579), - 0x54A => array(0x57A), - 0x54B => array(0x57B), - 0x54C => array(0x57C), - 0x54D => array(0x57D), - 0x54E => array(0x57E), - 0x54F => array(0x57F), - 0x550 => array(0x580), - 0x551 => array(0x581), - 0x552 => array(0x582), - 0x553 => array(0x583), - 0x554 => array(0x584), - 0x555 => array(0x585), - 0x556 => array(0x586), - 0x587 => array(0x565, 0x582), - 0x1E00 => array(0x1E01), - 0x1E02 => array(0x1E03), - 0x1E04 => array(0x1E05), - 0x1E06 => array(0x1E07), - 0x1E08 => array(0x1E09), - 0x1E0A => array(0x1E0B), - 0x1E0C => array(0x1E0D), - 0x1E0E => array(0x1E0F), - 0x1E10 => array(0x1E11), - 0x1E12 => array(0x1E13), - 0x1E14 => array(0x1E15), - 0x1E16 => array(0x1E17), - 0x1E18 => array(0x1E19), - 0x1E1A => array(0x1E1B), - 0x1E1C => array(0x1E1D), - 0x1E1E => array(0x1E1F), - 0x1E20 => array(0x1E21), - 0x1E22 => array(0x1E23), - 0x1E24 => array(0x1E25), - 0x1E26 => array(0x1E27), - 0x1E28 => array(0x1E29), - 0x1E2A => array(0x1E2B), - 0x1E2C => array(0x1E2D), - 0x1E2E => array(0x1E2F), - 0x1E30 => array(0x1E31), - 0x1E32 => array(0x1E33), - 0x1E34 => array(0x1E35), - 0x1E36 => array(0x1E37), - 0x1E38 => array(0x1E39), - 0x1E3A => array(0x1E3B), - 0x1E3C => array(0x1E3D), - 0x1E3E => array(0x1E3F), - 0x1E40 => array(0x1E41), - 0x1E42 => array(0x1E43), - 0x1E44 => array(0x1E45), - 0x1E46 => array(0x1E47), - 0x1E48 => array(0x1E49), - 0x1E4A => array(0x1E4B), - 0x1E4C => array(0x1E4D), - 0x1E4E => array(0x1E4F), - 0x1E50 => array(0x1E51), - 0x1E52 => array(0x1E53), - 0x1E54 => array(0x1E55), - 0x1E56 => array(0x1E57), - 0x1E58 => array(0x1E59), - 0x1E5A => array(0x1E5B), - 0x1E5C => array(0x1E5D), - 0x1E5E => array(0x1E5F), - 0x1E60 => array(0x1E61), - 0x1E62 => array(0x1E63), - 0x1E64 => array(0x1E65), - 0x1E66 => array(0x1E67), - 0x1E68 => array(0x1E69), - 0x1E6A => array(0x1E6B), - 0x1E6C => array(0x1E6D), - 0x1E6E => array(0x1E6F), - 0x1E70 => array(0x1E71), - 0x1E72 => array(0x1E73), - 0x1E74 => array(0x1E75), - 0x1E76 => array(0x1E77), - 0x1E78 => array(0x1E79), - 0x1E7A => array(0x1E7B), - 0x1E7C => array(0x1E7D), - 0x1E7E => array(0x1E7F), - 0x1E80 => array(0x1E81), - 0x1E82 => array(0x1E83), - 0x1E84 => array(0x1E85), - 0x1E86 => array(0x1E87), - 0x1E88 => array(0x1E89), - 0x1E8A => array(0x1E8B), - 0x1E8C => array(0x1E8D), - 0x1E8E => array(0x1E8F), - 0x1E90 => array(0x1E91), - 0x1E92 => array(0x1E93), - 0x1E94 => array(0x1E95), - 0x1E96 => array(0x68, 0x331), - 0x1E97 => array(0x74, 0x308), - 0x1E98 => array(0x77, 0x30A), - 0x1E99 => array(0x79, 0x30A), - 0x1E9A => array(0x61, 0x2BE), - 0x1E9B => array(0x1E61), - 0x1EA0 => array(0x1EA1), - 0x1EA2 => array(0x1EA3), - 0x1EA4 => array(0x1EA5), - 0x1EA6 => array(0x1EA7), - 0x1EA8 => array(0x1EA9), - 0x1EAA => array(0x1EAB), - 0x1EAC => array(0x1EAD), - 0x1EAE => array(0x1EAF), - 0x1EB0 => array(0x1EB1), - 0x1EB2 => array(0x1EB3), - 0x1EB4 => array(0x1EB5), - 0x1EB6 => array(0x1EB7), - 0x1EB8 => array(0x1EB9), - 0x1EBA => array(0x1EBB), - 0x1EBC => array(0x1EBD), - 0x1EBE => array(0x1EBF), - 0x1EC0 => array(0x1EC1), - 0x1EC2 => array(0x1EC3), - 0x1EC4 => array(0x1EC5), - 0x1EC6 => array(0x1EC7), - 0x1EC8 => array(0x1EC9), - 0x1ECA => array(0x1ECB), - 0x1ECC => array(0x1ECD), - 0x1ECE => array(0x1ECF), - 0x1ED0 => array(0x1ED1), - 0x1ED2 => array(0x1ED3), - 0x1ED4 => array(0x1ED5), - 0x1ED6 => array(0x1ED7), - 0x1ED8 => array(0x1ED9), - 0x1EDA => array(0x1EDB), - 0x1EDC => array(0x1EDD), - 0x1EDE => array(0x1EDF), - 0x1EE0 => array(0x1EE1), - 0x1EE2 => array(0x1EE3), - 0x1EE4 => array(0x1EE5), - 0x1EE6 => array(0x1EE7), - 0x1EE8 => array(0x1EE9), - 0x1EEA => array(0x1EEB), - 0x1EEC => array(0x1EED), - 0x1EEE => array(0x1EEF), - 0x1EF0 => array(0x1EF1), - 0x1EF2 => array(0x1EF3), - 0x1EF4 => array(0x1EF5), - 0x1EF6 => array(0x1EF7), - 0x1EF8 => array(0x1EF9), - 0x1F08 => array(0x1F00), - 0x1F09 => array(0x1F01), - 0x1F0A => array(0x1F02), - 0x1F0B => array(0x1F03), - 0x1F0C => array(0x1F04), - 0x1F0D => array(0x1F05), - 0x1F0E => array(0x1F06), - 0x1F0F => array(0x1F07), - 0x1F18 => array(0x1F10), - 0x1F19 => array(0x1F11), - 0x1F1A => array(0x1F12), - 0x1F1B => array(0x1F13), - 0x1F1C => array(0x1F14), - 0x1F1D => array(0x1F15), - 0x1F28 => array(0x1F20), - 0x1F29 => array(0x1F21), - 0x1F2A => array(0x1F22), - 0x1F2B => array(0x1F23), - 0x1F2C => array(0x1F24), - 0x1F2D => array(0x1F25), - 0x1F2E => array(0x1F26), - 0x1F2F => array(0x1F27), - 0x1F38 => array(0x1F30), - 0x1F39 => array(0x1F31), - 0x1F3A => array(0x1F32), - 0x1F3B => array(0x1F33), - 0x1F3C => array(0x1F34), - 0x1F3D => array(0x1F35), - 0x1F3E => array(0x1F36), - 0x1F3F => array(0x1F37), - 0x1F48 => array(0x1F40), - 0x1F49 => array(0x1F41), - 0x1F4A => array(0x1F42), - 0x1F4B => array(0x1F43), - 0x1F4C => array(0x1F44), - 0x1F4D => array(0x1F45), - 0x1F50 => array(0x3C5, 0x313), - 0x1F52 => array(0x3C5, 0x313, 0x300), - 0x1F54 => array(0x3C5, 0x313, 0x301), - 0x1F56 => array(0x3C5, 0x313, 0x342), - 0x1F59 => array(0x1F51), - 0x1F5B => array(0x1F53), - 0x1F5D => array(0x1F55), - 0x1F5F => array(0x1F57), - 0x1F68 => array(0x1F60), - 0x1F69 => array(0x1F61), - 0x1F6A => array(0x1F62), - 0x1F6B => array(0x1F63), - 0x1F6C => array(0x1F64), - 0x1F6D => array(0x1F65), - 0x1F6E => array(0x1F66), - 0x1F6F => array(0x1F67), - 0x1F80 => array(0x1F00, 0x3B9), - 0x1F81 => array(0x1F01, 0x3B9), - 0x1F82 => array(0x1F02, 0x3B9), - 0x1F83 => array(0x1F03, 0x3B9), - 0x1F84 => array(0x1F04, 0x3B9), - 0x1F85 => array(0x1F05, 0x3B9), - 0x1F86 => array(0x1F06, 0x3B9), - 0x1F87 => array(0x1F07, 0x3B9), - 0x1F88 => array(0x1F00, 0x3B9), - 0x1F89 => array(0x1F01, 0x3B9), - 0x1F8A => array(0x1F02, 0x3B9), - 0x1F8B => array(0x1F03, 0x3B9), - 0x1F8C => array(0x1F04, 0x3B9), - 0x1F8D => array(0x1F05, 0x3B9), - 0x1F8E => array(0x1F06, 0x3B9), - 0x1F8F => array(0x1F07, 0x3B9), - 0x1F90 => array(0x1F20, 0x3B9), - 0x1F91 => array(0x1F21, 0x3B9), - 0x1F92 => array(0x1F22, 0x3B9), - 0x1F93 => array(0x1F23, 0x3B9), - 0x1F94 => array(0x1F24, 0x3B9), - 0x1F95 => array(0x1F25, 0x3B9), - 0x1F96 => array(0x1F26, 0x3B9), - 0x1F97 => array(0x1F27, 0x3B9), - 0x1F98 => array(0x1F20, 0x3B9), - 0x1F99 => array(0x1F21, 0x3B9), - 0x1F9A => array(0x1F22, 0x3B9), - 0x1F9B => array(0x1F23, 0x3B9), - 0x1F9C => array(0x1F24, 0x3B9), - 0x1F9D => array(0x1F25, 0x3B9), - 0x1F9E => array(0x1F26, 0x3B9), - 0x1F9F => array(0x1F27, 0x3B9), - 0x1FA0 => array(0x1F60, 0x3B9), - 0x1FA1 => array(0x1F61, 0x3B9), - 0x1FA2 => array(0x1F62, 0x3B9), - 0x1FA3 => array(0x1F63, 0x3B9), - 0x1FA4 => array(0x1F64, 0x3B9), - 0x1FA5 => array(0x1F65, 0x3B9), - 0x1FA6 => array(0x1F66, 0x3B9), - 0x1FA7 => array(0x1F67, 0x3B9), - 0x1FA8 => array(0x1F60, 0x3B9), - 0x1FA9 => array(0x1F61, 0x3B9), - 0x1FAA => array(0x1F62, 0x3B9), - 0x1FAB => array(0x1F63, 0x3B9), - 0x1FAC => array(0x1F64, 0x3B9), - 0x1FAD => array(0x1F65, 0x3B9), - 0x1FAE => array(0x1F66, 0x3B9), - 0x1FAF => array(0x1F67, 0x3B9), - 0x1FB2 => array(0x1F70, 0x3B9), - 0x1FB3 => array(0x3B1, 0x3B9), - 0x1FB4 => array(0x3AC, 0x3B9), - 0x1FB6 => array(0x3B1, 0x342), - 0x1FB7 => array(0x3B1, 0x342, 0x3B9), - 0x1FB8 => array(0x1FB0), - 0x1FB9 => array(0x1FB1), - 0x1FBA => array(0x1F70), - 0x1FBB => array(0x1F71), - 0x1FBC => array(0x3B1, 0x3B9), - 0x1FBE => array(0x3B9), - 0x1FC2 => array(0x1F74, 0x3B9), - 0x1FC3 => array(0x3B7, 0x3B9), - 0x1FC4 => array(0x3AE, 0x3B9), - 0x1FC6 => array(0x3B7, 0x342), - 0x1FC7 => array(0x3B7, 0x342, 0x3B9), - 0x1FC8 => array(0x1F72), - 0x1FC9 => array(0x1F73), - 0x1FCA => array(0x1F74), - 0x1FCB => array(0x1F75), - 0x1FCC => array(0x3B7, 0x3B9), - 0x1FD2 => array(0x3B9, 0x308, 0x300), - 0x1FD3 => array(0x3B9, 0x308, 0x301), - 0x1FD6 => array(0x3B9, 0x342), - 0x1FD7 => array(0x3B9, 0x308, 0x342), - 0x1FD8 => array(0x1FD0), - 0x1FD9 => array(0x1FD1), - 0x1FDA => array(0x1F76), - 0x1FDB => array(0x1F77), - 0x1FE2 => array(0x3C5, 0x308, 0x300), - 0x1FE3 => array(0x3C5, 0x308, 0x301), - 0x1FE4 => array(0x3C1, 0x313), - 0x1FE6 => array(0x3C5, 0x342), - 0x1FE7 => array(0x3C5, 0x308, 0x342), - 0x1FE8 => array(0x1FE0), - 0x1FE9 => array(0x1FE1), - 0x1FEA => array(0x1F7A), - 0x1FEB => array(0x1F7B), - 0x1FEC => array(0x1FE5), - 0x1FF2 => array(0x1F7C, 0x3B9), - 0x1FF3 => array(0x3C9, 0x3B9), - 0x1FF4 => array(0x3CE, 0x3B9), - 0x1FF6 => array(0x3C9, 0x342), - 0x1FF7 => array(0x3C9, 0x342, 0x3B9), - 0x1FF8 => array(0x1F78), - 0x1FF9 => array(0x1F79), - 0x1FFA => array(0x1F7C), - 0x1FFB => array(0x1F7D), - 0x1FFC => array(0x3C9, 0x3B9), - 0x20A8 => array(0x72, 0x73), - 0x2102 => array(0x63), - 0x2103 => array(0xB0, 0x63), - 0x2107 => array(0x25B), - 0x2109 => array(0xB0, 0x66), - 0x210B => array(0x68), - 0x210C => array(0x68), - 0x210D => array(0x68), - 0x2110 => array(0x69), - 0x2111 => array(0x69), - 0x2112 => array(0x6C), - 0x2115 => array(0x6E), - 0x2116 => array(0x6E, 0x6F), - 0x2119 => array(0x70), - 0x211A => array(0x71), - 0x211B => array(0x72), - 0x211C => array(0x72), - 0x211D => array(0x72), - 0x2120 => array(0x73, 0x6D), - 0x2121 => array(0x74, 0x65, 0x6C), - 0x2122 => array(0x74, 0x6D), - 0x2124 => array(0x7A), - 0x2126 => array(0x3C9), - 0x2128 => array(0x7A), - 0x212A => array(0x6B), - 0x212B => array(0xE5), - 0x212C => array(0x62), - 0x212D => array(0x63), - 0x2130 => array(0x65), - 0x2131 => array(0x66), - 0x2133 => array(0x6D), - 0x213E => array(0x3B3), - 0x213F => array(0x3C0), - 0x2145 => array(0x64), - 0x2160 => array(0x2170), - 0x2161 => array(0x2171), - 0x2162 => array(0x2172), - 0x2163 => array(0x2173), - 0x2164 => array(0x2174), - 0x2165 => array(0x2175), - 0x2166 => array(0x2176), - 0x2167 => array(0x2177), - 0x2168 => array(0x2178), - 0x2169 => array(0x2179), - 0x216A => array(0x217A), - 0x216B => array(0x217B), - 0x216C => array(0x217C), - 0x216D => array(0x217D), - 0x216E => array(0x217E), - 0x216F => array(0x217F), - 0x24B6 => array(0x24D0), - 0x24B7 => array(0x24D1), - 0x24B8 => array(0x24D2), - 0x24B9 => array(0x24D3), - 0x24BA => array(0x24D4), - 0x24BB => array(0x24D5), - 0x24BC => array(0x24D6), - 0x24BD => array(0x24D7), - 0x24BE => array(0x24D8), - 0x24BF => array(0x24D9), - 0x24C0 => array(0x24DA), - 0x24C1 => array(0x24DB), - 0x24C2 => array(0x24DC), - 0x24C3 => array(0x24DD), - 0x24C4 => array(0x24DE), - 0x24C5 => array(0x24DF), - 0x24C6 => array(0x24E0), - 0x24C7 => array(0x24E1), - 0x24C8 => array(0x24E2), - 0x24C9 => array(0x24E3), - 0x24CA => array(0x24E4), - 0x24CB => array(0x24E5), - 0x24CC => array(0x24E6), - 0x24CD => array(0x24E7), - 0x24CE => array(0x24E8), - 0x24CF => array(0x24E9), - 0x3371 => array(0x68, 0x70, 0x61), - 0x3373 => array(0x61, 0x75), - 0x3375 => array(0x6F, 0x76), - 0x3380 => array(0x70, 0x61), - 0x3381 => array(0x6E, 0x61), - 0x3382 => array(0x3BC, 0x61), - 0x3383 => array(0x6D, 0x61), - 0x3384 => array(0x6B, 0x61), - 0x3385 => array(0x6B, 0x62), - 0x3386 => array(0x6D, 0x62), - 0x3387 => array(0x67, 0x62), - 0x338A => array(0x70, 0x66), - 0x338B => array(0x6E, 0x66), - 0x338C => array(0x3BC, 0x66), - 0x3390 => array(0x68, 0x7A), - 0x3391 => array(0x6B, 0x68, 0x7A), - 0x3392 => array(0x6D, 0x68, 0x7A), - 0x3393 => array(0x67, 0x68, 0x7A), - 0x3394 => array(0x74, 0x68, 0x7A), - 0x33A9 => array(0x70, 0x61), - 0x33AA => array(0x6B, 0x70, 0x61), - 0x33AB => array(0x6D, 0x70, 0x61), - 0x33AC => array(0x67, 0x70, 0x61), - 0x33B4 => array(0x70, 0x76), - 0x33B5 => array(0x6E, 0x76), - 0x33B6 => array(0x3BC, 0x76), - 0x33B7 => array(0x6D, 0x76), - 0x33B8 => array(0x6B, 0x76), - 0x33B9 => array(0x6D, 0x76), - 0x33BA => array(0x70, 0x77), - 0x33BB => array(0x6E, 0x77), - 0x33BC => array(0x3BC, 0x77), - 0x33BD => array(0x6D, 0x77), - 0x33BE => array(0x6B, 0x77), - 0x33BF => array(0x6D, 0x77), - 0x33C0 => array(0x6B, 0x3C9), - 0x33C1 => array(0x6D, 0x3C9), /* - 0x33C2 => array(0x61, 0x2E, 0x6D, 0x2E), */ - 0x33C3 => array(0x62, 0x71), - 0x33C6 => array(0x63, 0x2215, 0x6B, 0x67), - 0x33C7 => array(0x63, 0x6F, 0x2E), - 0x33C8 => array(0x64, 0x62), - 0x33C9 => array(0x67, 0x79), - 0x33CB => array(0x68, 0x70), - 0x33CD => array(0x6B, 0x6B), - 0x33CE => array(0x6B, 0x6D), - 0x33D7 => array(0x70, 0x68), - 0x33D9 => array(0x70, 0x70, 0x6D), - 0x33DA => array(0x70, 0x72), - 0x33DC => array(0x73, 0x76), - 0x33DD => array(0x77, 0x62), - 0xFB00 => array(0x66, 0x66), - 0xFB01 => array(0x66, 0x69), - 0xFB02 => array(0x66, 0x6C), - 0xFB03 => array(0x66, 0x66, 0x69), - 0xFB04 => array(0x66, 0x66, 0x6C), - 0xFB05 => array(0x73, 0x74), - 0xFB06 => array(0x73, 0x74), - 0xFB13 => array(0x574, 0x576), - 0xFB14 => array(0x574, 0x565), - 0xFB15 => array(0x574, 0x56B), - 0xFB16 => array(0x57E, 0x576), - 0xFB17 => array(0x574, 0x56D), - 0xFF21 => array(0xFF41), - 0xFF22 => array(0xFF42), - 0xFF23 => array(0xFF43), - 0xFF24 => array(0xFF44), - 0xFF25 => array(0xFF45), - 0xFF26 => array(0xFF46), - 0xFF27 => array(0xFF47), - 0xFF28 => array(0xFF48), - 0xFF29 => array(0xFF49), - 0xFF2A => array(0xFF4A), - 0xFF2B => array(0xFF4B), - 0xFF2C => array(0xFF4C), - 0xFF2D => array(0xFF4D), - 0xFF2E => array(0xFF4E), - 0xFF2F => array(0xFF4F), - 0xFF30 => array(0xFF50), - 0xFF31 => array(0xFF51), - 0xFF32 => array(0xFF52), - 0xFF33 => array(0xFF53), - 0xFF34 => array(0xFF54), - 0xFF35 => array(0xFF55), - 0xFF36 => array(0xFF56), - 0xFF37 => array(0xFF57), - 0xFF38 => array(0xFF58), - 0xFF39 => array(0xFF59), - 0xFF3A => array(0xFF5A), - 0x10400 => array(0x10428), - 0x10401 => array(0x10429), - 0x10402 => array(0x1042A), - 0x10403 => array(0x1042B), - 0x10404 => array(0x1042C), - 0x10405 => array(0x1042D), - 0x10406 => array(0x1042E), - 0x10407 => array(0x1042F), - 0x10408 => array(0x10430), - 0x10409 => array(0x10431), - 0x1040A => array(0x10432), - 0x1040B => array(0x10433), - 0x1040C => array(0x10434), - 0x1040D => array(0x10435), - 0x1040E => array(0x10436), - 0x1040F => array(0x10437), - 0x10410 => array(0x10438), - 0x10411 => array(0x10439), - 0x10412 => array(0x1043A), - 0x10413 => array(0x1043B), - 0x10414 => array(0x1043C), - 0x10415 => array(0x1043D), - 0x10416 => array(0x1043E), - 0x10417 => array(0x1043F), - 0x10418 => array(0x10440), - 0x10419 => array(0x10441), - 0x1041A => array(0x10442), - 0x1041B => array(0x10443), - 0x1041C => array(0x10444), - 0x1041D => array(0x10445), - 0x1041E => array(0x10446), - 0x1041F => array(0x10447), - 0x10420 => array(0x10448), - 0x10421 => array(0x10449), - 0x10422 => array(0x1044A), - 0x10423 => array(0x1044B), - 0x10424 => array(0x1044C), - 0x10425 => array(0x1044D), - 0x1D400 => array(0x61), - 0x1D401 => array(0x62), - 0x1D402 => array(0x63), - 0x1D403 => array(0x64), - 0x1D404 => array(0x65), - 0x1D405 => array(0x66), - 0x1D406 => array(0x67), - 0x1D407 => array(0x68), - 0x1D408 => array(0x69), - 0x1D409 => array(0x6A), - 0x1D40A => array(0x6B), - 0x1D40B => array(0x6C), - 0x1D40C => array(0x6D), - 0x1D40D => array(0x6E), - 0x1D40E => array(0x6F), - 0x1D40F => array(0x70), - 0x1D410 => array(0x71), - 0x1D411 => array(0x72), - 0x1D412 => array(0x73), - 0x1D413 => array(0x74), - 0x1D414 => array(0x75), - 0x1D415 => array(0x76), - 0x1D416 => array(0x77), - 0x1D417 => array(0x78), - 0x1D418 => array(0x79), - 0x1D419 => array(0x7A), - 0x1D434 => array(0x61), - 0x1D435 => array(0x62), - 0x1D436 => array(0x63), - 0x1D437 => array(0x64), - 0x1D438 => array(0x65), - 0x1D439 => array(0x66), - 0x1D43A => array(0x67), - 0x1D43B => array(0x68), - 0x1D43C => array(0x69), - 0x1D43D => array(0x6A), - 0x1D43E => array(0x6B), - 0x1D43F => array(0x6C), - 0x1D440 => array(0x6D), - 0x1D441 => array(0x6E), - 0x1D442 => array(0x6F), - 0x1D443 => array(0x70), - 0x1D444 => array(0x71), - 0x1D445 => array(0x72), - 0x1D446 => array(0x73), - 0x1D447 => array(0x74), - 0x1D448 => array(0x75), - 0x1D449 => array(0x76), - 0x1D44A => array(0x77), - 0x1D44B => array(0x78), - 0x1D44C => array(0x79), - 0x1D44D => array(0x7A), - 0x1D468 => array(0x61), - 0x1D469 => array(0x62), - 0x1D46A => array(0x63), - 0x1D46B => array(0x64), - 0x1D46C => array(0x65), - 0x1D46D => array(0x66), - 0x1D46E => array(0x67), - 0x1D46F => array(0x68), - 0x1D470 => array(0x69), - 0x1D471 => array(0x6A), - 0x1D472 => array(0x6B), - 0x1D473 => array(0x6C), - 0x1D474 => array(0x6D), - 0x1D475 => array(0x6E), - 0x1D476 => array(0x6F), - 0x1D477 => array(0x70), - 0x1D478 => array(0x71), - 0x1D479 => array(0x72), - 0x1D47A => array(0x73), - 0x1D47B => array(0x74), - 0x1D47C => array(0x75), - 0x1D47D => array(0x76), - 0x1D47E => array(0x77), - 0x1D47F => array(0x78), - 0x1D480 => array(0x79), - 0x1D481 => array(0x7A), - 0x1D49C => array(0x61), - 0x1D49E => array(0x63), - 0x1D49F => array(0x64), - 0x1D4A2 => array(0x67), - 0x1D4A5 => array(0x6A), - 0x1D4A6 => array(0x6B), - 0x1D4A9 => array(0x6E), - 0x1D4AA => array(0x6F), - 0x1D4AB => array(0x70), - 0x1D4AC => array(0x71), - 0x1D4AE => array(0x73), - 0x1D4AF => array(0x74), - 0x1D4B0 => array(0x75), - 0x1D4B1 => array(0x76), - 0x1D4B2 => array(0x77), - 0x1D4B3 => array(0x78), - 0x1D4B4 => array(0x79), - 0x1D4B5 => array(0x7A), - 0x1D4D0 => array(0x61), - 0x1D4D1 => array(0x62), - 0x1D4D2 => array(0x63), - 0x1D4D3 => array(0x64), - 0x1D4D4 => array(0x65), - 0x1D4D5 => array(0x66), - 0x1D4D6 => array(0x67), - 0x1D4D7 => array(0x68), - 0x1D4D8 => array(0x69), - 0x1D4D9 => array(0x6A), - 0x1D4DA => array(0x6B), - 0x1D4DB => array(0x6C), - 0x1D4DC => array(0x6D), - 0x1D4DD => array(0x6E), - 0x1D4DE => array(0x6F), - 0x1D4DF => array(0x70), - 0x1D4E0 => array(0x71), - 0x1D4E1 => array(0x72), - 0x1D4E2 => array(0x73), - 0x1D4E3 => array(0x74), - 0x1D4E4 => array(0x75), - 0x1D4E5 => array(0x76), - 0x1D4E6 => array(0x77), - 0x1D4E7 => array(0x78), - 0x1D4E8 => array(0x79), - 0x1D4E9 => array(0x7A), - 0x1D504 => array(0x61), - 0x1D505 => array(0x62), - 0x1D507 => array(0x64), - 0x1D508 => array(0x65), - 0x1D509 => array(0x66), - 0x1D50A => array(0x67), - 0x1D50D => array(0x6A), - 0x1D50E => array(0x6B), - 0x1D50F => array(0x6C), - 0x1D510 => array(0x6D), - 0x1D511 => array(0x6E), - 0x1D512 => array(0x6F), - 0x1D513 => array(0x70), - 0x1D514 => array(0x71), - 0x1D516 => array(0x73), - 0x1D517 => array(0x74), - 0x1D518 => array(0x75), - 0x1D519 => array(0x76), - 0x1D51A => array(0x77), - 0x1D51B => array(0x78), - 0x1D51C => array(0x79), - 0x1D538 => array(0x61), - 0x1D539 => array(0x62), - 0x1D53B => array(0x64), - 0x1D53C => array(0x65), - 0x1D53D => array(0x66), - 0x1D53E => array(0x67), - 0x1D540 => array(0x69), - 0x1D541 => array(0x6A), - 0x1D542 => array(0x6B), - 0x1D543 => array(0x6C), - 0x1D544 => array(0x6D), - 0x1D546 => array(0x6F), - 0x1D54A => array(0x73), - 0x1D54B => array(0x74), - 0x1D54C => array(0x75), - 0x1D54D => array(0x76), - 0x1D54E => array(0x77), - 0x1D54F => array(0x78), - 0x1D550 => array(0x79), - 0x1D56C => array(0x61), - 0x1D56D => array(0x62), - 0x1D56E => array(0x63), - 0x1D56F => array(0x64), - 0x1D570 => array(0x65), - 0x1D571 => array(0x66), - 0x1D572 => array(0x67), - 0x1D573 => array(0x68), - 0x1D574 => array(0x69), - 0x1D575 => array(0x6A), - 0x1D576 => array(0x6B), - 0x1D577 => array(0x6C), - 0x1D578 => array(0x6D), - 0x1D579 => array(0x6E), - 0x1D57A => array(0x6F), - 0x1D57B => array(0x70), - 0x1D57C => array(0x71), - 0x1D57D => array(0x72), - 0x1D57E => array(0x73), - 0x1D57F => array(0x74), - 0x1D580 => array(0x75), - 0x1D581 => array(0x76), - 0x1D582 => array(0x77), - 0x1D583 => array(0x78), - 0x1D584 => array(0x79), - 0x1D585 => array(0x7A), - 0x1D5A0 => array(0x61), - 0x1D5A1 => array(0x62), - 0x1D5A2 => array(0x63), - 0x1D5A3 => array(0x64), - 0x1D5A4 => array(0x65), - 0x1D5A5 => array(0x66), - 0x1D5A6 => array(0x67), - 0x1D5A7 => array(0x68), - 0x1D5A8 => array(0x69), - 0x1D5A9 => array(0x6A), - 0x1D5AA => array(0x6B), - 0x1D5AB => array(0x6C), - 0x1D5AC => array(0x6D), - 0x1D5AD => array(0x6E), - 0x1D5AE => array(0x6F), - 0x1D5AF => array(0x70), - 0x1D5B0 => array(0x71), - 0x1D5B1 => array(0x72), - 0x1D5B2 => array(0x73), - 0x1D5B3 => array(0x74), - 0x1D5B4 => array(0x75), - 0x1D5B5 => array(0x76), - 0x1D5B6 => array(0x77), - 0x1D5B7 => array(0x78), - 0x1D5B8 => array(0x79), - 0x1D5B9 => array(0x7A), - 0x1D5D4 => array(0x61), - 0x1D5D5 => array(0x62), - 0x1D5D6 => array(0x63), - 0x1D5D7 => array(0x64), - 0x1D5D8 => array(0x65), - 0x1D5D9 => array(0x66), - 0x1D5DA => array(0x67), - 0x1D5DB => array(0x68), - 0x1D5DC => array(0x69), - 0x1D5DD => array(0x6A), - 0x1D5DE => array(0x6B), - 0x1D5DF => array(0x6C), - 0x1D5E0 => array(0x6D), - 0x1D5E1 => array(0x6E), - 0x1D5E2 => array(0x6F), - 0x1D5E3 => array(0x70), - 0x1D5E4 => array(0x71), - 0x1D5E5 => array(0x72), - 0x1D5E6 => array(0x73), - 0x1D5E7 => array(0x74), - 0x1D5E8 => array(0x75), - 0x1D5E9 => array(0x76), - 0x1D5EA => array(0x77), - 0x1D5EB => array(0x78), - 0x1D5EC => array(0x79), - 0x1D5ED => array(0x7A), - 0x1D608 => array(0x61), - 0x1D609 => array(0x62), - 0x1D60A => array(0x63), - 0x1D60B => array(0x64), - 0x1D60C => array(0x65), - 0x1D60D => array(0x66), - 0x1D60E => array(0x67), - 0x1D60F => array(0x68), - 0x1D610 => array(0x69), - 0x1D611 => array(0x6A), - 0x1D612 => array(0x6B), - 0x1D613 => array(0x6C), - 0x1D614 => array(0x6D), - 0x1D615 => array(0x6E), - 0x1D616 => array(0x6F), - 0x1D617 => array(0x70), - 0x1D618 => array(0x71), - 0x1D619 => array(0x72), - 0x1D61A => array(0x73), - 0x1D61B => array(0x74), - 0x1D61C => array(0x75), - 0x1D61D => array(0x76), - 0x1D61E => array(0x77), - 0x1D61F => array(0x78), - 0x1D620 => array(0x79), - 0x1D621 => array(0x7A), - 0x1D63C => array(0x61), - 0x1D63D => array(0x62), - 0x1D63E => array(0x63), - 0x1D63F => array(0x64), - 0x1D640 => array(0x65), - 0x1D641 => array(0x66), - 0x1D642 => array(0x67), - 0x1D643 => array(0x68), - 0x1D644 => array(0x69), - 0x1D645 => array(0x6A), - 0x1D646 => array(0x6B), - 0x1D647 => array(0x6C), - 0x1D648 => array(0x6D), - 0x1D649 => array(0x6E), - 0x1D64A => array(0x6F), - 0x1D64B => array(0x70), - 0x1D64C => array(0x71), - 0x1D64D => array(0x72), - 0x1D64E => array(0x73), - 0x1D64F => array(0x74), - 0x1D650 => array(0x75), - 0x1D651 => array(0x76), - 0x1D652 => array(0x77), - 0x1D653 => array(0x78), - 0x1D654 => array(0x79), - 0x1D655 => array(0x7A), - 0x1D670 => array(0x61), - 0x1D671 => array(0x62), - 0x1D672 => array(0x63), - 0x1D673 => array(0x64), - 0x1D674 => array(0x65), - 0x1D675 => array(0x66), - 0x1D676 => array(0x67), - 0x1D677 => array(0x68), - 0x1D678 => array(0x69), - 0x1D679 => array(0x6A), - 0x1D67A => array(0x6B), - 0x1D67B => array(0x6C), - 0x1D67C => array(0x6D), - 0x1D67D => array(0x6E), - 0x1D67E => array(0x6F), - 0x1D67F => array(0x70), - 0x1D680 => array(0x71), - 0x1D681 => array(0x72), - 0x1D682 => array(0x73), - 0x1D683 => array(0x74), - 0x1D684 => array(0x75), - 0x1D685 => array(0x76), - 0x1D686 => array(0x77), - 0x1D687 => array(0x78), - 0x1D688 => array(0x79), - 0x1D689 => array(0x7A), - 0x1D6A8 => array(0x3B1), - 0x1D6A9 => array(0x3B2), - 0x1D6AA => array(0x3B3), - 0x1D6AB => array(0x3B4), - 0x1D6AC => array(0x3B5), - 0x1D6AD => array(0x3B6), - 0x1D6AE => array(0x3B7), - 0x1D6AF => array(0x3B8), - 0x1D6B0 => array(0x3B9), - 0x1D6B1 => array(0x3BA), - 0x1D6B2 => array(0x3BB), - 0x1D6B3 => array(0x3BC), - 0x1D6B4 => array(0x3BD), - 0x1D6B5 => array(0x3BE), - 0x1D6B6 => array(0x3BF), - 0x1D6B7 => array(0x3C0), - 0x1D6B8 => array(0x3C1), - 0x1D6B9 => array(0x3B8), - 0x1D6BA => array(0x3C3), - 0x1D6BB => array(0x3C4), - 0x1D6BC => array(0x3C5), - 0x1D6BD => array(0x3C6), - 0x1D6BE => array(0x3C7), - 0x1D6BF => array(0x3C8), - 0x1D6C0 => array(0x3C9), - 0x1D6D3 => array(0x3C3), - 0x1D6E2 => array(0x3B1), - 0x1D6E3 => array(0x3B2), - 0x1D6E4 => array(0x3B3), - 0x1D6E5 => array(0x3B4), - 0x1D6E6 => array(0x3B5), - 0x1D6E7 => array(0x3B6), - 0x1D6E8 => array(0x3B7), - 0x1D6E9 => array(0x3B8), - 0x1D6EA => array(0x3B9), - 0x1D6EB => array(0x3BA), - 0x1D6EC => array(0x3BB), - 0x1D6ED => array(0x3BC), - 0x1D6EE => array(0x3BD), - 0x1D6EF => array(0x3BE), - 0x1D6F0 => array(0x3BF), - 0x1D6F1 => array(0x3C0), - 0x1D6F2 => array(0x3C1), - 0x1D6F3 => array(0x3B8), - 0x1D6F4 => array(0x3C3), - 0x1D6F5 => array(0x3C4), - 0x1D6F6 => array(0x3C5), - 0x1D6F7 => array(0x3C6), - 0x1D6F8 => array(0x3C7), - 0x1D6F9 => array(0x3C8), - 0x1D6FA => array(0x3C9), - 0x1D70D => array(0x3C3), - 0x1D71C => array(0x3B1), - 0x1D71D => array(0x3B2), - 0x1D71E => array(0x3B3), - 0x1D71F => array(0x3B4), - 0x1D720 => array(0x3B5), - 0x1D721 => array(0x3B6), - 0x1D722 => array(0x3B7), - 0x1D723 => array(0x3B8), - 0x1D724 => array(0x3B9), - 0x1D725 => array(0x3BA), - 0x1D726 => array(0x3BB), - 0x1D727 => array(0x3BC), - 0x1D728 => array(0x3BD), - 0x1D729 => array(0x3BE), - 0x1D72A => array(0x3BF), - 0x1D72B => array(0x3C0), - 0x1D72C => array(0x3C1), - 0x1D72D => array(0x3B8), - 0x1D72E => array(0x3C3), - 0x1D72F => array(0x3C4), - 0x1D730 => array(0x3C5), - 0x1D731 => array(0x3C6), - 0x1D732 => array(0x3C7), - 0x1D733 => array(0x3C8), - 0x1D734 => array(0x3C9), - 0x1D747 => array(0x3C3), - 0x1D756 => array(0x3B1), - 0x1D757 => array(0x3B2), - 0x1D758 => array(0x3B3), - 0x1D759 => array(0x3B4), - 0x1D75A => array(0x3B5), - 0x1D75B => array(0x3B6), - 0x1D75C => array(0x3B7), - 0x1D75D => array(0x3B8), - 0x1D75E => array(0x3B9), - 0x1D75F => array(0x3BA), - 0x1D760 => array(0x3BB), - 0x1D761 => array(0x3BC), - 0x1D762 => array(0x3BD), - 0x1D763 => array(0x3BE), - 0x1D764 => array(0x3BF), - 0x1D765 => array(0x3C0), - 0x1D766 => array(0x3C1), - 0x1D767 => array(0x3B8), - 0x1D768 => array(0x3C3), - 0x1D769 => array(0x3C4), - 0x1D76A => array(0x3C5), - 0x1D76B => array(0x3C6), - 0x1D76C => array(0x3C7), - 0x1D76D => array(0x3C8), - 0x1D76E => array(0x3C9), - 0x1D781 => array(0x3C3), - 0x1D790 => array(0x3B1), - 0x1D791 => array(0x3B2), - 0x1D792 => array(0x3B3), - 0x1D793 => array(0x3B4), - 0x1D794 => array(0x3B5), - 0x1D795 => array(0x3B6), - 0x1D796 => array(0x3B7), - 0x1D797 => array(0x3B8), - 0x1D798 => array(0x3B9), - 0x1D799 => array(0x3BA), - 0x1D79A => array(0x3BB), - 0x1D79B => array(0x3BC), - 0x1D79C => array(0x3BD), - 0x1D79D => array(0x3BE), - 0x1D79E => array(0x3BF), - 0x1D79F => array(0x3C0), - 0x1D7A0 => array(0x3C1), - 0x1D7A1 => array(0x3B8), - 0x1D7A2 => array(0x3C3), - 0x1D7A3 => array(0x3C4), - 0x1D7A4 => array(0x3C5), - 0x1D7A5 => array(0x3C6), - 0x1D7A6 => array(0x3C7), - 0x1D7A7 => array(0x3C8), - 0x1D7A8 => array(0x3C9), - 0x1D7BB => array(0x3C3), - 0x3F9 => array(0x3C3), - 0x1D2C => array(0x61), - 0x1D2D => array(0xE6), - 0x1D2E => array(0x62), - 0x1D30 => array(0x64), - 0x1D31 => array(0x65), - 0x1D32 => array(0x1DD), - 0x1D33 => array(0x67), - 0x1D34 => array(0x68), - 0x1D35 => array(0x69), - 0x1D36 => array(0x6A), - 0x1D37 => array(0x6B), - 0x1D38 => array(0x6C), - 0x1D39 => array(0x6D), - 0x1D3A => array(0x6E), - 0x1D3C => array(0x6F), - 0x1D3D => array(0x223), - 0x1D3E => array(0x70), - 0x1D3F => array(0x72), - 0x1D40 => array(0x74), - 0x1D41 => array(0x75), - 0x1D42 => array(0x77), - 0x213B => array(0x66, 0x61, 0x78), - 0x3250 => array(0x70, 0x74, 0x65), - 0x32CC => array(0x68, 0x67), - 0x32CE => array(0x65, 0x76), - 0x32CF => array(0x6C, 0x74, 0x64), - 0x337A => array(0x69, 0x75), - 0x33DE => array(0x76, 0x2215, 0x6D), - 0x33DF => array(0x61, 0x2215, 0x6D) - ); - - /** - * Normalization Combining Classes; Code Points not listed - * got Combining Class 0. - * - * @static - * @var array - * @access private - */ - var $_np_norm_combcls = array( - 0x334 => 1, - 0x335 => 1, - 0x336 => 1, - 0x337 => 1, - 0x338 => 1, - 0x93C => 7, - 0x9BC => 7, - 0xA3C => 7, - 0xABC => 7, - 0xB3C => 7, - 0xCBC => 7, - 0x1037 => 7, - 0x3099 => 8, - 0x309A => 8, - 0x94D => 9, - 0x9CD => 9, - 0xA4D => 9, - 0xACD => 9, - 0xB4D => 9, - 0xBCD => 9, - 0xC4D => 9, - 0xCCD => 9, - 0xD4D => 9, - 0xDCA => 9, - 0xE3A => 9, - 0xF84 => 9, - 0x1039 => 9, - 0x1714 => 9, - 0x1734 => 9, - 0x17D2 => 9, - 0x5B0 => 10, - 0x5B1 => 11, - 0x5B2 => 12, - 0x5B3 => 13, - 0x5B4 => 14, - 0x5B5 => 15, - 0x5B6 => 16, - 0x5B7 => 17, - 0x5B8 => 18, - 0x5B9 => 19, - 0x5BB => 20, - 0x5Bc => 21, - 0x5BD => 22, - 0x5BF => 23, - 0x5C1 => 24, - 0x5C2 => 25, - 0xFB1E => 26, - 0x64B => 27, - 0x64C => 28, - 0x64D => 29, - 0x64E => 30, - 0x64F => 31, - 0x650 => 32, - 0x651 => 33, - 0x652 => 34, - 0x670 => 35, - 0x711 => 36, - 0xC55 => 84, - 0xC56 => 91, - 0xE38 => 103, - 0xE39 => 103, - 0xE48 => 107, - 0xE49 => 107, - 0xE4A => 107, - 0xE4B => 107, - 0xEB8 => 118, - 0xEB9 => 118, - 0xEC8 => 122, - 0xEC9 => 122, - 0xECA => 122, - 0xECB => 122, - 0xF71 => 129, - 0xF72 => 130, - 0xF7A => 130, - 0xF7B => 130, - 0xF7C => 130, - 0xF7D => 130, - 0xF80 => 130, - 0xF74 => 132, - 0x321 => 202, - 0x322 => 202, - 0x327 => 202, - 0x328 => 202, - 0x31B => 216, - 0xF39 => 216, - 0x1D165 => 216, - 0x1D166 => 216, - 0x1D16E => 216, - 0x1D16F => 216, - 0x1D170 => 216, - 0x1D171 => 216, - 0x1D172 => 216, - 0x302A => 218, - 0x316 => 220, - 0x317 => 220, - 0x318 => 220, - 0x319 => 220, - 0x31C => 220, - 0x31D => 220, - 0x31E => 220, - 0x31F => 220, - 0x320 => 220, - 0x323 => 220, - 0x324 => 220, - 0x325 => 220, - 0x326 => 220, - 0x329 => 220, - 0x32A => 220, - 0x32B => 220, - 0x32C => 220, - 0x32D => 220, - 0x32E => 220, - 0x32F => 220, - 0x330 => 220, - 0x331 => 220, - 0x332 => 220, - 0x333 => 220, - 0x339 => 220, - 0x33A => 220, - 0x33B => 220, - 0x33C => 220, - 0x347 => 220, - 0x348 => 220, - 0x349 => 220, - 0x34D => 220, - 0x34E => 220, - 0x353 => 220, - 0x354 => 220, - 0x355 => 220, - 0x356 => 220, - 0x591 => 220, - 0x596 => 220, - 0x59B => 220, - 0x5A3 => 220, - 0x5A4 => 220, - 0x5A5 => 220, - 0x5A6 => 220, - 0x5A7 => 220, - 0x5AA => 220, - 0x655 => 220, - 0x656 => 220, - 0x6E3 => 220, - 0x6EA => 220, - 0x6ED => 220, - 0x731 => 220, - 0x734 => 220, - 0x737 => 220, - 0x738 => 220, - 0x739 => 220, - 0x73B => 220, - 0x73C => 220, - 0x73E => 220, - 0x742 => 220, - 0x744 => 220, - 0x746 => 220, - 0x748 => 220, - 0x952 => 220, - 0xF18 => 220, - 0xF19 => 220, - 0xF35 => 220, - 0xF37 => 220, - 0xFC6 => 220, - 0x193B => 220, - 0x20E8 => 220, - 0x1D17B => 220, - 0x1D17C => 220, - 0x1D17D => 220, - 0x1D17E => 220, - 0x1D17F => 220, - 0x1D180 => 220, - 0x1D181 => 220, - 0x1D182 => 220, - 0x1D18A => 220, - 0x1D18B => 220, - 0x59A => 222, - 0x5AD => 222, - 0x1929 => 222, - 0x302D => 222, - 0x302E => 224, - 0x302F => 224, - 0x1D16D => 226, - 0x5AE => 228, - 0x18A9 => 228, - 0x302B => 228, - 0x300 => 230, - 0x301 => 230, - 0x302 => 230, - 0x303 => 230, - 0x304 => 230, - 0x305 => 230, - 0x306 => 230, - 0x307 => 230, - 0x308 => 230, - 0x309 => 230, - 0x30A => 230, - 0x30B => 230, - 0x30C => 230, - 0x30D => 230, - 0x30E => 230, - 0x30F => 230, - 0x310 => 230, - 0x311 => 230, - 0x312 => 230, - 0x313 => 230, - 0x314 => 230, - 0x33D => 230, - 0x33E => 230, - 0x33F => 230, - 0x340 => 230, - 0x341 => 230, - 0x342 => 230, - 0x343 => 230, - 0x344 => 230, - 0x346 => 230, - 0x34A => 230, - 0x34B => 230, - 0x34C => 230, - 0x350 => 230, - 0x351 => 230, - 0x352 => 230, - 0x357 => 230, - 0x363 => 230, - 0x364 => 230, - 0x365 => 230, - 0x366 => 230, - 0x367 => 230, - 0x368 => 230, - 0x369 => 230, - 0x36A => 230, - 0x36B => 230, - 0x36C => 230, - 0x36D => 230, - 0x36E => 230, - 0x36F => 230, - 0x483 => 230, - 0x484 => 230, - 0x485 => 230, - 0x486 => 230, - 0x592 => 230, - 0x593 => 230, - 0x594 => 230, - 0x595 => 230, - 0x597 => 230, - 0x598 => 230, - 0x599 => 230, - 0x59C => 230, - 0x59D => 230, - 0x59E => 230, - 0x59F => 230, - 0x5A0 => 230, - 0x5A1 => 230, - 0x5A8 => 230, - 0x5A9 => 230, - 0x5AB => 230, - 0x5AC => 230, - 0x5AF => 230, - 0x5C4 => 230, - 0x610 => 230, - 0x611 => 230, - 0x612 => 230, - 0x613 => 230, - 0x614 => 230, - 0x615 => 230, - 0x653 => 230, - 0x654 => 230, - 0x657 => 230, - 0x658 => 230, - 0x6D6 => 230, - 0x6D7 => 230, - 0x6D8 => 230, - 0x6D9 => 230, - 0x6DA => 230, - 0x6DB => 230, - 0x6DC => 230, - 0x6DF => 230, - 0x6E0 => 230, - 0x6E1 => 230, - 0x6E2 => 230, - 0x6E4 => 230, - 0x6E7 => 230, - 0x6E8 => 230, - 0x6EB => 230, - 0x6EC => 230, - 0x730 => 230, - 0x732 => 230, - 0x733 => 230, - 0x735 => 230, - 0x736 => 230, - 0x73A => 230, - 0x73D => 230, - 0x73F => 230, - 0x740 => 230, - 0x741 => 230, - 0x743 => 230, - 0x745 => 230, - 0x747 => 230, - 0x749 => 230, - 0x74A => 230, - 0x951 => 230, - 0x953 => 230, - 0x954 => 230, - 0xF82 => 230, - 0xF83 => 230, - 0xF86 => 230, - 0xF87 => 230, - 0x170D => 230, - 0x193A => 230, - 0x20D0 => 230, - 0x20D1 => 230, - 0x20D4 => 230, - 0x20D5 => 230, - 0x20D6 => 230, - 0x20D7 => 230, - 0x20DB => 230, - 0x20DC => 230, - 0x20E1 => 230, - 0x20E7 => 230, - 0x20E9 => 230, - 0xFE20 => 230, - 0xFE21 => 230, - 0xFE22 => 230, - 0xFE23 => 230, - 0x1D185 => 230, - 0x1D186 => 230, - 0x1D187 => 230, - 0x1D189 => 230, - 0x1D188 => 230, - 0x1D1AA => 230, - 0x1D1AB => 230, - 0x1D1AC => 230, - 0x1D1AD => 230, - 0x315 => 232, - 0x31A => 232, - 0x302C => 232, - 0x35F => 233, - 0x362 => 233, - 0x35D => 234, - 0x35E => 234, - 0x360 => 234, - 0x361 => 234, - 0x345 => 240 - ); - // }}} - - - // Internal settings, do not mess with them - var $_punycode_prefix = 'xn--'; - var $_invalid_ucs = 0x80000000; - var $_max_ucs = 0x10FFFF; - var $_base = 36; - var $_tmin = 1; - var $_tmax = 26; - var $_skew = 38; - var $_damp = 700; - var $_initial_bias = 72; - var $_initial_n = 0x80; - var $_sbase = 0xAC00; - var $_lbase = 0x1100; - var $_vbase = 0x1161; - var $_tbase = 0x11a7; - var $_lcount = 19; - var $_vcount = 21; - var $_tcount = 28; - var $_ncount = 588; // _vcount * _tcount - var $_scount = 11172; // _lcount * _tcount * _vcount - var $_error = false; - - // See set_parameter() for details of how to change the following settings - // from within your script / application - var $_api_encoding = 'utf8'; // Default input charset is UTF-8 - var $_allow_overlong = false; // Overlong UTF-8 encodings are forbidden - var $_strict_mode = false; // Behave strict or not - - // The constructor - function Net_IDNA_php4($options = false) - { - $this->slast = $this->_sbase + $this->_lcount * $this->_vcount * $this->_tcount; - // If parameters are given, pass these to the respective method - if (is_array($options)) { - return $this->set_parameter($options); - } - return true; - } - - /** - * Sets a new option value. Available options and values: - * [encoding - Use either UTF-8, UCS4 as array or UCS4 as string as input ('utf8' for UTF-8, - * 'ucs4_string' and 'ucs4_array' respectively for UCS4); The output is always UTF-8] - * [overlong - Unicode does not allow unnecessarily long encodings of chars, - * to allow this, set this parameter to true, else to false; - * default is false.] - * [strict - true: strict mode, good for registration purposes - Causes errors - * on failures; false: loose mode, ideal for "wildlife" applications - * by silently ignoring errors and returning the original input instead - * - * @param mixed Parameter to set (string: single parameter; array of Parameter => Value pairs) - * @param string Value to use (if parameter 1 is a string) - * @return boolean true on success, false otherwise - * @access public - */ - function set_parameter($option, $value = false) - { - if (!is_array($option)) { - $option = array($option => $value); - } - foreach ($option as $k => $v) { - switch ($k) { - case 'encoding': - switch ($v) { - case 'utf8': - case 'ucs4_string': - case 'ucs4_array': - $this->_api_encoding = $v; - break; - default: - $this->_error('Set Parameter: Unknown parameter '.$v.' for option '.$k); - return false; - } - break; - case 'overlong': - $this->_allow_overlong = ($v) ? true : false; - break; - case 'strict': - $this->_strict_mode = ($v) ? true : false; - break; - default: - $this->_error('Set Parameter: Unknown option '.$k); - return false; - } - } - return true; - } - - /** - * Decode a given ACE domain name - * @param string Domain name (ACE string) - * [@param string Desired output encoding, see {@link set_parameter}] - * @return string Decoded Domain name (UTF-8 or UCS-4) - * @access public - */ - function decode($input, $one_time_encoding = false) - { - // Optionally set - if ($one_time_encoding) { - switch ($one_time_encoding) { - case 'utf8': - case 'ucs4_string': - case 'ucs4_array': - break; - default: - $this->_error('Unknown encoding '.$one_time_encoding); - return false; - } - } - // Make sure to drop any newline characters around - $input = trim($input); - - // Negotiate input and try to determine, wether it is a plain string, - // an email address or something like a complete URL - if (strpos($input, '@')) { // Maybe it is an email address - // No no in strict mode - if ($this->_strict_mode) { - $this->_error('Only simple domain name parts can be handled in strict mode'); - return false; - } - list($email_pref, $input) = explode('@', $input, 2); - $arr = explode('.', $input); - foreach ($arr as $k => $v) { - $conv = $this->_decode($v); - if ($conv) $arr[$k] = $conv; - } - $return = $email_pref . '@' . join('.', $arr); - } elseif (preg_match('![:\./]!', $input)) { // Or a complete domain name (with or without paths / parameters) - // No no in strict mode - if ($this->_strict_mode) { - $this->_error('Only simple domain name parts can be handled in strict mode'); - return false; - } - $parsed = parse_url($input); - if (isset($parsed['host'])) { - $arr = explode('.', $parsed['host']); - foreach ($arr as $k => $v) { - $conv = $this->_decode($v); - if ($conv) $arr[$k] = $conv; - } - $parsed['host'] = join('.', $arr); - if (isset($parsed['scheme'])) { - $parsed['scheme'] .= (strtolower($parsed['scheme']) == 'mailto') ? ':' : '://'; - } - $return = join('', $parsed); - } else { // parse_url seems to have failed, try without it - $arr = explode('.', $input); - foreach ($arr as $k => $v) { - $conv = $this->_decode($v); - if ($conv) $arr[$k] = $conv; - } - $return = join('.', $arr); - } - } else { // Otherwise we consider it being a pure domain name string - $return = $this->_decode($input); - } - // The output is UTF-8 by default, other output formats need conversion here - // If one time encoding is given, use this, else the objects property - switch (($one_time_encoding) ? $one_time_encoding : $this->_api_encoding) { - case 'utf8': - return $return; - break; - case 'ucs4_string': - return $this->_ucs4_to_ucs4_string($this->_utf8_to_ucs4($return)); - break; - case 'ucs4_array': - return $this->_utf8_to_ucs4($return); - break; - default: - $this->_error('Unsupported output format'); - return false; - } - } - - /** - * Encode a given UTF-8 domain name - * @param string Domain name (UTF-8 or UCS-4) - * [@param string Desired input encoding, see {@link set_parameter}] - * @return string Encoded Domain name (ACE string) - * @access public - */ - function encode($decoded, $one_time_encoding = false) - { - // Forcing conversion of input to UCS4 array - // If one time encoding is given, use this, else the objects property - switch (($one_time_encoding) ? $one_time_encoding : $this->_api_encoding) { - case 'utf8': - $decoded = $this->_utf8_to_ucs4($decoded); - break; - case 'ucs4_string': - $decoded = $this->_ucs4_string_to_ucs4($decoded); - case 'ucs4_array': - break; - default: - // $this->_error('Unsupported input format: '.$this->_api_encoding); - $this->_error('Unsupported input format'); - return false; - } - - // No input, no output, what else did you expect? - if (empty($decoded)) return ''; - - // Anchors for iteration - $last_begin = 0; - // Output string - $output = ''; - foreach ($decoded as $k => $v) { - // Make sure to use just the plain dot - switch($v) { - case 0x3002: - case 0xFF0E: - case 0xFF61: - $decoded[$k] = 0x2E; - // It's right, no break here - // The codepoints above have to be converted to dots anyway - - // Stumbling across an anchoring character - case 0x2E: - case 0x2F: - case 0x3A: - case 0x3F: - case 0x40: - // Neither email addresses nor URLs allowed in strict mode - if ($this->_strict_mode) { - $this->_error('Neither email addresses nor URLs are allowed in strict mode.'); - return false; - } else { - // Skip first char - if ($k) { - $encoded = ''; - $encoded = $this->_encode(array_slice($decoded, $last_begin, (($k)-$last_begin))); - if ($encoded) { - $output .= $encoded; - } else { - $output .= $this->_ucs4_to_utf8(array_slice($decoded, $last_begin, (($k)-$last_begin))); - } - $output .= chr($decoded[$k]); - } - $last_begin = $k + 1; - } - } - } - // Catch the rest of the string - if ($last_begin) { - $inp_len = sizeof($decoded); - $encoded = ''; - $encoded = $this->_encode(array_slice($decoded, $last_begin, (($inp_len)-$last_begin))); - if ($encoded) { - $output .= $encoded; - } else { - $output .= $this->_ucs4_to_utf8(array_slice($decoded, $last_begin, (($inp_len)-$last_begin))); - } - return $output; - } else { - if ($output = $this->_encode($decoded)) { - return $output; - } else { - return $this->_ucs4_to_utf8($decoded); - } - } - } - - /** - * Use this method to get the last error ocurred - * @param void - * @return string The last error, that occured - * @access public - */ - function get_last_error() - { - return $this->_error; - } - - /** - * The actual decoding algorithm - * @access private - */ - function _decode($encoded) - { - // We do need to find the Punycode prefix - if (!preg_match('!^'.preg_quote($this->_punycode_prefix, '!').'!', $encoded)) { - $this->_error('This is not a punycode string'); - return false; - } - $encode_test = preg_replace('!^'.preg_quote($this->_punycode_prefix, '!').'!', '', $encoded); - // If nothing left after removing the prefix, it is hopeless - if (!$encode_test) { - $this->_error('The given encoded string was empty'); - return false; - } - // Find last occurence of the delimiter - $delim_pos = strrpos($encoded, '-'); - if ($delim_pos > strlen($this->_punycode_prefix)) { - for ($k = strlen($this->_punycode_prefix); $k < $delim_pos; ++$k) { - $decoded[] = ord($encoded{$k}); - } - } else { - $decoded = array(); - } - $deco_len = count($decoded); - $enco_len = strlen($encoded); - - // Wandering through the strings; init - $is_first = true; - $bias = $this->_initial_bias; - $idx = 0; - $char = $this->_initial_n; - - for ($enco_idx = ($delim_pos) ? ($delim_pos + 1) : 0; $enco_idx < $enco_len; ++$deco_len) { - for ($old_idx = $idx, $w = 1, $k = $this->_base; 1 ; $k += $this->_base) { - $digit = $this->_decode_digit($encoded{$enco_idx++}); - $idx += $digit * $w; - $t = ($k <= $bias) ? $this->_tmin : - (($k >= $bias + $this->_tmax) ? $this->_tmax : ($k - $bias)); - if ($digit < $t) break; - $w = (int) ($w * ($this->_base - $t)); - } - $bias = $this->_adapt($idx - $old_idx, $deco_len + 1, $is_first); - $is_first = false; - $char += (int) ($idx / ($deco_len + 1)); - $idx %= ($deco_len + 1); - if ($deco_len > 0) { - // Make room for the decoded char - for ($i = $deco_len; $i > $idx; $i--) { - $decoded[$i] = $decoded[($i - 1)]; - } - } - $decoded[$idx++] = $char; - } - return $this->_ucs4_to_utf8($decoded); - } - - /** - * The actual encoding algorithm - * @access private - */ - function _encode($decoded) - { - // We cannot encode a domain name containing the Punycode prefix - $extract = strlen($this->_punycode_prefix); - $check_pref = $this->_utf8_to_ucs4($this->_punycode_prefix); - $check_deco = array_slice($decoded, 0, $extract); - - if ($check_pref == $check_deco) { - $this->_error('This is already a punycode string'); - return false; - } - // We will not try to encode strings consisting of basic code points only - $encodable = false; - foreach ($decoded as $k => $v) { - if ($v > 0x7a) { - $encodable = true; - break; - } - } - if (!$encodable) { - $this->_error('The given string does not contain encodable chars'); - return false; - } - - // Do NAMEPREP - $decoded = $this->_nameprep($decoded); - if (!$decoded || !is_array($decoded)) return false; // NAMEPREP failed - - $deco_len = count($decoded); - if (!$deco_len) return false; // Empty array - - $codecount = 0; // How many chars have been consumed - - $encoded = ''; - // Copy all basic code points to output - for ($i = 0; $i < $deco_len; ++$i) { - $test = $decoded[$i]; - // Will match [0-9a-zA-Z-] - if ((0x2F < $test && $test < 0x40) - || (0x40 < $test && $test < 0x5B) - || (0x60 < $test && $test <= 0x7B) - || (0x2D == $test)) { - $encoded .= chr($decoded[$i]); - $codecount++; - } - } - - // All codepoints were basic ones - if ($codecount == $deco_len) { - return $encoded; - } - - // Start with the prefix; copy it to output - $encoded = $this->_punycode_prefix.$encoded; - - // If we have basic code points in output, add an hyphen to the end - if ($codecount) $encoded .= '-'; - - // Now find and encode all non-basic code points - $is_first = true; - $cur_code = $this->_initial_n; - $bias = $this->_initial_bias; - $delta = 0; - while ($codecount < $deco_len) { - // Find the smallest code point >= the current code point and - // remember the last ouccrence of it in the input - for ($i = 0, $next_code = $this->_max_ucs; $i < $deco_len; $i++) { - if ($decoded[$i] >= $cur_code && $decoded[$i] <= $next_code) { - $next_code = $decoded[$i]; - } - } - - $delta += ($next_code - $cur_code) * ($codecount + 1); - $cur_code = $next_code; - - // Scan input again and encode all characters whose code point is $cur_code - for ($i = 0; $i < $deco_len; $i++) { - if ($decoded[$i] < $cur_code) { - $delta++; - } elseif ($decoded[$i] == $cur_code) { - for ($q = $delta, $k = $this->_base; 1; $k += $this->_base) { - $t = ($k <= $bias) ? $this->_tmin : - (($k >= $bias + $this->_tmax) ? $this->_tmax : $k - $bias); - if ($q < $t) break; - $encoded .= $this->_encode_digit(ceil($t + (($q - $t) % ($this->_base - $t)))); - $q = ($q - $t) / ($this->_base - $t); - } - $encoded .= $this->_encode_digit($q); - $bias = $this->_adapt($delta, $codecount+1, $is_first); - $codecount++; - $delta = 0; - $is_first = false; - } - } - $delta++; - $cur_code++; - } - return $encoded; - } - - /** - * Adapt the bias according to the current code point and position - * @access private - */ - function _adapt($delta, $npoints, $is_first) - { - $delta = (int) ($is_first ? ($delta / $this->_damp) : ($delta / 2)); - $delta += (int) ($delta / $npoints); - for ($k = 0; $delta > (($this->_base - $this->_tmin) * $this->_tmax) / 2; $k += $this->_base) { - $delta = (int) ($delta / ($this->_base - $this->_tmin)); - } - return (int) ($k + ($this->_base - $this->_tmin + 1) * $delta / ($delta + $this->_skew)); - } - - /** - * Encoding a certain digit - * @access private - */ - function _encode_digit($d) - { - return chr($d + 22 + 75 * ($d < 26)); - } - - /** - * Decode a certain digit - * @access private - */ - function _decode_digit($cp) - { - $cp = ord($cp); - return ($cp - 48 < 10) ? $cp - 22 : (($cp - 65 < 26) ? $cp - 65 : (($cp - 97 < 26) ? $cp - 97 : $this->_base)); - } - - /** - * Internal error handling method - * @access private - */ - function _error($error = '') - { - $this->_error = $error; - } - - /** - * Do Nameprep according to RFC3491 and RFC3454 - * @param array Unicode Characters - * @return string Unicode Characters, Nameprep'd - * @access private - */ - function _nameprep($input) - { - $output = array(); - $error = false; - // - // Mapping - // Walking through the input array, performing the required steps on each of - // the input chars and putting the result into the output array - // While mapping required chars we apply the cannonical ordering - - // $this->_show_hex($input); - foreach ($input as $v) { - // Map to nothing == skip that code point - if (in_array($v, $this->_np_map_nothing)) continue; - - // Try to find prohibited input - if (in_array($v, $this->_np_prohibit) || in_array($v, $this->_general_prohibited)) { - $this->_error('NAMEPREP: Prohibited input U+'.sprintf('%08X', $v)); - return false; - } - foreach ($this->_np_prohibit_ranges as $range) { - if ($range[0] <= $v && $v <= $range[1]) { - $this->_error('NAMEPREP: Prohibited input U+'.sprintf('%08X', $v)); - return false; - } - } - // - // Hangul syllable decomposition - if (0xAC00 <= $v && $v <= 0xD7AF) { - foreach ($this->_hangul_decompose($v) as $out) { - $output[] = $out; - } - // There's a decomposition mapping for that code point - } elseif (isset($this->_np_replacemaps[$v])) { - foreach ($this->_apply_cannonical_ordering($this->_np_replacemaps[$v]) as $out) { - $output[] = $out; - } - } else { - $output[] = $v; - } - } - // - // Combine code points - // - $last_class = 0; - $last_starter = 0; - $out_len = count($output); - for ($i = 0; $i < $out_len; ++$i) { - $class = $this->_get_combining_class($output[$i]); - if ((!$last_class || $last_class != $class) && $class) { - // Try to match - $seq_len = $i - $last_starter; - $out = $this->_combine(array_slice($output, $last_starter, $seq_len)); - // On match: Replace the last starter with the composed character and remove - // the now redundant non-starter(s) - if ($out) { - $output[$last_starter] = $out; - if (count($out) != $seq_len) { - for ($j = $i+1; $j < $out_len; ++$j) { - $output[$j-1] = $output[$j]; - } - unset($output[$out_len]); - } - // Rewind the for loop by one, since there can be more possible compositions - $i--; - $out_len--; - $last_class = ($i == $last_starter) ? 0 : $this->_get_combining_class($output[$i-1]); - continue; - } - } - if (!$class) { // The current class is 0 - $last_starter = $i; - } - $last_class = $class; - } - return $output; - } - - /** - * Decomposes a Hangul syllable - * (see http://www.unicode.org/unicode/reports/tr15/#Hangul - * @param integer 32bit UCS4 code point - * @return array Either Hangul Syllable decomposed or original 32bit value as one value array - * @access private - */ - function _hangul_decompose($char) - { - $sindex = $char - $this->_sbase; - if ($sindex < 0 || $sindex >= $this->_scount) { - return array($char); - } - $result = array(); - $T = $this->_tbase + $sindex % $this->_tcount; - $result[] = (int) ($this->_lbase + $sindex / $this->_ncount); - $result[] = (int) ($this->_vbase + ($sindex % $this->_ncount) / $this->_tcount); - if ($T != $this->_tbase) $result[] = $T; - return $result; - } - - /** - * Ccomposes a Hangul syllable - * (see http://www.unicode.org/unicode/reports/tr15/#Hangul - * @param array Decomposed UCS4 sequence - * @return array UCS4 sequence with syllables composed - * @access private - */ - function _hangul_compose($input) - { - $inp_len = count($input); - if (!$inp_len) return array(); - $result = array(); - $last = $input[0]; - $result[] = $last; // copy first char from input to output - - for ($i = 1; $i < $inp_len; ++$i) { - $char = $input[$i]; - - // Find out, wether two current characters from L and V - $lindex = $last - $this->_lbase; - if (0 <= $lindex && $lindex < $this->_lcount) { - $vindex = $char - $this->_vbase; - if (0 <= $vindex && $vindex < $this->_vcount) { - // create syllable of form LV - $last = ($this->_sbase + ($lindex * $this->_vcount + $vindex) * $this->_tcount); - $out_off = count($result) - 1; - $result[$out_off] = $last; // reset last - continue; // discard char - } - } - - // Find out, wether two current characters are LV and T - $sindex = $last - $this->_sbase; - if (0 <= $sindex && $sindex < $this->_scount && ($sindex % $this->_tcount) == 0) { - $tindex = $char - $this->_tbase; - if (0 <= $tindex && $tindex <= $this->_tcount) { - // create syllable of form LVT - $last += $tindex; - $out_off = count($result) - 1; - $result[$out_off] = $last; // reset last - continue; // discard char - } - } - // if neither case was true, just add the character - $last = $char; - $result[] = $char; - } - return $result; - } - - /** - * Returns the combining class of a certain wide char - * @param integer Wide char to check (32bit integer) - * @return integer Combining class if found, else 0 - * @access private - */ - function _get_combining_class($char) - { - return isset($this->np_norm_combcls[$char]) ? $this->np_norm_combcls[$char] : 0; - } - - /** - * Apllies the cannonical ordering of a decomposed UCS4 sequence - * @param array Decomposed UCS4 sequence - * @return array Ordered USC4 sequence - * @access private - */ - function _apply_cannonical_ordering($input) - { - $swap = true; - $size = count($input); - while ($swap) { - $swap = false; - $last = $this->_get_combining_class($input[0]); - for ($i = 0; $i < $size - 1; ++$i) { - $next = $this->_get_combining_class($input[$i+1]); - if ($next != 0 && $last > $next) { - // Move item leftward until it fits - for ($j = $i + 1; $j > 0; --$j) { - if ($this->_get_combining_class($input[$j - 1]) <= $next) break; - $t = $input[$j]; - $input[$j] = $input[$j - 1]; - $input[$j - 1] = $t; - $swap = 1; - } - // Reentering the loop looking at the old character again - $next = $last; - } - $last = $next; - } - } - return $input; - } - - /** - * Do composition of a sequence of starter and non-starter - * @param array UCS4 Decomposed sequence - * @return array Ordered USC4 sequence - * @access private - */ - function _combine($input) - { - $inp_len = count($input); - // Is it a Hangul syllable? - if (1 != $inp_len) { - $hangul = $this->_hangul_compose($input); - if (count($hangul) != $inp_len) return $hangul; // This place is probably wrong - } - foreach ($this->np_casemap as $np_src => $np_target) { - if ($np_target[0] != $input[0]) continue; - if (count($np_target) != $inp_len) continue; - $hit = false; - foreach ($input as $k2 => $v2) { - if ($v2 == $np_target[$k2]) { - $hit = true; - } else { - $hit = false; - break; - } - } - if ($hit) return $np_src; - } - return false; - } - - /** - * This converts an UTF-8 encoded string to its UCS-4 representation - * By talking about UCS-4 "strings" we mean arrays of 32bit integers representing - * each of the "chars". This is due to PHP not being able to handle strings with - * bit depth different from 8. This apllies to the reverse method _ucs4_to_utf8(), too. - * The following UTF-8 encodings are supported: - * bytes bits representation - * 1 7 0xxxxxxx - * 2 11 110xxxxx 10xxxxxx - * 3 16 1110xxxx 10xxxxxx 10xxxxxx - * 4 21 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - * 5 26 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - * 6 31 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - * Each x represents a bit that can be used to store character data. - * The five and six byte sequences are part of Annex D of ISO/IEC 10646-1:2000 - * @access private - */ - function _utf8_to_ucs4($input) - { - $output = array(); - $out_len = 0; - $inp_len = strlen($input); - $mode = 'next'; - $test = 'none'; - for ($k = 0; $k < $inp_len; ++$k) { - $v = ord($input{$k}); // Extract byte from input string - - if ($v < 128) { // We found an ASCII char - put into stirng as is - $output[$out_len] = $v; - ++$out_len; - if ('add' == $mode) { - $this->_error('Conversion from UTF-8 to UCS-4 failed: malformed input at byte '.$k); - return false; - } - continue; - } - if ('next' == $mode) { // Try to find the next start byte; determine the width of the Unicode char - $start_byte = $v; - $mode = 'add'; - $test = 'range'; - if ($v >> 5 == 6) { // &110xxxxx 10xxxxx - $next_byte = 0; // Tells, how many times subsequent bitmasks must rotate 6bits to the left - $v = ($v - 192) << 6; - } elseif ($v >> 4 == 14) { // &1110xxxx 10xxxxxx 10xxxxxx - $next_byte = 1; - $v = ($v - 224) << 12; - } elseif ($v >> 3 == 30) { // &11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - $next_byte = 2; - $v = ($v - 240) << 18; - } elseif ($v >> 2 == 62) { // &111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - $next_byte = 3; - $v = ($v - 248) << 24; - } elseif ($v >> 1 == 126) { // &1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - $next_byte = 4; - $v = ($v - 252) << 30; - } else { - $this->_error('This might be UTF-8, but I don\'t understand it at byte '.$k); - return false; - } - if ('add' == $mode) { - $output[$out_len] = (int) $v; - ++$out_len; - continue; - } - } - if ('add' == $mode) { - if (!$this->_allow_overlong && $test == 'range') { - $test = 'none'; - if (($v < 0xA0 && $start_byte == 0xE0) || ($v < 0x90 && $start_byte == 0xF0) || ($v > 0x8F && $start_byte == 0xF4)) { - $this->_error('Bogus UTF-8 character detected (out of legal range) at byte '.$k); - return false; - } - } - if ($v >> 6 == 2) { // Bit mask must be 10xxxxxx - $v = ($v - 128) << ($next_byte * 6); - $output[($out_len - 1)] += $v; - --$next_byte; - } else { - $this->_error('Conversion from UTF-8 to UCS-4 failed: malformed input at byte '.$k); - return false; - } - if ($next_byte < 0) { - $mode = 'next'; - } - } - } // for - return $output; - } - - /** - * Convert UCS-4 string into UTF-8 string - * See _utf8_to_ucs4() for details - * @access private - */ - function _ucs4_to_utf8($input) - { - $output = ''; - foreach ($input as $v) { - // $v = ord($v); - if ($v < 128) { // 7bit are transferred literally - $output .= chr($v); - } elseif ($v < (1 << 11)) { // 2 bytes - $output .= chr(192 + ($v >> 6)) . chr(128 + ($v & 63)); - } elseif ($v < (1 << 16)) { // 3 bytes - $output .= chr(224 + ($v >> 12)) . chr(128 + (($v >> 6) & 63)) . chr(128 + ($v & 63)); - } elseif ($v < (1 << 21)) { // 4 bytes - $output .= chr(240 + ($v >> 18)) . chr(128 + (($v >> 12) & 63)) - . chr(128 + (($v >> 6) & 63)) . chr(128 + ($v & 63)); - } elseif ($v < (1 << 26)) { // 5 bytes - $output .= chr(248 + ($v >> 24)) . chr(128 + (($v >> 18) & 63)) - . chr(128 + (($v >> 12) & 63)) . chr(128 + (($v >> 6) & 63)) - . chr(128 + ($v & 63)); - } elseif ($v < (1 << 31)) { // 6 bytes - $output .= chr(252 + ($v >> 30)) . chr(128 + (($v >> 24) & 63)) - . chr(128 + (($v >> 18) & 63)) . chr(128 + (($v >> 12) & 63)) - . chr(128 + (($v >> 6) & 63)) . chr(128 + ($v & 63)); - } else { - $this->_error('Conversion from UCS-4 to UTF-8 failed: malformed input at byte '.$k); - return false; - } - } - return $output; - } - - /** - * Convert UCS-4 array into UCS-4 string - * - * @access private - */ - function _ucs4_to_ucs4_string($input) - { - $output = ''; - // Take array values and split output to 4 bytes per value - // The bit mask is 255, which reads &11111111 - foreach ($input as $v) { - $output .= chr(($v >> 24) & 255) - . chr(($v >> 16) & 255) - . chr(($v >> 8) & 255) - . chr($v & 255); - } - return $output; - } - - /** - * Convert UCS-4 strin into UCS-4 garray - * - * @access private - */ - function _ucs4_string_to_ucs4($input) - { - $output = array(); - - $inp_len = strlen($input); - // Input length must be dividable by 4 - if ($inp_len % 4) { - $this->_error('Input UCS4 string is broken'); - return false; - } - - // Empty input - return empty output - if (!$inp_len) return $output; - - for ($i = 0, $out_len = -1; $i < $inp_len; ++$i) { - // Increment output position every 4 input bytes - if (!($i % 4)) { - $out_len++; - $output[$out_len] = 0; - } - $output[$out_len] += ord($input{$i}) << (8 * (3 - ($i % 4) ) ); - } - return $output; - } - - /** - * Gives you a bit representation of given Byte (8 bits), Word (16 bits) or DWord (32 bits) - * Output width is automagically determined - * @access private - */ - function show_bitmask($octet) - { - if ($octet >= (1 << 16)) $w = 31; - elseif ($octet >= (1 << 8)) $w = 15; - else $w = 7; - $return = ''; - for ($i = $w; $i > -1; $i--) { - $return .= ($octet & (1 << $i)) ? 1 : '0'; - } - return $return; - } - - /** - * echo hex represnatation of UCS4 sequence to STDOUT - * @param array UCS4 sequence - * @param boolean include bitmask in output - * @return void - * @access private - */ - function _show_hex($input, $include_bit = false) - { - foreach ($input as $k => $v) { - echo '[', $k, '] => ', sprintf('%X', $v); - if ($include_bit) { - echo ' (', $this->show_bitmask($v), ')'; - } - echo "\n"; - } - } -} - -/** -* Adapter class for aligning the API of Net_IDNA_php4 with that of -* Net_IDNA -* @author Matthias Sommerfeld -*/ -class Net_IDNA extends Net_IDNA_php4 -{ - /** - * Constructor - * - * @param array $options - * @access public - * @see setParams() - */ - function Net_IDNA($options = false) - { - $this->IC = new idna_convert($options); - return $this->IC; - } - - /** - * Sets a new option value. Available options and values: - * - * [utf8 - Use either UTF-8 or ISO-8859-1 as input (true for UTF-8, false - * otherwise); The output is always UTF-8] - * [overlong - Unicode does not allow unnecessarily long encodings of chars, - * to allow this, set this parameter to true, else to false; - * default is false.] - * [strict - true: strict mode, good for registration purposes - Causes errors - * on failures; false: loose mode, ideal for "wildlife" applications - * by silently ignoring errors and returning the original input instead] - * - * @param mixed $option Parameter to set (string: single parameter; array of Parameter => Value pairs) - * @param string $value Value to use (if parameter 1 is a string) - * @return boolean true on success, false otherwise - * @access public - */ - function setParams($option, $param = false) - { - return $this->IC->set_parameters($option, $param); - } -} - -?> diff --git a/gulliver/thirdparty/pear/Net/IDNA/php5.php b/gulliver/thirdparty/pear/Net/IDNA/php5.php deleted file mode 100644 index cc8484b92..000000000 --- a/gulliver/thirdparty/pear/Net/IDNA/php5.php +++ /dev/null @@ -1,3233 +0,0 @@ - - * @author Matthias Sommerfeld - * @author Stefan Neufeind - * @package Net - * @version $Id: php5.php,v 1.3 2008/03/22 15:24:17 neufeind Exp $ - */ - -class Net_IDNA_php5 -{ - // {{{ npdata - /** - * These Unicode codepoints are - * mapped to nothing, See RFC3454 for details - * - * @static - * @var array - * @access private - */ - private static $_np_map_nothing = array( - 0xAD, - 0x34F, - 0x1806, - 0x180B, - 0x180C, - 0x180D, - 0x200B, - 0x200C, - 0x200D, - 0x2060, - 0xFE00, - 0xFE01, - 0xFE02, - 0xFE03, - 0xFE04, - 0xFE05, - 0xFE06, - 0xFE07, - 0xFE08, - 0xFE09, - 0xFE0A, - 0xFE0B, - 0xFE0C, - 0xFE0D, - 0xFE0E, - 0xFE0F, - 0xFEFF - ); - - /** - * Prohibited codepints - * - * @static - * @var array - * @access private - */ - private static $_general_prohibited = array( - 0, - 1, - 2, - 3, - 4, - 5, - 6, - 7, - 8, - 9, - 0xA, - 0xB, - 0xC, - 0xD, - 0xE, - 0xF, - 0x10, - 0x11, - 0x12, - 0x13, - 0x14, - 0x15, - 0x16, - 0x17, - 0x18, - 0x19, - 0x1A, - 0x1B, - 0x1C, - 0x1D, - 0x1E, - 0x1F, - 0x20, - 0x21, - 0x22, - 0x23, - 0x24, - 0x25, - 0x26, - 0x27, - 0x28, - 0x29, - 0x2A, - 0x2B, - 0x2C, - 0x2F, - 0x3B, - 0x3C, - 0x3D, - 0x3E, - 0x3F, - 0x40, - 0x5B, - 0x5C, - 0x5D, - 0x5E, - 0x5F, - 0x60, - 0x7B, - 0x7C, - 0x7D, - 0x7E, - 0x7F, - 0x3002 - ); - - /** - * Codepints prohibited by Nameprep - * @static - * @var array - * @access private - */ - private static $_np_prohibit = array( - 0xA0, - 0x1680, - 0x2000, - 0x2001, - 0x2002, - 0x2003, - 0x2004, - 0x2005, - 0x2006, - 0x2007, - 0x2008, - 0x2009, - 0x200A, - 0x200B, - 0x202F, - 0x205F, - 0x3000, - 0x6DD, - 0x70F, - 0x180E, - 0x200C, - 0x200D, - 0x2028, - 0x2029, - 0xFEFF, - 0xFFF9, - 0xFFFA, - 0xFFFB, - 0xFFFC, - 0xFFFE, - 0xFFFF, - 0x1FFFE, - 0x1FFFF, - 0x2FFFE, - 0x2FFFF, - 0x3FFFE, - 0x3FFFF, - 0x4FFFE, - 0x4FFFF, - 0x5FFFE, - 0x5FFFF, - 0x6FFFE, - 0x6FFFF, - 0x7FFFE, - 0x7FFFF, - 0x8FFFE, - 0x8FFFF, - 0x9FFFE, - 0x9FFFF, - 0xAFFFE, - 0xAFFFF, - 0xBFFFE, - 0xBFFFF, - 0xCFFFE, - 0xCFFFF, - 0xDFFFE, - 0xDFFFF, - 0xEFFFE, - 0xEFFFF, - 0xFFFFE, - 0xFFFFF, - 0x10FFFE, - 0x10FFFF, - 0xFFF9, - 0xFFFA, - 0xFFFB, - 0xFFFC, - 0xFFFD, - 0x340, - 0x341, - 0x200E, - 0x200F, - 0x202A, - 0x202B, - 0x202C, - 0x202D, - 0x202E, - 0x206A, - 0x206B, - 0x206C, - 0x206D, - 0x206E, - 0x206F, - 0xE0001 - ); - - /** - * Codepoint ranges prohibited by nameprep - * - * @static - * @var array - * @access private - */ - private static $_np_prohibit_ranges = array( - array(0x80, 0x9F ), - array(0x2060, 0x206F ), - array(0x1D173, 0x1D17A ), - array(0xE000, 0xF8FF ), - array(0xF0000, 0xFFFFD ), - array(0x100000, 0x10FFFD), - array(0xFDD0, 0xFDEF ), - array(0xD800, 0xDFFF ), - array(0x2FF0, 0x2FFB ), - array(0xE0020, 0xE007F ) - ); - - /** - * Replacement mappings (casemapping, replacement sequences, ...) - * - * @static - * @var array - * @access private - */ - private static $_np_replacemaps = array( - 0x41 => array(0x61), - 0x42 => array(0x62), - 0x43 => array(0x63), - 0x44 => array(0x64), - 0x45 => array(0x65), - 0x46 => array(0x66), - 0x47 => array(0x67), - 0x48 => array(0x68), - 0x49 => array(0x69), - 0x4A => array(0x6A), - 0x4B => array(0x6B), - 0x4C => array(0x6C), - 0x4D => array(0x6D), - 0x4E => array(0x6E), - 0x4F => array(0x6F), - 0x50 => array(0x70), - 0x51 => array(0x71), - 0x52 => array(0x72), - 0x53 => array(0x73), - 0x54 => array(0x74), - 0x55 => array(0x75), - 0x56 => array(0x76), - 0x57 => array(0x77), - 0x58 => array(0x78), - 0x59 => array(0x79), - 0x5A => array(0x7A), - 0xB5 => array(0x3BC), - 0xC0 => array(0xE0), - 0xC1 => array(0xE1), - 0xC2 => array(0xE2), - 0xC3 => array(0xE3), - 0xC4 => array(0xE4), - 0xC5 => array(0xE5), - 0xC6 => array(0xE6), - 0xC7 => array(0xE7), - 0xC8 => array(0xE8), - 0xC9 => array(0xE9), - 0xCA => array(0xEA), - 0xCB => array(0xEB), - 0xCC => array(0xEC), - 0xCD => array(0xED), - 0xCE => array(0xEE), - 0xCF => array(0xEF), - 0xD0 => array(0xF0), - 0xD1 => array(0xF1), - 0xD2 => array(0xF2), - 0xD3 => array(0xF3), - 0xD4 => array(0xF4), - 0xD5 => array(0xF5), - 0xD6 => array(0xF6), - 0xD8 => array(0xF8), - 0xD9 => array(0xF9), - 0xDA => array(0xFA), - 0xDB => array(0xFB), - 0xDC => array(0xFC), - 0xDD => array(0xFD), - 0xDE => array(0xFE), - 0xDF => array(0x73, 0x73), - 0x100 => array(0x101), - 0x102 => array(0x103), - 0x104 => array(0x105), - 0x106 => array(0x107), - 0x108 => array(0x109), - 0x10A => array(0x10B), - 0x10C => array(0x10D), - 0x10E => array(0x10F), - 0x110 => array(0x111), - 0x112 => array(0x113), - 0x114 => array(0x115), - 0x116 => array(0x117), - 0x118 => array(0x119), - 0x11A => array(0x11B), - 0x11C => array(0x11D), - 0x11E => array(0x11F), - 0x120 => array(0x121), - 0x122 => array(0x123), - 0x124 => array(0x125), - 0x126 => array(0x127), - 0x128 => array(0x129), - 0x12A => array(0x12B), - 0x12C => array(0x12D), - 0x12E => array(0x12F), - 0x130 => array(0x69, 0x307), - 0x132 => array(0x133), - 0x134 => array(0x135), - 0x136 => array(0x137), - 0x139 => array(0x13A), - 0x13B => array(0x13C), - 0x13D => array(0x13E), - 0x13F => array(0x140), - 0x141 => array(0x142), - 0x143 => array(0x144), - 0x145 => array(0x146), - 0x147 => array(0x148), - 0x149 => array(0x2BC, 0x6E), - 0x14A => array(0x14B), - 0x14C => array(0x14D), - 0x14E => array(0x14F), - 0x150 => array(0x151), - 0x152 => array(0x153), - 0x154 => array(0x155), - 0x156 => array(0x157), - 0x158 => array(0x159), - 0x15A => array(0x15B), - 0x15C => array(0x15D), - 0x15E => array(0x15F), - 0x160 => array(0x161), - 0x162 => array(0x163), - 0x164 => array(0x165), - 0x166 => array(0x167), - 0x168 => array(0x169), - 0x16A => array(0x16B), - 0x16C => array(0x16D), - 0x16E => array(0x16F), - 0x170 => array(0x171), - 0x172 => array(0x173), - 0x174 => array(0x175), - 0x176 => array(0x177), - 0x178 => array(0xFF), - 0x179 => array(0x17A), - 0x17B => array(0x17C), - 0x17D => array(0x17E), - 0x17F => array(0x73), - 0x181 => array(0x253), - 0x182 => array(0x183), - 0x184 => array(0x185), - 0x186 => array(0x254), - 0x187 => array(0x188), - 0x189 => array(0x256), - 0x18A => array(0x257), - 0x18B => array(0x18C), - 0x18E => array(0x1DD), - 0x18F => array(0x259), - 0x190 => array(0x25B), - 0x191 => array(0x192), - 0x193 => array(0x260), - 0x194 => array(0x263), - 0x196 => array(0x269), - 0x197 => array(0x268), - 0x198 => array(0x199), - 0x19C => array(0x26F), - 0x19D => array(0x272), - 0x19F => array(0x275), - 0x1A0 => array(0x1A1), - 0x1A2 => array(0x1A3), - 0x1A4 => array(0x1A5), - 0x1A6 => array(0x280), - 0x1A7 => array(0x1A8), - 0x1A9 => array(0x283), - 0x1AC => array(0x1AD), - 0x1AE => array(0x288), - 0x1AF => array(0x1B0), - 0x1B1 => array(0x28A), - 0x1B2 => array(0x28B), - 0x1B3 => array(0x1B4), - 0x1B5 => array(0x1B6), - 0x1B7 => array(0x292), - 0x1B8 => array(0x1B9), - 0x1BC => array(0x1BD), - 0x1C4 => array(0x1C6), - 0x1C5 => array(0x1C6), - 0x1C7 => array(0x1C9), - 0x1C8 => array(0x1C9), - 0x1CA => array(0x1CC), - 0x1CB => array(0x1CC), - 0x1CD => array(0x1CE), - 0x1CF => array(0x1D0), - 0x1D1 => array(0x1D2), - 0x1D3 => array(0x1D4), - 0x1D5 => array(0x1D6), - 0x1D7 => array(0x1D8), - 0x1D9 => array(0x1DA), - 0x1DB => array(0x1DC), - 0x1DE => array(0x1DF), - 0x1E0 => array(0x1E1), - 0x1E2 => array(0x1E3), - 0x1E4 => array(0x1E5), - 0x1E6 => array(0x1E7), - 0x1E8 => array(0x1E9), - 0x1EA => array(0x1EB), - 0x1EC => array(0x1ED), - 0x1EE => array(0x1EF), - 0x1F0 => array(0x6A, 0x30C), - 0x1F1 => array(0x1F3), - 0x1F2 => array(0x1F3), - 0x1F4 => array(0x1F5), - 0x1F6 => array(0x195), - 0x1F7 => array(0x1BF), - 0x1F8 => array(0x1F9), - 0x1FA => array(0x1FB), - 0x1FC => array(0x1FD), - 0x1FE => array(0x1FF), - 0x200 => array(0x201), - 0x202 => array(0x203), - 0x204 => array(0x205), - 0x206 => array(0x207), - 0x208 => array(0x209), - 0x20A => array(0x20B), - 0x20C => array(0x20D), - 0x20E => array(0x20F), - 0x210 => array(0x211), - 0x212 => array(0x213), - 0x214 => array(0x215), - 0x216 => array(0x217), - 0x218 => array(0x219), - 0x21A => array(0x21B), - 0x21C => array(0x21D), - 0x21E => array(0x21F), - 0x220 => array(0x19E), - 0x222 => array(0x223), - 0x224 => array(0x225), - 0x226 => array(0x227), - 0x228 => array(0x229), - 0x22A => array(0x22B), - 0x22C => array(0x22D), - 0x22E => array(0x22F), - 0x230 => array(0x231), - 0x232 => array(0x233), - 0x345 => array(0x3B9), - 0x37A => array(0x20, 0x3B9), - 0x386 => array(0x3AC), - 0x388 => array(0x3AD), - 0x389 => array(0x3AE), - 0x38A => array(0x3AF), - 0x38C => array(0x3CC), - 0x38E => array(0x3CD), - 0x38F => array(0x3CE), - 0x390 => array(0x3B9, 0x308, 0x301), - 0x391 => array(0x3B1), - 0x392 => array(0x3B2), - 0x393 => array(0x3B3), - 0x394 => array(0x3B4), - 0x395 => array(0x3B5), - 0x396 => array(0x3B6), - 0x397 => array(0x3B7), - 0x398 => array(0x3B8), - 0x399 => array(0x3B9), - 0x39A => array(0x3BA), - 0x39B => array(0x3BB), - 0x39C => array(0x3BC), - 0x39D => array(0x3BD), - 0x39E => array(0x3BE), - 0x39F => array(0x3BF), - 0x3A0 => array(0x3C0), - 0x3A1 => array(0x3C1), - 0x3A3 => array(0x3C3), - 0x3A4 => array(0x3C4), - 0x3A5 => array(0x3C5), - 0x3A6 => array(0x3C6), - 0x3A7 => array(0x3C7), - 0x3A8 => array(0x3C8), - 0x3A9 => array(0x3C9), - 0x3AA => array(0x3CA), - 0x3AB => array(0x3CB), - 0x3B0 => array(0x3C5, 0x308, 0x301), - 0x3C2 => array(0x3C3), - 0x3D0 => array(0x3B2), - 0x3D1 => array(0x3B8), - 0x3D2 => array(0x3C5), - 0x3D3 => array(0x3CD), - 0x3D4 => array(0x3CB), - 0x3D5 => array(0x3C6), - 0x3D6 => array(0x3C0), - 0x3D8 => array(0x3D9), - 0x3DA => array(0x3DB), - 0x3DC => array(0x3DD), - 0x3DE => array(0x3DF), - 0x3E0 => array(0x3E1), - 0x3E2 => array(0x3E3), - 0x3E4 => array(0x3E5), - 0x3E6 => array(0x3E7), - 0x3E8 => array(0x3E9), - 0x3EA => array(0x3EB), - 0x3EC => array(0x3ED), - 0x3EE => array(0x3EF), - 0x3F0 => array(0x3BA), - 0x3F1 => array(0x3C1), - 0x3F2 => array(0x3C3), - 0x3F4 => array(0x3B8), - 0x3F5 => array(0x3B5), - 0x400 => array(0x450), - 0x401 => array(0x451), - 0x402 => array(0x452), - 0x403 => array(0x453), - 0x404 => array(0x454), - 0x405 => array(0x455), - 0x406 => array(0x456), - 0x407 => array(0x457), - 0x408 => array(0x458), - 0x409 => array(0x459), - 0x40A => array(0x45A), - 0x40B => array(0x45B), - 0x40C => array(0x45C), - 0x40D => array(0x45D), - 0x40E => array(0x45E), - 0x40F => array(0x45F), - 0x410 => array(0x430), - 0x411 => array(0x431), - 0x412 => array(0x432), - 0x413 => array(0x433), - 0x414 => array(0x434), - 0x415 => array(0x435), - 0x416 => array(0x436), - 0x417 => array(0x437), - 0x418 => array(0x438), - 0x419 => array(0x439), - 0x41A => array(0x43A), - 0x41B => array(0x43B), - 0x41C => array(0x43C), - 0x41D => array(0x43D), - 0x41E => array(0x43E), - 0x41F => array(0x43F), - 0x420 => array(0x440), - 0x421 => array(0x441), - 0x422 => array(0x442), - 0x423 => array(0x443), - 0x424 => array(0x444), - 0x425 => array(0x445), - 0x426 => array(0x446), - 0x427 => array(0x447), - 0x428 => array(0x448), - 0x429 => array(0x449), - 0x42A => array(0x44A), - 0x42B => array(0x44B), - 0x42C => array(0x44C), - 0x42D => array(0x44D), - 0x42E => array(0x44E), - 0x42F => array(0x44F), - 0x460 => array(0x461), - 0x462 => array(0x463), - 0x464 => array(0x465), - 0x466 => array(0x467), - 0x468 => array(0x469), - 0x46A => array(0x46B), - 0x46C => array(0x46D), - 0x46E => array(0x46F), - 0x470 => array(0x471), - 0x472 => array(0x473), - 0x474 => array(0x475), - 0x476 => array(0x477), - 0x478 => array(0x479), - 0x47A => array(0x47B), - 0x47C => array(0x47D), - 0x47E => array(0x47F), - 0x480 => array(0x481), - 0x48A => array(0x48B), - 0x48C => array(0x48D), - 0x48E => array(0x48F), - 0x490 => array(0x491), - 0x492 => array(0x493), - 0x494 => array(0x495), - 0x496 => array(0x497), - 0x498 => array(0x499), - 0x49A => array(0x49B), - 0x49C => array(0x49D), - 0x49E => array(0x49F), - 0x4A0 => array(0x4A1), - 0x4A2 => array(0x4A3), - 0x4A4 => array(0x4A5), - 0x4A6 => array(0x4A7), - 0x4A8 => array(0x4A9), - 0x4AA => array(0x4AB), - 0x4AC => array(0x4AD), - 0x4AE => array(0x4AF), - 0x4B0 => array(0x4B1), - 0x4B2 => array(0x4B3), - 0x4B4 => array(0x4B5), - 0x4B6 => array(0x4B7), - 0x4B8 => array(0x4B9), - 0x4BA => array(0x4BB), - 0x4BC => array(0x4BD), - 0x4BE => array(0x4BF), - 0x4C1 => array(0x4C2), - 0x4C3 => array(0x4C4), - 0x4C5 => array(0x4C6), - 0x4C7 => array(0x4C8), - 0x4C9 => array(0x4CA), - 0x4CB => array(0x4CC), - 0x4CD => array(0x4CE), - 0x4D0 => array(0x4D1), - 0x4D2 => array(0x4D3), - 0x4D4 => array(0x4D5), - 0x4D6 => array(0x4D7), - 0x4D8 => array(0x4D9), - 0x4DA => array(0x4DB), - 0x4DC => array(0x4DD), - 0x4DE => array(0x4DF), - 0x4E0 => array(0x4E1), - 0x4E2 => array(0x4E3), - 0x4E4 => array(0x4E5), - 0x4E6 => array(0x4E7), - 0x4E8 => array(0x4E9), - 0x4EA => array(0x4EB), - 0x4EC => array(0x4ED), - 0x4EE => array(0x4EF), - 0x4F0 => array(0x4F1), - 0x4F2 => array(0x4F3), - 0x4F4 => array(0x4F5), - 0x4F8 => array(0x4F9), - 0x500 => array(0x501), - 0x502 => array(0x503), - 0x504 => array(0x505), - 0x506 => array(0x507), - 0x508 => array(0x509), - 0x50A => array(0x50B), - 0x50C => array(0x50D), - 0x50E => array(0x50F), - 0x531 => array(0x561), - 0x532 => array(0x562), - 0x533 => array(0x563), - 0x534 => array(0x564), - 0x535 => array(0x565), - 0x536 => array(0x566), - 0x537 => array(0x567), - 0x538 => array(0x568), - 0x539 => array(0x569), - 0x53A => array(0x56A), - 0x53B => array(0x56B), - 0x53C => array(0x56C), - 0x53D => array(0x56D), - 0x53E => array(0x56E), - 0x53F => array(0x56F), - 0x540 => array(0x570), - 0x541 => array(0x571), - 0x542 => array(0x572), - 0x543 => array(0x573), - 0x544 => array(0x574), - 0x545 => array(0x575), - 0x546 => array(0x576), - 0x547 => array(0x577), - 0x548 => array(0x578), - 0x549 => array(0x579), - 0x54A => array(0x57A), - 0x54B => array(0x57B), - 0x54C => array(0x57C), - 0x54D => array(0x57D), - 0x54E => array(0x57E), - 0x54F => array(0x57F), - 0x550 => array(0x580), - 0x551 => array(0x581), - 0x552 => array(0x582), - 0x553 => array(0x583), - 0x554 => array(0x584), - 0x555 => array(0x585), - 0x556 => array(0x586), - 0x587 => array(0x565, 0x582), - 0x1E00 => array(0x1E01), - 0x1E02 => array(0x1E03), - 0x1E04 => array(0x1E05), - 0x1E06 => array(0x1E07), - 0x1E08 => array(0x1E09), - 0x1E0A => array(0x1E0B), - 0x1E0C => array(0x1E0D), - 0x1E0E => array(0x1E0F), - 0x1E10 => array(0x1E11), - 0x1E12 => array(0x1E13), - 0x1E14 => array(0x1E15), - 0x1E16 => array(0x1E17), - 0x1E18 => array(0x1E19), - 0x1E1A => array(0x1E1B), - 0x1E1C => array(0x1E1D), - 0x1E1E => array(0x1E1F), - 0x1E20 => array(0x1E21), - 0x1E22 => array(0x1E23), - 0x1E24 => array(0x1E25), - 0x1E26 => array(0x1E27), - 0x1E28 => array(0x1E29), - 0x1E2A => array(0x1E2B), - 0x1E2C => array(0x1E2D), - 0x1E2E => array(0x1E2F), - 0x1E30 => array(0x1E31), - 0x1E32 => array(0x1E33), - 0x1E34 => array(0x1E35), - 0x1E36 => array(0x1E37), - 0x1E38 => array(0x1E39), - 0x1E3A => array(0x1E3B), - 0x1E3C => array(0x1E3D), - 0x1E3E => array(0x1E3F), - 0x1E40 => array(0x1E41), - 0x1E42 => array(0x1E43), - 0x1E44 => array(0x1E45), - 0x1E46 => array(0x1E47), - 0x1E48 => array(0x1E49), - 0x1E4A => array(0x1E4B), - 0x1E4C => array(0x1E4D), - 0x1E4E => array(0x1E4F), - 0x1E50 => array(0x1E51), - 0x1E52 => array(0x1E53), - 0x1E54 => array(0x1E55), - 0x1E56 => array(0x1E57), - 0x1E58 => array(0x1E59), - 0x1E5A => array(0x1E5B), - 0x1E5C => array(0x1E5D), - 0x1E5E => array(0x1E5F), - 0x1E60 => array(0x1E61), - 0x1E62 => array(0x1E63), - 0x1E64 => array(0x1E65), - 0x1E66 => array(0x1E67), - 0x1E68 => array(0x1E69), - 0x1E6A => array(0x1E6B), - 0x1E6C => array(0x1E6D), - 0x1E6E => array(0x1E6F), - 0x1E70 => array(0x1E71), - 0x1E72 => array(0x1E73), - 0x1E74 => array(0x1E75), - 0x1E76 => array(0x1E77), - 0x1E78 => array(0x1E79), - 0x1E7A => array(0x1E7B), - 0x1E7C => array(0x1E7D), - 0x1E7E => array(0x1E7F), - 0x1E80 => array(0x1E81), - 0x1E82 => array(0x1E83), - 0x1E84 => array(0x1E85), - 0x1E86 => array(0x1E87), - 0x1E88 => array(0x1E89), - 0x1E8A => array(0x1E8B), - 0x1E8C => array(0x1E8D), - 0x1E8E => array(0x1E8F), - 0x1E90 => array(0x1E91), - 0x1E92 => array(0x1E93), - 0x1E94 => array(0x1E95), - 0x1E96 => array(0x68, 0x331), - 0x1E97 => array(0x74, 0x308), - 0x1E98 => array(0x77, 0x30A), - 0x1E99 => array(0x79, 0x30A), - 0x1E9A => array(0x61, 0x2BE), - 0x1E9B => array(0x1E61), - 0x1EA0 => array(0x1EA1), - 0x1EA2 => array(0x1EA3), - 0x1EA4 => array(0x1EA5), - 0x1EA6 => array(0x1EA7), - 0x1EA8 => array(0x1EA9), - 0x1EAA => array(0x1EAB), - 0x1EAC => array(0x1EAD), - 0x1EAE => array(0x1EAF), - 0x1EB0 => array(0x1EB1), - 0x1EB2 => array(0x1EB3), - 0x1EB4 => array(0x1EB5), - 0x1EB6 => array(0x1EB7), - 0x1EB8 => array(0x1EB9), - 0x1EBA => array(0x1EBB), - 0x1EBC => array(0x1EBD), - 0x1EBE => array(0x1EBF), - 0x1EC0 => array(0x1EC1), - 0x1EC2 => array(0x1EC3), - 0x1EC4 => array(0x1EC5), - 0x1EC6 => array(0x1EC7), - 0x1EC8 => array(0x1EC9), - 0x1ECA => array(0x1ECB), - 0x1ECC => array(0x1ECD), - 0x1ECE => array(0x1ECF), - 0x1ED0 => array(0x1ED1), - 0x1ED2 => array(0x1ED3), - 0x1ED4 => array(0x1ED5), - 0x1ED6 => array(0x1ED7), - 0x1ED8 => array(0x1ED9), - 0x1EDA => array(0x1EDB), - 0x1EDC => array(0x1EDD), - 0x1EDE => array(0x1EDF), - 0x1EE0 => array(0x1EE1), - 0x1EE2 => array(0x1EE3), - 0x1EE4 => array(0x1EE5), - 0x1EE6 => array(0x1EE7), - 0x1EE8 => array(0x1EE9), - 0x1EEA => array(0x1EEB), - 0x1EEC => array(0x1EED), - 0x1EEE => array(0x1EEF), - 0x1EF0 => array(0x1EF1), - 0x1EF2 => array(0x1EF3), - 0x1EF4 => array(0x1EF5), - 0x1EF6 => array(0x1EF7), - 0x1EF8 => array(0x1EF9), - 0x1F08 => array(0x1F00), - 0x1F09 => array(0x1F01), - 0x1F0A => array(0x1F02), - 0x1F0B => array(0x1F03), - 0x1F0C => array(0x1F04), - 0x1F0D => array(0x1F05), - 0x1F0E => array(0x1F06), - 0x1F0F => array(0x1F07), - 0x1F18 => array(0x1F10), - 0x1F19 => array(0x1F11), - 0x1F1A => array(0x1F12), - 0x1F1B => array(0x1F13), - 0x1F1C => array(0x1F14), - 0x1F1D => array(0x1F15), - 0x1F28 => array(0x1F20), - 0x1F29 => array(0x1F21), - 0x1F2A => array(0x1F22), - 0x1F2B => array(0x1F23), - 0x1F2C => array(0x1F24), - 0x1F2D => array(0x1F25), - 0x1F2E => array(0x1F26), - 0x1F2F => array(0x1F27), - 0x1F38 => array(0x1F30), - 0x1F39 => array(0x1F31), - 0x1F3A => array(0x1F32), - 0x1F3B => array(0x1F33), - 0x1F3C => array(0x1F34), - 0x1F3D => array(0x1F35), - 0x1F3E => array(0x1F36), - 0x1F3F => array(0x1F37), - 0x1F48 => array(0x1F40), - 0x1F49 => array(0x1F41), - 0x1F4A => array(0x1F42), - 0x1F4B => array(0x1F43), - 0x1F4C => array(0x1F44), - 0x1F4D => array(0x1F45), - 0x1F50 => array(0x3C5, 0x313), - 0x1F52 => array(0x3C5, 0x313, 0x300), - 0x1F54 => array(0x3C5, 0x313, 0x301), - 0x1F56 => array(0x3C5, 0x313, 0x342), - 0x1F59 => array(0x1F51), - 0x1F5B => array(0x1F53), - 0x1F5D => array(0x1F55), - 0x1F5F => array(0x1F57), - 0x1F68 => array(0x1F60), - 0x1F69 => array(0x1F61), - 0x1F6A => array(0x1F62), - 0x1F6B => array(0x1F63), - 0x1F6C => array(0x1F64), - 0x1F6D => array(0x1F65), - 0x1F6E => array(0x1F66), - 0x1F6F => array(0x1F67), - 0x1F80 => array(0x1F00, 0x3B9), - 0x1F81 => array(0x1F01, 0x3B9), - 0x1F82 => array(0x1F02, 0x3B9), - 0x1F83 => array(0x1F03, 0x3B9), - 0x1F84 => array(0x1F04, 0x3B9), - 0x1F85 => array(0x1F05, 0x3B9), - 0x1F86 => array(0x1F06, 0x3B9), - 0x1F87 => array(0x1F07, 0x3B9), - 0x1F88 => array(0x1F00, 0x3B9), - 0x1F89 => array(0x1F01, 0x3B9), - 0x1F8A => array(0x1F02, 0x3B9), - 0x1F8B => array(0x1F03, 0x3B9), - 0x1F8C => array(0x1F04, 0x3B9), - 0x1F8D => array(0x1F05, 0x3B9), - 0x1F8E => array(0x1F06, 0x3B9), - 0x1F8F => array(0x1F07, 0x3B9), - 0x1F90 => array(0x1F20, 0x3B9), - 0x1F91 => array(0x1F21, 0x3B9), - 0x1F92 => array(0x1F22, 0x3B9), - 0x1F93 => array(0x1F23, 0x3B9), - 0x1F94 => array(0x1F24, 0x3B9), - 0x1F95 => array(0x1F25, 0x3B9), - 0x1F96 => array(0x1F26, 0x3B9), - 0x1F97 => array(0x1F27, 0x3B9), - 0x1F98 => array(0x1F20, 0x3B9), - 0x1F99 => array(0x1F21, 0x3B9), - 0x1F9A => array(0x1F22, 0x3B9), - 0x1F9B => array(0x1F23, 0x3B9), - 0x1F9C => array(0x1F24, 0x3B9), - 0x1F9D => array(0x1F25, 0x3B9), - 0x1F9E => array(0x1F26, 0x3B9), - 0x1F9F => array(0x1F27, 0x3B9), - 0x1FA0 => array(0x1F60, 0x3B9), - 0x1FA1 => array(0x1F61, 0x3B9), - 0x1FA2 => array(0x1F62, 0x3B9), - 0x1FA3 => array(0x1F63, 0x3B9), - 0x1FA4 => array(0x1F64, 0x3B9), - 0x1FA5 => array(0x1F65, 0x3B9), - 0x1FA6 => array(0x1F66, 0x3B9), - 0x1FA7 => array(0x1F67, 0x3B9), - 0x1FA8 => array(0x1F60, 0x3B9), - 0x1FA9 => array(0x1F61, 0x3B9), - 0x1FAA => array(0x1F62, 0x3B9), - 0x1FAB => array(0x1F63, 0x3B9), - 0x1FAC => array(0x1F64, 0x3B9), - 0x1FAD => array(0x1F65, 0x3B9), - 0x1FAE => array(0x1F66, 0x3B9), - 0x1FAF => array(0x1F67, 0x3B9), - 0x1FB2 => array(0x1F70, 0x3B9), - 0x1FB3 => array(0x3B1, 0x3B9), - 0x1FB4 => array(0x3AC, 0x3B9), - 0x1FB6 => array(0x3B1, 0x342), - 0x1FB7 => array(0x3B1, 0x342, 0x3B9), - 0x1FB8 => array(0x1FB0), - 0x1FB9 => array(0x1FB1), - 0x1FBA => array(0x1F70), - 0x1FBB => array(0x1F71), - 0x1FBC => array(0x3B1, 0x3B9), - 0x1FBE => array(0x3B9), - 0x1FC2 => array(0x1F74, 0x3B9), - 0x1FC3 => array(0x3B7, 0x3B9), - 0x1FC4 => array(0x3AE, 0x3B9), - 0x1FC6 => array(0x3B7, 0x342), - 0x1FC7 => array(0x3B7, 0x342, 0x3B9), - 0x1FC8 => array(0x1F72), - 0x1FC9 => array(0x1F73), - 0x1FCA => array(0x1F74), - 0x1FCB => array(0x1F75), - 0x1FCC => array(0x3B7, 0x3B9), - 0x1FD2 => array(0x3B9, 0x308, 0x300), - 0x1FD3 => array(0x3B9, 0x308, 0x301), - 0x1FD6 => array(0x3B9, 0x342), - 0x1FD7 => array(0x3B9, 0x308, 0x342), - 0x1FD8 => array(0x1FD0), - 0x1FD9 => array(0x1FD1), - 0x1FDA => array(0x1F76), - 0x1FDB => array(0x1F77), - 0x1FE2 => array(0x3C5, 0x308, 0x300), - 0x1FE3 => array(0x3C5, 0x308, 0x301), - 0x1FE4 => array(0x3C1, 0x313), - 0x1FE6 => array(0x3C5, 0x342), - 0x1FE7 => array(0x3C5, 0x308, 0x342), - 0x1FE8 => array(0x1FE0), - 0x1FE9 => array(0x1FE1), - 0x1FEA => array(0x1F7A), - 0x1FEB => array(0x1F7B), - 0x1FEC => array(0x1FE5), - 0x1FF2 => array(0x1F7C, 0x3B9), - 0x1FF3 => array(0x3C9, 0x3B9), - 0x1FF4 => array(0x3CE, 0x3B9), - 0x1FF6 => array(0x3C9, 0x342), - 0x1FF7 => array(0x3C9, 0x342, 0x3B9), - 0x1FF8 => array(0x1F78), - 0x1FF9 => array(0x1F79), - 0x1FFA => array(0x1F7C), - 0x1FFB => array(0x1F7D), - 0x1FFC => array(0x3C9, 0x3B9), - 0x20A8 => array(0x72, 0x73), - 0x2102 => array(0x63), - 0x2103 => array(0xB0, 0x63), - 0x2107 => array(0x25B), - 0x2109 => array(0xB0, 0x66), - 0x210B => array(0x68), - 0x210C => array(0x68), - 0x210D => array(0x68), - 0x2110 => array(0x69), - 0x2111 => array(0x69), - 0x2112 => array(0x6C), - 0x2115 => array(0x6E), - 0x2116 => array(0x6E, 0x6F), - 0x2119 => array(0x70), - 0x211A => array(0x71), - 0x211B => array(0x72), - 0x211C => array(0x72), - 0x211D => array(0x72), - 0x2120 => array(0x73, 0x6D), - 0x2121 => array(0x74, 0x65, 0x6C), - 0x2122 => array(0x74, 0x6D), - 0x2124 => array(0x7A), - 0x2126 => array(0x3C9), - 0x2128 => array(0x7A), - 0x212A => array(0x6B), - 0x212B => array(0xE5), - 0x212C => array(0x62), - 0x212D => array(0x63), - 0x2130 => array(0x65), - 0x2131 => array(0x66), - 0x2133 => array(0x6D), - 0x213E => array(0x3B3), - 0x213F => array(0x3C0), - 0x2145 => array(0x64), - 0x2160 => array(0x2170), - 0x2161 => array(0x2171), - 0x2162 => array(0x2172), - 0x2163 => array(0x2173), - 0x2164 => array(0x2174), - 0x2165 => array(0x2175), - 0x2166 => array(0x2176), - 0x2167 => array(0x2177), - 0x2168 => array(0x2178), - 0x2169 => array(0x2179), - 0x216A => array(0x217A), - 0x216B => array(0x217B), - 0x216C => array(0x217C), - 0x216D => array(0x217D), - 0x216E => array(0x217E), - 0x216F => array(0x217F), - 0x24B6 => array(0x24D0), - 0x24B7 => array(0x24D1), - 0x24B8 => array(0x24D2), - 0x24B9 => array(0x24D3), - 0x24BA => array(0x24D4), - 0x24BB => array(0x24D5), - 0x24BC => array(0x24D6), - 0x24BD => array(0x24D7), - 0x24BE => array(0x24D8), - 0x24BF => array(0x24D9), - 0x24C0 => array(0x24DA), - 0x24C1 => array(0x24DB), - 0x24C2 => array(0x24DC), - 0x24C3 => array(0x24DD), - 0x24C4 => array(0x24DE), - 0x24C5 => array(0x24DF), - 0x24C6 => array(0x24E0), - 0x24C7 => array(0x24E1), - 0x24C8 => array(0x24E2), - 0x24C9 => array(0x24E3), - 0x24CA => array(0x24E4), - 0x24CB => array(0x24E5), - 0x24CC => array(0x24E6), - 0x24CD => array(0x24E7), - 0x24CE => array(0x24E8), - 0x24CF => array(0x24E9), - 0x3371 => array(0x68, 0x70, 0x61), - 0x3373 => array(0x61, 0x75), - 0x3375 => array(0x6F, 0x76), - 0x3380 => array(0x70, 0x61), - 0x3381 => array(0x6E, 0x61), - 0x3382 => array(0x3BC, 0x61), - 0x3383 => array(0x6D, 0x61), - 0x3384 => array(0x6B, 0x61), - 0x3385 => array(0x6B, 0x62), - 0x3386 => array(0x6D, 0x62), - 0x3387 => array(0x67, 0x62), - 0x338A => array(0x70, 0x66), - 0x338B => array(0x6E, 0x66), - 0x338C => array(0x3BC, 0x66), - 0x3390 => array(0x68, 0x7A), - 0x3391 => array(0x6B, 0x68, 0x7A), - 0x3392 => array(0x6D, 0x68, 0x7A), - 0x3393 => array(0x67, 0x68, 0x7A), - 0x3394 => array(0x74, 0x68, 0x7A), - 0x33A9 => array(0x70, 0x61), - 0x33AA => array(0x6B, 0x70, 0x61), - 0x33AB => array(0x6D, 0x70, 0x61), - 0x33AC => array(0x67, 0x70, 0x61), - 0x33B4 => array(0x70, 0x76), - 0x33B5 => array(0x6E, 0x76), - 0x33B6 => array(0x3BC, 0x76), - 0x33B7 => array(0x6D, 0x76), - 0x33B8 => array(0x6B, 0x76), - 0x33B9 => array(0x6D, 0x76), - 0x33BA => array(0x70, 0x77), - 0x33BB => array(0x6E, 0x77), - 0x33BC => array(0x3BC, 0x77), - 0x33BD => array(0x6D, 0x77), - 0x33BE => array(0x6B, 0x77), - 0x33BF => array(0x6D, 0x77), - 0x33C0 => array(0x6B, 0x3C9), - 0x33C1 => array(0x6D, 0x3C9), /* - 0x33C2 => array(0x61, 0x2E, 0x6D, 0x2E), */ - 0x33C3 => array(0x62, 0x71), - 0x33C6 => array(0x63, 0x2215, 0x6B, 0x67), - 0x33C7 => array(0x63, 0x6F, 0x2E), - 0x33C8 => array(0x64, 0x62), - 0x33C9 => array(0x67, 0x79), - 0x33CB => array(0x68, 0x70), - 0x33CD => array(0x6B, 0x6B), - 0x33CE => array(0x6B, 0x6D), - 0x33D7 => array(0x70, 0x68), - 0x33D9 => array(0x70, 0x70, 0x6D), - 0x33DA => array(0x70, 0x72), - 0x33DC => array(0x73, 0x76), - 0x33DD => array(0x77, 0x62), - 0xFB00 => array(0x66, 0x66), - 0xFB01 => array(0x66, 0x69), - 0xFB02 => array(0x66, 0x6C), - 0xFB03 => array(0x66, 0x66, 0x69), - 0xFB04 => array(0x66, 0x66, 0x6C), - 0xFB05 => array(0x73, 0x74), - 0xFB06 => array(0x73, 0x74), - 0xFB13 => array(0x574, 0x576), - 0xFB14 => array(0x574, 0x565), - 0xFB15 => array(0x574, 0x56B), - 0xFB16 => array(0x57E, 0x576), - 0xFB17 => array(0x574, 0x56D), - 0xFF21 => array(0xFF41), - 0xFF22 => array(0xFF42), - 0xFF23 => array(0xFF43), - 0xFF24 => array(0xFF44), - 0xFF25 => array(0xFF45), - 0xFF26 => array(0xFF46), - 0xFF27 => array(0xFF47), - 0xFF28 => array(0xFF48), - 0xFF29 => array(0xFF49), - 0xFF2A => array(0xFF4A), - 0xFF2B => array(0xFF4B), - 0xFF2C => array(0xFF4C), - 0xFF2D => array(0xFF4D), - 0xFF2E => array(0xFF4E), - 0xFF2F => array(0xFF4F), - 0xFF30 => array(0xFF50), - 0xFF31 => array(0xFF51), - 0xFF32 => array(0xFF52), - 0xFF33 => array(0xFF53), - 0xFF34 => array(0xFF54), - 0xFF35 => array(0xFF55), - 0xFF36 => array(0xFF56), - 0xFF37 => array(0xFF57), - 0xFF38 => array(0xFF58), - 0xFF39 => array(0xFF59), - 0xFF3A => array(0xFF5A), - 0x10400 => array(0x10428), - 0x10401 => array(0x10429), - 0x10402 => array(0x1042A), - 0x10403 => array(0x1042B), - 0x10404 => array(0x1042C), - 0x10405 => array(0x1042D), - 0x10406 => array(0x1042E), - 0x10407 => array(0x1042F), - 0x10408 => array(0x10430), - 0x10409 => array(0x10431), - 0x1040A => array(0x10432), - 0x1040B => array(0x10433), - 0x1040C => array(0x10434), - 0x1040D => array(0x10435), - 0x1040E => array(0x10436), - 0x1040F => array(0x10437), - 0x10410 => array(0x10438), - 0x10411 => array(0x10439), - 0x10412 => array(0x1043A), - 0x10413 => array(0x1043B), - 0x10414 => array(0x1043C), - 0x10415 => array(0x1043D), - 0x10416 => array(0x1043E), - 0x10417 => array(0x1043F), - 0x10418 => array(0x10440), - 0x10419 => array(0x10441), - 0x1041A => array(0x10442), - 0x1041B => array(0x10443), - 0x1041C => array(0x10444), - 0x1041D => array(0x10445), - 0x1041E => array(0x10446), - 0x1041F => array(0x10447), - 0x10420 => array(0x10448), - 0x10421 => array(0x10449), - 0x10422 => array(0x1044A), - 0x10423 => array(0x1044B), - 0x10424 => array(0x1044C), - 0x10425 => array(0x1044D), - 0x1D400 => array(0x61), - 0x1D401 => array(0x62), - 0x1D402 => array(0x63), - 0x1D403 => array(0x64), - 0x1D404 => array(0x65), - 0x1D405 => array(0x66), - 0x1D406 => array(0x67), - 0x1D407 => array(0x68), - 0x1D408 => array(0x69), - 0x1D409 => array(0x6A), - 0x1D40A => array(0x6B), - 0x1D40B => array(0x6C), - 0x1D40C => array(0x6D), - 0x1D40D => array(0x6E), - 0x1D40E => array(0x6F), - 0x1D40F => array(0x70), - 0x1D410 => array(0x71), - 0x1D411 => array(0x72), - 0x1D412 => array(0x73), - 0x1D413 => array(0x74), - 0x1D414 => array(0x75), - 0x1D415 => array(0x76), - 0x1D416 => array(0x77), - 0x1D417 => array(0x78), - 0x1D418 => array(0x79), - 0x1D419 => array(0x7A), - 0x1D434 => array(0x61), - 0x1D435 => array(0x62), - 0x1D436 => array(0x63), - 0x1D437 => array(0x64), - 0x1D438 => array(0x65), - 0x1D439 => array(0x66), - 0x1D43A => array(0x67), - 0x1D43B => array(0x68), - 0x1D43C => array(0x69), - 0x1D43D => array(0x6A), - 0x1D43E => array(0x6B), - 0x1D43F => array(0x6C), - 0x1D440 => array(0x6D), - 0x1D441 => array(0x6E), - 0x1D442 => array(0x6F), - 0x1D443 => array(0x70), - 0x1D444 => array(0x71), - 0x1D445 => array(0x72), - 0x1D446 => array(0x73), - 0x1D447 => array(0x74), - 0x1D448 => array(0x75), - 0x1D449 => array(0x76), - 0x1D44A => array(0x77), - 0x1D44B => array(0x78), - 0x1D44C => array(0x79), - 0x1D44D => array(0x7A), - 0x1D468 => array(0x61), - 0x1D469 => array(0x62), - 0x1D46A => array(0x63), - 0x1D46B => array(0x64), - 0x1D46C => array(0x65), - 0x1D46D => array(0x66), - 0x1D46E => array(0x67), - 0x1D46F => array(0x68), - 0x1D470 => array(0x69), - 0x1D471 => array(0x6A), - 0x1D472 => array(0x6B), - 0x1D473 => array(0x6C), - 0x1D474 => array(0x6D), - 0x1D475 => array(0x6E), - 0x1D476 => array(0x6F), - 0x1D477 => array(0x70), - 0x1D478 => array(0x71), - 0x1D479 => array(0x72), - 0x1D47A => array(0x73), - 0x1D47B => array(0x74), - 0x1D47C => array(0x75), - 0x1D47D => array(0x76), - 0x1D47E => array(0x77), - 0x1D47F => array(0x78), - 0x1D480 => array(0x79), - 0x1D481 => array(0x7A), - 0x1D49C => array(0x61), - 0x1D49E => array(0x63), - 0x1D49F => array(0x64), - 0x1D4A2 => array(0x67), - 0x1D4A5 => array(0x6A), - 0x1D4A6 => array(0x6B), - 0x1D4A9 => array(0x6E), - 0x1D4AA => array(0x6F), - 0x1D4AB => array(0x70), - 0x1D4AC => array(0x71), - 0x1D4AE => array(0x73), - 0x1D4AF => array(0x74), - 0x1D4B0 => array(0x75), - 0x1D4B1 => array(0x76), - 0x1D4B2 => array(0x77), - 0x1D4B3 => array(0x78), - 0x1D4B4 => array(0x79), - 0x1D4B5 => array(0x7A), - 0x1D4D0 => array(0x61), - 0x1D4D1 => array(0x62), - 0x1D4D2 => array(0x63), - 0x1D4D3 => array(0x64), - 0x1D4D4 => array(0x65), - 0x1D4D5 => array(0x66), - 0x1D4D6 => array(0x67), - 0x1D4D7 => array(0x68), - 0x1D4D8 => array(0x69), - 0x1D4D9 => array(0x6A), - 0x1D4DA => array(0x6B), - 0x1D4DB => array(0x6C), - 0x1D4DC => array(0x6D), - 0x1D4DD => array(0x6E), - 0x1D4DE => array(0x6F), - 0x1D4DF => array(0x70), - 0x1D4E0 => array(0x71), - 0x1D4E1 => array(0x72), - 0x1D4E2 => array(0x73), - 0x1D4E3 => array(0x74), - 0x1D4E4 => array(0x75), - 0x1D4E5 => array(0x76), - 0x1D4E6 => array(0x77), - 0x1D4E7 => array(0x78), - 0x1D4E8 => array(0x79), - 0x1D4E9 => array(0x7A), - 0x1D504 => array(0x61), - 0x1D505 => array(0x62), - 0x1D507 => array(0x64), - 0x1D508 => array(0x65), - 0x1D509 => array(0x66), - 0x1D50A => array(0x67), - 0x1D50D => array(0x6A), - 0x1D50E => array(0x6B), - 0x1D50F => array(0x6C), - 0x1D510 => array(0x6D), - 0x1D511 => array(0x6E), - 0x1D512 => array(0x6F), - 0x1D513 => array(0x70), - 0x1D514 => array(0x71), - 0x1D516 => array(0x73), - 0x1D517 => array(0x74), - 0x1D518 => array(0x75), - 0x1D519 => array(0x76), - 0x1D51A => array(0x77), - 0x1D51B => array(0x78), - 0x1D51C => array(0x79), - 0x1D538 => array(0x61), - 0x1D539 => array(0x62), - 0x1D53B => array(0x64), - 0x1D53C => array(0x65), - 0x1D53D => array(0x66), - 0x1D53E => array(0x67), - 0x1D540 => array(0x69), - 0x1D541 => array(0x6A), - 0x1D542 => array(0x6B), - 0x1D543 => array(0x6C), - 0x1D544 => array(0x6D), - 0x1D546 => array(0x6F), - 0x1D54A => array(0x73), - 0x1D54B => array(0x74), - 0x1D54C => array(0x75), - 0x1D54D => array(0x76), - 0x1D54E => array(0x77), - 0x1D54F => array(0x78), - 0x1D550 => array(0x79), - 0x1D56C => array(0x61), - 0x1D56D => array(0x62), - 0x1D56E => array(0x63), - 0x1D56F => array(0x64), - 0x1D570 => array(0x65), - 0x1D571 => array(0x66), - 0x1D572 => array(0x67), - 0x1D573 => array(0x68), - 0x1D574 => array(0x69), - 0x1D575 => array(0x6A), - 0x1D576 => array(0x6B), - 0x1D577 => array(0x6C), - 0x1D578 => array(0x6D), - 0x1D579 => array(0x6E), - 0x1D57A => array(0x6F), - 0x1D57B => array(0x70), - 0x1D57C => array(0x71), - 0x1D57D => array(0x72), - 0x1D57E => array(0x73), - 0x1D57F => array(0x74), - 0x1D580 => array(0x75), - 0x1D581 => array(0x76), - 0x1D582 => array(0x77), - 0x1D583 => array(0x78), - 0x1D584 => array(0x79), - 0x1D585 => array(0x7A), - 0x1D5A0 => array(0x61), - 0x1D5A1 => array(0x62), - 0x1D5A2 => array(0x63), - 0x1D5A3 => array(0x64), - 0x1D5A4 => array(0x65), - 0x1D5A5 => array(0x66), - 0x1D5A6 => array(0x67), - 0x1D5A7 => array(0x68), - 0x1D5A8 => array(0x69), - 0x1D5A9 => array(0x6A), - 0x1D5AA => array(0x6B), - 0x1D5AB => array(0x6C), - 0x1D5AC => array(0x6D), - 0x1D5AD => array(0x6E), - 0x1D5AE => array(0x6F), - 0x1D5AF => array(0x70), - 0x1D5B0 => array(0x71), - 0x1D5B1 => array(0x72), - 0x1D5B2 => array(0x73), - 0x1D5B3 => array(0x74), - 0x1D5B4 => array(0x75), - 0x1D5B5 => array(0x76), - 0x1D5B6 => array(0x77), - 0x1D5B7 => array(0x78), - 0x1D5B8 => array(0x79), - 0x1D5B9 => array(0x7A), - 0x1D5D4 => array(0x61), - 0x1D5D5 => array(0x62), - 0x1D5D6 => array(0x63), - 0x1D5D7 => array(0x64), - 0x1D5D8 => array(0x65), - 0x1D5D9 => array(0x66), - 0x1D5DA => array(0x67), - 0x1D5DB => array(0x68), - 0x1D5DC => array(0x69), - 0x1D5DD => array(0x6A), - 0x1D5DE => array(0x6B), - 0x1D5DF => array(0x6C), - 0x1D5E0 => array(0x6D), - 0x1D5E1 => array(0x6E), - 0x1D5E2 => array(0x6F), - 0x1D5E3 => array(0x70), - 0x1D5E4 => array(0x71), - 0x1D5E5 => array(0x72), - 0x1D5E6 => array(0x73), - 0x1D5E7 => array(0x74), - 0x1D5E8 => array(0x75), - 0x1D5E9 => array(0x76), - 0x1D5EA => array(0x77), - 0x1D5EB => array(0x78), - 0x1D5EC => array(0x79), - 0x1D5ED => array(0x7A), - 0x1D608 => array(0x61), - 0x1D609 => array(0x62), - 0x1D60A => array(0x63), - 0x1D60B => array(0x64), - 0x1D60C => array(0x65), - 0x1D60D => array(0x66), - 0x1D60E => array(0x67), - 0x1D60F => array(0x68), - 0x1D610 => array(0x69), - 0x1D611 => array(0x6A), - 0x1D612 => array(0x6B), - 0x1D613 => array(0x6C), - 0x1D614 => array(0x6D), - 0x1D615 => array(0x6E), - 0x1D616 => array(0x6F), - 0x1D617 => array(0x70), - 0x1D618 => array(0x71), - 0x1D619 => array(0x72), - 0x1D61A => array(0x73), - 0x1D61B => array(0x74), - 0x1D61C => array(0x75), - 0x1D61D => array(0x76), - 0x1D61E => array(0x77), - 0x1D61F => array(0x78), - 0x1D620 => array(0x79), - 0x1D621 => array(0x7A), - 0x1D63C => array(0x61), - 0x1D63D => array(0x62), - 0x1D63E => array(0x63), - 0x1D63F => array(0x64), - 0x1D640 => array(0x65), - 0x1D641 => array(0x66), - 0x1D642 => array(0x67), - 0x1D643 => array(0x68), - 0x1D644 => array(0x69), - 0x1D645 => array(0x6A), - 0x1D646 => array(0x6B), - 0x1D647 => array(0x6C), - 0x1D648 => array(0x6D), - 0x1D649 => array(0x6E), - 0x1D64A => array(0x6F), - 0x1D64B => array(0x70), - 0x1D64C => array(0x71), - 0x1D64D => array(0x72), - 0x1D64E => array(0x73), - 0x1D64F => array(0x74), - 0x1D650 => array(0x75), - 0x1D651 => array(0x76), - 0x1D652 => array(0x77), - 0x1D653 => array(0x78), - 0x1D654 => array(0x79), - 0x1D655 => array(0x7A), - 0x1D670 => array(0x61), - 0x1D671 => array(0x62), - 0x1D672 => array(0x63), - 0x1D673 => array(0x64), - 0x1D674 => array(0x65), - 0x1D675 => array(0x66), - 0x1D676 => array(0x67), - 0x1D677 => array(0x68), - 0x1D678 => array(0x69), - 0x1D679 => array(0x6A), - 0x1D67A => array(0x6B), - 0x1D67B => array(0x6C), - 0x1D67C => array(0x6D), - 0x1D67D => array(0x6E), - 0x1D67E => array(0x6F), - 0x1D67F => array(0x70), - 0x1D680 => array(0x71), - 0x1D681 => array(0x72), - 0x1D682 => array(0x73), - 0x1D683 => array(0x74), - 0x1D684 => array(0x75), - 0x1D685 => array(0x76), - 0x1D686 => array(0x77), - 0x1D687 => array(0x78), - 0x1D688 => array(0x79), - 0x1D689 => array(0x7A), - 0x1D6A8 => array(0x3B1), - 0x1D6A9 => array(0x3B2), - 0x1D6AA => array(0x3B3), - 0x1D6AB => array(0x3B4), - 0x1D6AC => array(0x3B5), - 0x1D6AD => array(0x3B6), - 0x1D6AE => array(0x3B7), - 0x1D6AF => array(0x3B8), - 0x1D6B0 => array(0x3B9), - 0x1D6B1 => array(0x3BA), - 0x1D6B2 => array(0x3BB), - 0x1D6B3 => array(0x3BC), - 0x1D6B4 => array(0x3BD), - 0x1D6B5 => array(0x3BE), - 0x1D6B6 => array(0x3BF), - 0x1D6B7 => array(0x3C0), - 0x1D6B8 => array(0x3C1), - 0x1D6B9 => array(0x3B8), - 0x1D6BA => array(0x3C3), - 0x1D6BB => array(0x3C4), - 0x1D6BC => array(0x3C5), - 0x1D6BD => array(0x3C6), - 0x1D6BE => array(0x3C7), - 0x1D6BF => array(0x3C8), - 0x1D6C0 => array(0x3C9), - 0x1D6D3 => array(0x3C3), - 0x1D6E2 => array(0x3B1), - 0x1D6E3 => array(0x3B2), - 0x1D6E4 => array(0x3B3), - 0x1D6E5 => array(0x3B4), - 0x1D6E6 => array(0x3B5), - 0x1D6E7 => array(0x3B6), - 0x1D6E8 => array(0x3B7), - 0x1D6E9 => array(0x3B8), - 0x1D6EA => array(0x3B9), - 0x1D6EB => array(0x3BA), - 0x1D6EC => array(0x3BB), - 0x1D6ED => array(0x3BC), - 0x1D6EE => array(0x3BD), - 0x1D6EF => array(0x3BE), - 0x1D6F0 => array(0x3BF), - 0x1D6F1 => array(0x3C0), - 0x1D6F2 => array(0x3C1), - 0x1D6F3 => array(0x3B8), - 0x1D6F4 => array(0x3C3), - 0x1D6F5 => array(0x3C4), - 0x1D6F6 => array(0x3C5), - 0x1D6F7 => array(0x3C6), - 0x1D6F8 => array(0x3C7), - 0x1D6F9 => array(0x3C8), - 0x1D6FA => array(0x3C9), - 0x1D70D => array(0x3C3), - 0x1D71C => array(0x3B1), - 0x1D71D => array(0x3B2), - 0x1D71E => array(0x3B3), - 0x1D71F => array(0x3B4), - 0x1D720 => array(0x3B5), - 0x1D721 => array(0x3B6), - 0x1D722 => array(0x3B7), - 0x1D723 => array(0x3B8), - 0x1D724 => array(0x3B9), - 0x1D725 => array(0x3BA), - 0x1D726 => array(0x3BB), - 0x1D727 => array(0x3BC), - 0x1D728 => array(0x3BD), - 0x1D729 => array(0x3BE), - 0x1D72A => array(0x3BF), - 0x1D72B => array(0x3C0), - 0x1D72C => array(0x3C1), - 0x1D72D => array(0x3B8), - 0x1D72E => array(0x3C3), - 0x1D72F => array(0x3C4), - 0x1D730 => array(0x3C5), - 0x1D731 => array(0x3C6), - 0x1D732 => array(0x3C7), - 0x1D733 => array(0x3C8), - 0x1D734 => array(0x3C9), - 0x1D747 => array(0x3C3), - 0x1D756 => array(0x3B1), - 0x1D757 => array(0x3B2), - 0x1D758 => array(0x3B3), - 0x1D759 => array(0x3B4), - 0x1D75A => array(0x3B5), - 0x1D75B => array(0x3B6), - 0x1D75C => array(0x3B7), - 0x1D75D => array(0x3B8), - 0x1D75E => array(0x3B9), - 0x1D75F => array(0x3BA), - 0x1D760 => array(0x3BB), - 0x1D761 => array(0x3BC), - 0x1D762 => array(0x3BD), - 0x1D763 => array(0x3BE), - 0x1D764 => array(0x3BF), - 0x1D765 => array(0x3C0), - 0x1D766 => array(0x3C1), - 0x1D767 => array(0x3B8), - 0x1D768 => array(0x3C3), - 0x1D769 => array(0x3C4), - 0x1D76A => array(0x3C5), - 0x1D76B => array(0x3C6), - 0x1D76C => array(0x3C7), - 0x1D76D => array(0x3C8), - 0x1D76E => array(0x3C9), - 0x1D781 => array(0x3C3), - 0x1D790 => array(0x3B1), - 0x1D791 => array(0x3B2), - 0x1D792 => array(0x3B3), - 0x1D793 => array(0x3B4), - 0x1D794 => array(0x3B5), - 0x1D795 => array(0x3B6), - 0x1D796 => array(0x3B7), - 0x1D797 => array(0x3B8), - 0x1D798 => array(0x3B9), - 0x1D799 => array(0x3BA), - 0x1D79A => array(0x3BB), - 0x1D79B => array(0x3BC), - 0x1D79C => array(0x3BD), - 0x1D79D => array(0x3BE), - 0x1D79E => array(0x3BF), - 0x1D79F => array(0x3C0), - 0x1D7A0 => array(0x3C1), - 0x1D7A1 => array(0x3B8), - 0x1D7A2 => array(0x3C3), - 0x1D7A3 => array(0x3C4), - 0x1D7A4 => array(0x3C5), - 0x1D7A5 => array(0x3C6), - 0x1D7A6 => array(0x3C7), - 0x1D7A7 => array(0x3C8), - 0x1D7A8 => array(0x3C9), - 0x1D7BB => array(0x3C3), - 0x3F9 => array(0x3C3), - 0x1D2C => array(0x61), - 0x1D2D => array(0xE6), - 0x1D2E => array(0x62), - 0x1D30 => array(0x64), - 0x1D31 => array(0x65), - 0x1D32 => array(0x1DD), - 0x1D33 => array(0x67), - 0x1D34 => array(0x68), - 0x1D35 => array(0x69), - 0x1D36 => array(0x6A), - 0x1D37 => array(0x6B), - 0x1D38 => array(0x6C), - 0x1D39 => array(0x6D), - 0x1D3A => array(0x6E), - 0x1D3C => array(0x6F), - 0x1D3D => array(0x223), - 0x1D3E => array(0x70), - 0x1D3F => array(0x72), - 0x1D40 => array(0x74), - 0x1D41 => array(0x75), - 0x1D42 => array(0x77), - 0x213B => array(0x66, 0x61, 0x78), - 0x3250 => array(0x70, 0x74, 0x65), - 0x32CC => array(0x68, 0x67), - 0x32CE => array(0x65, 0x76), - 0x32CF => array(0x6C, 0x74, 0x64), - 0x337A => array(0x69, 0x75), - 0x33DE => array(0x76, 0x2215, 0x6D), - 0x33DF => array(0x61, 0x2215, 0x6D) - ); - - /** - * Normalization Combining Classes; Code Points not listed - * got Combining Class 0. - * - * @static - * @var array - * @access private - */ - private static $_np_norm_combcls = array( - 0x334 => 1, - 0x335 => 1, - 0x336 => 1, - 0x337 => 1, - 0x338 => 1, - 0x93C => 7, - 0x9BC => 7, - 0xA3C => 7, - 0xABC => 7, - 0xB3C => 7, - 0xCBC => 7, - 0x1037 => 7, - 0x3099 => 8, - 0x309A => 8, - 0x94D => 9, - 0x9CD => 9, - 0xA4D => 9, - 0xACD => 9, - 0xB4D => 9, - 0xBCD => 9, - 0xC4D => 9, - 0xCCD => 9, - 0xD4D => 9, - 0xDCA => 9, - 0xE3A => 9, - 0xF84 => 9, - 0x1039 => 9, - 0x1714 => 9, - 0x1734 => 9, - 0x17D2 => 9, - 0x5B0 => 10, - 0x5B1 => 11, - 0x5B2 => 12, - 0x5B3 => 13, - 0x5B4 => 14, - 0x5B5 => 15, - 0x5B6 => 16, - 0x5B7 => 17, - 0x5B8 => 18, - 0x5B9 => 19, - 0x5BB => 20, - 0x5Bc => 21, - 0x5BD => 22, - 0x5BF => 23, - 0x5C1 => 24, - 0x5C2 => 25, - 0xFB1E => 26, - 0x64B => 27, - 0x64C => 28, - 0x64D => 29, - 0x64E => 30, - 0x64F => 31, - 0x650 => 32, - 0x651 => 33, - 0x652 => 34, - 0x670 => 35, - 0x711 => 36, - 0xC55 => 84, - 0xC56 => 91, - 0xE38 => 103, - 0xE39 => 103, - 0xE48 => 107, - 0xE49 => 107, - 0xE4A => 107, - 0xE4B => 107, - 0xEB8 => 118, - 0xEB9 => 118, - 0xEC8 => 122, - 0xEC9 => 122, - 0xECA => 122, - 0xECB => 122, - 0xF71 => 129, - 0xF72 => 130, - 0xF7A => 130, - 0xF7B => 130, - 0xF7C => 130, - 0xF7D => 130, - 0xF80 => 130, - 0xF74 => 132, - 0x321 => 202, - 0x322 => 202, - 0x327 => 202, - 0x328 => 202, - 0x31B => 216, - 0xF39 => 216, - 0x1D165 => 216, - 0x1D166 => 216, - 0x1D16E => 216, - 0x1D16F => 216, - 0x1D170 => 216, - 0x1D171 => 216, - 0x1D172 => 216, - 0x302A => 218, - 0x316 => 220, - 0x317 => 220, - 0x318 => 220, - 0x319 => 220, - 0x31C => 220, - 0x31D => 220, - 0x31E => 220, - 0x31F => 220, - 0x320 => 220, - 0x323 => 220, - 0x324 => 220, - 0x325 => 220, - 0x326 => 220, - 0x329 => 220, - 0x32A => 220, - 0x32B => 220, - 0x32C => 220, - 0x32D => 220, - 0x32E => 220, - 0x32F => 220, - 0x330 => 220, - 0x331 => 220, - 0x332 => 220, - 0x333 => 220, - 0x339 => 220, - 0x33A => 220, - 0x33B => 220, - 0x33C => 220, - 0x347 => 220, - 0x348 => 220, - 0x349 => 220, - 0x34D => 220, - 0x34E => 220, - 0x353 => 220, - 0x354 => 220, - 0x355 => 220, - 0x356 => 220, - 0x591 => 220, - 0x596 => 220, - 0x59B => 220, - 0x5A3 => 220, - 0x5A4 => 220, - 0x5A5 => 220, - 0x5A6 => 220, - 0x5A7 => 220, - 0x5AA => 220, - 0x655 => 220, - 0x656 => 220, - 0x6E3 => 220, - 0x6EA => 220, - 0x6ED => 220, - 0x731 => 220, - 0x734 => 220, - 0x737 => 220, - 0x738 => 220, - 0x739 => 220, - 0x73B => 220, - 0x73C => 220, - 0x73E => 220, - 0x742 => 220, - 0x744 => 220, - 0x746 => 220, - 0x748 => 220, - 0x952 => 220, - 0xF18 => 220, - 0xF19 => 220, - 0xF35 => 220, - 0xF37 => 220, - 0xFC6 => 220, - 0x193B => 220, - 0x20E8 => 220, - 0x1D17B => 220, - 0x1D17C => 220, - 0x1D17D => 220, - 0x1D17E => 220, - 0x1D17F => 220, - 0x1D180 => 220, - 0x1D181 => 220, - 0x1D182 => 220, - 0x1D18A => 220, - 0x1D18B => 220, - 0x59A => 222, - 0x5AD => 222, - 0x1929 => 222, - 0x302D => 222, - 0x302E => 224, - 0x302F => 224, - 0x1D16D => 226, - 0x5AE => 228, - 0x18A9 => 228, - 0x302B => 228, - 0x300 => 230, - 0x301 => 230, - 0x302 => 230, - 0x303 => 230, - 0x304 => 230, - 0x305 => 230, - 0x306 => 230, - 0x307 => 230, - 0x308 => 230, - 0x309 => 230, - 0x30A => 230, - 0x30B => 230, - 0x30C => 230, - 0x30D => 230, - 0x30E => 230, - 0x30F => 230, - 0x310 => 230, - 0x311 => 230, - 0x312 => 230, - 0x313 => 230, - 0x314 => 230, - 0x33D => 230, - 0x33E => 230, - 0x33F => 230, - 0x340 => 230, - 0x341 => 230, - 0x342 => 230, - 0x343 => 230, - 0x344 => 230, - 0x346 => 230, - 0x34A => 230, - 0x34B => 230, - 0x34C => 230, - 0x350 => 230, - 0x351 => 230, - 0x352 => 230, - 0x357 => 230, - 0x363 => 230, - 0x364 => 230, - 0x365 => 230, - 0x366 => 230, - 0x367 => 230, - 0x368 => 230, - 0x369 => 230, - 0x36A => 230, - 0x36B => 230, - 0x36C => 230, - 0x36D => 230, - 0x36E => 230, - 0x36F => 230, - 0x483 => 230, - 0x484 => 230, - 0x485 => 230, - 0x486 => 230, - 0x592 => 230, - 0x593 => 230, - 0x594 => 230, - 0x595 => 230, - 0x597 => 230, - 0x598 => 230, - 0x599 => 230, - 0x59C => 230, - 0x59D => 230, - 0x59E => 230, - 0x59F => 230, - 0x5A0 => 230, - 0x5A1 => 230, - 0x5A8 => 230, - 0x5A9 => 230, - 0x5AB => 230, - 0x5AC => 230, - 0x5AF => 230, - 0x5C4 => 230, - 0x610 => 230, - 0x611 => 230, - 0x612 => 230, - 0x613 => 230, - 0x614 => 230, - 0x615 => 230, - 0x653 => 230, - 0x654 => 230, - 0x657 => 230, - 0x658 => 230, - 0x6D6 => 230, - 0x6D7 => 230, - 0x6D8 => 230, - 0x6D9 => 230, - 0x6DA => 230, - 0x6DB => 230, - 0x6DC => 230, - 0x6DF => 230, - 0x6E0 => 230, - 0x6E1 => 230, - 0x6E2 => 230, - 0x6E4 => 230, - 0x6E7 => 230, - 0x6E8 => 230, - 0x6EB => 230, - 0x6EC => 230, - 0x730 => 230, - 0x732 => 230, - 0x733 => 230, - 0x735 => 230, - 0x736 => 230, - 0x73A => 230, - 0x73D => 230, - 0x73F => 230, - 0x740 => 230, - 0x741 => 230, - 0x743 => 230, - 0x745 => 230, - 0x747 => 230, - 0x749 => 230, - 0x74A => 230, - 0x951 => 230, - 0x953 => 230, - 0x954 => 230, - 0xF82 => 230, - 0xF83 => 230, - 0xF86 => 230, - 0xF87 => 230, - 0x170D => 230, - 0x193A => 230, - 0x20D0 => 230, - 0x20D1 => 230, - 0x20D4 => 230, - 0x20D5 => 230, - 0x20D6 => 230, - 0x20D7 => 230, - 0x20DB => 230, - 0x20DC => 230, - 0x20E1 => 230, - 0x20E7 => 230, - 0x20E9 => 230, - 0xFE20 => 230, - 0xFE21 => 230, - 0xFE22 => 230, - 0xFE23 => 230, - 0x1D185 => 230, - 0x1D186 => 230, - 0x1D187 => 230, - 0x1D189 => 230, - 0x1D188 => 230, - 0x1D1AA => 230, - 0x1D1AB => 230, - 0x1D1AC => 230, - 0x1D1AD => 230, - 0x315 => 232, - 0x31A => 232, - 0x302C => 232, - 0x35F => 233, - 0x362 => 233, - 0x35D => 234, - 0x35E => 234, - 0x360 => 234, - 0x361 => 234, - 0x345 => 240 - ); - // }}} - - // {{{ properties - /** - * @var string - * @access private - */ - private $_punycode_prefix = 'xn--'; - - /** - * @access private - */ - private $_invalid_ucs = 0x80000000; - - /** - * @access private - */ - private $_max_ucs = 0x10FFFF; - - /** - * @var int - * @access private - */ - private $_base = 36; - - /** - * @var int - * @access private - */ - private $_tmin = 1; - - /** - * @var int - * @access private - */ - private $_tmax = 26; - - /** - * @var int - * @access private - */ - private $_skew = 38; - - /** - * @var int - * @access private - */ - private $_damp = 700; - - /** - * @var int - * @access private - */ - private $_initial_bias = 72; - - /** - * @var int - * @access private - */ - private $_initial_n = 0x80; - - /** - * @var int - * @access private - */ - private $_slast; - - /** - * @access private - */ - private $_sbase = 0xAC00; - - /** - * @access private - */ - private $_lbase = 0x1100; - - /** - * @access private - */ - private $_vbase = 0x1161; - - /** - * @access private - */ - private $_tbase = 0x11a7; - - /** - * @var int - * @access private - */ - private $_lcount = 19; - - /** - * @var int - * @access private - */ - private $_vcount = 21; - - /** - * @var int - * @access private - */ - private $_tcount = 28; - - /** - * vcount * tcount - * - * @var int - * @access private - */ - private $_ncount = 588; - - /** - * lcount * tcount * vcount - * - * @var int - * @access private - */ - private $_scount = 11172; - - /** - * Default encoding for encode()'s input and decode()'s output is UTF-8; - * Other possible encodings are ucs4_string and ucs4_array - * See {@link setParams()} for how to select these - * - * @var bool - * @access private - */ - private $_api_encoding = 'utf8'; - - /** - * Overlong UTF-8 encodings are forbidden - * - * @var bool - * @access private - */ - private $_allow_overlong = false; - - /** - * Behave strict or not - * - * @var bool - * @access private - */ - private $_strict_mode = false; - // }}} - - - // {{{ constructor - /** - * Constructor - * - * @param array $options - * @access public - * @see setParams() - */ - public function __construct($options = null) - { - $this->_slast = $this->_sbase + $this->_lcount * $this->_vcount * $this->_tcount; - - if (is_array($options)) { - $this->setParams($options); - } - } - // }}} - - - /** - * Sets a new option value. Available options and values: - * - * [utf8 - Use either UTF-8 or ISO-8859-1 as input (true for UTF-8, false - * otherwise); The output is always UTF-8] - * [overlong - Unicode does not allow unnecessarily long encodings of chars, - * to allow this, set this parameter to true, else to false; - * default is false.] - * [strict - true: strict mode, good for registration purposes - Causes errors - * on failures; false: loose mode, ideal for "wildlife" applications - * by silently ignoring errors and returning the original input instead] - * - * @param mixed $option Parameter to set (string: single parameter; array of Parameter => Value pairs) - * @param string $value Value to use (if parameter 1 is a string) - * @return boolean true on success, false otherwise - * @access public - */ - public function setParams($option, $value = false) - { - if (!is_array($option)) { - $option = array($option => $value); - } - - foreach ($option as $k => $v) { - switch ($k) { - case 'encoding': - switch ($v) { - case 'utf8': - case 'ucs4_string': - case 'ucs4_array': - $this->_api_encoding = $v; - break; - - default: - throw new Exception('Set Parameter: Unknown parameter '.$v.' for option '.$k); - } - - break; - - case 'overlong': - $this->_allow_overlong = ($v) ? true : false; - break; - - case 'strict': - $this->_strict_mode = ($v) ? true : false; - break; - - default: - return false; - } - } - - return true; - } - - /** - * Encode a given UTF-8 domain name. - * - * @param string $decoded Domain name (UTF-8 or UCS-4) - * [@param string $encoding Desired input encoding, see {@link set_parameter}] - * @return string Encoded Domain name (ACE string) - * @return mixed processed string - * @throws Exception - * @access public - */ - public function encode($decoded, $one_time_encoding = false) - { - // Forcing conversion of input to UCS4 array - // If one time encoding is given, use this, else the objects property - switch (($one_time_encoding) ? $one_time_encoding : $this->_api_encoding) { - case 'utf8': - $decoded = $this->_utf8_to_ucs4($decoded); - break; - case 'ucs4_string': - $decoded = $this->_ucs4_string_to_ucs4($decoded); - case 'ucs4_array': // No break; before this line. Catch case, but do nothing - break; - default: - throw new Exception('Unsupported input format'); - } - - // No input, no output, what else did you expect? - if (empty($decoded)) return ''; - - // Anchors for iteration - $last_begin = 0; - // Output string - $output = ''; - - foreach ($decoded as $k => $v) { - // Make sure to use just the plain dot - switch($v) { - case 0x3002: - case 0xFF0E: - case 0xFF61: - $decoded[$k] = 0x2E; - // It's right, no break here - // The codepoints above have to be converted to dots anyway - - // Stumbling across an anchoring character - case 0x2E: - case 0x2F: - case 0x3A: - case 0x3F: - case 0x40: - // Neither email addresses nor URLs allowed in strict mode - if ($this->_strict_mode) { - throw new Exception('Neither email addresses nor URLs are allowed in strict mode.'); - } else { - // Skip first char - if ($k) { - $encoded = ''; - $encoded = $this->_encode(array_slice($decoded, $last_begin, (($k)-$last_begin))); - if ($encoded) { - $output .= $encoded; - } else { - $output .= $this->_ucs4_to_utf8(array_slice($decoded, $last_begin, (($k)-$last_begin))); - } - $output .= chr($decoded[$k]); - } - $last_begin = $k + 1; - } - } - } - // Catch the rest of the string - if ($last_begin) { - $inp_len = sizeof($decoded); - $encoded = ''; - $encoded = $this->_encode(array_slice($decoded, $last_begin, (($inp_len)-$last_begin))); - if ($encoded) { - $output .= $encoded; - } else { - $output .= $this->_ucs4_to_utf8(array_slice($decoded, $last_begin, (($inp_len)-$last_begin))); - } - return $output; - } else { - if ($output = $this->_encode($decoded)) { - return $output; - } else { - return $this->_ucs4_to_utf8($decoded); - } - } - } - - /** - * Decode a given ACE domain name. - * - * @param string $encoded Domain name (ACE string) - * @param string $encoding Desired output encoding, see {@link set_parameter} - * @return string Decoded Domain name (UTF-8 or UCS-4) - * @throws Exception - * @access public - */ - public function decode($input, $one_time_encoding = false) - { - // Optionally set - if ($one_time_encoding) { - switch ($one_time_encoding) { - case 'utf8': - case 'ucs4_string': - case 'ucs4_array': - break; - default: - throw new Exception('Unknown encoding '.$one_time_encoding); - return false; - } - } - // Make sure to drop any newline characters around - $input = trim($input); - - // Negotiate input and try to determine, wether it is a plain string, - // an email address or something like a complete URL - if (strpos($input, '@')) { // Maybe it is an email address - // No no in strict mode - if ($this->_strict_mode) { - throw new Exception('Only simple domain name parts can be handled in strict mode'); - } - list($email_pref, $input) = explode('@', $input, 2); - $arr = explode('.', $input); - foreach ($arr as $k => $v) { - $conv = $this->_decode($v); - if ($conv) $arr[$k] = $conv; - } - $return = $email_pref . '@' . join('.', $arr); - } elseif (preg_match('![:\./]!', $input)) { // Or a complete domain name (with or without paths / parameters) - // No no in strict mode - if ($this->_strict_mode) { - throw new Exception('Only simple domain name parts can be handled in strict mode'); - } - $parsed = parse_url($input); - if (isset($parsed['host'])) { - $arr = explode('.', $parsed['host']); - foreach ($arr as $k => $v) { - $conv = $this->_decode($v); - if ($conv) $arr[$k] = $conv; - } - $parsed['host'] = join('.', $arr); - if (isset($parsed['scheme'])) { - $parsed['scheme'] .= (strtolower($parsed['scheme']) == 'mailto') ? ':' : '://'; - } - $return = join('', $parsed); - } else { // parse_url seems to have failed, try without it - $arr = explode('.', $input); - foreach ($arr as $k => $v) { - $conv = $this->_decode($v); - if ($conv) $arr[$k] = $conv; - } - $return = join('.', $arr); - } - } else { // Otherwise we consider it being a pure domain name string - $return = $this->_decode($input); - } - // The output is UTF-8 by default, other output formats need conversion here - // If one time encoding is given, use this, else the objects property - switch (($one_time_encoding) ? $one_time_encoding : $this->_api_encoding) { - case 'utf8': - return $return; - break; - case 'ucs4_string': - return $this->_ucs4_to_ucs4_string($this->_utf8_to_ucs4($return)); - break; - case 'ucs4_array': - return $this->_utf8_to_ucs4($return); - break; - default: - throw new Exception('Unsupported output format'); - } - } - - - // {{{ private - /** - * The actual encoding algorithm. - * - * @return string - * @throws Exception - * @access private - */ - private function _encode($decoded) - { - // We cannot encode a domain name containing the Punycode prefix - $extract = strlen($this->_punycode_prefix); - $check_pref = $this->_utf8_to_ucs4($this->_punycode_prefix); - $check_deco = array_slice($decoded, 0, $extract); - - if ($check_pref == $check_deco) { - throw new Exception('This is already a punycode string'); - } - // We will not try to encode strings consisting of basic code points only - $encodable = false; - foreach ($decoded as $k => $v) { - if ($v > 0x7a) { - $encodable = true; - break; - } - } - if (!$encodable) { - if ($this->_strict_mode) { - throw new Exception('The given string does not contain encodable chars'); - } else { - return false; - } - } - - // Do NAMEPREP - try { - $decoded = $this->_nameprep($decoded); - } catch (Exception $e) { - // hmm, serious - rethrow - throw $e; - } - - $deco_len = count($decoded); - - // Empty array - if (!$deco_len) { - return false; - } - - // How many chars have been consumed - $codecount = 0; - - // Start with the prefix; copy it to output - $encoded = $this->_punycode_prefix; - - $encoded = ''; - // Copy all basic code points to output - for ($i = 0; $i < $deco_len; ++$i) { - $test = $decoded[$i]; - // Will match [0-9a-zA-Z-] - if ((0x2F < $test && $test < 0x40) - || (0x40 < $test && $test < 0x5B) - || (0x60 < $test && $test <= 0x7B) - || (0x2D == $test)) { - $encoded .= chr($decoded[$i]); - $codecount++; - } - } - - // All codepoints were basic ones - if ($codecount == $deco_len) { - return $encoded; - } - - // Start with the prefix; copy it to output - $encoded = $this->_punycode_prefix . $encoded; - - // If we have basic code points in output, add an hyphen to the end - if ($codecount) { - $encoded .= '-'; - } - - // Now find and encode all non-basic code points - $is_first = true; - $cur_code = $this->_initial_n; - $bias = $this->_initial_bias; - $delta = 0; - - while ($codecount < $deco_len) { - // Find the smallest code point >= the current code point and - // remember the last ouccrence of it in the input - for ($i = 0, $next_code = $this->_max_ucs; $i < $deco_len; $i++) { - if ($decoded[$i] >= $cur_code && $decoded[$i] <= $next_code) { - $next_code = $decoded[$i]; - } - } - - $delta += ($next_code - $cur_code) * ($codecount + 1); - $cur_code = $next_code; - - // Scan input again and encode all characters whose code point is $cur_code - for ($i = 0; $i < $deco_len; $i++) { - if ($decoded[$i] < $cur_code) { - $delta++; - } else if ($decoded[$i] == $cur_code) { - for ($q = $delta, $k = $this->_base; 1; $k += $this->_base) { - $t = ($k <= $bias)? - $this->_tmin : - (($k >= $bias + $this->_tmax)? $this->_tmax : $k - $bias); - - if ($q < $t) { - break; - } - - $encoded .= $this->_encodeDigit(ceil($t + (($q - $t) % ($this->_base - $t)))); - $q = ($q - $t) / ($this->_base - $t); - } - - $encoded .= $this->_encodeDigit($q); - $bias = $this->_adapt($delta, $codecount + 1, $is_first); - $codecount++; - $delta = 0; - $is_first = false; - } - } - - $delta++; - $cur_code++; - } - - return $encoded; - } - - /** - * The actual decoding algorithm. - * - * @return string - * @throws Exception - * @access private - */ - private function _decode($encoded) - { - // We do need to find the Punycode prefix - if (!preg_match('!^' . preg_quote($this->_punycode_prefix, '!') . '!', $encoded)) { - return false; - } - - $encode_test = preg_replace('!^' . preg_quote($this->_punycode_prefix, '!') . '!', '', $encoded); - - // If nothing left after removing the prefix, it is hopeless - if (!$encode_test) { - return false; - } - - // Find last occurence of the delimiter - $delim_pos = strrpos($encoded, '-'); - - if ($delim_pos > strlen($this->_punycode_prefix)) { - for ($k = strlen($this->_punycode_prefix); $k < $delim_pos; ++$k) { - $decoded[] = ord($encoded{$k}); - } - } else { - $decoded = array(); - } - - $deco_len = count($decoded); - $enco_len = strlen($encoded); - - // Wandering through the strings; init - $is_first = true; - $bias = $this->_initial_bias; - $idx = 0; - $char = $this->_initial_n; - - for ($enco_idx = ($delim_pos)? ($delim_pos + 1) : 0; $enco_idx < $enco_len; ++$deco_len) { - for ($old_idx = $idx, $w = 1, $k = $this->_base; 1 ; $k += $this->_base) { - $digit = $this->_decodeDigit($encoded{$enco_idx++}); - $idx += $digit * $w; - - $t = ($k <= $bias) ? - $this->_tmin : - (($k >= $bias + $this->_tmax)? $this->_tmax : ($k - $bias)); - - if ($digit < $t) { - break; - } - - $w = (int)($w * ($this->_base - $t)); - } - - $bias = $this->_adapt($idx - $old_idx, $deco_len + 1, $is_first); - $is_first = false; - $char += (int) ($idx / ($deco_len + 1)); - $idx %= ($deco_len + 1); - - if ($deco_len > 0) { - // Make room for the decoded char - for ($i = $deco_len; $i > $idx; $i--) { - $decoded[$i] = $decoded[($i - 1)]; - } - } - - $decoded[$idx++] = $char; - } - - try { - return $this->_ucs4_to_utf8($decoded); - } catch (Exception $e) { - // rethrow - throw $e; - } - } - - /** - * Adapt the bias according to the current code point and position. - * - * @access private - */ - private function _adapt($delta, $npoints, $is_first) - { - $delta = (int) ($is_first ? ($delta / $this->_damp) : ($delta / 2)); - $delta += (int) ($delta / $npoints); - - for ($k = 0; $delta > (($this->_base - $this->_tmin) * $this->_tmax) / 2; $k += $this->_base) { - $delta = (int) ($delta / ($this->_base - $this->_tmin)); - } - - return (int) ($k + ($this->_base - $this->_tmin + 1) * $delta / ($delta + $this->_skew)); - } - - /** - * Encoding a certain digit. - * - * @access private - */ - private function _encodeDigit($d) - { - return chr($d + 22 + 75 * ($d < 26)); - } - - /** - * Decode a certain digit. - * - * @access private - */ - private function _decodeDigit($cp) - { - $cp = ord($cp); - return ($cp - 48 < 10)? $cp - 22 : (($cp - 65 < 26)? $cp - 65 : (($cp - 97 < 26)? $cp - 97 : $this->_base)); - } - - /** - * Do Nameprep according to RFC3491 and RFC3454. - * - * @param array $input Unicode Characters - * @return string Unicode Characters, Nameprep'd - * @throws Exception - * @access private - */ - private function _nameprep($input) - { - $output = array(); - - // Walking through the input array, performing the required steps on each of - // the input chars and putting the result into the output array - // While mapping required chars we apply the cannonical ordering - - foreach ($input as $v) { - // Map to nothing == skip that code point - if (in_array($v, self::$_np_map_nothing)) { - continue; - } - - // Try to find prohibited input - if (in_array($v, self::$_np_prohibit) || in_array($v, self::$_general_prohibited)) { - throw new Exception('NAMEPREP: Prohibited input U+' . sprintf('%08X', $v)); - } - - foreach (self::$_np_prohibit_ranges as $range) { - if ($range[0] <= $v && $v <= $range[1]) { - throw new Exception('NAMEPREP: Prohibited input U+' . sprintf('%08X', $v)); - } - } - - // Hangul syllable decomposition - if (0xAC00 <= $v && $v <= 0xD7AF) { - foreach ($this->_hangulDecompose($v) as $out) { - $output[] = $out; - } - } else if (isset(self::$_np_replacemaps[$v])) { // There's a decomposition mapping for that code point - foreach ($this->_applyCannonicalOrdering(self::$_np_replacemaps[$v]) as $out) { - $output[] = $out; - } - } else { - $output[] = $v; - } - } - - // Combine code points - - $last_class = 0; - $last_starter = 0; - $out_len = count($output); - - for ($i = 0; $i < $out_len; ++$i) { - $class = $this->_getCombiningClass($output[$i]); - - if ((!$last_class || $last_class != $class) && $class) { - // Try to match - $seq_len = $i - $last_starter; - $out = $this->_combine(array_slice($output, $last_starter, $seq_len)); - - // On match: Replace the last starter with the composed character and remove - // the now redundant non-starter(s) - if ($out) { - $output[$last_starter] = $out; - - if (count($out) != $seq_len) { - for ($j = $i + 1; $j < $out_len; ++$j) { - $output[$j - 1] = $output[$j]; - } - - unset($output[$out_len]); - } - - // Rewind the for loop by one, since there can be more possible compositions - $i--; - $out_len--; - $last_class = ($i == $last_starter)? 0 : $this->_getCombiningClass($output[$i - 1]); - - continue; - } - } - - // The current class is 0 - if (!$class) { - $last_starter = $i; - } - - $last_class = $class; - } - - return $output; - } - - /** - * Decomposes a Hangul syllable - * (see http://www.unicode.org/unicode/reports/tr15/#Hangul). - * - * @param integer $char 32bit UCS4 code point - * @return array Either Hangul Syllable decomposed or original 32bit - * value as one value array - * @access private - */ - private function _hangulDecompose($char) - { - $sindex = $char - $this->_sbase; - - if ($sindex < 0 || $sindex >= $this->_scount) { - return array($char); - } - - $result = array(); - $T = $this->_tbase + $sindex % $this->_tcount; - $result[] = (int)($this->_lbase + $sindex / $this->_ncount); - $result[] = (int)($this->_vbase + ($sindex % $this->_ncount) / $this->_tcount); - - if ($T != $this->_tbase) { - $result[] = $T; - } - - return $result; - } - - /** - * Ccomposes a Hangul syllable - * (see http://www.unicode.org/unicode/reports/tr15/#Hangul). - * - * @param array $input Decomposed UCS4 sequence - * @return array UCS4 sequence with syllables composed - * @access private - */ - private function _hangulCompose($input) - { - $inp_len = count($input); - - if (!$inp_len) { - return array(); - } - - $result = array(); - $last = $input[0]; - $result[] = $last; // copy first char from input to output - - for ($i = 1; $i < $inp_len; ++$i) { - $char = $input[$i]; - - // Find out, wether two current characters from L and V - $lindex = $last - $this->_lbase; - - if (0 <= $lindex && $lindex < $this->_lcount) { - $vindex = $char - $this->_vbase; - - if (0 <= $vindex && $vindex < $this->_vcount) { - // create syllable of form LV - $last = ($this->_sbase + ($lindex * $this->_vcount + $vindex) * $this->_tcount); - $out_off = count($result) - 1; - $result[$out_off] = $last; // reset last - - // discard char - continue; - } - } - - // Find out, wether two current characters are LV and T - $sindex = $last - $this->_sbase; - - if (0 <= $sindex && $sindex < $this->_scount && ($sindex % $this->_tcount) == 0) { - $tindex = $char - $this->_tbase; - - if (0 <= $tindex && $tindex <= $this->_tcount) { - // create syllable of form LVT - $last += $tindex; - $out_off = count($result) - 1; - $result[$out_off] = $last; // reset last - - // discard char - continue; - } - } - - // if neither case was true, just add the character - $last = $char; - $result[] = $char; - } - - return $result; - } - - /** - * Returns the combining class of a certain wide char. - * - * @param integer $char Wide char to check (32bit integer) - * @return integer Combining class if found, else 0 - * @access private - */ - private function _getCombiningClass($char) - { - return isset(self::$_np_norm_combcls[$char])? self::$_np_norm_combcls[$char] : 0; - } - - /** - * Apllies the cannonical ordering of a decomposed UCS4 sequence. - * - * @param array $input Decomposed UCS4 sequence - * @return array Ordered USC4 sequence - * @access private - */ - private function _applyCannonicalOrdering($input) - { - $swap = true; - $size = count($input); - - while ($swap) { - $swap = false; - $last = $this->_getCombiningClass($input[0]); - - for ($i = 0; $i < $size - 1; ++$i) { - $next = $this->_getCombiningClass($input[$i + 1]); - - if ($next != 0 && $last > $next) { - // Move item leftward until it fits - for ($j = $i + 1; $j > 0; --$j) { - if ($this->_getCombiningClass($input[$j - 1]) <= $next) { - break; - } - - $t = $input[$j]; - $input[$j] = $input[$j - 1]; - $input[$j - 1] = $t; - $swap = 1; - } - - // Reentering the loop looking at the old character again - $next = $last; - } - - $last = $next; - } - } - - return $input; - } - - /** - * Do composition of a sequence of starter and non-starter. - * - * @param array $input UCS4 Decomposed sequence - * @return array Ordered USC4 sequence - * @access private - */ - private function _combine($input) - { - $inp_len = count($input); - - // Is it a Hangul syllable? - if (1 != $inp_len) { - $hangul = $this->_hangulCompose($input); - - // This place is probably wrong - if (count($hangul) != $inp_len) { - return $hangul; - } - } - - foreach (self::$_np_replacemaps as $np_src => $np_target) { - if ($np_target[0] != $input[0]) { - continue; - } - - if (count($np_target) != $inp_len) { - continue; - } - - $hit = false; - - foreach ($input as $k2 => $v2) { - if ($v2 == $np_target[$k2]) { - $hit = true; - } else { - $hit = false; - break; - } - } - - if ($hit) { - return $np_src; - } - } - - return false; - } - - /** - * This converts an UTF-8 encoded string to its UCS-4 (array) representation - * By talking about UCS-4 we mean arrays of 32bit integers representing - * each of the "chars". This is due to PHP not being able to handle strings with - * bit depth different from 8. This applies to the reverse method _ucs4_to_utf8(), too. - * The following UTF-8 encodings are supported: - * - * bytes bits representation - * 1 7 0xxxxxxx - * 2 11 110xxxxx 10xxxxxx - * 3 16 1110xxxx 10xxxxxx 10xxxxxx - * 4 21 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - * 5 26 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - * 6 31 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - * - * Each x represents a bit that can be used to store character data. - * - * @access private - */ - private function _utf8_to_ucs4($input) - { - $output = array(); - $out_len = 0; - $inp_len = strlen($input); - $mode = 'next'; - $test = 'none'; - for ($k = 0; $k < $inp_len; ++$k) { - $v = ord($input{$k}); // Extract byte from input string - - if ($v < 128) { // We found an ASCII char - put into stirng as is - $output[$out_len] = $v; - ++$out_len; - if ('add' == $mode) { - throw new Exception('Conversion from UTF-8 to UCS-4 failed: malformed input at byte '.$k); - return false; - } - continue; - } - if ('next' == $mode) { // Try to find the next start byte; determine the width of the Unicode char - $start_byte = $v; - $mode = 'add'; - $test = 'range'; - if ($v >> 5 == 6) { // &110xxxxx 10xxxxx - $next_byte = 0; // Tells, how many times subsequent bitmasks must rotate 6bits to the left - $v = ($v - 192) << 6; - } elseif ($v >> 4 == 14) { // &1110xxxx 10xxxxxx 10xxxxxx - $next_byte = 1; - $v = ($v - 224) << 12; - } elseif ($v >> 3 == 30) { // &11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - $next_byte = 2; - $v = ($v - 240) << 18; - } elseif ($v >> 2 == 62) { // &111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - $next_byte = 3; - $v = ($v - 248) << 24; - } elseif ($v >> 1 == 126) { // &1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx - $next_byte = 4; - $v = ($v - 252) << 30; - } else { - throw new Exception('This might be UTF-8, but I don\'t understand it at byte '.$k); - return false; - } - if ('add' == $mode) { - $output[$out_len] = (int) $v; - ++$out_len; - continue; - } - } - if ('add' == $mode) { - if (!$this->_allow_overlong && $test == 'range') { - $test = 'none'; - if (($v < 0xA0 && $start_byte == 0xE0) || ($v < 0x90 && $start_byte == 0xF0) || ($v > 0x8F && $start_byte == 0xF4)) { - throw new Exception('Bogus UTF-8 character detected (out of legal range) at byte '.$k); - return false; - } - } - if ($v >> 6 == 2) { // Bit mask must be 10xxxxxx - $v = ($v - 128) << ($next_byte * 6); - $output[($out_len - 1)] += $v; - --$next_byte; - } else { - throw new Exception('Conversion from UTF-8 to UCS-4 failed: malformed input at byte '.$k); - return false; - } - if ($next_byte < 0) { - $mode = 'next'; - } - } - } // for - return $output; - } - - /** - * Convert UCS-4 array into UTF-8 string. - * - * @throws Exception - * @access private - */ - private function _ucs4_to_utf8($input) - { - $output = ''; - - foreach ($input as $v) { - // $v = ord($v); - - if ($v < 128) { - // 7bit are transferred literally - $output .= chr($v); - } else if ($v < 1 << 11) { - // 2 bytes - $output .= chr(192 + ($v >> 6)) - . chr(128 + ($v & 63)); - } else if ($v < 1 << 16) { - // 3 bytes - $output .= chr(224 + ($v >> 12)) - . chr(128 + (($v >> 6) & 63)) - . chr(128 + ($v & 63)); - } else if ($v < 1 << 21) { - // 4 bytes - $output .= chr(240 + ($v >> 18)) - . chr(128 + (($v >> 12) & 63)) - . chr(128 + (($v >> 6) & 63)) - . chr(128 + ($v & 63)); - } else if ($v < 1 << 26) { - // 5 bytes - $output .= chr(248 + ($v >> 24)) - . chr(128 + (($v >> 18) & 63)) - . chr(128 + (($v >> 12) & 63)) - . chr(128 + (($v >> 6) & 63)) - . chr(128 + ($v & 63)); - } else if ($v < 1 << 31) { - // 6 bytes - $output .= chr(252 + ($v >> 30)) - . chr(128 + (($v >> 24) & 63)) - . chr(128 + (($v >> 18) & 63)) - . chr(128 + (($v >> 12) & 63)) - . chr(128 + (($v >> 6) & 63)) - . chr(128 + ($v & 63)); - } else { - throw new Exception('Conversion from UCS-4 to UTF-8 failed: malformed input at byte ' . $k); - } - } - - return $output; - } - - /** - * Convert UCS-4 array into UCS-4 string - * - * @throws Exception - * @access private - */ - private function _ucs4_to_ucs4_string($input) - { - $output = ''; - // Take array values and split output to 4 bytes per value - // The bit mask is 255, which reads &11111111 - foreach ($input as $v) { - $output .= ($v & (255 << 24) >> 24) . ($v & (255 << 16) >> 16) . ($v & (255 << 8) >> 8) . ($v & 255); - } - return $output; - } - - /** - * Convert UCS-4 strin into UCS-4 garray - * - * @throws Exception - * @access private - */ - private function _ucs4_string_to_ucs4($input) - { - $output = array(); - - $inp_len = strlen($input); - // Input length must be dividable by 4 - if ($inp_len % 4) { - throw new Exception('Input UCS4 string is broken'); - return false; - } - - // Empty input - return empty output - if (!$inp_len) return $output; - - for ($i = 0, $out_len = -1; $i < $inp_len; ++$i) { - // Increment output position every 4 input bytes - if (!$i % 4) { - $out_len++; - $output[$out_len] = 0; - } - $output[$out_len] += ord($input{$i}) << (8 * (3 - ($i % 4) ) ); - } - return $output; - } - - /** - * Echo hex representation of UCS4 sequence. - * - * @param array $input UCS4 sequence - * @param boolean $include_bit Include bitmask in output - * @return void - * @static - * @access private - */ - private static function _showHex($input, $include_bit = false) - { - foreach ($input as $k => $v) { - echo '[', $k, '] => ', sprintf('%X', $v); - - if ($include_bit) { - echo ' (', Net_IDNA::_showBitmask($v), ')'; - } - - echo "\n"; - } - } - - /** - * Gives you a bit representation of given Byte (8 bits), Word (16 bits) or DWord (32 bits) - * Output width is automagically determined - * - * @static - * @access private - */ - private static function _showBitmask($octet) - { - if ($octet >= (1 << 16)) { - $w = 31; - } else if ($octet >= (1 << 8)) { - $w = 15; - } else { - $w = 7; - } - - $return = ''; - - for ($i = $w; $i > -1; $i--) { - $return .= ($octet & (1 << $i))? 1 : '0'; - } - - return $return; - } - // }}}} -} - -?> diff --git a/gulliver/thirdparty/pear/Net/IPv4.php b/gulliver/thirdparty/pear/Net/IPv4.php deleted file mode 100644 index e9195715d..000000000 --- a/gulliver/thirdparty/pear/Net/IPv4.php +++ /dev/null @@ -1,458 +0,0 @@ - -* @author Marco Kaiser -* @author Florian Anderiasch -* @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 -* @author Marco Kaiser -* @author Florian Anderiasch -* @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 - */ -?> diff --git a/gulliver/thirdparty/pear/Net/IPv6.php b/gulliver/thirdparty/pear/Net/IPv6.php deleted file mode 100644 index 296abe668..000000000 --- a/gulliver/thirdparty/pear/Net/IPv6.php +++ /dev/null @@ -1,218 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $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 -* @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; $i0) { - $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; - } - } - // }}} -} -?> diff --git a/gulliver/thirdparty/pear/Net/JSON.php b/gulliver/thirdparty/pear/Net/JSON.php deleted file mode 100644 index 71dcdea5d..000000000 --- a/gulliver/thirdparty/pear/Net/JSON.php +++ /dev/null @@ -1,806 +0,0 @@ - - * @author Matt Knapp - * @author Brett Stimmerman - * @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: - * - * - * // 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); - * - */ -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) - { - - } - } - -} - -?> diff --git a/gulliver/thirdparty/pear/Net/LDAP.php b/gulliver/thirdparty/pear/Net/LDAP.php deleted file mode 100644 index 7a8f43f21..000000000 --- a/gulliver/thirdparty/pear/Net/LDAP.php +++ /dev/null @@ -1,1065 +0,0 @@ - '', - 'host' => 'localhost', - 'password' => '', - 'tls' => false, - 'base' => '', - 'port' => 389, - 'version' => 3, - 'options' => array(), - 'filter' => '(objectClass=*)', - 'scope' => 'sub'); - - /** - * LDAP resource link. - * - * @access private - * @var resource - */ - var $_link; - - /** - * Net_LDAP Release Version - * - * @access private - * @var string - */ - var $_version = "0.6.6"; - - /** - * Net_LDAP_Schema object - * - * @access private - * @var object Net_LDAP_Schema - */ - var $_schema = null; - - /** - * Cache for attribute encoding checks - * - * @access private - * @var array Hash with attribute names as key and boolean value - * to determine whether they should be utf8 encoded or not. - */ - var $_schemaAttrs = array(); - - /** - * Net_LDAP constructor - * - * Sets the config array - * - * @access protected - * @param array Configuration array - * @return void - * @see $_config - */ - function Net_LDAP($_config = array()) - { - $this->PEAR('Net_LDAP_Error'); - - foreach ($_config as $k => $v) { - $this->_config[$k] = $v; - } - } - - /** - * Creates the initial ldap-object - * - * Static function that returns either an error object or the new Net_LDAP object. - * Something like a factory. Takes a config array with the needed parameters. - * - * @access public - * @param array Configuration array - * @return mixed object Net_LDAP_Error or Net_LDAP - * @see $_config - */ - function &connect($config = array()) - { - if (!function_exists('ldap_connect')){ - return Net_LDAP::raiseError("It seems that you do not have the ldap-extension installed. Please install it before using this package."); - } - @$obj =& new Net_LDAP($config); - $err = $obj->bind(); - - if (Net_LDAP::isError($err)) { - return $err; - } - return $obj; - } - - /** - * Bind to the ldap-server - * - * The function may be used if you do not create the object using Net_LDAP::connect. - * - * @access public - * @param array Configuration array - * @return mixed Net_LDAP_Error or true - * @see $_config - */ - function bind($config = array()) - { - foreach ($config as $k => $v) { - $this->_config[$k] = $v; - } - - if ($this->_config['host']) { - $this->_link = @ldap_connect($this->_config['host'], $this->_config['port']); - } else { - return $this->raiseError("Host not defined in config. {$this->_config['host']}"); - } - - if (!$this->_link) { - // there is no good errorcode for this one! I chose 52. - return $this->raiseError("Could not connect to server. ldap_connect failed.", 52); - } - // You must set the version and start tls BEFORE binding! - - if ($this->_config['version'] != 2 && Net_LDAP::isError($msg = $this->setLDAPVersion())) { - return $msg; - } - - if ($this->_config['tls'] && Net_LDAP::isError($msg = $this->startTLS())) { - return $msg; - } - - if (isset($this->_config['options']) && - is_array($this->_config['options']) && - count($this->_config['options'])) - { - foreach ($this->_config['options'] as $opt => $val) { - $err = $this->setOption($opt, $val); - if (Net_LDAP::isError($err)) { - return $err; - } - } - } - - if (isset($this->_config['dn']) && isset($this->_config['password'])) { - $bind = @ldap_bind($this->_link, $this->_config['dn'], $this->_config['password']); - } else { - $bind = @ldap_bind($this->_link); - } - - if (!$bind) { - return $this->raiseError("Bind failed " . @ldap_error($this->_link), @ldap_errno($this->_link)); - } - - return true; - } - - /** - * ReBind to the ldap-server using another dn and password - * - * The function may be used if you do not create the object using Net_LDAP::connect. - * - * @access public - * @param string $dn - the DN to bind as. - * string $password - the bassword to use. - * @return mixed Net_LDAP_Error or true - * @see $_config - */ - - function reBind ($dn = null, $password = null) - { - - if ($dn && $password ) { - $bind = @ldap_bind($this->_link, $dn, $password); - } else { - $bind = @ldap_bind($this->_link); - } - - if (!$bind) { - return $this->raiseError("Bind failed " . @ldap_error($this->_link), @ldap_errno($this->_link)); - } - return true; - } - - /** - * Starts an encrypted session - * - * @access public - * @return mixed True or Net_LDAP_Error - */ - function startTLS() - { - if (!@ldap_start_tls($this->_link)) { - return $this->raiseError("TLS not started. Error:" . @ldap_error($this->_link), @ldap_errno($this->_link)); - } - return true; - } - - /** - * alias function of startTLS() for perl-ldap interface - * - * @see startTLS() - */ - function start_tls() - { - $args = func_get_args(); - return call_user_func_array(array($this, 'startTLS' ), $args); - } - - /** - * Close LDAP connection. - * - * Closes the connection. Use this when the session is over. - * - * @return void - */ - function done() - { - $this->_Net_LDAP(); - } - - /** - * Destructor - * - * @access private - */ - function _Net_LDAP() - { - @ldap_close($this->_link); - } - - /** - * Add a new entryobject to a directory. - * - * Use add to add a new Net_LDAP_Entry object to the directory. - * - * @param object Net_LDAP_Entry - * @return mixed Net_LDAP_Error or true - */ - function add($entry) - { - if (@ldap_add($this->_link, $entry->dn(), $entry->attributes())) { - return true; - } else { - return $this->raiseError("Could not add entry " . $entry->dn() . " " . @ldap_error($this->_link), - @ldap_errno($this->_link)); - } - } - - /** - * Delete an entry from the directory - * - * The object may either be a string representing the dn or a Net_LDAP_Entry object. - * The param array may contain a boolean value named recursive. When set, all subentries - * of the Entry will be deleted as well - * - * @access public - * @param mixed string or Net_LDAP_Entry - * @param array - * @return mixed Net_LDAP_Error or true - */ - function delete($dn, $param = array()) - { - if (is_object($dn) && strtolower(get_class($dn)) == 'net_ldap_entry') { - $dn = $dn->dn(); - } else { - if (!is_string($dn)) { - // this is what the server would say: invalid_dn_syntax. - return $this->raiseError("$dn not a string nor an entryobject!", 34); - } - } - - if ($param['recursive'] ) { - $searchresult = @ldap_list($this->_link, $dn, '(objectClass=*)', array()); - - if ($searchresult) { - $entries = @ldap_get_entries($this->_link, $searchresult); - - for ($i=0; $i<$entries['count']; $i++) { - $result = $this->delete($entries[$i]['dn'], array('recursive' => true)); - if (!$result) { - $errno = @ldap_errno($this->_link); - return $this->raiseMessage ("Net_LDAP::delete: " . $this->errorMessage($errno), $errno); - } - if(PEAR::isError($result)){ - return $result; - } - } - } - } - if (!@ldap_delete($this->_link, $dn)) { - $error = ldap_errno($this->_link ); - if ($error == 66) { - /* entry has subentries */ - return $this->raiseError('Net_LDAP::delete: Cound not delete entry ' . $dn . - ' because of subentries. Use the recursive param to delete them.'); - } else { - return $this->raiseError("Net_LDAP::delete: Could not delete entry " . $dn ." because: ". - $this->errorMessage($error), $error); - } - } - return true; - } - - /** - * Modify an ldapentry - * - * This is taken from the perlpod of net::ldap, and explains things quite nicely. - * modify ( DN, OPTIONS ) - * Modify the contents of DN on the server. DN May be a - * string or a Net::LDAP::Entry object. - * - * dn This option is here for compatibility only, and - * may be removed in future. Previous releases did - * not take the DN argument which replaces this - * option. - * - * add The add option should be a reference to a HASH. - * The values of the HASH are the attributes to add, - * and the values may be a string or a reference to a - * list of values. - * - * delete - * A reference to an ARRAY of attributes to delete. - * TODO: This does not support deleting one or two values yet - use - * replace. - * - * replace - * The option takes a argument in the same - * form as add, but will cause any existing - * attributes with the same name to be replaced. If - * the value for any attribute in the årray is a ref­ - * erence to an empty string the all instances of the - * attribute will be deleted. - * - * changes - * This is an alternative to add, delete and replace - * where the whole operation can be given in a single - * argument. The argument should be a array - * - * Values in the ARRAY are used in pairs, the first - * is the operation add, delete or replace and the - * second is a reference to an ARRAY of attribute - * values. - * - * The attribute value list is also used in pairs. - * The first value in each pair is the attribute name - * and the second is a reference to a list of values. - * - * Example: - * $ldap->modify ( $dn, array (changes => array( - * 'delete' => array('faxNumber' => ''), - * 'add' => array('sn' => 'Barr'), - * 'replace' => array(email => 'tarjei@nu.no')))); - * - * @access public - * @param string - * @param array - * @return mixed Net_LDAP_Error or true - */ - function modify($dn , $params = array()) - { - if (is_object($dn)) { - $dn = $dn->dn(); - } - // since $params['dn'] is not used in net::ldap now: - if (isset($params['dn'])) { - return $this->raiseError("This feature will not be implemented!"); - } - // new code from rafael at krysciak dot de - if(array_key_exists('changes', $params)) { - $_params = $params; - } else { - $_params['changes'] = $params; - } - if (is_array($_params['changes'])) { - foreach($_params['changes'] AS $option => $atrr) { - switch($option) { - case 'add': - $command = $dn_exists ? 'ldap_mod_add':'ldap_add'; - break; - case 'replace': - $command = 'ldap_mod_replace'; - break; - case 'delete': - $command = 'ldap_mod_del'; - // to delete an attribute with a specific value you - // need a hash array('attr_name' => array('attr_value_1', ... ,'attr_value_n')) - // the hash array('attr_name' => 'attr_value') will be converted - // automatically to array('attr_name' => array('attr_value')) - foreach($atrr AS $atrr_field => $atrr_value) { - if(!is_array($atrr_value)) { - $atrr[$atrr_field] = array($atrr_value); - } - } - break; - default: - return $this->raiseError("Net_LDAP::modify: not supported option " . $option); - break; - } // end switch($option) { - - if(!@call_user_func($command, $this->_link, $dn, $atrr)) { - return $this->raiseError("Net_LDAP::modify: $dn not modified because:" . ldap_error($this->_link), ldap_errno($this->_link)); - } - } // end foreach($_params['changes'] AS $option => $atrr) { - } // end if (is_array($_params['changes'])) { - // everything went fine :) - return true; - - /* old broken code see bug#2987 - if (isset($params['changes'])) { - - if (isset($params['changes']['add']) && - !@ldap_modify($this->_link, $dn, $params['changes']['add'])) { - - return $this->raiseError("Net_LDAP::modify: $dn not modified because:" . ldap_error($this->_link), - ldap_errno($this->_link)); - } - - if (isset($params['changes']['replace']) && - !@ldap_modify($this->_link, $dn, $params['changes']['replace'])) { - - return $this->raiseError("Net_LDAP::modify: replace change didn't work: " . ldap_error($this->_link), - ldap_errno($this->_link)); - } - - if (isset($params['changes']['delete']) && - !@ldap_mod_del($this->_link, $dn, $params['changes']['delete'])) { - - return $this->raiseError("Net_LDAP::modify:delete did not work" . ldap_error($this->_link), - ldap_errno($this->_link)); - } - } - - if (isset($params['add']) && !@ldap_add($this->_link, $dn, $params['add'])) { - return $this->raiseError(ldap_error($this->_link), ldap_errno($this->_link)); - } - - if (isset($params['replace']) && !@ldap_modify($this->_link, $dn, $params['replace'])) { - return $this->raiseError(ldap_error($this->_link), ldap_errno($this->_link)); - } - - if (isset($params['delete'])) { - // since you delete an attribute by making it empty: - foreach ($params['delete'] as $k) { - $params['delete'][$k] = ''; - } - - if (!@ldap_modify($this->_link, $dn, $params['delete'])) { - return $this->raiseError(ldap_error($this->_link), ldap_errno($this->_link)); - } - } - // everything went fine :) - return true; - */ - - } - - /** - * Run a ldap query - * - * Search is used to query the ldap-database. - * $base and $filter may be ommitted. BaseDN and default filter will then be used. - * Params may contain: - * - * scope: The scope which will be used for searching - * base - Just one entry - * sub - The whole tree - * one - Immediately below $base - * sizelimit: Limit the number of entries returned (default: 0), - * timelimit: Limit the time spent for searching (default: 0), - * attrsonly: If true, the search will only return the attribute names, NO values - * attributes: Array of attribute names, which the entry should contain. It is good practice - * to limit this to just the ones you need, so by default this function does not - * return any attributes at all. - * [NOT IMPLEMENTED] - * deref: By default aliases are dereferenced to locate the base object for the search, but not when - * searching subordinates of the base object. This may be changed by specifying one of the - * following values: - * - * never - Do not dereference aliases in searching or in locating the base object of the search. - * search - Dereference aliases in subordinates of the base object in searching, but not in - * locating the base object of the search. - * find - * always - * - * @access public - * @param string LDAP searchbase - * @param string LDAP search filter - * @param array Array of options - * @return object mixed Net_LDAP_Search or Net_LDAP_Error - */ - function search($base = null, $filter = null, $params = array()) - { - if (is_null($base)) { - $base = $this->_config['base']; - } - if (is_null($filter)) { - $filter = $this->_config['filter']; - } - - /* setting searchparameters */ - (isset($params['sizelimit'])) ? $sizelimit = $params['sizelimit'] : $sizelimit = 0; - (isset($params['timelimit'])) ? $timelimit = $params['timelimit'] : $timelimit = 0; - (isset($params['attrsonly'])) ? $attrsonly = $params['attrsonly'] : $attrsonly = 0; - (isset($params['attributes'])) ? $attributes = $params['attributes'] : $attributes = array(''); - - if (!is_array($attributes)) { - $this->raiseError("The param attributes must be an array!"); - } - - /* scoping makes searches faster! */ - $scope = (isset($params['scope']) ? $params['scope'] : $this->_config['scope']); - - switch ($scope) { - case 'one': - $search_function = 'ldap_list'; - break; - case 'base': - $search_function = 'ldap_read'; - break; - default: - $search_function = 'ldap_search'; - } - - $search = @call_user_func($search_function, - $this->_link, - $base, - $filter, - $attributes, - $attrsonly, - $sizelimit, - $timelimit); - - if ($err = ldap_errno($this->_link)) { - - if ($err == 32) { - // Errorcode 32 = no such object, i.e. a nullresult. - return $obj =& new Net_LDAP_Search ($search, $this->_link); - - // Errorcode 4 = sizelimit exeeded. this will be handled better in time... - //} elseif ($err == 4) { - // return $obj = & new Net_LDAP_Search ($search, $this->_link); - - } elseif ($err == 87) { - // bad search filter - return $this->raiseError($this->errorMessage($err) . "($filter)", $err); - } else { - $msg = "\nParameters:\nBase: $base\nFilter: $filter\nScope: $scope"; - return $this->raiseError($this->errorMessage($err) . $msg, $err); - } - } else { - @$obj =& new Net_LDAP_Search($search, $this->_link); - return $obj; - } - - } - - /** - * Set an LDAP option - * - * @access public - * @param string Option to set - * @param mixed Value to set Option to - * @return mixed Net_LDAP_Error or true - */ - function setOption($option, $value) - { - if ($this->_link) { - if (defined($option)) { - if (@ldap_set_option($this->_link, constant($option), $value)) { - return true; - } else { - $err = @ldap_errno($this->_link); - if ($err) { - $msg = @ldap_err2str($err); - } else { - $err = NET_LDAP_ERROR; - $msg = $this->errorMessage($err); - } - return $this->raiseError($msg, $err); - } - } else { - return $this->raiseError("Unkown Option requested"); - } - } else { - return $this->raiseError("No LDAP connection"); - } - } - - /** - * Get an LDAP option value - * - * @access public - * @param string Option to get - * @return mixed Net_LDAP_Error or option value - */ - function getOption($option) - { - if ($this->_link) { - if (defined($option)) { - if (@ldap_get_option($this->_link, constant($option), $value)) { - return $value; - } else { - $err = @ldap_errno($this->_link); - if ($err) { - $msg = @ldap_err2str($err); - } else { - $err = NET_LDAP_ERROR; - $msg = $this->errorMessage($err); - } - return $this->raiseError($msg, $err); - } - } else { - $this->raiseError("Unkown Option requested"); - } - } else { - $this->raiseError("No LDAP connection"); - } - } - - /** - * Get the LDAP_PROTOCOL_VERSION that is used on the connection. - * - * A lot of ldap functionality is defined by what protocol version the ldap server speaks. - * This might be 2 or 3. - * - * @return int - */ - function getLDAPVersion() - { - if($this->_link) { - $version = $this->getOption("LDAP_OPT_PROTOCOL_VERSION"); - } else { - $version = $this->_config['version']; - } - return $version; - } - - /** - * Set the LDAP_PROTOCOL_VERSION that is used on the connection. - * - * @param int Version to set - * @return mixed Net_LDAP_Error or TRUE - */ - function setLDAPVersion($version = 0) - { - if (!$version) { - $version = $this->_config['version']; - } - return $this->setOption("LDAP_OPT_PROTOCOL_VERSION", $version); - } - - /** - * Get the Net_LDAP version. - * - * Return the Net_LDAP version - * - * @return string Net_LDAP version - */ - function getVersion () - { - return $this->_version; - } - - /** - * Tell if a dn already exists - * - * @param string - * @return boolean - */ - function dnExists($dn) - { - $dns = explode(",",$dn); - $filter = array_shift($dns); - $base= implode($dns,','); - //$base = $dn; - //$filter = '(objectclass=*)'; - - $result = @ldap_list($this->_link, $base, $filter, array(), 1, 1); - if (ldap_errno($this->_link) == 32) { - return false; - } - if (ldap_errno($this->_link) != 0) { - $this->raiseError(ldap_error($this->_link), ldap_errno($this->_link)); - } - if (@ldap_count_entries($this->_link, $result)) { - return true; - } - return false; - } - - - /** - * Get a specific entry based on the dn - * - * @param string dn - * @param array Array of Attributes to select - * @return object Net_LDAP_Entry or Net_LDAP_Error - */ - function &getEntry($dn, $attr = array('')) - { - $result = $this->search($dn, '(objectClass=*)', array('scope' => 'base', 'attributes' => $attr)); - if (Net_LDAP::isError($result)) { - return $result; - } - $entry = $result->shiftEntry(); - if (false == $entry) { - return $this->raiseError('Could not fetch entry'); - } - return $entry; - } - - - /** - * Returns the string for an ldap errorcode. - * - * Made to be able to make better errorhandling - * Function based on DB::errorMessage() - * Tip: The best description of the errorcodes is found here: http://www.directory-info.com/LDAP/LDAPErrorCodes.html - * - * @param int Error code - * @return string The errorstring for the error. - */ - function errorMessage($errorcode) - { - $errorMessages = array( - 0x00 => "LDAP_SUCCESS", - 0x01 => "LDAP_OPERATIONS_ERROR", - 0x02 => "LDAP_PROTOCOL_ERROR", - 0x03 => "LDAP_TIMELIMIT_EXCEEDED", - 0x04 => "LDAP_SIZELIMIT_EXCEEDED", - 0x05 => "LDAP_COMPARE_FALSE", - 0x06 => "LDAP_COMPARE_TRUE", - 0x07 => "LDAP_AUTH_METHOD_NOT_SUPPORTED", - 0x08 => "LDAP_STRONG_AUTH_REQUIRED", - 0x09 => "LDAP_PARTIAL_RESULTS", - 0x0a => "LDAP_REFERRAL", - 0x0b => "LDAP_ADMINLIMIT_EXCEEDED", - 0x0c => "LDAP_UNAVAILABLE_CRITICAL_EXTENSION", - 0x0d => "LDAP_CONFIDENTIALITY_REQUIRED", - 0x0e => "LDAP_SASL_BIND_INPROGRESS", - 0x10 => "LDAP_NO_SUCH_ATTRIBUTE", - 0x11 => "LDAP_UNDEFINED_TYPE", - 0x12 => "LDAP_INAPPROPRIATE_MATCHING", - 0x13 => "LDAP_CONSTRAINT_VIOLATION", - 0x14 => "LDAP_TYPE_OR_VALUE_EXISTS", - 0x15 => "LDAP_INVALID_SYNTAX", - 0x20 => "LDAP_NO_SUCH_OBJECT", - 0x21 => "LDAP_ALIAS_PROBLEM", - 0x22 => "LDAP_INVALID_DN_SYNTAX", - 0x23 => "LDAP_IS_LEAF", - 0x24 => "LDAP_ALIAS_DEREF_PROBLEM", - 0x30 => "LDAP_INAPPROPRIATE_AUTH", - 0x31 => "LDAP_INVALID_CREDENTIALS", - 0x32 => "LDAP_INSUFFICIENT_ACCESS", - 0x33 => "LDAP_BUSY", - 0x34 => "LDAP_UNAVAILABLE", - 0x35 => "LDAP_UNWILLING_TO_PERFORM", - 0x36 => "LDAP_LOOP_DETECT", - 0x3C => "LDAP_SORT_CONTROL_MISSING", - 0x3D => "LDAP_INDEX_RANGE_ERROR", - 0x40 => "LDAP_NAMING_VIOLATION", - 0x41 => "LDAP_OBJECT_CLASS_VIOLATION", - 0x42 => "LDAP_NOT_ALLOWED_ON_NONLEAF", - 0x43 => "LDAP_NOT_ALLOWED_ON_RDN", - 0x44 => "LDAP_ALREADY_EXISTS", - 0x45 => "LDAP_NO_OBJECT_CLASS_MODS", - 0x46 => "LDAP_RESULTS_TOO_LARGE", - 0x47 => "LDAP_AFFECTS_MULTIPLE_DSAS", - 0x50 => "LDAP_OTHER", - 0x51 => "LDAP_SERVER_DOWN", - 0x52 => "LDAP_LOCAL_ERROR", - 0x53 => "LDAP_ENCODING_ERROR", - 0x54 => "LDAP_DECODING_ERROR", - 0x55 => "LDAP_TIMEOUT", - 0x56 => "LDAP_AUTH_UNKNOWN", - 0x57 => "LDAP_FILTER_ERROR", - 0x58 => "LDAP_USER_CANCELLED", - 0x59 => "LDAP_PARAM_ERROR", - 0x5a => "LDAP_NO_MEMORY", - 0x5b => "LDAP_CONNECT_ERROR", - 0x5c => "LDAP_NOT_SUPPORTED", - 0x5d => "LDAP_CONTROL_NOT_FOUND", - 0x5e => "LDAP_NO_RESULTS_RETURNED", - 0x5f => "LDAP_MORE_RESULTS_TO_RETURN", - 0x60 => "LDAP_CLIENT_LOOP", - 0x61 => "LDAP_REFERRAL_LIMIT_EXCEEDED", - 1000 => "Unknown Net_LDAP error" - ); - - return isset($errorMessages[$errorcode]) ? $errorMessages[$errorcode] : $errorMessages[NET_LDAP_ERROR]; - } - - /** - * Tell whether value is a Net_LDAP_Error or not - * - * @access public - * @param mixed - * @return boolean - */ - function isError($value) - { - return (is_a($value, "Net_LDAP_Error") || parent::isError($value)); - } - - /** - * gets a root dse object - * - * @access public - * @author Jan Wagner - * @param array Array of attributes to search for - * @return object mixed Net_LDAP_Error or Net_LDAP_RootDSE - */ - function &rootDse($attrs = null) - { - require_once('Net/LDAP/RootDSE.php'); - - if (is_array($attrs) && count($attrs) > 0 ) { - $attributes = $attrs; - } else { - $attributes = array('namingContexts', - 'altServer', - 'supportedExtension', - 'supportedControl', - 'supportedSASLMechanisms', - 'supportedLDAPVersion', - 'subschemaSubentry' ); - } - $result = $this->search('', '(objectClass=*)', array('attributes' => $attributes, 'scope' => 'base')); - if (Net_LDAP::isError($result)) return $result; - - $entry = $result->shift_entry(); - if (false === $entry) return $this->raiseError('Could not fetch RootDSE entry'); - - return new Net_LDAP_RootDSE($entry); - } - - /** - * alias function of rootDse() for perl-ldap interface - * - * @access public - * @see rootDse() - */ - function &root_dse() - { - $args = func_get_args(); - return call_user_func_array(array($this, 'rootDse'), $args); - } - - /** - * get a schema object - * - * @access public - * @author Jan Wagner - * @param string Subschema entry dn - * @return object mixed Net_LDAP_Schema or Net_LDAP_Error - */ - function &schema($dn = null) - { - require_once('Net/LDAP/Schema.php'); - - $schema =& new Net_LDAP_Schema(); - - if (is_null($dn)) { - // get the subschema entry via root dse - $dse = $this->rootDSE(array('subschemaSubentry')); - if (false == Net_LDAP::isError($dse)) { - $base = $dse->getValue('subschemaSubentry', 'single'); - if (!Net_LDAP::isError($base)) { - $dn = $base; - } - } - } - if (is_null($dn)) { - $dn = 'cn=Subschema'; - } - - // fetch the subschema entry - $result = $this->search($dn, '(objectClass=*)', - array('attributes' => array_values($schema->types), 'scope' => 'base')); - if (Net_LDAP::isError($result)) { - return $result; - } - - $entry = $result->shift_entry(); - if (false === $entry) { - return $this->raiseError('Could not fetch Subschema entry'); - } - - $schema->parse($entry); - - return $schema; - } - - /** - * 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->_schema) { - $this->_schema = $this->schema(); - } - - if (!$this->_link || Net_LDAP::isError($this->_schema) || !function_exists($function)) { - return $attributes; - } - - if (is_array($attributes) && count($attributes) > 0) { - - foreach( $attributes as $k => $v ) { - - if (!isset($this->_schemaAttrs[$k])) { - - $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')) { - $encode = true; - } else { - $encode = false; - } - $this->_schemaAttrs[$k] = $encode; - - } else { - $encode = $this->_schemaAttrs[$k]; - } - - if ($encode) { - 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; - } -} - -/** - * Net_LDAP_Error implements a class for reporting portable LDAP error messages. - * - * @package Net_LDAP - */ -class Net_LDAP_Error extends PEAR_Error -{ - /** - * Net_LDAP_Error constructor. - * - * @param mixed Net_LDAP error code, or string with error message. - * @param integer what "error mode" to operate in - * @param integer what error level to use for $mode & PEAR_ERROR_TRIGGER - * @param mixed additional debug info, such as the last query - * @access public - * @see PEAR_Error - */ - function Net_LDAP_Error($code = NET_LDAP_ERROR, $mode = PEAR_ERROR_RETURN, - $level = E_USER_NOTICE, $debuginfo = null) - { - $mode = PEAR_ERROR_RETURN; - if (is_int($code)) { - $this->PEAR_Error('Net_LDAP_Error: ' . Net_LDAP::errorMessage($code), $code, $mode, $level, $debuginfo); - } else { - $this->PEAR_Error("Net_LDAP_Error: $code", NET_LDAP_ERROR, $mode, $level, $debuginfo); - } - } -} -?> diff --git a/gulliver/thirdparty/pear/Net/LDAP/Entry.php b/gulliver/thirdparty/pear/Net/LDAP/Entry.php deleted file mode 100644 index 56ecdefa8..000000000 --- a/gulliver/thirdparty/pear/Net/LDAP/Entry.php +++ /dev/null @@ -1,524 +0,0 @@ - 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 "
"; 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; - } - } -} - -?> diff --git a/gulliver/thirdparty/pear/Net/LDAP/RootDSE.php b/gulliver/thirdparty/pear/Net/LDAP/RootDSE.php deleted file mode 100644 index a2f3fc090..000000000 --- a/gulliver/thirdparty/pear/Net/LDAP/RootDSE.php +++ /dev/null @@ -1,192 +0,0 @@ - - * @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; - } -} - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/Net/LDAP/Schema.php b/gulliver/thirdparty/pear/Net/LDAP/Schema.php deleted file mode 100644 index 5fdd650d8..000000000 --- a/gulliver/thirdparty/pear/Net/LDAP/Schema.php +++ /dev/null @@ -1,355 +0,0 @@ - - * @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; - } - } - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/Net/LDAP/Search.php b/gulliver/thirdparty/pear/Net/LDAP/Search.php deleted file mode 100644 index f6b67f460..000000000 --- a/gulliver/thirdparty/pear/Net/LDAP/Search.php +++ /dev/null @@ -1,245 +0,0 @@ -_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(); - } -} - -?> diff --git a/gulliver/thirdparty/pear/Net/LDAP/Util.php b/gulliver/thirdparty/pear/Net/LDAP/Util.php deleted file mode 100644 index 19f37020b..000000000 --- a/gulliver/thirdparty/pear/Net/LDAP/Util.php +++ /dev/null @@ -1,132 +0,0 @@ - - * @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; - } -} - -?> diff --git a/gulliver/thirdparty/pear/Net/LDAP/fg.php b/gulliver/thirdparty/pear/Net/LDAP/fg.php deleted file mode 100644 index a7f0bfddf..000000000 --- a/gulliver/thirdparty/pear/Net/LDAP/fg.php +++ /dev/null @@ -1,38 +0,0 @@ - $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()); -} - diff --git a/gulliver/thirdparty/pear/Net/POP3.php b/gulliver/thirdparty/pear/Net/POP3.php deleted file mode 100644 index 8c6b7cda0..000000000 --- a/gulliver/thirdparty/pear/Net/POP3.php +++ /dev/null @@ -1,1240 +0,0 @@ - | -// | Co-Author: Damian Fernandez Sosa | -// +-----------------------------------------------------------------------+ -// -// $Id: POP3.php,v 1.2 2004/12/05 16:34:39 damian Exp $ - -require_once('Net/Socket.php'); - - - -/** -* +----------------------------- IMPORTANT ------------------------------+ -* | Usage of this class compared to native php extensions such as IMAP | -* | is slow and may be feature deficient. If available you are STRONGLY | -* | recommended to use the php extensions. | -* +----------------------------------------------------------------------+ -* -* POP3 Access Class -* -* For usage see the example script -*/ - -define('NET_POP3_STATE_DISCONNECTED', 1, true); -define('NET_POP3_STATE_AUTHORISATION', 2, true); -define('NET_POP3_STATE_TRANSACTION', 4, true); - -class Net_POP3 { - - /* - * Some basic information about the mail drop - * garnered from the STAT command - * - * @var array - */ - var $_maildrop; - - /* - * Used for APOP to store the timestamp - * - * @var string - */ - var $_timestamp; - - /* - * Timeout that is passed to the socket object - * - * @var integer - */ - var $_timeout; - - /* - * Socket object - * - * @var object - */ - var $_socket; - - /* - * Current state of the connection. Used with the - * constants defined above. - * - * @var integer - */ - var $_state; - - /* - * Hostname to connect to - * - * @var string - */ - var $_host; - - /* - * Port to connect to - * - * @var integer - */ - var $_port; - - /** - * To allow class debuging - * @var boolean - */ - var $_debug = false; - - - /** - * The auth methods this class support - * @var array - */ - //var $supportedAuthMethods=array('DIGEST-MD5', 'CRAM-MD5', 'APOP' , 'PLAIN' , 'LOGIN', 'USER'); - //Disabling DIGEST-MD5 for now - var $supportedAuthMethods=array( 'CRAM-MD5', 'APOP' , 'PLAIN' , 'LOGIN', 'USER'); - //var $supportedAuthMethods=array( 'CRAM-MD5', 'PLAIN' , 'LOGIN'); - //var $supportedAuthMethods=array( 'PLAIN' , 'LOGIN'); - - - /** - * The auth methods this class support - * @var array - */ - var $supportedSASLAuthMethods=array('DIGEST-MD5', 'CRAM-MD5'); - - - /** - * The capability response - * @var array - */ - var $_capability; - - /* - * Constructor. Sets up the object variables, and instantiates - * the socket object. - * - */ - - - function Net_POP3() - { - $this->_timestamp = ''; // Used for APOP - $this->_maildrop = array(); - $this->_timeout = 3; - $this->_state = NET_POP3_STATE_DISCONNECTED; - $this->_socket =& new Net_Socket(); - /* - * Include the Auth_SASL package. If the package is not available, - * we disable the authentication methods that depend upon it. - */ - if ((@include_once 'Auth/SASL.php') == false) { - if($this->_debug){ - echo "AUTH_SASL NOT PRESENT!\n"; - } - foreach($this->supportedSASLAuthMethods as $SASLMethod){ - $pos = array_search( $SASLMethod, $this->supportedAuthMethods ); - if($this->_debug){ - echo "DISABLING METHOD $SASLMethod\n"; - } - unset($this->supportedAuthMethods[$pos]); - } - } - - - - } - - - /** - * Handles the errors the class can find - * on the server - * - * @access private - * @return PEAR_Error - */ - - function _raiseError($msg, $code =-1) - { - include_once 'PEAR.php'; - return PEAR::raiseError($msg, $code); - } - - - - /* - * Connects to the given host on the given port. - * Also looks for the timestamp in the greeting - * needed for APOP authentication - * - * @param string $host Hostname/IP address to connect to - * @param string $port Port to use to connect to on host - * @return bool Success/Failure - */ - function connect($host = 'localhost', $port = 110) - { - $this->_host = $host; - $this->_port = $port; - - $result = $this->_socket->connect($host, $port, false, $this->_timeout); - if ($result === true) { - $data = $this->_recvLn(); - - if( $this->_checkResponse($data) ){ - // if the response begins with '+OK' ... -// if (@substr(strtoupper($data), 0, 3) == '+OK') { - // Check for string matching apop timestamp - if (preg_match('/<.+@.+>/U', $data, $matches)) { - $this->_timestamp = $matches[0]; - } - $this->_maildrop = array(); - $this->_state = NET_POP3_STATE_AUTHORISATION; - - return true; - } - } - - $this->_socket->disconnect(); - return false; - } - - /* - * Disconnect function. Sends the QUIT command - * and closes the socket. - * - * @return bool Success/Failure - */ - function disconnect() - { - return $this->_cmdQuit(); - } - - /* - * Performs the login procedure. If there is a timestamp - * stored, APOP will be tried first, then basic USER/PASS. - * - * @param string $user Username to use - * @param string $pass Password to use - * @param mixed $apop Whether to try APOP first, if used as string you can select the auth methd to use ( $pop3->login('validlogin', 'validpass', "CRAM-MD5"); - * Valid methods are: 'DIGEST-MD5','CRAM-MD5','LOGIN','PLAIN','APOP','USER' - * @return mixed true on Success/ PEAR_ERROR on error - */ - function login($user, $pass, $apop = true) - { - if ($this->_state == NET_POP3_STATE_AUTHORISATION) { - - if(PEAR::isError($ret= $this->_cmdAuthenticate($user , $pass , $apop ) ) ){ - return $ret; - } - if( ! PEAR::isError($ret)){ - $this->_state = NET_POP3_STATE_TRANSACTION; - return true; - } - - } - return $this->_raiseError('Generic login error' , 1); - } - - - - /** - * Parses the response from the capability command. Stores - * the result in $this->_capability - * - * @access private - */ - function _parseCapability() - { - - if(!PEAR::isError($data = $this->_sendCmd('CAPA'))){ - $data = $this->_getMultiline(); - }else { - // CAPA command not supported, reset data var - // to avoid Notice errors of preg_split on an object - $data = ''; - } - $data = preg_split('/\r?\n/', $data, -1, PREG_SPLIT_NO_EMPTY); - - for ($i = 0; $i < count($data); $i++) { - - $capa=''; - if (preg_match('/^([a-z,\-]+)( ((.*))|$)$/i', $data[$i], $matches)) { - - $capa=strtolower($matches[1]); - switch ($capa) { - case 'implementation': - $this->_capability['implementation'] = $matches[3]; - break; - case 'sasl': - $this->_capability['sasl'] = preg_split('/\s+/', $matches[3]); - break; - default : - $this->_capability[$capa] = $matches[2]; - break; - } - } - } - } - - - - - /** - * Returns the name of the best authentication method that the server - * has advertised. - * - * @param string if !=null,authenticate with this method ($userMethod). - * - * @return mixed Returns a string containing the name of the best - * supported authentication method or a PEAR_Error object - * if a failure condition is encountered. - * @access private - * @since 1.0 - */ - function _getBestAuthMethod($userMethod = null) - { - -/* - return 'USER'; - return 'APOP'; - return 'DIGEST-MD5'; - return 'CRAM-MD5'; -*/ - - - $this->_parseCapability(); - - //unset($this->_capability['sasl']); - - if( isset($this->_capability['sasl']) ){ - $serverMethods=$this->_capability['sasl']; - }else{ - $serverMethods=array('USER'); - // Check for timestamp before attempting APOP - if ($this->_timestamp != null) - { - $serverMethods[] = 'APOP'; - } - } - - if($userMethod !== null && $userMethod !== true ){ - $methods = array(); - $methods[] = $userMethod; - return $userMethod; - }else{ - $methods = $this->supportedAuthMethods; - } - - if( ($methods != null) && ($serverMethods != null)){ - - foreach ( $methods as $method ) { - - if ( in_array( $method , $serverMethods ) ) { - return $method; - } - } - $serverMethods=implode(',' , $serverMethods ); - $myMethods=implode(',' ,$this->supportedAuthMethods); - return $this->_raiseError("$method NOT supported authentication method!. This server " . - "supports these methods: $serverMethods, but I support $myMethods"); - }else{ - return $this->_raiseError("This server don't support any Auth methods"); - } - } - - - - - - - /* Handles the authentication using any known method - * - * @param string The userid to authenticate as. - * @param string The password to authenticate with. - * @param string The method to use ( if $usermethod == '' then the class chooses the best method (the stronger is the best ) ) - * - * @return mixed string or PEAR_Error - * - * @access private - * @since 1.0 - */ - function _cmdAuthenticate($uid , $pwd , $userMethod = null ) - { - - - if ( PEAR::isError( $method = $this->_getBestAuthMethod($userMethod) ) ) { - return $method; - } - - switch ($method) { - case 'DIGEST-MD5': - $result = $this->_authDigest_MD5( $uid , $pwd ); - break; - case 'CRAM-MD5': - $result = $this->_authCRAM_MD5( $uid , $pwd ); - break; - case 'LOGIN': - $result = $this->_authLOGIN( $uid , $pwd ); - break; - case 'PLAIN': - $result = $this->_authPLAIN( $uid , $pwd ); - break; - case 'APOP': - $result = $this->_cmdApop( $uid , $pwd ); - // if APOP fails fallback to USER auth - if( PEAR::isError( $result ) ){ - //echo "APOP FAILED!!!\n"; - $result=$this->_authUSER( $uid , $pwd ); - } - break; - case 'USER': - $result = $this->_authUSER( $uid , $pwd ); - break; - - - default : - $result = $this->_raiseError( "$method is not a supported authentication method" ); - break; - } - return $result; - } - - - - - /* Authenticates the user using the USER-PASS method. - * - * @param string The userid to authenticate as. - * @param string The password to authenticate with. - * - * @return mixed true on success or PEAR_Error on failure - * - * @access private - * @since 1.0 - */ - function _authUSER($user, $pass ) - { - if ( PEAR::isError($ret=$this->_cmdUser($user) ) ){ - return $ret; - } - if ( PEAR::isError($ret=$this->_cmdPass($pass) ) ){ - return $ret; - } - return true; - } - - - - - - - - - /* Authenticates the user using the PLAIN method. - * - * @param string The userid to authenticate as. - * @param string The password to authenticate with. - * - * @return array Returns an array containing the response - * - * @access private - * @since 1.0 - */ - function _authPLAIN($user, $pass ) - { - $cmd=sprintf('AUTH PLAIN %s', base64_encode( chr(0) . $user . chr(0) . $pass ) ); - - if ( PEAR::isError( $ret = $this->_send($cmd) ) ) { - return $ret; - } - if ( PEAR::isError( $challenge = $this->_recvLn() ) ){ - return $challenge; - } - if( PEAR::isError($ret=$this->_checkResponse($challenge) )){ - return $ret; - } - - return true; - } - - - - /* Authenticates the user using the PLAIN method. - * - * @param string The userid to authenticate as. - * @param string The password to authenticate with. - * - * @return array Returns an array containing the response - * - * @access private - * @since 1.0 - */ - function _authLOGIN($user, $pass ) - { - $this->_send('AUTH LOGIN'); - - if ( PEAR::isError( $challenge = $this->_recvLn() ) ) { - return $challenge; - } - if( PEAR::isError($ret=$this->_checkResponse($challenge) )){ - return $ret; - } - - - if ( PEAR::isError( $ret = $this->_send(sprintf('%s', base64_encode($user))) ) ) { - return $ret; - } - - if ( PEAR::isError( $challenge = $this->_recvLn() ) ) { - return $challenge; - } - if( PEAR::isError($ret=$this->_checkResponse($challenge) )){ - return $ret; - } - - if ( PEAR::isError( $ret = $this->_send(sprintf('%s', base64_encode($pass))) ) ) { - return $ret; - } - - if ( PEAR::isError( $challenge = $this->_recvLn() ) ) { - return $challenge; - } - return $this->_checkResponse($challenge); - } - - - - - - /* Authenticates the user using the CRAM-MD5 method. - * - * @param string The userid to authenticate as. - * @param string The password to authenticate with. - * - * @return array Returns an array containing the response - * - * @access private - * @since 1.0 - */ - function _authCRAM_MD5($uid, $pwd ) - { - if ( PEAR::isError( $ret = $this->_send( 'AUTH CRAM-MD5' ) ) ) { - return $ret; - } - - if ( PEAR::isError( $challenge = $this->_recvLn() ) ) { - return $challenge; - } - if( PEAR::isError($ret=$this->_checkResponse($challenge) )){ - return $ret; - } - - // remove '+ ' - - $challenge=substr($challenge,2); - - $challenge = base64_decode( $challenge ); - - $cram = &Auth_SASL::factory('crammd5'); - $auth_str = base64_encode( $cram->getResponse( $uid , $pwd , $challenge ) ); - - - if ( PEAR::isError($error = $this->_send( $auth_str ) ) ) { - return $error; - } - if ( PEAR::isError( $ret = $this->_recvLn() ) ) { - return $ret; - } - //echo "RET:$ret\n"; - return $this->_checkResponse($ret); - } - - - - /* Authenticates the user using the DIGEST-MD5 method. - * - * @param string The userid to authenticate as. - * @param string The password to authenticate with. - * @param string The efective user - * - * @return array Returns an array containing the response - * - * @access private - * @since 1.0 - */ - function _authDigest_MD5($uid, $pwd) - { - if ( PEAR::isError( $ret = $this->_send( 'AUTH DIGEST-MD5' ) ) ) { - return $ret; - } - - if ( PEAR::isError( $challenge = $this->_recvLn() ) ) { - return $challenge; - } - if( PEAR::isError($ret=$this->_checkResponse($challenge) )){ - return $ret; - } - - // remove '+ ' - $challenge=substr($challenge,2); - - $challenge = base64_decode( $challenge ); - $digest = &Auth_SASL::factory('digestmd5'); - $auth_str = base64_encode($digest->getResponse($uid, $pwd, $challenge, "localhost", "pop3" )); - - if ( PEAR::isError($error = $this->_send( $auth_str ) ) ) { - return $error; - } - - if ( PEAR::isError( $challenge = $this->_recvLn() ) ) { - return $challenge; - } - if( PEAR::isError($ret=$this->_checkResponse($challenge) )){ - return $ret; - } - /* - * We don't use the protocol's third step because POP3 doesn't allow - * subsequent authentication, so we just silently ignore it. - */ - - if ( PEAR::isError( $challenge = $this->_send("\r\n") ) ) { - return $challenge ; - } - - if ( PEAR::isError( $challenge = $this->_recvLn() ) ) { - return $challenge; - } - - return $this->_checkResponse($challenge); - - - } - - - - - - - - - - - /* - * Sends the APOP command - * - * @param $user Username to send - * @param $pass Password to send - * @return bool Success/Failure - */ - function _cmdApop($user, $pass) - { - if ($this->_state == NET_POP3_STATE_AUTHORISATION) { - - if (!empty($this->_timestamp)) { - if(PEAR::isError($data = $this->_sendCmd('APOP ' . $user . ' ' . $this->encryptOld($this->_timestamp . $pass)) ) ){ - return $data; - } - $this->_state = NET_POP3_STATE_TRANSACTION; - return true; - } - } - return $this->_raiseError('Not In NET_POP3_STATE_AUTHORISATION State1'); - } - - - - - - - - - - - - - - - - /* - * Returns the raw headers of the specified message. - * - * @param integer $msg_id Message number - * @return mixed Either raw headers or false on error - */ - function getRawHeaders($msg_id) - { - if ($this->_state == NET_POP3_STATE_TRANSACTION) { - return $this->_cmdTop($msg_id, 0); - } - - return false; - } - - /* - * Returns the headers of the specified message in an - * associative array. Array keys are the header names, array - * values are the header values. In the case of multiple headers - * having the same names, eg Received:, the array value will be - * an indexed array of all the header values. - * - * @param integer $msg_id Message number - * @return mixed Either array of headers or false on error - */ - function getParsedHeaders($msg_id) - { - if ($this->_state == NET_POP3_STATE_TRANSACTION) { - - $raw_headers = rtrim($this->getRawHeaders($msg_id)); - - $raw_headers = preg_replace("/\r\n[ \t]+/", ' ', $raw_headers); // Unfold headers - $raw_headers = explode("\r\n", $raw_headers); - foreach ($raw_headers as $value) { - $name = substr($value, 0, $pos = strpos($value, ':')); - $value = ltrim(substr($value, $pos + 1)); - if (isset($headers[$name]) AND is_array($headers[$name])) { - $headers[$name][] = $value; - } elseif (isset($headers[$name])) { - $headers[$name] = array($headers[$name], $value); - } else { - $headers[$name] = $value; - } - } - - return $headers; - } - - return false; - } - - /* - * Returns the body of the message with given message number. - * - * @param integer $msg_id Message number - * @return mixed Either message body or false on error - */ - function getBody($msg_id) - { - if ($this->_state == NET_POP3_STATE_TRANSACTION) { - $msg = $this->_cmdRetr($msg_id); - return substr($msg, strpos($msg, "\r\n\r\n")+4); - } - - return false; - } - - /* - * Returns the entire message with given message number. - * - * @param integer $msg_id Message number - * @return mixed Either entire message or false on error - */ - function getMsg($msg_id) - { - if ($this->_state == NET_POP3_STATE_TRANSACTION) { - return $this->_cmdRetr($msg_id); - } - - return false; - } - - /* - * Returns the size of the maildrop - * - * @return mixed Either size of maildrop or false on error - */ - function getSize() - { - if ($this->_state == NET_POP3_STATE_TRANSACTION) { - if (isset($this->_maildrop['size'])) { - return $this->_maildrop['size']; - } else { - list(, $size) = $this->_cmdStat(); - return $size; - } - } - - return false; - } - - /* - * Returns number of messages in this maildrop - * - * @return mixed Either number of messages or false on error - */ - function numMsg() - { - if ($this->_state == NET_POP3_STATE_TRANSACTION) { - if (isset($this->_maildrop['num_msg'])) { - return $this->_maildrop['num_msg']; - } else { - list($num_msg, ) = $this->_cmdStat(); - return $num_msg; - } - } - - return false; - } - - /* - * Marks a message for deletion. Only will be deleted if the - * disconnect() method is called. - * - * @param integer $msg_id Message to delete - * @return bool Success/Failure - */ - function deleteMsg($msg_id) - { - if ($this->_state == NET_POP3_STATE_TRANSACTION) { - return $this->_cmdDele($msg_id); - } - - return false; - } - - /* - * Combination of LIST/UIDL commands, returns an array - * of data - * - * @param integer $msg_id Optional message number - * @return mixed Array of data or false on error - */ - function getListing($msg_id = null) - { - - if ($this->_state == NET_POP3_STATE_TRANSACTION) { - if (!isset($msg_id)){ - - $list=array(); - if ($list = $this->_cmdList()) { - if ($uidl = $this->_cmdUidl()) { - foreach ($uidl as $i => $value) { - $list[$i]['uidl'] = $value['uidl']; - } - } - return $list; - }else{ - return array(); - } - } else { - if ($list = $this->_cmdList($msg_id) AND $uidl = $this->_cmdUidl($msg_id)) { - return array_merge($list, $uidl); - } - } - } - - return false; - } - - /* - * Sends the USER command - * - * @param string $user Username to send - * @return bool Success/Failure - */ - function _cmdUser($user) - { - if ($this->_state == NET_POP3_STATE_AUTHORISATION) { - return $this->_sendCmd('USER ' . $user); - } - return $this->_raiseError('Not In NET_POP3_STATE_AUTHORISATION State'); - } - - - /* - * Sends the PASS command - * - * @param string $pass Password to send - * @return bool Success/Failure - */ - function _cmdPass($pass) - { - if ($this->_state == NET_POP3_STATE_AUTHORISATION) { - return $this->_sendCmd('PASS ' . $pass); - } - return $this->_raiseError('Not In NET_POP3_STATE_AUTHORISATION State'); - } - - - /* - * Sends the STAT command - * - * @return mixed Indexed array of number of messages and - * maildrop size, or false on error. - */ - function _cmdStat() - { - if ($this->_state == NET_POP3_STATE_TRANSACTION) { - if(!PEAR::isError($data = $this->_sendCmd('STAT'))){ - sscanf($data, '+OK %d %d', $msg_num, $size); - $this->_maildrop['num_msg'] = $msg_num; - $this->_maildrop['size'] = $size; - - return array($msg_num, $size); - } - } - return false; - } - - - /* - * Sends the LIST command - * - * @param integer $msg_id Optional message number - * @return mixed Indexed array of msg_id/msg size or - * false on error - */ - function _cmdList($msg_id = null) - { - $return=array(); - if ($this->_state == NET_POP3_STATE_TRANSACTION) { - if (!isset($msg_id)) { - if(!PEAR::isError($data = $this->_sendCmd('LIST') )){ - $data = $this->_getMultiline(); - $data = explode("\r\n", $data); - foreach ($data as $line) { - if($line !=''){ - sscanf($line, '%s %s', $msg_id, $size); - $return[] = array('msg_id' => $msg_id, 'size' => $size); - } - } - return $return; - } - } else { - if(!PEAR::isError($data = $this->_sendCmd('LIST ' . $msg_id))){ - if($data!=''){ - sscanf($data, '+OK %d %d', $msg_id, $size); - return array('msg_id' => $msg_id, 'size' => $size); - } - return array(); - } - } - } - - - return false; - } - - - /* - * Sends the RETR command - * - * @param integer $msg_id The message number to retrieve - * @return mixed The message or false on error - */ - function _cmdRetr($msg_id) - { - if ($this->_state == NET_POP3_STATE_TRANSACTION) { - if(!PEAR::isError($data = $this->_sendCmd('RETR ' . $msg_id) )){ - $data = $this->_getMultiline(); - return $data; - } - } - - return false; - } - - - /* - * Sends the DELE command - * - * @param integer $msg_id Message number to mark as deleted - * @return bool Success/Failure - */ - function _cmdDele($msg_id) - { - if ($this->_state == NET_POP3_STATE_TRANSACTION) { - return $this->_sendCmd('DELE ' . $msg_id); - } - - return false; - } - - - /* - * Sends the NOOP command - * - * @return bool Success/Failure - */ - function _cmdNoop() - { - if ($this->_state == NET_POP3_STATE_TRANSACTION) { - if(!PEAR::isError($data = $this->_sendCmd('NOOP'))){ - return true; - } - } - - return false; - } - - /* - * Sends the RSET command - * - * @return bool Success/Failure - */ - function _cmdRset() - { - if ($this->_state == NET_POP3_STATE_TRANSACTION) { - if(!PEAR::isError($data = $this->_sendCmd('RSET'))){ - return true; - } - } - - return false; - } - - /* - * Sends the QUIT command - * - * @return bool Success/Failure - */ - function _cmdQuit() - { - $data = $this->_sendCmd('QUIT'); - $this->_state = NET_POP3_STATE_DISCONNECTED; - $this->_socket->disconnect(); - - return (bool)$data; - } - - - /* - * Sends the TOP command - * - * @param integer $msg_id Message number - * @param integer $num_lines Number of lines to retrieve - * @return mixed Message data or false on error - */ - function _cmdTop($msg_id, $num_lines) - { - if ($this->_state == NET_POP3_STATE_TRANSACTION) { - - if(!PEAR::isError($data = $this->_sendCmd('TOP ' . $msg_id . ' ' . $num_lines))){ - return $this->_getMultiline(); - } - } - - return false; - } - - /* - * Sends the UIDL command - * - * @param integer $msg_id Message number - * @return mixed indexed array of msg_id/uidl or false on error - */ - function _cmdUidl($msg_id = null) - { - if ($this->_state == NET_POP3_STATE_TRANSACTION) { - - if (!isset($msg_id)) { - if(!PEAR::isError($data = $this->_sendCmd('UIDL') )){ - $data = $this->_getMultiline(); - $data = explode("\r\n", $data); - foreach ($data as $line) { - sscanf($line, '%d %s', $msg_id, $uidl); - $return[] = array('msg_id' => $msg_id, 'uidl' => $uidl); - } - - return $return; - } - } else { - - $data = $this->_sendCmd('UIDL ' . $msg_id); - sscanf($data, '+OK %d %s', $msg_id, $uidl); - return array('msg_id' => $msg_id, 'uidl' => $uidl); - } - } - - return false; - } - - - - - - - - - - /* - * Sends a command, checks the reponse, and - * if good returns the reponse, other wise - * returns false. - * - * @param string $cmd Command to send (\r\n will be appended) - * @return mixed First line of response if successful, otherwise false - */ - function _sendCmd($cmd) - { - if (PEAR::isError($result = $this->_send($cmd) )){ - return $result ; - } - - if (PEAR::isError($data = $this->_recvLn() )){ - return $data; - } - - if ( strtoupper(substr($data, 0, 3)) == '+OK') { - return $data; - } - - - return $this->_raiseError($data); - } - - /* - * Reads a multiline reponse and returns the data - * - * @return string The reponse. - */ - function _getMultiline() - { - $data = ''; - while(!PEAR::isError($tmp = $this->_recvLn() ) ) { - if($tmp == '.'){ - return substr($data, 0, -2); - } - if (substr($tmp, 0, 2) == '..') { - $tmp = substr($tmp, 1); - } - $data .= $tmp . "\r\n"; - } - return substr($data, 0, -2); - } - - - /** - * Sets the bebug state - * - * @param bool $debug - * @access public - * @return void - */ - function setDebug($debug=true) - { - $this->_debug=$debug; - } - - - - - - /** - * Send the given string of data to the server. - * - * @param string $data The string of data to send. - * - * @return mixed True on success or a PEAR_Error object on failure. - * - * @access private - * @since 1.0 - */ - function _send($data) - { - if ($this->_debug) { - echo "C: $data\n"; - } - - if (PEAR::isError($error = $this->_socket->writeLine($data))) { - return $this->_raiseError('Failed to write to socket: ' . $error->getMessage()); - } - return true; - } - - - - /** - * Receive the given string of data from the server. - * - * @return mixed a line of response on success or a PEAR_Error object on failure. - * - * @access private - * @since 1.0 - */ - function _recvLn() - { - if (PEAR::isError( $lastline = $this->_socket->readLine( 8192 ) ) ) { - return $this->_raiseError('Failed to write to socket: ' . $this->lastline->getMessage() ); - } - if($this->_debug){ - // S: means this data was sent by the POP3 Server - echo "S:$lastline\n" ; - } - return $lastline; - } - - /** - * Checks de server Response - * - * @param string $response the response - * @return mixed true on success or a PEAR_Error object on failure. - * - * @access private - * @since 1.3.3 - */ - - function _checkResponse($response) - { - if (@substr(strtoupper($response), 0, 3) == '+OK') { - return true; - }else{ - if (@substr(strtoupper($response), 0, 4) == '-ERR') { - return $this->_raiseError($response); - }else{ - if (@substr(strtoupper($response), 0, 2) == '+ ') { - return true; - } - } - - } - return $this->_raiseError("Unknown Response ($response)"); - } - - 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); - } - - - -} - -?> diff --git a/gulliver/thirdparty/pear/Net/SMTP.php b/gulliver/thirdparty/pear/Net/SMTP.php deleted file mode 100644 index d632258d6..000000000 --- a/gulliver/thirdparty/pear/Net/SMTP.php +++ /dev/null @@ -1,1082 +0,0 @@ - | -// | Jon Parise | -// | Damian Alejandro Fernandez Sosa | -// +----------------------------------------------------------------------+ -// -// $Id: SMTP.php,v 1.63 2008/06/10 05:39:12 jon Exp $ - -require_once 'PEAR.php'; -require_once 'Net/Socket.php'; - -/** - * Provides an implementation of the SMTP protocol using PEAR's - * Net_Socket:: class. - * - * @package Net_SMTP - * @author Chuck Hagenbuch - * @author Jon Parise - * @author Damian Alejandro Fernandez Sosa - * - * @example basic.php A basic implementation of the Net_SMTP package. - */ -class Net_SMTP -{ - /** - * The server to connect to. - * @var string - * @access public - */ - var $host = 'localhost'; - - /** - * The port to connect to. - * @var int - * @access public - */ - var $port = 25; - - /** - * The value to give when sending EHLO or HELO. - * @var string - * @access public - */ - var $localhost = 'localhost'; - - /** - * List of supported authentication methods, in preferential order. - * @var array - * @access public - */ - var $auth_methods = array('DIGEST-MD5', 'CRAM-MD5', 'LOGIN', 'PLAIN'); - - /** - * Use SMTP command pipelining (specified in RFC 2920) if the SMTP - * server supports it. - * - * When pipeling is enabled, rcptTo(), mailFrom(), sendFrom(), - * somlFrom() and samlFrom() do not wait for a response from the - * SMTP server but return immediately. - * - * @var bool - * @access public - */ - var $pipelining = false; - - /** - * Number of pipelined commands. - * @var int - * @access private - */ - var $_pipelined_commands = 0; - - /** - * Should debugging output be enabled? - * @var boolean - * @access private - */ - var $_debug = false; - - /** - * The socket resource being used to connect to the SMTP server. - * @var resource - * @access private - */ - var $_socket = null; - - /** - * The most recent server response code. - * @var int - * @access private - */ - var $_code = -1; - - /** - * The most recent server response arguments. - * @var array - * @access private - */ - var $_arguments = array(); - - /** - * Stores detected features of the SMTP server. - * @var array - * @access private - */ - var $_esmtp = array(); - - /** - * Instantiates a new Net_SMTP object, overriding any defaults - * with parameters that are passed in. - * - * If you have SSL support in PHP, you can connect to a server - * over SSL using an 'ssl://' prefix: - * - * // 465 is a common smtps port. - * $smtp = new Net_SMTP('ssl://mail.host.com', 465); - * $smtp->connect(); - * - * @param string $host The server to connect to. - * @param integer $port The port to connect to. - * @param string $localhost The value to give when sending EHLO or HELO. - * @param boolean $pipeling Use SMTP command pipelining - * - * @access public - * @since 1.0 - */ - function Net_SMTP($host = null, $port = null, $localhost = null, $pipelining = false) - { - if (isset($host)) { - $this->host = $host; - } - if (isset($port)) { - $this->port = $port; - } - if (isset($localhost)) { - $this->localhost = $localhost; - } - $this->pipelining = $pipelining; - - $this->_socket = new Net_Socket(); - - /* Include the Auth_SASL package. If the package is not - * available, we disable the authentication methods that - * depend upon it. */ - if ((@include_once 'Auth/SASL.php') === false) { - $pos = array_search('DIGEST-MD5', $this->auth_methods); - unset($this->auth_methods[$pos]); - $pos = array_search('CRAM-MD5', $this->auth_methods); - unset($this->auth_methods[$pos]); - } - } - - /** - * Set the value of the debugging flag. - * - * @param boolean $debug New value for the debugging flag. - * - * @access public - * @since 1.1.0 - */ - function setDebug($debug) - { - $this->_debug = $debug; - } - - /** - * Send the given string of data to the server. - * - * @param string $data The string of data to send. - * - * @return mixed True on success or a PEAR_Error object on failure. - * - * @access private - * @since 1.1.0 - */ - function _send($data) - { - if ($this->_debug) { - echo "DEBUG: Send: $data\n"; - } - - if (PEAR::isError($error = $this->_socket->write($data))) { - return PEAR::raiseError('Failed to write to socket: ' . - $error->getMessage()); - } - - return true; - } - - /** - * Send a command to the server with an optional string of - * arguments. A carriage return / linefeed (CRLF) sequence will - * be appended to each command string before it is sent to the - * SMTP server - an error will be thrown if the command string - * already contains any newline characters. Use _send() for - * commands that must contain newlines. - * - * @param string $command The SMTP command to send to the server. - * @param string $args A string of optional arguments to append - * to the command. - * - * @return mixed The result of the _send() call. - * - * @access private - * @since 1.1.0 - */ - function _put($command, $args = '') - { - if (!empty($args)) { - $command .= ' ' . $args; - } - - if (strcspn($command, "\r\n") !== strlen($command)) { - return PEAR::raiseError('Commands cannot contain newlines'); - } - - return $this->_send($command . "\r\n"); - } - - /** - * Read a reply from the SMTP server. The reply consists of a response - * code and a response message. - * - * @param mixed $valid The set of valid response codes. These - * may be specified as an array of integer - * values or as a single integer value. - * @param bool $later Do not parse the response now, but wait - * until the last command in the pipelined - * command group - * - * @return mixed True if the server returned a valid response code or - * a PEAR_Error object is an error condition is reached. - * - * @access private - * @since 1.1.0 - * - * @see getResponse - */ - function _parseResponse($valid, $later = false) - { - $this->_code = -1; - $this->_arguments = array(); - - if ($later) { - $this->_pipelined_commands++; - return true; - } - - for ($i = 0; $i <= $this->_pipelined_commands; $i++) { - while ($line = $this->_socket->readLine()) { - if ($this->_debug) { - echo "DEBUG: Recv: $line\n"; - } - - /* If we receive an empty line, the connection has been closed. */ - if (empty($line)) { - $this->disconnect(); - return PEAR::raiseError('Connection was unexpectedly closed'); - } - - /* Read the code and store the rest in the arguments array. */ - $code = substr($line, 0, 3); - $this->_arguments[] = trim(substr($line, 4)); - - /* Check the syntax of the response code. */ - if (is_numeric($code)) { - $this->_code = (int)$code; - } else { - $this->_code = -1; - break; - } - - /* If this is not a multiline response, we're done. */ - if (substr($line, 3, 1) != '-') { - break; - } - } - } - - $this->_pipelined_commands = 0; - - /* Compare the server's response code with the valid code/codes. */ - if (is_int($valid) && ($this->_code === $valid)) { - return true; - } elseif (is_array($valid) && in_array($this->_code, $valid, true)) { - return true; - } - - return PEAR::raiseError('Invalid response code received from server', - $this->_code); - } - - /** - * Return a 2-tuple containing the last response from the SMTP server. - * - * @return array A two-element array: the first element contains the - * response code as an integer and the second element - * contains the response's arguments as a string. - * - * @access public - * @since 1.1.0 - */ - function getResponse() - { - return array($this->_code, join("\n", $this->_arguments)); - } - - /** - * Attempt to connect to the SMTP server. - * - * @param int $timeout The timeout value (in seconds) for the - * socket connection. - * @param bool $persistent Should a persistent socket connection - * be used? - * - * @return mixed Returns a PEAR_Error with an error message on any - * kind of failure, or true on success. - * @access public - * @since 1.0 - */ - function connect($timeout = null, $persistent = false) - { - $result = $this->_socket->connect($this->host, $this->port, - $persistent, $timeout); - if (PEAR::isError($result)) { - return PEAR::raiseError('Failed to connect socket: ' . - $result->getMessage()); - } - - if (PEAR::isError($error = $this->_parseResponse(220))) { - return $error; - } - if (PEAR::isError($error = $this->_negotiate())) { - return $error; - } - - return true; - } - - /** - * Attempt to disconnect from the SMTP server. - * - * @return mixed Returns a PEAR_Error with an error message on any - * kind of failure, or true on success. - * @access public - * @since 1.0 - */ - function disconnect() - { - if (PEAR::isError($error = $this->_put('QUIT'))) { - return $error; - } - if (PEAR::isError($error = $this->_parseResponse(221))) { - return $error; - } - if (PEAR::isError($error = $this->_socket->disconnect())) { - return PEAR::raiseError('Failed to disconnect socket: ' . - $error->getMessage()); - } - - return true; - } - - /** - * Attempt to send the EHLO command and obtain a list of ESMTP - * extensions available, and failing that just send HELO. - * - * @return mixed Returns a PEAR_Error with an error message on any - * kind of failure, or true on success. - * - * @access private - * @since 1.1.0 - */ - function _negotiate() - { - if (PEAR::isError($error = $this->_put('EHLO', $this->localhost))) { - return $error; - } - - if (PEAR::isError($this->_parseResponse(250))) { - /* If we receive a 503 response, we're already authenticated. */ - if ($this->_code === 503) { - return true; - } - - /* If the EHLO failed, try the simpler HELO command. */ - if (PEAR::isError($error = $this->_put('HELO', $this->localhost))) { - return $error; - } - if (PEAR::isError($this->_parseResponse(250))) { - return PEAR::raiseError('HELO was not accepted: ', $this->_code); - } - - return true; - } - - foreach ($this->_arguments as $argument) { - $verb = strtok($argument, ' '); - $arguments = substr($argument, strlen($verb) + 1, - strlen($argument) - strlen($verb) - 1); - $this->_esmtp[$verb] = $arguments; - } - - if (!isset($this->_esmtp['PIPELINING'])) { - $this->pipelining = false; - } - - return true; - } - - /** - * Returns the name of the best authentication method that the server - * has advertised. - * - * @return mixed Returns a string containing the name of the best - * supported authentication method or a PEAR_Error object - * if a failure condition is encountered. - * @access private - * @since 1.1.0 - */ - function _getBestAuthMethod() - { - $available_methods = explode(' ', $this->_esmtp['AUTH']); - - foreach ($this->auth_methods as $method) { - if (in_array($method, $available_methods)) { - return $method; - } - } - - return PEAR::raiseError('No supported authentication methods'); - } - - /** - * Attempt to do SMTP authentication. - * - * @param string The userid to authenticate as. - * @param string The password to authenticate with. - * @param string The requested authentication method. If none is - * specified, the best supported method will be used. - * - * @return mixed Returns a PEAR_Error with an error message on any - * kind of failure, or true on success. - * @access public - * @since 1.0 - */ - function auth($uid, $pwd , $method = '') - { - if (empty($this->_esmtp['AUTH'])) { - if (version_compare(PHP_VERSION, '5.1.0', '>=')) { - if (!isset($this->_esmtp['STARTTLS'])) { - return PEAR::raiseError('SMTP server does not support authentication'); - } - if (PEAR::isError($result = $this->_put('STARTTLS'))) { - return $result; - } - if (PEAR::isError($result = $this->_parseResponse(220))) { - return $result; - } - if (PEAR::isError($result = $this->_socket->enableCrypto(true, STREAM_CRYPTO_METHOD_TLS_CLIENT))) { - return $result; - } elseif ($result !== true) { - return PEAR::raiseError('STARTTLS failed'); - } - - /* Send EHLO again to recieve the AUTH string from the - * SMTP server. */ - $this->_negotiate(); - if (empty($this->_esmtp['AUTH'])) { - return PEAR::raiseError('SMTP server does not support authentication'); - } - } else { - return PEAR::raiseError('SMTP server does not support authentication'); - } - } - - /* If no method has been specified, get the name of the best - * supported method advertised by the SMTP server. */ - if (empty($method)) { - if (PEAR::isError($method = $this->_getBestAuthMethod())) { - /* Return the PEAR_Error object from _getBestAuthMethod(). */ - return $method; - } - } else { - $method = strtoupper($method); - if (!in_array($method, $this->auth_methods)) { - return PEAR::raiseError("$method is not a supported authentication method"); - } - } - - switch ($method) { - case 'DIGEST-MD5': - $result = $this->_authDigest_MD5($uid, $pwd); - break; - - case 'CRAM-MD5': - $result = $this->_authCRAM_MD5($uid, $pwd); - break; - - case 'LOGIN': - $result = $this->_authLogin($uid, $pwd); - break; - - case 'PLAIN': - $result = $this->_authPlain($uid, $pwd); - break; - - default: - $result = PEAR::raiseError("$method is not a supported authentication method"); - break; - } - - /* If an error was encountered, return the PEAR_Error object. */ - if (PEAR::isError($result)) { - return $result; - } - - return true; - } - - /** - * Authenticates the user using the DIGEST-MD5 method. - * - * @param string The userid to authenticate as. - * @param string The password to authenticate with. - * - * @return mixed Returns a PEAR_Error with an error message on any - * kind of failure, or true on success. - * @access private - * @since 1.1.0 - */ - function _authDigest_MD5($uid, $pwd) - { - if (PEAR::isError($error = $this->_put('AUTH', 'DIGEST-MD5'))) { - return $error; - } - /* 334: Continue authentication request */ - if (PEAR::isError($error = $this->_parseResponse(334))) { - /* 503: Error: already authenticated */ - if ($this->_code === 503) { - return true; - } - return $error; - } - - $challenge = base64_decode($this->_arguments[0]); - $digest = &Auth_SASL::factory('digestmd5'); - $auth_str = base64_encode($digest->getResponse($uid, $pwd, $challenge, - $this->host, "smtp")); - - if (PEAR::isError($error = $this->_put($auth_str))) { - return $error; - } - /* 334: Continue authentication request */ - if (PEAR::isError($error = $this->_parseResponse(334))) { - return $error; - } - - /* We don't use the protocol's third step because SMTP doesn't - * allow subsequent authentication, so we just silently ignore - * it. */ - if (PEAR::isError($error = $this->_put(''))) { - return $error; - } - /* 235: Authentication successful */ - if (PEAR::isError($error = $this->_parseResponse(235))) { - return $error; - } - } - - /** - * Authenticates the user using the CRAM-MD5 method. - * - * @param string The userid to authenticate as. - * @param string The password to authenticate with. - * - * @return mixed Returns a PEAR_Error with an error message on any - * kind of failure, or true on success. - * @access private - * @since 1.1.0 - */ - function _authCRAM_MD5($uid, $pwd) - { - if (PEAR::isError($error = $this->_put('AUTH', 'CRAM-MD5'))) { - return $error; - } - /* 334: Continue authentication request */ - if (PEAR::isError($error = $this->_parseResponse(334))) { - /* 503: Error: already authenticated */ - if ($this->_code === 503) { - return true; - } - return $error; - } - - $challenge = base64_decode($this->_arguments[0]); - $cram = &Auth_SASL::factory('crammd5'); - $auth_str = base64_encode($cram->getResponse($uid, $pwd, $challenge)); - - if (PEAR::isError($error = $this->_put($auth_str))) { - return $error; - } - - /* 235: Authentication successful */ - if (PEAR::isError($error = $this->_parseResponse(235))) { - return $error; - } - } - - /** - * Authenticates the user using the LOGIN method. - * - * @param string The userid to authenticate as. - * @param string The password to authenticate with. - * - * @return mixed Returns a PEAR_Error with an error message on any - * kind of failure, or true on success. - * @access private - * @since 1.1.0 - */ - function _authLogin($uid, $pwd) - { - if (PEAR::isError($error = $this->_put('AUTH', 'LOGIN'))) { - return $error; - } - /* 334: Continue authentication request */ - if (PEAR::isError($error = $this->_parseResponse(334))) { - /* 503: Error: already authenticated */ - if ($this->_code === 503) { - return true; - } - return $error; - } - - if (PEAR::isError($error = $this->_put(base64_encode($uid)))) { - return $error; - } - /* 334: Continue authentication request */ - if (PEAR::isError($error = $this->_parseResponse(334))) { - return $error; - } - - if (PEAR::isError($error = $this->_put(base64_encode($pwd)))) { - return $error; - } - - /* 235: Authentication successful */ - if (PEAR::isError($error = $this->_parseResponse(235))) { - return $error; - } - - return true; - } - - /** - * Authenticates the user using the PLAIN method. - * - * @param string The userid to authenticate as. - * @param string The password to authenticate with. - * - * @return mixed Returns a PEAR_Error with an error message on any - * kind of failure, or true on success. - * @access private - * @since 1.1.0 - */ - function _authPlain($uid, $pwd) - { - if (PEAR::isError($error = $this->_put('AUTH', 'PLAIN'))) { - return $error; - } - /* 334: Continue authentication request */ - if (PEAR::isError($error = $this->_parseResponse(334))) { - /* 503: Error: already authenticated */ - if ($this->_code === 503) { - return true; - } - return $error; - } - - $auth_str = base64_encode(chr(0) . $uid . chr(0) . $pwd); - - if (PEAR::isError($error = $this->_put($auth_str))) { - return $error; - } - - /* 235: Authentication successful */ - if (PEAR::isError($error = $this->_parseResponse(235))) { - return $error; - } - - return true; - } - - /** - * Send the HELO command. - * - * @param string The domain name to say we are. - * - * @return mixed Returns a PEAR_Error with an error message on any - * kind of failure, or true on success. - * @access public - * @since 1.0 - */ - function helo($domain) - { - if (PEAR::isError($error = $this->_put('HELO', $domain))) { - return $error; - } - if (PEAR::isError($error = $this->_parseResponse(250))) { - return $error; - } - - return true; - } - - /** - * Return the list of SMTP service extensions advertised by the server. - * - * @return array The list of SMTP service extensions. - * @access public - * @since 1.3 - */ - function getServiceExtensions() - { - return $this->_esmtp; - } - - /** - * Send the MAIL FROM: command. - * - * @param string $sender The sender (reverse path) to set. - * @param string $params String containing additional MAIL parameters, - * such as the NOTIFY flags defined by RFC 1891 - * or the VERP protocol. - * - * If $params is an array, only the 'verp' option - * is supported. If 'verp' is true, the XVERP - * parameter is appended to the MAIL command. If - * the 'verp' value is a string, the full - * XVERP=value parameter is appended. - * - * @return mixed Returns a PEAR_Error with an error message on any - * kind of failure, or true on success. - * @access public - * @since 1.0 - */ - function mailFrom($sender, $params = null) - { - $args = "FROM:<$sender>"; - - /* Support the deprecated array form of $params. */ - if (is_array($params) && isset($params['verp'])) { - /* XVERP */ - if ($params['verp'] === true) { - $args .= ' XVERP'; - - /* XVERP=something */ - } elseif (trim($params['verp'])) { - $args .= ' XVERP=' . $params['verp']; - } - } elseif (is_string($params)) { - $args .= ' ' . $params; - } - - if (PEAR::isError($error = $this->_put('MAIL', $args))) { - return $error; - } - if (PEAR::isError($error = $this->_parseResponse(250, $this->pipelining))) { - return $error; - } - - return true; - } - - /** - * Send the RCPT TO: command. - * - * @param string $recipient The recipient (forward path) to add. - * @param string $params String containing additional RCPT parameters, - * such as the NOTIFY flags defined by RFC 1891. - * - * @return mixed Returns a PEAR_Error with an error message on any - * kind of failure, or true on success. - * - * @access public - * @since 1.0 - */ - function rcptTo($recipient, $params = null) - { - $args = "TO:<$recipient>"; - if (is_string($params)) { - $args .= ' ' . $params; - } - - if (PEAR::isError($error = $this->_put('RCPT', $args))) { - return $error; - } - if (PEAR::isError($error = $this->_parseResponse(array(250, 251), $this->pipelining))) { - return $error; - } - - return true; - } - - /** - * Quote the data so that it meets SMTP standards. - * - * This is provided as a separate public function to facilitate - * easier overloading for the cases where it is desirable to - * customize the quoting behavior. - * - * @param string $data The message text to quote. The string must be passed - * by reference, and the text will be modified in place. - * - * @access public - * @since 1.2 - */ - function quotedata(&$data) - { - /* Change Unix (\n) and Mac (\r) linefeeds into - * Internet-standard CRLF (\r\n) linefeeds. */ - $data = preg_replace(array('/(?_esmtp['SIZE']) && ($this->_esmtp['SIZE'] > 0)) { - if (strlen($data) >= $this->_esmtp['SIZE']) { - $this->disconnect(); - return PEAR::raiseError('Message size excedes the server limit'); - } - } - - /* Quote the data based on the SMTP standards. */ - $this->quotedata($data); - - if (PEAR::isError($error = $this->_put('DATA'))) { - return $error; - } - if (PEAR::isError($error = $this->_parseResponse(354))) { - return $error; - } - - if (PEAR::isError($result = $this->_send($data . "\r\n.\r\n"))) { - return $result; - } - if (PEAR::isError($error = $this->_parseResponse(250, $this->pipelining))) { - return $error; - } - - return true; - } - - /** - * Send the SEND FROM: command. - * - * @param string The reverse path to send. - * - * @return mixed Returns a PEAR_Error with an error message on any - * kind of failure, or true on success. - * @access public - * @since 1.2.6 - */ - function sendFrom($path) - { - if (PEAR::isError($error = $this->_put('SEND', "FROM:<$path>"))) { - return $error; - } - if (PEAR::isError($error = $this->_parseResponse(250, $this->pipelining))) { - return $error; - } - - return true; - } - - /** - * Backwards-compatibility wrapper for sendFrom(). - * - * @param string The reverse path to send. - * - * @return mixed Returns a PEAR_Error with an error message on any - * kind of failure, or true on success. - * - * @access public - * @since 1.0 - * @deprecated 1.2.6 - */ - function send_from($path) - { - return sendFrom($path); - } - - /** - * Send the SOML FROM: command. - * - * @param string The reverse path to send. - * - * @return mixed Returns a PEAR_Error with an error message on any - * kind of failure, or true on success. - * @access public - * @since 1.2.6 - */ - function somlFrom($path) - { - if (PEAR::isError($error = $this->_put('SOML', "FROM:<$path>"))) { - return $error; - } - if (PEAR::isError($error = $this->_parseResponse(250, $this->pipelining))) { - return $error; - } - - return true; - } - - /** - * Backwards-compatibility wrapper for somlFrom(). - * - * @param string The reverse path to send. - * - * @return mixed Returns a PEAR_Error with an error message on any - * kind of failure, or true on success. - * - * @access public - * @since 1.0 - * @deprecated 1.2.6 - */ - function soml_from($path) - { - return somlFrom($path); - } - - /** - * Send the SAML FROM: command. - * - * @param string The reverse path to send. - * - * @return mixed Returns a PEAR_Error with an error message on any - * kind of failure, or true on success. - * @access public - * @since 1.2.6 - */ - function samlFrom($path) - { - if (PEAR::isError($error = $this->_put('SAML', "FROM:<$path>"))) { - return $error; - } - if (PEAR::isError($error = $this->_parseResponse(250, $this->pipelining))) { - return $error; - } - - return true; - } - - /** - * Backwards-compatibility wrapper for samlFrom(). - * - * @param string The reverse path to send. - * - * @return mixed Returns a PEAR_Error with an error message on any - * kind of failure, or true on success. - * - * @access public - * @since 1.0 - * @deprecated 1.2.6 - */ - function saml_from($path) - { - return samlFrom($path); - } - - /** - * Send the RSET command. - * - * @return mixed Returns a PEAR_Error with an error message on any - * kind of failure, or true on success. - * @access public - * @since 1.0 - */ - function rset() - { - if (PEAR::isError($error = $this->_put('RSET'))) { - return $error; - } - if (PEAR::isError($error = $this->_parseResponse(250, $this->pipelining))) { - return $error; - } - - return true; - } - - /** - * Send the VRFY command. - * - * @param string The string to verify - * - * @return mixed Returns a PEAR_Error with an error message on any - * kind of failure, or true on success. - * @access public - * @since 1.0 - */ - function vrfy($string) - { - /* Note: 251 is also a valid response code */ - if (PEAR::isError($error = $this->_put('VRFY', $string))) { - return $error; - } - if (PEAR::isError($error = $this->_parseResponse(array(250, 252)))) { - return $error; - } - - return true; - } - - /** - * Send the NOOP command. - * - * @return mixed Returns a PEAR_Error with an error message on any - * kind of failure, or true on success. - * @access public - * @since 1.0 - */ - function noop() - { - if (PEAR::isError($error = $this->_put('NOOP'))) { - return $error; - } - if (PEAR::isError($error = $this->_parseResponse(250))) { - return $error; - } - - return true; - } - - /** - * Backwards-compatibility method. identifySender()'s functionality is - * now handled internally. - * - * @return boolean This method always return true. - * - * @access public - * @since 1.0 - */ - function identifySender() - { - return true; - } - -} diff --git a/gulliver/thirdparty/pear/Net/Socket.php b/gulliver/thirdparty/pear/Net/Socket.php deleted file mode 100644 index d7a049566..000000000 --- a/gulliver/thirdparty/pear/Net/Socket.php +++ /dev/null @@ -1,576 +0,0 @@ - | -// | Chuck Hagenbuch | -// +----------------------------------------------------------------------+ -// -// $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 - * @author Chuck Hagenbuch - */ -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: - * - *

- * timed_out (bool) - The socket timed out waiting for data
- * blocked (bool) - The socket was blocked
- * eof (bool) - Indicates EOF event
- * unread_bytes (int) - Number of bytes left in the socket buffer
- *

- * - * @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'); - } - } - -} diff --git a/gulliver/thirdparty/pear/Net/URL.php b/gulliver/thirdparty/pear/Net/URL.php deleted file mode 100644 index 3dcfef60d..000000000 --- a/gulliver/thirdparty/pear/Net/URL.php +++ /dev/null @@ -1,485 +0,0 @@ - | -// +-----------------------------------------------------------------------+ -// -// $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 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 - */ - 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]; - } - -} -?> diff --git a/gulliver/thirdparty/pear/Net/URL2.php b/gulliver/thirdparty/pear/Net/URL2.php deleted file mode 100644 index 7a654aed8..000000000 --- a/gulliver/thirdparty/pear/Net/URL2.php +++ /dev/null @@ -1,813 +0,0 @@ - | -// +-----------------------------------------------------------------------+ -// -// $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; - } -} diff --git a/gulliver/thirdparty/pear/Net/UserAgent/Detect.php b/gulliver/thirdparty/pear/Net/UserAgent/Detect.php deleted file mode 100644 index 0ceb95faa..000000000 --- a/gulliver/thirdparty/pear/Net/UserAgent/Detect.php +++ /dev/null @@ -1,967 +0,0 @@ - | -// | Jason Rust | -// +----------------------------------------------------------------------+ - -// $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 - * @author Dan Allen - * @author Chuck Hagenbuch - * @author Jon Parise - * @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]; - } - - // }}} -} -?> diff --git a/gulliver/thirdparty/pear/Net/UserAgent/Detect/APC.php b/gulliver/thirdparty/pear/Net/UserAgent/Detect/APC.php deleted file mode 100644 index 7c8a23537..000000000 --- a/gulliver/thirdparty/pear/Net/UserAgent/Detect/APC.php +++ /dev/null @@ -1,123 +0,0 @@ - | -// +----------------------------------------------------------------------+ - -// $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)); - } - } -} -?> diff --git a/gulliver/thirdparty/pear/Numbers/Words.php b/gulliver/thirdparty/pear/Numbers/Words.php deleted file mode 100644 index 7397a6437..000000000 --- a/gulliver/thirdparty/pear/Numbers/Words.php +++ /dev/null @@ -1,145 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Words.php,v 1.7 2003/09/29 12:23:58 makler Exp $ -// - -/** - * The Numbers_Words class provides method to convert arabic numerals to - * words (also with currency name). - * - * @author Piotr Klaban - * @package Numbers_Words - */ - -// {{{ Numbers_Words - -/** - * The Numbers_Words class provides method to convert arabic numerals to words. - * - * @access public - * @author Piotr Klaban - * @since PHP 4.2.3 - * @package Numbers_Words - */ -class Numbers_Words -{ - // {{{ toWords() - - /** - * Converts a number to its word representation - * - * @param integer $num An integer between -infinity and infinity inclusive :) - * that should be converted to a words representation - * - * @param string $locale Language name abbreviation. Optional. Defaults to en_US. - * - * @return string The corresponding word representation - * - * @access public - * @author Piotr Klaban - * @since PHP 4.2.3 - */ - function toWords($num, $locale = 'en_US') { - - include_once("Numbers/Words/lang.${locale}.php"); - - $classname = "Numbers_Words_${locale}"; - - if (!class_exists($classname)) { - return Numbers_Words::raiseError("Unable to include the Numbers/Words/lang.${locale}.php file"); - } - - $methods = get_class_methods($classname); - - if (!in_array('toWords', $methods) && !in_array('towords', $methods)) { - return Numbers_Words::raiseError("Unable to find toWords method in '$classname' class"); - } - - @$obj =& new $classname; - - return trim($obj->toWords($num)); - } - // }}} - // {{{ toCurrency() - /** - * Converts a currency value to word representation (1.02 => one dollar two cents) - * If the number has not any fraction part, the "cents" number is omitted. - * - * @param float $num A float/integer number representing currency value - * - * @param string $locale Language name abbreviation. Optional. Defaults to en_US. - * - * @param string $int_curr International currency symbol - * as defined by the ISO 4217 standard (three characters). - * E.g. 'EUR', 'USD', 'PLN'. Optional. - * Defaults to $def_currency defined in the language class. - * - * @return string The corresponding word representation - * - * @access public - * @author Piotr Klaban - * @since PHP 4.2.3 - */ - function toCurrency($num, $locale = 'en_US', $int_curr = '') { - $ret = $num; - - @include_once("Numbers/Words/lang.${locale}.php"); - - $classname = "Numbers_Words_${locale}"; - - if (!class_exists($classname)) { - return Numbers_Words::raiseError("Unable to include the Numbers/Words/lang.${locale}.php file"); - } - - $methods = get_class_methods($classname); - - if (!in_array('toCurrencyWords', $methods) && !in_array('tocurrencywords', $methods)) { - return Numbers_Words::raiseError("Unable to find toCurrencyWords method in '$classname' class"); - } - - @$obj =& new $classname; - - if (strpos($num, '.') === false) - { - $ret = trim($obj->toCurrencyWords($int_curr, $num)); - } else { - $currency = explode('.', $num, 2); - $ret = trim($obj->toCurrencyWords($int_curr, $currency[0], $currency[1])); - } - return $ret; - } - // }}} - // {{{ raiseError() - /** - * Trigger a PEAR error - * - * To improve performances, the PEAR.php file is included dynamically. - * - * @param string error message - */ - function raiseError($msg) - { - include_once('PEAR.php'); - return PEAR::raiseError($msg); - } - // }}} -} - -// }}} -?> diff --git a/gulliver/thirdparty/pear/Numbers/Words/lang.bg.php b/gulliver/thirdparty/pear/Numbers/Words/lang.bg.php deleted file mode 100644 index 1204d29b7..000000000 --- a/gulliver/thirdparty/pear/Numbers/Words/lang.bg.php +++ /dev/null @@ -1,505 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id$ - -/** - * Include needed files - */ -require_once("Numbers/Words.php"); - -/** - * Class for translating numbers into Bulgarian. - * - * @author Kouber Saparev - * @package Numbers_Words - */ -class Numbers_Words_bg extends Numbers_Words -{ - - // {{{ properties - - /** - * Locale name. - * @var string - * @access public - */ - var $locale = 'bg'; - - /** - * Language name in English. - * @var string - * @access public - */ - var $lang = 'Bulgarian'; - - /** - * Native language name. - * @var string - * @access public - */ - var $lang_native = 'Áúëãàðñêè'; - - /** - * Some miscellaneous words and language constructs. - * @var string - * @access private - */ - var $_misc_strings = array( - 'deset'=>'äåñåò', // "ten" - 'edinadeset'=>'åäèíàäåñåò', // "eleven" - 'na'=>'íà', // liaison particle for 12 to 19 - 'sto'=>'ñòî', // "hundred" - 'sta'=>'ñòà', // suffix for 2 and 3 hundred - 'stotin'=>'ñòîòèí', // suffix for 4 to 9 hundred - 'hiliadi'=>'õèëÿäè' // plural form of "thousand" - ); - - - /** - * The words for digits (except zero). Note that, there are three genders for them (neuter, masculine and feminine). - * The words for 3 to 9 (masculine) and for 2 to 9 (feminine) are the same as neuter, so they're filled - * in the _initDigits() method, which is invoked from the constructor. - * @var string - * @access private - */ - var $_digits = array( - 0=>array(1=>"åäíî", "äâå", "òðè", "÷åòèðè", "ïåò", "øåñò", "ñåäåì", "îñåì", "äåâåò"), // neuter - 1=>array(1=>'åäèí', 'äâà'), // masculine - -1=>array(1=>'åäíà') // feminine - ); - - /** - * A flag, that determines if the _digits array is filled for masculine and feminine genders. - * @var string - * @access private - */ - var $_digits_initialized = false; - - /** - * A flag, that determines if the "and" word is placed already before the last non-empty group of digits. - * @var string - * @access private - */ - var $_last_and = false; - - /** - * The word for zero. - * @var string - * @access private - */ - var $_zero = 'íóëà'; - - /** - * The word for infinity. - * @var string - * @access private - */ - var $_infinity = 'áåçêðàéíîñò'; - - /** - * The word for the "and" language construct. - * @var string - * @access private - */ - var $_and = 'è'; - - /** - * The word separator. - * @var string - * @access private - */ - var $_sep = ' '; - - /** - * The word for the minus sign. - * @var string - * @access private - */ - var $_minus = 'ìèíóñ'; // minus sign - - /** - * The plural suffix (except for thousand). - * @var string - * @access private - */ - var $_plural = 'à'; // plural suffix - - /** - * The suffixes for exponents (singular). - * @var array - * @access private - */ - var $_exponent = array( - 0 => '', - 3 => 'õèëÿäà', - 6 => 'ìèëèîí', - 9 => 'ìèëèàðä', - 12 => 'òðèëèîí', - 15 => 'êâàäðèëèîí', - 18 => 'êâèíòèëèîí', - 21 => 'ñåêñòèëèîí', - 24 => 'ñåïòèëèîí', - 27 => 'îêòèëèîí', - 30 => 'íîíàëèîí', - 33 => 'äåêàëèîí', - 36 => 'óíäåêàëèîí', - 39 => 'äóîäåêàëèîí', - 42 => 'òðåäåêàëèîí', - 45 => 'êâàòîðäåêàëèîí', - 48 => 'êâèíòäåêàëèîí', - 51 => 'ñåêñäåêàëèîí', - 54 => 'ñåïòäåêàëèîí', - 57 => 'îêòîäåêàëèîí', - 60 => 'íîâåìäåêàëèîí', - 63 => 'âèãèíòèëèîí', - 66 => 'óíâèãèíòèëèîí', - 69 => 'äóîâèãèíòèëèîí', - 72 => 'òðåâèãèíòèëèîí', - 75 => 'êâàòîðâèãèíòèëèîí', - 78 => 'êâèíâèãèíòèëèîí', - 81 => 'ñåêñâèãèíòèëèîí', - 84 => 'ñåïòåíâèãèíòèëèîí', - 87 => 'îêòîâèãèíòèëèîí', - 90 => 'íîâåìâèãèíòèëèîí', - 93 => 'òðèãèíòèëèîí', - 96 => 'óíòðèãèíòèëèîí', - 99 => 'äóîòðèãèíòèëèîí', - 102 => 'òðåòðèãèíòèëèîí', - 105 => 'êâàòîðòðèãèíòèëèîí', - 108 => 'êâèíòðèãèíòèëèîí', - 111 => 'ñåêñòðèãèíòèëèîí', - 114 => 'ñåïòåíòðèãèíòèëèîí', - 117 => 'îêòîòðèãèíòèëèîí', - 120 => 'íîâåìòðèãèíòèëèîí', - 123 => 'êâàäðàãèíòèëèîí', - 126 => 'óíêâàäðàãèíòèëèîí', - 129 => 'äóîêâàäðàãèíòèëèîí', - 132 => 'òðåêâàäðàãèíòèëèîí', - 135 => 'êâàòîðêâàäðàãèíòèëèîí', - 138 => 'êâèíêâàäðàãèíòèëèîí', - 141 => 'ñåêñêâàäðàãèíòèëèîí', - 144 => 'ñåïòåíêâàäðàãèíòèëèîí', - 147 => 'îêòîêâàäðàãèíòèëèîí', - 150 => 'íîâåìêâàäðàãèíòèëèîí', - 153 => 'êâèíêâàãèíòèëèîí', - 156 => 'óíêâèíêàãèíòèëèîí', - 159 => 'äóîêâèíêàãèíòèëèîí', - 162 => 'òðåêâèíêàãèíòèëèîí', - 165 => 'êâàòîðêâèíêàãèíòèëèîí', - 168 => 'êâèíêâèíêàãèíòèëèîí', - 171 => 'ñåêñêâèíêàãèíòèëèîí', - 174 => 'ñåïòåíêâèíêàãèíòèëèîí', - 177 => 'îêòîêâèíêàãèíòèëèîí', - 180 => 'íîâåìêâèíêàãèíòèëèîí', - 183 => 'ñåêñàãèíòèëèîí', - 186 => 'óíñåêñàãèíòèëèîí', - 189 => 'äóîñåêñàãèíòèëèîí', - 192 => 'òðåñåêñàãèíòèëèîí', - 195 => 'êâàòîðñåêñàãèíòèëèîí', - 198 => 'êâèíñåêñàãèíòèëèîí', - 201 => 'ñåêññåêñàãèíòèëèîí', - 204 => 'ñåïòåíñåêñàãèíòèëèîí', - 207 => 'îêòîñåêñàãèíòèëèîí', - 210 => 'íîâåìñåêñàãèíòèëèîí', - 213 => 'ñåïòàãèíòèëèîí', - 216 => 'óíñåïòàãèíòèëèîí', - 219 => 'äóîñåïòàãèíòèëèîí', - 222 => 'òðåñåïòàãèíòèëèîí', - 225 => 'êâàòîðñåïòàãèíòèëèîí', - 228 => 'êâèíñåïòàãèíòèëèîí', - 231 => 'ñåêññåïòàãèíòèëèîí', - 234 => 'ñåïòåíñåïòàãèíòèëèîí', - 237 => 'îêòîñåïòàãèíòèëèîí', - 240 => 'íîâåìñåïòàãèíòèëèîí', - 243 => 'îêòîãèíòèëèîí', - 246 => 'óíîêòîãèíòèëèîí', - 249 => 'äóîîêòîãèíòèëèîí', - 252 => 'òðåîêòîãèíòèëèîí', - 255 => 'êâàòîðîêòîãèíòèëèîí', - 258 => 'êâèíîêòîãèíòèëèîí', - 261 => 'ñåêñîêòîãèíòèëèîí', - 264 => 'ñåïòîêòîãèíòèëèîí', - 267 => 'îêòîîêòîãèíòèëèîí', - 270 => 'íîâåìîêòîãèíòèëèîí', - 273 => 'íîíàãèíòèëèîí', - 276 => 'óííîíàãèíòèëèîí', - 279 => 'äóîíîíàãèíòèëèîí', - 282 => 'òðåíîíàãèíòèëèîí', - 285 => 'êâàòîðíîíàãèíòèëèîí', - 288 => 'êâèííîíàãèíòèëèîí', - 291 => 'ñåêñíîíàãèíòèëèîí', - 294 => 'ñåïòåííîíàãèíòèëèîí', - 297 => 'îêòîíîíàãèíòèëèîí', - 300 => 'íîâåìíîíàãèíòèëèîí', - 303 => 'öåíòèëèîí' - ); - // }}} - - // {{{ Numbers_Words_bg() - - /** - * The class constructor, used for calling the _initDigits method. - * - * @return void - * - * @access public - * @author Kouber Saparev - * @see function _initDigits - */ - function Numbers_Words_bg() { - $this->_initDigits(); - } - // }}} - - // {{{ _initDigits() - - /** - * Fills the _digits array for masculine and feminine genders with - * corresponding references to neuter words (when they're the same). - * - * @return void - * - * @access private - * @author Kouber Saparev - */ - function _initDigits() { - if (!$this->_digits_initialized) { - for ($i=3; $i<=9; $i++) { - $this->_digits[1][$i] =& $this->_digits[0][$i]; - } - for ($i=2; $i<=9; $i++) { - $this->_digits[-1][$i] =& $this->_digits[0][$i]; - } - $this->_digits_initialized = true; - } - } - // }}} - - // {{{ _splitNumber() - - /** - * Split a number to groups of three-digit numbers. - * - * @param mixed $num An integer or its string representation - * that need to be split - * - * @return array Groups of three-digit numbers. - * - * @access private - * @author Kouber Saparev - * @since PHP 4.2.3 - */ - - function _splitNumber($num) - { - if (is_string($num)) { - $ret = array(); - $strlen = strlen($num); - $first = substr($num, 0, $strlen%3); - preg_match_all('/\d{3}/', substr($num, $strlen%3, $strlen), $m); - $ret =& $m[0]; - if ($first) array_unshift($ret, $first); - return $ret; - } - else - return explode(' ', number_format($num, 0, '', ' ')); // a faster version for integers - } - // }}} - - // {{{ _showDigitsGroup() - - /** - * Converts a three-digit number to its word representation - * in Bulgarian language. - * - * @param integer $num An integer between 1 and 999 inclusive. - * - * @param integer $gender An integer which represents the gender of - * the current digits group. - * 0 - neuter - * 1 - masculine - * -1 - feminine - * - * @param boolean $last A flag that determines if the current digits group - * is the last one. - * - * @return string The words for the given number. - * - * @access private - * @author Kouber Saparev - */ - function _showDigitsGroup($num, $gender = 0, $last = false) - { - /* A storage array for the return string. - Positions 1, 3, 5 are intended for digit words - and everything else (0, 2, 4) for "and" words. - Both of the above types are optional, so the size of - the array may vary. - */ - $ret = array(); - - // extract the value of each digit from the three-digit number - $e = $num%10; // ones - $d = ($num-$e)%100/10; // tens - $s = ($num-$d*10-$e)%1000/100; // hundreds - - // process the "hundreds" digit. - if ($s) { - switch ($s) { - case 1: - $ret[1] = $this->_misc_strings['sto']; - break; - case 2: - case 3: - $ret[1] = $this->_digits[0][$s].$this->_misc_strings['sta']; - break; - default: - $ret[1] = $this->_digits[0][$s].$this->_misc_strings['stotin']; - } - } - - // process the "tens" digit, and optionally the "ones" digit. - if ($d) { - // in the case of 1, the "ones" digit also must be processed - if ($d==1) { - if (!$e) { - $ret[3] = $this->_misc_strings['deset']; // ten - } else { - if ($e==1) { - $ret[3] = $this->_misc_strings['edinadeset']; // eleven - } else { - $ret[3] = $this->_digits[1][$e].$this->_misc_strings['na'].$this->_misc_strings['deset']; // twelve - nineteen - } - // the "ones" digit is alredy processed, so skip a second processment - $e = 0; - } - } else { - $ret[3] = $this->_digits[1][$d].$this->_misc_strings['deset']; // twenty - ninety - } - } - - // process the "ones" digit - if ($e) { - $ret[5] = $this->_digits[$gender][$e]; - } - - // put "and" where needed - if (count($ret)>1) { - if ($e) { - $ret[4] = $this->_and; - } else { - $ret[2] = $this->_and; - } - } - - // put "and" optionally in the case this is the last non-empty group - if ($last) { - if (!$s||count($ret)==1) { - $ret[0] = $this->_and; - } - $this->_last_and = true; - } - - // sort the return array so that "and" constructs go to theirs appropriate places - ksort($ret); - - return implode($this->_sep, $ret); - } - // }}} - - // {{{ toWords() - - /** - * Converts a number to its word representation - * in Bulgarian language. - * - * @param integer $num An integer between 9.99*-10^302 and 9.99*10^302 (999 centillions) - * that need to be converted to words - * - * @return string The corresponding word representation - * - * @access public - * @author Kouber Saparev - */ - function toWords($num = 0) - { - $ret = array(); - $ret_minus = ''; - - // check if $num is a valid non-zero number - if (!$num || preg_match('/^-?0+$/', $num) || !preg_match('/^-?\d+$/', $num)) return $this->_zero; - - // add a minus sign - if (substr($num, 0, 1) == '-') { - $ret_minus = $this->_minus . $this->_sep; - $num = substr($num, 1); - } - - // if the absolute value is greater than 9.99*10^302, return infinity - if (strlen($num)>306) { - return $ret_minus . $this->_infinity; - } - - // strip excessive zero signs - $num = ltrim($num, '0'); - - // split $num to groups of three-digit numbers - $num_groups = $this->_splitNumber($num); - - $sizeof_numgroups = count($num_groups); - - // go through the groups in reverse order, so that the last group could be determined - for ($i=$sizeof_numgroups-1, $j=1; $i>=0; $i--, $j++) { - if (!isset($ret[$j])) { - $ret[$j] = ''; - } - - // what is the corresponding exponent for the current group - $pow = $sizeof_numgroups-$i; - - // skip processment for empty groups - if ($num_groups[$i]!='000') { - if ($num_groups[$i]>1) { - if ($pow==1) { - $ret[$j] .= $this->_showDigitsGroup($num_groups[$i], 0, !$this->_last_and && $i).$this->_sep; - $ret[$j] .= $this->_exponent[($pow-1)*3]; - } elseif ($pow==2) { - $ret[$j] .= $this->_showDigitsGroup($num_groups[$i], -1, !$this->_last_and && $i).$this->_sep; - $ret[$j] .= $this->_misc_strings['hiliadi'].$this->_sep; - } else { - $ret[$j] .= $this->_showDigitsGroup($num_groups[$i], 1, !$this->_last_and && $i).$this->_sep; - $ret[$j] .= $this->_exponent[($pow-1)*3].$this->_plural.$this->_sep; - } - } else { - if ($pow==1) { - $ret[$j] .= $this->_showDigitsGroup($num_groups[$i], 0, !$this->_last_and && $i).$this->_sep; - } elseif ($pow==2) { - $ret[$j] .= $this->_exponent[($pow-1)*3].$this->_sep; - } else { - $ret[$j] .= $this->_digits[1][1].$this->_sep.$this->_exponent[($pow-1)*3].$this->_sep; - } - } - } - } - - return $ret_minus . rtrim(implode('', array_reverse($ret)), $this->_sep); - } - // }}} -} -?> diff --git a/gulliver/thirdparty/pear/Numbers/Words/lang.de.php b/gulliver/thirdparty/pear/Numbers/Words/lang.de.php deleted file mode 100644 index 5d6026d26..000000000 --- a/gulliver/thirdparty/pear/Numbers/Words/lang.de.php +++ /dev/null @@ -1,318 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: lang.de.php,v 1.5 2003/09/29 12:23:58 makler Exp $ -// -// Numbers_Words class extension to spell numbers in German language. -// - -/** - * - * Class for translating numbers into German. - * @author Piotr Klaban - * @package Numbers_Words - */ - -/** - * Include needed files - */ -require_once("Numbers/Words.php"); - -/** - * Class for translating numbers into German. - * - * @author Piotr Klaban - * @package Numbers_Words - */ -class Numbers_Words_de extends Numbers_Words -{ - - // {{{ properties - - /** - * Locale name - * @var string - * @access public - */ - var $locale = 'de'; - - /** - * Language name in English - * @var string - * @access public - */ - var $lang = 'German'; - - /** - * Native language name - * @var string - * @access public - */ - var $lang_native = 'Deutsch'; - - /** - * The word for the minus sign - * @var string - * @access private - */ - var $_minus = 'Minus'; // minus sign - - /** - * The sufixes for exponents (singular and plural) - * Names partly based on: - * http://german.about.com/library/blzahlenaud.htm - * http://www3.osk.3web.ne.jp/~nagatani/common/zahlwort.htm - * @var array - * @access private - */ - var $_exponent = array( - 0 => array(''), - 3 => array('tausend','tausend'), - 6 => array('Millione','Millionen'), - 9 => array('Milliarde','Milliarden'), - 12 => array('Billion','Billionen'), - 15 => array('Billiarde','Billiarden'), - 18 => array('Trillion','Trillionen'), - 21 => array('Trilliarde','Trilliarden'), - 24 => array('Quadrillion','Quadrillionen'), - 27 => array('Quadrilliarde','Quadrilliarden'), - 30 => array('Quintillion','Quintillionen'), - 33 => array('Quintilliarde','Quintilliarden'), - 36 => array('Sextillion','Sextillionen'), - 39 => array('Sextilliarde','Sextilliarden'), - 42 => array('Septillion','Septillionen'), - 45 => array('Septilliarde','Septilliarden'), - 48 => array('Oktillion','Oktillionen'), // oder Octillionen - 51 => array('Oktilliarde','Oktilliarden'), - 54 => array('Nonillion','Nonillionen'), - 57 => array('Nonilliarde','Nonilliarden'), - 60 => array('Dezillion','Dezillionen'), - 63 => array('Dezilliarde','Dezilliarden'), - 120 => array('Vigintillion','Vigintillionen'), - 123 => array('Vigintilliarde','Vigintilliarden'), - 600 => array('Zentillion','Zentillionen'), // oder Centillion - 603 => array('Zentilliarde','Zentilliarden') - ); - - /** - * The array containing the digits (indexed by the digits themselves). - * @var array - * @access private - */ - var $_digits = array( - 0 => 'null', 'ein', 'zwei', 'drei', 'vier', - 'fünf', 'sechs', 'sieben', 'acht', 'neun' - ); - - /** - * The word separator - * @var string - * @access private - */ - var $_sep = ''; - - /** - * The exponent word separator - * @var string - * @access private - */ - var $_sep2 = ' '; - - // }}} - // {{{ toWords() - - /** - * Converts a number to its word representation - * in German language. - * - * @param integer $num An integer between -infinity and infinity inclusive :) - * that need to be converted to words - * @param integer $power The power of ten for the rest of the number to the right. - * Optional, defaults to 0. - * @param integer $powsuffix The power name to be added to the end of the return string. - * Used internally. Optional, defaults to ''. - * - * @return string The corresponding word representation - * - * @access private - * @author Piotr Klaban - * @since PHP 4.2.3 - */ - function toWords($num, $power = 0, $powsuffix = '') { - $ret = ''; - - // add a minus sign - if (substr($num, 0, 1) == '-') { - $ret = $this->_sep . $this->_minus; - $num = substr($num, 1); - } - - // strip excessive zero signs and spaces - $num = trim($num); - $num = preg_replace('/^0+/','',$num); - - if (strlen($num) > 3) { - $maxp = strlen($num)-1; - $curp = $maxp; - for ($p = $maxp; $p > 0; --$p) { // power - - // check for highest power - if (isset($this->_exponent[$p])) { - // send substr from $curp to $p - $snum = substr($num, $maxp - $curp, $curp - $p + 1); - $snum = preg_replace('/^0+/','',$snum); - if ($snum !== '') { - $cursuffix = $this->_exponent[$power][count($this->_exponent[$power])-1]; - if ($powsuffix != '') - $cursuffix .= $this->_sep . $powsuffix; - $ret .= $this->toWords($snum, $p, $cursuffix); - } - $curp = $p - 1; - continue; - } - } - $num = substr($num, $maxp - $curp, $curp - $p + 1); - if ($num == 0) { - return $ret; - } - } elseif ($num == 0 || $num == '') { - return $this->_sep . $this->_digits[0]; - } - - $h = $t = $d = 0; - - switch(strlen($num)) { - case 3: - $h = (int)substr($num,-3,1); - - case 2: - $t = (int)substr($num,-2,1); - - case 1: - $d = (int)substr($num,-1,1); - break; - - case 0: - return; - break; - } - - if ($h) { - - $ret .= $this->_sep . $this->_digits[$h] . $this->_sep . 'hundert'; - } - - if ($t != 1 && $d > 0) { // add digits only in <0>,<1,9> and <21,inf> - if ($t > 0) { - $ret .= $this->_digits[$d] . 'und'; - } else { - $ret .= $this->_digits[$d]; - if ($d == 1) - if ($power == 0) - $ret .= 's'; // fuer eins - else - $ret .= 'e'; // fuer eine - } - } - - // ten, twenty etc. - switch ($t) { - case 9: - case 8: - case 5: - $ret .= $this->_sep . $this->_digits[$t] . 'zig'; - break; - - case 7: - $ret .= $this->_sep . 'siebzig'; - break; - - case 6: - $ret .= $this->_sep . 'sechzig'; - break; - - case 4: - $ret .= $this->_sep . 'vierzig'; - break; - - case 3: - $ret .= $this->_sep . 'dreißig'; - break; - - case 2: - $ret .= $this->_sep . 'zwanzig'; - break; - - case 1: - switch ($d) { - case 0: - $ret .= $this->_sep . 'zehn'; - break; - - case 1: - $ret .= $this->_sep . 'elf'; - break; - - case 2: - $ret .= $this->_sep . 'zwölf'; - break; - - case 3: - case 4: - case 5: - case 8: - case 9: - $ret .= $this->_sep . $this->_digits[$d] . 'zehn'; - break; - - case 6: - $ret .= $this->_sep . 'sechzehn'; - break; - - case 7: - $ret .= $this->_sep . 'siebzehn'; - break; - } - break; - } - - if ($power > 0) { - if (isset($this->_exponent[$power])) - $lev = $this->_exponent[$power]; - - if (!isset($lev) || !is_array($lev)) - return null; - - if ($power == 3) - $ret .= $this->_sep . $lev[0]; - elseif ($d == 1 && ($t+$h) == 0) - $ret .= $this->_sep2 . $lev[0] . $this->_sep2; - else - $ret .= $this->_sep2 . $lev[1] . $this->_sep2; - } - - if ($powsuffix != '') - $ret .= $this->_sep . $powsuffix; - - return $ret; - } - // }}} -} - -?> diff --git a/gulliver/thirdparty/pear/Numbers/Words/lang.ee.php b/gulliver/thirdparty/pear/Numbers/Words/lang.ee.php deleted file mode 100644 index 2b27d1f1e..000000000 --- a/gulliver/thirdparty/pear/Numbers/Words/lang.ee.php +++ /dev/null @@ -1,349 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: lang.ee.php,v 1.5 2003/09/29 12:23:58 makler Exp $ -// -// Numbers_Words class extension to spell numbers in Estonian language. -// - -/** - * Class for translating numbers into Estonian. - * - * @author Erkki Saarniit - * @package Numbers_Words - */ - -/** - * Include needed files - */ -require_once("Numbers/Words.php"); - -/** - * Class for translating numbers into Estonian. - * - * @author Erkki Saarniit - * @package Numbers_Words - */ -class Numbers_Words_ee extends Numbers_Words -{ - - // {{{ properties - - /** - * Locale name - * @var string - * @access public - */ - var $locale = 'ee'; - - /** - * Language name in English - * @var string - * @access public - */ - var $lang = 'Estonian'; - - /** - * Native language name - * @var string - * @access public - */ - var $lang_native = 'eesti keel'; - - /** - * The word for the minus sign - * @var string - * @access private - */ - var $_minus = 'miinus'; // minus sign - - /** - * The sufixes for exponents (singular and plural) - * Names partly based on: - * http://home.earthlink.net/~mrob/pub/math/largenum.html - * http://mathforum.org/dr.math/faq/faq.large.numbers.html - * http://www.mazes.com/AmericanNumberingSystem.html - * @var array - * @access private - */ - var $_exponent = array( - 0 => array(''), - 3 => array('tuhat'), - 6 => array('miljon'), - 9 => array('miljard'), - 12 => array('triljon'), - 15 => array('kvadriljon'), - 18 => array('kvintiljon'), - 21 => array('sekstiljon'), - 24 => array('septiljon'), - 27 => array('oktiljon'), - 30 => array('noniljon'), - 33 => array('dekiljon'), - 36 => array('undekiljon'), - 39 => array('duodekiljon'), - 42 => array('tredekiljon'), - 45 => array('kvattuordekiljon'), - 48 => array('kvindekiljon'), - 51 => array('seksdekiljon'), - 54 => array('septendekiljon'), - 57 => array('oktodekiljon'), - 60 => array('novemdekiljon'), - 63 => array('vigintiljon'), - 66 => array('unvigintiljon'), - 69 => array('duovigintiljon'), - 72 => array('trevigintiljon'), - 75 => array('kvattuorvigintiljon'), - 78 => array('kvinvigintiljon'), - 81 => array('seksvigintiljon'), - 84 => array('septenvigintiljon'), - 87 => array('oktovigintiljon'), - 90 => array('novemvigintiljon'), - 93 => array('trigintiljon'), - 96 => array('untrigintiljon'), - 99 => array('duotrigintiljon'), - 102 => array('trestrigintiljon'), - 105 => array('kvattuortrigintiljon'), - 108 => array('kvintrigintiljon'), - 111 => array('sekstrigintiljon'), - 114 => array('septentrigintiljon'), - 117 => array('oktotrigintiljon'), - 120 => array('novemtrigintiljon'), - 123 => array('kvadragintiljon'), - 126 => array('unkvadragintiljon'), - 129 => array('duokvadragintiljon'), - 132 => array('trekvadragintiljon'), - 135 => array('kvattuorkvadragintiljon'), - 138 => array('kvinkvadragintiljon'), - 141 => array('sekskvadragintiljon'), - 144 => array('septenkvadragintiljon'), - 147 => array('oktokvadragintiljon'), - 150 => array('novemkvadragintiljon'), - 153 => array('kvinkvagintiljon'), - 156 => array('unkvinkvagintiljon'), - 159 => array('duokvinkvagintiljon'), - 162 => array('trekvinkvagintiljon'), - 165 => array('kvattuorkvinkvagintiljon'), - 168 => array('kvinkvinkvagintiljon'), - 171 => array('sekskvinkvagintiljon'), - 174 => array('septenkvinkvagintiljon'), - 177 => array('oktokvinkvagintiljon'), - 180 => array('novemkvinkvagintiljon'), - 183 => array('seksagintiljon'), - 186 => array('unseksagintiljon'), - 189 => array('duoseksagintiljon'), - 192 => array('treseksagintiljon'), - 195 => array('kvattuorseksagintiljon'), - 198 => array('kvinseksagintiljon'), - 201 => array('seksseksagintiljon'), - 204 => array('septenseksagintiljon'), - 207 => array('oktoseksagintiljon'), - 210 => array('novemseksagintiljon'), - 213 => array('septuagintiljon'), - 216 => array('unseptuagintiljon'), - 219 => array('duoseptuagintiljon'), - 222 => array('treseptuagintiljon'), - 225 => array('kvattuorseptuagintiljon'), - 228 => array('kvinseptuagintiljon'), - 231 => array('seksseptuagintiljon'), - 234 => array('septenseptuagintiljon'), - 237 => array('oktoseptuagintiljon'), - 240 => array('novemseptuagintiljon'), - 243 => array('oktogintiljon'), - 246 => array('unoktogintiljon'), - 249 => array('duooktogintiljon'), - 252 => array('treoktogintiljon'), - 255 => array('kvattuoroktogintiljon'), - 258 => array('kvinoktogintiljon'), - 261 => array('seksoktogintiljon'), - 264 => array('septoktogintiljon'), - 267 => array('oktooktogintiljon'), - 270 => array('novemoktogintiljon'), - 273 => array('nonagintiljon'), - 276 => array('unnonagintiljon'), - 279 => array('duononagintiljon'), - 282 => array('trenonagintiljon'), - 285 => array('kvattuornonagintiljon'), - 288 => array('kvinnonagintiljon'), - 291 => array('seksnonagintiljon'), - 294 => array('septennonagintiljon'), - 297 => array('oktononagintiljon'), - 300 => array('novemnonagintiljon'), - 303 => array('kentiljon'), - 309 => array('duokentiljon'), - 312 => array('trekentiljon'), - 366 => array('primo-vigesimo-kentiljon'), - 402 => array('trestrigintakentiljon'), - 603 => array('dukentiljon'), - 624 => array('septendukentiljon'), - 2421 => array('seksoktingentiljon'), - 3003 => array('milliljon'), - 3000003 => array('milli-milliljon') - ); - - /** - * The array containing the digits (indexed by the digits themselves). - * @var array - * @access private - */ - var $_digits = array( - 0 => 'null', 'üks', 'kaks', 'kolm', 'neli', - 'viis', 'kuus', 'seitse', 'kaheksa', 'üheksa' - ); - - /** - * The word separator - * @var string - * @access private - */ - var $_sep = ' '; - - // }}} - // {{{ toWords() - - /** - * Converts a number to its word representation - * in Estonian language - * - * @param integer $num An integer between -infinity and infinity inclusive :) - * that need to be converted to words - * @param integer $power The power of ten for the rest of the number to the right. - * Optional, defaults to 0. - * @param integer $powsuffix The power name to be added to the end of the return string. - * Used internally. Optional, defaults to ''. - * - * @return string The corresponding word representation - * - * @access public - * @since PHP 4.2.3 - */ - function toWords($num, $power = 0, $powsuffix = '') { - $ret = ''; - - if (substr($num, 0, 1) == '-') { - $ret = $this->_sep . $this->_minus; - $num = substr($num, 1); - } - - $num = trim($num); - $num = preg_replace('/^0+/','',$num); - - if (strlen($num) > 3) { - $maxp = strlen($num)-1; - $curp = $maxp; - for ($p = $maxp; $p > 0; --$p) { // power - if (isset($this->_exponent[$p])) { - $snum = substr($num, $maxp - $curp, $curp - $p + 1); - $snum = preg_replace('/^0+/','',$snum); - if ($snum !== '') { - $cursuffix = $this->_exponent[$power][count($this->_exponent[$power])-1]; - if ($powsuffix != '') - $cursuffix .= $this->_sep . $powsuffix; - $ret .= $this->toWords($snum, $p, $cursuffix); - } - $curp = $p - 1; - continue; - } - } - $num = substr($num, $maxp - $curp, $curp - $p + 1); - if ($num == 0) { - return $ret; - } - } elseif ($num == 0 || $num == '') { - return $this->_sep . $this->_digits[0]; - } - - $h = $t = $d = 0; - - switch(strlen($num)) { - case 3: - $h = (int)substr($num,-3,1); - - case 2: - $t = (int)substr($num,-2,1); - - case 1: - $d = (int)substr($num,-1,1); - break; - - case 0: - return; - break; - } - - if ($h) { - $ret .= $this->_sep . $this->_digits[$h] . 'sada'; - - } - - switch ($t) { - case 9: - case 8: - case 7: - case 6: - case 5: - case 4: - case 3: - case 2: - $ret .= $this->_sep . $this->_digits[$t] . 'kümmend'; - break; - - case 1: - switch ($d) { - case 0: - $ret .= $this->_sep . 'kümme'; - break; - - case 1: - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - case 8: - case 9: - $ret .= $this->_sep . $this->_digits[$d] . 'teist'; - break; - } - break; - } - if ($t != 1 && $d > 0) { - if ($t > 1) { - $ret .= ' ' . $this->_digits[$d]; - } else { - $ret .= $this->_sep . $this->_digits[$d]; - } - } - if ($power > 0) { - if (isset($this->_exponent[$power])) - $lev = $this->_exponent[$power]; - - if (!isset($lev) || !is_array($lev)) - return null; - $ret .= $this->_sep . $lev[0].($num != 1 && $power!= 3 ? 'it' : ''); - } - if ($powsuffix != '') - $ret .= $this->_sep . $powsuffix; - - return $ret; - } - // }}} -} - -?> diff --git a/gulliver/thirdparty/pear/Numbers/Words/lang.en_100.php b/gulliver/thirdparty/pear/Numbers/Words/lang.en_100.php deleted file mode 100644 index 0032622ac..000000000 --- a/gulliver/thirdparty/pear/Numbers/Words/lang.en_100.php +++ /dev/null @@ -1,307 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: lang.en_100.php,v 1.6 2003/09/29 12:23:58 makler Exp $ -// -// Numbers_Words class extension to spell numbers in Donald Knuth system, in English language. -// - -/** - * Class for translating numbers into Donald Knuth system, in English language. - * - * @author Piotr Klaban - * @package Numbers_Words - */ - -/** - * Include needed files - */ -require_once("Numbers/Words.php"); - -/** - * Class for translating numbers into Donald Knuth system, in English language. - * - * @author Piotr Klaban - * @package Numbers_Words - */ -class Numbers_Words_en_100 extends Numbers_Words -{ - - // {{{ properties - - /** - * Locale name - * @var string - * @access public - */ - var $locale = 'en_100'; - - /** - * Language name in English - * @var string - * @access public - */ - var $lang = 'English (Donald Knuth system)'; - - /** - * Native language name - * @var string - * @access public - */ - var $lang_native = 'English (Donald Knuth system)'; - - /** - * The word for the minus sign - * @var string - * @access private - */ - var $_minus = 'minus'; // minus sign - - /** - * The sufixes for exponents (singular and plural) - * Names based on: - * http://home.earthlink.net/~mrob/pub/math/largenum.html - * Donald Knuth system (power of 2) - * @var array - * @access private - */ - var $_exponent = array( - 0 => array(''), - 2 => array('hundred'), - 4 => array('myriad'), - 8 => array('myllion'), - 16 => array('byllion'), - 32 => array('tryllion'), - 64 => array('quadryllion'), - 128 => array('quintyllion'), - 256 => array('sextyllion'), - 512 => array('septyllion'), - 1024 => array('octyllion'), - 2048 => array('nonyllion'), - 4096 => array('decyllion'), - 8192 => array('undecyllion'), - 16384 => array('duodecyllion'), - 32768 => array('tredecyllion'), - 65536 => array('quattuordecyllion'), - 131072 => array('quindecyllion'), - 262144 => array('sexdecyllion'), - 524288 => array('septendecyllion'), - 1048576 => array('octodecyllion'), - 2097152 => array('novemdecyllion'), - 4194304 => array('vigintyllion') - ); - - /** - * The array containing the digits (indexed by the digits themselves). - * @var array - * @access private - */ - var $_digits = array( - 0 => 'zero', 'one', 'two', 'three', 'four', - 'five', 'six', 'seven', 'eight', 'nine' - ); - - /** - * The word separator - * @var string - * @access private - */ - var $_sep = ' '; - // }}} - // {{{ toWords() - /** - * Converts a number to its word representation - * in Donald Knuth system, in English language. - * - * @param integer $num An integer between -infinity and infinity inclusive :) - * that need to be converted to words - * @param integer $power The power of ten for the rest of the number to the right. - * Optional, defaults to 0. - * @param integer $powsuffix The power name to be added to the end of the return string. - * Used internally. Optional, defaults to ''. - * - * @return string The corresponding word representation - * - * @access public - * @author Piotr Klaban - * @since PHP 4.2.3 - */ - function toWords($num, $power = 0, $powsuffix = '') { - $ret = ''; - - // add a minus sign - if (substr($num, 0, 1) == '-') { - $ret = $this->_sep . $this->_minus; - $num = substr($num, 1); - } - - // strip excessive zero signs and spaces - $num = trim($num); - $num = preg_replace('/^0+/','',$num); - - if (strlen($num) > 3) { - $maxp = strlen($num)-1; - $curp = $maxp; - for ($p = $maxp; $p > 0; --$p) { // power - - // check for highest power - if (isset($this->_exponent[$p])) { - // send substr from $curp to $p - $snum = substr($num, $maxp - $curp, $curp - $p + 1); - $snum = preg_replace('/^0+/','',$snum); - if ($snum !== '') { - $cursuffix = $this->_exponent[$power][count($this->_exponent[$power])-1]; - if ($powsuffix != '') - $cursuffix .= $this->_sep . $powsuffix; - $ret .= $this->toWords($snum, $p, ''); // $cursuffix); - // normally cursuffix is added at the end, but not here - } - $curp = $p - 1; - continue; - } - } - $num = substr($num, $maxp - $curp, $curp - $p + 1); - if ($num == 0) { - return $ret; - } - } elseif ($num == 0 || $num == '') { - return $this->_sep . $this->_digits[0]; - } - - $h = $t = $d = 0; - - switch(strlen($num)) { - case 3: - $h = (int)substr($num,-3,1); - - case 2: - $t = (int)substr($num,-2,1); - - case 1: - $d = (int)substr($num,-1,1); - break; - - case 0: - return; - break; - } - - if ($h) { - $ret .= $this->_sep . $this->_digits[$h] . $this->_sep . 'hundred'; - - // in English only - add ' and' for [1-9]01..[1-9]99 - // (also for 1001..1099, 10001..10099 but it is harder) - // for now it is switched off, maybe some language purists - // can force me to enable it, or to remove it completely - // if (($t + $d) > 0) - // $ret .= $this->_sep . 'and'; - } - - // ten, twenty etc. - switch ($t) { - case 9: - case 7: - case 6: - $ret .= $this->_sep . $this->_digits[$t] . 'ty'; - break; - - case 8: - $ret .= $this->_sep . 'eighty'; - break; - - case 5: - $ret .= $this->_sep . 'fifty'; - break; - - case 4: - $ret .= $this->_sep . 'forty'; - break; - - case 3: - $ret .= $this->_sep . 'thirty'; - break; - - case 2: - $ret .= $this->_sep . 'twenty'; - break; - - case 1: - switch ($d) { - case 0: - $ret .= $this->_sep . 'ten'; - break; - - case 1: - $ret .= $this->_sep . 'eleven'; - break; - - case 2: - $ret .= $this->_sep . 'twelve'; - break; - - case 3: - $ret .= $this->_sep . 'thirteen'; - break; - - case 4: - case 6: - case 7: - case 9: - $ret .= $this->_sep . $this->_digits[$d] . 'teen'; - break; - - case 5: - $ret .= $this->_sep . 'fifteen'; - break; - - case 8: - $ret .= $this->_sep . 'eighteen'; - break; - } - break; - } - - if ($t != 1 && $d > 0) { // add digits only in <0>,<1,9> and <21,inf> - // add minus sign between [2-9] and digit - if ($t > 1) { - $ret .= '-' . $this->_digits[$d]; - } else { - $ret .= $this->_sep . $this->_digits[$d]; - } - } - - if ($power > 0) { - if (isset($this->_exponent[$power])) - $lev = $this->_exponent[$power]; - - if (!isset($lev) || !is_array($lev)) - return null; - - $ret .= $this->_sep . $lev[0]; - } - - if ($powsuffix != '') - $ret .= $this->_sep . $powsuffix; - - return $ret; - } - // }}} -} - -?> diff --git a/gulliver/thirdparty/pear/Numbers/Words/lang.en_GB.php b/gulliver/thirdparty/pear/Numbers/Words/lang.en_GB.php deleted file mode 100644 index 961aed54b..000000000 --- a/gulliver/thirdparty/pear/Numbers/Words/lang.en_GB.php +++ /dev/null @@ -1,308 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: lang.en_GB.php,v 1.7 2003/09/29 12:23:58 makler Exp $ -// -// Numbers_Words class extension to spell numbers in British English language. -// - -/** - * Class for translating numbers into British English. - * - * @author Piotr Klaban - * @package Numbers_Words - */ - -/** - * Include needed files - */ -require_once("Numbers/Words.php"); - -/** - * Class for translating numbers into British English. - * - * @author Piotr Klaban - * @package Numbers_Words - */ -class Numbers_Words_en_GB extends Numbers_Words -{ - - // {{{ properties - - /** - * Locale name - * @var string - * @access public - */ - var $locale = 'en_GB'; - - /** - * Language name in English - * @var string - * @access public - */ - var $lang = 'British English'; - - /** - * Native language name - * @var string - * @access public - */ - var $lang_native = 'British English'; - - /** - * The word for the minus sign - * @var string - * @access private - */ - var $_minus = 'minus'; // minus sign - - /** - * The sufixes for exponents (singular and plural) - * Names partly based on: - * http://www.users.dircon.co.uk/~shaunf/shaun/numbers/millions.htm - * @var array - * @access private - */ - var $_exponent = array( - 0 => array(''), - 3 => array('thousand'), - 6 => array('million'), - 12 => array('billion'), - 18 => array('trillion'), - 24 => array('quadrillion'), - 30 => array('quintillion'), - 36 => array('sextillion'), - 42 => array('septillion'), - 48 => array('octillion'), - 54 => array('nonillion'), - 60 => array('decillion'), - 66 => array('undecillion'), - 72 => array('duodecillion'), - 78 => array('tredecillion'), - 84 => array('quattuordecillion'), - 90 => array('quindecillion'), - 96 => array('sexdecillion'), - 102 => array('septendecillion'), - 108 => array('octodecillion'), - 114 => array('novemdecillion'), - 120 => array('vigintillion'), - 192 => array('duotrigintillion'), - 600 => array('centillion') - ); - - /** - * The array containing the digits (indexed by the digits themselves). - * @var array - * @access private - */ - var $_digits = array( - 0 => 'zero', 'one', 'two', 'three', 'four', - 'five', 'six', 'seven', 'eight', 'nine' - ); - - /** - * The word separator - * @var string - * @access private - */ - var $_sep = ' '; - - // }}} - // {{{ toWords() - - /** - * Converts a number to its word representation - * in British English language - * - * @param integer $num An integer between -infinity and infinity inclusive :) - * that need to be converted to words - * @param integer $power The power of ten for the rest of the number to the right. - * Optional, defaults to 0. - * @param integer $powsuffix The power name to be added to the end of the return string. - * Used internally. Optional, defaults to ''. - * - * @return string The corresponding word representation - * - * @access public - * @author Piotr Klaban - * @since PHP 4.2.3 - */ - function toWords($num, $power = 0, $powsuffix = '') { - $ret = ''; - - // add a minus sign - if (substr($num, 0, 1) == '-') { - $ret = $this->_sep . $this->_minus; - $num = substr($num, 1); - } - - // strip excessive zero signs and spaces - $num = trim($num); - $num = preg_replace('/^0+/','',$num); - - if (strlen($num) > 3) { - $maxp = strlen($num)-1; - $curp = $maxp; - for ($p = $maxp; $p > 0; --$p) { // power - - // check for highest power - if (isset($this->_exponent[$p])) { - // send substr from $curp to $p - $snum = substr($num, $maxp - $curp, $curp - $p + 1); - $snum = preg_replace('/^0+/','',$snum); - if ($snum !== '') { - $cursuffix = $this->_exponent[$power][count($this->_exponent[$power])-1]; - if ($powsuffix != '') - $cursuffix .= $this->_sep . $powsuffix; - $ret .= $this->toWords($snum, $p, $cursuffix); - } - $curp = $p - 1; - continue; - } - } - $num = substr($num, $maxp - $curp, $curp - $p + 1); - if ($num == 0) { - return $ret; - } - } elseif ($num == 0 || $num == '') { - return $this->_sep . $this->_digits[0]; - } - - $h = $t = $d = 0; - - switch(strlen($num)) { - case 3: - $h = (int)substr($num,-3,1); - - case 2: - $t = (int)substr($num,-2,1); - - case 1: - $d = (int)substr($num,-1,1); - break; - - case 0: - return; - break; - } - - if ($h) { - $ret .= $this->_sep . $this->_digits[$h] . $this->_sep . 'hundred'; - - // in English only - add ' and' for [1-9]01..[1-9]99 - // (also for 1001..1099, 10001..10099 but it is harder) - // for now it is switched off, maybe some language purists - // can force me to enable it, or to remove it completely - // if (($t + $d) > 0) - // $ret .= $this->_sep . 'and'; - } - - // ten, twenty etc. - switch ($t) { - case 9: - case 7: - case 6: - $ret .= $this->_sep . $this->_digits[$t] . 'ty'; - break; - - case 8: - $ret .= $this->_sep . 'eighty'; - break; - - case 5: - $ret .= $this->_sep . 'fifty'; - break; - - case 4: - $ret .= $this->_sep . 'forty'; - break; - - case 3: - $ret .= $this->_sep . 'thirty'; - break; - - case 2: - $ret .= $this->_sep . 'twenty'; - break; - - case 1: - switch ($d) { - case 0: - $ret .= $this->_sep . 'ten'; - break; - - case 1: - $ret .= $this->_sep . 'eleven'; - break; - - case 2: - $ret .= $this->_sep . 'twelve'; - break; - - case 3: - $ret .= $this->_sep . 'thirteen'; - break; - - case 4: - case 6: - case 7: - case 9: - $ret .= $this->_sep . $this->_digits[$d] . 'teen'; - break; - - case 5: - $ret .= $this->_sep . 'fifteen'; - break; - - case 8: - $ret .= $this->_sep . 'eighteen'; - break; - } - break; - } - - if ($t != 1 && $d > 0) { // add digits only in <0>,<1,9> and <21,inf> - // add minus sign between [2-9] and digit - if ($t > 1) { - $ret .= '-' . $this->_digits[$d]; - } else { - $ret .= $this->_sep . $this->_digits[$d]; - } - } - - if ($power > 0) { - if (isset($this->_exponent[$power])) - $lev = $this->_exponent[$power]; - - if (!isset($lev) || !is_array($lev)) - return null; - - $ret .= $this->_sep . $lev[0]; - } - - if ($powsuffix != '') - $ret .= $this->_sep . $powsuffix; - - return $ret; - } - // }}} -} - -?> diff --git a/gulliver/thirdparty/pear/Numbers/Words/lang.en_US.php b/gulliver/thirdparty/pear/Numbers/Words/lang.en_US.php deleted file mode 100644 index 47e2f7bfa..000000000 --- a/gulliver/thirdparty/pear/Numbers/Words/lang.en_US.php +++ /dev/null @@ -1,509 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: lang.en_US.php,v 1.7 2003/09/29 12:23:58 makler Exp $ -// -// Numbers_Words class extension to spell numbers in American English language. -// - -/** - * Class for translating numbers into American English. - * - * @author Piotr Klaban - * @package Numbers_Words - */ - -/** - * Include needed files - */ -require_once("Numbers/Words.php"); - -/** - * Class for translating numbers into American English. - * - * @author Piotr Klaban - * @package Numbers_Words - */ -class Numbers_Words_en_US extends Numbers_Words -{ - - // {{{ properties - - /** - * Locale name - * @var string - * @access public - */ - var $locale = 'en_US'; - - /** - * Language name in English - * @var string - * @access public - */ - var $lang = 'American English'; - - /** - * Native language name - * @var string - * @access public - */ - var $lang_native = 'American English'; - - /** - * The word for the minus sign - * @var string - * @access private - */ - var $_minus = 'minus'; // minus sign - - /** - * The sufixes for exponents (singular and plural) - * Names partly based on: - * http://home.earthlink.net/~mrob/pub/math/largenum.html - * http://mathforum.org/dr.math/faq/faq.large.numbers.html - * http://www.mazes.com/AmericanNumberingSystem.html - * @var array - * @access private - */ - var $_exponent = array( - 0 => array(''), - 3 => array('thousand'), - 6 => array('million'), - 9 => array('billion'), - 12 => array('trillion'), - 15 => array('quadrillion'), - 18 => array('quintillion'), - 21 => array('sextillion'), - 24 => array('septillion'), - 27 => array('octillion'), - 30 => array('nonillion'), - 33 => array('decillion'), - 36 => array('undecillion'), - 39 => array('duodecillion'), - 42 => array('tredecillion'), - 45 => array('quattuordecillion'), - 48 => array('quindecillion'), - 51 => array('sexdecillion'), - 54 => array('septendecillion'), - 57 => array('octodecillion'), - 60 => array('novemdecillion'), - 63 => array('vigintillion'), - 66 => array('unvigintillion'), - 69 => array('duovigintillion'), - 72 => array('trevigintillion'), - 75 => array('quattuorvigintillion'), - 78 => array('quinvigintillion'), - 81 => array('sexvigintillion'), - 84 => array('septenvigintillion'), - 87 => array('octovigintillion'), - 90 => array('novemvigintillion'), - 93 => array('trigintillion'), - 96 => array('untrigintillion'), - 99 => array('duotrigintillion'), - // 100 => array('googol') - not latin name - // 10^googol = 1 googolplex - 102 => array('trestrigintillion'), - 105 => array('quattuortrigintillion'), - 108 => array('quintrigintillion'), - 111 => array('sextrigintillion'), - 114 => array('septentrigintillion'), - 117 => array('octotrigintillion'), - 120 => array('novemtrigintillion'), - 123 => array('quadragintillion'), - 126 => array('unquadragintillion'), - 129 => array('duoquadragintillion'), - 132 => array('trequadragintillion'), - 135 => array('quattuorquadragintillion'), - 138 => array('quinquadragintillion'), - 141 => array('sexquadragintillion'), - 144 => array('septenquadragintillion'), - 147 => array('octoquadragintillion'), - 150 => array('novemquadragintillion'), - 153 => array('quinquagintillion'), - 156 => array('unquinquagintillion'), - 159 => array('duoquinquagintillion'), - 162 => array('trequinquagintillion'), - 165 => array('quattuorquinquagintillion'), - 168 => array('quinquinquagintillion'), - 171 => array('sexquinquagintillion'), - 174 => array('septenquinquagintillion'), - 177 => array('octoquinquagintillion'), - 180 => array('novemquinquagintillion'), - 183 => array('sexagintillion'), - 186 => array('unsexagintillion'), - 189 => array('duosexagintillion'), - 192 => array('tresexagintillion'), - 195 => array('quattuorsexagintillion'), - 198 => array('quinsexagintillion'), - 201 => array('sexsexagintillion'), - 204 => array('septensexagintillion'), - 207 => array('octosexagintillion'), - 210 => array('novemsexagintillion'), - 213 => array('septuagintillion'), - 216 => array('unseptuagintillion'), - 219 => array('duoseptuagintillion'), - 222 => array('treseptuagintillion'), - 225 => array('quattuorseptuagintillion'), - 228 => array('quinseptuagintillion'), - 231 => array('sexseptuagintillion'), - 234 => array('septenseptuagintillion'), - 237 => array('octoseptuagintillion'), - 240 => array('novemseptuagintillion'), - 243 => array('octogintillion'), - 246 => array('unoctogintillion'), - 249 => array('duooctogintillion'), - 252 => array('treoctogintillion'), - 255 => array('quattuoroctogintillion'), - 258 => array('quinoctogintillion'), - 261 => array('sexoctogintillion'), - 264 => array('septoctogintillion'), - 267 => array('octooctogintillion'), - 270 => array('novemoctogintillion'), - 273 => array('nonagintillion'), - 276 => array('unnonagintillion'), - 279 => array('duononagintillion'), - 282 => array('trenonagintillion'), - 285 => array('quattuornonagintillion'), - 288 => array('quinnonagintillion'), - 291 => array('sexnonagintillion'), - 294 => array('septennonagintillion'), - 297 => array('octononagintillion'), - 300 => array('novemnonagintillion'), - 303 => array('centillion'), - 309 => array('duocentillion'), - 312 => array('trecentillion'), - 366 => array('primo-vigesimo-centillion'), - 402 => array('trestrigintacentillion'), - 603 => array('ducentillion'), - 624 => array('septenducentillion'), - // bug on a earthlink page: 903 => array('trecentillion'), - 2421 => array('sexoctingentillion'), - 3003 => array('millillion'), - 3000003 => array('milli-millillion') - ); - - /** - * The array containing the digits (indexed by the digits themselves). - * @var array - * @access private - */ - var $_digits = array( - 0 => 'zero', 'one', 'two', 'three', 'four', - 'five', 'six', 'seven', 'eight', 'nine' - ); - - /** - * The word separator - * @var string - * @access private - */ - var $_sep = ' '; - - /** - * The currency names (based on the below links, - * informations from central bank websites and on encyclopedias) - * - * @var array - * @link http://30-03-67.dreamstation.com/currency_alfa.htm World Currency Information - * @link http://www.jhall.demon.co.uk/currency/by_abbrev.html World currencies - * @link http://www.shoestring.co.kr/world/p.visa/change.htm Currency names in English - * @access private - */ - var $_currency_names = array( - 'ALL' => array(array('lek'), array('qindarka')), - 'AUD' => array(array('Australian dollar'), array('cent')), - 'BAM' => array(array('convertible marka'), array('fenig')), - 'BGN' => array(array('lev'), array('stotinka')), - 'BRL' => array(array('real'), array('centavos')), - 'BYR' => array(array('Belarussian rouble'), array('kopiejka')), - 'CAD' => array(array('Canadian dollar'), array('cent')), - 'CHF' => array(array('Swiss franc'), array('rapp')), - 'CYP' => array(array('Cypriot pound'), array('cent')), - 'CZK' => array(array('Czech koruna'), array('halerz')), - 'DKK' => array(array('Danish krone'), array('ore')), - 'EEK' => array(array('kroon'), array('senti')), - 'EUR' => array(array('euro'), array('euro-cent')), - 'GBP' => array(array('pound', 'pounds'), array('pence')), - 'HKD' => array(array('Hong Kong dollar'), array('cent')), - 'HRK' => array(array('Croatian kuna'), array('lipa')), - 'HUF' => array(array('forint'), array('filler')), - 'ISK' => array(array('Icelandic króna'), array('aurar')), - 'JPY' => array(array('yen'), array('sen')), - 'LTL' => array(array('litas'), array('cent')), - 'LVL' => array(array('lat'), array('sentim')), - 'MKD' => array(array('Macedonian dinar'), array('deni')), - 'MTL' => array(array('Maltese lira'), array('centym')), - 'NOK' => array(array('Norwegian krone'), array('oere')), - 'PLN' => array(array('zloty', 'zlotys'), array('grosz')), - 'ROL' => array(array('Romanian leu'), array('bani')), - 'RUB' => array(array('Russian Federation rouble'), array('kopiejka')), - 'SEK' => array(array('Swedish krona'), array('oere')), - 'SIT' => array(array('Tolar'), array('stotinia')), - 'SKK' => array(array('Slovak koruna'), array()), - 'TRL' => array(array('lira'), array('kuruþ')), - 'UAH' => array(array('hryvna'), array('cent')), - 'USD' => array(array('dollar'), array('cent')), - 'YUM' => array(array('dinars'), array('para')), - 'ZAR' => array(array('rand'), array('cent')), - 'MXN' => array(array('Mexican Peso'), array('cent')) - ); - - /** - * The default currency name - * @var string - * @access public - */ - var $def_currency = 'USD'; // Polish zloty - - // }}} - // {{{ toWords() - - /** - * Converts a number to its word representation - * in American English language - * - * @param integer $num An integer between -infinity and infinity inclusive :) - * that need to be converted to words - * @param integer $power The power of ten for the rest of the number to the right. - * Optional, defaults to 0. - * @param integer $powsuffix The power name to be added to the end of the return string. - * Used internally. Optional, defaults to ''. - * - * @return string The corresponding word representation - * - * @access public - * @author Piotr Klaban - * @since PHP 4.2.3 - */ - function toWords($num, $power = 0, $powsuffix = '') { - $ret = ''; - - // add a minus sign - if (substr($num, 0, 1) == '-') { - $ret = $this->_sep . $this->_minus; - $num = substr($num, 1); - } - - // strip excessive zero signs and spaces - $num = trim($num); - $num = preg_replace('/^0+/','',$num); - - if (strlen($num) > 3) { - $maxp = strlen($num)-1; - $curp = $maxp; - for ($p = $maxp; $p > 0; --$p) { // power - - // check for highest power - if (isset($this->_exponent[$p])) { - // send substr from $curp to $p - $snum = substr($num, $maxp - $curp, $curp - $p + 1); - $snum = preg_replace('/^0+/','',$snum); - if ($snum !== '') { - $cursuffix = $this->_exponent[$power][count($this->_exponent[$power])-1]; - if ($powsuffix != '') - $cursuffix .= $this->_sep . $powsuffix; - $ret .= $this->toWords($snum, $p, $cursuffix); - } - $curp = $p - 1; - continue; - } - } - $num = substr($num, $maxp - $curp, $curp - $p + 1); - if ($num == 0) { - return $ret; - } - } elseif ($num == 0 || $num == '') { - return $this->_sep . $this->_digits[0]; - } - - $h = $t = $d = 0; - - switch(strlen($num)) { - case 3: - $h = (int)substr($num,-3,1); - - case 2: - $t = (int)substr($num,-2,1); - - case 1: - $d = (int)substr($num,-1,1); - break; - - case 0: - return; - break; - } - - if ($h) { - $ret .= $this->_sep . $this->_digits[$h] . $this->_sep . 'hundred'; - - // in English only - add ' and' for [1-9]01..[1-9]99 - // (also for 1001..1099, 10001..10099 but it is harder) - // for now it is switched off, maybe some language purists - // can force me to enable it, or to remove it completely - // if (($t + $d) > 0) - // $ret .= $this->_sep . 'and'; - } - - // ten, twenty etc. - switch ($t) { - case 9: - case 7: - case 6: - $ret .= $this->_sep . $this->_digits[$t] . 'ty'; - break; - - case 8: - $ret .= $this->_sep . 'eighty'; - break; - - case 5: - $ret .= $this->_sep . 'fifty'; - break; - - case 4: - $ret .= $this->_sep . 'forty'; - break; - - case 3: - $ret .= $this->_sep . 'thirty'; - break; - - case 2: - $ret .= $this->_sep . 'twenty'; - break; - - case 1: - switch ($d) { - case 0: - $ret .= $this->_sep . 'ten'; - break; - - case 1: - $ret .= $this->_sep . 'eleven'; - break; - - case 2: - $ret .= $this->_sep . 'twelve'; - break; - - case 3: - $ret .= $this->_sep . 'thirteen'; - break; - - case 4: - case 6: - case 7: - case 9: - $ret .= $this->_sep . $this->_digits[$d] . 'teen'; - break; - - case 5: - $ret .= $this->_sep . 'fifteen'; - break; - - case 8: - $ret .= $this->_sep . 'eighteen'; - break; - } - break; - } - - if ($t != 1 && $d > 0) { // add digits only in <0>,<1,9> and <21,inf> - // add minus sign between [2-9] and digit - if ($t > 1) { - $ret .= '-' . $this->_digits[$d]; - } else { - $ret .= $this->_sep . $this->_digits[$d]; - } - } - - if ($power > 0) { - if (isset($this->_exponent[$power])) - $lev = $this->_exponent[$power]; - - if (!isset($lev) || !is_array($lev)) - return null; - - $ret .= $this->_sep . $lev[0]; - } - - if ($powsuffix != '') - $ret .= $this->_sep . $powsuffix; - - return $ret; - } - // }}} - // {{{ toCurrency() - - /** - * Converts a currency value to its word representation - * (with monetary units) in English language - * - * @param integer $int_curr An international currency symbol - * as defined by the ISO 4217 standard (three characters) - * @param integer $decimal A money total amount without fraction part (e.g. amount of dollars) - * @param integer $fraction Fractional part of the money amount (e.g. amount of cents) - * Optional. Defaults to false. - * - * @return string The corresponding word representation for the currency - * - * @access public - * @author Piotr Klaban - * @since Numbers_Words 0.4 - */ - function toCurrencyWords($int_curr, $decimal, $fraction = false) { - $int_curr = strtoupper($int_curr); - if (!isset($this->_currency_names[$int_curr])) { - $int_curr = $this->def_currency; - } - $curr_names = $this->_currency_names[$int_curr]; - $ret = trim($this->toWords($decimal)); - $lev = ($decimal == 1) ? 0 : 1; - if ($lev > 0) { - if (count($curr_names[0]) > 1) { - $ret .= $this->_sep . $curr_names[0][$lev]; - } else { - $ret .= $this->_sep . $curr_names[0][0] . 's'; - } - } else { - $ret .= $this->_sep . $curr_names[0][0]; - } - - if ($fraction !== false) { - $ret .= $this->_sep . trim($this->toWords($fraction)); - $lev = ($fraction == 1) ? 0 : 1; - if ($lev > 0) { - if (count($curr_names[1]) > 1) { - $ret .= $this->_sep . $curr_names[1][$lev]; - } else { - $ret .= $this->_sep . $curr_names[1][0] . 's'; - } - } else { - $ret .= $this->_sep . $curr_names[1][0]; - } - } - return $ret; - } - // }}} - -} - -?> diff --git a/gulliver/thirdparty/pear/Numbers/Words/lang.es.php b/gulliver/thirdparty/pear/Numbers/Words/lang.es.php deleted file mode 100644 index 267937c28..000000000 --- a/gulliver/thirdparty/pear/Numbers/Words/lang.es.php +++ /dev/null @@ -1,343 +0,0 @@ - array('',''), - 3 => array('mil','mil'), - 6 => array('millón','millones'), - 12 => array('billón','billones'), - 18 => array('trilón','trillones'), - 24 => array('cuatrillón','cuatrillones'), - 30 => array('quintillón','quintillones'), - 36 => array('sextillón','sextillones'), - 42 => array('septillón','septillones'), - 48 => array('octallón','octallones'), - 54 => array('nonallón','nonallones'), - 60 => array('decallón','decallones'), - ); - /** - * The array containing the digits (indexed by the digits themselves). - * @var array - * @access private - */ - var $_digits = array( - 0 => 'cero', 'uno', 'dos', 'tres', 'cuatro', - 'cinco', 'seis', 'siete', 'ocho', 'nueve' - ); - /** - * The word separator - * @var string - * @access private - */ - var $_sep = ' '; - // }}} - // {{{ toWords() - /** - * Converts a number to its word representation - * in Spanish (Castellano). - * - * @param integer $num An integer between -infinity and infinity inclusive :) - * that should be converted to a words representation - * @param integer $power The power of ten for the rest of the number to the right. - * For example toWords(12,3) should give "doce mil". - * Optional, defaults to 0. - * @return string The corresponding word representation - * - * @access private - * @author Xavier Noguer - * @since PHP 4.2.3 - */ - function toWords($num, $power = 0) - { - // The return string; - $ret = ''; - - // add a the word for the minus sign if necessary - if (substr($num, 0, 1) == '-') - { - $ret = $this->_sep . $this->_minus; - $num = substr($num, 1); - } - - - // strip excessive zero signs - $num = preg_replace('/^0+/','',$num); - - if (strlen($num) > 6) - { - $current_power = 6; - // check for highest power - if (isset($this->_exponent[$power])) - { - // convert the number above the first 6 digits - // with it's corresponding $power. - $snum = substr($num, 0, -6); - $snum = preg_replace('/^0+/','',$snum); - if ($snum !== '') { - $ret .= $this->toWords($snum, $power + 6); - } - } - $num = substr($num, -6); - if ($num == 0) { - return $ret; - } - } - elseif ($num == 0 || $num == '') { - return(' '.$this->_digits[0]); - $current_power = strlen($num); - } - else { - $current_power = strlen($num); - } - - // See if we need "thousands" - $thousands = floor($num / 1000); - if ($thousands == 1) { - $ret .= $this->_sep . 'mil'; - } - elseif ($thousands > 1) { - $ret .= $this->toWords($thousands, 3); - } - - // values for digits, tens and hundreds - $h = floor(($num / 100) % 10); - $t = floor(($num / 10) % 10); - $d = floor($num % 10); - - // cientos: doscientos, trescientos, etc... - switch ($h) - { - case 1: - if (($d == 0) and ($t == 0)) { // is it's '100' use 'cien' - $ret .= $this->_sep . 'cien'; - } - else { - $ret .= $this->_sep . 'ciento'; - } - break; - case 2: - case 3: - case 4: - case 6: - case 8: - $ret .= $this->_sep . $this->_digits[$h] . 'cientos'; - break; - case 5: - $ret .= $this->_sep . 'quinientos'; - break; - case 7: - $ret .= $this->_sep . 'setecientos'; - break; - case 9: - $ret .= $this->_sep . 'novecientos'; - break; - } - - // decenas: veinte, treinta, etc... - switch ($t) - { - case 9: - $ret .= $this->_sep . 'noventa'; - break; - - case 8: - $ret .= $this->_sep . 'ochenta'; - break; - - case 7: - $ret .= $this->_sep . 'setenta'; - break; - - case 6: - $ret .= $this->_sep . 'sesenta'; - break; - - case 5: - $ret .= $this->_sep . 'cincuenta'; - break; - - case 4: - $ret .= $this->_sep . 'cuarenta'; - break; - - case 3: - $ret .= $this->_sep . 'treinta'; - break; - - case 2: - if ($d == 0) { - $ret .= $this->_sep . 'veinte'; - } - else { - if (($power > 0) and ($d == 1)) { - $ret .= $this->_sep . 'veintiún'; - } - else { - $ret .= $this->_sep . 'veinti' . $this->_digits[$d]; - } - } - break; - - case 1: - switch ($d) - { - case 0: - $ret .= $this->_sep . 'diez'; - break; - - case 1: - $ret .= $this->_sep . 'once'; - break; - - case 2: - $ret .= $this->_sep . 'doce'; - break; - - case 3: - $ret .= $this->_sep . 'trece'; - break; - - case 4: - $ret .= $this->_sep . 'catorce'; - break; - - case 5: - $ret .= $this->_sep . 'quince'; - break; - - case 6: - case 7: - case 9: - case 8: - $ret .= $this->_sep . 'dieci' . $this->_digits[$d]; - break; - } - break; - } - - // add digits only if it is a multiple of 10 and not 1x or 2x - if (($t != 1) and ($t != 2) and ($d > 0)) - { - if($t != 0) // don't add 'y' for numbers below 10 - { - // use 'un' instead of 'uno' when there is a suffix ('mil', 'millones', etc...) - if(($power > 0) and ($d == 1)) { - $ret .= $this->_sep.' y un'; - } - else { - $ret .= $this->_sep.'y '.$this->_digits[$d]; - } - } - else { - if(($power > 0) and ($d == 1)) { - $ret .= $this->_sep.'un'; - } - else { - $ret .= $this->_sep.$this->_digits[$d]; - } - } - } - - if ($power > 0) - { - if (isset($this->_exponent[$power])) { - $lev = $this->_exponent[$power]; - } - - if (!isset($lev) || !is_array($lev)) { - return null; - } - - // if it's only one use the singular suffix - if (($d == 1) and ($t == 0) and ($h == 0)) { - $suffix = $lev[0]; - } - else { - $suffix = $lev[1]; - } - if ($num != 0) { - $ret .= $this->_sep . $suffix; - } - } - - return $ret; - } - // }}} -} -?> diff --git a/gulliver/thirdparty/pear/Numbers/Words/lang.es_AR.php b/gulliver/thirdparty/pear/Numbers/Words/lang.es_AR.php deleted file mode 100644 index 4750631c5..000000000 --- a/gulliver/thirdparty/pear/Numbers/Words/lang.es_AR.php +++ /dev/null @@ -1,470 +0,0 @@ - | -// | Based On: lang_es.php - Xavier Noguer | -// +----------------------------------------------------------------------+ -// $Id: lang.es_AR.php 503 2004-02-23 19:25:42Z mmarre $ -// -// Numbers_Words class extension to spell numbers in Argentinian Spanish -// -// - -/** - * Class for translating numbers into Argentinian Spanish. - * - * @author Martin Marrese - * @package Numbers_Words - */ - -/** - * Include needed files - */ -require_once("Numbers/Words.php"); - -/** - * Class for translating numbers into Argentinian Spanish. - * It supports up to decallones (10^6). - * It doesn't support spanish tonic accents (acentos). - * - * @author Martin Marrese - * @package Numbers_Words - */ -class Numbers_Words_es_AR extends Numbers_Words -{ - // {{{ properties - - /** - * Locale name - * @var string - * @access public - */ - var $locale = 'es_AR'; - - /** - * Language name in English - * @var string - * @access public - */ - var $lang = 'Spanish'; - - /** - * Native language name - * @var string - * @access public - */ - var $lang_native = 'Español'; - - /** - * The word for the minus sign - * @var string - * @access private - */ - var $_minus = 'menos'; - - /** - * The sufixes for exponents (singular and plural) - * @var array - * @access private - */ - var $_exponent = array( - 0 => array('',''), - 3 => array('mil','mil'), - 6 => array('millón','millones'), - 12 => array('billón','billones'), - 18 => array('trilón','trillones'), - 24 => array('cuatrillón','cuatrillones'), - 30 => array('quintillón','quintillones'), - 36 => array('sextillón','sextillones'), - 42 => array('septillón','septillones'), - 48 => array('octallón','octallones'), - 54 => array('nonallón','nonallones'), - 60 => array('decallón','decallones'), - ); - /** - * The array containing the digits (indexed by the digits themselves). - * @var array - * @access private - */ - var $_digits = array( - 0 => 'cero', 'uno', 'dos', 'tres', 'cuatro', - 'cinco', 'seis', 'siete', 'ocho', 'nueve' - ); - /** - * The word separator - * @var string - * @access private - */ - var $_sep = ' '; - - /** - * The currency names (based on the below links, - * informations from central bank websites and on encyclopedias) - * - * @var array - * @link http://30-03-67.dreamstation.com/currency_alfa.htm World Currency Information - * @link http://www.jhall.demon.co.uk/currency/by_abbrev.html World currencies - * @link http://www.shoestring.co.kr/world/p.visa/change.htm Currency names in English - * @access private - */ - var $_currency_names = array( - 'ALL' => array(array('lek'), array('qindarka')), - 'AUD' => array(array('Australian dollar'), array('cent')), - 'ARS' => array(array('Peso'), array ('centavo')), - 'BAM' => array(array('convertible marka'), array('fenig')), - 'BGN' => array(array('lev'), array('stotinka')), - 'BRL' => array(array('real'), array('centavos')), - 'BYR' => array(array('Belarussian rouble'), array('kopiejka')), - 'CAD' => array(array('Canadian dollar'), array('cent')), - 'CHF' => array(array('Swiss franc'), array('rapp')), - 'CYP' => array(array('Cypriot pound'), array('cent')), - 'CZK' => array(array('Czech koruna'), array('halerz')), - 'DKK' => array(array('Danish krone'), array('ore')), - 'EEK' => array(array('kroon'), array('senti')), - 'EUR' => array(array('euro'), array('euro-cent')), - 'GBP' => array(array('pound', 'pounds'), array('pence')), - 'HKD' => array(array('Hong Kong dollar'), array('cent')), - 'HRK' => array(array('Croatian kuna'), array('lipa')), - 'HUF' => array(array('forint'), array('filler')), - 'ISK' => array(array('Icelandic króna'), array('aurar')), - 'JPY' => array(array('yen'), array('sen')), - 'LTL' => array(array('litas'), array('cent')), - 'LVL' => array(array('lat'), array('sentim')), - 'MKD' => array(array('Macedonian dinar'), array('deni')), - 'MTL' => array(array('Maltese lira'), array('centym')), - 'NOK' => array(array('Norwegian krone'), array('oere')), - 'PLN' => array(array('zloty', 'zlotys'), array('grosz')), - 'ROL' => array(array('Romanian leu'), array('bani')), - 'RUB' => array(array('Russian Federation rouble'), array('kopiejka')), - 'SEK' => array(array('Swedish krona'), array('oere')), - 'SIT' => array(array('Tolar'), array('stotinia')), - 'SKK' => array(array('Slovak koruna'), array()), - 'TRL' => array(array('lira'), array('kuruþ')), - 'UAH' => array(array('hryvna'), array('cent')), - 'USD' => array(array('dolar', 'DÓLARES'), array('centavo')), - 'YUM' => array(array('dinars'), array('para')), - 'ZAR' => array(array('rand'), array('cent')), - 'MXN' => array(array('Peso Mexicano', 'Pesos Mexicanos'), array('centavo')) - ); - - /** - * The default currency name - * @var string - * @access public - */ - var $def_currency = 'ARS'; // Argentinian Peso - - // }}} - // {{{ toWords() - /** - * Converts a number to its word representation - * in Argentinian Spanish. - * - * @param float $num An float between -infinity and infinity inclusive :) - * that should be converted to a words representation - * @param integer $power The power of ten for the rest of the number to the right. - * For example toWords(12,3) should give "doce mil". - * Optional, defaults to 0. - * @return string The corresponding word representation - * - * @access private - * @author Martin Marrese - */ - function toWords($num, $power = 0) - { - // The return string; - $ret = ''; - - // add a the word for the minus sign if necessary - if (substr($num, 0, 1) == '-') - { - $ret = $this->_sep . $this->_minus; - $num = substr($num, 1); - } - - - // strip excessive zero signs - $num = preg_replace('/^0+/','',$num); - - $num_tmp = split ('\.', $num); - - $num = $num_tmp[0]; - $dec = (@$num_tmp[1]) ? $num_tmp[1] : ''; - - if (strlen($num) > 6) - { - $current_power = 6; - // check for highest power - if (isset($this->_exponent[$power])) - { - // convert the number above the first 6 digits - // with it's corresponding $power. - $snum = substr($num, 0, -6); - $snum = preg_replace('/^0+/','',$snum); - if ($snum !== '') { - $ret .= $this->toWords($snum, $power + 6); - } - } - $num = substr($num, -6); - if ($num == 0) { - return $ret; - } - } - elseif ($num == 0 || $num == '') { - return(' '.$this->_digits[0]); - $current_power = strlen($num); - } - else { - $current_power = strlen($num); - } - - // See if we need "thousands" - $thousands = floor($num / 1000); - if ($thousands == 1) { - $ret .= $this->_sep . 'mil'; - } - elseif ($thousands > 1) { - $ret .= $this->toWords($thousands, 3); - } - - // values for digits, tens and hundreds - $h = floor(($num / 100) % 10); - $t = floor(($num / 10) % 10); - $d = floor($num % 10); - - // cientos: doscientos, trescientos, etc... - switch ($h) - { - case 1: - if (($d == 0) and ($t == 0)) { // is it's '100' use 'cien' - $ret .= $this->_sep . 'cien'; - } - else { - $ret .= $this->_sep . 'ciento'; - } - break; - case 2: - case 3: - case 4: - case 6: - case 8: - $ret .= $this->_sep . $this->_digits[$h] . 'cientos'; - break; - case 5: - $ret .= $this->_sep . 'quinientos'; - break; - case 7: - $ret .= $this->_sep . 'setecientos'; - break; - case 9: - $ret .= $this->_sep . 'novecientos'; - break; - } - - // decenas: veinte, treinta, etc... - switch ($t) - { - case 9: - $ret .= $this->_sep . 'noventa'; - break; - - case 8: - $ret .= $this->_sep . 'ochenta'; - break; - - case 7: - $ret .= $this->_sep . 'setenta'; - break; - - case 6: - $ret .= $this->_sep . 'sesenta'; - break; - - case 5: - $ret .= $this->_sep . 'cincuenta'; - break; - - case 4: - $ret .= $this->_sep . 'cuarenta'; - break; - - case 3: - $ret .= $this->_sep . 'treinta'; - break; - - case 2: - if ($d == 0) { - $ret .= $this->_sep . 'veinte'; - } - else { - if (($power > 0) and ($d == 1)) { - $ret .= $this->_sep . 'veintiún'; - } - else { - $ret .= $this->_sep . 'veinti' . $this->_digits[$d]; - } - } - break; - - case 1: - switch ($d) - { - case 0: - $ret .= $this->_sep . 'diez'; - break; - - case 1: - $ret .= $this->_sep . 'once'; - break; - - case 2: - $ret .= $this->_sep . 'doce'; - break; - - case 3: - $ret .= $this->_sep . 'trece'; - break; - - case 4: - $ret .= $this->_sep . 'catorce'; - break; - - case 5: - $ret .= $this->_sep . 'quince'; - break; - - case 6: - case 7: - case 9: - case 8: - $ret .= $this->_sep . 'dieci' . $this->_digits[$d]; - break; - } - break; - } - - // add digits only if it is a multiple of 10 and not 1x or 2x - if (($t != 1) and ($t != 2) and ($d > 0)) - { - if($t != 0) // don't add 'y' for numbers below 10 - { - // use 'un' instead of 'uno' when there is a suffix ('mil', 'millones', etc...) - if(($power > 0) and ($d == 1)) { - $ret .= $this->_sep.' y un'; - } - else { - $ret .= $this->_sep.'y '.$this->_digits[$d]; - } - } - else { - if(($power > 0) and ($d == 1)) { - $ret .= $this->_sep.'un'; - } - else { - $ret .= $this->_sep.$this->_digits[$d]; - } - } - } - - if ($power > 0) - { - if (isset($this->_exponent[$power])) { - $lev = $this->_exponent[$power]; - } - - if (!isset($lev) || !is_array($lev)) { - return null; - } - - // if it's only one use the singular suffix - if (($d == 1) and ($t == 0) and ($h == 0)) { - $suffix = $lev[0]; - } - else { - $suffix = $lev[1]; - } - if ($num != 0) { - $ret .= $this->_sep . $suffix; - } - } - - if ($dec) { - $dec = $this->toWords(trim($dec)); - $ret.= ' con ' . trim ($dec); - } - - return $ret; - } - // }}} - - // {{{ toCurrency() - - /** - * Converts a currency value to its word representation - * (with monetary units) in Agentinian Spanish language - * - * @param integer $int_curr An international currency symbol - * as defined by the ISO 4217 standard (three characters) - * @param integer $decimal A money total amount without fraction part (e.g. amount of dollars) - * @param integer $fraction Fractional part of the money amount (e.g. amount of cents) - * Optional. Defaults to false. - * - * @return string The corresponding word representation for the currency - * - * @access public - * @author Martin Marrese - */ - function toCurrencyWords($int_curr, $decimal, $fraction = false) { - $int_curr = strtoupper($int_curr); - if (!isset($this->_currency_names[$int_curr])) { - $int_curr = $this->def_currency; - } - $curr_names = $this->_currency_names[$int_curr]; - $ret .= $this->_sep . trim($this->toWords($decimal)); - $lev = ($decimal == 1) ? 0 : 1; - - if ($lev > 0) { - if (count($curr_names[0]) > 1) { - $ret .= $this->_sep . $curr_names[0][$lev]; - } else { - $ret .= $this->_sep . $curr_names[0][0] . 's'; - } - } else { - $ret .= $this->_sep . $curr_names[0][0]; - } - - - if ($fraction !== false) { - $ret .= $this->_sep .'con'. $this->_sep . trim($this->toWords($fraction)); - $lev = ($fraction == 1) ? 0 : 1; - if ($lev > 0) { - if (count($curr_names[1]) > 1) { - $ret .= $this->_sep . $curr_names[1][$lev]; - } else { - $ret .= $this->_sep . $curr_names[1][0] . 's'; - } - } else { - $ret .= $this->_sep . $curr_names[1][0]; - } - } - return $ret; - } - // }}} - - - -} -?> diff --git a/gulliver/thirdparty/pear/Numbers/Words/lang.fr.php b/gulliver/thirdparty/pear/Numbers/Words/lang.fr.php deleted file mode 100644 index ed756163f..000000000 --- a/gulliver/thirdparty/pear/Numbers/Words/lang.fr.php +++ /dev/null @@ -1,439 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id$ - -/** - * Include needed files - */ -require_once("Numbers/Words.php"); - -/** - * Class for translating numbers into French. - * - * @author Kouber Saparev - * @package Numbers_Words - */ -class Numbers_Words_fr extends Numbers_Words -{ - - // {{{ properties - - /** - * Locale name. - * @var string - * @access public - */ - var $locale = 'fr'; - - /** - * Language name in English. - * @var string - * @access public - */ - var $lang = 'French'; - - /** - * Native language name. - * @var string - * @access public - */ - var $lang_native = 'Français'; - - /** - * The words for some numbers. - * @var string - * @access private - */ - var $_misc_numbers = array( - 10=>'dix', // 10 - 'onze', // 11 - 'douze', // 12 - 'treize', // 13 - 'quatorze', // 14 - 'quinze', // 15 - 'seize', // 16 - 20=>'vingt', // 20 - 30=>'trente', // 30 - 40=>'quarante', // 40 - 50=>'cinquante',// 50 - 60=>'soixante', // 60 - 100=>'cent' // 100 - ); - - - /** - * The words for digits (except zero). - * @var string - * @access private - */ - var $_digits = array(1=>"un", "deux", "trois", "quatre", "cinq", "six", "sept", "huit", "neuf"); - - /** - * The word for zero. - * @var string - * @access private - */ - var $_zero = 'zéro'; - - /** - * The word for infinity. - * @var string - * @access private - */ - var $_infinity = 'infini'; - - /** - * The word for the "and" language construct. - * @var string - * @access private - */ - var $_and = 'et'; - - /** - * The word separator. - * @var string - * @access private - */ - var $_sep = ' '; - - /** - * The dash liaison. - * @var string - * @access private - */ - var $_dash = '-'; - - /** - * The word for the minus sign. - * @var string - * @access private - */ - var $_minus = 'moins'; // minus sign - - /** - * The plural suffix (except for hundred). - * @var string - * @access private - */ - var $_plural = 's'; // plural suffix - - /** - * The suffixes for exponents (singular). - * @var array - * @access private - */ - var $_exponent = array( - 0 => '', - 3 => 'mille', - 6 => 'million', - 9 => 'milliard', - 12 => 'trillion', - 15 => 'quadrillion', - 18 => 'quintillion', - 21 => 'sextillion', - 24 => 'septillion', - 27 => 'octillion', - 30 => 'nonillion', - 33 => 'decillion', - 36 => 'undecillion', - 39 => 'duodecillion', - 42 => 'tredecillion', - 45 => 'quattuordecillion', - 48 => 'quindecillion', - 51 => 'sexdecillion', - 54 => 'septendecillion', - 57 => 'octodecillion', - 60 => 'novemdecillion', - 63 => 'vigintillion', - 66 => 'unvigintillion', - 69 => 'duovigintillion', - 72 => 'trevigintillion', - 75 => 'quattuorvigintillion', - 78 => 'quinvigintillion', - 81 => 'sexvigintillion', - 84 => 'septenvigintillion', - 87 => 'octovigintillion', - 90 => 'novemvigintillion', - 93 => 'trigintillion', - 96 => 'untrigintillion', - 99 => 'duotrigintillion', - 102 => 'trestrigintillion', - 105 => 'quattuortrigintillion', - 108 => 'quintrigintillion', - 111 => 'sextrigintillion', - 114 => 'septentrigintillion', - 117 => 'octotrigintillion', - 120 => 'novemtrigintillion', - 123 => 'quadragintillion', - 126 => 'unquadragintillion', - 129 => 'duoquadragintillion', - 132 => 'trequadragintillion', - 135 => 'quattuorquadragintillion', - 138 => 'quinquadragintillion', - 141 => 'sexquadragintillion', - 144 => 'septenquadragintillion', - 147 => 'octoquadragintillion', - 150 => 'novemquadragintillion', - 153 => 'quinquagintillion', - 156 => 'unquinquagintillion', - 159 => 'duoquinquagintillion', - 162 => 'trequinquagintillion', - 165 => 'quattuorquinquagintillion', - 168 => 'quinquinquagintillion', - 171 => 'sexquinquagintillion', - 174 => 'septenquinquagintillion', - 177 => 'octoquinquagintillion', - 180 => 'novemquinquagintillion', - 183 => 'sexagintillion', - 186 => 'unsexagintillion', - 189 => 'duosexagintillion', - 192 => 'tresexagintillion', - 195 => 'quattuorsexagintillion', - 198 => 'quinsexagintillion', - 201 => 'sexsexagintillion', - 204 => 'septensexagintillion', - 207 => 'octosexagintillion', - 210 => 'novemsexagintillion', - 213 => 'septuagintillion', - 216 => 'unseptuagintillion', - 219 => 'duoseptuagintillion', - 222 => 'treseptuagintillion', - 225 => 'quattuorseptuagintillion', - 228 => 'quinseptuagintillion', - 231 => 'sexseptuagintillion', - 234 => 'septenseptuagintillion', - 237 => 'octoseptuagintillion', - 240 => 'novemseptuagintillion', - 243 => 'octogintillion', - 246 => 'unoctogintillion', - 249 => 'duooctogintillion', - 252 => 'treoctogintillion', - 255 => 'quattuoroctogintillion', - 258 => 'quinoctogintillion', - 261 => 'sexoctogintillion', - 264 => 'septoctogintillion', - 267 => 'octooctogintillion', - 270 => 'novemoctogintillion', - 273 => 'nonagintillion', - 276 => 'unnonagintillion', - 279 => 'duononagintillion', - 282 => 'trenonagintillion', - 285 => 'quattuornonagintillion', - 288 => 'quinnonagintillion', - 291 => 'sexnonagintillion', - 294 => 'septennonagintillion', - 297 => 'octononagintillion', - 300 => 'novemnonagintillion', - 303 => 'centillion' - ); - // }}} - - // {{{ _splitNumber() - - /** - * Split a number to groups of three-digit numbers. - * - * @param mixed $num An integer or its string representation - * that need to be split - * - * @return array Groups of three-digit numbers. - * - * @access private - * @author Kouber Saparev - * @since PHP 4.2.3 - */ - - function _splitNumber($num) - { - if (is_string($num)) { - $ret = array(); - $strlen = strlen($num); - $first = substr($num, 0, $strlen%3); - preg_match_all('/\d{3}/', substr($num, $strlen%3, $strlen), $m); - $ret =& $m[0]; - if ($first) array_unshift($ret, $first); - return $ret; - } - else - return explode(' ', number_format($num, 0, '', ' ')); // a faster version for integers - } - // }}} - - // {{{ _showDigitsGroup() - - /** - * Converts a three-digit number to its word representation - * in French language. - * - * @param integer $num An integer between 1 and 999 inclusive. - * - * @param boolean $last A flag, that determines if it is the last group of digits - - * this is used to accord the plural suffix of the "hundreds". - * Example: 200 = "deux cents", but 200000 = "deux cent mille". - * - * - * @return string The words for the given number. - * - * @access private - * @author Kouber Saparev - */ - function _showDigitsGroup($num, $last = false) - { - $ret = ''; - - // extract the value of each digit from the three-digit number - $e = $num%10; // ones - $d = ($num-$e)%100/10; // tens - $s = ($num-$d*10-$e)%1000/100; // hundreds - - // process the "hundreds" digit. - if ($s) { - if ($s>1) { - $ret .= $this->_digits[$s].$this->_sep.$this->_misc_numbers[100]; - if ($last && !$e && !$d) { - $ret .= $this->_plural; - } - } else { - $ret .= $this->_misc_numbers[100]; - } - $ret .= $this->_sep; - } - - // process the "tens" digit, and optionally the "ones" digit. - if ($d) { - // in the case of 1, the "ones" digit also must be processed - if ($d==1) { - if ($e<=6) { - $ret .= $this->_misc_numbers[10+$e]; - } else { - $ret .= $this->_misc_numbers[10].'-'.$this->_digits[$e]; - } - $e = 0; - } elseif ($d>5) { - if ($d<8) { - $ret .= $this->_misc_numbers[60]; - $resto = $d*10+$e-60; - if ($e==1) { - $ret .= $this->_sep.$this->_and.$this->_sep; - } - elseif ($resto) { - $ret .= $this->_dash; - } - - if ($resto) { - $ret .= $this->_showDigitsGroup($resto); - } - $e = 0; - } else { - $ret .= $this->_digits[4].$this->_dash.$this->_misc_numbers[20]; - $resto = $d*10+$e-80; - if ($resto) { - $ret .= $this->_dash; - $ret .= $this->_showDigitsGroup($resto); - $e = 0; - } else { - $ret .= $this->_plural; - } - } - } else { - $ret .= $this->_misc_numbers[$d*10]; - } - } - - // process the "ones" digit - if ($e) { - if ($d) { - if ($e==1) { - $ret .= $this->_sep.$this->_and.$this->_sep; - } else { - $ret .= $this->_dash; - } - } - $ret .= $this->_digits[$e]; - } - - // strip excessive separators - $ret = rtrim($ret, $this->_sep); - - return $ret; - } - // }}} - - // {{{ toWords() - - /** - * Converts a number to its word representation - * in French language. - * - * @param integer $num An integer (or its string representation) between 9.99*-10^302 - * and 9.99*10^302 (999 centillions) that need to be converted to words - * - * @return string The corresponding word representation - * - * @access public - * @author Kouber Saparev - */ - function toWords($num = 0) - { - $ret = ''; - - // check if $num is a valid non-zero number - if (!$num || preg_match('/^-?0+$/', $num) || !preg_match('/^-?\d+$/', $num)) return $this->_zero; - - // add a minus sign - if (substr($num, 0, 1) == '-') { - $ret = $this->_minus . $this->_sep; - $num = substr($num, 1); - } - - // if the absolute value is greater than 9.99*10^302, return infinity - if (strlen($num)>306) { - return $ret . $this->_infinity; - } - - // strip excessive zero signs - $num = ltrim($num, '0'); - - // split $num to groups of three-digit numbers - $num_groups = $this->_splitNumber($num); - - $sizeof_numgroups = count($num_groups); - - foreach ($num_groups as $i=>$number) { - // what is the corresponding exponent for the current group - $pow = $sizeof_numgroups-$i; - - // skip processment for empty groups - if ($number!='000') { - if ($number!=1 || $pow!=2) { - $ret .= $this->_showDigitsGroup($number, $i+1==$sizeof_numgroups).$this->_sep; - } - $ret .= $this->_exponent[($pow-1)*3]; - if ($pow>2 && $number>1) { - $ret .= $this->_plural; - } - $ret .= $this->_sep; - } - } - - return rtrim($ret, $this->_sep); - } - // }}} -} -?> diff --git a/gulliver/thirdparty/pear/Numbers/Words/lang.id.php b/gulliver/thirdparty/pear/Numbers/Words/lang.id.php deleted file mode 100644 index 21ab30cfb..000000000 --- a/gulliver/thirdparty/pear/Numbers/Words/lang.id.php +++ /dev/null @@ -1,277 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: lang.en_GB.php,v 1.3 2002/11/26 10:33:35 makler Exp $ -// -// Numbers_Words class extension to spell numbers in Indonesian language. -// - -require_once("PEAR.php"); -require_once("Numbers/Words.php"); - -/** -* Class for translating numbers into Indonesian. -* -* @author Ernas M. Jamil -*/ -class Numbers_Words_id extends Numbers_Words -{ - - // {{{ properties - - /** - * Locale name - * @var string - */ - var $locale = 'id'; - - /** - * Language name in English - * @var string - */ - var $lang = 'Indonesia Language'; - - /** - * Native language name - * @var string - */ - var $lang_native = 'Bahasa Indonesia'; - - /** - * The word for the minus sign - * @var string - */ - var $_minus = 'minus'; // minus sign - - /** - * The sufixes for exponents (singular and plural) - * Names partly based on: - * http://www.users.dircon.co.uk/~shaunf/shaun/numbers/millions.htm - * @var array - */ - var $_exponent = array( - 0 => array(''), - 3 => array('ribu'), - 6 => array('juta'), - 9 => array('milyar'), - 12 => array('trilyun'), - 24 => array('quadrillion'), - 30 => array('quintillion'), - 36 => array('sextillion'), - 42 => array('septillion'), - 48 => array('octillion'), - 54 => array('nonillion'), - 60 => array('decillion'), - 66 => array('undecillion'), - 72 => array('duodecillion'), - 78 => array('tredecillion'), - 84 => array('quattuordecillion'), - 90 => array('quindecillion'), - 96 => array('sexdecillion'), - 102 => array('septendecillion'), - 108 => array('octodecillion'), - 114 => array('novemdecillion'), - 120 => array('vigintillion'), - 192 => array('duotrigintillion'), - 600 => array('centillion') - ); - - /** - * The array containing the digits (indexed by the digits themselves). - * @var array - */ - var $_digits = array( - 0 => 'nol', 'satu', 'dua', 'tiga', 'empat', - 'lima', 'enam', 'tujuh', 'delapan', 'sembilan' - ); - - /** - * The word separator - * @var string - */ - var $_sep = ' '; - - // }}} - // {{{ toWords() - - /** - * Converts a number to its word representation - * in Indonesian language - * - * @param integer $num An integer between -infinity and infinity inclusive :) - * that need to be converted to words - * @param integer $power The power of ten for the rest of the number to the right. - * Optional, defaults to 0. - * @param integer $powsuffix The power name to be added to the end of the return string. - * Used internally. Optional, defaults to ''. - * - * @return string The corresponding word representation - * - * @access public - * @author Ernas M. Jamil - * @since PHP 4.2.3 - */ - function toWords($num, $power = 0, $powsuffix = '') { - $ret = ''; - - // add a minus sign - if (substr($num, 0, 1) == '-') { - $ret = $this->_sep . $this->_minus; - $num = substr($num, 1); - } - - // strip excessive zero signs and spaces - $num = trim($num); - $num = preg_replace('/^0+/','',$num); - - if (strlen($num) > 4) { - $maxp = strlen($num)-1; - $curp = $maxp; - for ($p = $maxp; $p > 0; --$p) { // power - - // check for highest power - if (isset($this->_exponent[$p])) { - // send substr from $curp to $p - $snum = substr($num, $maxp - $curp, $curp - $p + 1); - $snum = preg_replace('/^0+/','',$snum); - if ($snum !== '') { - $cursuffix = $this->_exponent[$power][count($this->_exponent[$power])-1]; - if ($powsuffix != '') - $cursuffix .= $this->_sep . $powsuffix; - $ret .= $this->toWords($snum, $p, $cursuffix); - } - $curp = $p - 1; - continue; - } - } - $num = substr($num, $maxp - $curp, $curp - $p + 1); - if ($num == 0) { - return $ret; - } - } elseif ($num == 0 || $num == '') { - return $this->_sep . $this->_digits[0]; - } - - $h = $t = $d = $th = 0; - - switch(strlen($num)) { - case 4: - $th = (int)substr($num,-4,1); - - case 3: - $h = (int)substr($num,-3,1); - - case 2: - $t = (int)substr($num,-2,1); - - case 1: - $d = (int)substr($num,-1,1); - break; - - case 0: - return; - break; - } - - if ($th) { - if ($th==1) - $ret .= $this->_sep . 'seribu'; - else - $ret .= $this->_sep . $this->_digits[$th] . $this->_sep . 'ribu'; - } - - if ($h) { - if ($h==1) - $ret .= $this->_sep . 'seratus'; - else - $ret .= $this->_sep . $this->_digits[$h] . $this->_sep . 'ratus'; - - // in English only - add ' and' for [1-9]01..[1-9]99 - // (also for 1001..1099, 10001..10099 but it is harder) - // for now it is switched off, maybe some language purists - // can force me to enable it, or to remove it completely - // if (($t + $d) > 0) - // $ret .= $this->_sep . 'and'; - } - - // ten, twenty etc. - switch ($t) { - case 9: - case 8: - case 7: - case 6: - case 5: - case 4: - case 3: - case 2: - $ret .= $this->_sep . $this->_digits[$t] . ' puluh'; - break; - - case 1: - switch ($d) { - case 0: - $ret .= $this->_sep . 'sepuluh'; - break; - - case 1: - $ret .= $this->_sep . 'sebelas'; - break; - - case 2: - case 3: - case 4: - case 5: - case 6: - case 7: - case 8: - case 9: - $ret .= $this->_sep . $this->_digits[$d] . ' belas'; - break; - } - break; - } - - if ($t != 1 && $d > 0) { // add digits only in <0>,<1,9> and <21,inf> - // add minus sign between [2-9] and digit - if ($t > 1) { - $ret .= ' ' . $this->_digits[$d]; - } else { - $ret .= $this->_sep . $this->_digits[$d]; - } - } - - if ($power > 0) { - if (isset($this->_exponent[$power])) - $lev = $this->_exponent[$power]; - - if (!isset($lev) || !is_array($lev)) - return null; - - $ret .= $this->_sep . $lev[0]; - } - - if ($powsuffix != '') - $ret .= $this->_sep . $powsuffix; - - return $ret; - } - // }}} -} - -?> diff --git a/gulliver/thirdparty/pear/Numbers/Words/lang.it_IT.php b/gulliver/thirdparty/pear/Numbers/Words/lang.it_IT.php deleted file mode 100644 index 50694f7bc..000000000 --- a/gulliver/thirdparty/pear/Numbers/Words/lang.it_IT.php +++ /dev/null @@ -1,348 +0,0 @@ - - * @author Davide Caironi - * @package Numbers_Words - */ - -/** - * Include needed files - */ -require_once("Numbers/Words.php"); - -/** - * Class for translating numbers into Italian. - * It supports up to quadrilions - * - * @author Filippo Beltramini - * @author Davide Caironi - * @package Numbers_Words - */ -class Numbers_Words_it_IT extends Numbers_Words -{ - // {{{ properties - - /** - * Locale name - * @var string - * @access public - */ - var $locale = 'it_IT'; - - /** - * Language name in English - * @var string - * @access public - */ - var $lang = 'Italian'; - - /** - * Native language name - * @var string - * @access public - */ - var $lang_native = 'Italiano'; - - /** - * The word for the minus sign - * @var string - * @access private - */ - var $_minus = 'meno '; - - /** - * The sufixes for exponents (singular and plural) - * @var array - * @access private - */ - var $_exponent = array( - 0 => array('',''), - 3 => array('mille','mila'), - 6 => array('milione','miloni'), - 12 => array('miliardo','miliardi'), - 18 => array('trillone','trilloni'), - 24 => array('quadrilione','quadrilioni'), - ); - /** - * The array containing the digits (indexed by the digits themselves). - * @var array - * @access private - */ - var $_digits = array( - 0 => 'zero', 'uno', 'due', 'tre', 'quattro', - 'cinque', 'sei', 'sette', 'otto', 'nove' - ); - - /** - * The word separator - * @var string - * @access private - */ - var $_sep = ''; - // }}} - // {{{ toWords() - /** - * Converts a number to its word representation - * in italiano. - * - * @param integer $num An integer between -infinity and infinity inclusive :) - * that should be converted to a words representation - * @param integer $power The power of ten for the rest of the number to the right. - * For example toWords(12,3) should give "doce mil". - * Optional, defaults to 0. - * @return string The corresponding word representation - * - * @access private - * @author Filippo Beltramini - * @since PHP 4.2.3 - */ - function toWords($num, $power = 0) - { - // The return string; - $ret = ''; - - // add a the word for the minus sign if necessary - if (substr($num, 0, 1) == '-') - { - $ret = $this->_sep . $this->_minus; - $num = substr($num, 1); - } - - - // strip excessive zero signs - $num = preg_replace('/^0+/','',$num); - - if (strlen($num) > 6) - { - $current_power = 6; - // check for highest power - if (isset($this->_exponent[$power])) - { - // convert the number above the first 6 digits - // with it's corresponding $power. - $snum = substr($num, 0, -6); - $snum = preg_replace('/^0+/','',$snum); - if ($snum !== '') { - $ret .= $this->toWords($snum, $power + 6); - } - } - $num = substr($num, -6); - if ($num == 0) { - return $ret; - } - } - elseif ($num == 0 || $num == '') { - return(' '.$this->_digits[0].' '); - $current_power = strlen($num); - } - else { - $current_power = strlen($num); - } - - // See if we need "thousands" - $thousands = floor($num / 1000); - if ($thousands == 1) { - $ret .= $this->_sep . 'mille' . $this->_sep; - } - elseif ($thousands > 1) { - $ret .= $this->toWords($thousands, 3) . $this->_sep;//. 'mil' . $this->_sep; - } - - // values for digits, tens and hundreds - $h = floor(($num / 100) % 10); - $t = floor(($num / 10) % 10); - $d = floor($num % 10); - - // centinaia: duecento, trecento, etc... - switch ($h) - { - case 1: - if (($d == 0) and ($t == 0)) { // is it's '100' use 'cien' - $ret .= $this->_sep . 'cento'; - } - else { - $ret .= $this->_sep . 'cento'; - } - break; - case 2: - case 3: - case 4: - case 6: - case 8: - $ret .= $this->_sep . $this->_digits[$h] . 'cento'; - break; - case 5: - $ret .= $this->_sep . 'cinquecento'; - break; - case 7: - $ret .= $this->_sep . 'settecento'; - break; - case 9: - $ret .= $this->_sep . 'novecento'; - break; - } - - // decine: venti trenta, etc... - switch ($t) - { - case 9: - $ret .= $this->_sep . 'novanta'; - break; - - case 8: - $ret .= $this->_sep . 'ottanta'; - break; - - case 7: - $ret .= $this->_sep . 'settanta'; - break; - - case 6: - $ret .= $this->_sep . 'sessanta'; - break; - - case 5: - $ret .= $this->_sep . 'cinquanta'; - break; - - case 4: - $ret .= $this->_sep . 'quaranta'; - break; - - case 3: - $ret .= $this->_sep . 'trenta'; - break; - - case 2: - if ($d == 0) { - $ret .= $this->_sep . 'venti'; - } - else { - if (($power > 0) and ($d == 1)) { - $ret .= $this->_sep . 'ventuno'; - } - else { - $ret .= $this->_sep . 'venti' . $this->_digits[$d]; - } - } - break; - - case 1: - switch ($d) - { - case 0: - $ret .= $this->_sep . 'dieci'; - break; - - case 1: - $ret .= $this->_sep . 'undici'; - break; - - case 2: - $ret .= $this->_sep . 'dodici'; - break; - - case 3: - $ret .= $this->_sep . 'tredici'; - break; - - case 4: - $ret .= $this->_sep . 'quattordici'; - break; - - case 5: - $ret .= $this->_sep . 'quindici'; - break; - - case 6: - $ret .= $this->_sep . 'sedici'; - break; - - case 7: - $ret .= $this->_sep . 'diciassette'; - break; - - case 8: - $ret .= $this->_sep . 'diciotto'; - break; - - case 9: - $ret .= $this->_sep . 'diciannove'; - break; - } - break; - } - - // add digits only if it is a multiple of 10 and not 1x or 2x - if (($t != 1) and ($t != 2) and ($d > 0)) - { - if($t != 0) // don't add 'e' for numbers below 10 - { - // use 'un' instead of 'uno' when there is a suffix ('mila', 'milloni', etc...) - if(($power > 0) and ($d == 1)) { - $ret .= $this->_sep.' e un'; - } - else { - $ret .= $this->_sep.''.$this->_digits[$d]; - } - } - else { - if(($power > 0) and ($d == 1)) { - $ret .= $this->_sep.'un '; - } - else { - $ret .= $this->_sep.$this->_digits[$d]; - } - } - } - - if ($power > 0) - { - if (isset($this->_exponent[$power])) { - $lev = $this->_exponent[$power]; - } - - if (!isset($lev) || !is_array($lev)) { - return null; - } - - // if it's only one use the singular suffix - if (($d == 1) and ($t == 0) and ($h == 0)) { - $suffix = $lev[0]; - } - else { - $suffix = $lev[1]; - } - if ($num != 0) { - $ret .= $this->_sep . $suffix; - } - } - - return $ret; - } - // }}} -} -?> diff --git a/gulliver/thirdparty/pear/Numbers/Words/lang.lt.php b/gulliver/thirdparty/pear/Numbers/Words/lang.lt.php deleted file mode 100644 index 48a418b2f..000000000 --- a/gulliver/thirdparty/pear/Numbers/Words/lang.lt.php +++ /dev/null @@ -1,310 +0,0 @@ - array(''), - 3 => array('tûkstantis','tûkstanèiai','tûkstanèiø'), - 6 => array('milijonas','milijonai','milijonø'), - 9 => array('bilijonas','bilijonai','bilijonø'), - 12 => array('trilijonas','trilijonai','trilijonø'), - 15 => array('kvadrilijonas','kvadrilijonai','kvadrilijonø'), - 18 => array('kvintilijonas','kvintilijonai','kvintilijonø') - ); - - /** - * The array containing the digits (indexed by the digits themselves). - * @var array - * @access private - */ - var $_digits = array( - 0 => 'nulis', 'vienas', 'du', 'trys', 'keturi', - 'penki', 'ðeði', 'septyni', 'aðtuoni', 'devyni' - ); - - /** - * The word separator - * @var string - * @access private - */ - var $_sep = ' '; - - /** - * The default currency name - * @var string - * @access public - */ - var $def_currency = 'LTL'; - - // }}} - // {{{ toWords() - - /** - * Converts a number to its word representation - * in Lithuanian language - * - * @param integer $num An integer between -infinity and infinity inclusive :) - * that need to be converted to words - * @param integer $power The power of ten for the rest of the number to the right. - * Optional, defaults to 0. - * @param integer $powsuffix The power name to be added to the end of the return string. - * Used internally. Optional, defaults to ''. - * - * @return string The corresponding word representation - * - * @access public - * @author Laurynas Butkus - * @since PHP 4.2.3 - */ - function toWords($num, $power = 0, $powsuffix = '') { - $ret = ''; - - // add a minus sign - if (substr($num, 0, 1) == '-') { - $ret = $this->_sep . $this->_minus; - $num = substr($num, 1); - } - - // strip excessive zero signs and spaces - $num = trim($num); - $num = preg_replace('/^0+/','',$num); - - if (strlen($num) > 3) { - $maxp = strlen($num)-1; - $curp = $maxp; - for ($p = $maxp; $p > 0; --$p) { // power - - // check for highest power - if (isset($this->_exponent[$p])) { - // send substr from $curp to $p - $snum = substr($num, $maxp - $curp, $curp - $p + 1); - $snum = preg_replace('/^0+/','',$snum); - if ($snum !== '') { - $cursuffix = $this->_exponent[$power][count($this->_exponent[$power])-1]; - if ($powsuffix != '') - $cursuffix .= $this->_sep . $powsuffix; - $ret .= $this->toWords($snum, $p, $cursuffix); - } - $curp = $p - 1; - continue; - } - } - $num = substr($num, $maxp - $curp, $curp - $p + 1); - if ($num == 0) { - return $ret; - } - } elseif ($num == 0 || $num == '') { - return $this->_sep . $this->_digits[0]; - } - - $h = $t = $d = 0; - - switch(strlen($num)) { - case 3: - $h = (int)substr($num,-3,1); - - case 2: - $t = (int)substr($num,-2,1); - - case 1: - $d = (int)substr($num,-1,1); - break; - - case 0: - return; - break; - } - - if ( $h > 1 ) - $ret .= $this->_sep . $this->_digits[$h] . $this->_sep . 'ðimtai'; - elseif ( $h ) - $ret .= $this->_sep . 'ðimtas'; - - // ten, twenty etc. - switch ($t) { - case 9: - $ret .= $this->_sep . 'devyniasdeðimt'; - break; - - case 8: - $ret .= $this->_sep . 'aðtuoniasdeðimt'; - break; - - case 7: - $ret .= $this->_sep . 'septyniasdeðimt'; - break; - - case 6: - $ret .= $this->_sep . 'ðeðiasdeðimt'; - break; - - case 5: - $ret .= $this->_sep . 'penkiasdeðimt'; - break; - - case 4: - $ret .= $this->_sep . 'keturiasdeðimt'; - break; - - case 3: - $ret .= $this->_sep . 'trisdeðimt'; - break; - - case 2: - $ret .= $this->_sep . 'dvideðimt'; - break; - - case 1: - switch ($d) { - case 0: - $ret .= $this->_sep . 'deðimt'; - break; - - case 1: - $ret .= $this->_sep . 'vienuolika'; - break; - - case 2: - $ret .= $this->_sep . 'dvylika'; - break; - - case 3: - $ret .= $this->_sep . 'trylika'; - break; - - case 4: - $ret .= $this->_sep . 'keturiolika'; - break; - - case 5: - $ret .= $this->_sep . 'penkiolika'; - break; - - case 6: - $ret .= $this->_sep . 'ðeðiolika'; - break; - - case 7: - $ret .= $this->_sep . 'septyniolika'; - break; - - case 8: - $ret .= $this->_sep . 'aðtuoniolika'; - break; - - case 9: - $ret .= $this->_sep . 'devyniolika'; - break; - - } - break; - } - - if ($t != 1 && $d > 0) { // add digits only in <0>,<1,9> and <21,inf> - if ( $d > 1 || !$power || $t ) - $ret .= $this->_sep . $this->_digits[$d]; - } - - if ($power > 0) { - if (isset($this->_exponent[$power])) - $lev = $this->_exponent[$power]; - - if (!isset($lev) || !is_array($lev)) - return null; - - //echo " $t $d
"; - - if ( $t == 1 || ( $t > 0 && $d == 0 ) ) - $ret .= $this->_sep . $lev[2]; - elseif ( $d > 1 ) - $ret .= $this->_sep . $lev[1]; - else - $ret .= $this->_sep . $lev[0]; - } - - if ($powsuffix != '') - $ret .= $this->_sep . $powsuffix; - - return $ret; - } - // }}} - -} - -?> diff --git a/gulliver/thirdparty/pear/Numbers/Words/lang.pl.php b/gulliver/thirdparty/pear/Numbers/Words/lang.pl.php deleted file mode 100644 index 54519e293..000000000 --- a/gulliver/thirdparty/pear/Numbers/Words/lang.pl.php +++ /dev/null @@ -1,513 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: lang.pl.php,v 1.9 2003/09/29 12:23:58 makler Exp $ -// -// Numbers_Words class extension to spell numbers in Polish. -// - -/** - * Class for translating numbers into Polish. - * - * @author Piotr Klaban - * @package Numbers_Words - */ - -/** - * Include needed files - */ -require_once("Numbers/Words.php"); - -/** - * Class for translating numbers into Polish. - * - * @author Piotr Klaban - * @package Numbers_Words - */ -class Numbers_Words_pl extends Numbers_Words -{ - - // {{{ properties - - /** - * Locale name - * @var string - * @access public - */ - var $locale = 'pl'; - - /** - * Language name in English - * @var string - * @access public - */ - var $lang = 'Polish'; - - /** - * Native language name - * @var string - * @access public - */ - var $lang_native = 'polski'; - - /** - * The word for the minus sign - * @var string - * @access private - */ - var $_minus = 'minus'; // minus sign - - /** - * The sufixes for exponents (singular and plural) - * Names based on: - * mathematical tables, my memory, and also: - * http://ux1.math.us.edu.pl/~szyjewski/FAQ/liczby/iony.htm - * @var array - * @access private - */ - var $_exponent = array( - // potêga dziesi±tki => liczba pojedyncza, podwójna, mnoga - 0 => array('','',''), - 3 => array('tysi±c','tysi±ce','tysiêcy'), - 6 => array('milion','miliony','milionów'), - 9 => array('miliard','miliardy','miliardów'), - 12 => array('bilion','biliony','bilionów'), - 15 => array('biliard','biliardy','biliardów'), - 18 => array('trylion','tryliony','trylionów'), - 21 => array('tryliard','tryliardy','tryliardów'), - 24 => array('kwadrylion','kwadryliony','kwadrylionów'), - 27 => array('kwadryliard','kwadryliardy','kwadryliardów'), - 30 => array('kwintylion','kwintyliony','kwintylionów'), - 33 => array('kwintyliiard','kwintyliardy','kwintyliardów'), - 36 => array('sekstylion','sekstyliony','sekstylionów'), - 39 => array('sekstyliard','sekstyliardy','sekstyliardów'), - 42 => array('septylion','septyliony','septylionów'), - 45 => array('septyliard','septyliardy','septyliardów'), - 48 => array('oktylion','oktyliony','oktylionów'), - 51 => array('oktyliard','oktyliardy','oktyliardów'), - 54 => array('nonylion','nonyliony','nonylionów'), - 57 => array('nonyliard','nonyliardy','nonyliardów'), - 60 => array('decylion','decyliony','decylionów'), - 63 => array('decyliard','decyliardy','decyliardów'), - 100 => array('centylion','centyliony','centylionów'), - 103 => array('centyliard','centyliardy','centyliardów'), - 120 => array('wicylion','wicylion','wicylion'), - 123 => array('wicyliard','wicyliardy','wicyliardów'), - 180 => array('trycylion','trycylion','trycylion'), - 183 => array('trycyliard','trycyliardy','trycyliardów'), - 240 => array('kwadragilion','kwadragilion','kwadragilion'), - 243 => array('kwadragiliard','kwadragiliardy','kwadragiliardów'), - 300 => array('kwinkwagilion','kwinkwagilion','kwinkwagilion'), - 303 => array('kwinkwagiliard','kwinkwagiliardy','kwinkwagiliardów'), - 360 => array('seskwilion','seskwilion','seskwilion'), - 363 => array('seskwiliard','seskwiliardy','seskwiliardów'), - 420 => array('septagilion','septagilion','septagilion'), - 423 => array('septagiliard','septagiliardy','septagiliardów'), - 480 => array('oktogilion','oktogilion','oktogilion'), - 483 => array('oktogiliard','oktogiliardy','oktogiliardów'), - 540 => array('nonagilion','nonagilion','nonagilion'), - 543 => array('nonagiliard','nonagiliardy','nonagiliardów'), - 600 => array('centylion','centyliony','centylionów'), - 603 => array('centyliard','centyliardy','centyliardów'), - 6000018 => array('milinilitrylion','milinilitryliony','milinilitrylionów') - ); - - /** - * The array containing the digits (indexed by the digits themselves). - * @var array - * @access private - */ - var $_digits = array( - 0 => 'zero', 'jeden', 'dwa', 'trzy', 'cztery', - 'piêæ', 'sze¶æ', 'siedem', 'osiem', 'dziewiêæ' - ); - - /** - * The word separator - * @var string - * @access private - */ - var $_sep = ' '; - - /** - * The currency names (based on the below links, - * informations from central bank websites and on encyclopedias) - * - * @var array - * @link http://www.xe.com/iso4217.htm Currency codes - * @link http://www.republika.pl/geographia/peuropy.htm Europe review - * @link http://pieniadz.hoga.pl/waluty_objasnienia.asp Currency service - * @access private - */ - var $_currency_names = array( - 'ALL' => array(array('lek','leki','leków'), array('quindarka','quindarki','quindarek')), - 'AUD' => array(array('dolar australijski', 'dolary australijskie', 'dolarów australijskich'), array('cent', 'centy', 'centów')), - 'BAM' => array(array('marka','marki','marek'), array('fenig','fenigi','fenigów')), - 'BGN' => array(array('lew','lewy','lew'), array('stotinka','stotinki','stotinek')), - 'BRL' => array(array('real','reale','realów'), array('centavos','centavos','centavos')), - 'BYR' => array(array('rubel','ruble','rubli'), array('kopiejka','kopiejki','kopiejek')), - 'CAD' => array(array('dolar kanadyjski', 'dolary kanadyjskie', 'dolarów kanadyjskich'), array('cent', 'centy', 'centów')), - 'CHF' => array(array('frank szwajcarski','franki szwajcarskie','franków szwajcarskich'), array('rapp','rappy','rappów')), - 'CYP' => array(array('funt cypryjski','funty cypryjskie','funtów cypryjskich'), array('cent', 'centy', 'centów')), - 'CZK' => array(array('korona czeska','korony czeskie','koron czeskich'), array('halerz','halerze','halerzy')), - 'DKK' => array(array('korona duñska','korony duñskie','koron duñskich'), array('ore','ore','ore')), - 'EEK' => array(array('korona estoñska','korony estoñskie','koron estoñskich'), array('senti','senti','senti')), - 'EUR' => array(array('euro', 'euro', 'euro'), array('eurocent', 'eurocenty', 'eurocentów')), - 'GBP' => array(array('funt szterling','funty szterlingi','funtów szterlingów'), array('pens','pensy','pensów')), - 'HKD' => array(array('dolar Hongkongu','dolary Hongkongu','dolarów Hongkongu'), array('cent', 'centy', 'centów')), - 'HRK' => array(array('kuna','kuny','kun'), array('lipa','lipy','lip')), - 'HUF' => array(array('forint','forinty','forintów'), array('filler','fillery','fillerów')), - 'ISK' => array(array('korona islandzka','korony islandzkie','koron islandzkich'), array('aurar','aurar','aurar')), - 'JPY' => array(array('jen','jeny','jenów'), array('sen','seny','senów')), - 'LTL' => array(array('lit','lity','litów'), array('cent', 'centy', 'centów')), - 'LVL' => array(array('³at','³aty','³atów'), array('sentim','sentimy','sentimów')), - 'MKD' => array(array('denar','denary','denarów'), array('deni','deni','deni')), - 'MTL' => array(array('lira maltañska','liry maltañskie','lir maltañskich'), array('centym','centymy','centymów')), - 'NOK' => array(array('korona norweska','korony norweskie','koron norweskich'), array('oere','oere','oere')), - 'PLN' => array(array('z³oty', 'z³ote', 'z³otych'), array('grosz', 'grosze', 'groszy')), - 'ROL' => array(array('lej','leje','lei'), array('bani','bani','bani')), - 'RUB' => array(array('rubel','ruble','rubli'), array('kopiejka','kopiejki','kopiejek')), - 'SEK' => array(array('korona szwedzka','korony szwedzkie','koron szweckich'), array('oere','oere','oere')), - 'SIT' => array(array('tolar','tolary','tolarów'), array('stotinia','stotinie','stotini')), - 'SKK' => array(array('korona s³owacka','korony s³owackie','koron s³owackich'), array('halerz','halerze','halerzy')), - 'TRL' => array(array('lira turecka','liry tureckie','lir tureckich'), array('kurusza','kurysze','kuruszy')), - 'UAH' => array(array('hrywna','hrywna','hrywna'), array('cent', 'centy', 'centów')), - 'USD' => array(array('dolar','dolary','dolarów'), array('cent', 'centy', 'centów')), - 'YUM' => array(array('dinar','dinary','dinarów'), array('para','para','para')), - 'ZAR' => array(array('rand','randy','randów'), array('cent', 'centy', 'centów')) - ); - - /** - * The default currency name - * @var string - * @access public - */ - var $def_currency = 'PLN'; // Polish zloty - - // }}} - // {{{ toWords() - - /** - * Converts a number to its word representation - * in Polish language - * - * @param integer $num An integer between -infinity and infinity inclusive :) - * that need to be converted to words - * @param integer $power The power of ten for the rest of the number to the right. - * Optional, defaults to 0. - * @param integer $powsuffix The power name to be added to the end of the return string. - * Used internally. Optional, defaults to ''. - * - * @return string The corresponding word representation - * - * @access public - * @author Piotr Klaban - * @since PHP 4.2.3 - */ - function toWords($num, $power = 0, $powsuffix = '') { - $ret = ''; - - // add a minus sign - if (substr($num, 0, 1) == '-') { - $ret = $this->_sep . $this->_minus; - $num = substr($num, 1); - } - - // strip excessive zero signs and spaces - $num = trim($num); - $num = preg_replace('/^0+/','',$num); - - if (strlen($num) > 3) { - $maxp = strlen($num)-1; - $curp = $maxp; - for ($p = $maxp; $p > 0; --$p) { // power - - // check for highest power - if (isset($this->_exponent[$p])) { - // send substr from $curp to $p - $snum = substr($num, $maxp - $curp, $curp - $p + 1); - $snum = preg_replace('/^0+/','',$snum); - if ($snum !== '') { - $cursuffix = $this->_exponent[$power][count($this->_exponent[$power])-1]; - if ($powsuffix != '') - $cursuffix .= $this->_sep . $powsuffix; - $ret .= $this->toWords($snum, $p, $cursuffix); - } - $curp = $p - 1; - continue; - } - } - $num = substr($num, $maxp - $curp, $curp - $p + 1); - if ($num == 0) { - return $ret; - } - } elseif ($num == 0 || $num == '') { - return $this->_sep . $this->_digits[0]; - } - - $h = $t = $d = 0; - - switch(strlen($num)) { - case 3: - $h = (int)substr($num,-3,1); - - case 2: - $t = (int)substr($num,-2,1); - - case 1: - $d = (int)substr($num,-1,1); - break; - - case 0: - return; - break; - } - - switch ($h) { - case 9: - $ret .= $this->_sep . 'dziewiêæset'; - break; - - case 8: - $ret .= $this->_sep . 'osiemset'; - break; - - case 7: - $ret .= $this->_sep . 'siedemset'; - break; - - case 6: - $ret .= $this->_sep . 'sze¶æset'; - break; - - case 5: - $ret .= $this->_sep . 'piêæset'; - break; - - case 4: - $ret .= $this->_sep . 'czterysta'; - break; - - case 3: - $ret .= $this->_sep . 'trzysta'; - break; - - case 2: - $ret .= $this->_sep . 'dwie¶cie'; - break; - - case 1: - $ret .= $this->_sep . 'sto'; - break; - } - - switch ($t) { - case 9: - case 8: - case 7: - case 6: - case 5: - $ret .= $this->_sep . $this->_digits[$t] . 'dziesi±t'; - break; - - case 4: - $ret .= $this->_sep . 'czterdzie¶ci'; - break; - - case 3: - $ret .= $this->_sep . 'trzydzie¶ci'; - break; - - case 2: - $ret .= $this->_sep . 'dwadzie¶cia'; - break; - - case 1: - switch ($d) { - case 0: - $ret .= $this->_sep . 'dziesiêæ'; - break; - - case 1: - $ret .= $this->_sep . 'jedena¶cie'; - break; - - case 2: - case 3: - case 7: - case 8: - $ret .= $this->_sep . $this->_digits[$d] . 'na¶cie'; - break; - - case 4: - $ret .= $this->_sep . 'czterna¶cie'; - break; - - case 5: - $ret .= $this->_sep . 'piêtna¶cie'; - break; - - case 6: - $ret .= $this->_sep . 'szesna¶cie'; - break; - - case 9: - $ret .= $this->_sep . 'dziewiêtna¶cie'; - break; - } - break; - } - - if ($t != 1 && $d > 0) - $ret .= $this->_sep . $this->_digits[$d]; - - if ($t == 1) - $d = 0; - - if (( $h + $t ) > 0 && $d == 1) - $d = 0; - - if ($power > 0) { - if (isset($this->_exponent[$power])) - $lev = $this->_exponent[$power]; - - if (!isset($lev) || !is_array($lev)) - return null; - - switch ($d) { - case 1: - $suf = $lev[0]; - break; - case 2: - case 3: - case 4: - $suf = $lev[1]; - break; - case 0: - case 5: - case 6: - case 7: - case 8: - case 9: - $suf = $lev[2]; - break; - } - $ret .= $this->_sep . $suf; - } - - if ($powsuffix != '') - $ret .= $this->_sep . $powsuffix; - - return $ret; - } - // }}} - // {{{ toCurrency() - - /** - * Converts a currency value to its word representation - * (with monetary units) in Polish language - * - * @param integer $int_curr An international currency symbol - * as defined by the ISO 4217 standard (three characters) - * @param integer $decimal A money total amount without fraction part (e.g. amount of dollars) - * @param integer $fraction Fractional part of the money amount (e.g. amount of cents) - * Optional. Defaults to false. - * - * @return string The corresponding word representation for the currency - * - * @access public - * @author Piotr Klaban - * @since Numbers_Words 0.4 - */ - function toCurrencyWords($int_curr, $decimal, $fraction = false) { - $int_curr = strtoupper($int_curr); - if (!isset($this->_currency_names[$int_curr])) { - $int_curr = $this->def_currency; - } - $curr_names = $this->_currency_names[$int_curr]; - $ret = trim($this->toWords($decimal)); - $lev = $this->_get_numlevel($decimal); - $ret .= $this->_sep . $curr_names[0][$lev]; - - if ($fraction !== false) { - $ret .= $this->_sep . trim($this->toWords($fraction)); - $lev = $this->_get_numlevel($fraction); - $ret .= $this->_sep . $curr_names[1][$lev]; - } - return $ret; - } - // }}} - // {{{ _get_numlevel() - - /** - * Returns grammatical "level" of the number - this is necessary - * for choosing the right suffix for exponents and currency names. - * - * @param integer $num An integer between -infinity and infinity inclusive - * that need to be converted to words - * - * @return integer The grammatical "level" of the number. - * - * @access private - * @author Piotr Klaban - * @since Numbers_Words 0.4 - */ - function _get_numlevel($num) { - $num = (int)substr($num,-3); - $h = $t = $d = $lev = 0; - - switch(strlen($num)) { - case 3: - $h = (int)substr($num,-3,1); - - case 2: - $t = (int)substr($num,-2,1); - - case 1: - $d = (int)substr($num,-1,1); - break; - - case 0: - return $lev; - break; - } - if ($t == 1) - $d = 0; - - if (( $h + $t ) > 0 && $d == 1) - $d = 0; - - switch ($d) { - case 1: - $lev = 0; - break; - case 2: - case 3: - case 4: - $lev = 1; - break; - default: - $lev = 2; - } - return $lev; - } - // }}} -} - -?> diff --git a/gulliver/thirdparty/pear/Numbers/Words/lang.pt_BR.php b/gulliver/thirdparty/pear/Numbers/Words/lang.pt_BR.php deleted file mode 100644 index 665afe092..000000000 --- a/gulliver/thirdparty/pear/Numbers/Words/lang.pt_BR.php +++ /dev/null @@ -1,241 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: lang.pt_BR.php,v 1.6 2003/09/29 12:23:58 makler Exp $ -// -// Numbers_Words class extension to spell numbers in Brazilian Portuguese language. -// - - -/** - * Class for translating numbers into Brazilian Portuguese. - * - * @author Marcelo Subtil Marcal - * @package Numbers_Words - */ - -/** - * Include needed files - */ -require_once "Numbers/Words.php"; - -/** - * Class for translating numbers into Brazilian Portuguese. - * - * @author Marcelo Subtil Marcal - * @package Numbers_Words - */ -class Numbers_Words_pt_BR extends Numbers_Words -{ - - /** - * Locale name - * @var string - * @access public - */ - var $locale = 'pt_BR'; - - /** - * Language name in English - * @var string - * @access public - */ - var $lang = 'Brazilian Portuguese'; - - /** - * Native language name - * @var string - * @access public - */ - var $lang_native = 'Português Brasileiro'; - - /** - * The word for the minus sign - * @var string - * @access private - */ - var $_minus = 'menos'; - - /** - * The word separator - * @var string - * @access private - */ - var $_sep = ' '; - - /** - * The array containing the digits (indexed by the digits themselves). - * @var array - * @access private - */ - var $_unidade = array( - '', - 'um', - 'dois', - 'três', - 'quatro', - 'cinco', - 'seis', - 'sete', - 'oito', - 'nove' - ); - - /** - * The array containing numbers 10-19. - * @var array - * @access private - */ - var $_dezena10 = array( - 'dez', - 'onze', - 'doze', - 'treze', - 'quatorze', - 'quinze', - 'dezesseis', - 'dezessete', - 'dezoito', - 'dezenove' - ); - - /** - * The array containing numbers for 10,20,...,90. - * @var array - * @access private - */ - var $_dezena = array( - '', - 'dez', - 'vinte', - 'trinta', - 'quarenta', - 'cinquenta', - 'sessenta', - 'setenta', - 'oitenta', - 'noventa' - ); - - /** - * The array containing numbers for hundrets. - * @var array - * @access private - */ - var $_centena = array( - '', - 'cem', - 'duzentos', - 'trezentos', - 'quatrocentos', - 'quinhentos', - 'seiscentos', - 'setecentos', - 'oitocentos', - 'novecentos' - ); - - /** - * The sufixes for exponents (singular and plural) - * @var array - * @access private - */ - var $_expoente = array( - '', - 'mil', - 'milhão', - 'bilhão', - 'trilhão', - 'quatrilhão', - 'quintilhão', - 'sextilhão', - 'setilhão', - 'octilhão', - 'nonilhão', - 'decilhão', - 'undecilhão', - 'dodecilhão', - 'tredecilhão', - 'quatuordecilhão', - 'quindecilhão', - 'sedecilhão', - 'septendecilhão' - ); - - - - /** - * Converts a number to its word representation - * in Brazilian Portuguese language - * - * @param integer $num An integer between -infinity and infinity inclusive :) - * that need to be converted to words - * - * @return string The corresponding word representation - * - * @access public - * @author Marcelo Subtil Marcal - * @since PHP 4.2.3 - */ - function toWords($num) { - - $ret = ''; - - $num = trim($num); - - if (substr($num, 0, 1) == '-') { - $ret = $this->_sep . $this->_minus; - $num = substr($num, 1); - } - - // strip excessive zero signs and spaces - $num = trim($num); - $num = preg_replace('/^0+/','',$num); - - while (strlen($num) % 3 != 0) { - $num = "0" . $num; - } - - $num = ereg_replace("(...)", "\\1.", $num); - $num = ereg_replace("\.$", "", $num); - - $inteiro = explode(".", $num); - - for ($i = 0; $i < count($inteiro); $i++) { - $ret .= (($inteiro[$i] > 100) && ($inteiro[$i] < 200)) ? "cento" : $this->_centena[$inteiro[$i][0]]; - $ret .= ($inteiro[$i][0] && ($inteiro[$i][1] || $inteiro[$i][2])) ? " e " : ""; - $ret .= ($inteiro[$i][1] < 2) ? "" : $this->_dezena[$inteiro[$i][1]]; - $ret .= (($inteiro[$i][1] > 1) && ($inteiro[$i][2])) ? " e " : ""; - $ret .= ($inteiro > 0) ? ( ($inteiro[$i][1] == 1) ? $this->_dezena10[$inteiro[$i][2]] : $this->_unidade[$inteiro[$i][2]] ) : ""; - $ret .= $inteiro[$i] > 0 ? " " . ($inteiro[$i] > 1 ? str_replace("ão", "ões", $this->_expoente[count($inteiro)-1-$i]) : $this->_expoente[count($inteiro)-1-$i]) : ""; - - if ($ret && (isset($inteiro[$i+1]))) { - if ($inteiro[$i+1] != "000") { - $ret .= ($i+1) == (count($inteiro)-1) ? " e " : ", "; - } - } - - } - - return $ret ? " $ret" : " zero"; - - } -} - -?> diff --git a/gulliver/thirdparty/pear/Numbers/Words/lang.ru.php b/gulliver/thirdparty/pear/Numbers/Words/lang.ru.php deleted file mode 100644 index 28735326a..000000000 --- a/gulliver/thirdparty/pear/Numbers/Words/lang.ru.php +++ /dev/null @@ -1,616 +0,0 @@ - | -// | Andrey Demenev | -// +----------------------------------------------------------------------+ -// -// $Id: $ -// -// Numbers_Words class extension to spell numbers in Russian language. -// - -/** - * Class for translating numbers into Russian. - * - * @author Andrey Demenev - * @package Numbers_Words - */ - -/** - * Include needed files - */ -require_once("Numbers/Words.php"); - -/** - * Class for translating numbers into Russian. - * - * @author Andrey Demenev - * @package Numbers_Words - */ -class Numbers_Words_ru extends Numbers_Words -{ - - // {{{ properties - - /** - * Locale name - * @var string - * @access public - */ - var $locale = 'ru'; - - /** - * Language name in English - * @var string - * @access public - */ - var $lang = 'Russian'; - - /** - * Native language name - * @var string - * @access public - */ - var $lang_native = 'Ðóññêèé'; - - /** - * The word for the minus sign - * @var string - * @access private - */ - var $_minus = 'ìèíóñ'; // minus sign - - /** - * The sufixes for exponents (singular) - * Names partly based on: - * http://home.earthlink.net/~mrob/pub/math/largenum.html - * http://mathforum.org/dr.math/faq/faq.large.numbers.html - * http://www.mazes.com/AmericanNumberingSystem.html - * @var array - * @access private - */ - var $_exponent = array( - 0 => '', - 6 => 'ìèëëèîí', - 9 => 'ìèëëèàðä', - 12 => 'òðèëëèîí', - 15 => 'êâàäðèëëèîí', - 18 => 'êâèíòèëëèîí', - 21 => 'ñåêñòèëëèîí', - 24 => 'ñåïòèëëèîí', - 27 => 'îêòèëëèîí', - 30 => 'íîíèëëèîí', - 33 => 'äåöèëëèîí', - 36 => 'óíäåöèëëèîí', - 39 => 'äóîäåöèëëèîí', - 42 => 'òðåäåöèëëèîí', - 45 => 'êâàòóîðäåöèëëèîí', - 48 => 'êâèíäåöèëëèîí', - 51 => 'ñåêñäåöèëëèîí', - 54 => 'ñåïòåíäåöèëëèîí', - 57 => 'îêòîäåöèëëèîí', - 60 => 'íîâåìäåöèëëèîí', - 63 => 'âèãèíòèëëèîí', - 66 => 'óíâèãèíòèëëèîí', - 69 => 'äóîâèãèíòèëëèîí', - 72 => 'òðåâèãèíòèëëèîí', - 75 => 'êâàòóîðâèãèíòèëëèîí', - 78 => 'êâèíâèãèíòèëëèîí', - 81 => 'ñåêñâèãèíòèëëèîí', - 84 => 'ñåïòåíâèãèíòèëëèîí', - 87 => 'îêòîâèãèíòèëëèîí', - 90 => 'íîâåìâèãèíòèëëèîí', - 93 => 'òðèãèíòèëëèîí', - 96 => 'óíòðèãèíòèëëèîí', - 99 => 'äóîòðèãèíòèëëèîí', - 102 => 'òðåòðèãèíòèëëèîí', - 105 => 'êâàòîðòðèãèíòèëëèîí', - 108 => 'êâèíòðèãèíòèëëèîí', - 111 => 'ñåêñòðèãèíòèëëèîí', - 114 => 'ñåïòåíòðèãèíòèëëèîí', - 117 => 'îêòîòðèãèíòèëëèîí', - 120 => 'íîâåìòðèãèíòèëëèîí', - 123 => 'êâàäðàãèíòèëëèîí', - 126 => 'óíêâàäðàãèíòèëëèîí', - 129 => 'äóîêâàäðàãèíòèëëèîí', - 132 => 'òðåêâàäðàãèíòèëëèîí', - 135 => 'êâàòîðêâàäðàãèíòèëëèîí', - 138 => 'êâèíêâàäðàãèíòèëëèîí', - 141 => 'ñåêñêâàäðàãèíòèëëèîí', - 144 => 'ñåïòåíêâàäðàãèíòèëëèîí', - 147 => 'îêòîêâàäðàãèíòèëëèîí', - 150 => 'íîâåìêâàäðàãèíòèëëèîí', - 153 => 'êâèíêâàãèíòèëëèîí', - 156 => 'óíêâèíêàãèíòèëëèîí', - 159 => 'äóîêâèíêàãèíòèëëèîí', - 162 => 'òðåêâèíêàãèíòèëëèîí', - 165 => 'êâàòîðêâèíêàãèíòèëëèîí', - 168 => 'êâèíêâèíêàãèíòèëëèîí', - 171 => 'ñåêñêâèíêàãèíòèëëèîí', - 174 => 'ñåïòåíêâèíêàãèíòèëëèîí', - 177 => 'îêòîêâèíêàãèíòèëëèîí', - 180 => 'íîâåìêâèíêàãèíòèëëèîí', - 183 => 'ñåêñàãèíòèëëèîí', - 186 => 'óíñåêñàãèíòèëëèîí', - 189 => 'äóîñåêñàãèíòèëëèîí', - 192 => 'òðåñåêñàãèíòèëëèîí', - 195 => 'êâàòîðñåêñàãèíòèëëèîí', - 198 => 'êâèíñåêñàãèíòèëëèîí', - 201 => 'ñåêññåêñàãèíòèëëèîí', - 204 => 'ñåïòåíñåêñàãèíòèëëèîí', - 207 => 'îêòîñåêñàãèíòèëëèîí', - 210 => 'íîâåìñåêñàãèíòèëëèîí', - 213 => 'ñåïòàãèíòèëëèîí', - 216 => 'óíñåïòàãèíòèëëèîí', - 219 => 'äóîñåïòàãèíòèëëèîí', - 222 => 'òðåñåïòàãèíòèëëèîí', - 225 => 'êâàòîðñåïòàãèíòèëëèîí', - 228 => 'êâèíñåïòàãèíòèëëèîí', - 231 => 'ñåêññåïòàãèíòèëëèîí', - 234 => 'ñåïòåíñåïòàãèíòèëëèîí', - 237 => 'îêòîñåïòàãèíòèëëèîí', - 240 => 'íîâåìñåïòàãèíòèëëèîí', - 243 => 'îêòîãèíòèëëèîí', - 246 => 'óíîêòîãèíòèëëèîí', - 249 => 'äóîîêòîãèíòèëëèîí', - 252 => 'òðåîêòîãèíòèëëèîí', - 255 => 'êâàòîðîêòîãèíòèëëèîí', - 258 => 'êâèíîêòîãèíòèëëèîí', - 261 => 'ñåêñîêòîãèíòèëëèîí', - 264 => 'ñåïòîêòîãèíòèëëèîí', - 267 => 'îêòîîêòîãèíòèëëèîí', - 270 => 'íîâåìîêòîãèíòèëëèîí', - 273 => 'íîíàãèíòèëëèîí', - 276 => 'óííîíàãèíòèëëèîí', - 279 => 'äóîíîíàãèíòèëëèîí', - 282 => 'òðåíîíàãèíòèëëèîí', - 285 => 'êâàòîðíîíàãèíòèëëèîí', - 288 => 'êâèííîíàãèíòèëëèîí', - 291 => 'ñåêñíîíàãèíòèëëèîí', - 294 => 'ñåïòåííîíàãèíòèëëèîí', - 297 => 'îêòîíîíàãèíòèëëèîí', - 300 => 'íîâåìíîíàãèíòèëëèîí', - 303 => 'öåíòèëëèîí' - ); - - /** - * The array containing the teens' :) names - * @var array - * @access private - */ - var $_teens = array( - 11=>'îäèííàäöàòü', - 12=>'äâåíàäöàòü', - 13=>'òðèíàäöàòü', - 14=>'÷åòûðíàäöàòü', - 15=>'ïÿòíàäöàòü', - 16=>'øåñòíàäöàòü', - 17=>'ñåìíàäöàòü', - 18=>'âîñåìíàäöàòü', - 19=>'äåâÿòíàäöàòü' - ); - - /** - * The array containing the tens' names - * @var array - * @access private - */ - var $_tens = array( - 2=>'äâàäöàòü', - 3=>'òðèäöàòü', - 4=>'ñîðîê', - 5=>'ïÿòüäåñÿò', - 6=>'øåñòüäåñÿò', - 7=>'ñåìüäåñÿò', - 8=>'âîñåìüäåñÿò', - 9=>'äåâÿíîñòî' - ); - - /** - * The array containing the hundreds' names - * @var array - * @access private - */ - var $_hundreds = array( - 1=>'ñòî', - 2=>'äâåñòè', - 3=>'òðèñòà', - 4=>'÷åûðåñòà', - 5=>'ïÿòüñîò', - 6=>'øåñòüñîò', - 7=>'ñåìüñîò', - 8=>'âîñåìüñîò', - 9=>'äåâÿòüñîò' - ); - - /** - * The array containing the digits - * for neutral, male and female - * @var array - * @access private - */ - var $_digits = array( - array('íîëü', 'îäíî', 'äâà', 'òðè', '÷åòûðå','ïÿòü', 'øåñòü', 'ñåìü', 'âîñåìü', 'äåâÿòü'), - array('íîëü', 'îäèí', 'äâà', 'òðè', '÷åòûðå','ïÿòü', 'øåñòü', 'ñåìü', 'âîñåìü', 'äåâÿòü'), - array('íîëü', 'îäíà', 'äâå', 'òðè', '÷åòûðå','ïÿòü', 'øåñòü', 'ñåìü', 'âîñåìü', 'äåâÿòü') - ); - - /** - * The word separator - * @var string - * @access private - */ - var $_sep = ' '; - - /** - * The currency names (based on the below links, - * informations from central bank websites and on encyclopedias) - * - * @var array - * @link http://www.jhall.demon.co.uk/currency/by_abbrev.html World currencies - * @link http://www.rusimpex.ru/Content/Reference/Refinfo/valuta.htm Foreign currencies names - * @link http://www.cofe.ru/Finance/money.asp Currencies names - * @access private - */ - var $_currency_names = array( - 'ALL' => array( - array(1,'ëåê','ëåêà','ëåêîâ'), - array(2,'êèíäàðêà','êèíäàðêè','êèíäàðîê') - ), - 'AUD' => array( - array(1,'àâñòðàëèéñêèé äîëëàð','àâñòðàëèéñêèõ äîëëàðà','àâñòðàëèéñêèõ äîëëàðîâ'), - array(1,'öåíò','öåíòà','öåíòîâ') - ), - 'BGN' => array( - array(1,'ëåâ','ëåâà','ëåâîâ'), - array(2,'ñòîòèíêà','ñòîòèíêè','ñòîòèíîê') - ), - 'BRL' => array( - array(1,'áðàçèëüñêèé ðåàë','áðàçèëüñêèõ ðåàëà','áðàçèëüñêèõ ðåàëîâ'), - array(1,'ñåíòàâî','ñåíòàâî','ñåíòàâî') - ), - 'BYR' => array( - array(1,'áåëîðóññêèé ðóáëü','áåëîðóññêèõ ðóáëÿ','áåëîðóññêèõ ðóáëåé'), - array(2,'êîïåéêà','êîïåéêè','êîïååê') - ), - 'CAD' => array( - array(1,'êàíàäñêèé äîëëàð','êàíàäñêèõ äîëëàðà','êàíàäñêèõ äîëëàðîâ'), - array(1,'öåíò','öåíòà','öåíòîâ') - ), - 'CHF' => array( - array(1,'øâåéöàðñêèé ôðàíê','øâåéöàðñêèõ ôðàíêà','øâåéöàðñêèõ ôðàíêîâ'), - array(1,'ñàíòèì','ñàíòèìà','ñàíòèìîâ') - ), - 'CYP' => array( - array(1,'êèïðñêèé ôóíò','êèïðñêèõ ôóíòà','êèïðñêèõ ôóíòîâ'), - array(1,'öåíò','öåíòà','öåíòîâ') - ), - 'CZK' => array( - array(2,'÷åøñêàÿ êðîíà','÷åøñêèõ êðîíû','÷åøñêèõ êðîí'), - array(1,'ãàëèðæ','ãàëèðæà','ãàëèðæåé') - ), - 'DKK' => array( - array(2,'äàòñêàÿ êðîíà','äàòñêèõ êðîíû','äàòñêèõ êðîí'), - array(1,'ýðå','ýðå','ýðå') - ), - 'EEK' => array( - array(2,'ýñòîíñêàÿ êðîíà','ýñòîíñêèõ êðîíû','ýñòîíñêèõ êðîí'), - array(1,'ñåíòè','ñåíòè','ñåíòè') - ), - 'EUR' => array( - array(1,'åâðî','åâðî','åâðî'), - array(1,'åâðîöåíò','åâðîöåíòà','åâðîöåíòîâ') - ), - 'CYP' => array( - array(1,'ôóíò ñòåðëèíãîâ','ôóíòà ñòåðëèíãîâ','ôóíòîâ ñòåðëèíãîâ'), - array(1,'ïåíñ','ïåíñà','ïåíñîâ') - ), - 'CAD' => array( - array(1,'ãîíêîíãñêèé äîëëàð','ãîíêîíãñêèõ äîëëàðà','ãîíêîíãñêèõ äîëëàðîâ'), - array(1,'öåíò','öåíòà','öåíòîâ') - ), - 'HRK' => array( - array(2,'õîðâàòñêàÿ êóíà','õîðâàòñêèõ êóíû','õîðâàòñêèõ êóí'), - array(2,'ëèïà','ëèïû','ëèï') - ), - 'HUF' => array( - array(1,'âåíãåðñêèé ôîðèíò','âåíãåðñêèõ ôîðèíòà','âåíãåðñêèõ ôîðèíòîâ'), - array(1,'ôèëëåð','ôèëëåðà','ôèëëåðîâ') - ), - 'ISK' => array( - array(2,'èñëàíäñêàÿ êðîíà','èñëàíäñêèõ êðîíû','èñëàíäñêèõ êðîí'), - array(1,'ýðå','ýðå','ýðå') - ), - 'JPY' => array( - array(2,'èåíà','èåíû','èåí'), - array(2,'ñåíà','ñåíû','ñåí') - ), - 'LTL' => array( - array(1,'ëèò','ëèòà','ëèòîâ'), - array(1,'öåíò','öåíòà','öåíòîâ') - ), - 'LVL' => array( - array(1,'ëàò','ëàòà','ëàòîâ'), - array(1,'ñåíòèì','ñåíòèìà','ñåíòèìîâ') - ), - 'MKD' => array( - array(1,'ìàêåäîíñêèé äèíàð','ìàêåäîíñêèõ äèíàðà','ìàêåäîíñêèõ äèíàðîâ'), - array(1,'äåíè','äåíè','äåíè') - ), - 'MTL' => array( - array(2,'ìàëüòèéñêàÿ ëèðà','ìàëüòèéñêèõ ëèðû','ìàëüòèéñêèõ ëèð'), - array(1,'ñåíòèì','ñåíòèìà','ñåíòèìîâ') - ), - 'NOK' => array( - array(2,'íîðâåæñêàÿ êðîíà','íîðâåæñêèõ êðîíû','íîðâåæñêèõ êðîí'), - array(0,'ýðå','ýðå','ýðå') - ), - 'PLN' => array( - array(1,'çëîòûé','çëîòûõ','çëîòûõ'), - array(1,'ãðîø','ãðîøà','ãðîøåé') - ), - 'ROL' => array( - array(1,'ðóìûíñêèé ëåé','ðóìûíñêèõ ëåé','ðóìûíñêèõ ëåé'), - array(1,'áàíè','áàíè','áàíè') - ), - // both RUR and RUR are used, I use RUB for shorter form - 'RUB' => array( - array(1,'ðóáëü','ðóáëÿ','ðóáëåé'), - array(2,'êîïåéêà','êîïåéêè','êîïååê') - ), - 'RUR' => array( - array(1,'ðîññèéñêèé ðóáëü','ðîññèéñêèõ ðóáëÿ','ðîññèéñêèõ ðóáëåé'), - array(2,'êîïåéêà','êîïåéêè','êîïååê') - ), - 'SEK' => array( - array(2,'øâåäñêàÿ êðîíà','øâåäñêèõ êðîíû','øâåäñêèõ êðîí'), - array(1,'ýðå','ýðå','ýðå') - ), - 'SIT' => array( - array(1,'ñëîâåíñêèé òîëàð','ñëîâåíñêèõ òîëàðà','ñëîâåíñêèõ òîëàðîâ'), - array(2,'ñòîòèíà','ñòîòèíû','ñòîòèí') - ), - 'SKK' => array( - array(2,'ñëîâàöêàÿ êðîíà','ñëîâàöêèõ êðîíû','ñëîâàöêèõ êðîí'), - array(0,'','','') - ), - 'TRL' => array( - array(2,'òóðåöêàÿ ëèðà','òóðåöêèõ ëèðû','òóðåöêèõ ëèð'), - array(1,'ïèàñòð','ïèàñòðà','ïèàñòðîâ') - ), - 'UAH' => array( - array(2,'ãðèâíà','ãðèâíû','ãðèâåí'), - array(1,'öåíò','öåíòà','öåíòîâ') - ), - 'USD' => array( - array(1,'äîëëàð ÑØÀ','äîëëàðà ÑØÀ','äîëëàðîâ ÑØÀ'), - array(1,'öåíò','öåíòà','öåíòîâ') - ), - 'YUM' => array( - array(1,'þãîñëàâñêèé äèíàð','þãîñëàâñêèõ äèíàðà','þãîñëàâñêèõ äèíàðîâ'), - array(1,'ïàðà','ïàðà','ïàðà') - ), - 'ZAR' => array( - array(1,'ðàíä','ðàíäà','ðàíäîâ'), - array(1,'öåíò','öåíòà','öåíòîâ') - ) - ); - - /** - * The default currency name - * @var string - * @access public - */ - var $def_currency = 'RUB'; // Russian rouble - - // }}} - // {{{ toWords() - - /** - * Converts a number to its word representation - * in Russian language - * - * @param integer $num An integer between -infinity and infinity inclusive :) - * that need to be converted to words - * @param integer $gender Gender of string, 0=neutral, 1=male, 2=female. - * Optional, defaults to 1. - * - * @return string The corresponding word representation - * - * @access private - * @author Andrey Demenev - */ - function toWords($num, $gender = 1) - { - return $this->_toWordsWithCase($num, $dummy, $gender); - } - - /** - * Converts a number to its word representation - * in Russian language and determines the case of string. - * - * @param integer $num An integer between -infinity and infinity inclusive :) - * that need to be converted to words - * @param integer $case A variable passed by reference which is set to case - * of the word associated with the number - * @param integer $gender Gender of string, 0=neutral, 1=male, 2=female. - * Optional, defaults to 1. - * - * @return string The corresponding word representation - * - * @access private - * @author Andrey Demenev - */ - function _toWordsWithCase($num, &$case, $gender = 1) - { - $ret = ''; - $case = 3; - - $num = trim($num); - - $sign = ""; - if (substr($num, 0, 1) == '-') { - $sign = $this->_minus . $this->_sep; - $num = substr($num, 1); - } - - while (strlen($num) % 3) $num = '0' . $num; - if ($num == 0 || $num == '') { - $ret .= $this->_digits[$gender][0]; - } - - else { - $power = 0; - while ($power < strlen($num)) { - if (!$power) { - $groupgender = $gender; - } elseif ($power == 3) { - $groupgender = 2; - } else { - $groupgender = 1; - } - $group = $this->_groupToWords(substr($num,-$power-3,3),$groupgender,$_case); - if (!$power) { - $case = $_case; - } - if ($power == 3) { - if ($_case == 1) { - $group .= $this->_sep . 'òûñÿ÷à'; - } elseif ($_case == 2) { - $group .= $this->_sep . 'òûñÿ÷è'; - } else { - $group .= $this->_sep . 'òûñÿ÷'; - } - } elseif ($group && $power>3 && isset($this->_exponent[$power])) { - $group .= $this->_sep . $this->_exponent[$power]; - if ($_case == 2) { - $group .= 'à'; - } elseif ($_case == 3) { - $group .= 'îâ'; - } - } - if ($group) { - $ret = $group . $this->_sep . $ret; - } - $power+=3; - } - } - - return $sign . $ret; - } - - // }}} - // {{{ _groupToWords() - - /** - * Converts a group of 3 digits to its word representation - * in Russian language. - * - * @param integer $num An integer between -infinity and infinity inclusive :) - * that need to be converted to words - * @param integer $gender Gender of string, 0=neutral, 1=male, 2=female. - * @param integer $case A variable passed by reference which is set to case - * of the word associated with the number - * - * @return string The corresponding word representation - * - * @access private - * @author Andrey Demenev - */ - function _groupToWords($num, $gender, &$case) - { - $ret = ''; - $case = 3; - if ((int)$num == 0) { - $ret = ''; - } elseif ($num < 10) { - $ret = $this->_digits[$gender][(int)$num]; - if ($num == 1) $case = 1; - elseif ($num < 5) $case = 2; - else $case = 3; - } else { - $num = str_pad($num,3,'0',STR_PAD_LEFT); - $hundreds = (int)$num{0}; - if ($hundreds) { - $ret = $this->_hundreds[$hundreds]; - if (substr($num,1) != '00') { - $ret .= $this->_sep; - } - $case = 3; - } - $tens=(int)$num{1}; - $ones=(int)$num{2}; - if ($tens || $ones) { - if ($tens == 1 && $ones == 0) $ret .= 'äåñÿòü'; - elseif ($tens < 2) $ret .= $this->_teens[$ones+10]; - else { - $ret .= $this->_tens[(int)$tens]; - if ($ones > 0) { - $ret .= $this->_sep - .$this->_digits[$gender][$ones]; - if ($ones == 1) { - $case = 1; - } elseif ($ones < 5) { - $case = 2; - } else { - $case = 3; - } - } - } - } - } - return $ret; - } - // }}} - // {{{ toCurrencyWords() - - /** - * Converts a currency value to its word representation - * (with monetary units) in Russian language - * - * @param integer $int_curr An international currency symbol - * as defined by the ISO 4217 standard (three characters) - * @param integer $decimal A money total amount without fraction part (e.g. amount of dollars) - * @param integer $fraction Fractional part of the money amount (e.g. amount of cents) - * Optional. Defaults to false. - * - * @return string The corresponding word representation for the currency - * - * @access public - * @author Andrey Demenev - */ - function toCurrencyWords($int_curr, $decimal, $fraction = false) - { - $int_curr = strtoupper($int_curr); - if (!isset($this->_currency_names[$int_curr])) { - $int_curr = $this->def_currency; - } - $curr_names = $this->_currency_names[$int_curr]; - $ret = trim($this->_toWordsWithCase($decimal, $case, 0, '', $curr_names[0][0])); - $ret .= $this->_sep . $curr_names[0][$case]; - - if ($fraction !== false) { - $ret .= $this->_sep . trim($this->_toWordsWithCase($fraction, $case, 0, '', $curr_names[1][0])); - $ret .= $this->_sep . $curr_names[1][$case]; - } - return $ret; - } - // }}} - -} - -?> diff --git a/gulliver/thirdparty/pear/Numbers/Words/lang.sv.php b/gulliver/thirdparty/pear/Numbers/Words/lang.sv.php deleted file mode 100644 index ac8024805..000000000 --- a/gulliver/thirdparty/pear/Numbers/Words/lang.sv.php +++ /dev/null @@ -1,310 +0,0 @@ - | -// | Robin Ericsson | -// +----------------------------------------------------------------------+ -// -// $Id: lang.de.php,v 1.1.1.1 2004/03/10 10:33:10 makler Exp $ -// -// Numbers_Words class extension to spell numbers in Swedish language. -// - -/** - * - * Class for translating numbers into Swedish. - * @author Robin Ericsson - * @package Numbers_Words - */ - -/** - * Include needed files - */ -require_once("Numbers/Words.php"); - -/** - * Class for translating numbers into Swedish. - * - * @author Robin Ericsson - * @package Numbers_Words - */ -class Numbers_Words_sv extends Numbers_Words -{ - - // {{{ properties - - /** - * Locale name - * @var string - * @access public - */ - var $locale = 'sv'; - - /** - * Language name in English - * @var string - * @access public - */ - var $lang = 'Swedish'; - - /** - * Native language name - * @var string - * @access public - */ - var $lang_native = 'Svenska'; - - /** - * The word for the minus sign - * @var string - * @access private - */ - var $_minus = 'Minus'; // minus sign - - /** - * The sufixes for exponents (singular and plural) - * @var array - * @access private - */ - var $_exponent = array( - 0 => array(''), - 3 => array('tusen', 'tusen'), - 6 => array('miljon','miljoner'), - 9 => array('miljard','miljarder'), - 12 => array('biljon','biljoner'), - 15 => array('biljard','biljarder'), - 18 => array('triljon','triljoner'), - 21 => array('triljard','triljarder'), - 24 => array('kvadriljon','kvadriljoner'), - 27 => array('kvadriljard','kvadriljarder'), - 30 => array('kvintiljon','kvintiljoner'), - 33 => array('kvintiljard','kvintiljarder'), - 36 => array('sextiljon','sextiljoner'), - 39 => array('sextiljard','sextiljarder'), - 42 => array('septiljon','septiljoner'), - 45 => array('septiljard','septiljarder'), - 48 => array('oktiljon','oktiljoner'), - 51 => array('oktiljard','oktiljarder'), - 54 => array('noniljon','noniljoner'), - 57 => array('noniljard','noniljarder'), - 60 => array('dekiljon','dekiljoner'), - 63 => array('dekiljard','dekiljarder'), - 120 => array('vigintiljon','vigintiljoner'), - 123 => array('vigintiljard','vigintiljarder'), - 600 => array('centiljon','centiljoner'), - 603 => array('centiljard','centiljarder') - ); - - /** - * The array containing the digits (indexed by the digits themselves). - * @var array - * @access private - */ - var $_digits = array( - 0 => 'noll', 'ett', 'två', 'tre', 'fyra', - 'fem', 'sex', 'sju', 'åtta', 'nio' - ); - - /** - * The word separator - * @var string - * @access private - */ - var $_sep = ''; - - /** - * The exponent word separator - * @var string - * @access private - */ - var $_sep2 = ' '; - - // }}} - // {{{ toWords() - - /** - * Converts a number to its word representation - * in Swedish language. - * - * @param integer $num An integer between -infinity and infinity inclusive :) - * that need to be converted to words - * @param integer $power The power of ten for the rest of the number to the right. - * Optional, defaults to 0. - * @param integer $powsuffix The power name to be added to the end of the return string. - * Used internally. Optional, defaults to ''. - * - * @return string The corresponding word representation - * - * @access private - * @author Piotr Klaban - * @author Robin Ericsson - * @since PHP 4.2.3 - */ - function toWords($num, $power = 0, $powsuffix = '') { - $ret = ''; - - // add a minus sign - if (substr($num, 0, 1) == '-') { - $ret = $this->_sep . $this->_minus; - $num = substr($num, 1); - } - - // strip excessive zero signs and spaces - $num = trim($num); - $num = preg_replace('/^0+/','',$num); - - if (strlen($num) > 3) { - $maxp = strlen($num)-1; - $curp = $maxp; - for ($p = $maxp; $p > 0; --$p) { // power - - // check for highest power - if (isset($this->_exponent[$p])) { - // send substr from $curp to $p - $snum = substr($num, $maxp - $curp, $curp - $p + 1); - $snum = preg_replace('/^0+/','',$snum); - if ($snum !== '') { - $cursuffix = $this->_exponent[$power][count($this->_exponent[$power])-1]; - if ($powsuffix != '') - $cursuffix .= $this->_sep . $powsuffix; - $ret .= $this->toWords($snum, $p, $cursuffix); - } - $curp = $p - 1; - continue; - } - } - $num = substr($num, $maxp - $curp, $curp - $p + 1); - if ($num == 0) { - return $ret; - } - } elseif ($num == 0 || $num == '') { - return $this->_sep . $this->_digits[0]; - } - - $h = $t = $d = 0; - - switch(strlen($num)) { - case 3: - $h = (int)substr($num,-3,1); - - case 2: - $t = (int)substr($num,-2,1); - - case 1: - $d = (int)substr($num,-1,1); - break; - - case 0: - return; - break; - } - - if ($h) { - $ret .= $this->_sep . $this->_digits[$h] . $this->_sep . 'hundra'; - } - - // ten, twenty etc. - switch ($t) { - case 5: - case 6: - case 7: - $ret .= $this->_sep . $this->_digits[$t] . 'tio'; - break; - - case 9: - $ret .= $this->_sep . 'nittio'; - break; - - case 8: - $ret .= $this->_sep . 'åttio'; - break; - - case 4: - $ret .= $this->_sep . 'fyrtio'; - break; - - case 3: - $ret .= $this->_sep . 'trettio'; - break; - - case 2: - $ret .= $this->_sep . 'tjugo'; - break; - - case 1: - switch ($d) { - case 0: - $ret .= $this->_sep . 'tio'; - break; - - case 1: - $ret .= $this->_sep . 'elva'; - break; - - case 2: - $ret .= $this->_sep . 'tolv'; - break; - - case 3: - $ret .= $this->_sep . 'tretton'; - break; - - case 4: - $ret .= $this->_sep . 'fjorton'; - break; - - case 5: - case 6: - $ret .= $this->_sep . $this->_digits[$d] . 'ton'; - break; - - case 7: - $ret .= $this->_sep . 'sjutton'; - break; - - case 8: - $ret .= $this->_sep . 'arton'; - break; - case 9: - $ret .= $this->_sep . 'nitton'; - } - break; - } - - if ($t != 1 && $d > 0) { // add digits only in <0>,<1,9> and <21,inf> - // add minus sign between [2-9] and digit - $ret .= $this->_sep . $this->_digits[$d]; - } - - if ($power > 0) { - if (isset($this->_exponent[$power])) - $lev = $this->_exponent[$power]; - - if (!isset($lev) || !is_array($lev)) - return null; - - $ret .= $this->_sep . $lev[0]; - } - - if ($powsuffix != '') - $ret .= $this->_sep . $powsuffix; - - return $ret; - } - // }}} -} - -?> diff --git a/gulliver/thirdparty/pear/OLE/OLE.php b/gulliver/thirdparty/pear/OLE/OLE.php deleted file mode 100644 index 637e189c8..000000000 --- a/gulliver/thirdparty/pear/OLE/OLE.php +++ /dev/null @@ -1,410 +0,0 @@ - | -// | Based on OLE::Storage_Lite by Kawai, Takanori | -// +----------------------------------------------------------------------+ -// -// $Id: OLE.php,v 1.7 2003/08/21 15:15:40 xnoguer Exp $ - - -/** -* Constants for OLE package -*/ -define('OLE_PPS_TYPE_ROOT', 5); -define('OLE_PPS_TYPE_DIR', 1); -define('OLE_PPS_TYPE_FILE', 2); -define('OLE_DATA_SIZE_SMALL', 0x1000); -define('OLE_LONG_INT_SIZE', 4); -define('OLE_PPS_SIZE', 0x80); - -require_once('PEAR.php'); -require_once 'OLE/PPS.php'; - -/** -* OLE package base class. -* -* @author Xavier Noguer -* @category Structures -* @package OLE -*/ -class OLE extends PEAR -{ - /** - * The file handle for reading an OLE container - * @var resource - */ - var $_file_handle; - - /** - * Array of PPS's found on the OLE container - * @var array - */ - var $_list; - - /** - * Creates a new OLE object - * Remember to use ampersand when creating an OLE object ($my_ole =& new OLE();) - * @access public - */ - function OLE() - { - $this->_list = array(); - } - - /** - * Reads an OLE container from the contents of the file given. - * - * @acces public - * @param string $file - * @return mixed true on success, PEAR_Error on failure - */ - function read($file) - { - /* consider storing offsets as constants */ - $big_block_size_offset = 30; - $iBdbCnt_offset = 44; - $bd_start_offset = 68; - - $fh = @fopen($file, "r"); - if ($fh == false) { - return $this->raiseError("Can't open file $file"); - } - $this->_file_handle = $fh; - - /* begin reading OLE attributes */ - fseek($fh, 0); - $signature = fread($fh, 8); - if ("\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" != $signature) { - return $this->raiseError("File doesn't seem to be an OLE container."); - } - fseek($fh, $big_block_size_offset); - $packed_array = unpack("v", fread($fh, 2)); - $big_block_size = pow(2, $packed_array['']); - - $packed_array = unpack("v", fread($fh, 2)); - $small_block_size = pow(2, $packed_array['']); - $i1stBdL = ($big_block_size - 0x4C) / OLE_LONG_INT_SIZE; - - fseek($fh, $iBdbCnt_offset); - $packed_array = unpack("V", fread($fh, 4)); - $iBdbCnt = $packed_array['']; - - $packed_array = unpack("V", fread($fh, 4)); - $pps_wk_start = $packed_array['']; - - fseek($fh, $bd_start_offset); - $packed_array = unpack("V", fread($fh, 4)); - $bd_start = $packed_array['']; - $packed_array = unpack("V", fread($fh, 4)); - $bd_count = $packed_array['']; - $packed_array = unpack("V", fread($fh, 4)); - $iAll = $packed_array['']; // this may be wrong - /* create OLE_PPS objects from */ - $ret = $this->_readPpsWks($pps_wk_start, $big_block_size); - if (PEAR::isError($ret)) { - return $ret; - } - return true; - } - - /** - * Destructor (using PEAR) - * Just closes the file handle on the OLE file. - * - * @access private - */ - function _OLE() - { - fclose($this->_file_handle); - } - - /** - * Gets information about all PPS's on the OLE container from the PPS WK's - * creates an OLE_PPS object for each one. - * - * @access private - * @param integer $pps_wk_start Position inside the OLE file where PPS WK's start - * @param integer $big_block_size Size of big blobks in the OLE file - * @return mixed true on success, PEAR_Error on failure - */ - function _readPpsWks($pps_wk_start, $big_block_size) - { - $pointer = ($pps_wk_start + 1) * $big_block_size; - while (1) - { - fseek($this->_file_handle, $pointer); - $pps_wk = fread($this->_file_handle, OLE_PPS_SIZE); - if (strlen($pps_wk) != OLE_PPS_SIZE) { - break; // Excel likes to add a trailing byte sometimes - //return $this->raiseError("PPS at $pointer seems too short: ".strlen($pps_wk)); - } - $name_length = unpack("c", substr($pps_wk, 64, 2)); // FIXME (2 bytes??) - $name_length = $name_length[''] - 2; - $name = substr($pps_wk, 0, $name_length); - $type = unpack("c", substr($pps_wk, 66, 1)); - if (($type[''] != OLE_PPS_TYPE_ROOT) and - ($type[''] != OLE_PPS_TYPE_DIR) and - ($type[''] != OLE_PPS_TYPE_FILE)) - { - return $this->raiseError("PPS at $pointer has unknown type: {$type['']}"); - } - $prev = unpack("V", substr($pps_wk, 68, 4)); - $next = unpack("V", substr($pps_wk, 72, 4)); - $dir = unpack("V", substr($pps_wk, 76, 4)); - // there is no magic number, it can take different values. - //$magic = unpack("V", strrev(substr($pps_wk, 92, 4))); - $time_1st = substr($pps_wk, 100, 8); - $time_2nd = substr($pps_wk, 108, 8); - $start_block = unpack("V", substr($pps_wk, 116, 4)); - $size = unpack("V", substr($pps_wk, 120, 4)); - // _data member will point to position in file!! - // OLE_PPS object is created with an empty children array!! - $this->_list[] = new OLE_PPS(null, '', $type[''], $prev[''], $next[''], - $dir[''], OLE::OLE2LocalDate($time_1st), - OLE::OLE2LocalDate($time_2nd), - ($start_block[''] + 1) * $big_block_size, array()); - // give it a size - $this->_list[count($this->_list) - 1]->Size = $size['']; - // check if the PPS tree (starting from root) is complete - if ($this->_ppsTreeComplete(0)) { - break; - } - $pointer += OLE_PPS_SIZE; - } - } - - /** - * It checks whether the PPS tree is complete (all PPS's read) - * starting with the given PPS (not necessarily root) - * - * @access private - * @param integer $index The index of the PPS from which we are checking - * @return boolean Whether the PPS tree for the given PPS is complete - */ - function _ppsTreeComplete($index) - { - if ($this->_list[$index]->NextPps != -1) { - if (!isset($this->_list[$this->_list[$index]->NextPps])) { - return false; - } - else { - return $this->_ppsTreeComplete($this->_list[$index]->NextPps); - } - } - if ($this->_list[$index]->DirPps != -1) { - if (!isset($this->_list[$this->_list[$index]->DirPps])) { - return false; - } - else { - return $this->_ppsTreeComplete($this->_list[$index]->DirPps); - } - } - return true; - } - - /** - * Checks whether a PPS is a File PPS or not. - * If there is no PPS for the index given, it will return false. - * - * @access public - * @param integer $index The index for the PPS - * @return bool true if it's a File PPS, false otherwise - */ - function isFile($index) - { - if (isset($this->_list[$index])) { - return ($this->_list[$index]->Type == OLE_PPS_TYPE_FILE); - } - return false; - } - - /** - * Checks whether a PPS is a Root PPS or not. - * If there is no PPS for the index given, it will return false. - * - * @access public - * @param integer $index The index for the PPS. - * @return bool true if it's a Root PPS, false otherwise - */ - function isRoot($index) - { - if (isset($this->_list[$index])) { - return ($this->_list[$index]->Type == OLE_PPS_TYPE_ROOT); - } - return false; - } - - /** - * Gives the total number of PPS's found in the OLE container. - * - * @access public - * @return integer The total number of PPS's found in the OLE container - */ - function ppsTotal() - { - return count($this->_list); - } - - /** - * Gets data from a PPS - * If there is no PPS for the index given, it will return an empty string. - * - * @access public - * @param integer $index The index for the PPS - * @param integer $position The position from which to start reading - * (relative to the PPS) - * @param integer $length The amount of bytes to read (at most) - * @return string The binary string containing the data requested - */ - function getData($index, $position, $length) - { - // if position is not valid return empty string - if (!isset($this->_list[$index]) or ($position >= $this->_list[$index]->Size) or ($position < 0)) { - return ''; - } - // Beware!!! _data member is actually a position - fseek($this->_file_handle, $this->_list[$index]->_data + $position); - return fread($this->_file_handle, $length); - } - - /** - * Gets the data length from a PPS - * If there is no PPS for the index given, it will return 0. - * - * @access public - * @param integer $index The index for the PPS - * @return integer The amount of bytes in data the PPS has - */ - function getDataLength($index) - { - if (isset($this->_list[$index])) { - return $this->_list[$index]->Size; - } - return 0; - } - - /** - * Utility function to transform ASCII text to Unicode - * - * @access public - * @static - * @param string $ascii The ASCII string to transform - * @return string The string in Unicode - */ - function Asc2Ucs($ascii) - { - $rawname = ''; - for ($i = 0; $i < strlen($ascii); $i++) { - $rawname .= $ascii{$i}."\x00"; - } - return $rawname; - } - - /** - * Utility function - * Returns a string for the OLE container with the date given - * - * @access public - * @static - * @param integer $date A timestamp - * @return string The string for the OLE container - */ - function LocalDate2OLE($date = null) - { - if (!isset($date)) { - return "\x00\x00\x00\x00\x00\x00\x00\x00"; - } - - // factor used for separating numbers into 4 bytes parts - $factor = pow(2,32); - - // days from 1-1-1601 until the beggining of UNIX era - $days = 134774; - // calculate seconds - $big_date = $days*24*3600 + gmmktime(date("H",$date),date("i",$date),date("s",$date), - date("m",$date),date("d",$date),date("Y",$date)); - // multiply just to make MS happy - $big_date *= 10000000; - - $high_part = floor($big_date/$factor); - // lower 4 bytes - $low_part = floor((($big_date/$factor) - $high_part)*$factor); - - // Make HEX string - $res = ''; - - for ($i=0; $i<4; $i++) - { - $hex = $low_part % 0x100; - $res .= pack('c', $hex); - $low_part /= 0x100; - } - for ($i=0; $i<4; $i++) - { - $hex = $high_part % 0x100; - $res .= pack('c', $hex); - $high_part /= 0x100; - } - return $res; - } - - /** - * Returns a timestamp from an OLE container's date - * - * @access public - * @static - * @param integer $string A binary string with the encoded date - * @return string The timestamp corresponding to the string - */ - function OLE2LocalDate($string) - { - if (strlen($string) != 8) { - return new PEAR_Error("Expecting 8 byte string"); - } - - // factor used for separating numbers into 4 bytes parts - $factor = pow(2,32); - $high_part = 0; - for ($i=0; $i<4; $i++) - { - $al = unpack('C', $string{(7 - $i)}); - $high_part += $al['']; - if ($i < 3) { - $high_part *= 0x100; - } - } - $low_part = 0; - for ($i=4; $i<8; $i++) - { - $al = unpack('C', $string{(7 - $i)}); - $low_part += $al['']; - if ($i < 7) { - $low_part *= 0x100; - } - } - $big_date = ($high_part*$factor) + $low_part; - // translate to seconds - $big_date /= 10000000; - - // days from 1-1-1601 until the beggining of UNIX era - $days = 134774; - - // translate to seconds from beggining of UNIX era - $big_date -= $days*24*3600; - return floor($big_date); - } -} -?> diff --git a/gulliver/thirdparty/pear/OLE/PPS.php b/gulliver/thirdparty/pear/OLE/PPS.php deleted file mode 100644 index 03dbd9018..000000000 --- a/gulliver/thirdparty/pear/OLE/PPS.php +++ /dev/null @@ -1,219 +0,0 @@ - | -// | Based on OLE::Storage_Lite by Kawai, Takanori | -// +----------------------------------------------------------------------+ -// -// $Id: PPS.php,v 1.5 2003/12/14 18:12:28 xnoguer Exp $ - - -require_once('PEAR.php'); -require_once('OLE.php'); - -/** -* Class for creating PPS's for OLE containers -* -* @author Xavier Noguer -* @category Structures -* @package OLE -*/ -class OLE_PPS extends PEAR -{ - /** - * The PPS index - * @var integer - */ - var $No; - - /** - * The PPS name (in Unicode) - * @var string - */ - var $Name; - - /** - * The PPS type. Dir, Root or File - * @var integer - */ - var $Type; - - /** - * The index of the previous PPS - * @var integer - */ - var $PrevPps; - - /** - * The index of the next PPS - * @var integer - */ - var $NextPps; - - /** - * The index of it's first child if this is a Dir or Root PPS - * @var integer - */ - var $DirPps; - - /** - * A timestamp - * @var integer - */ - var $Time1st; - - /** - * A timestamp - * @var integer - */ - var $Time2nd; - - /** - * Starting block (small or big) for this PPS's data inside the container - * @var integer - */ - var $_StartBlock; - - /** - * The size of the PPS's data (in bytes) - * @var integer - */ - var $Size; - - /** - * The PPS's data (only used if it's not using a temporary file) - * @var string - */ - var $_data; - - /** - * Array of child PPS's (only used by Root and Dir PPS's) - * @var array - */ - var $children = array(); - - /** - * The constructor - * - * @access public - * @param integer $No The PPS index - * @param string $name The PPS name (in Unicode) - * @param integer $type The PPS type. Dir, Root or File - * @param integer $prev The index of the previous PPS - * @param integer $next The index of the next PPS - * @param integer $dir The index of it's first child if this is a Dir or Root PPS - * @param integer $time_1st A timestamp - * @param integer $time_2nd A timestamp - * @param array $children Array containing children PPS for this PPS - */ - function OLE_PPS($No, $name, $type, $prev, $next, $dir, $time_1st, $time_2nd, $data, $children) - { - $this->No = $No; - $this->Name = $name; - $this->Type = $type; - $this->PrevPps = $prev; - $this->NextPps = $next; - $this->DirPps = $dir; - $this->Time1st = $time_1st; - $this->Time2nd = $time_2nd; - $this->_data = $data; - $this->children = $children; - if ($data != '') { - $this->Size = strlen($data); - } - else { - $this->Size = 0; - } - } - - /** - * Returns the amount of data saved for this PPS - * - * @access private - * @return integer The amount of data (in bytes) - */ - function _DataLen() - { - if (!isset($this->_data)) { - return 0; - } - if (isset($this->_PPS_FILE)) - { - fseek($this->_PPS_FILE, 0); - $stats = fstat($this->_PPS_FILE); - return $stats[7]; - } - else { - return strlen($this->_data); - } - } - - /** - * Returns a string with the PPS's WK (What is a WK?) - * - * @access private - * @return string The binary string - */ - function _getPpsWk() - { - $ret = $this->Name; - for ($i = 0; $i < (64 - strlen($this->Name)); $i++) { - $ret .= "\x00"; - } - $ret .= pack("v", strlen($this->Name) + 2) // 66 - . pack("c", $this->Type) // 67 - . pack("c", 0x00) //UK // 68 - . pack("V", $this->PrevPps) //Prev // 72 - . pack("V", $this->NextPps) //Next // 76 - . pack("V", $this->DirPps) //Dir // 80 - . "\x00\x09\x02\x00" // 84 - . "\x00\x00\x00\x00" // 88 - . "\xc0\x00\x00\x00" // 92 - . "\x00\x00\x00\x46" // 96 // Seems to be ok only for Root - . "\x00\x00\x00\x00" // 100 - . OLE::LocalDate2OLE($this->Time1st) // 108 - . OLE::LocalDate2OLE($this->Time2nd) // 116 - . pack("V", isset($this->_StartBlock)? - $this->_StartBlock:0) // 120 - . pack("V", $this->Size) // 124 - . pack("V", 0); // 128 - return $ret; - } - - /** - * Updates index and pointers to previous, next and children PPS's for this - * PPS. I don't think it'll work with Dir PPS's. - * - * @access private - * @param array &$pps_array Reference to the array of PPS's for the whole OLE - * container - * @return integer The index for this PPS - */ - function _savePpsSetPnt(&$pps_array) - { - $pps_array[count($pps_array)] = &$this; - $this->No = count($pps_array) - 1; - $this->PrevPps = 0xFFFFFFFF; - $this->NextPps = 0xFFFFFFFF; - if (count($this->children) > 0) { - $this->DirPps = $this->children[0]->_savePpsSetPnt($pps_array); - } - else { - $this->DirPps = 0xFFFFFFFF; - } - return $this->No; - } -} -?> diff --git a/gulliver/thirdparty/pear/OLE/PPS/File.php b/gulliver/thirdparty/pear/OLE/PPS/File.php deleted file mode 100644 index 852c7af10..000000000 --- a/gulliver/thirdparty/pear/OLE/PPS/File.php +++ /dev/null @@ -1,114 +0,0 @@ - | -// | Based on OLE::Storage_Lite by Kawai, Takanori | -// +----------------------------------------------------------------------+ -// -// $Id: File.php,v 1.8 2003/12/12 21:10:10 xnoguer Exp $ - - -require_once ('OLE/PPS.php'); - -/** -* Class for creating File PPS's for OLE containers -* -* @author Xavier Noguer -* @category Structures -* @package OLE -*/ -class OLE_PPS_File extends OLE_PPS -{ - /** - * The temporary dir for storing the OLE file - * @var string - */ - var $_tmp_dir; - - /** - * The constructor - * - * @access public - * @param string $name The name of the file (in Unicode) - * @see OLE::Asc2Ucs() - */ - function OLE_PPS_File($name) - { - $this->_tmp_dir = ''; - $this->OLE_PPS( - null, - $name, - OLE_PPS_TYPE_FILE, - null, - null, - null, - null, - null, - '', - array()); - } - - /** - * Sets the temp dir used for storing the OLE file - * - * @access public - * @param string $dir The dir to be used as temp dir - * @return true if given dir is valid, false otherwise - */ - function setTempDir($dir) - { - if (is_dir($dir)) { - $this->_tmp_dir = $dir; - return true; - } - return false; - } - - /** - * Initialization method. Has to be called right after OLE_PPS_File(). - * - * @access public - * @return mixed true on success. PEAR_Error on failure - */ - function init() - { - $this->_tmp_filename = tempnam($this->_tmp_dir, "OLE_PPS_File"); - $fh = @fopen($this->_tmp_filename, "w+b"); - if ($fh == false) { - return $this->raiseError("Can't create temporary file"); - } - $this->_PPS_FILE = $fh; - if ($this->_PPS_FILE) { - fseek($this->_PPS_FILE, 0); - } - } - - /** - * Append data to PPS - * - * @access public - * @param string $data The data to append - */ - function append($data) - { - if ($this->_PPS_FILE) { - fwrite($this->_PPS_FILE, $data); - } - else { - $this->_data .= $data; - } - } -} -?> diff --git a/gulliver/thirdparty/pear/OLE/PPS/Root.php b/gulliver/thirdparty/pear/OLE/PPS/Root.php deleted file mode 100644 index 9b86d18d7..000000000 --- a/gulliver/thirdparty/pear/OLE/PPS/Root.php +++ /dev/null @@ -1,519 +0,0 @@ - | -// | Based on OLE::Storage_Lite by Kawai, Takanori | -// +----------------------------------------------------------------------+ -// -// $Id: Root.php,v 1.7 2003/12/12 21:10:10 xnoguer Exp $ - - -require_once ('OLE/PPS.php'); - -/** -* Class for creating Root PPS's for OLE containers -* -* @author Xavier Noguer -* @category Structures -* @package OLE -*/ -class OLE_PPS_Root extends OLE_PPS -{ - /** - * The temporary dir for storing the OLE file - * @var string - */ - var $_tmp_dir; - - /** - * Constructor - * - * @access public - * @param integer $time_1st A timestamp - * @param integer $time_2nd A timestamp - */ - function OLE_PPS_Root($time_1st, $time_2nd, $raChild) - { - $this->_tmp_dir = ''; - $this->OLE_PPS( - null, - OLE::Asc2Ucs('Root Entry'), - OLE_PPS_TYPE_ROOT, - null, - null, - null, - $time_1st, - $time_2nd, - null, - $raChild); - } - - /** - * Sets the temp dir used for storing the OLE file - * - * @access public - * @param string $dir The dir to be used as temp dir - * @return true if given dir is valid, false otherwise - */ - function setTempDir($dir) - { - if (is_dir($dir)) { - $this->_tmp_dir = $dir; - return true; - } - return false; - } - - /** - * Method for saving the whole OLE container (including files). - * In fact, if called with an empty argument (or '-'), it saves to a - * temporary file and then outputs it's contents to stdout. - * - * @param string $filename The name of the file where to save the OLE container - * @access public - * @return mixed true on success, PEAR_Error on failure - */ - function save($filename) - { - // Initial Setting for saving - $this->_BIG_BLOCK_SIZE = pow(2, - ((isset($this->_BIG_BLOCK_SIZE))? $this->_adjust2($this->_BIG_BLOCK_SIZE) : 9)); - $this->_SMALL_BLOCK_SIZE= pow(2, - ((isset($this->_SMALL_BLOCK_SIZE))? $this->_adjust2($this->_SMALL_BLOCK_SIZE): 6)); - - // Open temp file if we are sending output to stdout - if (($filename == '-') or ($filename == '')) - { - $this->_tmp_filename = tempnam($this->_tmp_dir, "OLE_PPS_Root"); - $this->_FILEH_ = @fopen($this->_tmp_filename,"w+b"); - if ($this->_FILEH_ == false) { - return $this->raiseError("Can't create temporary file."); - } - } - else - { - $this->_FILEH_ = @fopen($filename, "wb"); - if ($this->_FILEH_ == false) { - return $this->raiseError("Can't open $filename. It may be in use or protected."); - } - } - // Make an array of PPS's (for Save) - $aList = array(); - $this->_savePpsSetPnt($aList); - // calculate values for header - list($iSBDcnt, $iBBcnt, $iPPScnt) = $this->_calcSize($aList); //, $rhInfo); - // Save Header - $this->_saveHeader($iSBDcnt, $iBBcnt, $iPPScnt); - - // Make Small Data string (write SBD) - $this->_data = $this->_makeSmallData($aList); - - // Write BB - $this->_saveBigData($iSBDcnt, $aList); - // Write PPS - $this->_savePps($aList); - // Write Big Block Depot and BDList and Adding Header informations - $this->_saveBbd($iSBDcnt, $iBBcnt, $iPPScnt); - // Close File, send it to stdout if necessary - if(($filename == '-') or ($filename == '')) - { - fseek($this->_FILEH_, 0); - fpassthru($this->_FILEH_); - @fclose($this->_FILEH_); - // Delete the temporary file. - @unlink($this->_tmp_filename); - } - else { - @fclose($this->_FILEH_); - } - return true; - } - - /** - * Calculate some numbers - * - * @access private - * @param array $raList Reference to an array of PPS's - * @return array The array of numbers - */ - function _calcSize(&$raList) - { - // Calculate Basic Setting - list($iSBDcnt, $iBBcnt, $iPPScnt) = array(0,0,0); - $iSmallLen = 0; - $iSBcnt = 0; - for ($i = 0; $i < count($raList); $i++) { - if($raList[$i]->Type == OLE_PPS_TYPE_FILE) { - $raList[$i]->Size = $raList[$i]->_DataLen(); - if($raList[$i]->Size < OLE_DATA_SIZE_SMALL) { - $iSBcnt += floor($raList[$i]->Size / $this->_SMALL_BLOCK_SIZE) - + (($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE)? 1: 0); - } - else { - $iBBcnt += (floor($raList[$i]->Size / $this->_BIG_BLOCK_SIZE) + - (($raList[$i]->Size % $this->_BIG_BLOCK_SIZE)? 1: 0)); - } - } - } - $iSmallLen = $iSBcnt * $this->_SMALL_BLOCK_SIZE; - $iSlCnt = floor($this->_BIG_BLOCK_SIZE / OLE_LONG_INT_SIZE); - $iSBDcnt = floor($iSBcnt / $iSlCnt) + (($iSBcnt % $iSlCnt)? 1:0); - $iBBcnt += (floor($iSmallLen / $this->_BIG_BLOCK_SIZE) + - (( $iSmallLen % $this->_BIG_BLOCK_SIZE)? 1: 0)); - $iCnt = count($raList); - $iBdCnt = $this->_BIG_BLOCK_SIZE / OLE_PPS_SIZE; - $iPPScnt = (floor($iCnt/$iBdCnt) + (($iCnt % $iBdCnt)? 1: 0)); - - return array($iSBDcnt, $iBBcnt, $iPPScnt); - } - - /** - * Helper function for caculating a magic value for block sizes - * - * @access private - * @param integer $i2 The argument - * @see save() - * @return integer - */ - function _adjust2($i2) - { - $iWk = log($i2)/log(2); - return ($iWk > floor($iWk))? floor($iWk)+1:$iWk; - } - - /** - * Save OLE header - * - * @access private - * @param integer $iSBDcnt - * @param integer $iBBcnt - * @param integer $iPPScnt - */ - function _saveHeader($iSBDcnt, $iBBcnt, $iPPScnt) - { - $FILE = $this->_FILEH_; - - // Calculate Basic Setting - $iBlCnt = $this->_BIG_BLOCK_SIZE / OLE_LONG_INT_SIZE; - $i1stBdL = ($this->_BIG_BLOCK_SIZE - 0x4C) / OLE_LONG_INT_SIZE; - - $iBdExL = 0; - $iAll = $iBBcnt + $iPPScnt + $iSBDcnt; - $iAllW = $iAll; - $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt)? 1: 0); - $iBdCnt = floor(($iAll + $iBdCntW) / $iBlCnt) + ((($iAllW+$iBdCntW) % $iBlCnt)? 1: 0); - - // Calculate BD count - if ($iBdCnt >$i1stBdL) - { - while (1) - { - $iBdExL++; - $iAllW++; - $iBdCntW = floor($iAllW / $iBlCnt) + (($iAllW % $iBlCnt)? 1: 0); - $iBdCnt = floor(($iAllW + $iBdCntW) / $iBlCnt) + ((($iAllW+$iBdCntW) % $iBlCnt)? 1: 0); - if ($iBdCnt <= ($iBdExL*$iBlCnt+ $i1stBdL)) { - break; - } - } - } - - // Save Header - fwrite($FILE, - "\xD0\xCF\x11\xE0\xA1\xB1\x1A\xE1" - . "\x00\x00\x00\x00" - . "\x00\x00\x00\x00" - . "\x00\x00\x00\x00" - . "\x00\x00\x00\x00" - . pack("v", 0x3b) - . pack("v", 0x03) - . pack("v", -2) - . pack("v", 9) - . pack("v", 6) - . pack("v", 0) - . "\x00\x00\x00\x00" - . "\x00\x00\x00\x00" - . pack("V", $iBdCnt) - . pack("V", $iBBcnt+$iSBDcnt) //ROOT START - . pack("V", 0) - . pack("V", 0x1000) - . pack("V", 0) //Small Block Depot - . pack("V", 1) - ); - // Extra BDList Start, Count - if ($iBdCnt < $i1stBdL) - { - fwrite($FILE, - pack("V", -2). // Extra BDList Start - pack("V", 0) // Extra BDList Count - ); - } - else - { - fwrite($FILE, pack("V", $iAll+$iBdCnt) . pack("V", $iBdExL)); - } - - // BDList - for ($i=0; $i<$i1stBdL and $i < $iBdCnt; $i++) { - fwrite($FILE, pack("V", $iAll+$i)); - } - if ($i < $i1stBdL) - { - for ($j = 0; $j < ($i1stBdL-$i); $j++) { - fwrite($FILE, (pack("V", -1))); - } - } - } - - /** - * Saving big data (PPS's with data bigger than OLE_DATA_SIZE_SMALL) - * - * @access private - * @param integer $iStBlk - * @param array &$raList Reference to array of PPS's - */ - function _saveBigData($iStBlk, &$raList) - { - $FILE = $this->_FILEH_; - - // cycle through PPS's - for ($i = 0; $i < count($raList); $i++) - { - if($raList[$i]->Type != OLE_PPS_TYPE_DIR) - { - $raList[$i]->Size = $raList[$i]->_DataLen(); - if(($raList[$i]->Size >= OLE_DATA_SIZE_SMALL) or - (($raList[$i]->Type == OLE_PPS_TYPE_ROOT) and isset($raList[$i]->_data))) - { - // Write Data - if(isset($raList[$i]->_PPS_FILE)) - { - $iLen = 0; - fseek($raList[$i]->_PPS_FILE, 0); // To The Top - while($sBuff = fread($raList[$i]->_PPS_FILE, 4096)) - { - $iLen += strlen($sBuff); - fwrite($FILE, $sBuff); - } - } - else { - fwrite($FILE, $raList[$i]->_data); - } - - if ($raList[$i]->Size % $this->_BIG_BLOCK_SIZE) - { - for ($j = 0; $j < ($this->_BIG_BLOCK_SIZE - ($raList[$i]->Size % $this->_BIG_BLOCK_SIZE)); $j++) { - fwrite($FILE, "\x00"); - } - } - // Set For PPS - $raList[$i]->_StartBlock = $iStBlk; - $iStBlk += - (floor($raList[$i]->Size / $this->_BIG_BLOCK_SIZE) + - (($raList[$i]->Size % $this->_BIG_BLOCK_SIZE)? 1: 0)); - } - // Close file for each PPS, and unlink it - if (isset($raList[$i]->_PPS_FILE)) - { - @fclose($raList[$i]->_PPS_FILE); - $raList[$i]->_PPS_FILE = null; - @unlink($raList[$i]->_tmp_filename); - } - } - } - } - - /** - * get small data (PPS's with data smaller than OLE_DATA_SIZE_SMALL) - * - * @access private - * @param array &$raList Reference to array of PPS's - */ - function _makeSmallData(&$raList) - { - $sRes = ''; - $FILE = $this->_FILEH_; - $iSmBlk = 0; - - for ($i = 0; $i < count($raList); $i++) - { - // Make SBD, small data string - if ($raList[$i]->Type == OLE_PPS_TYPE_FILE) - { - if ($raList[$i]->Size <= 0) { - continue; - } - if ($raList[$i]->Size < OLE_DATA_SIZE_SMALL) - { - $iSmbCnt = floor($raList[$i]->Size / $this->_SMALL_BLOCK_SIZE) - + (($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE)? 1: 0); - // Add to SBD - for ($j = 0; $j < ($iSmbCnt-1); $j++) { - fwrite($FILE, pack("V", $j+$iSmBlk+1)); - } - fwrite($FILE, pack("V", -2)); - - // Add to Data String(this will be written for RootEntry) - if ($raList[$i]->_PPS_FILE) - { - fseek($raList[$i]->_PPS_FILE, 0); // To The Top - while ($sBuff = fread($raList[$i]->_PPS_FILE, 4096)) { - $sRes .= $sBuff; - } - } - else { - $sRes .= $raList[$i]->_data; - } - if($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE) - { - for ($j = 0; $j < ($this->_SMALL_BLOCK_SIZE - ($raList[$i]->Size % $this->_SMALL_BLOCK_SIZE)); $j++) { - $sRes .= "\x00"; - } - } - // Set for PPS - $raList[$i]->_StartBlock = $iSmBlk; - $iSmBlk += $iSmbCnt; - } - } - } - $iSbCnt = floor($this->_BIG_BLOCK_SIZE / OLE_LONG_INT_SIZE); - if($iSmBlk % $iSbCnt) - { - for ($i = 0; $i < ($iSbCnt - ($iSmBlk % $iSbCnt)); $i++) { - fwrite($FILE, pack("V", -1)); - } - } - return $sRes; - } - - /** - * Saves all the PPS's WKs - * - * @access private - * @param array $raList Reference to an array with all PPS's - */ - function _savePps(&$raList) - { - // Save each PPS WK - for ($i = 0; $i < count($raList); $i++) { - fwrite($this->_FILEH_, $raList[$i]->_getPpsWk()); - } - // Adjust for Block - $iCnt = count($raList); - $iBCnt = $this->_BIG_BLOCK_SIZE / OLE_PPS_SIZE; - if ($iCnt % $iBCnt) - { - for ($i = 0; $i < (($iBCnt - ($iCnt % $iBCnt)) * OLE_PPS_SIZE); $i++) { - fwrite($this->_FILEH_, "\x00"); - } - } - } - - /** - * Saving Big Block Depot - * - * @access private - * @param integer $iSbdSize - * @param integer $iBsize - * @param integer $iPpsCnt - */ - function _saveBbd($iSbdSize, $iBsize, $iPpsCnt) - { - $FILE = $this->_FILEH_; - // Calculate Basic Setting - $iBbCnt = $this->_BIG_BLOCK_SIZE / OLE_LONG_INT_SIZE; - $i1stBdL = ($this->_BIG_BLOCK_SIZE - 0x4C) / OLE_LONG_INT_SIZE; - - $iBdExL = 0; - $iAll = $iBsize + $iPpsCnt + $iSbdSize; - $iAllW = $iAll; - $iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt)? 1: 0); - $iBdCnt = floor(($iAll + $iBdCntW) / $iBbCnt) + ((($iAllW+$iBdCntW) % $iBbCnt)? 1: 0); - // Calculate BD count - if ($iBdCnt >$i1stBdL) - { - while (1) - { - $iBdExL++; - $iAllW++; - $iBdCntW = floor($iAllW / $iBbCnt) + (($iAllW % $iBbCnt)? 1: 0); - $iBdCnt = floor(($iAllW + $iBdCntW) / $iBbCnt) + ((($iAllW+$iBdCntW) % $iBbCnt)? 1: 0); - if ($iBdCnt <= ($iBdExL*$iBbCnt+ $i1stBdL)) { - break; - } - } - } - - // Making BD - // Set for SBD - if ($iSbdSize > 0) - { - for ($i = 0; $i<($iSbdSize-1); $i++) { - fwrite($FILE, pack("V", $i+1)); - } - fwrite($FILE, pack("V", -2)); - } - // Set for B - for ($i = 0; $i<($iBsize-1); $i++) { - fwrite($FILE, pack("V", $i+$iSbdSize+1)); - } - fwrite($FILE, pack("V", -2)); - - // Set for PPS - for ($i = 0; $i<($iPpsCnt-1); $i++) { - fwrite($FILE, pack("V", $i+$iSbdSize+$iBsize+1)); - } - fwrite($FILE, pack("V", -2)); - // Set for BBD itself ( 0xFFFFFFFD : BBD) - for ($i=0; $i<$iBdCnt;$i++) { - fwrite($FILE, pack("V", 0xFFFFFFFD)); - } - // Set for ExtraBDList - for ($i=0; $i<$iBdExL;$i++) { - fwrite($FILE, pack("V", 0xFFFFFFFC)); - } - // Adjust for Block - if (($iAllW + $iBdCnt) % $iBbCnt) - { - for ($i = 0; $i < ($iBbCnt - (($iAllW + $iBdCnt) % $iBbCnt)); $i++) { - fwrite($FILE, pack("V", -1)); - } - } - // Extra BDList - if ($iBdCnt > $i1stBdL) - { - $iN=0; - $iNb=0; - for ($i=$i1stBdL;$i<$iBdCnt; $i++, $iN++) - { - if ($iN>=($iBbCnt-1)) - { - $iN = 0; - $iNb++; - fwrite($FILE, pack("V", $iAll+$iBdCnt+$iNb)); - } - fwrite($FILE, pack("V", $iBsize+$iSbdSize+$iPpsCnt+$i)); - } - if (($iBdCnt-$i1stBdL) % ($iBbCnt-1)) - { - for ($i = 0; $i < (($iBbCnt-1) - (($iBdCnt-$i1stBdL) % ($iBbCnt-1))); $i++) { - fwrite($FILE, pack("V", -1)); - } - } - fwrite($FILE, pack("V", -2)); - } - } -} -?> diff --git a/gulliver/thirdparty/pear/OS/Guess.php b/gulliver/thirdparty/pear/OS/Guess.php deleted file mode 100644 index abcae5946..000000000 --- a/gulliver/thirdparty/pear/OS/Guess.php +++ /dev/null @@ -1,265 +0,0 @@ - | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Guess.php,v 1.9 2003/04/03 23:11:50 ssb Exp $ - -// {{{ uname examples - -// php_uname() without args returns the same as 'uname -a', or a PHP-custom -// string for Windows. -// PHP versions prior to 4.3 return the uname of the host where PHP was built, -// as of 4.3 it returns the uname of the host running the PHP code. -// -// PC RedHat Linux 7.1: -// Linux host.example.com 2.4.2-2 #1 Sun Apr 8 20:41:30 EDT 2001 i686 unknown -// -// PC Debian Potato: -// Linux host 2.4.17 #2 SMP Tue Feb 12 15:10:04 CET 2002 i686 unknown -// -// PC FreeBSD 3.3: -// FreeBSD host.example.com 3.3-STABLE FreeBSD 3.3-STABLE #0: Mon Feb 21 00:42:31 CET 2000 root@example.com:/usr/src/sys/compile/CONFIG i386 -// -// PC FreeBSD 4.3: -// FreeBSD host.example.com 4.3-RELEASE FreeBSD 4.3-RELEASE #1: Mon Jun 25 11:19:43 EDT 2001 root@example.com:/usr/src/sys/compile/CONFIG i386 -// -// PC FreeBSD 4.5: -// FreeBSD host.example.com 4.5-STABLE FreeBSD 4.5-STABLE #0: Wed Feb 6 23:59:23 CET 2002 root@example.com:/usr/src/sys/compile/CONFIG i386 -// -// PC FreeBSD 4.5 w/uname from GNU shellutils: -// FreeBSD host.example.com 4.5-STABLE FreeBSD 4.5-STABLE #0: Wed Feb i386 unknown -// -// HP 9000/712 HP-UX 10: -// HP-UX iq B.10.10 A 9000/712 2008429113 two-user license -// -// HP 9000/712 HP-UX 10 w/uname from GNU shellutils: -// HP-UX host B.10.10 A 9000/712 unknown -// -// IBM RS6000/550 AIX 4.3: -// AIX host 3 4 000003531C00 -// -// AIX 4.3 w/uname from GNU shellutils: -// AIX host 3 4 000003531C00 unknown -// -// SGI Onyx IRIX 6.5 w/uname from GNU shellutils: -// IRIX64 host 6.5 01091820 IP19 mips -// -// SGI Onyx IRIX 6.5: -// IRIX64 host 6.5 01091820 IP19 -// -// SparcStation 20 Solaris 8 w/uname from GNU shellutils: -// SunOS host.example.com 5.8 Generic_108528-12 sun4m sparc -// -// SparcStation 20 Solaris 8: -// SunOS host.example.com 5.8 Generic_108528-12 sun4m sparc SUNW,SPARCstation-20 -// - -// }}} - -/* TODO: - * - define endianness, to allow matchSignature("bigend") etc. - */ - -class OS_Guess -{ - var $sysname; - var $nodename; - var $cpu; - var $release; - var $extra; - - function OS_Guess($uname = null) - { - list($this->sysname, - $this->release, - $this->cpu, - $this->extra, - $this->nodename) = $this->parseSignature($uname); - } - - function parseSignature($uname = null) - { - static $sysmap = array( - 'HP-UX' => 'hpux', - 'IRIX64' => 'irix', - // Darwin? - ); - static $cpumap = array( - 'i586' => 'i386', - 'i686' => 'i386', - ); - if ($uname === null) { - $uname = php_uname(); - } - $parts = explode('[[:space:]]+', trim($uname)); - $n = count($parts); - - $release = $machine = $cpu = ''; - $sysname = $parts[0]; - $nodename = $parts[1]; - $cpu = $parts[$n-1]; - $extra = ''; - if ($cpu == 'unknown') { - $cpu = $parts[$n-2]; - } - - switch ($sysname) { - case 'AIX': - $release = "$parts[3].$parts[2]"; - break; - case 'Windows': - switch ($parts[1]) { - case '95/98': - $release = '9x'; - break; - default: - $release = $parts[1]; - break; - } - $cpu = 'i386'; - break; - case 'Linux': - $extra = $this->_detectGlibcVersion(); - // use only the first two digits from the kernel version - $release = ereg_replace('^([[:digit:]]+\.[[:digit:]]+).*', '\1', $parts[2]); - break; - default: - $release = ereg_replace('-.*', '', $parts[2]); - break; - } - - - if (isset($sysmap[$sysname])) { - $sysname = $sysmap[$sysname]; - } else { - $sysname = strtolower($sysname); - } - if (isset($cpumap[$cpu])) { - $cpu = $cpumap[$cpu]; - } - return array($sysname, $release, $cpu, $extra, $nodename); - } - - function _detectGlibcVersion() - { - // Use glibc's header file to - // get major and minor version number: - include_once "System.php"; - $tmpfile = System::mktemp("glibctest"); - $fp = fopen($tmpfile, "w"); - fwrite($fp, "#include \n__GLIBC__ __GLIBC_MINOR__\n"); - fclose($fp); - $cpp = popen("/usr/bin/cpp $tmpfile", "r"); - $major = $minor = 0; - while ($line = fgets($cpp, 1024)) { - if ($line{0} == '#') { - continue; - } - if (list($major, $minor) = explode(' ', trim($line))) { - break; - } - } - pclose($cpp); - unlink($tmpfile); - if (!($major && $minor) && file_exists('/lib/libc.so.6')) { - // Let's try reading the libc.so.6 symlink - if (ereg('^libc-([.*])\.so$', basename(readlink('/lib/libc.so.6')), $matches)) { - list($major, $minor) = explode('.', $matches); - } - } - if (!($major && $minor)) { - return ''; - } - return "glibc{$major}.{$minor}"; - } - - function getSignature() - { - if (empty($this->extra)) { - return "{$this->sysname}-{$this->release}-{$this->cpu}"; - } - return "{$this->sysname}-{$this->release}-{$this->cpu}-{$this->extra}"; - } - - function getSysname() - { - return $this->sysname; - } - - function getNodename() - { - return $this->nodename; - } - - function getCpu() - { - return $this->cpu; - } - - function getRelease() - { - return $this->release; - } - - function getExtra() - { - return $this->extra; - } - - function matchSignature($match) - { - if (is_array($match)) { - $fragments = $match; - } else { - $fragments = explode('-', $match); - } - $n = count($fragments); - $matches = 0; - if ($n > 0) { - $matches += $this->_matchFragment($fragments[0], $this->sysname); - } - if ($n > 1) { - $matches += $this->_matchFragment($fragments[1], $this->release); - } - if ($n > 2) { - $matches += $this->_matchFragment($fragments[2], $this->cpu); - } - if ($n > 3) { - $matches += $this->_matchFragment($fragments[3], $this->extra); - } - return ($matches == $n); - } - - function _matchFragment($fragment, $value) - { - if (strcspn($fragment, '*?') < strlen($fragment)) { - $reg = '^' . str_replace(array('*', '?', '/'), array('.*', '.', '\\/'), $fragment) . '$'; - return preg_match($reg, $value); - } - return ($fragment == '*' || !strcasecmp($fragment, $value)); - } - -} - -/* - * Local Variables: - * indent-tabs-mode: nil - * c-basic-offset: 4 - * End: - */ -?> diff --git a/gulliver/thirdparty/pear/PEAR.php b/gulliver/thirdparty/pear/PEAR.php deleted file mode 100644 index 0cda6864d..000000000 --- a/gulliver/thirdparty/pear/PEAR.php +++ /dev/null @@ -1,1056 +0,0 @@ - | -// | Stig Bakken | -// | Tomas V.V.Cox | -// +--------------------------------------------------------------------+ -// -// $Id: PEAR.php 3355 2005-06-11 22:14:40Z nbm $ -// - -define('PEAR_ERROR_RETURN', 1); -define('PEAR_ERROR_PRINT', 2); -define('PEAR_ERROR_TRIGGER', 4); -define('PEAR_ERROR_DIE', 8); -define('PEAR_ERROR_CALLBACK', 16); -/** - * WARNING: obsolete - * @deprecated - */ -define('PEAR_ERROR_EXCEPTION', 32); -define('PEAR_ZE2', (function_exists('version_compare') && - version_compare(zend_version(), "2-dev", "ge"))); - -if (substr(PHP_OS, 0, 3) == 'WIN') { - define('OS_WINDOWS', true); - define('OS_UNIX', false); - define('PEAR_OS', 'Windows'); -} else { - define('OS_WINDOWS', false); - define('OS_UNIX', true); - define('PEAR_OS', 'Unix'); // blatant assumption -} - -// instant backwards compatibility -if (!defined('PATH_SEPARATOR')) { - if (OS_WINDOWS) { - define('PATH_SEPARATOR', ';'); - } else { - define('PATH_SEPARATOR', ':'); - } -} - -$GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_RETURN; -$GLOBALS['_PEAR_default_error_options'] = E_USER_NOTICE; -$GLOBALS['_PEAR_destructor_object_list'] = array(); -$GLOBALS['_PEAR_shutdown_funcs'] = array(); -$GLOBALS['_PEAR_error_handler_stack'] = array(); - -ini_set('track_errors', true); - -/** - * Base class for other PEAR classes. Provides rudimentary - * emulation of destructors. - * - * If you want a destructor in your class, inherit PEAR and make a - * destructor method called _yourclassname (same name as the - * constructor, but with a "_" prefix). Also, in your constructor you - * have to call the PEAR constructor: $this->PEAR();. - * The destructor method will be called without parameters. Note that - * at in some SAPI implementations (such as Apache), any output during - * the request shutdown (in which destructors are called) seems to be - * discarded. If you need to get any debug information from your - * destructor, use error_log(), syslog() or something similar. - * - * IMPORTANT! To use the emulated destructors you need to create the - * objects by reference: $obj =& new PEAR_child; - * - * @since PHP 4.0.2 - * @author Stig Bakken - * @see http://pear.php.net/manual/ - */ -class PEAR -{ - // {{{ properties - - /** - * Whether to enable internal debug messages. - * - * @var bool - * @access private - */ - var $_debug = false; - - /** - * Default error mode for this object. - * - * @var int - * @access private - */ - var $_default_error_mode = null; - - /** - * Default error options used for this object when error mode - * is PEAR_ERROR_TRIGGER. - * - * @var int - * @access private - */ - var $_default_error_options = null; - - /** - * Default error handler (callback) for this object, if error mode is - * PEAR_ERROR_CALLBACK. - * - * @var string - * @access private - */ - var $_default_error_handler = ''; - - /** - * Which class to use for error objects. - * - * @var string - * @access private - */ - var $_error_class = 'PEAR_Error'; - - /** - * An array of expected errors. - * - * @var array - * @access private - */ - var $_expected_errors = array(); - - // }}} - - // {{{ constructor - - /** - * Constructor. Registers this object in - * $_PEAR_destructor_object_list for destructor emulation if a - * destructor object exists. - * - * @param string $error_class (optional) which class to use for - * error objects, defaults to PEAR_Error. - * @access public - * @return void - */ - function PEAR($error_class = null) - { - $classname = strtolower(get_class($this)); - if ($this->_debug) { - print "PEAR constructor called, class=$classname\n"; - } - if ($error_class !== null) { - $this->_error_class = $error_class; - } - while ($classname && strcasecmp($classname, "pear")) { - $destructor = "_$classname"; - if (method_exists($this, $destructor)) { - global $_PEAR_destructor_object_list; - $_PEAR_destructor_object_list[] = &$this; - static $registered = false; - if (!$registered) { - register_shutdown_function("_PEAR_call_destructors"); - $registered = true; - } - break; - } else { - $classname = get_parent_class($classname); - } - } - } - - // }}} - // {{{ destructor - - /** - * Destructor (the emulated type of...). Does nothing right now, - * but is included for forward compatibility, so subclass - * destructors should always call it. - * - * See the note in the class desciption about output from - * destructors. - * - * @access public - * @return void - */ - function _PEAR() { - if ($this->_debug) { - printf("PEAR destructor called, class=%s\n", strtolower(get_class($this))); - } - } - - // }}} - // {{{ getStaticProperty() - - /** - * If you have a class that's mostly/entirely static, and you need static - * properties, you can use this method to simulate them. Eg. in your method(s) - * do this: $myVar = &PEAR::getStaticProperty('myclass', 'myVar'); - * You MUST use a reference, or they will not persist! - * - * @access public - * @param string $class The calling classname, to prevent clashes - * @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($class, $var) - { - static $properties; - return $properties[$class][$var]; - } - - // }}} - // {{{ registerShutdownFunc() - - /** - * Use this function to register a shutdown method for static - * classes. - * - * @access public - * @param mixed $func The function name (or array of class/method) to call - * @param mixed $args The arguments to pass to the function - * @return void - */ - function registerShutdownFunc($func, $args = array()) - { - $GLOBALS['_PEAR_shutdown_funcs'][] = array($func, $args); - } - - // }}} - // {{{ isError() - - /** - * Tell whether a value is a PEAR error. - * - * @param mixed $data the value to test - * @param int $code if $data is an error object, return true - * only if $code is a string and - * $obj->getMessage() == $code or - * $code is an integer and $obj->getCode() == $code - * @access public - * @return bool true if parameter is an error - */ - function isError($data, $code = null) - { - if (is_a($data, 'PEAR_Error')) { - if (is_null($code)) { - return true; - } elseif (is_string($code)) { - return $data->getMessage() == $code; - } else { - return $data->getCode() == $code; - } - } - return false; - } - - // }}} - // {{{ setErrorHandling() - - /** - * Sets how errors generated by this object should be handled. - * Can be invoked both in objects and statically. If called - * statically, setErrorHandling sets the default behaviour for all - * PEAR objects. If called in an object, setErrorHandling sets - * the default behaviour for that object. - * - * @param int $mode - * One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT, - * PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE, - * PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION. - * - * @param mixed $options - * When $mode is PEAR_ERROR_TRIGGER, this is the error level (one - * of E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR). - * - * When $mode is PEAR_ERROR_CALLBACK, this parameter is expected - * to be the callback function or method. A callback - * function is a string with the name of the function, a - * callback method is an array of two elements: the element - * at index 0 is the object, and the element at index 1 is - * the name of the method to call in the object. - * - * When $mode is PEAR_ERROR_PRINT or PEAR_ERROR_DIE, this is - * a printf format string used when printing the error - * message. - * - * @access public - * @return void - * @see PEAR_ERROR_RETURN - * @see PEAR_ERROR_PRINT - * @see PEAR_ERROR_TRIGGER - * @see PEAR_ERROR_DIE - * @see PEAR_ERROR_CALLBACK - * @see PEAR_ERROR_EXCEPTION - * - * @since PHP 4.0.5 - */ - - function setErrorHandling($mode = null, $options = null) - { - if (isset($this) && is_a($this, 'PEAR')) { - $setmode = &$this->_default_error_mode; - $setoptions = &$this->_default_error_options; - } else { - $setmode = &$GLOBALS['_PEAR_default_error_mode']; - $setoptions = &$GLOBALS['_PEAR_default_error_options']; - } - - switch ($mode) { - case PEAR_ERROR_EXCEPTION: - case PEAR_ERROR_RETURN: - case PEAR_ERROR_PRINT: - case PEAR_ERROR_TRIGGER: - case PEAR_ERROR_DIE: - case null: - $setmode = $mode; - $setoptions = $options; - break; - - case PEAR_ERROR_CALLBACK: - $setmode = $mode; - // class/object method callback - if (is_callable($options)) { - $setoptions = $options; - } else { - trigger_error("invalid error callback", E_USER_WARNING); - } - break; - - default: - trigger_error("invalid error mode", E_USER_WARNING); - break; - } - } - - // }}} - // {{{ expectError() - - /** - * This method is used to tell which errors you expect to get. - * Expected errors are always returned with error mode - * PEAR_ERROR_RETURN. Expected error codes are stored in a stack, - * and this method pushes a new element onto it. The list of - * expected errors are in effect until they are popped off the - * stack with the popExpect() method. - * - * Note that this method can not be called statically - * - * @param mixed $code a single error code or an array of error codes to expect - * - * @return int the new depth of the "expected errors" stack - * @access public - */ - function expectError($code = '*') - { - if (is_array($code)) { - array_push($this->_expected_errors, $code); - } else { - array_push($this->_expected_errors, array($code)); - } - return sizeof($this->_expected_errors); - } - - // }}} - // {{{ popExpect() - - /** - * This method pops one element off the expected error codes - * stack. - * - * @return array the list of error codes that were popped - */ - function popExpect() - { - return array_pop($this->_expected_errors); - } - - // }}} - // {{{ _checkDelExpect() - - /** - * This method checks unsets an error code if available - * - * @param mixed error code - * @return bool true if the error code was unset, false otherwise - * @access private - * @since PHP 4.3.0 - */ - function _checkDelExpect($error_code) - { - $deleted = false; - - foreach ($this->_expected_errors AS $key => $error_array) { - if (in_array($error_code, $error_array)) { - unset($this->_expected_errors[$key][array_search($error_code, $error_array)]); - $deleted = true; - } - - // clean up empty arrays - if (0 == count($this->_expected_errors[$key])) { - unset($this->_expected_errors[$key]); - } - } - return $deleted; - } - - // }}} - // {{{ delExpect() - - /** - * This method deletes all occurences of the specified element from - * the expected error codes stack. - * - * @param mixed $error_code error code that should be deleted - * @return mixed list of error codes that were deleted or error - * @access public - * @since PHP 4.3.0 - */ - function delExpect($error_code) - { - $deleted = false; - - if ((is_array($error_code) && (0 != count($error_code)))) { - // $error_code is a non-empty array here; - // we walk through it trying to unset all - // values - foreach($error_code as $key => $error) { - if ($this->_checkDelExpect($error)) { - $deleted = true; - } else { - $deleted = false; - } - } - return $deleted ? true : PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME - } elseif (!empty($error_code)) { - // $error_code comes alone, trying to unset it - if ($this->_checkDelExpect($error_code)) { - return true; - } else { - return PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME - } - } else { - // $error_code is empty - return PEAR::raiseError("The expected error you submitted is empty"); // IMPROVE ME - } - } - - // }}} - // {{{ raiseError() - - /** - * This method is a wrapper that returns an instance of the - * configured error class with this object's default error - * handling applied. If the $mode and $options parameters are not - * specified, the object's defaults are used. - * - * @param mixed $message a text error message or a PEAR error object - * - * @param int $code a numeric error code (it is up to your class - * to define these if you want to use codes) - * - * @param int $mode One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT, - * PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE, - * PEAR_ERROR_CALLBACK, PEAR_ERROR_EXCEPTION. - * - * @param mixed $options If $mode is PEAR_ERROR_TRIGGER, this parameter - * specifies the PHP-internal error level (one of - * E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR). - * If $mode is PEAR_ERROR_CALLBACK, this - * parameter specifies the callback function or - * method. In other error modes this parameter - * is ignored. - * - * @param string $userinfo If you need to pass along for example debug - * information, this parameter is meant for that. - * - * @param string $error_class The returned error object will be - * instantiated from this class, if specified. - * - * @param bool $skipmsg If true, raiseError will only pass error codes, - * the error message parameter will be dropped. - * - * @access public - * @return object a PEAR error object - * @see PEAR::setErrorHandling - * @since PHP 4.0.5 - */ - function raiseError($message = null, - $code = null, - $mode = null, - $options = null, - $userinfo = null, - $error_class = null, - $skipmsg = false) - { - // The error is yet a PEAR error object - if (is_object($message)) { - $code = $message->getCode(); - $userinfo = $message->getUserInfo(); - $error_class = $message->getType(); - $message->error_message_prefix = ''; - $message = $message->getMessage(); - } - - if (isset($this) && isset($this->_expected_errors) && sizeof($this->_expected_errors) > 0 && sizeof($exp = end($this->_expected_errors))) { - if ($exp[0] == "*" || - (is_int(reset($exp)) && in_array($code, $exp)) || - (is_string(reset($exp)) && in_array($message, $exp))) { - $mode = PEAR_ERROR_RETURN; - } - } - // No mode given, try global ones - if ($mode === null) { - // Class error handler - if (isset($this) && isset($this->_default_error_mode)) { - $mode = $this->_default_error_mode; - $options = $this->_default_error_options; - // Global error handler - } elseif (isset($GLOBALS['_PEAR_default_error_mode'])) { - $mode = $GLOBALS['_PEAR_default_error_mode']; - $options = $GLOBALS['_PEAR_default_error_options']; - } - } - - if ($error_class !== null) { - $ec = $error_class; - } elseif (isset($this) && isset($this->_error_class)) { - $ec = $this->_error_class; - } else { - $ec = 'PEAR_Error'; - } - if ($skipmsg) { - return new $ec($code, $mode, $options, $userinfo); - } else { - return new $ec($message, $code, $mode, $options, $userinfo); - } - } - - // }}} - // {{{ throwError() - - /** - * Simpler form of raiseError with fewer options. In most cases - * message, code and userinfo are enough. - * - * @param string $message - * - */ - function throwError($message = null, - $code = null, - $userinfo = null) - { - if (isset($this) && is_a($this, 'PEAR')) { - return $this->raiseError($message, $code, null, null, $userinfo); - } else { - return PEAR::raiseError($message, $code, null, null, $userinfo); - } - } - - // }}} - function staticPushErrorHandling($mode, $options = null) - { - $stack = &$GLOBALS['_PEAR_error_handler_stack']; - $def_mode = &$GLOBALS['_PEAR_default_error_mode']; - $def_options = &$GLOBALS['_PEAR_default_error_options']; - $stack[] = array($def_mode, $def_options); - switch ($mode) { - case PEAR_ERROR_EXCEPTION: - case PEAR_ERROR_RETURN: - case PEAR_ERROR_PRINT: - case PEAR_ERROR_TRIGGER: - case PEAR_ERROR_DIE: - case null: - $def_mode = $mode; - $def_options = $options; - break; - - case PEAR_ERROR_CALLBACK: - $def_mode = $mode; - // class/object method callback - if (is_callable($options)) { - $def_options = $options; - } else { - trigger_error("invalid error callback", E_USER_WARNING); - } - break; - - default: - trigger_error("invalid error mode", E_USER_WARNING); - break; - } - $stack[] = array($mode, $options); - return true; - } - - function staticPopErrorHandling() - { - $stack = &$GLOBALS['_PEAR_error_handler_stack']; - $setmode = &$GLOBALS['_PEAR_default_error_mode']; - $setoptions = &$GLOBALS['_PEAR_default_error_options']; - array_pop($stack); - list($mode, $options) = $stack[sizeof($stack) - 1]; - array_pop($stack); - switch ($mode) { - case PEAR_ERROR_EXCEPTION: - case PEAR_ERROR_RETURN: - case PEAR_ERROR_PRINT: - case PEAR_ERROR_TRIGGER: - case PEAR_ERROR_DIE: - case null: - $setmode = $mode; - $setoptions = $options; - break; - - case PEAR_ERROR_CALLBACK: - $setmode = $mode; - // class/object method callback - if (is_callable($options)) { - $setoptions = $options; - } else { - trigger_error("invalid error callback", E_USER_WARNING); - } - break; - - default: - trigger_error("invalid error mode", E_USER_WARNING); - break; - } - return true; - } - - // {{{ pushErrorHandling() - - /** - * Push a new error handler on top of the error handler options stack. With this - * you can easily override the actual error handler for some code and restore - * it later with popErrorHandling. - * - * @param mixed $mode (same as setErrorHandling) - * @param mixed $options (same as setErrorHandling) - * - * @return bool Always true - * - * @see PEAR::setErrorHandling - */ - function pushErrorHandling($mode, $options = null) - { - $stack = &$GLOBALS['_PEAR_error_handler_stack']; - if (isset($this) && is_a($this, 'PEAR')) { - $def_mode = &$this->_default_error_mode; - $def_options = &$this->_default_error_options; - } else { - $def_mode = &$GLOBALS['_PEAR_default_error_mode']; - $def_options = &$GLOBALS['_PEAR_default_error_options']; - } - $stack[] = array($def_mode, $def_options); - - if (isset($this) && is_a($this, 'PEAR')) { - $this->setErrorHandling($mode, $options); - } else { - PEAR::setErrorHandling($mode, $options); - } - $stack[] = array($mode, $options); - return true; - } - - // }}} - // {{{ popErrorHandling() - - /** - * Pop the last error handler used - * - * @return bool Always true - * - * @see PEAR::pushErrorHandling - */ - function popErrorHandling() - { - $stack = &$GLOBALS['_PEAR_error_handler_stack']; - array_pop($stack); - list($mode, $options) = $stack[sizeof($stack) - 1]; - array_pop($stack); - if (isset($this) && is_a($this, 'PEAR')) { - $this->setErrorHandling($mode, $options); - } else { - PEAR::setErrorHandling($mode, $options); - } - return true; - } - - // }}} - // {{{ loadExtension() - - /** - * OS independant PHP extension load. Remember to take care - * on the correct extension name for case sensitive OSes. - * - * @param string $ext The extension name - * @return bool Success or not on the dl() call - */ - function loadExtension($ext) - { - if (!extension_loaded($ext)) { - // if either returns true dl() will produce a FATAL error, stop that - if ((ini_get('enable_dl') != 1) || (ini_get('safe_mode') == 1)) { - return false; - } - if (OS_WINDOWS) { - $suffix = '.dll'; - } elseif (PHP_OS == 'HP-UX') { - $suffix = '.sl'; - } elseif (PHP_OS == 'AIX') { - $suffix = '.a'; - } elseif (PHP_OS == 'OSX') { - $suffix = '.bundle'; - } else { - $suffix = '.so'; - } - return @dl('php_'.$ext.$suffix) || @dl($ext.$suffix); - } - return true; - } - - // }}} -} - -// {{{ _PEAR_call_destructors() - -function _PEAR_call_destructors() -{ - global $_PEAR_destructor_object_list; - if (is_array($_PEAR_destructor_object_list) && - sizeof($_PEAR_destructor_object_list)) - { - reset($_PEAR_destructor_object_list); - if (@PEAR::getStaticProperty('PEAR', 'destructlifo')) { - $_PEAR_destructor_object_list = array_reverse($_PEAR_destructor_object_list); - } - while (list($k, $objref) = each($_PEAR_destructor_object_list)) { - $classname = get_class($objref); - while ($classname) { - $destructor = "_$classname"; - if (method_exists($objref, $destructor)) { - $objref->$destructor(); - break; - } else { - $classname = get_parent_class($classname); - } - } - } - // Empty the object list to ensure that destructors are - // not called more than once. - $_PEAR_destructor_object_list = array(); - } - - // Now call the shutdown functions - if (is_array($GLOBALS['_PEAR_shutdown_funcs']) AND !empty($GLOBALS['_PEAR_shutdown_funcs'])) { - foreach ($GLOBALS['_PEAR_shutdown_funcs'] as $value) { - call_user_func_array($value[0], $value[1]); - } - } -} - -// }}} - -class PEAR_Error -{ - // {{{ properties - - var $error_message_prefix = ''; - var $mode = PEAR_ERROR_RETURN; - var $level = E_USER_NOTICE; - var $code = -1; - var $message = ''; - var $userinfo = ''; - var $backtrace = null; - - // }}} - // {{{ constructor - - /** - * PEAR_Error constructor - * - * @param string $message message - * - * @param int $code (optional) error code - * - * @param int $mode (optional) error mode, one of: PEAR_ERROR_RETURN, - * PEAR_ERROR_PRINT, PEAR_ERROR_DIE, PEAR_ERROR_TRIGGER, - * PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION - * - * @param mixed $options (optional) error level, _OR_ in the case of - * PEAR_ERROR_CALLBACK, the callback function or object/method - * tuple. - * - * @param string $userinfo (optional) additional user/debug info - * - * @access public - * - */ - function PEAR_Error($message = 'unknown error', $code = null, - $mode = null, $options = null, $userinfo = null) - { - if ($mode === null) { - $mode = PEAR_ERROR_RETURN; - } - $this->message = $message; - $this->code = $code; - $this->mode = $mode; - $this->userinfo = $userinfo; - if (function_exists("debug_backtrace")) { - if (@!PEAR::getStaticProperty('PEAR_Error', 'skiptrace')) { - $this->backtrace = debug_backtrace(); - } - } - if ($mode & PEAR_ERROR_CALLBACK) { - $this->level = E_USER_NOTICE; - $this->callback = $options; - } else { - if ($options === null) { - $options = E_USER_NOTICE; - } - $this->level = $options; - $this->callback = null; - } - if ($this->mode & PEAR_ERROR_PRINT) { - if (is_null($options) || is_int($options)) { - $format = "%s"; - } else { - $format = $options; - } - printf($format, $this->getMessage()); - } - if ($this->mode & PEAR_ERROR_TRIGGER) { - trigger_error($this->getMessage(), $this->level); - } - if ($this->mode & PEAR_ERROR_DIE) { - $msg = $this->getMessage(); - if (is_null($options) || is_int($options)) { - $format = "%s"; - if (substr($msg, -1) != "\n") { - $msg .= "\n"; - } - } else { - $format = $options; - } - die(sprintf($format, $msg)); - } - if ($this->mode & PEAR_ERROR_CALLBACK) { - if (is_callable($this->callback)) { - call_user_func($this->callback, $this); - } - } - if ($this->mode & PEAR_ERROR_EXCEPTION) { - trigger_error("PEAR_ERROR_EXCEPTION is obsolete, use class PEAR_ErrorStack for exceptions", E_USER_WARNING); - eval('$e = new Exception($this->message, $this->code);$e->PEAR_Error = $this;throw($e);'); - } - } - - // }}} - // {{{ getMode() - - /** - * Get the error mode from an error object. - * - * @return int error mode - * @access public - */ - function getMode() { - return $this->mode; - } - - // }}} - // {{{ getCallback() - - /** - * Get the callback function/method from an error object. - * - * @return mixed callback function or object/method array - * @access public - */ - function getCallback() { - return $this->callback; - } - - // }}} - // {{{ getMessage() - - - /** - * Get the error message from an error object. - * - * @return string full error message - * @access public - */ - function getMessage() - { - return ($this->error_message_prefix . $this->message); - } - - - // }}} - // {{{ getCode() - - /** - * Get error code from an error object - * - * @return int error code - * @access public - */ - function getCode() - { - return $this->code; - } - - // }}} - // {{{ getType() - - /** - * Get the name of this error/exception. - * - * @return string error/exception name (type) - * @access public - */ - function getType() - { - return get_class($this); - } - - // }}} - // {{{ getUserInfo() - - /** - * Get additional user-supplied information. - * - * @return string user-supplied information - * @access public - */ - function getUserInfo() - { - return $this->userinfo; - } - - // }}} - // {{{ getDebugInfo() - - /** - * Get additional debug information supplied by the application. - * - * @return string debug information - * @access public - */ - function getDebugInfo() - { - return $this->getUserInfo(); - } - - // }}} - // {{{ getBacktrace() - - /** - * Get the call backtrace from where the error was generated. - * Supported with PHP 4.3.0 or newer. - * - * @param int $frame (optional) what frame to fetch - * @return array Backtrace, or NULL if not available. - * @access public - */ - function getBacktrace($frame = null) - { - if ($frame === null) { - return $this->backtrace; - } - return $this->backtrace[$frame]; - } - - // }}} - // {{{ addUserInfo() - - function addUserInfo($info) - { - if (empty($this->userinfo)) { - $this->userinfo = $info; - } else { - $this->userinfo .= " ** $info"; - } - } - - // }}} - // {{{ toString() - - /** - * Make a string representation of this object. - * - * @return string a string with an object summary - * @access public - */ - function toString() { - $modes = array(); - $levels = array(E_USER_NOTICE => 'notice', - E_USER_WARNING => 'warning', - E_USER_ERROR => 'error'); - if ($this->mode & PEAR_ERROR_CALLBACK) { - if (is_array($this->callback)) { - $callback = (is_object($this->callback[0]) ? - strtolower(get_class($this->callback[0])) : - $this->callback[0]) . '::' . - $this->callback[1]; - } else { - $callback = $this->callback; - } - return sprintf('[%s: message="%s" code=%d mode=callback '. - 'callback=%s prefix="%s" info="%s"]', - strtolower(get_class($this)), $this->message, $this->code, - $callback, $this->error_message_prefix, - $this->userinfo); - } - if ($this->mode & PEAR_ERROR_PRINT) { - $modes[] = 'print'; - } - if ($this->mode & PEAR_ERROR_TRIGGER) { - $modes[] = 'trigger'; - } - if ($this->mode & PEAR_ERROR_DIE) { - $modes[] = 'die'; - } - if ($this->mode & PEAR_ERROR_RETURN) { - $modes[] = 'return'; - } - return sprintf('[%s: message="%s" code=%d mode=%s level=%s '. - 'prefix="%s" info="%s"]', - strtolower(get_class($this)), $this->message, $this->code, - implode("|", $modes), $levels[$this->level], - $this->error_message_prefix, - $this->userinfo); - } - - // }}} -} - -/* - * Local Variables: - * mode: php - * tab-width: 4 - * c-basic-offset: 4 - * End: - */ -?> diff --git a/gulliver/thirdparty/pear/PEAR/Autoloader.php b/gulliver/thirdparty/pear/PEAR/Autoloader.php deleted file mode 100644 index 117e49fed..000000000 --- a/gulliver/thirdparty/pear/PEAR/Autoloader.php +++ /dev/null @@ -1,186 +0,0 @@ - | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Autoloader.php,v 1.6 2003/03/18 12:06:06 ssb Exp $ - -if (!extension_loaded("overload")) { - // die hard without ext/overload - die("Rebuild PHP with the `overload' extension to use PEAR_Autoloader"); -} - -require_once "PEAR.php"; - -/** - * This class is for objects where you want to separate the code for - * some methods into separate classes. This is useful if you have a - * class with not-frequently-used methods that contain lots of code - * that you would like to avoid always parsing. - * - * The PEAR_Autoloader class provides autoloading and aggregation. - * The autoloading lets you set up in which classes the separated - * methods are found. Aggregation is the technique used to import new - * methods, an instance of each class providing separated methods is - * stored and called every time the aggregated method is called. - * - * @author Stig S�ther Bakken - */ -class PEAR_Autoloader extends PEAR -{ - /** - * Map of methods and classes where they are defined - * - * @var array - * - * @access private - */ - var $_autoload_map = array(); - - /** - * Map of methods and aggregate objects - * - * @var array - * - * @access private - */ - var $_method_map = array(); - - /** - * Add one or more autoload entries. - * - * @param string $method which method to autoload - * - * @param string $classname (optional) which class to find the method in. - * If the $method parameter is an array, this - * parameter may be omitted (and will be ignored - * if not), and the $method parameter will be - * treated as an associative array with method - * names as keys and class names as values. - * - * @return void - * - * @access public - */ - function addAutoload($method, $classname = null) - { - if (is_array($method)) { - $this->_autoload_map = array_merge($this->_autoload_map, $method); - } else { - $this->_autoload_map[$method] = $classname; - } - } - - /** - * Remove an autoload entry. - * - * @param string $method which method to remove the autoload entry for - * - * @return bool TRUE if an entry was removed, FALSE if not - * - * @access public - */ - function removeAutoload($method) - { - $ok = isset($this->_autoload_map[$method]); - unset($this->_autoload_map[$method]); - return $ok; - } - - /** - * Add an aggregate object to this object. If the specified class - * is not defined, loading it will be attempted following PEAR's - * file naming scheme. All the methods in the class will be - * aggregated, except private ones (name starting with an - * underscore) and constructors. - * - * @param string $classname what class to instantiate for the object. - * - * @return void - * - * @access public - */ - function addAggregateObject($classname) - { - $classname = strtolower($classname); - if (!class_exists($classname)) { - $include_file = preg_replace('/[^a-z0-9]/i', '_', $classname); - include_once $include_file; - } - $obj =& new $classname; - $methods = get_class_methods($classname); - foreach ($methods as $method) { - // don't import priviate methods and constructors - if ($method{0} != '_' && $method != $classname) { - $this->_method_map[$method] = $obj; - } - } - } - - /** - * Remove an aggregate object. - * - * @param string $classname the class of the object to remove - * - * @return bool TRUE if an object was removed, FALSE if not - * - * @access public - */ - function removeAggregateObject($classname) - { - $ok = false; - $classname = strtolower($classname); - reset($this->_method_map); - while (list($method, $obj) = each($this->_method_map)) { - if (is_object($obj) && get_class($obj) == $classname) { - unset($this->_method_map[$method]); - $ok = true; - } - } - return $ok; - } - - /** - * Overloaded object call handler, called each time an - * undefined/aggregated method is invoked. This method repeats - * the call in the right aggregate object and passes on the return - * value. - * - * @param string $method which method that was called - * - * @param string $args An array of the parameters passed in the - * original call - * - * @return mixed The return value from the aggregated method, or a PEAR - * error if the called method was unknown. - */ - function __call($method, $args, &$retval) - { - if (empty($this->_method_map[$method]) && isset($this->_autoload_map[$method])) { - $this->addAggregateObject($this->_autoload_map[$method]); - } - if (isset($this->_method_map[$method])) { - $retval = call_user_func_array(array($this->_method_map[$method], $method), $args); - return true; - } - return false; - } -} - -overload("PEAR_Autoloader"); - -?> diff --git a/gulliver/thirdparty/pear/PEAR/Builder.php b/gulliver/thirdparty/pear/PEAR/Builder.php deleted file mode 100644 index cbd443d50..000000000 --- a/gulliver/thirdparty/pear/PEAR/Builder.php +++ /dev/null @@ -1,410 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Builder.php,v 1.10 2003/03/21 07:57:27 ssb Exp $ - -require_once 'PEAR/Common.php'; - -/** - * Class to handle building (compiling) extensions. - * - * @author Stig Sæther Bakken - */ -class PEAR_Builder extends PEAR_Common -{ - // {{{ properties - - var $php_api_version = 0; - var $zend_module_api_no = 0; - var $zend_extension_api_no = 0; - - var $extensions_built = array(); - - var $current_callback = null; - - // used for msdev builds - var $_lastline = null; - var $_firstline = null; - // }}} - // {{{ constructor - - /** - * PEAR_Builder constructor. - * - * @param object $ui user interface object (instance of PEAR_Frontend_*) - * - * @access public - */ - function PEAR_Builder(&$ui) - { - parent::PEAR_Common(); - $this->setFrontendObject($ui); - } - - // }}} - - // {{{ _build_win32() - - /** - * Build an extension from source on windows. - * requires msdev - */ - function _build_win32($descfile, $callback = null) - { - if (PEAR::isError($info = $this->infoFromDescriptionFile($descfile))) { - return $info; - } - $dir = dirname($descfile); - $old_cwd = getcwd(); - - if (!@chdir($dir)) { - return $this->raiseError("could not chdir to $dir"); - } - $this->log(2, "building in $dir"); - - $dsp = $info['package'].'.dsp'; - if (!@is_file("$dir/$dsp")) { - return $this->raiseError("The DSP $dsp does not exist."); - } - // XXX TODO: make release build type configurable - $command = 'msdev '.$dsp.' /MAKE "'.$info['package']. ' - Release"'; - - $this->current_callback = $callback; - $err = $this->_runCommand($command, array(&$this, 'msdevCallback')); - if (PEAR::isError($err)) { - return $err; - } - - // figure out the build platform and type - $platform = 'Win32'; - $buildtype = 'Release'; - if (preg_match('/.*?'.$info['package'].'\s-\s(\w+)\s(.*?)-+/i',$this->_firstline,$matches)) { - $platform = $matches[1]; - $buildtype = $matches[2]; - } - - if (preg_match('/(.*)?\s-\s(\d+).*?(\d+)/',$this->_lastline,$matches)) { - if ($matches[2]) { - // there were errors in the build - return $this->raiseError("There were errors during compilation."); - } - $out = $matches[1]; - } else { - return $this->raiseError("Did not understand the completion status returned from msdev.exe."); - } - - 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(); - $dsp = $filter->validateInput($dsp,"path"); - // msdev doesn't tell us the output directory :/ - // open the dsp, find /out and use that directory - $dsptext = join(file($dsp),''); - - // this regex depends on the build platform and type having been - // correctly identified above. - $regex ='/.*?!IF\s+"\$\(CFG\)"\s+==\s+("'. - $info['package'].'\s-\s'. - $platform.'\s'. - $buildtype.'").*?'. - '\/out:"(.*?)"/is'; - - if ($dsptext && preg_match($regex,$dsptext,$matches)) { - // what we get back is a relative path to the output file itself. - $outfile = realpath($matches[2]); - } else { - return $this->raiseError("Could not retrieve output information from $dsp."); - } - if (@copy($outfile, "$dir/$out")) { - $outfile = "$dir/$out"; - } - - $built_files[] = array( - 'file' => "$outfile", - 'php_api' => $this->php_api_version, - 'zend_mod_api' => $this->zend_module_api_no, - 'zend_ext_api' => $this->zend_extension_api_no, - ); - - return $built_files; - } - // }}} - - // {{{ msdevCallback() - function msdevCallback($what, $data) - { - if (!$this->_firstline) - $this->_firstline = $data; - $this->_lastline = $data; - } - // }}} - - // {{{ build() - - /** - * Build an extension from source. Runs "phpize" in the source - * directory, but compiles in a temporary directory - * (/var/tmp/pear-build-USER/PACKAGE-VERSION). - * - * @param string $descfile path to XML package description file - * - * @param mixed $callback callback function used to report output, - * see PEAR_Builder::_runCommand for details - * - * @return array an array of associative arrays with built files, - * format: - * array( array( 'file' => '/path/to/ext.so', - * 'php_api' => YYYYMMDD, - * 'zend_mod_api' => YYYYMMDD, - * 'zend_ext_api' => YYYYMMDD ), - * ... ) - * - * @access public - * - * @see PEAR_Builder::_runCommand - * @see PEAR_Common::infoFromDescriptionFile - */ - function build($descfile, $callback = null) - { - if (PEAR_OS == "Windows") { - return $this->_build_win32($descfile,$callback); - } - if (PEAR_OS != 'Unix') { - return $this->raiseError("building extensions not supported on this platform"); - } - if (PEAR::isError($info = $this->infoFromDescriptionFile($descfile))) { - return $info; - } - $dir = dirname($descfile); - $old_cwd = getcwd(); - if (!@chdir($dir)) { - return $this->raiseError("could not chdir to $dir"); - } - $vdir = "$info[package]-$info[version]"; - if (is_dir($vdir)) { - chdir($vdir); - } - $dir = getcwd(); - $this->log(2, "building in $dir"); - $this->current_callback = $callback; - $err = $this->_runCommand("phpize", array(&$this, 'phpizeCallback')); - if (PEAR::isError($err)) { - return $err; - } - if (!$err) { - return $this->raiseError("`phpize' failed"); - } - - // start of interactive part - $configure_command = "$dir/configure"; - if (isset($info['configure_options'])) { - foreach ($info['configure_options'] as $o) { - list($r) = $this->ui->userDialog('build', - array($o['prompt']), - array('text'), - array(@$o['default'])); - if (substr($o['name'], 0, 5) == 'with-' && - ($r == 'yes' || $r == 'autodetect')) { - $configure_command .= " --$o[name]"; - } else { - $configure_command .= " --$o[name]=$r"; - } - } - } - // end of interactive part - - // make configurable - if(!$user=getenv('USER')){ - $user='defaultuser'; - } - $build_basedir = "/var/tmp/pear-build-$user"; - $build_dir = "$build_basedir/$info[package]-$info[version]"; - $this->log(1, "building in $build_dir"); - if (is_dir($build_dir)) { - System::rm("-rf $build_dir"); - } - if (!System::mkDir("-p $build_dir")) { - return $this->raiseError("could not create build dir: $build_dir"); - } - $this->addTempFile($build_dir); - if (getenv('MAKE')) { - $make_command = getenv('MAKE'); - } else { - $make_command = 'make'; - } - $to_run = array( - $configure_command, - $make_command, - ); - if (!@chdir($build_dir)) { - return $this->raiseError("could not chdir to $build_dir"); - } - foreach ($to_run as $cmd) { - $err = $this->_runCommand($cmd, $callback); - if (PEAR::isError($err)) { - chdir($old_cwd); - return $err; - } - if (!$err) { - chdir($old_cwd); - return $this->raiseError("`$cmd' failed"); - } - } - if (!($dp = opendir("modules"))) { - chdir($old_cwd); - return $this->raiseError("no `modules' directory found"); - } - $built_files = array(); - while ($ent = readdir($dp)) { - if ($ent{0} == '.' || substr($ent, -3) == '.la') { - continue; - } - // harvest! - if (@copy("modules/$ent", "$dir/$ent")) { - $built_files[] = array( - 'file' => "$dir/$ent", - 'php_api' => $this->php_api_version, - 'zend_mod_api' => $this->zend_module_api_no, - 'zend_ext_api' => $this->zend_extension_api_no, - ); - - $this->log(1, "$ent copied to $dir/$ent"); - } else { - chdir($old_cwd); - return $this->raiseError("failed copying $ent to $dir"); - } - } - closedir($dp); - chdir($old_cwd); - return $built_files; - } - - // }}} - // {{{ phpizeCallback() - - /** - * Message callback function used when running the "phpize" - * program. Extracts the API numbers used. Ignores other message - * types than "cmdoutput". - * - * @param string $what the type of message - * @param mixed $data the message - * - * @return void - * - * @access public - */ - function phpizeCallback($what, $data) - { - if ($what != 'cmdoutput') { - return; - } - $this->log(3, rtrim($data)); - if (preg_match('/You should update your .aclocal.m4/', $data)) { - return; - } - $matches = array(); - if (preg_match('/^\s+(\S[^:]+):\s+(\d{8})/', $data, $matches)) { - $member = preg_replace('/[^a-z]/', '_', strtolower($matches[1])); - $apino = (int)$matches[2]; - if (isset($this->$member)) { - $this->$member = $apino; - $msg = sprintf("%-22s : %d", $matches[1], $apino); - $this->log(1, $msg); - } - } - } - - // }}} - // {{{ _runCommand() - - /** - * Run an external command, using a message callback to report - * output. The command will be run through popen and output is - * reported for every line with a "cmdoutput" message with the - * line string, including newlines, as payload. - * - * @param string $command the command to run - * - * @param mixed $callback (optional) function to use as message - * callback - * - * @return bool whether the command was successful (exit code 0 - * means success, any other means failure) - * - * @access private - */ - function _runCommand($command, $callback = null) - { - 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(); - $command = $filter->validateInput($command); - - $this->log(1, "running: $command"); - $pp = @popen("$command 2>&1", "r"); - if (!$pp) { - return $this->raiseError("failed to run `$command'"); - } - while ($line = fgets($pp, 1024)) { - if ($callback) { - call_user_func($callback, 'cmdoutput', $line); - } else { - $this->log(2, rtrim($line)); - } - } - $exitcode = @pclose($pp); - return ($exitcode == 0); - } - - // }}} - // {{{ log() - - function log($level, $msg) - { - if ($this->current_callback) { - if ($this->debug >= $level) { - call_user_func($this->current_callback, 'output', $msg); - } - return; - } - return PEAR_Common::log($level, $msg); - } - - // }}} -} - -?> diff --git a/gulliver/thirdparty/pear/PEAR/Command.php b/gulliver/thirdparty/pear/PEAR/Command.php deleted file mode 100644 index ba78c9136..000000000 --- a/gulliver/thirdparty/pear/PEAR/Command.php +++ /dev/null @@ -1,322 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Command.php,v 1.18 2003/03/18 12:06:06 ssb Exp $ - - -require_once "PEAR.php"; - -/** - * List of commands and what classes they are implemented in. - * @var array command => implementing class - */ -$GLOBALS['_PEAR_Command_commandlist'] = array(); - -/** - * List of shortcuts to common commands. - * @var array shortcut => command - */ -$GLOBALS['_PEAR_Command_shortcuts'] = array(); - -/** - * Array of command objects - * @var array class => object - */ -$GLOBALS['_PEAR_Command_objects'] = array(); - -/** - * Which user interface class is being used. - * @var string class name - */ -$GLOBALS['_PEAR_Command_uiclass'] = 'PEAR_Frontend_CLI'; - -/** - * Instance of $_PEAR_Command_uiclass. - * @var object - */ -$GLOBALS['_PEAR_Command_uiobject'] = null; - -/** - * PEAR command class, a simple factory class for administrative - * commands. - * - * How to implement command classes: - * - * - The class must be called PEAR_Command_Nnn, installed in the - * "PEAR/Common" subdir, with a method called getCommands() that - * returns an array of the commands implemented by the class (see - * PEAR/Command/Install.php for an example). - * - * - The class must implement a run() function that is called with three - * params: - * - * (string) command name - * (array) assoc array with options, freely defined by each - * command, for example: - * array('force' => true) - * (array) list of the other parameters - * - * The run() function returns a PEAR_CommandResponse object. Use - * these methods to get information: - * - * int getStatus() Returns PEAR_COMMAND_(SUCCESS|FAILURE|PARTIAL) - * *_PARTIAL means that you need to issue at least - * one more command to complete the operation - * (used for example for validation steps). - * - * string getMessage() Returns a message for the user. Remember, - * no HTML or other interface-specific markup. - * - * If something unexpected happens, run() returns a PEAR error. - * - * - DON'T OUTPUT ANYTHING! Return text for output instead. - * - * - DON'T USE HTML! The text you return will be used from both Gtk, - * web and command-line interfaces, so for now, keep everything to - * plain text. - * - * - DON'T USE EXIT OR DIE! Always use pear errors. From static - * classes do PEAR::raiseError(), from other classes do - * $this->raiseError(). - */ -class PEAR_Command -{ - /** - * Get the right object for executing a command. - * - * @param string $command The name of the command - * @param object $config Instance of PEAR_Config object - * - * @return object the command object or a PEAR error - * - * @access public - */ - function factory($command, &$config) - { - if (empty($GLOBALS['_PEAR_Command_commandlist'])) { - PEAR_Command::registerCommands(); - } - if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) { - $command = $GLOBALS['_PEAR_Command_shortcuts'][$command]; - } - $class = @$GLOBALS['_PEAR_Command_commandlist'][$command]; - if (empty($class)) { - return PEAR::raiseError("unknown command `$command'"); - } - $ui = PEAR_Command::getFrontendObject(); - $obj = &new $class($ui, $config); - return $obj; - } - - /** - * Get instance of frontend object. - * - * @return object - */ - function &getFrontendObject() - { - if (empty($GLOBALS['_PEAR_Command_uiobject'])) { - $GLOBALS['_PEAR_Command_uiobject'] = &new $GLOBALS['_PEAR_Command_uiclass']; - } - return $GLOBALS['_PEAR_Command_uiobject']; - } - - /** - * Load current frontend class. - * - * @param string $uiclass Name of class implementing the frontend - * - * @return object the frontend object, or a PEAR error - */ - function &setFrontendClass($uiclass) - { - if (is_object($GLOBALS['_PEAR_Command_uiobject']) && - strtolower($uiclass) == get_class($GLOBALS['_PEAR_Command_uiobject'])) { - return; - } - $file = str_replace('_', '/', $uiclass) . '.php'; - @include_once $file; - if (class_exists(strtolower($uiclass))) { - $obj = &new $uiclass; - // quick test to see if this class implements a few of the most - // important frontend methods - if (method_exists($obj, 'userConfirm')) { - $GLOBALS['_PEAR_Command_uiobject'] = &$obj; - $GLOBALS['_PEAR_Command_uiclass'] = $uiclass; - return $obj; - } else { - return PEAR::raiseError("not a frontend class: $uiclass"); - } - } - return PEAR::raiseError("no such class: $uiclass"); - } - - /** - * Set current frontend. - * - * @param string $uitype Name of the frontend type (for example "CLI") - * - * @return object the frontend object, or a PEAR error - */ - function setFrontendType($uitype) - { - $uiclass = 'PEAR_Frontend_' . $uitype; - return PEAR_Command::setFrontendClass($uiclass); - } - - /** - * Scan through the Command directory looking for classes - * and see what commands they implement. - * - * @param bool (optional) if FALSE (default), the new list of - * commands should replace the current one. If TRUE, - * new entries will be merged with old. - * - * @param string (optional) where (what directory) to look for - * classes, defaults to the Command subdirectory of - * the directory from where this file (__FILE__) is - * included. - * - * @return bool TRUE on success, a PEAR error on failure - * - * @access public - */ - function registerCommands($merge = false, $dir = null) - { - if ($dir === null) { - $dir = dirname(__FILE__) . '/Command'; - } - $dp = @opendir($dir); - if (empty($dp)) { - return PEAR::raiseError("registerCommands: opendir($dir) failed"); - } - if (!$merge) { - $GLOBALS['_PEAR_Command_commandlist'] = array(); - } - while ($entry = readdir($dp)) { - if ($entry{0} == '.' || substr($entry, -4) != '.php' || $entry == 'Common.php') { - continue; - } - $class = "PEAR_Command_".substr($entry, 0, -4); - $file = "$dir/$entry"; - include_once $file; - // List of commands - if (empty($GLOBALS['_PEAR_Command_objects'][$class])) { - $GLOBALS['_PEAR_Command_objects'][$class] = &new $class($ui, $config); - } - $implements = $GLOBALS['_PEAR_Command_objects'][$class]->getCommands(); - foreach ($implements as $command => $desc) { - $GLOBALS['_PEAR_Command_commandlist'][$command] = $class; - $GLOBALS['_PEAR_Command_commanddesc'][$command] = $desc; - } - $shortcuts = $GLOBALS['_PEAR_Command_objects'][$class]->getShortcuts(); - foreach ($shortcuts as $shortcut => $command) { - $GLOBALS['_PEAR_Command_shortcuts'][$shortcut] = $command; - } - } - return true; - } - - /** - * Get the list of currently supported commands, and what - * classes implement them. - * - * @return array command => implementing class - * - * @access public - */ - function getCommands() - { - if (empty($GLOBALS['_PEAR_Command_commandlist'])) { - PEAR_Command::registerCommands(); - } - return $GLOBALS['_PEAR_Command_commandlist']; - } - - /** - * Get the list of command shortcuts. - * - * @return array shortcut => command - * - * @access public - */ - function getShortcuts() - { - if (empty($GLOBALS['_PEAR_Command_shortcuts'])) { - PEAR_Command::registerCommands(); - } - return $GLOBALS['_PEAR_Command_shortcuts']; - } - - /** - * Compiles arguments for getopt. - * - * @param string $command command to get optstring for - * @param string $short_args (reference) short getopt format - * @param array $long_args (reference) long getopt format - * - * @return void - * - * @access public - */ - function getGetoptArgs($command, &$short_args, &$long_args) - { - if (empty($GLOBALS['_PEAR_Command_commandlist'])) { - PEAR_Command::registerCommands(); - } - $class = @$GLOBALS['_PEAR_Command_commandlist'][$command]; - if (empty($class)) { - return null; - } - $obj = &$GLOBALS['_PEAR_Command_objects'][$class]; - return $obj->getGetoptArgs($command, $short_args, $long_args); - } - - /** - * Get description for a command. - * - * @param string $command Name of the command - * - * @return string command description - * - * @access public - */ - function getDescription($command) - { - return @$GLOBALS['_PEAR_Command_commanddesc'][$command]; - } - - /** - * Get help for command. - * - * @param string $command Name of the command to return help for - * - * @access public - */ - function getHelp($command) - { - $cmds = PEAR_Command::getCommands(); - if (isset($cmds[$command])) { - $class = $cmds[$command]; - return $GLOBALS['_PEAR_Command_objects'][$class]->getHelp($command); - } - return false; - } -} - -?> diff --git a/gulliver/thirdparty/pear/PEAR/Command/Auth.php b/gulliver/thirdparty/pear/PEAR/Command/Auth.php deleted file mode 100644 index ae25f9b3a..000000000 --- a/gulliver/thirdparty/pear/PEAR/Command/Auth.php +++ /dev/null @@ -1,155 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Auth.php,v 1.13 2003/03/18 12:06:07 ssb Exp $ - -require_once "PEAR/Command/Common.php"; -require_once "PEAR/Remote.php"; -require_once "PEAR/Config.php"; - -/** - * PEAR commands for managing configuration data. - * - */ -class PEAR_Command_Auth extends PEAR_Command_Common -{ - // {{{ properties - - var $commands = array( - 'login' => array( - 'summary' => 'Connects and authenticates to remote server', - 'shortcut' => 'li', - 'function' => 'doLogin', - 'options' => array(), - 'doc' => ' -Log in to the remote server. To use remote functions in the installer -that require any kind of privileges, you need to log in first. The -username and password you enter here will be stored in your per-user -PEAR configuration (~/.pearrc on Unix-like systems). After logging -in, your username and password will be sent along in subsequent -operations on the remote server.', - ), - 'logout' => array( - 'summary' => 'Logs out from the remote server', - 'shortcut' => 'lo', - 'function' => 'doLogout', - 'options' => array(), - 'doc' => ' -Logs out from the remote server. This command does not actually -connect to the remote server, it only deletes the stored username and -password from your user configuration.', - ) - - ); - - // }}} - - // {{{ constructor - - /** - * PEAR_Command_Auth constructor. - * - * @access public - */ - function PEAR_Command_Auth(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ doLogin() - - /** - * Execute the 'login' command. - * - * @param string $command command name - * - * @param array $options option_name => value - * - * @param array $params list of additional parameters - * - * @return bool TRUE on success, FALSE for unknown commands, or - * a PEAR error on failure - * - * @access public - */ - function doLogin($command, $options, $params) - { - $server = $this->config->get('master_server'); - $remote = new PEAR_Remote($this->config); - $username = $this->config->get('username'); - if (empty($username)) { - $username = @$_ENV['USER']; - } - $this->ui->outputData("Logging in to $server.", $command); - - list($username, $password) = $this->ui->userDialog( - $command, - array('Username', 'Password'), - array('text', 'password'), - array($username, '') - ); - $username = trim($username); - $password = trim($password); - - $this->config->set('username', $username); - $this->config->set('password', $password); - - $remote->expectError(401); - $ok = $remote->call('logintest'); - $remote->popExpect(); - if ($ok === true) { - $this->ui->outputData("Logged in.", $command); - $this->config->store(); - } else { - return $this->raiseError("Login failed!"); - } - - } - - // }}} - // {{{ doLogout() - - /** - * Execute the 'logout' command. - * - * @param string $command command name - * - * @param array $options option_name => value - * - * @param array $params list of additional parameters - * - * @return bool TRUE on success, FALSE for unknown commands, or - * a PEAR error on failure - * - * @access public - */ - function doLogout($command, $options, $params) - { - $server = $this->config->get('master_server'); - $this->ui->outputData("Logging out from $server.", $command); - $this->config->remove('username'); - $this->config->remove('password'); - $this->config->store(); - } - - // }}} -} - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/PEAR/Command/Build.php b/gulliver/thirdparty/pear/PEAR/Command/Build.php deleted file mode 100644 index 07dea6036..000000000 --- a/gulliver/thirdparty/pear/PEAR/Command/Build.php +++ /dev/null @@ -1,89 +0,0 @@ - | -// | Tomas V.V.Cox | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Build.php,v 1.6 2003/03/18 12:06:07 ssb Exp $ - -require_once "PEAR/Command/Common.php"; -require_once "PEAR/Builder.php"; - -/** - * PEAR commands for building extensions. - * - */ -class PEAR_Command_Build extends PEAR_Command_Common -{ - // {{{ properties - - var $commands = array( - 'build' => array( - 'summary' => 'Build an Extension From C Source', - 'function' => 'doBuild', - 'shortcut' => 'b', - 'options' => array(), - 'doc' => '[package.xml] -Builds one or more extensions contained in a package.' - ), - ); - - // }}} - - // {{{ constructor - - /** - * PEAR_Command_Build constructor. - * - * @access public - */ - function PEAR_Command_Build(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ doBuild() - - function doBuild($command, $options, $params) - { - if (sizeof($params) < 1) { - $params[0] = 'package.xml'; - } - $builder = &new PEAR_Builder($this->ui); - $this->verbose = $this->config->get('verbose'); - $err = $builder->build($params[0], array(&$this, 'buildCallback')); - if (PEAR::isError($err)) { - return $err; - } - return true; - } - - // }}} - // {{{ buildCallback() - - function buildCallback($what, $data) - { - if (($what == 'cmdoutput' && $this->verbose > 1) || - ($what == 'output' && $this->verbose > 0)) { - $this->ui->outputData(rtrim($data), 'build'); - } - } - - // }}} -} diff --git a/gulliver/thirdparty/pear/PEAR/Command/Common.php b/gulliver/thirdparty/pear/PEAR/Command/Common.php deleted file mode 100644 index 430ad0356..000000000 --- a/gulliver/thirdparty/pear/PEAR/Command/Common.php +++ /dev/null @@ -1,249 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Common.php,v 1.22 2003/03/18 12:06:07 ssb Exp $ - -require_once "PEAR.php"; - -class PEAR_Command_Common extends PEAR -{ - // {{{ properties - - /** - * PEAR_Config object used to pass user system and configuration - * on when executing commands - * - * @var object - */ - var $config; - - /** - * User Interface object, for all interaction with the user. - * @var object - */ - var $ui; - - var $_deps_rel_trans = array( - 'lt' => '<', - 'le' => '<=', - 'eq' => '=', - 'ne' => '!=', - 'gt' => '>', - 'ge' => '>=', - 'has' => '==' - ); - - var $_deps_type_trans = array( - 'pkg' => 'package', - 'extension' => 'extension', - 'php' => 'PHP', - 'prog' => 'external program', - 'ldlib' => 'external library for linking', - 'rtlib' => 'external runtime library', - 'os' => 'operating system', - 'websrv' => 'web server', - 'sapi' => 'SAPI backend' - ); - - // }}} - // {{{ constructor - - /** - * PEAR_Command_Common constructor. - * - * @access public - */ - function PEAR_Command_Common(&$ui, &$config) - { - parent::PEAR(); - $this->config = &$config; - $this->ui = &$ui; - } - - // }}} - - // {{{ getCommands() - - /** - * Return a list of all the commands defined by this class. - * @return array list of commands - * @access public - */ - function getCommands() - { - $ret = array(); - foreach (array_keys($this->commands) as $command) { - $ret[$command] = $this->commands[$command]['summary']; - } - return $ret; - } - - // }}} - // {{{ getShortcuts() - - /** - * Return a list of all the command shortcuts defined by this class. - * @return array shortcut => command - * @access public - */ - function getShortcuts() - { - $ret = array(); - foreach (array_keys($this->commands) as $command) { - if (isset($this->commands[$command]['shortcut'])) { - $ret[$this->commands[$command]['shortcut']] = $command; - } - } - return $ret; - } - - // }}} - // {{{ getOptions() - - function getOptions($command) - { - return @$this->commands[$command]['options']; - } - - // }}} - // {{{ getGetoptArgs() - - function getGetoptArgs($command, &$short_args, &$long_args) - { - $short_args = ""; - $long_args = array(); - if (empty($this->commands[$command])) { - return; - } - reset($this->commands[$command]); - while (list($option, $info) = each($this->commands[$command]['options'])) { - $larg = $sarg = ''; - if (isset($info['arg'])) { - if ($info['arg']{0} == '(') { - $larg = '=='; - $sarg = '::'; - $arg = substr($info['arg'], 1, -1); - } else { - $larg = '='; - $sarg = ':'; - $arg = $info['arg']; - } - } - if (isset($info['shortopt'])) { - $short_args .= $info['shortopt'] . $sarg; - } - $long_args[] = $option . $larg; - } - } - - // }}} - // {{{ getHelp() - /** - * Returns the help message for the given command - * - * @param string $command The command - * @return mixed A fail string if the command does not have help or - * a two elements array containing [0]=>help string, - * [1]=> help string for the accepted cmd args - */ - function getHelp($command) - { - $config = &PEAR_Config::singleton(); - $help = @$this->commands[$command]['doc']; - if (empty($help)) { - // XXX (cox) Fallback to summary if there is no doc (show both?) - if (!$help = @$this->commands[$command]['summary']) { - return "No help for command \"$command\""; - } - } - if (preg_match_all('/{config\s+([^\}]+)}/e', $help, $matches)) { - foreach($matches[0] as $k => $v) { - $help = preg_replace("/$v/", $config->get($matches[1][$k]), $help); - } - } - return array($help, $this->getHelpArgs($command)); - } - - // }}} - // {{{ getHelpArgs() - /** - * Returns the help for the accepted arguments of a command - * - * @param string $command - * @return string The help string - */ - function getHelpArgs($command) - { - if (isset($this->commands[$command]['options']) && - count($this->commands[$command]['options'])) - { - $help = "Options:\n"; - foreach ($this->commands[$command]['options'] as $k => $v) { - if (isset($v['arg'])) { - if ($v['arg']{0} == '(') { - $arg = substr($v['arg'], 1, -1); - $sapp = " [$arg]"; - $lapp = "[=$arg]"; - } else { - $sapp = " $v[arg]"; - $lapp = "=$v[arg]"; - } - } else { - $sapp = $lapp = ""; - } - if (isset($v['shortopt'])) { - $s = $v['shortopt']; - @$help .= " -$s$sapp, --$k$lapp\n"; - } else { - @$help .= " --$k$lapp\n"; - } - $p = " "; - $doc = rtrim(str_replace("\n", "\n$p", $v['doc'])); - $help .= " $doc\n"; - } - return $help; - } - return null; - } - - // }}} - // {{{ run() - - function run($command, $options, $params) - { - $func = @$this->commands[$command]['function']; - if (empty($func)) { - // look for shortcuts - foreach (array_keys($this->commands) as $cmd) { - if (@$this->commands[$cmd]['shortcut'] == $command) { - $command = $cmd; - $func = @$this->commands[$command]['function']; - if (empty($func)) { - return $this->raiseError("unknown command `$command'"); - } - break; - } - } - } - return $this->$func($command, $options, $params); - } - - // }}} -} - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/PEAR/Command/Config.php b/gulliver/thirdparty/pear/PEAR/Command/Config.php deleted file mode 100644 index fdbaed270..000000000 --- a/gulliver/thirdparty/pear/PEAR/Command/Config.php +++ /dev/null @@ -1,225 +0,0 @@ - | -// | Tomas V.V.Cox | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Config.php,v 1.24 2003/03/18 12:06:07 ssb Exp $ - -require_once "PEAR/Command/Common.php"; -require_once "PEAR/Config.php"; - -/** - * PEAR commands for managing configuration data. - * - */ -class PEAR_Command_Config extends PEAR_Command_Common -{ - // {{{ properties - - var $commands = array( - 'config-show' => array( - 'summary' => 'Show All Settings', - 'function' => 'doConfigShow', - 'shortcut' => 'csh', - 'options' => array(), - 'doc' => ' -Displays all configuration values. An optional argument -may be used to tell which configuration layer to display. Valid -configuration layers are "user", "system" and "default". -', - ), - 'config-get' => array( - 'summary' => 'Show One Setting', - 'function' => 'doConfigGet', - 'shortcut' => 'cg', - 'options' => array(), - 'doc' => ' [layer] -Displays the value of one configuration parameter. The -first argument is the name of the parameter, an optional second argument -may be used to tell which configuration layer to look in. Valid configuration -layers are "user", "system" and "default". If no layer is specified, a value -will be picked from the first layer that defines the parameter, in the order -just specified. -', - ), - 'config-set' => array( - 'summary' => 'Change Setting', - 'function' => 'doConfigSet', - 'shortcut' => 'cs', - 'options' => array(), - 'doc' => ' [layer] -Sets the value of one configuration parameter. The first argument is -the name of the parameter, the second argument is the new value. Some -parameters are subject to validation, and the command will fail with -an error message if the new value does not make sense. An optional -third argument may be used to specify in which layer to set the -configuration parameter. The default layer is "user". -', - ), - 'config-help' => array( - 'summary' => 'Show Information About Setting', - 'function' => 'doConfigHelp', - 'shortcut' => 'ch', - 'options' => array(), - 'doc' => '[parameter] -Displays help for a configuration parameter. Without arguments it -displays help for all configuration parameters. -', - ), - ); - - // }}} - // {{{ constructor - - /** - * PEAR_Command_Config constructor. - * - * @access public - */ - function PEAR_Command_Config(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ doConfigShow() - - function doConfigShow($command, $options, $params) - { - // $params[0] -> the layer - if ($error = $this->_checkLayer(@$params[0])) { - return $this->raiseError($error); - } - $keys = $this->config->getKeys(); - sort($keys); - $data = array('caption' => 'Configuration:'); - foreach ($keys as $key) { - $type = $this->config->getType($key); - $value = $this->config->get($key, @$params[0]); - if ($type == 'password' && $value) { - $value = '********'; - } - if ($value === false) { - $value = 'false'; - } elseif ($value === true) { - $value = 'true'; - } - $data['data'][$this->config->getGroup($key)][] = array($this->config->getPrompt($key) , $key, $value); - } - $this->ui->outputData($data, $command); - return true; - } - - // }}} - // {{{ doConfigGet() - - function doConfigGet($command, $options, $params) - { - // $params[0] -> the parameter - // $params[1] -> the layer - if ($error = $this->_checkLayer(@$params[1])) { - return $this->raiseError($error); - } - if (sizeof($params) < 1 || sizeof($params) > 2) { - return $this->raiseError("config-get expects 1 or 2 parameters"); - } elseif (sizeof($params) == 1) { - $this->ui->outputData("$params[0]=" . $this->config->get($params[0]), $command); - } else { - $data = "$params[1].$params[0]=" .$this->config->get($params[0], $params[1]); - $this->ui->outputData($data, $command); - } - return true; - } - - // }}} - // {{{ doConfigSet() - - function doConfigSet($command, $options, $params) - { - // $param[0] -> a parameter to set - // $param[1] -> the value for the parameter - // $param[2] -> the layer - $failmsg = ''; - if (sizeof($params) < 2 || sizeof($params) > 3) { - $failmsg .= "config-set expects 2 or 3 parameters"; - return PEAR::raiseError($failmsg); - } - if ($error = $this->_checkLayer(@$params[2])) { - $failmsg .= $error; - return PEAR::raiseError($failmsg); - } - if (!call_user_func_array(array(&$this->config, 'set'), $params)) - { - $failmsg = "config-set (" . implode(", ", $params) . ") failed"; - } else { - $this->config->store(); - } - if ($failmsg) { - return $this->raiseError($failmsg); - } - return true; - } - - // }}} - // {{{ doConfigHelp() - - function doConfigHelp($command, $options, $params) - { - if (empty($params)) { - $params = $this->config->getKeys(); - } - $data['caption'] = "Config help" . ((count($params) == 1) ? " for $params[0]" : ''); - $data['headline'] = array('Name', 'Type', 'Description'); - $data['border'] = true; - foreach ($params as $name) { - $type = $this->config->getType($name); - $docs = $this->config->getDocs($name); - if ($type == 'set') { - $docs = rtrim($docs) . "\nValid set: " . - implode(' ', $this->config->getSetValues($name)); - } - $data['data'][] = array($name, $type, $docs); - } - $this->ui->outputData($data, $command); - } - - // }}} - // {{{ _checkLayer() - - /** - * Checks if a layer is defined or not - * - * @param string $layer The layer to search for - * @return mixed False on no error or the error message - */ - function _checkLayer($layer = null) - { - if (!empty($layer) && $layer != 'default') { - $layers = $this->config->getLayers(); - if (!in_array($layer, $layers)) { - return " only the layers: \"" . implode('" or "', $layers) . "\" are supported"; - } - } - return false; - } - - // }}} -} - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/PEAR/Command/Install.php b/gulliver/thirdparty/pear/PEAR/Command/Install.php deleted file mode 100644 index e4581aaba..000000000 --- a/gulliver/thirdparty/pear/PEAR/Command/Install.php +++ /dev/null @@ -1,302 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Install.php,v 1.42 2003/03/18 12:06:07 ssb Exp $ - -require_once "PEAR/Command/Common.php"; -require_once "PEAR/Installer.php"; -require_once "Console/Getopt.php"; - -/** - * PEAR commands for installation or deinstallation/upgrading of - * packages. - * - */ -class PEAR_Command_Install extends PEAR_Command_Common -{ - // {{{ properties - - var $commands = array( - 'install' => array( - 'summary' => 'Install Package', - 'function' => 'doInstall', - 'shortcut' => 'i', - 'options' => array( - 'force' => array( - 'shortopt' => 'f', - 'doc' => 'will overwrite newer installed packages', - ), - 'nodeps' => array( - 'shortopt' => 'n', - 'doc' => 'ignore dependencies, install anyway', - ), - 'register-only' => array( - 'shortopt' => 'r', - 'doc' => 'do not install files, only register the package as installed', - ), - 'soft' => array( - 'shortopt' => 's', - 'doc' => 'soft install, fail silently, or upgrade if already installed', - ), - 'nobuild' => array( - 'shortopt' => 'B', - 'doc' => 'don\'t build C extensions', - ), - 'nocompress' => array( - 'shortopt' => 'Z', - 'doc' => 'request uncompressed files when downloading', - ), - 'installroot' => array( - 'shortopt' => 'R', - 'arg' => 'DIR', - 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT)', - ), - 'ignore-errors' => array( - 'doc' => 'force install even if there were errors', - ), - ), - 'doc' => ' ... -Installs one or more PEAR packages. You can specify a package to -install in four ways: - -"Package-1.0.tgz" : installs from a local file - -"http://example.com/Package-1.0.tgz" : installs from -anywhere on the net. - -"package.xml" : installs the package described in -package.xml. Useful for testing, or for wrapping a PEAR package in -another package manager such as RPM. - -"Package" : queries your configured server -({config master_server}) and downloads the newest package with -the preferred quality/state ({config preferred_state}). - -More than one package may be specified at once. It is ok to mix these -four ways of specifying packages. -'), - 'upgrade' => array( - 'summary' => 'Upgrade Package', - 'function' => 'doInstall', - 'shortcut' => 'up', - 'options' => array( - 'force' => array( - 'shortopt' => 'f', - 'doc' => 'overwrite newer installed packages', - ), - 'nodeps' => array( - 'shortopt' => 'n', - 'doc' => 'ignore dependencies, upgrade anyway', - ), - 'register-only' => array( - 'shortopt' => 'r', - 'doc' => 'do not install files, only register the package as upgraded', - ), - 'nobuild' => array( - 'shortopt' => 'B', - 'doc' => 'don\'t build C extensions', - ), - 'nocompress' => array( - 'shortopt' => 'Z', - 'doc' => 'request uncompressed files when downloading', - ), - 'installroot' => array( - 'shortopt' => 'R', - 'arg' => 'DIR', - 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT)', - ), - 'ignore-errors' => array( - 'doc' => 'force install even if there were errors', - ), - ), - 'doc' => ' ... -Upgrades one or more PEAR packages. See documentation for the -"install" command for ways to specify a package. - -When upgrading, your package will be updated if the provided new -package has a higher version number (use the -f option if you need to -upgrade anyway). - -More than one package may be specified at once. -'), - 'upgrade-all' => array( - 'summary' => 'Upgrade All Packages', - 'function' => 'doInstall', - 'shortcut' => 'ua', - 'options' => array( - 'nodeps' => array( - 'shortopt' => 'n', - 'doc' => 'ignore dependencies, upgrade anyway', - ), - 'register-only' => array( - 'shortopt' => 'r', - 'doc' => 'do not install files, only register the package as upgraded', - ), - 'nobuild' => array( - 'shortopt' => 'B', - 'doc' => 'don\'t build C extensions', - ), - 'nocompress' => array( - 'shortopt' => 'Z', - 'doc' => 'request uncompressed files when downloading', - ), - 'installroot' => array( - 'shortopt' => 'R', - 'arg' => 'DIR', - 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT)', - ), - 'ignore-errors' => array( - 'doc' => 'force install even if there were errors', - ), - ), - 'doc' => ' -Upgrades all packages that have a newer release available. Upgrades are -done only if there is a release available of the state specified in -"preferred_state" (currently {config preferred_state}), or a state considered -more stable. -'), - 'uninstall' => array( - 'summary' => 'Un-install Package', - 'function' => 'doUninstall', - 'shortcut' => 'un', - 'options' => array( - 'nodeps' => array( - 'shortopt' => 'n', - 'doc' => 'ignore dependencies, uninstall anyway', - ), - 'register-only' => array( - 'shortopt' => 'r', - 'doc' => 'do not remove files, only register the packages as not installed', - ), - 'installroot' => array( - 'shortopt' => 'R', - 'arg' => 'DIR', - 'doc' => 'root directory used when installing files (ala PHP\'s INSTALL_ROOT)', - ), - 'ignore-errors' => array( - 'doc' => 'force install even if there were errors', - ), - ), - 'doc' => ' ... -Uninstalls one or more PEAR packages. More than one package may be -specified at once. -'), - - ); - - // }}} - // {{{ constructor - - /** - * PEAR_Command_Install constructor. - * - * @access public - */ - function PEAR_Command_Install(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ doInstall() - - function doInstall($command, $options, $params) - { - if (empty($this->installer)) { - $this->installer = &new PEAR_Installer($this->ui); - } - if ($command == 'upgrade') { - $options[$command] = true; - } - if ($command == 'upgrade-all') { - include_once "PEAR/Remote.php"; - $options['upgrade'] = true; - $remote = new PEAR_Remote($this->config); - $state = $this->config->get('preferred_state'); - if (empty($state) || $state == 'any') { - $latest = $remote->call("package.listLatestReleases"); - } else { - $latest = $remote->call("package.listLatestReleases", $state); - } - if (PEAR::isError($latest)) { - return $latest; - } - $reg = new PEAR_Registry($this->config->get('php_dir')); - $installed = array_flip($reg->listPackages()); - $params = array(); - foreach ($latest as $package => $info) { - if (!isset($installed[$package])) { - // skip packages we don't have installed - continue; - } - $inst_version = $reg->packageInfo($package, 'version'); - if (version_compare("$info[version]", "$inst_version", "le")) { - // installed version is up-to-date - continue; - } - $params[] = $package; - $this->ui->outputData("will upgrade $package", $command); - } - } - foreach ($params as $pkg) { - $bn = basename($pkg); - $info = $this->installer->install($pkg, $options, $this->config); - if (is_array($info)) { - if ($this->config->get('verbose') > 0) { - $label = "$info[package] $info[version]"; - $out = array('data' => "$command ok: $label"); - if (isset($info['release_warnings'])) { - $out['release_warnings'] = $info['release_warnings']; - } - $this->ui->outputData($out, $command); - } - } else { - return $this->raiseError("$command failed"); - } - } - return true; - } - - // }}} - // {{{ doUninstall() - - function doUninstall($command, $options, $params) - { - if (empty($this->installer)) { - $this->installer = &new PEAR_Installer($this->ui); - } - if (sizeof($params) < 1) { - return $this->raiseError("Please supply the package(s) you want to uninstall"); - } - foreach ($params as $pkg) { - if ($this->installer->uninstall($pkg, $options)) { - if ($this->config->get('verbose') > 0) { - $this->ui->outputData("uninstall ok: $pkg", $command); - } - } else { - return $this->raiseError("uninstall failed: $pkg"); - } - } - return true; - } - - // }}} -} - -?> diff --git a/gulliver/thirdparty/pear/PEAR/Command/Mirror.php b/gulliver/thirdparty/pear/PEAR/Command/Mirror.php deleted file mode 100644 index 226ed0892..000000000 --- a/gulliver/thirdparty/pear/PEAR/Command/Mirror.php +++ /dev/null @@ -1,99 +0,0 @@ - | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Mirror.php,v 1.1 2003/05/05 07:07:51 alexmerz Exp $ - -require_once "PEAR/Command/Common.php"; -require_once "PEAR/Command.php"; -require_once "PEAR/Remote.php"; -require_once "PEAR.php"; - -/** - * PEAR commands for providing file mirrors - * - */ -class PEAR_Command_Mirror extends PEAR_Command_Common -{ - // {{{ properties - - var $commands = array( - 'download-all' => array( - 'summary' => 'Downloads each avaible Package from master_server', - 'function' => 'doDownloadAll', - 'shortcut' => 'da', - 'options' => array(), - 'doc' => ' - Request a list of avaible Packages from the Package-Server - (master_server) and downloads them to current working dir' - ), - ); - - // }}} - - // {{{ constructor - - /** - * PEAR_Command_Mirror constructor. - * - * @access public - * @param object PEAR_Frontend a reference to an frontend - * @param object PEAR_Config a reference to the configuration data - */ - function PEAR_Command_Mirror(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ doDownloadAll() - /** - * retrieves a list of avaible Packages from master server - * and downloads them - * - * @access public - * @param string $command the command - * @param array $options the command options before the command - * @param array $params the stuff after the command name - * @return bool true if succesful - * @throw PEAR_Error - */ - function doDownloadAll($command, $options, $params) - { - $this->config->set("php_dir", "."); - $remote = &new PEAR_Remote($this->config); - $remoteInfo = $remote->call("package.listAll"); - if(PEAR::isError($remoteInfo)) { - return $remoteInfo; - } - $cmd = &PEAR_Command::factory("download", $this->config); - if(PEAR::isError($cmd)) { - return $cmd; - } - foreach($remoteInfo as $pkgn=>$pkg) { - // error handling not neccesary, because - // already done by the download command - $cmd->run("download", array(), array($pkgn)); - } - - return true; - } - - // }}} -} diff --git a/gulliver/thirdparty/pear/PEAR/Command/Package.php b/gulliver/thirdparty/pear/PEAR/Command/Package.php deleted file mode 100644 index d4bc4ef6a..000000000 --- a/gulliver/thirdparty/pear/PEAR/Command/Package.php +++ /dev/null @@ -1,658 +0,0 @@ - | -// | Martin Jansen | -// +----------------------------------------------------------------------+ -// -// $Id: Package.php,v 1.50 2003/03/18 12:06:07 ssb Exp $ - -require_once 'PEAR/Common.php'; -require_once 'PEAR/Command/Common.php'; - -class PEAR_Command_Package extends PEAR_Command_Common -{ - // {{{ properties - - var $commands = array( - 'package' => array( - 'summary' => 'Build Package', - 'function' => 'doPackage', - 'shortcut' => 'p', - 'options' => array( - 'nocompress' => array( - 'shortopt' => 'Z', - 'doc' => 'Do not gzip the package file' - ), - 'showname' => array( - 'shortopt' => 'n', - 'doc' => 'Print the name of the packaged file.', - ), - ), - 'doc' => '[descfile] -Creates a PEAR package from its description file (usually called -package.xml). -' - ), - 'package-validate' => array( - 'summary' => 'Validate Package Consistency', - 'function' => 'doPackageValidate', - 'shortcut' => 'pv', - 'options' => array(), - 'doc' => ' -', - ), - 'cvsdiff' => array( - 'summary' => 'Run a "cvs diff" for all files in a package', - 'function' => 'doCvsDiff', - 'shortcut' => 'cd', - 'options' => array( - 'quiet' => array( - 'shortopt' => 'q', - 'doc' => 'Be quiet', - ), - 'reallyquiet' => array( - 'shortopt' => 'Q', - 'doc' => 'Be really quiet', - ), - 'date' => array( - 'shortopt' => 'D', - 'doc' => 'Diff against revision of DATE', - 'arg' => 'DATE', - ), - 'release' => array( - 'shortopt' => 'R', - 'doc' => 'Diff against tag for package release REL', - 'arg' => 'REL', - ), - 'revision' => array( - 'shortopt' => 'r', - 'doc' => 'Diff against revision REV', - 'arg' => 'REV', - ), - 'context' => array( - 'shortopt' => 'c', - 'doc' => 'Generate context diff', - ), - 'unified' => array( - 'shortopt' => 'u', - 'doc' => 'Generate unified diff', - ), - 'ignore-case' => array( - 'shortopt' => 'i', - 'doc' => 'Ignore case, consider upper- and lower-case letters equivalent', - ), - 'ignore-whitespace' => array( - 'shortopt' => 'b', - 'doc' => 'Ignore changes in amount of white space', - ), - 'ignore-blank-lines' => array( - 'shortopt' => 'B', - 'doc' => 'Ignore changes that insert or delete blank lines', - ), - 'brief' => array( - 'doc' => 'Report only whether the files differ, no details', - ), - 'dry-run' => array( - 'shortopt' => 'n', - 'doc' => 'Don\'t do anything, just pretend', - ), - ), - 'doc' => ' -Compares all the files in a package. Without any options, this -command will compare the current code with the last checked-in code. -Using the -r or -R option you may compare the current code with that -of a specific release. -', - ), - 'cvstag' => array( - 'summary' => 'Set CVS Release Tag', - 'function' => 'doCvsTag', - 'shortcut' => 'ct', - 'options' => array( - 'quiet' => array( - 'shortopt' => 'q', - 'doc' => 'Be quiet', - ), - 'reallyquiet' => array( - 'shortopt' => 'Q', - 'doc' => 'Be really quiet', - ), - 'slide' => array( - 'shortopt' => 'F', - 'doc' => 'Move (slide) tag if it exists', - ), - 'delete' => array( - 'shortopt' => 'd', - 'doc' => 'Remove tag', - ), - 'dry-run' => array( - 'shortopt' => 'n', - 'doc' => 'Don\'t do anything, just pretend', - ), - ), - 'doc' => ' -Sets a CVS tag on all files in a package. Use this command after you have -packaged a distribution tarball with the "package" command to tag what -revisions of what files were in that release. If need to fix something -after running cvstag once, but before the tarball is released to the public, -use the "slide" option to move the release tag. -', - ), - 'package-dependencies' => array( - 'summary' => 'Show package dependencies', - 'function' => 'doPackageDependencies', - 'shortcut' => 'pd', - 'options' => array(), - 'doc' => ' -List all depencies the package has.' - ), - 'sign' => array( - 'summary' => 'Sign a package distribution file', - 'function' => 'doSign', - 'shortcut' => 'si', - 'options' => array(), - 'doc' => ' -Signs a package distribution (.tar or .tgz) file with GnuPG.', - ), - 'makerpm' => array( - 'summary' => 'Builds an RPM spec file from a PEAR package', - 'function' => 'doMakeRPM', - 'shortcut' => 'rpm', - 'options' => array( - 'spec-template' => array( - 'shortopt' => 't', - 'arg' => 'FILE', - 'doc' => 'Use FILE as RPM spec file template' - ), - 'rpm-pkgname' => array( - 'shortopt' => 'p', - 'arg' => 'FORMAT', - 'doc' => 'Use FORMAT as format string for RPM package name, %s is replaced -by the PEAR package name, defaults to "PEAR::%s".', - ), - ), - 'doc' => ' - -Creates an RPM .spec file for wrapping a PEAR package inside an RPM -package. Intended to be used from the SPECS directory, with the PEAR -package tarball in the SOURCES directory: - -$ pear makerpm ../SOURCES/Net_Socket-1.0.tgz -Wrote RPM spec file PEAR::Net_Geo-1.0.spec -$ rpm -bb PEAR::Net_Socket-1.0.spec -... -Wrote: /usr/src/redhat/RPMS/i386/PEAR::Net_Socket-1.0-1.i386.rpm -', - ), - ); - - var $output; - - // }}} - // {{{ constructor - - /** - * PEAR_Command_Package constructor. - * - * @access public - */ - function PEAR_Command_Package(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ _displayValidationResults() - - function _displayValidationResults($err, $warn, $strict = false) - { - foreach ($err as $e) { - $this->output .= "Error: $e\n"; - } - foreach ($warn as $w) { - $this->output .= "Warning: $w\n"; - } - $this->output .= sprintf('Validation: %d error(s), %d warning(s)'."\n", - sizeof($err), sizeof($warn)); - if ($strict && sizeof($err) > 0) { - $this->output .= "Fix these errors and try again."; - return false; - } - return true; - } - - // }}} - // {{{ doPackage() - - function doPackage($command, $options, $params) - { - $this->output = ''; - include_once 'PEAR/Packager.php'; - $pkginfofile = isset($params[0]) ? $params[0] : 'package.xml'; - $packager =& new PEAR_Packager($this->config->get('php_dir'), - $this->config->get('ext_dir'), - $this->config->get('doc_dir')); - $packager->debug = $this->config->get('verbose'); - $err = $warn = array(); - $dir = dirname($pkginfofile); - $compress = empty($options['nocompress']) ? true : false; - $result = $packager->package($pkginfofile, $compress); - if (PEAR::isError($result)) { - $this->ui->outputData($this->output, $command); - return $this->raiseError($result); - } - // Don't want output, only the package file name just created - if (isset($options['showname'])) { - $this->output = $result; - } - /* (cox) What is supposed to do that code? - $lines = explode("\n", $this->output); - foreach ($lines as $line) { - $this->output .= $line."n"; - } - */ - if (PEAR::isError($result)) { - $this->output .= "Package failed: ".$result->getMessage(); - } - $this->ui->outputData($this->output, $command); - return true; - } - - // }}} - // {{{ doPackageValidate() - - function doPackageValidate($command, $options, $params) - { - $this->output = ''; - if (sizeof($params) < 1) { - $params[0] = "package.xml"; - } - $obj = new PEAR_Common; - $info = null; - if ($fp = @fopen($params[0], "r")) { - $test = fread($fp, 5); - fclose($fp); - if ($test == "infoFromDescriptionFile($params[0]); - } - } - if (empty($info)) { - $info = $obj->infoFromTgzFile($params[0]); - } - if (PEAR::isError($info)) { - return $this->raiseError($info); - } - $obj->validatePackageInfo($info, $err, $warn); - $this->_displayValidationResults($err, $warn); - $this->ui->outputData($this->output, $command); - return true; - } - - // }}} - // {{{ doCvsTag() - - function doCvsTag($command, $options, $params) - { - $this->output = ''; - $_cmd = $command; - if (sizeof($params) < 1) { - $help = $this->getHelp($command); - return $this->raiseError("$command: missing parameter: $help[0]"); - } - $obj = new PEAR_Common; - $info = $obj->infoFromDescriptionFile($params[0]); - if (PEAR::isError($info)) { - return $this->raiseError($info); - } - $err = $warn = array(); - $obj->validatePackageInfo($info, $err, $warn); - if (!$this->_displayValidationResults($err, $warn, true)) { - $this->ui->outputData($this->output, $command); - break; - } - $version = $info['version']; - $cvsversion = preg_replace('/[^a-z0-9]/i', '_', $version); - $cvstag = "RELEASE_$cvsversion"; - $files = array_keys($info['filelist']); - $command = "cvs"; - if (isset($options['quiet'])) { - $command .= ' -q'; - } - if (isset($options['reallyquiet'])) { - $command .= ' -Q'; - } - $command .= ' tag'; - if (isset($options['slide'])) { - $command .= ' -F'; - } - if (isset($options['delete'])) { - $command .= ' -d'; - } - $command .= ' ' . $cvstag . ' ' . escapeshellarg($params[0]); - foreach ($files as $file) { - $command .= ' ' . escapeshellarg($file); - } - if ($this->config->get('verbose') > 1) { - $this->output .= "+ $command\n"; - } - $this->output .= "+ $command\n"; - - 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(); - $command = $filter->validateInput($command); - - if (empty($options['dry-run'])) { - $fp = popen($command, 'r'); - while ($line = fgets($fp, 1024)) { - $this->output .= rtrim($line)."\n"; - } - pclose($fp); - } - $this->ui->outputData($this->output, $_cmd); - return true; - } - - // }}} - // {{{ doCvsDiff() - - function doCvsDiff($command, $options, $params) - { - $this->output = ''; - if (sizeof($params) < 1) { - $help = $this->getHelp($command); - return $this->raiseError("$command: missing parameter: $help[0]"); - } - $obj = new PEAR_Common; - $info = $obj->infoFromDescriptionFile($params[0]); - if (PEAR::isError($info)) { - return $this->raiseError($info); - } - $files = array_keys($info['filelist']); - $cmd = "cvs"; - if (isset($options['quiet'])) { - $cmd .= ' -q'; - unset($options['quiet']); - } - if (isset($options['reallyquiet'])) { - $cmd .= ' -Q'; - unset($options['reallyquiet']); - } - if (isset($options['release'])) { - $cvsversion = preg_replace('/[^a-z0-9]/i', '_', $options['release']); - $cvstag = "RELEASE_$cvsversion"; - $options['revision'] = $cvstag; - unset($options['release']); - } - $execute = true; - if (isset($options['dry-run'])) { - $execute = false; - unset($options['dry-run']); - } - $cmd .= ' diff'; - // the rest of the options are passed right on to "cvs diff" - foreach ($options as $option => $optarg) { - $arg = @$this->commands[$command]['options'][$option]['arg']; - $short = @$this->commands[$command]['options'][$option]['shortopt']; - $cmd .= $short ? " -$short" : " --$option"; - if ($arg && $optarg) { - $cmd .= ($short ? '' : '=') . escapeshellarg($optarg); - } - } - foreach ($files as $file) { - $cmd .= ' ' . escapeshellarg($file); - } - if ($this->config->get('verbose') > 1) { - $this->output .= "+ $cmd\n"; - } - if ($execute) { - $fp = popen($cmd, 'r'); - while ($line = fgets($fp, 1024)) { - $this->output .= rtrim($line)."\n"; - } - pclose($fp); - } - $this->ui->outputData($this->output, $command); - return true; - } - - // }}} - // {{{ doPackageDependencies() - - function doPackageDependencies($command, $options, $params) - { - 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(); - $command = $filter->validateInput($command); - - // $params[0] -> the PEAR package to list its information - if (sizeof($params) != 1) { - return $this->raiseError("bad parameter(s), try \"help $command\""); - } - - $obj = new PEAR_Common(); - if (PEAR::isError($info = $obj->infoFromAny($params[0]))) { - return $this->raiseError($info); - } - - if (is_array($info['release_deps'])) { - $data = array( - 'caption' => 'Dependencies for ' . $info['package'], - 'border' => true, - 'headline' => array("Type", "Name", "Relation", "Version"), - ); - - foreach ($info['release_deps'] as $d) { - - if (isset($this->_deps_rel_trans[$d['rel']])) { - $rel = $this->_deps_rel_trans[$d['rel']]; - } else { - $rel = $d['rel']; - } - - if (isset($this->_deps_type_trans[$d['type']])) { - $type = ucfirst($this->_deps_type_trans[$d['type']]); - } else { - $type = $d['type']; - } - - if (isset($d['name'])) { - $name = $d['name']; - } else { - $name = ''; - } - - if (isset($d['version'])) { - $version = $d['version']; - } else { - $version = ''; - } - - $data['data'][] = array($type, $name, $rel, $version); - } - - $this->ui->outputData($data, $command); - return true; - } - - // Fallback - $this->ui->outputData("This package does not have any dependencies.", $command); - } - - // }}} - // {{{ doSign() - - function doSign($command, $options, $params) - { - // should move most of this code into PEAR_Packager - // so it'll be easy to implement "pear package --sign" - if (sizeof($params) != 1) { - return $this->raiseError("bad parameter(s), try \"help $command\""); - } - if (!file_exists($params[0])) { - return $this->raiseError("file does not exist: $params[0]"); - } - $obj = new PEAR_Common; - $info = $obj->infoFromTgzFile($params[0]); - if (PEAR::isError($info)) { - return $this->raiseError($info); - } - include_once "Archive/Tar.php"; - include_once "System.php"; - $tar = new Archive_Tar($params[0]); - $tmpdir = System::mktemp('-d pearsign'); - if (!$tar->extractList('package.xml package.sig', $tmpdir)) { - return $this->raiseError("failed to extract tar file"); - } - if (file_exists("$tmpdir/package.sig")) { - return $this->raiseError("package already signed"); - } - @unlink("$tmpdir/package.sig"); - $input = $this->ui->userDialog($command, - array('GnuPG Passphrase'), - array('password')); - $gpg = popen("gpg --batch --passphrase-fd 0 --armor --detach-sign --output $tmpdir/package.sig $tmpdir/package.xml 2>/dev/null", 'w'); - if (!$gpg) { - return $this->raiseError("gpg command failed"); - } - fwrite($gpg, "$input[0]\r"); - if (pclose($gpg) || !file_exists("$tmpdir/package.sig")) { - return $this->raiseError("gpg sign failed"); - } - $tar->addModify("$tmpdir/package.sig", '', $tmpdir); - return true; - } - - // }}} - // {{{ doMakeRPM() - - function doMakeRPM($command, $options, $params) - { - if (sizeof($params) != 1) { - return $this->raiseError("bad parameter(s), try \"help $command\""); - } - if (!file_exists($params[0])) { - return $this->raiseError("file does not exist: $params[0]"); - } - include_once "Archive/Tar.php"; - include_once "PEAR/Installer.php"; - include_once "System.php"; - $tar = new Archive_Tar($params[0]); - $tmpdir = System::mktemp('-d pear2rpm'); - $instroot = System::mktemp('-d pear2rpm'); - $tmp = $this->config->get('verbose'); - $this->config->set('verbose', 0); - $installer = new PEAR_Installer($this->ui); - $info = $installer->install($params[0], - array('installroot' => $instroot, - 'nodeps' => true)); - $pkgdir = "$info[package]-$info[version]"; -// print "instroot=$instroot\n"; -// print_r($info); -// return true; - - $info['rpm_xml_dir'] = '/var/lib/pear'; - $this->config->set('verbose', $tmp); - if (!$tar->extractList("$pkgdir/package.xml", $tmpdir, $pkgdir)) { - return $this->raiseError("failed to extract $params[0]"); - } - if (!file_exists("$tmpdir/package.xml")) { - return $this->raiseError("no package.xml found in $params[0]"); - } -// System::mkdir("-p $instroot$info[rpm_xml_dir]"); -// if (!@copy("$tmpdir/package.xml", "$instroot$info[rpm_xml_dir]/$info[package].xml")) { -// return $this->raiseError("could not copy package.xml file: $php_errormsg"); -// } - if (isset($options['spec-template'])) { - $spec_template = $options['spec-template']; - } else { - $spec_template = $this->config->get('data_dir') . - '/PEAR/template.spec'; - } - if (isset($options['rpm-pkgname'])) { - $rpm_pkgname_format = $options['rpm-pkgname']; - } else { - $rpm_pkgname_format = "PEAR::%s"; - } - - $info['extra_headers'] = ''; - $info['doc_files'] = ''; - $info['files'] = ''; - $info['rpm_package'] = sprintf($rpm_pkgname_format, $info['package']); - $srcfiles = 0; - foreach ($info['filelist'] as $name => $attr) { - if ($attr['role'] == 'doc') { - $info['doc_files'] .= " $name"; - } elseif ($attr['role'] == 'src') { - $srcfiles++; - } - $info['files'] .= "$attr[installed_as]\n"; - } - if ($srcfiles > 0) { - include_once "OS/Guess.php"; - $os = new OS_Guess; - $arch = $os->getCpu(); - } else { - $arch = 'noarch'; - } - $cfk = array('master_server', 'php_dir', 'ext_dir', 'doc_dir', - 'bin_dir', 'data_dir', 'test_dir'); - foreach ($cfg as $k) { - $info[$k] = $this->config->get($k); - } - $info['arch'] = $arch; - $fp = @fopen($spec_template, "r"); - if (!$fp) { - return $this->raiseError("could not open RPM spec file template $spec_template: $php_errormsg"); - } - $spec_contents = preg_replace('/@([a-z0-9_-]+)@/e', '$info["\1"]', fread($fp, filesize($spec_template))); - fclose($fp); - $spec_file = "$info[rpm_package]-$info[version].spec"; - $wp = fopen($spec_file, "w"); - if (!$wp) { - return $this->raiseError("could not write RPM spec file $spec_file: $php_errormsg"); - } - fwrite($wp, $spec_contents); - fclose($wp); - $this->ui->outputData("Wrote RPM spec file $spec_file", $command); - - return true; - } - - // }}} -} - -?> diff --git a/gulliver/thirdparty/pear/PEAR/Command/Registry.php b/gulliver/thirdparty/pear/PEAR/Command/Registry.php deleted file mode 100644 index a4b9e76a6..000000000 --- a/gulliver/thirdparty/pear/PEAR/Command/Registry.php +++ /dev/null @@ -1,319 +0,0 @@ - | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Registry.php,v 1.30 2003/03/18 12:06:07 ssb Exp $ - -require_once 'PEAR/Command/Common.php'; -require_once 'PEAR/Registry.php'; -require_once 'PEAR/Config.php'; - -class PEAR_Command_Registry extends PEAR_Command_Common -{ - // {{{ properties - - var $commands = array( - 'list' => array( - 'summary' => 'List Installed Packages', - 'function' => 'doList', - 'shortcut' => 'l', - 'options' => array(), - 'doc' => '[package] -If invoked without parameters, this command lists the PEAR packages -installed in your php_dir ({config php_dir)). With a parameter, it -lists the files in that package. -', - ), - 'shell-test' => array( - 'summary' => 'Shell Script Test', - 'function' => 'doShellTest', - 'shortcut' => 'st', - 'options' => array(), - 'doc' => ' [[relation] version] -Tests if a package is installed in the system. Will exit(1) if it is not. - The version comparison operator. One of: - <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne - The version to compare with -'), - 'info' => array( - 'summary' => 'Display information about a package', - 'function' => 'doInfo', - 'shortcut' => 'in', - 'options' => array(), - 'doc' => ' -Displays information about a package. The package argument may be a -local package file, an URL to a package file, or the name of an -installed package.' - ) - ); - - // }}} - // {{{ constructor - - /** - * PEAR_Command_Registry constructor. - * - * @access public - */ - function PEAR_Command_Registry(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ doList() - - function _sortinfo($a, $b) - { - return strcmp($a['package'], $b['package']); - } - - function doList($command, $options, $params) - { - $reg = new PEAR_Registry($this->config->get('php_dir')); - if (sizeof($params) == 0) { - $installed = $reg->packageInfo(); - usort($installed, array(&$this, '_sortinfo')); - $i = $j = 0; - $data = array( - 'caption' => 'Installed packages:', - 'border' => true, - 'headline' => array('Package', 'Version', 'State') - ); - foreach ($installed as $package) { - $data['data'][] = array($package['package'], - $package['version'], - @$package['release_state']); - } - if (count($installed)==0) { - $data = '(no packages installed)'; - } - $this->ui->outputData($data, $command); - } else { - if (file_exists($params[0]) && !is_dir($params[0])) { - include_once "PEAR/Common.php"; - $obj = &new PEAR_Common; - $info = $obj->infoFromAny($params[0]); - $headings = array('Package File', 'Install Path'); - $installed = false; - } else { - $info = $reg->packageInfo($params[0]); - $headings = array('Type', 'Install Path'); - $installed = true; - } - if (PEAR::isError($info)) { - return $this->raiseError($info); - } - if ($info === null) { - return $this->raiseError("`$params[0]' not installed"); - } - $list = $info['filelist']; - if ($installed) { - $caption = 'Installed Files For ' . $params[0]; - } else { - $caption = 'Contents of ' . basename($params[0]); - } - $data = array( - 'caption' => $caption, - 'border' => true, - 'headline' => $headings); - foreach ($list as $file => $att) { - if ($installed) { - if (empty($att['installed_as'])) { - continue; - } - $data['data'][] = array($att['role'], $att['installed_as']); - } else { - if (isset($att['baseinstalldir'])) { - $dest = $att['baseinstalldir'] . DIRECTORY_SEPARATOR . - $file; - } else { - $dest = $file; - } - switch ($att['role']) { - case 'test': - case 'data': - if ($installed) { - break 2; - } - $dest = '-- will not be installed --'; - break; - case 'doc': - $dest = $this->config->get('doc_dir') . DIRECTORY_SEPARATOR . - $dest; - break; - case 'php': - default: - $dest = $this->config->get('php_dir') . DIRECTORY_SEPARATOR . - $dest; - } - $dest = preg_replace('!/+!', '/', $dest); - $file = preg_replace('!/+!', '/', $file); - $data['data'][] = array($file, $dest); - } - } - $this->ui->outputData($data, $command); - - - } - return true; - } - - // }}} - // {{{ doShellTest() - - function doShellTest($command, $options, $params) - { - $this->pushErrorHandling(PEAR_ERROR_RETURN); - $reg = &new PEAR_Registry($this->config->get('php_dir')); - // "pear shell-test Foo" - if (sizeof($params) == 1) { - if (!$reg->packageExists($params[0])) { - exit(1); - } - // "pear shell-test Foo 1.0" - } elseif (sizeof($params) == 2) { - $v = $reg->packageInfo($params[0], 'version'); - if (!$v || !version_compare("$v", "{$params[1]}", "ge")) { - exit(1); - } - // "pear shell-test Foo ge 1.0" - } elseif (sizeof($params) == 3) { - $v = $reg->packageInfo($params[0], 'version'); - if (!$v || !version_compare("$v", "{$params[2]}", $params[1])) { - exit(1); - } - } else { - $this->popErrorHandling(); - $this->raiseError("$command: expects 1 to 3 parameters"); - exit(1); - } - } - - // }}} - // {{{ doInfo - - function doInfo($command, $options, $params) - { - // $params[0] The package for showing info - if (sizeof($params) != 1) { - return $this->raiseError("This command only accepts one param: ". - "the package you want information"); - } - if (@is_file($params[0])) { - $obj = &new PEAR_Common(); - $info = $obj->infoFromAny($params[0]); - } else { - $reg = &new PEAR_Registry($this->config->get('php_dir')); - $info = $reg->packageInfo($params[0]); - } - if (PEAR::isError($info)) { - return $info; - } - if (empty($info)) { - $this->ui->displayError("Nothing found for `$params[0]'"); - return; - } - unset($info['filelist']); - unset($info['changelog']); - $keys = array_keys($info); - $longtext = array('description', 'summary'); - foreach ($keys as $key) { - if (is_array($info[$key])) { - switch ($key) { - case 'maintainers': { - $i = 0; - $mstr = ''; - foreach ($info[$key] as $m) { - if ($i++ > 0) { - $mstr .= "\n"; - } - $mstr .= $m['name'] . " <"; - if (isset($m['email'])) { - $mstr .= $m['email']; - } else { - $mstr .= $m['handle'] . '@php.net'; - } - $mstr .= "> ($m[role])"; - } - $info[$key] = $mstr; - break; - } - case 'release_deps': { - $i = 0; - $dstr = ''; - foreach ($info[$key] as $d) { - if (isset($this->_deps_rel_trans[$d['rel']])) { - $rel = $this->_deps_rel_trans[$d['rel']]; - } else { - $rel = $d['rel']; - } - if (isset($this->_deps_type_trans[$d['type']])) { - $type = ucfirst($this->_deps_type_trans[$d['type']]); - } else { - $type = $d['type']; - } - if (isset($d['name'])) { - $name = $d['name'] . ' '; - } else { - $name = ''; - } - if (isset($d['version'])) { - $version = $d['version'] . ' '; - } else { - $version = ''; - } - $dstr .= "$type $name$rel $version\n"; - } - $info[$key] = $dstr; - break; - } - default: { - $info[$key] = implode(", ", $info[$key]); - break; - } - } - } - if ($key == '_lastmodified') { - $hdate = date('Y-m-d', $info[$key]); - unset($info[$key]); - $info['Last Modified'] = $hdate; - } else { - $info[$key] = trim($info[$key]); - if (in_array($key, $longtext)) { - $info[$key] = preg_replace('/ +/', ' ', $info[$key]); - } - } - } - $caption = 'About ' . $info['package'] . '-' . $info['version']; - $data = array( - 'caption' => $caption, - 'border' => true); - foreach ($info as $key => $value) { - $key = ucwords(trim(str_replace('_', ' ', $key))); - $data['data'][] = array($key, $value); - } - - $this->ui->outputData($data, 'package-info'); - } - - // }}} -} - -?> diff --git a/gulliver/thirdparty/pear/PEAR/Command/Remote.php b/gulliver/thirdparty/pear/PEAR/Command/Remote.php deleted file mode 100644 index 366d9daba..000000000 --- a/gulliver/thirdparty/pear/PEAR/Command/Remote.php +++ /dev/null @@ -1,407 +0,0 @@ - | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Remote.php,v 1.29 2003/03/18 12:06:07 ssb Exp $ - -require_once 'PEAR/Command/Common.php'; -require_once 'PEAR/Common.php'; -require_once 'PEAR/Remote.php'; -require_once 'PEAR/Registry.php'; - -class PEAR_Command_Remote extends PEAR_Command_Common -{ - // {{{ command definitions - - var $commands = array( - 'remote-info' => array( - 'summary' => 'Information About Remote Packages', - 'function' => 'doRemoteInfo', - 'shortcut' => 'ri', - 'options' => array(), - 'doc' => ' -Get details on a package from the server.', - ), - 'list-upgrades' => array( - 'summary' => 'List Available Upgrades', - 'function' => 'doListUpgrades', - 'shortcut' => 'lu', - 'options' => array(), - 'doc' => ' -List releases on the server of packages you have installed where -a newer version is available with the same release state (stable etc.).' - ), - 'remote-list' => array( - 'summary' => 'List Remote Packages', - 'function' => 'doRemoteList', - 'shortcut' => 'rl', - 'options' => array(), - 'doc' => ' -Lists the packages available on the configured server along with the -latest stable release of each package.', - ), - 'search' => array( - 'summary' => 'Search remote package database', - 'function' => 'doSearch', - 'shortcut' => 'sp', - 'options' => array(), - 'doc' => ' -Lists all packages which match the search parameters (first param -is package name, second package info)', - ), - 'list-all' => array( - 'summary' => 'List All Packages', - 'function' => 'doListAll', - 'shortcut' => 'la', - 'options' => array(), - 'doc' => ' -Lists the packages available on the configured server along with the -latest stable release of each package.', - ), - 'download' => array( - 'summary' => 'Download Package', - 'function' => 'doDownload', - 'shortcut' => 'd', - 'options' => array( - 'nocompress' => array( - 'shortopt' => 'Z', - 'doc' => 'download an uncompressed (.tar) file', - ), - ), - 'doc' => '{package|package-version} -Download a package tarball. The file will be named as suggested by the -server, for example if you download the DB package and the latest stable -version of DB is 1.2, the downloaded file will be DB-1.2.tgz.', - ), - 'clear-cache' => array( - 'summary' => 'Clear XML-RPC Cache', - 'function' => 'doClearCache', - 'shortcut' => 'cc', - 'options' => array(), - 'doc' => ' -Clear the XML-RPC cache. See also the cache_ttl configuration -parameter. -', - ), - ); - - // }}} - // {{{ constructor - - /** - * PEAR_Command_Remote constructor. - * - * @access public - */ - function PEAR_Command_Remote(&$ui, &$config) - { - parent::PEAR_Command_Common($ui, $config); - } - - // }}} - - // {{{ doRemoteInfo() - - function doRemoteInfo($command, $options, $params) - { - if (sizeof($params) != 1) { - return $this->raiseError("$command expects one param: the remote package name"); - } - $r = new PEAR_Remote($this->config); - $info = $r->call('package.info', $params[0]); - if (PEAR::isError($info)) { - return $this->raiseError($info); - } - - $reg = new PEAR_Registry($this->config->get('php_dir')); - $installed = $reg->packageInfo($info['name']); - $info['installed'] = $installed['version'] ? $installed['version'] : '- no -'; - - $this->ui->outputData($info, $command); - - return true; - } - - // }}} - // {{{ doRemoteList() - - function doRemoteList($command, $options, $params) - { - $r = new PEAR_Remote($this->config); - $list_options = false; - if ($this->config->get('preferred_state') == 'stable') - $list_options = true; - $available = $r->call('package.listAll', $list_options); - if (PEAR::isError($available)) { - return $this->raiseError($available); - } - $i = $j = 0; - $data = array( - 'caption' => 'Available packages:', - 'border' => true, - 'headline' => array('Package', 'Version'), - ); - foreach ($available as $name => $info) { - $data['data'][] = array($name, isset($info['stable']) ? $info['stable'] : '-n/a-'); - } - if (count($available)==0) { - $data = '(no packages installed yet)'; - } - $this->ui->outputData($data, $command); - return true; - } - - // }}} - // {{{ doListAll() - - function doListAll($command, $options, $params) - { - $r = new PEAR_Remote($this->config); - $reg = new PEAR_Registry($this->config->get('php_dir')); - $list_options = false; - if ($this->config->get('preferred_state') == 'stable') - $list_options = true; - $available = $r->call('package.listAll', $list_options); - if (PEAR::isError($available)) { - return $this->raiseError($available); - } - if (!is_array($available)) { - return $this->raiseError('The package list could not be fetched from the remote server. Please try again. (Debug info: "'.$available.'")'); - } - $data = array( - 'caption' => 'All packages:', - 'border' => true, - 'headline' => array('Package', 'Latest', 'Local'), - ); - - foreach ($available as $name => $info) { - $installed = $reg->packageInfo($name); - $desc = $info['summary']; - if (isset($params[$name])) - $desc .= "\n\n".$info['description']; - - if (isset($options['mode'])) - { - if ($options['mode'] == 'installed' && !isset($installed['version'])) - continue; - if ($options['mode'] == 'notinstalled' && isset($installed['version'])) - continue; - if ($options['mode'] == 'upgrades' - && (!isset($installed['version']) || $installed['version'] == $info['stable'])) - { - continue; - }; - }; - - $data['data'][$info['category']][] = array( - $name, - @$info['stable'], - @$installed['version'], - @$desc, - @$info['deps'], - ); - } - $this->ui->outputData($data, $command); - return true; - } - - // }}} - // {{{ doSearch() - - function doSearch($command, $options, $params) - { - if ((!isset($params[0]) || empty($params[0])) - && (!isset($params[1]) || empty($params[1]))) - { - return $this->raiseError('no valid search string supplied'); - }; - - $r = new PEAR_Remote($this->config); - $reg = new PEAR_Registry($this->config->get('php_dir')); - $available = $r->call('package.listAll', true); - if (PEAR::isError($available)) { - return $this->raiseError($available); - } - $data = array( - 'caption' => 'Matched packages:', - 'border' => true, - 'headline' => array('Package', 'Latest', 'Local'), - ); - - foreach ($available as $name => $info) { - $found = (!empty($params[0]) && stristr($name, $params[0]) !== false); - if (!$found && !(isset($params[1]) && !empty($params[1]) - && (stristr($info['summary'], $params[1]) !== false - || stristr($info['description'], $params[1]) !== false))) - { - continue; - }; - - $installed = $reg->packageInfo($name); - $desc = $info['summary']; - if (isset($params[$name])) - $desc .= "\n\n".$info['description']; - - $data['data'][$info['category']][] = array( - $name, - $info['stable'], - $installed['version'], - $desc, - ); - } - if (!isset($data['data'])) { - return $this->raiseError('no packages found'); - }; - $this->ui->outputData($data, $command); - return true; - } - - // }}} - // {{{ doDownload() - - function doDownload($command, $options, $params) - { - //$params[0] -> The package to download - if (count($params) != 1) { - return PEAR::raiseError("download expects one argument: the package to download"); - } - $server = $this->config->get('master_server'); - if (!ereg('^http://', $params[0])) { - $pkgfile = "http://$server/get/$params[0]"; - } else { - $pkgfile = $params[0]; - } - $this->bytes_downloaded = 0; - $saved = PEAR_Common::downloadHttp($pkgfile, $this->ui, '.', - array(&$this, 'downloadCallback')); - if (PEAR::isError($saved)) { - return $this->raiseError($saved); - } - $fname = basename($saved); - $this->ui->outputData("File $fname downloaded ($this->bytes_downloaded bytes)", $command); - return true; - } - - function downloadCallback($msg, $params = null) - { - if ($msg == 'done') { - $this->bytes_downloaded = $params; - } - } - - // }}} - // {{{ doListUpgrades() - - function doListUpgrades($command, $options, $params) - { - include_once "PEAR/Registry.php"; - $remote = new PEAR_Remote($this->config); - if (empty($params[0])) { - $state = $this->config->get('preferred_state'); - } else { - $state = $params[0]; - } - $caption = 'Available Upgrades'; - if (empty($state) || $state == 'any') { - $latest = $remote->call("package.listLatestReleases"); - } else { - $latest = $remote->call("package.listLatestReleases", $state); - $caption .= ' (' . $state . ')'; - } - $caption .= ':'; - if (PEAR::isError($latest)) { - return $latest; - } - $reg = new PEAR_Registry($this->config->get('php_dir')); - $inst = array_flip($reg->listPackages()); - $data = array( - 'caption' => $caption, - 'border' => 1, - 'headline' => array('Package', 'Version', 'Size'), - ); - foreach ($latest as $package => $info) { - if (!isset($inst[$package])) { - // skip packages we don't have installed - continue; - } - extract($info); - $inst_version = $reg->packageInfo($package, 'version'); - if (version_compare("$version", "$inst_version", "le")) { - // installed version is up-to-date - continue; - } - if ($filesize >= 20480) { - $filesize += 1024 - ($filesize % 1024); - $fs = sprintf("%dkB", $filesize / 1024); - } elseif ($filesize > 0) { - $filesize += 103 - ($filesize % 103); - $fs = sprintf("%.1fkB", $filesize / 1024.0); - } else { - $fs = " -"; // XXX center instead - } - $data['data'][] = array($package, $version, $fs); - } - if (empty($data['data'])) { - $this->ui->outputData('No upgrades available'); - } else { - $this->ui->outputData($data, $command); - } - return true; - } - - // }}} - // {{{ doClearCache() - - function doClearCache($command, $options, $params) - { - $cache_dir = $this->config->get('cache_dir'); - $verbose = $this->config->get('verbose'); - $output = ''; - if (!($dp = @opendir($cache_dir))) { - return $this->raiseError("opendir($cache_dir) failed: $php_errormsg"); - } - if ($verbose >= 1) { - $output .= "reading directory $cache_dir\n"; - } - $num = 0; - while ($ent = readdir($dp)) { - if (preg_match('/^xmlrpc_cache_[a-z0-9]{32}$/', $ent)) { - $path = $cache_dir . DIRECTORY_SEPARATOR . $ent; - $ok = @unlink($path); - if ($ok) { - if ($verbose >= 2) { - $output .= "deleted $path\n"; - } - $num++; - } elseif ($verbose >= 1) { - $output .= "failed to delete $path\n"; - } - } - } - closedir($dp); - if ($verbose >= 1) { - $output .= "$num cache entries cleared\n"; - } - $this->ui->outputData(rtrim($output), $command); - return $num; - } - - // }}} -} - -?> diff --git a/gulliver/thirdparty/pear/PEAR/Common.php b/gulliver/thirdparty/pear/PEAR/Common.php deleted file mode 100644 index 88a4f6049..000000000 --- a/gulliver/thirdparty/pear/PEAR/Common.php +++ /dev/null @@ -1,1702 +0,0 @@ - | -// | Tomas V.V.Cox | -// +----------------------------------------------------------------------+ -// -// $Id: Common.php,v 1.91 2003/05/09 12:03:09 derick Exp $ - -require_once 'PEAR.php'; -require_once 'Archive/Tar.php'; -require_once 'System.php'; -require_once 'PEAR/Config.php'; - -// {{{ constants and globals - -define('PEAR_COMMON_PACKAGE_NAME_PREG', '/^([A-Z][a-zA-Z0-9_]+|[a-z][a-z0-9_]+)$/'); - -/** - * List of temporary files and directories registered by - * PEAR_Common::addTempFile(). - * @var array - */ -$GLOBALS['_PEAR_Common_tempfiles'] = array(); - -/** - * Valid maintainer roles - * @var array - */ -$GLOBALS['_PEAR_Common_maintainer_roles'] = array('lead','developer','contributor','helper'); - -/** - * Valid release states - * @var array - */ -$GLOBALS['_PEAR_Common_release_states'] = array('alpha','beta','stable','snapshot','devel'); - -/** - * Valid dependency types - * @var array - */ -$GLOBALS['_PEAR_Common_dependency_types'] = array('pkg','ext','php','prog','ldlib','rtlib','os','websrv','sapi'); - -/** - * Valid dependency relations - * @var array - */ -$GLOBALS['_PEAR_Common_dependency_relations'] = array('has','eq','lt','le','gt','ge'); - -/** - * Valid file roles - * @var array - */ -$GLOBALS['_PEAR_Common_file_roles'] = array('php','ext','test','doc','data','src','script'); - -/** - * Valid replacement types - * @var array - */ -$GLOBALS['_PEAR_Common_replacement_types'] = array('php-const', 'pear-config', 'package-info'); - -/** - * Valid "provide" types - * @var array - */ -$GLOBALS['_PEAR_Common_provide_types'] = array('ext', 'prog', 'class', 'function', 'feature', 'api'); - -/** - * Valid "provide" types - * @var array - */ -$GLOBALS['_PEAR_Common_script_phases'] = array('pre-install', 'post-install', 'pre-uninstall', 'post-uninstall', 'pre-build', 'post-build', 'pre-configure', 'post-configure', 'pre-setup', 'post-setup'); - -// }}} - -/** - * Class providing common functionality for PEAR adminsitration classes. - */ -class PEAR_Common extends PEAR -{ - // {{{ properties - - /** stack of elements, gives some sort of XML context */ - var $element_stack = array(); - - /** name of currently parsed XML element */ - var $current_element; - - /** array of attributes of the currently parsed XML element */ - var $current_attributes = array(); - - /** assoc with information about a package */ - var $pkginfo = array(); - - /** - * User Interface object (PEAR_Frontend_* class). If null, - * the log() method uses print. - * @var object - */ - var $ui = null; - - /** - * Configuration object (PEAR_Config). - * @var object - */ - var $config = null; - - var $current_path = null; - - /** - * PEAR_SourceAnalyzer instance - * @var object - */ - var $source_analyzer = null; - - // }}} - - // {{{ constructor - - /** - * PEAR_Common constructor - * - * @access public - */ - function PEAR_Common() - { - parent::PEAR(); - $this->config = &PEAR_Config::singleton(); - $this->debug = $this->config->get('verbose'); - } - - // }}} - // {{{ destructor - - /** - * PEAR_Common destructor - * - * @access private - */ - function _PEAR_Common() - { - // doesn't work due to bug #14744 - //$tempfiles = $this->_tempfiles; - $tempfiles =& $GLOBALS['_PEAR_Common_tempfiles']; - while ($file = array_shift($tempfiles)) { - if (@is_dir($file)) { - System::rm("-rf $file"); - } elseif (file_exists($file)) { - unlink($file); - } - } - } - - // }}} - // {{{ addTempFile() - - /** - * Register a temporary file or directory. When the destructor is - * executed, all registered temporary files and directories are - * removed. - * - * @param string $file name of file or directory - * - * @return void - * - * @access public - */ - function addTempFile($file) - { - $GLOBALS['_PEAR_Common_tempfiles'][] = $file; - } - - // }}} - // {{{ mkDirHier() - - /** - * Wrapper to System::mkDir(), creates a directory as well as - * any necessary parent directories. - * - * @param string $dir directory name - * - * @return bool TRUE on success, or a PEAR error - * - * @access public - */ - function mkDirHier($dir) - { - $this->log(2, "+ create dir $dir"); - return System::mkDir("-p $dir"); - } - - // }}} - // {{{ log() - - /** - * Logging method. - * - * @param int $level log level (0 is quiet, higher is noisier) - * @param string $msg message to write to the log - * - * @return void - * - * @access public - */ - function log($level, $msg) - { - if ($this->debug >= $level) { - if (is_object($this->ui)) { - $this->ui->log($msg); - } else { - print "$msg\n"; - } - } - } - - // }}} - // {{{ mkTempDir() - - /** - * Create and register a temporary directory. - * - * @param string $tmpdir (optional) Directory to use as tmpdir. - * Will use system defaults (for example - * /tmp or c:\windows\temp) if not specified - * - * @return string name of created directory - * - * @access public - */ - function mkTempDir($tmpdir = '') - { - if ($tmpdir) { - $topt = "-t $tmpdir "; - } else { - $topt = ''; - } - if (!$tmpdir = System::mktemp($topt . '-d pear')) { - return false; - } - $this->addTempFile($tmpdir); - return $tmpdir; - } - - // }}} - // {{{ setFrontendObject() - - /** - * Set object that represents the frontend to be used. - * - * @param object Reference of the frontend object - * @return void - * @access public - */ - function setFrontendObject(&$ui) - { - $this->ui = &$ui; - } - - // }}} - - // {{{ _unIndent() - - /** - * Unindent given string (?) - * - * @param string $str The string that has to be unindented. - * @return string - * @access private - */ - function _unIndent($str) - { - // remove leading newlines - $str = preg_replace('/^[\r\n]+/', '', $str); - // find whitespace at the beginning of the first line - $indent_len = strspn($str, " \t"); - $indent = substr($str, 0, $indent_len); - $data = ''; - // remove the same amount of whitespace from following lines - foreach (explode("\n", $str) as $line) { - if (substr($line, 0, $indent_len) == $indent) { - $data .= substr($line, $indent_len) . "\n"; - } - } - return $data; - } - - // }}} - // {{{ _element_start() - - /** - * XML parser callback for starting elements. Used while package - * format version is not yet known. - * - * @param resource $xp XML parser resource - * @param string $name name of starting element - * @param array $attribs element attributes, name => value - * - * @return void - * - * @access private - */ - function _element_start($xp, $name, $attribs) - { - array_push($this->element_stack, $name); - $this->current_element = $name; - $spos = sizeof($this->element_stack) - 2; - $this->prev_element = ($spos >= 0) ? $this->element_stack[$spos] : ''; - $this->current_attributes = $attribs; - switch ($name) { - case 'package': { - if (isset($attribs['version'])) { - $vs = preg_replace('/[^0-9a-z]/', '_', $attribs['version']); - } else { - $vs = '1_0'; - } - $elem_start = '_element_start_'. $vs; - $elem_end = '_element_end_'. $vs; - $cdata = '_pkginfo_cdata_'. $vs; - xml_set_element_handler($xp, $elem_start, $elem_end); - xml_set_character_data_handler($xp, $cdata); - break; - } - } - } - - // }}} - // {{{ _element_end() - - /** - * XML parser callback for ending elements. Used while package - * format version is not yet known. - * - * @param resource $xp XML parser resource - * @param string $name name of ending element - * - * @return void - * - * @access private - */ - function _element_end($xp, $name) - { - } - - // }}} - - // Support for package DTD v1.0: - // {{{ _element_start_1_0() - - /** - * XML parser callback for ending elements. Used for version 1.0 - * packages. - * - * @param resource $xp XML parser resource - * @param string $name name of ending element - * - * @return void - * - * @access private - */ - function _element_start_1_0($xp, $name, $attribs) - { - array_push($this->element_stack, $name); - $this->current_element = $name; - $spos = sizeof($this->element_stack) - 2; - $this->prev_element = ($spos >= 0) ? $this->element_stack[$spos] : ''; - $this->current_attributes = $attribs; - $this->cdata = ''; - switch ($name) { - case 'dir': - if ($this->in_changelog) { - break; - } - if ($attribs['name'] != '/') { - $this->dir_names[] = $attribs['name']; - } - if (isset($attribs['baseinstalldir'])) { - $this->dir_install = $attribs['baseinstalldir']; - } - if (isset($attribs['role'])) { - $this->dir_role = $attribs['role']; - } - break; - case 'file': - if ($this->in_changelog) { - break; - } - if (isset($attribs['name'])) { - $path = ''; - if (count($this->dir_names)) { - foreach ($this->dir_names as $dir) { - $path .= $dir . DIRECTORY_SEPARATOR; - } - } - $path .= $attribs['name']; - unset($attribs['name']); - $this->current_path = $path; - $this->filelist[$path] = $attribs; - // Set the baseinstalldir only if the file don't have this attrib - if (!isset($this->filelist[$path]['baseinstalldir']) && - isset($this->dir_install)) - { - $this->filelist[$path]['baseinstalldir'] = $this->dir_install; - } - // Set the Role - if (!isset($this->filelist[$path]['role']) && isset($this->dir_role)) { - $this->filelist[$path]['role'] = $this->dir_role; - } - } - break; - case 'replace': - if (!$this->in_changelog) { - $this->filelist[$this->current_path]['replacements'][] = $attribs; - } - break; - case 'maintainers': - $this->pkginfo['maintainers'] = array(); - $this->m_i = 0; // maintainers array index - break; - case 'maintainer': - // compatibility check - if (!isset($this->pkginfo['maintainers'])) { - $this->pkginfo['maintainers'] = array(); - $this->m_i = 0; - } - $this->pkginfo['maintainers'][$this->m_i] = array(); - $this->current_maintainer =& $this->pkginfo['maintainers'][$this->m_i]; - break; - case 'changelog': - $this->pkginfo['changelog'] = array(); - $this->c_i = 0; // changelog array index - $this->in_changelog = true; - break; - case 'release': - if ($this->in_changelog) { - $this->pkginfo['changelog'][$this->c_i] = array(); - $this->current_release = &$this->pkginfo['changelog'][$this->c_i]; - } else { - $this->current_release = &$this->pkginfo; - } - break; - case 'deps': - if (!$this->in_changelog) { - $this->pkginfo['release_deps'] = array(); - } - break; - case 'dep': - // dependencies array index - if (!$this->in_changelog) { - $this->d_i++; - $this->pkginfo['release_deps'][$this->d_i] = $attribs; - } - break; - case 'configureoptions': - if (!$this->in_changelog) { - $this->pkginfo['configure_options'] = array(); - } - break; - case 'configureoption': - if (!$this->in_changelog) { - $this->pkginfo['configure_options'][] = $attribs; - } - break; - case 'provides': - if (empty($attribs['type']) || empty($attribs['name'])) { - break; - } - $attribs['explicit'] = true; - $this->pkginfo['provides']["$attribs[type];$attribs[name]"] = $attribs; - break; - } - } - - // }}} - // {{{ _element_end_1_0() - - /** - * XML parser callback for ending elements. Used for version 1.0 - * packages. - * - * @param resource $xp XML parser resource - * @param string $name name of ending element - * - * @return void - * - * @access private - */ - function _element_end_1_0($xp, $name) - { - $data = trim($this->cdata); - switch ($name) { - case 'name': - switch ($this->prev_element) { - case 'package': - // XXX should we check the package name here? - $this->pkginfo['package'] = ereg_replace('[^a-zA-Z0-9._]', '_', $data); - break; - case 'maintainer': - $this->current_maintainer['name'] = $data; - break; - } - break; - case 'summary': - $this->pkginfo['summary'] = $data; - break; - case 'description': - $data = $this->_unIndent($this->cdata); - $this->pkginfo['description'] = $data; - break; - case 'user': - $this->current_maintainer['handle'] = $data; - break; - case 'email': - $this->current_maintainer['email'] = $data; - break; - case 'role': - $this->current_maintainer['role'] = $data; - break; - case 'version': - $data = ereg_replace ('[^a-zA-Z0-9._\-]', '_', $data); - if ($this->in_changelog) { - $this->current_release['version'] = $data; - } else { - $this->pkginfo['version'] = $data; - } - break; - case 'date': - if ($this->in_changelog) { - $this->current_release['release_date'] = $data; - } else { - $this->pkginfo['release_date'] = $data; - } - break; - case 'notes': - // try to "de-indent" release notes in case someone - // has been over-indenting their xml ;-) - $data = $this->_unIndent($this->cdata); - if ($this->in_changelog) { - $this->current_release['release_notes'] = $data; - } else { - $this->pkginfo['release_notes'] = $data; - } - break; - case 'warnings': - if ($this->in_changelog) { - $this->current_release['release_warnings'] = $data; - } else { - $this->pkginfo['release_warnings'] = $data; - } - break; - case 'state': - if ($this->in_changelog) { - $this->current_release['release_state'] = $data; - } else { - $this->pkginfo['release_state'] = $data; - } - break; - case 'license': - $this->pkginfo['release_license'] = $data; - break; - case 'dep': - if ($data && !$this->in_changelog) { - $this->pkginfo['release_deps'][$this->d_i]['name'] = $data; - } - break; - case 'dir': - if ($this->in_changelog) { - break; - } - array_pop($this->dir_names); - break; - case 'file': - if ($this->in_changelog) { - break; - } - if ($data) { - $path = ''; - if (count($this->dir_names)) { - foreach ($this->dir_names as $dir) { - $path .= $dir . DIRECTORY_SEPARATOR; - } - } - $path .= $data; - $this->filelist[$path] = $this->current_attributes; - // Set the baseinstalldir only if the file don't have this attrib - if (!isset($this->filelist[$path]['baseinstalldir']) && - isset($this->dir_install)) - { - $this->filelist[$path]['baseinstalldir'] = $this->dir_install; - } - // Set the Role - if (!isset($this->filelist[$path]['role']) && isset($this->dir_role)) { - $this->filelist[$path]['role'] = $this->dir_role; - } - } - break; - case 'maintainer': - if (empty($this->pkginfo['maintainers'][$this->m_i]['role'])) { - $this->pkginfo['maintainers'][$this->m_i]['role'] = 'lead'; - } - $this->m_i++; - break; - case 'release': - if ($this->in_changelog) { - $this->c_i++; - } - break; - case 'changelog': - $this->in_changelog = false; - break; - case 'summary': - $this->pkginfo['summary'] = $data; - break; - } - array_pop($this->element_stack); - $spos = sizeof($this->element_stack) - 1; - $this->current_element = ($spos > 0) ? $this->element_stack[$spos] : ''; - $this->cdata = ''; - } - - // }}} - // {{{ _pkginfo_cdata_1_0() - - /** - * XML parser callback for character data. Used for version 1.0 - * packages. - * - * @param resource $xp XML parser resource - * @param string $name character data - * - * @return void - * - * @access private - */ - function _pkginfo_cdata_1_0($xp, $data) - { - if (isset($this->cdata)) { - $this->cdata .= $data; - } - } - - // }}} - - // {{{ infoFromTgzFile() - - /** - * Returns information about a package file. Expects the name of - * a gzipped tar file as input. - * - * @param string $file name of .tgz file - * - * @return array array with package information - * - * @access public - * - */ - function infoFromTgzFile($file) - { - if (!@is_file($file)) { - return $this->raiseError("could not open file \"$file\""); - } - $tar = new Archive_Tar($file); - $content = $tar->listContent(); - if (!is_array($content)) { - return $this->raiseError("could not get contents of package \"$file\""); - } - $xml = null; - foreach ($content as $file) { - $name = $file['filename']; - if ($name == 'package.xml') { - $xml = $name; - break; - } elseif (ereg('package.xml$', $name, $match)) { - $xml = $match[0]; - break; - } - } - $tmpdir = System::mkTemp('-d pear'); - $this->addTempFile($tmpdir); - if (!$xml || !$tar->extractList($xml, $tmpdir)) { - return $this->raiseError('could not extract the package.xml file'); - } - return $this->infoFromDescriptionFile("$tmpdir/$xml"); - } - - // }}} - // {{{ infoFromDescriptionFile() - - /** - * Returns information about a package file. Expects the name of - * a package xml file as input. - * - * @param string $descfile name of package xml file - * - * @return array array with package information - * - * @access public - * - */ - function infoFromDescriptionFile($descfile) - { - if (!@is_file($descfile) || !is_readable($descfile) || - (!$fp = @fopen($descfile, 'r'))) { - return $this->raiseError("Unable to open $descfile"); - } - - // read the whole thing so we only get one cdata callback - // for each block of cdata - $data = fread($fp, filesize($descfile)); - return $this->infoFromString($data); - } - - // }}} - // {{{ infoFromString() - - /** - * Returns information about a package file. Expects the contents - * of a package xml file as input. - * - * @param string $data name of package xml file - * - * @return array array with package information - * - * @access public - * - */ - function infoFromString($data) - { - require_once('PEAR/Dependency.php'); - if (PEAR_Dependency::checkExtension($error, 'xml')) { - return $this->raiseError($error); - } - $xp = @xml_parser_create(); - if (!$xp) { - return $this->raiseError('Unable to create XML parser'); - } - xml_set_object($xp, $this); - xml_set_element_handler($xp, '_element_start', '_element_end'); - xml_set_character_data_handler($xp, '_pkginfo_cdata'); - xml_parser_set_option($xp, XML_OPTION_CASE_FOLDING, false); - - $this->element_stack = array(); - $this->pkginfo = array('provides' => array()); - $this->current_element = false; - unset($this->dir_install); - $this->pkginfo['filelist'] = array(); - $this->filelist =& $this->pkginfo['filelist']; - $this->dir_names = array(); - $this->in_changelog = false; - $this->d_i = 0; - $this->cdata = ''; - - if (!xml_parse($xp, $data, 1)) { - $code = xml_get_error_code($xp); - $msg = sprintf("XML error: %s at line %d", - xml_error_string($code), - xml_get_current_line_number($xp)); - xml_parser_free($xp); - return $this->raiseError($msg, $code); - } - - xml_parser_free($xp); - - foreach ($this->pkginfo as $k => $v) { - if (!is_array($v)) { - $this->pkginfo[$k] = trim($v); - } - } - return $this->pkginfo; - } - // }}} - // {{{ infoFromAny() - - /** - * Returns package information from different sources - * - * This method is able to extract information about a package - * from a .tgz archive or from a XML package definition file. - * - * @access public - * @param string Filename of the source ('package.xml', '.tgz') - * @return string - */ - function infoFromAny($info) - { - if (is_string($info) && file_exists($info)) { - $tmp = substr($info, -4); - if ($tmp == '.xml') { - $info = $this->infoFromDescriptionFile($info); - } elseif ($tmp == '.tar' || $tmp == '.tgz') { - $info = $this->infoFromTgzFile($info); - } else { - $fp = fopen($info, "r"); - $test = fread($fp, 5); - fclose($fp); - if ($test == "infoFromDescriptionFile($info); - } else { - $info = $this->infoFromTgzFile($info); - } - } - if (PEAR::isError($info)) { - return $this->raiseError($info); - } - } - return $info; - } - - // }}} - // {{{ xmlFromInfo() - - /** - * Return an XML document based on the package info (as returned - * by the PEAR_Common::infoFrom* methods). - * - * @param array $pkginfo package info - * - * @return string XML data - * - * @access public - */ - function xmlFromInfo($pkginfo) - { - static $maint_map = array( - "handle" => "user", - "name" => "name", - "email" => "email", - "role" => "role", - ); - $ret = "\n"; - //$ret .= "\n"; - $ret .= " - $pkginfo[package] - ".htmlspecialchars($pkginfo['summary'])." - ".htmlspecialchars($pkginfo['description'])." - -"; - foreach ($pkginfo['maintainers'] as $maint) { - $ret .= " \n"; - foreach ($maint_map as $idx => $elm) { - $ret .= " <$elm>"; - $ret .= htmlspecialchars($maint[$idx]); - $ret .= "\n"; - } - $ret .= " \n"; - } - $ret .= " \n"; - $ret .= $this->_makeReleaseXml($pkginfo); - if (@sizeof($pkginfo['changelog']) > 0) { - $ret .= " \n"; - foreach ($pkginfo['changelog'] as $oldrelease) { - $ret .= $this->_makeReleaseXml($oldrelease, true); - } - $ret .= " \n"; - } - $ret .= "\n"; - return $ret; - } - - // }}} - // {{{ _makeReleaseXml() - - /** - * Generate part of an XML description with release information. - * - * @param array $pkginfo array with release information - * @param bool $changelog whether the result will be in a changelog element - * - * @return string XML data - * - * @access private - */ - function _makeReleaseXml($pkginfo, $changelog = false) - { - // XXX QUOTE ENTITIES IN PCDATA, OR EMBED IN CDATA BLOCKS!! - $indent = $changelog ? " " : ""; - $ret = "$indent \n"; - if (!empty($pkginfo['version'])) { - $ret .= "$indent $pkginfo[version]\n"; - } - if (!empty($pkginfo['release_date'])) { - $ret .= "$indent $pkginfo[release_date]\n"; - } - if (!empty($pkginfo['release_license'])) { - $ret .= "$indent $pkginfo[release_license]\n"; - } - if (!empty($pkginfo['release_state'])) { - $ret .= "$indent $pkginfo[release_state]\n"; - } - if (!empty($pkginfo['release_notes'])) { - $ret .= "$indent ".htmlspecialchars($pkginfo['release_notes'])."\n"; - } - if (!empty($pkginfo['release_warnings'])) { - $ret .= "$indent ".htmlspecialchars($pkginfo['release_warnings'])."\n"; - } - if (isset($pkginfo['release_deps']) && sizeof($pkginfo['release_deps']) > 0) { - $ret .= "$indent \n"; - foreach ($pkginfo['release_deps'] as $dep) { - $ret .= "$indent $what) { - $ret .= "$indent $fa) { - @$ret .= "$indent $v) { - $ret .= " $k=\"" . htmlspecialchars($v) .'"'; - } - $ret .= "/>\n"; - } - @$ret .= "$indent \n"; - } - } - $ret .= "$indent \n"; - } - $ret .= "$indent \n"; - return $ret; - } - - // }}} - // {{{ validatePackageInfo() - - /** - * Validate XML package definition file. - * - * @param string $info Filename of the package archive or of the - * package definition file - * @param array $errors Array that will contain the errors - * @param array $warnings Array that will contain the warnings - * @param string $dir_prefix (optional) directory where source files - * may be found, or empty if they are not available - * @access public - * @return boolean - */ - function validatePackageInfo($info, &$errors, &$warnings, $dir_prefix = '') - { - global $_PEAR_Common_maintainer_roles, - $_PEAR_Common_release_states, - $_PEAR_Common_dependency_types, - $_PEAR_Common_dependency_relations, - $_PEAR_Common_file_roles, - $_PEAR_Common_replacement_types; - if (PEAR::isError($info = $this->infoFromAny($info))) { - return $this->raiseError($info); - } - if (!is_array($info)) { - return false; - } - $errors = array(); - $warnings = array(); - if (empty($info['package'])) { - $errors[] = 'missing package name'; - } - if (empty($info['summary'])) { - $errors[] = 'missing summary'; - } elseif (strpos(trim($info['summary']), "\n") !== false) { - $warnings[] = 'summary should be on a single line'; - } - if (empty($info['description'])) { - $errors[] = 'missing description'; - } - if (empty($info['release_license'])) { - $errors[] = 'missing license'; - } - if (empty($info['version'])) { - $errors[] = 'missing version'; - } - if (empty($info['release_state'])) { - $errors[] = 'missing release state'; - } elseif (!in_array($info['release_state'], $_PEAR_Common_release_states)) { - $errors[] = "invalid release state `$info[release_state]', should be one of: ".implode(' ', $_PEAR_Common_release_states); - } - if (empty($info['release_date'])) { - $errors[] = 'missing release date'; - } elseif (!preg_match('/^\d{4}-\d\d-\d\d$/', $info['release_date'])) { - $errors[] = "invalid release date `$info[release_date]', format is YYYY-MM-DD"; - } - if (empty($info['release_notes'])) { - $errors[] = "missing release notes"; - } - if (empty($info['maintainers'])) { - $errors[] = 'no maintainer(s)'; - } else { - $i = 1; - foreach ($info['maintainers'] as $m) { - if (empty($m['handle'])) { - $errors[] = "maintainer $i: missing handle"; - } - if (empty($m['role'])) { - $errors[] = "maintainer $i: missing role"; - } elseif (!in_array($m['role'], $_PEAR_Common_maintainer_roles)) { - $errors[] = "maintainer $i: invalid role `$m[role]', should be one of: ".implode(' ', $_PEAR_Common_maintainer_roles); - } - if (empty($m['name'])) { - $errors[] = "maintainer $i: missing name"; - } - if (empty($m['email'])) { - $errors[] = "maintainer $i: missing email"; - } - $i++; - } - } - if (!empty($info['deps'])) { - $i = 1; - foreach ($info['deps'] as $d) { - if (empty($d['type'])) { - $errors[] = "depenency $i: missing type"; - } elseif (!in_array($d['type'], $_PEAR_Common_dependency_types)) { - $errors[] = "dependency $i: invalid type, should be one of: ".implode(' ', $_PEAR_Common_depenency_types); - } - if (empty($d['rel'])) { - $errors[] = "dependency $i: missing relation"; - } elseif (!in_array($d['rel'], $_PEAR_Common_dependency_relations)) { - $errors[] = "dependency $i: invalid relation, should be one of: ".implode(' ', $_PEAR_Common_dependency_relations); - } - if ($d['rel'] != 'has' && empty($d['version'])) { - $warnings[] = "dependency $i: missing version"; - } elseif ($d['rel'] == 'has' && !empty($d['version'])) { - $warnings[] = "dependency $i: version ignored for `has' dependencies"; - } - if ($d['type'] == 'php' && !empty($d['name'])) { - $warnings[] = "dependency $i: name ignored for php type dependencies"; - } elseif ($d['type'] != 'php' && empty($d['name'])) { - $errors[] = "dependency $i: missing name"; - } - $i++; - } - } - if (!empty($info['configure_options'])) { - $i = 1; - foreach ($info['configure_options'] as $c) { - if (empty($c['name'])) { - $errors[] = "configure option $i: missing name"; - } - if (empty($c['prompt'])) { - $errors[] = "configure option $i: missing prompt"; - } - } - } - if (empty($info['filelist'])) { - $errors[] = 'no files'; - } else { - foreach ($info['filelist'] as $file => $fa) { - if (empty($fa['role'])) { - $errors[] = "file $file: missing role"; - continue; - } elseif (!in_array($fa['role'], $_PEAR_Common_file_roles)) { - $errors[] = "file $file: invalid role, should be one of: ".implode(' ', $_PEAR_Common_file_roles); - } - if ($fa['role'] == 'php' && $dir_prefix) { - $this->log(1, "Analyzing $file"); - $srcinfo = $this->analyzeSourceCode($dir_prefix . DIRECTORY_SEPARATOR . $file); - if ($srcinfo) { - $this->buildProvidesArray($srcinfo); - } - } - // (ssb) Any checks we can do for baseinstalldir? - // (cox) Perhaps checks that either the target dir and - // baseInstall doesn't cointain "../../" - } - } - $pn = $info['package']; - $pnl = strlen($pn); - foreach ((array)$this->pkginfo['provides'] as $key => $what) { - if (isset($what['explicit'])) { - // skip conformance checks if the provides entry is - // specified in the package.xml file - continue; - } - extract($what); - if ($type == 'class') { - if (!strncasecmp($name, $pn, $pnl)) { - continue; - } - $warnings[] = "in $file: class \"$name\" not prefixed with package name \"$pn\""; - } elseif ($type == 'function') { - if (strstr($name, '::') || !strncasecmp($name, $pn, $pnl)) { - continue; - } - $warnings[] = "in $file: function \"$name\" not prefixed with package name \"$pn\""; - } - //print "$file: provides $what[type] $what[name]\n"; - } - return true; - } - - // }}} - // {{{ buildProvidesArray() - - /** - * Build a "provides" array from data returned by - * analyzeSourceCode(). The format of the built array is like - * this: - * - * array( - * 'class;MyClass' => 'array('type' => 'class', 'name' => 'MyClass'), - * ... - * ) - * - * - * @param array $srcinfo array with information about a source file - * as returned by the analyzeSourceCode() method. - * - * @return void - * - * @access public - * - */ - function buildProvidesArray($srcinfo) - { - foreach ($srcinfo['declared_classes'] as $class) { - $key = "class;$class"; - if (isset($this->pkginfo['provides'][$key])) { - continue; - } - $this->pkginfo['provides'][$key] = - array('type' => 'class', 'name' => $class); - if (isset($srcinfo['inheritance'][$class])) { - $this->pkginfo['provides'][$key]['extends'] = - $srcinfo['inheritance'][$class]; - } - } - foreach ($srcinfo['declared_methods'] as $class => $methods) { - foreach ($methods as $method) { - $function = "$class::$method"; - $key = "function;$function"; - if ($method{0} == '_' || !strcasecmp($method, $class) || - isset($this->pkginfo['provides'][$key])) { - continue; - } - $this->pkginfo['provides'][$key] = - array('type' => 'function', 'name' => $function); - } - } - foreach ($srcinfo['declared_functions'] as $function) { - $key = "function;$function"; - if ($function{0} == '_' || isset($this->pkginfo['provides'][$key])) { - continue; - } - $this->pkginfo['provides'][$key] = - array('type' => 'function', 'name' => $function); - } - } - - // }}} - // {{{ analyzeSourceCode() - - /** - * Analyze the source code of the given PHP file - * - * @param string Filename of the PHP file - * @return mixed - * @access public - */ - function analyzeSourceCode($file) - { - 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(); - $file = $filter->validateInput($file,"path"); - - if (!function_exists("token_get_all")) { - return false; - } - if (!$fp = @fopen($file, "r")) { - return false; - } - $contents = fread($fp, filesize($file)); - $tokens = token_get_all($contents); -/* - for ($i = 0; $i < sizeof($tokens); $i++) { - @list($token, $data) = $tokens[$i]; - if (is_string($token)) { - var_dump($token); - } else { - print token_name($token) . ' '; - var_dump(rtrim($data)); - } - } -*/ - $look_for = 0; - $paren_level = 0; - $bracket_level = 0; - $brace_level = 0; - $lastphpdoc = ''; - $current_class = ''; - $current_class_level = -1; - $current_function = ''; - $current_function_level = -1; - $declared_classes = array(); - $declared_functions = array(); - $declared_methods = array(); - $used_classes = array(); - $used_functions = array(); - $extends = array(); - $nodeps = array(); - for ($i = 0; $i < sizeof($tokens); $i++) { - if (is_array($tokens[$i])) { - list($token, $data) = $tokens[$i]; - } else { - $token = $tokens[$i]; - $data = ''; - } - switch ($token) { - case T_CURLY_OPEN: - case T_DOLLAR_OPEN_CURLY_BRACES: - case '{': $brace_level++; continue 2; - case '}': - $brace_level--; - if ($current_class_level == $brace_level) { - $current_class = ''; - $current_class_level = -1; - } - if ($current_function_level == $brace_level) { - $current_function = ''; - $current_function_level = -1; - } - continue 2; - case '[': $bracket_level++; continue 2; - case ']': $bracket_level--; continue 2; - case '(': $paren_level++; continue 2; - case ')': $paren_level--; continue 2; - case T_CLASS: - case T_FUNCTION: - case T_NEW: - case T_EXTENDS: - $look_for = $token; - continue 2; - case T_STRING: - if ($look_for == T_CLASS) { - $current_class = $data; - $current_class_level = $brace_level; - $declared_classes[] = $current_class; - } elseif ($look_for == T_EXTENDS) { - $extends[$current_class] = $data; - } elseif ($look_for == T_FUNCTION) { - if ($current_class) { - $current_function = "$current_class::$data"; - $declared_methods[$current_class][] = $data; - } else { - $current_function = $data; - $declared_functions[] = $current_function; - } - $current_function_level = $brace_level; - $m = array(); - } elseif ($look_for == T_NEW) { - $used_classes[$data] = true; - } - $look_for = 0; - continue 2; - case T_VARIABLE: - $look_for = 0; - continue 2; - case T_COMMENT: - if (preg_match('!^/\*\*\s!', $data)) { - $lastphpdoc = $data; - if (preg_match_all('/@nodep\s+(\S+)/', $lastphpdoc, $m)) { - $nodeps = array_merge($nodeps, $m[1]); - } - } - continue 2; - case T_DOUBLE_COLON: - $class = $tokens[$i - 1][1]; - if (strtolower($class) != 'parent') { - $used_classes[$class] = true; - } - continue 2; - } - } - return array( - "declared_classes" => $declared_classes, - "declared_methods" => $declared_methods, - "declared_functions" => $declared_functions, - "used_classes" => array_diff(array_keys($used_classes), $nodeps), - "inheritance" => $extends, - ); - } - - // }}} - // {{{ detectDependencies() - - function detectDependencies($any, $status_callback = null) - { - if (!function_exists("token_get_all")) { - return false; - } - if (PEAR::isError($info = $this->infoFromAny($any))) { - return $this->raiseError($info); - } - if (!is_array($info)) { - return false; - } - $deps = array(); - $used_c = $decl_c = $decl_f = $decl_m = array(); - foreach ($info['filelist'] as $file => $fa) { - $tmp = $this->analyzeSourceCode($file); - $used_c = @array_merge($used_c, $tmp['used_classes']); - $decl_c = @array_merge($decl_c, $tmp['declared_classes']); - $decl_f = @array_merge($decl_f, $tmp['declared_functions']); - $decl_m = @array_merge($decl_m, $tmp['declared_methods']); - $inheri = @array_merge($inheri, $tmp['inheritance']); - } - $used_c = array_unique($used_c); - $decl_c = array_unique($decl_c); - $undecl_c = array_diff($used_c, $decl_c); - return array('used_classes' => $used_c, - 'declared_classes' => $decl_c, - 'declared_methods' => $decl_m, - 'declared_functions' => $decl_f, - 'undeclared_classes' => $undecl_c, - 'inheritance' => $inheri, - ); - } - - // }}} - // {{{ getUserRoles() - - /** - * Get the valid roles for a PEAR package maintainer - * - * @return array - * @static - */ - function getUserRoles() - { - return $GLOBALS['_PEAR_Common_maintainer_roles']; - } - - // }}} - // {{{ getReleaseStates() - - /** - * Get the valid package release states of packages - * - * @return array - * @static - */ - function getReleaseStates() - { - return $GLOBALS['_PEAR_Common_release_states']; - } - - // }}} - // {{{ getDependencyTypes() - - /** - * Get the implemented dependency types (php, ext, pkg etc.) - * - * @return array - * @static - */ - function getDependencyTypes() - { - return $GLOBALS['_PEAR_Common_dependency_types']; - } - - // }}} - // {{{ getDependencyRelations() - - /** - * Get the implemented dependency relations (has, lt, ge etc.) - * - * @return array - * @static - */ - function getDependencyRelations() - { - return $GLOBALS['_PEAR_Common_dependency_relations']; - } - - // }}} - // {{{ getFileRoles() - - /** - * Get the implemented file roles - * - * @return array - * @static - */ - function getFileRoles() - { - return $GLOBALS['_PEAR_Common_file_roles']; - } - - // }}} - // {{{ getReplacementTypes() - - /** - * Get the implemented file replacement types in - * - * @return array - * @static - */ - function getReplacementTypes() - { - return $GLOBALS['_PEAR_Common_replacement_types']; - } - - // }}} - // {{{ getProvideTypes() - - /** - * Get the implemented file replacement types in - * - * @return array - * @static - */ - function getProvideTypes() - { - return $GLOBALS['_PEAR_Common_provide_types']; - } - - // }}} - // {{{ getScriptPhases() - - /** - * Get the implemented file replacement types in - * - * @return array - * @static - */ - function getScriptPhases() - { - return $GLOBALS['_PEAR_Common_script_phases']; - } - - // }}} - // {{{ validPackageName() - - /** - * Test whether a string contains a valid package name. - * - * @param string $name the package name to test - * - * @return bool - * - * @access public - */ - function validPackageName($name) - { - return (bool)preg_match(PEAR_COMMON_PACKAGE_NAME_PREG, $name); - } - - - // }}} - - // {{{ downloadHttp() - - /** - * Download a file through HTTP. Considers suggested file name in - * Content-disposition: header and can run a callback function for - * different events. The callback will be called with two - * parameters: the callback type, and parameters. The implemented - * callback types are: - * - * 'setup' called at the very beginning, parameter is a UI object - * that should be used for all output - * 'message' the parameter is a string with an informational message - * 'saveas' may be used to save with a different file name, the - * parameter is the filename that is about to be used. - * If a 'saveas' callback returns a non-empty string, - * that file name will be used as the filename instead. - * Note that $save_dir will not be affected by this, only - * the basename of the file. - * 'start' download is starting, parameter is number of bytes - * that are expected, or -1 if unknown - * 'bytesread' parameter is the number of bytes read so far - * 'done' download is complete, parameter is the total number - * of bytes read - * 'connfailed' if the TCP connection fails, this callback is called - * with array(host,port,errno,errmsg) - * 'writefailed' if writing to disk fails, this callback is called - * with array(destfile,errmsg) - * - * If an HTTP proxy has been configured (http_proxy PEAR_Config - * setting), the proxy will be used. - * - * @param string $url the URL to download - * @param object $ui PEAR_Frontend_* instance - * @param object $config PEAR_Config instance - * @param string $save_dir (optional) directory to save file in - * @param mixed $callback (optional) function/method to call for status - * updates - * - * @return string Returns the full path of the downloaded file or a PEAR - * error on failure. If the error is caused by - * socket-related errors, the error object will - * have the fsockopen error code available through - * getCode(). - * - * @access public - */ - function downloadHttp($url, &$ui, $save_dir = '.', $callback = null) - { - if ($callback) { - call_user_func($callback, 'setup', array(&$ui)); - } - if (preg_match('!^http://([^/:?#]*)(:(\d+))?(/.*)!', $url, $matches)) { - list(,$host,,$port,$path) = $matches; - } - if (isset($this)) { - $config = &$this->config; - } else { - $config = &PEAR_Config::singleton(); - } - $proxy_host = $proxy_port = $proxy_user = $proxy_pass = ''; - if ($proxy = parse_url($config->get('http_proxy'))) { - $proxy_host = @$proxy['host']; - $proxy_port = @$proxy['port']; - $proxy_user = @$proxy['user']; - $proxy_pass = @$proxy['pass']; - - if ($proxy_port == '') { - $proxy_port = 8080; - } - if ($callback) { - call_user_func($callback, 'message', "Using HTTP proxy $host:$port"); - } - } - if (empty($port)) { - $port = 80; - } - if ($proxy_host != '') { - $fp = @fsockopen($proxy_host, $proxy_port, $errno, $errstr); - if (!$fp) { - if ($callback) { - call_user_func($callback, 'connfailed', array($proxy_host, $proxy_port, - $errno, $errstr)); - } - return PEAR::raiseError("Connection to `$proxy_host:$proxy_port' failed: $errstr", $errno); - } - $request = "GET $url HTTP/1.0\r\n"; - } else { - $fp = @fsockopen($host, $port, $errno, $errstr); - if (!$fp) { - if ($callback) { - call_user_func($callback, 'connfailed', array($host, $port, - $errno, $errstr)); - } - return PEAR::raiseError("Connection to `$host:$port' failed: $errstr", $errno); - } - $request = "GET $path HTTP/1.0\r\n"; - } - $request .= "Host: $host:$port\r\n". - "User-Agent: PHP/".PHP_VERSION."\r\n"; - if ($proxy_host != '' && $proxy_user != '') { - $request .= 'Proxy-Authorization: Basic ' . - base64_encode($proxy_user . ':' . $proxy_pass) . "\r\n"; - } - $request .= "\r\n"; - fwrite($fp, $request); - $headers = array(); - while (trim($line = fgets($fp, 1024))) { - if (preg_match('/^([^:]+):\s+(.*)\s*$/', $line, $matches)) { - $headers[strtolower($matches[1])] = trim($matches[2]); - } elseif (preg_match('|^HTTP/1.[01] ([0-9]{3}) |', $line, $matches)) { - if ($matches[1] != 200) { - return PEAR::raiseError("File http://$host:$port$path not valid (received: $line)"); - } - } - } - if (isset($headers['content-disposition']) && - preg_match('/\sfilename=\"([^;]*\S)\"\s*(;|$)/', $headers['content-disposition'], $matches)) { - $save_as = basename($matches[1]); - } else { - $save_as = basename($url); - } - if ($callback) { - $tmp = call_user_func($callback, 'saveas', $save_as); - if ($tmp) { - $save_as = $tmp; - } - } - $dest_file = $save_dir . DIRECTORY_SEPARATOR . $save_as; - 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(); - $dest_file = $filter->validateInput($dest_file,"path"); - - if (!$wp = @fopen($dest_file, 'wb')) { - fclose($fp); - if ($callback) { - call_user_func($callback, 'writefailed', array($dest_file, $php_errormsg)); - } - return PEAR::raiseError("could not open $dest_file for writing"); - } - if (isset($headers['content-length'])) { - $length = $headers['content-length']; - } else { - $length = -1; - } - $bytes = 0; - if ($callback) { - call_user_func($callback, 'start', $length); - } - while ($data = @fread($fp, 1024)) { - $bytes += strlen($data); - if ($callback) { - call_user_func($callback, 'bytesread', $bytes); - } - if (!@fwrite($wp, $data)) { - fclose($fp); - if ($callback) { - call_user_func($callback, 'writefailed', array($dest_file, $php_errormsg)); - } - return PEAR::raiseError("$dest_file: write failed ($php_errormsg)"); - } - } - fclose($fp); - fclose($wp); - if ($callback) { - call_user_func($callback, 'done', $bytes); - } - return $dest_file; - } - - // }}} -} - -?> diff --git a/gulliver/thirdparty/pear/PEAR/Config.php b/gulliver/thirdparty/pear/PEAR/Config.php deleted file mode 100644 index 6cc2e40f4..000000000 --- a/gulliver/thirdparty/pear/PEAR/Config.php +++ /dev/null @@ -1,1139 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Config.php,v 1.43 2003/03/18 12:06:06 ssb Exp $ - -require_once 'PEAR.php'; -require_once 'System.php'; - -/** - * Last created PEAR_Config instance. - * @var object - */ -$GLOBALS['_PEAR_Config_instance'] = null; - -// Below we define constants with default values for all configuration -// parameters except username/password. All of them can have their -// defaults set through environment variables. The reason we use the -// PHP_ prefix is for some security, PHP protects environment -// variables starting with PHP_*. - -if (getenv('PHP_PEAR_SYSCONF_DIR')) { - define('PEAR_CONFIG_SYSCONFDIR', getenv('PHP_PEAR_SYSCONF_DIR')); -} elseif (getenv('SystemRoot')) { - define('PEAR_CONFIG_SYSCONFDIR', getenv('SystemRoot')); -} else { - define('PEAR_CONFIG_SYSCONFDIR', PHP_SYSCONFDIR); -} - -// Default for master_server -if (getenv('PHP_PEAR_MASTER_SERVER')) { - define('PEAR_CONFIG_DEFAULT_MASTER_SERVER', getenv('PHP_PEAR_MASTER_SERVER')); -} else { - define('PEAR_CONFIG_DEFAULT_MASTER_SERVER', 'pear.php.net'); -} - -// Default for http_proxy -if (getenv('PHP_PEAR_HTTP_PROXY')) { - define('PEAR_CONFIG_DEFAULT_HTTP_PROXY', getenv('PHP_PEAR_HTTP_PROXY')); -} elseif (getenv('http_proxy')) { - define('PEAR_CONFIG_DEFAULT_HTTP_PROXY', getenv('http_proxy')); -} else { - define('PEAR_CONFIG_DEFAULT_HTTP_PROXY', ''); -} - -// Default for php_dir -if (getenv('PHP_PEAR_INSTALL_DIR')) { - define('PEAR_CONFIG_DEFAULT_PHP_DIR', getenv('PHP_PEAR_INSTALL_DIR')); -} else { - if (@is_dir(PEAR_INSTALL_DIR.DIRECTORY_SEPARATOR.'lib')) { - define('PEAR_CONFIG_DEFAULT_PHP_DIR', - PEAR_INSTALL_DIR.DIRECTORY_SEPARATOR.'lib'); - } else { - define('PEAR_CONFIG_DEFAULT_PHP_DIR', PEAR_INSTALL_DIR); - } -} - -// Default for ext_dir -if (getenv('PHP_PEAR_EXTENSION_DIR')) { - define('PEAR_CONFIG_DEFAULT_EXT_DIR', getenv('PHP_PEAR_EXTENSION_DIR')); -} else { - define('PEAR_CONFIG_DEFAULT_EXT_DIR', ini_get('extension_dir')); -} - -// Default for doc_dir -if (getenv('PHP_PEAR_DOC_DIR')) { - define('PEAR_CONFIG_DEFAULT_DOC_DIR', getenv('PHP_PEAR_DOC_DIR')); -} else { - define('PEAR_CONFIG_DEFAULT_DOC_DIR', - PEAR_INSTALL_DIR.DIRECTORY_SEPARATOR.'docs'); -} - -// Default for bin_dir -if (getenv('PHP_PEAR_BIN_DIR')) { - define('PEAR_CONFIG_DEFAULT_BIN_DIR', getenv('PHP_PEAR_BIN_DIR')); -} else { - define('PEAR_CONFIG_DEFAULT_BIN_DIR', PHP_BINDIR); -} - -// Default for data_dir -if (getenv('PHP_PEAR_DATA_DIR')) { - define('PEAR_CONFIG_DEFAULT_DATA_DIR', getenv('PHP_PEAR_DATA_DIR')); -} else { - define('PEAR_CONFIG_DEFAULT_DATA_DIR', - PEAR_INSTALL_DIR.DIRECTORY_SEPARATOR.'data'); -} - -// Default for test_dir -if (getenv('PHP_PEAR_TEST_DIR')) { - define('PEAR_CONFIG_DEFAULT_TEST_DIR', getenv('PHP_PEAR_TEST_DIR')); -} else { - define('PEAR_CONFIG_DEFAULT_TEST_DIR', - PEAR_INSTALL_DIR.DIRECTORY_SEPARATOR.'tests'); -} - -// Default for cache_dir -if (getenv('PHP_PEAR_CACHE_DIR')) { - define('PEAR_CONFIG_DEFAULT_CACHE_DIR', getenv('PHP_PEAR_CACHE_DIR')); -} else { - define('PEAR_CONFIG_DEFAULT_CACHE_DIR', - System::tmpdir() . DIRECTORY_SEPARATOR . 'pear' . - DIRECTORY_SEPARATOR . 'cache'); -} - -// Default for php_bin -if (getenv('PHP_PEAR_PHP_BIN')) { - define('PEAR_CONFIG_DEFAULT_PHP_BIN', getenv('PHP_PEAR_PHP_BIN')); -} else { - define('PEAR_CONFIG_DEFAULT_PHP_BIN', PEAR_CONFIG_DEFAULT_BIN_DIR. - DIRECTORY_SEPARATOR.'php'.(OS_WINDOWS ? '.exe' : '')); -} - -// Default for verbose -if (getenv('PHP_PEAR_VERBOSE')) { - define('PEAR_CONFIG_DEFAULT_VERBOSE', getenv('PHP_PEAR_VERBOSE')); -} else { - define('PEAR_CONFIG_DEFAULT_VERBOSE', 1); -} - -// Default for preferred_state -if (getenv('PHP_PEAR_PREFERRED_STATE')) { - define('PEAR_CONFIG_DEFAULT_PREFERRED_STATE', getenv('PHP_PEAR_PREFERRED_STATE')); -} else { - define('PEAR_CONFIG_DEFAULT_PREFERRED_STATE', 'stable'); -} - -// Default for umask -if (getenv('PHP_PEAR_UMASK')) { - define('PEAR_CONFIG_DEFAULT_UMASK', getenv('PHP_PEAR_UMASK')); -} else { - define('PEAR_CONFIG_DEFAULT_UMASK', decoct(umask())); -} - -// Default for cache_ttl -if (getenv('PHP_PEAR_CACHE_TTL')) { - define('PEAR_CONFIG_DEFAULT_CACHE_TTL', getenv('PHP_PEAR_CACHE_TTL')); -} else { - define('PEAR_CONFIG_DEFAULT_CACHE_TTL', 3600); -} - -// Default for sig_type -if (getenv('PHP_PEAR_SIG_TYPE')) { - define('PEAR_CONFIG_DEFAULT_SIG_TYPE', getenv('PHP_PEAR_SIG_TYPE')); -} else { - define('PEAR_CONFIG_DEFAULT_SIG_TYPE', 'gpg'); -} - -// Default for sig_bin -if (getenv('PHP_PEAR_SIG_BIN')) { - define('PEAR_CONFIG_DEFAULT_SIG_BIN', getenv('PHP_PEAR_SIG_BIN')); -} else { - define('PEAR_CONFIG_DEFAULT_SIG_BIN', - System::which( - 'gpg', OS_WINDOWS ? 'c:\gnupg\gpg.exe' : '/usr/local/bin/gpg')); -} - -// Default for sig_keydir -if (getenv('PHP_PEAR_SIG_KEYDIR')) { - define('PEAR_CONFIG_DEFAULT_SIG_KEYDIR', getenv('PHP_PEAR_SIG_KEYDIR')); -} else { - define('PEAR_CONFIG_DEFAULT_SIG_KEYDIR', - PEAR_CONFIG_SYSCONFDIR . DIRECTORY_SEPARATOR . 'pearkeys'); -} - -/** - * This is a class for storing configuration data, keeping track of - * which are system-defined, user-defined or defaulted. - */ -class PEAR_Config extends PEAR -{ - // {{{ properties - - /** - * Array of config files used. - * - * @var array layer => config file - */ - var $files = array( - 'system' => '', - 'user' => '', - ); - - var $layers = array(); - - /** - * Configuration data, two-dimensional array where the first - * dimension is the config layer ('user', 'system' and 'default'), - * and the second dimension is keyname => value. - * - * The order in the first dimension is important! Earlier - * layers will shadow later ones when a config value is - * requested (if a 'user' value exists, it will be returned first, - * then 'system' and finally 'default'). - * - * @var array layer => array(keyname => value, ...) - */ - var $configuration = array( - 'user' => array(), - 'system' => array(), - 'default' => array(), - ); - - /** - * Information about the configuration data. Stores the type, - * default value and a documentation string for each configuration - * value. - * - * @var array layer => array(infotype => value, ...) - */ - var $configuration_info = array( - // Internet Access - 'master_server' => array( - 'type' => 'string', - 'default' => 'pear.php.net', - 'doc' => 'name of the main PEAR server', - 'prompt' => 'PEAR server', - 'group' => 'Internet Access', - ), - 'http_proxy' => array( - 'type' => 'string', - 'default' => PEAR_CONFIG_DEFAULT_HTTP_PROXY, - 'doc' => 'HTTP proxy (host:port) to use when downloading packages', - 'prompt' => 'HTTP Proxy Server Address', - 'group' => 'Internet Access', - ), - // File Locations - 'php_dir' => array( - 'type' => 'directory', - 'default' => PEAR_CONFIG_DEFAULT_PHP_DIR, - 'doc' => 'directory where .php files are installed', - 'prompt' => 'PEAR directory', - 'group' => 'File Locations', - ), - 'ext_dir' => array( - 'type' => 'directory', - 'default' => PEAR_CONFIG_DEFAULT_EXT_DIR, - 'doc' => 'directory where loadable extensions are installed', - 'prompt' => 'PHP extension directory', - 'group' => 'File Locations', - ), - 'doc_dir' => array( - 'type' => 'directory', - 'default' => PEAR_CONFIG_DEFAULT_DOC_DIR, - 'doc' => 'directory where documentation is installed', - 'prompt' => 'PEAR documentation directory', - 'group' => 'File Locations', - ), - 'bin_dir' => array( - 'type' => 'directory', - 'default' => PEAR_CONFIG_DEFAULT_BIN_DIR, - 'doc' => 'directory where executables are installed', - 'prompt' => 'PEAR executables directory', - 'group' => 'File Locations', - ), - 'data_dir' => array( - 'type' => 'directory', - 'default' => PEAR_CONFIG_DEFAULT_DATA_DIR, - 'doc' => 'directory where data files are installed', - 'prompt' => 'PEAR data directory', - 'group' => 'File Locations (Advanced)', - ), - 'test_dir' => array( - 'type' => 'directory', - 'default' => PEAR_CONFIG_DEFAULT_TEST_DIR, - 'doc' => 'directory where regression tests are installed', - 'prompt' => 'PEAR test directory', - 'group' => 'File Locations (Advanced)', - ), - 'cache_dir' => array( - 'type' => 'directory', - 'default' => PEAR_CONFIG_DEFAULT_CACHE_DIR, - 'doc' => 'directory which is used for XMLRPC cache', - 'prompt' => 'PEAR Installer cache directory', - 'group' => 'File Locations (Advanced)', - ), - 'php_bin' => array( - 'type' => 'file', - 'default' => PEAR_CONFIG_DEFAULT_PHP_BIN, - 'doc' => 'PHP CLI/CGI binary for executing scripts', - 'prompt' => 'PHP CLI/CGI binary', - 'group' => 'File Locations (Advanced)', - ), - // Maintainers - 'username' => array( - 'type' => 'string', - 'default' => '', - 'doc' => '(maintainers) your PEAR account name', - 'prompt' => 'PEAR username (for maintainers)', - 'group' => 'Maintainers', - ), - 'password' => array( - 'type' => 'password', - 'default' => '', - 'doc' => '(maintainers) your PEAR account password', - 'prompt' => 'PEAR password (for maintainers)', - 'group' => 'Maintainers', - ), - // Advanced - 'verbose' => array( - 'type' => 'integer', - 'default' => PEAR_CONFIG_DEFAULT_VERBOSE, - 'doc' => 'verbosity level -0: really quiet -1: somewhat quiet -2: verbose -3: debug', - 'prompt' => 'Debug Log Level', - 'group' => 'Advanced', - ), - 'preferred_state' => array( - 'type' => 'set', - 'default' => PEAR_CONFIG_DEFAULT_PREFERRED_STATE, - 'doc' => 'the installer will prefer releases with this state when installing packages without a version or state specified', - 'valid_set' => array( - 'stable', 'beta', 'alpha', 'devel', 'snapshot'), - 'prompt' => 'Preferred Package State', - 'group' => 'Advanced', - ), - 'umask' => array( - 'type' => 'mask', - 'default' => PEAR_CONFIG_DEFAULT_UMASK, - 'doc' => 'umask used when creating files (Unix-like systems only)', - 'prompt' => 'Unix file mask', - 'group' => 'Advanced', - ), - 'cache_ttl' => array( - 'type' => 'integer', - 'default' => PEAR_CONFIG_DEFAULT_CACHE_TTL, - 'doc' => 'amount of secs where the local cache is used and not updated', - 'prompt' => 'Cache TimeToLive', - 'group' => 'Advanced', - ), - 'sig_type' => array( - 'type' => 'set', - 'default' => PEAR_CONFIG_DEFAULT_SIG_TYPE, - 'doc' => 'which package signature mechanism to use', - 'valid_set' => array('gpg'), - 'prompt' => 'Package Signature Type', - 'group' => 'Maintainers', - ), - 'sig_bin' => array( - 'type' => 'string', - 'default' => PEAR_CONFIG_DEFAULT_SIG_BIN, - 'doc' => 'which package signature mechanism to use', - 'prompt' => 'Signature Handling Program', - 'group' => 'Maintainers', - ), - 'sig_keyid' => array( - 'type' => 'string', - 'default' => '', - 'doc' => 'which key to use for signing with', - 'prompt' => 'Signature Key Id', - 'group' => 'Maintainers', - ), - 'sig_keydir' => array( - 'type' => 'string', - 'default' => PEAR_CONFIG_DEFAULT_SIG_KEYDIR, - 'doc' => 'which package signature mechanism to use', - 'prompt' => 'Signature Key Directory', - 'group' => 'Maintainers', - ), - ); - - // }}} - - // {{{ PEAR_Config([file], [defaults_file]) - - /** - * Constructor. - * - * @param string (optional) file to read user-defined options from - * @param string (optional) file to read system-wide defaults from - * - * @access public - * - * @see PEAR_Config::singleton - */ - function PEAR_Config($user_file = '', $system_file = '') - { - $this->PEAR(); - $sl = DIRECTORY_SEPARATOR; - if (empty($user_file)) { - if (OS_WINDOWS) { - $user_file = PEAR_CONFIG_SYSCONFDIR . $sl . 'pear.ini'; - } else { - $user_file = getenv('HOME') . $sl . '.pearrc'; - } - } - if (empty($system_file)) { - if (OS_WINDOWS) { - $system_file = PEAR_CONFIG_SYSCONFDIR . $sl . 'pearsys.ini'; - } else { - $system_file = PEAR_CONFIG_SYSCONFDIR . $sl . 'pear.conf'; - } - } - $this->layers = array_keys($this->configuration); - $this->files['user'] = $user_file; - $this->files['system'] = $system_file; - if ($user_file && file_exists($user_file)) { - $this->readConfigFile($user_file); - } - if ($system_file && file_exists($system_file)) { - $this->mergeConfigFile($system_file, false, 'system'); - } - foreach ($this->configuration_info as $key => $info) { - $this->configuration['default'][$key] = $info['default']; - } - //$GLOBALS['_PEAR_Config_instance'] = &$this; - } - - // }}} - // {{{ singleton([file], [defaults_file]) - - /** - * Static singleton method. If you want to keep only one instance - * of this class in use, this method will give you a reference to - * the last created PEAR_Config object if one exists, or create a - * new object. - * - * @param string (optional) file to read user-defined options from - * @param string (optional) file to read system-wide defaults from - * - * @return object an existing or new PEAR_Config instance - * - * @access public - * - * @see PEAR_Config::PEAR_Config - */ - function &singleton($user_file = '', $system_file = '') - { - if (is_object($GLOBALS['_PEAR_Config_instance'])) { - return $GLOBALS['_PEAR_Config_instance']; - } - $GLOBALS['_PEAR_Config_instance'] = - &new PEAR_Config($user_file, $system_file); - return $GLOBALS['_PEAR_Config_instance']; - } - - // }}} - // {{{ readConfigFile([file], [layer]) - - /** - * Reads configuration data from a file. All existing values in - * the config layer are discarded and replaced with data from the - * file. - * - * @param string (optional) file to read from, if NULL or not - * specified, the last-used file for the same layer (second param) - * is used - * - * @param string (optional) config layer to insert data into - * ('user' or 'system') - * - * @return bool TRUE on success or a PEAR error on failure - * - * @access public - */ - function readConfigFile($file = null, $layer = 'user') - { - if (empty($this->files[$layer])) { - return $this->raiseError("unknown config file type `$layer'"); - } - if ($file === null) { - $file = $this->files[$layer]; - } - $data = $this->_readConfigDataFrom($file); - if (PEAR::isError($data)) { - return $data; - } - $this->_decodeInput($data); - $this->configuration[$layer] = $data; - return true; - } - - // }}} - // {{{ mergeConfigFile(file, [override], [layer]) - - /** - * Merges data into a config layer from a file. Does the same - * thing as readConfigFile, except it does not replace all - * existing values in the config layer. - * - * @param string file to read from - * - * @param bool (optional) whether to overwrite existing data - * (default TRUE) - * - * @param string config layer to insert data into ('user' or - * 'system') - * - * @return bool TRUE on success or a PEAR error on failure - * - * @access public. - */ - function mergeConfigFile($file, $override = true, $layer = 'user') - { - if (empty($this->files[$layer])) { - return $this->raiseError("unknown config file type `$layer'"); - } - if ($file === null) { - $file = $this->files[$layer]; - } - $data = $this->_readConfigDataFrom($file); - if (PEAR::isError($data)) { - return $data; - } - $this->_decodeInput($data); - if ($override) { - $this->configuration[$layer] = array_merge($this->configuration[$layer], $data); - } else { - $this->configuration[$layer] = array_merge($data, $this->configuration[$layer]); - } - return true; - } - - // }}} - // {{{ writeConfigFile([file], [layer]) - - /** - * Writes data into a config layer from a file. - * - * @param string file to read from - * - * @param bool (optional) whether to overwrite existing data - * (default TRUE) - * - * @param string config layer to insert data into ('user' or - * 'system') - * - * @return bool TRUE on success or a PEAR error on failure - * - * @access public. - */ - function writeConfigFile($file = null, $layer = 'user') - { - if ($layer == 'both' || $layer == 'all') { - foreach ($this->files as $type => $file) { - $err = $this->writeConfigFile($file, $type); - if (PEAR::isError($err)) { - return $err; - } - } - return true; - } - if (empty($this->files[$layer])) { - return $this->raiseError("unknown config file type `$layer'"); - } - if ($file === null) { - $file = $this->files[$layer]; - } - $data = $this->configuration[$layer]; - $this->_encodeOutput($data); - if (!@System::mkDir("-p " . dirname($file))) { - return $this->raiseError("could not create directory: " . dirname($file)); - } - if (@is_file($file) && !@is_writeable($file)) { - return $this->raiseError("no write access to $file!"); - } - $fp = @fopen($file, "w"); - if (!$fp) { - return $this->raiseError("PEAR_Config::writeConfigFile fopen('$file','w') failed"); - } - $contents = "#PEAR_Config 0.9\n" . serialize($data); - if (!@fwrite($fp, $contents)) { - return $this->raiseError("PEAR_Config::writeConfigFile: fwrite failed"); - } - return true; - } - - // }}} - // {{{ _readConfigDataFrom(file) - - /** - * Reads configuration data from a file and returns the parsed data - * in an array. - * - * @param string file to read from - * - * @return array configuration data or a PEAR error on failure - * - * @access private - */ - function _readConfigDataFrom($file) - { - $fp = @fopen($file, "r"); - if (!$fp) { - return $this->raiseError("PEAR_Config::readConfigFile fopen('$file','r') failed"); - } - $size = filesize($file); - $contents = fread($fp, $size); - fclose($fp); - $version = '0.1'; - if (preg_match('/^#PEAR_Config\s+(\S+)\s+/si', $contents, $matches)) { - $version = $matches[1]; - $contents = substr($contents, strlen($matches[0])); - } - if (version_compare("$version", '1', '<')) { - $data = unserialize($contents); - if (!is_array($data)) { - if (strlen(trim($contents)) > 0) { - $error = "PEAR_Config: bad data in $file"; -// if (isset($this)) { - return $this->raiseError($error); -// } else { -// return PEAR::raiseError($error); - } else { - $data = array(); - } - } - // add parsing of newer formats here... - } else { - return $this->raiseError("$file: unknown version `$version'"); - } - return $data; - } - - // }}} - // {{{ _encodeOutput(&data) - - /** - * Encodes/scrambles configuration data before writing to files. - * Currently, 'password' values will be base64-encoded as to avoid - * that people spot cleartext passwords by accident. - * - * @param array (reference) array to encode values in - * - * @return bool TRUE on success - * - * @access private - */ - function _encodeOutput(&$data) - { - foreach ($data as $key => $value) { - if (!isset($this->configuration_info[$key])) { - continue; - } - $type = $this->configuration_info[$key]['type']; - switch ($type) { - // we base64-encode passwords so they are at least - // not shown in plain by accident - case 'password': { - $data[$key] = base64_encode($data[$key]); - break; - } - case 'mask': { - $data[$key] = octdec($data[$key]); - break; - } - } - } - return true; - } - - // }}} - // {{{ _decodeInput(&data) - - /** - * Decodes/unscrambles configuration data after reading from files. - * - * @param array (reference) array to encode values in - * - * @return bool TRUE on success - * - * @access private - * - * @see PEAR_Config::_encodeOutput - */ - function _decodeInput(&$data) - { - if (!is_array($data)) { - return true; - } - foreach ($data as $key => $value) { - if (!isset($this->configuration_info[$key])) { - continue; - } - $type = $this->configuration_info[$key]['type']; - switch ($type) { - case 'password': { - $data[$key] = base64_decode($data[$key]); - break; - } - case 'mask': { - $data[$key] = decoct($data[$key]); - break; - } - } - } - return true; - } - - // }}} - // {{{ get(key, [layer]) - - /** - * Returns a configuration value, prioritizing layers as per the - * layers property. - * - * @param string config key - * - * @return mixed the config value, or NULL if not found - * - * @access public - */ - function get($key, $layer = null) - { - if ($layer === null) { - foreach ($this->layers as $layer) { - if (isset($this->configuration[$layer][$key])) { - return $this->configuration[$layer][$key]; - } - } - } elseif (isset($this->configuration[$layer][$key])) { - return $this->configuration[$layer][$key]; - } - return null; - } - - // }}} - // {{{ set(key, value, [layer]) - - /** - * Set a config value in a specific layer (defaults to 'user'). - * Enforces the types defined in the configuration_info array. An - * integer config variable will be cast to int, and a set config - * variable will be validated against its legal values. - * - * @param string config key - * - * @param string config value - * - * @param string (optional) config layer - * - * @return bool TRUE on success, FALSE on failure - * - * @access public - */ - function set($key, $value, $layer = 'user') - { - if (empty($this->configuration_info[$key])) { - return false; - } - extract($this->configuration_info[$key]); - switch ($type) { - case 'integer': - $value = (int)$value; - break; - case 'set': { - // If a valid_set is specified, require the value to - // be in the set. If there is no valid_set, accept - // any value. - if ($valid_set) { - reset($valid_set); - if ((key($valid_set) === 0 && !in_array($value, $valid_set)) || - (key($valid_set) !== 0 && empty($valid_set[$value]))) - { - return false; - } - } - break; - } - } - $this->configuration[$layer][$key] = $value; - return true; - } - - // }}} - // {{{ getType(key) - - /** - * Get the type of a config value. - * - * @param string config key - * - * @return string type, one of "string", "integer", "file", - * "directory", "set" or "password". - * - * @access public - * - */ - function getType($key) - { - if (isset($this->configuration_info[$key])) { - return $this->configuration_info[$key]['type']; - } - return false; - } - - // }}} - // {{{ getDocs(key) - - /** - * Get the documentation for a config value. - * - * @param string config key - * - * @return string documentation string - * - * @access public - * - */ - function getDocs($key) - { - if (isset($this->configuration_info[$key])) { - return $this->configuration_info[$key]['doc']; - } - return false; - } - // }}} - // {{{ getPrompt(key) - - /** - * Get the short documentation for a config value. - * - * @param string config key - * - * @return string short documentation string - * - * @access public - * - */ - function getPrompt($key) - { - if (isset($this->configuration_info[$key])) { - return $this->configuration_info[$key]['prompt']; - } - return false; - } - // }}} - // {{{ getGroup(key) - - /** - * Get the parameter group for a config key. - * - * @param string config key - * - * @return string parameter group - * - * @access public - * - */ - function getGroup($key) - { - if (isset($this->configuration_info[$key])) { - return $this->configuration_info[$key]['group']; - } - return false; - } - - // }}} - // {{{ getGroups() - - /** - * Get the list of parameter groups. - * - * @return array list of parameter groups - * - * @access public - * - */ - function getGroups() - { - $tmp = array(); - foreach ($this->configuration_info as $key => $info) { - $tmp[$info['group']] = 1; - } - return array_keys($tmp); - } - - // }}} - // {{{ getGroupKeys() - - /** - * Get the list of the parameters in a group. - * - * @param string $group parameter group - * - * @return array list of parameters in $group - * - * @access public - * - */ - function getGroupKeys($group) - { - $keys = array(); - foreach ($this->configuration_info as $key => $info) { - if ($info['group'] == $group) { - $keys[] = $key; - } - } - return $keys; - } - - // }}} - // {{{ getSetValues(key) - - /** - * Get the list of allowed set values for a config value. Returns - * NULL for config values that are not sets. - * - * @param string config key - * - * @return array enumerated array of set values, or NULL if the - * config key is unknown or not a set - * - * @access public - * - */ - function getSetValues($key) - { - if (isset($this->configuration_info[$key]) && - isset($this->configuration_info[$key]['type']) && - $this->configuration_info[$key]['type'] == 'set') - { - $valid_set = $this->configuration_info[$key]['valid_set']; - reset($valid_set); - if (key($valid_set) === 0) { - return $valid_set; - } - return array_keys($valid_set); - } - return false; - } - - // }}} - // {{{ getKeys() - - /** - * Get all the current config keys. - * - * @return array simple array of config keys - * - * @access public - */ - function getKeys() - { - $keys = array(); - foreach ($this->layers as $layer) { - $keys = array_merge($keys, $this->configuration[$layer]); - } - return array_keys($keys); - } - - // }}} - // {{{ remove(key, [layer]) - - /** - * Remove the a config key from a specific config layer. - * - * @param string config key - * - * @param string (optional) config layer - * - * @return bool TRUE on success, FALSE on failure - * - * @access public - */ - function remove($key, $layer = 'user') - { - if (isset($this->configuration[$layer][$key])) { - unset($this->configuration[$layer][$key]); - return true; - } - return false; - } - - // }}} - // {{{ removeLayer(layer) - - /** - * Temporarily remove an entire config layer. USE WITH CARE! - * - * @param string config key - * - * @param string (optional) config layer - * - * @return bool TRUE on success, FALSE on failure - * - * @access public - */ - function removeLayer($layer) - { - if (isset($this->configuration[$layer])) { - unset($this->configuration[$layer]); - return true; - } - return false; - } - - // }}} - // {{{ store([layer]) - - /** - * Stores configuration data in a layer. - * - * @param string config layer to store - * - * @return bool TRUE on success, or PEAR error on failure - * - * @access public - */ - function store($layer = 'user') - { - return $this->writeConfigFile(null, $layer); - } - - // }}} - // {{{ toDefault(key) - - /** - * Unset the user-defined value of a config key, reverting the - * value to the system-defined one. - * - * @param string config key - * - * @return bool TRUE on success, FALSE on failure - * - * @access public - */ - function toDefault($key) - { - trigger_error("PEAR_Config::toDefault() deprecated, use PEAR_Config::remove() instead", E_USER_NOTICE); - return $this->remove($key, 'user'); - } - - // }}} - // {{{ definedBy(key) - - /** - * Tells what config layer that gets to define a key. - * - * @param string config key - * - * @return string the config layer, or an empty string if not found - * - * @access public - */ - function definedBy($key) - { - foreach ($this->layers as $layer) { - if (isset($this->configuration[$layer][$key])) { - return $layer; - } - } - return ''; - } - - // }}} - // {{{ isDefaulted(key) - - /** - * Tells whether a config value has a system-defined value. - * - * @param string config key - * - * @return bool - * - * @access public - * - * @deprecated - */ - function isDefaulted($key) - { - trigger_error("PEAR_Config::isDefaulted() deprecated, use PEAR_Config::definedBy() instead", E_USER_NOTICE); - return $this->definedBy($key) == 'system'; - } - - // }}} - // {{{ isDefined(key) - - /** - * Tells whether a given key exists as a config value. - * - * @param string config key - * - * @return bool whether exists in this object - * - * @access public - */ - function isDefined($key) - { - foreach ($this->layers as $layer) { - if (isset($this->configuration[$layer][$key])) { - return true; - } - } - return false; - } - - // }}} - // {{{ isDefinedLayer(key) - - /** - * Tells whether a given config layer exists. - * - * @param string config layer - * - * @return bool whether exists in this object - * - * @access public - */ - function isDefinedLayer($layer) - { - return isset($this->configuration[$layer]); - } - - // }}} - // {{{ getLayers() - - /** - * Returns the layers defined (except the 'default' one) - * - * @return array of the defined layers - */ - function getLayers() - { - $cf = $this->configuration; - unset($cf['default']); - return array_keys($cf); - } - - // }}} -} - -?> diff --git a/gulliver/thirdparty/pear/PEAR/Dependency.php b/gulliver/thirdparty/pear/PEAR/Dependency.php deleted file mode 100644 index b4ae1599f..000000000 --- a/gulliver/thirdparty/pear/PEAR/Dependency.php +++ /dev/null @@ -1,356 +0,0 @@ - | -// | Stig Bakken | -// +----------------------------------------------------------------------+ -// -// $Id: Dependency.php,v 1.20 2003/05/15 19:44:32 mj Exp $ - -require_once "PEAR.php"; - -define('PEAR_DEPENDENCY_MISSING', -1); -define('PEAR_DEPENDENCY_CONFLICT', -2); -define('PEAR_DEPENDENCY_UPGRADE_MINOR', -3); -define('PEAR_DEPENDENCY_UPGRADE_MAJOR', -4); -define('PEAR_DEPENDENCY_BAD_DEPENDENCY', -5); - -/** - * Dependency check for PEAR packages - * - * The class is based on the dependency RFC that can be found at - * http://cvs.php.net/cvs.php/pearweb/rfc. It requires PHP >= 4.1 - * - * @author Tomas V.V.Vox - * @author Stig Bakken - */ -class PEAR_Dependency -{ - /** - * Constructor - * - * @access public - * @param object Registry object - * @return void - */ - function PEAR_Dependency(&$registry) - { - $this->registry = &$registry; - } - - /** - * This method maps the XML dependency definition to the - * corresponding one from PEAR_Dependency - * - * $opts => Array - * ( - * [type] => pkg - * [rel] => ge - * [version] => 3.4 - * [name] => HTML_Common - * ) - * - * @param string Error message - * @param array Options - * @return boolean - */ - function callCheckMethod(&$errmsg, $opts) - { - $rel = isset($opts['rel']) ? $opts['rel'] : 'has'; - $req = isset($opts['version']) ? $opts['version'] : null; - $name = isset($opts['name']) ? $opts['name'] : null; - $errmsg = ''; - switch ($opts['type']) { - case 'pkg': - return $this->checkPackage($errmsg, $name, $req, $rel); - break; - case 'ext': - return $this->checkExtension($errmsg, $name, $req, $rel); - break; - case 'php': - return $this->checkPHP($errmsg, $req, $rel); - break; - case 'prog': - return $this->checkProgram($errmsg, $name); - break; - case 'os': - return $this->checkOS($errmsg, $name); - break; - case 'sapi': - return $this->checkSAPI($errmsg, $name); - break; - case 'zend': - return $this->checkZend($errmsg, $name); - break; - default: - return "'{$opts['type']}' dependency type not supported"; - } - } - - /** - * Package dependencies check method - * - * @param string $name Name of the package to test - * @param string $version The package version required - * @param string $relation How to compare versions with eachother - * - * @return mixed bool false if no error or the error string - */ - function checkPackage(&$errmsg, $name, $req = null, $relation = 'has') - { - if (substr($relation, 0, 2) == 'v.') { - $relation = substr($relation, 2); - } - switch ($relation) { - case 'has': - if (!$this->registry->packageExists($name)) { - $errmsg = "requires package `$name'"; - return PEAR_DEPENDENCY_MISSING; - } - return false; - case 'not': - if (!$this->registry->packageExists($name)) { - $errmsg = "conflicts with package `$name'"; - return PEAR_DEPENDENCY_CONFLICT; - } - return false; - case 'lt': - case 'le': - case 'eq': - case 'ne': - case 'ge': - case 'gt': - $version = $this->registry->packageInfo($name, 'version'); - if (!$this->registry->packageExists($name) - || !version_compare("$version", "$req", $relation)) - { - $errmsg = "requires package `$name' " . - $this->signOperator($relation) . " $req"; - $code = $this->codeFromRelation($relation, $version, $req); - } - return false; - } - $errmsg = "relation '$relation' with requirement '$req' is not supported (name=$name)"; - return PEAR_DEPENDENCY_BAD_DEPENDENCY; - } - - /** - * Extension dependencies check method - * - * @param string $name Name of the extension to test - * @param string $req_ext_ver Required extension version to compare with - * @param string $relation How to compare versions with eachother - * - * @return mixed bool false if no error or the error string - */ - function checkExtension(&$errmsg, $name, $req = null, $relation = 'has') - { - // XXX (ssb): could we avoid loading the extension here? - if (!PEAR::loadExtension($name)) { - $errmsg = "'$name' PHP extension is not installed"; - return PEAR_DEPENDENCY_MISSING; - } - if ($relation == 'has') { - return false; - } - $code = false; - if (substr($relation, 0, 2) == 'v.') { - $ext_ver = phpversion($name); - $operator = substr($relation, 2); - // Force params to be strings, otherwise the comparation will fail (ex. 0.9==0.90) - settype($req, "string"); - if (!version_compare("$ext_ver", "$req", $operator)) { - $retval = "'$name' PHP extension version " . - $this->signOperator($operator) . " $req is required"; - $code = $this->codeFromRelation($relation, $ext_ver, $req); - } - } - return $code; - } - - /** - * Operating system dependencies check method - * - * @param string $os Name of the operating system - * - * @return mixed bool false if no error or the error string - */ - function checkOS(&$errmsg, $os) - { - // XXX Fixme: Implement a more flexible way, like - // comma separated values or something similar to PEAR_OS - static $myos; - if (empty($myos)) { - include_once "OS/Guess.php"; - $myos = new OS_Guess(); - } - // only 'has' relation is currently supported - if ($myos->matchSignature($os)) { - return false; - } - $errmsg = "'$os' operating system not supported"; - return PEAR_DEPENDENCY_CONFLICT; - } - - /** - * PHP version check method - * - * @param string $req which version to compare - * @param string $relation how to compare the version - * - * @return mixed bool false if no error or the error string - */ - function checkPHP(&$errmsg, $req, $relation = 'ge') - { - if (substr($req, 0, 2) == 'v.') { - $req = substr($req,2, strlen($req) - 2); - } - $php_ver = phpversion(); - $operator = substr($relation,0,2); - if (!version_compare("$php_ver", "$req", $operator)) { - $errmsg = "PHP version " . $this->signOperator($operator) . - " $req is required"; - return PEAR_DEPENDENCY_CONFLICT; - } - return false; - } - - /** - * External program check method. Looks for executable files in - * directories listed in the PATH environment variable. - * - * @param string $program which program to look for - * - * @return mixed bool false if no error or the error string - */ - function checkProgram(&$errmsg, $program) - { - // XXX FIXME honor safe mode - $path_delim = OS_WINDOWS ? ';' : ':'; - $exe_suffix = OS_WINDOWS ? '.exe' : ''; - $path_elements = explode($path_delim, getenv('PATH')); - foreach ($path_elements as $dir) { - $file = $dir . DIRECTORY_SEPARATOR . $program . $exe_suffix; - if (@file_exists($file) && @is_executable($file)) { - return false; - } - } - $errmsg = "'$program' program is not present in the PATH"; - return PEAR_DEPENDENCY_MISSING; - } - - /** - * SAPI backend check method. Version comparison is not yet - * available here. - * - * @param string $name name of SAPI backend - * @param string $req which version to compare - * @param string $relation how to compare versions (currently - * hardcoded to 'has') - * @return mixed bool false if no error or the error string - */ - function checkSAPI(&$errmsg, $name, $req = null, $relation = 'has') - { - // XXX Fixme: There is no way to know if the user has or - // not other SAPI backends installed than the installer one - - $sapi_backend = php_sapi_name(); - // Version comparisons not supported, sapi backends don't have - // version information yet. - if ($sapi_backend == $name) { - return false; - } - $errmsg = "'$sapi_backend' SAPI backend not supported"; - return PEAR_DEPENDENCY_CONFLICT; - } - - - /** - * Zend version check method - * - * @param string $req which version to compare - * @param string $relation how to compare the version - * - * @return mixed bool false if no error or the error string - */ - function checkZend(&$errmsg, $req, $relation = 'ge') - { - if (substr($req, 0, 2) == 'v.') { - $req = substr($req,2, strlen($req) - 2); - } - $zend_ver = zend_version(); - $operator = substr($relation,0,2); - if (!version_compare("$zend_ver", "$req", $operator)) { - $errmsg = "Zend version " . $this->signOperator($operator) . - " $req is required"; - return PEAR_DEPENDENCY_CONFLICT; - } - return false; - } - - /** - * Converts text comparing operators to them sign equivalents - * - * Example: 'ge' to '>=' - * - * @access public - * @param string Operator - * @return string Sign equivalent - */ - function signOperator($operator) - { - switch($operator) { - case 'lt': return '<'; - case 'le': return '<='; - case 'gt': return '>'; - case 'ge': return '>='; - case 'eq': return '=='; - case 'ne': return '!='; - default: - return $operator; - } - } - - /** - * Convert relation into corresponding code - * - * @access public - * @param string Relation - * @param string Version - * @param string Requirement - * @return integer - */ - function codeFromRelation($relation, $version, $req) - { - $code = PEAR_DEPENDENCY_BAD_DEPENDENCY; - switch ($relation) { - case 'gt': case 'ge': case 'eq': - // upgrade - $have_major = preg_replace('/\D.*/', '', $version); - $need_major = preg_replace('/\D.*/', '', $req); - if ($need_major > $have_major) { - $code = PEAR_DEPENDENCY_UPGRADE_MAJOR; - } else { - $code = PEAR_DEPENDENCY_UPGRADE_MINOR; - } - break; - case 'lt': case 'le': case 'ne': - $code = PEAR_DEPENDENCY_CONFLICT; - break; - } - return $code; - } -} -?> diff --git a/gulliver/thirdparty/pear/PEAR/Frontend/CLI.php b/gulliver/thirdparty/pear/PEAR/Frontend/CLI.php deleted file mode 100644 index 67c15b9ea..000000000 --- a/gulliver/thirdparty/pear/PEAR/Frontend/CLI.php +++ /dev/null @@ -1,506 +0,0 @@ - | - +----------------------------------------------------------------------+ - - $Id: CLI.php,v 1.31 2003/04/03 23:12:40 ssb Exp $ -*/ - -require_once "PEAR.php"; - -class PEAR_Frontend_CLI extends PEAR -{ - // {{{ properties - - /** - * What type of user interface this frontend is for. - * @var string - * @access public - */ - var $type = 'CLI'; - var $lp = ''; // line prefix - - var $params = array(); - var $term = array( - 'bold' => '', - 'normal' => '', - ); - - // }}} - - // {{{ constructor - - function PEAR_Frontend_CLI() - { - parent::PEAR(); - $term = getenv('TERM'); //(cox) $_ENV is empty for me in 4.1.1 - if ($term) { - // XXX can use ncurses extension here, if available - if (preg_match('/^(xterm|vt220|linux)/', $term)) { - $this->term['bold'] = sprintf("%c%c%c%c", 27, 91, 49, 109); - $this->term['normal']=sprintf("%c%c%c", 27, 91, 109); - } elseif (preg_match('/^vt100/', $term)) { - $this->term['bold'] = sprintf("%c%c%c%c%c%c", 27, 91, 49, 109, 0, 0); - $this->term['normal']=sprintf("%c%c%c%c%c", 27, 91, 109, 0, 0); - } - } elseif (OS_WINDOWS) { - // XXX add ANSI codes here - } - } - - // }}} - - // {{{ displayLine(text) - - function displayLine($text) - { - trigger_error("PEAR_Frontend_CLI::displayLine deprecated", E_USER_ERROR); - } - - function _displayLine($text) - { - $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.inputfilter.php'); - $filter = new InputFilter(); - $text = $filter->xssFilterHard($text); - print "$this->lp$text\n"; - } - - // }}} - // {{{ display(text) - - function display($text) - { - trigger_error("PEAR_Frontend_CLI::display deprecated", E_USER_ERROR); - } - - function _display($text) - { - print $text; - } - - // }}} - // {{{ displayError(eobj) - - function displayError($eobj) - { - return $this->_displayLine($eobj->getMessage()); - } - - // }}} - // {{{ displayFatalError(eobj) - - function displayFatalError($eobj) - { - $this->displayError($eobj); - exit(1); - } - - // }}} - // {{{ displayHeading(title) - - function displayHeading($title) - { - trigger_error("PEAR_Frontend_CLI::displayHeading deprecated", E_USER_ERROR); - } - - function _displayHeading($title) - { - print $this->lp.$this->bold($title)."\n"; - print $this->lp.str_repeat("=", strlen($title))."\n"; - } - - // }}} - // {{{ userDialog(prompt, [type], [default]) - - function userDialog($command, $prompts, $types = array(), $defaults = array()) - { - $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.inputfilter.php'); - $filter = new InputFilter(); - $result = array(); - if (is_array($prompts)) { - $fp = fopen("php://stdin", "r"); - foreach ($prompts as $key => $prompt) { - $type = $types[$key]; - $default = @$defaults[$key]; - $default = $filter->xssFilterHard($default); - if ($type == 'password') { - system('stty -echo'); - } - $prompt = $filter->xssFilterHard($prompt); - print "$this->lp$prompt "; - if ($default) { - print "[$default] "; - } - print ": "; - $line = fgets($fp, 2048); - if ($type == 'password') { - system('stty echo'); - print "\n"; - } - if ($default && trim($line) == "") { - $result[$key] = $default; - } else { - $result[$key] = $line; - } - } - fclose($fp); - } - return $result; - } - - // }}} - // {{{ userConfirm(prompt, [default]) - - function userConfirm($prompt, $default = 'yes') - { - trigger_error("PEAR_Frontend_CLI::userConfirm not yet converted", E_USER_ERROR); - static $positives = array('y', 'yes', 'on', '1'); - static $negatives = array('n', 'no', 'off', '0'); - print "$this->lp$prompt [$default] : "; - $fp = fopen("php://stdin", "r"); - $line = fgets($fp, 2048); - fclose($fp); - $answer = strtolower(trim($line)); - if (empty($answer)) { - $answer = $default; - } - if (in_array($answer, $positives)) { - return true; - } - if (in_array($answer, $negatives)) { - return false; - } - if (in_array($default, $positives)) { - return true; - } - return false; - } - - // }}} - // {{{ startTable([params]) - - function startTable($params = array()) - { - trigger_error("PEAR_Frontend_CLI::startTable deprecated", E_USER_ERROR); - } - - function _startTable($params = array()) - { - $params['table_data'] = array(); - $params['widest'] = array(); // indexed by column - $params['highest'] = array(); // indexed by row - $params['ncols'] = 0; - $this->params = $params; - } - - // }}} - // {{{ tableRow(columns, [rowparams], [colparams]) - - function tableRow($columns, $rowparams = array(), $colparams = array()) - { - trigger_error("PEAR_Frontend_CLI::tableRow deprecated", E_USER_ERROR); - } - - function _tableRow($columns, $rowparams = array(), $colparams = array()) - { - $highest = 1; - for ($i = 0; $i < sizeof($columns); $i++) { - $col = &$columns[$i]; - if (isset($colparams[$i]) && !empty($colparams[$i]['wrap'])) { - $col = wordwrap($col, $colparams[$i]['wrap'], "\n", 1); - } - if (strpos($col, "\n") !== false) { - $multiline = explode("\n", $col); - $w = 0; - foreach ($multiline as $n => $line) { - if (strlen($line) > $w) { - $w = strlen($line); - } - } - $lines = sizeof($multiline); - } else { - $w = strlen($col); - } - if ($w > @$this->params['widest'][$i]) { - $this->params['widest'][$i] = $w; - } - $tmp = count_chars($columns[$i], 1); - // handle unix, mac and windows formats - $lines = (isset($tmp[10]) ? $tmp[10] : @$tmp[13]) + 1; - if ($lines > $highest) { - $highest = $lines; - } - } - if (sizeof($columns) > $this->params['ncols']) { - $this->params['ncols'] = sizeof($columns); - } - $new_row = array( - 'data' => $columns, - 'height' => $highest, - 'rowparams' => $rowparams, - 'colparams' => $colparams, - ); - $this->params['table_data'][] = $new_row; - } - - // }}} - // {{{ endTable() - - function endTable() - { - trigger_error("PEAR_Frontend_CLI::endTable deprecated", E_USER_ERROR); - } - - function _endTable() - { - extract($this->params); - if (!empty($caption)) { - $this->_displayHeading($caption); - } - if (count($table_data) == 0) { - return; - } - if (!isset($width)) { - $width = $widest; - } else { - for ($i = 0; $i < $ncols; $i++) { - if (!isset($width[$i])) { - $width[$i] = $widest[$i]; - } - } - } - $border = false; - if (empty($border)) { - $cellstart = ''; - $cellend = ' '; - $rowend = ''; - $padrowend = false; - $borderline = ''; - } else { - $cellstart = '| '; - $cellend = ' '; - $rowend = '|'; - $padrowend = true; - $borderline = '+'; - foreach ($width as $w) { - $borderline .= str_repeat('-', $w + strlen($cellstart) + strlen($cellend) - 1); - $borderline .= '+'; - } - } - if ($borderline) { - $this->_displayLine($borderline); - } - for ($i = 0; $i < sizeof($table_data); $i++) { - extract($table_data[$i]); - $rowlines = array(); - if ($height > 1) { - for ($c = 0; $c < sizeof($data); $c++) { - $rowlines[$c] = preg_split('/(\r?\n|\r)/', $data[$c]); - if (sizeof($rowlines[$c]) < $height) { - $rowlines[$c] = array_pad($rowlines[$c], $height, ''); - } - } - } else { - for ($c = 0; $c < sizeof($data); $c++) { - $rowlines[$c] = array($data[$c]); - } - } - for ($r = 0; $r < $height; $r++) { - $rowtext = ''; - for ($c = 0; $c < sizeof($data); $c++) { - if (isset($colparams[$c])) { - $attribs = array_merge($rowparams, $colparams); - } else { - $attribs = $rowparams; - } - $w = isset($width[$c]) ? $width[$c] : 0; - //$cell = $data[$c]; - $cell = $rowlines[$c][$r]; - $l = strlen($cell); - if ($l > $w) { - $cell = substr($cell, 0, $w); - } - if (isset($attribs['bold'])) { - $cell = $this->bold($cell); - } - if ($l < $w) { - // not using str_pad here because we may - // add bold escape characters to $cell - $cell .= str_repeat(' ', $w - $l); - } - - $rowtext .= $cellstart . $cell . $cellend; - } - $rowtext .= $rowend; - $this->_displayLine($rowtext); - } - } - if ($borderline) { - $this->_displayLine($borderline); - } - } - - // }}} - // {{{ outputData() - - function outputData($data, $command = '_default') - { - switch ($command) - { - case 'install': - case 'upgrade': - case 'upgrade-all': - if (isset($data['release_warnings'])) { - $this->_displayLine(''); - $this->_startTable(array( - 'border' => false, - 'caption' => 'Release Warnings' - )); - $this->_tableRow(array($data['release_warnings']), null, array(1 => array('wrap' => 55))); - $this->_endTable(); - $this->_displayLine(''); - }; - $this->_displayLine($data['data']); - break; - case 'search': - $this->_startTable($data); - if (isset($data['headline']) && is_array($data['headline'])) - $this->_tableRow($data['headline'], array('bold' => true), array(1 => array('wrap' => 55))); - - foreach($data['data'] as $category) { - foreach($category as $pkg) { - $this->_tableRow($pkg, null, array(1 => array('wrap' => 55))); - } - }; - $this->_endTable(); - break; - case 'list-all': - $this->_startTable($data); - if (isset($data['headline']) && is_array($data['headline'])) - $this->_tableRow($data['headline'], array('bold' => true), array(1 => array('wrap' => 55))); - - foreach($data['data'] as $category) { - foreach($category as $pkg) { - unset($pkg[3]); - unset($pkg[4]); - $this->_tableRow($pkg, null, array(1 => array('wrap' => 55))); - } - }; - $this->_endTable(); - break; - case 'config-show': - $data['border'] = false; - $opts = array(0 => array('wrap' => 30), - 1 => array('wrap' => 20), - 2 => array('wrap' => 35)); - $this->_startTable($data); - if (isset($data['headline']) && is_array($data['headline'])) { - $this->_tableRow($data['headline'], - array('bold' => true), - $opts); - } - foreach($data['data'] as $group) { - foreach($group as $value) { - if ($value[2] == '') { - $value[2] = ""; - } - $this->_tableRow($value, null, $opts); - } - } - $this->_endTable(); - break; - case 'remote-info': - $data = array( - 'caption' => 'Package details:', - 'border' => false, - 'data' => array( - array("Latest", $data['stable']), - array("Installed", $data['installed']), - array("Package", $data['name']), - array("License", $data['license']), - array("Category", $data['category']), - array("Summary", $data['summary']), - array("Description", $data['description']), - ), - ); - default: { - if (is_array($data)) - { - $this->_startTable($data); - $count = count($data['data'][0]); - if ($count == 2) { - $opts = array(0 => array('wrap' => 25), - 1 => array('wrap' => 48) - ); - } elseif ($count == 3) { - $opts = array(0 => array('wrap' => 20), - 1 => array('wrap' => 20), - 2 => array('wrap' => 35) - ); - } - if (isset($data['headline']) && is_array($data['headline'])) { - $this->_tableRow($data['headline'], - array('bold' => true), - $opts); - } - foreach($data['data'] as $row) { - $this->_tableRow($row, null, $opts); - } - $this->_endTable(); - } else { - $this->_displayLine($data); - } - } - } - } - - // }}} - // {{{ log(text) - - - function log($text) - { - return $this->_displayLine($text); - } - - - // }}} - // {{{ bold($text) - - function bold($text) - { - if (empty($this->term['bold'])) { - return strtoupper($text); - } - return $this->term['bold'] . $text . $this->term['normal']; - } - - // }}} -} - -?> diff --git a/gulliver/thirdparty/pear/PEAR/Installer.php b/gulliver/thirdparty/pear/PEAR/Installer.php deleted file mode 100644 index 0e7f9d7fa..000000000 --- a/gulliver/thirdparty/pear/PEAR/Installer.php +++ /dev/null @@ -1,897 +0,0 @@ - | -// | Tomas V.V.Cox | -// +----------------------------------------------------------------------+ -// -// $Id: Installer.php,v 1.86 2003/03/18 12:06:06 ssb Exp $ - -require_once 'PEAR/Common.php'; -require_once 'PEAR/Registry.php'; -require_once 'PEAR/Dependency.php'; -require_once 'System.php'; - -define('PEAR_INSTALLER_OK', 1); -define('PEAR_INSTALLER_FAILED', 0); -define('PEAR_INSTALLER_SKIPPED', -1); - -/** - * Administration class used to install PEAR packages and maintain the - * installed package database. - * - * TODO: - * - Check dependencies break on package uninstall (when no force given) - * - add a guessInstallDest() method with the code from _installFile() and - * use that method in Registry::_rebuildFileMap() & Command_Registry::doList(), - * others.. - * - * @since PHP 4.0.2 - * @author Stig Bakken - */ -class PEAR_Installer extends PEAR_Common -{ - // {{{ properties - - /** name of the package directory, for example Foo-1.0 - * @var string - */ - var $pkgdir; - - /** directory where PHP code files go - * @var string - */ - var $phpdir; - - /** directory where PHP extension files go - * @var string - */ - var $extdir; - - /** directory where documentation goes - * @var string - */ - var $docdir; - - /** installation root directory (ala PHP's INSTALL_ROOT or - * automake's DESTDIR - * @var string - */ - var $installroot = ''; - - /** debug level - * @var int - */ - var $debug = 1; - - /** temporary directory - * @var string - */ - var $tmpdir; - - /** PEAR_Registry object used by the installer - * @var object - */ - var $registry; - - /** List of file transactions queued for an install/upgrade/uninstall. - * - * Format: - * array( - * 0 => array("rename => array("from-file", "to-file")), - * 1 => array("delete" => array("file-to-delete")), - * ... - * ) - * - * @var array - */ - var $file_operations = array(); - - // }}} - - // {{{ constructor - - /** - * PEAR_Installer constructor. - * - * @param object $ui user interface object (instance of PEAR_Frontend_*) - * - * @access public - */ - function PEAR_Installer(&$ui) - { - parent::PEAR_Common(); - $this->setFrontendObject($ui); - $this->debug = $this->config->get('verbose'); - $this->registry = &new PEAR_Registry($this->config->get('php_dir')); - } - - // }}} - - // {{{ _deletePackageFiles() - - /** - * Delete a package's installed files, remove empty directories. - * - * @param string $package package name - * - * @return bool TRUE on success, or a PEAR error on failure - * - * @access private - */ - function _deletePackageFiles($package) - { - if (!strlen($package)) { - return $this->raiseError("No package to uninstall given"); - } - $filelist = $this->registry->packageInfo($package, 'filelist'); - if ($filelist == null) { - return $this->raiseError("$package not installed"); - } - foreach ($filelist as $file => $props) { - if (empty($props['installed_as'])) { - continue; - } - $path = $this->_prependPath($props['installed_as'], $this->installroot); - $this->addFileOperation('delete', array($path)); - } - return true; - } - - // }}} - // {{{ _installFile() - - function _installFile($file, $atts, $tmp_path) - { - static $os; - if (isset($atts['platform'])) { - if (empty($os)) { - include_once "OS/Guess.php"; - $os = new OS_Guess(); - } - // return if this file is meant for another platform - if (!$os->matchSignature($atts['platform'])) { - $this->log(3, "skipped $file (meant for $atts[platform], we are ".$os->getSignature().")"); - return PEAR_INSTALLER_SKIPPED; - } - } - - switch ($atts['role']) { - case 'doc': - case 'data': - case 'test': - $dest_dir = $this->config->get($atts['role'] . '_dir') . - DIRECTORY_SEPARATOR . $this->pkginfo['package']; - unset($atts['baseinstalldir']); - break; - case 'ext': - case 'php': - $dest_dir = $this->config->get($atts['role'] . '_dir'); - break; - case 'script': - $dest_dir = $this->config->get('bin_dir'); - break; - case 'src': - case 'extsrc': - $this->source_files++; - return; - default: - return $this->raiseError("Invalid role `$atts[role]' for file $file"); - } - if (!empty($atts['baseinstalldir'])) { - $dest_dir .= DIRECTORY_SEPARATOR . $atts['baseinstalldir']; - } - if (dirname($file) != '.' && empty($atts['install-as'])) { - $dest_dir .= DIRECTORY_SEPARATOR . dirname($file); - } - if (empty($atts['install-as'])) { - $dest_file = $dest_dir . DIRECTORY_SEPARATOR . basename($file); - } else { - $dest_file = $dest_dir . DIRECTORY_SEPARATOR . $atts['install-as']; - } - $orig_file = $tmp_path . DIRECTORY_SEPARATOR . $file; - - // Clean up the DIRECTORY_SEPARATOR mess - $ds2 = DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR; - list($dest_file, $orig_file) = preg_replace(array('!\\\\+!', '!/!', "!$ds2+!"), - DIRECTORY_SEPARATOR, - array($dest_file, $orig_file)); - $installed_as = $dest_file; - $final_dest_file = $this->_prependPath($dest_file, $this->installroot); - $dest_dir = dirname($final_dest_file); - $dest_file = $dest_dir . DIRECTORY_SEPARATOR . '.tmp' . basename($final_dest_file); - if (!@is_dir($dest_dir)) { - if (!$this->mkDirHier($dest_dir)) { - return $this->raiseError("failed to mkdir $dest_dir", - PEAR_INSTALLER_FAILED); - } - $this->log(3, "+ mkdir $dest_dir"); - } - if (empty($atts['replacements'])) { - if (!@copy($orig_file, $dest_file)) { - return $this->raiseError("failed to write $dest_file", - PEAR_INSTALLER_FAILED); - } - $this->log(3, "+ cp $orig_file $dest_file"); - if (isset($atts['md5sum'])) { - $md5sum = md5_file($dest_file); - } - } else { - $fp = fopen($orig_file, "r"); - $contents = fread($fp, filesize($orig_file)); - fclose($fp); - 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 (isset($atts['md5sum'])) { - $md5sum = G::encryptOld($contents); - } - - G::LoadSystem('inputfilter'); - $filter = new InputFilter(); - - $subst_from = $subst_to = array(); - foreach ($atts['replacements'] as $a) { - $to = ''; - if ($a['type'] == 'php-const') { - if (preg_match('/^[a-z0-9_]+$/i', $a['to'])) { - $a['to'] = $filter->validateInput($a['to']); - eval("\$to = $a[to];"); - } else { - $this->log(0, "invalid php-const replacement: $a[to]"); - continue; - } - } elseif ($a['type'] == 'pear-config') { - $to = $this->config->get($a['to']); - } elseif ($a['type'] == 'package-info') { - $to = $this->pkginfo[$a['to']]; - } - if ($to) { - $subst_from[] = $a['from']; - $subst_to[] = $to; - } - } - $this->log(3, "doing ".sizeof($subst_from)." substitution(s) for $final_dest_file"); - if (sizeof($subst_from)) { - $contents = str_replace($subst_from, $subst_to, $contents); - } - $wp = @fopen($dest_file, "w"); - if (!is_resource($wp)) { - return $this->raiseError("failed to create $dest_file: $php_errormsg", - PEAR_INSTALLER_FAILED); - } - if (!fwrite($wp, $contents)) { - return $this->raiseError("failed writing to $dest_file: $php_errormsg", - PEAR_INSTALLER_FAILED); - } - fclose($wp); - } - if (isset($md5sum)) { - if ($md5sum == $atts['md5sum']) { - $this->log(3, "md5sum ok: $final_dest_file"); - } else { - $this->log(0, "warning : bad md5sum for file $final_dest_file"); - } - } - if (!OS_WINDOWS) { - if ($atts['role'] == 'script') { - $mode = 0777 & ~(int)octdec($this->config->get('umask')); - $this->log(3, "+ chmod +x $dest_file"); - } else { - $mode = 0666 & ~(int)octdec($this->config->get('umask')); - } - $this->addFileOperation("chmod", array($mode, $dest_file)); - if (!@chmod($dest_file, $mode)) { - $this->log(0, "failed to change mode of $dest_file"); - } - } - $this->addFileOperation("rename", array($dest_file, $final_dest_file)); - - // XXX SHOULD BE DONE ONLY AFTER COMMIT - // Store the full path where the file was installed for easy unistall - $this->pkginfo['filelist'][$file]['installed_as'] = $installed_as; - - //$this->log(2, "installed: $dest_file"); - return PEAR_INSTALLER_OK; - } - - // }}} - // {{{ addFileOperation() - - function addFileOperation($type, $data) - { - if ($type == 'chmod') { - $octmode = decoct($data[0]); - $this->log(3, "adding to transaction: $type $octmode $data[1]"); - } else { - $this->log(3, "adding to transaction: $type " . implode(" ", $data)); - } - $this->file_operations[] = array($type, $data); - } - - // }}} - // {{{ startFileTransaction() - - function startFileTransaction($rollback_in_case = false) - { - if (count($this->file_operations) && $rollback_in_case) { - $this->rollbackFileTransaction(); - } - $this->file_operations = array(); - } - - // }}} - // {{{ commitFileTransaction() - - function commitFileTransaction() - { - $n = count($this->file_operations); - $this->log(2, "about to commit $n file operations"); - // first, check permissions and such manually - $errors = array(); - foreach ($this->file_operations as $tr) { - list($type, $data) = $tr; - switch ($type) { - case 'rename': - // check that dest dir. is writable - if (!is_writable(dirname($data[1]))) { - $errors[] = "permission denied ($type): $data[1]"; - } - break; - case 'chmod': - // check that file is writable - if (!is_writable($data[1])) { - $errors[] = "permission denied ($type): $data[1]"; - } - break; - case 'delete': - // check that directory is writable - if (file_exists($data[0]) && !is_writable(dirname($data[0]))) { - $errors[] = "permission denied ($type): $data[0]"; - } - break; - } - - } - $m = sizeof($errors); - if ($m > 0) { - foreach ($errors as $error) { - $this->log(1, $error); - } - return false; - } - // really commit the transaction - foreach ($this->file_operations as $tr) { - list($type, $data) = $tr; - switch ($type) { - case 'rename': - @rename($data[0], $data[1]); - $this->log(3, "+ mv $data[0] $data[1]"); - break; - case 'chmod': - @chmod($data[0], $data[1]); - $octmode = decoct($data[0]); - $this->log(3, "+ chmod $octmode $data[1]"); - break; - case 'delete': - @unlink($data[0]); - $this->log(3, "+ rm $data[0]"); - break; - case 'rmdir': - @rmdir($data[0]); - $this->log(3, "+ rmdir $data[0]"); - break; - } - } - $this->log(2, "successfully commited $n file operations"); - $this->file_operations = array(); - return true; - } - - // }}} - // {{{ rollbackFileTransaction() - - function rollbackFileTransaction() - { - $n = count($this->file_operations); - $this->log(2, "rolling back $n file operations"); - foreach ($this->file_operations as $tr) { - list($type, $data) = $tr; - switch ($type) { - case 'rename': - @unlink($data[0]); - $this->log(3, "+ rm $data[0]"); - break; - case 'mkdir': - @rmdir($data[0]); - $this->log(3, "+ rmdir $data[0]"); - break; - case 'chmod': - break; - case 'delete': - break; - } - } - $this->file_operations = array(); - } - - // }}} - // {{{ getPackageDownloadUrl() - - function getPackageDownloadUrl($package) - { - if ($this === null || $this->config === null) { - $package = "http://pear.php.net/get/$package"; - } else { - $package = "http://" . $this->config->get('master_server') . - "/get/$package"; - } - if (!extension_loaded("zlib")) { - $package .= '?uncompress=yes'; - } - return $package; - } - - // }}} - // {{{ mkDirHier($dir) - - function mkDirHier($dir) - { - $this->addFileOperation('mkdir', array($dir)); - return parent::mkDirHier($dir); - } - - // }}} - - // {{{ _prependPath($path, $prepend) - - function _prependPath($path, $prepend) - { - if (strlen($prepend) > 0) { - if (OS_WINDOWS && preg_match('/^[a-z]:/i', $path)) { - $path = $prepend . substr($path, 2); - } else { - $path = $prepend . $path; - } - } - return $path; - } - - // }}} - - // {{{ install() - - /** - * Installs the files within the package file specified. - * - * @param $pkgfile path to the package file - * - * @return array package info if successful, null if not - */ - - function install($pkgfile, $options = array()) - { - // recognized options: - // - force : force installation - // - register-only : update registry but don't install files - // - upgrade : upgrade existing install - // - soft : fail silently - // - $php_dir = $this->config->get('php_dir'); - if (isset($options['installroot'])) { - if (substr($options['installroot'], -1) == DIRECTORY_SEPARATOR) { - $options['installroot'] = substr($options['installroot'], 0, -1); - } - $php_dir = $this->_prependPath($php_dir, $options['installroot']); - $this->registry = &new PEAR_Registry($php_dir); - $this->installroot = $options['installroot']; - } else { - $registry = &$this->registry; - $this->installroot = ''; - } - $need_download = false; - // ==> XXX should be removed later on - $flag_old_format = false; - if (preg_match('#^(http|ftp)://#', $pkgfile)) { - $need_download = true; - } elseif (!@is_file($pkgfile)) { - if ($this->validPackageName($pkgfile)) { - if ($this->registry->packageExists($pkgfile) && - empty($options['upgrade']) && empty($options['force'])) - { - return $this->raiseError("$pkgfile already installed"); - } - $pkgfile = $this->getPackageDownloadUrl($pkgfile); - $need_download = true; - } else { - if (strlen($pkgfile)) { - return $this->raiseError("Could not open the package file: $pkgfile"); - } else { - return $this->raiseError("No package file given"); - } - } - } - - // Download package ----------------------------------------------- - if ($need_download) { - $downloaddir = $this->config->get('download_dir'); - if (empty($downloaddir)) { - if (PEAR::isError($downloaddir = System::mktemp('-d'))) { - return $downloaddir; - } - $this->log(2, '+ tmp dir created at ' . $downloaddir); - } - $callback = $this->ui ? array(&$this, '_downloadCallback') : null; - $file = $this->downloadHttp($pkgfile, $this->ui, $downloaddir, $callback); - if (PEAR::isError($file)) { - return $this->raiseError($file); - } - $pkgfile = $file; - } - - if (substr($pkgfile, -4) == '.xml') { - $descfile = $pkgfile; - } else { - // Decompress pack in tmp dir ------------------------------------- - - // To allow relative package file names - $oldcwd = getcwd(); - if (@chdir(dirname($pkgfile))) { - $pkgfile = getcwd() . DIRECTORY_SEPARATOR . basename($pkgfile); - chdir($oldcwd); - } - - if (PEAR::isError($tmpdir = System::mktemp('-d'))) { - return $tmpdir; - } - $this->log(2, '+ tmp dir created at ' . $tmpdir); - - $tar = new Archive_Tar($pkgfile); - if (!@$tar->extract($tmpdir)) { - return $this->raiseError("unable to unpack $pkgfile"); - } - - // ----- Look for existing package file - $descfile = $tmpdir . DIRECTORY_SEPARATOR . 'package.xml'; - - if (!is_file($descfile)) { - // ----- Look for old package archive format - // In this format the package.xml file was inside the - // Package-n.n directory - $dp = opendir($tmpdir); - do { - $pkgdir = readdir($dp); - } while ($pkgdir{0} == '.'); - - $descfile = $tmpdir . DIRECTORY_SEPARATOR . $pkgdir . DIRECTORY_SEPARATOR . 'package.xml'; - $flag_old_format = true; - $this->log(0, "warning : you are using an archive with an old format"); - } - // <== XXX This part should be removed later on - } - - if (!is_file($descfile)) { - return $this->raiseError("no package.xml file after extracting the archive"); - } - - // Parse xml file ----------------------------------------------- - $pkginfo = $this->infoFromDescriptionFile($descfile); - if (PEAR::isError($pkginfo)) { - return $pkginfo; - } - $this->validatePackageInfo($pkginfo, $errors, $warnings); - // XXX We allow warnings, do we have to do it? - if (count($errors)) { - if (empty($options['force'])) { - return $this->raiseError("The following errors where found (use force option to install anyway):\n". - implode("\n", $errors)); - } else { - $this->log(0, "warning : the following errors were found:\n". - implode("\n", $errors)); - } - } - - $pkgname = $pkginfo['package']; - - // Check dependencies ------------------------------------------- - if (isset($pkginfo['release_deps']) && empty($options['nodeps'])) { - $error = $this->checkDeps($pkginfo); - if ($error) { - if (empty($options['soft'])) { - $this->log(0, $error); - } - return $this->raiseError("$pkgname: dependencies failed"); - } - } - - if (empty($options['force'])) { - // checks to do when not in "force" mode - $test = $this->registry->checkFileMap($pkginfo); - if (sizeof($test)) { - $tmp = $test; - foreach ($tmp as $file => $pkg) { - if ($pkg == $pkgname) { - unset($test[$file]); - } - } - if (sizeof($test)) { - $msg = "$pkgname: conflicting files found:\n"; - $longest = max(array_map("strlen", array_keys($test))); - $fmt = "%${longest}s (%s)\n"; - foreach ($test as $file => $pkg) { - $msg .= sprintf($fmt, $file, $pkg); - } - return $this->raiseError($msg); - } - } - } - - if (empty($options['upgrade'])) { - // checks to do only when installing new packages - if (empty($options['force']) && $this->registry->packageExists($pkgname)) { - return $this->raiseError("$pkgname already installed"); - } - } else { - // checks to do only when upgrading packages - if (!$this->registry->packageExists($pkgname)) { - return $this->raiseError("$pkgname not installed"); - } - $v1 = $this->registry->packageInfo($pkgname, 'version'); - $v2 = $pkginfo['version']; - $cmp = version_compare("$v1", "$v2", 'gt'); - if (empty($options['force']) && !version_compare("$v2", "$v1", 'gt')) { - return $this->raiseError("upgrade to a newer version ($v2 is not newer than $v1)"); - } - if (empty($options['register-only'])) { - // when upgrading, remove old release's files first: - if (PEAR::isError($err = $this->_deletePackageFiles($pkgname))) { - return $this->raiseError($err); - } - } - } - - // Copy files to dest dir --------------------------------------- - - // info from the package it self we want to access from _installFile - $this->pkginfo = &$pkginfo; - // used to determine whether we should build any C code - $this->source_files = 0; - - if (empty($options['register-only'])) { - if (!is_dir($php_dir)) { - return $this->raiseError("no script destination directory\n", - null, PEAR_ERROR_DIE); - } - - // don't want strange characters - $pkgname = ereg_replace ('[^a-zA-Z0-9._]', '_', $pkginfo['package']); - $pkgversion = ereg_replace ('[^a-zA-Z0-9._\-]', '_', $pkginfo['version']); - $tmp_path = dirname($descfile); - if (substr($pkgfile, -4) != '.xml') { - $tmp_path .= DIRECTORY_SEPARATOR . $pkgname . '-' . $pkgversion; - } - - // ==> XXX This part should be removed later on - if ($flag_old_format) { - $tmp_path = dirname($descfile); - } - // <== XXX This part should be removed later on - - foreach ($pkginfo['filelist'] as $file => $atts) { - $this->expectError(PEAR_INSTALLER_FAILED); - $res = $this->_installFile($file, $atts, $tmp_path); - $this->popExpect(); - if (PEAR::isError($res)) { - if (empty($options['ignore-errors'])) { - $this->rollbackFileTransaction(); - return $this->raiseError($res); - } else { - $this->log(0, "Warning: " . $res->getMessage()); - } - } - if ($res != PEAR_INSTALLER_OK) { - // Do not register files that were not installed - unset($pkginfo['filelist'][$file]); - } - } - - if ($this->source_files > 0 && empty($options['nobuild'])) { - $this->log(1, "$this->source_files source files, building"); - $bob = &new PEAR_Builder($this->ui); - $bob->debug = $this->debug; - $built = $bob->build($descfile, array(&$this, '_buildCallback')); - if (PEAR::isError($built)) { - $this->rollbackFileTransaction(); - return $built; - } - foreach ($built as $ext) { - $bn = basename($ext['file']); - $this->log(2, "installing $bn"); - $dest = $this->config->get('ext_dir') . DIRECTORY_SEPARATOR . $bn; - $this->log(3, "+ cp $ext[file] ext_dir"); - $copyto = $this->_prependPath($dest, $this->installroot); - if (!@copy($ext['file'], $copyto)) { - $this->rollbackFileTransaction(); - return $this->raiseError("failed to copy $bn to $copyto"); - } - $pkginfo['filelist'][$bn] = array( - 'role' => 'ext', - 'installed_as' => $dest, - 'php_api' => $ext['php_api'], - 'zend_mod_api' => $ext['zend_mod_api'], - 'zend_ext_api' => $ext['zend_ext_api'], - ); - } - } - } - - if (!$this->commitFileTransaction()) { - $this->rollbackFileTransaction(); - return $this->raiseError("commit failed", PEAR_INSTALLER_FAILED); - } - - // Register that the package is installed ----------------------- - if (empty($options['upgrade'])) { - // if 'force' is used, replace the info in registry - if (!empty($options['force']) && $this->registry->packageExists($pkgname)) { - $this->registry->deletePackage($pkgname); - } - $ret = $this->registry->addPackage($pkgname, $pkginfo); - } else { - $ret = $this->registry->updatePackage($pkgname, $pkginfo, false); - } - if (!$ret) { - return null; - } - return $pkginfo; - } - - // }}} - // {{{ uninstall() - - function uninstall($package, $options = array()) - { - $php_dir = $this->config->get('php_dir'); - if (isset($options['installroot'])) { - if (substr($options['installroot'], -1) == DIRECTORY_SEPARATOR) { - $options['installroot'] = substr($options['installroot'], 0, -1); - } - $this->installroot = $options['installroot']; - $php_dir = $this->_prependPath($php_dir, $this->installroot); - } else { - $this->installroot = ''; - } - $this->registry = &new PEAR_Registry($php_dir); - - // Delete the files - if (PEAR::isError($err = $this->_deletePackageFiles($package))) { - $this->rollbackFileTransaction(); - return $this->raiseError($err); - } - if (!$this->commitFileTransaction()) { - $this->rollbackFileTransaction(); - return $this->raiseError("uninstall failed"); - } - - // Register that the package is no longer installed - return $this->registry->deletePackage($package); - } - - // }}} - // {{{ checkDeps() - - function checkDeps(&$pkginfo) - { - $depchecker = &new PEAR_Dependency($this->registry); - $error = $errors = ''; - $failed_deps = array(); - if (is_array($pkginfo['release_deps'])) { - foreach($pkginfo['release_deps'] as $dep) { - $code = $depchecker->callCheckMethod($error, $dep); - if ($code) { - $failed_deps[] = array($dep, $code, $error); - } - } - $n = count($failed_deps); - if ($n > 0) { - $depinstaller =& new PEAR_Installer($this->ui); - $to_install = array(); - for ($i = 0; $i < $n; $i++) { - if (isset($failed_deps[$i]['type'])) { - $type = $failed_deps[$i]['type']; - } else { - $type = 'pkg'; - } - switch ($failed_deps[$i][1]) { - case PEAR_DEPENDENCY_MISSING: - if ($type == 'pkg') { - // install - } - $errors .= "\n" . $failed_deps[$i][2]; - break; - case PEAR_DEPENDENCY_UPGRADE_MINOR: - if ($type == 'pkg') { - // upgrade - } - $errors .= "\n" . $failed_deps[$i][2]; - break; - default: - $errors .= "\n" . $failed_deps[$i][2]; - break; - } - } - return substr($errors, 1); - } - } - return false; - } - - // }}} - // {{{ _downloadCallback() - - function _downloadCallback($msg, $params = null) - { - switch ($msg) { - case 'saveas': - $this->log(1, "downloading $params ..."); - break; - case 'done': - $this->log(1, '...done: ' . number_format($params, 0, '', ',') . ' bytes'); - break; - } - if (method_exists($this->ui, '_downloadCallback')) - $this->ui->_downloadCallback($msg, $params); - } - - // }}} - // {{{ _buildCallback() - - function _buildCallback($what, $data) - { - if (($what == 'cmdoutput' && $this->debug > 1) || - ($what == 'output' && $this->debug > 0)) { - $this->ui->outputData(rtrim($data), 'build'); - } - } - - // }}} -} - -if (!function_exists("md5_file")) { - function md5_file($filename) { - 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'); - } - $fp = fopen($filename, "r"); - if (!$fp) return null; - $contents = fread($fp, filesize($filename)); - fclose($fp); - return G::encryptOld($contents); - } -} - -?> diff --git a/gulliver/thirdparty/pear/PEAR/Packager.php b/gulliver/thirdparty/pear/PEAR/Packager.php deleted file mode 100644 index f0a240d7c..000000000 --- a/gulliver/thirdparty/pear/PEAR/Packager.php +++ /dev/null @@ -1,181 +0,0 @@ - | -// | Tomas V.V.Cox | -// +----------------------------------------------------------------------+ -// -// $Id: Packager.php,v 1.46 2003/03/18 12:06:06 ssb Exp $ - -require_once 'PEAR/Common.php'; -require_once 'System.php'; - -/** - * Administration class used to make a PEAR release tarball. - * - * TODO: - * - add an extra param the dir where to place the created package - * - * @since PHP 4.0.2 - * @author Stig Bakken - */ -class PEAR_Packager extends PEAR_Common -{ - // {{{ constructor - - function PEAR_Packager() - { - parent::PEAR_Common(); - } - - // }}} - // {{{ destructor - - function _PEAR_Packager() - { - parent::_PEAR_Common(); - } - - // }}} - - // {{{ package() - - function package($pkgfile = null, $compress = true) - { - if (empty($pkgfile)) { - $pkgfile = 'package.xml'; - } - $pkginfo = $this->infoFromDescriptionFile($pkgfile); - if (PEAR::isError($pkginfo)) { - return $this->raiseError($pkginfo); - } - if (empty($this->pkginfo['version'])) { - return $this->raiseError("No version info found in $pkgfile"); - } - // TMP DIR ------------------------------------------------- - // We allow calls like "pear package /home/user/mypack/package.xml" - $oldcwd = getcwd(); - $dir = dirname($pkgfile); - if (!@chdir($dir)) { - return $this->raiseError('Could not chdir to '.$dir); - } - $pkgfile = basename($pkgfile); - if (@$this->pkginfo['release_state'] == 'snapshot' && empty($this->pkginfo['version'])) { - $this->pkginfo['version'] = date('Ymd'); - } - // don't want strange characters - $pkgname = preg_replace('/[^a-z0-9._]/i', '_', $this->pkginfo['package']); - $pkgversion = preg_replace('/[^a-z0-9._-]/i', '_', $this->pkginfo['version']); - $pkgver = $pkgname . '-' . $pkgversion; - - $errors = $warnings = array(); - $this->validatePackageInfo($this->pkginfo, $errors, $warnings, $dir); - foreach ($warnings as $w) { - $this->log(1, "Warning: $w"); - } - foreach ($errors as $e) { - $this->log(0, "Error: $e"); - } - if (sizeof($errors) > 0) { - chdir($oldcwd); - return $this->raiseError('Errors in package'); - } - - // ----- Create the package file list - $filelist = array(); - $i = 0; - - // Copy files ----------------------------------------------- - foreach ($this->pkginfo['filelist'] as $fname => $atts) { - if (!file_exists($fname)) { - chdir($oldcwd); - return $this->raiseError("File does not exist: $fname"); - } else { - $filelist[$i++] = $fname; - if (empty($this->pkginfo['filelist'][$fname]['md5sum'])) { - $md5sum = md5_file($fname); - $this->pkginfo['filelist'][$fname]['md5sum'] = $md5sum; - } - $this->log(2, "Adding file $fname"); - } - } - $new_xml = $this->xmlFromInfo($this->pkginfo); - if (PEAR::isError($new_xml)) { - chdir($oldcwd); - return $this->raiseError($new_xml); - } - if (!($tmpdir = System::mktemp('-t '.getcwd().' -d'))) { - chdir($oldcwd); - return $this->raiseError("PEAR_Packager: mktemp failed"); - } - $newpkgfile = $tmpdir . DIRECTORY_SEPARATOR . 'package.xml'; - $np = @fopen($newpkgfile, "w"); - if (!$np) { - chdir($oldcwd); - return $this->raiseError("PEAR_Packager: unable to rewrite $pkgfile as $newpkgfile"); - } - fwrite($np, $new_xml); - fclose($np); - - // TAR the Package ------------------------------------------- - $ext = $compress ? '.tgz' : '.tar'; - $dest_package = $oldcwd . DIRECTORY_SEPARATOR . $pkgver . $ext; - $tar =& new Archive_Tar($dest_package, $compress); - $tar->setErrorHandling(PEAR_ERROR_RETURN); // XXX Don't print errors - // ----- Creates with the package.xml file - $ok = $tar->createModify($newpkgfile, '', $tmpdir); - if (PEAR::isError($ok)) { - chdir($oldcwd); - return $this->raiseError($ok); - } elseif (!$ok) { - chdir($oldcwd); - return $this->raiseError('PEAR_Packager: tarball creation failed'); - } - // ----- Add the content of the package - if (!$tar->addModify($filelist, $pkgver)) { - chdir($oldcwd); - return $this->raiseError('PEAR_Packager: tarball creation failed'); - } - $this->log(1, "Package $dest_package done"); - if (file_exists("CVS/Root")) { - $cvsversion = preg_replace('/[^a-z0-9]/i', '_', $pkgversion); - $cvstag = "RELEASE_$cvsversion"; - $this->log(1, "Tag the released code with `pear cvstag $pkgfile'"); - $this->log(1, "(or set the CVS tag $cvstag by hand)"); - } - chdir($oldcwd); - return $dest_package; - } - - // }}} -} - -if (!function_exists('md5_file')) { - function md5_file($file) { - if (!$fd = @fopen($file, 'r')) { - return false; - } - $md5 = encryptOld(fread($fd, filesize($file))); - fclose($fd); - return $md5; - } - - public function encryptOld($string) - { - return md5($string); - } -} - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/PEAR/Registry.php b/gulliver/thirdparty/pear/PEAR/Registry.php deleted file mode 100644 index 84d57292c..000000000 --- a/gulliver/thirdparty/pear/PEAR/Registry.php +++ /dev/null @@ -1,717 +0,0 @@ - | -// | Tomas V.V.Cox | -// | | -// +----------------------------------------------------------------------+ -// -// $Id: Registry.php,v 1.39 2003/05/08 17:11:02 pajoye Exp $ - -/* -TODO: - - Transform into singleton() - - Add application level lock (avoid change the registry from the cmdline - while using the GTK interface, for ex.) -*/ -require_once "System.php"; -require_once "PEAR.php"; - -define('PEAR_REGISTRY_ERROR_LOCK', -2); -define('PEAR_REGISTRY_ERROR_FORMAT', -3); -define('PEAR_REGISTRY_ERROR_FILE', -4); - -/** - * Administration class used to maintain the installed package database. - */ -class PEAR_Registry extends PEAR -{ - // {{{ properties - - /** Directory where registry files are stored. - * @var string - */ - var $statedir = ''; - - /** File where the file map is stored - * @var string - */ - var $filemap = ''; - - /** Name of file used for locking the registry - * @var string - */ - var $lockfile = ''; - - /** File descriptor used during locking - * @var resource - */ - var $lock_fp = null; - - /** Mode used during locking - * @var int - */ - var $lock_mode = 0; // XXX UNUSED - - /** Cache of package information. Structure: - * array( - * 'package' => array('id' => ... ), - * ... ) - * @var array - */ - var $pkginfo_cache = array(); - - /** Cache of file map. Structure: - * array( '/path/to/file' => 'package', ... ) - * @var array - */ - var $filemap_cache = array(); - - // }}} - - // {{{ constructor - - /** - * PEAR_Registry constructor. - * - * @param string (optional) PEAR install directory (for .php files) - * - * @access public - */ - function PEAR_Registry($pear_install_dir = PEAR_INSTALL_DIR) - { - parent::PEAR(); - $ds = DIRECTORY_SEPARATOR; - $this->install_dir = $pear_install_dir; - $this->statedir = $pear_install_dir.$ds.'.registry'; - $this->filemap = $pear_install_dir.$ds.'.filemap'; - $this->lockfile = $pear_install_dir.$ds.'.lock'; - if (!file_exists($this->filemap)) { - $this->rebuildFileMap(); - } - } - - // }}} - // {{{ destructor - - /** - * PEAR_Registry destructor. Makes sure no locks are forgotten. - * - * @access private - */ - function _PEAR_Registry() - { - parent::_PEAR(); - if (is_resource($this->lock_fp)) { - $this->_unlock(); - } - } - - // }}} - - // {{{ _assertStateDir() - - /** - * Make sure the directory where we keep registry files exists. - * - * @return bool TRUE if directory exists, FALSE if it could not be - * created - * - * @access private - */ - function _assertStateDir() - { - if (!@is_dir($this->statedir)) { - if (!System::mkdir("-p {$this->statedir}")) { - return $this->raiseError("could not create directory '{$this->statedir}'"); - } - } - return true; - } - - // }}} - // {{{ _packageFileName() - - /** - * Get the name of the file where data for a given package is stored. - * - * @param string package name - * - * @return string registry file name - * - * @access public - */ - function _packageFileName($package) - { - return "{$this->statedir}/{$package}.reg"; - } - - // }}} - // {{{ _openPackageFile() - - function _openPackageFile($package, $mode) - { - $this->_assertStateDir(); - $file = $this->_packageFileName($package); - 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(); - $file = $filter->validateInput($file,"path"); - - $fp = @fopen($file, $mode); - if (!$fp) { - return null; - } - return $fp; - } - - // }}} - // {{{ _closePackageFile() - - function _closePackageFile($fp) - { - fclose($fp); - } - - // }}} - // {{{ rebuildFileMap() - - function rebuildFileMap() - { - $packages = $this->listPackages(); - $files = array(); - foreach ($packages as $package) { - $version = $this->packageInfo($package, 'version'); - $filelist = $this->packageInfo($package, 'filelist'); - if (!is_array($filelist)) { - continue; - } - foreach ($filelist as $name => $attrs) { - if (isset($attrs['role']) && $attrs['role'] != 'php') { - continue; - } - if (isset($attrs['baseinstalldir'])) { - $file = $attrs['baseinstalldir'].DIRECTORY_SEPARATOR.$name; - } else { - $file = $name; - } - $file = preg_replace(',^/+,', '', $file); - $files[$file] = $package; - } - } - $this->_assertStateDir(); - $fp = @fopen($this->filemap, 'w'); - if (!$fp) { - return false; - } - $this->filemap_cache = $files; - fwrite($fp, serialize($files)); - fclose($fp); - return true; - } - - // }}} - // {{{ readFileMap() - - function readFileMap() - { - $fp = @fopen($this->filemap, 'r'); - if (!$fp) { - return $this->raiseError('PEAR_Registry: could not open filemap', PEAR_REGISTRY_ERROR_FILE, null, null, $php_errormsg); - } - $fsize = filesize($this->filemap); - $data = fread($fp, $fsize); - fclose($fp); - $tmp = unserialize($data); - if (!$tmp && $fsize > 7) { - return $this->raiseError('PEAR_Registry: invalid filemap data', PEAR_REGISTRY_ERROR_FORMAT, null, null, $data); - } - $this->filemap_cache = $tmp; - return true; - } - - // }}} - // {{{ _lock() - - /** - * Lock the registry. - * - * @param integer lock mode, one of LOCK_EX, LOCK_SH or LOCK_UN. - * See flock manual for more information. - * - * @return bool TRUE on success, FALSE if locking failed, or a - * PEAR error if some other error occurs (such as the - * lock file not being writable). - * - * @access private - */ - function _lock($mode = LOCK_EX) - { - if (!preg_match('/Windows 9/', php_uname())) { - if ($mode != LOCK_UN && is_resource($this->lock_fp)) { - // XXX does not check type of lock (LOCK_SH/LOCK_EX) - return true; - } - if (PEAR::isError($err = $this->_assertStateDir())) { - return $err; - } - $open_mode = 'w'; - // XXX People reported problems with LOCK_SH and 'w' - if ($mode === LOCK_SH) { - if (@!is_file($this->lockfile)) { - touch($this->lockfile); - } - $open_mode = 'r'; - } - - $this->lock_fp = @fopen($this->lockfile, $open_mode); - - if (!is_resource($this->lock_fp)) { - return $this->raiseError("could not create lock file" . - (isset($php_errormsg) ? ": " . $php_errormsg : "")); - } - if (!(int)flock($this->lock_fp, $mode)) { - switch ($mode) { - case LOCK_SH: $str = 'shared'; break; - case LOCK_EX: $str = 'exclusive'; break; - case LOCK_UN: $str = 'unlock'; break; - default: $str = 'unknown'; break; - } - return $this->raiseError("could not acquire $str lock ($this->lockfile)", - PEAR_REGISTRY_ERROR_LOCK); - } - } - return true; - } - - // }}} - // {{{ _unlock() - - function _unlock() - { - $ret = $this->_lock(LOCK_UN); - $this->lock_fp = null; - return $ret; - } - - // }}} - // {{{ _packageExists() - - function _packageExists($package) - { - return file_exists($this->_packageFileName($package)); - } - - // }}} - // {{{ _packageInfo() - - function _packageInfo($package = null, $key = null) - { - if ($package === null) { - return array_map(array($this, '_packageInfo'), - $this->_listPackages()); - } - $fp = $this->_openPackageFile($package, 'r'); - if ($fp === null) { - return null; - } - $data = fread($fp, filesize($this->_packageFileName($package))); - $this->_closePackageFile($fp); - $data = unserialize($data); - if ($key === null) { - return $data; - } - if (isset($data[$key])) { - return $data[$key]; - } - return null; - } - - // }}} - // {{{ _listPackages() - - function _listPackages() - { - $pkglist = array(); - $dp = @opendir($this->statedir); - if (!$dp) { - return $pkglist; - } - while ($ent = readdir($dp)) { - if ($ent{0} == '.' || substr($ent, -4) != '.reg') { - continue; - } - $pkglist[] = substr($ent, 0, -4); - } - return $pkglist; - } - - // }}} - - // {{{ packageExists() - - function packageExists($package) - { - if (PEAR::isError($e = $this->_lock(LOCK_SH))) { - return $e; - } - $ret = $this->_packageExists($package); - $this->_unlock(); - return $ret; - } - - // }}} - // {{{ packageInfo() - - function packageInfo($package = null, $key = null) - { - if (PEAR::isError($e = $this->_lock(LOCK_SH))) { - return $e; - } - $ret = $this->_packageInfo($package, $key); - $this->_unlock(); - return $ret; - } - - // }}} - // {{{ listPackages() - - function listPackages() - { - if (PEAR::isError($e = $this->_lock(LOCK_SH))) { - return $e; - } - $ret = $this->_listPackages(); - $this->_unlock(); - return $ret; - } - - // }}} - // {{{ addPackage() - - function addPackage($package, $info) - { - if ($this->packageExists($package)) { - return false; - } - if (PEAR::isError($e = $this->_lock(LOCK_EX))) { - return $e; - } - $fp = $this->_openPackageFile($package, 'w'); - if ($fp === null) { - $this->_unlock(); - return false; - } - $info['_lastmodified'] = time(); - fwrite($fp, serialize($info)); - $this->_closePackageFile($fp); - $this->_unlock(); - return true; - } - - // }}} - // {{{ deletePackage() - - function deletePackage($package) - { - if (PEAR::isError($e = $this->_lock(LOCK_EX))) { - return $e; - } - $file = $this->_packageFileName($package); - 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(); - $file = $filter->validateInput($file,"path"); - - $ret = @unlink($file); - $this->rebuildFileMap(); - $this->_unlock(); - return $ret; - } - - // }}} - // {{{ updatePackage() - - function updatePackage($package, $info, $merge = true) - { - $oldinfo = $this->packageInfo($package); - if (empty($oldinfo)) { - return false; - } - if (PEAR::isError($e = $this->_lock(LOCK_EX))) { - return $e; - } - $fp = $this->_openPackageFile($package, 'w'); - if ($fp === null) { - $this->_unlock(); - return false; - } - $info['_lastmodified'] = time(); - if ($merge) { - fwrite($fp, serialize(array_merge($oldinfo, $info))); - } else { - fwrite($fp, serialize($info)); - } - $this->_closePackageFile($fp); - if (isset($info['filelist'])) { - $this->rebuildFileMap(); - } - $this->_unlock(); - return true; - } - - // }}} - // {{{ checkFileMap() - - /** - * Test whether a file belongs to a package. - * - * @param string $path file path, absolute or relative to the pear - * install dir - * - * @return string which package the file belongs to, or an empty - * string if the file does not belong to an installed package - * - * @access public - */ - function checkFileMap($path) - { - if (is_array($path)) { - static $notempty; - if (empty($notempty)) { - $notempty = create_function('$a','return !empty($a);'); - } - $pkgs = array(); - foreach ($path as $name => $attrs) { - if (is_array($attrs) && isset($attrs['baseinstalldir'])) { - $name = $attrs['baseinstalldir'].DIRECTORY_SEPARATOR.$name; - } - $pkgs[$name] = $this->checkFileMap($name); - } - return array_filter($pkgs, $notempty); - } - if (empty($this->filemap_cache) && PEAR::isError($this->readFileMap())) { - return $err; - } - if (isset($this->filemap_cache[$path])) { - return $this->filemap_cache[$path]; - } - $l = strlen($this->install_dir); - if (substr($path, 0, $l) == $this->install_dir) { - $path = preg_replace('!^'.DIRECTORY_SEPARATOR.'+!', '', substr($path, $l)); - } - if (isset($this->filemap_cache[$path])) { - return $this->filemap_cache[$path]; - } - return ''; - } - - // }}} - - // {{{ rebuildDepsFile() - - /** - Experimental dependencies database handling functions (not yet in production) - - TODO: - - test it - - Think on the "not" dep relation. It's supposed that a package can't - be installed if conflicts with another. The problem comes when the - user forces the installation and later upgrades it - **/ - - // XXX Terrible slow, a lot of read, lock, write, unlock - function rebuildDepsFile() - { - // Init the file with empty data - $error = $this->_depWriteDepDB(array()); - if (PEAR::isError($error)) { - return $error; - } - $packages = $this->listPackages(); - foreach ($packages as $package) { - $deps = $this->packageInfo($package, 'release_deps'); - $error = $this->setPackageDep($package, $deps); - if (PEAR::isError($error)) { - return $error; - } - } - return true; - } - - function &_depGetDepDB() - { - if (!$fp = fopen($this->depfile, 'r')) { - return $this->raiseError("Could not open dependencies file `".$this->depfile."'"); - } - $data = fread($fp, filesize($this->depfile)); - fclose($fp); - return unserialize($data); - } - - function _depWriteDepDB(&$deps) - { - if (PEAR::isError($e = $this->_lock(LOCK_EX))) { - return $e; - } - if (!$fp = fopen($this->depfile, 'w')) { - $this->_unlock(); - return $this->raiseError("Could not open dependencies file `".$this->depfile."' for writting"); - } - fwrite($fp, serialize($deps)); - fclose($fp); - $this->_unlock(); - return true; - } - - /* - The data structure is as follows: - $dep_db = array( - // Other packages depends in some manner on this packages - 'deps' => array( - 'Package Name' => array( - 0 => array( - // This package depends on 'Package Name' - 'depend' => 'Package', - // Which version 'Package' needs of 'Package Name' - 'version' => '1.0', - // The requirement (version_compare() operator) - 'rel' => 'ge' - ), - ), - ) - // This packages are dependant on other packages - 'pkgs' => array( - 'Package Dependant' => array( - // This is a index list with paths over the 'deps' array for quick - // searching things like "what dependecies has this package?" - // $dep_db['deps']['Package Name'][3] - 'Package Name' => 3 // key in array ['deps']['Package Name'] - ), - ) - ) - - Note: It only supports package dependencies no other type - */ - - function removePackageDep($package) - { - $data = &$this->_depGetDepDB(); - if (PEAR::isError($data)) { - return $data; - } - // Other packages depends on this package, can't be removed - if (isset($data['deps'][$package])) { - return $data['deps'][$package]; - } - // The package depends on others, remove those dependencies - if (isset($data['pkgs'][$package])) { - foreach ($data['pkgs'][$package] as $pkg => $key) { - // remove the dependency - unset($data['deps'][$pkg][$key]); - // if no more dependencies, remove the subject too - if (!count($data['deps'][$pkg])) { - unset($data['deps'][$pkg]); - } - } - // remove the package from the index list - unset($data['pkgs'][$package]); - } - return $this->_depWriteDepDB(); - } - - /** - * Update or insert a the dependencies of a package, prechecking - * that the package won't break any dependency in the process - */ - function setPackageDep($package, $new_version, $rel_deps = array()) - { - $data = &$this->_depGetDepDB(); - if (PEAR::isError($deps)) { - return $deps; - } - // Other packages depend on this package, check deps. Mostly for - // handling uncommon cases like: - // Foo and we are trying to - // update Foo to version 2.0 - if (isset($data['deps'][$package])) { - foreach ($data['deps'][$package] as $dep) { - $require = $dep['version']; - $relation = $dep['rel']; - // XXX (cox) Possible problem with changes in the way - // PEAR_Dependency::checkPackage() works - if ($relation != 'has') { - if (!version_compare("$new_version", "$require", $relation)) { - $fails[] = $dep; - } - } - } - if (isset($fails)) { - return $fails; - } - } - - // This package has no dependencies - if (!is_array($rel_deps) || !count($rel_deps)) { - return true; - } - - // The package depends on others, register that - foreach ($rel_deps as $dep) { - // We only support deps of type 'pkg's - if ($dep && $dep['type'] == 'pkg' && isset($dep['name'])) { - $write = array('depend' => $package, - 'version' => $dep['version'], - 'rel' => $dep['rel']); - settype($data['deps'][$dep['name']], 'array'); - - // The dependency already exists, update it - if (isset($data['pkgs'][$package][$dep['name']])) { - $key = $data['pkgs'][$package][$dep['name']]; - $data['deps'][$dep['name']][$key] = $write; - - // New dependency, insert it - } else { - $data['deps'][$dep['name']][] = $write; - $key = key($data['deps'][$dep['name']]); - settype($data['pkgs'][$package], 'array'); - $data['pkgs'][$package][$dep['name']] = $key; - } - } - } - return $this->_depWriteDepDB($data); - } - - // }}} -} - -?> diff --git a/gulliver/thirdparty/pear/PEAR/Remote.php b/gulliver/thirdparty/pear/PEAR/Remote.php deleted file mode 100644 index b6108e2b4..000000000 --- a/gulliver/thirdparty/pear/PEAR/Remote.php +++ /dev/null @@ -1,381 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Remote.php,v 1.39 2003/03/18 12:06:06 ssb Exp $ - -require_once 'PEAR.php'; -require_once 'PEAR/Config.php'; - -/** - * This is a class for doing remote operations against the central - * PEAR database. - * - * @nodep XML_RPC_Value - * @nodep XML_RPC_Message - * @nodep XML_RPC_Client - */ -class PEAR_Remote extends PEAR -{ - // {{{ properties - - var $config = null; - var $cache = null; - - // }}} - - // {{{ PEAR_Remote(config_object) - - function PEAR_Remote(&$config) - { - $this->PEAR(); - $this->config = &$config; - } - - // }}} - - // {{{ getCache() - - - function getCache($args) - { - $id = $this->encryptOld(serialize($args)); - $cachedir = $this->config->get('cache_dir'); - if (!file_exists($cachedir)) { - System::mkdir('-p '.$cachedir); - } - $filename = $cachedir . DIRECTORY_SEPARATOR . 'xmlrpc_cache_' . $id; - if (!file_exists($filename)) { - return null; - }; - - $fp = fopen($filename, "rb"); - if ($fp === null) { - return null; - } - $content = fread($fp, filesize($filename)); - fclose($fp); - $result = array( - 'age' => time() - filemtime($filename), - 'lastChange' => filemtime($filename), - 'content' => unserialize($content), - ); - return $result; - } - - // }}} - - // {{{ saveCache() - - function saveCache($args, $data) - { - $id = $this->encryptOld(serialize($args)); - $cachedir = $this->config->get('cache_dir'); - if (!file_exists($cachedir)) { - System::mkdir('-p '.$cachedir); - } - $filename = $cachedir.'/xmlrpc_cache_'.$id; - - $fp = @fopen($filename, "wb"); - if ($fp !== null) { - fwrite($fp, serialize($data)); - fclose($fp); - }; - } - - // }}} - - // {{{ call(method, [args...]) - - function call($method) - { - $_args = $args = func_get_args(); - - $this->cache = $this->getCache($args); - $cachettl = $this->config->get('cache_ttl'); - // If cache is newer than $cachettl seconds, we use the cache! - if ($this->cache !== null && $this->cache['age'] < $cachettl) { - return $this->cache['content']; - }; - - if (extension_loaded("xmlrpc")) { - $result = call_user_func_array(array(&$this, 'call_epi'), $args); - if (!PEAR::isError($result)) { - $this->saveCache($_args, $result); - }; - return $result; - } - if (!@include_once("XML/RPC.php")) { - return $this->raiseError("For this remote PEAR operation you need to install the XML_RPC package"); - } - array_shift($args); - $server_host = $this->config->get('master_server'); - $username = $this->config->get('username'); - $password = $this->config->get('password'); - $eargs = array(); - foreach($args as $arg) $eargs[] = $this->_encode($arg); - $f = new XML_RPC_Message($method, $eargs); - if ($this->cache !== null) { - $maxAge = '?maxAge='.$this->cache['lastChange']; - } else { - $maxAge = ''; - }; - $proxy_host = $proxy_port = $proxy_user = $proxy_pass = ''; - if ($proxy = parse_url($this->config->get('http_proxy'))) { - $proxy_host = @$proxy['host']; - $proxy_port = @$proxy['port']; - $proxy_user = @$proxy['user']; - $proxy_pass = @$proxy['pass']; - } - $c = new XML_RPC_Client('/xmlrpc.php'.$maxAge, $server_host, 80, $proxy_host, $proxy_port, $proxy_user, $proxy_pass); - if ($username && $password) { - $c->setCredentials($username, $password); - } - if ($this->config->get('verbose') >= 3) { - $c->setDebug(1); - } - $r = $c->send($f); - if (!$r) { - return $this->raiseError("XML_RPC send failed"); - } - $v = $r->value(); - if ($e = $r->faultCode()) { - if ($e == $GLOBALS['XML_RPC_err']['http_error'] && strstr($r->faultString(), '304 Not Modified') !== false) { - return $this->cache['content']; - } - return $this->raiseError($r->faultString(), $e); - } - - $result = XML_RPC_decode($v); - $this->saveCache($_args, $result); - return $result; - } - - // }}} - - // {{{ call_epi(method, [args...]) - - function call_epi($method) - { - do { - if (extension_loaded("xmlrpc")) { - break; - } - if (OS_WINDOWS) { - $ext = 'dll'; - } elseif (PHP_OS == 'HP-UX') { - $ext = 'sl'; - } elseif (PHP_OS == 'AIX') { - $ext = 'a'; - } else { - $ext = 'so'; - } - $ext = OS_WINDOWS ? 'dll' : 'so'; - @dl("xmlrpc-epi.$ext"); - if (extension_loaded("xmlrpc")) { - break; - } - @dl("xmlrpc.$ext"); - if (extension_loaded("xmlrpc")) { - break; - } - return $this->raiseError("unable to load xmlrpc extension"); - } while (false); - $params = func_get_args(); - array_shift($params); - $method = str_replace("_", ".", $method); - $request = xmlrpc_encode_request($method, $params); - $server_host = $this->config->get("master_server"); - if (empty($server_host)) { - return $this->raiseError("PEAR_Remote::call: no master_server configured"); - } - $server_port = 80; - $fp = @fsockopen($server_host, $server_port); - if (!$fp) { - return $this->raiseError("PEAR_Remote::call: fsockopen(`$server_host', $server_port) failed"); - } - $len = strlen($request); - $req_headers = "Host: $server_host:$server_port\r\n" . - "Content-type: text/xml\r\n" . - "Content-length: $len\r\n"; - $username = $this->config->get('username'); - $password = $this->config->get('password'); - if ($username && $password) { - $req_headers .= "Cookie: PEAR_USER=$username; PEAR_PW=$password\r\n"; - $tmp = base64_encode("$username:$password"); - $req_headers .= "Authorization: Basic $tmp\r\n"; - } - if ($this->cache !== null) { - $maxAge = '?maxAge='.$this->cache['lastChange']; - } else { - $maxAge = ''; - }; - - if ($this->config->get('verbose') > 3) { - print "XMLRPC REQUEST HEADERS:\n"; - var_dump($req_headers); - print "XMLRPC REQUEST BODY:\n"; - var_dump($request); - } - - fwrite($fp, ("POST /xmlrpc.php$maxAge HTTP/1.0\r\n$req_headers\r\n$request")); - $response = ''; - $line1 = fgets($fp, 2048); - if (!preg_match('!^HTTP/[0-9\.]+ (\d+) (.*)!', $line1, $matches)) { - return $this->raiseError("PEAR_Remote: invalid HTTP response from XML-RPC server"); - } - switch ($matches[1]) { - case "200": // OK - break; - case "304": // Not Modified - return $this->cache['content']; - case "401": // Unauthorized - if ($username && $password) { - return $this->raiseError("PEAR_Remote: authorization failed", 401); - } else { - return $this->raiseError("PEAR_Remote: authorization required, please log in first", 401); - } - default: - return $this->raiseError("PEAR_Remote: unexpected HTTP response", (int)$matches[1], null, null, "$matches[1] $matches[2]"); - } - while (trim(fgets($fp, 2048)) != ''); // skip rest of headers - while ($chunk = fread($fp, 10240)) { - $response .= $chunk; - } - fclose($fp); - if ($this->config->get('verbose') > 3) { - print "XMLRPC RESPONSE:\n"; - var_dump($response); - } - $ret = xmlrpc_decode($response); - if (is_array($ret) && isset($ret['__PEAR_TYPE__'])) { - if ($ret['__PEAR_TYPE__'] == 'error') { - if (isset($ret['__PEAR_CLASS__'])) { - $class = $ret['__PEAR_CLASS__']; - } else { - $class = "PEAR_Error"; - } - if ($ret['code'] === '') $ret['code'] = null; - if ($ret['message'] === '') $ret['message'] = null; - if ($ret['userinfo'] === '') $ret['userinfo'] = null; - if (strtolower($class) == 'db_error') { - $ret = $this->raiseError(PEAR::errorMessage($ret['code']), - $ret['code'], null, null, - $ret['userinfo']); - } else { - $ret = $this->raiseError($ret['message'], $ret['code'], - null, null, $ret['userinfo']); - } - } - } elseif (is_array($ret) && sizeof($ret) == 1 && is_array($ret[0]) && - !empty($ret[0]['faultString']) && - !empty($ret[0]['faultCode'])) { - extract($ret[0]); - $faultString = "XML-RPC Server Fault: " . - str_replace("\n", " ", $faultString); - return $this->raiseError($faultString, $faultCode); - } - return $ret; - } - - // }}} - - // {{{ _encode - - // a slightly extended version of XML_RPC_encode - function _encode($php_val) - { - global $XML_RPC_Boolean, $XML_RPC_Int, $XML_RPC_Double; - global $XML_RPC_String, $XML_RPC_Array, $XML_RPC_Struct; - - $type = gettype($php_val); - $xmlrpcval = new XML_RPC_Value; - - switch($type) { - case "array": - reset($php_val); - $firstkey = key($php_val); - end($php_val); - $lastkey = key($php_val); - if ($firstkey === 0 && is_int($lastkey) && - ($lastkey + 1) == count($php_val)) { - $is_continuous = true; - reset($php_val); - $size = count($php_val); - for ($expect = 0; $expect < $size; $expect++, next($php_val)) { - if (key($php_val) !== $expect) { - $is_continuous = false; - break; - } - } - if ($is_continuous) { - reset($php_val); - $arr = array(); - while (list($k, $v) = each($php_val)) { - $arr[$k] = $this->_encode($v); - } - $xmlrpcval->addArray($arr); - break; - } - } - // fall though if not numerical and continuous - case "object": - $arr = array(); - while (list($k, $v) = each($php_val)) { - $arr[$k] = $this->_encode($v); - } - $xmlrpcval->addStruct($arr); - break; - case "integer": - $xmlrpcval->addScalar($php_val, $XML_RPC_Int); - break; - case "double": - $xmlrpcval->addScalar($php_val, $XML_RPC_Double); - break; - case "string": - case "NULL": - $xmlrpcval->addScalar($php_val, $XML_RPC_String); - break; - case "boolean": - $xmlrpcval->addScalar($php_val, $XML_RPC_Boolean); - break; - case "unknown type": - default: - return null; - } - return $xmlrpcval; - } - - // }}} - - 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); - } - -} - -?> diff --git a/gulliver/thirdparty/pear/README b/gulliver/thirdparty/pear/README deleted file mode 100644 index c953c26b1..000000000 --- a/gulliver/thirdparty/pear/README +++ /dev/null @@ -1,18 +0,0 @@ - PEAR - PHP Extension and Application Repository - =============================================== - Dedicated to Malin Bakken, born 1999-11-21 - -WHAT IS PEAR? - -PEAR is a code repository for PHP extensions and PHP library code -similar to TeX's CTAN and Perl's CPAN. - -The intention behind PEAR is to provide a means for library code -authors to organize their code in a defined way shared by other -developers, and to give the PHP community a single source for such -code. - - -DOCUMENTATION - -Documentation for PEAR can be found at http://pear.php.net/manual/. diff --git a/gulliver/thirdparty/pear/SOAP/Base.php b/gulliver/thirdparty/pear/SOAP/Base.php deleted file mode 100644 index 938e63066..000000000 --- a/gulliver/thirdparty/pear/SOAP/Base.php +++ /dev/null @@ -1,1116 +0,0 @@ - Original Author - * @author Shane Caraveo Port to PEAR and more - * @author Chuck Hagenbuch Maintenance - * @author Jan Schneider Maintenance - * @copyright 2003-2007 The PHP Group - * @license http://www.php.net/license/2_02.txt PHP License 2.02 - * @link http://pear.php.net/package/SOAP - */ - -define('MAIL_MIMEPART_CRLF', "\r\n"); -require_once 'PEAR.php'; - -if (!defined('INF')) { - define('INF', 1.8e307); -} -if (!defined('NAN')) { - define('NAN', 0.0); -} - -define('SOAP_LIBRARY_VERSION', '0.11.0'); -define('SOAP_LIBRARY_NAME', 'PEAR-SOAP 0.11.0-beta'); - -// Set schema version. -define('SOAP_XML_SCHEMA_VERSION', 'http://www.w3.org/2001/XMLSchema'); -define('SOAP_XML_SCHEMA_INSTANCE', 'http://www.w3.org/2001/XMLSchema-instance'); -define('SOAP_XML_SCHEMA_1999', 'http://www.w3.org/1999/XMLSchema'); -define('SOAP_SCHEMA', 'http://schemas.xmlsoap.org/wsdl/soap/'); -define('SOAP_SCHEMA_ENCODING', 'http://schemas.xmlsoap.org/soap/encoding/'); -define('SOAP_ENVELOP', 'http://schemas.xmlsoap.org/soap/envelope/'); - -define('SCHEMA_DISCO', 'http://schemas.xmlsoap.org/disco/'); -define('SCHEMA_DISCO_SCL', 'http://schemas.xmlsoap.org/disco/scl/'); - -define('SCHEMA_SOAP', 'http://schemas.xmlsoap.org/wsdl/soap/'); -define('SCHEMA_SOAP12', 'http://schemas.xmlsoap.org/wsdl/soap12/'); -define('SCHEMA_SOAP_HTTP', 'http://schemas.xmlsoap.org/soap/http'); -define('SCHEMA_WSDL_HTTP', 'http://schemas.xmlsoap.org/wsdl/http/'); -define('SCHEMA_MIME', 'http://schemas.xmlsoap.org/wsdl/mime/'); -define('SCHEMA_WSDL', 'http://schemas.xmlsoap.org/wsdl/'); -define('SCHEMA_DIME', 'http://schemas.xmlsoap.org/ws/2002/04/dime/wsdl/'); -define('SCHEMA_CONTENT', 'http://schemas.xmlsoap.org/ws/2002/04/content-type/'); -define('SCHEMA_REF', 'http://schemas.xmlsoap.org/ws/2002/04/reference/'); - -define('SOAP_DEFAULT_ENCODING', 'UTF-8'); - -class SOAP_Base_Object extends PEAR -{ - - /** - * Supported encodings, limited by XML extension. - * - * @var array $_encodings - */ - var $_encodings = array('ISO-8859-1', 'US-ASCII', 'UTF-8'); - - /** - * Fault code. - * - * @var string $_myfaultcode - */ - var $_myfaultcode = ''; - - /** - * Recent PEAR_Error object. - * - * @var PEAR_Error $fault - */ - var $fault = null; - - /** - * Constructor. - * - * @param string $faultcode Error code. - */ - function SOAP_Base_Object($faultcode = 'Client') - { - $this->_myfaultcode = $faultcode; - parent::PEAR('SOAP_Fault'); - } - - /** - * Raises a SOAP error. - * - * Please refer to the SOAP definition for an impression of what a certain - * parameter stands for. - * - * @param string|object $str Error message or object. - * @param string $detail Detailed error message. - * @param string $actorURI - * @param mixed $code - * @param mixed $mode - * @param mixed $options - * @param boolean $skipmsg - */ - function &_raiseSoapFault($str, $detail = '', $actorURI = '', $code = null, - $mode = null, $options = null, $skipmsg = false) - { - // Pass through previous faults. - $is_instance = isset($this) && is_a($this, 'SOAP_Base_Object'); - if (is_object($str)) { - $fault =& $str; - } else { - if (!$code) { - $code = $is_instance ? $this->_myfaultcode : 'Client'; - } - require_once 'SOAP/Fault.php'; - $fault = new SOAP_Fault($str, - $code, - $actorURI, - $detail, - $mode, - $options); - } - if ($is_instance) { - $this->fault =& $fault; - } - - return $fault; - } - - function _isfault() - { - return $this->fault != null; - } - - function &_getfault() - { - return $this->fault; - } - -} - -/** - * Common base class of all SOAP classes. - * - * @access public - * @package SOAP - * @author Shane Caraveo Conversion to PEAR and updates - */ -class SOAP_Base extends SOAP_Base_Object -{ - var $_XMLSchema = array('http://www.w3.org/2001/XMLSchema', - 'http://www.w3.org/1999/XMLSchema'); - var $_XMLSchemaVersion = 'http://www.w3.org/2001/XMLSchema'; - - // load types into typemap array - var $_typemap = array( - 'http://www.w3.org/2001/XMLSchema' => array( - 'string' => 'string', - 'boolean' => 'boolean', - 'float' => 'float', - 'double' => 'float', - 'decimal' => 'float', - 'duration' => 'integer', - 'dateTime' => 'string', - 'time' => 'string', - 'date' => 'string', - 'gYearMonth' => 'integer', - 'gYear' => 'integer', - 'gMonthDay' => 'integer', - 'gDay' => 'integer', - 'gMonth' => 'integer', - 'hexBinary' => 'string', - 'base64Binary' => 'string', - // derived datatypes - 'normalizedString' => 'string', - 'token' => 'string', - 'language' => 'string', - 'NMTOKEN' => 'string', - 'NMTOKENS' => 'string', - 'Name' => 'string', - 'NCName' => 'string', - 'ID' => 'string', - 'IDREF' => 'string', - 'IDREFS' => 'string', - 'ENTITY' => 'string', - 'ENTITIES' => 'string', - 'integer' => 'integer', - 'nonPositiveInteger' => 'integer', - 'negativeInteger' => 'integer', - // longs (64bit ints) are not supported cross-platform. - 'long' => 'string', - 'int' => 'integer', - 'short' => 'integer', - 'byte' => 'string', - 'nonNegativeInteger' => 'integer', - 'unsignedLong' => 'integer', - 'unsignedInt' => 'integer', - 'unsignedShort' => 'integer', - 'unsignedByte' => 'integer', - 'positiveInteger' => 'integer', - 'anyType' => 'string', - 'anyURI' => 'string', - 'QName' => 'string' - ), - 'http://www.w3.org/1999/XMLSchema' => array( - 'i4' => 'integer', - 'int' => 'integer', - 'boolean' => 'boolean', - 'string' => 'string', - 'double' => 'float', - 'float' => 'float', - 'dateTime' => 'string', - 'timeInstant' => 'string', - 'base64Binary' => 'string', - 'base64' => 'string', - 'ur-type' => 'string' - ), - 'http://schemas.xmlsoap.org/soap/encoding/' => array( - 'base64' => 'string', - 'array' => 'array', - 'Array' => 'array', - 'Struct' => 'array') - ); - - /** - * Default class name to use for decoded response objects. - * - * @var string $_defaultObjectClassname - */ - var $_defaultObjectClassname = 'stdClass'; - - /** - * Hash with used namespaces. - * - * @array - */ - var $_namespaces; - - /** - * The default namespace. - * - * @string - */ - var $_namespace; - - var $_xmlEntities = array('&' => '&', - '<' => '<', - '>' => '>', - "'" => ''', - '"' => '"'); - - var $_doconversion = false; - - var $_attachments = array(); - - var $_wsdl = null; - - /** - * True if we use section 5 encoding, or false if this is literal. - * - * @var boolean $_section5 - */ - var $_section5 = true; - - // Handle type to class mapping. - var $_auto_translation = false; - var $_type_translation = array(); - - /** - * Constructor. - * - * @param string $faultcode Error code. - */ - function SOAP_Base($faultcode = 'Client') - { - parent::SOAP_Base_Object($faultcode); - $this->_resetNamespaces(); - } - - /** - * Sets the default namespace. - * - * @param string $namespace The default namespace. - */ - function setDefaultNamespace($namespace) - { - $this->_namespace = $namespace; - } - - function _resetNamespaces() - { - $this->_namespaces = array( - 'http://schemas.xmlsoap.org/soap/envelope/' => 'SOAP-ENV', - 'http://www.w3.org/2001/XMLSchema' => 'xsd', - 'http://www.w3.org/2001/XMLSchema-instance' => 'xsi', - 'http://schemas.xmlsoap.org/soap/encoding/' => 'SOAP-ENC'); - } - - /** - * Sets the schema version used in the SOAP message. - * - * @access private - * @see $_XMLSchema - * - * @param string $schemaVersion The schema version. - */ - function _setSchemaVersion($schemaVersion) - { - if (!in_array($schemaVersion, $this->_XMLSchema)) { - return $this->_raiseSoapFault("unsuported XMLSchema $schemaVersion"); - } - $this->_XMLSchemaVersion = $schemaVersion; - $tmpNS = array_flip($this->_namespaces); - $tmpNS['xsd'] = $this->_XMLSchemaVersion; - $tmpNS['xsi'] = $this->_XMLSchemaVersion . '-instance'; - $this->_namespaces = array_flip($tmpNS); - } - - function _getNamespacePrefix($ns) - { - if ($this->_namespace && $ns == $this->_namespace) { - return ''; - } - if (isset($this->_namespaces[$ns])) { - return $this->_namespaces[$ns]; - } - $prefix = 'ns' . count($this->_namespaces); - $this->_namespaces[$ns] = $prefix; - return $prefix; - } - - function _getNamespaceForPrefix($prefix) - { - $flipped = array_flip($this->_namespaces); - if (isset($flipped[$prefix])) { - return $flipped[$prefix]; - } - return null; - } - - function _isSoapValue(&$value) - { - return is_a($value, 'SOAP_Value'); - } - - function _serializeValue(&$value, $name = '', $type = false, - $elNamespace = null, $typeNamespace = null, - $options = array(), $attributes = array(), - $artype = '') - { - $namespaces = array(); - $arrayType = $array_depth = $xmlout_value = null; - $typePrefix = $elPrefix = $xmlout_offset = $xmlout_arrayType = ''; - $xmlout_type = $xmlns = $ptype = $array_type_ns = ''; - - if (!$name || is_numeric($name)) { - $name = 'item'; - } - - if ($this->_wsdl) { - list($ptype, $arrayType, $array_type_ns, $array_depth) - = $this->_wsdl->getSchemaType($type, $name, $typeNamespace); - } - - if (!$arrayType) { - $arrayType = $artype; - } - if (!$ptype) { - $ptype = $this->_getType($value); - } - if (!$type) { - $type = $ptype; - } - - if (strcasecmp($ptype, 'Struct') == 0 || - strcasecmp($type, 'Struct') == 0) { - // Struct - $vars = null; - if (is_object($value)) { - $vars = get_object_vars($value); - } else { - $vars = &$value; - } - if (is_array($vars)) { - foreach (array_keys($vars) as $k) { - // Hide private vars. - if ($k[0] == '_') { - continue; - } - if (is_object($vars[$k])) { - if (is_a($vars[$k], 'SOAP_Value')) { - $xmlout_value .= $vars[$k]->serialize($this); - } else { - // XXX get the members and serialize them instead - // converting to an array is more overhead than we - // should really do. - $xmlout_value .= $this->_serializeValue(get_object_vars($vars[$k]), $k, false, $this->_section5 ? null : $elNamespace); - } - } else { - $xmlout_value .= $this->_serializeValue($vars[$k], $k, false, $this->_section5 ? null : $elNamespace); - } - } - } - } elseif (strcasecmp($ptype, 'Array') == 0 || - strcasecmp($type, 'Array') == 0) { - // Array. - $typeNamespace = SOAP_SCHEMA_ENCODING; - $orig_type = $type; - $type = 'Array'; - $numtypes = 0; - $value = (array)$value; - // XXX this will be slow on larger arrays. Basically, it flattens - // arrays to allow us to serialize multi-dimensional arrays. We - // only do this if arrayType is set, which will typically only - // happen if we are using WSDL - if (isset($options['flatten']) || - ($arrayType && - (strchr($arrayType, ',') || strstr($arrayType, '][')))) { - $numtypes = $this->_multiArrayType($value, $arrayType, - $ar_size, $xmlout_value); - } - - $array_type = $array_type_prefix = ''; - if ($numtypes != 1) { - $arrayTypeQName = new QName($arrayType); - $arrayType = $arrayTypeQName->name; - $array_types = array(); - $array_val = null; - - // Serialize each array element. - $ar_size = count($value); - foreach ($value as $array_val) { - if ($this->_isSoapValue($array_val)) { - $array_type = $array_val->type; - $array_types[$array_type] = 1; - $array_type_ns = $array_val->type_namespace; - $xmlout_value .= $array_val->serialize($this); - } else { - $array_type = $this->_getType($array_val); - $array_types[$array_type] = 1; - $xmlout_value .= $this->_serializeValue($array_val, 'item', $array_type, $this->_section5 ? null : $elNamespace); - } - } - - $xmlout_offset = ' SOAP-ENC:offset="[0]"'; - if (!$arrayType) { - $numtypes = count($array_types); - if ($numtypes == 1) { - $arrayType = $array_type; - } - // Using anyType is more interoperable. - if ($array_type == 'Struct') { - $array_type = ''; - } elseif ($array_type == 'Array') { - $arrayType = 'anyType'; - $array_type_prefix = 'xsd'; - } else { - if (!$arrayType) { - $arrayType = $array_type; - } - } - } - } - if (!$arrayType || $numtypes > 1) { - // Should reference what schema we're using. - $arrayType = 'xsd:anyType'; - } else { - if ($array_type_ns) { - $array_type_prefix = $this->_getNamespacePrefix($array_type_ns); - } elseif (isset($this->_typemap[$this->_XMLSchemaVersion][$arrayType])) { - $array_type_prefix = $this->_namespaces[$this->_XMLSchemaVersion]; - } - if ($array_type_prefix) { - $arrayType = $array_type_prefix . ':' . $arrayType; - } - } - - $xmlout_arrayType = ' SOAP-ENC:arrayType="' . $arrayType; - if ($array_depth != null) { - for ($i = 0; $i < $array_depth; $i++) { - $xmlout_arrayType .= '[]'; - } - } - $xmlout_arrayType .= "[$ar_size]\""; - } elseif ($this->_isSoapValue($value)) { - $xmlout_value = $value->serialize($this); - } elseif ($type == 'string') { - $xmlout_value = htmlspecialchars($value); - } elseif ($type == 'rawstring') { - $xmlout_value =& $value; - } elseif ($type == 'boolean') { - $xmlout_value = $value ? 'true' : 'false'; - } else { - $xmlout_value =& $value; - } - - // Add namespaces. - if ($elNamespace) { - $elPrefix = $this->_getNamespacePrefix($elNamespace); - if ($elPrefix) { - $xmlout_name = "$elPrefix:$name"; - } else { - $xmlout_name = $name; - } - } else { - $xmlout_name = $name; - } - - if ($typeNamespace) { - $typePrefix = $this->_getNamespacePrefix($typeNamespace); - if ($typePrefix) { - $xmlout_type = "$typePrefix:$type"; - } else { - $xmlout_type = $type; - } - } elseif ($type && - isset($this->_typemap[$this->_XMLSchemaVersion][$type])) { - $typePrefix = $this->_namespaces[$this->_XMLSchemaVersion]; - if ($typePrefix) { - $xmlout_type = "$typePrefix:$type"; - } else { - $xmlout_type = $type; - } - } - - // Handle additional attributes. - $xml_attr = ''; - if (count($attributes)) { - foreach ($attributes as $k => $v) { - $kqn = new QName($k); - $vqn = new QName($v); - $xml_attr .= ' ' . $kqn->fqn() . '="' . $vqn->fqn() . '"'; - } - } - - // Store the attachment for mime encoding. - if (isset($options['attachment']) && - !PEAR::isError($options['attachment'])) { - $this->_attachments[] = $options['attachment']; - } - - if ($this->_section5) { - if ($xmlout_type) { - $xmlout_type = " xsi:type=\"$xmlout_type\""; - } - if (is_null($xmlout_value)) { - $xml = "\r\n<$xmlout_name$xmlout_type$xmlns$xmlout_arrayType" . - "$xml_attr xsi:nil=\"true\"/>"; - } else { - $xml = "\r\n<$xmlout_name$xmlout_type$xmlns$xmlout_arrayType" . - "$xmlout_offset$xml_attr>$xmlout_value"; - } - } else { - if (is_null($xmlout_value)) { - $xml = "\r\n<$xmlout_name$xmlns$xml_attr/>"; - } else { - $xml = "\r\n<$xmlout_name$xmlns$xml_attr>" . - $xmlout_value . ""; - } - } - - return $xml; - } - - /** - * Converts a PHP type to a SOAP type. - * - * @access private - * - * @param string $value The value to inspect. - * - * @return string The value's SOAP type. - */ - function _getType(&$value) - { - $type = gettype($value); - switch ($type) { - case 'object': - if (is_a($value, 'soap_value')) { - $type = $value->type; - } else { - $type = 'Struct'; - } - break; - - case 'array': - // Hashes are always handled as structs. - if ($this->_isHash($value)) { - $type = 'Struct'; - } else { - $ar_size = count($value); - reset($value); - $key1 = key($value); - if ($ar_size > 0 && is_a($key1, 'SOAP_Value')) { - // FIXME: for non-wsdl structs that are all the same type - $key2 = key($value); - if ($ar_size > 1 && - $this->_isSoapValue($key1) && - $this->_isSoapValue($key2) && - $key1->name != $key2->name) { - // This is a struct, not an array. - $type = 'Struct'; - } else { - $type = 'Array'; - } - } else { - $type = 'Array'; - } - } - break; - - case 'integer': - case 'long': - $type = 'int'; - break; - - case 'boolean': - break; - - case 'double': - // double is deprecated in PHP 4.2 and later. - $type = 'float'; - break; - - case 'null': - $type = ''; - break; - - case 'string': - default: - break; - } - - return $type; - } - - function _multiArrayType($value, &$type, &$size, &$xml) - { - if (is_array($value)) { - // Seems we have a multi dimensional array, figure it out if we - // do. - for ($i = 0, $c = count($value); $i < $c; ++$i) { - $this->_multiArrayType($value[$i], $type, $size, $xml); - } - - $sz = count($value); - if ($size) { - $size = $sz . ',' . $size; - } else { - $size = $sz; - } - return 1; - } elseif (is_object($value)) { - $type = $value->type; - $xml .= $value->serialize($this); - } else { - $type = $this->_getType($value); - $xml .= $this->_serializeValue($value, 'item', $type); - } - $size = null; - - return 1; - } - - /** - * Returns whether a type is a base64 type. - * - * @param string $type A type name. - * - * @return boolean True if the type name is a base64 type. - */ - function _isBase64Type($type) - { - return $type == 'base64' || $type == 'base64Binary'; - } - - /** - * Returns whether an array is a hash. - * - * @param array $a An array to check. - * - * @return boolean True if the specified array is a hash. - */ - function _isHash(&$a) - { - // I really dislike having to loop through this in PHP code, really - // large arrays will be slow. We need a C function to do this. - $it = 0; - foreach ($a as $k => $v) { - // Checking the type is faster than regexp. - if (!is_int($k)) { - return true; - } - // If someone has a large hash they should really be defining the - // type. - if ($it++ > 10) { - $this->_raiseSoapFault('Large associative array passed where a SOAP_Value was expected'); - return false; - } - } - return false; - } - - function _un_htmlentities($string) - { - $trans_tbl = get_html_translation_table(HTML_ENTITIES); - $trans_tbl = array_flip($trans_tbl); - return strtr($string, $trans_tbl); - } - - /** - * Converts a SOAP_Value object into a StdClass PHP object - */ - function &_decode(&$soapval) - { - if (!$this->_isSoapValue($soapval)) { - return $soapval; - } elseif (is_array($soapval->value)) { - if ($soapval->type != 'Array') { - $classname = $this->_defaultObjectClassname; - if (isset($this->_type_translation[$soapval->tqn->fqn()])) { - // This will force an error in PHP if the class does not - // exist. - $classname = $this->_type_translation[$soapval->tqn->fqn()]; - } elseif (isset($this->_type_translation[$soapval->type])) { - // This will force an error in PHP if the class does not - // exist. - $classname = $this->_type_translation[$soapval->type]; - } elseif ($this->_auto_translation) { - if (class_exists($soapval->type)) { - $classname = $soapval->type; - } elseif ($this->_wsdl) { - $t = $this->_wsdl->getComplexTypeNameForElement($soapval->name, $soapval->namespace); - if ($t && class_exists($t)) { - $classname = $t; - } - } - } - $return = new $classname; - } else { - $return = array(); - } - - $counter = 1; - $isstruct = !is_array($return); - foreach ($soapval->value as $item) { - if (is_object($return)) { - if ($this->_wsdl) { - // Get this child's WSDL information. - // /$soapval->ns/$soapval->type/$item->ns/$item->name - $child_type = $this->_wsdl->getComplexTypeChildType( - $soapval->namespace, - $soapval->name, - $item->namespace, - $item->name); - if ($child_type) { - $item->type = $child_type; - } - } - if (!$isstruct || $item->type == 'Array') { - if (isset($return->{$item->name}) && - is_object($return->{$item->name})) { - $return->{$item->name} =& $this->_decode($item); - } elseif (isset($return->{$item->name}) && - is_array($return->{$item->name})) { - $return->{$item->name}[] = $this->_decode($item); - } elseif (isset($return->{$item->name})) { - $return->{$item->name} = array( - $return->{$item->name}, - $this->_decode($item) - ); - } elseif (is_array($return)) { - $return[] =& $this->_decode($item); - } else { - $return->{$item->name} =& $this->_decode($item); - } - } elseif (isset($return->{$item->name})) { - //$isstruct = false; - if (count(get_object_vars($return)) == 1) { - $d =& $this->_decode($item); - $return = array($return->{$item->name}, $d); - } else { - $d =& $this->_decode($item); - $return->{$item->name} = array($return->{$item->name}, $d); - } - } else { - $return->{$item->name} =& $this->_decode($item); - } - // Set the attributes as members in the class. - if (method_exists($return, '__set_attribute')) { - foreach ($soapval->attributes as $key => $value) { - call_user_func_array(array(&$return, - '__set_attribute'), - array($key, $value)); - } - } - } else { - if ($soapval->arrayType && $this->_isSoapValue($item)) { - if ($this->_isBase64Type($item->type) && - !$this->_isBase64Type($soapval->arrayType)) { - // Decode the value if we're losing the base64 - // type information. - $item->value = base64_decode($item->value); - } - $item->type = $soapval->arrayType; - } - if (!$isstruct) { - $return[] = $this->_decode($item); - } elseif (isset($return[$item->name])) { - $isstruct = false; - $d =& $this->_decode($item); - $return = array($return[$item->name], $d); - } else { - $return[$item->name] = $this->_decode($item); - } - } - } - - return $return; - } - - if ($soapval->type == 'boolean') { - if ($soapval->value != '0' && - strcasecmp($soapval->value, 'false') != 0) { - $soapval->value = true; - } else { - $soapval->value = false; - } - } elseif ($soapval->type && - isset($this->_typemap[SOAP_XML_SCHEMA_VERSION][$soapval->type])) { - // If we can, set variable type. - settype($soapval->value, - $this->_typemap[SOAP_XML_SCHEMA_VERSION][$soapval->type]); - } - - return $soapval->value; - } - - /** - * Creates the SOAP envelope with the SOAP envelop data. - * - * @param mixed $method - * @param array $headers - * @param string $encoding - * @param array $options - * - * @return string - */ - function makeEnvelope(&$method, &$headers, - $encoding = SOAP_DEFAULT_ENCODING, - $options = array()) - { - $smsg = $header_xml = $ns_string = ''; - - if ($headers) { - $c = count($headers); - for ($i = 0; $i < $c; $i++) { - $header_xml .= $headers[$i]->serialize($this); - } - $header_xml = "\r\n$header_xml\r\n\r\n"; - } - - if (!isset($options['input']) || $options['input'] == 'parse') { - if (is_array($method)) { - $c = count($method); - for ($i = 0; $i < $c; $i++) { - $smsg .= $method[$i]->serialize($this); - } - } else { - $smsg = $method->serialize($this); - } - } else { - $smsg = $method; - } - $body = "\r\n" . $smsg . "\r\n\r\n"; - - foreach ($this->_namespaces as $k => $v) { - $ns_string .= " xmlns:$v=\"$k\"\r\n"; - } - if ($this->_namespace) { - $ns_string .= " xmlns=\"{$this->_namespace}\"\r\n"; - } - - /* If 'use' == 'literal', we do not put in the encodingStyle. This is - * denoted by $this->_section5 being false. 'use' can be defined at a - * more granular level than we are dealing with here, so this does not - * work for all services. */ - $xml = "\r\n\r\n". - "_section5 ? ' SOAP-ENV:encodingStyle="' . SOAP_SCHEMA_ENCODING . '"' : ''). - ">\r\n". - "$header_xml$body\r\n"; - - return $xml; - } - - function _makeMimeMessage($xml, $encoding = SOAP_DEFAULT_ENCODING) - { - if (!@include_once 'Mail/mimePart.php') { - return $this->_raiseSoapFault('MIME messages are unsupported, the Mail_Mime package is not installed'); - } - - // Encode any attachments. See http://www.w3.org/TR/SOAP-attachments - // Now we have to mime encode the message. - $params = array('content_type' => 'multipart/related; type="text/xml"'); - $msg = new Mail_mimePart('', $params); - - // Add the xml part. - $params['content_type'] = 'text/xml'; - $params['charset'] = $encoding; - $params['encoding'] = 'base64'; - $msg->addSubPart($xml, $params); - - // Add the attachements - for ($i = 0, $c = count($this->_attachments); $i < $c; ++$i) { - $msg->addSubPart($this->_attachments[$i]['body'], - $this->_attachments[$i]); - } - - return $msg->encode(); - } - - // TODO: this needs to be used from the Transport system. - function _makeDIMEMessage($xml) - { - if (!@include_once 'Net/DIME.php') { - return $this->_raiseSoapFault('DIME messages are unsupported, the Net_DIME package is not installed'); - } - - // Encode any attachments. See - // http://search.ietf.org/internet-drafts/draft-nielsen-dime-soap-00.txt - // Now we have to DIME encode the message - $dime = new Net_DIME_Message(); - $msg = $dime->encodeData($xml, SOAP_ENVELOP, null, NET_DIME_TYPE_URI); - - // Add the attachments. - $c = count($this->_attachments); - for ($i = 0; $i < $c; $i++) { - $msg .= $dime->encodeData($this->_attachments[$i]['body'], - $this->_attachments[$i]['content_type'], - $this->_attachments[$i]['cid'], - NET_DIME_TYPE_MEDIA); - } - $msg .= $dime->endMessage(); - - return $msg; - } - - function _decodeMimeMessage(&$data, &$headers, &$attachments) - { - if (!@include_once 'Mail/mimeDecode.php') { - return $this->_raiseSoapFault('MIME messages are unsupported, the Mail_Mime package is not installed'); - } - - $params['include_bodies'] = true; - $params['decode_bodies'] = true; - $params['decode_headers'] = true; - - // Lame thing to have to do for decoding. - $decoder = new Mail_mimeDecode($data); - $structure = $decoder->decode($params); - - if (isset($structure->body)) { - $data = $structure->body; - $headers = $structure->headers; - - return; - } elseif (isset($structure->parts)) { - $data = $structure->parts[0]->body; - $headers = array_merge($structure->headers, - $structure->parts[0]->headers); - if (count($structure->parts) > 1) { - $mime_parts = array_splice($structure->parts,1); - // Prepare the parts for the SOAP parser. - - $c = count($mime_parts); - for ($i = 0; $i < $c; $i++) { - $p =& $mime_parts[$i]; - if (isset($p->headers['content-location'])) { - // TODO: modify location per SwA note section 3 - // http://www.w3.org/TR/SOAP-attachments - $attachments[$p->headers['content-location']] = $p->body; - } else { - $cid = 'cid:' . substr($p->headers['content-id'], 1, -1); - $attachments[$cid] = $p->body; - } - } - } - - return; - } - - $this->_raiseSoapFault('Mime parsing error', '', '', 'Server'); - } - - function _decodeDIMEMessage(&$data, &$headers, &$attachments) - { - if (!@include_once 'Net/DIME.php') { - return $this->_raiseSoapFault('DIME messages are unsupported, the Net_DIME package is not installed'); - } - - // This SHOULD be moved to the transport layer, e.g. PHP itself should - // handle parsing DIME ;) - $dime = new Net_DIME_Message(); - $err = $dime->decodeData($data); - if (PEAR::isError($err)) { - $this->_raiseSoapFault('Failed to decode the DIME message!', '', '', 'Server'); - return; - } - if (strcasecmp($dime->parts[0]['type'], SOAP_ENVELOP) != 0) { - $this->_raiseSoapFault('DIME record 1 is not a SOAP envelop!', '', '', 'Server'); - return; - } - - $data = $dime->parts[0]['data']; - // Fake it for now. - $headers['content-type'] = 'text/xml'; - $c = count($dime->parts); - for ($i = 0; $i < $c; $i++) { - $part =& $dime->parts[$i]; - // We need to handle URI's better. - $id = strncmp($part['id'], 'cid:', 4) - ? 'cid:' . $part['id'] - : $part['id']; - $attachments[$id] = $part['data']; - } - } - - /** - * @deprecated Use setTypeTranslation(). - */ - function __set_type_translation($type, $class = null) - { - $this->setTypeTranslation($type, $class); - } - - /** - * Explicitly sets the translation for a specific class. - * - * Auto translation works for all cases, but opens ANY class in the script - * to be used as a data type, and may not be desireable. - * - * @param string $type A SOAP type. - * @param string $class A PHP class name. - */ - function setTypeTranslation($type, $class = null) - { - $tq = new QName($type); - if (!$class) { - $class = $tq->name; - } - $this->_type_translation[$type]=$class; - } - -} - -/** - * Class used to handle QNAME values in XML. - * - * @access public - * @package SOAP - * @author Shane Caraveo Conversion to PEAR and updates - */ -class QName -{ - var $name = ''; - var $ns = ''; - var $namespace=''; - - function QName($name, $namespace = '') - { - if ($name && $name[0] == '{') { - preg_match('/\{(.*?)\}(.*)/', $name, $m); - $this->name = $m[2]; - $this->namespace = $m[1]; - } elseif (substr_count($name, ':') == 1) { - $s = explode(':', $name); - $s = array_reverse($s); - $this->name = $s[0]; - $this->ns = $s[1]; - $this->namespace = $namespace; - } else { - $this->name = $name; - $this->namespace = $namespace; - } - - // A little more magic than should be in a qname. - $p = strpos($this->name, '['); - if ($p) { - // TODO: Need to re-examine this logic later. - // Chop off []. - $this->arraySize = explode(',', substr($this->name, $p + 1, -$p - 2)); - $this->arrayInfo = substr($this->name, $p); - $this->name = substr($this->name, 0, $p); - } - } - - function fqn() - { - if ($this->namespace) { - return '{' . $this->namespace . '}' . $this->name; - } elseif ($this->ns) { - return $this->ns . ':' . $this->name; - } - return $this->name; - } - -} diff --git a/gulliver/thirdparty/pear/SOAP/Client.php b/gulliver/thirdparty/pear/SOAP/Client.php deleted file mode 100644 index de66e8084..000000000 --- a/gulliver/thirdparty/pear/SOAP/Client.php +++ /dev/null @@ -1,855 +0,0 @@ - Original Author - * @author Shane Caraveo Port to PEAR and more - * @author Chuck Hagenbuch Maintenance - * @author Jan Schneider Maintenance - * @copyright 2003-2005 The PHP Group - * @license http://www.php.net/license/2_02.txt PHP License 2.02 - * @link http://pear.php.net/package/SOAP - */ - -require_once 'SOAP/Value.php'; -require_once 'SOAP/Base.php'; -require_once 'SOAP/Transport.php'; -require_once 'SOAP/WSDL.php'; -require_once 'SOAP/Fault.php'; -require_once 'SOAP/Parser.php'; - -// Arnaud: the following code was taken from DataObject and adapted to suit - -// this will be horrifically slow!!!! -// NOTE: Overload SEGFAULTS ON PHP4 + Zend Optimizer -// these two are BC/FC handlers for call in PHP4/5 - -if (!class_exists('SOAP_Client_Overload')) { - if (substr(zend_version(), 0, 1) > 1) { - class SOAP_Client_Overload extends SOAP_Base { - function __call($method, $args) - { - $return = null; - $this->_call($method, $args, $return); - return $return; - } - } - } else { - if (!function_exists('clone')) { - eval('function clone($t) { return $t; }'); - } - eval(' - class SOAP_Client_Overload extends SOAP_Base { - function __call($method, $args, &$return) - { - return $this->_call($method, $args, $return); - } - }'); - } -} - -/** - * SOAP Client Class - * - * This class is the main interface for making soap requests. - * - * basic usage: - * $soapclient = new SOAP_Client( string path [ , boolean wsdl] ); - * echo $soapclient->call( string methodname [ , array parameters] ); - * - * or, if using PHP 5+ or the overload extension: - * $soapclient = new SOAP_Client( string path [ , boolean wsdl] ); - * echo $soapclient->methodname( [ array parameters] ); - * - * - * Originally based on SOAPx4 by Dietrich Ayala - * http://dietrich.ganx4.com/soapx4 - * - * @access public - * @package SOAP - * @author Shane Caraveo Conversion to PEAR and updates - * @author Stig Bakken Conversion to PEAR - * @author Dietrich Ayala Original Author - */ -class SOAP_Client extends SOAP_Client_Overload -{ - /** - * Communication endpoint. - * - * Currently the following transport formats are supported: - * - HTTP - * - SMTP - * - * Example endpoints: - * http://www.example.com/soap/server.php - * https://www.example.com/soap/server.php - * mailto:soap@example.com - * - * @see SOAP_Client() - * @var string - */ - var $_endpoint = ''; - - /** - * The SOAP PORT name that is used by the client. - * - * @var string - */ - var $_portName = ''; - - /** - * Endpoint type e.g. 'wdsl'. - * - * @var string - */ - var $_endpointType = ''; - - /** - * The received xml. - * - * @var string - */ - var $xml; - - /** - * The outgoing and incoming data stream for debugging. - * - * @var string - */ - var $wire; - - /** - * The outgoing data stream for debugging. - * - * @var string - */ - var $_last_request = null; - - /** - * The incoming data stream for debugging. - * - * @var string - */ - var $_last_response = null; - - /** - * Options. - * - * @var array - */ - var $_options = array('trace' => false); - - /** - * The character encoding used for XML parser, etc. - * - * @var string - */ - var $_encoding = SOAP_DEFAULT_ENCODING; - - /** - * The array of SOAP_Headers that we are sending. - * - * @var array - */ - var $headersOut = null; - - /** - * The headers we recieved back in the response. - * - * @var array - */ - var $headersIn = null; - - /** - * Options for the HTTP_Request class (see HTTP/Request.php). - * - * @var array - */ - var $_proxy_params = array(); - - /** - * The SOAP_Transport instance. - * - * @var SOAP_Transport - */ - var $_soap_transport = null; - - /** - * Constructor. - * - * @access public - * - * @param string $endpoint An URL. - * @param boolean $wsdl Whether the endpoint is a WSDL file. - * @param string $portName The service's port name to use. - * @param array $proxy_params Options for the HTTP_Request class - * @see HTTP_Request - * @param boolean|string $cache Use WSDL caching? The cache directory if - * a string. - */ - function SOAP_Client($endpoint, $wsdl = false, $portName = false, - $proxy_params = array(), $cache = false) - { - parent::SOAP_Base('Client'); - - $this->_endpoint = $endpoint; - $this->_portName = $portName; - $this->_proxy_params = $proxy_params; - - // This hack should perhaps be removed as it might cause unexpected - // behaviour. - $wsdl = $wsdl - ? $wsdl - : strtolower(substr($endpoint, -4)) == 'wsdl'; - - // make values - if ($wsdl) { - $this->_endpointType = 'wsdl'; - // instantiate wsdl class - $this->_wsdl = new SOAP_WSDL($this->_endpoint, - $this->_proxy_params, - $cache); - if ($this->_wsdl->fault) { - $this->_raiseSoapFault($this->_wsdl->fault); - } - } - } - - function _reset() - { - $this->xml = null; - $this->wire = null; - $this->_last_request = null; - $this->_last_response = null; - $this->headersIn = null; - $this->headersOut = null; - } - - /** - * Sets the character encoding. - * - * Limited to 'UTF-8', 'US_ASCII' and 'ISO-8859-1'. - * - * @access public - * - * @param string encoding - * - * @return mixed SOAP_Fault on error. - */ - function setEncoding($encoding) - { - if (in_array($encoding, $this->_encodings)) { - $this->_encoding = $encoding; - return; - } - return $this->_raiseSoapFault('Invalid Encoding'); - } - - /** - * Adds a header to the envelope. - * - * @access public - * - * @param SOAP_Header $soap_value A SOAP_Header or an array with the - * elements 'name', 'namespace', - * 'mustunderstand', and 'actor' to send - * as a header. - */ - function addHeader($soap_value) - { - // Add a new header to the message. - if (is_a($soap_value, 'SOAP_Header')) { - $this->headersOut[] = $soap_value; - } elseif (is_array($soap_value)) { - // name, value, namespace, mustunderstand, actor - $this->headersOut[] = new SOAP_Header($soap_value[0], - null, - $soap_value[1], - $soap_value[2], - $soap_value[3]); - } else { - $this->_raiseSoapFault('Invalid parameter provided to addHeader(). Must be an array or a SOAP_Header.'); - } - } - - /** - * Calls a method on the SOAP endpoint. - * - * The namespace parameter is overloaded to accept an array of options - * that can contain data necessary for various transports if it is used as - * an array, it MAY contain a namespace value and a soapaction value. If - * it is overloaded, the soapaction parameter is ignored and MUST be - * placed in the options array. This is done to provide backwards - * compatibility with current clients, but may be removed in the future. - * The currently supported values are:
-     *   namespace
-     *   soapaction
-     *   timeout (HTTP socket timeout)
-     *   transfer-encoding (SMTP, Content-Transfer-Encoding: header)
-     *   from (SMTP, From: header)
-     *   subject (SMTP, Subject: header)
-     *   headers (SMTP, hash of extra SMTP headers)
-     * 
- * - * @access public - * - * @param string $method The method to call. - * @param array $params The method parameters. - * @param string|array $namespace Namespace or hash with options. - * @param string $soapAction - * - * @return mixed The method result or a SOAP_Fault on error. - */ - function &call($method, &$params, $namespace = false, $soapAction = false) - { - $this->headersIn = null; - $this->_last_request = null; - $this->_last_response = null; - $this->wire = null; - $this->xml = null; - - $soap_data = $this->_generate($method, $params, $namespace, $soapAction); - if (PEAR::isError($soap_data)) { - $fault = $this->_raiseSoapFault($soap_data); - return $fault; - } - - // _generate() may have changed the endpoint if the WSDL has more - // than one service, so we need to see if we need to generate a new - // transport to hook to a different URI. Since the transport protocol - // can also change, we need to get an entirely new object. This could - // probably be optimized. - if (!$this->_soap_transport || - $this->_endpoint != $this->_soap_transport->url) { - $this->_soap_transport =& SOAP_Transport::getTransport($this->_endpoint); - if (PEAR::isError($this->_soap_transport)) { - $fault =& $this->_soap_transport; - $this->_soap_transport = null; - $fault = $this->_raiseSoapFault($fault); - return $fault; - } - } - $this->_soap_transport->encoding = $this->_encoding; - - // Send the message. - $transport_options = array_merge_recursive($this->_proxy_params, - $this->_options); - $this->xml = $this->_soap_transport->send($soap_data, $transport_options); - - // Save the wire information for debugging. - if ($this->_options['trace']) { - $this->_last_request = $this->_soap_transport->outgoing_payload; - $this->_last_response = $this->_soap_transport->incoming_payload; - $this->wire = $this->getWire(); - } - if ($this->_soap_transport->fault) { - $fault = $this->_raiseSoapFault($this->xml); - return $fault; - } - - if (isset($this->_options['result']) && - $this->_options['result'] != 'parse') { - return $this->xml; - } - - $this->__result_encoding = $this->_soap_transport->result_encoding; - - $result = &$this->parseResponse($this->xml, $this->__result_encoding, - $this->_soap_transport->attachments); - return $result; - } - - /** - * Sets an option to use with the transport layers. - * - * For example: - * - * $soapclient->setOpt('curl', CURLOPT_VERBOSE, 1) - * - * to pass a specific option to curl if using an SSL connection. - * - * @access public - * - * @param string $category Category to which the option applies or option - * name. - * @param string $option An option name if $category is a category name, - * an option value if $category is an option name. - * @param string $value An option value if $category is a category - * name. - */ - function setOpt($category, $option, $value = null) - { - if (!is_null($value)) { - if (!isset($this->_options[$category])) { - $this->_options[$category] = array(); - } - $this->_options[$category][$option] = $value; - } else { - $this->_options[$category] = $option; - } - } - - /** - * Call method supporting the overload extension. - * - * If the overload extension is loaded, you can call the client class with - * a soap method name: - * - * $soap = new SOAP_Client(....); - * $value = $soap->getStockQuote('MSFT'); - * - * - * @access public - * - * @param string $method The method to call. - * @param array $params The method parameters. - * @param mixed $return_value Will get the method's return value - * assigned. - * - * @return boolean Always true. - */ - function _call($method, $params, &$return_value) - { - // Overloading lowercases the method name, we need to look into the - // WSDL and try to find the correct method name to get the correct - // case for the call. - if ($this->_wsdl) { - $this->_wsdl->matchMethod($method); - } - - $return_value =& $this->call($method, $params); - - return true; - } - - /** - * @deprecated Use getLastRequest(). - */ - function &__getlastrequest() - { - $request = $this->getLastRequest(); - return $request; - } - - /** - * Returns the XML content of the last SOAP request. - * - * @return string The last request. - */ - function getLastRequest() - { - return $this->_last_request; - } - - /** - * @deprecated Use getLastResponse(). - */ - function &__getlastresponse() - { - $response =& $this->getLastResponse; - return $response; - } - - /** - * Returns the XML content of the last SOAP response. - * - * @return string The last response. - */ - function getLastResponse() - { - return $this->_last_response; - } - - /** - * @deprecated Use setUse(). - */ - function __use($use) - { - $this->setUse($use); - } - - /** - * Sets the SOAP encoding. - * - * @param string $use Either 'literal' or 'encoded' (section 5). - */ - function setUse($use) - { - $this->_options['use'] = $use; - } - - /** - * @deprecated Use setStyle(). - */ - function __style($style) - { - $this->setStyle($style); - } - - /** - * Sets the SOAP encoding style. - * - * @param string $style Either 'document' or 'rpc'. - */ - function setStyle($style) - { - $this->_options['style'] = $style; - } - - /** - * @deprecated Use setTrace(). - */ - function __trace($level) - { - $this->setTrace($level); - } - - /** - * Sets whether to trace the traffic on the transport level. - * - * @see getWire() - * - * @param boolean $trace - */ - function setTrace($trace) - { - $this->_options['trace'] = $trace; - } - - function _generate($method, &$params, $namespace = false, - $soapAction = false) - { - $this->fault = null; - $this->_options['input'] = 'parse'; - $this->_options['result'] = 'parse'; - $this->_options['parameters'] = false; - - if ($params && gettype($params) != 'array') { - $params = array($params); - } - - if (gettype($namespace) == 'array') { - foreach ($namespace as $optname => $opt) { - $this->_options[strtolower($optname)] = $opt; - } - if (isset($this->_options['namespace'])) { - $namespace = $this->_options['namespace']; - } else { - $namespace = false; - } - } else { - // We'll place $soapAction into our array for usage in the - // transport. - $this->_options['soapaction'] = $soapAction; - $this->_options['namespace'] = $namespace; - } - - if ($this->_endpointType == 'wsdl') { - $this->_setSchemaVersion($this->_wsdl->xsd); - - // Get port name. - if (!$this->_portName) { - $this->_portName = $this->_wsdl->getPortName($method); - } - if (PEAR::isError($this->_portName)) { - return $this->_raiseSoapFault($this->_portName); - } - - // Get endpoint. - $this->_endpoint = $this->_wsdl->getEndpoint($this->_portName); - if (PEAR::isError($this->_endpoint)) { - return $this->_raiseSoapFault($this->_endpoint); - } - - // Get operation data. - $opData = $this->_wsdl->getOperationData($this->_portName, $method); - - if (PEAR::isError($opData)) { - return $this->_raiseSoapFault($opData); - } - $namespace = $opData['namespace']; - $this->_options['style'] = $opData['style']; - $this->_options['use'] = $opData['input']['use']; - $this->_options['soapaction'] = $opData['soapAction']; - - // Set input parameters. - if ($this->_options['input'] == 'parse') { - $this->_options['parameters'] = $opData['parameters']; - $nparams = array(); - if (isset($opData['input']['parts']) && - count($opData['input']['parts'])) { - foreach ($opData['input']['parts'] as $name => $part) { - $xmlns = ''; - $attrs = array(); - // Is the name a complex type? - if (isset($part['element'])) { - $xmlns = $this->_wsdl->namespaces[$part['namespace']]; - $part = $this->_wsdl->elements[$part['namespace']][$part['type']]; - $name = $part['name']; - } - if (isset($params[$name]) || - $this->_wsdl->getDataHandler($name, $part['namespace'])) { - $nparams[$name] =& $params[$name]; - } else { - // We now force an associative array for - // parameters if using WSDL. - return $this->_raiseSoapFault("The named parameter $name is not in the call parameters."); - } - if (gettype($nparams[$name]) != 'object' || - !is_a($nparams[$name], 'SOAP_Value')) { - // Type is likely a qname, split it apart, and get - // the type namespace from WSDL. - $qname = new QName($part['type']); - if ($qname->ns) { - $type_namespace = $this->_wsdl->namespaces[$qname->ns]; - } elseif (isset($part['namespace'])) { - $type_namespace = $this->_wsdl->namespaces[$part['namespace']]; - } else { - $type_namespace = null; - } - $qname->namespace = $type_namespace; - $pqname = $name; - if ($xmlns) { - $pqname = '{' . $xmlns . '}' . $name; - } - $nparams[$name] = new SOAP_Value($pqname, - $qname->fqn(), - $nparams[$name], - $attrs); - } else { - // WSDL fixups to the SOAP value. - } - } - } - $params =& $nparams; - unset($nparams); - } - } else { - $this->_setSchemaVersion(SOAP_XML_SCHEMA_VERSION); - } - - // Serialize the message. - $this->_section5 = (!isset($this->_options['use']) || - $this->_options['use'] != 'literal'); - - if (!isset($this->_options['style']) || - $this->_options['style'] == 'rpc') { - $this->_options['style'] = 'rpc'; - $this->docparams = true; - $mqname = new QName($method, $namespace); - $methodValue = new SOAP_Value($mqname->fqn(), 'Struct', $params); - $soap_msg = $this->makeEnvelope($methodValue, - $this->headersOut, - $this->_encoding, - $this->_options); - } else { - if (!$params) { - $mqname = new QName($method, $namespace); - $mynull = null; - $params = new SOAP_Value($mqname->fqn(), 'Struct', $mynull); - } elseif ($this->_options['input'] == 'parse') { - if (is_array($params)) { - $nparams = array(); - $keys = array_keys($params); - foreach ($keys as $k) { - if (gettype($params[$k]) != 'object') { - $nparams[] = new SOAP_Value($k, - false, - $params[$k]); - } else { - $nparams[] =& $params[$k]; - } - } - $params =& $nparams; - } - if ($this->_options['parameters']) { - $mqname = new QName($method, $namespace); - $params = new SOAP_Value($mqname->fqn(), - 'Struct', - $params); - } - } - $soap_msg = $this->makeEnvelope($params, - $this->headersOut, - $this->_encoding, - $this->_options); - } - unset($this->headersOut); - - if (PEAR::isError($soap_msg)) { - return $this->_raiseSoapFault($soap_msg); - } - - // Handle MIME or DIME encoding. - // TODO: DIME encoding should move to the transport, do it here for - // now and for ease of getting it done. - if (count($this->_attachments)) { - if ((isset($this->_options['attachments']) && - $this->_options['attachments'] == 'Mime') || - isset($this->_options['Mime'])) { - $soap_msg = $this->_makeMimeMessage($soap_msg, $this->_encoding); - } else { - // default is dime - $soap_msg = $this->_makeDIMEMessage($soap_msg, $this->_encoding); - $this->_options['headers']['Content-Type'] = 'application/dime'; - } - if (PEAR::isError($soap_msg)) { - return $this->_raiseSoapFault($soap_msg); - } - } - - // Instantiate client. - if (is_array($soap_msg)) { - $soap_data = $soap_msg['body']; - if (count($soap_msg['headers'])) { - if (isset($this->_options['headers'])) { - $this->_options['headers'] = array_merge($this->_options['headers'], $soap_msg['headers']); - } else { - $this->_options['headers'] = $soap_msg['headers']; - } - } - } else { - $soap_data = $soap_msg; - } - - return $soap_data; - } - - /** - * @deprecated Use parseResponse(). - */ - function &__parse(&$response, $encoding, &$attachments) - { - return $this->parseResponse($response, $encoding, $attachments); - } - - /** - * Parses a SOAP response. - * - * @see SOAP_Parser:: - * - * @param string $response XML content of SOAP response. - * @param string $encoding Character set encoding, defaults to 'UTF-8'. - * @param array $attachments List of attachments. - */ - function &parseResponse($response, $encoding, &$attachments) - { - // Parse the response. - $response = new SOAP_Parser($response, $encoding, $attachments); - if ($response->fault) { - $fault =& $this->_raiseSoapFault($response->fault); - return $fault; - } - - // Return array of parameters. - $return =& $response->getResponse(); - $headers =& $response->getHeaders(); - if ($headers) { - $this->headersIn =& $this->_decodeResponse($headers, false); - } - - $decoded = &$this->_decodeResponse($return); - return $decoded; - } - - /** - * Converts a complex SOAP_Value into a PHP Array - * - * @param SOAP_Value $response value object - * @param boolean $shift FIXME - * @return Array - */ - function &_decodeResponse($response, $shift = true) - { - if (!$response) { - $decoded = null; - return $decoded; - } - - // Check for valid response. - if (PEAR::isError($response)) { - $fault =& $this->_raiseSoapFault($response); - return $fault; - } elseif (!is_a($response, 'soap_value')) { - $fault =& $this->_raiseSoapFault("Didn't get SOAP_Value object back from client"); - return $fault; - } - - // Decode to native php datatype. - $returnArray =& $this->_decode($response); - - // Fault? - if (PEAR::isError($returnArray)) { - $fault =& $this->_raiseSoapFault($returnArray); - return $fault; - } - - if (is_object($returnArray) && - strcasecmp(get_class($returnArray), 'stdClass') == 0) { - $returnArray = get_object_vars($returnArray); - } - if (is_array($returnArray)) { - if (isset($returnArray['faultcode']) || - isset($returnArray['SOAP-ENV:faultcode'])) { - $faultcode = $faultstring = $faultdetail = $faultactor = ''; - foreach ($returnArray as $k => $v) { - if (stristr($k, 'faultcode')) $faultcode = $v; - if (stristr($k, 'faultstring')) $faultstring = $v; - if (stristr($k, 'detail')) $faultdetail = $v; - if (stristr($k, 'faultactor')) $faultactor = $v; - } - $fault =& $this->_raiseSoapFault($faultstring, $faultdetail, $faultactor, $faultcode); - return $fault; - } - // Return array of return values. - if ($shift && count($returnArray) == 1) { - $decoded = array_shift($returnArray); - return $decoded; - } - return $returnArray; - } - return $returnArray; - } - - /** - * @deprecated Use getWire(). - */ - function __get_wire() - { - return $this->getWire(); - } - - /** - * Returns the outgoing and incoming traffic on the transport level. - * - * Tracing has to be enabled. - * - * @see setTrace() - * - * @return string The complete traffic between the client and the server. - */ - function getWire() - { - if ($this->_options['trace'] && - ($this->_last_request || $this->_last_response)) { - return "OUTGOING:\n\n" . - $this->_last_request . - "\n\nINCOMING\n\n" . - preg_replace("/>\r\n<", $this->_last_response); - } - - return null; - } - -} diff --git a/gulliver/thirdparty/pear/SOAP/Disco.php b/gulliver/thirdparty/pear/SOAP/Disco.php deleted file mode 100644 index 618e63d46..000000000 --- a/gulliver/thirdparty/pear/SOAP/Disco.php +++ /dev/null @@ -1,383 +0,0 @@ - - * @author Chuck Hagenbuch - * @author Jan Schneider - * @copyright 2003-2005 The PHP Group - * @license http://www.php.net/license/2_02.txt PHP License 2.02 - * @link http://pear.php.net/package/SOAP - */ - -require_once 'SOAP/Base.php'; - -class SOAP_DISCO_Server extends SOAP_Base_Object { - - var $namespaces = array(SCHEMA_WSDL => 'wsdl', SCHEMA_SOAP => 'soap'); - var $import_ns = array(); - var $wsdl = ''; - var $disco = ''; - var $_wsdl = array(); - var $_disco = array(); - var $_service_name = ''; - var $_service_ns = ''; - var $_service_desc = ''; - var $_portname = ''; - var $_bindingname = ''; - var $soap_server = NULL; - - - function SOAP_DISCO_Server($soap_server, $service_name, $service_desc = '', - $import_ns = null) - { - parent::SOAP_Base_Object('Server'); - - if ( !is_object($soap_server) - || !get_class($soap_server) == 'soap_server') return; - - $this->_service_name = $service_name; - $this->_service_ns = "urn:$service_name"; - $this->_service_desc = $service_desc; - $this->import_ns = isset($import_ns) ? $import_ns : $this->import_ns; - $this->soap_server = $soap_server; - $this->host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost'; - } - - function getDISCO() - { - $this->_generate_DISCO(); - return $this->disco; - } - - function getWSDL() - { - $this->_generate_WSDL(); - return $this->wsdl; - } - - function _generate_DISCO() - { - // DISCO - $this->_disco['disco:discovery']['attr']['xmlns:disco'] = SCHEMA_DISCO; - $this->_disco['disco:discovery']['attr']['xmlns:scl'] = SCHEMA_DISCO_SCL; - $this->_disco['disco:discovery']['scl:contractRef']['attr']['ref'] = - (array_key_exists('HTTPS', $_SERVER) && $_SERVER['HTTPS'] == 'on') - ? 'https://' . $this->host . $_SERVER['PHP_SELF'] . '?wsdl' - : 'http://' . $this->host . $_SERVER['PHP_SELF'] . '?wsdl'; - - // generate disco xml - $this->_generate_DISCO_XML($this->_disco); - } - - function _generate_WSDL() - { - // WSDL - if (is_array($this->soap_server->_namespaces)) { - // need to get: typens, xsd & SOAP-ENC - $flipped = array_flip($this->soap_server->_namespaces); - $this->namespaces[$this->_service_ns] = 'tns'; - $this->namespaces[$flipped['xsd']] = 'xsd'; - $this->namespaces[$flipped['SOAP-ENC']] = 'SOAP-ENC'; - } - - // DEFINITIONS - $this->_wsdl['definitions']['attr']['name'] = $this->_service_name; - $this->_wsdl['definitions']['attr']['targetNamespace'] = $this->_service_ns; - foreach ($this->namespaces as $ns => $prefix) { - $this->_wsdl['definitions']['attr']['xmlns:' . $prefix] = $ns; - } - $this->_wsdl['definitions']['attr']['xmlns'] = SCHEMA_WSDL; - - // Import namespaces. Seems to not work yet: wsdl.exe fom .NET can't - // handle imported complete wsdl-definitions. - if (count($this->import_ns)) { - $i = 0; - foreach ($this->import_ns as $_ns => $_location) { - $this->_wsdl['definitions']['import'][$i]['attr']['location'] = $_location; - $this->_wsdl['definitions']['import'][$i]['attr']['namespace'] = $_ns; - $i++; - } - } - $this->_wsdl['definitions']['types']['attr']['xmlns']='http://schemas.xmlsoap.org/wsdl/'; - $this->_wsdl['definitions']['types']['schema']=array(); - - // Placeholder for messages - $this->_wsdl['definitions']['message'] = array(); - - // PORTTYPE-NAME - $this->_portname = $this->_service_name . 'Port'; - $this->_wsdl['definitions']['portType']['attr']['name'] = $this->_portname; - - // BINDING-NAME - $this->_bindingname = $this->_service_name . 'Binding'; - $this->_wsdl['definitions']['binding']['attr']['name'] = $this->_bindingname; - $this->_wsdl['definitions']['binding']['attr']['type'] = 'tns:' . $this->_portname; - $this->_wsdl['definitions']['binding']['soap:binding']['attr']['style'] = 'rpc'; - $this->_wsdl['definitions']['binding']['soap:binding']['attr']['transport'] = SCHEMA_SOAP_HTTP; - - // SERVICE - $this->_wsdl['definitions']['service']['attr']['name'] = $this->_service_name . 'Service'; - $this->_wsdl['definitions']['service']['documentation']['attr'] = ''; - $this->_wsdl['definitions']['service']['documentation'] = htmlentities($this->_service_desc); - $this->_wsdl['definitions']['service']['port']['attr']['name'] = $this->_portname; - $this->_wsdl['definitions']['service']['port']['attr']['binding'] = 'tns:' . $this->_bindingname; - $this->_wsdl['definitions']['service']['port']['soap:address']['attr']['location'] = - (array_key_exists('HTTPS', $_SERVER) && $_SERVER['HTTPS'] == 'on') - ? 'https://' . $this->host . $_SERVER['PHP_SELF'] - : 'http://' . $this->host . $_SERVER['PHP_SELF']; - - // - $dispatch_keys = array_keys($this->soap_server->dispatch_objects); - $dc = count($dispatch_keys); - for ($di = 0; $di < $dc; $di++) { - $namespace = $dispatch_keys[$di]; - $namespace_objects =& $this->soap_server->dispatch_objects[$namespace]; - $oc = count($namespace_objects); - for ($oi = 0; $oi < $oc; $oi++) { - $object = $namespace_objects[$oi]; - // types definitions - $this->addSchemaFromMap($object->__typedef); - // MESSAGES - $this->addMethodsFromMap($object->__dispatch_map, $namespace, get_class($object)); - } - } - if (isset($this->soap_server->dispatch_map)) { - $this->addMethodsFromMap($this->soap_server->dispatch_map, $namespace); - } - - // generate wsdl - $this->_generate_WSDL_XML(); - } - - function &_getSchema($namespace) - { - // SCHEMA - $c = count($this->_wsdl['definitions']['types']['schema']); - for($i = 0; $i < $c; $i++) { - if ($this->_wsdl['definitions']['types']['schema'][$i]['attr']['targetNamespace'] == $namespace) { - return $this->_wsdl['definitions']['types']['schema'][$i]; - } - } - - // don't have this namespace - $schema = array(); - $schema['attr'] = array(); - $schema['complexType'] = array(); - $schema['attr']['xmlns'] = array_search('xsd',$this->namespaces); - $schema['attr']['targetNamespace'] = $namespace; - $this->_wsdl['definitions']['types']['schema'][] =& $schema; - - return $schema; - } - - function addSchemaFromMap(&$map) - { - if (!$map) { - return; - } - - foreach ($map as $_type_name => $_type_def) { - list($typens,$type) = $this->_getTypeNs($_type_name); - if ($typens == 'xsd') { - // cannot add to xsd, lets use method_namespace - $typens = 'tns'; - } - $schema =& $this->_getSchema(array_search($typens, $this->namespaces)); - if (!$this->_ifComplexTypeExists($schema['complexType'], $type)) { - $ctype =& $schema['complexType'][]; - $ctype['attr']['name'] = $type; - foreach ($_type_def as $_varname => $_vartype) { - if (!is_int($_varname)) { - list($_vartypens,$_vartype) = $this->_getTypeNs($_vartype); - $ctype['all']['attr'] = ''; - $el =& $ctype['all']['element'][]; - $el['attr']['name'] = $_varname; - $el['attr']['type'] = $_vartypens . ':' . $_vartype; - } else { - $ctype['complexContent']['attr'] = ''; - $ctype['complexContent']['restriction']['attr']['base'] = 'SOAP-ENC:Array'; - foreach ($_vartype as $array_type) { - list($_vartypens, $_vartype) = $this->_getTypeNs($array_type); - $ctype['complexContent']['restriction']['attribute']['attr']['ref'] = 'SOAP-ENC:arrayType'; - $ctype['complexContent']['restriction']['attribute']['attr']['wsdl:arrayType'] = $_vartypens . ':' . $_vartype . '[]'; - } - } - } - } - } - } - - function addMethodsFromMap(&$map, $namespace, $classname = null) - { - if (!$map) { - return; - } - - foreach ($map as $method_name => $method_types) { - if (array_key_exists('namespace', $method_types)) { - $method_namespace = $method_types['namespace']; - } else { - $method_namespace = $namespace; - } - - // INPUT - $input_message = array('attr' => array('name' => $method_name . 'Request')); - if (isset($method_types['in']) && is_array($method_types['in'])) { - foreach ($method_types['in'] as $name => $type) { - list($typens, $type) = $this->_getTypeNs($type); - $part = array(); - $part['attr']['name'] = $name; - $part['attr']['type'] = $typens . ':' . $type; - $input_message['part'][] = $part; - } - } - $this->_wsdl['definitions']['message'][] = $input_message; - - // OUTPUT - $output_message = array('attr' => array('name' => $method_name . 'Response')); - if (isset($method_types['out']) && is_array($method_types['out'])) { - foreach ($method_types['out'] as $name => $type) { - list($typens, $type) = $this->_getTypeNs($type); - $part = array(); - $part['attr']['name'] = $name; - $part['attr']['type'] = $typens . ':' . $type; - $output_message['part'][] = $part; - } - } - $this->_wsdl['definitions']['message'][] = $output_message; - - // PORTTYPES - $operation = array(); - $operation['attr']['name'] = $method_name; - // INPUT - $operation['input']['attr']['message'] = 'tns:' . $input_message['attr']['name']; - // OUTPUT - $operation['output']['attr']['message'] = 'tns:' . $output_message['attr']['name']; - $this->_wsdl['definitions']['portType']['operation'][] = $operation; - - // BINDING - $binding = array(); - $binding['attr']['name'] = $method_name; - $action = $method_namespace . '#' . ($classname ? $classname . '#' : '') . $method_name; - $binding['soap:operation']['attr']['soapAction'] = $action; - // INPUT - $binding['input']['attr'] = ''; - $binding['input']['soap:body']['attr']['use'] = 'encoded'; - $binding['input']['soap:body']['attr']['namespace'] = $method_namespace; - $binding['input']['soap:body']['attr']['encodingStyle'] = SOAP_SCHEMA_ENCODING; - // OUTPUT - $binding['output']['attr'] = ''; - $binding['output']['soap:body']['attr']['use'] = 'encoded'; - $binding['output']['soap:body']['attr']['namespace'] = $method_namespace; - $binding['output']['soap:body']['attr']['encodingStyle'] = SOAP_SCHEMA_ENCODING; - $this->_wsdl['definitions']['binding']['operation'][] = $binding; - } - } - - function _generate_DISCO_XML($disco_array) - { - $disco = ''; - foreach ($disco_array as $key => $val) { - $disco .= $this->_arrayToNode($key,$val); - } - $this->disco = $disco; - } - - function _generate_WSDL_XML() - { - $wsdl = ''; - foreach ($this->_wsdl as $key => $val) { - $wsdl .= $this->_arrayToNode($key, $val); - } - $this->wsdl = $wsdl; - } - - function _arrayToNode($node_name = '', $array) - { - $return = ''; - if (is_array($array)) { - // we have a node if there's key 'attr' - if (array_key_exists('attr',$array)) { - $return .= "<$node_name"; - if (is_array($array['attr'])) { - foreach ($array['attr'] as $attr_name => $attr_value) { - $return .= " $attr_name=\"$attr_value\""; - } - } - - // unset 'attr' and proceed other childs... - unset($array['attr']); - - if (count($array) > 0) { - $i = 0; - foreach ($array as $child_node_name => $child_node_value) { - $return .= $i == 0 ? ">\n" : ''; - $return .= $this->_arrayToNode($child_node_name,$child_node_value); - $i++; - } - $return .= "\n"; - } else { - $return .= " />\n"; - } - } else { - // we have no 'attr' key in array - so it's list of nodes with - // the same name ... - foreach ($array as $child_node_name => $child_node_value) { - $return .= $this->_arrayToNode($node_name,$child_node_value); - } - } - } else { - // $array is not an array - if ($array !='') { - // and its not empty - $return .= "<$node_name>$array\n"; - } else { - // and its empty... - $return .= "<$node_name />\n"; - } - } - return $return; - } - - function _getTypeNs($type) - { - preg_match_all("'\{(.*)\}'sm", $type, $m); - if (isset($m[1][0]) && $m[1][0] != '') { - if (!array_key_exists($m[1][0],$this->namespaces)) { - $ns_pref = 'ns' . count($this->namespaces); - $this->namespaces[$m[1][0]] = $ns_pref; - $this->_wsdl['definitions']['attr']['xmlns:' . $ns_pref] = $m[1][0]; - } - $typens = $this->namespaces[$m[1][0]]; - $type = ereg_replace($m[0][0],'',$type); - } else { - $typens = 'xsd'; - } - return array($typens,$type); - } - - function _ifComplexTypeExists($typesArray, $type_name) - { - if (is_array($typesArray)) { - foreach ($typesArray as $type_data) { - if ($type_data['attr']['name'] == $type_name) { - return true; - } - } - } - return false; - } -} diff --git a/gulliver/thirdparty/pear/SOAP/Fault.php b/gulliver/thirdparty/pear/SOAP/Fault.php deleted file mode 100644 index 594b817ca..000000000 --- a/gulliver/thirdparty/pear/SOAP/Fault.php +++ /dev/null @@ -1,127 +0,0 @@ - Original Author - * @author Shane Caraveo Port to PEAR and more - * @author Chuck Hagenbuch Maintenance - * @author Jan Schneider Maintenance - * @copyright 2003-2006 The PHP Group - * @license http://www.php.net/license/2_02.txt PHP License 2.02 - * @link http://pear.php.net/package/SOAP - */ - -require_once 'PEAR.php'; - -/** - * PEAR::Error wrapper used to match SOAP Faults to PEAR Errors - * - * SOAP_Fault transmissions normally contain a complete backtrace of the - * error. Revealing these details in a public web services is a bad idea - * because it can be used by attackers. Backtrace information can be kept out - * of SOAP_Fault responses by putting the following code in your script after - * your "require_once 'SOAP/Server.php';" line: - * - * - * $skiptrace =& PEAR::getStaticProperty('PEAR_Error', 'skiptrace'); - * $skiptrace = true; - * - * - * @package SOAP - * @access public - * @author Shane Caraveo Port to PEAR and more - * @author Dietrich Ayala Original Author - */ -class SOAP_Fault extends PEAR_Error -{ - /** - * Constructor. - * - * @param string $faultstring Message string for fault. - * @param mixed $faultcode The faultcode. - * @param mixed $faultactor - * @param mixed $detail @see PEAR_Error - * @param array $mode @see PEAR_Error - * @param array $options @see PEAR_Error - */ - function SOAP_Fault($faultstring = 'unknown error', $faultcode = 'Client', - $faultactor = null, $detail = null, $mode = null, - $options = null) - { - parent::PEAR_Error($faultstring, $faultcode, $mode, $options, $detail); - if ($faultactor) { - $this->error_message_prefix = $faultactor; - } - } - - /** - * Returns a SOAP XML message that can be sent as a server response. - * - * @return string - */ - function message($encoding = SOAP_DEFAULT_ENCODING) - { - $msg = new SOAP_Base(); - $params = array(); - $params[] = new SOAP_Value('faultcode', 'QName', 'SOAP-ENV:' . $this->code); - $params[] = new SOAP_Value('faultstring', 'string', $this->message); - $params[] = new SOAP_Value('faultactor', 'anyURI', $this->error_message_prefix); - if (isset($this->backtrace)) { - $params[] = new SOAP_Value('detail', 'string', $this->backtrace); - } else { - $params[] = new SOAP_Value('detail', 'string', $this->userinfo); - } - - $methodValue = new SOAP_Value('{' . SOAP_ENVELOP . '}Fault', 'Struct', $params); - $headers = null; - return $msg->makeEnvelope($methodValue, $headers, $encoding); - } - - /** - * Returns a simple native PHP array containing the fault data. - * - * @return array - */ - function getFault() - { - $fault = new stdClass(); - $fault->faultcode = $this->code; - $fault->faultstring = $this->message; - $fault->faultactor = $this->error_message_prefix; - $fault->detail = $this->userinfo; - return $fault; - } - - /** - * Returns the SOAP actor for the fault. - * - * @return string - */ - function getActor() - { - return $this->error_message_prefix; - } - - /** - * Returns the fault detail. - * - * @return string - */ - function getDetail() - { - return $this->userinfo; - } - -} diff --git a/gulliver/thirdparty/pear/SOAP/Interop/config.php.dist b/gulliver/thirdparty/pear/SOAP/Interop/config.php.dist deleted file mode 100644 index 4d8201cb1..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/config.php.dist +++ /dev/null @@ -1,4 +0,0 @@ - - - - - PEAR SOAP Interop - - - - -

PEAR SOAP Interop

-

Welcome to the PEAR SOAP Interop pages. These pages are set up for -SOAP Builder interop tests.

- -\n"; -} - -?> -
$test\n"; - echo "WSDL: wsdlURL}\">{$ep->wsdlURL}
\n"; - echo "Endpoint: {$ep->endpointURL}
\n"; - echo "
-

Interop Client

- -

-Notes: -Tests are done both "Direct" and with "WSDL". WSDL tests use the supplied interop WSDL -to run the tests against. The Direct method uses an internal prebuilt list of methods and parameters -for the test.

-

-Tests are also run against two methods of generating method parameters. The first, 'php', attempts -to directly serialize PHP variables into soap values. The second method, 'soapval', uses a SOAP_Value -class to define what the type of the value is. The second method is more interopable than the first -by nature. -

- -

Interop Client Test Results

-

This is a database of the current test results using PEAR SOAP Clients against interop servers.

-

-More detail (wire) about errors (marked yellow or red) can be obtained by clicking on the -link in the result box. If we have an HTTP error -attempting to connect to the endpoint, we will mark all consecutive attempts as errors, and skip -testing that endpoint. This reduces the time it takes to run the tests if a server is unavailable. -WSDLCACHE errors mean we cannot retreive the WSDL file specified for the endpoint. -

- - - - diff --git a/gulliver/thirdparty/pear/SOAP/Interop/interop_Round2Base.php b/gulliver/thirdparty/pear/SOAP/Interop/interop_Round2Base.php deleted file mode 100644 index c8b7b2f95..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/interop_Round2Base.php +++ /dev/null @@ -1,155 +0,0 @@ - Port to PEAR and more | -// | Authors: Dietrich Ayala Original Author | -// +----------------------------------------------------------------------+ -// -// $Id: interop_Round2Base.php,v 1.9 2007/01/26 00:06:11 yunosh Exp $ -// -require_once 'params_classes.php'; - -function &generateFault($short, $long) -{ - $params = array( - 'faultcode' => 'Server', - 'faultstring' => $short, - 'detail' => $long - ); - - $faultmsg = new SOAP_Message('Fault', $params, 'http://schemas.xmlsoap.org/soap/envelope/'); - return $faultmsg; -} - -function hex2bin($data) -{ - $len = strlen($data); - return pack('H' . $len, $data); -} - - -class SOAP_Interop_Base { - - function echoString($inputString) - { - return new SOAP_Value('outputString', 'string', $inputString); - } - - function echoStringArray($inputStringArray) - { - $ra = array(); - if ($inputStringArray) { - foreach($inputStringArray as $s) { - $ra[] = new SOAP_Value('item', 'string', $s); - } - } - return new SOAP_Value('outputStringArray', null, $ra); - } - - - function echoInteger($inputInteger) - { - return new SOAP_Value('outputInteger', 'int', (integer)$inputInteger); - } - - function echoIntegerArray($inputIntegerArray) - { - $ra = array(); - if ($inputIntegerArray) { - foreach ($inputIntegerArray as $i) { - $ra[] = new SOAP_Value('item', 'int', $i); - } - } - return new SOAP_Value('outputIntArray', null, $ra); - } - - function echoFloat($inputFloat) - { - return new SOAP_Value('outputFloat', 'float', (float)$inputFloat); - } - - function echoFloatArray($inputFloatArray) - { - $ra = array(); - if ($inputFloatArray) { - foreach($inputFloatArray as $float) { - $ra[] = new SOAP_Value('item', 'float', (FLOAT)$float); - } - } - return new SOAP_Value('outputFloatArray', null, $ra); - } - - function echoStruct($inputStruct) - { - if (is_object($inputStruct) && strtolower(get_class($inputStruct)) == 'soapstruct') { - return $inputStruct->__to_soap(); - } - return $inputStruct; - } - - function echoStructArray($inputStructArray) - { - $ra = array(); - if ($inputStructArray) { - $c = count($inputStructArray); - for ($i = 0; $i < $c; $i++) { - $ra[] = $this->echoStruct($inputStructArray[$i]); - } - } - return $ra; - } - - function echoVoid() - { - return NULL; - } - - function echoBase64($b_encoded) - { - return new SOAP_Value('return', 'base64Binary', base64_encode(base64_decode($b_encoded))); - } - - function echoDate($timeInstant) - { - require_once 'SOAP/Type/dateTime.php'; - $dt = new SOAP_Type_dateTime($timeInstant); - if ($dt->toUnixtime() != -1) { - $value = $dt->toSOAP(); - return new SOAP_Value('return', 'dateTime', $value); - } else { - return new SOAP_Fault("Value $timeInstant is not a dateTime value"); - } - } - - function echoHexBinary($hb) - { - return new SOAP_Value('return', 'hexBinary', bin2hex(hex2bin($hb))); - } - - function echoDecimal($dec) - { - return new SOAP_Value('return', 'decimal', (float)$dec); - } - - function echoBoolean($boolean) - { - return new SOAP_Value('return', 'boolean', $boolean); - } - - function echoMimeAttachment($stuff) - { - return new SOAP_Attachment('return', 'application/octet-stream', null, $stuff); - } -} diff --git a/gulliver/thirdparty/pear/SOAP/Interop/interop_Round2GroupB.php b/gulliver/thirdparty/pear/SOAP/Interop/interop_Round2GroupB.php deleted file mode 100644 index f02404826..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/interop_Round2GroupB.php +++ /dev/null @@ -1,99 +0,0 @@ - Port to PEAR and more | -// | Authors: Dietrich Ayala Original Author | -// +----------------------------------------------------------------------+ -// -// $Id: interop_Round2GroupB.php,v 1.9 2007/01/22 14:53:21 yunosh Exp $ -// -require_once 'params_classes.php'; - -class SOAP_Interop_GroupB { - - var $__dispatch_map = array(); - - function SOAP_Interop_GroupB() - { - $this->__dispatch_map['echoStructAsSimpleTypes'] = - array('in' => array('inputStruct' => 'SOAPStruct'), - 'out' => array('outputString' => 'string', 'outputInteger' => 'int', 'outputFloat' => 'float')); - $this->__dispatch_map['echoSimpleTypesAsStruct'] = - array('in' => array('inputString' => 'string', 'inputInteger' => 'int', 'inputFloat' => 'float'), - 'out' => array('return' => 'SOAPStruct')); - $this->__dispatch_map['echoNestedStruct'] = - array('in' => array('inputStruct' => 'SOAPStructStruct'), - 'out' => array('return' => 'SOAPStructStruct')); - $this->__dispatch_map['echo2DStringArray'] = - array('in' => array('input2DStringArray' => 'ArrayOfString2D'), - 'out' => array('return' => 'ArrayOfString2D')); - $this->__dispatch_map['echoNestedArray'] = - array('in' => array('inputString' => 'SOAPArrayStruct'), - 'out' => array('return' => 'SOAPArrayStruct')); - } - - /* this private function is called on by SOAP_Server to determine any - * special dispatch information that might be necessary. This, for - * example, can be used to set up a dispatch map for functions that return - * multiple OUT parameters. */ - function __dispatch($methodname) - { - if (array_key_exists($methodname,$this->__dispatch_map)) { - return $this->__dispatch_map[$methodname]; - } - return null; - } - - function echoStructAsSimpleTypes ($struct) - { - // Convert a SOAPStruct to an array. - return array( - new SOAP_Value('outputString','string',$struct->varString), - new SOAP_Value('outputInteger','int',$struct->varInt), - new SOAP_Value('outputFloat','float',$struct->varFloat)); - } - - function echoSimpleTypesAsStruct($string, $int, $float) - { - // Convert a input into struct. - $v = new SOAPStruct($string, $int, $float); - return new SOAP_Value('return', '{http://soapinterop.org/xsd}SOAPStruct', $v); - } - - function echoNestedStruct($struct) - { - $separator = "\n"; - $methods = get_class_methods($struct); - $arr_str = $separator . strtolower(implode($separator, $methods)); - $string = $separator . '__to_soap' . $separator; - if (strpos($arr_str, $string) !== false) { - return $struct->__to_soap(); - } - return $struct; - } - - function echo2DStringArray($array) - { - $ret = new SOAP_Value('return', 'Array', $array); - $ret->options['flatten'] = true; - return $ret; - } - - function echoNestedArray($array) - { - return $array; - } - -} diff --git a/gulliver/thirdparty/pear/SOAP/Interop/interop_Round2GroupC.php b/gulliver/thirdparty/pear/SOAP/Interop/interop_Round2GroupC.php deleted file mode 100644 index aca3d86db..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/interop_Round2GroupC.php +++ /dev/null @@ -1,35 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: interop_Round2GroupC.php,v 1.5 2007/01/22 14:53:21 yunosh Exp $ -// -require_once 'SOAP/Value.php'; - -class SOAP_Interop_GroupC_Headers { - - function echoMeStringRequest($string) - { - return new SOAP_Value('{http://soapinterop.org/echoheader/}echoMeStringResponse', 'string', $string); - } - - function echoMeStructRequest($struct) - { - return new SOAP_Value('{http://soapinterop.org/echoheader/}echoMeStructResponse', 'SOAPStruct', $struct); - } - -} diff --git a/gulliver/thirdparty/pear/SOAP/Interop/interop_Round3GroupD.php b/gulliver/thirdparty/pear/SOAP/Interop/interop_Round3GroupD.php deleted file mode 100644 index b4e198d2a..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/interop_Round3GroupD.php +++ /dev/null @@ -1,82 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: interop_Round3GroupD.php,v 1.5 2007/01/22 14:53:21 yunosh Exp $ -// -require_once 'params_classes.php'; - -// http://www.whitemesa.com/r3/interop3.html -// http://www.whitemesa.com/r3/plan.html - -class SOAP_Interop_GroupD { - - // wsdlns:SoapInteropEmptySABinding - function echoString($inputString) - { - return new SOAP_Value('outputString', 'string', $inputString); - } - - function echoStringArray($inputStringArray) - { - $ra = array(); - if ($inputStringArray) { - foreach ($inputStringArray as $s) { - $ra[] = new SOAP_Value('item', 'string', $s); - } - } - return new SOAP_Value('outputStringArray', null, $ra); - } - - function echoStruct($inputStruct) - { - return $inputStruct->to_soap(); - } - - function echoStructArray($inputStructArray) - { - $ra = array(); - if ($inputStructArray) { - $c = count($inputStructArray); - for ($i = 0; $i < $c; $i++) { - $ra[] = $inputStructArray[$i]->to_soap(); - } - } - return $ra; - } - - function echoVoid() - { - return null; - } - - function echoPerson() - { - return null; - } - - function x_Document(&$document) - { - return new SOAP_Value('result_Document', '{http://soapinterop.org/xsd}x_Document', $document); - } - - function echoEmployee() - { - return null; - } - -} diff --git a/gulliver/thirdparty/pear/SOAP/Interop/interop_client.php b/gulliver/thirdparty/pear/SOAP/Interop/interop_client.php deleted file mode 100644 index 75e3aa06e..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/interop_client.php +++ /dev/null @@ -1,805 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: interop_client.php,v 1.16 2007/01/26 17:21:26 yunosh Exp $ -// -require_once 'DB.php'; // PEAR/DB -require_once 'SOAP/Client.php'; - -require_once 'config.php'; -require_once 'interop_test_functions.php'; -require_once 'interop_test.php'; -require_once 'params_Round2Base.php'; -require_once 'params_Round2GroupB.php'; -require_once 'params_Round2GroupC.php'; -require_once 'params_Round3GroupD.php'; -require_once 'registrationAndNotification.php'; - -error_reporting(E_ALL ^ E_NOTICE); -$INTEROP_LOCAL_SERVER = false; - -class Interop_Client -{ - // database DNS - var $DSN; - - // our central interop server, where we can get the list of endpoints - var $registrationDB; - - // our local endpoint, will always get added to the database for all tests - var $localEndpoint; - - // specify testing - var $currentTest = ''; // see $tests above - var $paramType = 'php'; // 'php' or 'soapval' - var $useWSDL = false; // true: do wsdl tests - var $numServers = 0; // 0: all - var $specificEndpoint = ''; // test only this endpoint - var $testMethod = ''; // test only this method - var $skipEndpointList = array(); // endpoints to skip - var $nosave = false; - var $client_type = 'pear'; // name of client - - // debug output - var $show = 1; - var $debug = 0; - var $showFaults = 0; // used in result table output - - // PRIVATE VARIABLES - var $dbc = null; - var $totals = array(); - var $tests = array('Round 2 Base', - 'Round 2 Group B', - 'Round 2 Group C', - 'Round 3 Group D Compound 1', - 'Round 3 Group D Compound 2', - 'Round 3 Group D DocLit', - 'Round 3 Group D DocLitParams', - 'Round 3 Group D Import 1', - 'Round 3 Group D Import 2', - 'Round 3 Group D Import 3', - 'Round 3 Group D RpcEnc' - ); - var $paramTypes = array('php', 'soapval'); - var $endpoints = array(); - - function Interop_Client() { - global $interopConfig; - $this->DSN = $interopConfig['DSN']; - $this->registrationDB =& new SOAP_Interop_registrationDB(); - - // XXX for now, share the database for results also - $this->dbc =& $this->registrationDB->dbc; - } - - /** - * fetchEndpoints - * retreive endpoints interop server - * - * @return boolean result - * @access private - */ - function fetchEndpoints($name = 'Round 2 Base') { - $service =& $this->registrationDB->findService($name); - $this->endpoints =& $this->registrationDB->getServerList($service->id,true); - return true; - } - - /** - * getEndpoints - * retreive endpoints from either database or interop server - * - * @param string name (see local var $tests) - * @param boolean all (if false, only get valid endpoints, status=1) - * @return boolean result - * @access private - */ - function getEndpoints($name = 'Round 2 Base', $all = 0) { - $service =& $this->registrationDB->findService($name); - $this->endpoints =& $this->registrationDB->getServerList($service->id); - return true; - } - - /** - * Retreives results from the database and stuffs them into the endpoint - * array. - * - * @access private - */ - function getResults($test = 'Round 2 Base', $type = 'php', $wsdl = 0) - { - // Be sure we have the right endpoints for this test result. - $this->getEndpoints($test); - $c = count($this->endpoints); - - // Retreive the results and put them into the endpoint info. - $sql = "SELECT * FROM results WHERE class='$test' AND type='$type' AND wsdl=$wsdl"; - $results = $this->dbc->getAll($sql, null, DB_FETCHMODE_ASSOC); - for ($j = 0, $rc = count($results); $j < $rc; ++$j) { - $result = $results[$j]; - // Find the endpoint. - for ($i = 0; $i < $c; $i++) { - if ($this->endpoints[$i]->id == $result['endpoint']) { - // Store the info. - if (!isset($this->endpoints[$i]->methods)) { - $this->endpoints[$i]->methods = array(); - } - $this->endpoints[$i]->methods[$result['function']] = $result; - break; - } - } - } - } - - /** - * Saves the results of a method test into the database. - * - * @access private - */ - function _saveResults($endpoint_id, &$soap_test) - { - if ($this->nosave) { - return; - } - - $result =& $soap_test->result; - $wire = $result['wire']; - if ($result['success']) { - $success = 'OK'; - $error = ''; - } else { - $success = $result['fault']->faultcode; - $error = $result['fault']->faultstring; - if (!$wire) { - $wire = $result['fault']->faultdetail; - } - if (!$wire) { - $wire = $result['fault']->faultstring; - } - } - - $test_name = $soap_test->test_name; - // add header info to the test name - if ($soap_test->headers) { - foreach ($soap_test->headers as $h) { - $destination = 0; - if (is_object($h) && strtolower(get_class($h)) == 'soap_header') { - if ($h->attributes['SOAP-ENV:actor'] == 'http://schemas.xmlsoap.org/soap/actor/next') { - $destination = 1; - } - $test_name .= ":{$h->name},$destination,{$h->attributes['SOAP-ENV:mustUnderstand']}"; - } else { - if (!$h[3] || - $h[3] == 'http://schemas.xmlsoap.org/soap/actor/next') { - $destination = 1; - } - if (!$h[2]) { - $h[2] = 0; - } - $qn = new QName($h[0]); - $test_name .= ":{$qn->name},$destination," . (int)$h[2]; - } - } - } - - $sql = 'DELETE FROM results WHERE endpoint = ? AND class = ? AND type = ? AND wsdl = ? AND client = ? AND function = ?'; - $values = array($endpoint_id, $this->currentTest, $this->paramType, - $this->useWSDL, $this->client_type, $test_name); - $res = $this->dbc->query($sql, $values); - if (DB::isError($res)) { - die($res->getMessage()); - } - if (is_object($res)) { - $res->free(); - } - - $sql = 'INSERT INTO results (client, endpoint, stamp, class, type, wsdl, function, result, error, wire) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; - $values = array($this->client_type, $endpoint_id, time(), - $this->currentTest, $this->paramType, $this->useWSDL, - $test_name, $success, $error, - $wire ? $wire : ''); - //echo "\n".$sql; - $res = $this->dbc->query($sql, $values); - if (DB::isError($res)) { - die($res->getMessage()); - } - if (is_object($res)) { - $res->free(); - } - } - - /** - * Compares two PHP types for a match. - * - * @param mixed $expect - * @param mixed $test_result - * - * @return boolean - */ - function compareResult(&$expect, &$result, $type = null) - { - $expect_type = gettype($expect); - $result_type = gettype($result); - if ($expect_type == 'array' && $result_type == 'array') { - // compare arrays - return array_compare($expect, $result); - } - if ($type == 'float') { - // We'll only compare to 3 digits of precision. - return number_compare($expect, $result); - } - if ($type == 'boolean') { - return boolean_compare($expect, $result); - } - return string_compare($expect, $result); - } - - - /** - * Runs a method on an endpoint and stores its results to the database. - * - * @param array $endpoint_info - * @param SOAP_Test $soap_test - * - * @return boolean result - */ - function doEndpointMethod(&$endpoint_info, &$soap_test) - { - $ok = false; - - // Prepare a holder for the test results. - $soap_test->result['class'] = $this->currentTest; - $soap_test->result['type'] = $this->paramType; - $soap_test->result['wsdl'] = $this->useWSDL; - $opdata = null; - //global $soap_value_total; - //echo "SOAP VALUES TEST-START: $soap_value_total\n"; - - if ($this->useWSDL) { - if ($endpoint_info->wsdlURL) { - if (!$endpoint_info->client) { - if (0 /* dynamic client */) { - $endpoint_info->wsdl = new SOAP_WSDL($endpoint_info->wsdlURL); - $endpoint_info->wsdl->trace=1; - $endpoint_info->client = $endpoint_info->wsdl->getProxy('', $endpoint_info->name); - } else { - $endpoint_info->client = new SOAP_Client($endpoint_info->wsdlURL, 1); - } - $endpoint_info->client->_auto_translation = true; - } - if ($endpoint_info->client->_wsdl->_isfault()) { - $fault = $endpoint_info->client->_wsdl->fault->getFault(); - $detail = $fault->faultstring . "\n\n" . $fault->faultdetail; - $soap_test->setResult(0, - 'WSDL', - $detail, - $fault->faultstring, - $fault); - return false; - } - if ($soap_test->service) { - $endpoint_info->client->_wsdl->setService($soap_test->service); - } - $soap =& $endpoint_info->client; - //$port = $soap->_wsdl->getPortName($soap_test->method_name); - //$opdata = $soap->_wsdl->getOperationData($port, $soap_test->method_name); - } else { - $fault = array('faultcode' => 'WSDL', - 'faultstring' => "no WSDL defined for $endpoint"); - $soap_test->setResult(0, - 'WSDL', - $fault->faultstring, - $fault->faultstring, - $fault); - return false; - } - $options = array('trace' => 1); - } else { - $namespace = $soapaction = 'http://soapinterop.org/'; - // Hack to make tests work with MS SoapToolkit. - // It's the only one that uses this soapaction, and breaks if - // it isn't right. Can't wait for soapaction to be fully deprecated - // 8/25/2002, seems this is fixed now - //if ($this->currentTest == 'Round 2 Base' && - // strstr($endpoint_info->name,'MS SOAP ToolKit 2.0')) { - // $soapaction = 'urn:soapinterop'; - //} - if (!$endpoint_info->client) { - $endpoint_info->client = new SOAP_Client($endpoint_info->endpointURL); - $endpoint_info->client->_auto_translation = true; - } - $soap = &$endpoint_info->client; - $options = array('namespace' => $namespace, - 'soapaction' => $soapaction, - 'trace' => 1); - } - - // Add headers to the test. - if ($soap_test->headers) { - // $header is already a SOAP_Header class - $soap->headersOut = array(); - $soap->headersIn = array(); - for ($i = 0, $hc = count($soap_test->headers); $i < $hc; $i++) { - $soap->addHeader($soap_test->headers[$i]); - } - } - $soap->setEncoding($soap_test->encoding); - - //if ($opdata) { - // if (isset($opdata['style'])) - // $options['style'] = $opdata['style']; - // if (isset($opdata['soapAction'])) - // $options['soapaction'] = $opdata['soapAction']; - // if (isset($opdata['input']) && - // isset($opdata['input']['use'])) - // $options['use'] = $opdata['input']['use']; - // if (isset($opdata['input']) && - // isset($opdata['input']['namespace'])) - // $options['namespace'] = $soap->_wsdl->namespaces[$opdata['input']['namespace']]; - //} - //if ($this->useWSDL) { - // $wsdlcall = '$return = $soap->'.$soap_test->method_name.'('; - // $args = ''; - // if ($soap_test->method_params) { - // $pnames = array_keys($soap_test->method_params); - // foreach ($pnames as $argname) { - // if ($args) $args .=','; - // $args .= '$soap_test->method_params[\''.$argname.'\']'; - // } - // } - // $wsdlcall = $wsdlcall.$args.');'; - // eval($wsdlcall); - //} else { - $return =& $soap->call($soap_test->method_name, $soap_test->method_params, $options); - //} - - if (!PEAR::isError($return)) { - if (is_array($soap_test->method_params) && - count($soap_test->method_params) == 1) { - $sent = array_shift(array_values($soap_test->method_params)); - } else { - $sent = $soap_test->method_params; - } - - // Compare header results. - $header_result = array(); - $headers_ok = true; - if ($soap_test->headers) { - // $header is already a SOAP_Header class - for ($i = 0, $hc = count($soap_test->headers); $i < $hc; $i++) { - $header = $soap_test->headers[$i]; - if (is_object($header) && strtolower(get_class($header)) != 'soap_header') { - // Assume it's an array. - $header = new SOAP_Header($header[0], null, $header[1], $header[2], $header[3], $header[4]); - } - $expect = $soap_test->headers_expect[$header->name]; - $header_result[$header->name] = array(); - // XXX need to fix need_result to identify the actor correctly - $need_result = $hresult || - ($header->attributes['SOAP-ENV:actor'] == 'http://schemas.xmlsoap.org/soap/actor/next' - && $header->attributes['SOAP-ENV:mustUnderstand']); - if ($expect) { - $hresult = $soap->headersIn[key($expect)]; - $ok = !$need_result || $this->compareResult($hresult ,$expect[key($expect)]); - } else { - $hresult = $soap->headersIn[$header->name]; - $expect =& $soap->_decode($header); - $ok = !$need_result || $this->compareResult($hresult ,$expect); - } - $header_result[$header->name]['ok'] = $ok; - if (!$ok) { - $headers_ok = false; - } - } - } - - // We need to decode what we sent so we can compare! - if (gettype($sent) == 'object' && - (strtolower(get_class($sent)) == 'soap_value' || - is_subclass_of($sent, 'soap_value'))) { - $sent_d =& $soap->_decode($sent); - } else { - $sent_d =& $sent; - } - - // compare the results with what we sent - $ok = $this->compareResult($sent_d, $return, $sent->type); - $expected = $sent_d; - unset($sent_d); - unset($sent); - if (!$ok && $soap_test->expect) { - $ok = $this->compareResult($soap_test->expect, $return); - $expected = $soap_test->expect; - } - - if ($ok) { - if (!$headers_ok) { - $fault = new stdClass(); - $fault->faultcode = 'HEADER'; - $fault->faultstring = 'The returned result did not match what we expected to receive'; - $soap_test->setResult(0, - $fault->faultcode, - $soap->getWire(), - $fault->faultstring, - $fault); - } else { - $soap_test->setResult(1, 'OK', $soap->getWire()); - $success = true; - } - } else { - $fault = new stdClass(); - $fault->faultcode = 'RESULT'; - $fault->faultstring = 'The returned result did not match what we expected to receive'; - $fault->faultdetail = "RETURNED:\n" . var_export($return, true) . "\n\nEXPECTED:\n" . var_export($expected, true); - $soap_test->setResult(0, - $fault->faultcode, - $soap->getWire(), - $fault->faultstring, - $fault); - } - } else { - $fault = $return->getFault(); - if ($soap_test->expect_fault) { - $ok = 1; - $res = 'OK'; - } else { - $ok = 0; - $res = $fault->faultcode; - } - $soap_test->setResult($ok, - $res, - $soap->getWire(), - $fault->faultstring, - $fault); - } - $soap->_reset(); - unset($return); - - return $ok; - } - - /** - * Runs a single round of tests. - */ - function doTest() - { - global $soap_tests; - - $empty_string = ''; - // Get endpoints for this test. - if (!$this->currentTest) { - die("Asked to run a test, but no testname!\n"); - } - $this->getEndpoints($this->currentTest); - // Clear totals. - $this->totals = array(); - - for ($i = 0, $c = count($this->endpoints); $i < $c; ++$i) { - $endpoint_info = $this->endpoints[$i]; - // If we specify an endpoint, skip until we find it. - if (($this->specificEndpoint && - $endpoint_info->name != $this->specificEndpoint) || - ($this->useWSDL && !$endpoint_info->wsdlURL)) { - continue; - } - - $skipendpoint = false; - $this->totals['servers']++; - //$endpoint_info['tests'] = array(); - - if ($this->show) { - echo "Processing {$endpoint_info->name} at {$endpoint_info->endpointURL}\n"; - } - - for ($ti = 0, $tc = count($soap_tests[$this->currentTest]); $ti < $tc; ++$ti) { - $soap_test = $soap_tests[$this->currentTest][$ti]; - - // Only run the type of test we're looking for (php or - // soapval). - if ($soap_test->type != $this->paramType) { - continue; - } - - // If this is in our skip list, skip it. - if (in_array($endpoint_info->name, $this->skipEndpointList)) { - $skipendpoint = true; - $skipfault = new stdClass(); - $skipfault->faultcode = 'SKIP'; - $skipfault->faultstring = 'endpoint skipped'; - $soap_test->setResult(0, - $skipfault->faultcode, - $empty_string, - $skipfault->faultstring, - $skipfault); - //$endpoint_info['tests'][] = &$soap_test; - //$soap_test->showTestResult($this->debug); - //$this->_saveResults($endpoint_info['id'], $soap_test->method_name); - $soap_test->result = null; - continue; - } - - // If we're looking for a specific method, skip unless we have - // it. - if ($this->testMethod && - strcmp($this->testMethod, $soap_test->test_name) != 0) { - continue; - } - if ($this->testMethod && - $this->currentTest == 'Round 2 Group C') { - // We have to figure things out now. - if (!preg_match('/(.*):(.*),(\d),(\d)/', $this->testMethod, $m)) { - continue; - } - - // Is the header in the headers list? - $gotit = false; - $thc = count($soap_test->headers); - for ($thi = 0; $thi < $thc; $thi++) { - $header = $soap_test->headers[$thi]; - if (is_object($header) && strtolower(get_class($header)) == 'soap_header') { - if ($header->name == $m[2]) { - $gotit = $header->attributes['SOAP-ENV:actor'] == ($m[3] ? SOAP_TEST_ACTOR_NEXT : SOAP_TEST_ACTOR_OTHER); - $gotit = $gotit && $header->attributes['SOAP-ENV:mustUnderstand'] == $m[4]; - } - } elseif ($header[0] == $m[2]) { - $gotit = $gotit && $header[3] == ($m[3] ? SOAP_TEST_ACTOR_NEXT : SOAP_TEST_ACTOR_OTHER); - $gotit = $gotit && $header[4] == $m[4]; - } - } - if (!$gotit) { - continue; - } - } - - // If we are skipping the rest of the tests (due to error) - // note a fault. - if ($skipendpoint) { - $soap_test->setResult(0, - $skipfault->faultcode, - $empty_string, - $skipfault->faultstring, - $skipfault); - //$endpoint_info['tests'][] = &$soap_test; - $this->totals['fail']++; - } else { - // Run the endpoint test. - unset($soap_test->result); - if ($this->doEndpointMethod($endpoint_info, $soap_test)) { - $this->totals['success']++; - } else { - $skipendpoint = $soap_test->result['fault']->faultcode == 'HTTP'; - $skipfault = $skipendpoint ? $soap_test->result['fault'] : null; - $this->totals['fail']++; - } - //$endpoint_info['tests'][] = &$soap_test; - } - $soap_test->showTestResult($this->debug); - $this->_saveResults($endpoint_info->id, $soap_test); - $soap_test->reset(); - $this->totals['calls']++; - } - unset($endpoint_info->client); - if ($this->numservers && ++$i >= $this->numservers) { - break; - } - } - } - - function doGroupTests() { - $dowsdl = array(0,1); - foreach($dowsdl as $usewsdl) { - $this->useWSDL = $usewsdl; - foreach($this->paramTypes as $ptype) { - // skip a pointless test - if ($usewsdl && $ptype == 'soapval') break; - if (stristr($this->currentTest, 'Round 3') && !$usewsdl) break; - $this->paramType = $ptype; - $this->doTest(); - } - } - } - - /** - * Go all out. This takes time. - */ - function doTests() - { - // The mother of all interop tests. - $dowsdl = array(0, 1); - foreach ($this->tests as $test) { - $this->currentTest = $test; - foreach ($dowsdl as $usewsdl) { - $this->useWSDL = $usewsdl; - foreach ($this->paramTypes as $ptype) { - // Skip a pointless test. - if ($usewsdl && $ptype == 'soapval') { - break; - } - if (stristr($this->currentTest, 'Round 3') && !$usewsdl) { - break; - } - $this->paramType = $ptype; - $this->doTest(); - } - } - } - } - - /** - * @access private - */ - function getMethodList($test = 'base') - { - $this->dbc->setFetchMode(DB_FETCHMODE_ORDERED); - // Retreive the results and put them into the endpoint info. - $sql = "SELECT DISTINCT(function) FROM results WHERE client='$this->client_type' AND class='$test' ORDER BY function"; - $results = $this->dbc->getAll($sql); - $ar = array(); - foreach($results as $result) { - $ar[] = $result[0]; - } - return $ar; - } - - function outputTable() - { - $methods = $this->getMethodList($this->currentTest); - if (!$methods) { - return; - } - $this->getResults($this->currentTest,$this->paramType,$this->useWSDL); - - echo "Testing $this->currentTest "; - if ($this->useWSDL) { - echo "using WSDL "; - } else { - echo "using Direct calls "; - } - echo "with $this->paramType values
\n"; - - // Calculate totals for this table. - $this->totals['success'] = 0; - $this->totals['fail'] = 0; - $this->totals['result'] = 0; - $this->totals['wsdl'] = 0; - $this->totals['connect'] = 0; - $this->totals['servers'] = 0; //count($this->endpoints); - for ($i = 0, $c = count($this->endpoints); $i < $c; ++$i) { - $endpoint_info = $this->endpoints[$i]; - if (!$endpoint_info->name) { - continue; - } - if (count($endpoint_info->methods) > 0) { - $this->totals['servers']++; - foreach ($methods as $method) { - $r = $endpoint_info->methods[$method]['result']; - if ($r == 'OK') { - $this->totals['success']++; - } elseif (stristr($r, 'result')) { - $this->totals['result']++; - } elseif (stristr($r, 'wsdlcache')) { - $this->totals['connect']++; - } elseif (stristr($r, 'wsdl')) { - $this->totals['wsdl']++; - } elseif (stristr($r, 'http')) { - $this->totals['connect']++; - } else { - $this->totals['fail']++; - } - } - } else { - //unset($this->endpoints[$i]); - } - } - $this->totals['calls'] = count($methods) * $this->totals['servers']; - - //if ($this->totals['fail'] == $this->totals['calls']) { - // // assume tests have not run, skip outputing table - // echo "No Data Available
\n"; - // return; - //} - - echo "\n\nServers: {$this->totals['servers']} Calls: {$this->totals['calls']} Success: {$this->totals['success']}
\n" - . "System-Fail: {$this->totals['fail']} Result-Failure: {$this->totals['result']} Connect-Failure: {$this->totals['connect']} WSDL-Failure: {$this->totals['wsdl']}

\n" - - . "\n" - . "\n"; - foreach ($methods as $method) { - $info = explode(':', $method); - echo "\n"; - } - echo "\n"; - $faults = array(); - $fi = 0; - for ($i = 0, $c = count($this->endpoints); $i < $c; ++$i) { - $endpoint_info = $this->endpoints[$i]; - if (!$endpoint_info->name) { - continue; - } - if ($endpoint_info->wsdlURL) { - echo "\n"; - } else { - echo "\n"; - } - foreach ($methods as $method) { - $id = $endpoint_info->methods[$method]['id']; - $r = $endpoint_info->methods[$method]['result']; - $e = $endpoint_info->methods[$method]['error']; - if ($e) { - $faults[$fi++] = $e; - } - if ($r) { - echo "\n"; - } else { - echo "\n"; - } - } - echo "\n"; - } - echo "
Endpoint"; - foreach ($info as $m) { - $hi = explode(',', $m); - echo ''. $hi[0] . "
\n"; - if (count($hi) > 1) { - echo "  Actor=" - . ($hi[1] ? 'Target' : 'Not Target') - . "
\n  MustUnderstand=$hi[2]
\n"; - } - } - echo "
wsdlURL}\">{$endpoint_info->name}
{$endpoint_info->name}$runtested

\n"; - if ($this->showFaults && count($faults) > 0) { - echo "ERROR Details:
\n
    \n"; - // output more error detail - foreach ($faults as $fault) { - echo '
  • ' . htmlspecialchars($fault) . "
  • \n"; - } - } - echo "


\n"; - } - - function outputTables() - { - $dowsdl = array(0, 1); - foreach($this->tests as $test) { - $this->currentTest = $test; - foreach ($dowsdl as $usewsdl) { - $this->useWSDL = $usewsdl; - foreach ($this->paramTypes as $ptype) { - // Skip a pointless test. - if ($usewsdl && $ptype == 'soapval') { - break; - } - if (stristr($this->currentTest, 'Round 3') && !$usewsdl) { - break; - } - $this->paramType = $ptype; - $this->outputTable(); - } - } - } - } - - function showWire($id) - { - $results = $this->dbc->getAll("SELECT * FROM results WHERE id=$id", null, DB_FETCHMODE_ASSOC ); - //$wire = preg_replace("/>/",">\n",$results[0]['wire']); - $wire = $results[0]['wire']; - echo "
\n" . htmlspecialchars($wire) . "
\n"; - } - -} diff --git a/gulliver/thirdparty/pear/SOAP/Interop/interop_client_results.php b/gulliver/thirdparty/pear/SOAP/Interop/interop_client_results.php deleted file mode 100644 index 43e8ebc74..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/interop_client_results.php +++ /dev/null @@ -1,75 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: interop_client_results.php,v 1.3 2003/04/07 00:51:17 shane Exp $ -// -require_once 'interop_client.php'; -?> - - - - - - PEAR-PHP SOAP Interop Tests - - - -

SOAP Client Interop Test Results: Round2

- -Back to Interop Index
-

 

- -showFaults = 1; - -if ($_GET['wire']) { - $iop->showWire($_GET['wire']); -} else { - $iop->getEndpoints(); - $iop->getResults(); - - if ($_GET['test']) { - $iop->currentTest = $_GET['test']; - $iop->useWSDL = $_GET['wsdl']?$_GET['wsdl']:0; - $iop->paramType = $_GET['type']?$_GET['type']:'php'; - $iop->outputTable(); - } else { - $iop->outputTables(); - } -} -?> - - diff --git a/gulliver/thirdparty/pear/SOAP/Interop/interop_client_run.php b/gulliver/thirdparty/pear/SOAP/Interop/interop_client_run.php deleted file mode 100644 index 75d81fff7..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/interop_client_run.php +++ /dev/null @@ -1,205 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: interop_client_run.php,v 1.11 2007/01/26 15:03:24 yunosh Exp $ -// - -if (isset($_SERVER['SERVER_NAME'])) { - die("full test run cannot be done via webserver."); -} - -set_time_limit(0); -error_reporting(E_ALL); - -require 'Console/Getopt.php'; -require_once 'interop_client.php'; - -$INTEROP_LOCAL_SERVER = TRUE;// add local server to endpoints - -$iop =& new Interop_Client(); - -// debug output -$iop->show = 1; -$iop->debug = 0; -$iop->showFaults = 0; // used in result table output -$restrict = null; - -$args = Console_Getopt::getopt($_SERVER['argv'], - 'c:dehl:m:np:r:s:t:v:wq', - array('help')); -if (PEAR::isError($args)) { - echo "\n" . $args->getMessage() . "\n\n"; - help(); - exit; -} - -function help() { -print <<tests as $test) { - print " $test\n"; - } -} - -function print_endpoint_names() -{ - global $iop; - - 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(); - $currTest = $filter->xssFilterHard($iop->currentTest); - - if (!$iop->getEndpoints($iop->currentTest)) { - die("Unable to retrieve endpoints for $currTest\n"); - } - print "Interop Servers for $currTestt:\n"; - foreach ($iop->endpoints as $server) { - print " $server->name\n"; - } -} - -foreach ($args[0] as $arg) { - switch($arg[0]) { - case 'c': - $iop->client_type = $arg[1]; - break; - case 'd': - $iop->debug = true; - break; - case 'e': - $iop->fetchEndpoints(); - break; - case 'h': - case '--help': - help(); - exit(0); - case 'l': - $iop->skipEndpointList = explode(',', $arg[1]); - break; - case 'm': - $iop->testMethod = $arg[1]; - break; - case 'n': - $iop->nosave = true; - break; - case 'p': - if ($arg[1] == 't') { - print_test_names(); - } elseif ($arg[1] == 'e') { - if (!$iop->currentTest) { - print "You need to specify a test with -t\n"; - exit(0); - } - print_endpoint_names(); - } else { - die("invalid print argument\n"); - } - exit(0); - case 'r': - $restrict = $arg[1]; - break; - case 's': - $iop->specificEndpoint = $arg[1]; - break; - case 't': - $iop->currentTest = $arg[1]; - break; - case 'v': - if ($arg[1] != 'php' && $arg[1] != 'soapval') { - - 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(); - $arg[1] = $filter->xssFilterHard($arg[1]); - - die('Incorrect value for argument v: ' . $arg[1] . "\n"); - } - $iop->paramType = $arg[1]; - break; - case 'w': - $iop->useWSDL = true; - break; - case 'q': - exit(0); - } -} - -// These are endpoints that are listed in the interop server, but do not realy -// exist any longer. -$bad = array('Spheon JSOAP', 'Phalanx', 'SilverStream', 'SOAPx4 (PHP)', - 'Virtuoso (development)', 'Zolera SOAP Infrastructure'); -$iop->skipEndpointList = array_merge($iop->skipEndpointList, $bad); - -if ($restrict) { - $tests = $iop->tests; - $iop->tests = array(); - foreach ($tests as $test) { - if (stristr($test, $restrict)) { - $iop->tests[] = $test; - } - } -} - -if ($iop->currentTest) { - $iop->doTest(); // run a single set of tests using above options -} else { - // $iop->doGroupTests(); // run a group of tests set in $currentTest - $iop->doTests(); // run all tests, ignore above options -} - -echo "done\n"; diff --git a/gulliver/thirdparty/pear/SOAP/Interop/interop_database.sql b/gulliver/thirdparty/pear/SOAP/Interop/interop_database.sql deleted file mode 100644 index bb2f5119b..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/interop_database.sql +++ /dev/null @@ -1,76 +0,0 @@ -# Database soapinterop running on localhost - -# phpMyAdmin MySQL-Dump -# version 2.2.5 -# http://phpwizard.net/phpMyAdmin/ -# http://phpmyadmin.sourceforge.net/ (download page) -# -# Host: localhost -# Generation Time: Aug 31, 2002 at 06:36 PM -# Server version: 3.23.49 -# PHP Version: 4.2.1 -# Database : `soapinterop` -# -------------------------------------------------------- - -# -# Table structure for table `clientinfo` -# - -CREATE TABLE clientinfo ( - id char(40) NOT NULL default '', - name char(100) NOT NULL default '', - version char(20) NOT NULL default '', - resultsURL char(255) NOT NULL default '' -) TYPE=InnoDB; -# -------------------------------------------------------- - -# -# Table structure for table `results` -# - -CREATE TABLE results ( - id int(11) NOT NULL auto_increment, - client varchar(100) NOT NULL default '0', - endpoint int(11) NOT NULL default '0', - stamp int(11) NOT NULL default '0', - class varchar(50) NOT NULL default '', - type varchar(10) default NULL, - wsdl int(11) NOT NULL default '0', - function varchar(255) NOT NULL default '', - result varchar(25) NOT NULL default '', - error text, - wire text NOT NULL, - PRIMARY KEY (id) -) TYPE=InnoDB; -# -------------------------------------------------------- - -# -# Table structure for table `serverinfo` -# - -CREATE TABLE serverinfo ( - id int(11) NOT NULL auto_increment, - service_id char(40) NOT NULL default '', - name char(100) NOT NULL default '', - version char(20) NOT NULL default '', - endpointURL char(255) NOT NULL default '', - wsdlURL char(255) NOT NULL default '', - PRIMARY KEY (id) -) TYPE=InnoDB; -# -------------------------------------------------------- - -# -# Table structure for table `services` -# - -CREATE TABLE services ( - id char(40) NOT NULL default '', - name char(50) NOT NULL default '', - description char(255) NOT NULL default '', - wsdlURL char(255) NOT NULL default '', - websiteURL char(255) NOT NULL default '', - PRIMARY KEY (id) -) TYPE=InnoDB; - - - diff --git a/gulliver/thirdparty/pear/SOAP/Interop/interop_test.php b/gulliver/thirdparty/pear/SOAP/Interop/interop_test.php deleted file mode 100644 index 4b3107989..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/interop_test.php +++ /dev/null @@ -1,137 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: interop_test.php,v 1.10 2007/01/26 17:21:44 yunosh Exp $ -// -require_once 'SOAP/Value.php'; - -define('SOAP_TEST_ACTOR_NEXT','http://schemas.xmlsoap.org/soap/actor/next'); -define('SOAP_TEST_ACTOR_OTHER','http://some/other/actor'); - -class SOAP_Interop_Test { - - var $type = 'php'; - var $test_name = null; - var $method_name = null; - var $method_params = null; - var $expect = null; - var $expect_fault = false; - var $headers = null; - var $headers_expect = null; - var $result = array(); - var $show = 1; - var $debug = 0; - var $encoding = SOAP_DEFAULT_ENCODING; - - /** - * If multiple services, this sets to a specific service. - */ - var $service = null; - - function SOAP_Interop_Test($methodname, $params, $expect = null) - { - if (strchr($methodname, '(')) { - preg_match('/(.*)\((.*)\)/', $methodname, $matches); - $this->test_name = $methodname; - $this->method_name = $matches[1]; - } else { - $this->test_name = $this->method_name = $methodname; - } - $this->method_params = $params; - $this->expect = $expect; - - // determine test type - if ($params) { - $v = array_values($params); - if (gettype($v[0]) == 'object' && - strtolower(get_class($v[0])) == 'soap_value') { - $this->type = 'soapval'; - } - } - } - - function setResult($ok, $result, $wire, $error = '', $fault = null) - { - $this->result['success'] = $ok; - $this->result['result'] = $result; - $this->result['error'] = $error; - $this->result['wire'] = $wire; - $this->result['fault'] = $fault; - } - - function reset() - { - $this->result = array(); - } - - /** - * Prints simple output about a methods result. - */ - function showTestResult($debug = 0) - { - // Debug output - if ($debug) { - $this->show = 1; - echo str_repeat('-', 50) . "\n"; - } - - echo "Testing $this->test_name: "; - if ($this->headers) { - $hc = count($this->headers); - for ($i = 0; $i < $hc; $i++) { - $h = $this->headers[$i]; - if (strtolower(get_class($h)) == 'soap_header') { - echo "\n {$h->name},{$h->attributes['SOAP-ENV:actor']},{$h->attributes['SOAP-ENV:mustUnderstand']} : "; - } else { - if (!$h[4]) { - $h[4] = SOAP_TEST_ACTOR_NEXT; - } - if (!$h[3]) { - $h[3] = 0; - } - echo "\n $h[0],$h[4],$h[3] : "; - } - } - } - - if ($debug) { - echo "method params: "; - print_r($this->params); - echo "\n"; - } - - $ok = $this->result['success']; - if ($ok) { - echo "SUCCESS\n"; - } else { - $fault = $this->result['fault']; - if ($fault) { - echo "FAILED: [{$fault->faultcode}] {$fault->faultstring}\n"; - if (!empty($fault->faultdetail)) { - echo $fault->faultdetail . "\n"; - } - } else { - echo "FAILED: " . $this->result['result'] . "\n"; - } - } - if ($debug) { - echo "\n" . $this->result['wire'] . "\n"; - } - } - -} diff --git a/gulliver/thirdparty/pear/SOAP/Interop/interop_test_functions.php b/gulliver/thirdparty/pear/SOAP/Interop/interop_test_functions.php deleted file mode 100644 index e6277eaab..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/interop_test_functions.php +++ /dev/null @@ -1,90 +0,0 @@ - 3) $d = 3; - $f1 = round($f1, $d); - $f2 = round($f2, $d); - return bccomp($f1, $f2, $d) == 0; -} - -function boolean_compare($f1, $f2) -{ - if (($f1 == 'true' || $f1 === TRUE || $f1 != 0) && - ($f2 == 'true' || $f2 === TRUE || $f2 != 0)) return TRUE; - if (($f1 == 'false' || $f1 === FALSE || $f1 == 0) && - ($f2 == 'false' || $f2 === FALSE || $f2 == 0)) return TRUE; - return FALSE; -} - -function string_compare($e1, $e2) -{ - if (is_numeric($e1) && is_numeric($e2)) { - return number_compare($e1, $e2); - } - # handle dateTime comparison - $e1_type = gettype($e1); - $e2_type = gettype($e2); - $ok = FALSE; - if ($e1_type == "string") { - require_once 'SOAP/Type/dateTime.php'; - $dt =& new SOAP_Type_dateTime(); - $ok = $dt->compare($e1, $e2) == 0; - } - return $ok || $e1 == $e2 || strcasecmp(trim($e1), trim($e2)) == 0; -} - -function array_compare(&$ar1, &$ar2) -{ - if (gettype($ar1) != 'array' || gettype($ar2) != 'array') return FALSE; - # first a shallow diff - if (count($ar1) != count($ar2)) return FALSE; - $diff = array_diff($ar1, $ar2); - if (count($diff) == 0) return TRUE; - - # diff failed, do a full check of the array - foreach ($ar1 as $k => $v) { - #print "comparing $v == $ar2[$k]\n"; - if (gettype($v) == "array") { - if (!array_compare($v, $ar2[$k])) return FALSE; - } else { - if (!string_compare($v, $ar2[$k])) return FALSE; - if ($type == 'float') - # we'll only compare to 3 digits of precision - $ok = number_compare($expect, $result,3); - if ($type == 'boolean') - $ok = boolean_compare($expect, $result); - else - $ok = string_compare($expect, $result); - } - } - return TRUE; -} - - -function &parseMessage($msg) -{ - # strip line endings - #$msg = preg_replace('/\r|\n/', ' ', $msg); - $response =& new SOAP_Parser($msg); - if ($response->fault) { - return $response->fault->getFault(); - } - $return =& $response->getResponse(); - $v =& $response->decode($return); - if (gettype($v) == 'array' && count($v)==1) { - return array_shift($v); - } - return $v; -} - - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/SOAP/Interop/params_Round2Base.php b/gulliver/thirdparty/pear/SOAP/Interop/params_Round2Base.php deleted file mode 100644 index cfc821b15..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/params_Round2Base.php +++ /dev/null @@ -1,230 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: params_Round2Base.php,v 1.6 2007/01/26 14:54:51 yunosh Exp $ -// - -require_once 'params_values.php'; -require_once 'interop_test.php'; -define('INTEROP_R2BASE', 'Round 2 Base'); - -//*********************************************************** -// Base echoString - -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoString', - array('inputString' => $string), - $soap_test_null); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoString', - array('inputString' => $string_soapval)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoString(null)', - array('inputString' => $string_null)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoString(null)', - array('inputString' => $string_null_soapval)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoString(entities)', - array('inputString' => $string_entities)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoString(entities)', - array('inputString' => $string_entities_soapval)); -$test = new SOAP_Interop_Test( - 'echoString(utf-8)', - array('inputString' => $string_utf8)); -$test->encoding = 'UTF-8'; -$soap_tests[INTEROP_R2BASE][] = $test; -unset($test); - -$test = new SOAP_Interop_Test( - 'echoString(utf-8)', - array('inputString' => $string_utf8_soapval)); -$test->encoding = 'UTF-8'; -$soap_tests[INTEROP_R2BASE][] = $test; -unset($test); - -//*********************************************************** -// Base echoStringArray - -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoStringArray', - array('inputStringArray' => $string_array)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoStringArray', - array('inputStringArray' => $string_array_soapval)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoStringArray(one)', - array('inputStringArray' => $string_array_one)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoStringArray(one)', - array('inputStringArray' => $string_array_one_soapval)); -// null array test -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoStringArray(null)', - array('inputStringArray' => $string_array_null)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoStringArray(null)', - array('inputStringArray' => $string_array_null_soapval)); - -//*********************************************************** -// Base echoInteger - -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoInteger', - array('inputInteger' => $integer)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoInteger', - array('inputInteger' => $integer_soapval)); - -//*********************************************************** -// Base echoIntegerArray - -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoIntegerArray', - array('inputIntegerArray' => $integer_array)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoIntegerArray', - array('inputIntegerArray' => $integer_array_soapval)); - -// null array test -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoIntegerArray(null)', - array('inputIntegerArray' => $integer_array_null)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoIntegerArray(null)', - array('inputIntegerArray' => $integer_array_null_soapval)); - -//*********************************************************** -// Base echoFloat - -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoFloat', - array('inputFloat' => $float)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoFloat', - array('inputFloat' => $float_soapval)); - -//*********************************************************** -// Base echoFloatArray - -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoFloatArray', - array('inputFloatArray' => $float_array)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoFloatArray', - array('inputFloatArray' => $float_array_soapval)); - -//*********************************************************** -// Base echoStruct - -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoStruct', - array('inputStruct' => $soapstruct)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoStruct', - array('inputStruct' => $soapstruct_soapval)); - -//*********************************************************** -// Base echoStructArray - -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoStructArray', - array('inputStructArray' => $soapstruct_array)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoStructArray', - array('inputStructArray' => $soapstruct_array_soapval)); - -//*********************************************************** -// Base echoVoid - -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test('echoVoid', null); -$test = new SOAP_Interop_Test('echoVoid', null); -$test->type = 'soapval'; -$soap_tests[INTEROP_R2BASE][] = $test; -unset($test); - -//*********************************************************** -// Base echoBase64 - -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoBase64', - array('inputBase64' => $base64), - 'Nebraska'); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoBase64', - array('inputBase64' => $base64_soapval), - 'Nebraska'); - -//*********************************************************** -// Base echoHexBinary - -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoHexBinary', - array('inputHexBinary' => $hexBin)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoHexBinary', - array('inputHexBinary' => $hexBin_soapval)); - -//*********************************************************** -// Base echoDecimal - -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoDecimal', - array('inputDecimal' => $decimal)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoDecimal', - array('inputDecimal' => $decimal_soapval)); - -//*********************************************************** -// Base echoDate - -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoDate', - array('inputDate' => $dateTime)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoDate', - array('inputDate' => $dateTime_soapval)); - -//*********************************************************** -// Base echoBoolean - -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoBoolean(TRUE)', - array('inputBoolean' => $boolean_true)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoBoolean(TRUE)', - array('inputBoolean' => $boolean_true_soapval)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoBoolean(FALSE)', - array('inputBoolean' => $boolean_false)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoBoolean(FALSE)', - array('inputBoolean' => $boolean_false_soapval)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoBoolean(1)', - array('inputBoolean' => $boolean_one)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoBoolean(1)', - array('inputBoolean' => $boolean_one_soapval)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoBoolean(0)', - array('inputBoolean' => $boolean_zero)); -$soap_tests[INTEROP_R2BASE][] = new SOAP_Interop_Test( - 'echoBoolean(0)', - array('inputBoolean' => $boolean_zero_soapval)); diff --git a/gulliver/thirdparty/pear/SOAP/Interop/params_Round2GroupB.php b/gulliver/thirdparty/pear/SOAP/Interop/params_Round2GroupB.php deleted file mode 100644 index ba48201d2..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/params_Round2GroupB.php +++ /dev/null @@ -1,72 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: params_Round2GroupB.php,v 1.4 2003/04/07 00:51:17 shane Exp $ -// -require_once 'params_values.php'; -require_once 'interop_test.php'; -define('INTEROP_R2GROUPB','Round 2 Group B'); -//*********************************************************** -// GroupB echoStructAsSimpleTypes - -$expect = array( - 'outputString'=>'arg', - 'outputInteger'=>34, - 'outputFloat'=>325.325 - ); -$soap_tests[INTEROP_R2GROUPB][] = - new SOAP_Interop_Test('echoStructAsSimpleTypes', - array('inputStruct' => &$soapstruct), $expect); -$soap_tests[INTEROP_R2GROUPB][] = - new SOAP_Interop_Test('echoStructAsSimpleTypes', - array('inputStruct' => &$soapstruct_soapval), $expect); - -//*********************************************************** -// GroupB echoSimpleTypesAsStruct - -$soap_tests[INTEROP_R2GROUPB][] =& new SOAP_Interop_Test('echoSimpleTypesAsStruct', - $simpletypes, $soapstruct); -$soap_tests[INTEROP_R2GROUPB][] =& new SOAP_Interop_Test('echoSimpleTypesAsStruct', - $simpletypes_soapval, $soapstruct); - -//*********************************************************** -// GroupB echo2DStringArray - -$soap_tests[INTEROP_R2GROUPB][] =& new SOAP_Interop_Test('echo2DStringArray', - array('input2DStringArray' => &$multidimarray)); -$soap_tests[INTEROP_R2GROUPB][] =& new SOAP_Interop_Test('echo2DStringArray', - array('input2DStringArray' => &$multidimarray_soapval)); - -//*********************************************************** -// GroupB echoNestedStruct - -$soap_tests[INTEROP_R2GROUPB][] =& new SOAP_Interop_Test('echoNestedStruct', - array('inputStruct' => &$soapstructstruct)); -$soap_tests[INTEROP_R2GROUPB][] =& new SOAP_Interop_Test('echoNestedStruct', - array('inputStruct' => &$soapstructstruct_soapval)); - -//*********************************************************** -// GroupB echoNestedArray - -$soap_tests[INTEROP_R2GROUPB][] =& new SOAP_Interop_Test('echoNestedArray', - array('inputStruct' => &$soaparraystruct)); -$soap_tests[INTEROP_R2GROUPB][] =& new SOAP_Interop_Test('echoNestedArray', - array('inputStruct' => &$soaparraystruct_soapval)); - - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/SOAP/Interop/params_Round2GroupC.php b/gulliver/thirdparty/pear/SOAP/Interop/params_Round2GroupC.php deleted file mode 100644 index 9681d8851..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/params_Round2GroupC.php +++ /dev/null @@ -1,235 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: params_Round2GroupC.php,v 1.4 2003/04/07 00:51:17 shane Exp $ -// -require_once 'params_values.php'; -require_once 'interop_test.php'; -define('INTEROP_R2GROUPC','Round 2 Group C'); -//*********************************************************** -// echoMeStringRequest php val tests - -// echoMeStringRequest with endpoint as header destination, doesn't have to understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->headers[] = array('{http://soapinterop.org/echoheader/}echoMeStringRequest', &$string, 0,SOAP_TEST_ACTOR_NEXT); -$test->headers_expect['echoMeStringRequest'] = array('echoMeStringResponse'=>&$string); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -// echoMeStringRequest with endpoint as header destination, must understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->headers[] = array('{http://soapinterop.org/echoheader/}echoMeStringRequest', &$string, 1,SOAP_TEST_ACTOR_NEXT); -$test->headers_expect['echoMeStringRequest'] = array('echoMeStringResponse'=>&$string); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -// echoMeStringRequest with endpoint NOT header destination, doesn't have to understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->headers[] = array('{http://soapinterop.org/echoheader/}echoMeStringRequest', &$string, 0, SOAP_TEST_ACTOR_OTHER); -$test->headers_expect['echoMeStringRequest'] = array(); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -// echoMeStringRequest with endpoint NOT header destination, must understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->headers[] = array('{http://soapinterop.org/echoheader/}echoMeStringRequest', &$string, 1, SOAP_TEST_ACTOR_OTHER); -$test->headers_expect['echoMeStringRequest'] = array(); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -//*********************************************************** -// echoMeStringRequest soapval tests - -// echoMeStringRequest with endpoint as header destination, doesn't have to understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->type = 'soapval'; -$test->headers[] =& new SOAP_Header('{http://soapinterop.org/echoheader/}echoMeStringRequest', 'string', $string); -$test->headers_expect['echoMeStringRequest'] = array('echoMeStringResponse'=>&$string); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -// echoMeStringRequest with endpoint as header destination, must understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->type = 'soapval'; -$test->headers[] =& new SOAP_Header('{http://soapinterop.org/echoheader/}echoMeStringRequest', 'string', $string, 1); -$test->type = 'soapval'; // force a soapval version of this test -$test->headers_expect['echoMeStringRequest'] = array('echoMeStringResponse'=>&$string); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -// echoMeStringRequest with endpoint NOT header destination, doesn't have to understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->type = 'soapval'; -$test->headers[] =& new SOAP_Header('{http://soapinterop.org/echoheader/}echoMeStringRequest', 'string', $string, 0, SOAP_TEST_ACTOR_OTHER); -$test->headers_expect['echoMeStringRequest'] = array(); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -// echoMeStringRequest with endpoint NOT header destination, must understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->type = 'soapval'; -$test->headers[] =& new SOAP_Header('{http://soapinterop.org/echoheader/}echoMeStringRequest', 'string', $string, 1, SOAP_TEST_ACTOR_OTHER); -$test->headers_expect['echoMeStringRequest'] = array(); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -// echoMeStringRequest with endpoint header destination, must understand, -// invalid namespace, should recieve a fault -#$test =& new SOAP_Interop_Test('echoVoid', NULL); -#$test->type = 'soapval'; -#$test->headers[] =& new SOAP_Header('{http://unknown.org/echoheader/}echoMeStringRequest', 'string', 'hello world', 1); -#$test->headers_expect['echoMeStringRequest'] = array(); -#$test->expect_fault = TRUE; -#$soap_tests[INTEROP_R2GROUPC][] = $test; - -//*********************************************************** -// php val tests -// echoMeStructRequest with endpoint as header destination, doesn't have to understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->headers[] = $soapstruct->__to_soap('{http://soapinterop.org/echoheader/}echoMeStructRequest',TRUE); -$test->headers_expect['echoMeStructRequest'] = - array('echoMeStructResponse'=> &$soapstruct); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -// echoMeStructRequest with endpoint as header destination, must understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->headers[] = $soapstruct->__to_soap('{http://soapinterop.org/echoheader/}echoMeStructRequest',TRUE,1); -$test->headers_expect['echoMeStructRequest'] = - array('echoMeStructResponse'=> &$soapstruct); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -// echoMeStructRequest with endpoint NOT header destination, doesn't have to understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->headers[] = $soapstruct->__to_soap('{http://soapinterop.org/echoheader/}echoMeStructRequest',TRUE,0, SOAP_TEST_ACTOR_OTHER); -$test->headers_expect['echoMeStructRequest'] = array(); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -// echoMeStructRequest with endpoint NOT header destination, must understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->headers[] = $soapstruct->__to_soap('{http://soapinterop.org/echoheader/}echoMeStructRequest',TRUE,1, SOAP_TEST_ACTOR_OTHER); -$test->headers_expect['echoMeStructRequest'] = array(); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -//*********************************************************** -// soapval tests -// echoMeStructRequest with endpoint as header destination, doesn't have to understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->type = 'soapval'; -$test->headers[] = $soapstruct->__to_soap('{http://soapinterop.org/echoheader/}echoMeStructRequest',TRUE); -$test->headers_expect['echoMeStructRequest'] = - array('echoMeStructResponse'=> &$soapstruct); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -// echoMeStructRequest with endpoint as header destination, must understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->type = 'soapval'; -$test->headers[] = $soapstruct->__to_soap('{http://soapinterop.org/echoheader/}echoMeStructRequest',TRUE,1); -$test->headers_expect['echoMeStructRequest'] = - array('echoMeStructResponse'=> &$soapstruct); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -// echoMeStructRequest with endpoint NOT header destination, doesn't have to understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->type = 'soapval'; -$test->headers[] = $soapstruct->__to_soap('{http://soapinterop.org/echoheader/}echoMeStructRequest',TRUE,0, SOAP_TEST_ACTOR_OTHER); -$test->headers_expect['echoMeStructRequest'] = array(); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -// echoMeStructRequest with endpoint NOT header destination, must understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->type = 'soapval'; -$test->headers[] = $soapstruct->__to_soap('{http://soapinterop.org/echoheader/}echoMeStructRequest',TRUE,1, SOAP_TEST_ACTOR_OTHER); -$test->headers_expect['echoMeStructRequest'] = array(); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -//*********************************************************** -// echoMeUnknown php val tests -// echoMeUnknown with endpoint as header destination, doesn't have to understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->headers[] = array('{http://soapinterop.org/echoheader/}echoMeUnknown', $string,0,SOAP_TEST_ACTOR_NEXT); -$test->headers_expect['echoMeUnknown'] = array(); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -// echoMeUnknown with endpoint as header destination, must understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->headers[] = array('{http://soapinterop.org/echoheader/}echoMeUnknown', $string,1,SOAP_TEST_ACTOR_NEXT); -$test->headers_expect['echoMeUnknown'] = array(); -$test->expect_fault = TRUE; -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -// echoMeUnknown with endpoint NOT header destination, doesn't have to understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->headers[] = array('{http://soapinterop.org/echoheader/}echoMeUnknown', $string,0, SOAP_TEST_ACTOR_OTHER); -$test->headers_expect['echoMeUnknown'] = array(); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -// echoMeUnknown with endpoint NOT header destination, must understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->headers[] = array('{http://soapinterop.org/echoheader/}echoMeUnknown', $string, 1, SOAP_TEST_ACTOR_OTHER); -$test->headers_expect['echoMeUnknown'] = array(); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -//*********************************************************** -// echoMeUnknown soapval tests -// echoMeUnknown with endpoint as header destination, doesn't have to understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->type = 'soapval'; -$test->headers[] =& new SOAP_Header('{http://soapinterop.org/echoheader/}echoMeUnknown','string',$string); -$test->headers_expect['echoMeUnknown'] = array(); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -// echoMeUnknown with endpoint as header destination, must understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->type = 'soapval'; -$test->headers[] =& new SOAP_Header('{http://soapinterop.org/echoheader/}echoMeUnknown','string',$string,1); -$test->headers_expect['echoMeUnknown'] = array(); -$test->expect_fault = TRUE; -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -// echoMeUnknown with endpoint NOT header destination, doesn't have to understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->type = 'soapval'; -$test->headers[] =& new SOAP_Header('{http://soapinterop.org/echoheader/}echoMeUnknown','string',$string, 0, SOAP_TEST_ACTOR_OTHER); -$test->headers_expect['echoMeUnknown'] = array(); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - -// echoMeUnknown with endpoint NOT header destination, must understand -$test =& new SOAP_Interop_Test('echoVoid', NULL); -$test->type = 'soapval'; -$test->headers[] =& new SOAP_Header('{http://soapinterop.org/echoheader/}echoMeUnknown','string',$string, 1, SOAP_TEST_ACTOR_OTHER); -$test->headers_expect['echoMeUnknown'] = array(); -$soap_tests[INTEROP_R2GROUPC][] =& $test; -unset($test); - - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/SOAP/Interop/params_Round3GroupD.php b/gulliver/thirdparty/pear/SOAP/Interop/params_Round3GroupD.php deleted file mode 100644 index 70fde94e1..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/params_Round3GroupD.php +++ /dev/null @@ -1,121 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: params_Round3GroupD.php,v 1.7 2003/04/14 01:40:21 shane Exp $ -// -require_once 'params_values.php'; -require_once 'interop_test.php'; -define('INTEROP_R3D_COMPOUND1','Round 3 Group D Compound 1'); -define('INTEROP_R3D_COMPOUND2','Round 3 Group D Compound 2'); -define('INTEROP_R3D_DOCLIT','Round 3 Group D DocLit'); -define('INTEROP_R3D_DOCLIT_PARAM','Round 3 Group D DocLitParams'); -define('INTEROP_R3D_IMPORT1','Round 3 Group D Import 1'); -define('INTEROP_R3D_IMPORT2','Round 3 Group D Import 2'); -define('INTEROP_R3D_IMPORT3','Round 3 Group D Import 3'); -define('INTEROP_R3D_RPCENC','Round 3 Group D RpcEnc'); -//*********************************************************** -// GroupD - -# COMPOUND 1 tests -# http://www.whitemesa.net/wsdl/r3/compound1.wsdl -$test =& new SOAP_Interop_Test('echoPerson', array('x_Person'=>&$person)); -$test->type = 'php'; // force to php testing -$soap_tests[INTEROP_R3D_COMPOUND1][] = &$test; -unset($test); - -$test =& new SOAP_Interop_Test('echoDocument', array('x_Document'=>'Test Document Here')); -$test->type = 'php'; // force to php testing -$soap_tests[INTEROP_R3D_COMPOUND1][] = &$test; -unset($test); - -# COMPOUND 2 tests -# http://www.whitemesa.net/wsdl/r3/compound2.wsdl -$test =& new SOAP_Interop_Test('echoEmployee', array('x_Employee'=>&$employee)); -$test->type = 'php'; // force to php testing -$soap_tests[INTEROP_R3D_COMPOUND2][] = &$test; -unset($test); - -# DOC LIT Tests -# http://www.whitemesa.net/wsdl/r3/interoptestdoclit.wsdl -$soap_tests[INTEROP_R3D_DOCLIT][] =& - new SOAP_Interop_Test('echoString', - array('echoStringParam' => &$string)); -$soap_tests[INTEROP_R3D_DOCLIT][] =& - new SOAP_Interop_Test('echoStringArray', - array('echoStringArrayParam' => &$string_array)); -$soap_tests[INTEROP_R3D_DOCLIT][] =& - new SOAP_Interop_Test('echoStruct', - array('echoStructParam' => &$soapstruct)); -#$soap_tests[INTEROP_R3D_DOCLIT][] = -# new SOAP_Interop_Test('echoVoid', NULL); - -# DOC LIT w/Params Tests -# http://www.whitemesa.net/wsdl/r3/interoptestdoclitparameters.wsdl -$soap_tests[INTEROP_R3D_DOCLIT_PARAM][] =& - new SOAP_Interop_Test('echoString', - array('param0' => $string)); -$soap_tests[INTEROP_R3D_DOCLIT_PARAM][] =& - new SOAP_Interop_Test('echoStringArray', - array('param0' => &$string_array)); -$soap_tests[INTEROP_R3D_DOCLIT_PARAM][] =& - new SOAP_Interop_Test('echoStruct', - array('param0' => &$soapstruct)); -$soap_tests[INTEROP_R3D_DOCLIT_PARAM][] =& - new SOAP_Interop_Test('echoVoid', NULL); - -# IMPORT 1 tests -# http://www.whitemesa.net/wsdl/r3/import1.wsdl -$soap_tests[INTEROP_R3D_IMPORT1][] =& - new SOAP_Interop_Test('echoString', - array('x' => &$string)); - -# IMPORT 2 tests -# http://www.whitemesa.net/wsdl/r3/import2.wsdl -$soap_tests[INTEROP_R3D_IMPORT2][] =& - new SOAP_Interop_Test('echoStruct', - array('inputStruct' => &$soapstruct)); - -# IMPORT 2 tests -# http://www.whitemesa.net/wsdl/r3/import3.wsdl -$test =& new SOAP_Interop_Test('echoStruct', - array('inputStruct' => &$soapstruct)); -$test->service = 'Import3'; -$soap_tests[INTEROP_R3D_IMPORT3][] = &$test; -unset($test); - -$test =& new SOAP_Interop_Test('echoStructArray', - array('inputArray' =>&$soapstruct_array)); -$test->service = 'Import3'; -$soap_tests[INTEROP_R3D_IMPORT3][] = &$test; -unset($test); - -# RPC ENCODED Tests -# http://www.whitemesa.net/wsdl/r3/interoptestdoclitparameters.wsdl -$soap_tests[INTEROP_R3D_RPCENC][] =& - new SOAP_Interop_Test('echoString', - array('param0' => &$string)); -$soap_tests[INTEROP_R3D_RPCENC][] =& - new SOAP_Interop_Test('echoStringArray', - array('param0' => &$string_array)); -$soap_tests[INTEROP_R3D_RPCENC][] =& - new SOAP_Interop_Test('echoStruct', - array('param0' => &$soapstruct)); -$soap_tests[INTEROP_R3D_RPCENC][] =& - new SOAP_Interop_Test('echoVoid', NULL); - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/SOAP/Interop/params_classes.php b/gulliver/thirdparty/pear/SOAP/Interop/params_classes.php deleted file mode 100644 index 187b311ce..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/params_classes.php +++ /dev/null @@ -1,162 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: params_classes.php,v 1.8 2007/01/21 16:15:00 yunosh Exp $ -// -require_once 'SOAP/Value.php'; - -class SOAPStruct { - var $varString; - var $varInt; - var $varFloat; - function SOAPStruct($s=NULL, $i=NULL, $f=NULL) { - $this->varString = $s; - $this->varInt = $i; - $this->varFloat = $f; - } - - function __to_soap($name = 'inputStruct', $header=false, $mustUnderstand=0, $actor='http://schemas.xmlsoap.org/soap/actor/next') - { - $inner[] = new SOAP_Value('varString','string',$this->varString); - $inner[] = new SOAP_Value('varInt','int',$this->varInt); - $inner[] = new SOAP_Value('varFloat','float',$this->varFloat); - if ($header) { - return new SOAP_Header($name,'{http://soapinterop.org/xsd}SOAPStruct',$inner,$mustUnderstand,$actor); - } - return new SOAP_Value($name,'{http://soapinterop.org/xsd}SOAPStruct',$inner); - - } -} - -class SOAPStructStruct { - var $varString; - var $varInt; - var $varFloat; - var $varStruct; - function SOAPStructStruct($s=NULL, $i=NULL, $f=NULL, $ss=NULL) { - // XXX unfortunately, a copy of $ss will occure here - // ze2 can fix this I think - $this->varString = $s; - $this->varInt = $i; - $this->varFloat = $f; - $this->varStruct = $ss; - } - - function __to_soap($name = 'inputStruct') - { - $v[] = new SOAP_Value('varString','string',$this->varString); - $v[] = new SOAP_Value('varInt','int',$this->varInt); - $v[] = new SOAP_Value('varFloat','float',$this->varFloat); - $v[] = $this->varStruct->__to_soap('varStruct'); - return new SOAP_Value($name,'{http://soapinterop.org/xsd}SOAPStructStruct',$v); - } -} - -class SOAPArrayStruct { - var $varString; - var $varInt; - var $varFloat; - var $varArray; - function SOAPArrayStruct($s=NULL, $i=NULL, $f=NULL, $ss=NULL) { - // XXX unfortunately, a copy of $ss will occure here - // ze2 can fix this I think - $this->varString = $s; - $this->varInt = $i; - $this->varFloat = $f; - $this->varArray = $ss; - } - - function __to_soap($name = 'inputStruct') - { - $ar = array(); - $c = count($this->varArray); - for ($i=0; $i<$c; $i++) { - $ar[] = new SOAP_Value('item','string',$this->varArray[$i]); - } - $v[] = new SOAP_Value('varString','string',$this->varString); - $v[] = new SOAP_Value('varInt','int',$this->varInt); - $v[] = new SOAP_Value('varFloat','float',$this->varFloat); - $v[] = new SOAP_Value('varArray',false,$ar); - - return new SOAP_Value($name,'{http://soapinterop.org/xsd}SOAPArrayStruct',$v); - } -} - -class Person { - var $Age; - var $ID; - var $Name; - var $Male; - function Person($a=NULL, $i=NULL, $n=NULL, $m=NULL) { - $this->Age = $a; - $this->ID = $i; - $this->Name = $n; - $this->Male = $m; - } - - function __set_attribute($key, $value) - { - $this->$key = $value; - } - - function __to_soap($name = 'x_Person',$ns = 'http://soapinterop.org/xsd', $compound2=false) - { - if (!$compound2) { - $v[] = new SOAP_Value("\{$ns}Age",'double',$this->Age); - $v[] = new SOAP_Value("\{$ns}ID",'float',$this->ID); - return new SOAP_Value("\{$ns}$name",'Person', - $v,array('Name'=>$this->Name,'Male'=>$this->Male)); - } else - $v[] = new SOAP_Value("\{$ns}Name",'string',$this->Name); - $v[] = new SOAP_Value("\{$ns}Male",'boolean',$this->Male); - return new SOAP_Value("\{$ns}$name",'Person',$v); - } -} - -class x_Person extends Person { - function x_Person($a=NULL, $i=NULL, $n=NULL, $m=NULL) { - $parent->Person($a,$i,$n,$m); - } -} - -class Employee { - var $ID; - var $salary; - var $person; // class person2 - function Employee($person=NULL,$id=NULL,$salary=NULL) { - $this->person = $person; - $this->ID = $id; - $this->salary = $salary; - } - - function __to_soap($name = 'x_Employee', $ns='http://soapinterop.org/employee') - { - $person = $this->person->__to_soap('person','http://soapinterop.org/person',true); - $person->namespace = $ns; - $va[] = $person; - $va[] = new SOAP_Value("\{$ns}salary",'double',$this->salary); - $va[] = new SOAP_Value("\{$ns}ID",'int',$this->ID); - return new SOAP_Value("\{$ns}$name",'Employee',$va); - } -} - -class x_Employee extends Employee { - function x_Employee($person=NULL,$id=NULL,$salary=NULL) { - $parent->Employee($person,$id,$salary); - } -} diff --git a/gulliver/thirdparty/pear/SOAP/Interop/params_values.php b/gulliver/thirdparty/pear/SOAP/Interop/params_values.php deleted file mode 100644 index cfa27f09a..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/params_values.php +++ /dev/null @@ -1,173 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: params_values.php,v 1.7 2007/01/26 15:18:21 yunosh Exp $ -// - -require_once 'SOAP/Value.php'; -require_once 'params_classes.php'; - -$soap_test_null = null; - -$string = 'Hello World'; -$string_soapval = new SOAP_Value('inputString', 'string', $string); -$string_null = null; -$string_null_soapval = new SOAP_Value('inputString', 'string', $string_null); -$string_entities = "this is a test \n"; -$string_entities_soapval = new SOAP_Value('inputString', 'string', $string_entities); -$string_utf8 = utf8_encode('ỗÈéóÒ₧⅜ỗỸ'); -$string_utf8_soapval = new SOAP_Value('inputString', 'string', $string_utf8); -$string_array = array('good', 'bad'); -$string_array_soapval = new SOAP_Value( - 'inputStringArray', - 'Array', - array(new SOAP_Value('item', 'string', 'good'), - new SOAP_Value('item', 'string', 'bad'))); - -$string_array_one = array('good'); -$string_array_one_soapval = new SOAP_Value( - 'inputStringArray', - 'Array', - array(new SOAP_Value('item', 'string', 'good'))); - -$string_array_null = null; -$string_array_null_soapval = new SOAP_Value('inputStringArray', 'Array', null); -$string_array_null_soapval->arrayType='{http://www.w3.org/2001/XMLSchema}string'; - -$integer = 12345; -$integer_soapval = new SOAP_Value('inputInteger', 'int', $integer); -$integer_array = array(1, 234324324, 2); -$integer_array_soapval = new SOAP_Value( - 'inputIntegerArray', - 'Array', - array(new SOAP_Value('item', 'int', 1), - new SOAP_Value('item', 'int', 234324324), - new SOAP_Value('item', 'int', 2))); - -$integer_array_null = null; -$integer_array_null_soapval = new SOAP_Value('inputIntegerArray', 'Array', null); -$integer_array_null_soapval->arrayType='{http://www.w3.org/2001/XMLSchema}int'; - -$float = 123.45; -$float_soapval = new SOAP_Value('inputFloat', 'float', $float); -$float_array = array(1.0, 2343.24324, -2.5); -$float_array_soapval = new SOAP_Value( - 'inputFloatArray', - 'Array', - array(new SOAP_Value('item', 'float', 1.0), - new SOAP_Value('item', 'float', 2343.24324), - new SOAP_Value('item', 'float', -2.5))); - -$float_array_null = null; -$float_array_null_soapval = new SOAP_Value('inputFloatArray', 'Array', null); -$float_array_null_soapval->arrayType='{http://www.w3.org/2001/XMLSchema}float'; - -$soapstruct = new SOAPStruct('arg', 34, 325.325); -$soapstruct_soapval = $soapstruct->__to_soap(); -$soapstruct_header_soapval = $soapstruct->__to_soap('{http://soapinterop.org/echoheader/}echoMeStructRequest'); -$soapstruct_array = array($soapstruct, $soapstruct, $soapstruct); -$soapstruct_array_soapval = new SOAP_Value( - 'inputStructArray', - 'Array', - array($soapstruct_soapval, - $soapstruct_soapval, - $soapstruct_soapval)); - -$soapstructstruct = new SOAPStructStruct('arg', 34, 325.325, $soapstruct); -$soapstructstruct_soapval = $soapstructstruct->__to_soap(); -$soapstructstruct_array = array($soapstructstruct, $soapstructstruct, $soapstructstruct); -$soapstructstruct_array_soapval = new SOAP_Value( - 'inputStructArray', - 'Array', - array($soapstructstruct_soapval, - $soapstructstruct_soapval, - $soapstructstruct_soapval)); - -$soaparraystruct = new SOAPArrayStruct('arg', 34, 325.325, - array('good', 'bad', 'ugly')); -$soaparraystruct_soapval = $soaparraystruct->__to_soap(); -$soaparraystruct_array = array($soaparraystruct, $soaparraystruct, $soaparraystruct); -$soaparraystruct_array_soapval = new SOAP_Value( - 'inputStructArray', - 'Array', - array($soaparraystruct_soapval, - $soaparraystruct_soapval, - $soaparraystruct_soapval)); - -$simpletypes = array( - 'inputString'=>'arg', - 'inputInteger'=>34, - 'inputFloat'=>325.325 - ); - -$simpletypes_soapval = array(); -$simpletypes_soapval[] = new SOAP_Value('inputString', 'string', 'arg'); -$simpletypes_soapval[] = new SOAP_Value('inputInteger', 'int', 34); -$simpletypes_soapval[] = new SOAP_Value('inputFloat', 'float', 325.325); - -$base64 = 'TmVicmFza2E='; -$base64_soapval = new SOAP_Value('inputBase64', 'base64Binary', $base64); - -$hexBin = '736F61707834'; -$hexBin_soapval = new SOAP_Value('inputHexBinary', 'hexBinary', $hexBin); - -$decimal = 12345.67890; -$decimal_soapval =new SOAP_Value('inputDecimal', 'decimal', $decimal); - -$dateTime = '2001-05-24T17:31:41Z'; -$dateTime_soapval = new SOAP_Value('inputDate', 'dateTime', $dateTime); - -$boolean_true = true; -$boolean_true_soapval = new SOAP_Value('inputBoolean', 'boolean', true); -$boolean_false = false; -$boolean_false_soapval = new SOAP_Value('inputBoolean', 'boolean', false); -$boolean_one = 1; -$boolean_one_soapval = new SOAP_Value('inputBoolean', 'boolean', 1); -$boolean_zero = 0; -$boolean_zero_soapval = new SOAP_Value('inputBoolean', 'boolean', 0); - -// XXX I know this isn't quite right, need to deal with this better -function &make_2d($x, $y) -{ - $a = array(); - for ($_x = 0; $_x < $x; $_x++) { - $a[$_x] = array(); - for ($_y = 0; $_y < $y; $_y++) { - $a[$_x][$_y] = "x{$_x}y{$_y}"; - } - } - return $a; -} - -$multidimarray = make_2d(3, 3); -$multidimarray_soapval = new SOAP_Value( - 'input2DStringArray', - 'Array', - array(array(new SOAP_Value('item', 'string', 'row0col0'), - new SOAP_Value('item', 'string', 'row0col1'), - new SOAP_Value('item', 'string', 'row0col2')), - array(new SOAP_Value('item', 'string', 'row1col0'), - new SOAP_Value('item', 'string', 'row1col1'), - new SOAP_Value('item', 'string', 'row1col2')))); -$multidimarray_soapval->options['flatten'] = true; - -// Round2GroupC values -$_person = new Person(32, 12345, 'Shane', true); -$person = $_person->__to_soap(); -$_employee = new Employee($_person, 12345, 1000000.00); -$employee = $_employee->__to_soap(); diff --git a/gulliver/thirdparty/pear/SOAP/Interop/readme.txt b/gulliver/thirdparty/pear/SOAP/Interop/readme.txt deleted file mode 100644 index 933e65265..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/readme.txt +++ /dev/null @@ -1,23 +0,0 @@ -Round 2 Interop Test files - -Resources: -http://www.whitemesa.com/interop.htm -http://www.whitemesa.com/r3/interop3.html -http://www.pocketsoap.com/registration/ - -Requires an SQL database, schema for MySQL is in interop_database.sql. - -Run interop_client_run.php to store test results. -View index.php to see test results. - -To setup an interop server: - -1. Copy config.php.dist to config.php. -2. Web server must alias url /soap_interop/ to the pear/SOAP_Interop - directory. The alias url can be set in config.php. -3. index.php should be set for the default document. -4. MySQL should be set up, with a database called interop, schema is in - interop_database.sql. Database name, user, and password can be set in - config.php. -5. interop_client_run.php should not be left under the web root, it is - available for manual testing. diff --git a/gulliver/thirdparty/pear/SOAP/Interop/registrationAndNotification.php b/gulliver/thirdparty/pear/SOAP/Interop/registrationAndNotification.php deleted file mode 100644 index bda1d5a5c..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/registrationAndNotification.php +++ /dev/null @@ -1,473 +0,0 @@ -$v) { - $this->$k = $v; - } - } - } -} - -class serverInfo { - var $id; - var $service_id; - var $name; - var $version; - var $endpointURL; - var $wsdlURL; - - function serverInfo($ar=NULL) { - if (is_array($ar)) { - foreach ($ar as $k=>$v) { - $this->$k = $v; - } - } - } -} - -class Service { - var $id; - var $name; - var $description; - var $wsdlURL; - var $websiteURL; - - function Service($ar=NULL) { - if (is_array($ar)) { - foreach ($ar as $k=>$v) { - $this->$k = $v; - } - } - } -} - -class subscriberInfo { - var $notificationID; - var $expires; /* dateTime */ -} - -class ChangeItem { - var $id; - var $timestamp; /* dateTime */ - var $headline; - var $notes; - var $url; -} - -function getLocalInteropServer($testname,$id,$localBaseUrl='http://localhost/soap_interop/') { - $localServer = array(); - $localServer['service_id']=$id; - $localServer['name']='Local PEAR::SOAP'; - $localServer['version']=SOAP_LIBRARY_VERSION; - switch ($testname) { - case 'Round 2 Base': - $localServer['endpointURL']=$localBaseUrl.'server_Round2Base.php'; - $localServer['wsdlURL']=$localBaseUrl.'wsdl/interop.wsdl.php'; - return new serverInfo($localServer); - case 'Round 2 Group B': - $localServer['endpointURL']=$localBaseUrl.'server_Round2GroupB.php'; - $localServer['wsdlURL']=$localBaseUrl.'wsdl/interopB.wsdl.php'; - return new serverInfo($localServer); - case 'Round 2 Group C': - $localServer['endpointURL']=$localBaseUrl.'server_Round2GroupC.php'; - $localServer['wsdlURL']=$localBaseUrl.'wsdl/echoheadersvc.wsdl.php'; - return new serverInfo($localServer); - case 'Round 3 Group D EmptySA': - $localServer['endpointURL']=$localBaseUrl.'server_Round3GroupDEmptySA.php'; - $localServer['wsdlURL']=$localBaseUrl.'wsdl/emptysa.wsdl.php'; - return new serverInfo($localServer); - case 'Round 3 Group D Compound 1': - $localServer['endpointURL']=$localBaseUrl.'server_Round3GroupDCompound1.php'; - $localServer['wsdlURL']=$localBaseUrl.'wsdl/compound1.wsdl.php'; - return new serverInfo($localServer); - case 'Round 3 Group D Compound 2': - $localServer['endpointURL']=$localBaseUrl.'server_Round3GroupDCompound2.php'; - $localServer['wsdlURL']=$localBaseUrl.'wsdl/compound2.wsdl.php'; - return new serverInfo($localServer); - case 'Round 3 Group D DocLit': - $localServer['endpointURL']=$localBaseUrl.'server_Round3GroupDDocLit.php'; - $localServer['wsdlURL']=$localBaseUrl.'wsdl/InteropTestDocLit.wsdl.php'; - return new serverInfo($localServer); - case 'Round 3 Group D DocLitParams': - $localServer['endpointURL']=$localBaseUrl.'server_Round3GroupDDocLitParams.php'; - $localServer['wsdlURL']=$localBaseUrl.'wsdl/InteropTestDocLitParameters.wsdl.php'; - return new serverInfo($localServer); - case 'Round 3 Group D Import 1': - $localServer['endpointURL']=$localBaseUrl.'server_Round3GroupDImport1.php'; - $localServer['wsdlURL']=$localBaseUrl.'wsdl/import1.wsdl.php'; - return new serverInfo($localServer); - case 'Round 3 Group D Import 2': - $localServer['endpointURL']=$localBaseUrl.'server_Round3GroupDImport2.php'; - $localServer['wsdlURL']=$localBaseUrl.'wsdl/import2.wsdl.php'; - return new serverInfo($localServer); - case 'Round 3 Group D Import 3': - $localServer['endpointURL']=$localBaseUrl.'server_Round3GroupDImport3.php'; - $localServer['wsdlURL']=$localBaseUrl.'wsdl/import3.wsdl.php'; - return new serverInfo($localServer); - case 'Round 3 Group D RpcEnc': - $localServer['endpointURL']=$localBaseUrl.'server_Round3GroupDRpcEnc.php'; - $localServer['wsdlURL']=$localBaseUrl.'wsdl/InteropTestRpcEnc.wsdl.php'; - return new serverInfo($localServer); - #case 'Round 3 Group E DocLit': - #case 'Round 3 Group E RpcEnc': - #case 'Round 3 Group F Extensibility': - #case 'Round 3 Group F ExtensibilityRequired': - #case 'Round 3 Group F Headers': - #case 'Round 4 DIME/Doc Attachments': - #case 'Round 4 DIME/RPC Attachments': - #case 'Round 4 MIME/Doc Attachments': - #case 'Round 4 SwA/RPC Attachments': - } - return NULL; -} - -class SOAP_Interop_registrationAndNotificationService_ServicesPort extends SOAP_Client { - function SOAP_Interop_registrationAndNotificationService_ServicesPort() { - $this->SOAP_Client("http://soap.4s4c.com/registration/soap.asp", 0); - $this->_auto_translation = true; - } - function &ServiceList() { - return $this->call("ServiceList", - $v = NULL, - array('namespace'=>'http://soap.pocketsoap.com/registration/services', - 'soapaction'=>'http://soap.pocketsoap.com/registration/services#ServiceList', - 'style'=>'rpc', - 'use'=>'encoded')); - } - function &Servers($serviceID) { - return $this->call("Servers", - $v = array("serviceID"=>$serviceID), - array('namespace'=>'http://soap.pocketsoap.com/registration/services', - 'soapaction'=>'http://soap.pocketsoap.com/registration/services#Servers', - 'style'=>'rpc', - 'use'=>'encoded')); - } - function &Clients($serviceID) { - return $this->call("Clients", - $v = array("serviceID"=>$serviceID), - array('namespace'=>'http://soap.pocketsoap.com/registration/services', - 'soapaction'=>'http://soap.pocketsoap.com/registration/services#Clients', - 'style'=>'rpc', - 'use'=>'encoded')); - } -} -class SOAP_Interop_registrationAndNotificationService_ClientsPort extends SOAP_Client { - function SOAP_Interop_registrationAndNotificationService_ClientsPort() { - $this->SOAP_Client("http://soap.4s4c.com/registration/soap.asp", 0); - $this->_auto_translation = true; - } - function &RegisterClient($serviceID, $clientInfo) { - return $this->call("RegisterClient", - $v = array("serviceID"=>$serviceID, "clientInfo"=>$clientInfo), - array('namespace'=>'http://soap.pocketsoap.com/registration/clients', - 'soapaction'=>'http://soap.pocketsoap.com/registration/clients#RegisterClient', - 'style'=>'rpc', - 'use'=>'encoded')); - } - function &UpdateClient($clientID, $clientInfo) { - return $this->call("UpdateClient", - $v = array("clientID"=>$clientID, "clientInfo"=>$clientInfo), - array('namespace'=>'http://soap.pocketsoap.com/registration/clients', - 'soapaction'=>'http://soap.pocketsoap.com/registration/clients#UpdateClient', - 'style'=>'rpc', - 'use'=>'encoded')); - } - function &RemoveClient($clientID) { - return $this->call("RemoveClient", - $v = array("clientID"=>$clientID), - array('namespace'=>'http://soap.pocketsoap.com/registration/clients', - 'soapaction'=>'http://soap.pocketsoap.com/registration/clients#RemoveClient', - 'style'=>'rpc', - 'use'=>'encoded')); - } -} -class SOAP_Interop_registrationAndNotificationService_ServersPort extends SOAP_Client { - function SOAP_Interop_registrationAndNotificationService_ServersPort() { - $this->SOAP_Client("http://soap.4s4c.com/registration/soap.asp", 0); - $this->_auto_translation = true; - } - function &RegisterServer($serviceID, $serverInfo) { - return $this->call("RegisterServer", - $v = array("serviceID"=>$serviceID, "serverInfo"=>$serverInfo), - array('namespace'=>'http://soap.pocketsoap.com/registration/servers', - 'soapaction'=>'http://soap.pocketsoap.com/registration/servers#RegisterServer', - 'style'=>'rpc', - 'use'=>'encoded')); - } - function &UpdateServer($serverID, $serverInfo) { - return $this->call("UpdateServer", - $v = array("serverID"=>$serverID, "serverInfo"=>$serverInfo), - array('namespace'=>'http://soap.pocketsoap.com/registration/servers', - 'soapaction'=>'http://soap.pocketsoap.com/registration/servers#UpdateServer', - 'style'=>'rpc', - 'use'=>'encoded')); - } - function &RemoveServer($serverID) { - return $this->call("RemoveServer", - $v = array("serverID"=>$serverID), - array('namespace'=>'http://soap.pocketsoap.com/registration/servers', - 'soapaction'=>'http://soap.pocketsoap.com/registration/servers#RemoveServer', - 'style'=>'rpc', - 'use'=>'encoded')); - } -} -class SOAP_Interop_registrationAndNotificationService_SubscriberPort extends SOAP_Client { - function SOAP_Interop_registrationAndNotificationService_SubscriberPort() { - $this->SOAP_Client("http://soap.4s4c.com/registration/soap.asp", 0); - $this->_auto_translation = true; - } - function &Subscribe($serviceID, $ServerChanges, $ClientChanges, $NotificationURL) { - return $this->call("Subscribe", - $v = array("serviceID"=>$serviceID, "ServerChanges"=>$ServerChanges, "ClientChanges"=>$ClientChanges, "NotificationURL"=>$NotificationURL), - array('namespace'=>'http://soap.pocketsoap.com/registration/subscriber', - 'soapaction'=>'http://soap.pocketsoap.com/registration/subscriber#Subscribe', - 'style'=>'rpc', - 'use'=>'encoded')); - } - function &Renew($notificationID) { - return $this->call("Renew", - $v = array("notificationID"=>$notificationID), - array('namespace'=>'http://soap.pocketsoap.com/registration/subscriber', - 'soapaction'=>'http://soap.pocketsoap.com/registration/subscriber#Renew', - 'style'=>'rpc', - 'use'=>'encoded')); - } - function &Cancel($notificationID) { - return $this->call("Cancel", - $v = array("notificationID"=>$notificationID), - array('namespace'=>'http://soap.pocketsoap.com/registration/subscriber', - 'soapaction'=>'http://soap.pocketsoap.com/registration/subscriber#Cancel', - 'style'=>'rpc', - 'use'=>'encoded')); - } -} -class SOAP_Interop_registrationAndNotificationService_ChangeLogPort extends SOAP_Client { - function SOAP_Interop_registrationAndNotificationService_ChangeLogPort() { - $this->SOAP_Client("http://soap.4s4c.com/registration/soap.asp", 0); - $this->_auto_translation = true; - } - function &RecentChanges($MaxEntries) { - return $this->call("RecentChanges", - $v = array("MaxEntries"=>$MaxEntries), - array('namespace'=>'http://soap.pocketsoap.com/registration/changeLog', - 'soapaction'=>'http://soap.pocketsoap.com/registration/changeLog#RecentChanges', - 'style'=>'rpc', - 'use'=>'encoded')); - } -} - -class SOAP_Interop_registrationDB { - var $DSN; - var $dbc = NULL; - - var $client; // soap_client - var $services; - var $currentServiceId; - var $servers; - var $clients; - - function SOAP_Interop_registrationDB() - { - global $interopConfig; - $this->DSN = $interopConfig['DSN']; - $this->client =& new SOAP_Interop_registrationAndNotificationService_ServicesPort(); - $this->connectDB(); - $this->getServiceList(); - } - - function connectDB() - { - if (!$this->dbc) - $this->dbc =& DB::connect($this->DSN, true); - if (PEAR::isError($this->dbc)) { - echo $this->dbc->getMessage(); - $this->dbc = NULL; - return false; - } - return true; - } - - function updateDB() - { - $this->updateServiceDb(); - $this->updateServerDb(); - $this->updateClientsDb(); - } - - function &retreiveServiceList() - { - if (!$this->services) { - $this->services =& $this->client->ServiceList(); - } - return $this->services; - } - - function &retreiveServerList($serviceID) - { - if (!$this->servers || $this->currentServiceId != $serviceID) { - $this->currentServiceId = $serviceID; - $this->servers =& $this->client->Servers($serviceID); - } - return $this->servers; - } - - function &retreiveClientList($serviceID) - { - if (!$this->clients || $this->currentServiceId != $serviceID) { - $this->currentServiceId = $serviceID; - $this->clients =& $this->client->Clients($serviceID); - } - return $this->clients; - } - - function updateServiceDb() - { - if (!$this->connectDB()) return false; - $this->retreiveServiceList(); - echo "Updating Services\n"; - foreach ($this->services as $service) { - $res = $this->dbc->getRow("select id from services where id='{$service->id}'"); - if ($res && !PEAR::isError($res)) { - $res = $this->dbc->query("update services set name='{$service->name}',". - "description='{$service->description}',wsdlURL='{$service->wsdlURL}',". - "websiteURL='{$service->websiteURL}' where id='{$service->id}'"); - } else { - $res = $this->dbc->query("insert into services (id,name,description,wsdlURL,websiteURL) ". - "values('{$service->id}','{$service->name}','{$service->description}','{$service->wsdlURL}','{$service->websiteURL}')"); - } - } - } - - function _updateOrAddServer($id, $server) { - $res = $this->dbc->getRow("select * from serverinfo where service_id='$id' and name='{$server->name}'"); - if ($res && !PEAR::isError($res)) { - $res = $this->dbc->query("update serverinfo set ". - "version='{$server->version}', ". - "endpointURL='{$server->endpointURL}', ". - "wsdlURL='{$server->wsdlURL}' where id={$res->id}"); - } else { - $res = $this->dbc->query("insert into serverinfo (service_id,name,version,endpointURL,wsdlURL) ". - "values('$id','{$server->name}','{$server->version}','{$server->endpointURL}','{$server->wsdlURL}')"); - } - if (PEAR::isError($res)) { - echo $res->toString() . "\n"; - } - } - - function updateServerDb() - { - global $INTEROP_LOCAL_SERVER; - if (!$this->connectDB()) return false; - $this->retreiveServiceList(); - $c = count($this->services); - for ($i=0;$i<$c;$i++) { - $this->retreiveServerList($this->services[$i]->id); - echo "Updating Servers for {$this->services[$i]->name}\n"; - if (!$this->servers) continue; - foreach ($this->servers as $server) { - $this->_updateOrAddServer($this->services[$i]->id, $server); - } - // add the local server now - if ($INTEROP_LOCAL_SERVER) { - $server = getLocalInteropServer($this->services[$i]->name, $this->services[$i]->id); - if ($server) { - $this->_updateOrAddServer($this->services[$i]->id, $server); - } - } - } - } - - function updateClientsDb() - { - if (!$this->connectDB()) return false; - $this->retreiveServiceList(); - foreach ($this->services as $service) { - $this->retreiveClientList($service->id); - echo "Updating Clients for {$service->name}\n"; - if (!$this->clients) continue; - foreach ($this->clients as $client) { - $res = $this->dbc->getRow("select id from clientinfo where id='{$service->id}' and name='{$client->name}'"); - if ($res && !PEAR::isError($res)) { - $res = $this->dbc->query("update clientinfo set ". - "version='{$client->version}', ". - "resultsURL='{$client->resultsURL}' where ". - "id='{$service->id}',name='{$client->name}'"); - } else { - $res = $this->dbc->query("insert into clientinfo (id,name,version,resultsURL) ". - "values('{$service->id}','{$client->name}','{$client->version}','{$client->resultsURL}')"); - } - - } - } - } - - function &getServiceList($forcefetch=FALSE) - { - if (!$forcefetch && !$this->services) { - $this->dbc->setFetchMode(DB_FETCHMODE_OBJECT,'Service'); - $this->services = $this->dbc->getAll('select * from services',NULL, DB_FETCHMODE_OBJECT ); - } - if ($forcefetch || !$this->services) { - $this->updateServiceDb(); - } - return $this->services; - } - - function &getServerList($serviceID,$forcefetch=FALSE) - { - if (!$forcefetch && (!$this->servers || $this->currentServiceId != $serviceID)) { - $this->dbc->setFetchMode(DB_FETCHMODE_OBJECT,'serverInfo'); - $this->servers = $this->dbc->getAll("select * from serverinfo where service_id = '$serviceID'",NULL, DB_FETCHMODE_OBJECT ); - } - if ($forcefetch || !$this->servers) { - $this->updateServerDb(); - $this->dbc->setFetchMode(DB_FETCHMODE_OBJECT,'serverInfo'); - $this->servers = $this->dbc->getAll("select * from serverinfo where service_id = '$serviceID'",NULL, DB_FETCHMODE_OBJECT ); - if (!$this->servers) { - die("Error retrieving server list!\n"); - } - } - return $this->servers; - } - - function &getClientList($serviceID,$forcefetch=FALSE) - { - if (!$forcefetch && (!$this->clients || $this->currentServiceId != $serviceID)) { - $this->dbc->setFetchMode(DB_FETCHMODE_OBJECT,'clientInfo'); - $this->clients = $this->dbc->getAll("select * from clientinfo where id = '$serviceID'",NULL, DB_FETCHMODE_OBJECT ); - } - if ($forcefetch || !$this->clients) { - $this->updateClientDb(); - $this->dbc->setFetchMode(DB_FETCHMODE_OBJECT,'clientInfo'); - $this->clients = $this->dbc->getAll("select * from clientinfo where id = '$serviceID'",NULL, DB_FETCHMODE_OBJECT ); - if (!$this->clients) { - die("Error retrieving client list!\n"); - } - } - return $this->clients; - } - - function &findService($serviceName) - { - $this->getServiceList(); - $c = count($this->services); - for ($i=0 ; $i<$c; $i++) { - if (strcmp($serviceName, $this->services[$i]->name)==0) return $this->services[$i]; - } - return NULL; - } -} - -#$reg =& new SOAP_Interop_registrationAndNotificationDB(); -#$reg->updateDB(); -//print_r($l); -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/SOAP/Interop/server_Round2Base.php b/gulliver/thirdparty/pear/SOAP/Interop/server_Round2Base.php deleted file mode 100644 index 9a6f8ab6a..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/server_Round2Base.php +++ /dev/null @@ -1,51 +0,0 @@ - Port to PEAR and more | -// | Authors: Dietrich Ayala Original Author | -// +----------------------------------------------------------------------+ -// -// $Id: server_Round2Base.php,v 1.5 2003/08/05 16:56:43 arnaud Exp $ -// -require_once 'SOAP/Server.php'; -require_once 'interop_Round2Base.php'; - -$base =& new SOAP_Interop_Base(); -$server =& new SOAP_Server; -$server->_auto_translation = true; - -$server->addObjectMap($base,'http://soapinterop.org/'); -$server->service(isset($HTTP_RAW_POST_DATA)?$HTTP_RAW_POST_DATA:NULL); - -$test = ' - - - - - - -arg -34 -325.325 - -'; -#$server->service($test,'',TRUE); - -?> diff --git a/gulliver/thirdparty/pear/SOAP/Interop/server_Round2GroupB.php b/gulliver/thirdparty/pear/SOAP/Interop/server_Round2GroupB.php deleted file mode 100644 index 833c2e966..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/server_Round2GroupB.php +++ /dev/null @@ -1,55 +0,0 @@ - Port to PEAR and more | -// | Authors: Dietrich Ayala Original Author | -// +----------------------------------------------------------------------+ -// -// $Id: server_Round2GroupB.php,v 1.5 2003/08/05 16:56:43 arnaud Exp $ -// -require_once 'SOAP/Server.php'; -require_once 'interop_Round2GroupB.php'; - -$groupb =& new SOAP_Interop_GroupB(); -$server =& new SOAP_Server; -$server->_auto_translation = true; - -$server->addObjectMap($groupb,'http://soapinterop.org/'); -$server->service(isset($HTTP_RAW_POST_DATA)?$HTTP_RAW_POST_DATA:NULL); - -$test = ' - - - - - - -arg -34 -325.325 - -arg -34 -325.325 - -'; -#$server->service($test,'',TRUE); - -?> diff --git a/gulliver/thirdparty/pear/SOAP/Interop/server_Round2GroupC.php b/gulliver/thirdparty/pear/SOAP/Interop/server_Round2GroupC.php deleted file mode 100644 index d8a4cd9f5..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/server_Round2GroupC.php +++ /dev/null @@ -1,33 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: server_Round2GroupC.php,v 1.5 2003/08/05 16:56:43 arnaud Exp $ -// -require_once 'SOAP/Server.php'; -require_once 'interop_Round2Base.php'; -require_once 'interop_Round2GroupC.php'; - -$groupc_headers =& new SOAP_Interop_GroupC_Headers(); -$base =& new SOAP_Interop_Base(); -$server =& new SOAP_Server; -$server->_auto_translation = true; - -$server->addObjectMap($groupc_headers,'http://soapinterop.org/echoheader/'); -$server->addObjectMap($base,'http://soapinterop.org/'); -$server->service(isset($HTTP_RAW_POST_DATA)?$HTTP_RAW_POST_DATA:NULL); -?> diff --git a/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupD.php b/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupD.php deleted file mode 100644 index 08f3e46de..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupD.php +++ /dev/null @@ -1,49 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: server_Round3GroupD.php,v 1.4 2005/04/01 16:18:00 chagenbu Exp $ -// -require_once 'SOAP/Server.php'; -require_once 'interop_Round3GroupD.php'; - -// http://www.whitemesa.com/r3/interop3.html -// http://www.whitemesa.com/r3/plan.html - -$groupd = new SOAP_Interop_GroupD(); -$server = new SOAP_Server; -$server->_auto_translation = true; - -$server->addObjectMap($groupd, 'http://soapinterop/'); -$server->addObjectMap($groupd, 'http://soapinterop.org/xsd'); - -$server->service(isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : NULL); - -$test = ' - - - - -Test Document Here - -'; -#$server->service($test,'',TRUE); diff --git a/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDCompound1.php b/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDCompound1.php deleted file mode 100644 index 83227ce80..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDCompound1.php +++ /dev/null @@ -1,72 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: server_Round3GroupDCompound1.php,v 1.5 2007/01/22 14:53:22 yunosh Exp $ -// -require_once 'SOAP/Server.php'; -require_once 'params_classes.php'; - -// http://www.whitemesa.com/r3/interop3.html -// http://www.whitemesa.com/r3/plan.html - -class SOAP_Interop_GroupDCompound1 { - - function echoPerson($person) - { - return $person->__to_soap('result_Person'); - } - - function echoDocument($document) - { - $ns = '{http://soapinterop.org/xsd}'; - return new SOAP_Value($ns . 'result_Document', $ns . 'x_Document', $document); - } - -} - -// http://www.whitemesa.com/r3/interop3.html -// http://www.whitemesa.com/r3/plan.html - -$options = array('use' => 'literal', 'style' => 'document'); -$groupd = new SOAP_Interop_GroupDCompound1(); -$server = new SOAP_Server($options); -$server->_auto_translation = true; - -$server->addObjectMap($groupd, 'http://soapinterop/'); -$server->addObjectMap($groupd, 'http://soapinterop.org/xsd'); - -$server->bind('http://localhost/soap_interop/wsdl/compound1.wsdl.php'); -if (isset($_SERVER['SERVER_NAME'])) { - $server->service(isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : null); -} else { - // allows command line testing of specific request - $test = ' - - - - -Test Document Here - -'; - $server->service($test, '', true); -} diff --git a/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDCompound2.php b/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDCompound2.php deleted file mode 100644 index e14d2950b..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDCompound2.php +++ /dev/null @@ -1,70 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: server_Round3GroupDCompound2.php,v 1.5 2007/01/22 14:53:22 yunosh Exp $ -// -require_once 'SOAP/Server.php'; -require_once 'params_classes.php'; - -// http://www.whitemesa.com/r3/interop3.html -// http://www.whitemesa.com/r3/plan.html - -class SOAP_Interop_GroupDCompound2 { - - function echoEmployee(&$employee) - { - return $employee->__to_soap('result_Employee'); - } - -} - -// http://www.whitemesa.com/r3/interop3.html -// http://www.whitemesa.com/r3/plan.html - -$options = array('use' => 'literal', 'style' => 'document'); -$groupd = new SOAP_Interop_GroupDCompound2(); -$server = new SOAP_Server($options); -$server->_auto_translation = true; - -$server->addObjectMap($groupd, 'http://soapinterop.org/employee'); - -$server->bind('http://localhost/soap_interop/wsdl/compound2.wsdl.php'); -if (isset($_SERVER['SERVER_NAME'])) { - $server->service(isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : NULL); -} else { - $test = ' - - - - - - - Shane - true - 1000000 - 12345 - - '; - $server->service($test, '', true); -} diff --git a/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDDocLit.php b/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDDocLit.php deleted file mode 100644 index 91dc69213..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDDocLit.php +++ /dev/null @@ -1,98 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: server_Round3GroupDDocLit.php,v 1.6 2007/01/22 14:53:22 yunosh Exp $ -// -require_once 'SOAP/Server.php'; -require_once 'params_classes.php'; - -// http://www.whitemesa.com/r3/interop3.html -// http://www.whitemesa.com/r3/plan.html - -class SOAP_Interop_GroupDDocLit { - - // wsdlns:SoapInteropEmptySABinding - function echoString($inputString) - { - return new SOAP_Value('{http://soapinterop.org/xsd}echoStringReturn', 'string', $inputString); - } - - function echoStringArray($inputStringArray) - { - $ra = array(); - if ($inputStringArray) { - foreach ($inputStringArray as $s) { - $ra[] =& new SOAP_Value('item', 'string', $s); - } - } - return new SOAP_Value('{http://soapinterop.org/xsd}echoStringArrayReturn', null, $ra); - } - - function echoStruct($inputStruct) - { - $ns = '{http://soapinterop.org/xsd}'; - if (is_object($inputStruct) && - strtolower(get_class($inputStruct)) == 'soapstruct') { - return $inputStruct->__to_soap($ns.'echoStructReturn'); - } else { - if (is_object($inputStruct)) { - $inputStruct = get_object_vars($inputStruct); - } - $struct = new SOAPStruct($inputStruct['varString'], $inputStruct['varInt'], $inputStruct['varFloat']); - return $struct->__to_soap($ns.'echoStructReturn'); - } - } - -} - -// http://www.whitemesa.com/r3/interop3.html -// http://www.whitemesa.com/r3/plan.html - -$options = array('use'=>'literal', 'style'=>'document'); -$groupd = new SOAP_Interop_GroupDDocLit(); -$server = new SOAP_Server($options); -$server->_auto_translation = true; - -$server->addObjectMap($groupd, 'http://soapinterop.org/WSDLInteropTestDocLit'); -$server->addObjectMap($groupd, 'http://soapinterop.org/xsd'); - -$server->bind('http://localhost/soap_interop/wsdl/InteropTestDocLit.wsdl.php'); - -if (isset($_SERVER['SERVER_NAME'])) { - $server->service(isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : NULL); -} else { - // allows command line testing of specific request - $test = ' - - - - - -arg -34 -325.325 - -'; - $server->service($test, '', true); -} - diff --git a/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDDocLitParams.php b/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDDocLitParams.php deleted file mode 100644 index 48bb6c7a4..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDDocLitParams.php +++ /dev/null @@ -1,96 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: server_Round3GroupDDocLitParams.php,v 1.5 2007/01/22 14:53:22 yunosh Exp $ -// -require_once 'SOAP/Server.php'; -require_once 'params_classes.php'; - -// http://www.whitemesa.com/r3/interop3.html -// http://www.whitemesa.com/r3/plan.html - -class SOAP_Interop_GroupDDocLitParams { - - function echoString($inputString) - { - return new SOAP_Value('return', 'string', $inputString); - } - - function echoStringArray($inputStringArray) - { - $ra = array(); - if ($inputStringArray) { - foreach ($inputStringArray as $s) { - $ra[] =& new SOAP_Value('item', 'string', $s); - } - } - return new SOAP_Value('return', null, $ra); - } - - function echoStruct($inputStruct) - { - if (is_object($inputStruct) && - get_class($inputStruct) == 'soapstruct') { - return $inputStruct->__to_soap('return'); - } else { - if (is_object($inputStruct)) { - $inputStruct = get_object_vars($inputStruct); - } - $struct = new SOAPStruct($inputStruct['varString'], $inputStruct['varInt'], $inputStruct['varFloat']); - return $struct->__to_soap('return'); - } - } - - function echoVoid() - { - return null; - } - -} - -// http://www.whitemesa.com/r3/interop3.html -// http://www.whitemesa.com/r3/plan.html - -$options = array('use' => 'literal', 'style' => 'document'); -$groupd = new SOAP_Interop_GroupDDocLitParams(); -$server = new SOAP_Server($options); -$server->_auto_translation = true; - -$server->addObjectMap($groupd, 'http://soapinterop/'); -$server->addObjectMap($groupd, 'http://soapinterop.org/xsd'); - -$server->bind('http://localhost/soap_interop/wsdl/InteropTestDocLitParameters.wsdl.php'); -if (isset($_SERVER['SERVER_NAME'])) { - $server->service(isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : null); -} else { - // allows command line testing of specific request - $test = ' - - - - - - -'; - $server->service($test, '', true); -} diff --git a/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDEmptySA.php b/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDEmptySA.php deleted file mode 100644 index 31446b76e..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDEmptySA.php +++ /dev/null @@ -1,38 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: server_Round3GroupDEmptySA.php,v 1.4 2003/08/05 16:56:43 arnaud Exp $ -// -require_once 'SOAP/Server.php'; -require_once 'interop_Round3GroupD.php'; - -// http://www.whitemesa.com/r3/interop3.html -// http://www.whitemesa.com/r3/plan.html - -$options = array('use'=>'literal','style'=>'document'); -$groupd =& new SOAP_Interop_GroupD(); -$server =& new SOAP_Server($options); -$server->_auto_translation = true; - -$server->addObjectMap($groupd,'http://soapinterop/'); -$server->addObjectMap($groupd,'http://soapinterop.org/xsd'); - -$server->bind('http://localhost/soap_interop/wsdl/emptysa.wsdl.php'); -$server->service(isset($HTTP_RAW_POST_DATA)?$HTTP_RAW_POST_DATA:NULL); - -?> diff --git a/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDImport1.php b/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDImport1.php deleted file mode 100644 index afb8b8694..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDImport1.php +++ /dev/null @@ -1,64 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: server_Round3GroupDImport1.php,v 1.5 2007/01/22 14:53:22 yunosh Exp $ -// -require_once 'SOAP/Server.php'; -require_once 'params_classes.php'; - -// http://www.whitemesa.com/r3/interop3.html -// http://www.whitemesa.com/r3/plan.html - -class SOAP_Interop_GroupDImport1 { - - function echoString($inputString) - { - return new SOAP_Value('Result', 'string', $inputString); - } -} - -// http://www.whitemesa.com/r3/interop3.html -// http://www.whitemesa.com/r3/plan.html - -$groupd = new SOAP_Interop_GroupDImport1(); -$server = new SOAP_Server(); -$server->_auto_translation = true; - -$server->addObjectMap($groupd, 'http://soapinterop/echoString/'); - -$server->bind('http://localhost/soap_interop/wsdl/import1.wsdl.php'); -if (isset($_SERVER['SERVER_NAME'])) { - $server->service(isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : null); -} else { - // allows command line testing of specific request - $test = ' - - - - - -Hello World - -'; - $server->service($test, '', true); -} diff --git a/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDImport2.php b/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDImport2.php deleted file mode 100644 index 64fd0405f..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDImport2.php +++ /dev/null @@ -1,81 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: server_Round3GroupDImport2.php,v 1.6 2007/01/22 14:53:22 yunosh Exp $ -// -require_once 'SOAP/Server.php'; -require_once 'params_classes.php'; - -// http://www.whitemesa.com/r3/interop3.html -// http://www.whitemesa.com/r3/plan.html - -class SOAP_Interop_GroupDImport2 { - - function echoStruct($inputStruct) - { - if (is_object($inputStruct) && - strtolower(get_class($inputStruct)) == 'soapstruct') { - return $inputStruct->__to_soap('Result'); - } else { - if (is_object($inputStruct)) { - $inputStruct = get_object_vars($inputStruct); - } - $struct = new SOAPStruct($inputStruct['varString'], $inputStruct['varInt'], $inputStruct['varFloat']); - return $struct->__to_soap('Result'); - } - } - -} - -// http://www.whitemesa.com/r3/interop3.html -// http://www.whitemesa.com/r3/plan.html - -$groupd = new SOAP_Interop_GroupDImport2(); -$server = new SOAP_Server(); -$server->_auto_translation = true; - -$server->addObjectMap($groupd, 'http://soapinterop/'); -$server->addObjectMap($groupd, 'http://soapinterop.org/xsd'); - -if (isset($_SERVER['SERVER_NAME'])) { - $baseurl = 'http://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT'] . '/soap_interop/'; - $server->service(isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : null); -} else { - $baseurl = 'http://localhost/soap_interop/'; - $server->bind($baseurl.'wsdl/import2.wsdl.php'); - // allows command line testing of specific request - $test = ' - - - - - - -arg -34 -325.325 - -'; - $server->service($test, '', true); -} diff --git a/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDImport3.php b/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDImport3.php deleted file mode 100644 index 6a2d88903..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDImport3.php +++ /dev/null @@ -1,101 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: server_Round3GroupDImport3.php,v 1.6 2007/01/22 14:53:22 yunosh Exp $ -// -require_once 'SOAP/Server.php'; -require_once 'params_classes.php'; - -// http://www.whitemesa.com/r3/interop3.html -// http://www.whitemesa.com/r3/plan.html - -class SOAP_Interop_GroupDImport3 { - - function echoStruct($inputStruct) - { - $ns = '{http://soapinterop.org/xsd}'; - if (is_object($inputStruct) && - strtolower(get_class($inputStruct)) == 'soapstruct') { - return $inputStruct->__to_soap($ns . 'return'); - } else { - if (is_object($inputStruct)) { - $inputStruct = get_object_vars($inputStruct); - } - $struct = new SOAPStruct($inputStruct['varString'], $inputStruct['varInt'], $inputStruct['varFloat']); - return $struct->__to_soap($ns.'return'); - } - } - - function echoStructArray($inputStructArray) - { - $ra = array(); - if ($inputStructArray) { - $c = count($inputStructArray); - for ($i = 0; $i < $c; $i++) { - $ra[] = $inputStructArray[$i]->__to_soap('item'); - } - } - return $ra; - } - -} - -// http://www.whitemesa.com/r3/interop3.html -// http://www.whitemesa.com/r3/plan.html - -$groupd = new SOAP_Interop_GroupDImport3(); -$server = new SOAP_Server(); -$server->_auto_translation = true; - -$server->addObjectMap($groupd, 'http://soapinterop/'); -$server->addObjectMap($groupd, 'http://soapinterop.org/xsd'); - -$server->bind('http://localhost/soap_interop/wsdl/import3.wsdl.php'); -if (isset($_SERVER['SERVER_NAME'])) { - $server->service(isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : null); -} else { - // allows command line testing of specific request - $test = ' - - - - - - - -arg -34 -325.325 - -arg -34 -325.325 - -arg -34 -325.325 - -'; - $server->service($test, '', true); -} diff --git a/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDRpcEnc.php b/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDRpcEnc.php deleted file mode 100644 index cb67ae374..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/server_Round3GroupDRpcEnc.php +++ /dev/null @@ -1,79 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: server_Round3GroupDRpcEnc.php,v 1.6 2007/01/22 14:53:22 yunosh Exp $ -// -require_once 'SOAP/Server.php'; -require_once 'params_classes.php'; - -// http://www.whitemesa.com/r3/interop3.html -// http://www.whitemesa.com/r3/plan.html - -class SOAP_Interop_GroupDRpcEnc { - - // wsdlns:SoapInteropEmptySABinding - function echoString($inputString) - { - return new SOAP_Value('echoStringReturn', 'string', $inputString); - } - - function echoStringArray($inputStringArray) - { - $ra = array(); - if ($inputStringArray) { - foreach($inputStringArray as $s) { - $ra[] = new SOAP_Value('item', 'string', $s); - } - } - return new SOAP_Value('echoStringArrayReturn', null, $ra); - } - - function echoStruct($inputStruct) - { - if (is_object($inputStruct) && - strtolower(get_class($inputStruct)) == 'soapstruct') { - return $inputStruct->__to_soap('return'); - } else { - if (is_object($inputStruct)) { - $inputStruct = get_object_vars($inputStruct); - } - $struct = new SOAPStruct($inputStruct['varString'], $inputStruct['varInt'], $inputStruct['varFloat']); - return $struct->__to_soap('return'); - } - } - - function echoVoid() - { - return null; - } - -} - -// http://www.whitemesa.com/r3/interop3.html -// http://www.whitemesa.com/r3/plan.html - -$groupd = new SOAP_Interop_GroupDRpcEnc(); -$server = new SOAP_Server(); -$server->_auto_translation = true; - -$server->addObjectMap($groupd, 'http://soapinterop/'); -$server->addObjectMap($groupd, 'http://soapinterop.org/xsd'); -$server->addObjectMap($groupd, 'http://soapinterop.org/WSDLInteropTestRpcEnc'); - -$server->bind('http://localhost/soap_interop/wsdl/InteropTestRpcEnc.wsdl.php'); -$server->service(isset($HTTP_RAW_POST_DATA) ? $HTTP_RAW_POST_DATA : null); diff --git a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/InteropTestDocLit.wsdl.php b/gulliver/thirdparty/pear/SOAP/Interop/wsdl/InteropTestDocLit.wsdl.php deleted file mode 100644 index 1d4adad41..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/InteropTestDocLit.wsdl.php +++ /dev/null @@ -1,136 +0,0 @@ -\n"; ?> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /soap_interop/server_Round3GroupDDocLit.php"/> - - - diff --git a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/InteropTestDocLitParameters.wsdl.php b/gulliver/thirdparty/pear/SOAP/Interop/wsdl/InteropTestDocLitParameters.wsdl.php deleted file mode 100644 index 6c6da053f..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/InteropTestDocLitParameters.wsdl.php +++ /dev/null @@ -1,176 +0,0 @@ -\n"; ?> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /soap_interop/server_Round3GroupDDocLitParams.php"/> - - - diff --git a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/InteropTestExtensibility.wsdl.php b/gulliver/thirdparty/pear/SOAP/Interop/wsdl/InteropTestExtensibility.wsdl.php deleted file mode 100644 index b34fa689b..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/InteropTestExtensibility.wsdl.php +++ /dev/null @@ -1,74 +0,0 @@ -\n"; ?> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /soap_interop/server_round3.php"/> - - - - diff --git a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/InteropTestExtensibilityRequired.wsdl.php b/gulliver/thirdparty/pear/SOAP/Interop/wsdl/InteropTestExtensibilityRequired.wsdl.php deleted file mode 100644 index 001aa35a6..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/InteropTestExtensibilityRequired.wsdl.php +++ /dev/null @@ -1,75 +0,0 @@ -\n"; ?> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /soap_interop/server_round3.php"/> - - - - diff --git a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/InteropTestList.wsdl.php b/gulliver/thirdparty/pear/SOAP/Interop/wsdl/InteropTestList.wsdl.php deleted file mode 100644 index 6f172bb42..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/InteropTestList.wsdl.php +++ /dev/null @@ -1,62 +0,0 @@ -\n"; ?> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /soap_interop/server_round3.php"/> - - - diff --git a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/InteropTestRpcEnc.wsdl.php b/gulliver/thirdparty/pear/SOAP/Interop/wsdl/InteropTestRpcEnc.wsdl.php deleted file mode 100644 index 8357194f3..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/InteropTestRpcEnc.wsdl.php +++ /dev/null @@ -1,127 +0,0 @@ -\n"; ?> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /soap_interop/server_Round3GroupDRpcEnc.php"/> - - - diff --git a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/InteropTestheaders.wsdl.php b/gulliver/thirdparty/pear/SOAP/Interop/wsdl/InteropTestheaders.wsdl.php deleted file mode 100644 index 21cfeab52..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/InteropTestheaders.wsdl.php +++ /dev/null @@ -1,72 +0,0 @@ -\n"; ?> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /soap_interop/server_round3.php"/> - - - \ No newline at end of file diff --git a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/compound1.wsdl.php b/gulliver/thirdparty/pear/SOAP/Interop/wsdl/compound1.wsdl.php deleted file mode 100644 index 1a4dd73f0..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/compound1.wsdl.php +++ /dev/null @@ -1,86 +0,0 @@ -\n"; ?> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /soap_interop/server_Round3GroupDCompound1.php"/> - - - diff --git a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/compound2.wsdl.php b/gulliver/thirdparty/pear/SOAP/Interop/wsdl/compound2.wsdl.php deleted file mode 100644 index 7a3bbd9e7..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/compound2.wsdl.php +++ /dev/null @@ -1,67 +0,0 @@ -\n"; ?> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /soap_interop/server_Round3GroupDCompound2.php"/> - - - diff --git a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/echoheadersvc.wsdl.php b/gulliver/thirdparty/pear/SOAP/Interop/wsdl/echoheadersvc.wsdl.php deleted file mode 100644 index 67b7e676a..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/echoheadersvc.wsdl.php +++ /dev/null @@ -1,18 +0,0 @@ -\n"; ?> - - - - - - - - - - /soap_interop/server_Round2GroupC.php"/> - - - - - diff --git a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/emptysa.wsdl.php b/gulliver/thirdparty/pear/SOAP/Interop/wsdl/emptysa.wsdl.php deleted file mode 100644 index d51a6eef3..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/emptysa.wsdl.php +++ /dev/null @@ -1,39 +0,0 @@ -\n"; ?> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /soap_interop/server_Round3GroupDEmptySA.php"/> - - - diff --git a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/import1.wsdl.php b/gulliver/thirdparty/pear/SOAP/Interop/wsdl/import1.wsdl.php deleted file mode 100644 index f0ed6586a..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/import1.wsdl.php +++ /dev/null @@ -1,28 +0,0 @@ -\n"; ?> - - - - - - - - - - - - - - - - - - /soap_interop/server_Round3GroupDImport1.php"/> - - - diff --git a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/import2.wsdl.php b/gulliver/thirdparty/pear/SOAP/Interop/wsdl/import2.wsdl.php deleted file mode 100644 index 3875f10cf..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/import2.wsdl.php +++ /dev/null @@ -1,28 +0,0 @@ -\n"; ?> - - - - - - - - - - - - - - - - - - /soap_interop/server_Round3GroupDImport2.php"/> - - - diff --git a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/import3.wsdl.php b/gulliver/thirdparty/pear/SOAP/Interop/wsdl/import3.wsdl.php deleted file mode 100644 index 4396de741..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/import3.wsdl.php +++ /dev/null @@ -1,77 +0,0 @@ -\n"; ?> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - /soap_interop/server_Round3GroupDImport3.php"/> - - - diff --git a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/imported/import1B.wsdl b/gulliver/thirdparty/pear/SOAP/Interop/wsdl/imported/import1B.wsdl deleted file mode 100644 index 26ab6dbdd..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/imported/import1B.wsdl +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - diff --git a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/imported/import2B.wsdl b/gulliver/thirdparty/pear/SOAP/Interop/wsdl/imported/import2B.wsdl deleted file mode 100644 index 8a397bc0b..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/imported/import2B.wsdl +++ /dev/null @@ -1,22 +0,0 @@ - - - - - - - - - - - - - - - - - diff --git a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/imported/import2B.xsd b/gulliver/thirdparty/pear/SOAP/Interop/wsdl/imported/import2B.xsd deleted file mode 100644 index b35eded4f..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/imported/import2B.xsd +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - - - - - \ No newline at end of file diff --git a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/interop.wsdl.php b/gulliver/thirdparty/pear/SOAP/Interop/wsdl/interop.wsdl.php deleted file mode 100644 index 12a74b338..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/interop.wsdl.php +++ /dev/null @@ -1,19 +0,0 @@ -\n"; ?> - - - - - - - - - /soap_interop/server_Round2Base.php"/> - - - - diff --git a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/interopB.wsdl.php b/gulliver/thirdparty/pear/SOAP/Interop/wsdl/interopB.wsdl.php deleted file mode 100644 index 09c250c5a..000000000 --- a/gulliver/thirdparty/pear/SOAP/Interop/wsdl/interopB.wsdl.php +++ /dev/null @@ -1,15 +0,0 @@ -\n"; ?> - - - - - - - - /soap_interop/server_Round2GroupB.php"/> - - - - diff --git a/gulliver/thirdparty/pear/SOAP/Parser.php b/gulliver/thirdparty/pear/SOAP/Parser.php deleted file mode 100644 index 1627d1fb5..000000000 --- a/gulliver/thirdparty/pear/SOAP/Parser.php +++ /dev/null @@ -1,504 +0,0 @@ - Original Author - * @author Shane Caraveo Port to PEAR and more - * @author Chuck Hagenbuch Maintenance - * @author Jan Schneider Maintenance - * @copyright 2003-2005 The PHP Group - * @license http://www.php.net/license/2_02.txt PHP License 2.02 - * @link http://pear.php.net/package/SOAP - */ - -require_once 'SOAP/Base.php'; -require_once 'SOAP/Value.php'; - -/** - * SOAP Parser - * - * This class is used by SOAP::Message and SOAP::Server to parse soap - * packets. Originally based on SOAPx4 by Dietrich Ayala - * http://dietrich.ganx4.com/soapx4 - * - * @access public - * @package SOAP - * @author Shane Caraveo Conversion to PEAR and updates - * @author Dietrich Ayala Original Author - */ -class SOAP_Parser extends SOAP_Base -{ - var $status = ''; - var $position = 0; - var $depth = 0; - var $default_namespace = ''; - var $message = array(); - var $depth_array = array(); - var $parent = 0; - var $root_struct_name = array(); - var $header_struct_name = array(); - var $curent_root_struct_name = ''; - var $root_struct = array(); - var $header_struct = array(); - var $curent_root_struct = 0; - var $references = array(); - var $need_references = array(); - - /** - * Used to handle non-root elements before root body element. - * - * @var integer - */ - var $bodyDepth; - - /** - * Constructor. - * - * @param string $xml XML content. - * @param string $encoding Character set encoding, defaults to 'UTF-8'. - * @param array $attachments List of attachments. - */ - function SOAP_Parser($xml, $encoding = SOAP_DEFAULT_ENCODING, - $attachments = null) - { - parent::SOAP_Base('Parser'); - $this->_setSchemaVersion(SOAP_XML_SCHEMA_VERSION); - - $this->attachments = $attachments; - - // Check the XML tag for encoding. - if (preg_match('/<\?xml[^>]+encoding\s*?=\s*?(\'([^\']*)\'|"([^"]*)")[^>]*?[\?]>/', $xml, $m)) { - $encoding = strtoupper($m[2] ? $m[2] : $m[3]); - } - - // Determine where in the message we are (envelope, header, body, - // method). Check whether content has been read. - if (!empty($xml)) { - // Prepare the XML parser. - $parser = xml_parser_create($encoding); - xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); - xml_set_object($parser, $this); - xml_set_element_handler($parser, '_startElement', '_endElement'); - xml_set_character_data_handler($parser, '_characterData'); - - // Some lame SOAP implementations add nul bytes at the end of the - // SOAP stream, and expat chokes on that. - if ($xml[strlen($xml) - 1] == 0) { - $xml = trim($xml); - } - - // Parse the XML file. - if (!xml_parse($parser, $xml, true)) { - $err = sprintf('XML error on line %d col %d byte %d %s', - xml_get_current_line_number($parser), - xml_get_current_column_number($parser), - xml_get_current_byte_index($parser), - xml_error_string(xml_get_error_code($parser))); - $this->_raiseSoapFault($err, htmlspecialchars($xml)); - } - xml_parser_free($parser); - } - } - - /** - * Returns an array of responses. - * - * After parsing a SOAP message, use this to get the response. - * - * @return array - */ - function getResponse() - { - if (!empty($this->root_struct[0])) { - return $this->_buildResponse($this->root_struct[0]); - } else { - return $this->_raiseSoapFault('Cannot build response'); - } - } - - /** - * Returns an array of header responses. - * - * After parsing a SOAP message, use this to get the response. - * - * @return array - */ - function getHeaders() - { - if (!empty($this->header_struct[0])) { - return $this->_buildResponse($this->header_struct[0]); - } else { - // We don't fault if there are no headers; that can be handled by - // the application if necessary. - return null; - } - } - - /** - * Recurses to build a multi dimensional array. - * - * @see _buildResponse() - */ - function _domulti($d, &$ar, &$r, &$v, $ad = 0) - { - if ($d) { - $this->_domulti($d - 1, $ar, $r[$ar[$ad]], $v, $ad + 1); - } else { - $r = $v; - } - } - - /** - * Loops through the message, building response structures. - * - * @param integer $pos Position. - * - * @return SOAP_Value - */ - function _buildResponse($pos) - { - $response = null; - - if (isset($this->message[$pos]['children'])) { - $children = explode('|', $this->message[$pos]['children']); - foreach ($children as $c => $child_pos) { - if ($this->message[$child_pos]['type'] != null) { - $response[] = $this->_buildResponse($child_pos); - } - } - if (isset($this->message[$pos]['arraySize'])) { - $ardepth = count($this->message[$pos]['arraySize']); - if ($ardepth > 1) { - $ar = array_pad(array(), $ardepth, 0); - if (isset($this->message[$pos]['arrayOffset'])) { - for ($i = 0; $i < $ardepth; $i++) { - $ar[$i] += $this->message[$pos]['arrayOffset'][$i]; - } - } - $elc = count($response); - for ($i = 0; $i < $elc; $i++) { - // Recurse to build a multi dimensional array. - $this->_domulti($ardepth, $ar, $newresp, $response[$i]); - - // Increment our array pointers. - $ad = $ardepth - 1; - $ar[$ad]++; - while ($ad > 0 && - $ar[$ad] >= $this->message[$pos]['arraySize'][$ad]) { - $ar[$ad] = 0; - $ad--; - $ar[$ad]++; - } - } - $response = $newresp; - } elseif (isset($this->message[$pos]['arrayOffset']) && - $this->message[$pos]['arrayOffset'][0] > 0) { - // Check for padding. - $pad = $this->message[$pos]['arrayOffset'][0] + count($response) * -1; - $response = array_pad($response, $pad, null); - } - } - } - - // Build attributes. - $attrs = array(); - foreach ($this->message[$pos]['attrs'] as $atn => $atv) { - if (!strstr($atn, 'xmlns') && !strpos($atn, ':')) { - $attrs[$atn] = $atv; - } - } - - // Add current node's value. - if ($response) { - $nqn = new QName($this->message[$pos]['name'], - $this->message[$pos]['namespace']); - $tqn = new QName($this->message[$pos]['type'], - $this->message[$pos]['type_namespace']); - $response = new SOAP_Value($nqn->fqn(), - $tqn->fqn(), - $response, - $attrs); - if (isset($this->message[$pos]['arrayType'])) { - $response->arrayType = $this->message[$pos]['arrayType']; - } - } else { - $nqn = new QName($this->message[$pos]['name'], - $this->message[$pos]['namespace']); - $tqn = new QName($this->message[$pos]['type'], - $this->message[$pos]['type_namespace']); - // Check if value is an empty array - if ($tqn->name == 'Array') { - $response = new SOAP_Value($nqn->fqn(), $tqn->fqn(), - array(), $attrs); - } else { - $response = new SOAP_Value($nqn->fqn(), - $tqn->fqn(), - $this->message[$pos]['cdata'], - $attrs); - } - } - - // Handle header attribute that we need. - if (array_key_exists('actor', $this->message[$pos])) { - $response->actor = $this->message[$pos]['actor']; - } - if (array_key_exists('mustUnderstand', $this->message[$pos])) { - $response->mustunderstand = $this->message[$pos]['mustUnderstand']; - } - return $response; - } - - /** - * Start element handler used with the XML parser. - */ - function _startElement($parser, $name, $attrs) - { - // Position in a total number of elements, starting from 0. - // Update class level position. - $pos = $this->position++; - - // And set mine. - $this->message[$pos] = array( - 'type' => '', - 'type_namespace' => '', - 'cdata' => '', - 'pos' => $pos, - 'id' => ''); - - // Parent/child/depth determinations. - - // depth = How many levels removed from root? - // Set mine as current global depth and increment global depth value. - $this->message[$pos]['depth'] = $this->depth++; - - // Else add self as child to whoever the current parent is. - if ($pos != 0) { - if (isset($this->message[$this->parent]['children'])) { - $this->message[$this->parent]['children'] .= '|' . $pos; - } else { - $this->message[$this->parent]['children'] = $pos; - } - } - - // Set my parent. - $this->message[$pos]['parent'] = $this->parent; - - // Set self as current value for this depth. - $this->depth_array[$this->depth] = $pos; - // Set self as current parent. - $this->parent = $pos; - $qname = new QName($name); - // Set status. - if (strcasecmp('envelope', $qname->name) == 0) { - $this->status = 'envelope'; - } elseif (strcasecmp('header', $qname->name) == 0) { - $this->status = 'header'; - $this->header_struct_name[] = $this->curent_root_struct_name = $qname->name; - $this->header_struct[] = $this->curent_root_struct = $pos; - $this->message[$pos]['type'] = 'Struct'; - } elseif (strcasecmp('body', $qname->name) == 0) { - $this->status = 'body'; - $this->bodyDepth = $this->depth; - - // Set method - } elseif ($this->status == 'body') { - // Is this element allowed to be a root? - // TODO: this needs to be optimized, we loop through $attrs twice - // now. - $can_root = $this->depth == $this->bodyDepth + 1; - if ($can_root) { - foreach ($attrs as $key => $value) { - if (stristr($key, ':root') && !$value) { - $can_root = false; - } - } - } - - if ($can_root) { - $this->status = 'method'; - $this->root_struct_name[] = $this->curent_root_struct_name = $qname->name; - $this->root_struct[] = $this->curent_root_struct = $pos; - $this->message[$pos]['type'] = 'Struct'; - } - } - - // Set my status. - $this->message[$pos]['status'] = $this->status; - - // Set name. - $this->message[$pos]['name'] = htmlspecialchars($qname->name); - - // Set attributes. - $this->message[$pos]['attrs'] = $attrs; - - // Loop through attributes, logging ns and type declarations. - foreach ($attrs as $key => $value) { - // If ns declarations, add to class level array of valid - // namespaces. - $kqn = new QName($key); - if ($kqn->ns == 'xmlns') { - $prefix = $kqn->name; - - if (in_array($value, $this->_XMLSchema)) { - $this->_setSchemaVersion($value); - } - - $this->_namespaces[$value] = $prefix; - - // Set method namespace. - } elseif ($key == 'xmlns') { - $qname->ns = $this->_getNamespacePrefix($value); - $qname->namespace = $value; - } elseif ($kqn->name == 'actor') { - $this->message[$pos]['actor'] = $value; - } elseif ($kqn->name == 'mustUnderstand') { - $this->message[$pos]['mustUnderstand'] = $value; - - // If it's a type declaration, set type. - } elseif ($kqn->name == 'type') { - $vqn = new QName($value); - $this->message[$pos]['type'] = $vqn->name; - $this->message[$pos]['type_namespace'] = $this->_getNamespaceForPrefix($vqn->ns); - - // Should do something here with the namespace of specified - // type? - - } elseif ($kqn->name == 'arrayType') { - $vqn = new QName($value); - $this->message[$pos]['type'] = 'Array'; - if (isset($vqn->arraySize)) { - $this->message[$pos]['arraySize'] = $vqn->arraySize; - } - $this->message[$pos]['arrayType'] = $vqn->name; - - } elseif ($kqn->name == 'offset') { - $this->message[$pos]['arrayOffset'] = explode(',', substr($value, 1, strlen($value) - 2)); - - } elseif ($kqn->name == 'id') { - // Save id to reference array. - $this->references[$value] = $pos; - $this->message[$pos]['id'] = $value; - - } elseif ($kqn->name == 'href') { - if ($value[0] == '#') { - $ref = substr($value, 1); - if (isset($this->references[$ref])) { - // cdata, type, inval. - $ref_pos = $this->references[$ref]; - $this->message[$pos]['children'] = &$this->message[$ref_pos]['children']; - $this->message[$pos]['cdata'] = &$this->message[$ref_pos]['cdata']; - $this->message[$pos]['type'] = &$this->message[$ref_pos]['type']; - $this->message[$pos]['arraySize'] = &$this->message[$ref_pos]['arraySize']; - $this->message[$pos]['arrayType'] = &$this->message[$ref_pos]['arrayType']; - } else { - // Reverse reference, store in 'need reference'. - if (!isset($this->need_references[$ref])) { - $this->need_references[$ref] = array(); - } - $this->need_references[$ref][] = $pos; - } - } elseif (isset($this->attachments[$value])) { - $this->message[$pos]['cdata'] = $this->attachments[$value]; - } - } - } - // See if namespace is defined in tag. - if (isset($attrs['xmlns:' . $qname->ns])) { - $namespace = $attrs['xmlns:' . $qname->ns]; - } elseif ($qname->ns && !$qname->namespace) { - $namespace = $this->_getNamespaceForPrefix($qname->ns); - } else { - // Get namespace. - $namespace = $qname->namespace ? $qname->namespace : $this->default_namespace; - } - $this->message[$pos]['namespace'] = $namespace; - $this->default_namespace = $namespace; - } - - /** - * End element handler used with the XML parser. - */ - function _endElement($parser, $name) - { - // Position of current element is equal to the last value left in - // depth_array for my depth. - $pos = $this->depth_array[$this->depth]; - - // Bring depth down a notch. - $this->depth--; - $qname = new QName($name); - - // Get type if not explicitly declared in an xsi:type attribute. - // TODO: check on integrating WSDL validation here. - if ($this->message[$pos]['type'] == '') { - if (isset($this->message[$pos]['children'])) { - /* this is slow, need to look at some faster method - $children = explode('|', $this->message[$pos]['children']); - if (count($children) > 2 && - $this->message[$children[1]]['name'] == $this->message[$children[2]]['name']) { - $this->message[$pos]['type'] = 'Array'; - } else { - $this->message[$pos]['type'] = 'Struct'; - }*/ - $this->message[$pos]['type'] = 'Struct'; - } else { - $parent = $this->message[$pos]['parent']; - if ($this->message[$parent]['type'] == 'Array' && - isset($this->message[$parent]['arrayType'])) { - $this->message[$pos]['type'] = $this->message[$parent]['arrayType']; - } else { - $this->message[$pos]['type'] = 'string'; - } - } - } - - // If tag we are currently closing is the method wrapper. - if ($pos == $this->curent_root_struct) { - $this->status = 'body'; - } elseif ($qname->name == 'Body' || $qname->name == 'Header') { - $this->status = 'envelope'; - } - - // Set parent back to my parent. - $this->parent = $this->message[$pos]['parent']; - - // Handle any reverse references now. - $idref = $this->message[$pos]['id']; - - if ($idref != '' && isset($this->need_references[$idref])) { - foreach ($this->need_references[$idref] as $ref_pos) { - // XXX is this stuff there already? - $this->message[$ref_pos]['children'] = &$this->message[$pos]['children']; - $this->message[$ref_pos]['cdata'] = &$this->message[$pos]['cdata']; - $this->message[$ref_pos]['type'] = &$this->message[$pos]['type']; - $this->message[$ref_pos]['arraySize'] = &$this->message[$pos]['arraySize']; - $this->message[$ref_pos]['arrayType'] = &$this->message[$pos]['arrayType']; - } - } - } - - /** - * Element content handler used with the XML parser. - */ - function _characterData($parser, $data) - { - $pos = $this->depth_array[$this->depth]; - if (isset($this->message[$pos]['cdata'])) { - $this->message[$pos]['cdata'] .= $data; - } else { - $this->message[$pos]['cdata'] = $data; - } - } - -} diff --git a/gulliver/thirdparty/pear/SOAP/Server.php b/gulliver/thirdparty/pear/SOAP/Server.php deleted file mode 100644 index bfdc837ac..000000000 --- a/gulliver/thirdparty/pear/SOAP/Server.php +++ /dev/null @@ -1,816 +0,0 @@ - Original Author - * @author Shane Caraveo Port to PEAR and more - * @author Chuck Hagenbuch Maintenance - * @author Jan Schneider Maintenance - * @copyright 2003-2005 The PHP Group - * @license http://www.php.net/license/2_02.txt PHP License 2.02 - * @link http://pear.php.net/package/SOAP - */ - -require_once 'SOAP/Base.php'; -require_once 'SOAP/Fault.php'; -require_once 'SOAP/Parser.php'; -require_once 'SOAP/Value.php'; -require_once 'SOAP/WSDL.php'; - -/** - * SOAP Server Class - * - * Originaly based on SOAPx4 by Dietrich Ayala - * http://dietrich.ganx4.com/soapx4 - * - * @access public - * @package SOAP - * @author Shane Caraveo Conversion to PEAR and updates - * @author Dietrich Ayala Original Author - */ -class SOAP_Server extends SOAP_Base -{ - /** - * - * @var array - */ - var $dispatch_map = array(); // create empty dispatch map - var $dispatch_objects = array(); - var $soapobject = null; - var $call_methodname = null; - var $callHandler = null; - var $callValidation = true; - - /** - * A list of headers that are going to be sent back to the client. - * - * @var array - */ - var $headers = array(); - - /** - * - * @var string - */ - var $request = ''; - - /** - * - * @var string XML-Encoding - */ - var $xml_encoding = SOAP_DEFAULT_ENCODING; - var $response_encoding = 'UTF-8'; - - var $result = 'successful'; // for logging interop results to db - - var $endpoint = ''; // the uri to ME! - - var $service = ''; //soapaction header - var $method_namespace = null; - - /** - * Options. - * - * @var array - */ - var $_options = array('use' => 'encoded', - 'style' => 'rpc', - 'parameters' => 0, - 'http_status_success' => '200 OK', - 'http_status_fault' => '500 SOAP Fault'); - - function SOAP_Server($options = null) - { - ini_set('track_errors', 1); - parent::SOAP_Base('Server'); - - if (is_array($options)) { - if (isset($options['use'])) { - $this->_options['use'] = $options['use']; - } - if (isset($options['style'])) { - $this->_options['style'] = $options['style']; - } - if (isset($options['parameters'])) { - $this->_options['parameters'] = $options['parameters']; - } - } - // assume we encode with section 5 - $this->_section5 = true; - if ($this->_options['use'] == 'literal') { - $this->_section5 = false; - } - } - - /** - * Error handler for errors that happen in proxied methods. - * - * To always return a valid SOAP response even on errors that don't happen - * in this code, the errors are catched, transformed to a SOAP fault and - * immediately sent to the client. - * - * @see http://www.php.net/set_error_handler - */ - function _errorHandler($errno, $errmsg, $filename, $linenum) - { - /* The error handler should ignore '0' errors, eg. hidden by @ - see - * the set_error_handler manual page. (thanks to Alan Knowles). */ - if (!$errno || !error_reporting() || $errno == E_NOTICE || - (defined('E_STRICT') && $errno == constant('E_STRICT'))) { - return false; - } - - $this->fault = new SOAP_Fault($errmsg, 'Server', 'PHP', "Errno: $errno\nFilename: $filename\nLineno: $linenum\n"); - - $this->_sendResponse(); - exit; - } - - function _getContentEncoding($content_type) - { - /* Get the character encoding of the incoming request treat incoming - * data as UTF-8 if no encoding set. */ - $this->xml_encoding = 'UTF-8'; - if (strpos($content_type, '=')) { - $enc = strtoupper(str_replace('"', '', substr(strstr($content_type, '='), 1))); - if (!in_array($enc, $this->_encodings)) { - return false; - } - $this->xml_encoding = $enc; - } - - return true; - } - - - /** - * Parses the request and posts or returns the response. - * - * @param string $data The SOAP request data. - * @param string $endpoint The service endpoint. Determined automatically - * if left empty. - * @param boolean $test - * @param boolean $return Whether to return the SOAP response data - * instead of sending it to the client. - */ - function service($data, $endpoint = '', $test = false, $return = false) - { - $response = null; - $attachments = array(); - $useEncoding = 'DIME'; - - /* Figure out our endpoint. */ - $this->endpoint = $endpoint; - if (!$test && !$this->endpoint) { - /* We'll try to build our endpoint. */ - $this->endpoint = 'http://' . $_SERVER['SERVER_NAME']; - if ($_SERVER['SERVER_PORT']) { - $this->endpoint .= ':' . $_SERVER['SERVER_PORT']; - } - $this->endpoint .= $_SERVER['SCRIPT_NAME']; - } - - /* Get the character encoding of the incoming request treat incoming - * data as UTF-8 if no encoding set. */ - if (isset($_SERVER['CONTENT_TYPE'])) { - if (strcasecmp($_SERVER['CONTENT_TYPE'], 'application/dime') == 0) { - $this->_decodeDIMEMessage($data, $headers, $attachments); - $useEncoding = 'DIME'; - } elseif (stristr($_SERVER['CONTENT_TYPE'], 'multipart/related')) { - /* This is a mime message, let's decode it. */ - $data = 'Content-Type: ' . - stripslashes($_SERVER['CONTENT_TYPE']) . - "\r\n\r\n" . $data; - $this->_decodeMimeMessage($data, $headers, $attachments); - $useEncoding = 'Mime'; - } - if (!isset($headers['content-type'])) { - $headers['content-type'] = stripslashes($_SERVER['CONTENT_TYPE']); - } - if (!$this->fault && - !$this->_getContentEncoding($headers['content-type'])) { - $this->xml_encoding = SOAP_DEFAULT_ENCODING; - /* Found encoding we don't understand; return a fault. */ - $this->_raiseSoapFault('Unsupported encoding, use one of ISO-8859-1, US-ASCII, UTF-8', '', '', 'Server'); - } - } - - /* If this is not a POST with Content-Type text/xml, try to return a - * WSDL file. */ - if (!$this->fault && !$test && - ($_SERVER['REQUEST_METHOD'] != 'POST' || - strncmp($headers['content-type'], 'text/xml', 8) != 0)) { - /* This is not possibly a valid SOAP request, try to return a WSDL - * file. */ - $this->_raiseSoapFault('Invalid SOAP request, must be POST with content-type: text/xml, got: ' . (isset($headers['content-type']) ? $headers['content-type'] : 'Nothing!'), '', '', 'Server'); - } - - if (!$this->fault) { - /* $response is a SOAP_Msg object. */ - $soap_msg = $this->parseRequest($data, $attachments); - - /* Handle Mime or DIME encoding. */ - /* TODO: DIME decoding should move to the transport, do it here - * for now and for ease of getting it done. */ - if (count($this->_attachments)) { - if ($useEncoding == 'Mime') { - $soap_msg = $this->_makeMimeMessage($soap_msg); - } else { - // default is dime - $soap_msg = $this->_makeDIMEMessage($soap_msg); - $this->headers['Content-Type'] = 'application/dime'; - } - if (PEAR::isError($soap_msg)) { - return $this->_raiseSoapFault($soap_msg); - } - } - - if (is_array($soap_msg)) { - $response = $soap_msg['body']; - if (count($soap_msg['headers'])) { - $this->headers = $soap_msg['headers']; - } - } else { - $response = $soap_msg; - } - } - - if ($return) { - if ($this->fault) { - $response = $this->fault->message(); - } - return $response; - } - - $this->_sendResponse($response); - } - - /** - * Sends the final HTTP response to the client, including the HTTP header - * and the HTTP body. - * - * If an error happened, it returns a SOAP fault instead of the response - * body. - * - * @param string $response The response body. - */ - function _sendResponse($response = '') - { - /* Make distinction between the different SAPIs, running PHP as CGI or - * as a module. */ - if (stristr(php_sapi_name(), 'cgi') === 0) { - $hdrs_type = 'Status:'; - } else { - $hdrs_type = 'HTTP/1.1'; - } - - if ($this->fault) { - $hdrs = $hdrs_type . ' ' . $this->_options['http_status_fault'] . "\r\n"; - $response = $this->fault->message($this->response_encoding); - } else { - $hdrs = $hdrs_type . ' ' . $this->_options['http_status_success'] . "\r\n"; - } - header($hdrs); - - $this->headers['Server'] = SOAP_LIBRARY_NAME; - if (!isset($this->headers['Content-Type'])) { - $this->headers['Content-Type'] = 'text/xml; charset=' . - $this->response_encoding; - } - $this->headers['Content-Length'] = strlen($response); - - foreach ($this->headers as $k => $v) { - header("$k: $v"); - $hdrs .= "$k: $v\r\n"; - } - - $this->response = $hdrs . "\r\n" . $response; - print $response; - } - - function &callMethod($methodname, &$args) - { - if ($this->callHandler) { - $ret = @call_user_func_array($this->callHandler, array($methodname, $args)); - return $ret; - } - - set_error_handler(array($this, '_errorHandler')); - - if ($args) { - /* Call method with parameters. */ - if (isset($this->soapobject) && is_object($this->soapobject)) { - $ret = call_user_func_array(array(&$this->soapobject, $methodname), $args); - } else { - $ret = call_user_func_array($methodname, $args); - } - } else { - /* Call method withour parameters. */ - if (is_object($this->soapobject)) { - $ret = call_user_func(array(&$this->soapobject, $methodname)); - } else { - $ret = call_user_func($methodname); - } - } - - restore_error_handler(); - - return $ret; - } - - /** - * Creates SOAP_Value objects with return values from method. - * Uses method signature to determine type. - * - * @param mixed $method_response The result(s). - * @param array|string $type The type(s) of the return value(s). - * @param string $return_name The name of the return value. - * @param string $namespace The namespace of the return value. - * - * @return array List of SOAP_Value objects. - */ - function buildResult(&$method_response, &$return_type, - $return_name = 'return', $namespace = '') - { - if (is_a($method_response, 'SOAP_Value')) { - $return_val = array($method_response); - } else { - if (is_array($return_type) && is_array($method_response)) { - $i = 0; - - foreach ($return_type as $key => $type) { - if (is_numeric($key)) { - $key = 'item'; - } - if (is_a($method_response[$i], 'SOAP_Value')) { - $return_val[] =& $method_response[$i++]; - } else { - $qn = new QName($key, $namespace); - $return_val[] = new SOAP_Value($qn->fqn(), $type, $method_response[$i++]); - } - } - } else { - if (is_array($return_type)) { - $keys = array_keys($return_type); - if (!is_numeric($keys[0])) { - $return_name = $keys[0]; - } - $values = array_values($return_type); - $return_type = $values[0]; - } - $qn = new QName($return_name, $namespace); - $return_val = array(new SOAP_Value($qn->fqn(), $return_type, $method_response)); - } - } - return $return_val; - } - - function parseRequest($data = '', $attachments = null) - { - /* Parse response, get SOAP_Parser object. */ - $parser =& new SOAP_Parser($data, $this->xml_encoding, $attachments); - /* If fault occurred during message parsing. */ - if ($parser->fault) { - $this->fault = $parser->fault; - return null; - } - - /* Handle message headers. */ - $request_headers = $parser->getHeaders(); - $header_results = array(); - - if ($request_headers) { - if (!is_a($request_headers, 'SOAP_Value')) { - $this->_raiseSoapFault('Parser did not return SOAP_Value object: ' . $request_headers, '', '', 'Server'); - return null; - } - if ($request_headers->value) { - /* Handle headers now. */ - foreach ($request_headers->value as $header_val) { - $f_exists = $this->validateMethod($header_val->name, $header_val->namespace); - - /* TODO: this does not take into account message routing - * yet. */ - $myactor = !$header_val->actor || - $header_val->actor == 'http://schemas.xmlsoap.org/soap/actor/next' || - $header_val->actor == $this->endpoint; - - if (!$f_exists && $header_val->mustunderstand && $myactor) { - $this->_raiseSoapFault('I don\'t understand header ' . $header_val->name, '', '', 'MustUnderstand'); - return null; - } - - /* We only handle the header if it's for us. */ - $isok = $f_exists && $myactor; - - if ($isok) { - /* Call our header now! */ - $header_method = $header_val->name; - $header_data = array($this->_decode($header_val)); - /* If there are parameters to pass. */ - $hr =& $this->callMethod($header_method, $header_data); - if (PEAR::isError($hr)) { - $this->_raiseSoapFault($hr); - return null; - } - $results = $this->buildResult($hr, $this->return_type, $header_method, $header_val->namespace); - $header_results[] = $results[0]; - } - } - } - } - - /* Handle the method call. */ - /* Evaluate message, getting back a SOAP_Value object. */ - $this->call_methodname = $this->methodname = $parser->root_struct_name[0]; - - /* Figure out the method namespace. */ - $this->method_namespace = $parser->message[$parser->root_struct[0]]['namespace']; - - if ($this->_wsdl) { - $this->_setSchemaVersion($this->_wsdl->xsd); - $dataHandler = $this->_wsdl->getDataHandler($this->methodname, $this->method_namespace); - if ($dataHandler) - $this->call_methodname = $this->methodname = $dataHandler; - - $this->_portName = $this->_wsdl->getPortName($this->methodname); - if (PEAR::isError($this->_portName)) { - $this->_raiseSoapFault($this->_portName); - return null; - } - $opData = $this->_wsdl->getOperationData($this->_portName, $this->methodname); - if (PEAR::isError($opData)) { - $this->_raiseSoapFault($opData); - return null; - } - $this->_options['style'] = $opData['style']; - $this->_options['use'] = $opData['output']['use']; - $this->_options['parameters'] = $opData['parameters']; - } - - /* Does method exist? */ - if (!$this->methodname || - !$this->validateMethod($this->methodname, $this->method_namespace)) { - $this->_raiseSoapFault('method "' . $this->method_namespace . $this->methodname . '" not defined in service', '', '', 'Server'); - return null; - } - - if (!$request_val = $parser->getResponse()) { - return null; - } - if (!is_a($request_val, 'SOAP_Value')) { - $this->_raiseSoapFault('Parser did not return SOAP_Value object: ' . $request_val, '', '', 'Server'); - return null; - } - - /* Verify that SOAP_Value objects in request match the methods - * signature. */ - if (!$this->verifyMethod($request_val)) { - /* verifyMethod() creates the fault. */ - return null; - } - - /* Need to set special error detection inside the value class to - * differentiate between no params passed, and an error decoding. */ - $request_data = $this->__decodeRequest($request_val); - if (PEAR::isError($request_data)) { - $this->_raiseSoapFault($request_data); - return null; - } - $method_response =& $this->callMethod($this->call_methodname, $request_data); - if (PEAR::isError($method_response)) { - $this->_raiseSoapFault($method_response); - return null; - } - - if ($this->_options['parameters'] || - !$method_response || - $this->_options['style'] == 'rpc') { - /* Get the method result. */ - if (is_null($method_response)) { - $return_val = null; - } else { - $return_val = $this->buildResult($method_response, $this->return_type); - } - - $qn = new QName($this->methodname . 'Response', $this->method_namespace); - $methodValue = new SOAP_Value($qn->fqn(), 'Struct', $return_val); - } else { - $methodValue =& $method_response; - } - return $this->makeEnvelope($methodValue, $header_results, $this->response_encoding); - } - - function &__decodeRequest($request, $shift = false) - { - if (!$request) { - $decoded = null; - return $decoded; - } - - /* Check for valid response. */ - if (PEAR::isError($request)) { - $fault = &$this->_raiseSoapFault($request); - return $fault; - } else if (!is_a($request, 'SOAP_Value')) { - $fault = &$this->_raiseSoapFault('Invalid data in server::__decodeRequest'); - return $fault; - } - - /* Decode to native php datatype. */ - $requestArray = $this->_decode($request); - /* Fault? */ - if (PEAR::isError($requestArray)) { - $fault = &$this->_raiseSoapFault($requestArray); - return $fault; - } - if (is_object($requestArray) && - get_class($requestArray) == 'stdClass') { - $requestArray = get_object_vars($requestArray); - } elseif ($this->_options['style'] == 'document') { - $requestArray = array($requestArray); - } - if (is_array($requestArray)) { - if (isset($requestArray['faultcode']) || - isset($requestArray['SOAP-ENV:faultcode'])) { - $faultcode = $faultstring = $faultdetail = $faultactor = ''; - foreach ($requestArray as $k => $v) { - if (stristr($k, 'faultcode')) { - $faultcode = $v; - } - if (stristr($k, 'faultstring')) { - $faultstring = $v; - } - if (stristr($k, 'detail')) { - $faultdetail = $v; - } - if (stristr($k, 'faultactor')) { - $faultactor = $v; - } - } - $fault = &$this->_raiseSoapFault($faultstring, $faultdetail, $faultactor, $faultcode); - return $fault; - } - /* Return array of return values. */ - if ($shift && count($requestArray) == 1) { - $decoded = array_shift($requestArray); - return $decoded; - } - return $requestArray; - } - return $requestArray; - } - - function verifyMethod($request) - { - if (!$this->callValidation) { - return true; - } - - $params = $request->value; - - /* Get the dispatch map if one exists. */ - $map = null; - if (array_key_exists($this->methodname, $this->dispatch_map)) { - $map = $this->dispatch_map[$this->methodname]; - } elseif (isset($this->soapobject)) { - if (method_exists($this->soapobject, '__dispatch')) { - $map = $this->soapobject->__dispatch($this->methodname); - } elseif (method_exists($this->soapobject, $this->methodname)) { - /* No map, all public functions are SOAP functions. */ - return true; - } - } - if (!$map) { - $this->_raiseSoapFault('SOAP request specified an unhandled method "' . $this->methodname . '"', '', '', 'Client'); - return false; - } - - /* If we aliased the SOAP method name to a PHP function, change - * call_methodname so we do the right thing. */ - if (array_key_exists('alias', $map) && !empty($map['alias'])) { - $this->call_methodname = $map['alias']; - } - - /* If there are input parameters required. */ - if ($map['in']) { - $this->input_value = count($map['in']); - $this->return_type = false; - if (is_array($map['out'])) { - $this->return_type = count($map['out']) > 1 - ? $map['out'] - : array_shift($map['out']); - } - if (is_array($params)) { - /* Validate the number of parameters. */ - if (count($params) == count($map['in'])) { - /* Make array of param types. */ - foreach ($params as $param) { - $p[] = strtolower($param->type); - } - $sig_t = array_values($map['in']); - /* Validate each param's type. */ - for ($i = 0; $i < count($p); $i++) { - /* If SOAP types do not match, it's still fine if the - * mapped php types match this allows using plain PHP - * variables to work (i.e. stuff like Decimal would - * fail otherwise). We consider this only error if the - * types exist in our type maps, and they differ. */ - if (strcasecmp($sig_t[$i], $p[$i]) != 0 && - isset($this->_typemap[SOAP_XML_SCHEMA_VERSION][$sig_t[$i]]) && - strcasecmp($this->_typemap[SOAP_XML_SCHEMA_VERSION][$sig_t[$i]], $this->_typemap[SOAP_XML_SCHEMA_VERSION][$p[$i]]) != 0) { - - $param = $params[$i]; - $this->_raiseSoapFault("SOAP request contained mismatching parameters of name $param->name had type [{$p[$i]}], which did not match signature's type: [{$sig_t[$i]}], matched? " . (strcasecmp($sig_t[$i], $p[$i])), '', '', 'Client'); - return false; - } - } - return true; - } else { - /* Wrong number of params. */ - $this->_raiseSoapFault('SOAP request contained incorrect number of parameters. method "' . $this->methodname . '" required ' . count($map['in']) . ' and request provided ' . count($params), '', '', 'Client'); - return false; - } - } else { - /* No params. */ - $this->_raiseSoapFault('SOAP request contained incorrect number of parameters. method "' . $this->methodname . '" requires ' . count($map['in']) . ' parameters, and request provided none.', '', '', 'Client'); - return false; - } - } - - /* We'll try it anyway. */ - return true; - } - - function validateMethod($methodname, $namespace = null) - { - unset($this->soapobject); - - if (!$this->callValidation) { - return true; - } - - /* No SOAP access to private functions. */ - if ($methodname[0] == '_') { - return false; - } - - /* if it's in our function list, ok */ - if (array_key_exists($methodname, $this->dispatch_map) && - (!$namespace || - !array_key_exists('namespace', $this->dispatch_map[$methodname]) || - $namespace == $this->dispatch_map[$methodname]['namespace'])) { - if (array_key_exists('namespace', $this->dispatch_map[$methodname])) - $this->method_namespace = $this->dispatch_map[$methodname]['namespace']; - return true; - } - - /* if it's in an object, it's ok */ - if (isset($this->dispatch_objects[$namespace])) { - $c = count($this->dispatch_objects[$namespace]); - for ($i = 0; $i < $c; $i++) { - $obj =& $this->dispatch_objects[$namespace][$i]; - /* If we have a dispatch map, and the function is not in the - * dispatch map, then it is not callable! */ - if (method_exists($obj, '__dispatch')) { - if ($obj->__dispatch($methodname)) { - $this->method_namespace = $namespace; - $this->soapobject =& $obj; - return true; - } - } elseif (method_exists($obj, $methodname)) { - $this->method_namespace = $namespace; - $this->soapobject =& $obj; - return true; - } - } - } - - return false; - } - - function addObjectMap(&$obj, $namespace = null, $service_name = 'Default', - $service_desc = '') - { - if (!$namespace) { - if (isset($obj->namespace)) { - // XXX a bit of backwards compatibility - $namespace = $obj->namespace; - } else { - $this->_raiseSoapFault('No namespace provided for class!', '', '', 'Server'); - return false; - } - } - if (!isset($this->dispatch_objects[$namespace])) { - $this->dispatch_objects[$namespace] = array(); - } - $this->dispatch_objects[$namespace][] =& $obj; - - // Create internal WSDL structures for object - - // XXX Because some internal workings of PEAR::SOAP decide whether to - // do certain things by the presence or absence of _wsdl, we should - // only create a _wsdl structure if we know we can fill it; if - // __dispatch_map or __typedef for the object is missing, we should - // avoid creating it. Later, when we are using PHP 5 introspection, we - // will be able to make the data for all objects without any extra - // information from the developers, and this condition should be - // dropped. - - // XXX Known issue: if imported WSDL (bindWSDL) or another WSDL source - // is used to add _wsdl structure information, then addObjectWSDL is - // used, there is a high possibility of _wsdl data corruption; - // therefore you should avoid using __dispatch_map/__typedef - // definitions AND other WSDL data sources in the same service. We - // exclude classes that don't have __typedefs to allow external WSDL - // files to be used with classes with no internal type definitions - // (the types are defined in the WSDL file). When addObjectWSDL is - // refactored to not cause corruption, this restriction can be - // relaxed. - - // In summary, if you add an object with both a dispatch map and type - // definitions, then previous WSDL file operation and type definitions - // will be overwritten. - if (isset($obj->__dispatch_map) && isset($obj->__typedef)) { - $this->addObjectWSDL($obj, $namespace, $service_name, $service_desc); - } - - return true; - } - - /** - * Adds a method to the dispatch map. - */ - function addToMap($methodname, $in, $out, $namespace = null, $alias = null) - { - if (!$this->callHandler && !function_exists($methodname)) { - $this->_raiseSoapFault('Error mapping function', '', '', 'Server'); - return false; - } - - $this->dispatch_map[$methodname]['in'] = $in; - $this->dispatch_map[$methodname]['out'] = $out; - $this->dispatch_map[$methodname]['alias'] = $alias; - if ($namespace) { - $this->dispatch_map[$methodname]['namespace'] = $namespace; - } - - return true; - } - - function setCallHandler($callHandler, $validation = true) - { - $this->callHandler = $callHandler; - $this->callValidation = $validation; - } - - /** - * @deprecated use bindWSDL from now on - */ - function bind($wsdl_url) - { - $this->bindWSDL($wsdl_url); - } - - /** - * @param string a url to a WSDL resource - * @return void - */ - function bindWSDL($wsdl_url) - { - /* Instantiate WSDL class. */ - $this->_wsdl = new SOAP_WSDL($wsdl_url); - if ($this->_wsdl->fault) { - $this->_raiseSoapFault($this->_wsdl->fault); - } - } - - /** - * @return void - */ - function addObjectWSDL(&$wsdl_obj, $targetNamespace, $service_name, - $service_desc = '') - { - if (!isset($this->_wsdl)) { - $this->_wsdl = new SOAP_WSDL; - } - - $this->_wsdl->parseObject($wsdl_obj, $targetNamespace, $service_name, $service_desc); - - if ($this->_wsdl->fault) { - $this->_raiseSoapFault($this->_wsdl->fault); - } - } - -} diff --git a/gulliver/thirdparty/pear/SOAP/Server/Email.php b/gulliver/thirdparty/pear/SOAP/Server/Email.php deleted file mode 100644 index 8905f8928..000000000 --- a/gulliver/thirdparty/pear/SOAP/Server/Email.php +++ /dev/null @@ -1,198 +0,0 @@ - Port to PEAR and more - * @copyright 2003-2005 The PHP Group - * @license http://www.php.net/license/2_02.txt PHP License 2.02 - * @link http://pear.php.net/package/SOAP - */ - -require_once 'SOAP/Server.php'; -require_once 'SOAP/Client.php'; -require_once 'SOAP/Transport.php'; -require_once 'Mail/mimeDecode.php'; - -/** - * SOAP Server Class that implements an email SOAP server. - * http://www.pocketsoap.com/specs/smtpbinding/ - * - * This class overrides the default HTTP server, providing the ability to - * parse an email message and execute SOAP calls. This class DOES NOT pop the - * message; the message, complete with headers, must be passed in as a - * parameter to the service function call. - * - * @access public - * @package SOAP - * @author Shane Caraveo - */ -class SOAP_Server_Email extends SOAP_Server { - - var $headers = array(); - - function SOAP_Server_Email($send_response = true) - { - parent::SOAP_Server(); - $this->send_response = $send_response; - } - - /** - * Removes HTTP headers from response. - * - * TODO: use PEAR email classes - * - * @return boolean - * @access private - */ - function _parseEmail(&$data) - { - if (preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $data, $match)) { - - if (preg_match_all('/^(.*?):\s+(.*)$/m', $match[1], $matches)) { - $hc = count($matches[0]); - for ($i = 0; $i < $hc; $i++) { - $this->headers[strtolower($matches[1][$i])] = trim($matches[2][$i]); - } - } - - if (!stristr($this->headers['content-type'], 'text/xml')) { - $this->_raiseSoapFault('Invalid Content Type', '', '', 'Client'); - return false; - } - - if (strcasecmp($this->headers['content-transfer-encoding'], 'base64')==0) { - /* Unfold lines. */ - $enctext = preg_replace("/[\r|\n]/", '', $match[2]); - $data = base64_decode($enctext); - } else { - $data = $match[2]; - } - - /* If no content, return false. */ - return strlen($this->request) > 0; - } - - $this->_raiseSoapFault('Invalid Email Format', '', '', 'Client'); - - return false; - } - - function client(&$data) - { - $attachments = array(); - - /* If neither matches, we'll just try it anyway. */ - if (stristr($data, 'Content-Type: application/dime')) { - $this->_decodeDIMEMessage($data, $this->headers, $attachments); - } elseif (stristr($data, 'MIME-Version:')) { - /* This is a mime message, let's decode it. */ - $this->_decodeMimeMessage($data, $this->headers, $attachments); - } else { - /* The old fallback, but decodeMimeMessage handles things fine. */ - $this->_parseEmail($data); - } - - /* Get the character encoding of the incoming request treat incoming - * data as UTF-8 if no encoding set. */ - if (!$this->soapfault && - !$this->_getContentEncoding($this->headers['content-type'])) { - $this->xml_encoding = SOAP_DEFAULT_ENCODING; - /* An encoding we don't understand, return a fault. */ - $this->_raiseSoapFault('Unsupported encoding, use one of ISO-8859-1, US-ASCII, UTF-8', '', '', 'Server'); - } - - if ($this->soapfault) { - return $this->soapfault->getFault(); - } - - $client =& new SOAP_Client(null); - - return $client->parseResponse($data, $this->xml_encoding, $this->attachments); - } - - function service(&$data, $endpoint = '', $send_response = true, - $dump = false) - { - $this->endpoint = $endpoint; - $attachments = array(); - $headers = array(); - - /* If neither matches, we'll just try it anyway. */ - if (stristr($data, 'Content-Type: application/dime')) { - $this->_decodeDIMEMessage($data, $this->headers, $attachments); - $useEncoding = 'DIME'; - } elseif (stristr($data, 'MIME-Version:')) { - /* This is a mime message, let's decode it. */ - $this->_decodeMimeMessage($data, $this->headers, $attachments); - $useEncoding = 'Mime'; - } else { - /* The old fallback, but decodeMimeMessage handles things fine. */ - $this->_parseEmail($data); - } - - /* Get the character encoding of the incoming request treat incoming - * data as UTF-8 if no encoding set. */ - if (!$this->_getContentEncoding($this->headers['content-type'])) { - $this->xml_encoding = SOAP_DEFAULT_ENCODING; - /* An encoding we don't understand, return a fault. */ - $this->_raiseSoapFault('Unsupported encoding, use one of ISO-8859-1, US-ASCII, UTF-8', '', '', 'Server'); - $response = $this->getFaultMessage(); - } - - if ($this->soapfault) { - $response = $this->soapfault->message(); - } else { - $soap_msg = $this->parseRequest($data,$attachments); - - /* Handle Mime or DIME encoding. */ - /* TODO: DIME Encoding should move to the transport, do it here - * for now and for ease of getting it done. */ - if (count($this->_attachments)) { - if ($useEncoding == 'Mime') { - $soap_msg = $this->_makeMimeMessage($soap_msg); - } else { - /* Default is DIME. */ - $soap_msg = $this->_makeDIMEMessage($soap_msg); - $soap_msg['headers']['Content-Type'] = 'application/dime'; - } - if (PEAR::isError($soap_msg)) { - return $this->raiseSoapFault($soap_msg); - } - } - - if (is_array($soap_msg)) { - $response = $soap_msg['body']; - if (count($soap_msg['headers'])) { - $headers = $soap_msg['headers']; - } - } else { - $response = $soap_msg; - } - } - - if ($this->send_response) { - if ($dump) { - print $response; - } else { - $from = array_key_exists('reply-to', $this->headers) ? $this->headers['reply-to'] : $this->headers['from']; - - $soap_transport =& SOAP_Transport::getTransport('mailto:' . $from, $this->response_encoding); - $from = $this->endpoint ? $this->endpoint : $this->headers['to']; - $headers['In-Reply-To'] = $this->headers['message-id']; - $options = array('from' => $from, 'subject' => $this->headers['subject'], 'headers' => $headers); - $soap_transport->send($response, $options); - } - } - } -} diff --git a/gulliver/thirdparty/pear/SOAP/Server/Email_Gateway.php b/gulliver/thirdparty/pear/SOAP/Server/Email_Gateway.php deleted file mode 100644 index 81ddbf1ce..000000000 --- a/gulliver/thirdparty/pear/SOAP/Server/Email_Gateway.php +++ /dev/null @@ -1,138 +0,0 @@ - Port to PEAR and more - * @copyright 2003-2005 The PHP Group - * @license http://www.php.net/license/2_02.txt PHP License 2.02 - * @link http://pear.php.net/package/SOAP - */ - -require_once 'SOAP/Server/Email.php'; -require_once 'SOAP/Transport.php'; - -/** - * SOAP Server Class that implements an email SOAP server. - * http://www.pocketsoap.com/specs/smtpbinding/ - * - * This class overrides the default HTTP server, providing the ability to - * parse an email message and execute soap calls. This class DOES NOT pop the - * message; the message, complete with headers, must be passed in as a - * parameter to the service function call. - * - * This class calls a provided HTTP SOAP server, forwarding the email request, - * then sending the HTTP response out as an email. - * - * @access public - * @package SOAP - * @author Shane Caraveo - */ -class SOAP_Server_Email_Gateway extends SOAP_Server_Email { - - var $gateway = null; - var $dump = false; - - function SOAP_Server_Email_Gateway($gateway = '', $send_response = true, - $dump = false) - { - parent::SOAP_Server(); - $this->send_response = $send_response; - $this->gateway = $gateway; - $this->dump = $dump; - } - - function service(&$data, $gateway = '', $endpoint = '', - $send_response = true, $dump = false) - { - $this->endpoint = $endpoint; - $response = ''; - $useEncoding = 'Mime'; - $options = array(); - if (!$gateway) { - $gateway = $this->gateway; - } - - /* We have a full set of headers, need to find the first blank - * line. */ - $this->_parseEmail($data); - if ($this->fault) { - $response = $this->fault->message(); - } - if ($this->headers['content-type'] == 'application/dime') - $useEncoding = 'DIME'; - - /* Call the HTTP Server. */ - if (!$response) { - $soap_transport =& SOAP_Transport::getTransport($gateway, $this->xml_encoding); - if ($soap_transport->fault) { - $response = $soap_transport->fault->message(); - } - } - - /* Send the message. */ - if (!$response) { - $options['soapaction'] = $this->headers['soapaction']; - $options['headers']['Content-Type'] = $this->headers['content-type']; - - $response = $soap_transport->send($data, $options); - if (isset($this->headers['mime-version'])) - $options['headers']['MIME-Version'] = $this->headers['mime-version']; - - if ($soap_transport->fault) { - $response = $soap_transport->fault->message(); - } else { - foreach ($soap_transport->transport->attachments as $cid => $body) { - $this->attachments[] = array('body' => $body, 'cid' => $cid, 'encoding' => 'base64'); - } - if (count($this->_attachments)) { - if ($useEncoding == 'Mime') { - $soap_msg = $this->_makeMimeMessage($response); - $options['headers']['MIME-Version'] = '1.0'; - } else { - /* Default is DIME. */ - $soap_msg = $this->_makeDIMEMessage($response); - $options['headers']['Content-Type'] = 'application/dime'; - } - if (PEAR::isError($soap_msg)) { - return $this->_raiseSoapFault($soap_msg); - } - if (is_array($soap_msg)) { - $response = $soap_msg['body']; - if (count($soap_msg['headers'])) { - if (isset($options['headers'])) { - $options['headers'] = array_merge($options['headers'], $soap_msg['headers']); - } else { - $options['headers'] = $soap_msg['headers']; - } - } - } - } - } - } - - if ($this->send_response) { - if ($this->dump || $dump) { - print $response; - } else { - $from = array_key_exists('reply-to', $this->headers) ? $this->headers['reply-to'] : $this->headers['from']; - - $soap_transport =& SOAP_Transport::getTransport('mailto:' . $from, $this->response_encoding); - $from = $this->endpoint ? $this->endpoint : $this->headers['to']; - $headers = array('In-Reply-To' => $this->headers['message-id']); - $options = array('from' => $from, 'subject'=> $this->headers['subject'], 'headers' => $headers); - $soap_transport->send($response, $options); - } - } - } -} diff --git a/gulliver/thirdparty/pear/SOAP/Server/TCP.php b/gulliver/thirdparty/pear/SOAP/Server/TCP.php deleted file mode 100644 index 039a62722..000000000 --- a/gulliver/thirdparty/pear/SOAP/Server/TCP.php +++ /dev/null @@ -1,106 +0,0 @@ - Port to PEAR and more - * @copyright 2003-2005 The PHP Group - * @license http://www.php.net/license/2_02.txt PHP License 2.02 - * @link http://pear.php.net/package/SOAP - */ - -require_once 'SOAP/Server.php'; - -/** - * SOAP Server Class that implements a TCP SOAP Server. - * http://www.pocketsoap.com/specs/smtpbinding/ - * - * This class overrides the default HTTP server, providing the ability to - * accept socket connections and execute SOAP calls. - * - * TODO: - * use Net_Socket - * implement some security scheme - * implement support for attachments - * - * @access public - * @package SOAP - * @author Shane Caraveo - */ -class SOAP_Server_TCP extends SOAP_Server { - - var $headers = array(); - var $localaddr; - var $port; - var $listen; - var $reuse; - - function SOAP_Server_TCP($localaddr = '127.0.0.1', $port = 10000, - $listen = 5, $reuse = true) - { - parent::SOAP_Server(); - $this->localaddr = $localaddr; - $this->port = $port; - $this->listen = $listen; - $this->reuse = $reuse; - } - - function run() - { - if (($sock = socket_create(AF_INET, SOCK_STREAM, 0)) < 0) { - return $this->_raiseSoapFault('socket_create() failed. Reason: ' . socket_strerror($sock)); - } - if ($this->reuse && - !@socket_setopt($sock, SOL_SOCKET, SO_REUSEADDR, 1)) { - return $this->_raiseSoapFault('socket_setopt() failed. Reason: ' . socket_strerror(socket_last_error($sock))); - } - if (($ret = socket_bind($sock, $this->localaddr, $this->port)) < 0) { - return $this->_raiseSoapFault('socket_bind() failed. Reason: ' . socket_strerror($ret)); - } - if (($ret = socket_listen($sock, $this->listen)) < 0) { - return $this->_raiseSoapFault('socket_listen() failed. Reason: ' . socket_strerror($ret)); - } - - while (true) { - $data = null; - if (($msgsock = socket_accept($sock)) < 0) { - $this->_raiseSoapFault('socket_accept() failed. Reason: ' . socket_strerror($msgsock)); - break; - } - while ($buf = socket_read($msgsock, 8192)) { - if (!$buf = trim($buf)) { - continue; - } - $data .= $buf; - } - - if ($data) { - $response = $this->service($data); - /* Write to the socket. */ - if (!socket_write($msgsock, $response, strlen($response))) { - return $this->_raiseSoapFault('Error sending response data reason ' . socket_strerror()); - } - } - - socket_close ($msgsock); - } - - socket_close ($sock); - } - - function service(&$data) - { - /* TODO: we need to handle attachments somehow. */ - return $this->parseRequest($data, $attachments); - } -} diff --git a/gulliver/thirdparty/pear/SOAP/Transport.php b/gulliver/thirdparty/pear/SOAP/Transport.php deleted file mode 100644 index 016399334..000000000 --- a/gulliver/thirdparty/pear/SOAP/Transport.php +++ /dev/null @@ -1,151 +0,0 @@ - - * @author Shane Caraveo - * @author Jan Schneider - * @copyright 2003-2006 The PHP Group - * @license http://www.php.net/license/2_02.txt PHP License 2.02 - * @link http://pear.php.net/package/SOAP - */ - -require_once 'SOAP/Base.php'; - -/** - * SOAP Transport Layer - * - * This layer can use different protocols dependant on the endpoint url - * provided. - * - * No knowlege of the SOAP protocol is available at this level. - * No knowlege of the transport protocols is available at this level. - * - * @access public - * @package SOAP - * @author Shane Caraveo - * @author Jan Schneider - */ -class SOAP_Transport extends SOAP_Base -{ - /** - * Connection endpoint URL. - * - * @var string - */ - var $url = ''; - - /** - * Array containing urlparts. - * - * @see parse_url() - * - * @var mixed - */ - var $urlparts = null; - - /** - * Incoming payload. - * - * @var string - */ - var $incoming_payload = ''; - - /** - * Outgoing payload. - * - * @var string - */ - var $outgoing_payload = ''; - - /** - * Request encoding. - * - * @var string - */ - var $encoding = SOAP_DEFAULT_ENCODING; - - /** - * Response encoding. - * - * We assume UTF-8 if no encoding is set. - * - * @var string - */ - var $result_encoding = 'UTF-8'; - - /** - * Decoded attachments from the reponse. - * - * @var array - */ - var $attachments; - - /** - * Request User-Agent. - * - * @var string - */ - var $_userAgent = SOAP_LIBRARY_NAME; - - /** - * Sends and receives SOAP data. - * - * @access public - * @abstract - * - * @param string Outgoing SOAP data. - * @param array Options. - * - * @return string|SOAP_Fault - */ - function send($msg, $options = null) - { - return $this->_raiseSoapFault('SOAP_Transport::send() not implemented.'); - } - - function &getTransport($url, $encoding = SOAP_DEFAULT_ENCODING) - { - $urlparts = @parse_url($url); - - if (!$urlparts['scheme']) { - $fault = SOAP_Base_Object::_raiseSoapFault("Invalid transport URI: $url"); - return $fault; - } - - if (strcasecmp($urlparts['scheme'], 'mailto') == 0) { - $transport_type = 'SMTP'; - } elseif (strcasecmp($urlparts['scheme'], 'https') == 0) { - $transport_type = 'HTTP'; - } else { - /* Handle other transport types */ - $transport_type = strtoupper($urlparts['scheme']); - } - $transport_include = 'SOAP/Transport/' . basename($transport_type) . '.php'; - $res = @include_once($transport_include); - if (!$res) { - $fault = SOAP_Base_Object::_raiseSoapFault("No Transport for {$urlparts['scheme']}"); - return $fault; - } - $transport_class = "SOAP_Transport_$transport_type"; - if (!class_exists($transport_class)) { - $fault = SOAP_Base_Object::_raiseSoapFault("No Transport class $transport_class"); - return $fault; - } - $t = new $transport_class($url, $encoding); - - return $t; - } - -} diff --git a/gulliver/thirdparty/pear/SOAP/Transport/HTTP.php b/gulliver/thirdparty/pear/SOAP/Transport/HTTP.php deleted file mode 100644 index ec03f2418..000000000 --- a/gulliver/thirdparty/pear/SOAP/Transport/HTTP.php +++ /dev/null @@ -1,620 +0,0 @@ - - * @author Jan Schneider - * @copyright 2003-2006 The PHP Group - * @license http://www.php.net/license/2_02.txt PHP License 2.02 - * @link http://pear.php.net/package/SOAP - */ - -/** - * HTTP Transport class - * - * @package SOAP - * @category Web_Services - */ - -/** - * Needed Classes - */ -require_once 'SOAP/Transport.php'; - -/** - * HTTP Transport for SOAP - * - * @access public - * @package SOAP - * @author Shane Caraveo - * @author Jan Schneider - */ -class SOAP_Transport_HTTP extends SOAP_Transport -{ - /** - * Basic Auth string. - * - * @var array - */ - var $headers = array(); - - /** - * Cookies. - * - * @var array - */ - var $cookies; - - /** - * Connection timeout in seconds. 0 = none. - * - * @var integer - */ - var $timeout = 4; - - /** - * HTTP-Response Content-Type. - */ - var $result_content_type; - - var $result_headers = array(); - - var $result_cookies = array(); - - /** - * SOAP_Transport_HTTP Constructor - * - * @access public - * - * @param string $url HTTP url to SOAP endpoint. - * @param string $encoding Encoding to use. - */ - function SOAP_Transport_HTTP($url, $encoding = SOAP_DEFAULT_ENCODING) - { - parent::SOAP_Base('HTTP'); - $this->urlparts = @parse_url($url); - $this->url = $url; - $this->encoding = $encoding; - } - - /** - * Sends and receives SOAP data. - * - * @access public - * - * @param string Outgoing SOAP data. - * @param array Options. - * - * @return string|SOAP_Fault - */ - function send($msg, $options = array()) - { - $this->fault = null; - - if (!$this->_validateUrl()) { - return $this->fault; - } - - if (isset($options['timeout'])) { - $this->timeout = (int)$options['timeout']; - } - - if (strcasecmp($this->urlparts['scheme'], 'HTTP') == 0) { - return $this->_sendHTTP($msg, $options); - } elseif (strcasecmp($this->urlparts['scheme'], 'HTTPS') == 0) { - return $this->_sendHTTPS($msg, $options); - } - - return $this->_raiseSoapFault('Invalid url scheme ' . $this->url); - } - - /** - * Sets data for HTTP authentication, creates authorization header. - * - * @param string $username Username. - * @param string $password Response data, minus HTTP headers. - * - * @access public - */ - function setCredentials($username, $password) - { - $this->headers['Authorization'] = 'Basic ' . base64_encode($username . ':' . $password); - } - - /** - * Adds a cookie. - * - * @access public - * @param string $name Cookie name. - * @param mixed $value Cookie value. - */ - function addCookie($name, $value) - { - $this->cookies[$name] = $value; - } - - /** - * Generates the correct headers for the cookies. - * - * @access private - * - * @param array $options Cookie options. If 'nocookies' is set and true - * the cookies from the last response are added - * automatically. 'cookies' is name-value-hash with - * a list of cookies to add. - * - * @return string The cookie header value. - */ - function _generateCookieHeader($options) - { - $this->cookies = array(); - - if (empty($options['nocookies']) && - isset($this->result_cookies)) { - // Add the cookies we got from the last request. - foreach ($this->result_cookies as $cookie) { - if ($cookie['domain'] == $this->urlparts['host']) { - $this->cookies[$cookie['name']] = $cookie['value']; - } - } - } - - // Add cookies the user wants to set. - if (isset($options['cookies'])) { - foreach ($options['cookies'] as $cookie) { - if ($cookie['domain'] == $this->urlparts['host']) { - $this->cookies[$cookie['name']] = $cookie['value']; - } - } - } - - $cookies = ''; - foreach ($this->cookies as $name => $value) { - if (!empty($cookies)) { - $cookies .= '; '; - } - $cookies .= urlencode($name) . '=' . urlencode($value); - } - - return $cookies; - } - - /** - * Validate url data passed to constructor. - * - * @access private - * @return boolean - */ - function _validateUrl() - { - if (!is_array($this->urlparts) ) { - $this->_raiseSoapFault('Unable to parse URL ' . $this->url); - return false; - } - if (!isset($this->urlparts['host'])) { - $this->_raiseSoapFault('No host in URL ' . $this->url); - return false; - } - if (!isset($this->urlparts['port'])) { - if (strcasecmp($this->urlparts['scheme'], 'HTTP') == 0) { - $this->urlparts['port'] = 80; - } elseif (strcasecmp($this->urlparts['scheme'], 'HTTPS') == 0) { - $this->urlparts['port'] = 443; - } - - } - if (isset($this->urlparts['user'])) { - $this->setCredentials(urldecode($this->urlparts['user']), - urldecode($this->urlparts['pass'])); - } - if (!isset($this->urlparts['path']) || !$this->urlparts['path']) { - $this->urlparts['path'] = '/'; - } - - return true; - } - - /** - * Finds out what the encoding is. - * Sets the object property accordingly. - * - * @access private - * @param array $headers Headers. - */ - function _parseEncoding($headers) - { - $h = stristr($headers, 'Content-Type'); - preg_match_all('/^Content-Type:\s*(.*)$/im', $h, $ct, PREG_SET_ORDER); - $n = count($ct); - $ct = $ct[$n - 1]; - - // Strip the string of \r. - $this->result_content_type = str_replace("\r", '', $ct[1]); - - if (preg_match('/(.*?)(?:;\s?charset=)(.*)/i', - $this->result_content_type, - $m)) { - $this->result_content_type = $m[1]; - if (count($m) > 2) { - $enc = strtoupper(str_replace('"', '', $m[2])); - if (in_array($enc, $this->_encodings)) { - $this->result_encoding = $enc; - } - } - } - - // Deal with broken servers that don't set content type on faults. - if (!$this->result_content_type) { - $this->result_content_type = 'text/xml'; - } - } - - /** - * Parses the headers. - * - * @param array $headers The headers. - */ - function _parseHeaders($headers) - { - /* Largely borrowed from HTTP_Request. */ - $this->result_headers = array(); - $headers = explode("\r?\n", $headers); - foreach ($headers as $value) { - if (strpos($value,':') === false) { - $this->result_headers[0] = $value; - continue; - } - list($name, $value) = explode(':', $value); - $headername = strtolower($name); - $headervalue = trim($value); - $this->result_headers[$headername] = $headervalue; - - if ($headername == 'set-cookie') { - // Parse a SetCookie header to fill _cookies array. - $cookie = array('expires' => null, - 'domain' => $this->urlparts['host'], - 'path' => null, - 'secure' => false); - - if (!strpos($headervalue, ';')) { - // Only a name=value pair. - list($cookie['name'], $cookie['value']) = array_map('trim', explode('=', $headervalue)); - $cookie['name'] = urldecode($cookie['name']); - $cookie['value'] = urldecode($cookie['value']); - - } else { - // Some optional parameters are supplied. - $elements = explode(';', $headervalue); - list($cookie['name'], $cookie['value']) = array_map('trim', explode('=', $elements[0])); - $cookie['name'] = urldecode($cookie['name']); - $cookie['value'] = urldecode($cookie['value']); - - for ($i = 1; $i < count($elements);$i++) { - list($elName, $elValue) = array_map('trim', explode('=', $elements[$i])); - if ('secure' == $elName) { - $cookie['secure'] = true; - } elseif ('expires' == $elName) { - $cookie['expires'] = str_replace('"', '', $elValue); - } elseif ('path' == $elName OR 'domain' == $elName) { - $cookie[$elName] = urldecode($elValue); - } else { - $cookie[$elName] = $elValue; - } - } - } - $this->result_cookies[] = $cookie; - } - } - } - - /** - * Removes HTTP headers from response. - * - * @return boolean - * @access private - */ - function _parseResponse() - { - if (preg_match("/^(.*?)\r?\n\r?\n(.*)/s", - $this->incoming_payload, - $match)) { - $this->response = $match[2]; - // Find the response error, some servers response with 500 for - // SOAP faults. - $this->_parseHeaders($match[1]); - - list(, $code, $msg) = sscanf($this->result_headers[0], '%s %s %s'); - unset($this->result_headers[0]); - - switch($code) { - case 100: // Continue - $this->incoming_payload = $match[2]; - return $this->_parseResponse(); - case 400: - $this->_raiseSoapFault("HTTP Response $code Bad Request"); - return false; - break; - case 401: - $this->_raiseSoapFault("HTTP Response $code Authentication Failed"); - return false; - break; - case 403: - $this->_raiseSoapFault("HTTP Response $code Forbidden"); - return false; - break; - case 404: - $this->_raiseSoapFault("HTTP Response $code Not Found"); - return false; - break; - case 407: - $this->_raiseSoapFault("HTTP Response $code Proxy Authentication Required"); - return false; - break; - case 408: - $this->_raiseSoapFault("HTTP Response $code Request Timeout"); - return false; - break; - case 410: - $this->_raiseSoapFault("HTTP Response $code Gone"); - return false; - break; - default: - if ($code >= 400 && $code < 500) { - $this->_raiseSoapFault("HTTP Response $code Not Found, Server message: $msg"); - return false; - } - } - - $this->_parseEncoding($match[1]); - - if ($this->result_content_type == 'application/dime') { - // XXX quick hack insertion of DIME - if (PEAR::isError($this->_decodeDIMEMessage($this->response, $this->headers, $this->attachments))) { - // _decodeDIMEMessage already raised $this->fault - return false; - } - $this->result_content_type = $this->headers['content-type']; - } elseif (stristr($this->result_content_type, 'multipart/related')) { - $this->response = $this->incoming_payload; - if (PEAR::isError($this->_decodeMimeMessage($this->response, $this->headers, $this->attachments))) { - // _decodeMimeMessage already raised $this->fault - return false; - } - } elseif ($this->result_content_type != 'text/xml') { - $this->_raiseSoapFault($this->response); - return false; - } - // if no content, return false - return strlen($this->response) > 0; - } - $this->_raiseSoapFault('Invalid HTTP Response'); - return false; - } - - /** - * Creates an HTTP request, including headers, for the outgoing request. - * - * @access private - * - * @param string $msg Outgoing SOAP package. - * @param array $options Options. - * - * @return string Outgoing payload. - */ - function _getRequest($msg, $options) - { - $this->headers = array(); - - $action = isset($options['soapaction']) ? $options['soapaction'] : ''; - $fullpath = $this->urlparts['path']; - if (isset($this->urlparts['query'])) { - $fullpath .= '?' . $this->urlparts['query']; - } - if (isset($this->urlparts['fragment'])) { - $fullpath .= '#' . $this->urlparts['fragment']; - } - - if (isset($options['proxy_host'])) { - $fullpath = 'http://' . $this->urlparts['host'] . ':' . - $this->urlparts['port'] . $fullpath; - } - - if (isset($options['proxy_user'])) { - $this->headers['Proxy-Authorization'] = 'Basic ' . - base64_encode($options['proxy_user'] . ':' . - $options['proxy_pass']); - } - - if (isset($options['user'])) { - $this->setCredentials($options['user'], $options['pass']); - } - - $this->headers['User-Agent'] = $this->_userAgent; - $this->headers['Host'] = $this->urlparts['host']; - $this->headers['Content-Type'] = "text/xml; charset=$this->encoding"; - $this->headers['Content-Length'] = strlen($msg); - $this->headers['SOAPAction'] = '"' . $action . '"'; - $this->headers['Connection'] = 'close'; - - if (isset($options['headers'])) { - $this->headers = array_merge($this->headers, $options['headers']); - } - - $cookies = $this->_generateCookieHeader($options); - if ($cookies) { - $this->headers['Cookie'] = $cookies; - } - - $headers = ''; - foreach ($this->headers as $k => $v) { - $headers .= "$k: $v\r\n"; - } - $this->outgoing_payload = "POST $fullpath HTTP/1.0\r\n" . $headers . - "\r\n" . $msg; - - return $this->outgoing_payload; - } - - /** - * Sends the outgoing HTTP request and reads and parses the response. - * - * @access private - * - * @param string $msg Outgoing SOAP package. - * @param array $options Options. - * - * @return string Response data without HTTP headers. - */ - function _sendHTTP($msg, $options) - { - $this->incoming_payload = ''; - $this->_getRequest($msg, $options); - $host = $this->urlparts['host']; - $port = $this->urlparts['port']; - if (isset($options['proxy_host'])) { - $host = $options['proxy_host']; - $port = isset($options['proxy_port']) ? $options['proxy_port'] : 8080; - } - // Send. - if ($this->timeout > 0) { - $fp = @fsockopen($host, $port, $this->errno, $this->errmsg, $this->timeout); - } else { - $fp = @fsockopen($host, $port, $this->errno, $this->errmsg); - } - if (!$fp) { - return $this->_raiseSoapFault("Connect Error to $host:$port"); - } - if ($this->timeout > 0) { - // some builds of PHP do not support this, silence the warning - @socket_set_timeout($fp, $this->timeout); - } - if (!fputs($fp, $this->outgoing_payload, strlen($this->outgoing_payload))) { - return $this->_raiseSoapFault("Error POSTing Data to $host"); - } - - // get reponse - // XXX time consumer - do { - $data = fread($fp, 4096); - $_tmp_status = socket_get_status($fp); - if ($_tmp_status['timed_out']) { - return $this->_raiseSoapFault("Timed out read from $host"); - } else { - $this->incoming_payload .= $data; - } - } while (!$_tmp_status['eof']); - - fclose($fp); - - if (!$this->_parseResponse()) { - return $this->fault; - } - return $this->response; - } - - /** - * Sends the outgoing HTTPS request and reads and parses the response. - * - * @access private - * - * @param string $msg Outgoing SOAP package. - * @param array $options Options. - * - * @return string Response data without HTTP headers. - */ - function _sendHTTPS($msg, $options) - { - /* Check if the required curl extension is installed. */ - if (!extension_loaded('curl')) { - return $this->_raiseSoapFault('CURL Extension is required for HTTPS'); - } - - $ch = curl_init(); - - if (isset($options['proxy_host'])) { - $port = isset($options['proxy_port']) ? $options['proxy_port'] : 8080; - curl_setopt($ch, CURLOPT_PROXY, - $options['proxy_host'] . ':' . $port); - } - if (isset($options['proxy_user'])) { - curl_setopt($ch, CURLOPT_PROXYUSERPWD, - $options['proxy_user'] . ':' . $options['proxy_pass']); - } - - if (isset($options['user'])) { - curl_setopt($ch, CURLOPT_USERPWD, - $options['user'] . ':' . $options['pass']); - } - - if (!isset($options['soapaction'])) { - $options['soapaction'] = ''; - } - if (!isset($options['headers']['Content-Type'])) { - $options['headers']['Content-Type'] = 'text/xml'; - } - curl_setopt($ch, CURLOPT_HTTPHEADER, - array('Content-Type: ' . $options['headers']['Content-Type'] - . ';charset=' . $this->encoding, - 'SOAPAction: "' . $options['soapaction'] . '"')); - curl_setopt($ch, CURLOPT_USERAGENT, - $this->_userAgent); - - if ($this->timeout) { - curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout); - } - - curl_setopt($ch, CURLOPT_POSTFIELDS, $msg); - curl_setopt($ch, CURLOPT_URL, $this->url); - curl_setopt($ch, CURLOPT_POST, 1); - curl_setopt($ch, CURLOPT_FAILONERROR, 0); - curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($ch, CURLOPT_HEADER, 1); - if (defined('CURLOPT_HTTP_VERSION')) { - curl_setopt($ch, CURLOPT_HTTP_VERSION, 1); - } - if (!ini_get('safe_mode') && !ini_get('open_basedir')) { - curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); - } - $cookies = $this->_generateCookieHeader($options); - if ($cookies) { - curl_setopt($ch, CURLOPT_COOKIE, $cookies); - } - - if (isset($options['curl'])) { - foreach ($options['curl'] as $key => $val) { - curl_setopt($ch, $key, $val); - } - } - - // Save the outgoing XML. This doesn't quite match _sendHTTP as CURL - // generates the headers, but having the XML is usually the most - // important part for tracing/debugging. - $this->outgoing_payload = $msg; - - $this->incoming_payload = curl_exec($ch); - if (!$this->incoming_payload) { - $m = 'curl_exec error ' . curl_errno($ch) . ' ' . curl_error($ch); - curl_close($ch); - return $this->_raiseSoapFault($m); - } - curl_close($ch); - - if (!$this->_parseResponse()) { - return $this->fault; - } - - return $this->response; - } - -} diff --git a/gulliver/thirdparty/pear/SOAP/Transport/SMTP.php b/gulliver/thirdparty/pear/SOAP/Transport/SMTP.php deleted file mode 100644 index 4619012cd..000000000 --- a/gulliver/thirdparty/pear/SOAP/Transport/SMTP.php +++ /dev/null @@ -1,220 +0,0 @@ - - * @author Jan Schneider - * @copyright 2003-2006 The PHP Group - * @license http://www.php.net/license/2_02.txt PHP License 2.02 - * @link http://pear.php.net/package/SOAP - */ - -require_once 'SOAP/Transport.php'; -require_once 'Mail/smtp.php'; - -/** - * SMTP Transport for SOAP - * - * Implements SOAP-SMTP as defined at - * http://www.pocketsoap.com/specs/smtpbinding/ - * - * @todo use PEAR smtp and Mime classes - * - * @access public - * @package SOAP - * @author Shane Caraveo - * @author Jan Schneider - */ -class SOAP_Transport_SMTP extends SOAP_Transport -{ - var $credentials = ''; - var $timeout = 4; // connect timeout - var $host = '127.0.0.1'; - var $port = 25; - var $auth = null; - - /** - * SOAP_Transport_SMTP Constructor - * - * @param string $url mailto: address. - * - * @access public - */ - function SOAP_Transport_SMTP($url, $encoding = 'US-ASCII') - { - parent::SOAP_Base('SMTP'); - $this->encoding = $encoding; - $this->urlparts = @parse_url($url); - $this->url = $url; - } - - /** - * Sends and receives SOAP data. - * - * @access public - * - * @param string Outgoing SOAP data. - * @param array Options. - * - * @return string|SOAP_Fault - */ - function send($msg, $options = array()) - { - $this->fault = null; - $this->incoming_payload = ''; - $this->outgoing_payload = $msg; - if (!$this->_validateUrl()) { - return $this->fault; - } - if (!$options || !isset($options['from'])) { - return $this->_raiseSoapFault('No From: address to send message with'); - } - - if (isset($options['host'])) $this->host = $options['host']; - if (isset($options['port'])) $this->port = $options['port']; - if (isset($options['auth'])) $this->auth = $options['auth']; - if (isset($options['username'])) $this->username = $options['username']; - if (isset($options['password'])) $this->password = $options['password']; - - $headers = array(); - $headers['From'] = $options['from']; - $headers['X-Mailer'] = $this->_userAgent; - $headers['MIME-Version'] = '1.0'; - $headers['Message-ID'] = $this->encryptOld(time()) . '.soap@' . $this->host; - $headers['To'] = $this->urlparts['path']; - if (isset($options['soapaction'])) { - $headers['Soapaction'] = "\"{$options['soapaction']}\""; - } - - if (isset($options['headers'])) - $headers = array_merge($headers, $options['headers']); - - // If the content type is already set, we assume that MIME encoding is - // already done. - if (isset($headers['Content-Type'])) { - $out = $msg; - } else { - // Do a simple inline MIME encoding. - $headers['Content-Disposition'] = 'inline'; - $headers['Content-Type'] = "text/xml; charset=\"$this->encoding\""; - if (isset($options['transfer-encoding'])) { - if (strcasecmp($options['transfer-encoding'], 'quoted-printable') == 0) { - $headers['Content-Transfer-Encoding'] = $options['transfer-encoding']; - $out = $msg; - } elseif (strcasecmp($options['transfer-encoding'],'base64') == 0) { - $headers['Content-Transfer-Encoding'] = 'base64'; - $out = chunk_split(base64_encode($msg), 76, "\n"); - } else { - return $this->_raiseSoapFault("Invalid Transfer Encoding: {$options['transfer-encoding']}"); - } - } else { - // Default to base64. - $headers['Content-Transfer-Encoding'] = 'base64'; - $out = chunk_split(base64_encode($msg)); - } - } - - $headers['Subject'] = isset($options['subject']) ? $options['subject'] : 'SOAP Message'; - - foreach ($headers as $key => $value) { - $header_text .= "$key: $value\n"; - } - $this->outgoing_payload = $header_text . "\r\n" . $this->outgoing_payload; - - $mailer_params = array( - 'host' => $this->host, - 'port' => $this->port, - 'username' => $this->username, - 'password' => $this->password, - 'auth' => $this->auth - ); - $mailer = new Mail_smtp($mailer_params); - $result = $mailer->send($this->urlparts['path'], $headers, $out); - if (!PEAR::isError($result)) { - $val = new SOAP_Value('Message-ID', 'string', $headers['Message-ID']); - } else { - $sval[] = new SOAP_Value('faultcode', 'QName', 'SOAP-ENV:Client'); - $sval[] = new SOAP_Value('faultstring', 'string', "couldn't send SMTP message to {$this->urlparts['path']}"); - $val = new SOAP_Value('Fault', 'Struct', $sval); - } - - $methodValue = new SOAP_Value('Response', 'Struct', array($val)); - - $this->incoming_payload = $this->makeEnvelope($methodValue, - $this->headers, - $this->encoding); - - return $this->incoming_payload; - } - - /** - * Sets data for HTTP authentication, creates Authorization header. - * - * @param string $username Username. - * @param string $password Response data, minus HTTP headers. - * - * @access public - */ - function setCredentials($username, $password) - { - $this->username = $username; - $this->password = $password; - } - - /** - * Validates url data passed to constructor. - * - * @return boolean - * @access private - */ - function _validateUrl() - { - if (!is_array($this->urlparts)) { - $this->_raiseSoapFault("Unable to parse URL $this->url"); - return false; - } - if (!isset($this->urlparts['scheme']) || - strcasecmp($this->urlparts['scheme'], 'mailto') != 0) { - $this->_raiseSoapFault("Unable to parse URL $this->url"); - return false; - } - if (!isset($this->urlparts['path'])) { - $this->_raiseSoapFault("Unable to parse URL $this->url"); - return false; - } - return true; - } - - 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); - } - -} diff --git a/gulliver/thirdparty/pear/SOAP/Transport/TCP.php b/gulliver/thirdparty/pear/SOAP/Transport/TCP.php deleted file mode 100644 index cc386c7b8..000000000 --- a/gulliver/thirdparty/pear/SOAP/Transport/TCP.php +++ /dev/null @@ -1,153 +0,0 @@ - - * @author Jan Schneider - * @copyright 2003-2006 The PHP Group - * @license http://www.php.net/license/2_02.txt PHP License 2.02 - * @link http://pear.php.net/package/SOAP - */ - -require_once 'SOAP/Transport.php'; - -/** - * TCP transport for SOAP. - * - * @todo use Net_Socket; implement some security scheme; implement support - * for attachments - * @access public - * @package SOAP - * @author Shane Hanna - * @author Jan Schneider - */ -class SOAP_Transport_TCP extends SOAP_Transport -{ - /** - * Socket. - */ - var $socket = null; - - /** - * Constructor. - * - * @param string $url HTTP url to SOAP endpoint. - * - * @access public - */ - function SOAP_Transport_TCP($url, $encoding = SOAP_DEFAULT_ENCODING) - { - parent::SOAP_Base_Object('TCP'); - $this->urlparts = @parse_url($url); - $this->url = $url; - $this->encoding = $encoding; - } - - function _socket_ping() - { - // XXX how do we restart after socket_shutdown? - //if (!$this->socket) { - // Create socket resource. - $this->socket = @socket_create(AF_INET, SOCK_STREAM, SOL_TCP); - if ($this->socket < 0) { - return 0; - } - - // Connect. - $result = socket_connect($this->socket, $this->urlparts['host'], - $this->urlparts['port']); - if ($result < 0) { - return 0; - } - //} - return 1; - } - - /** - * Sends and receives SOAP data. - * - * @access public - * - * @param string Outgoing SOAP data. - * @param array Options. - * - * @return string|SOAP_Fault - */ - function send($msg, $options = array()) - { - $this->fault = null; - $this->incoming_payload = ''; - $this->outgoing_payload = $msg; - if (!$this->_validateUrl()) { - return $this->fault; - } - - // Check for TCP scheme. - if (strcasecmp($this->urlparts['scheme'], 'TCP') == 0) { - // Check connection. - if (!$this->_socket_ping()) { - return $this->_raiseSoapFault('Error connecting to ' . $this->url . '; reason: ' . socket_strerror(socket_last_error($this->socket))); - } - - // Write to the socket. - if (!@socket_write($this->socket, $this->outgoing_payload, - strlen($this->outgoing_payload))) { - return $this->_raiseSoapFault('Error sending data to ' . $this->url . '; reason: ' . socket_strerror(socket_last_error($this->socket))); - } - - // Shutdown writing. - if(!socket_shutdown($this->socket, 1)) { - return $this->_raiseSoapFault('Cannot change socket mode to read.'); - } - - // Read everything we can. - while ($buf = @socket_read($this->socket, 1024, PHP_BINARY_READ)) { - $this->incoming_payload .= $buf; - } - - // Return payload or die. - if ($this->incoming_payload) { - return $this->incoming_payload; - } - - return $this->_raiseSoapFault('Error reveiving data from ' . $this->url); - } - - return $this->_raiseSoapFault('Invalid url scheme ' . $this->url); - } - - /** - * Validates the url data passed to the constructor. - * - * @return boolean - * @access private - */ - function _validateUrl() - { - if (!is_array($this->urlparts) ) { - $this->_raiseSoapFault("Unable to parse URL $this->url"); - return false; - } - if (!isset($this->urlparts['host'])) { - $this->_raiseSoapFault("No host in URL $this->url"); - return false; - } - if (!isset($this->urlparts['path']) || !$this->urlparts['path']) { - $this->urlparts['path'] = '/'; - } - - return true; - } - -} diff --git a/gulliver/thirdparty/pear/SOAP/Type/dateTime.php b/gulliver/thirdparty/pear/SOAP/Type/dateTime.php deleted file mode 100644 index b969da722..000000000 --- a/gulliver/thirdparty/pear/SOAP/Type/dateTime.php +++ /dev/null @@ -1,243 +0,0 @@ - Original Author - * @author Shane Caraveo Port to PEAR and more - * @author Jan Schneider Maintenance - * @copyright 2003-2005 The PHP Group - * @license http://www.php.net/license/2_02.txt PHP License 2.02 - * @link http://pear.php.net/package/SOAP - */ - -/** - * This class converts from and to unix timestamps and ISO 8601 date/time. - * - * @access public - * @package SOAP - * @author Dietrich Ayala Original Author - * @author Shane Caraveo Port to PEAR and more - * @author Jan Schneider Maintenance - */ -class SOAP_Type_dateTime -{ - var $_iso8601 = - '# 1: centuries & years CCYY- - (-?[0-9]{4})- - # 2: months MM- - ([0-9]{2})- - # 3: days DD - ([0-9]{2}) - # 4: separator T - T - # 5: hours hh: - ([0-9]{2}): - # 6: minutes mm: - ([0-9]{2}): - # 7: seconds ss.ss... - ([0-9]{2})(\.[0-9]*)? - # 8: Z to indicate UTC, -+HH:MM:SS.SS... for local zones - (Z|[+\-][0-9]{4}|[+\-][0-9]{2}:[0-9]{2})?'; - - var $timestamp = -1; - - /** - * Constructor. - * - * @param string|integer $date The timestamp or ISO 8601 formatted - * date and time this object is going to - * represent. - */ - function SOAP_Type_dateTime($date = -1) - { - if ($date == -1) { - $this->timestamp = time(); - } elseif (is_int($date)) { - $this->timestamp = $date; - } else { - $this->timestamp = $this->toUnixtime($date); - } - } - - /** - * Alias of {@link SOAP_Type_dateTime::toUTC}. - */ - function toSOAP($date = NULL) - { - return $this->toUTC($date); - } - - /** - * Converts this object or a timestamp to an ISO 8601 date/time string. - * - * @param integer $timestamp A unix timestamp - * - * @return string An ISO 8601 formatted date/time string. - */ - function toString($timestamp = 0) - { - if (!$timestamp) { - $timestamp = $this->timestamp; - } - if ($timestamp < 0) { - return 0; - } - - //simulate PHP5's P parameter - $zone = date('O', $timestamp); - if (strlen($zone) == 5) { - $zone = substr($zone, 0, 3) . ':' . substr($zone, 3); - } - return date('Y-m-d\TH:i:s', $timestamp) . $zone; - } - - /** - * Splits a date/time into its components. - * - * @param string|integer $datestr A unix timestamp or ISO 8601 date/time - * string. If empty, this object is used. - * - * @return boolean|array An array with the date and time components or - * false on failure. - */ - function _split($datestr) - { - if (!$datestr) { - $datestr = $this->toString(); - } elseif (is_int($datestr)) { - $datestr = $this->toString($datestr); - } - - if (preg_match('/' . $this->_iso8601 . '/x', $datestr, $regs)) { - if (empty($regs[8])) { - $timestamp = strtotime(sprintf('%04d-%02d-%02d %02d:%02d:%02d', - $regs[1], - $regs[2], - $regs[3], - $regs[4], - $regs[5], - $regs[6])); - $regs[8] = date('O', $timestamp); - } - if ($regs[8] != 'Z') { - $op = substr($regs[8], 0, 1); - $h = substr($regs[8], 1, 2); - if (strstr($regs[8], ':')) { - $m = substr($regs[8], 4, 2); - } else { - $m = substr($regs[8], 3, 2); - } - if ($op == '+') { - $regs[4] = $regs[4] - $h; - if ($regs[4] < 0) { - $regs[4] += 24; - } - $regs[5] = $regs[5] - $m; - if ($regs[5] < 0) { - $regs[5] += 60; - } - } else { - $regs[4] = $regs[4] + $h; - if ($regs[4] > 23) { - $regs[4] -= 24; - } - $regs[5] = $regs[5] + $m; - if ($regs[5] > 59) { - $regs[5] -= 60; - } - } - } - return $regs; - } - - return false; - } - - /** - * Returns an ISO 8601 formatted UTC date/time string. - * - * @param string|integer $datestr @see SOAP_Type_dateTime::_split - * - * @return string The ISO 8601 formatted UTC date/time string. - */ - function toUTC($datestr = null) - { - $regs = $this->_split($datestr); - - if ($regs) { - return sprintf('%04d-%02d-%02dT%02d:%02d:%02dZ', - $regs[1], - $regs[2], - $regs[3], - $regs[4], - $regs[5], - $regs[6]); - } - - return ''; - } - - /** - * Returns a unix timestamp. - * - * @param string|integer $datestr @see SOAP_Type_dateTime::_split - * - * @return integer The unix timestamp. - */ - function toUnixtime($datestr = null) - { - $regs = $this->_split($datestr); - if ($regs) { - return strtotime(sprintf('%04d-%02d-%02d %02d:%02d:%02dZ', - $regs[1], - $regs[2], - $regs[3], - $regs[4], - $regs[5], - $regs[6])); - } - return -1; - } - - /** - * Compares two dates or this object with a second date. - * - * @param string|integer $date1 A unix timestamp or ISO 8601 date/time - * string. - * @param string|integer $date2 A unix timestamp or ISO 8601 date/time - * string. If empty, this object is used. - * - * @return integer The difference between the first and the second date. - */ - function compare($date1, $date2 = null) - { - if (is_null($date2)) { - $date2 = $date1; - $date1 = $this->timestamp; - } - if (!is_int($date1)) { - $date1 = $this->toUnixtime($date1); - } - if (!is_int($date2)) { - $date2 = $this->toUnixtime($date2); - } - - if ($date1 != -1 && $date2 != -1) { - return $date1 - $date2; - } - - return -1; - } - -} diff --git a/gulliver/thirdparty/pear/SOAP/Type/duration.php b/gulliver/thirdparty/pear/SOAP/Type/duration.php deleted file mode 100644 index 078e4a4fe..000000000 --- a/gulliver/thirdparty/pear/SOAP/Type/duration.php +++ /dev/null @@ -1,165 +0,0 @@ - \ No newline at end of file diff --git a/gulliver/thirdparty/pear/SOAP/Type/hexBinary.php b/gulliver/thirdparty/pear/SOAP/Type/hexBinary.php deleted file mode 100644 index e6bbdf43d..000000000 --- a/gulliver/thirdparty/pear/SOAP/Type/hexBinary.php +++ /dev/null @@ -1,45 +0,0 @@ - Original Author - * @author Shane Caraveo Port to PEAR and more - * @copyright 2003-2007 The PHP Group - * @license http://www.php.net/license/2_02.txt PHP License 2.02 - * @link http://pear.php.net/package/SOAP - */ -class SOAP_Type_hexBinary { - - function to_bin($value) - { - return pack('H' . strlen($value), $value); - } - - function to_hex($value) - { - return bin2hex($value); - } - - function is_hexbin($value) - { - // First see if there are any invalid chars. - if (!strlen($value) || preg_match('/[^A-Fa-f0-9]/', $value)) { - return false; - } - - return strcasecmp($value, SOAP_Type_hexBinary::to_hex(SOAP_Type_hexBinary::to_bin($value))) == 0; - } - -} diff --git a/gulliver/thirdparty/pear/SOAP/Value.php b/gulliver/thirdparty/pear/SOAP/Value.php deleted file mode 100644 index aafb53b7c..000000000 --- a/gulliver/thirdparty/pear/SOAP/Value.php +++ /dev/null @@ -1,252 +0,0 @@ - Original Author - * @author Shane Caraveo Port to PEAR and more - * @author Chuck Hagenbuch Maintenance - * @author Jan Schneider Maintenance - * @copyright 2003-2007 The PHP Group - * @license http://www.php.net/license/2_02.txt PHP License 2.02 - * @link http://pear.php.net/package/SOAP - */ - -require_once 'SOAP/Base.php'; - -/** - * SOAP::Value - * - * This class converts values between PHP and SOAP. - * - * Originally based on SOAPx4 by Dietrich Ayala - * http://dietrich.ganx4.com/soapx4 - * - * @access public - * @package SOAP - * @author Shane Caraveo Conversion to PEAR and updates - * @author Dietrich Ayala Original Author - */ -class SOAP_Value -{ - /** - * @var string - */ - var $value = null; - - /** - * @var string - */ - var $name = ''; - - /** - * @var string - */ - var $type = ''; - - /** - * Namespace - * - * @var string - */ - var $namespace = ''; - var $type_namespace = ''; - - var $attributes = array(); - - /** - * @var string - */ - var $arrayType = ''; - - var $options = array(); - - var $nqn; - var $tqn; - - /** - * Constructor. - * - * @param string $name Name of the SOAP value {namespace}name. - * @param mixed $type SOAP value {namespace}type. Determined - * automatically if not set. - * @param mixed $value Value to set. - * @param array $attributes Attributes. - */ - function SOAP_Value($name = '', $type = false, $value = null, - $attributes = array()) - { - // Detect type if not passed. - $this->nqn = new QName($name); - $this->name = $this->nqn->name; - $this->namespace = $this->nqn->namespace; - $this->tqn = new QName($type); - $this->type = $this->tqn->name; - $this->type_prefix = $this->tqn->ns; - $this->type_namespace = $this->tqn->namespace; - $this->value = $value; - $this->attributes = $attributes; - } - - /** - * Serializes this value. - * - * @param SOAP_Base $serializer A SOAP_Base instance or subclass to - * serialize with. - * - * @return string XML representation of $this. - */ - function serialize(&$serializer) - { - return $serializer->_serializeValue($this->value, - $this->name, - $this->type, - $this->namespace, - $this->type_namespace, - $this->options, - $this->attributes, - $this->arrayType); - } - -} - -/** - * This class converts values between PHP and SOAP. It is a simple wrapper - * around SOAP_Value, adding support for SOAP actor and mustunderstand - * parameters. - * - * Originally based on SOAPx4 by Dietrich Ayala - * http://dietrich.ganx4.com/soapx4 - * - * @access public - * @package SOAP - * @author Shane Caraveo Conversion to PEAR and updates - * @author Dietrich Ayala Original Author - */ -class SOAP_Header extends SOAP_Value -{ - /** - * Constructor - * - * @param string $name Name of the SOAP value {namespace}name. - * @param mixed $type SOAP value {namespace}type. Determined - * automatically if not set. - * @param mixed $value Value to set - * @param integer $mustunderstand Zero or one. - * @param mixed $attributes Attributes. - */ - function SOAP_Header($name = '', $type, $value, $mustunderstand = 0, - $attributes = array()) - { - if (!is_array($attributes)) { - $actor = $attributes; - $attributes = array(); - } - - parent::SOAP_Value($name, $type, $value, $attributes); - - if (isset($actor)) { - $this->attributes['SOAP-ENV:actor'] = $actor; - } elseif (!isset($this->attributes['SOAP-ENV:actor'])) { - $this->attributes['SOAP-ENV:actor'] = 'http://schemas.xmlsoap.org/soap/actor/next'; - } - $this->attributes['SOAP-ENV:mustUnderstand'] = (int)$mustunderstand; - } - -} - -/** - * This class handles MIME attachements per W3C's Note on Soap Attachements at - * http://www.w3.org/TR/SOAP-attachments - * - * @access public - * @package SOAP - * @author Shane Caraveo Conversion to PEAR and updates - */ -class SOAP_Attachment extends SOAP_Value -{ - /** - * Constructor. - * - * @param string $name Name of the SOAP value - * @param string $type The attachment's MIME type. - * @param string $filename The attachment's file name. Ignored if $file - * is provide. - * @param string $file The attachment data. - */ - function SOAP_Attachment($name = '', $type = 'application/octet-stream', - $filename, $file = null) - { - parent::SOAP_Value($name, null, null); - - $filedata = ($file === null) ? $this->_file2str($filename) : $file; - $filename = basename($filename); - if (PEAR::isError($filedata)) { - $this->options['attachment'] = $filedata; - return; - } - - $cid = $this->encryptOld(uniqid(time())); - - $this->attributes['href'] = 'cid:' . $cid; - - $this->options['attachment'] = array('body' => $filedata, - 'disposition' => $filename, - 'content_type' => $type, - 'encoding' => 'base64', - 'cid' => $cid); - } - - /** - * Returns the contents of the given file name as string. - * - * @access private - * - * @param string $file_name The file location. - * - * @return string The file data or a PEAR_Error. - */ - function _file2str($file_name) - { - if (!is_readable($file_name)) { - return PEAR::raiseError('File is not readable: ' . $file_name); - } - - if (function_exists('file_get_contents')) { - return file_get_contents($file_name); - } - - if (!$fd = fopen($file_name, 'rb')) { - return PEAR::raiseError('Could not open ' . $file_name); - } - $cont = fread($fd, filesize($file_name)); - fclose($fd); - - return $cont; - } - - 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); - } - -} diff --git a/gulliver/thirdparty/pear/SOAP/WSDL.php b/gulliver/thirdparty/pear/SOAP/WSDL.php deleted file mode 100644 index 9e760f519..000000000 --- a/gulliver/thirdparty/pear/SOAP/WSDL.php +++ /dev/null @@ -1,2294 +0,0 @@ - Original Author - * @author Shane Caraveo Port to PEAR and more - * @author Chuck Hagenbuch Maintenance - * @author Jan Schneider Maintenance - * @copyright 2003-2005 The PHP Group - * @license http://www.php.net/license/2_02.txt PHP License 2.02 - * @link http://pear.php.net/package/SOAP - */ - -require_once 'SOAP/Base.php'; -require_once 'SOAP/Fault.php'; -require_once 'HTTP/Request.php'; - -define('WSDL_CACHE_MAX_AGE', 43200); - -/** - * This class parses WSDL files, and can be used by SOAP::Client to properly - * register soap values for services. - * - * Originally based on SOAPx4 by Dietrich Ayala - * http://dietrich.ganx4.com/soapx4 - * - * @todo - * - add wsdl caching - * - refactor namespace handling ($namespace/$ns) - * - implement IDL type syntax declaration so we can generate WSDL - * - * @access public - * @package SOAP - * @author Shane Caraveo Conversion to PEAR and updates - * @author Dietrich Ayala Original Author - */ -class SOAP_WSDL extends SOAP_Base -{ - var $tns = null; - var $definition = array(); - var $namespaces = array(); - var $ns = array(); - var $xsd = SOAP_XML_SCHEMA_VERSION; - var $complexTypes = array(); - var $elements = array(); - var $messages = array(); - var $portTypes = array(); - var $bindings = array(); - var $imports = array(); - var $services = array(); - var $service = ''; - - /** - * URL to WSDL file. - * - * @var string - */ - var $uri; - - /** - * Parse documentation in the WSDL? - * - * @var boolean - */ - var $docs; - - /** - * Proxy parameters. - * - * @var array - */ - var $proxy; - - /** - * Enable tracing in the generated proxy class? - * - * @var boolean - */ - var $trace = false; - - /** - * Use WSDL cache? - * - * @var boolean - */ - var $cacheUse; - - /** - * WSDL cache directory. - * - * @var string - */ - var $cacheDir; - - /** - * Cache maximum lifetime (in seconds). - * - * @var integer - */ - var $cacheMaxAge; - - /** - * Class to use for WSDL parsing. Can be overridden for special cases, - * subclasses, etc. - * - * @var string - */ - var $wsdlParserClass = 'SOAP_WSDL_Parser'; - - /** - * Reserved PHP keywords. - * - * @link http://www.php.net/manual/en/reserved.php - * - * @var array - */ - var $_reserved = array('abstract', 'and', 'array', 'as', 'break', 'case', - 'catch', 'cfunction', 'class', 'clone', 'const', - 'continue', 'declare', 'default', 'die', 'do', - 'echo', 'else', 'elseif', 'empty', 'enddeclare', - 'endfor', 'endforeach', 'endif', 'endswitch', - 'endwhile', 'eval', 'exception', 'exit', 'extends', - 'final', 'for', 'foreach', 'function', 'global', - 'if', 'implements', 'include', 'include_once', - 'interface', 'isset', 'list', 'new', 'old_function', - 'or', 'php_user_filter', 'print', 'private', - 'protected', 'public', 'require', 'require_once', - 'return', 'static', 'switch', 'this', 'throw', - 'try', 'unset', 'use', 'var', 'while', 'xor'); - - /** - * Regular expressions for invalid PHP labels. - * - * @link http://www.php.net/manual/en/language.variables.php. - * - * @var string - */ - var $_invalid = array('/^[^a-zA-Z_\x7f-\xff]/', '/[^a-zA-Z0-9_\x7f-\xff]/'); - - /** - * SOAP_WSDL constructor. - * - * @param string $wsdl_uri URL to WSDL file. - * @param array $proxy Options for HTTP_Request class - * @see HTTP_Request. - * @param boolean|string $cacheUse Use WSDL caching? The cache directory - * if a string. - * @param integer $cacheMaxAge Cache maximum lifetime (in seconds). - * @param boolean $docs Parse documentation in the WSDL? - * - * @access public - */ - function SOAP_WSDL($wsdl_uri = false, - $proxy = array(), - $cacheUse = false, - $cacheMaxAge = WSDL_CACHE_MAX_AGE, - $docs = false) - { - parent::SOAP_Base('WSDL'); - $this->uri = $wsdl_uri; - $this->proxy = $proxy; - $this->cacheUse = !empty($cacheUse); - $this->cacheMaxAge = $cacheMaxAge; - $this->docs = $docs; - if (is_string($cacheUse)) { - $this->cacheDir = $cacheUse; - } - - if ($wsdl_uri) { - if (!PEAR::isError($this->parseURL($wsdl_uri))) { - reset($this->services); - $this->service = key($this->services); - } - } - } - - /** - * @deprecated Use setService(). - */ - function set_service($service) - { - $this->setService($service); - } - - /** - * Sets the service currently to be used. - * - * @param string $service An (existing) service name. - */ - function setService($service) - { - if (array_key_exists($service, $this->services)) { - $this->service = $service; - } - } - - /** - * Fills the WSDL array tree with data from a WSDL file. - * - * @param string $wsdl_uri URL to WSDL file. - */ - function parseURL($wsdl_uri) - { - $parser = new $this->wsdlParserClass($wsdl_uri, $this, $this->docs); - - if ($parser->fault) { - $this->_raiseSoapFault($parser->fault); - } - } - - /** - * Fills the WSDL array tree with data from one or more PHP class objects. - * - * @param mixed $wsdl_obj An object or array of objects to add to - * the internal WSDL tree. - * @param string $targetNamespace The target namespace of schema types - * etc. - * @param string $service_name Name of the WSDL service. - * @param string $service_desc Optional description of the WSDL - * service. - */ - function parseObject(&$wsdl_obj, $targetNamespace, $service_name, - $service_desc = '') - { - $parser = new SOAP_WSDL_ObjectParser($wsdl_obj, $this, - $targetNamespace, $service_name, - $service_desc); - - if ($parser->fault) { - $this->_raiseSoapFault($parser->fault); - } - } - - function getEndpoint($portName) - { - if ($this->_isfault()) { - return $this->_getfault(); - } - - return (isset($this->services[$this->service]['ports'][$portName]['address']['location'])) - ? $this->services[$this->service]['ports'][$portName]['address']['location'] - : $this->_raiseSoapFault("No endpoint for port for $portName", $this->uri); - } - - function _getPortName($operation, $service) - { - if (isset($this->services[$service]['ports'])) { - $ports = $this->services[$service]['ports']; - foreach ($ports as $port => $portAttrs) { - $type = $ports[$port]['type']; - if ($type == 'soap' && - isset($this->bindings[$portAttrs['binding']]['operations'][$operation])) { - return $port; - } - } - } - return null; - } - - /** - * Finds the name of the first port that contains an operation of name - * $operation. Always returns a SOAP portName. - */ - function getPortName($operation, $service = null) - { - if ($this->_isfault()) { - return $this->_getfault(); - } - - if (!$service) { - $service = $this->service; - } - if (isset($this->services[$service]['ports'])) { - if ($portName = $this->_getPortName($operation, $service)) { - return $portName; - } - } - // Try any service in the WSDL. - foreach ($this->services as $serviceName => $service) { - if (isset($this->services[$serviceName]['ports'])) { - if ($portName = $this->_getPortName($operation, $serviceName)) { - $this->service = $serviceName; - return $portName; - } - } - } - return $this->_raiseSoapFault("No operation $operation in WSDL.", $this->uri); - } - - function getOperationData($portName, $operation) - { - if ($this->_isfault()) { - return $this->_getfault(); - } - - if (!isset($this->services[$this->service]['ports'][$portName]['binding']) || - !($binding = $this->services[$this->service]['ports'][$portName]['binding'])) { - return $this->_raiseSoapFault("No binding for port $portName in WSDL.", $this->uri); - } - - // Get operation data from binding. - if (is_array($this->bindings[$binding]['operations'][$operation])) { - $opData = $this->bindings[$binding]['operations'][$operation]; - } - // get operation data from porttype - $portType = $this->bindings[$binding]['type']; - if (!$portType) { - return $this->_raiseSoapFault("No port type for binding $binding in WSDL.", $this->uri); - } - if (is_array($type = $this->portTypes[$portType][$operation])) { - if (isset($type['parameterOrder'])) { - $opData['parameterOrder'] = $type['parameterOrder']; - } - $opData['input'] = array_merge($opData['input'], $type['input']); - $opData['output'] = array_merge($opData['output'], $type['output']); - } - if (!$opData) - return $this->_raiseSoapFault("No operation $operation for port $portName in WSDL.", $this->uri); - $opData['parameters'] = false; - if (isset($this->bindings[$binding]['operations'][$operation]['input']['namespace'])) - $opData['namespace'] = $this->bindings[$binding]['operations'][$operation]['input']['namespace']; - // Message data from messages. - $inputMsg = $opData['input']['message']; - if (is_array($this->messages[$inputMsg])) { - foreach ($this->messages[$inputMsg] as $pname => $pattrs) { - if ($opData['style'] == 'document' && - $opData['input']['use'] == 'literal' && - $pname == 'parameters') { - $opData['parameters'] = true; - $opData['namespace'] = $this->namespaces[$pattrs['namespace']]; - $el = $this->elements[$pattrs['namespace']][$pattrs['type']]; - if (isset($el['elements'])) { - foreach ($el['elements'] as $elname => $elattrs) { - $opData['input']['parts'][$elname] = $elattrs; - } - } - } else { - $opData['input']['parts'][$pname] = $pattrs; - } - } - } - $outputMsg = $opData['output']['message']; - if (is_array($this->messages[$outputMsg])) { - foreach ($this->messages[$outputMsg] as $pname => $pattrs) { - if ($opData['style'] == 'document' && - $opData['output']['use'] == 'literal' && - $pname == 'parameters') { - - $el = $this->elements[$pattrs['namespace']][$pattrs['type']]; - if (isset($el['elements'])) { - foreach ($el['elements'] as $elname => $elattrs) { - $opData['output']['parts'][$elname] = $elattrs; - } - } - } else { - $opData['output']['parts'][$pname] = $pattrs; - } - } - } - return $opData; - } - - function matchMethod(&$operation) - { - if ($this->_isfault()) { - return $this->_getfault(); - } - - // Overloading lowercases function names :( - foreach ($this->services[$this->service]['ports'] as $portAttrs) { - foreach (array_keys($this->bindings[$portAttrs['binding']]['operations']) as $op) { - if (strcasecmp($op, $operation) == 0) { - $operation = $op; - } - } - } - } - - /** - * Given a datatype, what function handles the processing? - * - * This is used for doc/literal requests where we receive a datatype, and - * we need to pass it to a method in out server class. - * - * @param string $datatype - * @param string $namespace - * @return string - * @access public - */ - function getDataHandler($datatype, $namespace) - { - // See if we have an element by this name. - if (isset($this->namespaces[$namespace])) { - $namespace = $this->namespaces[$namespace]; - } - - if (isset($this->ns[$namespace])) { - $nsp = $this->ns[$namespace]; - //if (!isset($this->elements[$nsp])) - // $nsp = $this->namespaces[$nsp]; - if (isset($this->elements[$nsp][$datatype])) { - $checkmessages = array(); - // Find what messages use this datatype. - foreach ($this->messages as $messagename => $message) { - foreach ($message as $part) { - if ($part['type'] == $datatype) { - $checkmessages[] = $messagename; - break; - } - } - } - // Find the operation that uses this message. - foreach($this->portTypes as $porttype) { - foreach ($porttype as $opname => $opinfo) { - foreach ($checkmessages as $messagename) { - if ($opinfo['input']['message'] == $messagename) { - return $opname; - } - } - } - } - } - } - - return null; - } - - function getSoapAction($portName, $operation) - { - if ($this->_isfault()) { - return $this->_getfault(); - } - - if (!empty($this->bindings[$this->services[$this->service]['ports'][$portName]['binding']]['operations'][$operation]['soapAction'])) { - return $this->bindings[$this->services[$this->service]['ports'][$portName]['binding']]['operations'][$operation]['soapAction']; - } - - return false; - } - - function getNamespace($portName, $operation) - { - if ($this->_isfault()) { - return $this->_getfault(); - } - - if (!empty($this->bindings[$this->services[$this->service]['ports'][$portName]['binding']]['operations'][$operation]['input']['namespace'])) { - return $this->bindings[$this->services[$this->service]['ports'][$portName]['binding']]['operations'][$operation]['input']['namespace']; - } - - return false; - } - - function getNamespaceAttributeName($namespace) - { - /* If it doesn't exist at first, flip the array and check again. */ - if (empty($this->ns[$namespace])) { - $this->ns = array_flip($this->namespaces); - } - - /* If it doesn't exist now, add it. */ - if (empty($this->ns[$namespace])) { - return $this->addNamespace($namespace); - } - - return $this->ns[$namespace]; - } - - function addNamespace($namespace) - { - if (!empty($this->ns[$namespace])) { - return $this->ns[$namespace]; - } - - $n = count($this->ns); - $attr = 'ns' . $n; - $this->namespaces['ns' . $n] = $namespace; - $this->ns[$namespace] = $attr; - - return $attr; - } - - function _validateString($string) - { - return preg_match('/^[\w_:#\/]+$/', $string); - } - - function _addArg(&$args, &$argarray, $argname) - { - if ($args) { - $args .= ', '; - } - $args .= '$' . $argname; - if (!$this->_validateString($argname)) { - return; - } - if ($argarray) { - $argarray .= ', '; - } - $argarray .= "'$argname' => $" . $argname; - } - - function _elementArg(&$args, &$argarray, &$_argtype, $_argname) - { - $comments = ''; - $el = $this->elements[$_argtype['namespace']][$_argtype['type']]; - $tns = isset($this->ns[$el['namespace']]) - ? $this->ns[$el['namespace']] - : $_argtype['namespace']; - - if (!empty($el['complex']) || - (isset($el['type']) && - isset($this->complexTypes[$tns][$el['type']]))) { - // The element is a complex type. - $comments .= " // {$_argtype['type']} is a ComplexType, refer to the WSDL for more info.\n"; - $attrname = "{$_argtype['type']}_attr"; - if (isset($el['type']) && - isset($this->complexTypes[$tns][$el['type']]['attribute'])) { - $comments .= " // {$_argtype['type']} may require attributes, refer to the WSDL for more info.\n"; - } - $comments .= " \${$attrname}['xmlns'] = '{$this->namespaces[$_argtype['namespace']]}';\n"; - $comments .= " \${$_argtype['type']} = new SOAP_Value('{$_argtype['type']}', false, \${$_argtype['type']}, \$$attrname);\n"; - $this->_addArg($args, $argarray, $_argtype['type']); - if (isset($el['type']) && - isset($this->complexTypes[$tns][$el['type']]['attribute'])) { - if ($args) { - $args .= ', '; - } - $args .= '$' . $attrname; - } - } elseif (isset($el['elements'])) { - foreach ($el['elements'] as $ename => $element) { - $comments .= " \$$ename = new SOAP_Value('{{$this->namespaces[$element['namespace']]}}$ename', '" . - (isset($element['type']) ? $element['type'] : false) . - "', \$$ename);\n"; - $this->_addArg($args, $argarray, $ename); - } - } else { - $comments .= " \$$_argname = new SOAP_Value('{{$this->namespaces[$tns]}}$_argname', '{$el['type']}', \$$_argname);\n"; - $this->_addArg($args, $argarray, $_argname); - } - - return $comments; - } - - function _complexTypeArg(&$args, &$argarray, &$_argtype, $_argname) - { - $comments = ''; - if (isset($this->complexTypes[$_argtype['namespace']][$_argtype['type']])) { - $comments = " // $_argname is a ComplexType {$_argtype['type']},\n" . - " // refer to wsdl for more info\n"; - if (isset($this->complexTypes[$_argtype['namespace']][$_argtype['type']]['attribute'])) { - $comments .= " // $_argname may require attributes, refer to wsdl for more info\n"; - } - $wrapname = '{' . $this->namespaces[$_argtype['namespace']].'}' . $_argtype['type']; - $comments .= " \$$_argname = new SOAP_Value('$_argname', '$wrapname', \$$_argname);\n"; - } - - $this->_addArg($args, $argarray, $_argname); - - return $comments; - } - - /** - * Generates stub code from the WSDL that can be saved to a file or eval'd - * into existence. - */ - function generateProxyCode($port = '', $classname = '') - { - if ($this->_isfault()) { - return $this->_getfault(); - } - - $multiport = count($this->services[$this->service]['ports']) > 1; - if (!$port) { - reset($this->services[$this->service]['ports']); - $port = current($this->services[$this->service]['ports']); - } - // XXX currently do not support HTTP ports - if ($port['type'] != 'soap') { - return null; - } - - // XXX currentPort is BAD - $clienturl = $port['address']['location']; - if (!$classname) { - if ($multiport || $port) { - $classname = 'WebService_' . $this->service . '_' . $port['name']; - } else { - $classname = 'WebService_' . $this->service; - } - $classname = $this->_sanitize($classname); - } - - if (!$this->_validateString($classname)) { - return null; - } - - if (is_array($this->proxy) && count($this->proxy)) { - $class = "class $classname extends SOAP_Client\n{\n" . - " function $classname(\$path = '$clienturl')\n {\n" . - " \$this->SOAP_Client(\$path, 0, 0,\n" . - ' array('; - - foreach ($this->proxy as $key => $val) { - if (is_array($val)) { - $class .= "'$key' => array("; - foreach ($val as $key2 => $val2) { - $class .= "'$key2' => '$val2', "; - } - $class .= ')'; - } else { - $class .= "'$key' => '$val', "; - } - } - $class .= "));\n }\n"; - $class = str_replace(', ))', '))', $class); - } else { - $class = "class $classname extends SOAP_Client\n{\n" . - " function $classname(\$path = '$clienturl')\n {\n" . - " \$this->SOAP_Client(\$path, 0);\n" . - " }\n"; - } - - // Get the binding, from that get the port type. - $primaryBinding = $port['binding']; - $primaryBinding = preg_replace("/^(.*:)/", '', $primaryBinding); - $portType = $this->bindings[$primaryBinding]['type']; - $portType = preg_replace("/^(.*:)/", '', $portType); - $style = $this->bindings[$primaryBinding]['style']; - - // XXX currentPortType is BAD - foreach ($this->portTypes[$portType] as $opname => $operation) { - $binding = $this->bindings[$primaryBinding]['operations'][$opname]; - if (isset($binding['soapAction'])) { - $soapaction = $binding['soapAction']; - } else { - $soapaction = null; - } - if (isset($binding['style'])) { - $opstyle = $binding['style']; - } else { - $opstyle = $style; - } - $use = $binding['input']['use']; - if ($use == 'encoded') { - $namespace = $binding['input']['namespace']; - } else { - $bindingType = $this->bindings[$primaryBinding]['type']; - $ns = $this->portTypes[$bindingType][$opname]['input']['namespace']; - $namespace = $this->namespaces[$ns]; - } - - $args = ''; - $argarray = ''; - $comments = ''; - $wrappers = ''; - foreach ($operation['input'] as $argname => $argtype) { - if ($argname == 'message') { - foreach ($this->messages[$argtype] as $_argname => $_argtype) { - $_argname = $this->_sanitize($_argname); - if ($opstyle == 'document' && $use == 'literal' && - $_argtype['name'] == 'parameters') { - // The type or element refered to is used for - // parameters. - $elattrs = null; - $el = $this->elements[$_argtype['namespace']][$_argtype['type']]; - - if ($el['complex']) { - $namespace = $this->namespaces[$_argtype['namespace']]; - // XXX need to wrap the parameters in a - // SOAP_Value. - } - if (isset($el['elements'])) { - foreach ($el['elements'] as $elname => $elattrs) { - $elname = $this->_sanitize($elname); - // Is the element a complex type? - if (isset($this->complexTypes[$elattrs['namespace']][$elname])) { - $comments .= $this->_complexTypeArg($args, $argarray, $_argtype, $_argname); - } else { - $this->_addArg($args, $argarray, $elname); - } - } - } - if ($el['complex'] && $argarray) { - $wrapname = '{' . $this->namespaces[$_argtype['namespace']].'}' . $el['name']; - $comments .= " \${$el['name']} = new SOAP_Value('$wrapname', false, \$v = array($argarray));\n"; - $argarray = "'{$el['name']}' => \${$el['name']}"; - } - } else { - if (isset($_argtype['element'])) { - // Element argument. - $comments .= $this->_elementArg($args, $argarray, $_argtype, $_argtype['type']); - } else { - // Complex type argument. - $comments .= $this->_complexTypeArg($args, $argarray, $_argtype, $_argname); - } - } - } - } - } - - // Validate entries. - - // Operation names are function names, so try to make sure it's - // legal. This could potentially cause collisions, but let's try - // to make everything callable and see how many problems that - // causes. - $opname_php = $this->_sanitize($opname); - if (!$this->_validateString($opname_php)) { - return null; - } - - if ($argarray) { - $argarray = "array($argarray)"; - } else { - $argarray = 'null'; - } - - $class .= " function &$opname_php($args)\n {\n$comments$wrappers" . - " \$result = \$this->call('$opname',\n" . - " \$v = $argarray,\n" . - " array('namespace' => '$namespace',\n" . - " 'soapaction' => '$soapaction',\n" . - " 'style' => '$opstyle',\n" . - " 'use' => '$use'" . - ($this->trace ? ",\n 'trace' => true" : '') . "));\n" . - " return \$result;\n" . - " }\n"; - } - - $class .= "}\n"; - - return $class; - } - - function generateAllProxies() - { - $proxycode = ''; - foreach (array_keys($this->services[$this->service]['ports']) as $key) { - $port =& $this->services[$this->service]['ports'][$key]; - $proxycode .= $this->generateProxyCode($port); - } - return $proxycode; - } - - function &getProxy($port = '', $name = '') - { - if ($this->_isfault()) { - $fault =& $this->_getfault(); - return $fault; - } - - $multiport = count($this->services[$this->service]['ports']) > 1; - - if (!$port) { - reset($this->services[$this->service]['ports']); - $port = current($this->services[$this->service]['ports']); - } - - if ($multiport || $port) { - $classname = 'WebService_' . $this->service . '_' . $port['name']; - } else { - $classname = 'WebService_' . $this->service; - } - - if ($name) { - $classname = $name . '_' . $classname; - } - - $classname = $this->_sanitize($classname); - if (!class_exists($classname)) { - $proxy = $this->generateProxyCode($port, $classname); - require_once 'SOAP/Client.php'; - eval($proxy); - } - $proxy = new $classname; - - return $proxy; - } - - /** - * Sanitizes a SOAP value, method or class name so that it can be used as - * a valid PHP identifier. Invalid characters are converted into - * underscores and reserved words are prefixed with an underscore. - * - * @param string $name The identifier to sanitize. - * - * @return string The sanitized identifier. - */ - function _sanitize($name) - { - $name = preg_replace($this->_invalid, '_', $name); - if (in_array($name, $this->_reserved)) { - $name = '_' . $name; - } - return $name; - } - - function &_getComplexTypeForElement($name, $namespace) - { - $t = null; - if (isset($this->ns[$namespace]) && - isset($this->elements[$this->ns[$namespace]][$name]['type'])) { - - $type = $this->elements[$this->ns[$namespace]][$name]['type']; - $ns = $this->elements[$this->ns[$namespace]][$name]['namespace']; - - if (isset($this->complexTypes[$ns][$type])) { - $t = $this->complexTypes[$ns][$type]; - } - } - return $t; - } - - function getComplexTypeNameForElement($name, $namespace) - { - $t = $this->_getComplexTypeForElement($name, $namespace); - if ($t) { - return $t['name']; - } - return null; - } - - function getComplexTypeChildType($ns, $name, $child_ns, $child_name) - { - // Is the type an element? - $t = $this->_getComplexTypeForElement($name, $ns); - if ($t) { - // No, get it from complex types directly. - if (isset($t['elements'][$child_name]['type'])) - return $t['elements'][$child_name]['type']; - } elseif (isset($this->ns[$ns]) && - isset($this->elements[$this->ns[$ns]][$name]['complex']) && - $this->elements[$this->ns[$ns]][$name]['complex']) { - // Type is not an element but complex. - return $this->elements[$this->ns[$ns]][$name]['elements'][$child_name]['type']; - } - return null; - } - - function getSchemaType($type, $name, $type_namespace) - { - // see if it's a complex type so we can deal properly with - // SOAPENC:arrayType. - if ($name && $type) { - // XXX TODO: - // look up the name in the wsdl and validate the type. - foreach ($this->complexTypes as $types) { - if (isset($types[$type])) { - if (isset($types[$type]['type'])) { - list($arraytype_ns, $arraytype, $array_depth) = isset($types[$type]['arrayType']) - ? $this->_getDeepestArrayType($types[$type]['namespace'], $types[$type]['arrayType']) - : array($this->namespaces[$types[$type]['namespace']], null, 0); - return array($types[$type]['type'], $arraytype, $arraytype_ns, $array_depth); - } - if (isset($types[$type]['arrayType'])) { - list($arraytype_ns, $arraytype, $array_depth) = - $this->_getDeepestArrayType($types[$type]['namespace'], $types[$type]['arrayType']); - return array('Array', $arraytype, $arraytype_ns, $array_depth); - } - if (!empty($types[$type]['elements'][$name])) { - $type = $types[$type]['elements']['type']; - return array($type, null, $this->namespaces[$types[$type]['namespace']], null); - } - break; - } - } - } - if ($type && $type_namespace) { - $arrayType = null; - // XXX TODO: - // this code currently handles only one way of encoding array - // types in wsdl need to do a generalized function to figure out - // complex types - $p = $this->ns[$type_namespace]; - if ($p && !empty($this->complexTypes[$p][$type])) { - if ($arrayType = $this->complexTypes[$p][$type]['arrayType']) { - $type = 'Array'; - } elseif ($this->complexTypes[$p][$type]['order'] == 'sequence' && - array_key_exists('elements', $this->complexTypes[$p][$type])) { - reset($this->complexTypes[$p][$type]['elements']); - // assume an array - if (count($this->complexTypes[$p][$type]['elements']) == 1) { - $arg = current($this->complexTypes[$p][$type]['elements']); - $arrayType = $arg['type']; - $type = 'Array'; - } else { - foreach ($this->complexTypes[$p][$type]['elements'] as $element) { - if ($element['name'] == $type) { - $arrayType = $element['type']; - $type = $element['type']; - } - } - } - } else { - $type = 'Struct'; - } - return array($type, $arrayType, $type_namespace, null); - } - } - return array(null, null, null, null); - } - - /** - * Recurse through the WSDL structure looking for the innermost array type - * of multi-dimensional arrays. - * - * Takes a namespace prefix and a type, which can be in the form 'type' or - * 'type[]', and returns the full namespace URI, the type of the most - * deeply nested array type found, and the number of levels of nesting. - * - * @access private - * @return mixed array or nothing - */ - function _getDeepestArrayType($nsPrefix, $arrayType) - { - static $trail = array(); - - $arrayType = ereg_replace('\[\]$', '', $arrayType); - - // Protect against circular references XXX We really need to remove - // trail from this altogether (it's very inefficient and in the wrong - // place!) and put circular reference checking in when the WSDL info - // is generated in the first place - if (array_search($nsPrefix . ':' . $arrayType, $trail)) { - return array(null, null, -count($trail)); - } - - if (array_key_exists($nsPrefix, $this->complexTypes) && - array_key_exists($arrayType, $this->complexTypes[$nsPrefix]) && - array_key_exists('arrayType', $this->complexTypes[$nsPrefix][$arrayType])) { - $trail[] = $nsPrefix . ':' . $arrayType; - $result = $this->_getDeepestArrayType($this->complexTypes[$nsPrefix][$arrayType]['namespace'], - $this->complexTypes[$nsPrefix][$arrayType]['arrayType']); - return array($result[0], $result[1], $result[2] + 1); - } - return array($this->namespaces[$nsPrefix], $arrayType, 0); - } - -} - -class SOAP_WSDL_Cache extends SOAP_Base -{ - /** - * Use WSDL cache? - * - * @var boolean - */ - var $_cacheUse; - - /** - * WSDL cache directory. - * - * @var string - */ - var $_cacheDir; - - /** - * Cache maximum lifetime (in seconds) - * - * @var integer - */ - var $_cacheMaxAge; - - /** - * Constructor. - * - * @param boolean $cashUse Use caching? - * @param integer $cacheMaxAge Cache maximum lifetime (in seconds) - */ - function SOAP_WSDL_Cache($cacheUse = false, - $cacheMaxAge = WSDL_CACHE_MAX_AGE, - $cacheDir = null) - { - parent::SOAP_Base('WSDLCACHE'); - $this->_cacheUse = $cacheUse; - $this->_cacheDir = $cacheDir; - $this->_cacheMaxAge = $cacheMaxAge; - } - - /** - * Returns the path to the cache and creates it, if it doesn't exist. - * - * @private - * - * @return string The directory to use for the cache. - */ - function _cacheDir() - { - if (!empty($this->_cacheDir)) { - $dir = $this->_cacheDir; - } else { - $dir = getenv('WSDLCACHE'); - if (empty($dir)) { - $dir = './wsdlcache'; - } - } - @mkdir($dir, 0700); - return $dir; - } - - /** - * Retrieves a file from cache if it exists, otherwise retreive from net, - * add to cache, and return from cache. - * - * @param string URL to WSDL - * @param array proxy parameters - * @param int expected MD5 of WSDL URL - * @access public - * @return string data - */ - function get($wsdl_fname, $proxy_params = array(), $cache = 0) - { - $cachename = $md5_wsdl = $file_data = ''; - if ($this->_cacheUse) { - // Try to retrieve WSDL from cache - $cachename = $this->_cacheDir() . '/' . $this->encryptOld($wsdl_fname). ' .wsdl'; - if (file_exists($cachename)) { - $wf = fopen($cachename, 'rb'); - if ($wf) { - // Reading cached file - $file_data = fread($wf, filesize($cachename)); - $md5_wsdl = $this->encryptOld($file_data); - fclose($wf); - } - if ($cache) { - if ($cache != $md5_wsdl) { - return $this->_raiseSoapFault('WSDL Checksum error!', $wsdl_fname); - } - } else { - $fi = stat($cachename); - $cache_mtime = $fi[8]; - //print cache_mtime, time() - if ($cache_mtime + $this->_cacheMaxAge < time()) { - // expired - $md5_wsdl = ''; // refetch - } - } - } - } - - if (!$md5_wsdl) { - // Not cached or not using cache. Retrieve WSDL from URL - - // is it a local file? - // this section should be replace by curl at some point - if (!preg_match('/^(https?|file):\/\//', $wsdl_fname)) { - if (!file_exists($wsdl_fname)) { - return $this->_raiseSoapFault("Unable to read local WSDL $wsdl_fname", $wsdl_fname); - } - $file_data = file_get_contents($wsdl_fname); - } else { - $uri = explode('?', $wsdl_fname); - $rq = new HTTP_Request($uri[0], $proxy_params); - // the user agent HTTP_Request uses fouls things up - if (isset($uri[1])) { - $rq->addRawQueryString($uri[1]); - } - - if (isset($proxy_params['proxy_host']) && - isset($proxy_params['proxy_port']) && - isset($proxy_params['proxy_user']) && - isset($proxy_params['proxy_pass'])) { - $rq->setProxy($proxy_params['proxy_host'], $proxy_params['proxy_port'], - $proxy_params['proxy_user'], $proxy_params['proxy_pass']); - } elseif (isset($proxy_params['proxy_host']) && - isset($proxy_params['proxy_port'])) { - $rq->setProxy($proxy_params['proxy_host'], $proxy_params['proxy_port']); - } - - $result = $rq->sendRequest(); - if (PEAR::isError($result)) { - return $this->_raiseSoapFault("Unable to retrieve WSDL $wsdl_fname," . $rq->getResponseCode(), $wsdl_fname); - } - $file_data = $rq->getResponseBody(); - if (!$file_data) { - return $this->_raiseSoapFault("Unable to retrieve WSDL $wsdl_fname, no http body", $wsdl_fname); - } - } - - $md5_wsdl = $this->encryptOld($file_data); - - if ($this->_cacheUse) { - $fp = fopen($cachename, "wb"); - fwrite($fp, $file_data); - fclose($fp); - } - } - if ($this->_cacheUse && $cache && $cache != $md5_wsdl) { - return $this->_raiseSoapFault("WSDL Checksum error!", $wsdl_fname); - } - return $file_data; - } - - 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); - } - -} - -class SOAP_WSDL_Parser extends SOAP_Base -{ - - /** - * Define internal arrays of bindings, ports, operations, - * messages, etc. - */ - var $currentMessage; - var $currentOperation; - var $currentPortType; - var $currentBinding; - var $currentPort; - - /** - * Parser vars. - */ - var $cache; - - var $tns = null; - var $soapns = array('soap'); - var $uri = ''; - var $wsdl = null; - - var $status = ''; - var $element_stack = array(); - var $parentElement = ''; - - var $schema = ''; - var $schemaStatus = ''; - var $schema_stack = array(); - var $currentComplexType; - var $schema_element_stack = array(); - var $currentElement; - - /** - * Constructor. - */ - function SOAP_WSDL_Parser($uri, &$wsdl, $docs = false) - { - parent::SOAP_Base('WSDLPARSER'); - $this->cache = new SOAP_WSDL_Cache($wsdl->cacheUse, - $wsdl->cacheMaxAge, - $wsdl->cacheDir); - $this->uri = $uri; - $this->wsdl = &$wsdl; - $this->docs = $docs; - $this->parse($uri); - } - - function parse($uri) - { - // Check whether content has been read. - $fd = $this->cache->get($uri, $this->wsdl->proxy); - if (PEAR::isError($fd)) { - return $this->_raiseSoapFault($fd); - } - - // Create an XML parser. - $parser = xml_parser_create(); - xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0); - xml_set_object($parser, $this); - xml_set_element_handler($parser, 'startElement', 'endElement'); - if ($this->docs) { - xml_set_character_data_handler($parser, 'characterData'); - } - - if (!xml_parse($parser, $fd, true)) { - $detail = sprintf('XML error on line %d: %s', - xml_get_current_line_number($parser), - xml_error_string(xml_get_error_code($parser))); - return $this->_raiseSoapFault("Unable to parse WSDL file $uri\n$detail"); - } - xml_parser_free($parser); - return true; - } - - /** - * start-element handler - */ - function startElement($parser, $name, $attrs) - { - // Get element prefix. - $qname = new QName($name); - if ($qname->ns) { - $ns = $qname->ns; - if ($ns && ((!$this->tns && strcasecmp($qname->name, 'definitions') == 0) || $ns == $this->tns)) { - $name = $qname->name; - } - } - $this->currentTag = $qname->name; - $this->parentElement = ''; - $stack_size = count($this->element_stack); - if ($stack_size) { - $this->parentElement = $this->element_stack[$stack_size - 1]; - } - $this->element_stack[] = $this->currentTag; - - // Find status, register data. - switch ($this->status) { - case 'types': - // sect 2.2 wsdl:types - // children: xsd:schema - $parent_tag = ''; - $stack_size = count($this->schema_stack); - if ($stack_size) { - $parent_tag = $this->schema_stack[$stack_size - 1]; - } - - switch ($qname->name) { - case 'schema': - // No parent should be in the stack. - if (!$parent_tag || $parent_tag == 'types') { - if (array_key_exists('targetNamespace', $attrs)) { - $this->schema = $this->wsdl->getNamespaceAttributeName($attrs['targetNamespace']); - } else { - $this->schema = $this->wsdl->getNamespaceAttributeName($this->wsdl->tns); - } - $this->wsdl->complexTypes[$this->schema] = array(); - $this->wsdl->elements[$this->schema] = array(); - } - break; - - case 'complexType': - if ($parent_tag == 'schema') { - $this->currentComplexType = $attrs['name']; - if (!isset($attrs['namespace'])) { - $attrs['namespace'] = $this->schema; - } - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType] = $attrs; - if (array_key_exists('base', $attrs)) { - $qn = new QName($attrs['base']); - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] = $qn->name; - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['namespace'] = $qn->ns; - } else { - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] = 'Struct'; - } - $this->schemaStatus = 'complexType'; - } else { - $this->wsdl->elements[$this->schema][$this->currentElement]['complex'] = true; - } - break; - - case 'element': - if (isset($attrs['type'])) { - $qn = new QName($attrs['type']); - $attrs['type'] = $qn->name; - if ($qn->ns && array_key_exists($qn->ns, $this->wsdl->namespaces)) { - $attrs['namespace'] = $qn->ns; - } - } - - $parentElement = ''; - $stack_size = count($this->schema_element_stack); - if ($stack_size > 0) { - $parentElement = $this->schema_element_stack[$stack_size - 1]; - } - - if (isset($attrs['ref'])) { - $qn = new QName($attrs['ref']); - $this->currentElement = $qn->name; - } else { - $this->currentElement = $attrs['name']; - } - $this->schema_element_stack[] = $this->currentElement; - if (!isset($attrs['namespace'])) { - $attrs['namespace'] = $this->schema; - } - - if ($parent_tag == 'schema') { - $this->wsdl->elements[$this->schema][$this->currentElement] = $attrs; - $this->wsdl->elements[$this->schema][$this->currentElement]['complex'] = false; - $this->schemaStatus = 'element'; - } elseif ($this->currentComplexType) { - // we're inside a complexType - if ((isset($this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['order']) && - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['order'] == 'sequence') - && $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] == 'Array') { - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['arrayType'] = isset($attrs['type']) ? $attrs['type'] : null; - } - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['elements'][$this->currentElement] = $attrs; - } else { - $this->wsdl->elements[$this->schema][$parentElement]['elements'][$this->currentElement] = $attrs; - } - break; - - case 'complexContent': - case 'simpleContent': - break; - - case 'extension': - case 'restriction': - if ($this->schemaStatus == 'complexType') { - if (!empty($attrs['base'])) { - $qn = new QName($attrs['base']); - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] = $qn->name; - - // Types that extend from other types aren't - // *of* those types. Reflect this by denoting - // which type they extend. I'm leaving the - // 'type' setting here since I'm not sure what - // removing it might break at the moment. - if ($qname->name == 'extension') { - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['extends'] = $qn->name; - } - } else { - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] = 'Struct'; - } - } - break; - - case 'sequence': - if ($this->schemaStatus == 'complexType') { - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['order'] = $qname->name; - if (!isset($this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'])) { - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] = 'Array'; - } - } - break; - - case 'all': - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['order'] = $qname->name; - if (!isset($this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'])) { - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] = 'Struct'; - } - break; - - case 'choice': - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['order'] = $qname->name; - if (!isset($this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'])) { - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] = 'Array'; - } - - case 'attribute': - if ($this->schemaStatus == 'complexType') { - if (isset($attrs['name'])) { - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['attribute'][$attrs['name']] = $attrs; - } else { - if (isset($attrs['ref'])) { - $q = new QName($attrs['ref']); - foreach ($attrs as $k => $v) { - if ($k != 'ref' && strstr($k, $q->name)) { - $vq = new QName($v); - if ($q->name == 'arrayType') { - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType][$q->name] = $vq->name. $vq->arrayInfo; - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] = 'Array'; - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['namespace'] = $vq->ns; - } else { - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType][$q->name] = $vq->name; - } - } - } - } - } - } - break; - } - - $this->schema_stack[] = $qname->name; - break; - - case 'message': - // sect 2.3 wsdl:message child wsdl:part - switch ($qname->name) { - case 'part': - $qn = null; - if (isset($attrs['type'])) { - $qn = new QName($attrs['type']); - } elseif (isset($attrs['element'])) { - $qn = new QName($attrs['element']); - } - if ($qn) { - $attrs['type'] = $qn->name; - $attrs['namespace'] = $qn->ns; - } - $this->wsdl->messages[$this->currentMessage][$attrs['name']] = $attrs; - // error in wsdl - - case 'documentation': - break; - - default: - break; - } - break; - - case 'portType': - // sect 2.4 - switch ($qname->name) { - case 'operation': - // attributes: name - // children: wsdl:input wsdl:output wsdl:fault - $this->currentOperation = $attrs['name']; - $this->wsdl->portTypes[$this->currentPortType][$this->currentOperation] = $attrs; - break; - - case 'input': - case 'output': - case 'fault': - // wsdl:input wsdl:output wsdl:fault - // attributes: name message parameterOrder(optional) - if ($this->currentOperation) { - if (isset($this->wsdl->portTypes[$this->currentPortType][$this->currentOperation][$name])) { - $this->wsdl->portTypes[$this->currentPortType][$this->currentOperation][$name] = array_merge($this->wsdl->portTypes[$this->currentPortType][$this->currentOperation][$name], $attrs); - } else { - $this->wsdl->portTypes[$this->currentPortType][$this->currentOperation][$name] = $attrs; - } - if (array_key_exists('message', $attrs)) { - $qn = new QName($attrs['message']); - $this->wsdl->portTypes[$this->currentPortType][$this->currentOperation][$name]['message'] = $qn->name; - $this->wsdl->portTypes[$this->currentPortType][$this->currentOperation][$name]['namespace'] = $qn->ns; - } - } - break; - - case 'documentation': - break; - - default: - break; - } - break; - - case 'binding': - $ns = $qname->ns ? $this->wsdl->namespaces[$qname->ns] : SCHEMA_WSDL; - switch ($ns) { - case SCHEMA_SOAP: - case SCHEMA_SOAP12: - // this deals with wsdl section 3 soap binding - switch ($qname->name) { - case 'binding': - // sect 3.3 - // soap:binding, attributes: transport(required), style(optional, default = document) - // if style is missing, it is assumed to be 'document' - if (!isset($attrs['style'])) { - $attrs['style'] = 'document'; - } - $this->wsdl->bindings[$this->currentBinding] = array_merge($this->wsdl->bindings[$this->currentBinding], $attrs); - break; - - case 'operation': - // sect 3.4 - // soap:operation, attributes: soapAction(required), style(optional, default = soap:binding:style) - if (!isset($attrs['style'])) { - $attrs['style'] = $this->wsdl->bindings[$this->currentBinding]['style']; - } - if (isset($this->wsdl->bindings[$this->currentBinding]['operations'][$this->currentOperation])) { - $this->wsdl->bindings[$this->currentBinding]['operations'][$this->currentOperation] = array_merge($this->wsdl->bindings[$this->currentBinding]['operations'][$this->currentOperation], $attrs); - } else { - $this->wsdl->bindings[$this->currentBinding]['operations'][$this->currentOperation] = $attrs; - } - break; - - case 'body': - // sect 3.5 - // soap:body attributes: - // part - optional. listed parts must appear in body, missing means all parts appear in body - // use - required. encoded|literal - // encodingStyle - optional. space seperated list of encodings (uri's) - $this->wsdl->bindings[$this->currentBinding] - ['operations'][$this->currentOperation][$this->opStatus] = $attrs; - break; - - case 'fault': - // sect 3.6 - // soap:fault attributes: name use encodingStyle namespace - $this->wsdl->bindings[$this->currentBinding] - ['operations'][$this->currentOperation][$this->opStatus] = $attrs; - break; - - case 'header': - // sect 3.7 - // soap:header attributes: message part use encodingStyle namespace - $this->wsdl->bindings[$this->currentBinding] - ['operations'][$this->currentOperation][$this->opStatus]['headers'][] = $attrs; - break; - - case 'headerfault': - // sect 3.7 - // soap:header attributes: message part use encodingStyle namespace - $header = count($this->wsdl->bindings[$this->currentBinding] - ['operations'][$this->currentOperation][$this->opStatus]['headers'])-1; - $this->wsdl->bindings[$this->currentBinding] - ['operations'][$this->currentOperation][$this->opStatus]['headers'][$header]['fault'] = $attrs; - break; - - case 'documentation': - break; - - default: - // error! not a valid element inside binding - break; - } - break; - - case SCHEMA_WSDL: - // XXX verify correct namespace - // for now, default is the 'wsdl' namespace - // other possible namespaces include smtp, http, etc. for alternate bindings - switch ($qname->name) { - case 'operation': - // sect 2.5 - // wsdl:operation attributes: name - $this->currentOperation = $attrs['name']; - break; - - case 'output': - case 'input': - case 'fault': - // sect 2.5 - // wsdl:input attributes: name - $this->opStatus = $qname->name; - break; - - case 'documentation': - break; - - default: - break; - } - break; - - case SCHEMA_WSDL_HTTP: - switch ($qname->name) { - case 'binding': - // sect 4.4 - // http:binding attributes: verb - // parent: wsdl:binding - $this->wsdl->bindings[$this->currentBinding] = array_merge($this->wsdl->bindings[$this->currentBinding], $attrs); - break; - - case 'operation': - // sect 4.5 - // http:operation attributes: location - // parent: wsdl:operation - $this->wsdl->bindings[$this->currentBinding]['operations'] - [$this->currentOperation] = $attrs; - break; - - case 'urlEncoded': - // sect 4.6 - // http:urlEncoded attributes: location - // parent: wsdl:input wsdl:output etc. - $this->wsdl->bindings[$this->currentBinding]['operations'][$this->opStatus] - [$this->currentOperation]['uri'] = 'urlEncoded'; - break; - - case 'urlReplacement': - // sect 4.7 - // http:urlReplacement attributes: location - // parent: wsdl:input wsdl:output etc. - $this->wsdl->bindings[$this->currentBinding]['operations'][$this->opStatus] - [$this->currentOperation]['uri'] = 'urlReplacement'; - break; - - case 'documentation': - break; - - default: - // error - break; - } - - case SCHEMA_MIME: - // sect 5 - // all mime parts are children of wsdl:input, wsdl:output, etc. - // unsuported as of yet - switch ($qname->name) { - case 'content': - // sect 5.3 mime:content - // - // part attribute only required if content is child of multipart related, - // it contains the name of the part - // type attribute contains the mime type - case 'multipartRelated': - // sect 5.4 mime:multipartRelated - case 'part': - case 'mimeXml': - // sect 5.6 mime:mimeXml - // - // - case 'documentation': - break; - - default: - // error - break; - } - - case SCHEMA_DIME: - // DIME is defined in: - // http://gotdotnet.com/team/xml_wsspecs/dime/WSDL-Extension-for-DIME.htm - // all DIME parts are children of wsdl:input, wsdl:output, etc. - // unsuported as of yet - switch ($qname->name) { - case 'message': - // sect 4.1 dime:message - // appears in binding section - $this->wsdl->bindings[$this->currentBinding]['dime'] = $attrs; - break; - - default: - break; - } - - default: - break; - } - break; - - case 'service': - $ns = $qname->ns ? $this->wsdl->namespaces[$qname->ns] : SCHEMA_WSDL; - - switch ($qname->name) { - case 'port': - // sect 2.6 wsdl:port attributes: name binding - $this->currentPort = $attrs['name']; - $this->wsdl->services[$this->currentService]['ports'][$this->currentPort] = $attrs; - // XXX hack to deal with binding namespaces - $qn = new QName($attrs['binding']); - $this->wsdl->services[$this->currentService]['ports'][$this->currentPort]['binding'] = $qn->name; - $this->wsdl->services[$this->currentService]['ports'][$this->currentPort]['namespace'] = $qn->ns; - break; - - case 'address': - $this->wsdl->services[$this->currentService]['ports'][$this->currentPort]['address'] = $attrs; - // what TYPE of port is it? SOAP or HTTP? - $ns = $qname->ns ? $this->wsdl->namespaces[$qname->ns] : SCHEMA_WSDL; - switch ($ns) { - case SCHEMA_WSDL_HTTP: - $this->wsdl->services[$this->currentService]['ports'][$this->currentPort]['type']='http'; - break; - - case SCHEMA_SOAP: - $this->wsdl->services[$this->currentService]['ports'][$this->currentPort]['type']='soap'; - break; - - default: - // Shouldn't happen, we'll assume SOAP. - $this->wsdl->services[$this->currentService]['ports'][$this->currentPort]['type']='soap'; - } - - break; - - case 'documentation': - break; - - default: - break; - } - } - - // Top level elements found under wsdl:definitions. - switch ($qname->name) { - case 'import': - // sect 2.1.1 wsdl:import attributes: namespace location - if ((isset($attrs['location']) || isset($attrs['schemaLocation'])) && - !isset($this->wsdl->imports[$attrs['namespace']])) { - $uri = isset($attrs['location']) ? $attrs['location'] : $attrs['schemaLocation']; - $location = @parse_url($uri); - if (!isset($location['scheme'])) { - $base = @parse_url($this->uri); - $uri = $this->mergeUrl($base, $uri); - } - - $this->wsdl->imports[$attrs['namespace']] = $attrs; - $import_parser_class = get_class($this); - $import_parser = new $import_parser_class($uri, $this->wsdl, $this->docs); - if ($import_parser->fault) { - unset($this->wsdl->imports[$attrs['namespace']]); - return false; - } - $this->currentImport = $attrs['namespace']; - } - // Continue on to the 'types' case - lack of break; is - // intentional. - - case 'types': - // sect 2.2 wsdl:types - $this->status = 'types'; - break; - - case 'schema': - // We can hit this at the top level if we've been asked to - // import an XSD file. - if (!empty($attrs['targetNamespace'])) { - $this->schema = $this->wsdl->getNamespaceAttributeName($attrs['targetNamespace']); - } else { - $this->schema = $this->wsdl->getNamespaceAttributeName($this->wsdl->tns); - } - $this->wsdl->complexTypes[$this->schema] = array(); - $this->wsdl->elements[$this->schema] = array(); - $this->schema_stack[] = $qname->name; - $this->status = 'types'; - break; - - case 'message': - // sect 2.3 wsdl:message attributes: name children:wsdl:part - $this->status = 'message'; - if (isset($attrs['name'])) { - $this->currentMessage = $attrs['name']; - $this->wsdl->messages[$this->currentMessage] = array(); - } - break; - - case 'portType': - // sect 2.4 wsdl:portType - // attributes: name - // children: wsdl:operation - $this->status = 'portType'; - $this->currentPortType = $attrs['name']; - $this->wsdl->portTypes[$this->currentPortType] = array(); - break; - - case 'binding': - // sect 2.5 wsdl:binding attributes: name type - // children: wsdl:operation soap:binding http:binding - if ($qname->ns && $qname->ns != $this->tns) { - break; - } - $this->status = 'binding'; - $this->currentBinding = $attrs['name']; - $qn = new QName($attrs['type']); - $this->wsdl->bindings[$this->currentBinding]['type'] = $qn->name; - $this->wsdl->bindings[$this->currentBinding]['namespace'] = $qn->ns; - break; - - case 'service': - // sect 2.7 wsdl:service attributes: name children: ports - $this->currentService = $attrs['name']; - $this->wsdl->services[$this->currentService]['ports'] = array(); - $this->status = 'service'; - break; - - case 'definitions': - // sec 2.1 wsdl:definitions - // attributes: name targetNamespace xmlns:* - // children: wsdl:import wsdl:types wsdl:message wsdl:portType wsdl:binding wsdl:service - $this->wsdl->definition = $attrs; - foreach ($attrs as $key => $value) { - if (strstr($key, 'xmlns:') !== false) { - $qn = new QName($key); - // XXX need to refactor ns handling. - $this->wsdl->namespaces[$qn->name] = $value; - $this->wsdl->ns[$value] = $qn->name; - if ($key == 'targetNamespace' || - strcasecmp($value,SOAP_SCHEMA) == 0) { - $this->soapns[] = $qn->name; - } else { - if (in_array($value, $this->_XMLSchema)) { - $this->wsdl->xsd = $value; - } - } - } - } - if (isset($ns) && $ns) { - $namespace = 'xmlns:' . $ns; - if (!$this->wsdl->definition[$namespace]) { - return $this->_raiseSoapFault("parse error, no namespace for $namespace", $this->uri); - } - $this->tns = $ns; - } - break; - } - } - - /** - * end-element handler. - */ - function endElement($parser, $name) - { - $stacksize = count($this->element_stack); - if ($stacksize) { - if ($this->element_stack[$stacksize - 1] == 'definitions') { - $this->status = ''; - } - array_pop($this->element_stack); - } - - if (stristr($name, 'schema')) { - array_pop($this->schema_stack); - $this->schema = ''; - } - - if ($this->schema) { - array_pop($this->schema_stack); - if (count($this->schema_stack) <= 1) { - /* Correct the type for sequences with multiple - * elements. */ - if (isset($this->currentComplexType) && isset($this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type']) - && $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] == 'Array' - && array_key_exists('elements', $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]) - && count($this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['elements']) > 1) { - $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['type'] = 'Struct'; - } - } - if (stristr($name, 'complexType')) { - $this->currentComplexType = ''; - if (count($this->schema_element_stack)) { - $this->currentElement = array_pop($this->schema_element_stack); - } else { - $this->currentElement = ''; - } - } elseif (stristr($name, 'element')) { - if (count($this->schema_element_stack)) { - $this->currentElement = array_pop($this->schema_element_stack); - } else { - $this->currentElement = ''; - } - } - } - } - - /** - * Element content handler. - */ - function characterData($parser, $data) - { - // Store the documentation in the WSDL file. - if ($this->currentTag == 'documentation') { - $data = trim(preg_replace('/\s+/', ' ', $data)); - if (!strlen($data)) { - return; - } - - switch ($this->status) { - case 'service': - $ptr =& $this->wsdl->services[$this->currentService]; - break; - - case 'portType': - $ptr =& $this->wsdl->portTypes[$this->currentPortType][$this->currentOperation]; - break; - - case 'binding': - $ptr =& $this->wsdl->bindings[$this->currentBinding]; - break; - - case 'message': - $ptr =& $this->wsdl->messages[$this->currentMessage]; - break; - - case 'operation': - break; - - case 'types': - if (isset($this->currentComplexType) && - isset($this->wsdl->complexTypes[$this->schema][$this->currentComplexType])) { - if ($this->currentElement) { - $ptr =& $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]['elements'][$this->currentElement]; - } else { - $ptr =& $this->wsdl->complexTypes[$this->schema][$this->currentComplexType]; - } - } - break; - } - - if (isset($ptr)) { - if (!isset($ptr['documentation'])) { - $ptr['documentation'] = ''; - } else { - $ptr['documentation'] .= ' '; - } - $ptr['documentation'] .= $data; - } - } - } - - /** - * $parsed is an array returned by parse_url(). - * - * @access private - */ - function mergeUrl($parsed, $path) - { - if (!is_array($parsed)) { - return false; - } - - $uri = ''; - if (!empty($parsed['scheme'])) { - $sep = (strtolower($parsed['scheme']) == 'mailto' ? ':' : '://'); - $uri = $parsed['scheme'] . $sep; - } - - if (isset($parsed['pass'])) { - $uri .= "$parsed[user]:$parsed[pass]@"; - } elseif (isset($parsed['user'])) { - $uri .= "$parsed[user]@"; - } - - if (isset($parsed['host'])) { - $uri .= $parsed['host']; - } - if (isset($parsed['port'])) { - $uri .= ":$parsed[port]"; - } - if ($path[0] != '/' && isset($parsed['path'])) { - if ($parsed['path'][strlen($parsed['path']) - 1] != '/') { - $path = dirname($parsed['path']) . '/' . $path; - } else { - $path = $parsed['path'] . $path; - } - $path = $this->_normalize($path); - } - $sep = $path[0] == '/' ? '' : '/'; - $uri .= $sep . $path; - - return $uri; - } - - function _normalize($path_str) - { - $pwd = ''; - $strArr = preg_split('/(\/)/', $path_str, -1, PREG_SPLIT_NO_EMPTY); - $pwdArr = ''; - $j = 0; - for ($i = 0; $i < count($strArr); $i++) { - if ($strArr[$i] != ' ..') { - if ($strArr[$i] != ' .') { - $pwdArr[$j] = $strArr[$i]; - $j++; - } - } else { - array_pop($pwdArr); - $j--; - } - } - $pStr = implode('/', $pwdArr); - $pwd = (strlen($pStr) > 0) ? ('/' . $pStr) : '/'; - return $pwd; - } - -} - -/** - * Parses the types and methods used in web service objects into the internal - * data structures used by SOAP_WSDL. - * - * Assumes the SOAP_WSDL class is unpopulated to start with. - * - * @author Chris Coe - */ -class SOAP_WSDL_ObjectParser extends SOAP_Base -{ - /** - * Target namespace for the WSDL document will have the following - * prefix. - */ - var $tnsPrefix = 'tns'; - - /** - * Reference to the SOAP_WSDL object to populate. - */ - var $wsdl = null; - - /** - * Constructor. - * - * @param object|array $objects Reference to the object or array of - * objects to parse. - * @param SOAP_WSDL $wsdl Reference to the SOAP_WSDL object to - * populate. - * @param string $targetNamespace The target namespace of schema types - * etc. - * @param string $service_name Name of the WSDL . - * @param string $service_desc Optional description of the WSDL - * . - */ - function SOAP_WSDL_ObjectParser(&$objects, &$wsdl, $targetNamespace, - $service_name, $service_desc = '') - { - parent::SOAP_Base('WSDLOBJECTPARSER'); - - $this->wsdl = &$wsdl; - - // Set up the SOAP_WSDL object - $this->_initialise($service_name); - - // Parse each web service object - $wsdl_ref = (is_array($objects)? $objects : array(&$objects)); - - foreach ($wsdl_ref as $ref_item) { - if (!is_object($ref_item)) { - $this->_raiseSoapFault('Invalid web service object passed to object parser'); - continue; - } - - if (!$this->_parse($ref_item, $targetNamespace, $service_name)) { - break; - } - } - - // Build bindings from abstract data. - if ($this->fault == null) { - $this->_generateBindingsAndServices($targetNamespace, $service_name, $service_desc); - } - } - - /** - * Initialise the SOAP_WSDL tree (destructive). - * - * If the object has already been initialised, the only effect - * will be to change the tns namespace to the new service name. - * - * @param $service_name Name of the WSDL - * @access private - */ - function _initialise($service_name) - { - // Set up the basic namespaces that all WSDL definitions use. - $this->wsdl->namespaces['wsdl'] = SCHEMA_WSDL; // WSDL language - $this->wsdl->namespaces['soap'] = SCHEMA_SOAP; // WSDL SOAP bindings - $this->wsdl->namespaces[$this->tnsPrefix] = 'urn:' . $service_name; // Target namespace - $this->wsdl->namespaces['xsd'] = array_search('xsd', $this->_namespaces); // XML Schema - $this->wsdl->namespaces['SOAP-ENC'] = array_search('SOAP-ENC', $this->_namespaces); // SOAP types - - // XXX Refactor $namespace/$ns for Shane :-) - unset($this->wsdl->ns['urn:' . $service_name]); - $this->wsdl->ns += array_flip($this->wsdl->namespaces); - - // Imports are not implemented in WSDL generation from classes. - // *** *** - } - - /** - * Parser - takes a single object to add to tree (non-destructive). - * - * @access private - * - * @param object $object Reference to the object to parse. - * @param string $schemaNamespace - * @param string $service_name Name of the WSDL . - */ - function _parse(&$object, $schemaNamespace, $service_name) - { - // Create namespace prefix for the schema - list($schPrefix,) = $this->_getTypeNs('{' . $schemaNamespace . '}'); - - // Parse all the types defined by the object in whatever - // schema language we are using (currently __typedef arrays) - // *** *** - foreach ($object->__typedef as $typeName => $typeValue) { - // Get/create namespace definition - list($nsPrefix, $typeName) = $this->_getTypeNs($typeName); - - // Create type definition - $this->wsdl->complexTypes[$schPrefix][$typeName] = array('name' => $typeName); - $thisType =& $this->wsdl->complexTypes[$schPrefix][$typeName]; - - // According to Dmitri's documentation, __typedef comes in two - // flavors: - // Array = array(array("item" => "value")) - // Struct = array("item1" => "value1", "item2" => "value2", ...) - if (is_array($typeValue)) { - if (is_array(current($typeValue)) && count($typeValue) == 1 - && count(current($typeValue)) == 1) { - // It's an array - $thisType['type'] = 'Array'; - $nsType = current(current($typeValue)); - list($nsPrefix, $typeName) = $this->_getTypeNs($nsType); - $thisType['namespace'] = $nsPrefix; - $thisType['arrayType'] = $typeName . '[]'; - } elseif (!is_array(current($typeValue))) { - // It's a struct - $thisType['type'] = 'Struct'; - $thisType['order'] = 'all'; - $thisType['namespace'] = $nsPrefix; - $thisType['elements'] = array(); - - foreach ($typeValue as $elementName => $elementType) { - list($nsPrefix, $typeName) = $this->_getTypeNs($elementType); - $thisType['elements'][$elementName]['name'] = $elementName; - $thisType['elements'][$elementName]['type'] = $typeName; - $thisType['elements'][$elementName]['namespace'] = $nsPrefix; - } - } else { - // It's erroneous - return $this->_raiseSoapFault("The type definition for $nsPrefix:$typeName is invalid.", 'urn:' . get_class($object)); - } - } else { - // It's erroneous - return $this->_raiseSoapFault("The type definition for $nsPrefix:$typeName is invalid.", 'urn:' . get_class($object)); - } - } - - // Create an empty element array with the target namespace - // prefix, to match the results of WSDL parsing. - $this->wsdl->elements[$schPrefix] = array(); - - // Populate tree with message information - // *** *** - foreach ($object->__dispatch_map as $operationName => $messages) { - foreach ($messages as $messageType => $messageParts) { - unset($thisMessage); - - switch ($messageType) { - case 'in': - $this->wsdl->messages[$operationName . 'Request'] = array(); - $thisMessage =& $this->wsdl->messages[$operationName . 'Request']; - break; - - case 'out': - $this->wsdl->messages[$operationName . 'Response'] = array(); - $thisMessage =& $this->wsdl->messages[$operationName . 'Response']; - break; - - case 'alias': - // Do nothing - break; - - default: - // Error condition - break; - } - - if (isset($thisMessage)) { - foreach ($messageParts as $partName => $partType) { - list ($nsPrefix, $typeName) = $this->_getTypeNs($partType); - - $thisMessage[$partName] = array( - 'name' => $partName, - 'type' => $typeName, - 'namespace' => $nsPrefix - ); - } - } - } - } - - // Populate tree with portType information - // XXX Current implementation only supports one portType that - // encompasses all of the operations available. - // *** *** - if (!isset($this->wsdl->portTypes[$service_name . 'Port'])) { - $this->wsdl->portTypes[$service_name . 'Port'] = array(); - } - $thisPortType =& $this->wsdl->portTypes[$service_name . 'Port']; - - foreach ($object->__dispatch_map as $operationName => $messages) { - $thisPortType[$operationName] = array('name' => $operationName); - - foreach ($messages as $messageType => $messageParts) { - switch ($messageType) { - case 'in': - $thisPortType[$operationName]['input'] = array( - 'message' => $operationName . 'Request', - 'namespace' => $this->tnsPrefix); - break; - - case 'out': - $thisPortType[$operationName]['output'] = array( - 'message' => $operationName . 'Response', - 'namespace' => $this->tnsPrefix); - break; - } - } - } - - return true; - } - - /** - * Takes all the abstract WSDL data and builds concrete bindings and - * services (destructive). - * - * @access private - * @todo Current implementation discards $service_desc. - * - * @param string $schemaNamespace Namespace for types etc. - * @param string $service_name Name of the WSDL . - * @param string $service_desc Optional description of the WSDL - * . - */ - function _generateBindingsAndServices($schemaNamespace, $service_name, - $service_desc = '') - { - // Populate tree with bindings information - // XXX Current implementation only supports one binding that - // matches the single portType and all of its operations. - // XXX Is this the correct use of $schemaNamespace here? - // *** *** - $this->wsdl->bindings[$service_name . 'Binding'] = array( - 'type' => $service_name . 'Port', - 'namespace' => $this->tnsPrefix, - 'style' => 'rpc', - 'transport' => SCHEMA_SOAP_HTTP, - 'operations' => array()); - $thisBinding =& $this->wsdl->bindings[$service_name . 'Binding']; - - foreach ($this->wsdl->portTypes[$service_name . 'Port'] as $operationName => $operationData) { - $thisBinding['operations'][$operationName] = array( - 'soapAction' => $schemaNamespace . '#' . $operationName, - 'style' => $thisBinding['style']); - - foreach (array('input', 'output') as $messageType) - if (isset($operationData[$messageType])) { - $thisBinding['operations'][$operationName][$messageType] = array( - 'use' => 'encoded', - 'namespace' => $schemaNamespace, - 'encodingStyle' => SOAP_SCHEMA_ENCODING); - } - } - - // Populate tree with service information - // XXX Current implementation supports one service which groups - // all of the ports together, one port per binding - // *** *** - - $this->wsdl->services[$service_name . 'Service'] = array('ports' => array()); - $thisService =& $this->wsdl->services[$service_name . 'Service']['ports']; - $https = (isset($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] == 'on')) || - getenv('SSL_PROTOCOL_VERSION'); - - foreach ($this->wsdl->bindings as $bindingName => $bindingData) { - $thisService[$bindingData['type']] = array( - 'name' => $bindingData['type'], - 'binding' => $bindingName, - 'namespace' => $this->tnsPrefix, - 'address' => array('location' => - ($https ? 'https://' : 'http://') . - $_SERVER['SERVER_NAME'] . $_SERVER['PHP_SELF'] . - (isset($_SERVER['QUERY_STRING']) ? '?' . $_SERVER['QUERY_STRING'] : '')), - 'type' => 'soap'); - } - - // Set service - $this->wsdl->set_service($service_name . 'Service'); - $this->wsdl->uri = $this->wsdl->namespaces[$this->tnsPrefix]; - - // Create WSDL definition - // *** *** - - $this->wsdl->definition = array( - 'name' => $service_name, - 'targetNamespace' => $this->wsdl->namespaces[$this->tnsPrefix], - 'xmlns' => SCHEMA_WSDL); - - foreach ($this->wsdl->namespaces as $nsPrefix => $namespace) { - $this->wsdl->definition['xmlns:' . $nsPrefix] = $namespace; - } - } - - /** - * This function is adapted from Dmitri V's implementation of - * DISCO/WSDL generation. It separates namespace from type name in - * a __typedef key and creates a new namespace entry in the WSDL - * structure if the namespace has not been used before. The - * namespace prefix and type name are returned. If no namespace is - * specified, xsd is assumed. - * - * We will not need this function anymore once __typedef is - * eliminated. - */ - function _getTypeNs($type) - { - preg_match_all('/\{(.*)\}/sm', $type, $m); - if (!empty($m[1][0])) { - if (!isset($this->wsdl->ns[$m[1][0]])) { - $ns_pref = 'ns' . count($this->wsdl->namespaces); - $this->wsdl->ns[$m[1][0]] = $ns_pref; - $this->wsdl->namespaces[$ns_pref] = $m[1][0]; - } - $typens = $this->wsdl->ns[$m[1][0]]; - $type = str_replace($m[0][0], '', $type); - } else { - $typens = 'xsd'; - } - - return array($typens, $type); - } - -} diff --git a/gulliver/thirdparty/pear/SOAP/tools/genproxy.php b/gulliver/thirdparty/pear/SOAP/tools/genproxy.php deleted file mode 100644 index 8a334e1ef..000000000 --- a/gulliver/thirdparty/pear/SOAP/tools/genproxy.php +++ /dev/null @@ -1,21 +0,0 @@ - foo.php - * - */ - -function do_wsdl($uri) { - $wsdl =& new SOAP_WSDL($uri); - print $wsdl->generateAllProxies(); -} -echo ""; -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer.php b/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer.php deleted file mode 100644 index eda612035..000000000 --- a/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer.php +++ /dev/null @@ -1,104 +0,0 @@ - -* -* PERL Spreadsheet::WriteExcel module. -* -* The author of the Spreadsheet::WriteExcel module is John McNamara -* -* -* I _DO_ maintain this code, and John McNamara has nothing to do with the -* porting of this code to PHP. Any questions directly related to this -* class library should be directed to me. -* -* License Information: -* -* Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets -* Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com -* -* 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 -*/ - -require_once('PEAR.php'); -require_once('Spreadsheet/Excel/Writer/Workbook.php'); - -/** -* Class for writing Excel Spreadsheets. This class should change COMPLETELY. -* -* @author Xavier Noguer -* @category FileFormats -* @package Spreadsheet_Excel_Writer -*/ - -class Spreadsheet_Excel_Writer extends Spreadsheet_Excel_Writer_Workbook -{ - /** - * The constructor. It just creates a Workbook - * - * @param string $filename The optional filename for the Workbook. - * @return Spreadsheet_Excel_Writer_Workbook The Workbook created - */ - function Spreadsheet_Excel_Writer($filename = '') - { - $this->_filename = $filename; - $this->Spreadsheet_Excel_Writer_Workbook($filename); - } - - /** - * Send HTTP headers for the Excel file. - * - * @param string $filename The filename to use for HTTP headers - * @access public - */ - function send($filename) - { - header("Content-type: application/vnd.ms-excel"); - header("Content-Disposition: attachment; filename=$filename"); - header("Expires: 0"); - header("Cache-Control: must-revalidate, post-check=0,pre-check=0"); - header("Pragma: public"); - } - - /** - * Utility function for writing formulas - * Converts a cell's coordinates to the A1 format. - * - * @access public - * @static - * @param integer $row Row for the cell to convert (0-indexed). - * @param integer $col Column for the cell to convert (0-indexed). - * @return string The cell identifier in A1 format - */ - function rowcolToCell($row, $col) - { - if ($col > 255) { //maximum column value exceeded - return new PEAR_Error("Maximum column value exceeded: $col"); - } - - $int = (int)($col / 26); - $frac = $col % 26; - $chr1 = ''; - - if ($int > 0) { - $chr1 = chr(ord('A') + $int - 1); - } - - $chr2 = chr(ord('A') + $frac); - $row++; - - return $chr1.$chr2.$row; - } -} -?> diff --git a/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer.php.bk b/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer.php.bk deleted file mode 100644 index eda612035..000000000 --- a/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer.php.bk +++ /dev/null @@ -1,104 +0,0 @@ - -* -* PERL Spreadsheet::WriteExcel module. -* -* The author of the Spreadsheet::WriteExcel module is John McNamara -* -* -* I _DO_ maintain this code, and John McNamara has nothing to do with the -* porting of this code to PHP. Any questions directly related to this -* class library should be directed to me. -* -* License Information: -* -* Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets -* Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com -* -* 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 -*/ - -require_once('PEAR.php'); -require_once('Spreadsheet/Excel/Writer/Workbook.php'); - -/** -* Class for writing Excel Spreadsheets. This class should change COMPLETELY. -* -* @author Xavier Noguer -* @category FileFormats -* @package Spreadsheet_Excel_Writer -*/ - -class Spreadsheet_Excel_Writer extends Spreadsheet_Excel_Writer_Workbook -{ - /** - * The constructor. It just creates a Workbook - * - * @param string $filename The optional filename for the Workbook. - * @return Spreadsheet_Excel_Writer_Workbook The Workbook created - */ - function Spreadsheet_Excel_Writer($filename = '') - { - $this->_filename = $filename; - $this->Spreadsheet_Excel_Writer_Workbook($filename); - } - - /** - * Send HTTP headers for the Excel file. - * - * @param string $filename The filename to use for HTTP headers - * @access public - */ - function send($filename) - { - header("Content-type: application/vnd.ms-excel"); - header("Content-Disposition: attachment; filename=$filename"); - header("Expires: 0"); - header("Cache-Control: must-revalidate, post-check=0,pre-check=0"); - header("Pragma: public"); - } - - /** - * Utility function for writing formulas - * Converts a cell's coordinates to the A1 format. - * - * @access public - * @static - * @param integer $row Row for the cell to convert (0-indexed). - * @param integer $col Column for the cell to convert (0-indexed). - * @return string The cell identifier in A1 format - */ - function rowcolToCell($row, $col) - { - if ($col > 255) { //maximum column value exceeded - return new PEAR_Error("Maximum column value exceeded: $col"); - } - - $int = (int)($col / 26); - $frac = $col % 26; - $chr1 = ''; - - if ($int > 0) { - $chr1 = chr(ord('A') + $int - 1); - } - - $chr2 = chr(ord('A') + $frac); - $row++; - - return $chr1.$chr2.$row; - } -} -?> diff --git a/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer/BIFFwriter.php b/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer/BIFFwriter.php deleted file mode 100644 index 1f700dfb5..000000000 --- a/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer/BIFFwriter.php +++ /dev/null @@ -1,241 +0,0 @@ - -* -* The majority of this is _NOT_ my code. I simply ported it from the -* PERL Spreadsheet::WriteExcel module. -* -* The author of the Spreadsheet::WriteExcel module is John McNamara -* -* -* I _DO_ maintain this code, and John McNamara has nothing to do with the -* porting of this code to PHP. Any questions directly related to this -* class library should be directed to me. -* -* License Information: -* -* Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets -* Copyright (c) 2002-2003 Xavier Noguer xnoguer@php.net -* -* 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 -*/ - -require_once('PEAR.php'); - -/** -* Class for writing Excel BIFF records. -* -* From "MICROSOFT EXCEL BINARY FILE FORMAT" by Mark O'Brien (Microsoft Corporation): -* -* BIFF (BInary File Format) is the file format in which Excel documents are -* saved on disk. A BIFF file is a complete description of an Excel document. -* BIFF files consist of sequences of variable-length records. There are many -* different types of BIFF records. For example, one record type describes a -* formula entered into a cell; one describes the size and location of a -* window into a document; another describes a picture format. -* -* @author Xavier Noguer -* @category FileFormats -* @package Spreadsheet_Excel_Writer -*/ - -class Spreadsheet_Excel_Writer_BIFFwriter extends PEAR -{ - /** - * The BIFF/Excel version (5). - * @var integer - */ - var $_BIFF_version = 0x0500; - - /** - * The byte order of this architecture. 0 => little endian, 1 => big endian - * @var integer - */ - var $_byte_order; - - /** - * The string containing the data of the BIFF stream - * @var string - */ - var $_data; - - /** - * The size of the data in bytes. Should be the same as strlen($this->_data) - * @var integer - */ - var $_datasize; - - /** - * The maximun length for a BIFF record. See _addContinue() - * @var integer - * @see _addContinue() - */ - var $_limit; - - /** - * Constructor - * - * @access public - */ - function Spreadsheet_Excel_Writer_BIFFwriter() - { - $this->_byte_order = ''; - $this->_data = ''; - $this->_datasize = 0; - $this->_limit = 2080; - // Set the byte order - $this->_setByteOrder(); - } - - /** - * Determine the byte order and store it as class data to avoid - * recalculating it for each call to new(). - * - * @access private - */ - function _setByteOrder() - { - // Check if "pack" gives the required IEEE 64bit float - $teststr = pack("d", 1.2345); - $number = pack("C8", 0x8D, 0x97, 0x6E, 0x12, 0x83, 0xC0, 0xF3, 0x3F); - if ($number == $teststr) { - $byte_order = 0; // Little Endian - } - elseif ($number == strrev($teststr)){ - $byte_order = 1; // Big Endian - } - else { - // Give up. I'll fix this in a later version. - return $this->raiseError("Required floating point format ". - "not supported on this platform."); - } - $this->_byte_order = $byte_order; - } - - /** - * General storage function - * - * @param string $data binary data to prepend - * @access private - */ - function _prepend($data) - { - if (strlen($data) > $this->_limit) { - $data = $this->_addContinue($data); - } - $this->_data = $data.$this->_data; - $this->_datasize += strlen($data); - } - - /** - * General storage function - * - * @param string $data binary data to append - * @access private - */ - function _append($data) - { - if (strlen($data) > $this->_limit) { - $data = $this->_addContinue($data); - } - $this->_data = $this->_data.$data; - $this->_datasize += strlen($data); - } - - /** - * Writes Excel BOF record to indicate the beginning of a stream or - * sub-stream in the BIFF file. - * - * @param integer $type Type of BIFF file to write: 0x0005 Workbook, - * 0x0010 Worksheet. - * @access private - */ - function _storeBof($type) - { - $record = 0x0809; // Record identifier - - // According to the SDK $build and $year should be set to zero. - // However, this throws a warning in Excel 5. So, use magic numbers. - if ($this->_BIFF_version == 0x0500) { - $length = 0x0008; - $unknown = ''; - $build = 0x096C; - $year = 0x07C9; - } - elseif ($this->_BIFF_version == 0x0600) { - $length = 0x0010; - $unknown = pack("VV", 0x00000041, 0x00000006); //unknown last 8 bytes for BIFF8 - $build = 0x0DBB; - $year = 0x07CC; - } - $version = $this->_BIFF_version; - - $header = pack("vv", $record, $length); - $data = pack("vvvv", $version, $type, $build, $year); - $this->_prepend($header.$data.$unknown); - } - - /** - * Writes Excel EOF record to indicate the end of a BIFF stream. - * - * @access private - */ - function _storeEof() - { - $record = 0x000A; // Record identifier - $length = 0x0000; // Number of bytes to follow - $header = pack("vv", $record, $length); - $this->_append($header); - } - - /** - * Excel limits the size of BIFF records. In Excel 5 the limit is 2084 bytes. In - * Excel 97 the limit is 8228 bytes. Records that are longer than these limits - * must be split up into CONTINUE blocks. - * - * This function takes a long BIFF record and inserts CONTINUE records as - * necessary. - * - * @param string $data The original binary data to be written - * @return string A very convenient string of continue blocks - * @access private - */ - function _addContinue($data) - { - $limit = $this->_limit; - $record = 0x003C; // Record identifier - - // The first 2080/8224 bytes remain intact. However, we have to change - // the length field of the record. - $tmp = substr($data, 0, 2).pack("v", $limit-4).substr($data, 4, $limit - 4); - - $header = pack("vv", $record, $limit); // Headers for continue records - - // Retrieve chunks of 2080/8224 bytes +4 for the header. - for($i = $limit; $i < strlen($data) - $limit; $i += $limit) - { - $tmp .= $header; - $tmp .= substr($data, $i, $limit); - } - - // Retrieve the last chunk of data - $header = pack("vv", $record, strlen($data) - $i); - $tmp .= $header; - $tmp .= substr($data,$i,strlen($data) - $i); - - return $tmp; - } -} -?> diff --git a/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer/Format.php b/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer/Format.php deleted file mode 100644 index 788d25bb8..000000000 --- a/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer/Format.php +++ /dev/null @@ -1,1035 +0,0 @@ - -* -* The majority of this is _NOT_ my code. I simply ported it from the -* PERL Spreadsheet::WriteExcel module. -* -* The author of the Spreadsheet::WriteExcel module is John McNamara -* -* -* I _DO_ maintain this code, and John McNamara has nothing to do with the -* porting of this code to PHP. Any questions directly related to this -* class library should be directed to me. -* -* License Information: -* -* Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets -* Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com -* -* 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 -*/ - -require_once('PEAR.php'); - -/** -* Class for generating Excel XF records (formats) -* -* @author Xavier Noguer -* @category FileFormats -* @package Spreadsheet_Excel_Writer -*/ - -class Spreadsheet_Excel_Writer_Format extends PEAR -{ - /** - * The index given by the workbook when creating a new format. - * @var integer - */ - var $_xf_index; - - /** - * Index to the FONT record. - * @var integer - */ - var $font_index; - - /** - * The font name (ASCII). - * @var string - */ - var $_font_name; - - /** - * Height of font (1/20 of a point) - * @var integer - */ - var $_size; - - /** - * Bold style - * @var integer - */ - var $_bold; - - /** - * Bit specifiying if the font is italic. - * @var integer - */ - var $_italic; - - /** - * Index to the cell's color - * @var integer - */ - var $_color; - - /** - * The text underline property - * @var integer - */ - var $_underline; - - /** - * Bit specifiying if the font has strikeout. - * @var integer - */ - var $_font_strikeout; - - /** - * Bit specifiying if the font has outline. - * @var integer - */ - var $_font_outline; - - /** - * Bit specifiying if the font has shadow. - * @var integer - */ - var $_font_shadow; - - /** - * 2 bytes specifiying the script type for the font. - * @var integer - */ - var $_font_script; - - /** - * Byte specifiying the font family. - * @var integer - */ - var $_font_family; - - /** - * Byte specifiying the font charset. - * @var integer - */ - var $_font_charset; - - /** - * An index (2 bytes) to a FORMAT record (number format). - * @var integer - */ - var $_num_format; - - /** - * Bit specifying if formulas are hidden. - * @var integer - */ - var $_hidden; - - /** - * Bit specifying if the cell is locked. - * @var integer - */ - var $_locked; - - /** - * The three bits specifying the text horizontal alignment. - * @var integer - */ - var $_text_h_align; - - /** - * Bit specifying if the text is wrapped at the right border. - * @var integer - */ - var $_text_wrap; - - /** - * The three bits specifying the text vertical alignment. - * @var integer - */ - var $_text_v_align; - - /** - * 1 bit, apparently not used. - * @var integer - */ - var $_text_justlast; - - /** - * The two bits specifying the text rotation. - * @var integer - */ - var $_rotation; - - /** - * The cell's foreground color. - * @var integer - */ - var $_fg_color; - - /** - * The cell's background color. - * @var integer - */ - var $_bg_color; - - /** - * The cell's background fill pattern. - * @var integer - */ - var $_pattern; - - /** - * Style of the bottom border of the cell - * @var integer - */ - var $_bottom; - - /** - * Color of the bottom border of the cell. - * @var integer - */ - var $_bottom_color; - - /** - * Style of the top border of the cell - * @var integer - */ - var $_top; - - /** - * Color of the top border of the cell. - * @var integer - */ - var $_top_color; - - /** - * Style of the left border of the cell - * @var integer - */ - var $_left; - - /** - * Color of the left border of the cell. - * @var integer - */ - var $_left_color; - - /** - * Style of the right border of the cell - * @var integer - */ - var $_right; - - /** - * Color of the right border of the cell. - * @var integer - */ - var $_right_color; - - /** - * Constructor - * - * @access private - * @param integer $index the XF index for the format. - * @param array $properties array with properties to be set on initialization. - */ - function Spreadsheet_Excel_Writer_Format($BIFF_version, $index = 0, $properties = array()) - { - $this->_xf_index = $index; - $this->_BIFF_version = $BIFF_version; - $this->font_index = 0; - $this->_font_name = 'Arial'; - $this->_size = 10; - $this->_bold = 0x0190; - $this->_italic = 0; - $this->_color = 0x7FFF; - $this->_underline = 0; - $this->_font_strikeout = 0; - $this->_font_outline = 0; - $this->_font_shadow = 0; - $this->_font_script = 0; - $this->_font_family = 0; - $this->_font_charset = 0; - - $this->_num_format = 0; - - $this->_hidden = 0; - $this->_locked = 0; - - $this->_text_h_align = 0; - $this->_text_wrap = 0; - $this->_text_v_align = 2; - $this->_text_justlast = 0; - $this->_rotation = 0; - - $this->_fg_color = 0x40; - $this->_bg_color = 0x41; - - $this->_pattern = 0; - - $this->_bottom = 0; - $this->_top = 0; - $this->_left = 0; - $this->_right = 0; - $this->_diag = 0; - - $this->_bottom_color = 0x40; - $this->_top_color = 0x40; - $this->_left_color = 0x40; - $this->_right_color = 0x40; - $this->_diag_color = 0x40; - - // Set properties passed to Spreadsheet_Excel_Writer_Workbook::addFormat() - foreach($properties as $property => $value) - { - if(method_exists($this,'set'.ucwords($property))) - { - $method_name = 'set'.ucwords($property); - $this->$method_name($value); - } - } - } - - - /** - * Generate an Excel BIFF XF record (style or cell). - * - * @param string $style The type of the XF record ('style' or 'cell'). - * @return string The XF record - */ - function getXf($style) - { - // Set the type of the XF record and some of the attributes. - if ($style == "style") { - $style = 0xFFF5; - } - else { - $style = $this->_locked; - $style |= $this->_hidden << 1; - } - - // Flags to indicate if attributes have been set. - $atr_num = ($this->_num_format != 0)?1:0; - $atr_fnt = ($this->font_index != 0)?1:0; - $atr_alc = ($this->_text_wrap)?1:0; - $atr_bdr = ($this->_bottom || - $this->_top || - $this->_left || - $this->_right)?1:0; - $atr_pat = (($this->_fg_color != 0x40) || - ($this->_bg_color != 0x41) || - $this->_pattern)?1:0; - $atr_prot = $this->_locked | $this->_hidden; - - // Zero the default border colour if the border has not been set. - if ($this->_bottom == 0) { - $this->_bottom_color = 0; - } - if ($this->_top == 0) { - $this->_top_color = 0; - } - if ($this->_right == 0) { - $this->_right_color = 0; - } - if ($this->_left == 0) { - $this->_left_color = 0; - } - if ($this->_diag == 0) { - $this->_diag_color = 0; - } - - $record = 0x00E0; // Record identifier - if ($this->_BIFF_version == 0x0500) { - $length = 0x0010; // Number of bytes to follow - } - if ($this->_BIFF_version == 0x0600) { - $length = 0x0014; - } - - $ifnt = $this->font_index; // Index to FONT record - $ifmt = $this->_num_format; // Index to FORMAT record - if ($this->_BIFF_version == 0x0500) - { - $align = $this->_text_h_align; // Alignment - $align |= $this->_text_wrap << 3; - $align |= $this->_text_v_align << 4; - $align |= $this->_text_justlast << 7; - $align |= $this->_rotation << 8; - $align |= $atr_num << 10; - $align |= $atr_fnt << 11; - $align |= $atr_alc << 12; - $align |= $atr_bdr << 13; - $align |= $atr_pat << 14; - $align |= $atr_prot << 15; - - $icv = $this->_fg_color; // fg and bg pattern colors - $icv |= $this->_bg_color << 7; - - $fill = $this->_pattern; // Fill and border line style - $fill |= $this->_bottom << 6; - $fill |= $this->_bottom_color << 9; - - $border1 = $this->_top; // Border line style and color - $border1 |= $this->_left << 3; - $border1 |= $this->_right << 6; - $border1 |= $this->_top_color << 9; - - $border2 = $this->_left_color; // Border color - $border2 |= $this->_right_color << 7; - - $header = pack("vv", $record, $length); - $data = pack("vvvvvvvv", $ifnt, $ifmt, $style, $align, - $icv, $fill, - $border1, $border2); - } - elseif ($this->_BIFF_version == 0x0600) - { - $align = $this->_text_h_align; // Alignment - $align |= $this->_text_wrap << 3; - $align |= $this->_text_v_align << 4; - $align |= $this->_text_justlast << 7; - - $used_attrib = $atr_num << 2; - $used_attrib |= $atr_fnt << 3; - $used_attrib |= $atr_alc << 4; - $used_attrib |= $atr_bdr << 5; - $used_attrib |= $atr_pat << 6; - $used_attrib |= $atr_prot << 7; - - $icv = $this->_fg_color; // fg and bg pattern colors - $icv |= $this->_bg_color << 7; - - $border1 = $this->_left; // Border line style and color - $border1 |= $this->_right << 4; - $border1 |= $this->_top << 8; - $border1 |= $this->_bottom << 12; - $border1 |= $this->_left_color << 16; - $border1 |= $this->_right_color << 23; - $diag_tl_to_rb = 0; // FIXME: add method - $diag_tr_to_lb = 0; // FIXME: add method - $border1 |= $diag_tl_to_rb << 30; - $border1 |= $diag_tr_to_lb << 31; - - $border2 = $this->_top_color; // Border color - $border2 |= $this->_bottom_color << 7; - $border2 |= $this->_diag_color << 14; - $border2 |= $this->_diag << 21; - $border2 |= $this->_pattern << 26; - - $header = pack("vv", $record, $length); - - $rotation = 0x00; - $biff8_options = 0x00; - $data = pack("vvvC", $ifnt, $ifmt, $style, $align); - $data .= pack("CCC", $rotation, $biff8_options, $used_attrib); - $data .= pack("VVv", $border1, $border2, $icv); - } - - return($header.$data); - } - - /** - * Generate an Excel BIFF FONT record. - * - * @return string The FONT record - */ - function getFont() - { - $dyHeight = $this->_size * 20; // Height of font (1/20 of a point) - $icv = $this->_color; // Index to color palette - $bls = $this->_bold; // Bold style - $sss = $this->_font_script; // Superscript/subscript - $uls = $this->_underline; // Underline - $bFamily = $this->_font_family; // Font family - $bCharSet = $this->_font_charset; // Character set - $encoding = 0; // TODO: Unicode support - - $cch = strlen($this->_font_name); // Length of font name - $record = 0x31; // Record identifier - if ($this->_BIFF_version == 0x0500) { - $length = 0x0F + $cch; // Record length - } - elseif ($this->_BIFF_version == 0x0600) { - $length = 0x10 + $cch; - } - $reserved = 0x00; // Reserved - $grbit = 0x00; // Font attributes - if ($this->_italic) { - $grbit |= 0x02; - } - if ($this->_font_strikeout) { - $grbit |= 0x08; - } - if ($this->_font_outline) { - $grbit |= 0x10; - } - if ($this->_font_shadow) { - $grbit |= 0x20; - } - - $header = pack("vv", $record, $length); - if ($this->_BIFF_version == 0x0500) { - $data = pack("vvvvvCCCCC", $dyHeight, $grbit, $icv, $bls, - $sss, $uls, $bFamily, - $bCharSet, $reserved, $cch); - } - elseif ($this->_BIFF_version == 0x0600) { - $data = pack("vvvvvCCCCCC", $dyHeight, $grbit, $icv, $bls, - $sss, $uls, $bFamily, - $bCharSet, $reserved, $cch, $encoding); - } - return($header . $data. $this->_font_name); - } - - /** - * Returns a unique hash key for a font. - * Used by Spreadsheet_Excel_Writer_Workbook::_storeAllFonts() - * - * The elements that form the key are arranged to increase the probability of - * generating a unique key. Elements that hold a large range of numbers - * (eg. _color) are placed between two binary elements such as _italic - * - * @return string A key for this font - */ - function getFontKey() - { - $key = "$this->_font_name$this->_size"; - $key .= "$this->_font_script$this->_underline"; - $key .= "$this->_font_strikeout$this->_bold$this->_font_outline"; - $key .= "$this->_font_family$this->_font_charset"; - $key .= "$this->_font_shadow$this->_color$this->_italic"; - $key = str_replace(" ","_",$key); - return ($key); - } - - /** - * Returns the index used by Spreadsheet_Excel_Writer_Worksheet::_XF() - * - * @return integer The index for the XF record - */ - function getXfIndex() - { - return($this->_xf_index); - } - - /** - * Used in conjunction with the set_xxx_color methods to convert a color - * string into a number. Color range is 0..63 but we will restrict it - * to 8..63 to comply with Gnumeric. Colors 0..7 are repeated in 8..15. - * - * @access private - * @param string $name_color name of the color (i.e.: 'blue', 'red', etc..). Optional. - * @return integer The color index - */ - function _getColor($name_color = '') - { - $colors = array( - 'aqua' => 0x0F, - 'cyan' => 0x0F, - 'black' => 0x08, - 'blue' => 0x0C, - 'brown' => 0x10, - 'magenta' => 0x0E, - 'fuchsia' => 0x0E, - 'gray' => 0x17, - 'grey' => 0x17, - 'green' => 0x11, - 'lime' => 0x0B, - 'navy' => 0x12, - 'orange' => 0x35, - 'purple' => 0x14, - 'red' => 0x0A, - 'silver' => 0x16, - 'white' => 0x09, - 'yellow' => 0x0D - ); - - // Return the default color, 0x7FFF, if undef, - if($name_color == '') { - return(0x7FFF); - } - - // or the color string converted to an integer, - if(isset($colors[$name_color])) { - return($colors[$name_color]); - } - - // or the default color if string is unrecognised, - if(preg_match("/\D/",$name_color)) { - return(0x7FFF); - } - - // or an index < 8 mapped into the correct range, - if($name_color < 8) { - return($name_color + 8); - } - - // or the default color if arg is outside range, - if($name_color > 63) { - return(0x7FFF); - } - - // or an integer in the valid range - return($name_color); - } - - /** - * Set cell alignment. - * - * @access public - * @param string $location alignment for the cell ('left', 'right', etc...). - */ - function setAlign($location) - { - if (preg_match("/\d/",$location)) { - return; // Ignore numbers - } - - $location = strtolower($location); - - if ($location == 'left') { - $this->_text_h_align = 1; - } - if ($location == 'centre') { - $this->_text_h_align = 2; - } - if ($location == 'center') { - $this->_text_h_align = 2; - } - if ($location == 'right') { - $this->_text_h_align = 3; - } - if ($location == 'fill') { - $this->_text_h_align = 4; - } - if ($location == 'justify') { - $this->_text_h_align = 5; - } - if ($location == 'merge') { - $this->_text_h_align = 6; - } - if ($location == 'equal_space') { // For T.K. - $this->_text_h_align = 7; - } - if ($location == 'top') { - $this->_text_v_align = 0; - } - if ($location == 'vcentre') { - $this->_text_v_align = 1; - } - if ($location == 'vcenter') { - $this->_text_v_align = 1; - } - if ($location == 'bottom') { - $this->_text_v_align = 2; - } - if ($location == 'vjustify') { - $this->_text_v_align = 3; - } - if ($location == 'vequal_space') { // For T.K. - $this->_text_v_align = 4; - } - } - - /** - * This is an alias for the unintuitive setAlign('merge') - * - * @access public - */ - function setMerge() - { - $this->setAlign('merge'); - } - - /** - * Sets the boldness of the text. - * Bold has a range 100..1000. - * 0 (400) is normal. 1 (700) is bold. - * - * @access public - * @param integer $weight Weight for the text, 0 maps to 400 (normal text), - 1 maps to 700 (bold text). Valid range is: 100-1000. - It's Optional, default is 1 (bold). - */ - function setBold($weight = 1) - { - if($weight == 1) { - $weight = 0x2BC; // Bold text - } - if($weight == 0) { - $weight = 0x190; // Normal text - } - if($weight < 0x064) { - $weight = 0x190; // Lower bound - } - if($weight > 0x3E8) { - $weight = 0x190; // Upper bound - } - $this->_bold = $weight; - } - - - /************************************ - * FUNCTIONS FOR SETTING CELLS BORDERS - */ - - /** - * Sets the width for the bottom border of the cell - * - * @access public - * @param integer $style style of the cell border. 1 => thin, 2 => thick. - */ - function setBottom($style) - { - $this->_bottom = $style; - } - - /** - * Sets the width for the top border of the cell - * - * @access public - * @param integer $style style of the cell top border. 1 => thin, 2 => thick. - */ - function setTop($style) - { - $this->_top = $style; - } - - /** - * Sets the width for the left border of the cell - * - * @access public - * @param integer $style style of the cell left border. 1 => thin, 2 => thick. - */ - function setLeft($style) - { - $this->_left = $style; - } - - /** - * Sets the width for the right border of the cell - * - * @access public - * @param integer $style style of the cell right border. 1 => thin, 2 => thick. - */ - function setRight($style) - { - $this->_right = $style; - } - - - /** - * Set cells borders to the same style - * - * @access public - * @param integer $style style to apply for all cell borders. 1 => thin, 2 => thick. - */ - function setBorder($style) - { - $this->setBottom($style); - $this->setTop($style); - $this->setLeft($style); - $this->setRight($style); - } - - - /******************************************* - * FUNCTIONS FOR SETTING CELLS BORDERS COLORS - */ - - /** - * Sets all the cell's borders to the same color - * - * @access public - * @param mixed $color The color we are setting. Either a string (like 'blue'), - * or an integer (range is [8...63]). - */ - function setBorderColor($color) - { - $this->setBottomColor($color); - $this->setTopColor($color); - $this->setLeftColor($color); - $this->setRightColor($color); - } - - /** - * Sets the cell's bottom border color - * - * @access public - * @param mixed $color either a string (like 'blue'), or an integer (range is [8...63]). - */ - function setBottomColor($color) - { - $value = $this->_getColor($color); - $this->_bottom_color = $value; - } - - /** - * Sets the cell's top border color - * - * @access public - * @param mixed $color either a string (like 'blue'), or an integer (range is [8...63]). - */ - function setTopColor($color) - { - $value = $this->_getColor($color); - $this->_top_color = $value; - } - - /** - * Sets the cell's left border color - * - * @access public - * @param mixed $color either a string (like 'blue'), or an integer (range is [8...63]). - */ - function setLeftColor($color) - { - $value = $this->_getColor($color); - $this->_left_color = $value; - } - - /** - * Sets the cell's right border color - * - * @access public - * @param mixed $color either a string (like 'blue'), or an integer (range is [8...63]). - */ - function setRightColor($color) - { - $value = $this->_getColor($color); - $this->_right_color = $value; - } - - - /** - * Sets the cell's foreground color - * - * @access public - * @param mixed $color either a string (like 'blue'), or an integer (range is [8...63]). - */ - function setFgColor($color) - { - $value = $this->_getColor($color); - $this->_fg_color = $value; - if ($this->_pattern == 0) { // force color to be seen - $this->_pattern = 1; - } - } - - /** - * Sets the cell's background color - * - * @access public - * @param mixed $color either a string (like 'blue'), or an integer (range is [8...63]). - */ - function setBgColor($color) - { - $value = $this->_getColor($color); - $this->_bg_color = $value; - if ($this->_pattern == 0) { // force color to be seen - $this->_pattern = 1; - } - } - - /** - * Sets the cell's color - * - * @access public - * @param mixed $color either a string (like 'blue'), or an integer (range is [8...63]). - */ - function setColor($color) - { - $value = $this->_getColor($color); - $this->_color = $value; - } - - /** - * Sets the fill pattern attribute of a cell - * - * @access public - * @param integer $arg Optional. Defaults to 1. Meaningful values are: 0-18, - * 0 meaning no background. - */ - function setPattern($arg = 1) - { - $this->_pattern = $arg; - } - - /** - * Sets the underline of the text - * - * @access public - * @param integer $underline The value for underline. Possible values are: - * 1 => underline, 2 => double underline. - */ - function setUnderline($underline) - { - $this->_underline = $underline; - } - - /** - * Sets the font style as italic - * - * @access public - */ - function setItalic() - { - $this->_italic = 1; - } - - /** - * Sets the font size - * - * @access public - * @param integer $size The font size (in pixels I think). - */ - function setSize($size) - { - $this->_size = $size; - } - - /** - * Sets text wrapping - * - * @access public - */ - function setTextWrap() - { - $this->_text_wrap = 1; - } - - /** - * Sets the orientation of the text - * - * @access public - * @param integer $angle The rotation angle for the text (clockwise). Possible - values are: 0, 90, 270 and -1 for stacking top-to-bottom. - */ - function setTextRotation($angle) - { - switch ($angle) - { - case 0: - $this->_rotation = 0; - break; - case 90: - $this->_rotation = 3; - break; - case 270: - $this->_rotation = 2; - break; - case -1: - $this->_rotation = 1; - break; - default : - return $this->raiseError("Invalid value for angle.". - " Possible values are: 0, 90, 270 and -1 ". - "for stacking top-to-bottom."); - $this->_rotation = 0; - break; - } - } - - /** - * Sets the numeric format. - * It can be date, time, currency, etc... - * - * @access public - * @param integer $num_format The numeric format. - */ - function setNumFormat($num_format) - { - $this->_num_format = $num_format; - } - - /** - * Sets font as strikeout. - * - * @access public - */ - function setStrikeOut() - { - $this->_font_strikeout = 1; - } - - /** - * Sets outlining for a font. - * - * @access public - */ - function setOutLine() - { - $this->_font_outline = 1; - } - - /** - * Sets font as shadow. - * - * @access public - */ - function setShadow() - { - $this->_font_shadow = 1; - } - - /** - * Sets the script type of the text - * - * @access public - * @param integer $script The value for script type. Possible values are: - * 1 => superscript, 2 => subscript. - */ - function setScript($script) - { - $this->_font_script = $script; - } - - /** - * Locks a cell. - * - * @access public - */ - function setLocked() - { - $this->_locked = 1; - } - - /** - * Unlocks a cell. Useful for unprotecting particular cells of a protected sheet. - * - * @access public - */ - function setUnLocked() - { - $this->_locked = 0; - } - - /** - * Sets the font family name. - * - * @access public - * @param string $fontfamily The font family name. Possible values are: - * 'Times New Roman', 'Arial', 'Courier'. - */ - function setFontFamily($font_family) - { - $this->_font_name = $font_family; - } -} -?> diff --git a/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer/Parser.php b/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer/Parser.php deleted file mode 100644 index 651bec9f9..000000000 --- a/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer/Parser.php +++ /dev/null @@ -1,1761 +0,0 @@ -" -*/ -define('SPREADSHEET_EXCEL_WRITER_GT',">"); - -/** -* @const SPREADSHEET_EXCEL_WRITER_LT token identifier for character "<" -*/ -define('SPREADSHEET_EXCEL_WRITER_LT',"<"); - -/** -* @const SPREADSHEET_EXCEL_WRITER_LE token identifier for character "<=" -*/ -define('SPREADSHEET_EXCEL_WRITER_LE',"<="); - -/** -* @const SPREADSHEET_EXCEL_WRITER_GE token identifier for character ">=" -*/ -define('SPREADSHEET_EXCEL_WRITER_GE',">="); - -/** -* @const SPREADSHEET_EXCEL_WRITER_EQ token identifier for character "=" -*/ -define('SPREADSHEET_EXCEL_WRITER_EQ',"="); - -/** -* @const SPREADSHEET_EXCEL_WRITER_NE token identifier for character "<>" -*/ -define('SPREADSHEET_EXCEL_WRITER_NE',"<>"); - - -require_once('PEAR.php'); - -/** -* Class for parsing Excel formulas -* -* @author Xavier Noguer -* @category FileFormats -* @package Spreadsheet_Excel_Writer -*/ - -class Spreadsheet_Excel_Writer_Parser extends PEAR -{ - /** - * The index of the character we are currently looking at - * @var integer - */ - var $_current_char; - - /** - * The token we are working on. - * @var string - */ - var $_current_token; - - /** - * The formula to parse - * @var string - */ - var $_formula; - - /** - * The character ahead of the current char - * @var string - */ - var $_lookahead; - - /** - * The parse tree to be generated - * @var string - */ - var $_parse_tree; - - /** - * The byte order. 1 => big endian, 0 => little endian. - * @var integer - */ - var $_byte_order; - - /** - * Array of external sheets - * @var array - */ - var $_ext_sheets; - - /** - * Array of sheet references in the form of REF structures - * @var array - */ - var $_references; - - /** - * The BIFF version for the workbook - * @var integer - */ - var $_BIFF_version; - - /** - * The class constructor - * - * @param integer $byte_order The byte order (Little endian or Big endian) of the architecture - (optional). 1 => big endian, 0 (default) little endian. - */ - function Spreadsheet_Excel_Writer_Parser($byte_order, $biff_version) - { - $this->_current_char = 0; - $this->_BIFF_version = $biff_version; - $this->_current_token = ''; // The token we are working on. - $this->_formula = ""; // The formula to parse. - $this->_lookahead = ''; // The character ahead of the current char. - $this->_parse_tree = ''; // The parse tree to be generated. - $this->_initializeHashes(); // Initialize the hashes: ptg's and function's ptg's - $this->_byte_order = $byte_order; // Little Endian or Big Endian - $this->_ext_sheets = array(); - $this->_references = array(); - } - - /** - * Initialize the ptg and function hashes. - * - * @access private - */ - function _initializeHashes() - { - // The Excel ptg indices - $this->ptg = array( - 'ptgExp' => 0x01, - 'ptgTbl' => 0x02, - 'ptgAdd' => 0x03, - 'ptgSub' => 0x04, - 'ptgMul' => 0x05, - 'ptgDiv' => 0x06, - 'ptgPower' => 0x07, - 'ptgConcat' => 0x08, - 'ptgLT' => 0x09, - 'ptgLE' => 0x0A, - 'ptgEQ' => 0x0B, - 'ptgGE' => 0x0C, - 'ptgGT' => 0x0D, - 'ptgNE' => 0x0E, - 'ptgIsect' => 0x0F, - 'ptgUnion' => 0x10, - 'ptgRange' => 0x11, - 'ptgUplus' => 0x12, - 'ptgUminus' => 0x13, - 'ptgPercent' => 0x14, - 'ptgParen' => 0x15, - 'ptgMissArg' => 0x16, - 'ptgStr' => 0x17, - 'ptgAttr' => 0x19, - 'ptgSheet' => 0x1A, - 'ptgEndSheet' => 0x1B, - 'ptgErr' => 0x1C, - 'ptgBool' => 0x1D, - 'ptgInt' => 0x1E, - 'ptgNum' => 0x1F, - 'ptgArray' => 0x20, - 'ptgFunc' => 0x21, - 'ptgFuncVar' => 0x22, - 'ptgName' => 0x23, - 'ptgRef' => 0x24, - 'ptgArea' => 0x25, - 'ptgMemArea' => 0x26, - 'ptgMemErr' => 0x27, - 'ptgMemNoMem' => 0x28, - 'ptgMemFunc' => 0x29, - 'ptgRefErr' => 0x2A, - 'ptgAreaErr' => 0x2B, - 'ptgRefN' => 0x2C, - 'ptgAreaN' => 0x2D, - 'ptgMemAreaN' => 0x2E, - 'ptgMemNoMemN' => 0x2F, - 'ptgNameX' => 0x39, - 'ptgRef3d' => 0x3A, - 'ptgArea3d' => 0x3B, - 'ptgRefErr3d' => 0x3C, - 'ptgAreaErr3d' => 0x3D, - 'ptgArrayV' => 0x40, - 'ptgFuncV' => 0x41, - 'ptgFuncVarV' => 0x42, - 'ptgNameV' => 0x43, - 'ptgRefV' => 0x44, - 'ptgAreaV' => 0x45, - 'ptgMemAreaV' => 0x46, - 'ptgMemErrV' => 0x47, - 'ptgMemNoMemV' => 0x48, - 'ptgMemFuncV' => 0x49, - 'ptgRefErrV' => 0x4A, - 'ptgAreaErrV' => 0x4B, - 'ptgRefNV' => 0x4C, - 'ptgAreaNV' => 0x4D, - 'ptgMemAreaNV' => 0x4E, - 'ptgMemNoMemN' => 0x4F, - 'ptgFuncCEV' => 0x58, - 'ptgNameXV' => 0x59, - 'ptgRef3dV' => 0x5A, - 'ptgArea3dV' => 0x5B, - 'ptgRefErr3dV' => 0x5C, - 'ptgAreaErr3d' => 0x5D, - 'ptgArrayA' => 0x60, - 'ptgFuncA' => 0x61, - 'ptgFuncVarA' => 0x62, - 'ptgNameA' => 0x63, - 'ptgRefA' => 0x64, - 'ptgAreaA' => 0x65, - 'ptgMemAreaA' => 0x66, - 'ptgMemErrA' => 0x67, - 'ptgMemNoMemA' => 0x68, - 'ptgMemFuncA' => 0x69, - 'ptgRefErrA' => 0x6A, - 'ptgAreaErrA' => 0x6B, - 'ptgRefNA' => 0x6C, - 'ptgAreaNA' => 0x6D, - 'ptgMemAreaNA' => 0x6E, - 'ptgMemNoMemN' => 0x6F, - 'ptgFuncCEA' => 0x78, - 'ptgNameXA' => 0x79, - 'ptgRef3dA' => 0x7A, - 'ptgArea3dA' => 0x7B, - 'ptgRefErr3dA' => 0x7C, - 'ptgAreaErr3d' => 0x7D - ); - - // Thanks to Michael Meeks and Gnumeric for the initial arg values. - // - // The following hash was generated by "function_locale.pl" in the distro. - // Refer to function_locale.pl for non-English function names. - // - // The array elements are as follow: - // ptg: The Excel function ptg code. - // args: The number of arguments that the function takes: - // >=0 is a fixed number of arguments. - // -1 is a variable number of arguments. - // class: The reference, value or array class of the function args. - // vol: The function is volatile. - // - $this->_functions = array( - // function ptg args class vol - 'COUNT' => array( 0, -1, 0, 0 ), - 'IF' => array( 1, -1, 1, 0 ), - 'ISNA' => array( 2, 1, 1, 0 ), - 'ISERROR' => array( 3, 1, 1, 0 ), - 'SUM' => array( 4, -1, 0, 0 ), - 'AVERAGE' => array( 5, -1, 0, 0 ), - 'MIN' => array( 6, -1, 0, 0 ), - 'MAX' => array( 7, -1, 0, 0 ), - 'ROW' => array( 8, -1, 0, 0 ), - 'COLUMN' => array( 9, -1, 0, 0 ), - 'NA' => array( 10, 0, 0, 0 ), - 'NPV' => array( 11, -1, 1, 0 ), - 'STDEV' => array( 12, -1, 0, 0 ), - 'DOLLAR' => array( 13, -1, 1, 0 ), - 'FIXED' => array( 14, -1, 1, 0 ), - 'SIN' => array( 15, 1, 1, 0 ), - 'COS' => array( 16, 1, 1, 0 ), - 'TAN' => array( 17, 1, 1, 0 ), - 'ATAN' => array( 18, 1, 1, 0 ), - 'PI' => array( 19, 0, 1, 0 ), - 'SQRT' => array( 20, 1, 1, 0 ), - 'EXP' => array( 21, 1, 1, 0 ), - 'LN' => array( 22, 1, 1, 0 ), - 'LOG10' => array( 23, 1, 1, 0 ), - 'ABS' => array( 24, 1, 1, 0 ), - 'INT' => array( 25, 1, 1, 0 ), - 'SIGN' => array( 26, 1, 1, 0 ), - 'ROUND' => array( 27, 2, 1, 0 ), - 'LOOKUP' => array( 28, -1, 0, 0 ), - 'INDEX' => array( 29, -1, 0, 1 ), - 'REPT' => array( 30, 2, 1, 0 ), - 'MID' => array( 31, 3, 1, 0 ), - 'LEN' => array( 32, 1, 1, 0 ), - 'VALUE' => array( 33, 1, 1, 0 ), - 'TRUE' => array( 34, 0, 1, 0 ), - 'FALSE' => array( 35, 0, 1, 0 ), - 'AND' => array( 36, -1, 0, 0 ), - 'OR' => array( 37, -1, 0, 0 ), - 'NOT' => array( 38, 1, 1, 0 ), - 'MOD' => array( 39, 2, 1, 0 ), - 'DCOUNT' => array( 40, 3, 0, 0 ), - 'DSUM' => array( 41, 3, 0, 0 ), - 'DAVERAGE' => array( 42, 3, 0, 0 ), - 'DMIN' => array( 43, 3, 0, 0 ), - 'DMAX' => array( 44, 3, 0, 0 ), - 'DSTDEV' => array( 45, 3, 0, 0 ), - 'VAR' => array( 46, -1, 0, 0 ), - 'DVAR' => array( 47, 3, 0, 0 ), - 'TEXT' => array( 48, 2, 1, 0 ), - 'LINEST' => array( 49, -1, 0, 0 ), - 'TREND' => array( 50, -1, 0, 0 ), - 'LOGEST' => array( 51, -1, 0, 0 ), - 'GROWTH' => array( 52, -1, 0, 0 ), - 'PV' => array( 56, -1, 1, 0 ), - 'FV' => array( 57, -1, 1, 0 ), - 'NPER' => array( 58, -1, 1, 0 ), - 'PMT' => array( 59, -1, 1, 0 ), - 'RATE' => array( 60, -1, 1, 0 ), - 'MIRR' => array( 61, 3, 0, 0 ), - 'IRR' => array( 62, -1, 0, 0 ), - 'RAND' => array( 63, 0, 1, 1 ), - 'MATCH' => array( 64, -1, 0, 0 ), - 'DATE' => array( 65, 3, 1, 0 ), - 'TIME' => array( 66, 3, 1, 0 ), - 'DAY' => array( 67, 1, 1, 0 ), - 'MONTH' => array( 68, 1, 1, 0 ), - 'YEAR' => array( 69, 1, 1, 0 ), - 'WEEKDAY' => array( 70, -1, 1, 0 ), - 'HOUR' => array( 71, 1, 1, 0 ), - 'MINUTE' => array( 72, 1, 1, 0 ), - 'SECOND' => array( 73, 1, 1, 0 ), - 'NOW' => array( 74, 0, 1, 1 ), - 'AREAS' => array( 75, 1, 0, 1 ), - 'ROWS' => array( 76, 1, 0, 1 ), - 'COLUMNS' => array( 77, 1, 0, 1 ), - 'OFFSET' => array( 78, -1, 0, 1 ), - 'SEARCH' => array( 82, -1, 1, 0 ), - 'TRANSPOSE' => array( 83, 1, 1, 0 ), - 'TYPE' => array( 86, 1, 1, 0 ), - 'ATAN2' => array( 97, 2, 1, 0 ), - 'ASIN' => array( 98, 1, 1, 0 ), - 'ACOS' => array( 99, 1, 1, 0 ), - 'CHOOSE' => array( 100, -1, 1, 0 ), - 'HLOOKUP' => array( 101, -1, 0, 0 ), - 'VLOOKUP' => array( 102, -1, 0, 0 ), - 'ISREF' => array( 105, 1, 0, 0 ), - 'LOG' => array( 109, -1, 1, 0 ), - 'CHAR' => array( 111, 1, 1, 0 ), - 'LOWER' => array( 112, 1, 1, 0 ), - 'UPPER' => array( 113, 1, 1, 0 ), - 'PROPER' => array( 114, 1, 1, 0 ), - 'LEFT' => array( 115, -1, 1, 0 ), - 'RIGHT' => array( 116, -1, 1, 0 ), - 'EXACT' => array( 117, 2, 1, 0 ), - 'TRIM' => array( 118, 1, 1, 0 ), - 'REPLACE' => array( 119, 4, 1, 0 ), - 'SUBSTITUTE' => array( 120, -1, 1, 0 ), - 'CODE' => array( 121, 1, 1, 0 ), - 'FIND' => array( 124, -1, 1, 0 ), - 'CELL' => array( 125, -1, 0, 1 ), - 'ISERR' => array( 126, 1, 1, 0 ), - 'ISTEXT' => array( 127, 1, 1, 0 ), - 'ISNUMBER' => array( 128, 1, 1, 0 ), - 'ISBLANK' => array( 129, 1, 1, 0 ), - 'T' => array( 130, 1, 0, 0 ), - 'N' => array( 131, 1, 0, 0 ), - 'DATEVALUE' => array( 140, 1, 1, 0 ), - 'TIMEVALUE' => array( 141, 1, 1, 0 ), - 'SLN' => array( 142, 3, 1, 0 ), - 'SYD' => array( 143, 4, 1, 0 ), - 'DDB' => array( 144, -1, 1, 0 ), - 'INDIRECT' => array( 148, -1, 1, 1 ), - 'CALL' => array( 150, -1, 1, 0 ), - 'CLEAN' => array( 162, 1, 1, 0 ), - 'MDETERM' => array( 163, 1, 2, 0 ), - 'MINVERSE' => array( 164, 1, 2, 0 ), - 'MMULT' => array( 165, 2, 2, 0 ), - 'IPMT' => array( 167, -1, 1, 0 ), - 'PPMT' => array( 168, -1, 1, 0 ), - 'COUNTA' => array( 169, -1, 0, 0 ), - 'PRODUCT' => array( 183, -1, 0, 0 ), - 'FACT' => array( 184, 1, 1, 0 ), - 'DPRODUCT' => array( 189, 3, 0, 0 ), - 'ISNONTEXT' => array( 190, 1, 1, 0 ), - 'STDEVP' => array( 193, -1, 0, 0 ), - 'VARP' => array( 194, -1, 0, 0 ), - 'DSTDEVP' => array( 195, 3, 0, 0 ), - 'DVARP' => array( 196, 3, 0, 0 ), - 'TRUNC' => array( 197, -1, 1, 0 ), - 'ISLOGICAL' => array( 198, 1, 1, 0 ), - 'DCOUNTA' => array( 199, 3, 0, 0 ), - 'ROUNDUP' => array( 212, 2, 1, 0 ), - 'ROUNDDOWN' => array( 213, 2, 1, 0 ), - 'RANK' => array( 216, -1, 0, 0 ), - 'ADDRESS' => array( 219, -1, 1, 0 ), - 'DAYS360' => array( 220, -1, 1, 0 ), - 'TODAY' => array( 221, 0, 1, 1 ), - 'VDB' => array( 222, -1, 1, 0 ), - 'MEDIAN' => array( 227, -1, 0, 0 ), - 'SUMPRODUCT' => array( 228, -1, 2, 0 ), - 'SINH' => array( 229, 1, 1, 0 ), - 'COSH' => array( 230, 1, 1, 0 ), - 'TANH' => array( 231, 1, 1, 0 ), - 'ASINH' => array( 232, 1, 1, 0 ), - 'ACOSH' => array( 233, 1, 1, 0 ), - 'ATANH' => array( 234, 1, 1, 0 ), - 'DGET' => array( 235, 3, 0, 0 ), - 'INFO' => array( 244, 1, 1, 1 ), - 'DB' => array( 247, -1, 1, 0 ), - 'FREQUENCY' => array( 252, 2, 0, 0 ), - 'ERROR.TYPE' => array( 261, 1, 1, 0 ), - 'REGISTER.ID' => array( 267, -1, 1, 0 ), - 'AVEDEV' => array( 269, -1, 0, 0 ), - 'BETADIST' => array( 270, -1, 1, 0 ), - 'GAMMALN' => array( 271, 1, 1, 0 ), - 'BETAINV' => array( 272, -1, 1, 0 ), - 'BINOMDIST' => array( 273, 4, 1, 0 ), - 'CHIDIST' => array( 274, 2, 1, 0 ), - 'CHIINV' => array( 275, 2, 1, 0 ), - 'COMBIN' => array( 276, 2, 1, 0 ), - 'CONFIDENCE' => array( 277, 3, 1, 0 ), - 'CRITBINOM' => array( 278, 3, 1, 0 ), - 'EVEN' => array( 279, 1, 1, 0 ), - 'EXPONDIST' => array( 280, 3, 1, 0 ), - 'FDIST' => array( 281, 3, 1, 0 ), - 'FINV' => array( 282, 3, 1, 0 ), - 'FISHER' => array( 283, 1, 1, 0 ), - 'FISHERINV' => array( 284, 1, 1, 0 ), - 'FLOOR' => array( 285, 2, 1, 0 ), - 'GAMMADIST' => array( 286, 4, 1, 0 ), - 'GAMMAINV' => array( 287, 3, 1, 0 ), - 'CEILING' => array( 288, 2, 1, 0 ), - 'HYPGEOMDIST' => array( 289, 4, 1, 0 ), - 'LOGNORMDIST' => array( 290, 3, 1, 0 ), - 'LOGINV' => array( 291, 3, 1, 0 ), - 'NEGBINOMDIST' => array( 292, 3, 1, 0 ), - 'NORMDIST' => array( 293, 4, 1, 0 ), - 'NORMSDIST' => array( 294, 1, 1, 0 ), - 'NORMINV' => array( 295, 3, 1, 0 ), - 'NORMSINV' => array( 296, 1, 1, 0 ), - 'STANDARDIZE' => array( 297, 3, 1, 0 ), - 'ODD' => array( 298, 1, 1, 0 ), - 'PERMUT' => array( 299, 2, 1, 0 ), - 'POISSON' => array( 300, 3, 1, 0 ), - 'TDIST' => array( 301, 3, 1, 0 ), - 'WEIBULL' => array( 302, 4, 1, 0 ), - 'SUMXMY2' => array( 303, 2, 2, 0 ), - 'SUMX2MY2' => array( 304, 2, 2, 0 ), - 'SUMX2PY2' => array( 305, 2, 2, 0 ), - 'CHITEST' => array( 306, 2, 2, 0 ), - 'CORREL' => array( 307, 2, 2, 0 ), - 'COVAR' => array( 308, 2, 2, 0 ), - 'FORECAST' => array( 309, 3, 2, 0 ), - 'FTEST' => array( 310, 2, 2, 0 ), - 'INTERCEPT' => array( 311, 2, 2, 0 ), - 'PEARSON' => array( 312, 2, 2, 0 ), - 'RSQ' => array( 313, 2, 2, 0 ), - 'STEYX' => array( 314, 2, 2, 0 ), - 'SLOPE' => array( 315, 2, 2, 0 ), - 'TTEST' => array( 316, 4, 2, 0 ), - 'PROB' => array( 317, -1, 2, 0 ), - 'DEVSQ' => array( 318, -1, 0, 0 ), - 'GEOMEAN' => array( 319, -1, 0, 0 ), - 'HARMEAN' => array( 320, -1, 0, 0 ), - 'SUMSQ' => array( 321, -1, 0, 0 ), - 'KURT' => array( 322, -1, 0, 0 ), - 'SKEW' => array( 323, -1, 0, 0 ), - 'ZTEST' => array( 324, -1, 0, 0 ), - 'LARGE' => array( 325, 2, 0, 0 ), - 'SMALL' => array( 326, 2, 0, 0 ), - 'QUARTILE' => array( 327, 2, 0, 0 ), - 'PERCENTILE' => array( 328, 2, 0, 0 ), - 'PERCENTRANK' => array( 329, -1, 0, 0 ), - 'MODE' => array( 330, -1, 2, 0 ), - 'TRIMMEAN' => array( 331, 2, 0, 0 ), - 'TINV' => array( 332, 2, 1, 0 ), - 'CONCATENATE' => array( 336, -1, 1, 0 ), - 'POWER' => array( 337, 2, 1, 0 ), - 'RADIANS' => array( 342, 1, 1, 0 ), - 'DEGREES' => array( 343, 1, 1, 0 ), - 'SUBTOTAL' => array( 344, -1, 0, 0 ), - 'SUMIF' => array( 345, -1, 0, 0 ), - 'COUNTIF' => array( 346, 2, 0, 0 ), - 'COUNTBLANK' => array( 347, 1, 0, 0 ), - 'ROMAN' => array( 354, -1, 1, 0 ) - ); - } - - /** - * Convert a token to the proper ptg value. - * - * @access private - * @param mixed $token The token to convert. - * @return mixed the converted token on success. PEAR_Error if the token - * is not recognized - */ - function _convert($token) - { - if (preg_match("/^\"[^\"]{0,255}\"$/", $token)) - { - return $this->_convertString($token); - } - elseif (is_numeric($token)) - { - return $this->_convertNumber($token); - } - // match references like A1 or $A$1 - elseif (preg_match('/^\$?([A-Ia-i]?[A-Za-z])\$?(\d+)$/',$token)) - { - return $this->_convertRef2d($token); - } - // match external references like Sheet1!A1 or Sheet1:Sheet2!A1 - elseif (preg_match("/^\w+(\:\w+)?\![A-Ia-i]?[A-Za-z](\d+)$/",$token)) - { - return $this->_convertRef3d($token); - } - // match external references like Sheet1!A1 or Sheet1:Sheet2!A1 - elseif (preg_match("/^'\w+(\:\w+)?'\![A-Ia-i]?[A-Za-z](\d+)$/",$token)) - { - return $this->_convertRef3d($token); - } - // match ranges like A1:B2 - elseif (preg_match("/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)\:(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/",$token)) - { - return $this->_convertRange2d($token); - } - // match ranges like A1..B2 - elseif (preg_match("/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/",$token)) - { - return $this->_convertRange2d($token); - } - // match external ranges like Sheet1!A1 or Sheet1:Sheet2!A1:B2 - elseif (preg_match("/^\w+(\:\w+)?\!([A-Ia-i]?[A-Za-z])?(\d+)\:([A-Ia-i]?[A-Za-z])?(\d+)$/",$token)) - { - return $this->_convertRange3d($token); - } - // match external ranges like 'Sheet1'!A1 or 'Sheet1:Sheet2'!A1:B2 - elseif (preg_match("/^'\w+(\:\w+)?'\!([A-Ia-i]?[A-Za-z])?(\d+)\:([A-Ia-i]?[A-Za-z])?(\d+)$/",$token)) - { - return $this->_convertRange3d($token); - } - elseif (isset($this->ptg[$token])) // operators (including parentheses) - { - return pack("C", $this->ptg[$token]); - } - // commented so argument number can be processed correctly. See toReversePolish(). - /*elseif (preg_match("/[A-Z0-9\xc0-\xdc\.]+/",$token)) - { - return($this->_convertFunction($token,$this->_func_args)); - }*/ - // if it's an argument, ignore the token (the argument remains) - elseif ($token == 'arg') - { - return ''; - } - // TODO: use real error codes - return $this->raiseError("Unknown token $token"); - } - - /** - * Convert a number token to ptgInt or ptgNum - * - * @access private - * @param mixed $num an integer or double for conversion to its ptg value - */ - function _convertNumber($num) - { - // Integer in the range 0..2**16-1 - if ((preg_match("/^\d+$/",$num)) and ($num <= 65535)) { - return pack("Cv", $this->ptg['ptgInt'], $num); - } - else // A float - { - if ($this->_byte_order) { // if it's Big Endian - $num = strrev($num); - } - return pack("Cd", $this->ptg['ptgNum'], $num); - } - } - - /** - * Convert a string token to ptgStr - * - * @access private - * @param string $string A string for conversion to its ptg value. - * @return mixed the converted token on success. PEAR_Error if the string - * is longer than 255 characters. - */ - function _convertString($string) - { - // chop away beggining and ending quotes - $string = substr($string, 1, strlen($string) - 2); - if (strlen($string) > 255) { - return $this->raiseError("String is too long"); - } - if ($this->_BIFF_version == 0x0500) { - return pack("CC", $this->ptg['ptgStr'], strlen($string)).$string; - } - elseif ($this->_BIFF_version == 0x0600) { - $encoding = 0; // TODO: Unicode support - return pack("CCC", $this->ptg['ptgStr'], strlen($string), $encoding).$string; - } - } - - /** - * Convert a function to a ptgFunc or ptgFuncVarV depending on the number of - * args that it takes. - * - * @access private - * @param string $token The name of the function for convertion to ptg value. - * @param integer $num_args The number of arguments the function receives. - * @return string The packed ptg for the function - */ - function _convertFunction($token, $num_args) - { - $args = $this->_functions[$token][1]; - $volatile = $this->_functions[$token][3]; - - // Fixed number of args eg. TIME($i,$j,$k). - if ($args >= 0) { - return pack("Cv", $this->ptg['ptgFuncV'], $this->_functions[$token][0]); - } - // Variable number of args eg. SUM($i,$j,$k, ..). - if ($args == -1) { - return pack("CCv", $this->ptg['ptgFuncVarV'], $num_args, $this->_functions[$token][0]); - } - } - - /** - * Convert an Excel range such as A1:D4 to a ptgRefV. - * - * @access private - * @param string $range An Excel range in the A1:A2 or A1..A2 format. - */ - function _convertRange2d($range) - { - $class = 2; // as far as I know, this is magick. - - // Split the range into 2 cell refs - if (preg_match("/^([A-Ia-i]?[A-Za-z])(\d+)\:([A-Ia-i]?[A-Za-z])(\d+)$/",$range)) { - list($cell1, $cell2) = explode(':', $range); - } - elseif (preg_match("/^([A-Ia-i]?[A-Za-z])(\d+)\.\.([A-Ia-i]?[A-Za-z])(\d+)$/",$range)) { - list($cell1, $cell2) = explode('\.\.', $range); - - } - else { - // TODO: use real error codes - return $this->raiseError("Unknown range separator", 0, PEAR_ERROR_DIE); - } - - // Convert the cell references - $cell_array1 = $this->_cellToPackedRowcol($cell1); - if (PEAR::isError($cell_array1)) { - return $cell_array1; - } - list($row1, $col1) = $cell_array1; - $cell_array2 = $this->_cellToPackedRowcol($cell2); - if (PEAR::isError($cell_array2)) { - return $cell_array2; - } - list($row2, $col2) = $cell_array2; - - // The ptg value depends on the class of the ptg. - if ($class == 0) { - $ptgArea = pack("C", $this->ptg['ptgArea']); - } - elseif ($class == 1) { - $ptgArea = pack("C", $this->ptg['ptgAreaV']); - } - elseif ($class == 2) { - $ptgArea = pack("C", $this->ptg['ptgAreaA']); - } - else { - // TODO: use real error codes - return $this->raiseError("Unknown class $class", 0, PEAR_ERROR_DIE); - } - return $ptgArea . $row1 . $row2 . $col1. $col2; - } - - /** - * Convert an Excel 3d range such as "Sheet1!A1:D4" or "Sheet1:Sheet2!A1:D4" to - * a ptgArea3d. - * - * @access private - * @param string $token An Excel range in the Sheet1!A1:A2 format. - * @return mixed The packed ptgArea3d token on success, PEAR_Error on failure. - */ - function _convertRange3d($token) - { - $class = 2; // as far as I know, this is magick. - - // Split the ref at the ! symbol - list($ext_ref, $range) = explode('!', $token); - - // Convert the external reference part (different for BIFF8) - if ($this->_BIFF_version == 0x0500) { - $ext_ref = $this->_packExtRef($ext_ref); - if (PEAR::isError($ext_ref)) { - return $ext_ref; - } - } - elseif ($this->_BIFF_version == 0x0600) { - $ext_ref = $this->_getRefIndex($ext_ref); - if (PEAR::isError($ext_ref)) { - return $ext_ref; - } - } - - // Split the range into 2 cell refs - list($cell1, $cell2) = explode(':', $range); - - // Convert the cell references - if (preg_match("/^(\$)?[A-Ia-i]?[A-Za-z](\$)?(\d+)$/", $cell1)) - { - $cell_array1 = $this->_cellToPackedRowcol($cell1); - if (PEAR::isError($cell_array1)) { - return $cell_array1; - } - list($row1, $col1) = $cell_array1; - $cell_array2 = $this->_cellToPackedRowcol($cell2); - if (PEAR::isError($cell_array2)) { - return $cell_array2; - } - list($row2, $col2) = $cell_array2; - } - else { // It's a rows range (like 26:27) - $cells_array = $this->_rangeToPackedRange($cell1.':'.$cell2); - if (PEAR::isError($cells_array)) { - return $cells_array; - } - list($row1, $col1, $row2, $col2) = $cells_array; - } - - // The ptg value depends on the class of the ptg. - if ($class == 0) { - $ptgArea = pack("C", $this->ptg['ptgArea3d']); - } - elseif ($class == 1) { - $ptgArea = pack("C", $this->ptg['ptgArea3dV']); - } - elseif ($class == 2) { - $ptgArea = pack("C", $this->ptg['ptgArea3dA']); - } - else { - return $this->raiseError("Unknown class $class", 0, PEAR_ERROR_DIE); - } - - return $ptgArea . $ext_ref . $row1 . $row2 . $col1. $col2; - } - - /** - * Convert an Excel reference such as A1, $B2, C$3 or $D$4 to a ptgRefV. - * - * @access private - * @param string $cell An Excel cell reference - * @return string The cell in packed() format with the corresponding ptg - */ - function _convertRef2d($cell) - { - $class = 2; // as far as I know, this is magick. - - // Convert the cell reference - $cell_array = $this->_cellToPackedRowcol($cell); - if (PEAR::isError($cell_array)) { - return $cell_array; - } - list($row, $col) = $cell_array; - - // The ptg value depends on the class of the ptg. - if ($class == 0) { - $ptgRef = pack("C", $this->ptg['ptgRef']); - } - elseif ($class == 1) { - $ptgRef = pack("C", $this->ptg['ptgRefV']); - } - elseif ($class == 2) { - $ptgRef = pack("C", $this->ptg['ptgRefA']); - } - else { - // TODO: use real error codes - return $this->raiseError("Unknown class $class"); - } - return $ptgRef.$row.$col; - } - - /** - * Convert an Excel 3d reference such as "Sheet1!A1" or "Sheet1:Sheet2!A1" to a - * ptgRef3d. - * - * @access private - * @param string $cell An Excel cell reference - * @return mixed The packed ptgRef3d token on success, PEAR_Error on failure. - */ - function _convertRef3d($cell) - { - $class = 2; // as far as I know, this is magick. - - // Split the ref at the ! symbol - list($ext_ref, $cell) = explode('!', $cell); - - // Convert the external reference part (different for BIFF8) - if ($this->_BIFF_version == 0x0500) { - $ext_ref = $this->_packExtRef($ext_ref); - if (PEAR::isError($ext_ref)) { - return $ext_ref; - } - } - elseif ($this->_BIFF_version == 0x0600) { - $ext_ref = $this->_getRefIndex($ext_ref); - if (PEAR::isError($ext_ref)) { - return $ext_ref; - } - } - - // Convert the cell reference part - list($row, $col) = $this->_cellToPackedRowcol($cell); - - // The ptg value depends on the class of the ptg. - if ($class == 0) { - $ptgRef = pack("C", $this->ptg['ptgRef3d']); - } - elseif ($class == 1) { - $ptgRef = pack("C", $this->ptg['ptgRef3dV']); - } - elseif ($class == 2) { - $ptgRef = pack("C", $this->ptg['ptgRef3dA']); - } - else { - return $this->raiseError("Unknown class $class", 0, PEAR_ERROR_DIE); - } - - return $ptgRef . $ext_ref. $row . $col; - } - - /** - * Convert the sheet name part of an external reference, for example "Sheet1" or - * "Sheet1:Sheet2", to a packed structure. - * - * @access private - * @param string $ext_ref The name of the external reference - * @return string The reference index in packed() format - */ - function _packExtRef($ext_ref) - { - $ext_ref = preg_replace("/^'/", '', $ext_ref); // Remove leading ' if any. - $ext_ref = preg_replace("/'$/", '', $ext_ref); // Remove trailing ' if any. - - // Check if there is a sheet range eg., Sheet1:Sheet2. - if (preg_match("/:/", $ext_ref)) - { - list($sheet_name1, $sheet_name2) = explode(':', $ext_ref); - - $sheet1 = $this->_getSheetIndex($sheet_name1); - if ($sheet1 == -1) { - return $this->raiseError("Unknown sheet name $sheet_name1 in formula"); - } - $sheet2 = $this->_getSheetIndex($sheet_name2); - if ($sheet2 == -1) { - return $this->raiseError("Unknown sheet name $sheet_name2 in formula"); - } - - // Reverse max and min sheet numbers if necessary - if ($sheet1 > $sheet2) { - list($sheet1, $sheet2) = array($sheet2, $sheet1); - } - } - else // Single sheet name only. - { - $sheet1 = $this->_getSheetIndex($ext_ref); - if ($sheet1 == -1) { - return $this->raiseError("Unknown sheet name $ext_ref in formula"); - } - $sheet2 = $sheet1; - } - - // References are stored relative to 0xFFFF. - $offset = -1 - $sheet1; - - return pack('vdvv', $offset, 0x00, $sheet1, $sheet2); - } - - /** - * Look up the REF index that corresponds to an external sheet name - * (or range). If it doesn't exist yet add it to the workbook's references - * array. It assumes all sheet names given must exist. - * - * @access private - * @param string $ext_ref The name of the external reference - * @return mixed The reference index in packed() format on success, - * PEAR_Error on failure - */ - function _getRefIndex($ext_ref) - { - $ext_ref = preg_replace("/^'/", '', $ext_ref); // Remove leading ' if any. - $ext_ref = preg_replace("/'$/", '', $ext_ref); // Remove trailing ' if any. - - // Check if there is a sheet range eg., Sheet1:Sheet2. - if (preg_match("/:/", $ext_ref)) - { - list($sheet_name1, $sheet_name2) = explode(':', $ext_ref); - - $sheet1 = $this->_getSheetIndex($sheet_name1); - if ($sheet1 == -1) { - return $this->raiseError("Unknown sheet name $sheet_name1 in formula"); - } - $sheet2 = $this->_getSheetIndex($sheet_name2); - if ($sheet2 == -1) { - return $this->raiseError("Unknown sheet name $sheet_name2 in formula"); - } - - // Reverse max and min sheet numbers if necessary - if ($sheet1 > $sheet2) { - list($sheet1, $sheet2) = array($sheet2, $sheet1); - } - } - else // Single sheet name only. - { - $sheet1 = $this->_getSheetIndex($ext_ref); - if ($sheet1 == -1) { - return $this->raiseError("Unknown sheet name $ext_ref in formula"); - } - $sheet2 = $sheet1; - } - - // assume all references belong to this document - $supbook_index = 0x00; - $ref = pack('vvv', $supbook_index, $sheet1, $sheet2); - $total_references = count($this->_references); - $index = -1; - for ($i = 0; $i < $total_references; $i++) - { - if ($ref == $this->_references[$i]) { - $index = $i; - break; - } - } - // if REF was not found add it to references array - if ($index == -1) - { - $this->_references[$total_references] = $ref; - $index = $total_references; - } - - return pack('v', $index); - } - - /** - * Look up the index that corresponds to an external sheet name. The hash of - * sheet names is updated by the addworksheet() method of the - * Spreadsheet_Excel_Writer_Workbook class. - * - * @access private - * @return integer The sheet index, -1 if the sheet was not found - */ - function _getSheetIndex($sheet_name) - { - if (!isset($this->_ext_sheets[$sheet_name])) { - return -1; - } - else { - return $this->_ext_sheets[$sheet_name]; - } - } - - /** - * This method is used to update the array of sheet names. It is - * called by the addWorksheet() method of the - * Spreadsheet_Excel_Writer_Workbook class. - * - * @access public - * @see Spreadsheet_Excel_Writer_Workbook::addWorksheet() - * @param string $name The name of the worksheet being added - * @param integer $index The index of the worksheet being added - */ - function setExtSheet($name, $index) - { - $this->_ext_sheets[$name] = $index; - } - - /** - * pack() row and column into the required 3 or 4 byte format. - * - * @access private - * @param string $cell The Excel cell reference to be packed - * @return array Array containing the row and column in packed() format - */ - function _cellToPackedRowcol($cell) - { - $cell = strtoupper($cell); - list($row, $col, $row_rel, $col_rel) = $this->_cellToRowcol($cell); - if ($col >= 256) { - return $this->raiseError("Column in: $cell greater than 255"); - } - // FIXME: change for BIFF8 - if ($row >= 16384) { - return $this->raiseError("Row in: $cell greater than 16384 "); - } - - // Set the high bits to indicate if row or col are relative. - if ($this->_BIFF_version == 0x0500) { - $row |= $col_rel << 14; - $row |= $row_rel << 15; - $col = pack('C', $col); - } - elseif ($this->_BIFF_version == 0x0600) { - $col |= $col_rel << 14; - $col |= $row_rel << 15; - $col = pack('v', $col); - } - $row = pack('v', $row); - - return array($row, $col); - } - - /** - * pack() row range into the required 3 or 4 byte format. - * Just using maximum col/rows, which is probably not the correct solution - * - * @access private - * @param string $range The Excel range to be packed - * @return array Array containing (row1,col1,row2,col2) in packed() format - */ - function _rangeToPackedRange($range) - { - preg_match('/(\$)?(\d+)\:(\$)?(\d+)/', $range, $match); - // return absolute rows if there is a $ in the ref - $row1_rel = empty($match[1]) ? 1 : 0; - $row1 = $match[2]; - $row2_rel = empty($match[3]) ? 1 : 0; - $row2 = $match[4]; - // Convert 1-index to zero-index - $row1--; - $row2--; - // Trick poor inocent Excel - $col1 = 0; - $col2 = 16383; // FIXME: maximum possible value for Excel 5 (change this!!!) - - // FIXME: this changes for BIFF8 - if (($row1 >= 16384) or ($row2 >= 16384)) { - return $this->raiseError("Row in: $range greater than 16384 "); - } - - // Set the high bits to indicate if rows are relative. - if ($this->_BIFF_version == 0x0500) { - $row1 |= $row1_rel << 14; // FIXME: probably a bug - $row2 |= $row2_rel << 15; - $col1 = pack('C', $col1); - $col2 = pack('C', $col2); - } - elseif ($this->_BIFF_version == 0x0600) { - $col1 |= $row1_rel << 15; - $col2 |= $row2_rel << 15; - $col1 = pack('v', $col1); - $col2 = pack('v', $col2); - } - $row1 = pack('v', $row1); - $row2 = pack('v', $row2); - - return array($row1, $col1, $row2, $col2); - } - - /** - * Convert an Excel cell reference such as A1 or $B2 or C$3 or $D$4 to a zero - * indexed row and column number. Also returns two (0,1) values to indicate - * whether the row or column are relative references. - * - * @access private - * @param string $cell The Excel cell reference in A1 format. - * @return array - */ - function _cellToRowcol($cell) - { - preg_match('/(\$)?([A-I]?[A-Z])(\$)?(\d+)/',$cell,$match); - // return absolute column if there is a $ in the ref - $col_rel = empty($match[1]) ? 1 : 0; - $col_ref = $match[2]; - $row_rel = empty($match[3]) ? 1 : 0; - $row = $match[4]; - - // Convert base26 column string to a number. - $expn = strlen($col_ref) - 1; - $col = 0; - for ($i=0; $i < strlen($col_ref); $i++) - { - $col += (ord($col_ref{$i}) - ord('A') + 1) * pow(26, $expn); - $expn--; - } - - // Convert 1-index to zero-index - $row--; - $col--; - - return array($row, $col, $row_rel, $col_rel); - } - - /** - * Advance to the next valid token. - * - * @access private - */ - function _advance() - { - $i = $this->_current_char; - // eat up white spaces - if ($i < strlen($this->_formula)) - { - while ($this->_formula{$i} == " ") { - $i++; - } - if ($i < strlen($this->_formula) - 1) { - $this->_lookahead = $this->_formula{$i+1}; - } - $token = ""; - } - while ($i < strlen($this->_formula)) - { - $token .= $this->_formula{$i}; - if ($i < strlen($this->_formula) - 1) { - $this->_lookahead = $this->_formula{$i+1}; - } - else { - $this->_lookahead = ''; - } - if ($this->_match($token) != '') - { - //if ($i < strlen($this->_formula) - 1) { - // $this->_lookahead = $this->_formula{$i+1}; - //} - $this->_current_char = $i + 1; - $this->_current_token = $token; - return 1; - } - if ($i < strlen($this->_formula) - 2) { - $this->_lookahead = $this->_formula{$i+2}; - } - // if we run out of characters _lookahead becomes empty - else { - $this->_lookahead = ''; - } - $i++; - } - //die("Lexical error ".$this->_current_char); - } - - /** - * Checks if it's a valid token. - * - * @access private - * @param mixed $token The token to check. - * @return mixed The checked token or false on failure - */ - function _match($token) - { - switch($token) - { - case SPREADSHEET_EXCEL_WRITER_ADD: - return $token; - break; - case SPREADSHEET_EXCEL_WRITER_SUB: - return $token; - break; - case SPREADSHEET_EXCEL_WRITER_MUL: - return $token; - break; - case SPREADSHEET_EXCEL_WRITER_DIV: - return $token; - break; - case SPREADSHEET_EXCEL_WRITER_OPEN: - return $token; - break; - case SPREADSHEET_EXCEL_WRITER_CLOSE: - return $token; - break; - case SPREADSHEET_EXCEL_WRITER_COMA: - return $token; - break; - case SPREADSHEET_EXCEL_WRITER_SEMICOLON: - return $token; - break; - case SPREADSHEET_EXCEL_WRITER_GT: - if ($this->_lookahead == '=') { // it's a GE token - break; - } - return $token; - break; - case SPREADSHEET_EXCEL_WRITER_LT: - // it's a LE or a NE token - if (($this->_lookahead == '=') or ($this->_lookahead == '>')) { - break; - } - return $token; - break; - case SPREADSHEET_EXCEL_WRITER_GE: - return $token; - break; - case SPREADSHEET_EXCEL_WRITER_LE: - return $token; - break; - case SPREADSHEET_EXCEL_WRITER_EQ: - return $token; - break; - case SPREADSHEET_EXCEL_WRITER_NE: - return $token; - break; - default: - // if it's a reference - if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/',$token) and - !ereg("[0-9]",$this->_lookahead) and - ($this->_lookahead != ':') and ($this->_lookahead != '.') and - ($this->_lookahead != '!')) - { - return $token; - } - // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1) - elseif (preg_match("/^\w+(\:\w+)?\![A-Ia-i]?[A-Za-z][0-9]+$/",$token) and - !ereg("[0-9]",$this->_lookahead) and - ($this->_lookahead != ':') and ($this->_lookahead != '.')) - { - return $token; - } - // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1) - elseif (preg_match("/^'\w+(\:\w+)?'\![A-Ia-i]?[A-Za-z][0-9]+$/",$token) and - !ereg("[0-9]",$this->_lookahead) and - ($this->_lookahead != ':') and ($this->_lookahead != '.')) - { - return $token; - } - // if it's a range (A1:A2) - elseif (preg_match("/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/",$token) and - !ereg("[0-9]",$this->_lookahead)) - { - return $token; - } - // if it's a range (A1..A2) - elseif (preg_match("/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/",$token) and - !ereg("[0-9]",$this->_lookahead)) - { - return $token; - } - // If it's an external range like Sheet1!A1 or Sheet1:Sheet2!A1:B2 - elseif (preg_match("/^\w+(\:\w+)?\!([A-Ia-i]?[A-Za-z])?[0-9]+:([A-Ia-i]?[A-Za-z])?[0-9]+$/",$token) and - !ereg("[0-9]",$this->_lookahead)) - { - return $token; - } - // If it's an external range like 'Sheet1'!A1 or 'Sheet1:Sheet2'!A1:B2 - elseif (preg_match("/^'\w+(\:\w+)?'\!([A-Ia-i]?[A-Za-z])?[0-9]+:([A-Ia-i]?[A-Za-z])?[0-9]+$/",$token) and - !ereg("[0-9]",$this->_lookahead)) - { - return $token; - } - // If it's a number (check that it's not a sheet name or range) - elseif (is_numeric($token) and - (!is_numeric($token.$this->_lookahead) or ($this->_lookahead == '')) and - ($this->_lookahead != '!') and ($this->_lookahead != ':')) - { - return $token; - } - // If it's a string (of maximum 255 characters) - //elseif (ereg("^\"[^\"]{0,255}\"$",$token)) - elseif (preg_match("/{0,255}/",$token)) - { - return $token; - } - // if it's a function call - elseif (preg_match("/[A-Z0-9\xc0-\xdc\.]/",$token) and ($this->_lookahead == "(")) - { - return $token; - } - return ''; - } - } - - /** - * The parsing method. It parses a formula. - * - * @access public - * @param string $formula The formula to parse, without the initial equal - * sign (=). - * @return mixed true on success, PEAR_Error on failure - */ - function parse($formula) - { - $this->_current_char = 0; - $this->_formula = $formula; - $this->_lookahead = $formula{1}; - $this->_advance(); - $this->_parse_tree = $this->_condition(); - if (PEAR::isError($this->_parse_tree)) { - return $this->_parse_tree; - } - return true; - } - - /** - * It parses a condition. It assumes the following rule: - * Cond -> Expr [(">" | "<") Expr] - * - * @access private - * @return mixed The parsed ptg'd tree on success, PEAR_Error on failure - */ - function _condition() - { - $result = $this->_expression(); - if (PEAR::isError($result)) { - return $result; - } - if ($this->_current_token == SPREADSHEET_EXCEL_WRITER_LT) - { - $this->_advance(); - $result2 = $this->_expression(); - if (PEAR::isError($result2)) { - return $result2; - } - $result = $this->_createTree('ptgLT', $result, $result2); - } - elseif ($this->_current_token == SPREADSHEET_EXCEL_WRITER_GT) - { - $this->_advance(); - $result2 = $this->_expression(); - if (PEAR::isError($result2)) { - return $result2; - } - $result = $this->_createTree('ptgGT', $result, $result2); - } - elseif ($this->_current_token == SPREADSHEET_EXCEL_WRITER_LE) - { - $this->_advance(); - $result2 = $this->_expression(); - if (PEAR::isError($result2)) { - return $result2; - } - $result = $this->_createTree('ptgLE', $result, $result2); - } - elseif ($this->_current_token == SPREADSHEET_EXCEL_WRITER_GE) - { - $this->_advance(); - $result2 = $this->_expression(); - if (PEAR::isError($result2)) { - return $result2; - } - $result = $this->_createTree('ptgGE', $result, $result2); - } - elseif ($this->_current_token == SPREADSHEET_EXCEL_WRITER_EQ) - { - $this->_advance(); - $result2 = $this->_expression(); - if (PEAR::isError($result2)) { - return $result2; - } - $result = $this->_createTree('ptgEQ', $result, $result2); - } - elseif ($this->_current_token == SPREADSHEET_EXCEL_WRITER_NE) - { - $this->_advance(); - $result2 = $this->_expression(); - if (PEAR::isError($result2)) { - return $result2; - } - $result = $this->_createTree('ptgNE', $result, $result2); - } - return $result; - } - - /** - * It parses a expression. It assumes the following rule: - * Expr -> Term [("+" | "-") Term] - * -> "string" - * -> "-" Term - * - * @access private - * @return mixed The parsed ptg'd tree on success, PEAR_Error on failure - */ - function _expression() - { - // If it's a string return a string node - if (ereg("^\"[^\"]{0,255}\"$", $this->_current_token)) { - $result = $this->_createTree($this->_current_token, '', ''); - $this->_advance(); - return $result; - } - // catch "-" Term - elseif ($this->_current_token == SPREADSHEET_EXCEL_WRITER_SUB) { - $this->_advance(); - $result2 = $this->_expression(); - $result = $this->_createTree('ptgUminus', $result2, ''); - return $result; - } - $result = $this->_term(); - if (PEAR::isError($result)) { - return $result; - } - while (($this->_current_token == SPREADSHEET_EXCEL_WRITER_ADD) or - ($this->_current_token == SPREADSHEET_EXCEL_WRITER_SUB)) - { - if ($this->_current_token == SPREADSHEET_EXCEL_WRITER_ADD) - { - $this->_advance(); - $result2 = $this->_term(); - if (PEAR::isError($result2)) { - return $result2; - } - $result = $this->_createTree('ptgAdd', $result, $result2); - } - else - { - $this->_advance(); - $result2 = $this->_term(); - if (PEAR::isError($result2)) { - return $result2; - } - $result = $this->_createTree('ptgSub', $result, $result2); - } - } - return $result; - } - - /** - * This function just introduces a ptgParen element in the tree, so that Excel - * doesn't get confused when working with a parenthesized formula afterwards. - * - * @access private - * @see _fact() - * @return array The parsed ptg'd tree - */ - function _parenthesizedExpression() - { - $result = $this->_createTree('ptgParen', $this->_expression(), ''); - return $result; - } - - /** - * It parses a term. It assumes the following rule: - * Term -> Fact [("*" | "/") Fact] - * - * @access private - * @return mixed The parsed ptg'd tree on success, PEAR_Error on failure - */ - function _term() - { - $result = $this->_fact(); - if (PEAR::isError($result)) { - return $result; - } - while (($this->_current_token == SPREADSHEET_EXCEL_WRITER_MUL) or - ($this->_current_token == SPREADSHEET_EXCEL_WRITER_DIV)) - { - if ($this->_current_token == SPREADSHEET_EXCEL_WRITER_MUL) - { - $this->_advance(); - $result2 = $this->_fact(); - if (PEAR::isError($result2)) { - return $result2; - } - $result = $this->_createTree('ptgMul', $result, $result2); - } - else - { - $this->_advance(); - $result2 = $this->_fact(); - if (PEAR::isError($result2)) { - return $result2; - } - $result = $this->_createTree('ptgDiv', $result, $result2); - } - } - return $result; - } - - /** - * It parses a factor. It assumes the following rule: - * Fact -> ( Expr ) - * | CellRef - * | CellRange - * | Number - * | Function - * - * @access private - * @return mixed The parsed ptg'd tree on success, PEAR_Error on failure - */ - function _fact() - { - if ($this->_current_token == SPREADSHEET_EXCEL_WRITER_OPEN) - { - $this->_advance(); // eat the "(" - $result = $this->_parenthesizedExpression(); - if ($this->_current_token != SPREADSHEET_EXCEL_WRITER_CLOSE) { - return $this->raiseError("')' token expected."); - } - $this->_advance(); // eat the ")" - return $result; - } - // if it's a reference - if (preg_match('/^\$?[A-Ia-i]?[A-Za-z]\$?[0-9]+$/',$this->_current_token)) - { - $result = $this->_createTree($this->_current_token, '', ''); - $this->_advance(); - return $result; - } - // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1) - elseif (preg_match("/^\w+(\:\w+)?\![A-Ia-i]?[A-Za-z][0-9]+$/",$this->_current_token)) - { - $result = $this->_createTree($this->_current_token, '', ''); - $this->_advance(); - return $result; - } - // If it's an external reference (Sheet1!A1 or Sheet1:Sheet2!A1) - elseif (preg_match("/^'\w+(\:\w+)?'\![A-Ia-i]?[A-Za-z][0-9]+$/",$this->_current_token)) - { - $result = $this->_createTree($this->_current_token, '', ''); - $this->_advance(); - return $result; - } - // if it's a range - elseif (preg_match("/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+:(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/",$this->_current_token) or - preg_match("/^(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+\.\.(\$)?[A-Ia-i]?[A-Za-z](\$)?[0-9]+$/",$this->_current_token)) - { - $result = $this->_current_token; - $this->_advance(); - return $result; - } - // If it's an external range (Sheet1!A1 or Sheet1!A1:B2) - elseif (preg_match("/^\w+(\:\w+)?\!([A-Ia-i]?[A-Za-z])?[0-9]+:([A-Ia-i]?[A-Za-z])?[0-9]+$/",$this->_current_token)) - { - $result = $this->_current_token; - $this->_advance(); - return $result; - } - // If it's an external range ('Sheet1'!A1 or 'Sheet1'!A1:B2) - elseif (preg_match("/^'\w+(\:\w+)?'\!([A-Ia-i]?[A-Za-z])?[0-9]+:([A-Ia-i]?[A-Za-z])?[0-9]+$/",$this->_current_token)) - { - $result = $this->_current_token; - $this->_advance(); - return $result; - } - elseif (is_numeric($this->_current_token)) - { - $result = $this->_createTree($this->_current_token, '', ''); - $this->_advance(); - return $result; - } - // if it's a function call - elseif (preg_match("/[A-Z0-9\xc0-\xdc\.]/",$this->_current_token)) - { - $result = $this->_func(); - return $result; - } - return $this->raiseError("Syntax error: ".$this->_current_token. - ", lookahead: ".$this->_lookahead. - ", current char: ".$this->_current_char); - } - - /** - * It parses a function call. It assumes the following rule: - * Func -> ( Expr [,Expr]* ) - * - * @access private - * @return mixed The parsed ptg'd tree on success, PEAR_Error on failure - */ - function _func() - { - $num_args = 0; // number of arguments received - $function = $this->_current_token; - $this->_advance(); - $this->_advance(); // eat the "(" - while ($this->_current_token != ')') - { - if ($num_args > 0) - { - if ($this->_current_token == SPREADSHEET_EXCEL_WRITER_COMA || - $this->_current_token == SPREADSHEET_EXCEL_WRITER_SEMICOLON) - { - $this->_advance(); // eat the "," or ";" - } - else { - return $this->raiseError("Syntax error: comma expected in ". - "function $function, arg #{$num_args}"); - } - $result2 = $this->_condition(); - if (PEAR::isError($result2)) { - return $result2; - } - $result = $this->_createTree('arg', $result, $result2); - } - else // first argument - { - $result2 = $this->_condition(); - if (PEAR::isError($result2)) { - return $result2; - } - $result = $this->_createTree('arg', '', $result2); - } - $num_args++; - } - $args = $this->_functions[$function][1]; - // If fixed number of args eg. TIME($i,$j,$k). Check that the number of args is valid. - if (($args >= 0) and ($args != $num_args)) { - return $this->raiseError("Incorrect number of arguments in function $function() "); - } - - $result = $this->_createTree($function, $result, $num_args); - $this->_advance(); // eat the ")" - return $result; - } - - /** - * Creates a tree. In fact an array which may have one or two arrays (sub-trees) - * as elements. - * - * @access private - * @param mixed $value The value of this node. - * @param mixed $left The left array (sub-tree) or a final node. - * @param mixed $right The right array (sub-tree) or a final node. - * @return array A tree - */ - function _createTree($value, $left, $right) - { - return array('value' => $value, 'left' => $left, 'right' => $right); - } - - /** - * Builds a string containing the tree in reverse polish notation (What you - * would use in a HP calculator stack). - * The following tree: - * - * + - * / \ - * 2 3 - * - * produces: "23+" - * - * The following tree: - * - * + - * / \ - * 3 * - * / \ - * 6 A1 - * - * produces: "36A1*+" - * - * In fact all operands, functions, references, etc... are written as ptg's - * - * @access public - * @param array $tree The optional tree to convert. - * @return string The tree in reverse polish notation - */ - function toReversePolish($tree = array()) - { - $polish = ""; // the string we are going to return - if (empty($tree)) // If it's the first call use _parse_tree - { - $tree = $this->_parse_tree; - } - if (is_array($tree['left'])) - { - $converted_tree = $this->toReversePolish($tree['left']); - if (PEAR::isError($converted_tree)) { - return $converted_tree; - } - $polish .= $converted_tree; - } - elseif ($tree['left'] != '') // It's a final node - { - $converted_tree = $this->_convert($tree['left']); - if (PEAR::isError($converted_tree)) { - return $converted_tree; - } - $polish .= $converted_tree; - } - if (is_array($tree['right'])) - { - $converted_tree = $this->toReversePolish($tree['right']); - if (PEAR::isError($converted_tree)) { - return $converted_tree; - } - $polish .= $converted_tree; - } - elseif ($tree['right'] != '') // It's a final node - { - $converted_tree = $this->_convert($tree['right']); - if (PEAR::isError($converted_tree)) { - return $converted_tree; - } - $polish .= $converted_tree; - } - // if it's a function convert it here (so we can set it's arguments) - if (preg_match("/^[A-Z0-9\xc0-\xdc\.]+$/",$tree['value']) and - !preg_match('/^([A-Ia-i]?[A-Za-z])(\d+)$/',$tree['value']) and - !preg_match("/^[A-Ia-i]?[A-Za-z](\d+)\.\.[A-Ia-i]?[A-Za-z](\d+)$/",$tree['value']) and - !is_numeric($tree['value']) and - !isset($this->ptg[$tree['value']])) - { - // left subtree for a function is always an array. - if ($tree['left'] != '') { - $left_tree = $this->toReversePolish($tree['left']); - } - else { - $left_tree = ''; - } - if (PEAR::isError($left_tree)) { - return $left_tree; - } - // add it's left subtree and return. - return $left_tree.$this->_convertFunction($tree['value'], $tree['right']); - } - else - { - $converted_tree = $this->_convert($tree['value']); - if (PEAR::isError($converted_tree)) { - return $converted_tree; - } - } - $polish .= $converted_tree; - return $polish; - } -} -?> diff --git a/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer/Validator.php b/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer/Validator.php deleted file mode 100644 index 6d99afebf..000000000 --- a/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer/Validator.php +++ /dev/null @@ -1,225 +0,0 @@ - -* -* License Information: -* -* Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets -* Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com -* -* 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 -*/ - -//require_once('PEAR.php'); - -// Possible operator types - -/* -FIXME: change prefixes -*/ -define("OP_BETWEEN", 0x00); -define("OP_NOTBETWEEN", 0x01); -define("OP_EQUAL", 0x02); -define("OP_NOTEQUAL", 0x03); -define("OP_GT", 0x04); -define("OP_LT", 0x05); -define("OP_GTE", 0x06); -define("OP_LTE", 0x07); - -/** -* Baseclass for generating Excel DV records (validations) -* -* @author Herman Kuiper -* @category FileFormats -* @package Spreadsheet_Excel_Writer -*/ -class Spreadsheet_Excel_Writer_Validator -{ - var $_type; - var $_style; - var $_fixedList; - var $_blank; - var $_incell; - var $_showprompt; - var $_showerror; - var $_title_prompt; - var $_descr_prompt; - var $_title_error; - var $_descr_error; - var $_operator; - var $_formula1; - var $_formula2; - /** - * The parser from the workbook. Used to parse validation formulas also - * @var Spreadsheet_Excel_Writer_Parser - */ - var $_parser; - - function Spreadsheet_Excel_Writer_Validator(&$parser) - { - $this->_parser = $parser; - $this->_type = 0x01; // FIXME: add method for setting datatype - $this->_style = 0x00; - $this->_fixedList = false; - $this->_blank = false; - $this->_incell = false; - $this->_showprompt = false; - $this->_showerror = true; - $this->_title_prompt = "\x00"; - $this->_descr_prompt = "\x00"; - $this->_title_error = "\x00"; - $this->_descr_error = "\x00"; - $this->_operator = 0x00; // default is equal - $this->_formula1 = ""; - $this->_formula2 = ""; - } - - function setPrompt($promptTitle = "\x00", $promptDescription = "\x00", $showPrompt = true) - { - $this->_showprompt = $showPrompt; - $this->_title_prompt = $promptTitle; - $this->_descr_prompt = $promptDescription; - } - - function setError($errorTitle = "\x00", $errorDescription = "\x00", $showError = true) - { - $this->_showerror = $showError; - $this->_title_error = $errorTitle; - $this->_descr_error = $errorDescription; - } - - function allowBlank() - { - $this->_blank = true; - } - - function onInvalidStop() - { - $this->_style = 0x00; - } - - function onInvalidWarn() - { - $this->_style = 0x01; - } - - function onInvalidInfo() - { - $this->_style = 0x02; - } - - function setFormula1($formula) - { - // Parse the formula using the parser in Parser.php - $error = $this->_parser->parse($formula); - if (PEAR::isError($error)) { - return $this->_formula1; - } - - $this->_formula1 = $this->_parser->toReversePolish(); - if (PEAR::isError($this->_formula1)) { - return $this->_formula1; - } - return true; - } - - function setFormula2($formula) - { - // Parse the formula using the parser in Parser.php - $error = $this->_parser->parse($formula); - if (PEAR::isError($error)) { - return $this->_formula2; - } - - $this->_formula2 = $this->_parser->toReversePolish(); - if (PEAR::isError($this->_formula2)) { - return $this->_formula2; - } - return true; - } - - function _getOptions() - { - $options = $this->_type; - $options |= $this->_style << 3; - if($this->_fixedList) - $options |= 0x80; - if($this->_blank) - $options |= 0x100; - if(!$this->_incell) - $options |= 0x200; - if($this->_showprompt) - $options |= 0x40000; - if($this->_showerror) - $options |= 0x80000; - $options |= $this->_operator << 20; - - return $options; - } - - function _getData() - { - $title_prompt_len = strlen($this->_title_prompt); - $descr_prompt_len = strlen($this->_descr_prompt); - $title_error_len = strlen($this->_title_error); - $descr_error_len = strlen($this->_descr_error); - - $formula1_size = strlen($this->_formula1); - $formula2_size = strlen($this->_formula2); - - $data = pack("V", $this->_getOptions()); - $data .= pack("vC", $title_prompt_len, 0x00) . $this->_title_prompt; - $data .= pack("vC", $title_error_len, 0x00) . $this->_title_error; - $data .= pack("vC", $descr_prompt_len, 0x00) . $this->_descr_prompt; - $data .= pack("vC", $descr_error_len, 0x00) . $this->_descr_error; - - $data .= pack("vv", $formula1_size, 0x0000) . $this->_formula1; - $data .= pack("vv", $formula2_size, 0x0000) . $this->_formula2; - - return $data; - } -} - -/*class Spreadsheet_Excel_Writer_Validation_List extends Spreadsheet_Excel_Writer_Validation -{ - function Spreadsheet_Excel_Writer_Validation_list() - { - parent::Spreadsheet_Excel_Writer_Validation(); - $this->_type = 0x03; - } - - function setList($source, $incell = true) - { - $this->_incell = $incell; - $this->_fixedList = true; - - $source = implode("\x00", $source); - $this->_formula1 = pack("CCC", 0x17, strlen($source), 0x0c) . $source; - } - - function setRow($row, $col1, $col2, $incell = true) - { - $this->_incell = $incell; - //$this->_formula1 = ...; - } - - function setCol($col, $row1, $row2, $incell = true) - { - $this->_incell = $incell; - //$this->_formula1 = ...; - } -}*/ - -?> diff --git a/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer/Workbook.php b/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer/Workbook.php deleted file mode 100644 index 91f8a6b3d..000000000 --- a/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer/Workbook.php +++ /dev/null @@ -1,1545 +0,0 @@ - -* -* The majority of this is _NOT_ my code. I simply ported it from the -* PERL Spreadsheet::WriteExcel module. -* -* The author of the Spreadsheet::WriteExcel module is John McNamara -* -* -* I _DO_ maintain this code, and John McNamara has nothing to do with the -* porting of this code to PHP. Any questions directly related to this -* class library should be directed to me. -* -* License Information: -* -* Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets -* Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com -* -* 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 -*/ - -require_once('Spreadsheet/Excel/Writer/Format.php'); -require_once('Spreadsheet/Excel/Writer/BIFFwriter.php'); -require_once('Spreadsheet/Excel/Writer/Worksheet.php'); -require_once('Spreadsheet/Excel/Writer/Parser.php'); -require_once('OLE/PPS/Root.php'); -require_once('OLE/PPS/File.php'); - -/** -* Class for generating Excel Spreadsheets -* -* @author Xavier Noguer -* @category FileFormats -* @package Spreadsheet_Excel_Writer -*/ - -class Spreadsheet_Excel_Writer_Workbook extends Spreadsheet_Excel_Writer_BIFFwriter -{ - /** - * Filename for the Workbook - * @var string - */ - var $_filename; - - /** - * Formula parser - * @var object Parser - */ - var $_parser; - - /** - * Flag for 1904 date system (0 => base date is 1900, 1 => base date is 1904) - * @var integer - */ - var $_1904; - - /** - * The active worksheet of the workbook (0 indexed) - * @var integer - */ - var $_activesheet; - - /** - * 1st displayed worksheet in the workbook (0 indexed) - * @var integer - */ - var $_firstsheet; - - /** - * Number of workbook tabs selected - * @var integer - */ - var $_selected; - - /** - * Index for creating adding new formats to the workbook - * @var integer - */ - var $_xf_index; - - /** - * Flag for preventing close from being called twice. - * @var integer - * @see close() - */ - var $_fileclosed; - - /** - * The BIFF file size for the workbook. - * @var integer - * @see _calcSheetOffsets() - */ - var $_biffsize; - - /** - * The default sheetname for all sheets created. - * @var string - */ - var $_sheetname; - - /** - * The default XF format. - * @var object Format - */ - var $_tmp_format; - - /** - * Array containing references to all of this workbook's worksheets - * @var array - */ - var $_worksheets; - - /** - * Array of sheetnames for creating the EXTERNSHEET records - * @var array - */ - var $_sheetnames; - - /** - * Array containing references to all of this workbook's formats - * @var array - */ - var $_formats; - - /** - * Array containing the colour palette - * @var array - */ - var $_palette; - - /** - * The default format for URLs. - * @var object Format - */ - var $_url_format; - - /** - * The codepage indicates the text encoding used for strings - * @var integer - */ - var $_codepage; - - /** - * The country code used for localization - * @var integer - */ - var $_country_code; - - /** - * The temporary dir for storing the OLE file - * @var string - */ - var $_tmp_dir; - - /** - * Class constructor - * - * @param string filename for storing the workbook. "-" for writing to stdout. - * @access public - */ - function Spreadsheet_Excel_Writer_Workbook($filename) - { - // It needs to call its parent's constructor explicitly - $this->Spreadsheet_Excel_Writer_BIFFwriter(); - - $this->_filename = $filename; - $this->_parser =& new Spreadsheet_Excel_Writer_Parser($this->_byte_order, $this->_BIFF_version); - $this->_1904 = 0; - $this->_activesheet = 0; - $this->_firstsheet = 0; - $this->_selected = 0; - $this->_xf_index = 16; // 15 style XF's and 1 cell XF. - $this->_fileclosed = 0; - $this->_biffsize = 0; - $this->_sheetname = "Sheet"; - $this->_tmp_format =& new Spreadsheet_Excel_Writer_Format($this->_BIFF_version); - $this->_worksheets = array(); - $this->_sheetnames = array(); - $this->_formats = array(); - $this->_palette = array(); - $this->_codepage = 0x04E4; // FIXME: should change for BIFF8 - $this->_country_code = -1; - - // Add the default format for hyperlinks - $this->_url_format =& $this->addFormat(array('color' => 'blue', 'underline' => 1)); - $this->_str_total = 0; - $this->_str_unique = 0; - $this->_str_table = array(); - $this->_setPaletteXl97(); - $this->_tmp_dir = ''; - - // Add the default format Moneda - Currency (by JHL) - //$this->_currency_format =& $this->addFormat(array('color' => 'blue', 'underline' => 1)); - - } - - /** - * Calls finalization methods. - * This method should always be the last one to be called on every workbook - * - * @access public - * @return mixed true on success. PEAR_Error on failure - */ - function close() - { - if ($this->_fileclosed) { // Prevent close() from being called twice. - return true; - } - $res = $this->_storeWorkbook(); - if ($this->isError($res)) { - return $this->raiseError($res->getMessage()); - } - $this->_fileclosed = 1; - return true; - } - - /** - * An accessor for the _worksheets[] array - * Returns an array of the worksheet objects in a workbook - * It actually calls to worksheets() - * - * @access public - * @see worksheets() - * @return array - */ - function sheets() - { - return $this->worksheets(); - } - - /** - * An accessor for the _worksheets[] array. - * Returns an array of the worksheet objects in a workbook - * - * @access public - * @return array - */ - function worksheets() - { - return $this->_worksheets; - } - - /** - * Sets the BIFF version. - * This method exists just to access experimental functionality - * from BIFF8. It will be deprecated ! - * Only possible value is 8 (Excel 97/2000). - * For any other value it fails silently. - * - * @access public - * @param integer $version The BIFF version - */ - function setVersion($version) - { - if ($version == 8) { // only accept version 8 - $version = 0x0600; - $this->_BIFF_version = $version; - // change BIFFwriter limit for CONTINUE records - $this->_limit = 8224; - $this->_tmp_format->_BIFF_version = $version; - $this->_url_format->_BIFF_version = $version; - $this->_parser->_BIFF_version = $version; - $total_worksheets = count($this->_worksheets); - // change version for all worksheets too - for ($i = 0; $i < $total_worksheets; $i++) { - $this->_worksheets[$i]->_BIFF_version = $version; - } - $total_formats = count($this->_formats); - // change version for all formats too - for ($i = 0; $i < $total_formats; $i++) { - $this->_formats[$i]->_BIFF_version = $version; - } - } - } - - /** - * Set the country identifier for the workbook - * - * @access public - * @param integer $code Is the international calling country code for the - * chosen country. - */ - function setCountry($code) - { - $this->_country_code = $code; - } - - /** - * Add a new worksheet to the Excel workbook. - * If no name is given the name of the worksheet will be Sheeti$i, with - * $i in [1..]. - * - * @access public - * @param string $name the optional name of the worksheet - * @return mixed reference to a worksheet object on success, PEAR_Error - * on failure - */ - function &addWorksheet($name = '') - { - $index = count($this->_worksheets); - $sheetname = $this->_sheetname; - - if ($name == '') { - $name = $sheetname.($index+1); - } - - // Check that sheetname is <= 31 chars (Excel limit). - if (strlen($name) > 31) { - return $this->raiseError("Sheetname $name must be <= 31 chars"); - } - - // Check that the worksheet name doesn't already exist: a fatal Excel error. - $total_worksheets = count($this->_worksheets); - for ($i=0; $i < $total_worksheets; $i++) - { - if ($name == $this->_worksheets[$i]->getName()) { - return $this->raiseError("Worksheet '$name' already exists"); - } - } - - $worksheet = new Spreadsheet_Excel_Writer_Worksheet($this->_BIFF_version, - $name, $index, - $this->_activesheet, $this->_firstsheet, - $this->_str_total, $this->_str_unique, - $this->_str_table, $this->_url_format, - $this->_parser); - - $this->_worksheets[$index] = &$worksheet; // Store ref for iterator - $this->_sheetnames[$index] = $name; // Store EXTERNSHEET names - $this->_parser->setExtSheet($name, $index); // Register worksheet name with parser - return $worksheet; - } - - /** - * Add a new format to the Excel workbook. - * Also, pass any properties to the Format constructor. - * - * @access public - * @param array $properties array with properties for initializing the format. - * @return &Spreadsheet_Excel_Writer_Format reference to an Excel Format - */ - function &addFormat($properties = array()) - { - $format = new Spreadsheet_Excel_Writer_Format($this->_BIFF_version, $this->_xf_index,$properties); - $this->_xf_index += 1; - $this->_formats[] = &$format; - return $format; - } - - /** - * Create new validator. - * - * @access public - * @return &Spreadsheet_Excel_Writer_Validator reference to a Validator - */ - function &addValidator() - { - include_once('Spreadsheet/Excel/Writer/Validator.php'); - /* FIXME: check for successful inclusion*/ - $valid = new Spreadsheet_Excel_Writer_Validator($this->_parser); - return $valid; - } - - /** - * Change the RGB components of the elements in the colour palette. - * - * @access public - * @param integer $index colour index - * @param integer $red red RGB value [0-255] - * @param integer $green green RGB value [0-255] - * @param integer $blue blue RGB value [0-255] - * @return integer The palette index for the custom color - */ - function setCustomColor($index,$red,$green,$blue) - { - // Match a HTML #xxyyzz style parameter - /*if (defined $_[1] and $_[1] =~ /^#(\w\w)(\w\w)(\w\w)/ ) { - @_ = ($_[0], hex $1, hex $2, hex $3); - }*/ - - // Check that the colour index is the right range - if ($index < 8 or $index > 64) { - // TODO: assign real error codes - return $this->raiseError("Color index $index outside range: 8 <= index <= 64"); - } - - // Check that the colour components are in the right range - if ( ($red < 0 or $red > 255) or - ($green < 0 or $green > 255) or - ($blue < 0 or $blue > 255) ) - { - return $this->raiseError("Color component outside range: 0 <= color <= 255"); - } - - $index -= 8; // Adjust colour index (wingless dragonfly) - - // Set the RGB value - $this->_palette[$index] = array($red, $green, $blue, 0); - return($index + 8); - } - - /** - * Sets the colour palette to the Excel 97+ default. - * - * @access private - */ - function _setPaletteXl97() - { - $this->_palette = array( - array(0x00, 0x00, 0x00, 0x00), // 8 - array(0xff, 0xff, 0xff, 0x00), // 9 - array(0xff, 0x00, 0x00, 0x00), // 10 - array(0x00, 0xff, 0x00, 0x00), // 11 - array(0x00, 0x00, 0xff, 0x00), // 12 - array(0xff, 0xff, 0x00, 0x00), // 13 - array(0xff, 0x00, 0xff, 0x00), // 14 - array(0x00, 0xff, 0xff, 0x00), // 15 - array(0x80, 0x00, 0x00, 0x00), // 16 - array(0x00, 0x80, 0x00, 0x00), // 17 - array(0x00, 0x00, 0x80, 0x00), // 18 - array(0x80, 0x80, 0x00, 0x00), // 19 - array(0x80, 0x00, 0x80, 0x00), // 20 - array(0x00, 0x80, 0x80, 0x00), // 21 - array(0xc0, 0xc0, 0xc0, 0x00), // 22 - array(0x80, 0x80, 0x80, 0x00), // 23 - array(0x99, 0x99, 0xff, 0x00), // 24 - array(0x99, 0x33, 0x66, 0x00), // 25 - array(0xff, 0xff, 0xcc, 0x00), // 26 - array(0xcc, 0xff, 0xff, 0x00), // 27 - array(0x66, 0x00, 0x66, 0x00), // 28 - array(0xff, 0x80, 0x80, 0x00), // 29 - array(0x00, 0x66, 0xcc, 0x00), // 30 - array(0xcc, 0xcc, 0xff, 0x00), // 31 - array(0x00, 0x00, 0x80, 0x00), // 32 - array(0xff, 0x00, 0xff, 0x00), // 33 - array(0xff, 0xff, 0x00, 0x00), // 34 - array(0x00, 0xff, 0xff, 0x00), // 35 - array(0x80, 0x00, 0x80, 0x00), // 36 - array(0x80, 0x00, 0x00, 0x00), // 37 - array(0x00, 0x80, 0x80, 0x00), // 38 - array(0x00, 0x00, 0xff, 0x00), // 39 - array(0x00, 0xcc, 0xff, 0x00), // 40 - array(0xcc, 0xff, 0xff, 0x00), // 41 - array(0xcc, 0xff, 0xcc, 0x00), // 42 - array(0xff, 0xff, 0x99, 0x00), // 43 - array(0x99, 0xcc, 0xff, 0x00), // 44 - array(0xff, 0x99, 0xcc, 0x00), // 45 - array(0xcc, 0x99, 0xff, 0x00), // 46 - array(0xff, 0xcc, 0x99, 0x00), // 47 - array(0x33, 0x66, 0xff, 0x00), // 48 - array(0x33, 0xcc, 0xcc, 0x00), // 49 - array(0x99, 0xcc, 0x00, 0x00), // 50 - array(0xff, 0xcc, 0x00, 0x00), // 51 - array(0xff, 0x99, 0x00, 0x00), // 52 - array(0xff, 0x66, 0x00, 0x00), // 53 - array(0x66, 0x66, 0x99, 0x00), // 54 - array(0x96, 0x96, 0x96, 0x00), // 55 - array(0x00, 0x33, 0x66, 0x00), // 56 - array(0x33, 0x99, 0x66, 0x00), // 57 - array(0x00, 0x33, 0x00, 0x00), // 58 - array(0x33, 0x33, 0x00, 0x00), // 59 - array(0x99, 0x33, 0x00, 0x00), // 60 - array(0x99, 0x33, 0x66, 0x00), // 61 - array(0x33, 0x33, 0x99, 0x00), // 62 - array(0x33, 0x33, 0x33, 0x00), // 63 - ); - } - - /** - * Assemble worksheets into a workbook and send the BIFF data to an OLE - * storage. - * - * @access private - * @return mixed true on success. PEAR_Error on failure - */ - function _storeWorkbook() - { - // Ensure that at least one worksheet has been selected. - if ($this->_activesheet == 0) { - $this->_worksheets[0]->selected = 1; - } - - // Calculate the number of selected worksheet tabs and call the finalization - // methods for each worksheet - $total_worksheets = count($this->_worksheets); - for ($i=0; $i < $total_worksheets; $i++) { - if ($this->_worksheets[$i]->selected) { - $this->_selected++; - } - $this->_worksheets[$i]->close($this->_sheetnames); - } - - // Add Workbook globals - $this->_storeBof(0x0005); - if ($this->_BIFF_version == 0x0600) { - $this->_storeCodepage(); - $this->_storeWindow1(); - } - if ($this->_BIFF_version == 0x0500) { - $this->_storeExterns(); // For print area and repeat rows - } - $this->_storeNames(); // For print area and repeat rows - if ($this->_BIFF_version == 0x0500) { - $this->_storeWindow1(); - } - $this->_storeDatemode(); - $this->_storeAllFonts(); - $this->_storeAllNumFormats(); - $this->_storeAllXfs(); - $this->_storeAllStyles(); - $this->_storePalette(); - $this->_calcSheetOffsets(); - - // Add BOUNDSHEET records - for ($i=0; $i < $total_worksheets; $i++) { - $this->_storeBoundsheet($this->_worksheets[$i]->name,$this->_worksheets[$i]->offset); - } - - if ($this->_country_code != -1) { - $this->_storeCountry(); - } - - if ($this->_BIFF_version == 0x0600) { - //$this->_storeSupbookInternal(); - /* TODO: store external SUPBOOK records and XCT and CRN records - in case of external references for BIFF8 */ - //$this->_storeExternsheetBiff8(); - $this->_storeSharedStringsTable(); - } - - // End Workbook globals - $this->_storeEof(); - - // Store the workbook in an OLE container - $res = $this->_storeOLEFile(); - if ($this->isError($res)) { - return $this->raiseError($res->getMessage()); - } - return true; - } - - /** - * Sets the temp dir used for storing the OLE file - * - * @access public - * @param string $dir The dir to be used as temp dir - * @return true if given dir is valid, false otherwise - */ - function setTempDir($dir) - { - if (is_dir($dir)) { - $this->_tmp_dir = $dir; - return true; - } - return false; - } - - /** - * Store the workbook in an OLE container - * - * @access private - * @return mixed true on success. PEAR_Error on failure - */ - function _storeOLEFile() - { - $OLE = new OLE_PPS_File(OLE::Asc2Ucs('Book')); - if ($this->_tmp_dir != '') { - $OLE->setTempDir($this->_tmp_dir); - } - $res = $OLE->init(); - if ($this->isError($res)) { - return $this->raiseError("OLE Error: ".$res->getMessage()); - } - $OLE->append($this->_data); - $total_worksheets = count($this->_worksheets); - for ($i = 0; $i < $total_worksheets; $i++) - { - while ($tmp = $this->_worksheets[$i]->getData()) { - $OLE->append($tmp); - } - } - $root = new OLE_PPS_Root(time(), time(), array($OLE)); - if ($this->_tmp_dir != '') { - $root->setTempDir($this->_tmp_dir); - } - $res = $root->save($this->_filename); - if ($this->isError($res)) { - return $this->raiseError("OLE Error: ".$res->getMessage()); - } - return true; - } - - /** - * Calculate offsets for Worksheet BOF records. - * - * @access private - */ - function _calcSheetOffsets() - { - if ($this->_BIFF_version == 0x0600) { - $boundsheet_length = 12; // fixed length for a BOUNDSHEET record - } - else { - $boundsheet_length = 11; - } - $EOF = 4; - $offset = $this->_datasize; - - if ($this->_BIFF_version == 0x0600) { - // add the length of the SST - /* TODO: check this works for a lot of strings (> 8224 bytes) */ - $offset += $this->_calculateSharedStringsSizes(); - if ($this->_country_code != -1) { - $offset += 8; // adding COUNTRY record - } - // add the lenght of SUPBOOK, EXTERNSHEET and NAME records - //$offset += 8; // FIXME: calculate real value when storing the records - } - $total_worksheets = count($this->_worksheets); - // add the length of the BOUNDSHEET records - for ($i=0; $i < $total_worksheets; $i++) { - $offset += $boundsheet_length + strlen($this->_worksheets[$i]->name); - } - $offset += $EOF; - - for ($i=0; $i < $total_worksheets; $i++) { - $this->_worksheets[$i]->offset = $offset; - $offset += $this->_worksheets[$i]->_datasize; - } - $this->_biffsize = $offset; - } - - /** - * Store the Excel FONT records. - * - * @access private - */ - function _storeAllFonts() - { - // tmp_format is added by the constructor. We use this to write the default XF's - $format = $this->_tmp_format; - $font = $format->getFont(); - - // Note: Fonts are 0-indexed. According to the SDK there is no index 4, - // so the following fonts are 0, 1, 2, 3, 5 - // - for ($i=1; $i <= 5; $i++){ - $this->_append($font); - } - - // Iterate through the XF objects and write a FONT record if it isn't the - // same as the default FONT and if it hasn't already been used. - // - $fonts = array(); - $index = 6; // The first user defined FONT - - $key = $format->getFontKey(); // The default font from _tmp_format - $fonts[$key] = 0; // Index of the default font - - $total_formats = count($this->_formats); - for ($i=0; $i < $total_formats; $i++) - { - $key = $this->_formats[$i]->getFontKey(); - if (isset($fonts[$key])) { - // FONT has already been used - $this->_formats[$i]->font_index = $fonts[$key]; - } - else { - // Add a new FONT record - $fonts[$key] = $index; - $this->_formats[$i]->font_index = $index; - $index++; - $font = $this->_formats[$i]->getFont(); - $this->_append($font); - } - } - } - - /** - * Store user defined numerical formats i.e. FORMAT records - * - * @access private - */ - function _storeAllNumFormats() - { - // Leaning num_format syndrome - $hash_num_formats = array(); - $num_formats = array(); - $index = 164; - - // Iterate through the XF objects and write a FORMAT record if it isn't a - // built-in format type and if the FORMAT string hasn't already been used. - $total_formats = count($this->_formats); - for ($i=0; $i < $total_formats; $i++) - { - $num_format = $this->_formats[$i]->_num_format; - - // Check if $num_format is an index to a built-in format. - // Also check for a string of zeros, which is a valid format string - // but would evaluate to zero. - // - if (!preg_match("/^0+\d/",$num_format)) - { - if (preg_match("/^\d+$/",$num_format)) { // built-in format - continue; - } - } - - if (isset($hash_num_formats[$num_format])) { - // FORMAT has already been used - $this->_formats[$i]->_num_format = $hash_num_formats[$num_format]; - } - else{ - // Add a new FORMAT - $hash_num_formats[$num_format] = $index; - $this->_formats[$i]->_num_format = $index; - array_push($num_formats,$num_format); - $index++; - } - } - - // Write the new FORMAT records starting from 0xA4 - $index = 164; - foreach ($num_formats as $num_format) { - $this->_storeNumFormat($num_format,$index); - $index++; - } - } - - /** - * Write all XF records. - * - * @access private - */ - function _storeAllXfs() - { - // _tmp_format is added by the constructor. We use this to write the default XF's - // The default font index is 0 - // - $format = $this->_tmp_format; - for ($i=0; $i <= 14; $i++) { - $xf = $format->getXf('style'); // Style XF - $this->_append($xf); - } - - $xf = $format->getXf('cell'); // Cell XF - $this->_append($xf); - - // User defined XFs - $total_formats = count($this->_formats); - for ($i=0; $i < $total_formats; $i++) { - $xf = $this->_formats[$i]->getXf('cell'); - $this->_append($xf); - } - } - - /** - * Write all STYLE records. - * - * @access private - */ - function _storeAllStyles() - { - $this->_storeStyle(); - } - - /** - * Write the EXTERNCOUNT and EXTERNSHEET records. These are used as indexes for - * the NAME records. - * - * @access private - */ - function _storeExterns() - { - // Create EXTERNCOUNT with number of worksheets - $this->_storeExterncount(count($this->_worksheets)); - - // Create EXTERNSHEET for each worksheet - foreach ($this->_sheetnames as $sheetname) { - $this->_storeExternsheet($sheetname); - } - } - - /** - * Write the NAME record to define the print area and the repeat rows and cols. - * - * @access private - */ - function _storeNames() - { - // Create the print area NAME records - $total_worksheets = count($this->_worksheets); - for ($i = 0; $i < $total_worksheets; $i++) { - // Write a Name record if the print area has been defined - if (isset($this->_worksheets[$i]->print_rowmin)) - { - $this->_storeNameShort( - $this->_worksheets[$i]->index, - 0x06, // NAME type - $this->_worksheets[$i]->print_rowmin, - $this->_worksheets[$i]->print_rowmax, - $this->_worksheets[$i]->print_colmin, - $this->_worksheets[$i]->print_colmax - ); - } - } - - // Create the print title NAME records - $total_worksheets = count($this->_worksheets); - for ($i = 0; $i < $total_worksheets; $i++) { - $rowmin = $this->_worksheets[$i]->title_rowmin; - $rowmax = $this->_worksheets[$i]->title_rowmax; - $colmin = $this->_worksheets[$i]->title_colmin; - $colmax = $this->_worksheets[$i]->title_colmax; - - // Determine if row + col, row, col or nothing has been defined - // and write the appropriate record - // - if (isset($rowmin) and isset($colmin)) { - // Row and column titles have been defined. - // Row title has been defined. - $this->_storeNameLong( - $this->_worksheets[$i]->index, - 0x07, // NAME type - $rowmin, - $rowmax, - $colmin, - $colmax - ); - } - elseif (isset($rowmin)) { - // Row title has been defined. - $this->_storeNameShort( - $this->_worksheets[$i]->index, - 0x07, // NAME type - $rowmin, - $rowmax, - 0x00, - 0xff - ); - } - elseif (isset($colmin)) { - // Column title has been defined. - $this->_storeNameShort( - $this->_worksheets[$i]->index, - 0x07, // NAME type - 0x0000, - 0x3fff, - $colmin, - $colmax - ); - } - else { - // Print title hasn't been defined. - } - } - } - - - - - /****************************************************************************** - * - * BIFF RECORDS - * - */ - - /** - * Stores the CODEPAGE biff record. - * - * @access private - */ - function _storeCodepage() - { - $record = 0x0042; // Record identifier - $length = 0x0002; // Number of bytes to follow - $cv = $this->_codepage; // The code page - - $header = pack('vv', $record, $length); - $data = pack('v', $cv); - - $this->_append($header.$data); - } - - /** - * Write Excel BIFF WINDOW1 record. - * - * @access private - */ - function _storeWindow1() - { - $record = 0x003D; // Record identifier - $length = 0x0012; // Number of bytes to follow - - $xWn = 0x0000; // Horizontal position of window - $yWn = 0x0000; // Vertical position of window - $dxWn = 0x25BC; // Width of window - $dyWn = 0x1572; // Height of window - - $grbit = 0x0038; // Option flags - $ctabsel = $this->_selected; // Number of workbook tabs selected - $wTabRatio = 0x0258; // Tab to scrollbar ratio - - $itabFirst = $this->_firstsheet; // 1st displayed worksheet - $itabCur = $this->_activesheet; // Active worksheet - - $header = pack("vv", $record, $length); - $data = pack("vvvvvvvvv", $xWn, $yWn, $dxWn, $dyWn, - $grbit, - $itabCur, $itabFirst, - $ctabsel, $wTabRatio); - $this->_append($header.$data); - } - - /** - * Writes Excel BIFF BOUNDSHEET record. - * FIXME: inconsistent with BIFF documentation - * - * @param string $sheetname Worksheet name - * @param integer $offset Location of worksheet BOF - * @access private - */ - function _storeBoundsheet($sheetname,$offset) - { - $record = 0x0085; // Record identifier - if ($this->_BIFF_version == 0x0600) { - $length = 0x08 + strlen($sheetname); // Number of bytes to follow - } - else { - $length = 0x07 + strlen($sheetname); // Number of bytes to follow - } - - $grbit = 0x0000; // Visibility and sheet type - $cch = strlen($sheetname); // Length of sheet name - - $header = pack("vv", $record, $length); - if ($this->_BIFF_version == 0x0600) { - $data = pack("Vvv", $offset, $grbit, $cch); - } - else { - $data = pack("VvC", $offset, $grbit, $cch); - } - $this->_append($header.$data.$sheetname); - } - - /** - * Write Internal SUPBOOK record - * - * @access private - */ - function _storeSupbookInternal() - { - $record = 0x01AE; // Record identifier - $length = 0x0004; // Bytes to follow - - $header = pack("vv", $record, $length); - $data = pack("vv", count($this->_worksheets), 0x0104); - $this->_append($header.$data); - } - - /** - * Writes the Excel BIFF EXTERNSHEET record. These references are used by - * formulas. - * - * @param string $sheetname Worksheet name - * @access private - */ - function _storeExternsheetBiff8() - { - $total_references = count($this->_parser->_references); - $record = 0x0017; // Record identifier - $length = 2 + 6 * $total_references; // Number of bytes to follow - - $supbook_index = 0; // FIXME: only using internal SUPBOOK record - $header = pack("vv", $record, $length); - $data = pack('v', $total_references); - for ($i = 0; $i < $total_references; $i++) { - $data .= $this->_parser->_references[$i]; - } - $this->_append($header.$data); - } - - /** - * Write Excel BIFF STYLE records. - * - * @access private - */ - function _storeStyle() - { - $record = 0x0293; // Record identifier - $length = 0x0004; // Bytes to follow - - $ixfe = 0x8000; // Index to style XF - $BuiltIn = 0x00; // Built-in style - $iLevel = 0xff; // Outline style level - - $header = pack("vv", $record, $length); - $data = pack("vCC", $ixfe, $BuiltIn, $iLevel); - $this->_append($header.$data); - } - - - /** - * Writes Excel FORMAT record for non "built-in" numerical formats. - * - * @param string $format Custom format string - * @param integer $ifmt Format index code - * @access private - */ - function _storeNumFormat($format,$ifmt) - { - $record = 0x041E; // Record identifier - - if ($this->_BIFF_version == 0x0600) { - $length = 5 + strlen($format); // Number of bytes to follow - $encoding = 0x0; - } - elseif ($this->_BIFF_version == 0x0500) { - $length = 3 + strlen($format); // Number of bytes to follow - } - - $cch = strlen($format); // Length of format string - - $header = pack("vv", $record, $length); - if ($this->_BIFF_version == 0x0600) { - $data = pack("vvC", $ifmt, $cch, $encoding); - } - elseif ($this->_BIFF_version == 0x0500) { - $data = pack("vC", $ifmt, $cch); - } - $this->_append($header.$data.$format); - } - - /** - * Write DATEMODE record to indicate the date system in use (1904 or 1900). - * - * @access private - */ - function _storeDatemode() - { - $record = 0x0022; // Record identifier - $length = 0x0002; // Bytes to follow - - $f1904 = $this->_1904; // Flag for 1904 date system - - $header = pack("vv", $record, $length); - $data = pack("v", $f1904); - $this->_append($header.$data); - } - - - /** - * Write BIFF record EXTERNCOUNT to indicate the number of external sheet - * references in the workbook. - * - * Excel only stores references to external sheets that are used in NAME. - * The workbook NAME record is required to define the print area and the repeat - * rows and columns. - * - * A similar method is used in Worksheet.php for a slightly different purpose. - * - * @param integer $cxals Number of external references - * @access private - */ - function _storeExterncount($cxals) - { - $record = 0x0016; // Record identifier - $length = 0x0002; // Number of bytes to follow - - $header = pack("vv", $record, $length); - $data = pack("v", $cxals); - $this->_append($header.$data); - } - - - /** - * Writes the Excel BIFF EXTERNSHEET record. These references are used by - * formulas. NAME record is required to define the print area and the repeat - * rows and columns. - * - * A similar method is used in Worksheet.php for a slightly different purpose. - * - * @param string $sheetname Worksheet name - * @access private - */ - function _storeExternsheet($sheetname) - { - $record = 0x0017; // Record identifier - $length = 0x02 + strlen($sheetname); // Number of bytes to follow - - $cch = strlen($sheetname); // Length of sheet name - $rgch = 0x03; // Filename encoding - - $header = pack("vv", $record, $length); - $data = pack("CC", $cch, $rgch); - $this->_append($header.$data.$sheetname); - } - - - /** - * Store the NAME record in the short format that is used for storing the print - * area, repeat rows only and repeat columns only. - * - * @param integer $index Sheet index - * @param integer $type Built-in name type - * @param integer $rowmin Start row - * @param integer $rowmax End row - * @param integer $colmin Start colum - * @param integer $colmax End column - * @access private - */ - function _storeNameShort($index,$type,$rowmin,$rowmax,$colmin,$colmax) - { - $record = 0x0018; // Record identifier - $length = 0x0024; // Number of bytes to follow - - $grbit = 0x0020; // Option flags - $chKey = 0x00; // Keyboard shortcut - $cch = 0x01; // Length of text name - $cce = 0x0015; // Length of text definition - $ixals = $index + 1; // Sheet index - $itab = $ixals; // Equal to ixals - $cchCustMenu = 0x00; // Length of cust menu text - $cchDescription = 0x00; // Length of description text - $cchHelptopic = 0x00; // Length of help topic text - $cchStatustext = 0x00; // Length of status bar text - $rgch = $type; // Built-in name type - - $unknown03 = 0x3b; - $unknown04 = 0xffff-$index; - $unknown05 = 0x0000; - $unknown06 = 0x0000; - $unknown07 = 0x1087; - $unknown08 = 0x8005; - - $header = pack("vv", $record, $length); - $data = pack("v", $grbit); - $data .= pack("C", $chKey); - $data .= pack("C", $cch); - $data .= pack("v", $cce); - $data .= pack("v", $ixals); - $data .= pack("v", $itab); - $data .= pack("C", $cchCustMenu); - $data .= pack("C", $cchDescription); - $data .= pack("C", $cchHelptopic); - $data .= pack("C", $cchStatustext); - $data .= pack("C", $rgch); - $data .= pack("C", $unknown03); - $data .= pack("v", $unknown04); - $data .= pack("v", $unknown05); - $data .= pack("v", $unknown06); - $data .= pack("v", $unknown07); - $data .= pack("v", $unknown08); - $data .= pack("v", $index); - $data .= pack("v", $index); - $data .= pack("v", $rowmin); - $data .= pack("v", $rowmax); - $data .= pack("C", $colmin); - $data .= pack("C", $colmax); - $this->_append($header.$data); - } - - - /** - * Store the NAME record in the long format that is used for storing the repeat - * rows and columns when both are specified. This shares a lot of code with - * _storeNameShort() but we use a separate method to keep the code clean. - * Code abstraction for reuse can be carried too far, and I should know. ;-) - * - * @param integer $index Sheet index - * @param integer $type Built-in name type - * @param integer $rowmin Start row - * @param integer $rowmax End row - * @param integer $colmin Start colum - * @param integer $colmax End column - * @access private - */ - function _storeNameLong($index,$type,$rowmin,$rowmax,$colmin,$colmax) - { - $record = 0x0018; // Record identifier - $length = 0x003d; // Number of bytes to follow - $grbit = 0x0020; // Option flags - $chKey = 0x00; // Keyboard shortcut - $cch = 0x01; // Length of text name - $cce = 0x002e; // Length of text definition - $ixals = $index + 1; // Sheet index - $itab = $ixals; // Equal to ixals - $cchCustMenu = 0x00; // Length of cust menu text - $cchDescription = 0x00; // Length of description text - $cchHelptopic = 0x00; // Length of help topic text - $cchStatustext = 0x00; // Length of status bar text - $rgch = $type; // Built-in name type - - $unknown01 = 0x29; - $unknown02 = 0x002b; - $unknown03 = 0x3b; - $unknown04 = 0xffff-$index; - $unknown05 = 0x0000; - $unknown06 = 0x0000; - $unknown07 = 0x1087; - $unknown08 = 0x8008; - - $header = pack("vv", $record, $length); - $data = pack("v", $grbit); - $data .= pack("C", $chKey); - $data .= pack("C", $cch); - $data .= pack("v", $cce); - $data .= pack("v", $ixals); - $data .= pack("v", $itab); - $data .= pack("C", $cchCustMenu); - $data .= pack("C", $cchDescription); - $data .= pack("C", $cchHelptopic); - $data .= pack("C", $cchStatustext); - $data .= pack("C", $rgch); - $data .= pack("C", $unknown01); - $data .= pack("v", $unknown02); - // Column definition - $data .= pack("C", $unknown03); - $data .= pack("v", $unknown04); - $data .= pack("v", $unknown05); - $data .= pack("v", $unknown06); - $data .= pack("v", $unknown07); - $data .= pack("v", $unknown08); - $data .= pack("v", $index); - $data .= pack("v", $index); - $data .= pack("v", 0x0000); - $data .= pack("v", 0x3fff); - $data .= pack("C", $colmin); - $data .= pack("C", $colmax); - // Row definition - $data .= pack("C", $unknown03); - $data .= pack("v", $unknown04); - $data .= pack("v", $unknown05); - $data .= pack("v", $unknown06); - $data .= pack("v", $unknown07); - $data .= pack("v", $unknown08); - $data .= pack("v", $index); - $data .= pack("v", $index); - $data .= pack("v", $rowmin); - $data .= pack("v", $rowmax); - $data .= pack("C", 0x00); - $data .= pack("C", 0xff); - // End of data - $data .= pack("C", 0x10); - $this->_append($header.$data); - } - - /** - * Stores the COUNTRY record for localization - * - * @access private - */ - function _storeCountry() - { - $record = 0x008C; // Record identifier - $length = 4; // Number of bytes to follow - - $header = pack('vv', $record, $length); - /* using the same country code always for simplicity */ - $data = pack('vv', $this->_country_code, $this->_country_code); - $this->_append($header.$data); - } - - /** - * Stores the PALETTE biff record. - * - * @access private - */ - function _storePalette() - { - $aref = $this->_palette; - - $record = 0x0092; // Record identifier - $length = 2 + 4 * count($aref); // Number of bytes to follow - $ccv = count($aref); // Number of RGB values to follow - $data = ''; // The RGB data - - // Pack the RGB data - foreach($aref as $color) - { - foreach($color as $byte) { - $data .= pack("C",$byte); - } - } - - $header = pack("vvv", $record, $length, $ccv); - $this->_append($header.$data); - } - - /** - * Calculate - * Handling of the SST continue blocks is complicated by the need to include an - * additional continuation byte depending on whether the string is split between - * blocks or whether it starts at the beginning of the block. (There are also - * additional complications that will arise later when/if Rich Strings are - * supported). - * - * @access private - */ - function _calculateSharedStringsSizes() - { - /* Iterate through the strings to calculate the CONTINUE block sizes. - The SST blocks requires a specialised CONTINUE block, so we have to - ensure that the maximum data block size is less than the limit used by - _add_continue() in BIFFwriter.pm. For simplicity we use the same size - for the SST and CONTINUE records: - 8228 : Maximum Excel97 block size - -4 : Length of block header - -8 : Length of additional SST header information - -8 : Arbitrary number to keep within _add_continue() limit - = 8208 - */ - $total_offset = 12; - $continue_limit = 8208; - $block_length = 0; - $written = 0; - $this->_block_sizes = array(); - $continue = 0; - - foreach (array_keys($this->_str_table) as $string) { - $string_length = strlen($string); - - // Block length is the total length of the strings that will be - // written out in a single SST or CONTINUE block. - $block_length += $string_length; - - // We can write the string if it doesn't cross a CONTINUE boundary - if ($block_length < $continue_limit) { - $written += $string_length; - $total_offset += $string_length; - continue; - } - - // Deal with the cases where the next string to be written will exceed - // the CONTINUE boundary. If the string is very long it may need to be - // written in more than one CONTINUE record. - while ($block_length >= $continue_limit) { - - // We need to avoid the case where a string is continued in the first - // n bytes that contain the string header information. - $header_length = 3; // Min string + header size -1 - $space_remaining = $continue_limit - $written - $continue; - - - /* TODO: Unicode data should only be split on char (2 byte) - boundaries. Therefore, in some cases we need to reduce the - amount of available - */ - - if ($space_remaining > $header_length) { - // Write as much as possible of the string in the current block - $written += $space_remaining; - - // Reduce the current block length by the amount written - $block_length -= $continue_limit + $continue; - - // Store the max size for this block - $this->_block_sizes[] = $continue_limit; - - // If the current string was split then the next CONTINUE block - // should have the string continue flag (grbit) set unless the - // split string fits exactly into the remaining space. - if ($block_length > 0) { - $continue = 1; - } - else { - $continue = 0; - } - - } - else { - // Store the max size for this block - $this->_block_sizes[] = $written + $continue; - - // Not enough space to start the string in the current block - $block_length -= $continue_limit - $space_remaining - $continue; - $continue = 0; - - } - - // If the string (or substr) is small enough we can write it in the - // new CONTINUE block. Else, go through the loop again to write it in - // one or more CONTINUE blocks - if ($block_length < $continue_limit) { - $written = $block_length; - } - else { - $written = 0; - } - } - } - - // Store the max size for the last block unless it is empty - if ($written + $continue) { - $this->_block_sizes[] = $written + $continue; - } - - - /* Calculate the total length of the SST and associated CONTINUEs (if any). - The SST record will have a length even if it contains no strings. - This length is required to set the offsets in the BOUNDSHEET records since - they must be written before the SST records - */ - if (!empty($this->_block_sizes)) { - $total_offset += (count($this->_block_sizes) - 1) * 4; // add CONTINUE headers - } - return $total_offset; - } - - /** - * Write all of the workbooks strings into an indexed array. - * See the comments in _calculate_shared_string_sizes() for more information. - * - * The Excel documentation says that the SST record should be followed by an - * EXTSST record. The EXTSST record is a hash table that is used to optimise - * access to SST. However, despite the documentation it doesn't seem to be - * required so we will ignore it. - * - * @access private - */ - /* FIXME: update _calcSheetOffsets() when updating this method */ - function _storeSharedStringsTable() - { - $record = 0x00fc; // Record identifier - $length = 8 + array_sum($this->_block_sizes); // Number of bytes to follow - - // Write the SST block header information - $header = pack("vv", $record, $length); - $data = pack("VV", $this->_str_total, $this->_str_unique); - $this->_append($header.$data); - - - // Iterate through the strings to calculate the CONTINUE block sizes - $continue_limit = 8208; - $block_length = 0; - $written = 0; - $continue = 0; - - - /* TODO: not good for performance */ - foreach (array_keys($this->_str_table) as $string) { - - $string_length = strlen($string); - $encoding = 0; // assume there are no Unicode strings - $split_string = 0; - - // Block length is the total length of the strings that will be - // written out in a single SST or CONTINUE block. - // - $block_length += $string_length; - - - // We can write the string if it doesn't cross a CONTINUE boundary - if ($block_length < $continue_limit) { - $this->_append($string); - $written += $string_length; - continue; - } - - // Deal with the cases where the next string to be written will exceed - // the CONTINUE boundary. If the string is very long it may need to be - // written in more than one CONTINUE record. - // - while ($block_length >= $continue_limit) { - - // We need to avoid the case where a string is continued in the first - // n bytes that contain the string header information. - // - $header_length = 3; // Min string + header size -1 - $space_remaining = $continue_limit - $written - $continue; - - - // Unicode data should only be split on char (2 byte) boundaries. - // Therefore, in some cases we need to reduce the amount of available - - if ($space_remaining > $header_length) { - // Write as much as possible of the string in the current block - $tmp = substr($string, 0, $space_remaining); - $this->_append($tmp); - - // The remainder will be written in the next block(s) - $string = substr($string, $space_remaining); - - // Reduce the current block length by the amount written - $block_length -= $continue_limit - $continue; - - // If the current string was split then the next CONTINUE block - // should have the string continue flag (grbit) set unless the - // split string fits exactly into the remaining space. - // - if ($block_length > 0) { - $continue = 1; - } - else { - $continue = 0; - } - } - else { - // Not enough space to start the string in the current block - $block_length -= $continue_limit - $space_remaining - $continue; - $continue = 0; - } - - // Write the CONTINUE block header - if (!empty($this->_block_sizes)) { - $record = 0x003C; - $length = array_pop($this->_block_sizes); - - $header = pack('vv', $record, $length); - if ($continue) { - $header .= pack('C', $encoding); - } - $this->_append($header); - } - - // If the string (or substr) is small enough we can write it in the - // new CONTINUE block. Else, go through the loop again to write it in - // one or more CONTINUE blocks - // - if ($block_length < $continue_limit) { - $this->_append($string); - - $written = $block_length; - } - else { - $written = 0; - } - } - } - } -} -?> diff --git a/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer/Worksheet.php b/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer/Worksheet.php deleted file mode 100644 index 64cb22c78..000000000 --- a/gulliver/thirdparty/pear/Spreadsheet/Excel/Writer/Worksheet.php +++ /dev/null @@ -1,3495 +0,0 @@ - -* -* The majority of this is _NOT_ my code. I simply ported it from the -* PERL Spreadsheet::WriteExcel module. -* -* The author of the Spreadsheet::WriteExcel module is John McNamara -* -* -* I _DO_ maintain this code, and John McNamara has nothing to do with the -* porting of this code to PHP. Any questions directly related to this -* class library should be directed to me. -* -* License Information: -* -* Spreadsheet_Excel_Writer: A library for generating Excel Spreadsheets -* Copyright (c) 2002-2003 Xavier Noguer xnoguer@rezebra.com -* -* 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 -*/ - -require_once('Spreadsheet/Excel/Writer/Parser.php'); -require_once('Spreadsheet/Excel/Writer/BIFFwriter.php'); - -/** -* Class for generating Excel Spreadsheets -* -* @author Xavier Noguer -* @category FileFormats -* @package Spreadsheet_Excel_Writer -*/ - -class Spreadsheet_Excel_Writer_Worksheet extends Spreadsheet_Excel_Writer_BIFFwriter -{ - /** - * Name of the Worksheet - * @var string - */ - var $name; - - /** - * Index for the Worksheet - * @var integer - */ - var $index; - - /** - * Reference to the (default) Format object for URLs - * @var object Format - */ - var $_url_format; - - /** - * Reference to the parser used for parsing formulas - * @var object Format - */ - var $_parser; - - /** - * Filehandle to the temporary file for storing data - * @var resource - */ - var $_filehandle; - - /** - * Boolean indicating if we are using a temporary file for storing data - * @var bool - */ - var $_using_tmpfile; - - /** - * Maximum number of rows for an Excel spreadsheet (BIFF5) - * @var integer - */ - var $_xls_rowmax; - - /** - * Maximum number of columns for an Excel spreadsheet (BIFF5) - * @var integer - */ - var $_xls_colmax; - - /** - * Maximum number of characters for a string (LABEL record in BIFF5) - * @var integer - */ - var $_xls_strmax; - - /** - * First row for the DIMENSIONS record - * @var integer - * @see _storeDimensions() - */ - var $_dim_rowmin; - - /** - * Last row for the DIMENSIONS record - * @var integer - * @see _storeDimensions() - */ - var $_dim_rowmax; - - /** - * First column for the DIMENSIONS record - * @var integer - * @see _storeDimensions() - */ - var $_dim_colmin; - - /** - * Last column for the DIMENSIONS record - * @var integer - * @see _storeDimensions() - */ - var $_dim_colmax; - - /** - * Array containing format information for columns - * @var array - */ - var $_colinfo; - - /** - * Array containing the selected area for the worksheet - * @var array - */ - var $_selection; - - /** - * Array containing the panes for the worksheet - * @var array - */ - var $_panes; - - /** - * The active pane for the worksheet - * @var integer - */ - var $_active_pane; - - /** - * Bit specifying if panes are frozen - * @var integer - */ - var $_frozen; - - /** - * Bit specifying if the worksheet is selected - * @var integer - */ - var $selected; - - /** - * The paper size (for printing) (DOCUMENT!!!) - * @var integer - */ - var $_paper_size; - - /** - * Bit specifying paper orientation (for printing). 0 => landscape, 1 => portrait - * @var integer - */ - var $_orientation; - - /** - * The page header caption - * @var string - */ - var $_header; - - /** - * The page footer caption - * @var string - */ - var $_footer; - - /** - * The horizontal centering value for the page - * @var integer - */ - var $_hcenter; - - /** - * The vertical centering value for the page - * @var integer - */ - var $_vcenter; - - /** - * The margin for the header - * @var float - */ - var $_margin_head; - - /** - * The margin for the footer - * @var float - */ - var $_margin_foot; - - /** - * The left margin for the worksheet in inches - * @var float - */ - var $_margin_left; - - /** - * The right margin for the worksheet in inches - * @var float - */ - var $_margin_right; - - /** - * The top margin for the worksheet in inches - * @var float - */ - var $_margin_top; - - /** - * The bottom margin for the worksheet in inches - * @var float - */ - var $_margin_bottom; - - /** - * First row to reapeat on each printed page - * @var integer - */ - var $title_rowmin; - - /** - * Last row to reapeat on each printed page - * @var integer - */ - var $title_rowmax; - - /** - * First column to reapeat on each printed page - * @var integer - */ - var $title_colmin; - - /** - * First row of the area to print - * @var integer - */ - var $print_rowmin; - - /** - * Last row to of the area to print - * @var integer - */ - var $print_rowmax; - - /** - * First column of the area to print - * @var integer - */ - var $print_colmin; - - /** - * Last column of the area to print - * @var integer - */ - var $print_colmax; - - /** - * Whether to use outline. - * @var integer - */ - var $_outline_on; - - /** - * Auto outline styles. - * @var bool - */ - var $_outline_style; - - /** - * Whether to have outline summary below. - * @var bool - */ - var $_outline_below; - - /** - * Whether to have outline summary at the right. - * @var bool - */ - var $_outline_right; - - /** - * Outline row level. - * @var integer - */ - var $_outline_row_level; - - /** - * Whether to fit to page when printing or not. - * @var bool - */ - var $_fit_page; - - /** - * Number of pages to fit wide - * @var integer - */ - var $_fit_width; - - /** - * Number of pages to fit high - * @var integer - */ - var $_fit_height; - - /** - * Reference to the total number of strings in the workbook - * @var integer - */ - var $_str_total; - - /** - * Reference to the number of unique strings in the workbook - * @var integer - */ - var $_str_unique; - - /** - * Reference to the array containing all the unique strings in the workbook - * @var array - */ - var $_str_table; - - /** - * Merged cell ranges - * @var array - */ - var $_merged_ranges; - - /** - * Constructor - * - * @param string $name The name of the new worksheet - * @param integer $index The index of the new worksheet - * @param mixed &$activesheet The current activesheet of the workbook we belong to - * @param mixed &$firstsheet The first worksheet in the workbook we belong to - * @param mixed &$url_format The default format for hyperlinks - * @param mixed &$parser The formula parser created for the Workbook - * @access private - */ - function Spreadsheet_Excel_Writer_Worksheet($BIFF_version, $name, - $index, &$activesheet, - &$firstsheet, &$str_total, - &$str_unique, &$str_table, - &$url_format, &$parser) - { - // It needs to call its parent's constructor explicitly - $this->Spreadsheet_Excel_Writer_BIFFwriter(); - $this->_BIFF_version = $BIFF_version; - $rowmax = 65536; // 16384 in Excel 5 - $colmax = 256; - - $this->name = $name; - $this->index = $index; - $this->activesheet = &$activesheet; - $this->firstsheet = &$firstsheet; - $this->_str_total = &$str_total; - $this->_str_unique = &$str_unique; - $this->_str_table = &$str_table; - $this->_url_format = &$url_format; - $this->_parser = &$parser; - - //$this->ext_sheets = array(); - $this->_filehandle = ""; - $this->_using_tmpfile = true; - //$this->fileclosed = 0; - //$this->offset = 0; - $this->_xls_rowmax = $rowmax; - $this->_xls_colmax = $colmax; - $this->_xls_strmax = 255; - $this->_dim_rowmin = $rowmax + 1; - $this->_dim_rowmax = 0; - $this->_dim_colmin = $colmax + 1; - $this->_dim_colmax = 0; - $this->_colinfo = array(); - $this->_selection = array(0,0,0,0); - $this->_panes = array(); - $this->_active_pane = 3; - $this->_frozen = 0; - $this->selected = 0; - - $this->_paper_size = 0x0; - $this->_orientation = 0x1; - $this->_header = ''; - $this->_footer = ''; - $this->_hcenter = 0; - $this->_vcenter = 0; - $this->_margin_head = 0.50; - $this->_margin_foot = 0.50; - $this->_margin_left = 0.75; - $this->_margin_right = 0.75; - $this->_margin_top = 1.00; - $this->_margin_bottom = 1.00; - - $this->title_rowmin = NULL; - $this->title_rowmax = NULL; - $this->title_colmin = NULL; - $this->title_colmax = NULL; - $this->print_rowmin = NULL; - $this->print_rowmax = NULL; - $this->print_colmin = NULL; - $this->print_colmax = NULL; - - $this->_print_gridlines = 1; - $this->_print_headers = 0; - - $this->_fit_page = 0; - $this->_fit_width = 0; - $this->_fit_height = 0; - - $this->_hbreaks = array(); - $this->_vbreaks = array(); - - $this->_protect = 0; - $this->_password = NULL; - - $this->col_sizes = array(); - $this->row_sizes = array(); - - $this->_zoom = 100; - $this->_print_scale = 100; - - $this->_outline_row_level = 0; - $this->_outline_style = 0; - $this->_outline_below = 1; - $this->_outline_right = 1; - $this->_outline_on = 1; - - $this->_merged_ranges = array(); - - $this->_dv = array(); - - $this->_initialize(); - } - - /** - * Open a tmp file to store the majority of the Worksheet data. If this fails, - * for example due to write permissions, store the data in memory. This can be - * slow for large files. - * - * @access private - */ - function _initialize() - { - // Open tmp file for storing Worksheet data - $fh = tmpfile(); - if ( $fh) { - // Store filehandle - $this->_filehandle = $fh; - } - else { - // If tmpfile() fails store data in memory - $this->_using_tmpfile = false; - } - } - - /** - * Add data to the beginning of the workbook (note the reverse order) - * and to the end of the workbook. - * - * @access public - * @see Spreadsheet_Excel_Writer_Workbook::storeWorkbook() - * @param array $sheetnames The array of sheetnames from the Workbook this - * worksheet belongs to - */ - function close($sheetnames) - { - $num_sheets = count($sheetnames); - - /*********************************************** - * Prepend in reverse order!! - */ - - // Prepend the sheet dimensions - $this->_storeDimensions(); - - // Prepend the sheet password - $this->_storePassword(); - - // Prepend the sheet protection - $this->_storeProtect(); - - // Prepend the page setup - $this->_storeSetup(); - - /* FIXME: margins are actually appended */ - // Prepend the bottom margin - $this->_storeMarginBottom(); - - // Prepend the top margin - $this->_storeMarginTop(); - - // Prepend the right margin - $this->_storeMarginRight(); - - // Prepend the left margin - $this->_storeMarginLeft(); - - // Prepend the page vertical centering - $this->_storeVcenter(); - - // Prepend the page horizontal centering - $this->_storeHcenter(); - - // Prepend the page footer - $this->_storeFooter(); - - // Prepend the page header - $this->_storeHeader(); - - // Prepend the vertical page breaks - $this->_storeVbreak(); - - // Prepend the horizontal page breaks - $this->_storeHbreak(); - - // Prepend WSBOOL - $this->_storeWsbool(); - - // Prepend GRIDSET - $this->_storeGridset(); - - // Prepend GUTS - if ($this->_BIFF_version == 0x0500) { - $this->_storeGuts(); - } - - // Prepend PRINTGRIDLINES - $this->_storePrintGridlines(); - - // Prepend PRINTHEADERS - $this->_storePrintHeaders(); - - // Prepend EXTERNSHEET references - if ($this->_BIFF_version == 0x0500) { - for ($i = $num_sheets; $i > 0; $i--) { - $sheetname = $sheetnames[$i-1]; - $this->_storeExternsheet($sheetname); - } - } - - // Prepend the EXTERNCOUNT of external references. - if ($this->_BIFF_version == 0x0500) { - $this->_storeExterncount($num_sheets); - } - - // Prepend the COLINFO records if they exist - if (!empty($this->_colinfo)) - { - for ($i=0; $i < count($this->_colinfo); $i++) { - $this->_storeColinfo($this->_colinfo[$i]); - } - $this->_storeDefcol(); - } - - // Prepend the BOF record - $this->_storeBof(0x0010); - - /* - * End of prepend. Read upwards from here. - ***********************************************/ - - // Append - $this->_storeWindow2(); - $this->_storeZoom(); - if (!empty($this->_panes)) { - $this->_storePanes($this->_panes); - } - $this->_storeSelection($this->_selection); - $this->_storeMergedCells(); - /* TODO: add data validity */ - /*if ($this->_BIFF_version == 0x0600) { - $this->_storeDataValidity(); - }*/ - $this->_storeEof(); - } - - /** - * Retrieve the worksheet name. - * This is usefull when creating worksheets without a name. - * - * @access public - * @return string The worksheet's name - */ - function getName() - { - return $this->name; - } - - /** - * Retrieves data from memory in one chunk, or from disk in $buffer - * sized chunks. - * - * @return string The data - */ - function getData() - { - $buffer = 4096; - - // Return data stored in memory - if (isset($this->_data)) - { - $tmp = $this->_data; - unset($this->_data); - $fh = $this->_filehandle; - if ($this->_using_tmpfile) { - fseek($fh, 0); - } - return $tmp; - } - // Return data stored on disk - if ($this->_using_tmpfile) - { - if ($tmp = fread($this->_filehandle, $buffer)) { - return $tmp; - } - } - - // No data to return - return ''; - } - - /** - * Sets a merged cell range - * - * @access public - * @param integer $first_row First row of the area to merge - * @param integer $first_col First column of the area to merge - * @param integer $last_row Last row of the area to merge - * @param integer $last_col Last column of the area to merge - */ - function setMerge($first_row, $first_col, $last_row, $last_col) - { - if (($last_row < $first_row) or ($last_col < $first_col)) { - return; - } - // don't check rowmin, rowmax, etc... because we don't know when this - // is going to be called - $this->_merged_ranges[] = array($first_row, $first_col, $last_row, $last_col); - } - - /** - * Set this worksheet as a selected worksheet, - * i.e. the worksheet has its tab highlighted. - * - * @access public - */ - function select() - { - $this->selected = 1; - } - - /** - * Set this worksheet as the active worksheet, - * i.e. the worksheet that is displayed when the workbook is opened. - * Also set it as selected. - * - * @access public - */ - function activate() - { - $this->selected = 1; - $this->activesheet = $this->index; - } - - /** - * Set this worksheet as the first visible sheet. - * This is necessary when there are a large number of worksheets and the - * activated worksheet is not visible on the screen. - * - * @access public - */ - function setFirstSheet() - { - $this->firstsheet = $this->index; - } - - /** - * Set the worksheet protection flag - * to prevent accidental modification and to - * hide formulas if the locked and hidden format properties have been set. - * - * @access public - * @param string $password The password to use for protecting the sheet. - */ - function protect($password) - { - $this->_protect = 1; - $this->_password = $this->_encodePassword($password); - } - - /** - * Set the width of a single column or a range of columns. - * - * @access public - * @param integer $firstcol first column on the range - * @param integer $lastcol last column on the range - * @param integer $width width to set - * @param mixed $format The optional XF format to apply to the columns - * @param integer $hidden The optional hidden atribute - * @param integer $level The optional outline level - */ - function setColumn($firstcol, $lastcol, $width, $format = 0, $hidden = 0, $level = 0) - { - $this->_colinfo[] = array($firstcol, $lastcol, $width, &$format, $hidden, $level); - - // Set width to zero if column is hidden - $width = ($hidden) ? 0 : $width; - - for ($col = $firstcol; $col <= $lastcol; $col++) { - $this->col_sizes[$col] = $width; - } - } - - /** - * Set which cell or cells are selected in a worksheet - * - * @access public - * @param integer $first_row first row in the selected quadrant - * @param integer $first_column first column in the selected quadrant - * @param integer $last_row last row in the selected quadrant - * @param integer $last_column last column in the selected quadrant - */ - function setSelection($first_row,$first_column,$last_row,$last_column) - { - $this->_selection = array($first_row,$first_column,$last_row,$last_column); - } - - /** - * Set panes and mark them as frozen. - * - * @access public - * @param array $panes This is the only parameter received and is composed of the following: - * 0 => Vertical split position, - * 1 => Horizontal split position - * 2 => Top row visible - * 3 => Leftmost column visible - * 4 => Active pane - */ - function freezePanes($panes) - { - $this->_frozen = 1; - $this->_panes = $panes; - } - - /** - * Set panes and mark them as unfrozen. - * - * @access public - * @param array $panes This is the only parameter received and is composed of the following: - * 0 => Vertical split position, - * 1 => Horizontal split position - * 2 => Top row visible - * 3 => Leftmost column visible - * 4 => Active pane - */ - function thawPanes($panes) - { - $this->_frozen = 0; - $this->_panes = $panes; - } - - /** - * Set the page orientation as portrait. - * - * @access public - */ - function setPortrait() - { - $this->_orientation = 1; - } - - /** - * Set the page orientation as landscape. - * - * @access public - */ - function setLandscape() - { - $this->_orientation = 0; - } - - /** - * Set the paper type. Ex. 1 = US Letter, 9 = A4 - * - * @access public - * @param integer $size The type of paper size to use - */ - function setPaper($size = 0) - { - $this->_paper_size = $size; - } - - - /** - * Set the page header caption and optional margin. - * - * @access public - * @param string $string The header text - * @param float $margin optional head margin in inches. - */ - function setHeader($string,$margin = 0.50) - { - if (strlen($string) >= 255) { - //carp 'Header string must be less than 255 characters'; - return; - } - $this->_header = $string; - $this->_margin_head = $margin; - } - - /** - * Set the page footer caption and optional margin. - * - * @access public - * @param string $string The footer text - * @param float $margin optional foot margin in inches. - */ - function setFooter($string,$margin = 0.50) - { - if (strlen($string) >= 255) { - //carp 'Footer string must be less than 255 characters'; - return; - } - $this->_footer = $string; - $this->_margin_foot = $margin; - } - - /** - * Center the page horinzontally. - * - * @access public - * @param integer $center the optional value for centering. Defaults to 1 (center). - */ - function centerHorizontally($center = 1) - { - $this->_hcenter = $center; - } - - /** - * Center the page vertically. - * - * @access public - * @param integer $center the optional value for centering. Defaults to 1 (center). - */ - function centerVertically($center = 1) - { - $this->_vcenter = $center; - } - - /** - * Set all the page margins to the same value in inches. - * - * @access public - * @param float $margin The margin to set in inches - */ - function setMargins($margin) - { - $this->setMarginLeft($margin); - $this->setMarginRight($margin); - $this->setMarginTop($margin); - $this->setMarginBottom($margin); - } - - /** - * Set the left and right margins to the same value in inches. - * - * @access public - * @param float $margin The margin to set in inches - */ - function setMargins_LR($margin) - { - $this->setMarginLeft($margin); - $this->setMarginRight($margin); - } - - /** - * Set the top and bottom margins to the same value in inches. - * - * @access public - * @param float $margin The margin to set in inches - */ - function setMargins_TB($margin) - { - $this->setMarginTop($margin); - $this->setMarginBottom($margin); - } - - /** - * Set the left margin in inches. - * - * @access public - * @param float $margin The margin to set in inches - */ - function setMarginLeft($margin = 0.75) - { - $this->_margin_left = $margin; - } - - /** - * Set the right margin in inches. - * - * @access public - * @param float $margin The margin to set in inches - */ - function setMarginRight($margin = 0.75) - { - $this->_margin_right = $margin; - } - - /** - * Set the top margin in inches. - * - * @access public - * @param float $margin The margin to set in inches - */ - function setMarginTop($margin = 1.00) - { - $this->_margin_top = $margin; - } - - /** - * Set the bottom margin in inches. - * - * @access public - * @param float $margin The margin to set in inches - */ - function setMarginBottom($margin = 1.00) - { - $this->_margin_bottom = $margin; - } - - /** - * Set the rows to repeat at the top of each printed page. - * - * @access public - * @param integer $first_row First row to repeat - * @param integer $last_row Last row to repeat. Optional. - */ - function repeatRows($first_row, $last_row = NULL) - { - $this->title_rowmin = $first_row; - if (isset($last_row)) { //Second row is optional - $this->title_rowmax = $last_row; - } - else { - $this->title_rowmax = $first_row; - } - } - - /** - * Set the columns to repeat at the left hand side of each printed page. - * - * @access public - * @param integer $first_col First column to repeat - * @param integer $last_col Last column to repeat. Optional. - */ - function repeatColumns($first_col, $last_col = NULL) - { - $this->title_colmin = $first_col; - if (isset($last_col)) { // Second col is optional - $this->title_colmax = $last_col; - } - else { - $this->title_colmax = $first_col; - } - } - - /** - * Set the area of each worksheet that will be printed. - * - * @access public - * @param integer $first_row First row of the area to print - * @param integer $first_col First column of the area to print - * @param integer $last_row Last row of the area to print - * @param integer $last_col Last column of the area to print - */ - function printArea($first_row, $first_col, $last_row, $last_col) - { - $this->print_rowmin = $first_row; - $this->print_colmin = $first_col; - $this->print_rowmax = $last_row; - $this->print_colmax = $last_col; - } - - - /** - * Set the option to hide gridlines on the printed page. - * - * @access public - */ - function hideGridlines() - { - $this->_print_gridlines = 0; - } - - /** - * Set the option to print the row and column headers on the printed page. - * - * @access public - * @param integer $print Whether to print the headers or not. Defaults to 1 (print). - */ - function printRowColHeaders($print = 1) - { - $this->_print_headers = $print; - } - - /** - * Set the vertical and horizontal number of pages that will define the maximum area printed. - * It doesn't seem to work with OpenOffice. - * - * @access public - * @param integer $width Maximun width of printed area in pages - * @param integer $height Maximun heigth of printed area in pages - * @see setPrintScale() - */ - function fitToPages($width, $height) - { - $this->_fit_page = 1; - $this->_fit_width = $width; - $this->_fit_height = $height; - } - - /** - * Store the horizontal page breaks on a worksheet (for printing). - * The breaks represent the row after which the break is inserted. - * - * @access public - * @param array $breaks Array containing the horizontal page breaks - */ - function setHPagebreaks($breaks) - { - foreach($breaks as $break) { - array_push($this->_hbreaks,$break); - } - } - - /** - * Store the vertical page breaks on a worksheet (for printing). - * The breaks represent the column after which the break is inserted. - * - * @access public - * @param array $breaks Array containing the vertical page breaks - */ - function setVPagebreaks($breaks) - { - foreach($breaks as $break) { - array_push($this->_vbreaks,$break); - } - } - - - /** - * Set the worksheet zoom factor. - * - * @access public - * @param integer $scale The zoom factor - */ - function setZoom($scale = 100) - { - // Confine the scale to Excel's range - if ($scale < 10 or $scale > 400) - { - $this->raiseError("Zoom factor $scale outside range: 10 <= zoom <= 400"); - $scale = 100; - } - - $this->_zoom = floor($scale); - } - - /** - * Set the scale factor for the printed page. - * It turns off the "fit to page" option - * - * @access public - * @param integer $scale The optional scale factor. Defaults to 100 - */ - function setPrintScale($scale = 100) - { - // Confine the scale to Excel's range - if ($scale < 10 or $scale > 400) - { - $this->raiseError("Print scale $scale outside range: 10 <= zoom <= 400"); - $scale = 100; - } - - // Turn off "fit to page" option - $this->_fit_page = 0; - - $this->_print_scale = floor($scale); - } - - /** - * Map to the appropriate write method acording to the token recieved. - * - * @access public - * @param integer $row The row of the cell we are writing to - * @param integer $col The column of the cell we are writing to - * @param mixed $token What we are writing - * @param mixed $format The optional format to apply to the cell - */ - function write($row, $col, $token, $format = 0) - { - // Check for a cell reference in A1 notation and substitute row and column - /*if ($_[0] =~ /^\D/) { - @_ = $this->_substituteCellref(@_); - }*/ - - - // Match number - if (preg_match("/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/",$token)) { - return $this->writeNumber($row,$col,$token,$format); - } - // Match http or ftp URL - elseif (preg_match("/^[fh]tt?p:\/\//",$token)) { - return $this->writeUrl($row, $col, $token, '', $format); - } - // Match mailto: - elseif (preg_match("/^mailto:/",$token)) { - return $this->writeUrl($row, $col, $token, '', $format); - } - // Match internal or external sheet link - elseif (preg_match("/^(?:in|ex)ternal:/",$token)) { - return $this->writeUrl($row, $col, $token, '', $format); - } - // Match formula - elseif (preg_match("/^=/",$token)) { - return $this->writeFormula($row, $col, $token, $format); - } - // Match formula - elseif (preg_match("/^@/",$token)) { - return $this->writeFormula($row, $col, $token, $format); - } - // Match blank - elseif ($token == '') { - return $this->writeBlank($row,$col,$format); - } - // Default: match string - else { - return $this->writeString($row,$col,$token,$format); - } - } - - /** - * Write an array of values as a row - * - * @access public - * @param integer $row The row we are writing to - * @param integer $col The first col (leftmost col) we are writing to - * @param array $val The array of values to write - * @param mixed $format The optional format to apply to the cell - * @return mixed PEAR_Error on failure - */ - - function writeRow($row, $col, $val, $format=0) - { - $retval = ''; - if (is_array($val)) { - foreach($val as $v) { - if (is_array($v)) { - $this->writeCol($row, $col, $v, $format); - } else { - $this->write($row, $col, $v, $format); - } - $col++; - } - } else { - $retval = new PEAR_Error('$val needs to be an array'); - } - return($retval); - } - - /** - * Write an array of values as a column - * - * @access public - * @param integer $row The first row (uppermost row) we are writing to - * @param integer $col The col we are writing to - * @param array $val The array of values to write - * @param mixed $format The optional format to apply to the cell - * @return mixed PEAR_Error on failure - */ - - function writeCol($row, $col, $val, $format=0) - { - $retval = ''; - if (is_array($val)) { - foreach($val as $v) { - $this->write($row, $col, $v, $format); - $row++; - } - } else { - $retval = new PEAR_Error('$val needs to be an array'); - } - return($retval); - } - - /** - * Returns an index to the XF record in the workbook - * - * @access private - * @param mixed &$format The optional XF format - * @return integer The XF record index - */ - function _XF(&$format) - { - if ($format != 0) { - return($format->getXfIndex()); - } - else { - return(0x0F); - } - } - - - /****************************************************************************** - ******************************************************************************* - * - * Internal methods - */ - - - /** - * Store Worksheet data in memory using the parent's class append() or to a - * temporary file, the default. - * - * @access private - * @param string $data The binary data to append - */ - function _append($data) - { - if ($this->_using_tmpfile) - { - // Add CONTINUE records if necessary - if (strlen($data) > $this->_limit) { - $data = $this->_addContinue($data); - } - fwrite($this->_filehandle,$data); - $this->_datasize += strlen($data); - } - else { - parent::_append($data); - } - } - - /** - * Substitute an Excel cell reference in A1 notation for zero based row and - * column values in an argument list. - * - * Ex: ("A4", "Hello") is converted to (3, 0, "Hello"). - * - * @access private - * @param string $cell The cell reference. Or range of cells. - * @return array - */ - function _substituteCellref($cell) - { - $cell = strtoupper($cell); - - // Convert a column range: 'A:A' or 'B:G' - if (preg_match("/([A-I]?[A-Z]):([A-I]?[A-Z])/",$cell,$match)) { - list($no_use, $col1) = $this->_cellToRowcol($match[1] .'1'); // Add a dummy row - list($no_use, $col2) = $this->_cellToRowcol($match[2] .'1'); // Add a dummy row - return(array($col1, $col2)); - } - - // Convert a cell range: 'A1:B7' - if (preg_match("/\$?([A-I]?[A-Z]\$?\d+):\$?([A-I]?[A-Z]\$?\d+)/",$cell,$match)) { - list($row1, $col1) = $this->_cellToRowcol($match[1]); - list($row2, $col2) = $this->_cellToRowcol($match[2]); - return(array($row1, $col1, $row2, $col2)); - } - - // Convert a cell reference: 'A1' or 'AD2000' - if (preg_match("/\$?([A-I]?[A-Z]\$?\d+)/",$cell)) { - list($row1, $col1) = $this->_cellToRowcol($match[1]); - return(array($row1, $col1)); - } - - // TODO use real error codes - $this->raiseError("Unknown cell reference $cell", 0, PEAR_ERROR_DIE); - } - - /** - * Convert an Excel cell reference in A1 notation to a zero based row and column - * reference; converts C1 to (0, 2). - * - * @access private - * @param string $cell The cell reference. - * @return array containing (row, column) - */ - function _cellToRowcol($cell) - { - preg_match("/\$?([A-I]?[A-Z])\$?(\d+)/",$cell,$match); - $col = $match[1]; - $row = $match[2]; - - // Convert base26 column string to number - $chars = explode('', $col); - $expn = 0; - $col = 0; - - while ($chars) { - $char = array_pop($chars); // LS char first - $col += (ord($char) -ord('A') +1) * pow(26,$expn); - $expn++; - } - - // Convert 1-index to zero-index - $row--; - $col--; - - return(array($row, $col)); - } - - /** - * Based on the algorithm provided by Daniel Rentz of OpenOffice. - * - * @access private - * @param string $plaintext The password to be encoded in plaintext. - * @return string The encoded password - */ - function _encodePassword($plaintext) - { - $password = 0x0000; - $i = 1; // char position - - // split the plain text password in its component characters - $chars = preg_split('//', $plaintext, -1, PREG_SPLIT_NO_EMPTY); - foreach($chars as $char) - { - $value = ord($char) << $i; // shifted ASCII value - $rotated_bits = $value >> 15; // rotated bits beyond bit 15 - $value &= 0x7fff; // first 15 bits - $password ^= ($value | $rotated_bits); - $i++; - } - - $password ^= strlen($plaintext); - $password ^= 0xCE4B; - - return($password); - } - - /** - * This method sets the properties for outlining and grouping. The defaults - * correspond to Excel's defaults. - * - * @param bool $visible - * @param bool $symbols_below - * @param bool $symbols_right - * @param bool $auto_style - */ - function setOutline($visible = true, $symbols_below = true, $symbols_right = true, $auto_style = false) - { - $this->_outline_on = $visible; - $this->_outline_below = $symbols_below; - $this->_outline_right = $symbols_right; - $this->_outline_style = $auto_style; - - // Ensure this is a boolean vale for Window2 - if ($this->_outline_on) { - $this->_outline_on = 1; - } - } - - /****************************************************************************** - ******************************************************************************* - * - * BIFF RECORDS - */ - - - /** - * Write a double to the specified row and column (zero indexed). - * An integer can be written as a double. Excel will display an - * integer. $format is optional. - * - * Returns 0 : normal termination - * -2 : row or column out of range - * - * @access public - * @param integer $row Zero indexed row - * @param integer $col Zero indexed column - * @param float $num The number to write - * @param mixed $format The optional XF format - * @return integer - */ - function writeNumber($row, $col, $num, $format = 0) - { - - - $record = 0x0203; // Record identifier - $length = 0x000E; // Number of bytes to follow - - $xf = $this->_XF($format); // The cell format - - // Check that row and col are valid and store max and min values - if ($row >= $this->_xls_rowmax) - { - return(-2); - } - if ($col >= $this->_xls_colmax) - { - return(-2); - } - if ($row < $this->_dim_rowmin) - { - $this->_dim_rowmin = $row; - } - if ($row > $this->_dim_rowmax) - { - $this->_dim_rowmax = $row; - } - if ($col < $this->_dim_colmin) - { - $this->_dim_colmin = $col; - } - if ($col > $this->_dim_colmax) - { - $this->_dim_colmax = $col; - } - - $header = pack("vv", $record, $length); - $data = pack("vvv", $row, $col, $xf); - $xl_double = pack("d", $num); - if ($this->_byte_order) // if it's Big Endian - { - $xl_double = strrev($xl_double); - } - - $this->_append($header.$data.$xl_double); - return(0); - } - - /** - * Write a string to the specified row and column (zero indexed). - * NOTE: there is an Excel 5 defined limit of 255 characters. - * $format is optional. - * Returns 0 : normal termination - * -2 : row or column out of range - * -3 : long string truncated to 255 chars - * - * @access public - * @param integer $row Zero indexed row - * @param integer $col Zero indexed column - * @param string $str The string to write - * @param mixed $format The XF format for the cell - * @return integer - */ - function writeString($row, $col, $str, $format = 0) - { - - - - if ($this->_BIFF_version == 0x0600) { - return $this->writeStringBIFF8($row, $col, $str, $format); - } - - $strlen = strlen($str); - $record = 0x0204; // Record identifier - $length = 0x0008 + $strlen; // Bytes to follow - $xf = $this->_XF($format); // The cell format - - $str_error = 0; - - // Check that row and col are valid and store max and min values - if ($row >= $this->_xls_rowmax) - { - return(-2); - } - if ($col >= $this->_xls_colmax) - { - return(-2); - } - if ($row < $this->_dim_rowmin) - { - $this->_dim_rowmin = $row; - } - if ($row > $this->_dim_rowmax) - { - $this->_dim_rowmax = $row; - } - if ($col < $this->_dim_colmin) - { - $this->_dim_colmin = $col; - } - if ($col > $this->_dim_colmax) - { - $this->_dim_colmax = $col; - } - - if ($strlen > $this->_xls_strmax) // LABEL must be < 255 chars - { - $str = substr($str, 0, $this->_xls_strmax); - $length = 0x0008 + $this->_xls_strmax; - $strlen = $this->_xls_strmax; - $str_error = -3; - } - - $header = pack("vv", $record, $length); - $data = pack("vvvv", $row, $col, $xf, $strlen); - $this->_append($header.$data.$str); - return($str_error); - } - - function writeStringBIFF8($row, $col, $str, $format = 0) - { - $strlen = strlen($str); - $record = 0x00FD; // Record identifier - $length = 0x000A; // Bytes to follow - $xf = $this->_XF($format); // The cell format - $encoding = 0x0; - - $str_error = 0; - - // Check that row and col are valid and store max and min values - if ($this->_checkRowCol($row, $col) == false) { - return -2; - } - - $str = pack('vC', $strlen, $encoding).$str; - - /* check if string is already present */ - if (!isset($this->_str_table[$str])) { - $this->_str_table[$str] = $this->_str_unique++; - } - $this->_str_total++; - - $header = pack('vv', $record, $length); - $data = pack('vvvV', $row, $col, $xf, $this->_str_table[$str]); - $this->_append($header.$data); - return $str_error; - } - - /** - * Check row and col before writing to a cell, and update the sheet's - * dimensions accordingly - * - * @access private - * @param integer $row Zero indexed row - * @param integer $col Zero indexed column - * @return boolean true for success, false if row and/or col are grester - * then maximums allowed. - */ - function _checkRowCol($row, $col) - { - if ($row >= $this->_xls_rowmax) { - return false; - } - if ($col >= $this->_xls_colmax) { - return false; - } - if ($row < $this->_dim_rowmin) { - $this->_dim_rowmin = $row; - } - if ($row > $this->_dim_rowmax) { - $this->_dim_rowmax = $row; - } - if ($col < $this->_dim_colmin) { - $this->_dim_colmin = $col; - } - if ($col > $this->_dim_colmax) { - $this->_dim_colmax = $col; - } - return true; - } - - /** - * Writes a note associated with the cell given by the row and column. - * NOTE records don't have a length limit. - * - * @access public - * @param integer $row Zero indexed row - * @param integer $col Zero indexed column - * @param string $note The note to write - */ - function writeNote($row, $col, $note) - { - $note_length = strlen($note); - $record = 0x001C; // Record identifier - $max_length = 2048; // Maximun length for a NOTE record - //$length = 0x0006 + $note_length; // Bytes to follow - - // Check that row and col are valid and store max and min values - if ($row >= $this->_xls_rowmax) - { - return(-2); - } - if ($col >= $this->_xls_colmax) - { - return(-2); - } - if ($row < $this->_dim_rowmin) - { - $this->_dim_rowmin = $row; - } - if ($row > $this->_dim_rowmax) - { - $this->_dim_rowmax = $row; - } - if ($col < $this->_dim_colmin) - { - $this->_dim_colmin = $col; - } - if ($col > $this->_dim_colmax) - { - $this->_dim_colmax = $col; - } - - // Length for this record is no more than 2048 + 6 - $length = 0x0006 + min($note_length, 2048); - $header = pack("vv", $record, $length); - $data = pack("vvv", $row, $col, $note_length); - $this->_append($header.$data.substr($note, 0, 2048)); - - for($i = $max_length; $i < $note_length; $i += $max_length) - { - $chunk = substr($note, $i, $max_length); - $length = 0x0006 + strlen($chunk); - $header = pack("vv", $record, $length); - $data = pack("vvv", -1, 0, strlen($chunk)); - $this->_append($header.$data.$chunk); - } - return(0); - } - - /** - * Write a blank cell to the specified row and column (zero indexed). - * A blank cell is used to specify formatting without adding a string - * or a number. - * - * A blank cell without a format serves no purpose. Therefore, we don't write - * a BLANK record unless a format is specified. - * - * Returns 0 : normal termination (including no format) - * -1 : insufficient number of arguments - * -2 : row or column out of range - * - * @access public - * @param integer $row Zero indexed row - * @param integer $col Zero indexed column - * @param mixed $format The XF format - */ - function writeBlank($row, $col, $format) - { - // Don't write a blank cell unless it has a format - if ($format == 0) - { - return(0); - } - - $record = 0x0201; // Record identifier - $length = 0x0006; // Number of bytes to follow - $xf = $this->_XF($format); // The cell format - - // Check that row and col are valid and store max and min values - if ($row >= $this->_xls_rowmax) - { - return(-2); - } - if ($col >= $this->_xls_colmax) - { - return(-2); - } - if ($row < $this->_dim_rowmin) - { - $this->_dim_rowmin = $row; - } - if ($row > $this->_dim_rowmax) - { - $this->_dim_rowmax = $row; - } - if ($col < $this->_dim_colmin) - { - $this->_dim_colmin = $col; - } - if ($col > $this->_dim_colmax) - { - $this->_dim_colmax = $col; - } - - $header = pack("vv", $record, $length); - $data = pack("vvv", $row, $col, $xf); - $this->_append($header.$data); - return 0; - } - - /** - * Write a formula to the specified row and column (zero indexed). - * The textual representation of the formula is passed to the parser in - * Parser.php which returns a packed binary string. - * - * Returns 0 : normal termination - * -1 : formula errors (bad formula) - * -2 : row or column out of range - * - * @access public - * @param integer $row Zero indexed row - * @param integer $col Zero indexed column - * @param string $formula The formula text string - * @param mixed $format The optional XF format - * @return integer - */ - function writeFormula($row, $col, $formula, $format = 0) - { - $record = 0x0006; // Record identifier - - // Excel normally stores the last calculated value of the formula in $num. - // Clearly we are not in a position to calculate this a priori. Instead - // we set $num to zero and set the option flags in $grbit to ensure - // automatic calculation of the formula when the file is opened. - // - $xf = $this->_XF($format); // The cell format - $num = 0x00; // Current value of formula - $grbit = 0x03; // Option flags - $unknown = 0x0000; // Must be zero - - - // Check that row and col are valid and store max and min values - if ($this->_checkRowCol($row, $col) == false) { - return -2; - } - - // Strip the '=' or '@' sign at the beginning of the formula string - if (preg_match("/^=/",$formula)) { - $formula = preg_replace("/(^=)/","",$formula); - } - elseif (preg_match("/^@/",$formula)) { - $formula = preg_replace("/(^@)/","",$formula); - } - else - { - // Error handling - $this->writeString($row, $col, 'Unrecognised character for formula'); - return -1; - } - - // Parse the formula using the parser in Parser.php - $error = $this->_parser->parse($formula); - if ($this->isError($error)) - { - $this->writeString($row, $col, $error->getMessage()); - return -1; - } - - $formula = $this->_parser->toReversePolish(); - if ($this->isError($formula)) - { - $this->writeString($row, $col, $formula->getMessage()); - return -1; - } - - $formlen = strlen($formula); // Length of the binary string - $length = 0x16 + $formlen; // Length of the record data - - $header = pack("vv", $record, $length); - $data = pack("vvvdvVv", $row, $col, $xf, $num, - $grbit, $unknown, $formlen); - - $this->_append($header.$data.$formula); - return 0; - } - - /** - * Write a hyperlink. - * This is comprised of two elements: the visible label and - * the invisible link. The visible label is the same as the link unless an - * alternative string is specified. The label is written using the - * writeString() method. Therefore the 255 characters string limit applies. - * $string and $format are optional. - * - * The hyperlink can be to a http, ftp, mail, internal sheet (not yet), or external - * directory url. - * - * Returns 0 : normal termination - * -2 : row or column out of range - * -3 : long string truncated to 255 chars - * - * @access public - * @param integer $row Row - * @param integer $col Column - * @param string $url URL string - * @param string $string Alternative label - * @param mixed $format The cell format - * @return integer - */ - function writeUrl($row, $col, $url, $string = '', $format = 0) - { - // Add start row and col to arg list - return($this->_writeUrlRange($row, $col, $row, $col, $url, $string, $format)); - } - - /** - * This is the more general form of writeUrl(). It allows a hyperlink to be - * written to a range of cells. This function also decides the type of hyperlink - * to be written. These are either, Web (http, ftp, mailto), Internal - * (Sheet1!A1) or external ('c:\temp\foo.xls#Sheet1!A1'). - * - * @access private - * @see writeUrl() - * @param integer $row1 Start row - * @param integer $col1 Start column - * @param integer $row2 End row - * @param integer $col2 End column - * @param string $url URL string - * @param string $string Alternative label - * @param mixed $format The cell format - * @return integer - */ - - function _writeUrlRange($row1, $col1, $row2, $col2, $url, $string = '', $format = 0) - { - - // Check for internal/external sheet links or default to web link - if (preg_match('[^internal:]', $url)) { - return($this->_writeUrlInternal($row1, $col1, $row2, $col2, $url, $string, $format)); - } - if (preg_match('[^external:]', $url)) { - return($this->_writeUrlExternal($row1, $col1, $row2, $col2, $url, $string, $format)); - } - return($this->_writeUrlWeb($row1, $col1, $row2, $col2, $url, $string, $format)); - } - - - /** - * Used to write http, ftp and mailto hyperlinks. - * The link type ($options) is 0x03 is the same as absolute dir ref without - * sheet. However it is differentiated by the $unknown2 data stream. - * - * @access private - * @see writeUrl() - * @param integer $row1 Start row - * @param integer $col1 Start column - * @param integer $row2 End row - * @param integer $col2 End column - * @param string $url URL string - * @param string $str Alternative label - * @param mixed $format The cell format - * @return integer - */ - function _writeUrlWeb($row1, $col1, $row2, $col2, $url, $str, $format = 0) - { - $record = 0x01B8; // Record identifier - $length = 0x00000; // Bytes to follow - - if ($format == 0) { - $format = $this->_url_format; - } - - // Write the visible label using the writeString() method. - if ($str == '') { - $str = $url; - } - $str_error = $this->writeString($row1, $col1, $str, $format); - if (($str_error == -2) or ($str_error == -3)) { - return $str_error; - } - - // Pack the undocumented parts of the hyperlink stream - $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000"); - $unknown2 = pack("H*", "E0C9EA79F9BACE118C8200AA004BA90B"); - - // Pack the option flags - $options = pack("V", 0x03); - - // Convert URL to a null terminated wchar string - $url = join("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY)); - $url = $url . "\0\0\0"; - - // Pack the length of the URL - $url_len = pack("V", strlen($url)); - - // Calculate the data length - $length = 0x34 + strlen($url); - - // Pack the header data - $header = pack("vv", $record, $length); - $data = pack("vvvv", $row1, $row2, $col1, $col2); - - // Write the packed data - $this->_append( $header. $data. - $unknown1. $options. - $unknown2. $url_len. $url); - return($str_error); - } - - /** - * Used to write internal reference hyperlinks such as "Sheet1!A1". - * - * @access private - * @see writeUrl() - * @param integer $row1 Start row - * @param integer $col1 Start column - * @param integer $row2 End row - * @param integer $col2 End column - * @param string $url URL string - * @param string $str Alternative label - * @param mixed $format The cell format - * @return integer - */ - function _writeUrlInternal($row1, $col1, $row2, $col2, $url, $str, $format = 0) - { - $record = 0x01B8; // Record identifier - $length = 0x00000; // Bytes to follow - - if ($format == 0) { - $format = $this->_url_format; - } - - // Strip URL type - $url = preg_replace('s[^internal:]', '', $url); - - // Write the visible label - if ($str == '') { - $str = $url; - } - $str_error = $this->writeString($row1, $col1, $str, $format); - if (($str_error == -2) or ($str_error == -3)) { - return $str_error; - } - - // Pack the undocumented parts of the hyperlink stream - $unknown1 = pack("H*", "D0C9EA79F9BACE118C8200AA004BA90B02000000"); - - // Pack the option flags - $options = pack("V", 0x08); - - // Convert the URL type and to a null terminated wchar string - $url = join("\0", preg_split("''", $url, -1, PREG_SPLIT_NO_EMPTY)); - $url = $url . "\0\0\0"; - - // Pack the length of the URL as chars (not wchars) - $url_len = pack("V", floor(strlen($url)/2)); - - // Calculate the data length - $length = 0x24 + strlen($url); - - // Pack the header data - $header = pack("vv", $record, $length); - $data = pack("vvvv", $row1, $row2, $col1, $col2); - - // Write the packed data - $this->_append($header. $data. - $unknown1. $options. - $url_len. $url); - return($str_error); - } - - /** - * Write links to external directory names such as 'c:\foo.xls', - * c:\foo.xls#Sheet1!A1', '../../foo.xls'. and '../../foo.xls#Sheet1!A1'. - * - * Note: Excel writes some relative links with the $dir_long string. We ignore - * these cases for the sake of simpler code. - * - * @access private - * @see writeUrl() - * @param integer $row1 Start row - * @param integer $col1 Start column - * @param integer $row2 End row - * @param integer $col2 End column - * @param string $url URL string - * @param string $str Alternative label - * @param mixed $format The cell format - * @return integer - */ - function _writeUrlExternal($row1, $col1, $row2, $col2, $url, $str, $format = 0) - { - // Network drives are different. We will handle them separately - // MS/Novell network drives and shares start with \\ - if (preg_match('[^external:\\\\]', $url)) { - return; //($this->_writeUrlExternal_net($row1, $col1, $row2, $col2, $url, $str, $format)); - } - - $record = 0x01B8; // Record identifier - $length = 0x00000; // Bytes to follow - - if ($format == 0) { - $format = $this->_url_format; - } - - // Strip URL type and change Unix dir separator to Dos style (if needed) - // - $url = preg_replace('[^external:]', '', $url); - $url = preg_replace('[/]', "\\", $url); - - // Write the visible label - if ($str == '') { - $str = preg_replace('[\#]', ' - ', $url); - } - $str_error = $this->writeString($row1, $col1, $str, $format); - if (($str_error == -2) or ($str_error == -3)) { - return $str_error; - } - - // Determine if the link is relative or absolute: - // relative if link contains no dir separator, "somefile.xls" - // relative if link starts with up-dir, "..\..\somefile.xls" - // otherwise, absolute - - $absolute = 0x02; // Bit mask - if (!preg_match('[\\]', $url)) { - $absolute = 0x00; - } - if (preg_match('[^\.\.\\]', $url)) { - $absolute = 0x00; - } - - // Determine if the link contains a sheet reference and change some of the - // parameters accordingly. - // Split the dir name and sheet name (if it exists) - list($dir_long , $sheet) = explode('/\#/', $url); - $link_type = 0x01 | $absolute; - - if (isset($sheet)) { - $link_type |= 0x08; - $sheet_len = pack("V", strlen($sheet) + 0x01); - $sheet = join("\0", explode('', $sheet)); - $sheet .= "\0\0\0"; - } - else { - $sheet_len = ''; - $sheet = ''; - } - - // Pack the link type - $link_type = pack("V", $link_type); - - // Calculate the up-level dir count e.g.. (..\..\..\ == 3) - $up_count = preg_match_all("/\.\.\\/", $dir_long, $useless); - $up_count = pack("v", $up_count); - - // Store the short dos dir name (null terminated) - $dir_short = preg_replace('/\.\.\\/', '', $dir_long) . "\0"; - - // Store the long dir name as a wchar string (non-null terminated) - $dir_long = join("\0", explode('', $dir_long)); - $dir_long = $dir_long . "\0"; - - // Pack the lengths of the dir strings - $dir_short_len = pack("V", strlen($dir_short) ); - $dir_long_len = pack("V", strlen($dir_long) ); - $stream_len = pack("V", strlen($dir_long) + 0x06); - - // Pack the undocumented parts of the hyperlink stream - $unknown1 = pack("H*",'D0C9EA79F9BACE118C8200AA004BA90B02000000' ); - $unknown2 = pack("H*",'0303000000000000C000000000000046' ); - $unknown3 = pack("H*",'FFFFADDE000000000000000000000000000000000000000'); - $unknown4 = pack("v", 0x03 ); - - // Pack the main data stream - $data = pack("vvvv", $row1, $row2, $col1, $col2) . - $unknown1 . - $link_type . - $unknown2 . - $up_count . - $dir_short_len. - $dir_short . - $unknown3 . - $stream_len . - $dir_long_len . - $unknown4 . - $dir_long . - $sheet_len . - $sheet ; - - // Pack the header data - $length = strlen($data); - $header = pack("vv", $record, $length); - - // Write the packed data - $this->_append($header. $data); - return($str_error); - } - - - /** - * This method is used to set the height and format for a row. - * - * @access public - * @param integer $row The row to set - * @param integer $height Height we are giving to the row. - * Use NULL to set XF without setting height - * @param mixed $format XF format we are giving to the row - * @param bool $hidden The optional hidden attribute - * @param integer $level The optional outline level for row, in range [0,7] - */ - function setRow($row, $height, $format = 0, $hidden = false, $level = 0) - { - $record = 0x0208; // Record identifier - $length = 0x0010; // Number of bytes to follow - - $colMic = 0x0000; // First defined column - $colMac = 0x0000; // Last defined column - $irwMac = 0x0000; // Used by Excel to optimise loading - $reserved = 0x0000; // Reserved - $grbit = 0x0000; // Option flags - $ixfe = $this->_XF($format); // XF index - - // Use setRow($row, NULL, $XF) to set XF format without setting height - if ($height != NULL) { - $miyRw = $height * 20; // row height - } - else { - $miyRw = 0xff; // default row height is 256 - } - - $level = max(0, min($level, 7)); // level should be between 0 and 7 - $this->_outline_row_level = max($level, $this->_outline_row_level); - - - // Set the options flags. fUnsynced is used to show that the font and row - // heights are not compatible. This is usually the case for WriteExcel. - // The collapsed flag 0x10 doesn't seem to be used to indicate that a row - // is collapsed. Instead it is used to indicate that the previous row is - // collapsed. The zero height flag, 0x20, is used to collapse a row. - - $grbit |= $level; - if ($hidden) { - $grbit |= 0x0020; - } - $grbit |= 0x0040; // fUnsynced - if ($format) { - $grbit |= 0x0080; - } - $grbit |= 0x0100; - - $header = pack("vv", $record, $length); - $data = pack("vvvvvvvv", $row, $colMic, $colMac, $miyRw, - $irwMac,$reserved, $grbit, $ixfe); - $this->_append($header.$data); - } - - /** - * Writes Excel DIMENSIONS to define the area in which there is data. - * - * @access private - */ - function _storeDimensions() - { - $record = 0x0200; // Record identifier - $row_min = $this->_dim_rowmin; // First row - $row_max = $this->_dim_rowmax + 1; // Last row plus 1 - $col_min = $this->_dim_colmin; // First column - $col_max = $this->_dim_colmax + 1; // Last column plus 1 - $reserved = 0x0000; // Reserved by Excel - - if ($this->_BIFF_version == 0x0500) { - $length = 0x000A; // Number of bytes to follow - $data = pack("vvvvv", $row_min, $row_max, - $col_min, $col_max, $reserved); - } - elseif ($this->_BIFF_version == 0x0600) { - $length = 0x000E; - $data = pack("VVvvv", $row_min, $row_max, - $col_min, $col_max, $reserved); - } - $header = pack("vv", $record, $length); - $this->_prepend($header.$data); - } - - /** - * Write BIFF record Window2. - * - * @access private - */ - function _storeWindow2() - { - $record = 0x023E; // Record identifier - if ($this->_BIFF_version == 0x0500) { - $length = 0x000A; // Number of bytes to follow - } - elseif ($this->_BIFF_version == 0x0600) { - $length = 0x0012; - } - - $grbit = 0x00B6; // Option flags - $rwTop = 0x0000; // Top row visible in window - $colLeft = 0x0000; // Leftmost column visible in window - - - // The options flags that comprise $grbit - $fDspFmla = 0; // 0 - bit - $fDspGrid = 1; // 1 - $fDspRwCol = 1; // 2 - $fFrozen = $this->_frozen; // 3 - $fDspZeros = 1; // 4 - $fDefaultHdr = 1; // 5 - $fArabic = 0; // 6 - $fDspGuts = $this->_outline_on; // 7 - $fFrozenNoSplit = 0; // 0 - bit - $fSelected = $this->selected; // 1 - $fPaged = 1; // 2 - - $grbit = $fDspFmla; - $grbit |= $fDspGrid << 1; - $grbit |= $fDspRwCol << 2; - $grbit |= $fFrozen << 3; - $grbit |= $fDspZeros << 4; - $grbit |= $fDefaultHdr << 5; - $grbit |= $fArabic << 6; - $grbit |= $fDspGuts << 7; - $grbit |= $fFrozenNoSplit << 8; - $grbit |= $fSelected << 9; - $grbit |= $fPaged << 10; - - $header = pack("vv", $record, $length); - $data = pack("vvv", $grbit, $rwTop, $colLeft); - // FIXME !!! - if ($this->_BIFF_version == 0x0500) { - $rgbHdr = 0x00000000; // Row/column heading and gridline color - $data .= pack("V", $rgbHdr); - } - elseif ($this->_BIFF_version == 0x0600) { - $rgbHdr = 0x0040; // Row/column heading and gridline color index - $zoom_factor_page_break = 0x0000; - $zoom_factor_normal = 0x0000; - $data .= pack("vvvvV", $rgbHdr, 0x0000, $zoom_factor_page_break, $zoom_factor_normal, 0x00000000); - } - $this->_append($header.$data); - } - - /** - * Write BIFF record DEFCOLWIDTH if COLINFO records are in use. - * - * @access private - */ - function _storeDefcol() - { - $record = 0x0055; // Record identifier - $length = 0x0002; // Number of bytes to follow - $colwidth = 0x0008; // Default column width - - $header = pack("vv", $record, $length); - $data = pack("v", $colwidth); - $this->_prepend($header.$data); - } - - /** - * Write BIFF record COLINFO to define column widths - * - * Note: The SDK says the record length is 0x0B but Excel writes a 0x0C - * length record. - * - * @access private - * @param array $col_array This is the only parameter received and is composed of the following: - * 0 => First formatted column, - * 1 => Last formatted column, - * 2 => Col width (8.43 is Excel default), - * 3 => The optional XF format of the column, - * 4 => Option flags. - * 5 => Optional outline level - */ - function _storeColinfo($col_array) - { - if (isset($col_array[0])) { - $colFirst = $col_array[0]; - } - if (isset($col_array[1])) { - $colLast = $col_array[1]; - } - if (isset($col_array[2])) { - $coldx = $col_array[2]; - } - else { - $coldx = 8.43; - } - if (isset($col_array[3])) { - $format = $col_array[3]; - } - else { - $format = 0; - } - if (isset($col_array[4])) { - $grbit = $col_array[4]; - } - else { - $grbit = 0; - } - if (isset($col_array[5])) { - $level = $col_array[5]; - } - else { - $level = 0; - } - $record = 0x007D; // Record identifier - $length = 0x000B; // Number of bytes to follow - - $coldx += 0.72; // Fudge. Excel subtracts 0.72 !? - $coldx *= 256; // Convert to units of 1/256 of a char - - $ixfe = $this->_XF($format); - $reserved = 0x00; // Reserved - - $level = max(0, min($level, 7)); - $grbit |= $level << 8; - - $header = pack("vv", $record, $length); - $data = pack("vvvvvC", $colFirst, $colLast, $coldx, - $ixfe, $grbit, $reserved); - $this->_prepend($header.$data); - } - - /** - * Write BIFF record SELECTION. - * - * @access private - * @param array $array array containing ($rwFirst,$colFirst,$rwLast,$colLast) - * @see setSelection() - */ - function _storeSelection($array) - { - list($rwFirst,$colFirst,$rwLast,$colLast) = $array; - $record = 0x001D; // Record identifier - $length = 0x000F; // Number of bytes to follow - - $pnn = $this->_active_pane; // Pane position - $rwAct = $rwFirst; // Active row - $colAct = $colFirst; // Active column - $irefAct = 0; // Active cell ref - $cref = 1; // Number of refs - - if (!isset($rwLast)) { - $rwLast = $rwFirst; // Last row in reference - } - if (!isset($colLast)) { - $colLast = $colFirst; // Last col in reference - } - - // Swap last row/col for first row/col as necessary - if ($rwFirst > $rwLast) - { - list($rwFirst, $rwLast) = array($rwLast, $rwFirst); - } - - if ($colFirst > $colLast) - { - list($colFirst, $colLast) = array($colLast, $colFirst); - } - - $header = pack("vv", $record, $length); - $data = pack("CvvvvvvCC", $pnn, $rwAct, $colAct, - $irefAct, $cref, - $rwFirst, $rwLast, - $colFirst, $colLast); - $this->_append($header.$data); - } - - /** - * Store the MERGEDCELLS record for all ranges of merged cells - * - * @access private - */ - function _storeMergedCells() - { - // if there are no merged cell ranges set, return - if (count($this->_merged_ranges) == 0) { - return; - } - $record = 0x00E5; - $length = 2 + count($this->_merged_ranges) * 8; - - $header = pack('vv', $record, $length); - $data = pack('v', count($this->_merged_ranges)); - foreach ($this->_merged_ranges as $range) { - $data .= pack('vvvv', $range[0], $range[2], $range[1], $range[3]); - } - $this->_append($header.$data); - } - - /** - * Write BIFF record EXTERNCOUNT to indicate the number of external sheet - * references in a worksheet. - * - * Excel only stores references to external sheets that are used in formulas. - * For simplicity we store references to all the sheets in the workbook - * regardless of whether they are used or not. This reduces the overall - * complexity and eliminates the need for a two way dialogue between the formula - * parser the worksheet objects. - * - * @access private - * @param integer $count The number of external sheet references in this worksheet - */ - function _storeExterncount($count) - { - $record = 0x0016; // Record identifier - $length = 0x0002; // Number of bytes to follow - - $header = pack("vv", $record, $length); - $data = pack("v", $count); - $this->_prepend($header.$data); - } - - /** - * Writes the Excel BIFF EXTERNSHEET record. These references are used by - * formulas. A formula references a sheet name via an index. Since we store a - * reference to all of the external worksheets the EXTERNSHEET index is the same - * as the worksheet index. - * - * @access private - * @param string $sheetname The name of a external worksheet - */ - function _storeExternsheet($sheetname) - { - $record = 0x0017; // Record identifier - - // References to the current sheet are encoded differently to references to - // external sheets. - // - if ($this->name == $sheetname) { - $sheetname = ''; - $length = 0x02; // The following 2 bytes - $cch = 1; // The following byte - $rgch = 0x02; // Self reference - } - else { - $length = 0x02 + strlen($sheetname); - $cch = strlen($sheetname); - $rgch = 0x03; // Reference to a sheet in the current workbook - } - - $header = pack("vv", $record, $length); - $data = pack("CC", $cch, $rgch); - $this->_prepend($header.$data.$sheetname); - } - - /** - * Writes the Excel BIFF PANE record. - * The panes can either be frozen or thawed (unfrozen). - * Frozen panes are specified in terms of an integer number of rows and columns. - * Thawed panes are specified in terms of Excel's units for rows and columns. - * - * @access private - * @param array $panes This is the only parameter received and is composed of the following: - * 0 => Vertical split position, - * 1 => Horizontal split position - * 2 => Top row visible - * 3 => Leftmost column visible - * 4 => Active pane - */ - function _storePanes($panes) - { - $y = $panes[0]; - $x = $panes[1]; - $rwTop = $panes[2]; - $colLeft = $panes[3]; - if (count($panes) > 4) { // if Active pane was received - $pnnAct = $panes[4]; - } - else { - $pnnAct = NULL; - } - $record = 0x0041; // Record identifier - $length = 0x000A; // Number of bytes to follow - - // Code specific to frozen or thawed panes. - if ($this->_frozen) - { - // Set default values for $rwTop and $colLeft - if (!isset($rwTop)) { - $rwTop = $y; - } - if (!isset($colLeft)) { - $colLeft = $x; - } - } - else - { - // Set default values for $rwTop and $colLeft - if (!isset($rwTop)) { - $rwTop = 0; - } - if (!isset($colLeft)) { - $colLeft = 0; - } - - // Convert Excel's row and column units to the internal units. - // The default row height is 12.75 - // The default column width is 8.43 - // The following slope and intersection values were interpolated. - // - $y = 20*$y + 255; - $x = 113.879*$x + 390; - } - - - // Determine which pane should be active. There is also the undocumented - // option to override this should it be necessary: may be removed later. - // - if (!isset($pnnAct)) - { - if ($x != 0 and $y != 0) - $pnnAct = 0; // Bottom right - if ($x != 0 and $y == 0) - $pnnAct = 1; // Top right - if ($x == 0 and $y != 0) - $pnnAct = 2; // Bottom left - if ($x == 0 and $y == 0) - $pnnAct = 3; // Top left - } - - $this->_active_pane = $pnnAct; // Used in _storeSelection - - $header = pack("vv", $record, $length); - $data = pack("vvvvv", $x, $y, $rwTop, $colLeft, $pnnAct); - $this->_append($header.$data); - } - - /** - * Store the page setup SETUP BIFF record. - * - * @access private - */ - function _storeSetup() - { - $record = 0x00A1; // Record identifier - $length = 0x0022; // Number of bytes to follow - - $iPaperSize = $this->_paper_size; // Paper size - $iScale = $this->_print_scale; // Print scaling factor - $iPageStart = 0x01; // Starting page number - $iFitWidth = $this->_fit_width; // Fit to number of pages wide - $iFitHeight = $this->_fit_height; // Fit to number of pages high - $grbit = 0x00; // Option flags - $iRes = 0x0258; // Print resolution - $iVRes = 0x0258; // Vertical print resolution - $numHdr = $this->_margin_head; // Header Margin - $numFtr = $this->_margin_foot; // Footer Margin - $iCopies = 0x01; // Number of copies - - $fLeftToRight = 0x0; // Print over then down - $fLandscape = $this->_orientation; // Page orientation - $fNoPls = 0x0; // Setup not read from printer - $fNoColor = 0x0; // Print black and white - $fDraft = 0x0; // Print draft quality - $fNotes = 0x0; // Print notes - $fNoOrient = 0x0; // Orientation not set - $fUsePage = 0x0; // Use custom starting page - - $grbit = $fLeftToRight; - $grbit |= $fLandscape << 1; - $grbit |= $fNoPls << 2; - $grbit |= $fNoColor << 3; - $grbit |= $fDraft << 4; - $grbit |= $fNotes << 5; - $grbit |= $fNoOrient << 6; - $grbit |= $fUsePage << 7; - - $numHdr = pack("d", $numHdr); - $numFtr = pack("d", $numFtr); - if ($this->_byte_order) // if it's Big Endian - { - $numHdr = strrev($numHdr); - $numFtr = strrev($numFtr); - } - - $header = pack("vv", $record, $length); - $data1 = pack("vvvvvvvv", $iPaperSize, - $iScale, - $iPageStart, - $iFitWidth, - $iFitHeight, - $grbit, - $iRes, - $iVRes); - $data2 = $numHdr.$numFtr; - $data3 = pack("v", $iCopies); - $this->_prepend($header.$data1.$data2.$data3); - } - - /** - * Store the header caption BIFF record. - * - * @access private - */ - function _storeHeader() - { - $record = 0x0014; // Record identifier - - $str = $this->_header; // header string - $cch = strlen($str); // Length of header string - if ($this->_BIFF_version == 0x0600) { - $encoding = 0x0; // TODO: Unicode support - $length = 3 + $cch; // Bytes to follow - } - else { - $length = 1 + $cch; // Bytes to follow - } - $header = pack("vv", $record, $length); - if ($this->_BIFF_version == 0x0600) { - $data = pack("vC", $cch, $encoding); - } - else { - $data = pack("C", $cch); - } - - $this->_append($header.$data.$str); - } - - /** - * Store the footer caption BIFF record. - * - * @access private - */ - function _storeFooter() - { - $record = 0x0015; // Record identifier - - $str = $this->_footer; // Footer string - $cch = strlen($str); // Length of footer string - if ($this->_BIFF_version == 0x0600) { - $encoding = 0x0; // TODO: Unicode support - $length = 3 + $cch; // Bytes to follow - } - else { - $length = 1 + $cch; - } - $header = pack("vv", $record, $length); - if ($this->_BIFF_version == 0x0600) { - $data = pack("vC", $cch, $encoding); - } - else { - $data = pack("C", $cch); - } - - $this->_append($header.$data.$str); - } - - /** - * Store the horizontal centering HCENTER BIFF record. - * - * @access private - */ - function _storeHcenter() - { - $record = 0x0083; // Record identifier - $length = 0x0002; // Bytes to follow - - $fHCenter = $this->_hcenter; // Horizontal centering - - $header = pack("vv", $record, $length); - $data = pack("v", $fHCenter); - - $this->_append($header.$data); - } - - /** - * Store the vertical centering VCENTER BIFF record. - * - * @access private - */ - function _storeVcenter() - { - $record = 0x0084; // Record identifier - $length = 0x0002; // Bytes to follow - - $fVCenter = $this->_vcenter; // Horizontal centering - - $header = pack("vv", $record, $length); - $data = pack("v", $fVCenter); - $this->_append($header.$data); - } - - /** - * Store the LEFTMARGIN BIFF record. - * - * @access private - */ - function _storeMarginLeft() - { - $record = 0x0026; // Record identifier - $length = 0x0008; // Bytes to follow - - $margin = $this->_margin_left; // Margin in inches - - $header = pack("vv", $record, $length); - $data = pack("d", $margin); - if ($this->_byte_order) // if it's Big Endian - { - $data = strrev($data); - } - - $this->_append($header.$data); - } - - /** - * Store the RIGHTMARGIN BIFF record. - * - * @access private - */ - function _storeMarginRight() - { - $record = 0x0027; // Record identifier - $length = 0x0008; // Bytes to follow - - $margin = $this->_margin_right; // Margin in inches - - $header = pack("vv", $record, $length); - $data = pack("d", $margin); - if ($this->_byte_order) // if it's Big Endian - { - $data = strrev($data); - } - - $this->_append($header.$data); - } - - /** - * Store the TOPMARGIN BIFF record. - * - * @access private - */ - function _storeMarginTop() - { - $record = 0x0028; // Record identifier - $length = 0x0008; // Bytes to follow - - $margin = $this->_margin_top; // Margin in inches - - $header = pack("vv", $record, $length); - $data = pack("d", $margin); - if ($this->_byte_order) // if it's Big Endian - { - $data = strrev($data); - } - - $this->_append($header.$data); - } - - /** - * Store the BOTTOMMARGIN BIFF record. - * - * @access private - */ - function _storeMarginBottom() - { - $record = 0x0029; // Record identifier - $length = 0x0008; // Bytes to follow - - $margin = $this->_margin_bottom; // Margin in inches - - $header = pack("vv", $record, $length); - $data = pack("d", $margin); - if ($this->_byte_order) // if it's Big Endian - { - $data = strrev($data); - } - - $this->_append($header.$data); - } - - /** - * Merges the area given by its arguments. - * This is an Excel97/2000 method. It is required to perform more complicated - * merging than the normal setAlign('merge'). - * - * @access public - * @param integer $first_row First row of the area to merge - * @param integer $first_col First column of the area to merge - * @param integer $last_row Last row of the area to merge - * @param integer $last_col Last column of the area to merge - */ - function mergeCells($first_row, $first_col, $last_row, $last_col) - { - $record = 0x00E5; // Record identifier - $length = 0x000A; // Bytes to follow - $cref = 1; // Number of refs - - // Swap last row/col for first row/col as necessary - if ($first_row > $last_row) { - list($first_row, $last_row) = array($last_row, $first_row); - } - - if ($first_col > $last_col) { - list($first_col, $last_col) = array($last_col, $first_col); - } - - $header = pack("vv", $record, $length); - $data = pack("vvvvv", $cref, $first_row, $last_row, - $first_col, $last_col); - - $this->_append($header.$data); - } - - /** - * Write the PRINTHEADERS BIFF record. - * - * @access private - */ - function _storePrintHeaders() - { - $record = 0x002a; // Record identifier - $length = 0x0002; // Bytes to follow - - $fPrintRwCol = $this->_print_headers; // Boolean flag - - $header = pack("vv", $record, $length); - $data = pack("v", $fPrintRwCol); - $this->_prepend($header.$data); - } - - /** - * Write the PRINTGRIDLINES BIFF record. Must be used in conjunction with the - * GRIDSET record. - * - * @access private - */ - function _storePrintGridlines() - { - $record = 0x002b; // Record identifier - $length = 0x0002; // Bytes to follow - - $fPrintGrid = $this->_print_gridlines; // Boolean flag - - $header = pack("vv", $record, $length); - $data = pack("v", $fPrintGrid); - $this->_prepend($header.$data); - } - - /** - * Write the GRIDSET BIFF record. Must be used in conjunction with the - * PRINTGRIDLINES record. - * - * @access private - */ - function _storeGridset() - { - $record = 0x0082; // Record identifier - $length = 0x0002; // Bytes to follow - - $fGridSet = !($this->_print_gridlines); // Boolean flag - - $header = pack("vv", $record, $length); - $data = pack("v", $fGridSet); - $this->_prepend($header.$data); - } - - /** - * Write the GUTS BIFF record. This is used to configure the gutter margins - * where Excel outline symbols are displayed. The visibility of the gutters is - * controlled by a flag in WSBOOL. - * - * @see _storeWsbool() - * @access private - */ - function _storeGuts() - { - $record = 0x0080; // Record identifier - $length = 0x0008; // Bytes to follow - - $dxRwGut = 0x0000; // Size of row gutter - $dxColGut = 0x0000; // Size of col gutter - - $row_level = $this->_outline_row_level; - $col_level = 0; - - // Calculate the maximum column outline level. The equivalent calculation - // for the row outline level is carried out in setRow(). - for ($i=0; $i < count($this->_colinfo); $i++) - { - // Skip cols without outline level info. - if (count($col_level) >= 6) { - $col_level = max($this->_colinfo[$i][5], $col_level); - } - } - - // Set the limits for the outline levels (0 <= x <= 7). - $col_level = max(0, min($col_level, 7)); - - // The displayed level is one greater than the max outline levels - if ($row_level) { - $row_level++; - } - if ($col_level) { - $col_level++; - } - - $header = pack("vv", $record, $length); - $data = pack("vvvv", $dxRwGut, $dxColGut, $row_level, $col_level); - - $this->_prepend($header.$data); - } - - - /** - * Write the WSBOOL BIFF record, mainly for fit-to-page. Used in conjunction - * with the SETUP record. - * - * @access private - */ - function _storeWsbool() - { - $record = 0x0081; // Record identifier - $length = 0x0002; // Bytes to follow - $grbit = 0x0000; - - // The only option that is of interest is the flag for fit to page. So we - // set all the options in one go. - // - /*if ($this->_fit_page) { - $grbit = 0x05c1; - } - else { - $grbit = 0x04c1; - }*/ - // Set the option flags - $grbit |= 0x0001; // Auto page breaks visible - if ($this->_outline_style) { - $grbit |= 0x0020; // Auto outline styles - } - if ($this->_outline_below) { - $grbit |= 0x0040; // Outline summary below - } - if ($this->_outline_right) { - $grbit |= 0x0080; // Outline summary right - } - if ($this->_fit_page) { - $grbit |= 0x0100; // Page setup fit to page - } - if ($this->_outline_on) { - $grbit |= 0x0400; // Outline symbols displayed - } - - $header = pack("vv", $record, $length); - $data = pack("v", $grbit); - $this->_prepend($header.$data); - } - - /** - * Write the HORIZONTALPAGEBREAKS BIFF record. - * - * @access private - */ - function _storeHbreak() - { - // Return if the user hasn't specified pagebreaks - if (empty($this->_hbreaks)) { - return; - } - - // Sort and filter array of page breaks - $breaks = $this->_hbreaks; - sort($breaks, SORT_NUMERIC); - if ($breaks[0] == 0) { // don't use first break if it's 0 - array_shift($breaks); - } - - $record = 0x001b; // Record identifier - $cbrk = count($breaks); // Number of page breaks - $length = 2 + 6*$cbrk; // Bytes to follow - - $header = pack("vv", $record, $length); - $data = pack("v", $cbrk); - - // Append each page break - foreach($breaks as $break) { - $data .= pack("vvv", $break, 0x0000, 0x00ff); - } - - $this->_prepend($header.$data); - } - - - /** - * Write the VERTICALPAGEBREAKS BIFF record. - * - * @access private - */ - function _storeVbreak() - { - // Return if the user hasn't specified pagebreaks - if (empty($this->_vbreaks)) { - return; - } - - // 1000 vertical pagebreaks appears to be an internal Excel 5 limit. - // It is slightly higher in Excel 97/200, approx. 1026 - $breaks = array_slice($this->_vbreaks,0,1000); - - // Sort and filter array of page breaks - sort($breaks, SORT_NUMERIC); - if ($breaks[0] == 0) { // don't use first break if it's 0 - array_shift($breaks); - } - - $record = 0x001a; // Record identifier - $cbrk = count($breaks); // Number of page breaks - $length = 2 + 6*$cbrk; // Bytes to follow - - $header = pack("vv", $record, $length); - $data = pack("v", $cbrk); - - // Append each page break - foreach ($breaks as $break) { - $data .= pack("vvv", $break, 0x0000, 0xffff); - } - - $this->_prepend($header.$data); - } - - /** - * Set the Biff PROTECT record to indicate that the worksheet is protected. - * - * @access private - */ - function _storeProtect() - { - // Exit unless sheet protection has been specified - if ($this->_protect == 0) { - return; - } - - $record = 0x0012; // Record identifier - $length = 0x0002; // Bytes to follow - - $fLock = $this->_protect; // Worksheet is protected - - $header = pack("vv", $record, $length); - $data = pack("v", $fLock); - - $this->_prepend($header.$data); - } - - /** - * Write the worksheet PASSWORD record. - * - * @access private - */ - function _storePassword() - { - // Exit unless sheet protection and password have been specified - if (($this->_protect == 0) or (!isset($this->_password))) { - return; - } - - $record = 0x0013; // Record identifier - $length = 0x0002; // Bytes to follow - - $wPassword = $this->_password; // Encoded password - - $header = pack("vv", $record, $length); - $data = pack("v", $wPassword); - - $this->_prepend($header.$data); - } - - - /** - * Insert a 24bit bitmap image in a worksheet. - * - * @access public - * @param integer $row The row we are going to insert the bitmap into - * @param integer $col The column we are going to insert the bitmap into - * @param string $bitmap The bitmap filename - * @param integer $x The horizontal position (offset) of the image inside the cell. - * @param integer $y The vertical position (offset) of the image inside the cell. - * @param integer $scale_x The horizontal scale - * @param integer $scale_y The vertical scale - */ - function insertBitmap($row, $col, $bitmap, $x = 0, $y = 0, $scale_x = 1, $scale_y = 1) - { - $bitmap_array = $this->_processBitmap($bitmap); - if ($this->isError($bitmap_array)) - { - $this->writeString($row, $col, $bitmap_array->getMessage()); - return; - } - list($width, $height, $size, $data) = $bitmap_array; //$this->_processBitmap($bitmap); - - // Scale the frame of the image. - $width *= $scale_x; - $height *= $scale_y; - - // Calculate the vertices of the image and write the OBJ record - $this->_positionImage($col, $row, $x, $y, $width, $height); - - // Write the IMDATA record to store the bitmap data - $record = 0x007f; - $length = 8 + $size; - $cf = 0x09; - $env = 0x01; - $lcb = $size; - - $header = pack("vvvvV", $record, $length, $cf, $env, $lcb); - $this->_append($header.$data); - } - - /** - * Calculate the vertices that define the position of the image as required by - * the OBJ record. - * - * +------------+------------+ - * | A | B | - * +-----+------------+------------+ - * | |(x1,y1) | | - * | 1 |(A1)._______|______ | - * | | | | | - * | | | | | - * +-----+----| BITMAP |-----+ - * | | | | | - * | 2 | |______________. | - * | | | (B2)| - * | | | (x2,y2)| - * +---- +------------+------------+ - * - * Example of a bitmap that covers some of the area from cell A1 to cell B2. - * - * Based on the width and height of the bitmap we need to calculate 8 vars: - * $col_start, $row_start, $col_end, $row_end, $x1, $y1, $x2, $y2. - * The width and height of the cells are also variable and have to be taken into - * account. - * The values of $col_start and $row_start are passed in from the calling - * function. The values of $col_end and $row_end are calculated by subtracting - * the width and height of the bitmap from the width and height of the - * underlying cells. - * The vertices are expressed as a percentage of the underlying cell width as - * follows (rhs values are in pixels): - * - * x1 = X / W *1024 - * y1 = Y / H *256 - * x2 = (X-1) / W *1024 - * y2 = (Y-1) / H *256 - * - * Where: X is distance from the left side of the underlying cell - * Y is distance from the top of the underlying cell - * W is the width of the cell - * H is the height of the cell - * - * @access private - * @note the SDK incorrectly states that the height should be expressed as a - * percentage of 1024. - * @param integer $col_start Col containing upper left corner of object - * @param integer $row_start Row containing top left corner of object - * @param integer $x1 Distance to left side of object - * @param integer $y1 Distance to top of object - * @param integer $width Width of image frame - * @param integer $height Height of image frame - */ - function _positionImage($col_start, $row_start, $x1, $y1, $width, $height) - { - // Initialise end cell to the same as the start cell - $col_end = $col_start; // Col containing lower right corner of object - $row_end = $row_start; // Row containing bottom right corner of object - - // Zero the specified offset if greater than the cell dimensions - if ($x1 >= $this->_sizeCol($col_start)) - { - $x1 = 0; - } - if ($y1 >= $this->_sizeRow($row_start)) - { - $y1 = 0; - } - - $width = $width + $x1 -1; - $height = $height + $y1 -1; - - // Subtract the underlying cell widths to find the end cell of the image - while ($width >= $this->_sizeCol($col_end)) { - $width -= $this->_sizeCol($col_end); - $col_end++; - } - - // Subtract the underlying cell heights to find the end cell of the image - while ($height >= $this->_sizeRow($row_end)) { - $height -= $this->_sizeRow($row_end); - $row_end++; - } - - // Bitmap isn't allowed to start or finish in a hidden cell, i.e. a cell - // with zero eight or width. - // - if ($this->_sizeCol($col_start) == 0) - return; - if ($this->_sizeCol($col_end) == 0) - return; - if ($this->_sizeRow($row_start) == 0) - return; - if ($this->_sizeRow($row_end) == 0) - return; - - // Convert the pixel values to the percentage value expected by Excel - $x1 = $x1 / $this->_sizeCol($col_start) * 1024; - $y1 = $y1 / $this->_sizeRow($row_start) * 256; - $x2 = $width / $this->_sizeCol($col_end) * 1024; // Distance to right side of object - $y2 = $height / $this->_sizeRow($row_end) * 256; // Distance to bottom of object - - $this->_storeObjPicture( $col_start, $x1, - $row_start, $y1, - $col_end, $x2, - $row_end, $y2 - ); - } - - /** - * Convert the width of a cell from user's units to pixels. By interpolation - * the relationship is: y = 7x +5. If the width hasn't been set by the user we - * use the default value. If the col is hidden we use a value of zero. - * - * @access private - * @param integer $col The column - * @return integer The width in pixels - */ - function _sizeCol($col) - { - // Look up the cell value to see if it has been changed - if (isset($this->col_sizes[$col])) { - if ($this->col_sizes[$col] == 0) { - return(0); - } - else { - return(floor(7 * $this->col_sizes[$col] + 5)); - } - } - else { - return(64); - } - } - - /** - * Convert the height of a cell from user's units to pixels. By interpolation - * the relationship is: y = 4/3x. If the height hasn't been set by the user we - * use the default value. If the row is hidden we use a value of zero. (Not - * possible to hide row yet). - * - * @access private - * @param integer $row The row - * @return integer The width in pixels - */ - function _sizeRow($row) - { - // Look up the cell value to see if it has been changed - if (isset($this->row_sizes[$row])) { - if ($this->row_sizes[$row] == 0) { - return(0); - } - else { - return(floor(4/3 * $this->row_sizes[$row])); - } - } - else { - return(17); - } - } - - /** - * Store the OBJ record that precedes an IMDATA record. This could be generalise - * to support other Excel objects. - * - * @access private - * @param integer $colL Column containing upper left corner of object - * @param integer $dxL Distance from left side of cell - * @param integer $rwT Row containing top left corner of object - * @param integer $dyT Distance from top of cell - * @param integer $colR Column containing lower right corner of object - * @param integer $dxR Distance from right of cell - * @param integer $rwB Row containing bottom right corner of object - * @param integer $dyB Distance from bottom of cell - */ - function _storeObjPicture($colL,$dxL,$rwT,$dyT,$colR,$dxR,$rwB,$dyB) - { - $record = 0x005d; // Record identifier - $length = 0x003c; // Bytes to follow - - $cObj = 0x0001; // Count of objects in file (set to 1) - $OT = 0x0008; // Object type. 8 = Picture - $id = 0x0001; // Object ID - $grbit = 0x0614; // Option flags - - $cbMacro = 0x0000; // Length of FMLA structure - $Reserved1 = 0x0000; // Reserved - $Reserved2 = 0x0000; // Reserved - - $icvBack = 0x09; // Background colour - $icvFore = 0x09; // Foreground colour - $fls = 0x00; // Fill pattern - $fAuto = 0x00; // Automatic fill - $icv = 0x08; // Line colour - $lns = 0xff; // Line style - $lnw = 0x01; // Line weight - $fAutoB = 0x00; // Automatic border - $frs = 0x0000; // Frame style - $cf = 0x0009; // Image format, 9 = bitmap - $Reserved3 = 0x0000; // Reserved - $cbPictFmla = 0x0000; // Length of FMLA structure - $Reserved4 = 0x0000; // Reserved - $grbit2 = 0x0001; // Option flags - $Reserved5 = 0x0000; // Reserved - - - $header = pack("vv", $record, $length); - $data = pack("V", $cObj); - $data .= pack("v", $OT); - $data .= pack("v", $id); - $data .= pack("v", $grbit); - $data .= pack("v", $colL); - $data .= pack("v", $dxL); - $data .= pack("v", $rwT); - $data .= pack("v", $dyT); - $data .= pack("v", $colR); - $data .= pack("v", $dxR); - $data .= pack("v", $rwB); - $data .= pack("v", $dyB); - $data .= pack("v", $cbMacro); - $data .= pack("V", $Reserved1); - $data .= pack("v", $Reserved2); - $data .= pack("C", $icvBack); - $data .= pack("C", $icvFore); - $data .= pack("C", $fls); - $data .= pack("C", $fAuto); - $data .= pack("C", $icv); - $data .= pack("C", $lns); - $data .= pack("C", $lnw); - $data .= pack("C", $fAutoB); - $data .= pack("v", $frs); - $data .= pack("V", $cf); - $data .= pack("v", $Reserved3); - $data .= pack("v", $cbPictFmla); - $data .= pack("v", $Reserved4); - $data .= pack("v", $grbit2); - $data .= pack("V", $Reserved5); - - $this->_append($header.$data); - } - - /** - * Convert a 24 bit bitmap into the modified internal format used by Windows. - * This is described in BITMAPCOREHEADER and BITMAPCOREINFO structures in the - * MSDN library. - * - * @access private - * @param string $bitmap The bitmap to process - * @return array Array with data and properties of the bitmap - */ - function _processBitmap($bitmap) - { - // Open file. - $bmp_fd = @fopen($bitmap,"rb"); - if (!$bmp_fd) { - $this->raiseError("Couldn't import $bitmap"); - } - - // Slurp the file into a string. - $data = fread($bmp_fd, filesize($bitmap)); - - // Check that the file is big enough to be a bitmap. - if (strlen($data) <= 0x36) { - $this->raiseError("$bitmap doesn't contain enough data.\n"); - } - - // The first 2 bytes are used to identify the bitmap. - $identity = unpack("A2", $data); - if ($identity[''] != "BM") { - $this->raiseError("$bitmap doesn't appear to be a valid bitmap image.\n"); - } - - // Remove bitmap data: ID. - $data = substr($data, 2); - - // Read and remove the bitmap size. This is more reliable than reading - // the data size at offset 0x22. - // - $size_array = unpack("V", substr($data, 0, 4)); - $size = $size_array['']; - $data = substr($data, 4); - $size -= 0x36; // Subtract size of bitmap header. - $size += 0x0C; // Add size of BIFF header. - - // Remove bitmap data: reserved, offset, header length. - $data = substr($data, 12); - - // Read and remove the bitmap width and height. Verify the sizes. - $width_and_height = unpack("V2", substr($data, 0, 8)); - $width = $width_and_height[1]; - $height = $width_and_height[2]; - $data = substr($data, 8); - if ($width > 0xFFFF) { - $this->raiseError("$bitmap: largest image width supported is 65k.\n"); - } - if ($height > 0xFFFF) { - $this->raiseError("$bitmap: largest image height supported is 65k.\n"); - } - - // Read and remove the bitmap planes and bpp data. Verify them. - $planes_and_bitcount = unpack("v2", substr($data, 0, 4)); - $data = substr($data, 4); - if ($planes_and_bitcount[2] != 24) { // Bitcount - $this->raiseError("$bitmap isn't a 24bit true color bitmap.\n"); - } - if ($planes_and_bitcount[1] != 1) { - $this->raiseError("$bitmap: only 1 plane nupported in bitmap image.\n"); - } - - // Read and remove the bitmap compression. Verify compression. - $compression = unpack("V", substr($data, 0, 4)); - $data = substr($data, 4); - - //$compression = 0; - if ($compression[""] != 0) { - $this->raiseError("$bitmap: compression not supported in bitmap image.\n"); - } - - // Remove bitmap data: data size, hres, vres, colours, imp. colours. - $data = substr($data, 20); - - // Add the BITMAPCOREHEADER data - $header = pack("Vvvvv", 0x000c, $width, $height, 0x01, 0x18); - $data = $header . $data; - - return (array($width, $height, $size, $data)); - } - - /** - * Store the window zoom factor. This should be a reduced fraction but for - * simplicity we will store all fractions with a numerator of 100. - * - * @access private - */ - function _storeZoom() - { - // If scale is 100 we don't need to write a record - if ($this->_zoom == 100) { - return; - } - - $record = 0x00A0; // Record identifier - $length = 0x0004; // Bytes to follow - - $header = pack("vv", $record, $length); - $data = pack("vv", $this->_zoom, 100); - $this->_append($header.$data); - } - - /** - * FIXME: add comments - */ - function setValidation($row1, $col1, $row2, $col2, &$validator) - { - $this->_dv[] = $validator->_getData() . - pack("vvvvv", 1, $row1, $row2, $col1, $col2); - } - - /** - * Store the DVAL and DV records. - * - * @access private - */ - function _storeDataValidity() - { - $record = 0x01b2; // Record identifier - $length = 0x0012; // Bytes to follow - - $grbit = 0x0002; // Prompt box at cell, no cached validity data at DV records - $horPos = 0x00000000; // Horizontal position of prompt box, if fixed position - $verPos = 0x00000000; // Vertical position of prompt box, if fixed position - $objId = 0xffffffff; // Object identifier of drop down arrow object, or -1 if not visible - - $header = pack('vv', $record, $length); - $data = pack('vVVVV', $grbit, $horPos, $verPos, $objId, - count($this->_dv)); - $this->_append($header.$data); - - $record = 0x01be; // Record identifier - foreach($this->_dv as $dv) - { - $length = strlen($dv); // Bytes to follow - $header = pack("vv", $record, $length); - $this->_append($header.$dv); - } - } -} -?> diff --git a/gulliver/thirdparty/pear/Spreadsheet/package.xml b/gulliver/thirdparty/pear/Spreadsheet/package.xml deleted file mode 100644 index 53fe8ba13..000000000 --- a/gulliver/thirdparty/pear/Spreadsheet/package.xml +++ /dev/null @@ -1,61 +0,0 @@ - - - OLE - Package for reading and writing OLE containers - This package allows reading and writing of OLE (Object Linking and Embedding) files, the format used as container for Excel, Word and other MS file formats. - Documentation for the OLE format can be found at: http://user.cs.tu-berlin.de/~schwartz/pmh/guide.html - - - xnoguer - Xavier Noguer - xnoguer@php.net - lead - - - - 0.5 - 2003-12-14 - PHP - beta - - BC break!!! OLE/OLE.php file moved to OLE.php to comply with PEAR - standards. You will have to change your require('OLE/OLE.php')'s - for require('OLE.php')'s -- If you are using Spreadsheet_Excel_Writer, do not upgrade to this - version yet. A new version of Spreadsheet_Excel_Writer will be - released soon so the BC break won't affect you. -- allowing setting of temp dir for OLE_PPS_File and OLE_PPS_Root objects -- fixed problem when reading files (not reading the whole OLE tree) - - - - - - - - - - 0.4 - 2003-09-25 - beta - -deleting tmp files (Herman Kuiper). --fixed hardcoded tmp dir (Herman Kuiper). --fixed pass by reference warning (Herman Kuiper). - - - - 0.3 - 2003-08-21 - beta - -added OLE_PPS_File::init() initialization method. --better error handling. - - - - 0.2.1 - 2003-05-12 - alpha - Fixing install dir - - - - diff --git a/gulliver/thirdparty/pear/System.php b/gulliver/thirdparty/pear/System.php deleted file mode 100644 index 910596988..000000000 --- a/gulliver/thirdparty/pear/System.php +++ /dev/null @@ -1,540 +0,0 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: System.php 6820 2007-06-20 13:35:30Z kevin_fourie $ -// - -require_once 'PEAR.php'; -require_once 'Console/Getopt.php'; - -$GLOBALS['_System_temp_files'] = array(); - -/** -* System offers cross plattform compatible system functions -* -* Static functions for different operations. Should work under -* Unix and Windows. The names and usage has been taken from its respectively -* GNU commands. The functions will return (bool) false on error and will -* trigger the error with the PHP trigger_error() function (you can silence -* the error by prefixing a '@' sign after the function call). -* -* Documentation on this class you can find in: -* http://pear.php.net/manual/ -* -* Example usage: -* if (!@System::rm('-r file1 dir1')) { -* print "could not delete file1 or dir1"; -* } -* -* In case you need to to pass file names with spaces, -* pass the params as an array: -* -* System::rm(array('-r', $file1, $dir1)); -* -* @package System -* @author Tomas V.V.Cox -* @version $Revision: 6820 $ -* @access public -* @see http://pear.php.net/manual/ -*/ -class System -{ - /** - * returns the commandline arguments of a function - * - * @param string $argv the commandline - * @param string $short_options the allowed option short-tags - * @param string $long_options the allowed option long-tags - * @return array the given options and there values - * @access private - */ - function _parseArgs($argv, $short_options, $long_options = null) - { - if (!is_array($argv) && $argv !== null) { - $argv = preg_split('/\s+/', $argv); - } - return Console_Getopt::getopt2($argv, $short_options); - } - - /** - * Output errors with PHP trigger_error(). You can silence the errors - * with prefixing a "@" sign to the function call: @System::mkdir(..); - * - * @param mixed $error a PEAR error or a string with the error message - * @return bool false - * @access private - */ - function raiseError($error) - { - if (PEAR::isError($error)) { - $error = $error->getMessage(); - } - trigger_error($error, E_USER_WARNING); - return false; - } - - /** - * Creates a nested array representing the structure of a directory - * - * System::_dirToStruct('dir1', 0) => - * Array - * ( - * [dirs] => Array - * ( - * [0] => dir1 - * ) - * - * [files] => Array - * ( - * [0] => dir1/file2 - * [1] => dir1/file3 - * ) - * ) - * @param string $sPath Name of the directory - * @param integer $maxinst max. deep of the lookup - * @param integer $aktinst starting deep of the lookup - * @return array the structure of the dir - * @access private - */ - - function _dirToStruct($sPath, $maxinst, $aktinst = 0) - { - $struct = array('dirs' => array(), 'files' => array()); - if (($dir = @opendir($sPath)) === false) { - System::raiseError("Could not open dir $sPath"); - return $struct; // XXX could not open error - } - $struct['dirs'][] = $sPath; // XXX don't add if '.' or '..' ? - $list = array(); - while ($file = readdir($dir)) { - if ($file != '.' && $file != '..') { - $list[] = $file; - } - } - closedir($dir); - sort($list); - if ($aktinst < $maxinst || $maxinst == 0) { - foreach($list as $val) { - $path = $sPath . DIRECTORY_SEPARATOR . $val; - if (is_dir($path)) { - $tmp = System::_dirToStruct($path, $maxinst, $aktinst+1); - $struct = array_merge_recursive($tmp, $struct); - } else { - $struct['files'][] = $path; - } - } - } - return $struct; - } - - /** - * Creates a nested array representing the structure of a directory and files - * - * @param array $files Array listing files and dirs - * @return array - * @see System::_dirToStruct() - */ - function _multipleToStruct($files) - { - $struct = array('dirs' => array(), 'files' => array()); - settype($files, 'array'); - foreach ($files as $file) { - if (is_dir($file)) { - $tmp = System::_dirToStruct($file, 0); - $struct = array_merge_recursive($tmp, $struct); - } else { - $struct['files'][] = $file; - } - } - return $struct; - } - - /** - * The rm command for removing files. - * Supports multiple files and dirs and also recursive deletes - * - * @param string $args the arguments for rm - * @return mixed PEAR_Error or true for success - * @access public - */ - function rm($args) - { - $opts = System::_parseArgs($args, 'rf'); // "f" do nothing but like it :-) - if (PEAR::isError($opts)) { - return System::raiseError($opts); - } - foreach($opts[0] as $opt) { - if ($opt[0] == 'r') { - $do_recursive = true; - } - } - $ret = true; - if (isset($do_recursive)) { - $struct = System::_multipleToStruct($opts[1]); - foreach($struct['files'] as $file) { - if (!@unlink($file)) { - $ret = false; - } - } - foreach($struct['dirs'] as $dir) { - if (!@rmdir($dir)) { - $ret = false; - } - } - } else { - foreach ($opts[1] as $file) { - $delete = (is_dir($file)) ? 'rmdir' : 'unlink'; - if (!@$delete($file)) { - $ret = false; - } - } - } - return $ret; - } - - /** - * Make directories. Note that we use call_user_func('mkdir') to avoid - * a problem with ZE2 calling System::mkDir instead of the native PHP func. - * - * @param string $args the name of the director(y|ies) to create - * @return bool True for success - * @access public - */ - function mkDir($args) - { - $opts = System::_parseArgs($args, 'pm:'); - if (PEAR::isError($opts)) { - return System::raiseError($opts); - } - $mode = 0777; // default mode - foreach($opts[0] as $opt) { - if ($opt[0] == 'p') { - $create_parents = true; - } elseif($opt[0] == 'm') { - // if the mode is clearly an octal number (starts with 0) - // convert it to decimal - if (strlen($opt[1]) && $opt[1]{0} == '0') { - $opt[1] = octdec($opt[1]); - } else { - // convert to int - $opt[1] += 0; - } - $mode = $opt[1]; - } - } - $ret = true; - if (isset($create_parents)) { - foreach($opts[1] as $dir) { - $dirstack = array(); - while (!@is_dir($dir) && $dir != DIRECTORY_SEPARATOR) { - array_unshift($dirstack, $dir); - $dir = dirname($dir); - } - while ($newdir = array_shift($dirstack)) { - if (!call_user_func('mkdir', $newdir, $mode)) { - $ret = false; - } - } - } - } else { - foreach($opts[1] as $dir) { - if (!@is_dir($dir) && !call_user_func('mkdir', $dir, $mode)) { - $ret = false; - } - } - } - return $ret; - } - - /** - * Concatenate files - * - * Usage: - * 1) $var = System::cat('sample.txt test.txt'); - * 2) System::cat('sample.txt test.txt > final.txt'); - * 3) System::cat('sample.txt test.txt >> final.txt'); - * - * Note: as the class use fopen, urls should work also (test that) - * - * @param string $args the arguments - * @return boolean true on success - * @access public - */ - function &cat($args) - { - $ret = null; - $files = array(); - if (!is_array($args)) { - $args = preg_split('/\s+/', $args); - } - for($i=0; $i < count($args); $i++) { - if ($args[$i] == '>') { - $mode = 'wb'; - $outputfile = $args[$i+1]; - break; - } elseif ($args[$i] == '>>') { - $mode = 'ab+'; - $outputfile = $args[$i+1]; - break; - } else { - $files[] = $args[$i]; - } - } - if (isset($mode)) { - if (!$outputfd = fopen($outputfile, $mode)) { - $err = System::raiseError("Could not open $outputfile"); - return $err; - } - $ret = true; - } - foreach ($files as $file) { - if (!$fd = fopen($file, 'r')) { - System::raiseError("Could not open $file"); - continue; - } - while ($cont = fread($fd, 2048)) { - if (isset($outputfd)) { - fwrite($outputfd, $cont); - } else { - $ret .= $cont; - } - } - fclose($fd); - } - if (@is_resource($outputfd)) { - fclose($outputfd); - } - return $ret; - } - - /** - * Creates temporary files or directories. This function will remove - * the created files when the scripts finish its execution. - * - * Usage: - * 1) $tempfile = System::mktemp("prefix"); - * 2) $tempdir = System::mktemp("-d prefix"); - * 3) $tempfile = System::mktemp(); - * 4) $tempfile = System::mktemp("-t /var/tmp prefix"); - * - * prefix -> The string that will be prepended to the temp name - * (defaults to "tmp"). - * -d -> A temporary dir will be created instead of a file. - * -t -> The target dir where the temporary (file|dir) will be created. If - * this param is missing by default the env vars TMP on Windows or - * TMPDIR in Unix will be used. If these vars are also missing - * c:\windows\temp or /tmp will be used. - * - * @param string $args The arguments - * @return mixed the full path of the created (file|dir) or false - * @see System::tmpdir() - * @access public - */ - function mktemp($args = null) - { - static $first_time = true; - $opts = System::_parseArgs($args, 't:d'); - if (PEAR::isError($opts)) { - return System::raiseError($opts); - } - foreach($opts[0] as $opt) { - if($opt[0] == 'd') { - $tmp_is_dir = true; - } elseif($opt[0] == 't') { - $tmpdir = $opt[1]; - } - } - $prefix = (isset($opts[1][0])) ? $opts[1][0] : 'tmp'; - if (!isset($tmpdir)) { - $tmpdir = System::tmpdir(); - } - if (!System::mkDir("-p $tmpdir")) { - return false; - } - $tmp = tempnam($tmpdir, $prefix); - if (isset($tmp_is_dir)) { - unlink($tmp); // be careful possible race condition here - if (!call_user_func('mkdir', $tmp, 0700)) { - return System::raiseError("Unable to create temporary directory $tmpdir"); - } - } - $GLOBALS['_System_temp_files'][] = $tmp; - if ($first_time) { - PEAR::registerShutdownFunc(array('System', '_removeTmpFiles')); - $first_time = false; - } - return $tmp; - } - - /** - * Remove temporary files created my mkTemp. This function is executed - * at script shutdown time - * - * @access private - */ - function _removeTmpFiles() - { - if (count($GLOBALS['_System_temp_files'])) { - $delete = $GLOBALS['_System_temp_files']; - array_unshift($delete, '-r'); - System::rm($delete); - } - } - - /** - * Get the path of the temporal directory set in the system - * by looking in its environments variables. - * Note: php.ini-recommended removes the "E" from the variables_order setting, - * making unavaible the $_ENV array, that s why we do tests with _ENV - * - * @return string The temporal directory on the system - */ - function tmpdir() - { - if (OS_WINDOWS) { - if ($var = isset($_ENV['TEMP']) ? $_ENV['TEMP'] : getenv('TEMP')) { - return $var; - } - if ($var = isset($_ENV['TMP']) ? $_ENV['TMP'] : getenv('TMP')) { - return $var; - } - if ($var = isset($_ENV['windir']) ? $_ENV['windir'] : getenv('windir')) { - return $var; - } - return getenv('SystemRoot') . '\temp'; - } - if ($var = isset($_ENV['TMPDIR']) ? $_ENV['TMPDIR'] : getenv('TMPDIR')) { - return $var; - } - return '/tmp'; - } - - /** - * The "which" command (show the full path of a command) - * - * @param string $program The command to search for - * @return mixed A string with the full path or false if not found - * @author Stig Bakken - */ - function which($program, $fallback = false) - { - // is_executable() is not available on windows - if (OS_WINDOWS) { - $pear_is_executable = 'is_file'; - } else { - $pear_is_executable = 'is_executable'; - } - - // full path given - if (basename($program) != $program) { - return (@$pear_is_executable($program)) ? $program : $fallback; - } - - // XXX FIXME honor safe mode - $path_delim = OS_WINDOWS ? ';' : ':'; - $exe_suffixes = OS_WINDOWS ? array('.exe','.bat','.cmd','.com') : array(''); - $path_elements = explode($path_delim, getenv('PATH')); - foreach ($exe_suffixes as $suff) { - foreach ($path_elements as $dir) { - $file = $dir . DIRECTORY_SEPARATOR . $program . $suff; - if (@is_file($file) && @$pear_is_executable($file)) { - return $file; - } - } - } - return $fallback; - } - - /** - * The "find" command - * - * Usage: - * - * System::find($dir); - * System::find("$dir -type d"); - * System::find("$dir -type f"); - * System::find("$dir -name *.php"); - * System::find("$dir -name *.php -name *.htm*"); - * System::find("$dir -maxdepth 1"); - * - * Params implmented: - * $dir -> Start the search at this directory - * -type d -> return only directories - * -type f -> return only files - * -maxdepth -> max depth of recursion - * -name -> search pattern (bash style). Multiple -name param allowed - * - * @param mixed Either array or string with the command line - * @return array Array of found files - * - */ - function find($args) - { - if (!is_array($args)) { - $args = preg_split('/\s+/', $args, -1, PREG_SPLIT_NO_EMPTY); - } - $dir = array_shift($args); - $patterns = array(); - $depth = 0; - $do_files = $do_dirs = true; - for ($i = 0; $i < count($args); $i++) { - switch ($args[$i]) { - case '-type': - if (in_array($args[$i+1], array('d', 'f'))) { - if ($args[$i+1] == 'd') { - $do_files = false; - } else { - $do_dirs = false; - } - } - $i++; - break; - case '-name': - $patterns[] = "(" . preg_replace(array('/\./', '/\*/'), - array('\.', '.*'), - $args[$i+1]) - . ")"; - $i++; - break; - case '-maxdepth': - $depth = $args[$i+1]; - break; - } - } - $path = System::_dirToStruct($dir, $depth); - if ($do_files && $do_dirs) { - $files = array_merge($path['files'], $path['dirs']); - } elseif ($do_dirs) { - $files = $path['dirs']; - } else { - $files = $path['files']; - } - if (count($patterns)) { - $patterns = implode('|', $patterns); - $ret = array(); - for ($i = 0; $i < count($files); $i++) { - if (preg_match("#^$patterns\$#", $files[$i])) { - $ret[] = $files[$i]; - } - } - return $ret; - } - return $files; - } -} -?> diff --git a/gulliver/thirdparty/pear/UDDI.php b/gulliver/thirdparty/pear/UDDI.php deleted file mode 100644 index bb1ba571c..000000000 --- a/gulliver/thirdparty/pear/UDDI.php +++ /dev/null @@ -1,720 +0,0 @@ - | -// | Tobias Hauser | -// +----------------------------------------------------------------------+ -// -// $Id$ -/* Original Credits: - - phpUDDI - A PHP class library implementing the Universal Description, - Discovery and Integration API for locating and publishing Web - Services listings in a UBR (UDDI Business Registry). - - Copyright (C) 2002-2004 Lee Reynolds and Jon Stephens - - This program is free software; you can redistribute it and/or - modify it under the terms of the GNU General Public License - as published by the Free Software Foundation; either version 2 - of the License, or (at your option) any later version. - - This program 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 General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA - or point your web browser to http://www.gnu.org/licenses/lgpl.html. - - Conceived and developed in conjunction with the - authors' work for the book "PHP Web Services" from Wrox Press - Ltd. (ISBN-1861008074) - - Original developers: - Lee Reynolds lee@annasart.com - Jon Stephens jon@hiveminds.info - - Useful Links: - - Wrox Press "Programmer To Programmer" Discussion Groups - Pro PHP: http://p2p.wrox.com/list.asp?list=pro_php - Pro XML: http://p2p.wrox.com/list.asp?list=xml - - HiveMinds Group - http://www.hiveminds.info/ - http://forums.hiveminds.info/ - - Version History: - - 0.1 -- 15 November 2002 -- Basic Proof of concept - 0.2 -- 20 November 2002 -- Base class redefinition to - include public and private methods - 0.3 -- 25 November 2002 -- All UDDI 2.0 Inquiry APIs implemented - 0.3.1 -- 14 March 2004 -- small bugfixes (Christian); license change to LPGL (Lee, Jon) - - Objective for 1.0 release is complete implementation of the UDDI 2.0 API - (http://www.uddi.org/pubs/ProgrammersAPI-V2.04-Published-20020719.pdf). - - Objective for 1.5 release is backwards compatibility with UDDI 1.0. - - Objective for 2.0 release is complete implementation of the UDDI 3.0 API - (http://www.uddi.org/pubs/uddi-v3.00-published-20020719.pdf). - -*/ - -require_once 'PEAR.php'; - -/** - * PEAR::UDDI - * class that implements the UDDI API - * @link http://www.uddi.org/ - * - * pearified version of phpUDDI by Stephens & Reynolds - * - * - * @category Web Services - * @package UDDI - * @version 0.2.0alpha4 - * @author Christian Wenz - * @author Tobias Hauser - * @todo fully implement UDDI 2.0 (and later 1.0, 3.0) - * @todo more helper functions (for analyzing the data returned by querying a UBR) - - -Name: - UDDI.php - UDDI Registry access library (PEARified version) - -Synopsis: - require_once 'UDDI/UDDI.php'; - -Currently, PEAR::UDDI supports 1 function call in one UDDI API. - -Variables supported: - $UDDI::_api - currently 2 values are supported, and they represent 2 of the 6 published APIs by UDDI.org. - 'Inquiry' which represents the search and _query API - 'Publish' which represents the publishing API - - Usage: - - $UDDI::_api = 'Inquiry'; // (default) - $UDDI::_api = 'Publish'; - - - $UDDI::_uddiversion - This is the API version of the UPI spec you want to use - Values are either 1, 2, or 3. - - Usage: - - $UDDI::_uddiversion = 2; - - - Default: - currently, the version default is '1'; - - Note: As stated above, we are aiming for a 1.0 release of this library which implements - the UDDI 2.0 Programming API; we cannot guarantee at this time that any of the API functions - as implemented here will work correctly (or at all) unless you set the version to 2 as shown - under 'Usage' immediately above or by setting the version when you call the UDDI class constructor: - - - $my_uddi = new UDDI('Microsoft', 2); - - - At a later date we will make this class compatible with UDDI Versions 1.0 and 3.0. - - $UDDI::_regarray - We currently support 2 test registry entries. These are 'IBM' and 'Microsoft'. - We also support 2 API interfaces. These are, as noted above, 'Inquiry' and 'Publish'. - - To add live registry entries, or your own test registry, you must append a multiple index array element - to $UDDI::_regarray. The form for this follows: - - array('registry name' => - array('Inquiry' => - array('url' => 'url_for_inquiry', - 'port' => 80), - 'Publish' => - array('url' => 'url_for_publish', - 'port' => 443))); - - Internally this is accessed as - URL = $_regarray['registry_name']['Inquiry']['url'] - , and - port = $_regarray['registry_name']['Inquiry']['port'] - - PLEASE NOTE: You're adding elements to this array, instead of overwriting old ones. - - Usage: - - $UDDI::_regarray = array('private' => - array('Inquiry' => - array('url' =>'url_for_inquiry', - 'port' => 80), - 'Publish' => - array('url' => 'url_for_publishing', - 'port' => 443))); - - - $UDDI::_xmlns - You can modify the XML namespace by reassigning a value to this - - Usage: - - $UDDI::_xmlns = 'new_ns_definition'; - - - Default: - 'urn:uddi-org:api' - - $UDDI::_debug - Turns on debugging by echoing HTTP headers and UDDI queries. - - Usage: - - $UDDI::_debug = true; - - - Default: - false - - $UDDI::_transmit - Turns on _posting of UDDI message to UBR. - - Usage: - - $UDDI::_transmit = false; - - - Default: - true; - - -EXAMPLE: - -This queries IBM's UDDI Registry for the first 50 businesses whose names include -the word "Acme", matches sorted first in ascending order by name, then in descending -order by date last updated. The raw XML that's returned is escaped and echoed to the page. - - -$my_uddi = new UDDI('IBM', 1); -$result = htmlspecialchars($my_uddi->find_business(array('name' => '%Acme%', 'maxRows' => 50, 'findQualifiers' => 'sortByNameAsc,sortByDateAsc'))); -echo "
$result
"; -
- -*/ - - -// {{{ constants -/** - * version of corresponding phpUDDI version - * still included so that moving from phpUDDI to PEAR::UDDI is easier - */ - -define('UDDI_PHP_LIB_VERSION', '0.3.1p'); //suffix p = PEAR :-) - -// }}} -// {{{ UDDI - -/** - * UDDI - * - * class that implements the UDDI API - * - * @package UDDI - * @author Christian Wenz - * @author Tobias Hauser -*/ -class UDDI extends PEAR -{ - // {{{ properties - - /** - * version of package - * @var string $_version - */ - var $_version = '0.2.0alpha4'; - - /** - * list of known registries - * @var array $regarray - */ - - var $_regarray = - array('IBM' => - array('Inquiry' => - array('url' => 'www-3.ibm.com/services/uddi/testregistry/inquiryapi', - 'port' => 80), - 'Publish' => - array('url' => 'https://www-3.ibm.com/services/uddi/testregistry/protect/publishapi', - 'port' => 443)), - - 'Microsoft' => - array('Inquiry' => - array('url' => 'test.uddi.microsoft.com/inquire', - 'port' => 80), - 'Publish' => - array('url' => 'https://test.uddi.microsoft.com/publish', - 'port' => 443))); - - - /** - * which API to use (Inquiry/Publish) - * @var string $_api - */ - var $_api = 'Inquiry'; - - /** - * used XML namespace - * @var string $_xmlns - */ - var $_xmlns = 'urn:uddi-org:api'; - - /** - * used UDDI version - * @var string $_uddiversion - */ - var $_uddiversion = 1; - - /** - * used XML generic version - * @var string $_generic - */ - var $_generic; - - /** - * debug mode - * @var boolean $_debug - */ - var $_debug = false; - - /** - * Turns on _posting of UDDI message to UBR - * @var boolean $_transmit - */ - var $_transmit = true; - - /** - * Host to use - * @var string $_host - */ - var $_host; - - /** - * URL to use - * @var string $_url - */ - var $_url; - - // }}} - // {{{ constructor - - /** - * constructor - * - * @access public - * @param string $registry name of registry to use - * @param integer $version UDDI version to use - */ - function UDDI($registry = 'IBM', $version = 1) - { - $this->splitUrl($registry, $version); - } - - // }}} - // {{{ splitUrl() - - /** - * retrieves information from URL and sets params - * - * @access public - * @param string $registry name of registry to use - * @param integer $version UDDI version to use - */ - function splitUrl($registry, $version) - { - $this->_registry = $registry; - $reg = $this->_regarray[$this->_registry][$this->_api]['url']; - $reg = str_replace('http://', '', $reg); - $pos = strpos($reg, '/') - or PEAR::raiseError("Invalid registry (POS = $pos, URL = '$reg')\n"); - $this->_host = substr($reg, 0, $pos); - $this->_url = substr($reg, $pos, strlen($reg) - 1); - - if ($version > 1) { - $this->_xmlns .= "_v$version"; - } - - $this->_generic = "$version.0"; - } - - // }}} - // {{{ post() - - /** - * assembles HTTP headers and posts these and the UDDI message to the UBR - * - * @access public - * @param string $message the UDDI message to send - * @return string $data data returned from the UBR - */ - function post($message) - { - $msg_length = strlen($message); - $php_version = phpversion(); - $date = str_replace('+0000', 'GMT', gmdate('r', time())); - - $header = ''; - $header .= "POST $this->_url HTTP/1.0\r\n"; - $header .= "Date: $date\r\n"; - $header .= "Content-Type: text/xml; charset=UTF-8\r\n"; - $header .= "User-agent: PEAR::UDDI/$this->_version php/$php_version\r\n"; - $header .= "Host: $this->_host\r\n"; - $header .= "SOAPAction: \"\"\r\n"; - $header .= "Content-Length: $msg_length\r\n\r\n"; - - // echoes HTTP header and UDDI message to page if true - if ($this->_debug) { - echo '
' . htmlspecialchars(str_replace('><', ">\n<", $header . $message)) . '
'; - } - - // sends header and message to UBR if true - if ($this->_transmit) { - $port = $this->_regarray[$this->_registry][$this->_api]['port']; - $fp = fsockopen($this->_host, $port, $errno, $errstr, 5) - or PEAR::raiseError("Couldn't connect to server at $this->_host:$port.
Error #$errno: $errstr."); - - fputs($fp, $header) - or PEAR::raiseError('Couldn\'t send HTTP headers.'); - fputs($fp, "$message\n\n") - or PEAR::raiseError('Couldn\'t send UDDI message.'); - - $response = ''; - while (!feof($fp)) { - $response .= fgets($fp, 1024) - or PEAR::raiseError('No response from server.'); - } - fclose($fp) - or PEAR::raiseError('Warning: Couldn\'t close HTTP connection.'); - - $response = str_replace('><', ">\n<", $response); - return $response; - } - } - - // }}} - // {{{ query() - - /** - * sends and UDDI query to the registry server - * - * @access public - * @param string $method the UDDI message to send - * @param array $params parameters for the query - * @return string $data response from the registry server - */ - function query($method, $params) - { - $message = $this->assemble($method, $params); - - return $this->post($message); - } - - // }}} - // {{{ assemble() - - /** - * generate XML creating the UDDI query - * - * @access public - * @param string $method the UDDI message to send - * @param array $params parameters for the query - * @return string $data the desired XML query code - */ - function assemble($method, $params) - { - $head = ''; - $head .= ''; - $head .= ''; - - $end = ""; - - $attrib = ''; - $element = ''; - - if (isset($params['discoveryURLs']) && ($params['discoveryURLs'] != '')) { - $element .= '' . $params['discoveryURLs'] . ''; - } - - if (isset($params['bindingKey']) && ($params['bindingKey'] != '')) { - $element .= '' . $params['bindingKey'] . ''; - } - - if (isset($params['businessKey']) && ($params['businessKey'] != '')) { - $element .= '' . $params['businessKey'] . ''; - } - - if (isset($params['serviceKey']) && ($params['serviceKey'] != '')) { - - if ($method == 'find_binding') { - $attrib .= ' serviceKey="' . $params['serviceKey'] . '"'; - } - if ($method == 'get_serviceDetail') { - $element .= '' . $params['serviceKey'] . ''; - } - } - - if (isset($params['tModelKey']) && ($params['tModelKey'] != '')) { - $element .= 'uuid:' . $params['tModelKey'] . ''; - } - - if (isset($params['findQualifiers']) && ($params['findQualifiers'] != '')) { - $element .= ''; - $findQualifiers = explode(',', $params['findQualifiers']); - for ($i = 0; $i < count($findQualifiers); $i++) { - $element .= '' . $findQualifiers[$i] . ''; - } - $element .= ''; - } - - if (isset($params['tModelBag']) && ($params['tModelBag'] != '')) { - $tModelKey = explode(',', $params['tModelBag']); - $element .= ''; - for ($i = 0; $i < count($tModelKey); $i++) { - $element .= 'uuid:' . $tModelKey[$i] . ''; - $element .= ''; - } - } - - if (isset($params['name']) && ($params['name'] != '')) { - $lang = ''; - if (isset($params['lang']) && ($params['lang'] != '')) { - $lang = "xml:lang=\"$lang\""; - } - $element .= '' . $params['name'] . ''; - } - - if (isset($params['identifierBag']) && ($params['identifierBag'] != '')) { - $element .= ''; - $keyedReference = explode(',', $params['identifierBag']); - for ($i = 0; $i < count($keyedReference); $i++) { - $element .= '' . $keyedReference[$i] . ''; - } - $element .= ''; - } - - if (isset($params['categoryBag']) && ($params['categoryBag'] != '')) { - $element .= ''; - $keyedReference = explode(',', $params['identifierBag']); - for ($i = 0; $i'; - } - $element .= ''; - } - - if (isset($params['maxRows']) && ($params['maxRows'] != '')) { - $attrib .= ' maxRows="' . $params['maxRows'] . '"'; - } - - $head .= "<$method $attrib xmlns=\"$this->_xmlns\" generic=\"$this->_generic\">"; - - $message = $head; - $message .= $element; - $message .= $end; - - return $message; - } - - // }}} - // {{{ find_binding() - - /** - * Sends find_binding inquiry to UBR (searchs for bindings within a businessService element) - * - * @access public - * @param array $params parameters for the query - * @return string $data response from the registry server - */ - function find_binding($params) - { - $data = $this->query('find_binding', $params); - return $data; - } - - // }}} - // {{{ find_business() - - /** - * Sends find_business inquiry to UBR (searchs businessEntity elements) - * - * @access public - * @param array $params parameters for the query - * @return string $data response from the registry server - */ - function find_business($params) - { - $data = $this->query('find_business', $params); - return $data; - } - - // }}} - // {{{ find_relatedBusinesses() - - /** - * Sends find_relatedBusinesses inquiry to UBR (searchs for related businessEntity elements for a given businessKey) - * - * @access public - * @param array $params parameters for the query - * @return string $data response from the registry server - */ - function find_relatedBusinesses($params) - { - $data = $this->query('find_relatedBusinesses', $params); - return $data; - } - - // }}} - // {{{ find_service() - - /** - * Sends find_service inquiry to UBR (searchs for businessService elements) - * - * @access public - * @param array $params parameters for the query - * @return string $data response from the registry server - */ - function find_service($params) - { - $data = $this->query('find_service', $params); - return $data; - } - - // }}} - // {{{ find_tModel() - - /** - * Sends find_tModel inquiry to UBR (searchs for tModel elements) - * - * @access public - * @param array $params parameters for the query - * @return string $data response from the registry server - */ - function find_tModel($params) - { - $data = $this->query('find_tModel', $params); - return $data; - } - - // }}} - // {{{ get_bindingDetail() - - /** - * Sends get_bindingDetail inquiry to UBR (returns bindingDetail elements for one or more bindingKey elements) - * - * @access public - * @param array $params parameters for the query - * @return string $data response from the registry server - */ - function get_bindingDetail($params) - { - $data = $this->query('get_bindingDetail', $params); - return $data; - } - - // }}} - // {{{ get_businessDetail() - - /** - * Sends get_businessDetail inquiry to UBR (returns information about one or more businessEntity elements) - * - * @access public - * @param array $params parameters for the query - * @return string $data response from the registry server - */ - function get_businessDetail($params) - { - $data = $this->query('get_businessDetail', $params); - return $data; - } - - // }}} - // {{{ get_businessDetailExt() - - /** - * Sends get_businessDetailExt inquiry to UBR (returns extended information about one or more businessEntity elements) - * - * @access public - * @param array $params parameters for the query - * @return string $data response from the registry server - */ - function get_businessDetailExt($params) - { - $data = $this->query('get_businessDetailExt', $params); - return $data; - } - - // }}} - // {{{ get_serviceDetail() - - /** - * Sends get_serviceDetail inquiry to UBR (returns information about one or more businessService elements) - * - * @access public - * @param array $params parameters for the query - * @return string $data response from the registry server - */ - function get_serviceDetail($params) - { - $data = $this->query('get_serviceDetail', $params); - return $data; - } - - // }}} - // {{{ get_tModelDetail() - - /** - * Sends get_tModelDetail inquiry to UBR (returns information about one or more tModel elements) - * - * @access public - * @param array $params parameters for the query - * @return string $data response from the registry server - */ - function get_tModelDetail($params) - { - $data = $this->query('get_tModelDetail', $params); - return $data; - } - - // }}} - -} - -// }}} - -?> diff --git a/gulliver/thirdparty/pear/XML/Parser.php b/gulliver/thirdparty/pear/XML/Parser.php deleted file mode 100644 index 664008b01..000000000 --- a/gulliver/thirdparty/pear/XML/Parser.php +++ /dev/null @@ -1,684 +0,0 @@ - | -// | Tomas V.V.Cox | -// | Stephan Schmidt | -// +----------------------------------------------------------------------+ -// -// $Id: Parser.php,v 1.25 2005/03/25 17:13:10 schst Exp $ - -/** - * XML Parser class. - * - * This is an XML parser based on PHP's "xml" extension, - * based on the bundled expat library. - * - * @category XML - * @package XML_Parser - * @author Stig Bakken - * @author Tomas V.V.Cox - * @author Stephan Schmidt - */ - -/** - * uses PEAR's error handling - */ -require_once 'PEAR.php'; - -/** - * resource could not be created - */ -define('XML_PARSER_ERROR_NO_RESOURCE', 200); - -/** - * unsupported mode - */ -define('XML_PARSER_ERROR_UNSUPPORTED_MODE', 201); - -/** - * invalid encoding was given - */ -define('XML_PARSER_ERROR_INVALID_ENCODING', 202); - -/** - * specified file could not be read - */ -define('XML_PARSER_ERROR_FILE_NOT_READABLE', 203); - -/** - * invalid input - */ -define('XML_PARSER_ERROR_INVALID_INPUT', 204); - -/** - * remote file cannot be retrieved in safe mode - */ -define('XML_PARSER_ERROR_REMOTE', 205); - -/** - * XML Parser class. - * - * This is an XML parser based on PHP's "xml" extension, - * based on the bundled expat library. - * - * Notes: - * - It requires PHP 4.0.4pl1 or greater - * - From revision 1.17, the function names used by the 'func' mode - * are in the format "xmltag_$elem", for example: use "xmltag_name" - * to handle the tags of your xml file. - * - * @category XML - * @package XML_Parser - * @author Stig Bakken - * @author Tomas V.V.Cox - * @author Stephan Schmidt - * @todo create XML_Parser_Namespace to parse documents with namespaces - * @todo create XML_Parser_Pull - * @todo Tests that need to be made: - * - mixing character encodings - * - a test using all expat handlers - * - options (folding, output charset) - * - different parsing modes - */ -class XML_Parser extends PEAR -{ - // {{{ properties - - /** - * XML parser handle - * - * @var resource - * @see xml_parser_create() - */ - var $parser; - - /** - * File handle if parsing from a file - * - * @var resource - */ - var $fp; - - /** - * Whether to do case folding - * - * If set to true, all tag and attribute names will - * be converted to UPPER CASE. - * - * @var boolean - */ - var $folding = true; - - /** - * Mode of operation, one of "event" or "func" - * - * @var string - */ - var $mode; - - /** - * Mapping from expat handler function to class method. - * - * @var array - */ - var $handler = array( - 'character_data_handler' => 'cdataHandler', - 'default_handler' => 'defaultHandler', - 'processing_instruction_handler' => 'piHandler', - 'unparsed_entity_decl_handler' => 'unparsedHandler', - 'notation_decl_handler' => 'notationHandler', - 'external_entity_ref_handler' => 'entityrefHandler' - ); - - /** - * source encoding - * - * @var string - */ - var $srcenc; - - /** - * target encoding - * - * @var string - */ - var $tgtenc; - - /** - * handler object - * - * @var object - */ - var $_handlerObj; - - // }}} - // {{{ constructor - - /** - * Creates an XML parser. - * - * This is needed for PHP4 compatibility, it will - * call the constructor, when a new instance is created. - * - * @param string $srcenc source charset encoding, use NULL (default) to use - * whatever the document specifies - * @param string $mode how this parser object should work, "event" for - * startelement/endelement-type events, "func" - * to have it call functions named after elements - * @param string $tgenc a valid target encoding - */ - function XML_Parser($srcenc = null, $mode = 'event', $tgtenc = null) - { - XML_Parser::__construct($srcenc, $mode, $tgtenc); - } - // }}} - - /** - * PHP5 constructor - * - * @param string $srcenc source charset encoding, use NULL (default) to use - * whatever the document specifies - * @param string $mode how this parser object should work, "event" for - * startelement/endelement-type events, "func" - * to have it call functions named after elements - * @param string $tgenc a valid target encoding - */ - function __construct($srcenc = null, $mode = 'event', $tgtenc = null) - { - $this->PEAR('XML_Parser_Error'); - - $this->mode = $mode; - $this->srcenc = $srcenc; - $this->tgtenc = $tgtenc; - } - // }}} - - /** - * Sets the mode of the parser. - * - * Possible modes are: - * - func - * - event - * - * You can set the mode using the second parameter - * in the constructor. - * - * This method is only needed, when switching to a new - * mode at a later point. - * - * @access public - * @param string mode, either 'func' or 'event' - * @return boolean|object true on success, PEAR_Error otherwise - */ - function setMode($mode) - { - if ($mode != 'func' && $mode != 'event') { - $this->raiseError('Unsupported mode given', XML_PARSER_ERROR_UNSUPPORTED_MODE); - } - - $this->mode = $mode; - return true; - } - - /** - * Sets the object, that will handle the XML events - * - * This allows you to create a handler object independent of the - * parser object that you are using and easily switch the underlying - * parser. - * - * If no object will be set, XML_Parser assumes that you - * extend this class and handle the events in $this. - * - * @access public - * @param object object to handle the events - * @return boolean will always return true - * @since v1.2.0beta3 - */ - function setHandlerObj(&$obj) - { - $this->_handlerObj = &$obj; - return true; - } - - /** - * Init the element handlers - * - * @access private - */ - function _initHandlers() - { - if (!is_resource($this->parser)) { - return false; - } - - if (!is_object($this->_handlerObj)) { - $this->_handlerObj = &$this; - } - switch ($this->mode) { - - case 'func': - xml_set_object($this->parser, $this->_handlerObj); - xml_set_element_handler($this->parser, array(&$this, 'funcStartHandler'), array(&$this, 'funcEndHandler')); - break; - - case 'event': - xml_set_object($this->parser, $this->_handlerObj); - xml_set_element_handler($this->parser, 'startHandler', 'endHandler'); - break; - default: - return $this->raiseError('Unsupported mode given', XML_PARSER_ERROR_UNSUPPORTED_MODE); - break; - } - - - /** - * set additional handlers for character data, entities, etc. - */ - foreach ($this->handler as $xml_func => $method) { - if (method_exists($this->_handlerObj, $method)) { - $xml_func = 'xml_set_' . $xml_func; - $xml_func($this->parser, $method); - } - } - } - - // {{{ _create() - - /** - * create the XML parser resource - * - * Has been moved from the constructor to avoid - * problems with object references. - * - * Furthermore it allows us returning an error - * if something fails. - * - * @access private - * @return boolean|object true on success, PEAR_Error otherwise - * - * @see xml_parser_create - */ - function _create() - { - if ($this->srcenc === null) { - $xp = @xml_parser_create(); - } else { - $xp = @xml_parser_create($this->srcenc); - } - if (is_resource($xp)) { - if ($this->tgtenc !== null) { - if (!@xml_parser_set_option($xp, XML_OPTION_TARGET_ENCODING, - $this->tgtenc)) { - return $this->raiseError('invalid target encoding', XML_PARSER_ERROR_INVALID_ENCODING); - } - } - $this->parser = $xp; - $result = $this->_initHandlers($this->mode); - if ($this->isError($result)) { - return $result; - } - xml_parser_set_option($xp, XML_OPTION_CASE_FOLDING, $this->folding); - - return true; - } - return $this->raiseError('Unable to create XML parser resource.', XML_PARSER_ERROR_NO_RESOURCE); - } - - // }}} - // {{{ reset() - - /** - * Reset the parser. - * - * This allows you to use one parser instance - * to parse multiple XML documents. - * - * @access public - * @return boolean|object true on success, PEAR_Error otherwise - */ - function reset() - { - $result = $this->_create(); - if ($this->isError( $result )) { - return $result; - } - return true; - } - - // }}} - // {{{ setInputFile() - - /** - * Sets the input xml file to be parsed - * - * @param string Filename (full path) - * @return resource fopen handle of the given file - * @throws XML_Parser_Error - * @see setInput(), setInputString(), parse() - * @access public - */ - function setInputFile($file) - { - /** - * check, if file is a remote file - */ - if (preg_match('/(http|ftp):///', substr($file, 0, 10))) { - if (!ini_get('allow_url_fopen')) { - return $this->raiseError('Remote files cannot be parsed, as safe mode is enabled.', XML_PARSER_ERROR_REMOTE); - } - } - - $fp = @fopen($file, 'rb'); - if (is_resource($fp)) { - $this->fp = $fp; - return $fp; - } - return $this->raiseError('File could not be opened.', XML_PARSER_ERROR_FILE_NOT_READABLE); - } - - // }}} - // {{{ setInputString() - - /** - * XML_Parser::setInputString() - * - * Sets the xml input from a string - * - * @param string $data a string containing the XML document - * @return null - **/ - function setInputString($data) - { - $this->fp = $data; - return null; - } - - // }}} - // {{{ setInput() - - /** - * Sets the file handle to use with parse(). - * - * You should use setInputFile() or setInputString() if you - * pass a string - * - * @param mixed $fp Can be either a resource returned from fopen(), - * a URL, a local filename or a string. - * @access public - * @see parse() - * @uses setInputString(), setInputFile() - */ - function setInput($fp) - { - if (is_resource($fp)) { - $this->fp = $fp; - return true; - } - // see if it's an absolute URL (has a scheme at the beginning) - elseif (preg_match('/[a-z]+:///', substr($fp, 0, 10))) { - return $this->setInputFile($fp); - } - // see if it's a local file - elseif (file_exists($fp)) { - return $this->setInputFile($fp); - } - // it must be a string - else { - $this->fp = $fp; - return true; - } - - return $this->raiseError('Illegal input format', XML_PARSER_ERROR_INVALID_INPUT); - } - - // }}} - // {{{ parse() - - /** - * Central parsing function. - * - * @return true|object PEAR error returns true on success, or a PEAR_Error otherwise - * @access public - */ - function parse() - { - /** - * reset the parser - */ - $result = $this->reset(); - if ($this->isError($result)) { - return $result; - } - // if $this->fp was fopened previously - if (is_resource($this->fp)) { - - while ($data = fread($this->fp, 4096)) { - if (!$this->_parseString($data, feof($this->fp))) { - $error = &$this->raiseError(); - $this->free(); - return $error; - } - } - // otherwise, $this->fp must be a string - } else { - if (!$this->_parseString($this->fp, true)) { - $error = &$this->raiseError(); - $this->free(); - return $error; - } - } - $this->free(); - - return true; - } - - /** - * XML_Parser::_parseString() - * - * @param string $data - * @param boolean $eof - * @return bool - * @access private - * @see parseString() - **/ - function _parseString($data, $eof = false) - { - return xml_parse($this->parser, $data, $eof); - } - - // }}} - // {{{ parseString() - - /** - * XML_Parser::parseString() - * - * Parses a string. - * - * @param string $data XML data - * @param boolean $eof If set and TRUE, data is the last piece of data sent in this parser - * @throws XML_Parser_Error - * @return Pear Error|true true on success or a PEAR Error - * @see _parseString() - */ - function parseString($data, $eof = false) - { - if (!isset($this->parser) || !is_resource($this->parser)) { - $this->reset(); - } - - if (!$this->_parseString($data, $eof)) { - $error = &$this->raiseError(); - $this->free(); - return $error; - } - - if ($eof === true) { - $this->free(); - } - return true; - } - - /** - * XML_Parser::free() - * - * Free the internal resources associated with the parser - * - * @return null - **/ - function free() - { - if (isset($this->parser) && is_resource($this->parser)) { - xml_parser_free($this->parser); - unset( $this->parser ); - } - if (isset($this->fp) && is_resource($this->fp)) { - fclose($this->fp); - } - unset($this->fp); - return null; - } - - /** - * XML_Parser::raiseError() - * - * Throws a XML_Parser_Error - * - * @param string $msg the error message - * @param integer $ecode the error message code - * @return XML_Parser_Error - **/ - function raiseError($msg = null, $ecode = 0) - { - $msg = !is_null($msg) ? $msg : $this->parser; - $err = &new XML_Parser_Error($msg, $ecode); - return parent::raiseError($err); - } - - // }}} - // {{{ funcStartHandler() - - function funcStartHandler($xp, $elem, $attribs) - { - $func = 'xmltag_' . $elem; - if (strchr($func, '.')) { - $func = str_replace('.', '_', $func); - } - if (method_exists($this->_handlerObj, $func)) { - call_user_func(array(&$this->_handlerObj, $func), $xp, $elem, $attribs); - } elseif (method_exists($this->_handlerObj, 'xmltag')) { - call_user_func(array(&$this->_handlerObj, 'xmltag'), $xp, $elem, $attribs); - } - } - - // }}} - // {{{ funcEndHandler() - - function funcEndHandler($xp, $elem) - { - $func = 'xmltag_' . $elem . '_'; - if (strchr($func, '.')) { - $func = str_replace('.', '_', $func); - } - if (method_exists($this->_handlerObj, $func)) { - call_user_func(array(&$this->_handlerObj, $func), $xp, $elem); - } elseif (method_exists($this->_handlerObj, 'xmltag_')) { - call_user_func(array(&$this->_handlerObj, 'xmltag_'), $xp, $elem); - } - } - - // }}} - // {{{ startHandler() - - /** - * - * @abstract - */ - function startHandler($xp, $elem, &$attribs) - { - return NULL; - } - - // }}} - // {{{ endHandler() - - /** - * - * @abstract - */ - function endHandler($xp, $elem) - { - return NULL; - } - - - // }}}me -} - -/** - * error class, replaces PEAR_Error - * - * An instance of this class will be returned - * if an error occurs inside XML_Parser. - * - * There are three advantages over using the standard PEAR_Error: - * - All messages will be prefixed - * - check for XML_Parser error, using is_a( $error, 'XML_Parser_Error' ) - * - messages can be generated from the xml_parser resource - * - * @package XML_Parser - * @access public - * @see PEAR_Error - */ -class XML_Parser_Error extends PEAR_Error -{ - // {{{ properties - - /** - * prefix for all messages - * - * @var string - */ - var $error_message_prefix = 'XML_Parser: '; - - // }}} - // {{{ constructor() - /** - * construct a new error instance - * - * You may either pass a message or an xml_parser resource as first - * parameter. If a resource has been passed, the last error that - * happened will be retrieved and returned. - * - * @access public - * @param string|resource message or parser resource - * @param integer error code - * @param integer error handling - * @param integer error level - */ - function XML_Parser_Error($msgorparser = 'unknown error', $code = 0, $mode = PEAR_ERROR_RETURN, $level = E_USER_NOTICE) - { - if (is_resource($msgorparser)) { - $code = xml_get_error_code($msgorparser); - $msgorparser = sprintf('%s at XML input line %d', - xml_error_string($code), - xml_get_current_line_number($msgorparser)); - } - $this->PEAR_Error($msgorparser, $code, $mode, $level); - } - // }}} -} -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/archive_tar/.gitignore b/gulliver/thirdparty/pear/archive_tar/.gitignore deleted file mode 100644 index 12262da27..000000000 --- a/gulliver/thirdparty/pear/archive_tar/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -# composer related -composer.lock -composer.phar -vendor -# IDE -.idea diff --git a/gulliver/thirdparty/pear/archive_tar/.travis.sh b/gulliver/thirdparty/pear/archive_tar/.travis.sh deleted file mode 100644 index 02c2010c5..000000000 --- a/gulliver/thirdparty/pear/archive_tar/.travis.sh +++ /dev/null @@ -1,5 +0,0 @@ -#!/bin/bash - -composer validate -cd tests -pear run-tests diff --git a/gulliver/thirdparty/pear/archive_tar/.travis.yml b/gulliver/thirdparty/pear/archive_tar/.travis.yml deleted file mode 100644 index 44b7111b9..000000000 --- a/gulliver/thirdparty/pear/archive_tar/.travis.yml +++ /dev/null @@ -1,15 +0,0 @@ -sudo: false -language: php -php: - - 5.2 - - 5.3 - - 5.4 - - 5.5 - - 5.6 - - 7 - - hhvm -matrix: - fast_finish: true - allow_failures: - - php: hhvm -script: ./.travis.sh diff --git a/gulliver/thirdparty/pear/archive_tar/Archive/Tar.php b/gulliver/thirdparty/pear/archive_tar/Archive/Tar.php deleted file mode 100644 index 0bd1c6caa..000000000 --- a/gulliver/thirdparty/pear/archive_tar/Archive/Tar.php +++ /dev/null @@ -1,2421 +0,0 @@ - - * 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. - * - * 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 File_Formats - * @package Archive_Tar - * @author Vincent Blavet - * @copyright 1997-2010 The Authors - * @license http://www.opensource.org/licenses/bsd-license.php New BSD License - * @version CVS: $Id$ - * @link http://pear.php.net/package/Archive_Tar - */ - -// If the PEAR class cannot be loaded via the autoloader, -// then try to require_once it from the PHP include path. -if (!class_exists('PEAR')) { - require_once 'PEAR.php'; -} - -define('ARCHIVE_TAR_ATT_SEPARATOR', 90001); -define('ARCHIVE_TAR_END_BLOCK', pack("a512", '')); - -if (!function_exists('gzopen') && function_exists('gzopen64')) { - function gzopen($filename, $mode, $use_include_path = 0) - { - return gzopen64($filename, $mode, $use_include_path); - } -} - -if (!function_exists('gztell') && function_exists('gztell64')) { - function gztell($zp) - { - return gztell64($zp); - } -} - -if (!function_exists('gzseek') && function_exists('gzseek64')) { - function gzseek($zp, $offset, $whence = SEEK_SET) - { - return gzseek64($zp, $offset, $whence); - } -} - -/** - * Creates a (compressed) Tar archive - * - * @package Archive_Tar - * @author Vincent Blavet - * @license http://www.opensource.org/licenses/bsd-license.php New BSD License - * @version $Revision$ - */ -class Archive_Tar extends PEAR -{ - /** - * @var string Name of the Tar - */ - public $_tarname = ''; - - /** - * @var boolean if true, the Tar file will be gzipped - */ - public $_compress = false; - - /** - * @var string Type of compression : 'none', 'gz', 'bz2' or 'lzma2' - */ - public $_compress_type = 'none'; - - /** - * @var string Explode separator - */ - public $_separator = ' '; - - /** - * @var file descriptor - */ - public $_file = 0; - - /** - * @var string Local Tar name of a remote Tar (http:// or ftp://) - */ - public $_temp_tarname = ''; - - /** - * @var string regular expression for ignoring files or directories - */ - public $_ignore_regexp = ''; - - /** - * @var object PEAR_Error object - */ - public $error_object = null; - - /** - * Format for data extraction - * - * @var string - */ - public $_fmt =''; - /** - * Archive_Tar Class constructor. This flavour of the constructor only - * declare a new Archive_Tar object, identifying it by the name of the - * tar file. - * If the compress argument is set the tar will be read or created as a - * gzip or bz2 compressed TAR file. - * - * @param string $p_tarname The name of the tar archive to create - * @param string $p_compress can be null, 'gz', 'bz2' or 'lzma2'. This - * parameter indicates if gzip, bz2 or lzma2 compression - * is required. For compatibility reason the - * boolean value 'true' means 'gz'. - * - * @return bool - */ - public function __construct($p_tarname, $p_compress = null) - { - parent::__construct(); - - $this->_compress = false; - $this->_compress_type = 'none'; - if (($p_compress === null) || ($p_compress == '')) { - if (@file_exists($p_tarname)) { - if ($fp = @fopen($p_tarname, "rb")) { - // look for gzip magic cookie - $data = fread($fp, 2); - fclose($fp); - if ($data == "\37\213") { - $this->_compress = true; - $this->_compress_type = 'gz'; - // No sure it's enought for a magic code .... - } elseif ($data == "BZ") { - $this->_compress = true; - $this->_compress_type = 'bz2'; - } elseif (file_get_contents($p_tarname, false, null, 1, 4) == '7zXZ') { - $this->_compress = true; - $this->_compress_type = 'lzma2'; - } - } - } else { - // probably a remote file or some file accessible - // through a stream interface - if (substr($p_tarname, -2) == 'gz') { - $this->_compress = true; - $this->_compress_type = 'gz'; - } elseif ((substr($p_tarname, -3) == 'bz2') || - (substr($p_tarname, -2) == 'bz') - ) { - $this->_compress = true; - $this->_compress_type = 'bz2'; - } else { - if (substr($p_tarname, -2) == 'xz') { - $this->_compress = true; - $this->_compress_type = 'lzma2'; - } - } - } - } else { - if (($p_compress === true) || ($p_compress == 'gz')) { - $this->_compress = true; - $this->_compress_type = 'gz'; - } else { - if ($p_compress == 'bz2') { - $this->_compress = true; - $this->_compress_type = 'bz2'; - } else { - if ($p_compress == 'lzma2') { - $this->_compress = true; - $this->_compress_type = 'lzma2'; - } else { - $this->_error( - "Unsupported compression type '$p_compress'\n" . - "Supported types are 'gz', 'bz2' and 'lzma2'.\n" - ); - return false; - } - } - } - } - $this->_tarname = $p_tarname; - if ($this->_compress) { // assert zlib or bz2 or xz extension support - if ($this->_compress_type == 'gz') { - $extname = 'zlib'; - } else { - if ($this->_compress_type == 'bz2') { - $extname = 'bz2'; - } else { - if ($this->_compress_type == 'lzma2') { - $extname = 'xz'; - } - } - } - - if (!extension_loaded($extname)) { - PEAR::loadExtension($extname); - } - if (!extension_loaded($extname)) { - $this->_error( - "The extension '$extname' couldn't be found.\n" . - "Please make sure your version of PHP was built " . - "with '$extname' support.\n" - ); - return false; - } - } - - - if (version_compare(PHP_VERSION, "5.5.0-dev") < 0) { - $this->_fmt = "a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/" . - "a8checksum/a1typeflag/a100link/a6magic/a2version/" . - "a32uname/a32gname/a8devmajor/a8devminor/a131prefix"; - } else { - $this->_fmt = "Z100filename/Z8mode/Z8uid/Z8gid/Z12size/Z12mtime/" . - "Z8checksum/Z1typeflag/Z100link/Z6magic/Z2version/" . - "Z32uname/Z32gname/Z8devmajor/Z8devminor/Z131prefix"; - } - - - } - - public function __destruct() - { - $this->_close(); - // ----- Look for a local copy to delete - if ($this->_temp_tarname != '') { - @unlink($this->_temp_tarname); - } - } - - /** - * This method creates the archive file and add the files / directories - * that are listed in $p_filelist. - * If a file with the same name exist and is writable, it is replaced - * by the new tar. - * The method return false and a PEAR error text. - * The $p_filelist parameter can be an array of string, each string - * representing a filename or a directory name with their path if - * needed. It can also be a single string with names separated by a - * single blank. - * For each directory added in the archive, the files and - * sub-directories are also added. - * See also createModify() method for more details. - * - * @param array $p_filelist An array of filenames and directory names, or a - * single string with names separated by a single - * blank space. - * - * @return true on success, false on error. - * @see createModify() - */ - public function create($p_filelist) - { - return $this->createModify($p_filelist, '', ''); - } - - /** - * This method add the files / directories that are listed in $p_filelist in - * the archive. If the archive does not exist it is created. - * The method return false and a PEAR error text. - * The files and directories listed are only added at the end of the archive, - * even if a file with the same name is already archived. - * See also createModify() method for more details. - * - * @param array $p_filelist An array of filenames and directory names, or a - * single string with names separated by a single - * blank space. - * - * @return true on success, false on error. - * @see createModify() - * @access public - */ - public function add($p_filelist) - { - return $this->addModify($p_filelist, '', ''); - } - - /** - * @param string $p_path - * @param bool $p_preserve - * @return bool - */ - public function extract($p_path = '', $p_preserve = false) - { - return $this->extractModify($p_path, '', $p_preserve); - } - - /** - * @return array|int - */ - public function listContent() - { - $v_list_detail = array(); - - if ($this->_openRead()) { - if (!$this->_extractList('', $v_list_detail, "list", '', '')) { - unset($v_list_detail); - $v_list_detail = 0; - } - $this->_close(); - } - - return $v_list_detail; - } - - /** - * This method creates the archive file and add the files / directories - * that are listed in $p_filelist. - * If the file already exists and is writable, it is replaced by the - * new tar. It is a create and not an add. If the file exists and is - * read-only or is a directory it is not replaced. The method return - * false and a PEAR error text. - * The $p_filelist parameter can be an array of string, each string - * representing a filename or a directory name with their path if - * needed. It can also be a single string with names separated by a - * single blank. - * The path indicated in $p_remove_dir will be removed from the - * memorized path of each file / directory listed when this path - * exists. By default nothing is removed (empty path '') - * The path indicated in $p_add_dir will be added at the beginning of - * the memorized path of each file / directory listed. However it can - * be set to empty ''. The adding of a path is done after the removing - * of path. - * The path add/remove ability enables the user to prepare an archive - * for extraction in a different path than the origin files are. - * See also addModify() method for file adding properties. - * - * @param array $p_filelist An array of filenames and directory names, - * or a single string with names separated by - * a single blank space. - * @param string $p_add_dir A string which contains a path to be added - * to the memorized path of each element in - * the list. - * @param string $p_remove_dir A string which contains a path to be - * removed from the memorized path of each - * element in the list, when relevant. - * - * @return boolean true on success, false on error. - * @see addModify() - */ - public function createModify($p_filelist, $p_add_dir, $p_remove_dir = '') - { - $v_result = true; - - if (!$this->_openWrite()) { - return false; - } - - if ($p_filelist != '') { - if (is_array($p_filelist)) { - $v_list = $p_filelist; - } elseif (is_string($p_filelist)) { - $v_list = explode($this->_separator, $p_filelist); - } else { - $this->_cleanFile(); - $this->_error('Invalid file list'); - return false; - } - - $v_result = $this->_addList($v_list, $p_add_dir, $p_remove_dir); - } - - if ($v_result) { - $this->_writeFooter(); - $this->_close(); - } else { - $this->_cleanFile(); - } - - return $v_result; - } - - /** - * This method add the files / directories listed in $p_filelist at the - * end of the existing archive. If the archive does not yet exists it - * is created. - * The $p_filelist parameter can be an array of string, each string - * representing a filename or a directory name with their path if - * needed. It can also be a single string with names separated by a - * single blank. - * The path indicated in $p_remove_dir will be removed from the - * memorized path of each file / directory listed when this path - * exists. By default nothing is removed (empty path '') - * The path indicated in $p_add_dir will be added at the beginning of - * the memorized path of each file / directory listed. However it can - * be set to empty ''. The adding of a path is done after the removing - * of path. - * The path add/remove ability enables the user to prepare an archive - * for extraction in a different path than the origin files are. - * If a file/dir is already in the archive it will only be added at the - * end of the archive. There is no update of the existing archived - * file/dir. However while extracting the archive, the last file will - * replace the first one. This results in a none optimization of the - * archive size. - * If a file/dir does not exist the file/dir is ignored. However an - * error text is send to PEAR error. - * If a file/dir is not readable the file/dir is ignored. However an - * error text is send to PEAR error. - * - * @param array $p_filelist An array of filenames and directory - * names, or a single string with names - * separated by a single blank space. - * @param string $p_add_dir A string which contains a path to be - * added to the memorized path of each - * element in the list. - * @param string $p_remove_dir A string which contains a path to be - * removed from the memorized path of - * each element in the list, when - * relevant. - * - * @return true on success, false on error. - */ - public function addModify($p_filelist, $p_add_dir, $p_remove_dir = '') - { - $v_result = true; - - if (!$this->_isArchive()) { - $v_result = $this->createModify( - $p_filelist, - $p_add_dir, - $p_remove_dir - ); - } else { - if (is_array($p_filelist)) { - $v_list = $p_filelist; - } elseif (is_string($p_filelist)) { - $v_list = explode($this->_separator, $p_filelist); - } else { - $this->_error('Invalid file list'); - return false; - } - - $v_result = $this->_append($v_list, $p_add_dir, $p_remove_dir); - } - - return $v_result; - } - - /** - * This method add a single string as a file at the - * end of the existing archive. If the archive does not yet exists it - * is created. - * - * @param string $p_filename A string which contains the full - * filename path that will be associated - * with the string. - * @param string $p_string The content of the file added in - * the archive. - * @param bool|int $p_datetime A custom date/time (unix timestamp) - * for the file (optional). - * @param array $p_params An array of optional params: - * stamp => the datetime (replaces - * datetime above if it exists) - * mode => the permissions on the - * file (600 by default) - * type => is this a link? See the - * tar specification for details. - * (default = regular file) - * uid => the user ID of the file - * (default = 0 = root) - * gid => the group ID of the file - * (default = 0 = root) - * - * @return true on success, false on error. - */ - public function addString($p_filename, $p_string, $p_datetime = false, $p_params = array()) - { - $p_stamp = @$p_params["stamp"] ? $p_params["stamp"] : ($p_datetime ? $p_datetime : time()); - $p_mode = @$p_params["mode"] ? $p_params["mode"] : 0600; - $p_type = @$p_params["type"] ? $p_params["type"] : ""; - $p_uid = @$p_params["uid"] ? $p_params["uid"] : ""; - $p_gid = @$p_params["gid"] ? $p_params["gid"] : ""; - $v_result = true; - - if (!$this->_isArchive()) { - if (!$this->_openWrite()) { - return false; - } - $this->_close(); - } - - if (!$this->_openAppend()) { - return false; - } - - // Need to check the get back to the temporary file ? .... - $v_result = $this->_addString($p_filename, $p_string, $p_datetime, $p_params); - - $this->_writeFooter(); - - $this->_close(); - - return $v_result; - } - - /** - * This method extract all the content of the archive in the directory - * indicated by $p_path. When relevant the memorized path of the - * files/dir can be modified by removing the $p_remove_path path at the - * beginning of the file/dir path. - * While extracting a file, if the directory path does not exists it is - * created. - * While extracting a file, if the file already exists it is replaced - * without looking for last modification date. - * While extracting a file, if the file already exists and is write - * protected, the extraction is aborted. - * While extracting a file, if a directory with the same name already - * exists, the extraction is aborted. - * While extracting a directory, if a file with the same name already - * exists, the extraction is aborted. - * While extracting a file/directory if the destination directory exist - * and is write protected, or does not exist but can not be created, - * the extraction is aborted. - * If after extraction an extracted file does not show the correct - * stored file size, the extraction is aborted. - * When the extraction is aborted, a PEAR error text is set and false - * is returned. However the result can be a partial extraction that may - * need to be manually cleaned. - * - * @param string $p_path The path of the directory where the - * files/dir need to by extracted. - * @param string $p_remove_path Part of the memorized path that can be - * removed if present at the beginning of - * the file/dir path. - * @param boolean $p_preserve Preserve user/group ownership of files - * - * @return boolean true on success, false on error. - * @see extractList() - */ - public function extractModify($p_path, $p_remove_path, $p_preserve = false) - { - $v_result = true; - $v_list_detail = array(); - - if ($v_result = $this->_openRead()) { - $v_result = $this->_extractList( - $p_path, - $v_list_detail, - "complete", - 0, - $p_remove_path, - $p_preserve - ); - $this->_close(); - } - - return $v_result; - } - - /** - * This method extract from the archive one file identified by $p_filename. - * The return value is a string with the file content, or NULL on error. - * - * @param string $p_filename The path of the file to extract in a string. - * - * @return a string with the file content or NULL. - */ - public function extractInString($p_filename) - { - if ($this->_openRead()) { - $v_result = $this->_extractInString($p_filename); - $this->_close(); - } else { - $v_result = null; - } - - return $v_result; - } - - /** - * This method extract from the archive only the files indicated in the - * $p_filelist. These files are extracted in the current directory or - * in the directory indicated by the optional $p_path parameter. - * If indicated the $p_remove_path can be used in the same way as it is - * used in extractModify() method. - * - * @param array $p_filelist An array of filenames and directory names, - * or a single string with names separated - * by a single blank space. - * @param string $p_path The path of the directory where the - * files/dir need to by extracted. - * @param string $p_remove_path Part of the memorized path that can be - * removed if present at the beginning of - * the file/dir path. - * @param boolean $p_preserve Preserve user/group ownership of files - * - * @return true on success, false on error. - * @see extractModify() - */ - public function extractList($p_filelist, $p_path = '', $p_remove_path = '', $p_preserve = false) - { - $v_result = true; - $v_list_detail = array(); - - if (is_array($p_filelist)) { - $v_list = $p_filelist; - } elseif (is_string($p_filelist)) { - $v_list = explode($this->_separator, $p_filelist); - } else { - $this->_error('Invalid string list'); - return false; - } - - if ($v_result = $this->_openRead()) { - $v_result = $this->_extractList( - $p_path, - $v_list_detail, - "partial", - $v_list, - $p_remove_path, - $p_preserve - ); - $this->_close(); - } - - return $v_result; - } - - /** - * This method set specific attributes of the archive. It uses a variable - * list of parameters, in the format attribute code + attribute values : - * $arch->setAttribute(ARCHIVE_TAR_ATT_SEPARATOR, ','); - * - * @return true on success, false on error. - */ - public function setAttribute() - { - $v_result = true; - - // ----- Get the number of variable list of arguments - if (($v_size = func_num_args()) == 0) { - return true; - } - - // ----- Get the arguments - $v_att_list = func_get_args(); - - // ----- Read the attributes - $i = 0; - while ($i < $v_size) { - - // ----- Look for next option - switch ($v_att_list[$i]) { - // ----- Look for options that request a string value - case ARCHIVE_TAR_ATT_SEPARATOR : - // ----- Check the number of parameters - if (($i + 1) >= $v_size) { - $this->_error( - 'Invalid number of parameters for ' - . 'attribute ARCHIVE_TAR_ATT_SEPARATOR' - ); - return false; - } - - // ----- Get the value - $this->_separator = $v_att_list[$i + 1]; - $i++; - break; - - default : - $this->_error('Unknown attribute code ' . $v_att_list[$i] . ''); - return false; - } - - // ----- Next attribute - $i++; - } - - return $v_result; - } - - /** - * This method sets the regular expression for ignoring files and directories - * at import, for example: - * $arch->setIgnoreRegexp("#CVS|\.svn#"); - * - * @param string $regexp regular expression defining which files or directories to ignore - */ - public function setIgnoreRegexp($regexp) - { - $this->_ignore_regexp = $regexp; - } - - /** - * This method sets the regular expression for ignoring all files and directories - * matching the filenames in the array list at import, for example: - * $arch->setIgnoreList(array('CVS', '.svn', 'bin/tool')); - * - * @param array $list a list of file or directory names to ignore - * - * @access public - */ - public function setIgnoreList($list) - { - $regexp = str_replace(array('#', '.', '^', '$'), array('\#', '\.', '\^', '\$'), $list); - $regexp = '#/' . join('$|/', $list) . '#'; - $this->setIgnoreRegexp($regexp); - } - - /** - * @param string $p_message - */ - public function _error($p_message) - { - $this->error_object = $this->raiseError($p_message); - } - - /** - * @param string $p_message - */ - public function _warning($p_message) - { - $this->error_object = $this->raiseError($p_message); - } - - /** - * @param string $p_filename - * @return bool - */ - public function _isArchive($p_filename = null) - { - if ($p_filename == null) { - $p_filename = $this->_tarname; - } - clearstatcache(); - return @is_file($p_filename) && !@is_link($p_filename); - } - - /** - * @return bool - */ - public function _openWrite() - { - if ($this->_compress_type == 'gz' && function_exists('gzopen')) { - $this->_file = @gzopen($this->_tarname, "wb9"); - } else { - if ($this->_compress_type == 'bz2' && function_exists('bzopen')) { - $this->_file = @bzopen($this->_tarname, "w"); - } else { - if ($this->_compress_type == 'lzma2' && function_exists('xzopen')) { - $this->_file = @xzopen($this->_tarname, 'w'); - } else { - if ($this->_compress_type == 'none') { - $this->_file = @fopen($this->_tarname, "wb"); - } else { - $this->_error( - 'Unknown or missing compression type (' - . $this->_compress_type . ')' - ); - return false; - } - } - } - } - - if ($this->_file == 0) { - $this->_error( - 'Unable to open in write mode \'' - . $this->_tarname . '\'' - ); - return false; - } - - return true; - } - - /** - * @return bool - */ - public function _openRead() - { - if (strtolower(substr($this->_tarname, 0, 7)) == 'http://') { - - // ----- Look if a local copy need to be done - if ($this->_temp_tarname == '') { - $this->_temp_tarname = uniqid('tar') . '.tmp'; - if (!$v_file_from = @fopen($this->_tarname, 'rb')) { - $this->_error( - 'Unable to open in read mode \'' - . $this->_tarname . '\'' - ); - $this->_temp_tarname = ''; - return false; - } - if (!$v_file_to = @fopen($this->_temp_tarname, 'wb')) { - $this->_error( - 'Unable to open in write mode \'' - . $this->_temp_tarname . '\'' - ); - $this->_temp_tarname = ''; - return false; - } - while ($v_data = @fread($v_file_from, 1024)) { - @fwrite($v_file_to, $v_data); - } - @fclose($v_file_from); - @fclose($v_file_to); - } - - // ----- File to open if the local copy - $v_filename = $this->_temp_tarname; - } else { - // ----- File to open if the normal Tar file - - $v_filename = $this->_tarname; - } - - if ($this->_compress_type == 'gz' && function_exists('gzopen')) { - $this->_file = @gzopen($v_filename, "rb"); - } else { - if ($this->_compress_type == 'bz2' && function_exists('bzopen')) { - $this->_file = @bzopen($v_filename, "r"); - } else { - if ($this->_compress_type == 'lzma2' && function_exists('xzopen')) { - $this->_file = @xzopen($v_filename, "r"); - } else { - if ($this->_compress_type == 'none') { - $this->_file = @fopen($v_filename, "rb"); - } else { - $this->_error( - 'Unknown or missing compression type (' - . $this->_compress_type . ')' - ); - return false; - } - } - } - } - - if ($this->_file == 0) { - $this->_error('Unable to open in read mode \'' . $v_filename . '\''); - return false; - } - - return true; - } - - /** - * @return bool - */ - public function _openReadWrite() - { - if ($this->_compress_type == 'gz') { - $this->_file = @gzopen($this->_tarname, "r+b"); - } else { - if ($this->_compress_type == 'bz2') { - $this->_error( - 'Unable to open bz2 in read/write mode \'' - . $this->_tarname . '\' (limitation of bz2 extension)' - ); - return false; - } else { - if ($this->_compress_type == 'lzma2') { - $this->_error( - 'Unable to open lzma2 in read/write mode \'' - . $this->_tarname . '\' (limitation of lzma2 extension)' - ); - return false; - } else { - if ($this->_compress_type == 'none') { - $this->_file = @fopen($this->_tarname, "r+b"); - } else { - $this->_error( - 'Unknown or missing compression type (' - . $this->_compress_type . ')' - ); - return false; - } - } - } - } - - if ($this->_file == 0) { - $this->_error( - 'Unable to open in read/write mode \'' - . $this->_tarname . '\'' - ); - return false; - } - - return true; - } - - /** - * @return bool - */ - public function _close() - { - //if (isset($this->_file)) { - if (is_resource($this->_file)) { - if ($this->_compress_type == 'gz') { - @gzclose($this->_file); - } else { - if ($this->_compress_type == 'bz2') { - @bzclose($this->_file); - } else { - if ($this->_compress_type == 'lzma2') { - @xzclose($this->_file); - } else { - if ($this->_compress_type == 'none') { - @fclose($this->_file); - } else { - $this->_error( - 'Unknown or missing compression type (' - . $this->_compress_type . ')' - ); - } - } - } - } - - $this->_file = 0; - } - - // ----- Look if a local copy need to be erase - // Note that it might be interesting to keep the url for a time : ToDo - if ($this->_temp_tarname != '') { - @unlink($this->_temp_tarname); - $this->_temp_tarname = ''; - } - - return true; - } - - /** - * @return bool - */ - public function _cleanFile() - { - $this->_close(); - - // ----- Look for a local copy - if ($this->_temp_tarname != '') { - // ----- Remove the local copy but not the remote tarname - @unlink($this->_temp_tarname); - $this->_temp_tarname = ''; - } else { - // ----- Remove the local tarname file - @unlink($this->_tarname); - } - $this->_tarname = ''; - - return true; - } - - /** - * @param mixed $p_binary_data - * @param integer $p_len - * @return bool - */ - public function _writeBlock($p_binary_data, $p_len = null) - { - if (is_resource($this->_file)) { - if ($p_len === null) { - if ($this->_compress_type == 'gz') { - @gzputs($this->_file, $p_binary_data); - } else { - if ($this->_compress_type == 'bz2') { - @bzwrite($this->_file, $p_binary_data); - } else { - if ($this->_compress_type == 'lzma2') { - @xzwrite($this->_file, $p_binary_data); - } else { - if ($this->_compress_type == 'none') { - @fputs($this->_file, $p_binary_data); - } else { - $this->_error( - 'Unknown or missing compression type (' - . $this->_compress_type . ')' - ); - } - } - } - } - } else { - if ($this->_compress_type == 'gz') { - @gzputs($this->_file, $p_binary_data, $p_len); - } else { - if ($this->_compress_type == 'bz2') { - @bzwrite($this->_file, $p_binary_data, $p_len); - } else { - if ($this->_compress_type == 'lzma2') { - @xzwrite($this->_file, $p_binary_data, $p_len); - } else { - if ($this->_compress_type == 'none') { - @fputs($this->_file, $p_binary_data, $p_len); - } else { - $this->_error( - 'Unknown or missing compression type (' - . $this->_compress_type . ')' - ); - } - } - } - } - } - } - return true; - } - - /** - * @return null|string - */ - public function _readBlock() - { - $v_block = null; - if (is_resource($this->_file)) { - if ($this->_compress_type == 'gz') { - $v_block = @gzread($this->_file, 512); - } else { - if ($this->_compress_type == 'bz2') { - $v_block = @bzread($this->_file, 512); - } else { - if ($this->_compress_type == 'lzma2') { - $v_block = @xzread($this->_file, 512); - } else { - if ($this->_compress_type == 'none') { - $v_block = @fread($this->_file, 512); - } else { - $this->_error( - 'Unknown or missing compression type (' - . $this->_compress_type . ')' - ); - } - } - } - } - } - return $v_block; - } - - /** - * @param null $p_len - * @return bool - */ - public function _jumpBlock($p_len = null) - { - if (is_resource($this->_file)) { - if ($p_len === null) { - $p_len = 1; - } - - if ($this->_compress_type == 'gz') { - @gzseek($this->_file, gztell($this->_file) + ($p_len * 512)); - } else { - if ($this->_compress_type == 'bz2') { - // ----- Replace missing bztell() and bzseek() - for ($i = 0; $i < $p_len; $i++) { - $this->_readBlock(); - } - } else { - if ($this->_compress_type == 'lzma2') { - // ----- Replace missing xztell() and xzseek() - for ($i = 0; $i < $p_len; $i++) { - $this->_readBlock(); - } - } else { - if ($this->_compress_type == 'none') { - @fseek($this->_file, $p_len * 512, SEEK_CUR); - } else { - $this->_error( - 'Unknown or missing compression type (' - . $this->_compress_type . ')' - ); - } - } - } - } - } - return true; - } - - /** - * @return bool - */ - public function _writeFooter() - { - if (is_resource($this->_file)) { - // ----- Write the last 0 filled block for end of archive - $v_binary_data = pack('a1024', ''); - $this->_writeBlock($v_binary_data); - } - return true; - } - - /** - * @param array $p_list - * @param string $p_add_dir - * @param string $p_remove_dir - * @return bool - */ - public function _addList($p_list, $p_add_dir, $p_remove_dir) - { - $v_result = true; - $v_header = array(); - - // ----- Remove potential windows directory separator - $p_add_dir = $this->_translateWinPath($p_add_dir); - $p_remove_dir = $this->_translateWinPath($p_remove_dir, false); - - if (!$this->_file) { - $this->_error('Invalid file descriptor'); - return false; - } - - if (sizeof($p_list) == 0) { - return true; - } - - foreach ($p_list as $v_filename) { - if (!$v_result) { - break; - } - - // ----- Skip the current tar name - if ($v_filename == $this->_tarname) { - continue; - } - - if ($v_filename == '') { - continue; - } - - // ----- ignore files and directories matching the ignore regular expression - if ($this->_ignore_regexp && preg_match($this->_ignore_regexp, '/' . $v_filename)) { - $this->_warning("File '$v_filename' ignored"); - continue; - } - - if (!file_exists($v_filename) && !is_link($v_filename)) { - $this->_warning("File '$v_filename' does not exist"); - continue; - } - - // ----- Add the file or directory header - if (!$this->_addFile($v_filename, $v_header, $p_add_dir, $p_remove_dir)) { - return false; - } - - if (@is_dir($v_filename) && !@is_link($v_filename)) { - if (!($p_hdir = opendir($v_filename))) { - $this->_warning("Directory '$v_filename' can not be read"); - continue; - } - while (false !== ($p_hitem = readdir($p_hdir))) { - if (($p_hitem != '.') && ($p_hitem != '..')) { - if ($v_filename != ".") { - $p_temp_list[0] = $v_filename . '/' . $p_hitem; - } else { - $p_temp_list[0] = $p_hitem; - } - - $v_result = $this->_addList( - $p_temp_list, - $p_add_dir, - $p_remove_dir - ); - } - } - - unset($p_temp_list); - unset($p_hdir); - unset($p_hitem); - } - } - - return $v_result; - } - - /** - * @param string $p_filename - * @param mixed $p_header - * @param string $p_add_dir - * @param string $p_remove_dir - * @param null $v_stored_filename - * @return bool - */ - public function _addFile($p_filename, &$p_header, $p_add_dir, $p_remove_dir, $v_stored_filename = null) - { - if (!$this->_file) { - $this->_error('Invalid file descriptor'); - return false; - } - - if ($p_filename == '') { - $this->_error('Invalid file name'); - return false; - } - - if (is_null($v_stored_filename)) { - // ----- Calculate the stored filename - $p_filename = $this->_translateWinPath($p_filename, false); - $v_stored_filename = $p_filename; - - if (strcmp($p_filename, $p_remove_dir) == 0) { - return true; - } - - if ($p_remove_dir != '') { - if (substr($p_remove_dir, -1) != '/') { - $p_remove_dir .= '/'; - } - - if (substr($p_filename, 0, strlen($p_remove_dir)) == $p_remove_dir) { - $v_stored_filename = substr($p_filename, strlen($p_remove_dir)); - } - } - - $v_stored_filename = $this->_translateWinPath($v_stored_filename); - if ($p_add_dir != '') { - if (substr($p_add_dir, -1) == '/') { - $v_stored_filename = $p_add_dir . $v_stored_filename; - } else { - $v_stored_filename = $p_add_dir . '/' . $v_stored_filename; - } - } - - $v_stored_filename = $this->_pathReduction($v_stored_filename); - } - - if ($this->_isArchive($p_filename)) { - if (($v_file = @fopen($p_filename, "rb")) == 0) { - $this->_warning( - "Unable to open file '" . $p_filename - . "' in binary read mode" - ); - return true; - } - - if (!$this->_writeHeader($p_filename, $v_stored_filename)) { - return false; - } - - while (($v_buffer = fread($v_file, 512)) != '') { - $v_binary_data = pack("a512", "$v_buffer"); - $this->_writeBlock($v_binary_data); - } - - fclose($v_file); - } else { - // ----- Only header for dir - if (!$this->_writeHeader($p_filename, $v_stored_filename)) { - return false; - } - } - - return true; - } - - /** - * @param string $p_filename - * @param string $p_string - * @param bool $p_datetime - * @param array $p_params - * @return bool - */ - public function _addString($p_filename, $p_string, $p_datetime = false, $p_params = array()) - { - $p_stamp = @$p_params["stamp"] ? $p_params["stamp"] : ($p_datetime ? $p_datetime : time()); - $p_mode = @$p_params["mode"] ? $p_params["mode"] : 0600; - $p_type = @$p_params["type"] ? $p_params["type"] : ""; - $p_uid = @$p_params["uid"] ? $p_params["uid"] : 0; - $p_gid = @$p_params["gid"] ? $p_params["gid"] : 0; - if (!$this->_file) { - $this->_error('Invalid file descriptor'); - return false; - } - - if ($p_filename == '') { - $this->_error('Invalid file name'); - return false; - } - - // ----- Calculate the stored filename - $p_filename = $this->_translateWinPath($p_filename, false); - - // ----- If datetime is not specified, set current time - if ($p_datetime === false) { - $p_datetime = time(); - } - - if (!$this->_writeHeaderBlock( - $p_filename, - strlen($p_string), - $p_stamp, - $p_mode, - $p_type, - $p_uid, - $p_gid - ) - ) { - return false; - } - - $i = 0; - while (($v_buffer = substr($p_string, (($i++) * 512), 512)) != '') { - $v_binary_data = pack("a512", $v_buffer); - $this->_writeBlock($v_binary_data); - } - - return true; - } - - /** - * @param string $p_filename - * @param string $p_stored_filename - * @return bool - */ - public function _writeHeader($p_filename, $p_stored_filename) - { - if ($p_stored_filename == '') { - $p_stored_filename = $p_filename; - } - $v_reduce_filename = $this->_pathReduction($p_stored_filename); - - if (strlen($v_reduce_filename) > 99) { - if (!$this->_writeLongHeader($v_reduce_filename)) { - return false; - } - } - - $v_info = lstat($p_filename); - $v_uid = sprintf("%07s", DecOct($v_info[4])); - $v_gid = sprintf("%07s", DecOct($v_info[5])); - $v_perms = sprintf("%07s", DecOct($v_info['mode'] & 000777)); - - $v_mtime = sprintf("%011s", DecOct($v_info['mtime'])); - - $v_linkname = ''; - - if (@is_link($p_filename)) { - $v_typeflag = '2'; - $v_linkname = readlink($p_filename); - $v_size = sprintf("%011s", DecOct(0)); - } elseif (@is_dir($p_filename)) { - $v_typeflag = "5"; - $v_size = sprintf("%011s", DecOct(0)); - } else { - $v_typeflag = '0'; - clearstatcache(); - $v_size = sprintf("%011s", DecOct($v_info['size'])); - } - - $v_magic = 'ustar '; - - $v_version = ' '; - - if (function_exists('posix_getpwuid')) { - $userinfo = posix_getpwuid($v_info[4]); - $groupinfo = posix_getgrgid($v_info[5]); - - $v_uname = $userinfo['name']; - $v_gname = $groupinfo['name']; - } else { - $v_uname = ''; - $v_gname = ''; - } - - $v_devmajor = ''; - - $v_devminor = ''; - - $v_prefix = ''; - - $v_binary_data_first = pack( - "a100a8a8a8a12a12", - $v_reduce_filename, - $v_perms, - $v_uid, - $v_gid, - $v_size, - $v_mtime - ); - $v_binary_data_last = pack( - "a1a100a6a2a32a32a8a8a155a12", - $v_typeflag, - $v_linkname, - $v_magic, - $v_version, - $v_uname, - $v_gname, - $v_devmajor, - $v_devminor, - $v_prefix, - '' - ); - - // ----- Calculate the checksum - $v_checksum = 0; - // ..... First part of the header - for ($i = 0; $i < 148; $i++) { - $v_checksum += ord(substr($v_binary_data_first, $i, 1)); - } - // ..... Ignore the checksum value and replace it by ' ' (space) - for ($i = 148; $i < 156; $i++) { - $v_checksum += ord(' '); - } - // ..... Last part of the header - for ($i = 156, $j = 0; $i < 512; $i++, $j++) { - $v_checksum += ord(substr($v_binary_data_last, $j, 1)); - } - - // ----- Write the first 148 bytes of the header in the archive - $this->_writeBlock($v_binary_data_first, 148); - - // ----- Write the calculated checksum - $v_checksum = sprintf("%06s ", DecOct($v_checksum)); - $v_binary_data = pack("a8", $v_checksum); - $this->_writeBlock($v_binary_data, 8); - - // ----- Write the last 356 bytes of the header in the archive - $this->_writeBlock($v_binary_data_last, 356); - - return true; - } - - /** - * @param string $p_filename - * @param int $p_size - * @param int $p_mtime - * @param int $p_perms - * @param string $p_type - * @param int $p_uid - * @param int $p_gid - * @return bool - */ - public function _writeHeaderBlock( - $p_filename, - $p_size, - $p_mtime = 0, - $p_perms = 0, - $p_type = '', - $p_uid = 0, - $p_gid = 0 - ) { - $p_filename = $this->_pathReduction($p_filename); - - if (strlen($p_filename) > 99) { - if (!$this->_writeLongHeader($p_filename)) { - return false; - } - } - - if ($p_type == "5") { - $v_size = sprintf("%011s", DecOct(0)); - } else { - $v_size = sprintf("%011s", DecOct($p_size)); - } - - $v_uid = sprintf("%07s", DecOct($p_uid)); - $v_gid = sprintf("%07s", DecOct($p_gid)); - $v_perms = sprintf("%07s", DecOct($p_perms & 000777)); - - $v_mtime = sprintf("%11s", DecOct($p_mtime)); - - $v_linkname = ''; - - $v_magic = 'ustar '; - - $v_version = ' '; - - if (function_exists('posix_getpwuid')) { - $userinfo = posix_getpwuid($p_uid); - $groupinfo = posix_getgrgid($p_gid); - - $v_uname = $userinfo['name']; - $v_gname = $groupinfo['name']; - } else { - $v_uname = ''; - $v_gname = ''; - } - - $v_devmajor = ''; - - $v_devminor = ''; - - $v_prefix = ''; - - $v_binary_data_first = pack( - "a100a8a8a8a12A12", - $p_filename, - $v_perms, - $v_uid, - $v_gid, - $v_size, - $v_mtime - ); - $v_binary_data_last = pack( - "a1a100a6a2a32a32a8a8a155a12", - $p_type, - $v_linkname, - $v_magic, - $v_version, - $v_uname, - $v_gname, - $v_devmajor, - $v_devminor, - $v_prefix, - '' - ); - - // ----- Calculate the checksum - $v_checksum = 0; - // ..... First part of the header - for ($i = 0; $i < 148; $i++) { - $v_checksum += ord(substr($v_binary_data_first, $i, 1)); - } - // ..... Ignore the checksum value and replace it by ' ' (space) - for ($i = 148; $i < 156; $i++) { - $v_checksum += ord(' '); - } - // ..... Last part of the header - for ($i = 156, $j = 0; $i < 512; $i++, $j++) { - $v_checksum += ord(substr($v_binary_data_last, $j, 1)); - } - - // ----- Write the first 148 bytes of the header in the archive - $this->_writeBlock($v_binary_data_first, 148); - - // ----- Write the calculated checksum - $v_checksum = sprintf("%06s ", DecOct($v_checksum)); - $v_binary_data = pack("a8", $v_checksum); - $this->_writeBlock($v_binary_data, 8); - - // ----- Write the last 356 bytes of the header in the archive - $this->_writeBlock($v_binary_data_last, 356); - - return true; - } - - /** - * @param string $p_filename - * @return bool - */ - public function _writeLongHeader($p_filename) - { - $v_size = sprintf("%11s ", DecOct(strlen($p_filename))); - - $v_typeflag = 'L'; - - $v_linkname = ''; - - $v_magic = ''; - - $v_version = ''; - - $v_uname = ''; - - $v_gname = ''; - - $v_devmajor = ''; - - $v_devminor = ''; - - $v_prefix = ''; - - $v_binary_data_first = pack( - "a100a8a8a8a12a12", - '././@LongLink', - 0, - 0, - 0, - $v_size, - 0 - ); - $v_binary_data_last = pack( - "a1a100a6a2a32a32a8a8a155a12", - $v_typeflag, - $v_linkname, - $v_magic, - $v_version, - $v_uname, - $v_gname, - $v_devmajor, - $v_devminor, - $v_prefix, - '' - ); - - // ----- Calculate the checksum - $v_checksum = 0; - // ..... First part of the header - for ($i = 0; $i < 148; $i++) { - $v_checksum += ord(substr($v_binary_data_first, $i, 1)); - } - // ..... Ignore the checksum value and replace it by ' ' (space) - for ($i = 148; $i < 156; $i++) { - $v_checksum += ord(' '); - } - // ..... Last part of the header - for ($i = 156, $j = 0; $i < 512; $i++, $j++) { - $v_checksum += ord(substr($v_binary_data_last, $j, 1)); - } - - // ----- Write the first 148 bytes of the header in the archive - $this->_writeBlock($v_binary_data_first, 148); - - // ----- Write the calculated checksum - $v_checksum = sprintf("%06s ", DecOct($v_checksum)); - $v_binary_data = pack("a8", $v_checksum); - $this->_writeBlock($v_binary_data, 8); - - // ----- Write the last 356 bytes of the header in the archive - $this->_writeBlock($v_binary_data_last, 356); - - // ----- Write the filename as content of the block - $i = 0; - while (($v_buffer = substr($p_filename, (($i++) * 512), 512)) != '') { - $v_binary_data = pack("a512", "$v_buffer"); - $this->_writeBlock($v_binary_data); - } - - return true; - } - - /** - * @param mixed $v_binary_data - * @param mixed $v_header - * @return bool - */ - public function _readHeader($v_binary_data, &$v_header) - { - if (strlen($v_binary_data) == 0) { - $v_header['filename'] = ''; - return true; - } - - if (strlen($v_binary_data) != 512) { - $v_header['filename'] = ''; - $this->_error('Invalid block size : ' . strlen($v_binary_data)); - return false; - } - - if (!is_array($v_header)) { - $v_header = array(); - } - // ----- Calculate the checksum - $v_checksum = 0; - // ..... First part of the header - $v_binary_split = str_split($v_binary_data); - $v_checksum += array_sum(array_map('ord', array_slice($v_binary_split, 0, 148))); - $v_checksum += array_sum(array_map('ord', array(' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',))); - $v_checksum += array_sum(array_map('ord', array_slice($v_binary_split, 156, 512))); - - - $v_data = unpack($this->_fmt, $v_binary_data); - - if (strlen($v_data["prefix"]) > 0) { - $v_data["filename"] = "$v_data[prefix]/$v_data[filename]"; - } - - // ----- Extract the checksum - $v_header['checksum'] = OctDec(trim($v_data['checksum'])); - if ($v_header['checksum'] != $v_checksum) { - $v_header['filename'] = ''; - - // ----- Look for last block (empty block) - if (($v_checksum == 256) && ($v_header['checksum'] == 0)) { - return true; - } - - $this->_error( - 'Invalid checksum for file "' . $v_data['filename'] - . '" : ' . $v_checksum . ' calculated, ' - . $v_header['checksum'] . ' expected' - ); - return false; - } - - // ----- Extract the properties - $v_header['filename'] = rtrim($v_data['filename'], "\0"); - if ($this->_maliciousFilename($v_header['filename'])) { - $this->_error( - 'Malicious .tar detected, file "' . $v_header['filename'] . - '" will not install in desired directory tree' - ); - return false; - } - $v_header['mode'] = OctDec(trim($v_data['mode'])); - $v_header['uid'] = OctDec(trim($v_data['uid'])); - $v_header['gid'] = OctDec(trim($v_data['gid'])); - $v_header['size'] = $this->_tarRecToSize($v_data['size']); - $v_header['mtime'] = OctDec(trim($v_data['mtime'])); - if (($v_header['typeflag'] = $v_data['typeflag']) == "5") { - $v_header['size'] = 0; - } - $v_header['link'] = trim($v_data['link']); - /* ----- All these fields are removed form the header because - they do not carry interesting info - $v_header[magic] = trim($v_data[magic]); - $v_header[version] = trim($v_data[version]); - $v_header[uname] = trim($v_data[uname]); - $v_header[gname] = trim($v_data[gname]); - $v_header[devmajor] = trim($v_data[devmajor]); - $v_header[devminor] = trim($v_data[devminor]); - */ - - return true; - } - - /** - * Convert Tar record size to actual size - * - * @param string $tar_size - * @return size of tar record in bytes - */ - private function _tarRecToSize($tar_size) - { - /* - * First byte of size has a special meaning if bit 7 is set. - * - * Bit 7 indicates base-256 encoding if set. - * Bit 6 is the sign bit. - * Bits 5:0 are most significant value bits. - */ - $ch = ord($tar_size[0]); - if ($ch & 0x80) { - // Full 12-bytes record is required. - $rec_str = $tar_size . "\x00"; - - $size = ($ch & 0x40) ? -1 : 0; - $size = ($size << 6) | ($ch & 0x3f); - - for ($num_ch = 1; $num_ch < 12; ++$num_ch) { - $size = ($size * 256) + ord($rec_str[$num_ch]); - } - - return $size; - - } else { - return OctDec(trim($tar_size)); - } - } - - /** - * Detect and report a malicious file name - * - * @param string $file - * - * @return bool - */ - private function _maliciousFilename($file) - { - if (strpos($file, '/../') !== false) { - return true; - } - if (strpos($file, '../') === 0) { - return true; - } - return false; - } - - /** - * @param $v_header - * @return bool - */ - public function _readLongHeader(&$v_header) - { - $v_filename = ''; - $v_filesize = $v_header['size']; - $n = floor($v_header['size'] / 512); - for ($i = 0; $i < $n; $i++) { - $v_content = $this->_readBlock(); - $v_filename .= $v_content; - } - if (($v_header['size'] % 512) != 0) { - $v_content = $this->_readBlock(); - $v_filename .= $v_content; - } - - // ----- Read the next header - $v_binary_data = $this->_readBlock(); - - if (!$this->_readHeader($v_binary_data, $v_header)) { - return false; - } - - $v_filename = rtrim(substr($v_filename, 0, $v_filesize), "\0"); - $v_header['filename'] = $v_filename; - if ($this->_maliciousFilename($v_filename)) { - $this->_error( - 'Malicious .tar detected, file "' . $v_filename . - '" will not install in desired directory tree' - ); - return false; - } - - return true; - } - - /** - * This method extract from the archive one file identified by $p_filename. - * The return value is a string with the file content, or null on error. - * - * @param string $p_filename The path of the file to extract in a string. - * - * @return a string with the file content or null. - */ - private function _extractInString($p_filename) - { - $v_result_str = ""; - - while (strlen($v_binary_data = $this->_readBlock()) != 0) { - if (!$this->_readHeader($v_binary_data, $v_header)) { - return null; - } - - if ($v_header['filename'] == '') { - continue; - } - - // ----- Look for long filename - if ($v_header['typeflag'] == 'L') { - if (!$this->_readLongHeader($v_header)) { - return null; - } - } - - if ($v_header['filename'] == $p_filename) { - if ($v_header['typeflag'] == "5") { - $this->_error( - 'Unable to extract in string a directory ' - . 'entry {' . $v_header['filename'] . '}' - ); - return null; - } else { - $n = floor($v_header['size'] / 512); - for ($i = 0; $i < $n; $i++) { - $v_result_str .= $this->_readBlock(); - } - if (($v_header['size'] % 512) != 0) { - $v_content = $this->_readBlock(); - $v_result_str .= substr( - $v_content, - 0, - ($v_header['size'] % 512) - ); - } - return $v_result_str; - } - } else { - $this->_jumpBlock(ceil(($v_header['size'] / 512))); - } - } - - return null; - } - - /** - * @param string $p_path - * @param string $p_list_detail - * @param string $p_mode - * @param string $p_file_list - * @param string $p_remove_path - * @param bool $p_preserve - * @return bool - */ - public function _extractList( - $p_path, - &$p_list_detail, - $p_mode, - $p_file_list, - $p_remove_path, - $p_preserve = false - ) { - $v_result = true; - $v_nb = 0; - $v_extract_all = true; - $v_listing = false; - - $p_path = $this->_translateWinPath($p_path, false); - if ($p_path == '' || (substr($p_path, 0, 1) != '/' - && substr($p_path, 0, 3) != "../" && !strpos($p_path, ':')) - ) { - $p_path = "./" . $p_path; - } - $p_remove_path = $this->_translateWinPath($p_remove_path); - - // ----- Look for path to remove format (should end by /) - if (($p_remove_path != '') && (substr($p_remove_path, -1) != '/')) { - $p_remove_path .= '/'; - } - $p_remove_path_size = strlen($p_remove_path); - - switch ($p_mode) { - case "complete" : - $v_extract_all = true; - $v_listing = false; - break; - case "partial" : - $v_extract_all = false; - $v_listing = false; - break; - case "list" : - $v_extract_all = false; - $v_listing = true; - break; - default : - $this->_error('Invalid extract mode (' . $p_mode . ')'); - return false; - } - - clearstatcache(); - - while (strlen($v_binary_data = $this->_readBlock()) != 0) { - $v_extract_file = false; - $v_extraction_stopped = 0; - - if (!$this->_readHeader($v_binary_data, $v_header)) { - return false; - } - - if ($v_header['filename'] == '') { - continue; - } - - // ----- Look for long filename - if ($v_header['typeflag'] == 'L') { - if (!$this->_readLongHeader($v_header)) { - return false; - } - } - - // ignore extended / pax headers - if ($v_header['typeflag'] == 'x' || $v_header['typeflag'] == 'g') { - $this->_jumpBlock(ceil(($v_header['size'] / 512))); - continue; - } - - if ((!$v_extract_all) && (is_array($p_file_list))) { - // ----- By default no unzip if the file is not found - $v_extract_file = false; - - for ($i = 0; $i < sizeof($p_file_list); $i++) { - // ----- Look if it is a directory - if (substr($p_file_list[$i], -1) == '/') { - // ----- Look if the directory is in the filename path - if ((strlen($v_header['filename']) > strlen($p_file_list[$i])) - && (substr($v_header['filename'], 0, strlen($p_file_list[$i])) - == $p_file_list[$i]) - ) { - $v_extract_file = true; - break; - } - } // ----- It is a file, so compare the file names - elseif ($p_file_list[$i] == $v_header['filename']) { - $v_extract_file = true; - break; - } - } - } else { - $v_extract_file = true; - } - - // ----- Look if this file need to be extracted - if (($v_extract_file) && (!$v_listing)) { - if (($p_remove_path != '') - && (substr($v_header['filename'] . '/', 0, $p_remove_path_size) - == $p_remove_path) - ) { - $v_header['filename'] = substr( - $v_header['filename'], - $p_remove_path_size - ); - if ($v_header['filename'] == '') { - continue; - } - } - if (($p_path != './') && ($p_path != '/')) { - while (substr($p_path, -1) == '/') { - $p_path = substr($p_path, 0, strlen($p_path) - 1); - } - - if (substr($v_header['filename'], 0, 1) == '/') { - $v_header['filename'] = $p_path . $v_header['filename']; - } else { - $v_header['filename'] = $p_path . '/' . $v_header['filename']; - } - } - if (file_exists($v_header['filename'])) { - if ((@is_dir($v_header['filename'])) - && ($v_header['typeflag'] == '') - ) { - $this->_error( - 'File ' . $v_header['filename'] - . ' already exists as a directory' - ); - return false; - } - if (($this->_isArchive($v_header['filename'])) - && ($v_header['typeflag'] == "5") - ) { - $this->_error( - 'Directory ' . $v_header['filename'] - . ' already exists as a file' - ); - return false; - } - if (!is_writeable($v_header['filename'])) { - $this->_error( - 'File ' . $v_header['filename'] - . ' already exists and is write protected' - ); - return false; - } - if (filemtime($v_header['filename']) > $v_header['mtime']) { - // To be completed : An error or silent no replace ? - } - } // ----- Check the directory availability and create it if necessary - elseif (($v_result - = $this->_dirCheck( - ($v_header['typeflag'] == "5" - ? $v_header['filename'] - : dirname($v_header['filename'])) - )) != 1 - ) { - $this->_error('Unable to create path for ' . $v_header['filename']); - return false; - } - - if ($v_extract_file) { - if ($v_header['typeflag'] == "5") { - if (!@file_exists($v_header['filename'])) { - if (!@mkdir($v_header['filename'], 0777)) { - $this->_error( - 'Unable to create directory {' - . $v_header['filename'] . '}' - ); - return false; - } - } - } elseif ($v_header['typeflag'] == "2") { - if (@file_exists($v_header['filename'])) { - @unlink($v_header['filename']); - } - if (!@symlink($v_header['link'], $v_header['filename'])) { - $this->_error( - 'Unable to extract symbolic link {' - . $v_header['filename'] . '}' - ); - return false; - } - } else { - if (($v_dest_file = @fopen($v_header['filename'], "wb")) == 0) { - $this->_error( - 'Error while opening {' . $v_header['filename'] - . '} in write binary mode' - ); - return false; - } else { - $n = floor($v_header['size'] / 512); - for ($i = 0; $i < $n; $i++) { - $v_content = $this->_readBlock(); - fwrite($v_dest_file, $v_content, 512); - } - if (($v_header['size'] % 512) != 0) { - $v_content = $this->_readBlock(); - fwrite($v_dest_file, $v_content, ($v_header['size'] % 512)); - } - - @fclose($v_dest_file); - - if ($p_preserve) { - @chown($v_header['filename'], $v_header['uid']); - @chgrp($v_header['filename'], $v_header['gid']); - } - - // ----- Change the file mode, mtime - @touch($v_header['filename'], $v_header['mtime']); - if ($v_header['mode'] & 0111) { - // make file executable, obey umask - $mode = fileperms($v_header['filename']) | (~umask() & 0111); - @chmod($v_header['filename'], $mode); - } - } - - // ----- Check the file size - clearstatcache(); - if (!is_file($v_header['filename'])) { - $this->_error( - 'Extracted file ' . $v_header['filename'] - . 'does not exist. Archive may be corrupted.' - ); - return false; - } - - $filesize = filesize($v_header['filename']); - if ($filesize != $v_header['size']) { - $this->_error( - 'Extracted file ' . $v_header['filename'] - . ' does not have the correct file size \'' - . $filesize - . '\' (' . $v_header['size'] - . ' expected). Archive may be corrupted.' - ); - return false; - } - } - } else { - $this->_jumpBlock(ceil(($v_header['size'] / 512))); - } - } else { - $this->_jumpBlock(ceil(($v_header['size'] / 512))); - } - - /* TBC : Seems to be unused ... - if ($this->_compress) - $v_end_of_file = @gzeof($this->_file); - else - $v_end_of_file = @feof($this->_file); - */ - - if ($v_listing || $v_extract_file || $v_extraction_stopped) { - // ----- Log extracted files - if (($v_file_dir = dirname($v_header['filename'])) - == $v_header['filename'] - ) { - $v_file_dir = ''; - } - if ((substr($v_header['filename'], 0, 1) == '/') && ($v_file_dir == '')) { - $v_file_dir = '/'; - } - - $p_list_detail[$v_nb++] = $v_header; - if (is_array($p_file_list) && (count($p_list_detail) == count($p_file_list))) { - return true; - } - } - } - - return true; - } - - /** - * @return bool - */ - public function _openAppend() - { - if (filesize($this->_tarname) == 0) { - return $this->_openWrite(); - } - - if ($this->_compress) { - $this->_close(); - - if (!@rename($this->_tarname, $this->_tarname . ".tmp")) { - $this->_error( - 'Error while renaming \'' . $this->_tarname - . '\' to temporary file \'' . $this->_tarname - . '.tmp\'' - ); - return false; - } - - if ($this->_compress_type == 'gz') { - $v_temp_tar = @gzopen($this->_tarname . ".tmp", "rb"); - } elseif ($this->_compress_type == 'bz2') { - $v_temp_tar = @bzopen($this->_tarname . ".tmp", "r"); - } elseif ($this->_compress_type == 'lzma2') { - $v_temp_tar = @xzopen($this->_tarname . ".tmp", "r"); - } - - - if ($v_temp_tar == 0) { - $this->_error( - 'Unable to open file \'' . $this->_tarname - . '.tmp\' in binary read mode' - ); - @rename($this->_tarname . ".tmp", $this->_tarname); - return false; - } - - if (!$this->_openWrite()) { - @rename($this->_tarname . ".tmp", $this->_tarname); - return false; - } - - if ($this->_compress_type == 'gz') { - $end_blocks = 0; - - while (!@gzeof($v_temp_tar)) { - $v_buffer = @gzread($v_temp_tar, 512); - if ($v_buffer == ARCHIVE_TAR_END_BLOCK || strlen($v_buffer) == 0) { - $end_blocks++; - // do not copy end blocks, we will re-make them - // after appending - continue; - } elseif ($end_blocks > 0) { - for ($i = 0; $i < $end_blocks; $i++) { - $this->_writeBlock(ARCHIVE_TAR_END_BLOCK); - } - $end_blocks = 0; - } - $v_binary_data = pack("a512", $v_buffer); - $this->_writeBlock($v_binary_data); - } - - @gzclose($v_temp_tar); - } elseif ($this->_compress_type == 'bz2') { - $end_blocks = 0; - - while (strlen($v_buffer = @bzread($v_temp_tar, 512)) > 0) { - if ($v_buffer == ARCHIVE_TAR_END_BLOCK || strlen($v_buffer) == 0) { - $end_blocks++; - // do not copy end blocks, we will re-make them - // after appending - continue; - } elseif ($end_blocks > 0) { - for ($i = 0; $i < $end_blocks; $i++) { - $this->_writeBlock(ARCHIVE_TAR_END_BLOCK); - } - $end_blocks = 0; - } - $v_binary_data = pack("a512", $v_buffer); - $this->_writeBlock($v_binary_data); - } - - @bzclose($v_temp_tar); - } elseif ($this->_compress_type == 'lzma2') { - $end_blocks = 0; - - while (strlen($v_buffer = @xzread($v_temp_tar, 512)) > 0) { - if ($v_buffer == ARCHIVE_TAR_END_BLOCK || strlen($v_buffer) == 0) { - $end_blocks++; - // do not copy end blocks, we will re-make them - // after appending - continue; - } elseif ($end_blocks > 0) { - for ($i = 0; $i < $end_blocks; $i++) { - $this->_writeBlock(ARCHIVE_TAR_END_BLOCK); - } - $end_blocks = 0; - } - $v_binary_data = pack("a512", $v_buffer); - $this->_writeBlock($v_binary_data); - } - - @xzclose($v_temp_tar); - } - - if (!@unlink($this->_tarname . ".tmp")) { - $this->_error( - 'Error while deleting temporary file \'' - . $this->_tarname . '.tmp\'' - ); - } - } else { - // ----- For not compressed tar, just add files before the last - // one or two 512 bytes block - if (!$this->_openReadWrite()) { - return false; - } - - clearstatcache(); - $v_size = filesize($this->_tarname); - - // We might have zero, one or two end blocks. - // The standard is two, but we should try to handle - // other cases. - fseek($this->_file, $v_size - 1024); - if (fread($this->_file, 512) == ARCHIVE_TAR_END_BLOCK) { - fseek($this->_file, $v_size - 1024); - } elseif (fread($this->_file, 512) == ARCHIVE_TAR_END_BLOCK) { - fseek($this->_file, $v_size - 512); - } - } - - return true; - } - - /** - * @param $p_filelist - * @param string $p_add_dir - * @param string $p_remove_dir - * @return bool - */ - public function _append($p_filelist, $p_add_dir = '', $p_remove_dir = '') - { - if (!$this->_openAppend()) { - return false; - } - - if ($this->_addList($p_filelist, $p_add_dir, $p_remove_dir)) { - $this->_writeFooter(); - } - - $this->_close(); - - return true; - } - - /** - * Check if a directory exists and create it (including parent - * dirs) if not. - * - * @param string $p_dir directory to check - * - * @return bool true if the directory exists or was created - */ - public function _dirCheck($p_dir) - { - clearstatcache(); - if ((@is_dir($p_dir)) || ($p_dir == '')) { - return true; - } - - $p_parent_dir = dirname($p_dir); - - if (($p_parent_dir != $p_dir) && - ($p_parent_dir != '') && - (!$this->_dirCheck($p_parent_dir)) - ) { - return false; - } - - if (!@mkdir($p_dir, 0777)) { - $this->_error("Unable to create directory '$p_dir'"); - return false; - } - - return true; - } - - /** - * Compress path by changing for example "/dir/foo/../bar" to "/dir/bar", - * rand emove double slashes. - * - * @param string $p_dir path to reduce - * - * @return string reduced path - */ - private function _pathReduction($p_dir) - { - $v_result = ''; - - // ----- Look for not empty path - if ($p_dir != '') { - // ----- Explode path by directory names - $v_list = explode('/', $p_dir); - - // ----- Study directories from last to first - for ($i = sizeof($v_list) - 1; $i >= 0; $i--) { - // ----- Look for current path - if ($v_list[$i] == ".") { - // ----- Ignore this directory - // Should be the first $i=0, but no check is done - } else { - if ($v_list[$i] == "..") { - // ----- Ignore it and ignore the $i-1 - $i--; - } else { - if (($v_list[$i] == '') - && ($i != (sizeof($v_list) - 1)) - && ($i != 0) - ) { - // ----- Ignore only the double '//' in path, - // but not the first and last / - } else { - $v_result = $v_list[$i] . ($i != (sizeof($v_list) - 1) ? '/' - . $v_result : ''); - } - } - } - } - } - - if (defined('OS_WINDOWS') && OS_WINDOWS) { - $v_result = strtr($v_result, '\\', '/'); - } - - return $v_result; - } - - /** - * @param $p_path - * @param bool $p_remove_disk_letter - * @return string - */ - public function _translateWinPath($p_path, $p_remove_disk_letter = true) - { - if (defined('OS_WINDOWS') && OS_WINDOWS) { - // ----- Look for potential disk letter - if (($p_remove_disk_letter) - && (($v_position = strpos($p_path, ':')) != false) - ) { - $p_path = substr($p_path, $v_position + 1); - } - // ----- Change potential windows directory separator - if ((strpos($p_path, '\\') > 0) || (substr($p_path, 0, 1) == '\\')) { - $p_path = strtr($p_path, '\\', '/'); - } - } - return $p_path; - } -} diff --git a/gulliver/thirdparty/pear/archive_tar/README.md b/gulliver/thirdparty/pear/archive_tar/README.md deleted file mode 100644 index fcf246cdc..000000000 --- a/gulliver/thirdparty/pear/archive_tar/README.md +++ /dev/null @@ -1,33 +0,0 @@ -Archive_Tar -========== - -[![Build Status](https://secure.travis-ci.org/pear/Archive_Tar.png?branch=master)](https://travis-ci.org/pear/Archive_Tar) - -This package provides handling of tar files in PHP. -It supports creating, listing, extracting and adding to tar files. -Gzip support is available if PHP has the zlib extension built-in or -loaded. Bz2 compression is also supported with the bz2 extension loaded. - -This package is hosted at http://pear.php.net/package/Archive_Tar - -Please report all new issues via the PEAR bug tracker. - -Pull requests are welcome! - - -Testing, building ------------------ - -To test, run either -$ phpunit tests/ - or -$ pear run-tests -r - -To build, simply -$ pear package - -To install from scratch -$ pear install package.xml - -To upgrade -$ pear upgrade -f package.xml diff --git a/gulliver/thirdparty/pear/archive_tar/composer.json b/gulliver/thirdparty/pear/archive_tar/composer.json deleted file mode 100644 index c50b0a9a9..000000000 --- a/gulliver/thirdparty/pear/archive_tar/composer.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "name": "pear/archive_tar", - "description": "Tar file management class", - "type": "library", - "keywords": [ - "archive", - "tar" - ], - "homepage": "https://github.com/pear/Archive_Tar", - "license": "BSD-3-Clause", - "authors": [ - { - "name": "Vincent Blavet", - "email": "vincent@phpconcept.net" - }, - { - "name": "Greg Beaver", - "email": "greg@chiaraquartet.net" - }, - { - "name": "Michiel Rook", - "email": "mrook@php.net" - } - ], - "require": { - "php": ">=5.2.0", - "pear/pear-core-minimal": "^1.10.0alpha2" - }, - "suggest": { - "ext-zlib": "Gzip compression support.", - "ext-bz2": "bz2 compression support.", - "ext-xz": "lzma2 compression support." - }, - "autoload": { - "psr-0": { - "Archive_Tar": "" - } - }, - "include-path": [ - "./" - ], - "support": { - "issues": "http://pear.php.net/bugs/search.php?cmd=display&package_name[]=Archive_Tar", - "source": "https://github.com/pear/Archive_Tar" - }, - "require-dev": { - "phpunit/phpunit": "*" - }, - "extra": { - "branch-alias": { - "dev-master": "1.4.x-dev" - } - } -} diff --git a/gulliver/thirdparty/pear/archive_tar/docs/Archive_Tar.txt b/gulliver/thirdparty/pear/archive_tar/docs/Archive_Tar.txt deleted file mode 100644 index 2e8ec47c1..000000000 --- a/gulliver/thirdparty/pear/archive_tar/docs/Archive_Tar.txt +++ /dev/null @@ -1,475 +0,0 @@ -Documentation for class Archive_Tar -=================================== -Last update : 2001-08-15 - - - -Overview : ----------- - - The Archive_Tar class helps in creating and managing GNU TAR format - files compressed by GNU ZIP or not. - The class offers basic functions like creating an archive, adding - files in the archive, extracting files from the archive and listing - the archive content. - It also provide advanced functions that allow the adding and - extraction of files with path manipulation. - - -Sample : --------- - - // ----- Creating the object (uncompressed archive) - $tar_object = new Archive_Tar("tarname.tar"); - $tar_object->setErrorHandling(PEAR_ERROR_PRINT); - - // ----- Creating the archive - $v_list[0]="file.txt"; - $v_list[1]="data/"; - $v_list[2]="file.log"; - $tar_object->create($v_list); - - // ----- Adding files - $v_list[0]="dev/file.txt"; - $v_list[1]="dev/data/"; - $v_list[2]="log/file.log"; - $tar_object->add($v_list); - - // ----- Adding more files - $tar_object->add("release/newfile.log release/readme.txt"); - - // ----- Listing the content - if (($v_list = $tar_object->listContent()) != 0) - for ($i=0; $i"; - echo " .size :'".$v_list[$i][size]."'
"; - echo " .mtime :'".$v_list[$i][mtime]."' (".date("l dS of F Y h:i:s A", $v_list[$i][mtime]).")
"; - echo " .mode :'".$v_list[$i][mode]."'
"; - echo " .uid :'".$v_list[$i][uid]."'
"; - echo " .gid :'".$v_list[$i][gid]."'
"; - echo " .typeflag :'".$v_list[$i][typeflag]."'
"; - } - - // ----- Extracting the archive in directory "install" - $tar_object->extract("install"); - - -Public arguments : ------------------- - -None - - -Public Methods : ----------------- - -Method : Archive_Tar($p_tarname, $compress = null) -Description : - Archive_Tar Class constructor. This flavour of the constructor only - declare a new Archive_Tar object, identifying it by the name of the - tar file. - If the compress argument is set the tar will be read or created as a - gzip or bz2 compressed TAR file. -Arguments : - $p_tarname : A valid filename for the tar archive file. - $p_compress : can be null, 'gz' or 'bz2'. For - compatibility reason it can also be true. This - parameter indicates if gzip or bz2 compression - is required. -Return value : - The Archive_Tar object. -Sample : - $tar_object = new Archive_Tar("tarname.tar"); - $tar_object_compressed = new Archive_Tar("tarname.tgz", true); -How it works : - Initialize the object. - -Method : create($p_filelist) -Description : - This method creates the archive file and add the files / directories - that are listed in $p_filelist. - If the file already exists and is writable, it is replaced by the - new tar. It is a create and not an add. If the file exists and is - read-only or is a directory it is not replaced. The method return - false and a PEAR error text. - The $p_filelist parameter can be an array of string, each string - representing a filename or a directory name with their path if - needed. It can also be a single string with names separated by a - single blank. - See also createModify() method for more details. -Arguments : - $p_filelist : An array of filenames and directory names, or a single - string with names separated by a single blank space. -Return value : - true on success, false on error. -Sample 1 : - $tar_object = new Archive_Tar("tarname.tar"); - $tar_object->setErrorHandling(PEAR_ERROR_PRINT); // Optional error handling - $v_list[0]="file.txt"; - $v_list[1]="data/"; (Optional '/' at the end) - $v_list[2]="file.log"; - $tar_object->create($v_list); -Sample 2 : - $tar_object = new Archive_Tar("tarname.tar"); - $tar_object->setErrorHandling(PEAR_ERROR_PRINT); // Optional error handling - $tar_object->create("file.txt data/ file.log"); -How it works : - Just calling the createModify() method with the right parameters. - -Method : createModify($p_filelist, $p_add_dir, $p_remove_dir = "") -Description : - This method creates the archive file and add the files / directories - that are listed in $p_filelist. - If the file already exists and is writable, it is replaced by the - new tar. It is a create and not an add. If the file exists and is - read-only or is a directory it is not replaced. The method return - false and a PEAR error text. - The $p_filelist parameter can be an array of string, each string - representing a filename or a directory name with their path if - needed. It can also be a single string with names separated by a - single blank. - The path indicated in $p_remove_dir will be removed from the - memorized path of each file / directory listed when this path - exists. By default nothing is removed (empty path "") - The path indicated in $p_add_dir will be added at the beginning of - the memorized path of each file / directory listed. However it can - be set to empty "". The adding of a path is done after the removing - of path. - The path add/remove ability enables the user to prepare an archive - for extraction in a different path than the origin files are. - See also addModify() method for file adding properties. -Arguments : - $p_filelist : An array of filenames and directory names, or a single - string with names separated by a single blank space. - $p_add_dir : A string which contains a path to be added to the - memorized path of each element in the list. - $p_remove_dir : A string which contains a path to be removed from - the memorized path of each element in the list, when - relevant. -Return value : - true on success, false on error. -Sample 1 : - $tar_object = new Archive_Tar("tarname.tar"); - $tar_object->setErrorHandling(PEAR_ERROR_PRINT); // Optional error handling - $v_list[0]="file.txt"; - $v_list[1]="data/"; (Optional '/' at the end) - $v_list[2]="file.log"; - $tar_object->createModify($v_list, "install"); - // files are stored in the archive as : - // install/file.txt - // install/data - // install/data/file1.txt - // install/data/... all the files and sub-dirs of data/ - // install/file.log -Sample 2 : - $tar_object = new Archive_Tar("tarname.tar"); - $tar_object->setErrorHandling(PEAR_ERROR_PRINT); // Optional error handling - $v_list[0]="dev/file.txt"; - $v_list[1]="dev/data/"; (Optional '/' at the end) - $v_list[2]="log/file.log"; - $tar_object->createModify($v_list, "install", "dev"); - // files are stored in the archive as : - // install/file.txt - // install/data - // install/data/file1.txt - // install/data/... all the files and sub-dirs of data/ - // install/log/file.log -How it works : - Open the file in write mode (erasing the existing one if one), - call the _addList() method for adding the files in an empty archive, - add the tar footer (512 bytes block), close the tar file. - - -Method : addModify($p_filelist, $p_add_dir, $p_remove_dir="") -Description : - This method add the files / directories listed in $p_filelist at the - end of the existing archive. If the archive does not yet exists it - is created. - The $p_filelist parameter can be an array of string, each string - representing a filename or a directory name with their path if - needed. It can also be a single string with names separated by a - single blank. - The path indicated in $p_remove_dir will be removed from the - memorized path of each file / directory listed when this path - exists. By default nothing is removed (empty path "") - The path indicated in $p_add_dir will be added at the beginning of - the memorized path of each file / directory listed. However it can - be set to empty "". The adding of a path is done after the removing - of path. - The path add/remove ability enables the user to prepare an archive - for extraction in a different path than the origin files are. - If a file/dir is already in the archive it will only be added at the - end of the archive. There is no update of the existing archived - file/dir. However while extracting the archive, the last file will - replace the first one. This results in a none optimization of the - archive size. - If a file/dir does not exist the file/dir is ignored. However an - error text is send to PEAR error. - If a file/dir is not readable the file/dir is ignored. However an - error text is send to PEAR error. - If the resulting filename/dirname (after the add/remove option or - not) string is greater than 99 char, the file/dir is - ignored. However an error text is send to PEAR error. -Arguments : - $p_filelist : An array of filenames and directory names, or a single - string with names separated by a single blank space. - $p_add_dir : A string which contains a path to be added to the - memorized path of each element in the list. - $p_remove_dir : A string which contains a path to be removed from - the memorized path of each element in the list, when - relevant. -Return value : - true on success, false on error. -Sample 1 : - $tar_object = new Archive_Tar("tarname.tar"); - [...] - $v_list[0]="dev/file.txt"; - $v_list[1]="dev/data/"; (Optional '/' at the end) - $v_list[2]="log/file.log"; - $tar_object->addModify($v_list, "install"); - // files are stored in the archive as : - // install/file.txt - // install/data - // install/data/file1.txt - // install/data/... all the files and sub-dirs of data/ - // install/file.log -Sample 2 : - $tar_object = new Archive_Tar("tarname.tar"); - [...] - $v_list[0]="dev/file.txt"; - $v_list[1]="dev/data/"; (Optional '/' at the end) - $v_list[2]="log/file.log"; - $tar_object->addModify($v_list, "install", "dev"); - // files are stored in the archive as : - // install/file.txt - // install/data - // install/data/file1.txt - // install/data/... all the files and sub-dirs of data/ - // install/log/file.log -How it works : - If the archive does not exists it create it and add the files. - If the archive does exists and is not compressed, it open it, jump - before the last empty 512 bytes block (tar footer) and add the files - at this point. - If the archive does exists and is compressed, a temporary copy file - is created. This temporary file is then 'gzip' read block by block - until the last empty block. The new files are then added in the - compressed file. - The adding of files is done by going through the file/dir list, - adding files per files, in a recursive way through the - directory. Each time a path need to be added/removed it is done - before writing the file header in the archive. - -Method : add($p_filelist) -Description : - This method add the files / directories listed in $p_filelist at the - end of the existing archive. If the archive does not yet exists it - is created. - The $p_filelist parameter can be an array of string, each string - representing a filename or a directory name with their path if - needed. It can also be a single string with names separated by a - single blank. - See addModify() method for details and limitations. -Arguments : - $p_filelist : An array of filenames and directory names, or a single - string with names separated by a single blank space. -Return value : - true on success, false on error. -Sample 1 : - $tar_object = new Archive_Tar("tarname.tar"); - [...] - $v_list[0]="dev/file.txt"; - $v_list[1]="dev/data/"; (Optional '/' at the end) - $v_list[2]="log/file.log"; - $tar_object->add($v_list); -Sample 2 : - $tar_object = new Archive_Tar("tarname.tgz", true); - [...] - $v_list[0]="dev/file.txt"; - $v_list[1]="dev/data/"; (Optional '/' at the end) - $v_list[2]="log/file.log"; - $tar_object->add($v_list); -How it works : - Simply call the addModify() method with the right parameters. - -Method : addString($p_filename, $p_string, $p_datetime, $p_params) -Description : - This method add a single string as a file at the - end of the existing archive. If the archive does not yet exists it - is created. -Arguments : - $p_filename : A string which contains the full filename path - that will be associated with the string. - $p_string : The content of the file added in the archive. - $p_datetime : (Optional) Timestamp of the file (default = now) - $p_params : (Optional) Various file metadata: - stamp - As above, timestamp of the file - mode - UNIX-style permissions (default 0600) - type - Is this a regular file or link (see TAR - format spec for how to create a hard/symlink) - uid - UNIX-style user ID (default 0 = root) - gid - UNIX-style group ID (default 0 = root) -Return value : - true on success, false on error. -Sample 1 : - $v_archive = & new Archive_Tar($p_filename); - $v_archive->setErrorHandling(PEAR_ERROR_PRINT); - $v_result = $v_archive->addString('data/test.txt', 'This is the text of the string'); - $v_result = $v_archive->addString( - 'data/test.sh', - "#!/bin/sh\necho 'Hello'", - time(), - array( "mode" => 0755, "uid" => 34 ) - ); - - -Method : extract($p_path = "") -Description : - This method extract all the content of the archive in the directory - indicated by $p_path.If $p_path is optional, if not set the archive - is extracted in the current directory. - While extracting a file, if the directory path does not exists it is - created. - See extractModify() for details and limitations. -Arguments : - $p_path : Optional path where the files/dir need to by extracted. -Return value : - true on success, false on error. -Sample : - $tar_object = new Archive_Tar("tarname.tar"); - $tar_object->extract(); -How it works : - Simply call the extractModify() method with appropriate parameters. - -Method : extractModify($p_path, $p_remove_path) -Description : - This method extract all the content of the archive in the directory - indicated by $p_path. When relevant the memorized path of the - files/dir can be modified by removing the $p_remove_path path at the - beginning of the file/dir path. - While extracting a file, if the directory path does not exists it is - created. - While extracting a file, if the file already exists it is replaced - without looking for last modification date. - While extracting a file, if the file already exists and is write - protected, the extraction is aborted. - While extracting a file, if a directory with the same name already - exists, the extraction is aborted. - While extracting a directory, if a file with the same name already - exists, the extraction is aborted. - While extracting a file/directory if the destination directory exist - and is write protected, or does not exist but can not be created, - the extraction is aborted. - If after extraction an extracted file does not show the correct - stored file size, the extraction is aborted. - When the extraction is aborted, a PEAR error text is set and false - is returned. However the result can be a partial extraction that may - need to be manually cleaned. -Arguments : - $p_path : The path of the directory where the files/dir need to by - extracted. - $p_remove_path : Part of the memorized path that can be removed if - present at the beginning of the file/dir path. -Return value : - true on success, false on error. -Sample : - // Imagine tarname.tar with files : - // dev/data/file.txt - // dev/data/log.txt - // readme.txt - $tar_object = new Archive_Tar("tarname.tar"); - $tar_object->extractModify("install", "dev"); - // Files will be extracted there : - // install/data/file.txt - // install/data/log.txt - // install/readme.txt -How it works : - Open the archive and call a more generic function that can extract - only a part of the archive or all the archive. - See extractList() method for more details. - -Method : extractInString($p_filename) -Description : - This method extract from the archive one file identified by $p_filename. - The return value is a string with the file content, or NULL on error. -Arguments : - $p_filename : The path of the file to extract in a string. -Return value : - a string with the file content or NULL. -Sample : - // Imagine tarname.tar with files : - // dev/data/file.txt - // dev/data/log.txt - // dev/readme.txt - $v_archive = & new Archive_Tar('tarname.tar'); - $v_archive->setErrorHandling(PEAR_ERROR_PRINT); - $v_string = $v_archive->extractInString('dev/readme.txt'); - echo $v_string; - -Method : listContent() -Description : - This method returns an array of arrays that describe each - file/directory present in the archive. - The array is not sorted, so it show the position of the file in the - archive. - The file informations are : - $file[filename] : Name and path of the file/dir. - $file[mode] : File permissions (result of fileperms()) - $file[uid] : user id - $file[gid] : group id - $file[size] : filesize - $file[mtime] : Last modification time (result of filemtime()) - $file[typeflag] : "" for file, "5" for directory -Arguments : -Return value : - An array of arrays or 0 on error. -Sample : - $tar_object = new Archive_Tar("tarname.tar"); - if (($v_list = $tar_object->listContent()) != 0) - for ($i=0; $i"; - echo " .size :'".$v_list[$i][size]."'
"; - echo " .mtime :'".$v_list[$i][mtime]."' (". - date("l dS of F Y h:i:s A", $v_list[$i][mtime]).")
"; - echo " .mode :'".$v_list[$i][mode]."'
"; - echo " .uid :'".$v_list[$i][uid]."'
"; - echo " .gid :'".$v_list[$i][gid]."'
"; - echo " .typeflag :'".$v_list[$i][typeflag]."'
"; - } -How it works : - Call the same function as an extract however with a flag to only go - through the archive without extracting the files. - -Method : extractList($p_filelist, $p_path = "", $p_remove_path = "") -Description : - This method extract from the archive only the files indicated in the - $p_filelist. These files are extracted in the current directory or - in the directory indicated by the optional $p_path parameter. - If indicated the $p_remove_path can be used in the same way as it is - used in extractModify() method. -Arguments : - $p_filelist : An array of filenames and directory names, or a single - string with names separated by a single blank space. - $p_path : The path of the directory where the files/dir need to by - extracted. - $p_remove_path : Part of the memorized path that can be removed if - present at the beginning of the file/dir path. -Return value : - true on success, false on error. -Sample : - // Imagine tarname.tar with files : - // dev/data/file.txt - // dev/data/log.txt - // readme.txt - $tar_object = new Archive_Tar("tarname.tar"); - $tar_object->extractList("dev/data/file.txt readme.txt", "install", - "dev"); - // Files will be extracted there : - // install/data/file.txt - // install/readme.txt -How it works : - Go through the archive and extract only the files present in the - list. - diff --git a/gulliver/thirdparty/pear/archive_tar/package.xml b/gulliver/thirdparty/pear/archive_tar/package.xml deleted file mode 100644 index 993618099..000000000 --- a/gulliver/thirdparty/pear/archive_tar/package.xml +++ /dev/null @@ -1,544 +0,0 @@ - - - Archive_Tar - pear.php.net - Tar file management class - This class provides handling of tar files in PHP. -It supports creating, listing, extracting and adding to tar files. -Gzip support is available if PHP has the zlib extension built-in or -loaded. Bz2 compression is also supported with the bz2 extension loaded. - - Vincent Blavet - vblavet - vincent@phpconcept.net - no - - - Greg Beaver - cellog - greg@chiaraquartet.net - no - - - Michiel Rook - mrook - mrook@php.net - yes - - - Stig Bakken - ssb - stig@php.net - no - - 2017-06-11 - - - 1.4.3 - 1.4.0 - - - stable - stable - - New BSD License - -* Fix Bug #21218: Cannot use result of built-in function in write context in PHP - 7.2.0alpha1 [mrook] - - - - - - - - - - - - - PEAR - pear.php.net - 1.8.0 - 1.10.10 - - - - - 5.2.0 - - - 1.9.0 - - - - - - - - 1.4.2 - 1.4.0 - - - stable - stable - - 2016-02-25 - New BSD License - -* Fix reading of archives with files > 8GB -* Performance optimizations -* Do not try to call require_once on PEAR.php if it has already been loaded by the autoloader - - - - - 1.4.1 - 1.4.0 - - - stable - stable - - 2015-08-05 - New BSD License - -* Update composer.json to use pear-core-minimal 1.10.0alpha2 - - - - - 1.4.0 - 1.4.0 - - - stable - stable - - 2015-07-20 - New BSD License - -* Add support for PHP 7 -* Drop support for PHP 4 -* Add visibility declarations to methods and properties - - - - - 1.3.16 - 1.3.1 - - - stable - stable - - 2015-04-14 - New BSD License - -* Fix Bug #20514: invalid package.xml; not installable with pyrus [mrook] - - - - - 1.3.15 - 1.3.1 - - - stable - stable - - 2015-03-05 - New BSD License - -* Fixes composer.json parse error - - - - - 1.3.14 - 1.3.1 - - - stable - stable - - 2015-02-26 - New BSD License - -* Fix Bug #18505: Possible incorrect handling of file names in TAR [mrook] - - - - - 1.3.13 - 1.3.1 - - - stable - stable - - 2014-09-02 - New BSD - License - -* Fix Bug #20382: gzopen fix [mrook] - - - - - 1.3.12 - 1.3.1 - - - stable - stable - - 2014-08-04 - New BSD - License - -* Fix Bug #19964: Memory leaking in Archive_Tar [mrook] - * Fix Bug #20246: Broken with php 5.5.9 [mrook] - * Fix Bug #20275: "pax_global_header" looks like a regular file - * [mrook] - * Implement Feature #19827: pass filename to _addFile function - downstream - * patch [mrook] - * Implement Feature #20132: Add custom mode/uid/gid to addString() [mrook] - - - - - 1.3.11 - 1.3.1 - - - stable - stable - - 2013-02-09 - New BSD - License - -* Fix Bug #19746: Broken with PHP 5.5 [mrook] - * Implement Feature #11258: Custom date/time in files added on-the-fly - * [mrook] - - - - - 1.3.10 - 1.3.1 - - - stable - stable - - 2012-04-10 - New BSD - License - -* Fix Bug #13361: Unable to add() some files (ex. mp3) [mrook] - * Fix Bug #19330: Class creates incorrect (non-readable) tar.gz file - * [mrook] - - - - - 1.3.9 - 1.3.1 - - - stable - stable - - 2012-02-27 - New BSD License - -* Fix Bug #16759: No error thrown from missing PHP zlib functions [mrook] - * Fix Bug #18877: Incorrect handling of backslashes in filenames on Linux [mrook] - * Fix Bug #19085: Error while packaging [mrook] - * Fix Bug #19289: Invalid tar file generated [mrook] - - - - - 1.3.8 - 1.3.1 - - - stable - stable - - 2011-10-14 - New BSD License - -* Fix Bug #17853: Test failure: dirtraversal.phpt [mrook] - * Fix Bug #18512: dead links are not saved in tar file [mrook] - * Fix Bug #18702: Unpacks incorrectly on long file names using header prefix [mrook] - * Implement Feature #10145: Patch to return a Pear Error Object on failure [mrook] - * Implement Feature #17491: Option to preserve permissions [mrook] - * Implement Feature #17813: Prevent PHP notice when extracting corrupted archive [mrook] - - - - - 1.3.7 - 1.3.1 - - - stable - stable - - 2010-04-26 - New BSD License - -PEAR compatibility update - - - - - 1.3.6 - 1.3.1 - - - stable - stable - - 2010-03-09 - New BSD License - -* Fix Bug #16963: extractList can't extract zipped files from big tar [mrook] - * Implement Feature #4013: Ignoring files and directories on creating an archive. [mrook] - - - - - 1.3.5 - 1.3.1 - - - stable - stable - - 2009-12-31 - New BSD License - -* Fix Bug #16958: Update 'compatible' tag in package.xml [mrook] - - - - - 1.3.4 - 1.3.1 - - - stable - stable - - 2009-12-30 - New BSD License - -* Fix Bug #11871: wrong result of ::listContent() if filename begins or ends with space [mrook] - * Fix Bug #12462: invalid tar magic [mrook] - * Fix Bug #13918: Long filenames may get up to 511 0x00 bytes appended on read [mrook] - * Fix Bug #16202: Bogus modification times [mrook] - * Implement Feature #16212: Die is not exception [mrook] - - - - - 1.3.3 - 1.3.1 - - - stable - stable - - 2009-03-27 - New BSD License - -Change the license to New BSD license - - minor bugfix release - * fix Bug #9921 compression with bzip2 fails [cellog] - * fix Bug #11594 _readLongHeader leaves 0 bytes in filename [jamessas] - * fix Bug #11769 Incorrect symlink handing [fajar99] - - - - - 1.3.2 - 1.3.1 - - - stable - stable - - 2007-01-03 - PHP License - -Correct Bug #4016 -Remove duplicate remove error display with '@' -Correct Bug #3909 : Check existence of OS_WINDOWS constant -Correct Bug #5452 fix for "lone zero block" when untarring packages -Change filemode (from pear-core/Archive/Tar.php v.1.21) -Correct Bug #6486 Can not extract symlinks -Correct Bug #6933 Archive_Tar (Tar file management class) Directory traversal -Correct Bug #8114 Files added on-the-fly not storing date -Correct Bug #9352 Bug on _dirCheck function over nfs path - - - - - 1.3.1 - 1.3.1 - - - stable - stable - - 2005-03-17 - PHP License - -Correct Bug #3855 - - - - - 1.3.0 - 1.3.0 - - - stable - stable - - 2005-03-06 - PHP License - -Bugs correction (2475, 2488, 2135, 2176) - - - - - 1.2 - 1.2 - - - stable - stable - - 2004-05-08 - PHP License - -Add support for other separator than the space char and bug - correction - - - - - 1.1 - 1.1 - - - stable - stable - - 2003-05-28 - PHP License - -* Add support for BZ2 compression -* Add support for add and extract without using temporary files : methods addString() and extractInString() - - - - - 1.0 - 1.0 - - - stable - stable - - 2003-01-24 - PHP License - -Change status to stable - - - - - 0.10-b1 - 0.10-b1 - - - beta - beta - - 2003-01-08 - PHP License - -Add support for long filenames (greater than 99 characters) - - - - - 0.9 - 0.9 - - - stable - stable - - 2002-05-27 - PHP License - -Auto-detect gzip'ed files - - - - - 0.4 - 0.4 - - - stable - stable - - 2002-05-20 - PHP License - -Windows bugfix: use forward slashes inside archives - - - - - 0.2 - 0.2 - - - stable - stable - - 2002-02-18 - PHP License - -From initial commit to stable - - - - - 0.3 - 0.3 - - - stable - stable - - 2002-04-13 - PHP License - -Windows bugfix: used wrong directory separators - - - - diff --git a/gulliver/thirdparty/pear/archive_tar/scripts/phptar.in b/gulliver/thirdparty/pear/archive_tar/scripts/phptar.in deleted file mode 100644 index 08361c1d0..000000000 --- a/gulliver/thirdparty/pear/archive_tar/scripts/phptar.in +++ /dev/null @@ -1,236 +0,0 @@ -#!@prefix@/bin/php -Cq - 1) { - usage("Only one of -c, -t and -x can be specified at once!"); -} - -if ($op_create + $op_list + $op_extract == 0) { - usage("Please specify either -c, -t or -x!"); -} - -if (empty($file)) { - if ($op_create) { - $file = "php://stdout"; - } else { - $file = "php://stdin"; - } -} - -// }}} - -$tar = new Archive_Tar($file, $use_gzip); -$tar->setErrorHandling(PEAR_ERROR_DIE, "$progname error: %s\n"); - -if ($op_create) { - do_create($tar, $options[1]); - $tar->create($options[1]); -} elseif ($op_list) { - do_list($tar, $verbose); -} elseif ($op_extract) { - do_extract($tar); -} - -// {{{ getrwx() - -function getrwx($bits) { - $str = ''; - $str .= ($bits & 4) ? 'r' : '-'; - $str .= ($bits & 2) ? 'w' : '-'; - $str .= ($bits & 1) ? 'x' : '-'; - return $str; -} - -// }}} -// {{{ getfiletype() - -function getfiletype($bits) { - static $map = array( - '-' => S_IFREG, - 'd' => S_IFDIR, - 'l' => S_IFLNK, - 'c' => S_IFCHR, - 'b' => S_IFBLK, - 'p' => S_IFIFO, - 's' => S_IFSOCK, - ); - foreach ($map as $char => $mask) { - if ($bits & $mask) { - return $char; - } - } -} - -// }}} -// {{{ getuser() - -function getuser($uid) { - static $cache = array(); - if (isset($cache[$uid])) { - return $cache[$uid]; - } - if (function_exists("posix_getpwuid")) { - if (is_array($user = @posix_getpwuid($uid))) { - $cache[$uid] = $user['name']; - return $user['name']; - } - } - $cache[$uid] = $uid; - return $uid; -} - -// }}} -// {{{ getgroup() - -function getgroup($gid) { - static $cache = array(); - if (isset($cache[$gid])) { - return $cache[$gid]; - } - if (function_exists("posix_getgrgid")) { - if (is_array($group = @posix_getgrgid($gid))) { - $cache[$gid] = $group['name']; - return $group['name']; - } - } - $cache[$gid] = $gid; - return $gid; -} - -// }}} -// {{{ do_create() - -function do_create(&$tar, &$files) -{ - $tar->create($files); -} - -// }}} -// {{{ do_list() - -function do_list(&$tar, $verbose) -{ - static $rwx = array(4 => 'r', 2 => 'w', 1 => 'x'); - $files = $tar->listContent(); - if (is_array($files) && sizeof($files) > 0) { - foreach ($files as $file) { - if ($verbose) { - $fm = (int)$file['mode']; - $mode = sprintf('%s%s%s%s', getfiletype($fm), - getrwx(($fm >> 6) & 7), getrwx(($fm >> 3) & 7), - getrwx($fm & 7)); - $owner = getuser($file['uid']) . '/' . getgroup($file['gid']); - printf("%10s %-11s %7d %s %s\n", $mode, $owner, $file['size'], - date('Y-m-d H:i:s', $file['mtime']), $file['filename']); - } else { - printf("%s\n", $file['filename']); - } - } - } -} - -// }}} -// {{{ do_extract() - -function do_extract(&$tar, $destdir = ".") -{ - $tar->extract($destdir); -} - -// }}} -// {{{ usage() - -function usage($errormsg = '') -{ - global $progname; - $fp = fopen("php://stderr", "w"); - if ($errormsg) { - if (PEAR::isError($errormsg)) { - fwrite($fp, $errormsg->getMessage() . "\n"); - } else { - fwrite($fp, "$errormsg\n"); - } - } - fwrite($fp, "$progname [-h|-?] {-c|-t|-x} [-z] [-v] [-f file] [file(s)...] -Options: - -h, -? Show this screen - -c Create archive - -t List archive - -x Extract archive - -z Run input/output through gzip - -f file Use as input or output (default is stdin/stdout) - -"); - fclose($fp); - exit; -} - -// }}} - -?> diff --git a/gulliver/thirdparty/pear/archive_tar/sync-php4 b/gulliver/thirdparty/pear/archive_tar/sync-php4 deleted file mode 100644 index 9fb57ff84..000000000 --- a/gulliver/thirdparty/pear/archive_tar/sync-php4 +++ /dev/null @@ -1,6 +0,0 @@ -#!/bin/sh - -rsync -av Archive/Tar.php ../../php4/pear/Archive/. -rsync -av package.xml ../../php4/pear/package-Archive_Tar.xml -rsync -av docs/Archive_Tar.txt ../../php4/pear/docs/. - diff --git a/gulliver/thirdparty/pear/archive_tar/tests/deadlinks.phpt b/gulliver/thirdparty/pear/archive_tar/tests/deadlinks.phpt deleted file mode 100644 index ef8705af0..000000000 --- a/gulliver/thirdparty/pear/archive_tar/tests/deadlinks.phpt +++ /dev/null @@ -1,46 +0,0 @@ ---TEST-- -test saving of dead symbolic links ---SKIPIF-- ---FILE-- - '.$item['link']; -} - -//prepare filesystem -@mkdir('test'); -@mkdir('test/a'); -@touch('test/b'); -@symlink('a', 'test/dir_link'); -@symlink('b', 'test/file_link'); -@symlink('dead', 'test/dead_link'); - -//prepare reference tar -system('tar -cf test1.tar test'); -$tar1=new Archive_Tar('test1.tar'); -$tar1List=array_map('fileName',$tar1->listContent()); -//create tar -$tar2=new Archive_Tar('test2.tar'); -$tar2->create(array('test','nonExisting'));// to make sure we are still report nonExisting -$tar2List=array_map('fileName',$tar2->listContent()); - -$phpunit->assertErrors(array( - array('package' => 'PEAR_Error', 'message' => "File 'nonExisting' does not exist")), 'after 1'); -$phpunit->assertEquals($tar1List, $tar2List, 'bla'); -echo 'tests done'; -?> ---CLEAN-- - ---EXPECT-- -tests done diff --git a/gulliver/thirdparty/pear/archive_tar/tests/dirtraversal.phpt b/gulliver/thirdparty/pear/archive_tar/tests/dirtraversal.phpt deleted file mode 100644 index 7e5d11f48..000000000 --- a/gulliver/thirdparty/pear/archive_tar/tests/dirtraversal.phpt +++ /dev/null @@ -1,24 +0,0 @@ ---TEST-- -test directory traversal security vulnerability ---SKIPIF-- ---FILE-- -listContent(); -$phpunit->assertErrors(array( - array('package' => 'PEAR_Error', 'message' => 'Malicious .tar detected, file "/../../../../../../../../../../../../../../AAAAAAAAAAAAAAAAA/BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB.txt" will not install in desired directory tree') -), 'after 1'); -$tar->extract(); -$phpunit->assertErrors(array( - array('package' => 'PEAR_Error', 'message' => 'Malicious .tar detected, file "/../../../../../../../../../../../../../../AAAAAAAAAAAAAAAAA/BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB.txt" will not install in desired directory tree') -), 'after 2'); -echo 'tests done'; -?> ---CLEAN-- - ---EXPECT-- -tests done diff --git a/gulliver/thirdparty/pear/archive_tar/tests/hamidTARtester2.tar b/gulliver/thirdparty/pear/archive_tar/tests/hamidTARtester2.tar deleted file mode 100644 index 0aefdbf62..000000000 Binary files a/gulliver/thirdparty/pear/archive_tar/tests/hamidTARtester2.tar and /dev/null differ diff --git a/gulliver/thirdparty/pear/archive_tar/tests/invalidblock.phpt b/gulliver/thirdparty/pear/archive_tar/tests/invalidblock.phpt deleted file mode 100644 index ddd114738..000000000 --- a/gulliver/thirdparty/pear/archive_tar/tests/invalidblock.phpt +++ /dev/null @@ -1,20 +0,0 @@ ---TEST-- -test files that happen to contain the endblock ---SKIPIF-- ---FILE-- -add(dirname(__FILE__) . '/testblock1'); -$tar->add(dirname(__FILE__) . '/testblock2'); -$tar = new Archive_Tar(dirname(__FILE__) . '/testblock.tar.gz'); -$tar->listContent(); -$phpunit->assertNoErrors('after'); -echo 'tests done'; -?> ---CLEAN-- - ---EXPECT-- -tests done diff --git a/gulliver/thirdparty/pear/archive_tar/tests/longfilename.phpt b/gulliver/thirdparty/pear/archive_tar/tests/longfilename.phpt deleted file mode 100644 index efbf17bed..000000000 --- a/gulliver/thirdparty/pear/archive_tar/tests/longfilename.phpt +++ /dev/null @@ -1,29 +0,0 @@ ---TEST-- -test trimming of characters in long filenames ---SKIPIF-- ---FILE-- -addModify(array($longfilename), '', dirname(__FILE__)); -$tar = new Archive_Tar(dirname(__FILE__) . '/testlongfilename.tar'); -$files = $tar->listContent(); -$file = reset($files); -$lastChar = $file['filename'][strlen($file['filename']) - 1]; -$phpunit->assertEquals(' ', $lastChar, 'should contain space as last character'); -echo 'tests done'; -?> ---CLEAN-- - ---EXPECT-- -tests done diff --git a/gulliver/thirdparty/pear/archive_tar/tests/pax.phpt b/gulliver/thirdparty/pear/archive_tar/tests/pax.phpt deleted file mode 100644 index b4ab6ad46..000000000 --- a/gulliver/thirdparty/pear/archive_tar/tests/pax.phpt +++ /dev/null @@ -1,13 +0,0 @@ ---TEST-- -tests if pax global / extended headers are ignored ---SKIPIF-- ---FILE-- -assertEquals(1, count($tar->listContent()), "count should be 1"); -echo 'tests done'; -?> ---CLEAN-- ---EXPECT-- -tests done diff --git a/gulliver/thirdparty/pear/archive_tar/tests/permissions.phpt b/gulliver/thirdparty/pear/archive_tar/tests/permissions.phpt deleted file mode 100644 index d27075080..000000000 --- a/gulliver/thirdparty/pear/archive_tar/tests/permissions.phpt +++ /dev/null @@ -1,18 +0,0 @@ ---TEST-- -test preserving of permissions ---SKIPIF-- ---FILE-- -extract('', true); -$phpunit->assertNoErrors('after'); -echo 'tests done'; -?> ---CLEAN-- - ---EXPECT-- -tests done diff --git a/gulliver/thirdparty/pear/archive_tar/tests/phpt_test.php.inc b/gulliver/thirdparty/pear/archive_tar/tests/phpt_test.php.inc deleted file mode 100644 index 67222e8df..000000000 --- a/gulliver/thirdparty/pear/archive_tar/tests/phpt_test.php.inc +++ /dev/null @@ -1,414 +0,0 @@ -_diffonly = $diffonly; - $this->_errors = array(); - PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($this, 'pearerrorCallback')); - if (!$noStackCatch) { - PEAR_ErrorStack::setDefaultCallback(array($this, 'pearerrorstackCallback')); - } - } - - function pearerrorCallback($err) - { - PEAR_ErrorStack::staticPush('PEAR_Error', -1, 'error', array('obj' => $err), - $err->getMessage()); - } - - function pearerrorstackCallback($err) - { - $this->_errors[] = $err; - } - - function assertPEARError($err, $message) - { - if (is_a($err, 'PEAR_Error')) { - return true; - } - $this->_failTest(debug_backtrace(), $message); - echo "Not a PEAR_Error\n"; - return false; - } - - function assertNoErrors($message, $trace = null) - { - if (count($this->_errors) == 0) { - return true; - } - if ($trace === null) { - $trace = debug_backtrace(); - } - $this->_failTest($trace, $message); - foreach ($this->_errors as $err) { - if ($err['package'] == 'PEAR_Error') { - echo "Unexpected PEAR_Error:\n"; - echo 'message "' . $err['message'] . "\"\n"; - } else { - echo "Unexpected PEAR_ErrorStack error:\n"; - echo 'package "' . $err['package'] . "\"\n"; - echo 'message "' . $err['message'] . "\"\n"; - } - } - $this->_errors = array(); - return false; - } - - function assertErrors($errors, $message, $trace = null) - { - if (!count($this->_errors)) { - if ($trace === null) { - $trace = debug_backtrace(); - } - $this->_failTest($trace, $message); - echo "No errors caught, but errors were expected\n"; - return false; - } - if (!isset($errors[0])) { - $errors = array($errors); - } - $failed = false; - foreach ($errors as $err) { - $found = false; - foreach ($this->_errors as $i => $caughterror) { - if ($caughterror['package'] == $err['package']) { - if ($caughterror['message'] == $err['message']) { - $found = true; - break; - } - } - } - if ($found) { - unset($this->_errors[$i]); - continue; - } - if (!$failed) { - if ($trace === null) { - $trace = debug_backtrace(); - } - $failed = true; - $this->_failTest($trace, $message); - } - echo "Unthrown error:\n"; - if ($err['package'] == 'PEAR_Error') { - echo "PEAR_Error:\n"; - } else { - echo "error package: \"$err[package]\"\n"; - } - echo "message: \"$err[message]\"\n"; - } - if (count($this->_errors)) { - if (!$failed) { - if ($trace === null) { - $trace = debug_backtrace(); - } - $failed = true; - $this->_failTest($trace, $message); - } - foreach ($this->_errors as $err) { - echo "Unexpected error:\n"; - if ($err['package'] == 'PEAR_Error') { - echo "PEAR_Error:\n"; - } else { - echo "error package: \"$err[package]\"\n"; - } - echo "message: \"$err[message]\"\n"; - } - } - $this->_errors = array(); - return !$failed; - } - - function assertTrue($test, $message) - { - $this->assertNoErrors($message, debug_backtrace()); - if ($test === true) { - return true; - } - $this->_failTest(debug_backtrace(), $message); - echo "Unexpected non-true value: \n"; - var_export($test); - echo "\n'$message'\n"; - return false; - } - - function assertIsa($control, $test, $message) - { - $this->assertNoErrors($message, debug_backtrace()); - if (is_a($test, $control)) { - return true; - } - $this->_failTest(debug_backtrace(), $message); - echo "Unexpected non-$control object: \n"; - var_export($test); - echo "\n'$message'\n"; - return false; - } - - function assertNull($test, $message) - { - $this->assertNoErrors($message, debug_backtrace()); - if ($test === null) { - return true; - } - $this->_failTest(debug_backtrace(), $message); - echo "Unexpected non-null value: \n"; - var_export($test); - echo "\n'$message'\n"; - return false; - } - - function assertNotNull($test, $message) - { - $this->assertNoErrors($message, debug_backtrace()); - if ($test !== null) { - return true; - } - $this->_failTest(debug_backtrace(), $message); - echo "Unexpected null: \n"; - var_export($test); - echo "\n'$message'\n"; - return false; - } - - function assertSame($test, $test1, $message) - { - $this->assertNoErrors($message, debug_backtrace()); - if ($test === $test1) { - return true; - } - $this->_failTest(debug_backtrace(), $message); - echo "Unexpectedly two vars are not the same thing: \n"; - echo "\n'$message'\n"; - return false; - } - - function assertNotSame($test, $test1, $message) - { - $this->assertNoErrors($message, debug_backtrace()); - if ($test !== $test1) { - return true; - } - $this->_failTest(debug_backtrace(), $message); - echo "Unexpectedly two vars are the same thing: \n"; - echo "\n'$message'\n"; - return false; - } - - function assertFalse($test, $message) - { - $this->assertNoErrors($message, debug_backtrace()); - if ($test === false) { - return true; - } - $this->_failTest(debug_backtrace(), $message); - echo "Unexpected non-false value: \n"; - var_export($test); - echo "\n'$message'\n"; - return false; - } - - function assertNotTrue($test, $message) - { - $this->assertNoErrors($message, debug_backtrace()); - if (!$test) { - return true; - } - $this->_failTest(debug_backtrace(), $message); - echo "Unexpected loose true value: \n"; - var_export($test); - echo "\n'$message'\n"; - return false; - } - - function assertNotFalse($test, $message) - { - $this->assertNoErrors($message, debug_backtrace()); - if ($test) { - return true; - } - $this->_failTest(debug_backtrace(), $message); - echo "Unexpected loose false value: \n"; - var_export($test); - echo "\n'$message'\n"; - return false; - } - - function assertEquals($control, $test, $message) - { - $this->assertNoErrors($message, debug_backtrace()); - if (str_replace(array("\r", "\n"), array('', ''), - var_export($control, true)) != str_replace(array("\r", "\n"), array('', ''), - var_export($test, true))) { - $this->_failTest(debug_backtrace(), $message); - if (class_exists('Text_Diff')) { - echo "Diff of expecting/received:\n"; - $diff = new Text_Diff( - explode("\n", var_export($control, true)), - explode("\n", var_export($test, true))); - - // Output the diff in unified format. - $renderer = new Text_Diff_Renderer_unified(); - echo $renderer->render($diff); - if ($this->_diffonly) { - return false; - } - } - echo "Expecting:\n"; - var_export($control); - echo "\nReceived:\n"; - var_export($test); - echo "\n"; - return false; - } - return true; - } - - function assertFileExists($fname, $message) - { - $this->assertNoErrors($message, debug_backtrace()); - if (!@file_exists($fname)) { - $this->_failTest(debug_backtrace(), $message); - echo "File '$fname' does not exist, and should\n"; - return false; - } - return true; - } - - function assertFileNotExists($fname, $message) - { - $this->assertNoErrors($message, debug_backtrace()); - if (@file_exists($fname)) { - $this->_failTest(debug_backtrace(), $message); - echo "File '$fname' exists, and should not\n"; - return false; - } - return true; - } - - function assertRegEquals($dump, &$reg, $message) - { - $actualdump = var_export(trim($this->dumpReg($reg)), true); - $testdump = var_export(trim($dump), true); - return $this->assertEquals($testdump, $actualdump, $message); - } - - function assertPackageInfoEquals($control, $test, $message) - { - $this->assertNoErrors($message, debug_backtrace()); - if (isset($control[0])) { - if (!isset($test[0]) || (count($control) != count($test))) { - echo "Invalid packageInfo\n"; - $ret = $this->assertEquals($control, $test, $message); - } - $ret = true; - foreach ($control as $i => $packageinfo) { - $ret = $ret && - $this->assertPackageInfoEquals($packageinfo, $test[$i], $message . $i); - } - return $ret; - } - if (isset($control['_lastmodified'])) { - if (!isset($test['_lastmodified'])) { - echo "_lastmodified is not set in packageInfo() output\n"; - $this->_failTest(debug_backtrace(), $message); - return false; - } - } - $savecontrol = sort($control); - $savetest = sort($test); - unset($control['_lastmodified']); - unset($test['_lastmodified']); - if (var_export($control, true) != var_export($test, true)) { - $this->_failTest(debug_backtrace(), $message); - if (class_exists('Text_Diff')) { - echo "Diff of expecting/received:\n"; - $diff = new Text_Diff( - explode("\n", var_export($control, true)), - explode("\n", var_export($test, true))); - - // Output the diff in unified format. - $renderer = new Text_Diff_Renderer_unified(); - echo $renderer->render($diff); - if ($this->_diffonly) { - return false; - } - } - echo "Expecting:\n"; - var_export($savecontrol); - echo "\nReceived:\n"; - var_export($savetest); - return false; - } - return true; - } - - function _sortRegEntries($a, $b) - { - return strnatcasecmp($a['name'], $b['name']); - } - - function dumpReg(&$reg) - { - ob_start(); - print "dumping registry...\n"; - $infos = $reg->packageInfo(null, null, null); - ksort($infos); - foreach ($infos as $channel => $info) { - echo "channel $channel:\n"; - usort($info, array($this, '_sortRegEntries')); - foreach ($info as $pkg) { - print $pkg["name"] . ":"; - unset($pkg["name"]); - foreach ($pkg as $k => $v) { - if ($k == '_lastmodified') { - print " _lastmodified is set"; - continue; - } - if (is_array($v) && $k == 'filelist') { - print " $k=array("; - $i = 0; - foreach ($v as $k2 => $v2) { - if ($i++ > 0) print ","; - print "{$k2}["; - $j = 0; - foreach ($v2 as $k3 => $v3) { - if ($j++ > 0) print ","; - print "$k3=$v3"; - } - print "]"; - } - print ")"; - } else { - print " $k=\"$v\""; - } - } - print "\n"; - } - } - print "dump done\n"; - $ret = ob_get_contents(); - ob_end_clean(); - return $ret; - } - - function _failTest($trace, $message) - { - echo 'Test Failure: "' . $message . "\"\n in " . $trace[0]['file'] . ' line ' . - $trace[0]['line'] . "\n"; - } - - function showAll() - { - $this->_diffonly = false; - } -} -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/archive_tar/tests/setup.php.inc b/gulliver/thirdparty/pear/archive_tar/tests/setup.php.inc deleted file mode 100644 index b2415a906..000000000 --- a/gulliver/thirdparty/pear/archive_tar/tests/setup.php.inc +++ /dev/null @@ -1,4 +0,0 @@ -extract(); -$phpunit->assertNoErrors('after'); -$phpunit->assertFileExists('testme', 'dir'); -$phpunit->assertFileExists('testme/file1.txt', 'file1.txt'); -$phpunit->assertFileExists('testme/symlink.txt', 'symlink.txt'); -$phpunit->assertTrue(is_link('testme/symlink.txt'), 'is link'); -echo 'tests done'; -?> ---CLEAN-- - ---EXPECT-- -tests done diff --git a/gulliver/thirdparty/pear/archive_tar/tests/testblock1/a.txt b/gulliver/thirdparty/pear/archive_tar/tests/testblock1/a.txt deleted file mode 100644 index 8baef1b4a..000000000 --- a/gulliver/thirdparty/pear/archive_tar/tests/testblock1/a.txt +++ /dev/null @@ -1 +0,0 @@ -abc diff --git a/gulliver/thirdparty/pear/archive_tar/tests/testblock1/bugTriggeringPng.png b/gulliver/thirdparty/pear/archive_tar/tests/testblock1/bugTriggeringPng.png deleted file mode 100644 index f68f74e6e..000000000 Binary files a/gulliver/thirdparty/pear/archive_tar/tests/testblock1/bugTriggeringPng.png and /dev/null differ diff --git a/gulliver/thirdparty/pear/archive_tar/tests/testblock2/.gitignore b/gulliver/thirdparty/pear/archive_tar/tests/testblock2/.gitignore deleted file mode 100644 index e69de29bb..000000000 diff --git a/gulliver/thirdparty/pear/archive_tar/tests/testpax.tar b/gulliver/thirdparty/pear/archive_tar/tests/testpax.tar deleted file mode 100644 index 2c8a62589..000000000 Binary files a/gulliver/thirdparty/pear/archive_tar/tests/testpax.tar and /dev/null differ diff --git a/gulliver/thirdparty/pear/archive_tar/tests/testperms.tar b/gulliver/thirdparty/pear/archive_tar/tests/testperms.tar deleted file mode 100644 index 01349e865..000000000 Binary files a/gulliver/thirdparty/pear/archive_tar/tests/testperms.tar and /dev/null differ diff --git a/gulliver/thirdparty/pear/archive_tar/tests/testsymlink.tar b/gulliver/thirdparty/pear/archive_tar/tests/testsymlink.tar deleted file mode 100644 index 984c4251b..000000000 Binary files a/gulliver/thirdparty/pear/archive_tar/tests/testsymlink.tar and /dev/null differ diff --git a/gulliver/thirdparty/pear/catalog b/gulliver/thirdparty/pear/catalog deleted file mode 100644 index 6e0c69d40..000000000 --- a/gulliver/thirdparty/pear/catalog +++ /dev/null @@ -1 +0,0 @@ -PUBLIC "-//PHP Group//DTD PEAR Package 1.0//EN//XML" "package.dtd" diff --git a/gulliver/thirdparty/pear/class.nusoap_base.php b/gulliver/thirdparty/pear/class.nusoap_base.php deleted file mode 100644 index 332348b37..000000000 --- a/gulliver/thirdparty/pear/class.nusoap_base.php +++ /dev/null @@ -1,905 +0,0 @@ -globalDebugLevel = 9; - -/** -* -* nusoap_base -* -* @author Dietrich Ayala -* @version $Id: class.nusoap_base.php,v 1.43 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class nusoap_base { - /** - * Identification for HTTP headers. - * - * @var string - * @access private - */ - var $title = 'NuSOAP'; - /** - * Version for HTTP headers. - * - * @var string - * @access private - */ - var $version = '0.7.2'; - /** - * CVS revision for HTTP headers. - * - * @var string - * @access private - */ - var $revision = '$Revision: 1.43 $'; - /** - * Current error string (manipulated by getError/setError) - * - * @var string - * @access private - */ - var $error_str = ''; - /** - * Current debug string (manipulated by debug/appendDebug/clearDebug/getDebug/getDebugAsXMLComment) - * - * @var string - * @access private - */ - var $debug_str = ''; - /** - * toggles automatic encoding of special characters as entities - * (should always be true, I think) - * - * @var boolean - * @access private - */ - var $charencoding = true; - /** - * the debug level for this instance - * - * @var integer - * @access private - */ - var $debugLevel; - - /** - * set schema version - * - * @var string - * @access public - */ - var $XMLSchemaVersion = 'http://www.w3.org/2001/XMLSchema'; - - /** - * charset encoding for outgoing messages - * - * @var string - * @access public - */ - var $soap_defencoding = 'ISO-8859-1'; - //var $soap_defencoding = 'UTF-8'; - - /** - * namespaces in an array of prefix => uri - * - * this is "seeded" by a set of constants, but it may be altered by code - * - * @var array - * @access public - */ - var $namespaces = array( - 'SOAP-ENV' => 'http://schemas.xmlsoap.org/soap/envelope/', - 'xsd' => 'http://www.w3.org/2001/XMLSchema', - 'xsi' => 'http://www.w3.org/2001/XMLSchema-instance', - 'SOAP-ENC' => 'http://schemas.xmlsoap.org/soap/encoding/' - ); - - /** - * namespaces used in the current context, e.g. during serialization - * - * @var array - * @access private - */ - var $usedNamespaces = array(); - - /** - * XML Schema types in an array of uri => (array of xml type => php type) - * is this legacy yet? - * no, this is used by the xmlschema class to verify type => namespace mappings. - * @var array - * @access public - */ - var $typemap = array( - 'http://www.w3.org/2001/XMLSchema' => array( - 'string'=>'string','boolean'=>'boolean','float'=>'double','double'=>'double','decimal'=>'double', - 'duration'=>'','dateTime'=>'string','time'=>'string','date'=>'string','gYearMonth'=>'', - 'gYear'=>'','gMonthDay'=>'','gDay'=>'','gMonth'=>'','hexBinary'=>'string','base64Binary'=>'string', - // abstract "any" types - 'anyType'=>'string','anySimpleType'=>'string', - // derived datatypes - 'normalizedString'=>'string','token'=>'string','language'=>'','NMTOKEN'=>'','NMTOKENS'=>'','Name'=>'','NCName'=>'','ID'=>'', - 'IDREF'=>'','IDREFS'=>'','ENTITY'=>'','ENTITIES'=>'','integer'=>'integer','nonPositiveInteger'=>'integer', - 'negativeInteger'=>'integer','long'=>'integer','int'=>'integer','short'=>'integer','byte'=>'integer','nonNegativeInteger'=>'integer', - 'unsignedLong'=>'','unsignedInt'=>'','unsignedShort'=>'','unsignedByte'=>'','positiveInteger'=>''), - 'http://www.w3.org/2000/10/XMLSchema' => array( - 'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double', - 'float'=>'double','dateTime'=>'string', - 'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'), - 'http://www.w3.org/1999/XMLSchema' => array( - 'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double', - 'float'=>'double','dateTime'=>'string', - 'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'), - 'http://soapinterop.org/xsd' => array('SOAPStruct'=>'struct'), - 'http://schemas.xmlsoap.org/soap/encoding/' => array('base64'=>'string','array'=>'array','Array'=>'array'), - 'http://xml.apache.org/xml-soap' => array('Map') - ); - - /** - * XML entities to convert - * - * @var array - * @access public - * @deprecated - * @see expandEntities - */ - var $xmlEntities = array('quot' => '"','amp' => '&', - 'lt' => '<','gt' => '>','apos' => "'"); - - /** - * constructor - * - * @access public - */ - function nusoap_base() { - $this->debugLevel = $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel; - } - - /** - * gets the global debug level, which applies to future instances - * - * @return integer Debug level 0-9, where 0 turns off - * @access public - */ - function getGlobalDebugLevel() { - return $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel; - } - - /** - * sets the global debug level, which applies to future instances - * - * @param int $level Debug level 0-9, where 0 turns off - * @access public - */ - function setGlobalDebugLevel($level) { - $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel = $level; - } - - /** - * gets the debug level for this instance - * - * @return int Debug level 0-9, where 0 turns off - * @access public - */ - function getDebugLevel() { - return $this->debugLevel; - } - - /** - * sets the debug level for this instance - * - * @param int $level Debug level 0-9, where 0 turns off - * @access public - */ - function setDebugLevel($level) { - $this->debugLevel = $level; - } - - /** - * adds debug data to the instance debug string with formatting - * - * @param string $string debug data - * @access private - */ - function debug($string){ - if ($this->debugLevel > 0) { - $this->appendDebug($this->getmicrotime().' '.get_class($this).": $string\n"); - } - } - - /** - * adds debug data to the instance debug string without formatting - * - * @param string $string debug data - * @access public - */ - function appendDebug($string){ - if ($this->debugLevel > 0) { - // it would be nice to use a memory stream here to use - // memory more efficiently - $this->debug_str .= $string; - } - } - - /** - * clears the current debug data for this instance - * - * @access public - */ - function clearDebug() { - // it would be nice to use a memory stream here to use - // memory more efficiently - $this->debug_str = ''; - } - - /** - * gets the current debug data for this instance - * - * @return debug data - * @access public - */ - function &getDebug() { - // it would be nice to use a memory stream here to use - // memory more efficiently - return $this->debug_str; - } - - /** - * gets the current debug data for this instance as an XML comment - * this may change the contents of the debug data - * - * @return debug data as an XML comment - * @access public - */ - function &getDebugAsXMLComment() { - // it would be nice to use a memory stream here to use - // memory more efficiently - while (strpos($this->debug_str, '--')) { - $this->debug_str = str_replace('--', '- -', $this->debug_str); - } - return ""; - } - - /** - * expands entities, e.g. changes '<' to '<'. - * - * @param string $val The string in which to expand entities. - * @access private - */ - function expandEntities($val) { - if ($this->charencoding) { - $val = str_replace('&', '&', $val); - $val = str_replace("'", ''', $val); - $val = str_replace('"', '"', $val); - $val = str_replace('<', '<', $val); - $val = str_replace('>', '>', $val); - } - return $val; - } - - /** - * returns error string if present - * - * @return mixed error string or false - * @access public - */ - function getError(){ - if($this->error_str != ''){ - return $this->error_str; - } - return false; - } - - /** - * sets error string - * - * @return boolean $string error string - * @access private - */ - function setError($str){ - $this->error_str = $str; - } - - /** - * detect if array is a simple array or a struct (associative array) - * - * @param mixed $val The PHP array - * @return string (arraySimple|arrayStruct) - * @access private - */ - function isArraySimpleOrStruct($val) { - $keyList = array_keys($val); - foreach ($keyList as $keyListValue) { - if (!is_int($keyListValue)) { - return 'arrayStruct'; - } - } - return 'arraySimple'; - } - - /** - * serializes PHP values in accordance w/ section 5. Type information is - * not serialized if $use == 'literal'. - * - * @param mixed $val The value to serialize - * @param string $name The name (local part) of the XML element - * @param string $type The XML schema type (local part) for the element - * @param string $name_ns The namespace for the name of the XML element - * @param string $type_ns The namespace for the type of the element - * @param array $attributes The attributes to serialize as name=>value pairs - * @param string $use The WSDL "use" (encoded|literal) - * @return string The serialized element, possibly with child elements - * @access public - */ - function serialize_val($val,$name=false,$type=false,$name_ns=false,$type_ns=false,$attributes=false,$use='encoded'){ - $this->debug("in serialize_val: name=$name, type=$type, name_ns=$name_ns, type_ns=$type_ns, use=$use"); - $this->appendDebug('value=' . $this->varDump($val)); - $this->appendDebug('attributes=' . $this->varDump($attributes)); - - if(is_object($val) && get_class($val) == 'soapval'){ - return $val->serialize($use); - } - // force valid name if necessary - if (is_numeric($name)) { - $name = '__numeric_' . $name; - } elseif (! $name) { - $name = 'noname'; - } - // if name has ns, add ns prefix to name - $xmlns = ''; - if($name_ns){ - $prefix = 'nu'.rand(1000,9999); - $name = $prefix.':'.$name; - $xmlns .= " xmlns:$prefix=\"$name_ns\""; - } - // if type is prefixed, create type prefix - if($type_ns != '' && $type_ns == $this->namespaces['xsd']){ - // need to fix this. shouldn't default to xsd if no ns specified - // w/o checking against typemap - $type_prefix = 'xsd'; - } elseif($type_ns){ - $type_prefix = 'ns'.rand(1000,9999); - $xmlns .= " xmlns:$type_prefix=\"$type_ns\""; - } - // serialize attributes if present - $atts = ''; - if($attributes){ - foreach($attributes as $k => $v){ - $atts .= " $k=\"".$this->expandEntities($v).'"'; - } - } - // serialize null value - if (is_null($val)) { - if ($use == 'literal') { - // TODO: depends on minOccurs - return "<$name$xmlns $atts/>"; - } else { - if (isset($type) && isset($type_prefix)) { - $type_str = " xsi:type=\"$type_prefix:$type\""; - } else { - $type_str = ''; - } - return "<$name$xmlns$type_str $atts xsi:nil=\"true\"/>"; - } - } - // serialize if an xsd built-in primitive type - if($type != '' && isset($this->typemap[$this->XMLSchemaVersion][$type])){ - if (is_bool($val)) { - if ($type == 'boolean') { - $val = $val ? 'true' : 'false'; - } elseif (! $val) { - $val = 0; - } - } else if (is_string($val)) { - $val = $this->expandEntities($val); - } - if ($use == 'literal') { - return "<$name$xmlns $atts>$val"; - } else { - return "<$name$xmlns $atts xsi:type=\"xsd:$type\">$val"; - } - } - // detect type and serialize - $xml = ''; - switch(true) { - case (is_bool($val) || $type == 'boolean'): - if ($type == 'boolean') { - $val = $val ? 'true' : 'false'; - } elseif (! $val) { - $val = 0; - } - if ($use == 'literal') { - $xml .= "<$name$xmlns $atts>$val"; - } else { - $xml .= "<$name$xmlns xsi:type=\"xsd:boolean\"$atts>$val"; - } - break; - case (is_int($val) || is_long($val) || $type == 'int'): - if ($use == 'literal') { - $xml .= "<$name$xmlns $atts>$val"; - } else { - $xml .= "<$name$xmlns xsi:type=\"xsd:int\"$atts>$val"; - } - break; - case (is_float($val)|| is_double($val) || $type == 'float'): - if ($use == 'literal') { - $xml .= "<$name$xmlns $atts>$val"; - } else { - $xml .= "<$name$xmlns xsi:type=\"xsd:float\"$atts>$val"; - } - break; - case (is_string($val) || $type == 'string'): - $val = $this->expandEntities($val); - if ($use == 'literal') { - $xml .= "<$name$xmlns $atts>$val"; - } else { - $xml .= "<$name$xmlns xsi:type=\"xsd:string\"$atts>$val"; - } - break; - case is_object($val): - if (! $name) { - $name = get_class($val); - $this->debug("In serialize_val, used class name $name as element name"); - } else { - $this->debug("In serialize_val, do not override name $name for element name for class " . get_class($val)); - } - foreach(get_object_vars($val) as $k => $v){ - $pXml = isset($pXml) ? $pXml.$this->serialize_val($v,$k,false,false,false,false,$use) : $this->serialize_val($v,$k,false,false,false,false,$use); - } - $xml .= '<'.$name.'>'.$pXml.''; - break; - break; - case (is_array($val) || $type): - // detect if struct or array - $valueType = $this->isArraySimpleOrStruct($val); - if($valueType=='arraySimple' || ereg('^ArrayOf',$type)){ - $i = 0; - if(is_array($val) && count($val)> 0){ - foreach($val as $v){ - if(is_object($v) && get_class($v) == 'soapval'){ - $tt_ns = $v->type_ns; - $tt = $v->type; - } elseif (is_array($v)) { - $tt = $this->isArraySimpleOrStruct($v); - } else { - $tt = gettype($v); - } - $array_types[$tt] = 1; - // TODO: for literal, the name should be $name - $xml .= $this->serialize_val($v,'item',false,false,false,false,$use); - ++$i; - } - if(count($array_types) > 1){ - $array_typename = 'xsd:anyType'; - } elseif(isset($tt) && isset($this->typemap[$this->XMLSchemaVersion][$tt])) { - if ($tt == 'integer') { - $tt = 'int'; - } - $array_typename = 'xsd:'.$tt; - } elseif(isset($tt) && $tt == 'arraySimple'){ - $array_typename = 'SOAP-ENC:Array'; - } elseif(isset($tt) && $tt == 'arrayStruct'){ - $array_typename = 'unnamed_struct_use_soapval'; - } else { - // if type is prefixed, create type prefix - if ($tt_ns != '' && $tt_ns == $this->namespaces['xsd']){ - $array_typename = 'xsd:' . $tt; - } elseif ($tt_ns) { - $tt_prefix = 'ns' . rand(1000, 9999); - $array_typename = "$tt_prefix:$tt"; - $xmlns .= " xmlns:$tt_prefix=\"$tt_ns\""; - } else { - $array_typename = $tt; - } - } - $array_type = $i; - if ($use == 'literal') { - $type_str = ''; - } else if (isset($type) && isset($type_prefix)) { - $type_str = " xsi:type=\"$type_prefix:$type\""; - } else { - $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"".$array_typename."[$array_type]\""; - } - // empty array - } else { - if ($use == 'literal') { - $type_str = ''; - } else if (isset($type) && isset($type_prefix)) { - $type_str = " xsi:type=\"$type_prefix:$type\""; - } else { - $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"xsd:anyType[0]\""; - } - } - // TODO: for array in literal, there is no wrapper here - $xml = "<$name$xmlns$type_str$atts>".$xml.""; - } else { - // got a struct - if(isset($type) && isset($type_prefix)){ - $type_str = " xsi:type=\"$type_prefix:$type\""; - } else { - $type_str = ''; - } - if ($use == 'literal') { - $xml .= "<$name$xmlns $atts>"; - } else { - $xml .= "<$name$xmlns$type_str$atts>"; - } - foreach($val as $k => $v){ - // Apache Map - if ($type == 'Map' && $type_ns == 'http://xml.apache.org/xml-soap') { - $xml .= ''; - $xml .= $this->serialize_val($k,'key',false,false,false,false,$use); - $xml .= $this->serialize_val($v,'value',false,false,false,false,$use); - $xml .= ''; - } else { - $xml .= $this->serialize_val($v,$k,false,false,false,false,$use); - } - } - $xml .= ""; - } - break; - default: - $xml .= 'not detected, got '.gettype($val).' for '.$val; - break; - } - return $xml; - } - - /** - * serializes a message - * - * @param string $body the XML of the SOAP body - * @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers - * @param array $namespaces optional the namespaces used in generating the body and headers - * @param string $style optional (rpc|document) - * @param string $use optional (encoded|literal) - * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded) - * @return string the message - * @access public - */ - function serializeEnvelope($body,$headers=false,$namespaces=array(),$style='rpc',$use='encoded',$encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'){ - // TODO: add an option to automatically run utf8_encode on $body and $headers - // if $this->soap_defencoding is UTF-8. Not doing this automatically allows - // one to send arbitrary UTF-8 characters, not just characters that map to ISO-8859-1 - - $this->debug("In serializeEnvelope length=" . strlen($body) . " body (max 1000 characters)=" . substr($body, 0, 1000) . " style=$style use=$use encodingStyle=$encodingStyle"); - $this->debug("headers:"); - $this->appendDebug($this->varDump($headers)); - $this->debug("namespaces:"); - $this->appendDebug($this->varDump($namespaces)); - - // serialize namespaces - $ns_string = ''; - foreach(array_merge($this->namespaces,$namespaces) as $k => $v){ - $ns_string .= " xmlns:$k=\"$v\""; - } - if($encodingStyle) { - $ns_string = " SOAP-ENV:encodingStyle=\"$encodingStyle\"$ns_string"; - } - - // serialize headers - if($headers){ - if (is_array($headers)) { - $xml = ''; - foreach ($headers as $header) { - $xml .= $this->serialize_val($header, false, false, false, false, false, $use); - } - $headers = $xml; - $this->debug("In serializeEnvelope, serialzied array of headers to $headers"); - } - $headers = "".$headers.""; - } - // serialize envelope - return - 'soap_defencoding .'"?'.">". - '". - $headers. - "". - $body. - "". - ""; - } - - /** - * formats a string to be inserted into an HTML stream - * - * @param string $str The string to format - * @return string The formatted string - * @access public - * @deprecated - */ - function formatDump($str){ - $str = htmlspecialchars($str); - return nl2br($str); - } - - /** - * contracts (changes namespace to prefix) a qualified name - * - * @param string $qname qname - * @return string contracted qname - * @access private - */ - function contractQname($qname){ - // get element namespace - //$this->xdebug("Contract $qname"); - if (strrpos($qname, ':')) { - // get unqualified name - $name = substr($qname, strrpos($qname, ':') + 1); - // get ns - $ns = substr($qname, 0, strrpos($qname, ':')); - $p = $this->getPrefixFromNamespace($ns); - if ($p) { - return $p . ':' . $name; - } - return $qname; - } else { - return $qname; - } - } - - /** - * expands (changes prefix to namespace) a qualified name - * - * @param string $string qname - * @return string expanded qname - * @access private - */ - function expandQname($qname){ - // get element prefix - if(strpos($qname,':') && !ereg('^http://',$qname)){ - // get unqualified name - $name = substr(strstr($qname,':'),1); - // get ns prefix - $prefix = substr($qname,0,strpos($qname,':')); - if(isset($this->namespaces[$prefix])){ - return $this->namespaces[$prefix].':'.$name; - } else { - return $qname; - } - } else { - return $qname; - } - } - - /** - * returns the local part of a prefixed string - * returns the original string, if not prefixed - * - * @param string $str The prefixed string - * @return string The local part - * @access public - */ - function getLocalPart($str){ - if($sstr = strrchr($str,':')){ - // get unqualified name - return substr( $sstr, 1 ); - } else { - return $str; - } - } - - /** - * returns the prefix part of a prefixed string - * returns false, if not prefixed - * - * @param string $str The prefixed string - * @return mixed The prefix or false if there is no prefix - * @access public - */ - function getPrefix($str){ - if($pos = strrpos($str,':')){ - // get prefix - return substr($str,0,$pos); - } - return false; - } - - /** - * pass it a prefix, it returns a namespace - * - * @param string $prefix The prefix - * @return mixed The namespace, false if no namespace has the specified prefix - * @access public - */ - function getNamespaceFromPrefix($prefix){ - if (isset($this->namespaces[$prefix])) { - return $this->namespaces[$prefix]; - } - //$this->setError("No namespace registered for prefix '$prefix'"); - return false; - } - - /** - * returns the prefix for a given namespace (or prefix) - * or false if no prefixes registered for the given namespace - * - * @param string $ns The namespace - * @return mixed The prefix, false if the namespace has no prefixes - * @access public - */ - function getPrefixFromNamespace($ns) { - foreach ($this->namespaces as $p => $n) { - if ($ns == $n || $ns == $p) { - $this->usedNamespaces[$p] = $n; - return $p; - } - } - return false; - } - - /** - * returns the time in ODBC canonical form with microseconds - * - * @return string The time in ODBC canonical form with microseconds - * @access public - */ - function getmicrotime() { - if (function_exists('gettimeofday')) { - $tod = gettimeofday(); - $sec = $tod['sec']; - $usec = $tod['usec']; - } else { - $sec = time(); - $usec = 0; - } - return strftime('%Y-%m-%d %H:%M:%S', $sec) . '.' . sprintf('%06d', $usec); - } - - /** - * Returns a string with the output of var_dump - * - * @param mixed $data The variable to var_dump - * @return string The output of var_dump - * @access public - */ - function varDump($data) { - ob_start(); - var_dump($data); - $ret_val = ob_get_contents(); - ob_end_clean(); - return $ret_val; - } -} - -// XML Schema Datatype Helper Functions - -//xsd:dateTime helpers - -/** -* convert unix timestamp to ISO 8601 compliant date string -* -* @param string $timestamp Unix time stamp -* @access public -*/ -function timestamp_to_iso8601($timestamp,$utc=true){ - $datestr = date('Y-m-d\TH:i:sO',$timestamp); - if($utc){ - $eregStr = - '([0-9]{4})-'. // centuries & years CCYY- - '([0-9]{2})-'. // months MM- - '([0-9]{2})'. // days DD - 'T'. // separator T - '([0-9]{2}):'. // hours hh: - '([0-9]{2}):'. // minutes mm: - '([0-9]{2})(\.[0-9]*)?'. // seconds ss.ss... - '(Z|[+\-][0-9]{2}:?[0-9]{2})?'; // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's - - if(ereg($eregStr,$datestr,$regs)){ - return sprintf('%04d-%02d-%02dT%02d:%02d:%02dZ',$regs[1],$regs[2],$regs[3],$regs[4],$regs[5],$regs[6]); - } - return false; - } else { - return $datestr; - } -} - -/** -* convert ISO 8601 compliant date string to unix timestamp -* -* @param string $datestr ISO 8601 compliant date string -* @access public -*/ -function iso8601_to_timestamp($datestr){ - $eregStr = - '([0-9]{4})-'. // centuries & years CCYY- - '([0-9]{2})-'. // months MM- - '([0-9]{2})'. // days DD - 'T'. // separator T - '([0-9]{2}):'. // hours hh: - '([0-9]{2}):'. // minutes mm: - '([0-9]{2})(\.[0-9]+)?'. // seconds ss.ss... - '(Z|[+\-][0-9]{2}:?[0-9]{2})?'; // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's - if(ereg($eregStr,$datestr,$regs)){ - // not utc - if($regs[8] != 'Z'){ - $op = substr($regs[8],0,1); - $h = substr($regs[8],1,2); - $m = substr($regs[8],strlen($regs[8])-2,2); - if($op == '-'){ - $regs[4] = $regs[4] + $h; - $regs[5] = $regs[5] + $m; - } elseif($op == '+'){ - $regs[4] = $regs[4] - $h; - $regs[5] = $regs[5] - $m; - } - } - return strtotime("$regs[1]-$regs[2]-$regs[3] $regs[4]:$regs[5]:$regs[6]Z"); - } else { - return false; - } -} - -/** -* sleeps some number of microseconds -* -* @param string $usec the number of microseconds to sleep -* @access public -* @deprecated -*/ -function usleepWindows($usec) -{ - $start = gettimeofday(); - - do - { - $stop = gettimeofday(); - $timePassed = 1000000 * ($stop['sec'] - $start['sec']) - + $stop['usec'] - $start['usec']; - } - while ($timePassed < $usec); -} - - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/class.soap_fault.php b/gulliver/thirdparty/pear/class.soap_fault.php deleted file mode 100644 index 139d375dd..000000000 --- a/gulliver/thirdparty/pear/class.soap_fault.php +++ /dev/null @@ -1,86 +0,0 @@ - -* @version $Id: class.soap_fault.php,v 1.12 2005/07/27 19:24:42 snichol Exp $ -* @access public -*/ -class soap_fault extends nusoap_base { - /** - * The fault code (client|server) - * @var string - * @access private - */ - var $faultcode; - /** - * The fault actor - * @var string - * @access private - */ - var $faultactor; - /** - * The fault string, a description of the fault - * @var string - * @access private - */ - var $faultstring; - /** - * The fault detail, typically a string or array of string - * @var mixed - * @access private - */ - var $faultdetail; - - /** - * constructor - * - * @param string $faultcode (client | server) - * @param string $faultactor only used when msg routed between multiple actors - * @param string $faultstring human readable error message - * @param mixed $faultdetail detail, typically a string or array of string - */ - function soap_fault($faultcode,$faultactor='',$faultstring='',$faultdetail=''){ - parent::nusoap_base(); - $this->faultcode = $faultcode; - $this->faultactor = $faultactor; - $this->faultstring = $faultstring; - $this->faultdetail = $faultdetail; - } - - /** - * serialize a fault - * - * @return string The serialization of the fault instance. - * @access public - */ - function serialize(){ - $ns_string = ''; - foreach($this->namespaces as $k => $v){ - $ns_string .= "\n xmlns:$k=\"$v\""; - } - $return_msg = - 'soap_defencoding.'"?>'. - '\n". - ''. - ''. - $this->serialize_val($this->faultcode, 'faultcode'). - $this->serialize_val($this->faultactor, 'faultactor'). - $this->serialize_val($this->faultstring, 'faultstring'). - $this->serialize_val($this->faultdetail, 'detail'). - ''. - ''. - ''; - return $return_msg; - } -} - - - - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/class.soap_parser.php b/gulliver/thirdparty/pear/class.soap_parser.php deleted file mode 100644 index 098d1582b..000000000 --- a/gulliver/thirdparty/pear/class.soap_parser.php +++ /dev/null @@ -1,599 +0,0 @@ - -* @version $Id: class.soap_parser.php,v 1.36 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class soap_parser extends nusoap_base { - - var $xml = ''; - var $xml_encoding = ''; - var $method = ''; - var $root_struct = ''; - var $root_struct_name = ''; - var $root_struct_namespace = ''; - var $root_header = ''; - var $document = ''; // incoming SOAP body (text) - // determines where in the message we are (envelope,header,body,method) - var $status = ''; - var $position = 0; - var $depth = 0; - var $default_namespace = ''; - var $namespaces = array(); - var $message = array(); - var $parent = ''; - var $fault = false; - var $fault_code = ''; - var $fault_str = ''; - var $fault_detail = ''; - var $depth_array = array(); - var $debug_flag = true; - var $soapresponse = NULL; - var $responseHeaders = ''; // incoming SOAP headers (text) - var $body_position = 0; - // for multiref parsing: - // array of id => pos - var $ids = array(); - // array of id => hrefs => pos - var $multirefs = array(); - // toggle for auto-decoding element content - var $decode_utf8 = true; - - /** - * constructor that actually does the parsing - * - * @param string $xml SOAP message - * @param string $encoding character encoding scheme of message - * @param string $method method for which XML is parsed (unused?) - * @param string $decode_utf8 whether to decode UTF-8 to ISO-8859-1 - * @access public - */ - function soap_parser($xml,$encoding='UTF-8',$method='',$decode_utf8=true){ - parent::nusoap_base(); - $this->xml = $xml; - $this->xml_encoding = $encoding; - $this->method = $method; - $this->decode_utf8 = $decode_utf8; - - // Check whether content has been read. - if(!empty($xml)){ - // Check XML encoding - $pos_xml = strpos($xml, '', $pos_xml + 2) - $pos_xml + 1); - if (preg_match("/encoding=[\"']([^\"']*)[\"']/", $xml_decl, $res)) { - $xml_encoding = $res[1]; - if (strtoupper($xml_encoding) != $encoding) { - $err = "Charset from HTTP Content-Type '" . $encoding . "' does not match encoding from XML declaration '" . $xml_encoding . "'"; - $this->debug($err); - if ($encoding != 'ISO-8859-1' || strtoupper($xml_encoding) != 'UTF-8') { - $this->setError($err); - return; - } - // when HTTP says ISO-8859-1 (the default) and XML says UTF-8 (the typical), assume the other endpoint is just sloppy and proceed - } else { - $this->debug('Charset from HTTP Content-Type matches encoding from XML declaration'); - } - } else { - $this->debug('No encoding specified in XML declaration'); - } - } else { - $this->debug('No XML declaration'); - } - $this->debug('Entering soap_parser(), length='.strlen($xml).', encoding='.$encoding); - // Create an XML parser - why not xml_parser_create_ns? - $this->parser = xml_parser_create($this->xml_encoding); - // Set the options for parsing the XML data. - //xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); - xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); - xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, $this->xml_encoding); - // Set the object for the parser. - xml_set_object($this->parser, $this); - // Set the element handlers for the parser. - xml_set_element_handler($this->parser, 'start_element','end_element'); - xml_set_character_data_handler($this->parser,'character_data'); - - // Parse the XML file. - if(!xml_parse($this->parser,$xml,true)){ - // Display an error message. - $err = sprintf('XML error parsing SOAP payload on line %d: %s', - xml_get_current_line_number($this->parser), - xml_error_string(xml_get_error_code($this->parser))); - $this->debug($err); - $this->debug("XML payload:\n" . $xml); - $this->setError($err); - } else { - $this->debug('parsed successfully, found root struct: '.$this->root_struct.' of name '.$this->root_struct_name); - // get final value - $this->soapresponse = $this->message[$this->root_struct]['result']; - // get header value: no, because this is documented as XML string -// if($this->root_header != '' && isset($this->message[$this->root_header]['result'])){ -// $this->responseHeaders = $this->message[$this->root_header]['result']; -// } - // resolve hrefs/ids - if(sizeof($this->multirefs) > 0){ - foreach($this->multirefs as $id => $hrefs){ - $this->debug('resolving multirefs for id: '.$id); - $idVal = $this->buildVal($this->ids[$id]); - if (is_array($idVal) && isset($idVal['!id'])) { - unset($idVal['!id']); - } - foreach($hrefs as $refPos => $ref){ - $this->debug('resolving href at pos '.$refPos); - $this->multirefs[$id][$refPos] = $idVal; - } - } - } - } - xml_parser_free($this->parser); - } else { - $this->debug('xml was empty, didn\'t parse!'); - $this->setError('xml was empty, didn\'t parse!'); - } - } - - /** - * start-element handler - * - * @param resource $parser XML parser object - * @param string $name element name - * @param array $attrs associative array of attributes - * @access private - */ - function start_element($parser, $name, $attrs) { - // position in a total number of elements, starting from 0 - // update class level pos - $pos = $this->position++; - // and set mine - $this->message[$pos] = array('pos' => $pos,'children'=>'','cdata'=>''); - // depth = how many levels removed from root? - // set mine as current global depth and increment global depth value - $this->message[$pos]['depth'] = $this->depth++; - - // else add self as child to whoever the current parent is - if($pos != 0){ - $this->message[$this->parent]['children'] .= '|'.$pos; - } - // set my parent - $this->message[$pos]['parent'] = $this->parent; - // set self as current parent - $this->parent = $pos; - // set self as current value for this depth - $this->depth_array[$this->depth] = $pos; - // get element prefix - if(strpos($name,':')){ - // get ns prefix - $prefix = substr($name,0,strpos($name,':')); - // get unqualified name - $name = substr(strstr($name,':'),1); - } - // set status - if($name == 'Envelope'){ - $this->status = 'envelope'; - } elseif($name == 'Header'){ - $this->root_header = $pos; - $this->status = 'header'; - } elseif($name == 'Body'){ - $this->status = 'body'; - $this->body_position = $pos; - // set method - } elseif($this->status == 'body' && $pos == ($this->body_position+1)){ - $this->status = 'method'; - $this->root_struct_name = $name; - $this->root_struct = $pos; - $this->message[$pos]['type'] = 'struct'; - $this->debug("found root struct $this->root_struct_name, pos $this->root_struct"); - } - // set my status - $this->message[$pos]['status'] = $this->status; - // set name - $this->message[$pos]['name'] = htmlspecialchars($name); - // set attrs - $this->message[$pos]['attrs'] = $attrs; - - // loop through atts, logging ns and type declarations - $attstr = ''; - foreach($attrs as $key => $value){ - $key_prefix = $this->getPrefix($key); - $key_localpart = $this->getLocalPart($key); - // if ns declarations, add to class level array of valid namespaces - if($key_prefix == 'xmlns'){ - if(ereg('^http://www.w3.org/[0-9]{4}/XMLSchema$',$value)){ - $this->XMLSchemaVersion = $value; - $this->namespaces['xsd'] = $this->XMLSchemaVersion; - $this->namespaces['xsi'] = $this->XMLSchemaVersion.'-instance'; - } - $this->namespaces[$key_localpart] = $value; - // set method namespace - if($name == $this->root_struct_name){ - $this->methodNamespace = $value; - } - // if it's a type declaration, set type - } elseif($key_localpart == 'type'){ - $value_prefix = $this->getPrefix($value); - $value_localpart = $this->getLocalPart($value); - $this->message[$pos]['type'] = $value_localpart; - $this->message[$pos]['typePrefix'] = $value_prefix; - if(isset($this->namespaces[$value_prefix])){ - $this->message[$pos]['type_namespace'] = $this->namespaces[$value_prefix]; - } else if(isset($attrs['xmlns:'.$value_prefix])) { - $this->message[$pos]['type_namespace'] = $attrs['xmlns:'.$value_prefix]; - } - // should do something here with the namespace of specified type? - } elseif($key_localpart == 'arrayType'){ - $this->message[$pos]['type'] = 'array'; - /* do arrayType ereg here - [1] arrayTypeValue ::= atype asize - [2] atype ::= QName rank* - [3] rank ::= '[' (',')* ']' - [4] asize ::= '[' length~ ']' - [5] length ::= nextDimension* Digit+ - [6] nextDimension ::= Digit+ ',' - */ - $expr = '([A-Za-z0-9_]+):([A-Za-z]+[A-Za-z0-9_]+)\[([0-9]+),?([0-9]*)\]'; - if(ereg($expr,$value,$regs)){ - $this->message[$pos]['typePrefix'] = $regs[1]; - $this->message[$pos]['arrayTypePrefix'] = $regs[1]; - if (isset($this->namespaces[$regs[1]])) { - $this->message[$pos]['arrayTypeNamespace'] = $this->namespaces[$regs[1]]; - } else if (isset($attrs['xmlns:'.$regs[1]])) { - $this->message[$pos]['arrayTypeNamespace'] = $attrs['xmlns:'.$regs[1]]; - } - $this->message[$pos]['arrayType'] = $regs[2]; - $this->message[$pos]['arraySize'] = $regs[3]; - $this->message[$pos]['arrayCols'] = $regs[4]; - } - // specifies nil value (or not) - } elseif ($key_localpart == 'nil'){ - $this->message[$pos]['nil'] = ($value == 'true' || $value == '1'); - // some other attribute - } elseif ($key != 'href' && $key != 'xmlns' && $key_localpart != 'encodingStyle' && $key_localpart != 'root') { - $this->message[$pos]['xattrs']['!' . $key] = $value; - } - - if ($key == 'xmlns') { - $this->default_namespace = $value; - } - // log id - if($key == 'id'){ - $this->ids[$value] = $pos; - } - // root - if($key_localpart == 'root' && $value == 1){ - $this->status = 'method'; - $this->root_struct_name = $name; - $this->root_struct = $pos; - $this->debug("found root struct $this->root_struct_name, pos $pos"); - } - // for doclit - $attstr .= " $key=\"$value\""; - } - // get namespace - must be done after namespace atts are processed - if(isset($prefix)){ - $this->message[$pos]['namespace'] = $this->namespaces[$prefix]; - $this->default_namespace = $this->namespaces[$prefix]; - } else { - $this->message[$pos]['namespace'] = $this->default_namespace; - } - if($this->status == 'header'){ - if ($this->root_header != $pos) { - $this->responseHeaders .= "<" . (isset($prefix) ? $prefix . ':' : '') . "$name$attstr>"; - } - } elseif($this->root_struct_name != ''){ - $this->document .= "<" . (isset($prefix) ? $prefix . ':' : '') . "$name$attstr>"; - } - } - - /** - * end-element handler - * - * @param resource $parser XML parser object - * @param string $name element name - * @access private - */ - function end_element($parser, $name) { - // position of current element is equal to the last value left in depth_array for my depth - $pos = $this->depth_array[$this->depth--]; - - // get element prefix - if(strpos($name,':')){ - // get ns prefix - $prefix = substr($name,0,strpos($name,':')); - // get unqualified name - $name = substr(strstr($name,':'),1); - } - - // build to native type - if(isset($this->body_position) && $pos > $this->body_position){ - // deal w/ multirefs - if(isset($this->message[$pos]['attrs']['href'])){ - // get id - $id = substr($this->message[$pos]['attrs']['href'],1); - // add placeholder to href array - $this->multirefs[$id][$pos] = 'placeholder'; - // add set a reference to it as the result value - $this->message[$pos]['result'] =& $this->multirefs[$id][$pos]; - // build complexType values - } elseif($this->message[$pos]['children'] != ''){ - // if result has already been generated (struct/array) - if(!isset($this->message[$pos]['result'])){ - $this->message[$pos]['result'] = $this->buildVal($pos); - } - // build complexType values of attributes and possibly simpleContent - } elseif (isset($this->message[$pos]['xattrs'])) { - if (isset($this->message[$pos]['nil']) && $this->message[$pos]['nil']) { - $this->message[$pos]['xattrs']['!'] = null; - } elseif (isset($this->message[$pos]['cdata']) && trim($this->message[$pos]['cdata']) != '') { - if (isset($this->message[$pos]['type'])) { - $this->message[$pos]['xattrs']['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : ''); - } else { - $parent = $this->message[$pos]['parent']; - if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) { - $this->message[$pos]['xattrs']['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : ''); - } else { - $this->message[$pos]['xattrs']['!'] = $this->message[$pos]['cdata']; - } - } - } - $this->message[$pos]['result'] = $this->message[$pos]['xattrs']; - // set value of simpleType (or nil complexType) - } else { - //$this->debug('adding data for scalar value '.$this->message[$pos]['name'].' of value '.$this->message[$pos]['cdata']); - if (isset($this->message[$pos]['nil']) && $this->message[$pos]['nil']) { - $this->message[$pos]['xattrs']['!'] = null; - } elseif (isset($this->message[$pos]['type'])) { - $this->message[$pos]['result'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : ''); - } else { - $parent = $this->message[$pos]['parent']; - if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) { - $this->message[$pos]['result'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : ''); - } else { - $this->message[$pos]['result'] = $this->message[$pos]['cdata']; - } - } - - /* add value to parent's result, if parent is struct/array - $parent = $this->message[$pos]['parent']; - if($this->message[$parent]['type'] != 'map'){ - if(strtolower($this->message[$parent]['type']) == 'array'){ - $this->message[$parent]['result'][] = $this->message[$pos]['result']; - } else { - $this->message[$parent]['result'][$this->message[$pos]['name']] = $this->message[$pos]['result']; - } - } - */ - } - } - - // for doclit - if($this->status == 'header'){ - if ($this->root_header != $pos) { - $this->responseHeaders .= ""; - } - } elseif($pos >= $this->root_struct){ - $this->document .= ""; - } - // switch status - if($pos == $this->root_struct){ - $this->status = 'body'; - $this->root_struct_namespace = $this->message[$pos]['namespace']; - } elseif($name == 'Body'){ - $this->status = 'envelope'; - } elseif($name == 'Header'){ - $this->status = 'envelope'; - } elseif($name == 'Envelope'){ - // - } - // set parent back to my parent - $this->parent = $this->message[$pos]['parent']; - } - - /** - * element content handler - * - * @param resource $parser XML parser object - * @param string $data element content - * @access private - */ - function character_data($parser, $data){ - $pos = $this->depth_array[$this->depth]; - if ($this->xml_encoding=='UTF-8'){ - // TODO: add an option to disable this for folks who want - // raw UTF-8 that, e.g., might not map to iso-8859-1 - // TODO: this can also be handled with xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "ISO-8859-1"); - if($this->decode_utf8){ - $data = utf8_decode($data); - } - } - $this->message[$pos]['cdata'] .= $data; - // for doclit - if($this->status == 'header'){ - $this->responseHeaders .= $data; - } else { - $this->document .= $data; - } - } - - /** - * get the parsed message - * - * @return mixed - * @access public - */ - function get_response(){ - return $this->soapresponse; - } - - /** - * get the parsed headers - * - * @return string XML or empty if no headers - * @access public - */ - function getHeaders(){ - return $this->responseHeaders; - } - - /** - * decodes simple types into PHP variables - * - * @param string $value value to decode - * @param string $type XML type to decode - * @param string $typens XML type namespace to decode - * @return mixed PHP value - * @access private - */ - function decodeSimple($value, $type, $typens) { - // TODO: use the namespace! - if ((!isset($type)) || $type == 'string' || $type == 'long' || $type == 'unsignedLong') { - return (string) $value; - } - if ($type == 'int' || $type == 'integer' || $type == 'short' || $type == 'byte') { - return (int) $value; - } - if ($type == 'float' || $type == 'double' || $type == 'decimal') { - return (double) $value; - } - if ($type == 'boolean') { - if (strtolower($value) == 'false' || strtolower($value) == 'f') { - return false; - } - return (boolean) $value; - } - if ($type == 'base64' || $type == 'base64Binary') { - $this->debug('Decode base64 value'); - return base64_decode($value); - } - // obscure numeric types - if ($type == 'nonPositiveInteger' || $type == 'negativeInteger' - || $type == 'nonNegativeInteger' || $type == 'positiveInteger' - || $type == 'unsignedInt' - || $type == 'unsignedShort' || $type == 'unsignedByte') { - return (int) $value; - } - // bogus: parser treats array with no elements as a simple type - if ($type == 'array') { - return array(); - } - // everything else - return (string) $value; - } - - /** - * builds response structures for compound values (arrays/structs) - * and scalars - * - * @param integer $pos position in node tree - * @return mixed PHP value - * @access private - */ - function buildVal($pos){ - if(!isset($this->message[$pos]['type'])){ - $this->message[$pos]['type'] = ''; - } - $this->debug('in buildVal() for '.$this->message[$pos]['name']."(pos $pos) of type ".$this->message[$pos]['type']); - // if there are children... - if($this->message[$pos]['children'] != ''){ - $this->debug('in buildVal, there are children'); - $children = explode('|',$this->message[$pos]['children']); - array_shift($children); // knock off empty - // md array - if(isset($this->message[$pos]['arrayCols']) && $this->message[$pos]['arrayCols'] != ''){ - $r=0; // rowcount - $c=0; // colcount - foreach($children as $child_pos){ - $this->debug("in buildVal, got an MD array element: $r, $c"); - $params[$r][] = $this->message[$child_pos]['result']; - $c++; - if($c == $this->message[$pos]['arrayCols']){ - $c = 0; - $r++; - } - } - // array - } elseif($this->message[$pos]['type'] == 'array' || $this->message[$pos]['type'] == 'Array'){ - $this->debug('in buildVal, adding array '.$this->message[$pos]['name']); - foreach($children as $child_pos){ - $params[] = &$this->message[$child_pos]['result']; - } - // apache Map type: java hashtable - } elseif($this->message[$pos]['type'] == 'Map' && $this->message[$pos]['type_namespace'] == 'http://xml.apache.org/xml-soap'){ - $this->debug('in buildVal, Java Map '.$this->message[$pos]['name']); - foreach($children as $child_pos){ - $kv = explode("|",$this->message[$child_pos]['children']); - $params[$this->message[$kv[1]]['result']] = &$this->message[$kv[2]]['result']; - } - // generic compound type - //} elseif($this->message[$pos]['type'] == 'SOAPStruct' || $this->message[$pos]['type'] == 'struct') { - } else { - // Apache Vector type: treat as an array - $this->debug('in buildVal, adding Java Vector '.$this->message[$pos]['name']); - if ($this->message[$pos]['type'] == 'Vector' && $this->message[$pos]['type_namespace'] == 'http://xml.apache.org/xml-soap') { - $notstruct = 1; - } else { - $notstruct = 0; - } - // - foreach($children as $child_pos){ - if($notstruct){ - $params[] = &$this->message[$child_pos]['result']; - } else { - if (isset($params[$this->message[$child_pos]['name']])) { - // de-serialize repeated element name into an array - if ((!is_array($params[$this->message[$child_pos]['name']])) || (!isset($params[$this->message[$child_pos]['name']][0]))) { - $params[$this->message[$child_pos]['name']] = array($params[$this->message[$child_pos]['name']]); - } - $params[$this->message[$child_pos]['name']][] = &$this->message[$child_pos]['result']; - } else { - $params[$this->message[$child_pos]['name']] = &$this->message[$child_pos]['result']; - } - } - } - } - if (isset($this->message[$pos]['xattrs'])) { - $this->debug('in buildVal, handling attributes'); - foreach ($this->message[$pos]['xattrs'] as $n => $v) { - $params[$n] = $v; - } - } - // handle simpleContent - if (isset($this->message[$pos]['cdata']) && trim($this->message[$pos]['cdata']) != '') { - $this->debug('in buildVal, handling simpleContent'); - if (isset($this->message[$pos]['type'])) { - $params['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : ''); - } else { - $parent = $this->message[$pos]['parent']; - if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) { - $params['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : ''); - } else { - $params['!'] = $this->message[$pos]['cdata']; - } - } - } - return is_array($params) ? $params : array(); - } else { - $this->debug('in buildVal, no children, building scalar'); - $cdata = isset($this->message[$pos]['cdata']) ? $this->message[$pos]['cdata'] : ''; - if (isset($this->message[$pos]['type'])) { - return $this->decodeSimple($cdata, $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : ''); - } - $parent = $this->message[$pos]['parent']; - if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) { - return $this->decodeSimple($cdata, $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : ''); - } - return $this->message[$pos]['cdata']; - } - } -} - - - - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/class.soap_server.php b/gulliver/thirdparty/pear/class.soap_server.php deleted file mode 100644 index 21ce9cd40..000000000 --- a/gulliver/thirdparty/pear/class.soap_server.php +++ /dev/null @@ -1,1038 +0,0 @@ - -* @version $Id: class.soap_server.php,v 1.48 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class soap_server extends nusoap_base { - /** - * HTTP headers of request - * @var array - * @access private - */ - var $headers = array(); - /** - * HTTP request - * @var string - * @access private - */ - var $request = ''; - /** - * SOAP headers from request (incomplete namespace resolution; special characters not escaped) (text) - * @var string - * @access public - */ - var $requestHeaders = ''; - /** - * SOAP body request portion (incomplete namespace resolution; special characters not escaped) (text) - * @var string - * @access public - */ - var $document = ''; - /** - * SOAP payload for request (text) - * @var string - * @access public - */ - var $requestSOAP = ''; - /** - * requested method namespace URI - * @var string - * @access private - */ - var $methodURI = ''; - /** - * name of method requested - * @var string - * @access private - */ - var $methodname = ''; - /** - * method parameters from request - * @var array - * @access private - */ - var $methodparams = array(); - /** - * SOAP Action from request - * @var string - * @access private - */ - var $SOAPAction = ''; - /** - * character set encoding of incoming (request) messages - * @var string - * @access public - */ - var $xml_encoding = ''; - /** - * toggles whether the parser decodes element content w/ utf8_decode() - * @var boolean - * @access public - */ - var $decode_utf8 = true; - - /** - * HTTP headers of response - * @var array - * @access public - */ - var $outgoing_headers = array(); - /** - * HTTP response - * @var string - * @access private - */ - var $response = ''; - /** - * SOAP headers for response (text) - * @var string - * @access public - */ - var $responseHeaders = ''; - /** - * SOAP payload for response (text) - * @var string - * @access private - */ - var $responseSOAP = ''; - /** - * method return value to place in response - * @var mixed - * @access private - */ - var $methodreturn = false; - /** - * whether $methodreturn is a string of literal XML - * @var boolean - * @access public - */ - var $methodreturnisliteralxml = false; - /** - * SOAP fault for response (or false) - * @var mixed - * @access private - */ - var $fault = false; - /** - * text indication of result (for debugging) - * @var string - * @access private - */ - var $result = 'successful'; - - /** - * assoc array of operations => opData; operations are added by the register() - * method or by parsing an external WSDL definition - * @var array - * @access private - */ - var $operations = array(); - /** - * wsdl instance (if one) - * @var mixed - * @access private - */ - var $wsdl = false; - /** - * URL for WSDL (if one) - * @var mixed - * @access private - */ - var $externalWSDLURL = false; - /** - * whether to append debug to response as XML comment - * @var boolean - * @access public - */ - var $debug_flag = false; - - - /** - * constructor - * the optional parameter is a path to a WSDL file that you'd like to bind the server instance to. - * - * @param mixed $wsdl file path or URL (string), or wsdl instance (object) - * @access public - */ - function soap_server($wsdl=false){ - parent::nusoap_base(); - // turn on debugging? - global $debug; - global $HTTP_SERVER_VARS; - - if (isset($_SERVER)) { - $this->debug("_SERVER is defined:"); - $this->appendDebug($this->varDump($_SERVER)); - } elseif (isset($HTTP_SERVER_VARS)) { - $this->debug("HTTP_SERVER_VARS is defined:"); - $this->appendDebug($this->varDump($HTTP_SERVER_VARS)); - } else { - $this->debug("Neither _SERVER nor HTTP_SERVER_VARS is defined."); - } - - if (isset($debug)) { - $this->debug("In soap_server, set debug_flag=$debug based on global flag"); - $this->debug_flag = $debug; - } elseif (isset($_SERVER['QUERY_STRING'])) { - $qs = explode('&', $_SERVER['QUERY_STRING']); - foreach ($qs as $v) { - if (substr($v, 0, 6) == 'debug=') { - $this->debug("In soap_server, set debug_flag=" . substr($v, 6) . " based on query string #1"); - $this->debug_flag = substr($v, 6); - } - } - } elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) { - $qs = explode('&', $HTTP_SERVER_VARS['QUERY_STRING']); - foreach ($qs as $v) { - if (substr($v, 0, 6) == 'debug=') { - $this->debug("In soap_server, set debug_flag=" . substr($v, 6) . " based on query string #2"); - $this->debug_flag = substr($v, 6); - } - } - } - - // wsdl - if($wsdl){ - $this->debug("In soap_server, WSDL is specified"); - if (is_object($wsdl) && (get_class($wsdl) == 'wsdl')) { - $this->wsdl = $wsdl; - $this->externalWSDLURL = $this->wsdl->wsdl; - $this->debug('Use existing wsdl instance from ' . $this->externalWSDLURL); - } else { - $this->debug('Create wsdl from ' . $wsdl); - $this->wsdl = new wsdl($wsdl); - $this->externalWSDLURL = $wsdl; - } - $this->appendDebug($this->wsdl->getDebug()); - $this->wsdl->clearDebug(); - if($err = $this->wsdl->getError()){ - die('WSDL ERROR: '.$err); - } - } - } - - /** - * processes request and returns response - * - * @param string $data usually is the value of $HTTP_RAW_POST_DATA - * @access public - */ - function service($data){ - global $HTTP_SERVER_VARS; - - if (isset($_SERVER['QUERY_STRING'])) { - $qs = $_SERVER['QUERY_STRING']; - } elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) { - $qs = $HTTP_SERVER_VARS['QUERY_STRING']; - } else { - $qs = ''; - } - $this->debug("In service, query string=$qs"); - - if (ereg('wsdl', $qs) ){ - $this->debug("In service, this is a request for WSDL"); - if($this->externalWSDLURL){ - if (strpos($this->externalWSDLURL,"://")!==false) { // assume URL - header('Location: '.$this->externalWSDLURL); - } else { // assume file - header("Content-Type: text/xml\r\n"); - $fp = fopen($this->externalWSDLURL, 'r'); - fpassthru($fp); - } - } elseif ($this->wsdl) { - header("Content-Type: text/xml; charset=ISO-8859-1\r\n"); - print $this->wsdl->serialize($this->debug_flag); - if ($this->debug_flag) { - $this->debug('wsdl:'); - $this->appendDebug($this->varDump($this->wsdl)); - print $this->getDebugAsXMLComment(); - } - } else { - header("Content-Type: text/html; charset=ISO-8859-1\r\n"); - print "This service does not provide WSDL"; - } - } elseif ($data == '' && $this->wsdl) { - $this->debug("In service, there is no data, so return Web description"); - print $this->wsdl->webDescription(); - } else { - $this->debug("In service, invoke the request"); - $this->parse_request($data); - if (! $this->fault) { - $this->invoke_method(); - } - if (! $this->fault) { - $this->serialize_return(); - } - $this->send_response(); - } - } - - /** - * parses HTTP request headers. - * - * The following fields are set by this function (when successful) - * - * headers - * request - * xml_encoding - * SOAPAction - * - * @access private - */ - function parse_http_headers() { - global $HTTP_SERVER_VARS; - - $this->request = ''; - $this->SOAPAction = ''; - if(function_exists('getallheaders')){ - $this->debug("In parse_http_headers, use getallheaders"); - $headers = getallheaders(); - foreach($headers as $k=>$v){ - $k = strtolower($k); - $this->headers[$k] = $v; - $this->request .= "$k: $v\r\n"; - $this->debug("$k: $v"); - } - // get SOAPAction header - if(isset($this->headers['soapaction'])){ - $this->SOAPAction = str_replace('"','',$this->headers['soapaction']); - } - // get the character encoding of the incoming request - if(isset($this->headers['content-type']) && strpos($this->headers['content-type'],'=')){ - $enc = str_replace('"','',substr(strstr($this->headers["content-type"],'='),1)); - if(preg_match('/(ISO-8859-1|US-ASCII|UTF-8)/',$enc)){ - $this->xml_encoding = strtoupper($enc); - } else { - $this->xml_encoding = 'US-ASCII'; - } - } else { - // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 - $this->xml_encoding = 'ISO-8859-1'; - } - } elseif(isset($_SERVER) && is_array($_SERVER)){ - $this->debug("In parse_http_headers, use _SERVER"); - foreach ($_SERVER as $k => $v) { - if (substr($k, 0, 5) == 'HTTP_') { - $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5)))); $k = strtolower(substr($k, 5)); - } else { - $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k))); $k = strtolower($k); - } - if ($k == 'soapaction') { - // get SOAPAction header - $k = 'SOAPAction'; - $v = str_replace('"', '', $v); - $v = str_replace('\\', '', $v); - $this->SOAPAction = $v; - } else if ($k == 'content-type') { - // get the character encoding of the incoming request - if (strpos($v, '=')) { - $enc = substr(strstr($v, '='), 1); - $enc = str_replace('"', '', $enc); - $enc = str_replace('\\', '', $enc); - if (preg_match('/(ISO-8859-1|US-ASCII|UTF-8)/', $enc)) { - $this->xml_encoding = strtoupper($enc); - } else { - $this->xml_encoding = 'US-ASCII'; - } - } else { - // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 - $this->xml_encoding = 'ISO-8859-1'; - } - } - $this->headers[$k] = $v; - $this->request .= "$k: $v\r\n"; - $this->debug("$k: $v"); - } - } elseif (is_array($HTTP_SERVER_VARS)) { - $this->debug("In parse_http_headers, use HTTP_SERVER_VARS"); - foreach ($HTTP_SERVER_VARS as $k => $v) { - if (substr($k, 0, 5) == 'HTTP_') { - $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5)))); $k = strtolower(substr($k, 5)); - } else { - $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k))); $k = strtolower($k); - } - if ($k == 'soapaction') { - // get SOAPAction header - $k = 'SOAPAction'; - $v = str_replace('"', '', $v); - $v = str_replace('\\', '', $v); - $this->SOAPAction = $v; - } else if ($k == 'content-type') { - // get the character encoding of the incoming request - if (strpos($v, '=')) { - $enc = substr(strstr($v, '='), 1); - $enc = str_replace('"', '', $enc); - $enc = str_replace('\\', '', $enc); - if (preg_match('/(ISO-8859-1|US-ASCII|UTF-8)/', $enc)) { - $this->xml_encoding = strtoupper($enc); - } else { - $this->xml_encoding = 'US-ASCII'; - } - } else { - // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 - $this->xml_encoding = 'ISO-8859-1'; - } - } - $this->headers[$k] = $v; - $this->request .= "$k: $v\r\n"; - $this->debug("$k: $v"); - } - } else { - $this->debug("In parse_http_headers, HTTP headers not accessible"); - $this->setError("HTTP headers not accessible"); - } - } - - /** - * parses a request - * - * The following fields are set by this function (when successful) - * - * headers - * request - * xml_encoding - * SOAPAction - * request - * requestSOAP - * methodURI - * methodname - * methodparams - * requestHeaders - * document - * - * This sets the fault field on error - * - * @param string $data XML string - * @access private - */ - function parse_request($data='') { - $this->debug('entering parse_request()'); - $this->parse_http_headers(); - $this->debug('got character encoding: '.$this->xml_encoding); - // uncompress if necessary - if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] != '') { - $this->debug('got content encoding: ' . $this->headers['content-encoding']); - if ($this->headers['content-encoding'] == 'deflate' || $this->headers['content-encoding'] == 'gzip') { - // if decoding works, use it. else assume data wasn't gzencoded - if (function_exists('gzuncompress')) { - if ($this->headers['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) { - $data = $degzdata; - } elseif ($this->headers['content-encoding'] == 'gzip' && $degzdata = gzinflate(substr($data, 10))) { - $data = $degzdata; - } else { - $this->fault('Client', 'Errors occurred when trying to decode the data'); - return; - } - } else { - $this->fault('Client', 'This Server does not support compressed data'); - return; - } - } - } - $this->request .= "\r\n".$data; - $data = $this->parseRequest($this->headers, $data); - $this->requestSOAP = $data; - $this->debug('leaving parse_request'); - } - - /** - * invokes a PHP function for the requested SOAP method - * - * The following fields are set by this function (when successful) - * - * methodreturn - * - * Note that the PHP function that is called may also set the following - * fields to affect the response sent to the client - * - * responseHeaders - * outgoing_headers - * - * This sets the fault field on error - * - * @access private - */ - function invoke_method() { - $this->debug('in invoke_method, methodname=' . $this->methodname . ' methodURI=' . $this->methodURI . ' SOAPAction=' . $this->SOAPAction); - - if ($this->wsdl) { - if ($this->opData = $this->wsdl->getOperationData($this->methodname)) { - $this->debug('in invoke_method, found WSDL operation=' . $this->methodname); - $this->appendDebug('opData=' . $this->varDump($this->opData)); - } elseif ($this->opData = $this->wsdl->getOperationDataForSoapAction($this->SOAPAction)) { - // Note: hopefully this case will only be used for doc/lit, since rpc services should have wrapper element - $this->debug('in invoke_method, found WSDL soapAction=' . $this->SOAPAction . ' for operation=' . $this->opData['name']); - $this->appendDebug('opData=' . $this->varDump($this->opData)); - $this->methodname = $this->opData['name']; - } else { - $this->debug('in invoke_method, no WSDL for operation=' . $this->methodname); - $this->fault('Client', "Operation '" . $this->methodname . "' is not defined in the WSDL for this service"); - return; - } - } else { - $this->debug('in invoke_method, no WSDL to validate method'); - } - - // if a . is present in $this->methodname, we see if there is a class in scope, - // which could be referred to. We will also distinguish between two deliminators, - // to allow methods to be called a the class or an instance - $class = ''; - $method = ''; - if (strpos($this->methodname, '..') > 0) { - $delim = '..'; - } else if (strpos($this->methodname, '.') > 0) { - $delim = '.'; - } else { - $delim = ''; - } - - if (strlen($delim) > 0 && substr_count($this->methodname, $delim) == 1 && - class_exists(substr($this->methodname, 0, strpos($this->methodname, $delim)))) { - // get the class and method name - $class = substr($this->methodname, 0, strpos($this->methodname, $delim)); - $method = substr($this->methodname, strpos($this->methodname, $delim) + strlen($delim)); - $this->debug("in invoke_method, class=$class method=$method delim=$delim"); - } - - // does method exist? - if ($class == '') { - if (!function_exists($this->methodname)) { - $this->debug("in invoke_method, function '$this->methodname' not found!"); - $this->result = 'fault: method not found'; - $this->fault('Client',"method '$this->methodname' not defined in service"); - return; - } - } else { - $method_to_compare = (substr(phpversion(), 0, 2) == '4.') ? strtolower($method) : $method; - if (!in_array($method_to_compare, get_class_methods($class))) { - $this->debug("in invoke_method, method '$this->methodname' not found in class '$class'!"); - $this->result = 'fault: method not found'; - $this->fault('Client',"method '$this->methodname' not defined in service"); - return; - } - } - - // evaluate message, getting back parameters - // verify that request parameters match the method's signature - if(! $this->verify_method($this->methodname,$this->methodparams)){ - // debug - $this->debug('ERROR: request not verified against method signature'); - $this->result = 'fault: request failed validation against method signature'; - // return fault - $this->fault('Client',"Operation '$this->methodname' not defined in service."); - return; - } - - // if there are parameters to pass - $this->debug('in invoke_method, params:'); - $this->appendDebug($this->varDump($this->methodparams)); - $this->debug("in invoke_method, calling '$this->methodname'"); - if (!function_exists('call_user_func_array')) { - if ($class == '') { - $this->debug('in invoke_method, calling function using eval()'); - $funcCall = "\$this->methodreturn = $this->methodname("; - } else { - if ($delim == '..') { - $this->debug('in invoke_method, calling class method using eval()'); - $funcCall = "\$this->methodreturn = ".$class."::".$method."("; - } else { - $this->debug('in invoke_method, calling instance method using eval()'); - // generate unique instance name - $instname = "\$inst_".time(); - $funcCall = $instname." = new ".$class."(); "; - $funcCall .= "\$this->methodreturn = ".$instname."->".$method."("; - } - } - if ($this->methodparams) { - foreach ($this->methodparams as $param) { - if (is_array($param)) { - $this->fault('Client', 'NuSOAP does not handle complexType parameters correctly when using eval; call_user_func_array must be available'); - return; - } - $funcCall .= "\"$param\","; - } - $funcCall = substr($funcCall, 0, -1); - } - $funcCall .= ');'; - $this->debug('in invoke_method, function call: '.$funcCall); - @eval($funcCall); - } else { - if ($class == '') { - $this->debug('in invoke_method, calling function using call_user_func_array()'); - $call_arg = "$this->methodname"; // straight assignment changes $this->methodname to lower case after call_user_func_array() - } elseif ($delim == '..') { - $this->debug('in invoke_method, calling class method using call_user_func_array()'); - $call_arg = array ($class, $method); - } else { - $this->debug('in invoke_method, calling instance method using call_user_func_array()'); - $instance = new $class (); - $call_arg = array(&$instance, $method); - } - $this->methodreturn = call_user_func_array($call_arg, $this->methodparams); - } - $this->debug('in invoke_method, methodreturn:'); - $this->appendDebug($this->varDump($this->methodreturn)); - $this->debug("in invoke_method, called method $this->methodname, received $this->methodreturn of type ".gettype($this->methodreturn)); - } - - /** - * serializes the return value from a PHP function into a full SOAP Envelope - * - * The following fields are set by this function (when successful) - * - * responseSOAP - * - * This sets the fault field on error - * - * @access private - */ - function serialize_return() { - $this->debug('Entering serialize_return methodname: ' . $this->methodname . ' methodURI: ' . $this->methodURI); - // if fault - if (isset($this->methodreturn) && (get_class($this->methodreturn) == 'soap_fault')) { - $this->debug('got a fault object from method'); - $this->fault = $this->methodreturn; - return; - } elseif ($this->methodreturnisliteralxml) { - $return_val = $this->methodreturn; - // returned value(s) - } else { - $this->debug('got a(n) '.gettype($this->methodreturn).' from method'); - $this->debug('serializing return value'); - if($this->wsdl){ - // weak attempt at supporting multiple output params - if(sizeof($this->opData['output']['parts']) > 1){ - $opParams = $this->methodreturn; - } else { - // TODO: is this really necessary? - $opParams = array($this->methodreturn); - } - $return_val = $this->wsdl->serializeRPCParameters($this->methodname,'output',$opParams); - $this->appendDebug($this->wsdl->getDebug()); - $this->wsdl->clearDebug(); - if($errstr = $this->wsdl->getError()){ - $this->debug('got wsdl error: '.$errstr); - $this->fault('Server', 'unable to serialize result'); - return; - } - } else { - if (isset($this->methodreturn)) { - $return_val = $this->serialize_val($this->methodreturn, 'return'); - } else { - $return_val = ''; - $this->debug('in absence of WSDL, assume void return for backward compatibility'); - } - } - } - $this->debug('return value:'); - $this->appendDebug($this->varDump($return_val)); - - $this->debug('serializing response'); - if ($this->wsdl) { - $this->debug('have WSDL for serialization: style is ' . $this->opData['style']); - if ($this->opData['style'] == 'rpc') { - $this->debug('style is rpc for serialization: use is ' . $this->opData['output']['use']); - if ($this->opData['output']['use'] == 'literal') { - $payload = '<'.$this->methodname.'Response xmlns="'.$this->methodURI.'">'.$return_val.'methodname."Response>"; - } else { - $payload = 'methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'methodname."Response>"; - } - } else { - $this->debug('style is not rpc for serialization: assume document'); - $payload = $return_val; - } - } else { - $this->debug('do not have WSDL for serialization: assume rpc/encoded'); - $payload = 'methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'methodname."Response>"; - } - $this->result = 'successful'; - if($this->wsdl){ - //if($this->debug_flag){ - $this->appendDebug($this->wsdl->getDebug()); - // } - if (isset($opData['output']['encodingStyle'])) { - $encodingStyle = $opData['output']['encodingStyle']; - } else { - $encodingStyle = ''; - } - // Added: In case we use a WSDL, return a serialized env. WITH the usedNamespaces. - $this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders,$this->wsdl->usedNamespaces,$this->opData['style'],$encodingStyle); - } else { - $this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders); - } - $this->debug("Leaving serialize_return"); - } - - /** - * sends an HTTP response - * - * The following fields are set by this function (when successful) - * - * outgoing_headers - * response - * - * @access private - */ - function send_response() { - $this->debug('Enter send_response'); - if ($this->fault) { - $payload = $this->fault->serialize(); - $this->outgoing_headers[] = "HTTP/1.0 500 Internal Server Error"; - $this->outgoing_headers[] = "Status: 500 Internal Server Error"; - } else { - $payload = $this->responseSOAP; - // Some combinations of PHP+Web server allow the Status - // to come through as a header. Since OK is the default - // just do nothing. - // $this->outgoing_headers[] = "HTTP/1.0 200 OK"; - // $this->outgoing_headers[] = "Status: 200 OK"; - } - // add debug data if in debug mode - if(isset($this->debug_flag) && $this->debug_flag){ - $payload .= $this->getDebugAsXMLComment(); - } - $this->outgoing_headers[] = "Server: $this->title Server v$this->version"; - ereg('\$Revisio' . 'n: ([^ ]+)', $this->revision, $rev); - $this->outgoing_headers[] = "X-SOAP-Server: $this->title/$this->version (".$rev[1].")"; - // Let the Web server decide about this - //$this->outgoing_headers[] = "Connection: Close\r\n"; - $payload = $this->getHTTPBody($payload); - $type = $this->getHTTPContentType(); - $charset = $this->getHTTPContentTypeCharset(); - $this->outgoing_headers[] = "Content-Type: $type" . ($charset ? '; charset=' . $charset : ''); - //begin code to compress payload - by John - // NOTE: there is no way to know whether the Web server will also compress - // this data. - if (strlen($payload) > 1024 && isset($this->headers) && isset($this->headers['accept-encoding'])) { - if (strstr($this->headers['accept-encoding'], 'gzip')) { - if (function_exists('gzencode')) { - if (isset($this->debug_flag) && $this->debug_flag) { - $payload .= ""; - } - $this->outgoing_headers[] = "Content-Encoding: gzip"; - $payload = gzencode($payload); - } else { - if (isset($this->debug_flag) && $this->debug_flag) { - $payload .= ""; - } - } - } elseif (strstr($this->headers['accept-encoding'], 'deflate')) { - // Note: MSIE requires gzdeflate output (no Zlib header and checksum), - // instead of gzcompress output, - // which conflicts with HTTP 1.1 spec (http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5) - if (function_exists('gzdeflate')) { - if (isset($this->debug_flag) && $this->debug_flag) { - $payload .= ""; - } - $this->outgoing_headers[] = "Content-Encoding: deflate"; - $payload = gzdeflate($payload); - } else { - if (isset($this->debug_flag) && $this->debug_flag) { - $payload .= ""; - } - } - } - } - //end code - $this->outgoing_headers[] = "Content-Length: ".strlen($payload); - reset($this->outgoing_headers); - foreach($this->outgoing_headers as $hdr){ - header($hdr, false); - } - print $payload; - $this->response = join("\r\n",$this->outgoing_headers)."\r\n\r\n".$payload; - } - - /** - * takes the value that was created by parsing the request - * and compares to the method's signature, if available. - * - * @param string $operation The operation to be invoked - * @param array $request The array of parameter values - * @return boolean Whether the operation was found - * @access private - */ - function verify_method($operation,$request){ - if(isset($this->wsdl) && is_object($this->wsdl)){ - if($this->wsdl->getOperationData($operation)){ - return true; - } - } elseif(isset($this->operations[$operation])){ - return true; - } - return false; - } - - /** - * processes SOAP message received from client - * - * @param array $headers The HTTP headers - * @param string $data unprocessed request data from client - * @return mixed value of the message, decoded into a PHP type - * @access private - */ - function parseRequest($headers, $data) { - $this->debug('Entering parseRequest() for data of length ' . strlen($data) . ' and type ' . $headers['content-type']); - if (!strstr($headers['content-type'], 'text/xml')) { - $this->setError('Request not of type text/xml'); - return false; - } - if (strpos($headers['content-type'], '=')) { - $enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1)); - $this->debug('Got response encoding: ' . $enc); - if(preg_match('/(ISO-8859-1|US-ASCII|UTF-8)/',$enc)){ - $this->xml_encoding = strtoupper($enc); - } else { - $this->xml_encoding = 'US-ASCII'; - } - } else { - // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 - $this->xml_encoding = 'ISO-8859-1'; - } - $this->debug('Use encoding: ' . $this->xml_encoding . ' when creating soap_parser'); - // parse response, get soap parser obj - $parser = new soap_parser($data,$this->xml_encoding,'',$this->decode_utf8); - // parser debug - $this->debug("parser debug: \n".$parser->getDebug()); - // if fault occurred during message parsing - if($err = $parser->getError()){ - $this->result = 'fault: error in msg parsing: '.$err; - $this->fault('Client',"error in msg parsing:\n".$err); - // else successfully parsed request into soapval object - } else { - // get/set methodname - $this->methodURI = $parser->root_struct_namespace; - $this->methodname = $parser->root_struct_name; - $this->debug('methodname: '.$this->methodname.' methodURI: '.$this->methodURI); - $this->debug('calling parser->get_response()'); - $this->methodparams = $parser->get_response(); - // get SOAP headers - $this->requestHeaders = $parser->getHeaders(); - // add document for doclit support - $this->document = $parser->document; - } - } - - /** - * gets the HTTP body for the current response. - * - * @param string $soapmsg The SOAP payload - * @return string The HTTP body, which includes the SOAP payload - * @access private - */ - function getHTTPBody($soapmsg) { - return $soapmsg; - } - - /** - * gets the HTTP content type for the current response. - * - * Note: getHTTPBody must be called before this. - * - * @return string the HTTP content type for the current response. - * @access private - */ - function getHTTPContentType() { - return 'text/xml'; - } - - /** - * gets the HTTP content type charset for the current response. - * returns false for non-text content types. - * - * Note: getHTTPBody must be called before this. - * - * @return string the HTTP content type charset for the current response. - * @access private - */ - function getHTTPContentTypeCharset() { - return $this->soap_defencoding; - } - - /** - * add a method to the dispatch map (this has been replaced by the register method) - * - * @param string $methodname - * @param string $in array of input values - * @param string $out array of output values - * @access public - * @deprecated - */ - function add_to_map($methodname,$in,$out){ - $this->operations[$methodname] = array('name' => $methodname,'in' => $in,'out' => $out); - } - - /** - * register a service function with the server - * - * @param string $name the name of the PHP function, class.method or class..method - * @param array $in assoc array of input values: key = param name, value = param type - * @param array $out assoc array of output values: key = param name, value = param type - * @param mixed $namespace the element namespace for the method or false - * @param mixed $soapaction the soapaction for the method or false - * @param mixed $style optional (rpc|document) or false Note: when 'document' is specified, parameter and return wrappers are created for you automatically - * @param mixed $use optional (encoded|literal) or false - * @param string $documentation optional Description to include in WSDL - * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded) - * @access public - */ - function register($name,$in=array(),$out=array(),$namespace=false,$soapaction=false,$style=false,$use=false,$documentation='',$encodingStyle=''){ - global $HTTP_SERVER_VARS; - - if($this->externalWSDLURL){ - die('You cannot bind to an external WSDL file, and register methods outside of it! Please choose either WSDL or no WSDL.'); - } - if (! $name) { - die('You must specify a name when you register an operation'); - } - if (!is_array($in)) { - die('You must provide an array for operation inputs'); - } - if (!is_array($out)) { - die('You must provide an array for operation outputs'); - } - if(false == $namespace) { - } - if(false == $soapaction) { - if (isset($_SERVER)) { - $SERVER_NAME = $_SERVER['SERVER_NAME']; - $SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']; - } elseif (isset($HTTP_SERVER_VARS)) { - $SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME']; - $SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME']; - } else { - $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available"); - } - $soapaction = "http://$SERVER_NAME$SCRIPT_NAME/$name"; - } - if(false == $style) { - $style = "rpc"; - } - if(false == $use) { - $use = "encoded"; - } - if ($use == 'encoded' && $encodingStyle = '') { - $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; - } - - $this->operations[$name] = array( - 'name' => $name, - 'in' => $in, - 'out' => $out, - 'namespace' => $namespace, - 'soapaction' => $soapaction, - 'style' => $style); - if($this->wsdl){ - $this->wsdl->addOperation($name,$in,$out,$namespace,$soapaction,$style,$use,$documentation,$encodingStyle); - } - return true; - } - - /** - * Specify a fault to be returned to the client. - * This also acts as a flag to the server that a fault has occured. - * - * @param string $faultcode - * @param string $faultstring - * @param string $faultactor - * @param string $faultdetail - * @access public - */ - function fault($faultcode,$faultstring,$faultactor='',$faultdetail=''){ - if ($faultdetail == '' && $this->debug_flag) { - $faultdetail = $this->getDebug(); - } - $this->fault = new soap_fault($faultcode,$faultactor,$faultstring,$faultdetail); - $this->fault->soap_defencoding = $this->soap_defencoding; - } - - /** - * Sets up wsdl object. - * Acts as a flag to enable internal WSDL generation - * - * @param string $serviceName, name of the service - * @param mixed $namespace optional 'tns' service namespace or false - * @param mixed $endpoint optional URL of service endpoint or false - * @param string $style optional (rpc|document) WSDL style (also specified by operation) - * @param string $transport optional SOAP transport - * @param mixed $schemaTargetNamespace optional 'types' targetNamespace for service schema or false - */ - function configureWSDL($serviceName,$namespace = false,$endpoint = false,$style='rpc', $transport = 'http://schemas.xmlsoap.org/soap/http', $schemaTargetNamespace = false) - { - global $HTTP_SERVER_VARS; - - if (isset($_SERVER)) { - $SERVER_NAME = $_SERVER['SERVER_NAME']; - $SERVER_PORT = $_SERVER['SERVER_PORT']; - $SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']; - $HTTPS = $_SERVER['HTTPS']; - } elseif (isset($HTTP_SERVER_VARS)) { - $SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME']; - $SERVER_PORT = $HTTP_SERVER_VARS['SERVER_PORT']; - $SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME']; - $HTTPS = $HTTP_SERVER_VARS['HTTPS']; - } else { - $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available"); - } - if ($SERVER_PORT == 80) { - $SERVER_PORT = ''; - } else { - $SERVER_PORT = ':' . $SERVER_PORT; - } - if(false == $namespace) { - $namespace = "http://$SERVER_NAME/soap/$serviceName"; - } - - if(false == $endpoint) { - if ($HTTPS == '1' || $HTTPS == 'on') { - $SCHEME = 'https'; - } else { - $SCHEME = 'http'; - } - $endpoint = "$SCHEME://$SERVER_NAME$SERVER_PORT$SCRIPT_NAME"; - } - - if(false == $schemaTargetNamespace) { - $schemaTargetNamespace = $namespace; - } - - $this->wsdl = new wsdl; - $this->wsdl->serviceName = $serviceName; - $this->wsdl->endpoint = $endpoint; - $this->wsdl->namespaces['tns'] = $namespace; - $this->wsdl->namespaces['soap'] = 'http://schemas.xmlsoap.org/wsdl/soap/'; - $this->wsdl->namespaces['wsdl'] = 'http://schemas.xmlsoap.org/wsdl/'; - if ($schemaTargetNamespace != $namespace) { - $this->wsdl->namespaces['types'] = $schemaTargetNamespace; - } - $this->wsdl->schemas[$schemaTargetNamespace][0] = new xmlschema('', '', $this->wsdl->namespaces); - $this->wsdl->schemas[$schemaTargetNamespace][0]->schemaTargetNamespace = $schemaTargetNamespace; - $this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/soap/encoding/'][0] = array('location' => '', 'loaded' => true); - $this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/wsdl/'][0] = array('location' => '', 'loaded' => true); - $this->wsdl->bindings[$serviceName.'Binding'] = array( - 'name'=>$serviceName.'Binding', - 'style'=>$style, - 'transport'=>$transport, - 'portType'=>$serviceName.'PortType'); - $this->wsdl->ports[$serviceName.'Port'] = array( - 'binding'=>$serviceName.'Binding', - 'location'=>$endpoint, - 'bindingType'=>'http://schemas.xmlsoap.org/wsdl/soap/'); - } -} - - - - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/class.soap_transport_http.php b/gulliver/thirdparty/pear/class.soap_transport_http.php deleted file mode 100644 index cf8094191..000000000 --- a/gulliver/thirdparty/pear/class.soap_transport_http.php +++ /dev/null @@ -1,1038 +0,0 @@ - -* @version $Id: class.soap_transport_http.php,v 1.57 2005/07/27 19:24:42 snichol Exp $ -* @access public -*/ -class soap_transport_http extends nusoap_base { - - var $url = ''; - var $uri = ''; - var $digest_uri = ''; - var $scheme = ''; - var $host = ''; - var $port = ''; - var $path = ''; - var $request_method = 'POST'; - var $protocol_version = '1.0'; - var $encoding = ''; - var $outgoing_headers = array(); - var $incoming_headers = array(); - var $incoming_cookies = array(); - var $outgoing_payload = ''; - var $incoming_payload = ''; - var $useSOAPAction = true; - var $persistentConnection = false; - var $ch = false; // cURL handle - var $username = ''; - var $password = ''; - var $authtype = ''; - var $digestRequest = array(); - var $certRequest = array(); // keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional) - // cainfofile: certificate authority file, e.g. '$pathToPemFiles/rootca.pem' - // sslcertfile: SSL certificate file, e.g. '$pathToPemFiles/mycert.pem' - // sslkeyfile: SSL key file, e.g. '$pathToPemFiles/mykey.pem' - // passphrase: SSL key password/passphrase - // verifypeer: default is 1 - // verifyhost: default is 1 - - /** - * constructor - */ - function soap_transport_http($url){ - parent::nusoap_base(); - $this->setURL($url); - ereg('\$Revisio' . 'n: ([^ ]+)', $this->revision, $rev); - $this->outgoing_headers['User-Agent'] = $this->title.'/'.$this->version.' ('.$rev[1].')'; - $this->debug('set User-Agent: ' . $this->outgoing_headers['User-Agent']); - } - - function setURL($url) { - $this->url = $url; - - $u = parse_url($url); - foreach($u as $k => $v){ - $this->debug("$k = $v"); - $this->$k = $v; - } - - // add any GET params to path - if(isset($u['query']) && $u['query'] != ''){ - $this->path .= '?' . $u['query']; - } - - // set default port - if(!isset($u['port'])){ - if($u['scheme'] == 'https'){ - $this->port = 443; - } else { - $this->port = 80; - } - } - - $this->uri = $this->path; - $this->digest_uri = $this->uri; - - // build headers - if (!isset($u['port'])) { - $this->outgoing_headers['Host'] = $this->host; - } else { - $this->outgoing_headers['Host'] = $this->host.':'.$this->port; - } - $this->debug('set Host: ' . $this->outgoing_headers['Host']); - - if (isset($u['user']) && $u['user'] != '') { - $this->setCredentials(urldecode($u['user']), isset($u['pass']) ? urldecode($u['pass']) : ''); - } - } - - function connect($connection_timeout=0,$response_timeout=30){ - // For PHP 4.3 with OpenSSL, change https scheme to ssl, then treat like - // "regular" socket. - // TODO: disabled for now because OpenSSL must be *compiled* in (not just - // loaded), and until PHP5 stream_get_wrappers is not available. -// if ($this->scheme == 'https') { -// if (version_compare(phpversion(), '4.3.0') >= 0) { -// if (extension_loaded('openssl')) { -// $this->scheme = 'ssl'; -// $this->debug('Using SSL over OpenSSL'); -// } -// } -// } - $this->debug("connect connection_timeout $connection_timeout, response_timeout $response_timeout, scheme $this->scheme, host $this->host, port $this->port"); - if ($this->scheme == 'http' || $this->scheme == 'ssl') { - // use persistent connection - if($this->persistentConnection && isset($this->fp) && is_resource($this->fp)){ - if (!feof($this->fp)) { - $this->debug('Re-use persistent connection'); - return true; - } - fclose($this->fp); - $this->debug('Closed persistent connection at EOF'); - } - - // munge host if using OpenSSL - if ($this->scheme == 'ssl') { - $host = 'ssl://' . $this->host; - } else { - $host = $this->host; - } - $this->debug('calling fsockopen with host ' . $host . ' connection_timeout ' . $connection_timeout); - - // open socket - if($connection_timeout > 0){ - $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str, $connection_timeout); - } else { - $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str); - } - - // test pointer - if(!$this->fp) { - $msg = 'Couldn\'t open socket connection to server ' . $this->url; - if ($this->errno) { - $msg .= ', Error ('.$this->errno.'): '.$this->error_str; - } else { - $msg .= ' prior to connect(). This is often a problem looking up the host name.'; - } - $this->debug($msg); - $this->setError($msg); - return false; - } - - // set response timeout - $this->debug('set response timeout to ' . $response_timeout); - socket_set_timeout( $this->fp, $response_timeout); - - $this->debug('socket connected'); - return true; - } else if ($this->scheme == 'https') { - if (!extension_loaded('curl')) { - $this->setError('CURL Extension, or OpenSSL extension w/ PHP version >= 4.3 is required for HTTPS'); - return false; - } - $this->debug('connect using https'); - // init CURL - $this->ch = curl_init(); - // set url - $hostURL = ($this->port != '') ? "https://$this->host:$this->port" : "https://$this->host"; - // add path - $hostURL .= $this->path; - curl_setopt($this->ch, CURLOPT_URL, $hostURL); - // follow location headers (re-directs) - curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 1); - // ask for headers in the response output - curl_setopt($this->ch, CURLOPT_HEADER, 1); - // ask for the response output as the return value - curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1); - // encode - // We manage this ourselves through headers and encoding -// if(function_exists('gzuncompress')){ -// curl_setopt($this->ch, CURLOPT_ENCODING, 'deflate'); -// } - // persistent connection - if ($this->persistentConnection) { - // The way we send data, we cannot use persistent connections, since - // there will be some "junk" at the end of our request. - //curl_setopt($this->ch, CURL_HTTP_VERSION_1_1, true); - $this->persistentConnection = false; - $this->outgoing_headers['Connection'] = 'close'; - $this->debug('set Connection: ' . $this->outgoing_headers['Connection']); - } - // set timeout - if ($connection_timeout != 0) { - curl_setopt($this->ch, CURLOPT_TIMEOUT, $connection_timeout); - } - // TODO: cURL has added a connection timeout separate from the response timeout - //if ($connection_timeout != 0) { - // curl_setopt($this->ch, CURLOPT_CONNECTIONTIMEOUT, $connection_timeout); - //} - //if ($response_timeout != 0) { - // curl_setopt($this->ch, CURLOPT_TIMEOUT, $response_timeout); - //} - - // recent versions of cURL turn on peer/host checking by default, - // while PHP binaries are not compiled with a default location for the - // CA cert bundle, so disable peer/host checking. -//curl_setopt($this->ch, CURLOPT_CAINFO, 'f:\php-4.3.2-win32\extensions\curl-ca-bundle.crt'); - curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0); - curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 0); - - // support client certificates (thanks Tobias Boes, Doug Anarino, Eryan Ariobowo) - if ($this->authtype == 'certificate') { - if (isset($this->certRequest['cainfofile'])) { - curl_setopt($this->ch, CURLOPT_CAINFO, $this->certRequest['cainfofile']); - } - if (isset($this->certRequest['verifypeer'])) { - curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, $this->certRequest['verifypeer']); - } else { - curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 1); - } - if (isset($this->certRequest['verifyhost'])) { - curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, $this->certRequest['verifyhost']); - } else { - curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 1); - } - if (isset($this->certRequest['sslcertfile'])) { - curl_setopt($this->ch, CURLOPT_SSLCERT, $this->certRequest['sslcertfile']); - } - if (isset($this->certRequest['sslkeyfile'])) { - curl_setopt($this->ch, CURLOPT_SSLKEY, $this->certRequest['sslkeyfile']); - } - if (isset($this->certRequest['passphrase'])) { - curl_setopt($this->ch, CURLOPT_SSLKEYPASSWD , $this->certRequest['passphrase']); - } - } - $this->debug('cURL connection set up'); - return true; - } else { - $this->setError('Unknown scheme ' . $this->scheme); - $this->debug('Unknown scheme ' . $this->scheme); - return false; - } - } - - /** - * send the SOAP message via HTTP - * - * @param string $data message data - * @param integer $timeout set connection timeout in seconds - * @param integer $response_timeout set response timeout in seconds - * @param array $cookies cookies to send - * @return string data - * @access public - */ - function send($data, $timeout=0, $response_timeout=30, $cookies=NULL) { - - $this->debug('entered send() with data of length: '.strlen($data)); - - $this->tryagain = true; - $tries = 0; - while ($this->tryagain) { - $this->tryagain = false; - if ($tries++ < 2) { - // make connnection - if (!$this->connect($timeout, $response_timeout)){ - return false; - } - - // send request - if (!$this->sendRequest($data, $cookies)){ - return false; - } - - // get response - $respdata = $this->getResponse(); - } else { - $this->setError('Too many tries to get an OK response'); - } - } - $this->debug('end of send()'); - return $respdata; - } - - - /** - * send the SOAP message via HTTPS 1.0 using CURL - * - * @param string $msg message data - * @param integer $timeout set connection timeout in seconds - * @param integer $response_timeout set response timeout in seconds - * @param array $cookies cookies to send - * @return string data - * @access public - */ - function sendHTTPS($data, $timeout=0, $response_timeout=30, $cookies) { - return $this->send($data, $timeout, $response_timeout, $cookies); - } - - /** - * if authenticating, set user credentials here - * - * @param string $username - * @param string $password - * @param string $authtype (basic, digest, certificate) - * @param array $digestRequest (keys must be nonce, nc, realm, qop) - * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs) - * @access public - */ - function setCredentials($username, $password, $authtype = 'basic', $digestRequest = array(), $certRequest = array()) { - $this->debug("Set credentials for authtype $authtype"); - // cf. RFC 2617 - if ($authtype == 'basic') { - $this->outgoing_headers['Authorization'] = 'Basic '.base64_encode(str_replace(':','',$username).':'.$password); - } elseif ($authtype == 'digest') { - if (isset($digestRequest['nonce'])) { - $digestRequest['nc'] = isset($digestRequest['nc']) ? $digestRequest['nc']++ : 1; - - // calculate the Digest hashes (calculate code based on digest implementation found at: http://www.rassoc.com/gregr/weblog/stories/2002/07/09/webServicesSecurityHttpDigestAuthenticationWithoutActiveDirectory.html) - - // A1 = unq(username-value) ":" unq(realm-value) ":" passwd - $A1 = $username. ':' . (isset($digestRequest['realm']) ? $digestRequest['realm'] : '') . ':' . $password; - - // H(A1) = MD5(A1) - $HA1 = G::encryptOld($A1); - - // A2 = Method ":" digest-uri-value - $A2 = 'POST:' . $this->digest_uri; - - // H(A2) - $HA2 = G::encryptOld($A2); - - // KD(secret, data) = H(concat(secret, ":", data)) - // if qop == auth: - // request-digest = <"> < KD ( H(A1), unq(nonce-value) - // ":" nc-value - // ":" unq(cnonce-value) - // ":" unq(qop-value) - // ":" H(A2) - // ) <"> - // if qop is missing, - // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > <"> - - $unhashedDigest = ''; - $nonce = isset($digestRequest['nonce']) ? $digestRequest['nonce'] : ''; - $cnonce = $nonce; - if ($digestRequest['qop'] != '') { - $unhashedDigest = $HA1 . ':' . $nonce . ':' . sprintf("%08d", $digestRequest['nc']) . ':' . $cnonce . ':' . $digestRequest['qop'] . ':' . $HA2; - } else { - $unhashedDigest = $HA1 . ':' . $nonce . ':' . $HA2; - } - - $hashedDigest = G::encryptOld($unhashedDigest); - - $this->outgoing_headers['Authorization'] = 'Digest username="' . $username . '", realm="' . $digestRequest['realm'] . '", nonce="' . $nonce . '", uri="' . $this->digest_uri . '", cnonce="' . $cnonce . '", nc=' . sprintf("%08x", $digestRequest['nc']) . ', qop="' . $digestRequest['qop'] . '", response="' . $hashedDigest . '"'; - } - } elseif ($authtype == 'certificate') { - $this->certRequest = $certRequest; - } - $this->username = $username; - $this->password = $password; - $this->authtype = $authtype; - $this->digestRequest = $digestRequest; - - if (isset($this->outgoing_headers['Authorization'])) { - $this->debug('set Authorization: ' . substr($this->outgoing_headers['Authorization'], 0, 12) . '...'); - } else { - $this->debug('Authorization header not set'); - } - } - - /** - * set the soapaction value - * - * @param string $soapaction - * @access public - */ - function setSOAPAction($soapaction) { - $this->outgoing_headers['SOAPAction'] = '"' . $soapaction . '"'; - $this->debug('set SOAPAction: ' . $this->outgoing_headers['SOAPAction']); - } - - /** - * use http encoding - * - * @param string $enc encoding style. supported values: gzip, deflate, or both - * @access public - */ - function setEncoding($enc='gzip, deflate') { - if (function_exists('gzdeflate')) { - $this->protocol_version = '1.1'; - $this->outgoing_headers['Accept-Encoding'] = $enc; - $this->debug('set Accept-Encoding: ' . $this->outgoing_headers['Accept-Encoding']); - if (!isset($this->outgoing_headers['Connection'])) { - $this->outgoing_headers['Connection'] = 'close'; - $this->persistentConnection = false; - $this->debug('set Connection: ' . $this->outgoing_headers['Connection']); - } - set_magic_quotes_runtime(0); - // deprecated - $this->encoding = $enc; - } - } - - /** - * set proxy info here - * - * @param string $proxyhost - * @param string $proxyport - * @param string $proxyusername - * @param string $proxypassword - * @access public - */ - function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '') { - $this->uri = $this->url; - $this->host = $proxyhost; - $this->port = $proxyport; - if ($proxyusername != '' && $proxypassword != '') { - $this->outgoing_headers['Proxy-Authorization'] = ' Basic '.base64_encode($proxyusername.':'.$proxypassword); - $this->debug('set Proxy-Authorization: ' . $this->outgoing_headers['Proxy-Authorization']); - } - } - - /** - * decode a string that is encoded w/ "chunked' transfer encoding - * as defined in RFC2068 19.4.6 - * - * @param string $buffer - * @param string $lb - * @returns string - * @access public - * @deprecated - */ - function decodeChunked($buffer, $lb){ - // length := 0 - $length = 0; - $new = ''; - - // read chunk-size, chunk-extension (if any) and CRLF - // get the position of the linebreak - $chunkend = strpos($buffer, $lb); - if ($chunkend == FALSE) { - $this->debug('no linebreak found in decodeChunked'); - return $new; - } - $temp = substr($buffer,0,$chunkend); - $chunk_size = hexdec( trim($temp) ); - $chunkstart = $chunkend + strlen($lb); - // while (chunk-size > 0) { - while ($chunk_size > 0) { - $this->debug("chunkstart: $chunkstart chunk_size: $chunk_size"); - $chunkend = strpos( $buffer, $lb, $chunkstart + $chunk_size); - - // Just in case we got a broken connection - if ($chunkend == FALSE) { - $chunk = substr($buffer,$chunkstart); - // append chunk-data to entity-body - $new .= $chunk; - $length += strlen($chunk); - break; - } - - // read chunk-data and CRLF - $chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart); - // append chunk-data to entity-body - $new .= $chunk; - // length := length + chunk-size - $length += strlen($chunk); - // read chunk-size and CRLF - $chunkstart = $chunkend + strlen($lb); - - $chunkend = strpos($buffer, $lb, $chunkstart) + strlen($lb); - if ($chunkend == FALSE) { - break; //Just in case we got a broken connection - } - $temp = substr($buffer,$chunkstart,$chunkend-$chunkstart); - $chunk_size = hexdec( trim($temp) ); - $chunkstart = $chunkend; - } - return $new; - } - - /* - * Writes payload, including HTTP headers, to $this->outgoing_payload. - */ - function buildPayload($data, $cookie_str = '') { - // add content-length header - $this->outgoing_headers['Content-Length'] = strlen($data); - $this->debug('set Content-Length: ' . $this->outgoing_headers['Content-Length']); - - // start building outgoing payload: - $req = "$this->request_method $this->uri HTTP/$this->protocol_version"; - $this->debug("HTTP request: $req"); - $this->outgoing_payload = "$req\r\n"; - - // loop thru headers, serializing - foreach($this->outgoing_headers as $k => $v){ - $hdr = $k.': '.$v; - $this->debug("HTTP header: $hdr"); - $this->outgoing_payload .= "$hdr\r\n"; - } - - // add any cookies - if ($cookie_str != '') { - $hdr = 'Cookie: '.$cookie_str; - $this->debug("HTTP header: $hdr"); - $this->outgoing_payload .= "$hdr\r\n"; - } - - // header/body separator - $this->outgoing_payload .= "\r\n"; - - // add data - $this->outgoing_payload .= $data; - } - - function sendRequest($data, $cookies = NULL) { - // build cookie string - $cookie_str = $this->getCookiesForRequest($cookies, (($this->scheme == 'ssl') || ($this->scheme == 'https'))); - - // build payload - $this->buildPayload($data, $cookie_str); - - if ($this->scheme == 'http' || $this->scheme == 'ssl') { - // send payload - if(!fputs($this->fp, $this->outgoing_payload, strlen($this->outgoing_payload))) { - $this->setError('couldn\'t write message data to socket'); - $this->debug('couldn\'t write message data to socket'); - return false; - } - $this->debug('wrote data to socket, length = ' . strlen($this->outgoing_payload)); - return true; - } else if ($this->scheme == 'https') { - // set payload - // TODO: cURL does say this should only be the verb, and in fact it - // turns out that the URI and HTTP version are appended to this, which - // some servers refuse to work with - //curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $this->outgoing_payload); - foreach($this->outgoing_headers as $k => $v){ - $curl_headers[] = "$k: $v"; - } - if ($cookie_str != '') { - $curl_headers[] = 'Cookie: ' . $cookie_str; - } - curl_setopt($this->ch, CURLOPT_HTTPHEADER, $curl_headers); - if ($this->request_method == "POST") { - curl_setopt($this->ch, CURLOPT_POST, 1); - curl_setopt($this->ch, CURLOPT_POSTFIELDS, $data); - } else { - } - $this->debug('set cURL payload'); - return true; - } - } - - function getResponse(){ - $this->incoming_payload = ''; - - if ($this->scheme == 'http' || $this->scheme == 'ssl') { - // loop until headers have been retrieved - $data = ''; - while (!isset($lb)){ - - // We might EOF during header read. - if(feof($this->fp)) { - $this->incoming_payload = $data; - $this->debug('found no headers before EOF after length ' . strlen($data)); - $this->debug("received before EOF:\n" . $data); - $this->setError('server failed to send headers'); - return false; - } - - $tmp = fgets($this->fp, 256); - $tmplen = strlen($tmp); - $this->debug("read line of $tmplen bytes: " . trim($tmp)); - - if ($tmplen == 0) { - $this->incoming_payload = $data; - $this->debug('socket read of headers timed out after length ' . strlen($data)); - $this->debug("read before timeout: " . $data); - $this->setError('socket read of headers timed out'); - return false; - } - - $data .= $tmp; - $pos = strpos($data,"\r\n\r\n"); - if($pos > 1){ - $lb = "\r\n"; - } else { - $pos = strpos($data,"\n\n"); - if($pos > 1){ - $lb = "\n"; - } - } - // remove 100 header - if(isset($lb) && ereg('^HTTP/1.1 100',$data)){ - unset($lb); - $data = ''; - }// - } - // store header data - $this->incoming_payload .= $data; - $this->debug('found end of headers after length ' . strlen($data)); - // process headers - $header_data = trim(substr($data,0,$pos)); - $header_array = explode($lb,$header_data); - $this->incoming_headers = array(); - $this->incoming_cookies = array(); - foreach($header_array as $header_line){ - $arr = explode(':',$header_line, 2); - if(count($arr) > 1){ - $header_name = strtolower(trim($arr[0])); - $this->incoming_headers[$header_name] = trim($arr[1]); - if ($header_name == 'set-cookie') { - // TODO: allow multiple cookies from parseCookie - $cookie = $this->parseCookie(trim($arr[1])); - if ($cookie) { - $this->incoming_cookies[] = $cookie; - $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']); - } else { - $this->debug('did not find cookie in ' . trim($arr[1])); - } - } - } else if (isset($header_name)) { - // append continuation line to previous header - $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line; - } - } - - // loop until msg has been received - if (isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked') { - $content_length = 2147483647; // ignore any content-length header - $chunked = true; - $this->debug("want to read chunked content"); - } elseif (isset($this->incoming_headers['content-length'])) { - $content_length = $this->incoming_headers['content-length']; - $chunked = false; - $this->debug("want to read content of length $content_length"); - } else { - $content_length = 2147483647; - $chunked = false; - $this->debug("want to read content to EOF"); - } - $data = ''; - do { - if ($chunked) { - $tmp = fgets($this->fp, 256); - $tmplen = strlen($tmp); - $this->debug("read chunk line of $tmplen bytes"); - if ($tmplen == 0) { - $this->incoming_payload = $data; - $this->debug('socket read of chunk length timed out after length ' . strlen($data)); - $this->debug("read before timeout:\n" . $data); - $this->setError('socket read of chunk length timed out'); - return false; - } - $content_length = hexdec(trim($tmp)); - $this->debug("chunk length $content_length"); - } - $strlen = 0; - while (($strlen < $content_length) && (!feof($this->fp))) { - $readlen = min(8192, $content_length - $strlen); - $tmp = fread($this->fp, $readlen); - $tmplen = strlen($tmp); - $this->debug("read buffer of $tmplen bytes"); - if (($tmplen == 0) && (!feof($this->fp))) { - $this->incoming_payload = $data; - $this->debug('socket read of body timed out after length ' . strlen($data)); - $this->debug("read before timeout:\n" . $data); - $this->setError('socket read of body timed out'); - return false; - } - $strlen += $tmplen; - $data .= $tmp; - } - if ($chunked && ($content_length > 0)) { - $tmp = fgets($this->fp, 256); - $tmplen = strlen($tmp); - $this->debug("read chunk terminator of $tmplen bytes"); - if ($tmplen == 0) { - $this->incoming_payload = $data; - $this->debug('socket read of chunk terminator timed out after length ' . strlen($data)); - $this->debug("read before timeout:\n" . $data); - $this->setError('socket read of chunk terminator timed out'); - return false; - } - } - } while ($chunked && ($content_length > 0) && (!feof($this->fp))); - if (feof($this->fp)) { - $this->debug('read to EOF'); - } - $this->debug('read body of length ' . strlen($data)); - $this->incoming_payload .= $data; - $this->debug('received a total of '.strlen($this->incoming_payload).' bytes of data from server'); - - // close filepointer - if( - (isset($this->incoming_headers['connection']) && strtolower($this->incoming_headers['connection']) == 'close') || - (! $this->persistentConnection) || feof($this->fp)){ - fclose($this->fp); - $this->fp = false; - $this->debug('closed socket'); - } - - // connection was closed unexpectedly - if($this->incoming_payload == ''){ - $this->setError('no response from server'); - return false; - } - - // decode transfer-encoding -// if(isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked'){ -// if(!$data = $this->decodeChunked($data, $lb)){ -// $this->setError('Decoding of chunked data failed'); -// return false; -// } - //print "
\nde-chunked:\n---------------\n$data\n\n---------------\n
"; - // set decoded payload -// $this->incoming_payload = $header_data.$lb.$lb.$data; -// } - - } else if ($this->scheme == 'https') { - // send and receive - $this->debug('send and receive with cURL'); - $this->incoming_payload = curl_exec($this->ch); - $data = $this->incoming_payload; - - $cErr = curl_error($this->ch); - if ($cErr != '') { - $err = 'cURL ERROR: '.curl_errno($this->ch).': '.$cErr.'
'; - // TODO: there is a PHP bug that can cause this to SEGV for CURLINFO_CONTENT_TYPE - foreach(curl_getinfo($this->ch) as $k => $v){ - $err .= "$k: $v
"; - } - $this->debug($err); - $this->setError($err); - curl_close($this->ch); - return false; - } else { - //echo '
';
-			//var_dump(curl_getinfo($this->ch));
-			//echo '
'; - } - // close curl - $this->debug('No cURL error, closing cURL'); - curl_close($this->ch); - - // remove 100 header(s) - while (ereg('^HTTP/1.1 100',$data)) { - if ($pos = strpos($data,"\r\n\r\n")) { - $data = ltrim(substr($data,$pos)); - } elseif($pos = strpos($data,"\n\n") ) { - $data = ltrim(substr($data,$pos)); - } - } - - // separate content from HTTP headers - if ($pos = strpos($data,"\r\n\r\n")) { - $lb = "\r\n"; - } elseif( $pos = strpos($data,"\n\n")) { - $lb = "\n"; - } else { - $this->debug('no proper separation of headers and document'); - $this->setError('no proper separation of headers and document'); - return false; - } - $header_data = trim(substr($data,0,$pos)); - $header_array = explode($lb,$header_data); - $data = ltrim(substr($data,$pos)); - $this->debug('found proper separation of headers and document'); - $this->debug('cleaned data, stringlen: '.strlen($data)); - // clean headers - foreach ($header_array as $header_line) { - $arr = explode(':',$header_line,2); - if(count($arr) > 1){ - $header_name = strtolower(trim($arr[0])); - $this->incoming_headers[$header_name] = trim($arr[1]); - if ($header_name == 'set-cookie') { - // TODO: allow multiple cookies from parseCookie - $cookie = $this->parseCookie(trim($arr[1])); - if ($cookie) { - $this->incoming_cookies[] = $cookie; - $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']); - } else { - $this->debug('did not find cookie in ' . trim($arr[1])); - } - } - } else if (isset($header_name)) { - // append continuation line to previous header - $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line; - } - } - } - - $arr = explode(' ', $header_array[0], 3); - $http_version = $arr[0]; - $http_status = intval($arr[1]); - $http_reason = count($arr) > 2 ? $arr[2] : ''; - - // see if we need to resend the request with http digest authentication - if (isset($this->incoming_headers['location']) && $http_status == 301) { - $this->debug("Got 301 $http_reason with Location: " . $this->incoming_headers['location']); - $this->setURL($this->incoming_headers['location']); - $this->tryagain = true; - return false; - } - - // see if we need to resend the request with http digest authentication - if (isset($this->incoming_headers['www-authenticate']) && $http_status == 401) { - $this->debug("Got 401 $http_reason with WWW-Authenticate: " . $this->incoming_headers['www-authenticate']); - if (strstr($this->incoming_headers['www-authenticate'], "Digest ")) { - $this->debug('Server wants digest authentication'); - // remove "Digest " from our elements - $digestString = str_replace('Digest ', '', $this->incoming_headers['www-authenticate']); - - // parse elements into array - $digestElements = explode(',', $digestString); - foreach ($digestElements as $val) { - $tempElement = explode('=', trim($val), 2); - $digestRequest[$tempElement[0]] = str_replace("\"", '', $tempElement[1]); - } - - // should have (at least) qop, realm, nonce - if (isset($digestRequest['nonce'])) { - $this->setCredentials($this->username, $this->password, 'digest', $digestRequest); - $this->tryagain = true; - return false; - } - } - $this->debug('HTTP authentication failed'); - $this->setError('HTTP authentication failed'); - return false; - } - - if ( - ($http_status >= 300 && $http_status <= 307) || - ($http_status >= 400 && $http_status <= 417) || - ($http_status >= 501 && $http_status <= 505) - ) { - $this->setError("Unsupported HTTP response status $http_status $http_reason (soapclient->response has contents of the response)"); - return false; - } - - // decode content-encoding - if(isset($this->incoming_headers['content-encoding']) && $this->incoming_headers['content-encoding'] != ''){ - if(strtolower($this->incoming_headers['content-encoding']) == 'deflate' || strtolower($this->incoming_headers['content-encoding']) == 'gzip'){ - // if decoding works, use it. else assume data wasn't gzencoded - if(function_exists('gzinflate')){ - //$timer->setMarker('starting decoding of gzip/deflated content'); - // IIS 5 requires gzinflate instead of gzuncompress (similar to IE 5 and gzdeflate v. gzcompress) - // this means there are no Zlib headers, although there should be - $this->debug('The gzinflate function exists'); - $datalen = strlen($data); - if ($this->incoming_headers['content-encoding'] == 'deflate') { - if ($degzdata = @gzinflate($data)) { - $data = $degzdata; - $this->debug('The payload has been inflated to ' . strlen($data) . ' bytes'); - if (strlen($data) < $datalen) { - // test for the case that the payload has been compressed twice - $this->debug('The inflated payload is smaller than the gzipped one; try again'); - if ($degzdata = @gzinflate($data)) { - $data = $degzdata; - $this->debug('The payload has been inflated again to ' . strlen($data) . ' bytes'); - } - } - } else { - $this->debug('Error using gzinflate to inflate the payload'); - $this->setError('Error using gzinflate to inflate the payload'); - } - } elseif ($this->incoming_headers['content-encoding'] == 'gzip') { - if ($degzdata = @gzinflate(substr($data, 10))) { // do our best - $data = $degzdata; - $this->debug('The payload has been un-gzipped to ' . strlen($data) . ' bytes'); - if (strlen($data) < $datalen) { - // test for the case that the payload has been compressed twice - $this->debug('The un-gzipped payload is smaller than the gzipped one; try again'); - if ($degzdata = @gzinflate(substr($data, 10))) { - $data = $degzdata; - $this->debug('The payload has been un-gzipped again to ' . strlen($data) . ' bytes'); - } - } - } else { - $this->debug('Error using gzinflate to un-gzip the payload'); - $this->setError('Error using gzinflate to un-gzip the payload'); - } - } - //$timer->setMarker('finished decoding of gzip/deflated content'); - //print "\nde-inflated:\n---------------\n$data\n-------------\n"; - // set decoded payload - $this->incoming_payload = $header_data.$lb.$lb.$data; - } else { - $this->debug('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.'); - $this->setError('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.'); - } - } else { - $this->debug('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']); - $this->setError('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']); - } - } else { - $this->debug('No Content-Encoding header'); - } - - if(strlen($data) == 0){ - $this->debug('no data after headers!'); - $this->setError('no data present after HTTP headers'); - return false; - } - - return $data; - } - - function setContentType($type, $charset = false) { - $this->outgoing_headers['Content-Type'] = $type . ($charset ? '; charset=' . $charset : ''); - $this->debug('set Content-Type: ' . $this->outgoing_headers['Content-Type']); - } - - function usePersistentConnection(){ - if (isset($this->outgoing_headers['Accept-Encoding'])) { - return false; - } - $this->protocol_version = '1.1'; - $this->persistentConnection = true; - $this->outgoing_headers['Connection'] = 'Keep-Alive'; - $this->debug('set Connection: ' . $this->outgoing_headers['Connection']); - return true; - } - - /** - * parse an incoming Cookie into it's parts - * - * @param string $cookie_str content of cookie - * @return array with data of that cookie - * @access private - */ - /* - * TODO: allow a Set-Cookie string to be parsed into multiple cookies - */ - function parseCookie($cookie_str) { - $cookie_str = str_replace('; ', ';', $cookie_str) . ';'; - $data = explode(';', $cookie_str); - $value_str = $data[0]; - - $cookie_param = 'domain='; - $start = strpos($cookie_str, $cookie_param); - if ($start > 0) { - $domain = substr($cookie_str, $start + strlen($cookie_param)); - $domain = substr($domain, 0, strpos($domain, ';')); - } else { - $domain = ''; - } - - $cookie_param = 'expires='; - $start = strpos($cookie_str, $cookie_param); - if ($start > 0) { - $expires = substr($cookie_str, $start + strlen($cookie_param)); - $expires = substr($expires, 0, strpos($expires, ';')); - } else { - $expires = ''; - } - - $cookie_param = 'path='; - $start = strpos($cookie_str, $cookie_param); - if ( $start > 0 ) { - $path = substr($cookie_str, $start + strlen($cookie_param)); - $path = substr($path, 0, strpos($path, ';')); - } else { - $path = '/'; - } - - $cookie_param = ';secure;'; - if (strpos($cookie_str, $cookie_param) !== FALSE) { - $secure = true; - } else { - $secure = false; - } - - $sep_pos = strpos($value_str, '='); - - if ($sep_pos) { - $name = substr($value_str, 0, $sep_pos); - $value = substr($value_str, $sep_pos + 1); - $cookie= array( 'name' => $name, - 'value' => $value, - 'domain' => $domain, - 'path' => $path, - 'expires' => $expires, - 'secure' => $secure - ); - return $cookie; - } - return false; - } - - /** - * sort out cookies for the current request - * - * @param array $cookies array with all cookies - * @param boolean $secure is the send-content secure or not? - * @return string for Cookie-HTTP-Header - * @access private - */ - function getCookiesForRequest($cookies, $secure=false) { - $cookie_str = ''; - if ((! is_null($cookies)) && (is_array($cookies))) { - foreach ($cookies as $cookie) { - if (! is_array($cookie)) { - continue; - } - $this->debug("check cookie for validity: ".$cookie['name'].'='.$cookie['value']); - if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) { - if (strtotime($cookie['expires']) <= time()) { - $this->debug('cookie has expired'); - continue; - } - } - if ((isset($cookie['domain'])) && (! empty($cookie['domain']))) { - $domain = preg_quote($cookie['domain']); - if (! preg_match("'.*$domain$'i", $this->host)) { - $this->debug('cookie has different domain'); - continue; - } - } - if ((isset($cookie['path'])) && (! empty($cookie['path']))) { - $path = preg_quote($cookie['path']); - if (! preg_match("'^$path.*'i", $this->path)) { - $this->debug('cookie is for a different path'); - continue; - } - } - if ((! $secure) && (isset($cookie['secure'])) && ($cookie['secure'])) { - $this->debug('cookie is secure, transport is not'); - continue; - } - $cookie_str .= $cookie['name'] . '=' . $cookie['value'] . '; '; - $this->debug('add cookie to Cookie-String: ' . $cookie['name'] . '=' . $cookie['value']); - } - } - return $cookie_str; - } -} - - -?> diff --git a/gulliver/thirdparty/pear/class.soap_val.php b/gulliver/thirdparty/pear/class.soap_val.php deleted file mode 100644 index c3618eb08..000000000 --- a/gulliver/thirdparty/pear/class.soap_val.php +++ /dev/null @@ -1,107 +0,0 @@ - -* @version $Id: class.soap_val.php,v 1.9 2005/07/27 19:24:42 snichol Exp $ -* @access public -*/ -class soapval extends nusoap_base { - /** - * The XML element name - * - * @var string - * @access private - */ - var $name; - /** - * The XML type name (string or false) - * - * @var mixed - * @access private - */ - var $type; - /** - * The PHP value - * - * @var mixed - * @access private - */ - var $value; - /** - * The XML element namespace (string or false) - * - * @var mixed - * @access private - */ - var $element_ns; - /** - * The XML type namespace (string or false) - * - * @var mixed - * @access private - */ - var $type_ns; - /** - * The XML element attributes (array or false) - * - * @var mixed - * @access private - */ - var $attributes; - - /** - * constructor - * - * @param string $name optional name - * @param mixed $type optional type name - * @param mixed $value optional value - * @param mixed $element_ns optional namespace of value - * @param mixed $type_ns optional namespace of type - * @param mixed $attributes associative array of attributes to add to element serialization - * @access public - */ - function soapval($name='soapval',$type=false,$value=-1,$element_ns=false,$type_ns=false,$attributes=false) { - parent::nusoap_base(); - $this->name = $name; - $this->type = $type; - $this->value = $value; - $this->element_ns = $element_ns; - $this->type_ns = $type_ns; - $this->attributes = $attributes; - } - - /** - * return serialized value - * - * @param string $use The WSDL use value (encoded|literal) - * @return string XML data - * @access public - */ - function serialize($use='encoded') { - return $this->serialize_val($this->value,$this->name,$this->type,$this->element_ns,$this->type_ns,$this->attributes,$use); - } - - /** - * decodes a soapval object into a PHP native type - * - * @return mixed - * @access public - */ - function decode(){ - return $this->value; - } -} - - - - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/class.soapclient.php b/gulliver/thirdparty/pear/class.soapclient.php deleted file mode 100644 index e1bf899a3..000000000 --- a/gulliver/thirdparty/pear/class.soapclient.php +++ /dev/null @@ -1,859 +0,0 @@ -call( string methodname [ ,array parameters] ); -* -* // bye bye client -* unset($soapclient); -* -* @author Dietrich Ayala -* @version $Id: class.soapclient.php,v 1.52 2005/07/27 19:24:42 snichol Exp $ -* @access public -*/ -class soapclient extends nusoap_base { - - var $username = ''; - var $password = ''; - var $authtype = ''; - var $certRequest = array(); - var $requestHeaders = false; // SOAP headers in request (text) - var $responseHeaders = ''; // SOAP headers from response (incomplete namespace resolution) (text) - var $document = ''; // SOAP body response portion (incomplete namespace resolution) (text) - var $endpoint; - var $forceEndpoint = ''; // overrides WSDL endpoint - var $proxyhost = ''; - var $proxyport = ''; - var $proxyusername = ''; - var $proxypassword = ''; - var $xml_encoding = ''; // character set encoding of incoming (response) messages - var $http_encoding = false; - var $timeout = 0; // HTTP connection timeout - var $response_timeout = 30; // HTTP response timeout - var $endpointType = ''; // soap|wsdl, empty for WSDL initialization error - var $persistentConnection = false; - var $defaultRpcParams = false; // This is no longer used - var $request = ''; // HTTP request - var $response = ''; // HTTP response - var $responseData = ''; // SOAP payload of response - var $cookies = array(); // Cookies from response or for request - var $decode_utf8 = true; // toggles whether the parser decodes element content w/ utf8_decode() - var $operations = array(); // WSDL operations, empty for WSDL initialization error - - /* - * fault related variables - */ - /** - * @var fault - * @access public - */ - var $fault; - /** - * @var faultcode - * @access public - */ - var $faultcode; - /** - * @var faultstring - * @access public - */ - var $faultstring; - /** - * @var faultdetail - * @access public - */ - var $faultdetail; - - /** - * constructor - * - * @param mixed $endpoint SOAP server or WSDL URL (string), or wsdl instance (object) - * @param bool $wsdl optional, set to true if using WSDL - * @param int $portName optional portName in WSDL document - * @param string $proxyhost - * @param string $proxyport - * @param string $proxyusername - * @param string $proxypassword - * @param integer $timeout set the connection timeout - * @param integer $response_timeout set the response timeout - * @access public - */ - function soapclient($endpoint,$wsdl = false,$proxyhost = false,$proxyport = false,$proxyusername = false, $proxypassword = false, $timeout = 0, $response_timeout = 30){ - parent::nusoap_base(); - $this->endpoint = $endpoint; - $this->proxyhost = $proxyhost; - $this->proxyport = $proxyport; - $this->proxyusername = $proxyusername; - $this->proxypassword = $proxypassword; - $this->timeout = $timeout; - $this->response_timeout = $response_timeout; - - // make values - if($wsdl){ - if (is_object($endpoint) && (get_class($endpoint) == 'wsdl')) { - $this->wsdl = $endpoint; - $this->endpoint = $this->wsdl->wsdl; - $this->wsdlFile = $this->endpoint; - $this->debug('existing wsdl instance created from ' . $this->endpoint); - } else { - $this->wsdlFile = $this->endpoint; - - // instantiate wsdl object and parse wsdl file - $this->debug('instantiating wsdl class with doc: '.$endpoint); - $this->wsdl =& new wsdl($this->wsdlFile,$this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword,$this->timeout,$this->response_timeout); - } - $this->appendDebug($this->wsdl->getDebug()); - $this->wsdl->clearDebug(); - // catch errors - if($errstr = $this->wsdl->getError()){ - $this->debug('got wsdl error: '.$errstr); - $this->setError('wsdl error: '.$errstr); - } elseif($this->operations = $this->wsdl->getOperations()){ - $this->debug( 'got '.count($this->operations).' operations from wsdl '.$this->wsdlFile); - $this->endpointType = 'wsdl'; - } else { - $this->debug( 'getOperations returned false'); - $this->setError('no operations defined in the WSDL document!'); - } - } else { - $this->debug("instantiate SOAP with endpoint at $endpoint"); - $this->endpointType = 'soap'; - } - } - - /** - * calls method, returns PHP native type - * - * @param string $method SOAP server URL or path - * @param mixed $params An array, associative or simple, of the parameters - * for the method call, or a string that is the XML - * for the call. For rpc style, this call will - * wrap the XML in a tag named after the method, as - * well as the SOAP Envelope and Body. For document - * style, this will only wrap with the Envelope and Body. - * IMPORTANT: when using an array with document style, - * in which case there - * is really one parameter, the root of the fragment - * used in the call, which encloses what programmers - * normally think of parameters. A parameter array - * *must* include the wrapper. - * @param string $namespace optional method namespace (WSDL can override) - * @param string $soapAction optional SOAPAction value (WSDL can override) - * @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers - * @param boolean $rpcParams optional (no longer used) - * @param string $style optional (rpc|document) the style to use when serializing parameters (WSDL can override) - * @param string $use optional (encoded|literal) the use when serializing parameters (WSDL can override) - * @return mixed response from SOAP call - * @access public - */ - function call($operation,$params=array(),$namespace='http://tempuri.org',$soapAction='',$headers=false,$rpcParams=null,$style='rpc',$use='encoded'){ - $this->operation = $operation; - $this->fault = false; - $this->setError(''); - $this->request = ''; - $this->response = ''; - $this->responseData = ''; - $this->faultstring = ''; - $this->faultcode = ''; - $this->opData = array(); - - $this->debug("call: operation=$operation, namespace=$namespace, soapAction=$soapAction, rpcParams=$rpcParams, style=$style, use=$use, endpointType=$this->endpointType"); - $this->appendDebug('params=' . $this->varDump($params)); - $this->appendDebug('headers=' . $this->varDump($headers)); - if ($headers) { - $this->requestHeaders = $headers; - } - // serialize parameters - if($this->endpointType == 'wsdl' && $opData = $this->getOperationData($operation)){ - // use WSDL for operation - $this->opData = $opData; - $this->debug("found operation"); - $this->appendDebug('opData=' . $this->varDump($opData)); - if (isset($opData['soapAction'])) { - $soapAction = $opData['soapAction']; - } - if (! $this->forceEndpoint) { - $this->endpoint = $opData['endpoint']; - } else { - $this->endpoint = $this->forceEndpoint; - } - $namespace = isset($opData['input']['namespace']) ? $opData['input']['namespace'] : $namespace; - $style = $opData['style']; - $use = $opData['input']['use']; - // add ns to ns array - if($namespace != '' && !isset($this->wsdl->namespaces[$namespace])){ - $nsPrefix = 'ns' . rand(1000, 9999); - $this->wsdl->namespaces[$nsPrefix] = $namespace; - } - $nsPrefix = $this->wsdl->getPrefixFromNamespace($namespace); - // serialize payload - if (is_string($params)) { - $this->debug("serializing param string for WSDL operation $operation"); - $payload = $params; - } elseif (is_array($params)) { - $this->debug("serializing param array for WSDL operation $operation"); - $payload = $this->wsdl->serializeRPCParameters($operation,'input',$params); - } else { - $this->debug('params must be array or string'); - $this->setError('params must be array or string'); - return false; - } - $usedNamespaces = $this->wsdl->usedNamespaces; - if (isset($opData['input']['encodingStyle'])) { - $encodingStyle = $opData['input']['encodingStyle']; - } else { - $encodingStyle = ''; - } - $this->appendDebug($this->wsdl->getDebug()); - $this->wsdl->clearDebug(); - if ($errstr = $this->wsdl->getError()) { - $this->debug('got wsdl error: '.$errstr); - $this->setError('wsdl error: '.$errstr); - return false; - } - } elseif($this->endpointType == 'wsdl') { - // operation not in WSDL - $this->appendDebug($this->wsdl->getDebug()); - $this->wsdl->clearDebug(); - $this->setError( 'operation '.$operation.' not present.'); - $this->debug("operation '$operation' not present."); - return false; - } else { - // no WSDL - //$this->namespaces['ns1'] = $namespace; - $nsPrefix = 'ns' . rand(1000, 9999); - // serialize - $payload = ''; - if (is_string($params)) { - $this->debug("serializing param string for operation $operation"); - $payload = $params; - } elseif (is_array($params)) { - $this->debug("serializing param array for operation $operation"); - foreach($params as $k => $v){ - $payload .= $this->serialize_val($v,$k,false,false,false,false,$use); - } - } else { - $this->debug('params must be array or string'); - $this->setError('params must be array or string'); - return false; - } - $usedNamespaces = array(); - if ($use == 'encoded') { - $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; - } else { - $encodingStyle = ''; - } - } - // wrap RPC calls with method element - if ($style == 'rpc') { - if ($use == 'literal') { - $this->debug("wrapping RPC request with literal method element"); - if ($namespace) { - $payload = "<$operation xmlns=\"$namespace\">" . $payload . ""; - } else { - $payload = "<$operation>" . $payload . ""; - } - } else { - $this->debug("wrapping RPC request with encoded method element"); - if ($namespace) { - $payload = "<$nsPrefix:$operation xmlns:$nsPrefix=\"$namespace\">" . - $payload . - ""; - } else { - $payload = "<$operation>" . - $payload . - ""; - } - } - } - // serialize envelope - $soapmsg = $this->serializeEnvelope($payload,$this->requestHeaders,$usedNamespaces,$style,$use,$encodingStyle); - $this->debug("endpoint=$this->endpoint, soapAction=$soapAction, namespace=$namespace, style=$style, use=$use, encodingStyle=$encodingStyle"); - $this->debug('SOAP message length=' . strlen($soapmsg) . ' contents (max 1000 bytes)=' . substr($soapmsg, 0, 1000)); - // send - $return = $this->send($this->getHTTPBody($soapmsg),$soapAction,$this->timeout,$this->response_timeout); - if($errstr = $this->getError()){ - $this->debug('Error: '.$errstr); - return false; - } else { - $this->return = $return; - $this->debug('sent message successfully and got a(n) '.gettype($return)); - $this->appendDebug('return=' . $this->varDump($return)); - - // fault? - if(is_array($return) && isset($return['faultcode'])){ - $this->debug('got fault'); - $this->setError($return['faultcode'].': '.$return['faultstring']); - $this->fault = true; - foreach($return as $k => $v){ - $this->$k = $v; - $this->debug("$k = $v
"); - } - return $return; - } elseif ($style == 'document') { - // NOTE: if the response is defined to have multiple parts (i.e. unwrapped), - // we are only going to return the first part here...sorry about that - return $return; - } else { - // array of return values - if(is_array($return)){ - // multiple 'out' parameters, which we return wrapped up - // in the array - if(sizeof($return) > 1){ - return $return; - } - // single 'out' parameter (normally the return value) - $return = array_shift($return); - $this->debug('return shifted value: '); - $this->appendDebug($this->varDump($return)); - return $return; - // nothing returned (ie, echoVoid) - } else { - return ""; - } - } - } - } - - /** - * get available data pertaining to an operation - * - * @param string $operation operation name - * @return array array of data pertaining to the operation - * @access public - */ - function getOperationData($operation){ - if(isset($this->operations[$operation])){ - return $this->operations[$operation]; - } - $this->debug("No data for operation: $operation"); - } - - /** - * send the SOAP message - * - * Note: if the operation has multiple return values - * the return value of this method will be an array - * of those values. - * - * @param string $msg a SOAPx4 soapmsg object - * @param string $soapaction SOAPAction value - * @param integer $timeout set connection timeout in seconds - * @param integer $response_timeout set response timeout in seconds - * @return mixed native PHP types. - * @access private - */ - function send($msg, $soapaction = '', $timeout=0, $response_timeout=30) { - $this->checkCookies(); - // detect transport - switch(true){ - // http(s) - case ereg('^http',$this->endpoint): - $this->debug('transporting via HTTP'); - if($this->persistentConnection == true && is_object($this->persistentConnection)){ - $http =& $this->persistentConnection; - } else { - $http = new soap_transport_http($this->endpoint); - if ($this->persistentConnection) { - $http->usePersistentConnection(); - } - } - $http->setContentType($this->getHTTPContentType(), $this->getHTTPContentTypeCharset()); - $http->setSOAPAction($soapaction); - if($this->proxyhost && $this->proxyport){ - $http->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword); - } - if($this->authtype != '') { - $http->setCredentials($this->username, $this->password, $this->authtype, array(), $this->certRequest); - } - if($this->http_encoding != ''){ - $http->setEncoding($this->http_encoding); - } - $this->debug('sending message, length='.strlen($msg)); - if(ereg('^http:',$this->endpoint)){ - //if(strpos($this->endpoint,'http:')){ - $this->responseData = $http->send($msg,$timeout,$response_timeout,$this->cookies); - } elseif(ereg('^https',$this->endpoint)){ - //} elseif(strpos($this->endpoint,'https:')){ - //if(phpversion() == '4.3.0-dev'){ - //$response = $http->send($msg,$timeout,$response_timeout); - //$this->request = $http->outgoing_payload; - //$this->response = $http->incoming_payload; - //} else - $this->responseData = $http->sendHTTPS($msg,$timeout,$response_timeout,$this->cookies); - } else { - $this->setError('no http/s in endpoint url'); - } - $this->request = $http->outgoing_payload; - $this->response = $http->incoming_payload; - $this->appendDebug($http->getDebug()); - $this->UpdateCookies($http->incoming_cookies); - - // save transport object if using persistent connections - if ($this->persistentConnection) { - $http->clearDebug(); - if (!is_object($this->persistentConnection)) { - $this->persistentConnection = $http; - } - } - - if($err = $http->getError()){ - $this->setError('HTTP Error: '.$err); - return false; - } elseif($this->getError()){ - return false; - } else { - $this->debug('got response, length='. strlen($this->responseData).' type='.$http->incoming_headers['content-type']); - return $this->parseResponse($http->incoming_headers, $this->responseData); - } - break; - default: - $this->setError('no transport found, or selected transport is not yet supported!'); - return false; - break; - } - } - - /** - * processes SOAP message returned from server - * - * @param array $headers The HTTP headers - * @param string $data unprocessed response data from server - * @return mixed value of the message, decoded into a PHP type - * @access private - */ - function parseResponse($headers, $data) { - $this->debug('Entering parseResponse() for data of length ' . strlen($data) . ' and type ' . $headers['content-type']); - if (!strstr($headers['content-type'], 'text/xml')) { - $this->setError('Response not of type text/xml'); - return false; - } - if (strpos($headers['content-type'], '=')) { - $enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1)); - $this->debug('Got response encoding: ' . $enc); - if(preg_match('/(ISO-8859-1|US-ASCII|UTF-8)/',$enc)){ - $this->xml_encoding = strtoupper($enc); - } else { - $this->xml_encoding = 'US-ASCII'; - } - } else { - // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 - $this->xml_encoding = 'ISO-8859-1'; - } - $this->debug('Use encoding: ' . $this->xml_encoding . ' when creating soap_parser'); - $parser = new soap_parser($data,$this->xml_encoding,$this->operation,$this->decode_utf8); - // add parser debug data to our debug - $this->appendDebug($parser->getDebug()); - // if parse errors - if($errstr = $parser->getError()){ - $this->setError( $errstr); - // destroy the parser object - unset($parser); - return false; - } else { - // get SOAP headers - $this->responseHeaders = $parser->getHeaders(); - // get decoded message - $return = $parser->get_response(); - // add document for doclit support - $this->document = $parser->document; - // destroy the parser object - unset($parser); - // return decode message - return $return; - } - } - - /** - * sets the SOAP endpoint, which can override WSDL - * - * @param $endpoint string The endpoint URL to use, or empty string or false to prevent override - * @access public - */ - function setEndpoint($endpoint) { - $this->forceEndpoint = $endpoint; - } - - /** - * set the SOAP headers - * - * @param $headers mixed String of XML with SOAP header content, or array of soapval objects for SOAP headers - * @access public - */ - function setHeaders($headers){ - $this->requestHeaders = $headers; - } - - /** - * get the SOAP response headers (namespace resolution incomplete) - * - * @return string - * @access public - */ - function getHeaders(){ - return $this->responseHeaders; - } - - /** - * set proxy info here - * - * @param string $proxyhost - * @param string $proxyport - * @param string $proxyusername - * @param string $proxypassword - * @access public - */ - function setHTTPProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '') { - $this->proxyhost = $proxyhost; - $this->proxyport = $proxyport; - $this->proxyusername = $proxyusername; - $this->proxypassword = $proxypassword; - } - - /** - * if authenticating, set user credentials here - * - * @param string $username - * @param string $password - * @param string $authtype (basic|digest|certificate) - * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs) - * @access public - */ - function setCredentials($username, $password, $authtype = 'basic', $certRequest = array()) { - $this->username = $username; - $this->password = $password; - $this->authtype = $authtype; - $this->certRequest = $certRequest; - } - - /** - * use HTTP encoding - * - * @param string $enc - * @access public - */ - function setHTTPEncoding($enc='gzip, deflate'){ - $this->http_encoding = $enc; - } - - /** - * use HTTP persistent connections if possible - * - * @access public - */ - function useHTTPPersistentConnection(){ - $this->persistentConnection = true; - } - - /** - * gets the default RPC parameter setting. - * If true, default is that call params are like RPC even for document style. - * Each call() can override this value. - * - * This is no longer used. - * - * @return boolean - * @access public - * @deprecated - */ - function getDefaultRpcParams() { - return $this->defaultRpcParams; - } - - /** - * sets the default RPC parameter setting. - * If true, default is that call params are like RPC even for document style - * Each call() can override this value. - * - * This is no longer used. - * - * @param boolean $rpcParams - * @access public - * @deprecated - */ - function setDefaultRpcParams($rpcParams) { - $this->defaultRpcParams = $rpcParams; - } - - /** - * dynamically creates an instance of a proxy class, - * allowing user to directly call methods from wsdl - * - * @return object soap_proxy object - * @access public - */ - function getProxy(){ - $r = rand(); - $evalStr = $this->_getProxyClassCode($r); - //$this->debug("proxy class: $evalStr"; - // eval the class - eval($evalStr); - // instantiate proxy object - eval("\$proxy = new soap_proxy_$r('');"); - // transfer current wsdl data to the proxy thereby avoiding parsing the wsdl twice - $proxy->endpointType = 'wsdl'; - $proxy->wsdlFile = $this->wsdlFile; - $proxy->wsdl = $this->wsdl; - $proxy->operations = $this->operations; - $proxy->defaultRpcParams = $this->defaultRpcParams; - // transfer other state - $proxy->username = $this->username; - $proxy->password = $this->password; - $proxy->authtype = $this->authtype; - $proxy->proxyhost = $this->proxyhost; - $proxy->proxyport = $this->proxyport; - $proxy->proxyusername = $this->proxyusername; - $proxy->proxypassword = $this->proxypassword; - $proxy->timeout = $this->timeout; - $proxy->response_timeout = $this->response_timeout; - $proxy->http_encoding = $this->http_encoding; - $proxy->persistentConnection = $this->persistentConnection; - $proxy->requestHeaders = $this->requestHeaders; - $proxy->soap_defencoding = $this->soap_defencoding; - $proxy->endpoint = $this->endpoint; - $proxy->forceEndpoint = $this->forceEndpoint; - return $proxy; - } - - /** - * dynamically creates proxy class code - * - * @return string PHP/NuSOAP code for the proxy class - * @access private - */ - function _getProxyClassCode($r) { - if ($this->endpointType != 'wsdl') { - $evalStr = 'A proxy can only be created for a WSDL client'; - $this->setError($evalStr); - return $evalStr; - } - $evalStr = ''; - foreach ($this->operations as $operation => $opData) { - if ($operation != '') { - // create param string and param comment string - if (sizeof($opData['input']['parts']) > 0) { - $paramStr = ''; - $paramArrayStr = ''; - $paramCommentStr = ''; - foreach ($opData['input']['parts'] as $name => $type) { - $paramStr .= "\$$name, "; - $paramArrayStr .= "'$name' => \$$name, "; - $paramCommentStr .= "$type \$$name, "; - } - $paramStr = substr($paramStr, 0, strlen($paramStr)-2); - $paramArrayStr = substr($paramArrayStr, 0, strlen($paramArrayStr)-2); - $paramCommentStr = substr($paramCommentStr, 0, strlen($paramCommentStr)-2); - } else { - $paramStr = ''; - $paramCommentStr = 'void'; - } - $opData['namespace'] = !isset($opData['namespace']) ? 'http://testuri.com' : $opData['namespace']; - $evalStr .= "// $paramCommentStr - function " . str_replace('.', '__', $operation) . "($paramStr) { - \$params = array($paramArrayStr); - return \$this->call('$operation', \$params, '".$opData['namespace']."', '".(isset($opData['soapAction']) ? $opData['soapAction'] : '')."'); - } - "; - unset($paramStr); - unset($paramCommentStr); - } - } - $evalStr = 'class soap_proxy_'.$r.' extends soapclient { - '.$evalStr.' -}'; - return $evalStr; - } - - /** - * dynamically creates proxy class code - * - * @return string PHP/NuSOAP code for the proxy class - * @access public - */ - function getProxyClassCode() { - $r = rand(); - return $this->_getProxyClassCode($r); - } - - /** - * gets the HTTP body for the current request. - * - * @param string $soapmsg The SOAP payload - * @return string The HTTP body, which includes the SOAP payload - * @access private - */ - function getHTTPBody($soapmsg) { - return $soapmsg; - } - - /** - * gets the HTTP content type for the current request. - * - * Note: getHTTPBody must be called before this. - * - * @return string the HTTP content type for the current request. - * @access private - */ - function getHTTPContentType() { - return 'text/xml'; - } - - /** - * gets the HTTP content type charset for the current request. - * returns false for non-text content types. - * - * Note: getHTTPBody must be called before this. - * - * @return string the HTTP content type charset for the current request. - * @access private - */ - function getHTTPContentTypeCharset() { - return $this->soap_defencoding; - } - - /* - * whether or not parser should decode utf8 element content - * - * @return always returns true - * @access public - */ - function decodeUTF8($bool){ - $this->decode_utf8 = $bool; - return true; - } - - /** - * adds a new Cookie into $this->cookies array - * - * @param string $name Cookie Name - * @param string $value Cookie Value - * @return if cookie-set was successful returns true, else false - * @access public - */ - function setCookie($name, $value) { - if (strlen($name) == 0) { - return false; - } - $this->cookies[] = array('name' => $name, 'value' => $value); - return true; - } - - /** - * gets all Cookies - * - * @return array with all internal cookies - * @access public - */ - function getCookies() { - return $this->cookies; - } - - /** - * checks all Cookies and delete those which are expired - * - * @return always return true - * @access private - */ - function checkCookies() { - if (sizeof($this->cookies) == 0) { - return true; - } - $this->debug('checkCookie: check ' . sizeof($this->cookies) . ' cookies'); - $curr_cookies = $this->cookies; - $this->cookies = array(); - foreach ($curr_cookies as $cookie) { - if (! is_array($cookie)) { - $this->debug('Remove cookie that is not an array'); - continue; - } - if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) { - if (strtotime($cookie['expires']) > time()) { - $this->cookies[] = $cookie; - } else { - $this->debug('Remove expired cookie ' . $cookie['name']); - } - } else { - $this->cookies[] = $cookie; - } - } - $this->debug('checkCookie: '.sizeof($this->cookies).' cookies left in array'); - return true; - } - - /** - * updates the current cookies with a new set - * - * @param array $cookies new cookies with which to update current ones - * @return always return true - * @access private - */ - function UpdateCookies($cookies) { - if (sizeof($this->cookies) == 0) { - // no existing cookies: take whatever is new - if (sizeof($cookies) > 0) { - $this->debug('Setting new cookie(s)'); - $this->cookies = $cookies; - } - return true; - } - if (sizeof($cookies) == 0) { - // no new cookies: keep what we've got - return true; - } - // merge - foreach ($cookies as $newCookie) { - if (!is_array($newCookie)) { - continue; - } - if ((!isset($newCookie['name'])) || (!isset($newCookie['value']))) { - continue; - } - $newName = $newCookie['name']; - - $found = false; - for ($i = 0; $i < count($this->cookies); $i++) { - $cookie = $this->cookies[$i]; - if (!is_array($cookie)) { - continue; - } - if (!isset($cookie['name'])) { - continue; - } - if ($newName != $cookie['name']) { - continue; - } - $newDomain = isset($newCookie['domain']) ? $newCookie['domain'] : 'NODOMAIN'; - $domain = isset($cookie['domain']) ? $cookie['domain'] : 'NODOMAIN'; - if ($newDomain != $domain) { - continue; - } - $newPath = isset($newCookie['path']) ? $newCookie['path'] : 'NOPATH'; - $path = isset($cookie['path']) ? $cookie['path'] : 'NOPATH'; - if ($newPath != $path) { - continue; - } - $this->cookies[$i] = $newCookie; - $found = true; - $this->debug('Update cookie ' . $newName . '=' . $newCookie['value']); - break; - } - if (! $found) { - $this->debug('Add cookie ' . $newName . '=' . $newCookie['value']); - $this->cookies[] = $newCookie; - } - } - return true; - } -} -?> diff --git a/gulliver/thirdparty/pear/class.wsdl.php b/gulliver/thirdparty/pear/class.wsdl.php deleted file mode 100644 index 0d4100927..000000000 --- a/gulliver/thirdparty/pear/class.wsdl.php +++ /dev/null @@ -1,1727 +0,0 @@ - -* @version $Id: class.wsdl.php,v 1.56 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class wsdl extends nusoap_base { - // URL or filename of the root of this WSDL - var $wsdl; - // define internal arrays of bindings, ports, operations, messages, etc. - var $schemas = array(); - var $currentSchema; - var $message = array(); - var $complexTypes = array(); - var $messages = array(); - var $currentMessage; - var $currentOperation; - var $portTypes = array(); - var $currentPortType; - var $bindings = array(); - var $currentBinding; - var $ports = array(); - var $currentPort; - var $opData = array(); - var $status = ''; - var $documentation = false; - var $endpoint = ''; - // array of wsdl docs to import - var $import = array(); - // parser vars - var $parser; - var $position = 0; - var $depth = 0; - var $depth_array = array(); - // for getting wsdl - var $proxyhost = ''; - var $proxyport = ''; - var $proxyusername = ''; - var $proxypassword = ''; - var $timeout = 0; - var $response_timeout = 30; - - /** - * constructor - * - * @param string $wsdl WSDL document URL - * @param string $proxyhost - * @param string $proxyport - * @param string $proxyusername - * @param string $proxypassword - * @param integer $timeout set the connection timeout - * @param integer $response_timeout set the response timeout - * @access public - */ - function wsdl($wsdl = '',$proxyhost=false,$proxyport=false,$proxyusername=false,$proxypassword=false,$timeout=0,$response_timeout=30){ - parent::nusoap_base(); - $this->wsdl = $wsdl; - $this->proxyhost = $proxyhost; - $this->proxyport = $proxyport; - $this->proxyusername = $proxyusername; - $this->proxypassword = $proxypassword; - $this->timeout = $timeout; - $this->response_timeout = $response_timeout; - - // parse wsdl file - if ($wsdl != "") { - $this->debug('initial wsdl URL: ' . $wsdl); - $this->parseWSDL($wsdl); - } - // imports - // TODO: handle imports more properly, grabbing them in-line and nesting them - $imported_urls = array(); - $imported = 1; - while ($imported > 0) { - $imported = 0; - // Schema imports - foreach ($this->schemas as $ns => $list) { - foreach ($list as $xs) { - $wsdlparts = parse_url($this->wsdl); // this is bogusly simple! - foreach ($xs->imports as $ns2 => $list2) { - for ($ii = 0; $ii < count($list2); $ii++) { - if (! $list2[$ii]['loaded']) { - $this->schemas[$ns]->imports[$ns2][$ii]['loaded'] = true; - $url = $list2[$ii]['location']; - if ($url != '') { - $urlparts = parse_url($url); - if (!isset($urlparts['host'])) { - $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' .$wsdlparts['port'] : '') . - substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path']; - } - if (! in_array($url, $imported_urls)) { - $this->parseWSDL($url); - $imported++; - $imported_urls[] = $url; - } - } else { - $this->debug("Unexpected scenario: empty URL for unloaded import"); - } - } - } - } - } - } - // WSDL imports - $wsdlparts = parse_url($this->wsdl); // this is bogusly simple! - foreach ($this->import as $ns => $list) { - for ($ii = 0; $ii < count($list); $ii++) { - if (! $list[$ii]['loaded']) { - $this->import[$ns][$ii]['loaded'] = true; - $url = $list[$ii]['location']; - if ($url != '') { - $urlparts = parse_url($url); - if (!isset($urlparts['host'])) { - $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' . $wsdlparts['port'] : '') . - substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path']; - } - if (! in_array($url, $imported_urls)) { - $this->parseWSDL($url); - $imported++; - $imported_urls[] = $url; - } - } else { - $this->debug("Unexpected scenario: empty URL for unloaded import"); - } - } - } - } - } - // add new data to operation data - foreach($this->bindings as $binding => $bindingData) { - if (isset($bindingData['operations']) && is_array($bindingData['operations'])) { - foreach($bindingData['operations'] as $operation => $data) { - $this->debug('post-parse data gathering for ' . $operation); - $this->bindings[$binding]['operations'][$operation]['input'] = - isset($this->bindings[$binding]['operations'][$operation]['input']) ? - array_merge($this->bindings[$binding]['operations'][$operation]['input'], $this->portTypes[ $bindingData['portType'] ][$operation]['input']) : - $this->portTypes[ $bindingData['portType'] ][$operation]['input']; - $this->bindings[$binding]['operations'][$operation]['output'] = - isset($this->bindings[$binding]['operations'][$operation]['output']) ? - array_merge($this->bindings[$binding]['operations'][$operation]['output'], $this->portTypes[ $bindingData['portType'] ][$operation]['output']) : - $this->portTypes[ $bindingData['portType'] ][$operation]['output']; - if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ])){ - $this->bindings[$binding]['operations'][$operation]['input']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ]; - } - if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ])){ - $this->bindings[$binding]['operations'][$operation]['output']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ]; - } - if (isset($bindingData['style'])) { - $this->bindings[$binding]['operations'][$operation]['style'] = $bindingData['style']; - } - $this->bindings[$binding]['operations'][$operation]['transport'] = isset($bindingData['transport']) ? $bindingData['transport'] : ''; - $this->bindings[$binding]['operations'][$operation]['documentation'] = isset($this->portTypes[ $bindingData['portType'] ][$operation]['documentation']) ? $this->portTypes[ $bindingData['portType'] ][$operation]['documentation'] : ''; - $this->bindings[$binding]['operations'][$operation]['endpoint'] = isset($bindingData['endpoint']) ? $bindingData['endpoint'] : ''; - } - } - } - } - - /** - * parses the wsdl document - * - * @param string $wsdl path or URL - * @access private - */ - function parseWSDL($wsdl = '') - { - if ($wsdl == '') { - $this->debug('no wsdl passed to parseWSDL()!!'); - $this->setError('no wsdl passed to parseWSDL()!!'); - return false; - } - - // parse $wsdl for url format - $wsdl_props = parse_url($wsdl); - - if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'http' || $wsdl_props['scheme'] == 'https')) { - $this->debug('getting WSDL http(s) URL ' . $wsdl); - // get wsdl - $tr = new soap_transport_http($wsdl); - $tr->request_method = 'GET'; - $tr->useSOAPAction = false; - if($this->proxyhost && $this->proxyport){ - $tr->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword); - } - $tr->setEncoding('gzip, deflate'); - $wsdl_string = $tr->send('', $this->timeout, $this->response_timeout); - //$this->debug("WSDL request\n" . $tr->outgoing_payload); - //$this->debug("WSDL response\n" . $tr->incoming_payload); - $this->appendDebug($tr->getDebug()); - // catch errors - if($err = $tr->getError() ){ - $errstr = 'HTTP ERROR: '.$err; - $this->debug($errstr); - $this->setError($errstr); - unset($tr); - return false; - } - unset($tr); - $this->debug("got WSDL URL"); - } else { - // $wsdl is not http(s), so treat it as a file URL or plain file path - if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'file') && isset($wsdl_props['path'])) { - $path = isset($wsdl_props['host']) ? ($wsdl_props['host'] . ':' . $wsdl_props['path']) : $wsdl_props['path']; - } else { - $path = $wsdl; - } - $this->debug('getting WSDL file ' . $path); - if ($fp = @fopen($path, 'r')) { - $wsdl_string = ''; - while ($data = fread($fp, 32768)) { - $wsdl_string .= $data; - } - fclose($fp); - } else { - $errstr = "Bad path to WSDL file $path"; - $this->debug($errstr); - $this->setError($errstr); - return false; - } - } - $this->debug('Parse WSDL'); - // end new code added - // Create an XML parser. - $this->parser = xml_parser_create(); - // Set the options for parsing the XML data. - // xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); - xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); - // Set the object for the parser. - xml_set_object($this->parser, $this); - // Set the element handlers for the parser. - xml_set_element_handler($this->parser, 'start_element', 'end_element'); - xml_set_character_data_handler($this->parser, 'character_data'); - // Parse the XML file. - if (!xml_parse($this->parser, $wsdl_string, true)) { - // Display an error message. - $errstr = sprintf( - 'XML error parsing WSDL from %s on line %d: %s', - $wsdl, - xml_get_current_line_number($this->parser), - xml_error_string(xml_get_error_code($this->parser)) - ); - $this->debug($errstr); - $this->debug("XML payload:\n" . $wsdl_string); - $this->setError($errstr); - return false; - } - // free the parser - xml_parser_free($this->parser); - $this->debug('Parsing WSDL done'); - // catch wsdl parse errors - if($this->getError()){ - return false; - } - return true; - } - - /** - * start-element handler - * - * @param string $parser XML parser object - * @param string $name element name - * @param string $attrs associative array of attributes - * @access private - */ - function start_element($parser, $name, $attrs) - { - if ($this->status == 'schema') { - $this->currentSchema->schemaStartElement($parser, $name, $attrs); - $this->appendDebug($this->currentSchema->getDebug()); - $this->currentSchema->clearDebug(); - } elseif (ereg('schema$', $name)) { - $this->debug('Parsing WSDL schema'); - // $this->debug("startElement for $name ($attrs[name]). status = $this->status (".$this->getLocalPart($name).")"); - $this->status = 'schema'; - $this->currentSchema = new xmlschema('', '', $this->namespaces); - $this->currentSchema->schemaStartElement($parser, $name, $attrs); - $this->appendDebug($this->currentSchema->getDebug()); - $this->currentSchema->clearDebug(); - } else { - // position in the total number of elements, starting from 0 - $pos = $this->position++; - $depth = $this->depth++; - // set self as current value for this depth - $this->depth_array[$depth] = $pos; - $this->message[$pos] = array('cdata' => ''); - // process attributes - if (count($attrs) > 0) { - // register namespace declarations - foreach($attrs as $k => $v) { - if (ereg("^xmlns", $k)) { - if ($ns_prefix = substr(strrchr($k, ':'), 1)) { - $this->namespaces[$ns_prefix] = $v; - } else { - $this->namespaces['ns' . (count($this->namespaces) + 1)] = $v; - } - if ($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema') { - $this->XMLSchemaVersion = $v; - $this->namespaces['xsi'] = $v . '-instance'; - } - } - } - // expand each attribute prefix to its namespace - foreach($attrs as $k => $v) { - $k = strpos($k, ':') ? $this->expandQname($k) : $k; - if ($k != 'location' && $k != 'soapAction' && $k != 'namespace') { - $v = strpos($v, ':') ? $this->expandQname($v) : $v; - } - $eAttrs[$k] = $v; - } - $attrs = $eAttrs; - } else { - $attrs = array(); - } - // get element prefix, namespace and name - if (ereg(':', $name)) { - // get ns prefix - $prefix = substr($name, 0, strpos($name, ':')); - // get ns - $namespace = isset($this->namespaces[$prefix]) ? $this->namespaces[$prefix] : ''; - // get unqualified name - $name = substr(strstr($name, ':'), 1); - } - // process attributes, expanding any prefixes to namespaces - // find status, register data - switch ($this->status) { - case 'message': - if ($name == 'part') { - if (isset($attrs['type'])) { - $this->debug("msg " . $this->currentMessage . ": found part $attrs[name]: " . implode(',', $attrs)); - $this->messages[$this->currentMessage][$attrs['name']] = $attrs['type']; - } - if (isset($attrs['element'])) { - $this->debug("msg " . $this->currentMessage . ": found part $attrs[name]: " . implode(',', $attrs)); - $this->messages[$this->currentMessage][$attrs['name']] = $attrs['element']; - } - } - break; - case 'portType': - switch ($name) { - case 'operation': - $this->currentPortOperation = $attrs['name']; - $this->debug("portType $this->currentPortType operation: $this->currentPortOperation"); - if (isset($attrs['parameterOrder'])) { - $this->portTypes[$this->currentPortType][$attrs['name']]['parameterOrder'] = $attrs['parameterOrder']; - } - break; - case 'documentation': - $this->documentation = true; - break; - // merge input/output data - default: - $m = isset($attrs['message']) ? $this->getLocalPart($attrs['message']) : ''; - $this->portTypes[$this->currentPortType][$this->currentPortOperation][$name]['message'] = $m; - break; - } - break; - case 'binding': - switch ($name) { - case 'binding': - // get ns prefix - if (isset($attrs['style'])) { - $this->bindings[$this->currentBinding]['prefix'] = $prefix; - } - $this->bindings[$this->currentBinding] = array_merge($this->bindings[$this->currentBinding], $attrs); - break; - case 'header': - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus]['headers'][] = $attrs; - break; - case 'operation': - if (isset($attrs['soapAction'])) { - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['soapAction'] = $attrs['soapAction']; - } - if (isset($attrs['style'])) { - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['style'] = $attrs['style']; - } - if (isset($attrs['name'])) { - $this->currentOperation = $attrs['name']; - $this->debug("current binding operation: $this->currentOperation"); - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['name'] = $attrs['name']; - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['binding'] = $this->currentBinding; - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['endpoint'] = isset($this->bindings[$this->currentBinding]['endpoint']) ? $this->bindings[$this->currentBinding]['endpoint'] : ''; - } - break; - case 'input': - $this->opStatus = 'input'; - break; - case 'output': - $this->opStatus = 'output'; - break; - case 'body': - if (isset($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus])) { - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = array_merge($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus], $attrs); - } else { - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = $attrs; - } - break; - } - break; - case 'service': - switch ($name) { - case 'port': - $this->currentPort = $attrs['name']; - $this->debug('current port: ' . $this->currentPort); - $this->ports[$this->currentPort]['binding'] = $this->getLocalPart($attrs['binding']); - - break; - case 'address': - $this->ports[$this->currentPort]['location'] = $attrs['location']; - $this->ports[$this->currentPort]['bindingType'] = $namespace; - $this->bindings[ $this->ports[$this->currentPort]['binding'] ]['bindingType'] = $namespace; - $this->bindings[ $this->ports[$this->currentPort]['binding'] ]['endpoint'] = $attrs['location']; - break; - } - break; - } - // set status - switch ($name) { - case 'import': - if (isset($attrs['location'])) { - $this->import[$attrs['namespace']][] = array('location' => $attrs['location'], 'loaded' => false); - $this->debug('parsing import ' . $attrs['namespace']. ' - ' . $attrs['location'] . ' (' . count($this->import[$attrs['namespace']]).')'); - } else { - $this->import[$attrs['namespace']][] = array('location' => '', 'loaded' => true); - if (! $this->getPrefixFromNamespace($attrs['namespace'])) { - $this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace']; - } - $this->debug('parsing import ' . $attrs['namespace']. ' - [no location] (' . count($this->import[$attrs['namespace']]).')'); - } - break; - //wait for schema - //case 'types': - // $this->status = 'schema'; - // break; - case 'message': - $this->status = 'message'; - $this->messages[$attrs['name']] = array(); - $this->currentMessage = $attrs['name']; - break; - case 'portType': - $this->status = 'portType'; - $this->portTypes[$attrs['name']] = array(); - $this->currentPortType = $attrs['name']; - break; - case "binding": - if (isset($attrs['name'])) { - // get binding name - if (strpos($attrs['name'], ':')) { - $this->currentBinding = $this->getLocalPart($attrs['name']); - } else { - $this->currentBinding = $attrs['name']; - } - $this->status = 'binding'; - $this->bindings[$this->currentBinding]['portType'] = $this->getLocalPart($attrs['type']); - $this->debug("current binding: $this->currentBinding of portType: " . $attrs['type']); - } - break; - case 'service': - $this->serviceName = $attrs['name']; - $this->status = 'service'; - $this->debug('current service: ' . $this->serviceName); - break; - case 'definitions': - foreach ($attrs as $name => $value) { - $this->wsdl_info[$name] = $value; - } - break; - } - } - } - - /** - * end-element handler - * - * @param string $parser XML parser object - * @param string $name element name - * @access private - */ - function end_element($parser, $name){ - // unset schema status - if (/*ereg('types$', $name) ||*/ ereg('schema$', $name)) { - $this->status = ""; - $this->appendDebug($this->currentSchema->getDebug()); - $this->currentSchema->clearDebug(); - $this->schemas[$this->currentSchema->schemaTargetNamespace][] = $this->currentSchema; - $this->debug('Parsing WSDL schema done'); - } - if ($this->status == 'schema') { - $this->currentSchema->schemaEndElement($parser, $name); - } else { - // bring depth down a notch - $this->depth--; - } - // end documentation - if ($this->documentation) { - //TODO: track the node to which documentation should be assigned; it can be a part, message, etc. - //$this->portTypes[$this->currentPortType][$this->currentPortOperation]['documentation'] = $this->documentation; - $this->documentation = false; - } - } - - /** - * element content handler - * - * @param string $parser XML parser object - * @param string $data element content - * @access private - */ - function character_data($parser, $data) - { - $pos = isset($this->depth_array[$this->depth]) ? $this->depth_array[$this->depth] : 0; - if (isset($this->message[$pos]['cdata'])) { - $this->message[$pos]['cdata'] .= $data; - } - if ($this->documentation) { - $this->documentation .= $data; - } - } - - function getBindingData($binding) - { - if (is_array($this->bindings[$binding])) { - return $this->bindings[$binding]; - } - } - - /** - * returns an assoc array of operation names => operation data - * - * @param string $bindingType eg: soap, smtp, dime (only soap is currently supported) - * @return array - * @access public - */ - function getOperations($bindingType = 'soap') - { - $ops = array(); - if ($bindingType == 'soap') { - $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/'; - } - // loop thru ports - foreach($this->ports as $port => $portData) { - // binding type of port matches parameter - if ($portData['bindingType'] == $bindingType) { - //$this->debug("getOperations for port $port"); - //$this->debug("port data: " . $this->varDump($portData)); - //$this->debug("bindings: " . $this->varDump($this->bindings[ $portData['binding'] ])); - // merge bindings - if (isset($this->bindings[ $portData['binding'] ]['operations'])) { - $ops = array_merge ($ops, $this->bindings[ $portData['binding'] ]['operations']); - } - } - } - return $ops; - } - - /** - * returns an associative array of data necessary for calling an operation - * - * @param string $operation , name of operation - * @param string $bindingType , type of binding eg: soap - * @return array - * @access public - */ - function getOperationData($operation, $bindingType = 'soap') - { - if ($bindingType == 'soap') { - $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/'; - } - // loop thru ports - foreach($this->ports as $port => $portData) { - // binding type of port matches parameter - if ($portData['bindingType'] == $bindingType) { - // get binding - //foreach($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) { - foreach(array_keys($this->bindings[ $portData['binding'] ]['operations']) as $bOperation) { - // note that we could/should also check the namespace here - if ($operation == $bOperation) { - $opData = $this->bindings[ $portData['binding'] ]['operations'][$operation]; - return $opData; - } - } - } - } - } - - /** - * returns an associative array of data necessary for calling an operation - * - * @param string $soapAction soapAction for operation - * @param string $bindingType type of binding eg: soap - * @return array - * @access public - */ - function getOperationDataForSoapAction($soapAction, $bindingType = 'soap') { - if ($bindingType == 'soap') { - $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/'; - } - // loop thru ports - foreach($this->ports as $port => $portData) { - // binding type of port matches parameter - if ($portData['bindingType'] == $bindingType) { - // loop through operations for the binding - foreach ($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) { - if ($opData['soapAction'] == $soapAction) { - return $opData; - } - } - } - } - } - - /** - * returns an array of information about a given type - * returns false if no type exists by the given name - * - * typeDef = array( - * 'elements' => array(), // refs to elements array - * 'restrictionBase' => '', - * 'phpType' => '', - * 'order' => '(sequence|all)', - * 'attrs' => array() // refs to attributes array - * ) - * - * @param $type string the type - * @param $ns string namespace (not prefix) of the type - * @return mixed - * @access public - * @see xmlschema - */ - function getTypeDef($type, $ns) { - $this->debug("in getTypeDef: type=$type, ns=$ns"); - if ((! $ns) && isset($this->namespaces['tns'])) { - $ns = $this->namespaces['tns']; - $this->debug("in getTypeDef: type namespace forced to $ns"); - } - if (isset($this->schemas[$ns])) { - $this->debug("in getTypeDef: have schema for namespace $ns"); - for ($i = 0; $i < count($this->schemas[$ns]); $i++) { - $xs = &$this->schemas[$ns][$i]; - $t = $xs->getTypeDef($type); - $this->appendDebug($xs->getDebug()); - $xs->clearDebug(); - if ($t) { - if (!isset($t['phpType'])) { - // get info for type to tack onto the element - $uqType = substr($t['type'], strrpos($t['type'], ':') + 1); - $ns = substr($t['type'], 0, strrpos($t['type'], ':')); - $etype = $this->getTypeDef($uqType, $ns); - if ($etype) { - $this->debug("found type for [element] $type:"); - $this->debug($this->varDump($etype)); - if (isset($etype['phpType'])) { - $t['phpType'] = $etype['phpType']; - } - if (isset($etype['elements'])) { - $t['elements'] = $etype['elements']; - } - if (isset($etype['attrs'])) { - $t['attrs'] = $etype['attrs']; - } - } - } - return $t; - } - } - } else { - $this->debug("in getTypeDef: do not have schema for namespace $ns"); - } - return false; - } - - /** - * prints html description of services - * - * @access private - */ - function webDescription(){ - global $HTTP_SERVER_VARS; - - if (isset($_SERVER)) { - $PHP_SELF = $_SERVER['PHP_SELF']; - } elseif (isset($HTTP_SERVER_VARS)) { - $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF']; - } else { - $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available"); - } - - $b = ' - NuSOAP: '.$this->serviceName.' - - - - -
-

-
'.$this->serviceName.'
- -
'; - return $b; - } - - /** - * serialize the parsed wsdl - * - * @param mixed $debug whether to put debug=1 in endpoint URL - * @return string serialization of WSDL - * @access public - */ - function serialize($debug = 0) - { - $xml = ''; - $xml .= "\nnamespaces as $k => $v) { - $xml .= " xmlns:$k=\"$v\""; - } - // 10.9.02 - add poulter fix for wsdl and tns declarations - if (isset($this->namespaces['wsdl'])) { - $xml .= " xmlns=\"" . $this->namespaces['wsdl'] . "\""; - } - if (isset($this->namespaces['tns'])) { - $xml .= " targetNamespace=\"" . $this->namespaces['tns'] . "\""; - } - $xml .= '>'; - // imports - if (sizeof($this->import) > 0) { - foreach($this->import as $ns => $list) { - foreach ($list as $ii) { - if ($ii['location'] != '') { - $xml .= ''; - } else { - $xml .= ''; - } - } - } - } - // types - if (count($this->schemas)>=1) { - $xml .= "\n"; - foreach ($this->schemas as $ns => $list) { - foreach ($list as $xs) { - $xml .= $xs->serializeSchema(); - } - } - $xml .= ''; - } - // messages - if (count($this->messages) >= 1) { - foreach($this->messages as $msgName => $msgParts) { - $xml .= "\n'; - if(is_array($msgParts)){ - foreach($msgParts as $partName => $partType) { - // print 'serializing '.$partType.', sv: '.$this->XMLSchemaVersion.'
'; - if (strpos($partType, ':')) { - $typePrefix = $this->getPrefixFromNamespace($this->getPrefix($partType)); - } elseif (isset($this->typemap[$this->namespaces['xsd']][$partType])) { - // print 'checking typemap: '.$this->XMLSchemaVersion.'
'; - $typePrefix = 'xsd'; - } else { - foreach($this->typemap as $ns => $types) { - if (isset($types[$partType])) { - $typePrefix = $this->getPrefixFromNamespace($ns); - } - } - if (!isset($typePrefix)) { - die("$partType has no namespace!"); - } - } - $ns = $this->getNamespaceFromPrefix($typePrefix); - $typeDef = $this->getTypeDef($this->getLocalPart($partType), $ns); - if ($typeDef['typeClass'] == 'element') { - $elementortype = 'element'; - } else { - $elementortype = 'type'; - } - $xml .= ''; - } - } - $xml .= '
'; - } - } - // bindings & porttypes - if (count($this->bindings) >= 1) { - $binding_xml = ''; - $portType_xml = ''; - foreach($this->bindings as $bindingName => $attrs) { - $binding_xml .= "\n'; - $binding_xml .= ''; - $portType_xml .= "\n'; - foreach($attrs['operations'] as $opName => $opParts) { - $binding_xml .= ''; - $binding_xml .= ''; - if (isset($opParts['input']['encodingStyle']) && $opParts['input']['encodingStyle'] != '') { - $enc_style = ' encodingStyle="' . $opParts['input']['encodingStyle'] . '"'; - } else { - $enc_style = ''; - } - $binding_xml .= ''; - if (isset($opParts['output']['encodingStyle']) && $opParts['output']['encodingStyle'] != '') { - $enc_style = ' encodingStyle="' . $opParts['output']['encodingStyle'] . '"'; - } else { - $enc_style = ''; - } - $binding_xml .= ''; - $binding_xml .= ''; - $portType_xml .= ''; - } - $portType_xml .= ''; - $portType_xml .= ''; - $portType_xml .= ''; - } - $portType_xml .= ''; - $binding_xml .= ''; - } - $xml .= $portType_xml . $binding_xml; - } - // services - $xml .= "\nserviceName . '">'; - if (count($this->ports) >= 1) { - foreach($this->ports as $pName => $attrs) { - $xml .= ''; - $xml .= ''; - $xml .= ''; - } - } - $xml .= ''; - return $xml . "\n"; - } - - /** - * serialize PHP values according to a WSDL message definition - * - * TODO - * - multi-ref serialization - * - validate PHP values against type definitions, return errors if invalid - * - * @param string $operation operation name - * @param string $direction (input|output) - * @param mixed $parameters parameter value(s) - * @return mixed parameters serialized as XML or false on error (e.g. operation not found) - * @access public - */ - function serializeRPCParameters($operation, $direction, $parameters) - { - $this->debug("in serializeRPCParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion"); - $this->appendDebug('parameters=' . $this->varDump($parameters)); - - if ($direction != 'input' && $direction != 'output') { - $this->debug('The value of the \$direction argument needs to be either "input" or "output"'); - $this->setError('The value of the \$direction argument needs to be either "input" or "output"'); - return false; - } - if (!$opData = $this->getOperationData($operation)) { - $this->debug('Unable to retrieve WSDL data for operation: ' . $operation); - $this->setError('Unable to retrieve WSDL data for operation: ' . $operation); - return false; - } - $this->debug('opData:'); - $this->appendDebug($this->varDump($opData)); - - // Get encoding style for output and set to current - $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; - if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) { - $encodingStyle = $opData['output']['encodingStyle']; - $enc_style = $encodingStyle; - } - - // set input params - $xml = ''; - if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) { - - $use = $opData[$direction]['use']; - $this->debug('have ' . count($opData[$direction]['parts']) . ' part(s) to serialize'); - if (is_array($parameters)) { - $parametersArrayType = $this->isArraySimpleOrStruct($parameters); - $this->debug('have ' . count($parameters) . ' parameter(s) provided as ' . $parametersArrayType . ' to serialize'); - foreach($opData[$direction]['parts'] as $name => $type) { - $this->debug('serializing part "'.$name.'" of type "'.$type.'"'); - // Track encoding style - if (isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) { - $encodingStyle = $opData[$direction]['encodingStyle']; - $enc_style = $encodingStyle; - } else { - $enc_style = false; - } - // NOTE: add error handling here - // if serializeType returns false, then catch global error and fault - if ($parametersArrayType == 'arraySimple') { - $p = array_shift($parameters); - $this->debug('calling serializeType w/indexed param'); - $xml .= $this->serializeType($name, $type, $p, $use, $enc_style); - } elseif (isset($parameters[$name])) { - $this->debug('calling serializeType w/named param'); - $xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style); - } else { - // TODO: only send nillable - $this->debug('calling serializeType w/null param'); - $xml .= $this->serializeType($name, $type, null, $use, $enc_style); - } - } - } else { - $this->debug('no parameters passed.'); - } - } - $this->debug("serializeRPCParameters returning: $xml"); - return $xml; - } - - /** - * serialize a PHP value according to a WSDL message definition - * - * TODO - * - multi-ref serialization - * - validate PHP values against type definitions, return errors if invalid - * - * @param string $ type name - * @param mixed $ param value - * @return mixed new param or false if initial value didn't validate - * @access public - * @deprecated - */ - function serializeParameters($operation, $direction, $parameters) - { - $this->debug("in serializeParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion"); - $this->appendDebug('parameters=' . $this->varDump($parameters)); - - if ($direction != 'input' && $direction != 'output') { - $this->debug('The value of the \$direction argument needs to be either "input" or "output"'); - $this->setError('The value of the \$direction argument needs to be either "input" or "output"'); - return false; - } - if (!$opData = $this->getOperationData($operation)) { - $this->debug('Unable to retrieve WSDL data for operation: ' . $operation); - $this->setError('Unable to retrieve WSDL data for operation: ' . $operation); - return false; - } - $this->debug('opData:'); - $this->appendDebug($this->varDump($opData)); - - // Get encoding style for output and set to current - $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; - if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) { - $encodingStyle = $opData['output']['encodingStyle']; - $enc_style = $encodingStyle; - } - - // set input params - $xml = ''; - if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) { - - $use = $opData[$direction]['use']; - $this->debug("use=$use"); - $this->debug('got ' . count($opData[$direction]['parts']) . ' part(s)'); - if (is_array($parameters)) { - $parametersArrayType = $this->isArraySimpleOrStruct($parameters); - $this->debug('have ' . $parametersArrayType . ' parameters'); - foreach($opData[$direction]['parts'] as $name => $type) { - $this->debug('serializing part "'.$name.'" of type "'.$type.'"'); - // Track encoding style - if(isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) { - $encodingStyle = $opData[$direction]['encodingStyle']; - $enc_style = $encodingStyle; - } else { - $enc_style = false; - } - // NOTE: add error handling here - // if serializeType returns false, then catch global error and fault - if ($parametersArrayType == 'arraySimple') { - $p = array_shift($parameters); - $this->debug('calling serializeType w/indexed param'); - $xml .= $this->serializeType($name, $type, $p, $use, $enc_style); - } elseif (isset($parameters[$name])) { - $this->debug('calling serializeType w/named param'); - $xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style); - } else { - // TODO: only send nillable - $this->debug('calling serializeType w/null param'); - $xml .= $this->serializeType($name, $type, null, $use, $enc_style); - } - } - } else { - $this->debug('no parameters passed.'); - } - } - $this->debug("serializeParameters returning: $xml"); - return $xml; - } - - /** - * serializes a PHP value according a given type definition - * - * @param string $name name of value (part or element) - * @param string $type XML schema type of value (type or element) - * @param mixed $value a native PHP value (parameter value) - * @param string $use use for part (encoded|literal) - * @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style) - * @param boolean $unqualified a kludge for what should be XML namespace form handling - * @return string value serialized as an XML string - * @access private - */ - function serializeType($name, $type, $value, $use='encoded', $encodingStyle=false, $unqualified=false) - { - $this->debug("in serializeType: name=$name, type=$type, use=$use, encodingStyle=$encodingStyle, unqualified=" . ($unqualified ? "unqualified" : "qualified")); - $this->appendDebug("value=" . $this->varDump($value)); - if($use == 'encoded' && $encodingStyle) { - $encodingStyle = ' SOAP-ENV:encodingStyle="' . $encodingStyle . '"'; - } - - // if a soapval has been supplied, let its type override the WSDL - if (is_object($value) && get_class($value) == 'soapval') { - if ($value->type_ns) { - $type = $value->type_ns . ':' . $value->type; - $forceType = true; - $this->debug("in serializeType: soapval overrides type to $type"); - } elseif ($value->type) { - $type = $value->type; - $forceType = true; - $this->debug("in serializeType: soapval overrides type to $type"); - } else { - $forceType = false; - $this->debug("in serializeType: soapval does not override type"); - } - $attrs = $value->attributes; - $value = $value->value; - $this->debug("in serializeType: soapval overrides value to $value"); - if ($attrs) { - if (!is_array($value)) { - $value['!'] = $value; - } - foreach ($attrs as $n => $v) { - $value['!' . $n] = $v; - } - $this->debug("in serializeType: soapval provides attributes"); - } - } else { - $forceType = false; - } - - $xml = ''; - if (strpos($type, ':')) { - $uqType = substr($type, strrpos($type, ':') + 1); - $ns = substr($type, 0, strrpos($type, ':')); - $this->debug("in serializeType: got a prefixed type: $uqType, $ns"); - if ($this->getNamespaceFromPrefix($ns)) { - $ns = $this->getNamespaceFromPrefix($ns); - $this->debug("in serializeType: expanded prefixed type: $uqType, $ns"); - } - - if($ns == $this->XMLSchemaVersion || $ns == 'http://schemas.xmlsoap.org/soap/encoding/'){ - $this->debug('in serializeType: type namespace indicates XML Schema or SOAP Encoding type'); - if ($unqualified && $use == 'literal') { - $elementNS = " xmlns=\"\""; - } else { - $elementNS = ''; - } - if (is_null($value)) { - if ($use == 'literal') { - // TODO: depends on minOccurs - $xml = "<$name$elementNS/>"; - } else { - // TODO: depends on nillable, which should be checked before calling this method - $xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>"; - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - if ($uqType == 'boolean') { - if ((is_string($value) && $value == 'false') || (! $value)) { - $value = 'false'; - } else { - $value = 'true'; - } - } - if ($uqType == 'string' && gettype($value) == 'string') { - $value = $this->expandEntities($value); - } - if (($uqType == 'long' || $uqType == 'unsignedLong') && gettype($value) == 'double') { - $value = sprintf("%.0lf", $value); - } - // it's a scalar - // TODO: what about null/nil values? - // check type isn't a custom type extending xmlschema namespace - if (!$this->getTypeDef($uqType, $ns)) { - if ($use == 'literal') { - if ($forceType) { - $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value"; - } else { - $xml = "<$name$elementNS>$value"; - } - } else { - $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value"; - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - $this->debug('custom type extends XML Schema or SOAP Encoding namespace (yuck)'); - } else if ($ns == 'http://xml.apache.org/xml-soap') { - $this->debug('in serializeType: appears to be Apache SOAP type'); - if ($uqType == 'Map') { - $tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap'); - if (! $tt_prefix) { - $this->debug('in serializeType: Add namespace for Apache SOAP type'); - $tt_prefix = 'ns' . rand(1000, 9999); - $this->namespaces[$tt_prefix] = 'http://xml.apache.org/xml-soap'; - // force this to be added to usedNamespaces - $tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap'); - } - $contents = ''; - foreach($value as $k => $v) { - $this->debug("serializing map element: key $k, value $v"); - $contents .= ''; - $contents .= $this->serialize_val($k,'key',false,false,false,false,$use); - $contents .= $this->serialize_val($v,'value',false,false,false,false,$use); - $contents .= ''; - } - if ($use == 'literal') { - if ($forceType) { - $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\">$contents"; - } else { - $xml = "<$name>$contents"; - } - } else { - $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\"$encodingStyle>$contents"; - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - $this->debug('in serializeType: Apache SOAP type, but only support Map'); - } - } else { - // TODO: should the type be compared to types in XSD, and the namespace - // set to XSD if the type matches? - $this->debug("in serializeType: No namespace for type $type"); - $ns = ''; - $uqType = $type; - } - if(!$typeDef = $this->getTypeDef($uqType, $ns)){ - $this->setError("$type ($uqType) is not a supported type."); - $this->debug("in serializeType: $type ($uqType) is not a supported type."); - return false; - } else { - $this->debug("in serializeType: found typeDef"); - $this->appendDebug('typeDef=' . $this->varDump($typeDef)); - } - $phpType = $typeDef['phpType']; - $this->debug("in serializeType: uqType: $uqType, ns: $ns, phptype: $phpType, arrayType: " . (isset($typeDef['arrayType']) ? $typeDef['arrayType'] : '') ); - // if php type == struct, map value to the element names - if ($phpType == 'struct') { - if (isset($typeDef['typeClass']) && $typeDef['typeClass'] == 'element') { - $elementName = $uqType; - if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) { - $elementNS = " xmlns=\"$ns\""; - } else { - $elementNS = " xmlns=\"\""; - } - } else { - $elementName = $name; - if ($unqualified) { - $elementNS = " xmlns=\"\""; - } else { - $elementNS = ''; - } - } - if (is_null($value)) { - if ($use == 'literal') { - // TODO: depends on minOccurs - $xml = "<$elementName$elementNS/>"; - } else { - $xml = "<$elementName$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>"; - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - if (is_object($value)) { - $value = get_object_vars($value); - } - if (is_array($value)) { - $elementAttrs = $this->serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType); - if ($use == 'literal') { - if ($forceType) { - $xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">"; - } else { - $xml = "<$elementName$elementNS$elementAttrs>"; - } - } else { - $xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>"; - } - - $xml .= $this->serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use, $encodingStyle); - $xml .= ""; - } else { - $this->debug("in serializeType: phpType is struct, but value is not an array"); - $this->setError("phpType is struct, but value is not an array: see debug output for details"); - $xml = ''; - } - } elseif ($phpType == 'array') { - if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) { - $elementNS = " xmlns=\"$ns\""; - } else { - if ($unqualified) { - $elementNS = " xmlns=\"\""; - } else { - $elementNS = ''; - } - } - if (is_null($value)) { - if ($use == 'literal') { - // TODO: depends on minOccurs - $xml = "<$name$elementNS/>"; - } else { - $xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" . - $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') . - ":Array\" " . - $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') . - ':arrayType="' . - $this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType'])) . - ':' . - $this->getLocalPart($typeDef['arrayType'])."[0]\"/>"; - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - if (isset($typeDef['multidimensional'])) { - $nv = array(); - foreach($value as $v) { - $cols = ',' . sizeof($v); - $nv = array_merge($nv, $v); - } - $value = $nv; - } else { - $cols = ''; - } - if (is_array($value) && sizeof($value) >= 1) { - $rows = sizeof($value); - $contents = ''; - foreach($value as $k => $v) { - $this->debug("serializing array element: $k, $v of type: $typeDef[arrayType]"); - //if (strpos($typeDef['arrayType'], ':') ) { - if (!in_array($typeDef['arrayType'],$this->typemap['http://www.w3.org/2001/XMLSchema'])) { - $contents .= $this->serializeType('item', $typeDef['arrayType'], $v, $use); - } else { - $contents .= $this->serialize_val($v, 'item', $typeDef['arrayType'], null, $this->XMLSchemaVersion, false, $use); - } - } - } else { - $rows = 0; - $contents = null; - } - // TODO: for now, an empty value will be serialized as a zero element - // array. Revisit this when coding the handling of null/nil values. - if ($use == 'literal') { - $xml = "<$name$elementNS>" - .$contents - .""; - } else { - $xml = "<$name$elementNS xsi:type=\"".$this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/').':Array" '. - $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') - .':arrayType="' - .$this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType'])) - .":".$this->getLocalPart($typeDef['arrayType'])."[$rows$cols]\">" - .$contents - .""; - } - } elseif ($phpType == 'scalar') { - if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) { - $elementNS = " xmlns=\"$ns\""; - } else { - if ($unqualified) { - $elementNS = " xmlns=\"\""; - } else { - $elementNS = ''; - } - } - if ($use == 'literal') { - if ($forceType) { - $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value"; - } else { - $xml = "<$name$elementNS>$value"; - } - } else { - $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value"; - } - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - - /** - * serializes the attributes for a complexType - * - * @param array $typeDef our internal representation of an XML schema type (or element) - * @param mixed $value a native PHP value (parameter value) - * @param string $ns the namespace of the type - * @param string $uqType the local part of the type - * @return string value serialized as an XML string - * @access private - */ - function serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType) { - $xml = ''; - if (isset($typeDef['attrs']) && is_array($typeDef['attrs'])) { - $this->debug("serialize attributes for XML Schema type $ns:$uqType"); - if (is_array($value)) { - $xvalue = $value; - } elseif (is_object($value)) { - $xvalue = get_object_vars($value); - } else { - $this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType"); - $xvalue = array(); - } - foreach ($typeDef['attrs'] as $aName => $attrs) { - if (isset($xvalue['!' . $aName])) { - $xname = '!' . $aName; - $this->debug("value provided for attribute $aName with key $xname"); - } elseif (isset($xvalue[$aName])) { - $xname = $aName; - $this->debug("value provided for attribute $aName with key $xname"); - } elseif (isset($attrs['default'])) { - $xname = '!' . $aName; - $xvalue[$xname] = $attrs['default']; - $this->debug('use default value of ' . $xvalue[$aName] . ' for attribute ' . $aName); - } else { - $xname = ''; - $this->debug("no value provided for attribute $aName"); - } - if ($xname) { - $xml .= " $aName=\"" . $this->expandEntities($xvalue[$xname]) . "\""; - } - } - } else { - $this->debug("no attributes to serialize for XML Schema type $ns:$uqType"); - } - if (isset($typeDef['extensionBase'])) { - $ns = $this->getPrefix($typeDef['extensionBase']); - $uqType = $this->getLocalPart($typeDef['extensionBase']); - if ($this->getNamespaceFromPrefix($ns)) { - $ns = $this->getNamespaceFromPrefix($ns); - } - if ($typeDef = $this->getTypeDef($uqType, $ns)) { - $this->debug("serialize attributes for extension base $ns:$uqType"); - $xml .= $this->serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType); - } else { - $this->debug("extension base $ns:$uqType is not a supported type"); - } - } - return $xml; - } - - /** - * serializes the elements for a complexType - * - * @param array $typeDef our internal representation of an XML schema type (or element) - * @param mixed $value a native PHP value (parameter value) - * @param string $ns the namespace of the type - * @param string $uqType the local part of the type - * @param string $use use for part (encoded|literal) - * @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style) - * @return string value serialized as an XML string - * @access private - */ - function serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use='encoded', $encodingStyle=false) { - $xml = ''; - if (isset($typeDef['elements']) && is_array($typeDef['elements'])) { - $this->debug("in serializeComplexTypeElements, serialize elements for XML Schema type $ns:$uqType"); - if (is_array($value)) { - $xvalue = $value; - } elseif (is_object($value)) { - $xvalue = get_object_vars($value); - } else { - $this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType"); - $xvalue = array(); - } - // toggle whether all elements are present - ideally should validate against schema - if (count($typeDef['elements']) != count($xvalue)){ - $optionals = true; - } - foreach ($typeDef['elements'] as $eName => $attrs) { - if (!isset($xvalue[$eName])) { - if (isset($attrs['default'])) { - $xvalue[$eName] = $attrs['default']; - $this->debug('use default value of ' . $xvalue[$eName] . ' for element ' . $eName); - } - } - // if user took advantage of a minOccurs=0, then only serialize named parameters - if (isset($optionals) - && (!isset($xvalue[$eName])) - && ( (!isset($attrs['nillable'])) || $attrs['nillable'] != 'true') - ){ - if (isset($attrs['minOccurs']) && $attrs['minOccurs'] <> '0') { - $this->debug("apparent error: no value provided for element $eName with minOccurs=" . $attrs['minOccurs']); - } - // do nothing - $this->debug("no value provided for complexType element $eName and element is not nillable, so serialize nothing"); - } else { - // get value - if (isset($xvalue[$eName])) { - $v = $xvalue[$eName]; - } else { - $v = null; - } - if (isset($attrs['form'])) { - $unqualified = ($attrs['form'] == 'unqualified'); - } else { - $unqualified = false; - } - if (isset($attrs['maxOccurs']) && ($attrs['maxOccurs'] == 'unbounded' || $attrs['maxOccurs'] > 1) && isset($v) && is_array($v) && $this->isArraySimpleOrStruct($v) == 'arraySimple') { - $vv = $v; - foreach ($vv as $k => $v) { - if (isset($attrs['type']) || isset($attrs['ref'])) { - // serialize schema-defined type - $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified); - } else { - // serialize generic type (can this ever really happen?) - $this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use"); - $xml .= $this->serialize_val($v, $eName, false, false, false, false, $use); - } - } - } else { - if (isset($attrs['type']) || isset($attrs['ref'])) { - // serialize schema-defined type - $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified); - } else { - // serialize generic type (can this ever really happen?) - $this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use"); - $xml .= $this->serialize_val($v, $eName, false, false, false, false, $use); - } - } - } - } - } else { - $this->debug("no elements to serialize for XML Schema type $ns:$uqType"); - } - if (isset($typeDef['extensionBase'])) { - $ns = $this->getPrefix($typeDef['extensionBase']); - $uqType = $this->getLocalPart($typeDef['extensionBase']); - if ($this->getNamespaceFromPrefix($ns)) { - $ns = $this->getNamespaceFromPrefix($ns); - } - if ($typeDef = $this->getTypeDef($uqType, $ns)) { - $this->debug("serialize elements for extension base $ns:$uqType"); - $xml .= $this->serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use, $encodingStyle); - } else { - $this->debug("extension base $ns:$uqType is not a supported type"); - } - } - return $xml; - } - - /** - * adds an XML Schema complex type to the WSDL types - * - * @param string name - * @param string typeClass (complexType|simpleType|attribute) - * @param string phpType: currently supported are array and struct (php assoc array) - * @param string compositor (all|sequence|choice) - * @param string restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) - * @param array elements = array ( name => array(name=>'',type=>'') ) - * @param array attrs = array(array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'xsd:string[]')) - * @param string arrayType: namespace:name (xsd:string) - * @see xmlschema - * @access public - */ - function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType='') { - if (count($elements) > 0) { - foreach($elements as $n => $e){ - // expand each element - foreach ($e as $k => $v) { - $k = strpos($k,':') ? $this->expandQname($k) : $k; - $v = strpos($v,':') ? $this->expandQname($v) : $v; - $ee[$k] = $v; - } - $eElements[$n] = $ee; - } - $elements = $eElements; - } - - if (count($attrs) > 0) { - foreach($attrs as $n => $a){ - // expand each attribute - foreach ($a as $k => $v) { - $k = strpos($k,':') ? $this->expandQname($k) : $k; - $v = strpos($v,':') ? $this->expandQname($v) : $v; - $aa[$k] = $v; - } - $eAttrs[$n] = $aa; - } - $attrs = $eAttrs; - } - - $restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase; - $arrayType = strpos($arrayType,':') ? $this->expandQname($arrayType) : $arrayType; - - $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns']; - $this->schemas[$typens][0]->addComplexType($name,$typeClass,$phpType,$compositor,$restrictionBase,$elements,$attrs,$arrayType); - } - - /** - * adds an XML Schema simple type to the WSDL types - * - * @param string $name - * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) - * @param string $typeClass (should always be simpleType) - * @param string $phpType (should always be scalar) - * @param array $enumeration array of values - * @see xmlschema - * @access public - */ - function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) { - $restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase; - - $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns']; - $this->schemas[$typens][0]->addSimpleType($name, $restrictionBase, $typeClass, $phpType, $enumeration); - } - - /** - * adds an element to the WSDL types - * - * @param array $attrs attributes that must include name and type - * @see xmlschema - * @access public - */ - function addElement($attrs) { - $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns']; - $this->schemas[$typens][0]->addElement($attrs); - } - - /** - * register an operation with the server - * - * @param string $name operation (method) name - * @param array $in assoc array of input values: key = param name, value = param type - * @param array $out assoc array of output values: key = param name, value = param type - * @param string $namespace optional The namespace for the operation - * @param string $soapaction optional The soapaction for the operation - * @param string $style (rpc|document) optional The style for the operation Note: when 'document' is specified, parameter and return wrappers are created for you automatically - * @param string $use (encoded|literal) optional The use for the parameters (cannot mix right now) - * @param string $documentation optional The description to include in the WSDL - * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded) - * @access public - */ - function addOperation($name, $in = false, $out = false, $namespace = false, $soapaction = false, $style = 'rpc', $use = 'encoded', $documentation = '', $encodingStyle = ''){ - if ($use == 'encoded' && $encodingStyle == '') { - $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; - } - - if ($style == 'document') { - $elements = array(); - foreach ($in as $n => $t) { - $elements[$n] = array('name' => $n, 'type' => $t); - } - $this->addComplexType($name . 'RequestType', 'complexType', 'struct', 'all', '', $elements); - $this->addElement(array('name' => $name, 'type' => $name . 'RequestType')); - $in = array('parameters' => 'tns:' . $name); - - $elements = array(); - foreach ($out as $n => $t) { - $elements[$n] = array('name' => $n, 'type' => $t); - } - $this->addComplexType($name . 'ResponseType', 'complexType', 'struct', 'all', '', $elements); - $this->addElement(array('name' => $name . 'Response', 'type' => $name . 'ResponseType')); - $out = array('parameters' => 'tns:' . $name . 'Response'); - } - - // get binding - $this->bindings[ $this->serviceName . 'Binding' ]['operations'][$name] = - array( - 'name' => $name, - 'binding' => $this->serviceName . 'Binding', - 'endpoint' => $this->endpoint, - 'soapAction' => $soapaction, - 'style' => $style, - 'input' => array( - 'use' => $use, - 'namespace' => $namespace, - 'encodingStyle' => $encodingStyle, - 'message' => $name . 'Request', - 'parts' => $in), - 'output' => array( - 'use' => $use, - 'namespace' => $namespace, - 'encodingStyle' => $encodingStyle, - 'message' => $name . 'Response', - 'parts' => $out), - 'namespace' => $namespace, - 'transport' => 'http://schemas.xmlsoap.org/soap/http', - 'documentation' => $documentation); - // add portTypes - // add messages - if($in) - { - foreach($in as $pName => $pType) - { - if(strpos($pType,':')) { - $pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType); - } - $this->messages[$name.'Request'][$pName] = $pType; - } - } else { - $this->messages[$name.'Request']= '0'; - } - if($out) - { - foreach($out as $pName => $pType) - { - if(strpos($pType,':')) { - $pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType); - } - $this->messages[$name.'Response'][$pName] = $pType; - } - } else { - $this->messages[$name.'Response']= '0'; - } - return true; - } -} - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/class.wsdlcache.php b/gulliver/thirdparty/pear/class.wsdlcache.php deleted file mode 100644 index 6e5075bed..000000000 --- a/gulliver/thirdparty/pear/class.wsdlcache.php +++ /dev/null @@ -1,211 +0,0 @@ - -* @author Ingo Fischer -* @version $Id: class.wsdlcache.php,v 1.5 2005/05/20 17:58:17 snichol Exp $ -* @access public -*/ -class wsdlcache { - /** - * @var resource - * @access private - */ - var $fplock; - /** - * @var integer - * @access private - */ - var $cache_lifetime; - /** - * @var string - * @access private - */ - var $cache_dir; - /** - * @var string - * @access public - */ - var $debug_str = ''; - - /** - * constructor - * - * @param string $cache_dir directory for cache-files - * @param integer $cache_lifetime lifetime for caching-files in seconds or 0 for unlimited - * @access public - */ - function wsdlcache($cache_dir='.', $cache_lifetime=0) { - $this->fplock = array(); - $this->cache_dir = $cache_dir != '' ? $cache_dir : '.'; - $this->cache_lifetime = $cache_lifetime; - } - - /** - * creates the filename used to cache a wsdl instance - * - * @param string $wsdl The URL of the wsdl instance - * @return string The filename used to cache the instance - * @access private - */ - function createFilename($wsdl) { - 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 $this->cache_dir.'/wsdlcache-' . G::encryptOld($wsdl); - } - - /** - * adds debug data to the class level debug string - * - * @param string $string debug data - * @access private - */ - function debug($string){ - $this->debug_str .= get_class($this).": $string\n"; - } - - /** - * gets a wsdl instance from the cache - * - * @param string $wsdl The URL of the wsdl instance - * @return object wsdl The cached wsdl instance, null if the instance is not in the cache - * @access public - */ - function get($wsdl) { - $filename = $this->createFilename($wsdl); - if ($this->obtainMutex($filename, "r")) { - // check for expired WSDL that must be removed from the cache - if ($this->cache_lifetime > 0) { - if (file_exists($filename) && (time() - filemtime($filename) > $this->cache_lifetime)) { - unlink($filename); - $this->debug("Expired $wsdl ($filename) from cache"); - $this->releaseMutex($filename); - return null; - } - } - // see what there is to return - $fp = @fopen($filename, "r"); - if ($fp) { - $s = implode("", @file($filename)); - fclose($fp); - $this->debug("Got $wsdl ($filename) from cache"); - } else { - $s = null; - $this->debug("$wsdl ($filename) not in cache"); - } - $this->releaseMutex($filename); - return (!is_null($s)) ? unserialize($s) : null; - } else { - $this->debug("Unable to obtain mutex for $filename in get"); - } - return null; - } - - /** - * obtains the local mutex - * - * @param string $filename The Filename of the Cache to lock - * @param string $mode The open-mode ("r" or "w") or the file - affects lock-mode - * @return boolean Lock successfully obtained ?! - * @access private - */ - function obtainMutex($filename, $mode) { - 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 (isset($this->fplock[G::encryptOld($filename)])) { - $this->debug("Lock for $filename already exists"); - return false; - } - $this->fplock[G::encryptOld($filename)] = fopen($filename.".lock", "w"); - if ($mode == "r") { - return flock($this->fplock[G::encryptOld($filename)], LOCK_SH); - } else { - return flock($this->fplock[G::encryptOld($filename)], LOCK_EX); - } - } - - /** - * adds a wsdl instance to the cache - * - * @param object wsdl $wsdl_instance The wsdl instance to add - * @return boolean WSDL successfully cached - * @access public - */ - function put($wsdl_instance) { - $filename = $this->createFilename($wsdl_instance->wsdl); - $s = serialize($wsdl_instance); - if ($this->obtainMutex($filename, "w")) { - $fp = fopen($filename, "w"); - fputs($fp, $s); - fclose($fp); - $this->debug("Put $wsdl_instance->wsdl ($filename) in cache"); - $this->releaseMutex($filename); - return true; - } else { - $this->debug("Unable to obtain mutex for $filename in put"); - } - return false; - } - - /** - * releases the local mutex - * - * @param string $filename The Filename of the Cache to lock - * @return boolean Lock successfully released - * @access private - */ - function releaseMutex($filename) { - 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'); - } - $ret = flock($this->fplock[G::encryptOld($filename)], LOCK_UN); - fclose($this->fplock[G::encryptOld($filename)]); - unset($this->fplock[G::encryptOld($filename)]); - if (! $ret) { - $this->debug("Not able to release lock for $filename"); - } - return $ret; - } - - /** - * removes a wsdl instance from the cache - * - * @param string $wsdl The URL of the wsdl instance - * @return boolean Whether there was an instance to remove - * @access public - */ - function remove($wsdl) { - $filename = $this->createFilename($wsdl); - // ignore errors obtaining mutex - $this->obtainMutex($filename, "w"); - $ret = unlink($filename); - $this->debug("Removed ($ret) $wsdl ($filename) from cache"); - $this->releaseMutex($filename); - return $ret; - } -} -?> diff --git a/gulliver/thirdparty/pear/class.xmlschema.php b/gulliver/thirdparty/pear/class.xmlschema.php deleted file mode 100644 index 7a4ece49d..000000000 --- a/gulliver/thirdparty/pear/class.xmlschema.php +++ /dev/null @@ -1,906 +0,0 @@ - -* @version $Id: class.xmlschema.php,v 1.39 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class XMLSchema extends nusoap_base { - - // files - var $schema = ''; - var $xml = ''; - // namespaces - var $enclosingNamespaces; - // schema info - var $schemaInfo = array(); - var $schemaTargetNamespace = ''; - // types, elements, attributes defined by the schema - var $attributes = array(); - var $complexTypes = array(); - var $complexTypeStack = array(); - var $currentComplexType = null; - var $elements = array(); - var $elementStack = array(); - var $currentElement = null; - var $simpleTypes = array(); - var $simpleTypeStack = array(); - var $currentSimpleType = null; - // imports - var $imports = array(); - // parser vars - var $parser; - var $position = 0; - var $depth = 0; - var $depth_array = array(); - var $message = array(); - var $defaultNamespace = array(); - - /** - * constructor - * - * @param string $schema schema document URI - * @param string $xml xml document URI - * @param string $namespaces namespaces defined in enclosing XML - * @access public - */ - function XMLSchema($schema='',$xml='',$namespaces=array()){ - parent::nusoap_base(); - $this->debug('xmlschema class instantiated, inside constructor'); - // files - $this->schema = $schema; - $this->xml = $xml; - - // namespaces - $this->enclosingNamespaces = $namespaces; - $this->namespaces = array_merge($this->namespaces, $namespaces); - - // parse schema file - if($schema != ''){ - $this->debug('initial schema file: '.$schema); - $this->parseFile($schema, 'schema'); - } - - // parse xml file - if($xml != ''){ - $this->debug('initial xml file: '.$xml); - $this->parseFile($xml, 'xml'); - } - - } - - /** - * parse an XML file - * - * @param string $xml, path/URL to XML file - * @param string $type, (schema | xml) - * @return boolean - * @access public - */ - function parseFile($xml,$type){ - // parse xml file - if($xml != ""){ - $xmlStr = @join("",@file($xml)); - if($xmlStr == ""){ - $msg = 'Error reading XML from '.$xml; - $this->setError($msg); - $this->debug($msg); - return false; - } else { - $this->debug("parsing $xml"); - $this->parseString($xmlStr,$type); - $this->debug("done parsing $xml"); - return true; - } - } - return false; - } - - /** - * parse an XML string - * - * @param string $xml path or URL - * @param string $type, (schema|xml) - * @access private - */ - function parseString($xml,$type){ - // parse xml string - if($xml != ""){ - - // Create an XML parser. - $this->parser = xml_parser_create(); - // Set the options for parsing the XML data. - xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); - - // Set the object for the parser. - xml_set_object($this->parser, $this); - - // Set the element handlers for the parser. - if($type == "schema"){ - xml_set_element_handler($this->parser, 'schemaStartElement','schemaEndElement'); - xml_set_character_data_handler($this->parser,'schemaCharacterData'); - } elseif($type == "xml"){ - xml_set_element_handler($this->parser, 'xmlStartElement','xmlEndElement'); - xml_set_character_data_handler($this->parser,'xmlCharacterData'); - } - - // Parse the XML file. - if(!xml_parse($this->parser,$xml,true)){ - // Display an error message. - $errstr = sprintf('XML error parsing XML schema on line %d: %s', - xml_get_current_line_number($this->parser), - xml_error_string(xml_get_error_code($this->parser)) - ); - $this->debug($errstr); - $this->debug("XML payload:\n" . $xml); - $this->setError($errstr); - } - - xml_parser_free($this->parser); - } else{ - $this->debug('no xml passed to parseString()!!'); - $this->setError('no xml passed to parseString()!!'); - } - } - - /** - * start-element handler - * - * @param string $parser XML parser object - * @param string $name element name - * @param string $attrs associative array of attributes - * @access private - */ - function schemaStartElement($parser, $name, $attrs) { - - // position in the total number of elements, starting from 0 - $pos = $this->position++; - $depth = $this->depth++; - // set self as current value for this depth - $this->depth_array[$depth] = $pos; - $this->message[$pos] = array('cdata' => ''); - if ($depth > 0) { - $this->defaultNamespace[$pos] = $this->defaultNamespace[$this->depth_array[$depth - 1]]; - } else { - $this->defaultNamespace[$pos] = false; - } - - // get element prefix - if($prefix = $this->getPrefix($name)){ - // get unqualified name - $name = $this->getLocalPart($name); - } else { - $prefix = ''; - } - - // loop thru attributes, expanding, and registering namespace declarations - if(count($attrs) > 0){ - foreach($attrs as $k => $v){ - // if ns declarations, add to class level array of valid namespaces - if(ereg("^xmlns",$k)){ - //$this->xdebug("$k: $v"); - //$this->xdebug('ns_prefix: '.$this->getPrefix($k)); - if($ns_prefix = substr(strrchr($k,':'),1)){ - //$this->xdebug("Add namespace[$ns_prefix] = $v"); - $this->namespaces[$ns_prefix] = $v; - } else { - $this->defaultNamespace[$pos] = $v; - if (! $this->getPrefixFromNamespace($v)) { - $this->namespaces['ns'.(count($this->namespaces)+1)] = $v; - } - } - if($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema'){ - $this->XMLSchemaVersion = $v; - $this->namespaces['xsi'] = $v.'-instance'; - } - } - } - foreach($attrs as $k => $v){ - // expand each attribute - $k = strpos($k,':') ? $this->expandQname($k) : $k; - $v = strpos($v,':') ? $this->expandQname($v) : $v; - $eAttrs[$k] = $v; - } - $attrs = $eAttrs; - } else { - $attrs = array(); - } - // find status, register data - switch($name){ - case 'all': // (optional) compositor content for a complexType - case 'choice': - case 'group': - case 'sequence': - //$this->xdebug("compositor $name for currentComplexType: $this->currentComplexType and currentElement: $this->currentElement"); - $this->complexTypes[$this->currentComplexType]['compositor'] = $name; - //if($name == 'all' || $name == 'sequence'){ - // $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct'; - //} - break; - case 'attribute': // complexType attribute - //$this->xdebug("parsing attribute $attrs[name] $attrs[ref] of value: ".$attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']); - $this->xdebug("parsing attribute:"); - $this->appendDebug($this->varDump($attrs)); - if (!isset($attrs['form'])) { - $attrs['form'] = $this->schemaInfo['attributeFormDefault']; - } - if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) { - $v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; - if (!strpos($v, ':')) { - // no namespace in arrayType attribute value... - if ($this->defaultNamespace[$pos]) { - // ...so use the default - $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'] = $this->defaultNamespace[$pos] . ':' . $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; - } - } - } - if(isset($attrs['name'])){ - $this->attributes[$attrs['name']] = $attrs; - $aname = $attrs['name']; - } elseif(isset($attrs['ref']) && $attrs['ref'] == 'http://schemas.xmlsoap.org/soap/encoding/:arrayType'){ - if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) { - $aname = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; - } else { - $aname = ''; - } - } elseif(isset($attrs['ref'])){ - $aname = $attrs['ref']; - $this->attributes[$attrs['ref']] = $attrs; - } - - if($this->currentComplexType){ // This should *always* be - $this->complexTypes[$this->currentComplexType]['attrs'][$aname] = $attrs; - } - // arrayType attribute - if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']) || $this->getLocalPart($aname) == 'arrayType'){ - $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; - $prefix = $this->getPrefix($aname); - if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])){ - $v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; - } else { - $v = ''; - } - if(strpos($v,'[,]')){ - $this->complexTypes[$this->currentComplexType]['multidimensional'] = true; - } - $v = substr($v,0,strpos($v,'[')); // clip the [] - if(!strpos($v,':') && isset($this->typemap[$this->XMLSchemaVersion][$v])){ - $v = $this->XMLSchemaVersion.':'.$v; - } - $this->complexTypes[$this->currentComplexType]['arrayType'] = $v; - } - break; - case 'complexContent': // (optional) content for a complexType - break; - case 'complexType': - array_push($this->complexTypeStack, $this->currentComplexType); - if(isset($attrs['name'])){ - $this->xdebug('processing named complexType '.$attrs['name']); - //$this->currentElement = false; - $this->currentComplexType = $attrs['name']; - $this->complexTypes[$this->currentComplexType] = $attrs; - $this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType'; - // This is for constructs like - // - // - // - // - // - if(isset($attrs['base']) && ereg(':Array$',$attrs['base'])){ - $this->xdebug('complexType is unusual array'); - $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; - } else { - $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct'; - } - }else{ - $this->xdebug('processing unnamed complexType for element '.$this->currentElement); - $this->currentComplexType = $this->currentElement . '_ContainedType'; - //$this->currentElement = false; - $this->complexTypes[$this->currentComplexType] = $attrs; - $this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType'; - // This is for constructs like - // - // - // - // - // - if(isset($attrs['base']) && ereg(':Array$',$attrs['base'])){ - $this->xdebug('complexType is unusual array'); - $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; - } else { - $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct'; - } - } - break; - case 'element': - array_push($this->elementStack, $this->currentElement); - // elements defined as part of a complex type should - // not really be added to $this->elements, but for some - // reason, they are - if (!isset($attrs['form'])) { - $attrs['form'] = $this->schemaInfo['elementFormDefault']; - } - if(isset($attrs['type'])){ - $this->xdebug("processing typed element ".$attrs['name']." of type ".$attrs['type']); - if (! $this->getPrefix($attrs['type'])) { - if ($this->defaultNamespace[$pos]) { - $attrs['type'] = $this->defaultNamespace[$pos] . ':' . $attrs['type']; - $this->xdebug('used default namespace to make type ' . $attrs['type']); - } - } - // This is for constructs like - // - // - // - // - // - if ($this->currentComplexType && $this->complexTypes[$this->currentComplexType]['phpType'] == 'array') { - $this->xdebug('arrayType for unusual array is ' . $attrs['type']); - $this->complexTypes[$this->currentComplexType]['arrayType'] = $attrs['type']; - } - $this->currentElement = $attrs['name']; - $this->elements[ $attrs['name'] ] = $attrs; - $this->elements[ $attrs['name'] ]['typeClass'] = 'element'; - $ename = $attrs['name']; - } elseif(isset($attrs['ref'])){ - $this->xdebug("processing element as ref to ".$attrs['ref']); - $this->currentElement = "ref to ".$attrs['ref']; - $ename = $this->getLocalPart($attrs['ref']); - } else { - $this->xdebug("processing untyped element ".$attrs['name']); - $this->currentElement = $attrs['name']; - $this->elements[ $attrs['name'] ] = $attrs; - $this->elements[ $attrs['name'] ]['typeClass'] = 'element'; - $attrs['type'] = $this->schemaTargetNamespace . ':' . $attrs['name'] . '_ContainedType'; - $this->elements[ $attrs['name'] ]['type'] = $attrs['type']; - $ename = $attrs['name']; - } - if(isset($ename) && $this->currentComplexType){ - $this->complexTypes[$this->currentComplexType]['elements'][$ename] = $attrs; - } - break; - case 'enumeration': // restriction value list member - $this->xdebug('enumeration ' . $attrs['value']); - if ($this->currentSimpleType) { - $this->simpleTypes[$this->currentSimpleType]['enumeration'][] = $attrs['value']; - } elseif ($this->currentComplexType) { - $this->complexTypes[$this->currentComplexType]['enumeration'][] = $attrs['value']; - } - break; - case 'extension': // simpleContent or complexContent type extension - $this->xdebug('extension ' . $attrs['base']); - if ($this->currentComplexType) { - $this->complexTypes[$this->currentComplexType]['extensionBase'] = $attrs['base']; - } - break; - case 'import': - if (isset($attrs['schemaLocation'])) { - //$this->xdebug('import namespace ' . $attrs['namespace'] . ' from ' . $attrs['schemaLocation']); - $this->imports[$attrs['namespace']][] = array('location' => $attrs['schemaLocation'], 'loaded' => false); - } else { - //$this->xdebug('import namespace ' . $attrs['namespace']); - $this->imports[$attrs['namespace']][] = array('location' => '', 'loaded' => true); - if (! $this->getPrefixFromNamespace($attrs['namespace'])) { - $this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace']; - } - } - break; - case 'list': // simpleType value list - break; - case 'restriction': // simpleType, simpleContent or complexContent value restriction - $this->xdebug('restriction ' . $attrs['base']); - if($this->currentSimpleType){ - $this->simpleTypes[$this->currentSimpleType]['type'] = $attrs['base']; - } elseif($this->currentComplexType){ - $this->complexTypes[$this->currentComplexType]['restrictionBase'] = $attrs['base']; - if(strstr($attrs['base'],':') == ':Array'){ - $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; - } - } - break; - case 'schema': - $this->schemaInfo = $attrs; - $this->schemaInfo['schemaVersion'] = $this->getNamespaceFromPrefix($prefix); - if (isset($attrs['targetNamespace'])) { - $this->schemaTargetNamespace = $attrs['targetNamespace']; - } - if (!isset($attrs['elementFormDefault'])) { - $this->schemaInfo['elementFormDefault'] = 'unqualified'; - } - if (!isset($attrs['attributeFormDefault'])) { - $this->schemaInfo['attributeFormDefault'] = 'unqualified'; - } - break; - case 'simpleContent': // (optional) content for a complexType - break; - case 'simpleType': - array_push($this->simpleTypeStack, $this->currentSimpleType); - if(isset($attrs['name'])){ - $this->xdebug("processing simpleType for name " . $attrs['name']); - $this->currentSimpleType = $attrs['name']; - $this->simpleTypes[ $attrs['name'] ] = $attrs; - $this->simpleTypes[ $attrs['name'] ]['typeClass'] = 'simpleType'; - $this->simpleTypes[ $attrs['name'] ]['phpType'] = 'scalar'; - } else { - $this->xdebug('processing unnamed simpleType for element '.$this->currentElement); - $this->currentSimpleType = $this->currentElement . '_ContainedType'; - //$this->currentElement = false; - $this->simpleTypes[$this->currentSimpleType] = $attrs; - $this->simpleTypes[$this->currentSimpleType]['phpType'] = 'scalar'; - } - break; - case 'union': // simpleType type list - break; - default: - //$this->xdebug("do not have anything to do for element $name"); - } - } - - /** - * end-element handler - * - * @param string $parser XML parser object - * @param string $name element name - * @access private - */ - function schemaEndElement($parser, $name) { - // bring depth down a notch - $this->depth--; - // position of current element is equal to the last value left in depth_array for my depth - if(isset($this->depth_array[$this->depth])){ - $pos = $this->depth_array[$this->depth]; - } - // get element prefix - if ($prefix = $this->getPrefix($name)){ - // get unqualified name - $name = $this->getLocalPart($name); - } else { - $prefix = ''; - } - // move on... - if($name == 'complexType'){ - $this->xdebug('done processing complexType ' . ($this->currentComplexType ? $this->currentComplexType : '(unknown)')); - $this->currentComplexType = array_pop($this->complexTypeStack); - //$this->currentElement = false; - } - if($name == 'element'){ - $this->xdebug('done processing element ' . ($this->currentElement ? $this->currentElement : '(unknown)')); - $this->currentElement = array_pop($this->elementStack); - } - if($name == 'simpleType'){ - $this->xdebug('done processing simpleType ' . ($this->currentSimpleType ? $this->currentSimpleType : '(unknown)')); - $this->currentSimpleType = array_pop($this->simpleTypeStack); - } - } - - /** - * element content handler - * - * @param string $parser XML parser object - * @param string $data element content - * @access private - */ - function schemaCharacterData($parser, $data){ - $pos = $this->depth_array[$this->depth - 1]; - $this->message[$pos]['cdata'] .= $data; - } - - /** - * serialize the schema - * - * @access public - */ - function serializeSchema(){ - - $schemaPrefix = $this->getPrefixFromNamespace($this->XMLSchemaVersion); - $xml = ''; - // imports - if (sizeof($this->imports) > 0) { - foreach($this->imports as $ns => $list) { - foreach ($list as $ii) { - if ($ii['location'] != '') { - $xml .= " <$schemaPrefix:import location=\"" . $ii['location'] . '" namespace="' . $ns . "\" />\n"; - } else { - $xml .= " <$schemaPrefix:import namespace=\"" . $ns . "\" />\n"; - } - } - } - } - // complex types - foreach($this->complexTypes as $typeName => $attrs){ - $contentStr = ''; - // serialize child elements - if(isset($attrs['elements']) && (count($attrs['elements']) > 0)){ - foreach($attrs['elements'] as $element => $eParts){ - if(isset($eParts['ref'])){ - $contentStr .= " <$schemaPrefix:element ref=\"$element\"/>\n"; - } else { - $contentStr .= " <$schemaPrefix:element name=\"$element\" type=\"" . $this->contractQName($eParts['type']) . "\""; - foreach ($eParts as $aName => $aValue) { - // handle, e.g., abstract, default, form, minOccurs, maxOccurs, nillable - if ($aName != 'name' && $aName != 'type') { - $contentStr .= " $aName=\"$aValue\""; - } - } - $contentStr .= "/>\n"; - } - } - // compositor wraps elements - if (isset($attrs['compositor']) && ($attrs['compositor'] != '')) { - $contentStr = " <$schemaPrefix:$attrs[compositor]>\n".$contentStr." \n"; - } - } - // attributes - if(isset($attrs['attrs']) && (count($attrs['attrs']) >= 1)){ - foreach($attrs['attrs'] as $attr => $aParts){ - $contentStr .= " <$schemaPrefix:attribute"; - foreach ($aParts as $a => $v) { - if ($a == 'ref' || $a == 'type') { - $contentStr .= " $a=\"".$this->contractQName($v).'"'; - } elseif ($a == 'http://schemas.xmlsoap.org/wsdl/:arrayType') { - $this->usedNamespaces['wsdl'] = $this->namespaces['wsdl']; - $contentStr .= ' wsdl:arrayType="'.$this->contractQName($v).'"'; - } else { - $contentStr .= " $a=\"$v\""; - } - } - $contentStr .= "/>\n"; - } - } - // if restriction - if (isset($attrs['restrictionBase']) && $attrs['restrictionBase'] != ''){ - $contentStr = " <$schemaPrefix:restriction base=\"".$this->contractQName($attrs['restrictionBase'])."\">\n".$contentStr." \n"; - // complex or simple content - if ((isset($attrs['elements']) && count($attrs['elements']) > 0) || (isset($attrs['attrs']) && count($attrs['attrs']) > 0)){ - $contentStr = " <$schemaPrefix:complexContent>\n".$contentStr." \n"; - } - } - // finalize complex type - if($contentStr != ''){ - $contentStr = " <$schemaPrefix:complexType name=\"$typeName\">\n".$contentStr." \n"; - } else { - $contentStr = " <$schemaPrefix:complexType name=\"$typeName\"/>\n"; - } - $xml .= $contentStr; - } - // simple types - if(isset($this->simpleTypes) && count($this->simpleTypes) > 0){ - foreach($this->simpleTypes as $typeName => $eParts){ - $xml .= " <$schemaPrefix:simpleType name=\"$typeName\">\n <$schemaPrefix:restriction base=\"".$this->contractQName($eParts['type'])."\"/>\n"; - if (isset($eParts['enumeration'])) { - foreach ($eParts['enumeration'] as $e) { - $xml .= " <$schemaPrefix:enumeration value=\"$e\"/>\n"; - } - } - $xml .= " "; - } - } - // elements - if(isset($this->elements) && count($this->elements) > 0){ - foreach($this->elements as $element => $eParts){ - $xml .= " <$schemaPrefix:element name=\"$element\" type=\"".$this->contractQName($eParts['type'])."\"/>\n"; - } - } - // attributes - if(isset($this->attributes) && count($this->attributes) > 0){ - foreach($this->attributes as $attr => $aParts){ - $xml .= " <$schemaPrefix:attribute name=\"$attr\" type=\"".$this->contractQName($aParts['type'])."\"\n/>"; - } - } - // finish 'er up - $el = "<$schemaPrefix:schema targetNamespace=\"$this->schemaTargetNamespace\"\n"; - foreach (array_diff($this->usedNamespaces, $this->enclosingNamespaces) as $nsp => $ns) { - $el .= " xmlns:$nsp=\"$ns\"\n"; - } - $xml = $el . ">\n".$xml."\n"; - return $xml; - } - - /** - * adds debug data to the clas level debug string - * - * @param string $string debug data - * @access private - */ - function xdebug($string){ - $this->debug('<' . $this->schemaTargetNamespace . '> '.$string); - } - - /** - * get the PHP type of a user defined type in the schema - * PHP type is kind of a misnomer since it actually returns 'struct' for assoc. arrays - * returns false if no type exists, or not w/ the given namespace - * else returns a string that is either a native php type, or 'struct' - * - * @param string $type, name of defined type - * @param string $ns, namespace of type - * @return mixed - * @access public - * @deprecated - */ - function getPHPType($type,$ns){ - if(isset($this->typemap[$ns][$type])){ - //print "found type '$type' and ns $ns in typemap
"; - return $this->typemap[$ns][$type]; - } elseif(isset($this->complexTypes[$type])){ - //print "getting type '$type' and ns $ns from complexTypes array
"; - return $this->complexTypes[$type]['phpType']; - } - return false; - } - - /** - * returns an associative array of information about a given type - * returns false if no type exists by the given name - * - * For a complexType typeDef = array( - * 'restrictionBase' => '', - * 'phpType' => '', - * 'compositor' => '(sequence|all)', - * 'elements' => array(), // refs to elements array - * 'attrs' => array() // refs to attributes array - * ... and so on (see addComplexType) - * ) - * - * For simpleType or element, the array has different keys. - * - * @param string - * @return mixed - * @access public - * @see addComplexType - * @see addSimpleType - * @see addElement - */ - function getTypeDef($type){ - //$this->debug("in getTypeDef for type $type"); - if(isset($this->complexTypes[$type])){ - $this->xdebug("in getTypeDef, found complexType $type"); - return $this->complexTypes[$type]; - } elseif(isset($this->simpleTypes[$type])){ - $this->xdebug("in getTypeDef, found simpleType $type"); - if (!isset($this->simpleTypes[$type]['phpType'])) { - // get info for type to tack onto the simple type - // TODO: can this ever really apply (i.e. what is a simpleType really?) - $uqType = substr($this->simpleTypes[$type]['type'], strrpos($this->simpleTypes[$type]['type'], ':') + 1); - $ns = substr($this->simpleTypes[$type]['type'], 0, strrpos($this->simpleTypes[$type]['type'], ':')); - $etype = $this->getTypeDef($uqType); - if ($etype) { - $this->xdebug("in getTypeDef, found type for simpleType $type:"); - $this->xdebug($this->varDump($etype)); - if (isset($etype['phpType'])) { - $this->simpleTypes[$type]['phpType'] = $etype['phpType']; - } - if (isset($etype['elements'])) { - $this->simpleTypes[$type]['elements'] = $etype['elements']; - } - } - } - return $this->simpleTypes[$type]; - } elseif(isset($this->elements[$type])){ - $this->xdebug("in getTypeDef, found element $type"); - if (!isset($this->elements[$type]['phpType'])) { - // get info for type to tack onto the element - $uqType = substr($this->elements[$type]['type'], strrpos($this->elements[$type]['type'], ':') + 1); - $ns = substr($this->elements[$type]['type'], 0, strrpos($this->elements[$type]['type'], ':')); - $etype = $this->getTypeDef($uqType); - if ($etype) { - $this->xdebug("in getTypeDef, found type for element $type:"); - $this->xdebug($this->varDump($etype)); - if (isset($etype['phpType'])) { - $this->elements[$type]['phpType'] = $etype['phpType']; - } - if (isset($etype['elements'])) { - $this->elements[$type]['elements'] = $etype['elements']; - } - } elseif ($ns == 'http://www.w3.org/2001/XMLSchema') { - $this->xdebug("in getTypeDef, element $type is an XSD type"); - $this->elements[$type]['phpType'] = 'scalar'; - } - } - return $this->elements[$type]; - } elseif(isset($this->attributes[$type])){ - $this->xdebug("in getTypeDef, found attribute $type"); - return $this->attributes[$type]; - } elseif (ereg('_ContainedType$', $type)) { - $this->xdebug("in getTypeDef, have an untyped element $type"); - $typeDef['typeClass'] = 'simpleType'; - $typeDef['phpType'] = 'scalar'; - $typeDef['type'] = 'http://www.w3.org/2001/XMLSchema:string'; - return $typeDef; - } - $this->xdebug("in getTypeDef, did not find $type"); - return false; - } - - /** - * returns a sample serialization of a given type, or false if no type by the given name - * - * @param string $type, name of type - * @return mixed - * @access public - * @deprecated - */ - function serializeTypeDef($type){ - //print "in sTD() for type $type
"; - if($typeDef = $this->getTypeDef($type)){ - $str .= '<'.$type; - if(is_array($typeDef['attrs'])){ - foreach($attrs as $attName => $data){ - $str .= " $attName=\"{type = ".$data['type']."}\""; - } - } - $str .= " xmlns=\"".$this->schema['targetNamespace']."\""; - if(count($typeDef['elements']) > 0){ - $str .= ">"; - foreach($typeDef['elements'] as $element => $eData){ - $str .= $this->serializeTypeDef($element); - } - $str .= ""; - } elseif($typeDef['typeClass'] == 'element') { - $str .= ">"; - } else { - $str .= "/>"; - } - return $str; - } - return false; - } - - /** - * returns HTML form elements that allow a user - * to enter values for creating an instance of the given type. - * - * @param string $name, name for type instance - * @param string $type, name of type - * @return string - * @access public - * @deprecated - */ - function typeToForm($name,$type){ - // get typedef - if($typeDef = $this->getTypeDef($type)){ - // if struct - if($typeDef['phpType'] == 'struct'){ - $buffer .= ''; - foreach($typeDef['elements'] as $child => $childDef){ - $buffer .= " - - "; - } - $buffer .= '
$childDef[name] (type: ".$this->getLocalPart($childDef['type'])."):
'; - // if array - } elseif($typeDef['phpType'] == 'array'){ - $buffer .= ''; - for($i=0;$i < 3; $i++){ - $buffer .= " - - "; - } - $buffer .= '
array item (type: $typeDef[arrayType]):
'; - // if scalar - } else { - $buffer .= ""; - } - } else { - $buffer .= ""; - } - return $buffer; - } - - /** - * adds a complex type to the schema - * - * example: array - * - * addType( - * 'ArrayOfstring', - * 'complexType', - * 'array', - * '', - * 'SOAP-ENC:Array', - * array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'string[]'), - * 'xsd:string' - * ); - * - * example: PHP associative array ( SOAP Struct ) - * - * addType( - * 'SOAPStruct', - * 'complexType', - * 'struct', - * 'all', - * array('myVar'=> array('name'=>'myVar','type'=>'string') - * ); - * - * @param name - * @param typeClass (complexType|simpleType|attribute) - * @param phpType: currently supported are array and struct (php assoc array) - * @param compositor (all|sequence|choice) - * @param restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) - * @param elements = array ( name = array(name=>'',type=>'') ) - * @param attrs = array( - * array( - * 'ref' => "http://schemas.xmlsoap.org/soap/encoding/:arrayType", - * "http://schemas.xmlsoap.org/wsdl/:arrayType" => "string[]" - * ) - * ) - * @param arrayType: namespace:name (http://www.w3.org/2001/XMLSchema:string) - * @access public - * @see getTypeDef - */ - function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType=''){ - $this->complexTypes[$name] = array( - 'name' => $name, - 'typeClass' => $typeClass, - 'phpType' => $phpType, - 'compositor'=> $compositor, - 'restrictionBase' => $restrictionBase, - 'elements' => $elements, - 'attrs' => $attrs, - 'arrayType' => $arrayType - ); - - $this->xdebug("addComplexType $name:"); - $this->appendDebug($this->varDump($this->complexTypes[$name])); - } - - /** - * adds a simple type to the schema - * - * @param string $name - * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) - * @param string $typeClass (should always be simpleType) - * @param string $phpType (should always be scalar) - * @param array $enumeration array of values - * @access public - * @see xmlschema - * @see getTypeDef - */ - function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) { - $this->simpleTypes[$name] = array( - 'name' => $name, - 'typeClass' => $typeClass, - 'phpType' => $phpType, - 'type' => $restrictionBase, - 'enumeration' => $enumeration - ); - - $this->xdebug("addSimpleType $name:"); - $this->appendDebug($this->varDump($this->simpleTypes[$name])); - } - - /** - * adds an element to the schema - * - * @param array $attrs attributes that must include name and type - * @see xmlschema - * @access public - */ - function addElement($attrs) { - if (! $this->getPrefix($attrs['type'])) { - $attrs['type'] = $this->schemaTargetNamespace . ':' . $attrs['type']; - } - $this->elements[ $attrs['name'] ] = $attrs; - $this->elements[ $attrs['name'] ]['typeClass'] = 'element'; - - $this->xdebug("addElement " . $attrs['name']); - $this->appendDebug($this->varDump($this->elements[ $attrs['name'] ])); - } -} - - - - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/console_getopt/.gitignore b/gulliver/thirdparty/pear/console_getopt/.gitignore deleted file mode 100644 index 783582816..000000000 --- a/gulliver/thirdparty/pear/console_getopt/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -# composer related -composer.lock -composer.phar -vendor -README.html -dist/ diff --git a/gulliver/thirdparty/pear/console_getopt/.travis.yml b/gulliver/thirdparty/pear/console_getopt/.travis.yml deleted file mode 100644 index 2711415f5..000000000 --- a/gulliver/thirdparty/pear/console_getopt/.travis.yml +++ /dev/null @@ -1,9 +0,0 @@ -language: php -php: - - 7 - - 5.6 - - 5.5 - - 5.4 -sudo: false -script: - - pear run-tests -r tests/ diff --git a/gulliver/thirdparty/pear/console_getopt/Console/Getopt.php b/gulliver/thirdparty/pear/console_getopt/Console/Getopt.php deleted file mode 100644 index 0da88585d..000000000 --- a/gulliver/thirdparty/pear/console_getopt/Console/Getopt.php +++ /dev/null @@ -1,360 +0,0 @@ - - * @license http://www.php.net/license/3_0.txt PHP 3.0 - * @version CVS: $Id$ - * @link http://pear.php.net/package/Console_Getopt - */ - -require_once 'PEAR.php'; - -/** - * Command-line options parsing class. - * - * @category Console - * @package Console_Getopt - * @author Andrei Zmievski - * @license http://www.php.net/license/3_0.txt PHP 3.0 - * @link http://pear.php.net/package/Console_Getopt - */ -class Console_Getopt -{ - - /** - * Parses the command-line options. - * - * The first parameter to this function should be the list of command-line - * arguments without the leading reference to the running program. - * - * The second parameter is a string of allowed short options. Each of the - * option letters can be followed by a colon ':' to specify that the option - * requires an argument, or a double colon '::' to specify that the option - * takes an optional argument. - * - * The third argument is an optional array of allowed long options. The - * leading '--' should not be included in the option name. Options that - * require an argument should be followed by '=', and options that take an - * option argument should be followed by '=='. - * - * The return value is an array of two elements: the list of parsed - * options and the list of non-option command-line arguments. Each entry in - * the list of parsed options is a pair of elements - the first one - * specifies the option, and the second one specifies the option argument, - * if there was one. - * - * Long and short options can be mixed. - * - * Most of the semantics of this function are based on GNU getopt_long(). - * - * @param array $args an array of command-line arguments - * @param string $short_options specifies the list of allowed short options - * @param array $long_options specifies the list of allowed long options - * @param boolean $skip_unknown suppresses Console_Getopt: unrecognized option - * - * @return array two-element array containing the list of parsed options and - * the non-option arguments - */ - public static function getopt2($args, $short_options, $long_options = null, $skip_unknown = false) - { - return Console_Getopt::doGetopt(2, $args, $short_options, $long_options, $skip_unknown); - } - - /** - * This function expects $args to start with the script name (POSIX-style). - * Preserved for backwards compatibility. - * - * @param array $args an array of command-line arguments - * @param string $short_options specifies the list of allowed short options - * @param array $long_options specifies the list of allowed long options - * - * @see getopt2() - * @return array two-element array containing the list of parsed options and - * the non-option arguments - */ - public static function getopt($args, $short_options, $long_options = null, $skip_unknown = false) - { - return Console_Getopt::doGetopt(1, $args, $short_options, $long_options, $skip_unknown); - } - - /** - * The actual implementation of the argument parsing code. - * - * @param int $version Version to use - * @param array $args an array of command-line arguments - * @param string $short_options specifies the list of allowed short options - * @param array $long_options specifies the list of allowed long options - * @param boolean $skip_unknown suppresses Console_Getopt: unrecognized option - * - * @return array - */ - public static function doGetopt($version, $args, $short_options, $long_options = null, $skip_unknown = false) - { - // in case you pass directly readPHPArgv() as the first arg - if (PEAR::isError($args)) { - return $args; - } - - if (empty($args)) { - return array(array(), array()); - } - - $non_opts = $opts = array(); - - settype($args, 'array'); - - if ($long_options) { - sort($long_options); - } - - /* - * Preserve backwards compatibility with callers that relied on - * erroneous POSIX fix. - */ - if ($version < 2) { - if (isset($args[0]{0}) && $args[0]{0} != '-') { - array_shift($args); - } - } - - reset($args); - while (list($i, $arg) = each($args)) { - /* The special element '--' means explicit end of - options. Treat the rest of the arguments as non-options - and end the loop. */ - if ($arg == '--') { - $non_opts = array_merge($non_opts, array_slice($args, $i + 1)); - break; - } - - if ($arg{0} != '-' || (strlen($arg) > 1 && $arg{1} == '-' && !$long_options)) { - $non_opts = array_merge($non_opts, array_slice($args, $i)); - break; - } elseif (strlen($arg) > 1 && $arg{1} == '-') { - $error = Console_Getopt::_parseLongOption(substr($arg, 2), - $long_options, - $opts, - $args, - $skip_unknown); - if (PEAR::isError($error)) { - return $error; - } - } elseif ($arg == '-') { - // - is stdin - $non_opts = array_merge($non_opts, array_slice($args, $i)); - break; - } else { - $error = Console_Getopt::_parseShortOption(substr($arg, 1), - $short_options, - $opts, - $args, - $skip_unknown); - if (PEAR::isError($error)) { - return $error; - } - } - } - - return array($opts, $non_opts); - } - - /** - * Parse short option - * - * @param string $arg Argument - * @param string[] $short_options Available short options - * @param string[][] &$opts - * @param string[] &$args - * @param boolean $skip_unknown suppresses Console_Getopt: unrecognized option - * - * @return void - */ - protected static function _parseShortOption($arg, $short_options, &$opts, &$args, $skip_unknown) - { - for ($i = 0; $i < strlen($arg); $i++) { - $opt = $arg{$i}; - $opt_arg = null; - - /* Try to find the short option in the specifier string. */ - if (($spec = strstr($short_options, $opt)) === false || $arg{$i} == ':') { - if ($skip_unknown === true) { - break; - } - - $msg = "Console_Getopt: unrecognized option -- $opt"; - return PEAR::raiseError($msg); - } - - if (strlen($spec) > 1 && $spec{1} == ':') { - if (strlen($spec) > 2 && $spec{2} == ':') { - if ($i + 1 < strlen($arg)) { - /* Option takes an optional argument. Use the remainder of - the arg string if there is anything left. */ - $opts[] = array($opt, substr($arg, $i + 1)); - break; - } - } else { - /* Option requires an argument. Use the remainder of the arg - string if there is anything left. */ - if ($i + 1 < strlen($arg)) { - $opts[] = array($opt, substr($arg, $i + 1)); - break; - } else if (list(, $opt_arg) = each($args)) { - /* Else use the next argument. */; - if (Console_Getopt::_isShortOpt($opt_arg) - || Console_Getopt::_isLongOpt($opt_arg)) { - $msg = "option requires an argument --$opt"; - return PEAR::raiseError("Console_Getopt: " . $msg); - } - } else { - $msg = "option requires an argument --$opt"; - return PEAR::raiseError("Console_Getopt: " . $msg); - } - } - } - - $opts[] = array($opt, $opt_arg); - } - } - - /** - * Checks if an argument is a short option - * - * @param string $arg Argument to check - * - * @return bool - */ - protected static function _isShortOpt($arg) - { - return strlen($arg) == 2 && $arg[0] == '-' - && preg_match('/[a-zA-Z]/', $arg[1]); - } - - /** - * Checks if an argument is a long option - * - * @param string $arg Argument to check - * - * @return bool - */ - protected static function _isLongOpt($arg) - { - return strlen($arg) > 2 && $arg[0] == '-' && $arg[1] == '-' && - preg_match('/[a-zA-Z]+$/', substr($arg, 2)); - } - - /** - * Parse long option - * - * @param string $arg Argument - * @param string[] $long_options Available long options - * @param string[][] &$opts - * @param string[] &$args - * - * @return void|PEAR_Error - */ - protected static function _parseLongOption($arg, $long_options, &$opts, &$args, $skip_unknown) - { - @list($opt, $opt_arg) = explode('=', $arg, 2); - - $opt_len = strlen($opt); - - for ($i = 0; $i < count($long_options); $i++) { - $long_opt = $long_options[$i]; - $opt_start = substr($long_opt, 0, $opt_len); - - $long_opt_name = str_replace('=', '', $long_opt); - - /* Option doesn't match. Go on to the next one. */ - if ($long_opt_name != $opt) { - continue; - } - - $opt_rest = substr($long_opt, $opt_len); - - /* Check that the options uniquely matches one of the allowed - options. */ - if ($i + 1 < count($long_options)) { - $next_option_rest = substr($long_options[$i + 1], $opt_len); - } else { - $next_option_rest = ''; - } - - if ($opt_rest != '' && $opt{0} != '=' && - $i + 1 < count($long_options) && - $opt == substr($long_options[$i+1], 0, $opt_len) && - $next_option_rest != '' && - $next_option_rest{0} != '=') { - - $msg = "Console_Getopt: option --$opt is ambiguous"; - return PEAR::raiseError($msg); - } - - if (substr($long_opt, -1) == '=') { - if (substr($long_opt, -2) != '==') { - /* Long option requires an argument. - Take the next argument if one wasn't specified. */; - if (!strlen($opt_arg) && !(list(, $opt_arg) = each($args))) { - $msg = "Console_Getopt: option requires an argument --$opt"; - return PEAR::raiseError($msg); - } - - if (Console_Getopt::_isShortOpt($opt_arg) - || Console_Getopt::_isLongOpt($opt_arg)) { - $msg = "Console_Getopt: option requires an argument --$opt"; - return PEAR::raiseError($msg); - } - } - } else if ($opt_arg) { - $msg = "Console_Getopt: option --$opt doesn't allow an argument"; - return PEAR::raiseError($msg); - } - - $opts[] = array('--' . $opt, $opt_arg); - return; - } - - if ($skip_unknown === true) { - return; - } - - return PEAR::raiseError("Console_Getopt: unrecognized option --$opt"); - } - - /** - * Safely read the $argv PHP array across different PHP configurations. - * Will take care on register_globals and register_argc_argv ini directives - * - * @return mixed the $argv PHP array or PEAR error if not registered - */ - public static function readPHPArgv() - { - global $argv; - if (!is_array($argv)) { - if (!@is_array($_SERVER['argv'])) { - if (!@is_array($GLOBALS['HTTP_SERVER_VARS']['argv'])) { - $msg = "Could not read cmd args (register_argc_argv=Off?)"; - return PEAR::raiseError("Console_Getopt: " . $msg); - } - return $GLOBALS['HTTP_SERVER_VARS']['argv']; - } - return $_SERVER['argv']; - } - return $argv; - } - -} \ No newline at end of file diff --git a/gulliver/thirdparty/pear/console_getopt/LICENSE b/gulliver/thirdparty/pear/console_getopt/LICENSE deleted file mode 100644 index 452b08839..000000000 --- a/gulliver/thirdparty/pear/console_getopt/LICENSE +++ /dev/null @@ -1,25 +0,0 @@ -Copyright (c) 2001-2015, The PEAR developers -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -1. Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - -2. 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 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 -HOLDER 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. diff --git a/gulliver/thirdparty/pear/console_getopt/README.rst b/gulliver/thirdparty/pear/console_getopt/README.rst deleted file mode 100644 index 64e5b41be..000000000 --- a/gulliver/thirdparty/pear/console_getopt/README.rst +++ /dev/null @@ -1,26 +0,0 @@ -******************************************* -Console_Getopt - Command-line option parser -******************************************* - -This is a PHP implementation of "getopt" supporting both short and long options. -It helps parsing command line options in your PHP script. - -Homepage: http://pear.php.net/package/Console_Getopt - -.. image:: https://travis-ci.org/pear/Console_Getopt.svg?branch=master - :target: https://travis-ci.org/pear/Console_Getopt - - -Alternatives -============ - -* Console_CommandLine__ (recommended) -* Console_GetoptPlus__ - -__ http://pear.php.net/package/Console_CommandLine -__ http://pear.php.net/package/Console_GetoptPlus - - -License -======= -BSD-2-Clause diff --git a/gulliver/thirdparty/pear/console_getopt/composer.json b/gulliver/thirdparty/pear/console_getopt/composer.json deleted file mode 100644 index 4dc7e7cca..000000000 --- a/gulliver/thirdparty/pear/console_getopt/composer.json +++ /dev/null @@ -1,35 +0,0 @@ -{ - "authors": [ - { - "email": "andrei@php.net", - "name": "Andrei Zmievski", - "role": "Lead" - }, - { - "email": "stig@php.net", - "name": "Stig Bakken", - "role": "Developer" - }, - { - "email": "cellog@php.net", - "name": "Greg Beaver", - "role": "Helper" - } - ], - "autoload": { - "psr-0": { - "Console": "./" - } - }, - "description": "More info available on: http://pear.php.net/package/Console_Getopt", - "include-path": [ - "./" - ], - "license": "BSD-2-Clause", - "name": "pear/console_getopt", - "support": { - "issues": "http://pear.php.net/bugs/search.php?cmd=display&package_name[]=Console_Getopt", - "source": "https://github.com/pear/Console_Getopt" - }, - "type": "library" -} diff --git a/gulliver/thirdparty/pear/console_getopt/package.xml b/gulliver/thirdparty/pear/console_getopt/package.xml deleted file mode 100644 index 7e8deb0e8..000000000 --- a/gulliver/thirdparty/pear/console_getopt/package.xml +++ /dev/null @@ -1,269 +0,0 @@ - - - Console_Getopt - pear.php.net - Command-line option parser - This is a PHP implementation of "getopt" supporting both -short and long options. - - Andrei Zmievski - andrei - andrei@php.net - no - - - Stig Bakken - ssb - stig@php.net - no - - - Greg Beaver - cellog - cellog@php.net - yes - - - 2015-07-20 - - - 1.4.1 - 1.4.0 - - - stable - stable - - BSD-2-Clause - - -* Fix unit test on PHP 7 [cweiske] - - - - - - - - - - - - - - - - - - PEAR - pear.php.net - 1.4.0 - 1.999.999 - - - - - - 5.4.0 - - - 1.8.0 - - - - - - - - - - 2015-07-20 - - 1.4.1 - 1.4.0 - - - stable - stable - - BSD-2-Clause - - * Fix unit test on PHP 7 [cweiske] - - - - - 2015-02-22 - - 1.4.0 - 1.4.0 - - - stable - stable - - BSD-2-Clause - - * Change license to BSD-2-Clause - * Set minimum PHP version to 5.4.0 - * Mark static methods with "static" keyword - - - - - 2011-03-07 - - 1.3.1 - 1.3.0 - - - stable - stable - - PHP License - - * Change the minimum PEAR installer dep to be lower - - - - - 2010-12-11 - - - 1.3.0 - 1.3.0 - - - stable - stable - - PHP License - - * Implement Request #13140: [PATCH] to skip unknown parameters. [patch by rquadling, improved on by dufuz] - - - - - 2007-06-12 - - 1.2.3 - 1.2.1 - - - stable - stable - - PHP License - -* fix Bug #11068: No way to read plain "-" option [cardoe] - - - - - 1.2.2 - 1.2.1 - - - stable - stable - - 2007-02-17 - PHP License - -* fix Bug #4475: An ambiguous error occurred when specifying similar longoption name. -* fix Bug #10055: Not failing properly on short options missing required values - - - - - 1.2.1 - 1.2.1 - - - stable - stable - - 2006-12-08 - PHP License - -Fixed bugs #4448 (Long parameter values truncated with longoption parameter) and #7444 (Trailing spaces after php closing tag) - - - - - 1.2 - 1.2 - - - stable - stable - - 2003-12-11 - PHP License - -Fix to preserve BC with 1.0 and allow correct behaviour for new users - - - - - 1.0 - 1.0 - - - stable - stable - - 2002-09-13 - PHP License - -Stable release - - - - - 0.11 - 0.11 - - - beta - beta - - 2002-05-26 - PHP License - -POSIX getopt compatibility fix: treat first element of args - array as command name - - - - - 0.10 - 0.10 - - - beta - beta - - 2002-05-12 - PHP License - -Packaging fix - - - - - 0.9 - 0.9 - - - beta - beta - - 2002-05-12 - PHP License - -Initial release - - - - diff --git a/gulliver/thirdparty/pear/console_getopt/tests/001-getopt.phpt b/gulliver/thirdparty/pear/console_getopt/tests/001-getopt.phpt deleted file mode 100644 index 75ae8481b..000000000 --- a/gulliver/thirdparty/pear/console_getopt/tests/001-getopt.phpt +++ /dev/null @@ -1,63 +0,0 @@ ---TEST-- -Console_Getopt ---FILE-- - $d) { - if ($i++ > 0) { - print ", "; - } - print $d[0] . '=' . $d[1]; - } - print "\n"; - print "params: " . implode(", ", $non_opts) . "\n"; - print "\n"; -} - -test("-abc", "abc"); -test("-abc foo", "abc"); -test("-abc foo", "abc:"); -test("-abc foo bar gazonk", "abc"); -test("-abc foo bar gazonk", "abc:"); -test("-a -b -c", "abc"); -test("-a -b -c", "abc:"); -test("-abc", "ab:c"); -test("-abc foo -bar gazonk", "abc"); -?> ---EXPECT-- -options: a=, b=, c= -params: - -options: a=, b=, c= -params: foo - -options: a=, b=, c=foo -params: - -options: a=, b=, c= -params: foo, bar, gazonk - -options: a=, b=, c=foo -params: bar, gazonk - -options: a=, b=, c= -params: - -Console_Getopt: option requires an argument --c - -options: a=, b=c -params: - -options: a=, b=, c= -params: foo, -bar, gazonk diff --git a/gulliver/thirdparty/pear/console_getopt/tests/bug10557.phpt b/gulliver/thirdparty/pear/console_getopt/tests/bug10557.phpt deleted file mode 100644 index 08b72ac8f..000000000 --- a/gulliver/thirdparty/pear/console_getopt/tests/bug10557.phpt +++ /dev/null @@ -1,22 +0,0 @@ ---TEST-- -Console_Getopt [bug 10557] ---SKIPIF-- ---FILE-- -getMessage()."\n"; - echo 'FATAL'; - exit; -} - -print_r($ret); -?> ---EXPECT-- -Console_Getopt: option requires an argument --to -FATAL \ No newline at end of file diff --git a/gulliver/thirdparty/pear/console_getopt/tests/bug11068.phpt b/gulliver/thirdparty/pear/console_getopt/tests/bug11068.phpt deleted file mode 100644 index 8bbe4bfce..000000000 --- a/gulliver/thirdparty/pear/console_getopt/tests/bug11068.phpt +++ /dev/null @@ -1,44 +0,0 @@ ---TEST-- -Console_Getopt [bug 11068] ---SKIPIF-- ---FILE-- -getMessage()."\n"; - echo 'FATAL'; - exit; -} - -print_r($ret); -?> ---EXPECT-- -Array -( - [0] => Array - ( - [0] => Array - ( - [0] => f - [1] => jjohnston@mail.com - ) - - [1] => Array - ( - [0] => --to - [1] => hi - ) - - ) - - [1] => Array - ( - [0] => - - ) - -) \ No newline at end of file diff --git a/gulliver/thirdparty/pear/console_getopt/tests/bug13140.phpt b/gulliver/thirdparty/pear/console_getopt/tests/bug13140.phpt deleted file mode 100644 index 4ce13bbf9..000000000 --- a/gulliver/thirdparty/pear/console_getopt/tests/bug13140.phpt +++ /dev/null @@ -1,75 +0,0 @@ ---TEST-- -Console_Getopt [bug 13140] ---SKIPIF-- ---FILE-- -getopt2($cg->readPHPArgv(), 't', array('test'), true)); -print_r($cg->getopt2($cg->readPHPArgv(), 'bar', array('foo'), true)); -?> ---EXPECT-- -Array -( - [0] => Array - ( - [0] => Array - ( - [0] => --test - [1] => - ) - - ) - - [1] => Array - ( - [0] => thisshouldbehere - ) - -) -Array -( - [0] => Array - ( - [0] => Array - ( - [0] => --foo - [1] => - ) - - [1] => Array - ( - [0] => b - [1] => - ) - - [2] => Array - ( - [0] => a - [1] => - ) - - [3] => Array - ( - [0] => r - [1] => - ) - - [4] => Array - ( - [0] => r - [1] => - ) - - ) - - [1] => Array - ( - [0] => thisshouldbehere - ) - -) diff --git a/gulliver/thirdparty/pear/install-pear.php b/gulliver/thirdparty/pear/install-pear.php deleted file mode 100644 index 1585ee81f..000000000 --- a/gulliver/thirdparty/pear/install-pear.php +++ /dev/null @@ -1,109 +0,0 @@ - install_file -$install_files = array(); - -/* -$dp = opendir($pear_dir); -while ($ent = readdir($dp)) { - if (ereg('^package-(.*)\.xml$', $ent, $matches)) { - $install_files[$matches[1]] = $ent; - } -} -closedir($dp); -*/ -foreach ($argv as $arg) { - $bn = basename($arg); - if (ereg('^package-(.*)\.xml$', $bn, $matches) || - ereg('^([A-Za-z0-9_:]+)-.*\.(tar|tgz)$', $bn, $matches)) { - $install_files[$matches[1]] = $arg; - } -} - -$config = &PEAR_Config::singleton(); - -// make sure we use only default values -$config_layers = $config->getLayers(); -foreach ($config_layers as $layer) { - if ($layer == 'default') continue; - $config->removeLayer($layer); -} -$config->set('verbose', 0, 'default'); - -$options = array(); -$install_root = getenv("INSTALL_ROOT"); -$php_dir = $config->get('php_dir'); -if (!empty($install_root)) { - $options['installroot'] = $install_root; - $reg_dir = $install_root . $php_dir; -} else { - $reg_dir = $php_dir; -} - -$reg = &new PEAR_Registry($reg_dir); -$ui = &new PEAR_Frontend_CLI(); -$installer = &new PEAR_Installer($ui); -$installer->registry = &$reg; - -foreach ($install_files as $package => $instfile) { - if ($reg->packageExists($package)) { - $info = $installer->infoFromAny($instfile); - if (PEAR::isError($info)) { - $ui->outputData(sprintf("[PEAR] %s: %s", $package, $info->getMessage())); - continue; - } - $new_ver = $info['version']; - $old_ver = $reg->packageInfo($package, 'version'); - if (version_compare($new_ver, $old_ver, 'gt')) { - $options['upgrade'] = true; - $err = $installer->install($instfile, $options); - if (PEAR::isError($err)) { - $ui->outputData(sprintf("[PEAR] %s: %s", $package, $err->getMessage())); - continue; - } - $ui->outputData(sprintf("[PEAR] %-15s- upgraded: %s", $package, $new_ver)); - } else { - if (@$argv[1] == '--force') { - $options['force'] = true; - $err = $installer->install($instfile, $options); - if (PEAR::isError($err)) { - $ui->outputData(sprintf("[PEAR] %s: %s", $package, $err->getMessage())); - continue; - } - $ui->outputData(sprintf("[PEAR] %-15s- installed: %s", $package, $new_ver)); - } else { - $ui->outputData(sprintf("[PEAR] %-15s- already installed: %s", $package, $old_ver)); - } - } - } else { - $options['nodeps'] = true; - $err = $installer->install($instfile, $options); - if (PEAR::isError($err)) { - $ui->outputData(sprintf("[PEAR] %s: %s", $package, $err->getMessage())); - continue; - } - $new_ver = $reg->packageInfo($package, 'version'); - $ui->outputData(sprintf("[PEAR] %-15s- installed: %s", $package, $new_ver)); - } -} - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/install-pear.txt b/gulliver/thirdparty/pear/install-pear.txt deleted file mode 100644 index ec632e8ad..000000000 --- a/gulliver/thirdparty/pear/install-pear.txt +++ /dev/null @@ -1,11 +0,0 @@ -+----------------------------------------------------------------------+ -| The installation process is incomplete. The following resources were | -| not installed: | -| | -| Self-contained Extension Support | -| PEAR: PHP Extension and Application Repository | -| | -| To install these components, become the superuser and execute: | -| | -| # make install-su | -+----------------------------------------------------------------------+ diff --git a/gulliver/thirdparty/pear/json/class.json.php b/gulliver/thirdparty/pear/json/class.json.php deleted file mode 100644 index a6ae92da9..000000000 --- a/gulliver/thirdparty/pear/json/class.json.php +++ /dev/null @@ -1,817 +0,0 @@ - - * @author Matt Knapp - * @author Brett Stimmerman - * @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 - */ -if ( !defined('SERVICES_JSON_SLICE')) { - define('SERVICES_JSON_SLICE', 1); -} -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -if ( !defined('SERVICES_JSON_IN_STR')) { -define('SERVICES_JSON_IN_STR', 2); -} -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -if ( !defined('SERVICES_JSON_IN_ARR')) { - define('SERVICES_JSON_IN_ARR', 3); -} -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -if ( !defined('SERVICES_JSON_IN_OBJ')) { - define('SERVICES_JSON_IN_OBJ', 4); -} -/** - * Marker constant for Services_JSON::decode(), used to flag stack state - */ -if ( !defined('SERVICES_JSON_IN_CMT')) { - define('SERVICES_JSON_IN_CMT', 5); -} -/** - * Behavior switch for Services_JSON::decode() - */ -if ( !defined('SERVICES_JSON_LOOSE_TYPE')) { - define('SERVICES_JSON_LOOSE_TYPE', 16); -} -/** - * Behavior switch for Services_JSON::decode() - */ -if ( !defined('SERVICES_JSON_SUPPRESS_ERRORS')) { - define('SERVICES_JSON_SUPPRESS_ERRORS', 32); -} -/** - * Converts to and from JSON format. - * - * Brief example of use: - * - * - * // 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); - * - */ - -if (class_exists ('Services_JSON') ) { - return; -} -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) - { - - } - } - -} - -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/nusoap.colosa.php b/gulliver/thirdparty/pear/nusoap.colosa.php deleted file mode 100644 index ab3b3cc32..000000000 --- a/gulliver/thirdparty/pear/nusoap.colosa.php +++ /dev/null @@ -1,7305 +0,0 @@ -globalDebugLevel = 9; - -/** -* -* nusoap_base -* -* @author Dietrich Ayala -* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class nusoap_base_colosa { - /** - * Identification for HTTP headers. - * - * @var string - * @access private - */ - var $title = 'NuSOAP_colosa'; - /** - * Version for HTTP headers. - * - * @var string - * @access private - */ - var $version = '0.7.2'; - /** - * CVS revision for HTTP headers. - * - * @var string - * @access private - */ - var $revision = '$Revision: 1.94 $'; - /** - * Current error string (manipulated by getError/setError) - * - * @var string - * @access private - */ - var $error_str = ''; - /** - * Current debug string (manipulated by debug/appendDebug/clearDebug/getDebug/getDebugAsXMLComment) - * - * @var string - * @access private - */ - var $debug_str = ''; - /** - * toggles automatic encoding of special characters as entities - * (should always be true, I think) - * - * @var boolean - * @access private - */ - var $charencoding = true; - /** - * the debug level for this instance - * - * @var integer - * @access private - */ - var $debugLevel; - - /** - * set schema version - * - * @var string - * @access public - */ - var $XMLSchemaVersion = 'http://www.w3.org/2001/XMLSchema'; - - /** - * charset encoding for outgoing messages - * - * @var string - * @access public - */ - var $soap_defencoding = 'ISO-8859-1'; - //var $soap_defencoding = 'UTF-8'; - - /** - * namespaces in an array of prefix => uri - * - * this is "seeded" by a set of constants, but it may be altered by code - * - * @var array - * @access public - */ - var $namespaces = array( - 'SOAP-ENV' => 'http://schemas.xmlsoap.org/soap/envelope/', - 'xsd' => 'http://www.w3.org/2001/XMLSchema', - 'xsi' => 'http://www.w3.org/2001/XMLSchema-instance', - 'SOAP-ENC' => 'http://schemas.xmlsoap.org/soap/encoding/' - ); - - /** - * namespaces used in the current context, e.g. during serialization - * - * @var array - * @access private - */ - var $usedNamespaces = array(); - - /** - * XML Schema types in an array of uri => (array of xml type => php type) - * is this legacy yet? - * no, this is used by the xmlschema class to verify type => namespace mappings. - * @var array - * @access public - */ - var $typemap = array( - 'http://www.w3.org/2001/XMLSchema' => array( - 'string'=>'string','boolean'=>'boolean','float'=>'double','double'=>'double','decimal'=>'double', - 'duration'=>'','dateTime'=>'string','time'=>'string','date'=>'string','gYearMonth'=>'', - 'gYear'=>'','gMonthDay'=>'','gDay'=>'','gMonth'=>'','hexBinary'=>'string','base64Binary'=>'string', - // abstract "any" types - 'anyType'=>'string','anySimpleType'=>'string', - // derived datatypes - 'normalizedString'=>'string','token'=>'string','language'=>'','NMTOKEN'=>'','NMTOKENS'=>'','Name'=>'','NCName'=>'','ID'=>'', - 'IDREF'=>'','IDREFS'=>'','ENTITY'=>'','ENTITIES'=>'','integer'=>'integer','nonPositiveInteger'=>'integer', - 'negativeInteger'=>'integer','long'=>'integer','int'=>'integer','short'=>'integer','byte'=>'integer','nonNegativeInteger'=>'integer', - 'unsignedLong'=>'','unsignedInt'=>'','unsignedShort'=>'','unsignedByte'=>'','positiveInteger'=>''), - 'http://www.w3.org/2000/10/XMLSchema' => array( - 'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double', - 'float'=>'double','dateTime'=>'string', - 'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'), - 'http://www.w3.org/1999/XMLSchema' => array( - 'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double', - 'float'=>'double','dateTime'=>'string', - 'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'), - 'http://soapinterop.org/xsd' => array('SOAPStruct'=>'struct'), - 'http://schemas.xmlsoap.org/soap/encoding/' => array('base64'=>'string','array'=>'array','Array'=>'array'), - 'http://xml.apache.org/xml-soap' => array('Map') - ); - - /** - * XML entities to convert - * - * @var array - * @access public - * @deprecated - * @see expandEntities - */ - var $xmlEntities = array('quot' => '"','amp' => '&', - 'lt' => '<','gt' => '>','apos' => "'"); - - /** - * constructor - * - * @access public - */ - function nusoap_base_colosa() { - $this->debugLevel = $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel; - } - - /** - * gets the global debug level, which applies to future instances - * - * @return integer Debug level 0-9, where 0 turns off - * @access public - */ - function getGlobalDebugLevel() { - return $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel; - } - - /** - * sets the global debug level, which applies to future instances - * - * @param int $level Debug level 0-9, where 0 turns off - * @access public - */ - function setGlobalDebugLevel($level) { - $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel = $level; - } - - /** - * gets the debug level for this instance - * - * @return int Debug level 0-9, where 0 turns off - * @access public - */ - function getDebugLevel() { - return $this->debugLevel; - } - - /** - * sets the debug level for this instance - * - * @param int $level Debug level 0-9, where 0 turns off - * @access public - */ - function setDebugLevel($level) { - $this->debugLevel = $level; - } - - /** - * adds debug data to the instance debug string with formatting - * - * @param string $string debug data - * @access private - */ - function debug($string){ - if ($this->debugLevel > 0) { - $this->appendDebug($this->getmicrotime().' '.get_class($this).": $string\n"); - } - } - - /** - * adds debug data to the instance debug string without formatting - * - * @param string $string debug data - * @access public - */ - function appendDebug($string){ - if ($this->debugLevel > 0) { - // it would be nice to use a memory stream here to use - // memory more efficiently - $this->debug_str .= $string; - } - } - - /** - * clears the current debug data for this instance - * - * @access public - */ - function clearDebug() { - // it would be nice to use a memory stream here to use - // memory more efficiently - $this->debug_str = ''; - } - - /** - * gets the current debug data for this instance - * - * @return debug data - * @access public - */ - function &getDebug() { - // it would be nice to use a memory stream here to use - // memory more efficiently - return $this->debug_str; - } - - /** - * gets the current debug data for this instance as an XML comment - * this may change the contents of the debug data - * - * @return debug data as an XML comment - * @access public - */ - function &getDebugAsXMLComment() { - // it would be nice to use a memory stream here to use - // memory more efficiently - while (strpos($this->debug_str, '--')) { - $this->debug_str = str_replace('--', '- -', $this->debug_str); - } - return ""; - } - - /** - * expands entities, e.g. changes '<' to '<'. - * - * @param string $val The string in which to expand entities. - * @access private - */ - function expandEntities($val) { - if ($this->charencoding) { - $val = str_replace('&', '&', $val); - $val = str_replace("'", ''', $val); - $val = str_replace('"', '"', $val); - $val = str_replace('<', '<', $val); - $val = str_replace('>', '>', $val); - } - return $val; - } - - /** - * returns error string if present - * - * @return mixed error string or false - * @access public - */ - function getError(){ - if($this->error_str != ''){ - return $this->error_str; - } - return false; - } - - /** - * sets error string - * - * @return boolean $string error string - * @access private - */ - function setError($str){ - $this->error_str = $str; - } - - /** - * detect if array is a simple array or a struct (associative array) - * - * @param mixed $val The PHP array - * @return string (arraySimple|arrayStruct) - * @access private - */ - function isArraySimpleOrStruct($val) { - $keyList = array_keys($val); - foreach ($keyList as $keyListValue) { - if (!is_int($keyListValue)) { - return 'arrayStruct'; - } - } - return 'arraySimple'; - } - - /** - * serializes PHP values in accordance w/ section 5. Type information is - * not serialized if $use == 'literal'. - * - * @param mixed $val The value to serialize - * @param string $name The name (local part) of the XML element - * @param string $type The XML schema type (local part) for the element - * @param string $name_ns The namespace for the name of the XML element - * @param string $type_ns The namespace for the type of the element - * @param array $attributes The attributes to serialize as name=>value pairs - * @param string $use The WSDL "use" (encoded|literal) - * @return string The serialized element, possibly with child elements - * @access public - */ - function serialize_val($val,$name=false,$type=false,$name_ns=false,$type_ns=false,$attributes=false,$use='encoded'){ - $this->debug("in serialize_val: name=$name, type=$type, name_ns=$name_ns, type_ns=$type_ns, use=$use"); - $this->appendDebug('value=' . $this->varDump($val)); - $this->appendDebug('attributes=' . $this->varDump($attributes)); - - if(is_object($val) && get_class($val) == 'soapval'){ - return $val->serialize($use); - } - // force valid name if necessary - if (is_numeric($name)) { - $name = '__numeric_' . $name; - } elseif (! $name) { - $name = 'noname'; - } - // if name has ns, add ns prefix to name - $xmlns = ''; - if($name_ns){ - $prefix = 'nu'.rand(1000,9999); - $name = $prefix.':'.$name; - $xmlns .= " xmlns:$prefix=\"$name_ns\""; - } - // if type is prefixed, create type prefix - if($type_ns != '' && $type_ns == $this->namespaces['xsd']){ - // need to fix this. shouldn't default to xsd if no ns specified - // w/o checking against typemap - $type_prefix = 'xsd'; - } elseif($type_ns){ - $type_prefix = 'ns'.rand(1000,9999); - $xmlns .= " xmlns:$type_prefix=\"$type_ns\""; - } - // serialize attributes if present - $atts = ''; - if($attributes){ - foreach($attributes as $k => $v){ - $atts .= " $k=\"".$this->expandEntities($v).'"'; - } - } - // serialize null value - if (is_null($val)) { - if ($use == 'literal') { - // TODO: depends on minOccurs - return "<$name$xmlns $atts/>"; - } else { - if (isset($type) && isset($type_prefix)) { - $type_str = " xsi:type=\"$type_prefix:$type\""; - } else { - $type_str = ''; - } - return "<$name$xmlns$type_str $atts xsi:nil=\"true\"/>"; - } - } - // serialize if an xsd built-in primitive type - if($type != '' && isset($this->typemap[$this->XMLSchemaVersion][$type])){ - if (is_bool($val)) { - if ($type == 'boolean') { - $val = $val ? 'true' : 'false'; - } elseif (! $val) { - $val = 0; - } - } else if (is_string($val)) { - $val = $this->expandEntities($val); - } - if ($use == 'literal') { - return "<$name$xmlns $atts>$val"; - } else { - return "<$name$xmlns $atts xsi:type=\"xsd:$type\">$val"; - } - } - // detect type and serialize - $xml = ''; - switch(true) { - case (is_bool($val) || $type == 'boolean'): - if ($type == 'boolean') { - $val = $val ? 'true' : 'false'; - } elseif (! $val) { - $val = 0; - } - if ($use == 'literal') { - $xml .= "<$name$xmlns $atts>$val"; - } else { - $xml .= "<$name$xmlns xsi:type=\"xsd:boolean\"$atts>$val"; - } - break; - case (is_int($val) || is_long($val) || $type == 'int'): - if ($use == 'literal') { - $xml .= "<$name$xmlns $atts>$val"; -// $xml .= "<$name$xmlns xsi:type=\"xsd:long\">$val"; - } else { - $xml .= "<$name$xmlns xsi:type=\"xsd:int\">$val"; - } - break; - case (is_float($val)|| is_double($val) || $type == 'float'): - if ($use == 'literal') { - $xml .= "<$name$xmlns $atts>$val"; - } else { - $xml .= "<$name$xmlns xsi:type=\"xsd:float\"$atts>$val"; - } - break; - case (is_string($val) || $type == 'string'): - $val = $this->expandEntities($val); - if ($use == 'literal') { - $xml .= "<$name$xmlns $atts>$val"; - } else { - $xml .= "<$name$xmlns xsi:type=\"xsd:string\"$atts>$val"; - } - break; - case is_object($val): - if (! $name) { - $name = get_class($val); - $this->debug("In serialize_val, used class name $name as element name"); - } else { - $this->debug("In serialize_val, do not override name $name for element name for class " . get_class($val)); - } - foreach(get_object_vars($val) as $k => $v){ - $pXml = isset($pXml) ? $pXml.$this->serialize_val($v,$k,false,false,false,false,$use) : $this->serialize_val($v,$k,false,false,false,false,$use); - } - $xml .= '<'.$name.'>'.$pXml.''; - break; - break; - case (is_array($val) || $type): - // detect if struct or array - $valueType = $this->isArraySimpleOrStruct($val); - if($valueType=='arraySimple' || ereg('^ArrayOf',$type)){ - $i = 0; - if(is_array($val) && count($val)> 0){ - foreach($val as $v){ - if(is_object($v) && get_class($v) == 'soapval'){ - $tt_ns = $v->type_ns; - $tt = $v->type; - } elseif (is_array($v)) { - $tt = $this->isArraySimpleOrStruct($v); - } else { - $tt = gettype($v); - } - $array_types[$tt] = 1; - // TODO: for literal, the name should be $name - $xml .= $this->serialize_val($v,'item',false,false,false,false,$use); - ++$i; - } - if(count($array_types) > 1){ - $array_typename = 'xsd:anyType'; - } elseif(isset($tt) && isset($this->typemap[$this->XMLSchemaVersion][$tt])) { - if ($tt == 'integer') { - $tt = 'int'; - } - $array_typename = 'xsd:'.$tt; - } elseif(isset($tt) && $tt == 'arraySimple'){ - $array_typename = 'SOAP-ENC:Array'; - } elseif(isset($tt) && $tt == 'arrayStruct'){ - $array_typename = 'unnamed_struct_use_soapval'; - } else { - // if type is prefixed, create type prefix - if ($tt_ns != '' && $tt_ns == $this->namespaces['xsd']){ - $array_typename = 'xsd:' . $tt; - } elseif ($tt_ns) { - $tt_prefix = 'ns' . rand(1000, 9999); - $array_typename = "$tt_prefix:$tt"; - $xmlns .= " xmlns:$tt_prefix=\"$tt_ns\""; - } else { - $array_typename = $tt; - } - } - $array_type = $i; - if ($use == 'literal') { - $type_str = ''; - } else if (isset($type) && isset($type_prefix)) { - $type_str = " xsi:type=\"$type_prefix:$type\""; - } else { - $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"".$array_typename."[$array_type]\""; - } - // empty array - } else { - if ($use == 'literal') { - $type_str = ''; - } else if (isset($type) && isset($type_prefix)) { - $type_str = " xsi:type=\"$type_prefix:$type\""; - } else { - $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"xsd:anyType[0]\""; - } - } - // TODO: for array in literal, there is no wrapper here - $xml = "<$name$xmlns$type_str$atts>".$xml.""; - } else { - // got a struct - if(isset($type) && isset($type_prefix)){ - $type_str = " xsi:type=\"$type_prefix:$type\""; - } else { - $type_str = ''; - } - if ($use == 'literal') { - $xml .= "<$name$xmlns $atts>"; - } else { - $xml .= "<$name$xmlns$type_str$atts>"; - } - foreach($val as $k => $v){ - // Apache Map - if ($type == 'Map' && $type_ns == 'http://xml.apache.org/xml-soap') { - $xml .= ''; - $xml .= $this->serialize_val($k,'key',false,false,false,false,$use); - $xml .= $this->serialize_val($v,'value',false,false,false,false,$use); - $xml .= ''; - } else { - $xml .= $this->serialize_val($v,$k,false,false,false,false,$use); - } - } - $xml .= ""; - } - break; - default: - $xml .= 'not detected, got '.gettype($val).' for '.$val; - break; - } - return $xml; - } - - /** - * serializes a message - * - * @param string $body the XML of the SOAP body - * @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers - * @param array $namespaces optional the namespaces used in generating the body and headers - * @param string $style optional (rpc|document) - * @param string $use optional (encoded|literal) - * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded) - * @return string the message - * @access public - */ - function serializeEnvelope($body,$headers=false,$namespaces=array(),$style='rpc',$use='encoded',$encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'){ - // TODO: add an option to automatically run utf8_encode on $body and $headers - // if $this->soap_defencoding is UTF-8. Not doing this automatically allows - // one to send arbitrary UTF-8 characters, not just characters that map to ISO-8859-1 - - $this->debug("In serializeEnvelope length=" . strlen($body) . " body (max 1000 characters)=" . substr($body, 0, 1000) . " style=$style use=$use encodingStyle=$encodingStyle"); - $this->debug("headers:"); - $this->appendDebug($this->varDump($headers)); - $this->debug("namespaces:"); - $this->appendDebug($this->varDump($namespaces)); - - // serialize namespaces - $ns_string = ''; - foreach(array_merge($this->namespaces,$namespaces) as $k => $v){ - $ns_string .= " xmlns:$k=\"$v\""; - } - if($encodingStyle) { - $ns_string = " SOAP-ENV:encodingStyle=\"$encodingStyle\"$ns_string"; - } - - // serialize headers - if($headers){ - if (is_array($headers)) { - $xml = ''; - foreach ($headers as $header) { - $xml .= $this->serialize_val($header, false, false, false, false, false, $use); - } - $headers = $xml; - $this->debug("In serializeEnvelope, serialzied array of headers to $headers"); - } - $headers = "".$headers.""; - } - // serialize envelope - return - 'soap_defencoding .'"?'.">". - '". - $headers. - "". - $body. - "". - ""; - } - - /** - * formats a string to be inserted into an HTML stream - * - * @param string $str The string to format - * @return string The formatted string - * @access public - * @deprecated - */ - function formatDump($str){ - $str = htmlspecialchars($str); - return nl2br($str); - } - - /** - * contracts (changes namespace to prefix) a qualified name - * - * @param string $qname qname - * @return string contracted qname - * @access private - */ - function contractQname($qname){ - // get element namespace - //$this->xdebug("Contract $qname"); - if (strrpos($qname, ':')) { - // get unqualified name - $name = substr($qname, strrpos($qname, ':') + 1); - // get ns - $ns = substr($qname, 0, strrpos($qname, ':')); - $p = $this->getPrefixFromNamespace($ns); - if ($p) { - return $p . ':' . $name; - } - return $qname; - } else { - return $qname; - } - } - - /** - * expands (changes prefix to namespace) a qualified name - * - * @param string $string qname - * @return string expanded qname - * @access private - */ - function expandQname($qname){ - // get element prefix - if(strpos($qname,':') && !ereg('^http://',$qname)){ - // get unqualified name - $name = substr(strstr($qname,':'),1); - // get ns prefix - $prefix = substr($qname,0,strpos($qname,':')); - if(isset($this->namespaces[$prefix])){ - return $this->namespaces[$prefix].':'.$name; - } else { - return $qname; - } - } else { - return $qname; - } - } - - /** - * returns the local part of a prefixed string - * returns the original string, if not prefixed - * - * @param string $str The prefixed string - * @return string The local part - * @access public - */ - function getLocalPart($str){ - if($sstr = strrchr($str,':')){ - // get unqualified name - return substr( $sstr, 1 ); - } else { - return $str; - } - } - - /** - * returns the prefix part of a prefixed string - * returns false, if not prefixed - * - * @param string $str The prefixed string - * @return mixed The prefix or false if there is no prefix - * @access public - */ - function getPrefix($str){ - if($pos = strrpos($str,':')){ - // get prefix - return substr($str,0,$pos); - } - return false; - } - - /** - * pass it a prefix, it returns a namespace - * - * @param string $prefix The prefix - * @return mixed The namespace, false if no namespace has the specified prefix - * @access public - */ - function getNamespaceFromPrefix($prefix){ - if (isset($this->namespaces[$prefix])) { - return $this->namespaces[$prefix]; - } - //$this->setError("No namespace registered for prefix '$prefix'"); - return false; - } - - /** - * returns the prefix for a given namespace (or prefix) - * or false if no prefixes registered for the given namespace - * - * @param string $ns The namespace - * @return mixed The prefix, false if the namespace has no prefixes - * @access public - */ - function getPrefixFromNamespace($ns) { - foreach ($this->namespaces as $p => $n) { - if ($ns == $n || $ns == $p) { - $this->usedNamespaces[$p] = $n; - return $p; - } - } - return false; - } - - /** - * returns the time in ODBC canonical form with microseconds - * - * @return string The time in ODBC canonical form with microseconds - * @access public - */ - function getmicrotime() { - if (function_exists('gettimeofday')) { - $tod = gettimeofday(); - $sec = $tod['sec']; - $usec = $tod['usec']; - } else { - $sec = time(); - $usec = 0; - } - return strftime('%Y-%m-%d %H:%M:%S', $sec) . '.' . sprintf('%06d', $usec); - } - - /** - * Returns a string with the output of var_dump - * - * @param mixed $data The variable to var_dump - * @return string The output of var_dump - * @access public - */ - function varDump($data) { - ob_start(); - - 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(); - $data = $filter->xssFilterHard($data); - - var_dump($data); - $ret_val = ob_get_contents(); - ob_end_clean(); - return $ret_val; - } -} - -// XML Schema Datatype Helper Functions - -//xsd:dateTime helpers - -/** -* convert unix timestamp to ISO 8601 compliant date string -* -* @param string $timestamp Unix time stamp -* @access public -*/ -function timestamp_to_iso8601($timestamp,$utc=true){ - $datestr = date('Y-m-d\TH:i:sO',$timestamp); - if($utc){ - $eregStr = - '([0-9]{4})-'. // centuries & years CCYY- - '([0-9]{2})-'. // months MM- - '([0-9]{2})'. // days DD - 'T'. // separator T - '([0-9]{2}):'. // hours hh: - '([0-9]{2}):'. // minutes mm: - '([0-9]{2})(\.[0-9]*)?'. // seconds ss.ss... - '(Z|[+\-][0-9]{2}:?[0-9]{2})?'; // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's - - if(ereg($eregStr,$datestr,$regs)){ - return sprintf('%04d-%02d-%02dT%02d:%02d:%02dZ',$regs[1],$regs[2],$regs[3],$regs[4],$regs[5],$regs[6]); - } - return false; - } else { - return $datestr; - } -} - -/** -* convert ISO 8601 compliant date string to unix timestamp -* -* @param string $datestr ISO 8601 compliant date string -* @access public -*/ -function iso8601_to_timestamp($datestr){ - $eregStr = - '([0-9]{4})-'. // centuries & years CCYY- - '([0-9]{2})-'. // months MM- - '([0-9]{2})'. // days DD - 'T'. // separator T - '([0-9]{2}):'. // hours hh: - '([0-9]{2}):'. // minutes mm: - '([0-9]{2})(\.[0-9]+)?'. // seconds ss.ss... - '(Z|[+\-][0-9]{2}:?[0-9]{2})?'; // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's - if(ereg($eregStr,$datestr,$regs)){ - // not utc - if($regs[8] != 'Z'){ - $op = substr($regs[8],0,1); - $h = substr($regs[8],1,2); - $m = substr($regs[8],strlen($regs[8])-2,2); - if($op == '-'){ - $regs[4] = $regs[4] + $h; - $regs[5] = $regs[5] + $m; - } elseif($op == '+'){ - $regs[4] = $regs[4] - $h; - $regs[5] = $regs[5] - $m; - } - } - return strtotime("$regs[1]-$regs[2]-$regs[3] $regs[4]:$regs[5]:$regs[6]Z"); - } else { - return false; - } -} - -/** -* sleeps some number of microseconds -* -* @param string $usec the number of microseconds to sleep -* @access public -* @deprecated -*/ -function usleepWindows($usec) -{ - $start = gettimeofday(); - - do - { - $stop = gettimeofday(); - $timePassed = 1000000 * ($stop['sec'] - $start['sec']) - + $stop['usec'] - $start['usec']; - } - while ($timePassed < $usec); -} - -?> -* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class soap_fault_colosa extends nusoap_base_colosa { - /** - * The fault code (client|server) - * @var string - * @access private - */ - var $faultcode; - /** - * The fault actor - * @var string - * @access private - */ - var $faultactor; - /** - * The fault string, a description of the fault - * @var string - * @access private - */ - var $faultstring; - /** - * The fault detail, typically a string or array of string - * @var mixed - * @access private - */ - var $faultdetail; - - /** - * constructor - * - * @param string $faultcode (client | server) - * @param string $faultactor only used when msg routed between multiple actors - * @param string $faultstring human readable error message - * @param mixed $faultdetail detail, typically a string or array of string - */ - function soap_fault_colosa($faultcode,$faultactor='',$faultstring='',$faultdetail=''){ - parent::nusoap_base_colosa(); - $this->faultcode = $faultcode; - $this->faultactor = $faultactor; - $this->faultstring = $faultstring; - $this->faultdetail = $faultdetail; - } - - /** - * serialize a fault - * - * @return string The serialization of the fault instance. - * @access public - */ - function serialize(){ - $ns_string = ''; - foreach($this->namespaces as $k => $v){ - $ns_string .= "\n xmlns:$k=\"$v\""; - } - $return_msg = - 'soap_defencoding.'"?>'. - '\n". - ''. - ''. - $this->serialize_val($this->faultcode, 'faultcode'). - $this->serialize_val($this->faultactor, 'faultactor'). - $this->serialize_val($this->faultstring, 'faultstring'). - $this->serialize_val($this->faultdetail, 'detail'). - ''. - ''. - ''; - return $return_msg; - } -} - - - -?> -* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class XMLSchema extends nusoap_base_colosa { - - // files - var $schema = ''; - var $xml = ''; - // namespaces - var $enclosingNamespaces; - // schema info - var $schemaInfo = array(); - var $schemaTargetNamespace = ''; - // types, elements, attributes defined by the schema - var $attributes = array(); - var $complexTypes = array(); - var $complexTypeStack = array(); - var $currentComplexType = null; - var $elements = array(); - var $elementStack = array(); - var $currentElement = null; - var $simpleTypes = array(); - var $simpleTypeStack = array(); - var $currentSimpleType = null; - // imports - var $imports = array(); - // parser vars - var $parser; - var $position = 0; - var $depth = 0; - var $depth_array = array(); - var $message = array(); - var $defaultNamespace = array(); - - /** - * constructor - * - * @param string $schema schema document URI - * @param string $xml xml document URI - * @param string $namespaces namespaces defined in enclosing XML - * @access public - */ - function XMLSchema($schema='',$xml='',$namespaces=array()){ - parent::nusoap_base_colosa(); - $this->debug('xmlschema class instantiated, inside constructor'); - // files - $this->schema = $schema; - $this->xml = $xml; - - // namespaces - $this->enclosingNamespaces = $namespaces; - $this->namespaces = array_merge($this->namespaces, $namespaces); - - // parse schema file - if($schema != ''){ - $this->debug('initial schema file: '.$schema); - $this->parseFile($schema, 'schema'); - } - - // parse xml file - if($xml != ''){ - $this->debug('initial xml file: '.$xml); - $this->parseFile($xml, 'xml'); - } - - } - - /** - * parse an XML file - * - * @param string $xml, path/URL to XML file - * @param string $type, (schema | xml) - * @return boolean - * @access public - */ - function parseFile($xml,$type){ - // parse xml file - if($xml != ""){ - $xmlStr = @join("",@file($xml)); - if($xmlStr == ""){ - $msg = 'Error reading XML from '.$xml; - $this->setError($msg); - $this->debug($msg); - return false; - } else { - $this->debug("parsing $xml"); - $this->parseString($xmlStr,$type); - $this->debug("done parsing $xml"); - return true; - } - } - return false; - } - - /** - * parse an XML string - * - * @param string $xml path or URL - * @param string $type, (schema|xml) - * @access private - */ - function parseString($xml,$type){ - // parse xml string - if($xml != ""){ - - // Create an XML parser. - $this->parser = xml_parser_create(); - // Set the options for parsing the XML data. - xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); - - // Set the object for the parser. - xml_set_object($this->parser, $this); - - // Set the element handlers for the parser. - if($type == "schema"){ - xml_set_element_handler($this->parser, 'schemaStartElement','schemaEndElement'); - xml_set_character_data_handler($this->parser,'schemaCharacterData'); - } elseif($type == "xml"){ - xml_set_element_handler($this->parser, 'xmlStartElement','xmlEndElement'); - xml_set_character_data_handler($this->parser,'xmlCharacterData'); - } - - // Parse the XML file. - if(!xml_parse($this->parser,$xml,true)){ - // Display an error message. - $errstr = sprintf('XML error parsing XML schema on line %d: %s', - xml_get_current_line_number($this->parser), - xml_error_string(xml_get_error_code($this->parser)) - ); - $this->debug($errstr); - $this->debug("XML payload:\n" . $xml); - $this->setError($errstr); - } - - xml_parser_free($this->parser); - } else{ - $this->debug('no xml passed to parseString()!!'); - $this->setError('no xml passed to parseString()!!'); - } - } - - /** - * start-element handler - * - * @param string $parser XML parser object - * @param string $name element name - * @param string $attrs associative array of attributes - * @access private - */ - function schemaStartElement($parser, $name, $attrs) { - - // position in the total number of elements, starting from 0 - $pos = $this->position++; - $depth = $this->depth++; - // set self as current value for this depth - $this->depth_array[$depth] = $pos; - $this->message[$pos] = array('cdata' => ''); - if ($depth > 0) { - $this->defaultNamespace[$pos] = $this->defaultNamespace[$this->depth_array[$depth - 1]]; - } else { - $this->defaultNamespace[$pos] = false; - } - - // get element prefix - if($prefix = $this->getPrefix($name)){ - // get unqualified name - $name = $this->getLocalPart($name); - } else { - $prefix = ''; - } - - // loop thru attributes, expanding, and registering namespace declarations - if(count($attrs) > 0){ - foreach($attrs as $k => $v){ - // if ns declarations, add to class level array of valid namespaces - if(ereg("^xmlns",$k)){ - //$this->xdebug("$k: $v"); - //$this->xdebug('ns_prefix: '.$this->getPrefix($k)); - if($ns_prefix = substr(strrchr($k,':'),1)){ - //$this->xdebug("Add namespace[$ns_prefix] = $v"); - $this->namespaces[$ns_prefix] = $v; - } else { - $this->defaultNamespace[$pos] = $v; - if (! $this->getPrefixFromNamespace($v)) { - $this->namespaces['ns'.(count($this->namespaces)+1)] = $v; - } - } - if($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema'){ - $this->XMLSchemaVersion = $v; - $this->namespaces['xsi'] = $v.'-instance'; - } - } - } - foreach($attrs as $k => $v){ - // expand each attribute - $k = strpos($k,':') ? $this->expandQname($k) : $k; - $v = strpos($v,':') ? $this->expandQname($v) : $v; - $eAttrs[$k] = $v; - } - $attrs = $eAttrs; - } else { - $attrs = array(); - } - // find status, register data - switch($name){ - case 'all': // (optional) compositor content for a complexType - case 'choice': - case 'group': - case 'sequence': - //$this->xdebug("compositor $name for currentComplexType: $this->currentComplexType and currentElement: $this->currentElement"); - $this->complexTypes[$this->currentComplexType]['compositor'] = $name; - //if($name == 'all' || $name == 'sequence'){ - // $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct'; - //} - break; - case 'attribute': // complexType attribute - //$this->xdebug("parsing attribute $attrs[name] $attrs[ref] of value: ".$attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']); - $this->xdebug("parsing attribute:"); - $this->appendDebug($this->varDump($attrs)); - if (!isset($attrs['form'])) { - $attrs['form'] = $this->schemaInfo['attributeFormDefault']; - } - if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) { - $v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; - if (!strpos($v, ':')) { - // no namespace in arrayType attribute value... - if ($this->defaultNamespace[$pos]) { - // ...so use the default - $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'] = $this->defaultNamespace[$pos] . ':' . $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; - } - } - } - if(isset($attrs['name'])){ - $this->attributes[$attrs['name']] = $attrs; - $aname = $attrs['name']; - } elseif(isset($attrs['ref']) && $attrs['ref'] == 'http://schemas.xmlsoap.org/soap/encoding/:arrayType'){ - if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) { - $aname = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; - } else { - $aname = ''; - } - } elseif(isset($attrs['ref'])){ - $aname = $attrs['ref']; - $this->attributes[$attrs['ref']] = $attrs; - } - - if($this->currentComplexType){ // This should *always* be - $this->complexTypes[$this->currentComplexType]['attrs'][$aname] = $attrs; - } - // arrayType attribute - if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']) || $this->getLocalPart($aname) == 'arrayType'){ - $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; - $prefix = $this->getPrefix($aname); - if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])){ - $v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; - } else { - $v = ''; - } - if(strpos($v,'[,]')){ - $this->complexTypes[$this->currentComplexType]['multidimensional'] = true; - } - $v = substr($v,0,strpos($v,'[')); // clip the [] - if(!strpos($v,':') && isset($this->typemap[$this->XMLSchemaVersion][$v])){ - $v = $this->XMLSchemaVersion.':'.$v; - } - $this->complexTypes[$this->currentComplexType]['arrayType'] = $v; - } - break; - case 'complexContent': // (optional) content for a complexType - break; - case 'complexType': - array_push($this->complexTypeStack, $this->currentComplexType); - if(isset($attrs['name'])){ - $this->xdebug('processing named complexType '.$attrs['name']); - //$this->currentElement = false; - $this->currentComplexType = $attrs['name']; - $this->complexTypes[$this->currentComplexType] = $attrs; - $this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType'; - // This is for constructs like - // - // - // - // - // - if(isset($attrs['base']) && ereg(':Array$',$attrs['base'])){ - $this->xdebug('complexType is unusual array'); - $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; - } else { - $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct'; - } - }else{ - $this->xdebug('processing unnamed complexType for element '.$this->currentElement); - $this->currentComplexType = $this->currentElement . '_ContainedType'; - //$this->currentElement = false; - $this->complexTypes[$this->currentComplexType] = $attrs; - $this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType'; - // This is for constructs like - // - // - // - // - // - if(isset($attrs['base']) && ereg(':Array$',$attrs['base'])){ - $this->xdebug('complexType is unusual array'); - $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; - } else { - $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct'; - } - } - break; - case 'element': - array_push($this->elementStack, $this->currentElement); - // elements defined as part of a complex type should - // not really be added to $this->elements, but for some - // reason, they are - if (!isset($attrs['form'])) { - $attrs['form'] = $this->schemaInfo['elementFormDefault']; - } - if(isset($attrs['type'])){ - $this->xdebug("processing typed element ".$attrs['name']." of type ".$attrs['type']); - if (! $this->getPrefix($attrs['type'])) { - if ($this->defaultNamespace[$pos]) { - $attrs['type'] = $this->defaultNamespace[$pos] . ':' . $attrs['type']; - $this->xdebug('used default namespace to make type ' . $attrs['type']); - } - } - // This is for constructs like - // - // - // - // - // - if ($this->currentComplexType && $this->complexTypes[$this->currentComplexType]['phpType'] == 'array') { - $this->xdebug('arrayType for unusual array is ' . $attrs['type']); - $this->complexTypes[$this->currentComplexType]['arrayType'] = $attrs['type']; - } - $this->currentElement = $attrs['name']; - $this->elements[ $attrs['name'] ] = $attrs; - $this->elements[ $attrs['name'] ]['typeClass'] = 'element'; - $ename = $attrs['name']; - } elseif(isset($attrs['ref'])){ - $this->xdebug("processing element as ref to ".$attrs['ref']); - $this->currentElement = "ref to ".$attrs['ref']; - $ename = $this->getLocalPart($attrs['ref']); - } else { - $this->xdebug("processing untyped element ".$attrs['name']); - $this->currentElement = $attrs['name']; - $this->elements[ $attrs['name'] ] = $attrs; - $this->elements[ $attrs['name'] ]['typeClass'] = 'element'; - $attrs['type'] = $this->schemaTargetNamespace . ':' . $attrs['name'] . '_ContainedType'; - $this->elements[ $attrs['name'] ]['type'] = $attrs['type']; - $ename = $attrs['name']; - } - if(isset($ename) && $this->currentComplexType){ - $this->complexTypes[$this->currentComplexType]['elements'][$ename] = $attrs; - } - break; - case 'enumeration': // restriction value list member - $this->xdebug('enumeration ' . $attrs['value']); - if ($this->currentSimpleType) { - $this->simpleTypes[$this->currentSimpleType]['enumeration'][] = $attrs['value']; - } elseif ($this->currentComplexType) { - $this->complexTypes[$this->currentComplexType]['enumeration'][] = $attrs['value']; - } - break; - case 'extension': // simpleContent or complexContent type extension - $this->xdebug('extension ' . $attrs['base']); - if ($this->currentComplexType) { - $this->complexTypes[$this->currentComplexType]['extensionBase'] = $attrs['base']; - } - break; - case 'import': - if (isset($attrs['schemaLocation'])) { - //$this->xdebug('import namespace ' . $attrs['namespace'] . ' from ' . $attrs['schemaLocation']); - $this->imports[$attrs['namespace']][] = array('location' => $attrs['schemaLocation'], 'loaded' => false); - } else { - //$this->xdebug('import namespace ' . $attrs['namespace']); - $this->imports[$attrs['namespace']][] = array('location' => '', 'loaded' => true); - if (! $this->getPrefixFromNamespace($attrs['namespace'])) { - $this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace']; - } - } - break; - case 'list': // simpleType value list - break; - case 'restriction': // simpleType, simpleContent or complexContent value restriction - $this->xdebug('restriction ' . $attrs['base']); - if($this->currentSimpleType){ - $this->simpleTypes[$this->currentSimpleType]['type'] = $attrs['base']; - } elseif($this->currentComplexType){ - $this->complexTypes[$this->currentComplexType]['restrictionBase'] = $attrs['base']; - if(strstr($attrs['base'],':') == ':Array'){ - $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; - } - } - break; - case 'schema': - $this->schemaInfo = $attrs; - $this->schemaInfo['schemaVersion'] = $this->getNamespaceFromPrefix($prefix); - if (isset($attrs['targetNamespace'])) { - $this->schemaTargetNamespace = $attrs['targetNamespace']; - } - if (!isset($attrs['elementFormDefault'])) { - $this->schemaInfo['elementFormDefault'] = 'unqualified'; - } - if (!isset($attrs['attributeFormDefault'])) { - $this->schemaInfo['attributeFormDefault'] = 'unqualified'; - } - break; - case 'simpleContent': // (optional) content for a complexType - break; - case 'simpleType': - array_push($this->simpleTypeStack, $this->currentSimpleType); - if(isset($attrs['name'])){ - $this->xdebug("processing simpleType for name " . $attrs['name']); - $this->currentSimpleType = $attrs['name']; - $this->simpleTypes[ $attrs['name'] ] = $attrs; - $this->simpleTypes[ $attrs['name'] ]['typeClass'] = 'simpleType'; - $this->simpleTypes[ $attrs['name'] ]['phpType'] = 'scalar'; - } else { - $this->xdebug('processing unnamed simpleType for element '.$this->currentElement); - $this->currentSimpleType = $this->currentElement . '_ContainedType'; - //$this->currentElement = false; - $this->simpleTypes[$this->currentSimpleType] = $attrs; - $this->simpleTypes[$this->currentSimpleType]['phpType'] = 'scalar'; - } - break; - case 'union': // simpleType type list - break; - default: - //$this->xdebug("do not have anything to do for element $name"); - } - } - - /** - * end-element handler - * - * @param string $parser XML parser object - * @param string $name element name - * @access private - */ - function schemaEndElement($parser, $name) { - // bring depth down a notch - $this->depth--; - // position of current element is equal to the last value left in depth_array for my depth - if(isset($this->depth_array[$this->depth])){ - $pos = $this->depth_array[$this->depth]; - } - // get element prefix - if ($prefix = $this->getPrefix($name)){ - // get unqualified name - $name = $this->getLocalPart($name); - } else { - $prefix = ''; - } - // move on... - if($name == 'complexType'){ - $this->xdebug('done processing complexType ' . ($this->currentComplexType ? $this->currentComplexType : '(unknown)')); - $this->currentComplexType = array_pop($this->complexTypeStack); - //$this->currentElement = false; - } - if($name == 'element'){ - $this->xdebug('done processing element ' . ($this->currentElement ? $this->currentElement : '(unknown)')); - $this->currentElement = array_pop($this->elementStack); - } - if($name == 'simpleType'){ - $this->xdebug('done processing simpleType ' . ($this->currentSimpleType ? $this->currentSimpleType : '(unknown)')); - $this->currentSimpleType = array_pop($this->simpleTypeStack); - } - } - - /** - * element content handler - * - * @param string $parser XML parser object - * @param string $data element content - * @access private - */ - function schemaCharacterData($parser, $data){ - $pos = $this->depth_array[$this->depth - 1]; - $this->message[$pos]['cdata'] .= $data; - } - - /** - * serialize the schema - * - * @access public - */ - function serializeSchema(){ - - $schemaPrefix = $this->getPrefixFromNamespace($this->XMLSchemaVersion); - $xml = ''; - // imports - if (sizeof($this->imports) > 0) { - foreach($this->imports as $ns => $list) { - foreach ($list as $ii) { - if ($ii['location'] != '') { - $xml .= " <$schemaPrefix:import location=\"" . $ii['location'] . '" namespace="' . $ns . "\" />\n"; - } else { - $xml .= " <$schemaPrefix:import namespace=\"" . $ns . "\" />\n"; - } - } - } - } - // complex types - foreach($this->complexTypes as $typeName => $attrs){ - $contentStr = ''; - // serialize child elements - if(isset($attrs['elements']) && (count($attrs['elements']) > 0)){ - foreach($attrs['elements'] as $element => $eParts){ - if(isset($eParts['ref'])){ - $contentStr .= " <$schemaPrefix:element ref=\"$element\"/>\n"; - } else { - $contentStr .= " <$schemaPrefix:element name=\"$element\" type=\"" . $this->contractQName($eParts['type']) . "\""; - foreach ($eParts as $aName => $aValue) { - // handle, e.g., abstract, default, form, minOccurs, maxOccurs, nillable - if ($aName != 'name' && $aName != 'type') { - $contentStr .= " $aName=\"$aValue\""; - } - } - $contentStr .= "/>\n"; - } - } - // compositor wraps elements - if (isset($attrs['compositor']) && ($attrs['compositor'] != '')) { - $contentStr = " <$schemaPrefix:$attrs[compositor]>\n".$contentStr." \n"; - } - } - // attributes - if(isset($attrs['attrs']) && (count($attrs['attrs']) >= 1)){ - foreach($attrs['attrs'] as $attr => $aParts){ - $contentStr .= " <$schemaPrefix:attribute"; - foreach ($aParts as $a => $v) { - if ($a == 'ref' || $a == 'type') { - $contentStr .= " $a=\"".$this->contractQName($v).'"'; - } elseif ($a == 'http://schemas.xmlsoap.org/wsdl/:arrayType') { - $this->usedNamespaces['wsdl'] = $this->namespaces['wsdl']; - $contentStr .= ' wsdl:arrayType="'.$this->contractQName($v).'"'; - } else { - $contentStr .= " $a=\"$v\""; - } - } - $contentStr .= "/>\n"; - } - } - // if restriction - if (isset($attrs['restrictionBase']) && $attrs['restrictionBase'] != ''){ - $contentStr = " <$schemaPrefix:restriction base=\"".$this->contractQName($attrs['restrictionBase'])."\">\n".$contentStr." \n"; - // complex or simple content - if ((isset($attrs['elements']) && count($attrs['elements']) > 0) || (isset($attrs['attrs']) && count($attrs['attrs']) > 0)){ - $contentStr = " <$schemaPrefix:complexContent>\n".$contentStr." \n"; - } - } - // finalize complex type - if($contentStr != ''){ - $contentStr = " <$schemaPrefix:complexType name=\"$typeName\">\n".$contentStr." \n"; - } else { - $contentStr = " <$schemaPrefix:complexType name=\"$typeName\"/>\n"; - } - $xml .= $contentStr; - } - // simple types - if(isset($this->simpleTypes) && count($this->simpleTypes) > 0){ - foreach($this->simpleTypes as $typeName => $eParts){ - $xml .= " <$schemaPrefix:simpleType name=\"$typeName\">\n <$schemaPrefix:restriction base=\"".$this->contractQName($eParts['type'])."\"/>\n"; - if (isset($eParts['enumeration'])) { - foreach ($eParts['enumeration'] as $e) { - $xml .= " <$schemaPrefix:enumeration value=\"$e\"/>\n"; - } - } - $xml .= " "; - } - } - // elements - if(isset($this->elements) && count($this->elements) > 0){ - foreach($this->elements as $element => $eParts){ - $xml .= " <$schemaPrefix:element name=\"$element\" type=\"".$this->contractQName($eParts['type'])."\"/>\n"; - } - } - // attributes - if(isset($this->attributes) && count($this->attributes) > 0){ - foreach($this->attributes as $attr => $aParts){ - $xml .= " <$schemaPrefix:attribute name=\"$attr\" type=\"".$this->contractQName($aParts['type'])."\"\n/>"; - } - } - // finish 'er up - $el = "<$schemaPrefix:schema targetNamespace=\"$this->schemaTargetNamespace\"\n"; - foreach (array_diff($this->usedNamespaces, $this->enclosingNamespaces) as $nsp => $ns) { - $el .= " xmlns:$nsp=\"$ns\"\n"; - } - $xml = $el . ">\n".$xml."\n"; - return $xml; - } - - /** - * adds debug data to the clas level debug string - * - * @param string $string debug data - * @access private - */ - function xdebug($string){ - $this->debug('<' . $this->schemaTargetNamespace . '> '.$string); - } - - /** - * get the PHP type of a user defined type in the schema - * PHP type is kind of a misnomer since it actually returns 'struct' for assoc. arrays - * returns false if no type exists, or not w/ the given namespace - * else returns a string that is either a native php type, or 'struct' - * - * @param string $type, name of defined type - * @param string $ns, namespace of type - * @return mixed - * @access public - * @deprecated - */ - function getPHPType($type,$ns){ - if(isset($this->typemap[$ns][$type])){ - //print "found type '$type' and ns $ns in typemap
"; - return $this->typemap[$ns][$type]; - } elseif(isset($this->complexTypes[$type])){ - //print "getting type '$type' and ns $ns from complexTypes array
"; - return $this->complexTypes[$type]['phpType']; - } - return false; - } - - /** - * returns an associative array of information about a given type - * returns false if no type exists by the given name - * - * For a complexType typeDef = array( - * 'restrictionBase' => '', - * 'phpType' => '', - * 'compositor' => '(sequence|all)', - * 'elements' => array(), // refs to elements array - * 'attrs' => array() // refs to attributes array - * ... and so on (see addComplexType) - * ) - * - * For simpleType or element, the array has different keys. - * - * @param string - * @return mixed - * @access public - * @see addComplexType - * @see addSimpleType - * @see addElement - */ - function getTypeDef($type){ - //$this->debug("in getTypeDef for type $type"); - if(isset($this->complexTypes[$type])){ - $this->xdebug("in getTypeDef, found complexType $type"); - return $this->complexTypes[$type]; - } elseif(isset($this->simpleTypes[$type])){ - $this->xdebug("in getTypeDef, found simpleType $type"); - if (!isset($this->simpleTypes[$type]['phpType'])) { - // get info for type to tack onto the simple type - // TODO: can this ever really apply (i.e. what is a simpleType really?) - $uqType = substr($this->simpleTypes[$type]['type'], strrpos($this->simpleTypes[$type]['type'], ':') + 1); - $ns = substr($this->simpleTypes[$type]['type'], 0, strrpos($this->simpleTypes[$type]['type'], ':')); - $etype = $this->getTypeDef($uqType); - if ($etype) { - $this->xdebug("in getTypeDef, found type for simpleType $type:"); - $this->xdebug($this->varDump($etype)); - if (isset($etype['phpType'])) { - $this->simpleTypes[$type]['phpType'] = $etype['phpType']; - } - if (isset($etype['elements'])) { - $this->simpleTypes[$type]['elements'] = $etype['elements']; - } - } - } - return $this->simpleTypes[$type]; - } elseif(isset($this->elements[$type])){ - $this->xdebug("in getTypeDef, found element $type"); - if (!isset($this->elements[$type]['phpType'])) { - // get info for type to tack onto the element - $uqType = substr($this->elements[$type]['type'], strrpos($this->elements[$type]['type'], ':') + 1); - $ns = substr($this->elements[$type]['type'], 0, strrpos($this->elements[$type]['type'], ':')); - $etype = $this->getTypeDef($uqType); - if ($etype) { - $this->xdebug("in getTypeDef, found type for element $type:"); - $this->xdebug($this->varDump($etype)); - if (isset($etype['phpType'])) { - $this->elements[$type]['phpType'] = $etype['phpType']; - } - if (isset($etype['elements'])) { - $this->elements[$type]['elements'] = $etype['elements']; - } - } elseif ($ns == 'http://www.w3.org/2001/XMLSchema') { - $this->xdebug("in getTypeDef, element $type is an XSD type"); - $this->elements[$type]['phpType'] = 'scalar'; - } - } - return $this->elements[$type]; - } elseif(isset($this->attributes[$type])){ - $this->xdebug("in getTypeDef, found attribute $type"); - return $this->attributes[$type]; - } elseif (ereg('_ContainedType$', $type)) { - $this->xdebug("in getTypeDef, have an untyped element $type"); - $typeDef['typeClass'] = 'simpleType'; - $typeDef['phpType'] = 'scalar'; - $typeDef['type'] = 'http://www.w3.org/2001/XMLSchema:string'; - return $typeDef; - } - $this->xdebug("in getTypeDef, did not find $type"); - return false; - } - - /** - * returns a sample serialization of a given type, or false if no type by the given name - * - * @param string $type, name of type - * @return mixed - * @access public - * @deprecated - */ - function serializeTypeDef($type){ - //print "in sTD() for type $type
"; - if($typeDef = $this->getTypeDef($type)){ - $str .= '<'.$type; - if(is_array($typeDef['attrs'])){ - foreach($attrs as $attName => $data){ - $str .= " $attName=\"{type = ".$data['type']."}\""; - } - } - $str .= " xmlns=\"".$this->schema['targetNamespace']."\""; - if(count($typeDef['elements']) > 0){ - $str .= ">"; - foreach($typeDef['elements'] as $element => $eData){ - $str .= $this->serializeTypeDef($element); - } - $str .= ""; - } elseif($typeDef['typeClass'] == 'element') { - $str .= ">"; - } else { - $str .= "/>"; - } - return $str; - } - return false; - } - - /** - * returns HTML form elements that allow a user - * to enter values for creating an instance of the given type. - * - * @param string $name, name for type instance - * @param string $type, name of type - * @return string - * @access public - * @deprecated - */ - function typeToForm($name,$type){ - // get typedef - if($typeDef = $this->getTypeDef($type)){ - // if struct - if($typeDef['phpType'] == 'struct'){ - $buffer .= ''; - foreach($typeDef['elements'] as $child => $childDef){ - $buffer .= " - - "; - } - $buffer .= '
$childDef[name] (type: ".$this->getLocalPart($childDef['type'])."):
'; - // if array - } elseif($typeDef['phpType'] == 'array'){ - $buffer .= ''; - for($i=0;$i < 3; $i++){ - $buffer .= " - - "; - } - $buffer .= '
array item (type: $typeDef[arrayType]):
'; - // if scalar - } else { - $buffer .= ""; - } - } else { - $buffer .= ""; - } - return $buffer; - } - - /** - * adds a complex type to the schema - * - * example: array - * - * addType( - * 'ArrayOfstring', - * 'complexType', - * 'array', - * '', - * 'SOAP-ENC:Array', - * array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'string[]'), - * 'xsd:string' - * ); - * - * example: PHP associative array ( SOAP Struct ) - * - * addType( - * 'SOAPStruct', - * 'complexType', - * 'struct', - * 'all', - * array('myVar'=> array('name'=>'myVar','type'=>'string') - * ); - * - * @param name - * @param typeClass (complexType|simpleType|attribute) - * @param phpType: currently supported are array and struct (php assoc array) - * @param compositor (all|sequence|choice) - * @param restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) - * @param elements = array ( name = array(name=>'',type=>'') ) - * @param attrs = array( - * array( - * 'ref' => "http://schemas.xmlsoap.org/soap/encoding/:arrayType", - * "http://schemas.xmlsoap.org/wsdl/:arrayType" => "string[]" - * ) - * ) - * @param arrayType: namespace:name (http://www.w3.org/2001/XMLSchema:string) - * @access public - * @see getTypeDef - */ - function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType=''){ - $this->complexTypes[$name] = array( - 'name' => $name, - 'typeClass' => $typeClass, - 'phpType' => $phpType, - 'compositor'=> $compositor, - 'restrictionBase' => $restrictionBase, - 'elements' => $elements, - 'attrs' => $attrs, - 'arrayType' => $arrayType - ); - - $this->xdebug("addComplexType $name:"); - $this->appendDebug($this->varDump($this->complexTypes[$name])); - } - - /** - * adds a simple type to the schema - * - * @param string $name - * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) - * @param string $typeClass (should always be simpleType) - * @param string $phpType (should always be scalar) - * @param array $enumeration array of values - * @access public - * @see xmlschema - * @see getTypeDef - */ - function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) { - $this->simpleTypes[$name] = array( - 'name' => $name, - 'typeClass' => $typeClass, - 'phpType' => $phpType, - 'type' => $restrictionBase, - 'enumeration' => $enumeration - ); - - $this->xdebug("addSimpleType $name:"); - $this->appendDebug($this->varDump($this->simpleTypes[$name])); - } - - /** - * adds an element to the schema - * - * @param array $attrs attributes that must include name and type - * @see xmlschema - * @access public - */ - function addElement($attrs) { - if (! $this->getPrefix($attrs['type'])) { - $attrs['type'] = $this->schemaTargetNamespace . ':' . $attrs['type']; - } - $this->elements[ $attrs['name'] ] = $attrs; - $this->elements[ $attrs['name'] ]['typeClass'] = 'element'; - - $this->xdebug("addElement " . $attrs['name']); - $this->appendDebug($this->varDump($this->elements[ $attrs['name'] ])); - } -} - - - -?> -* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class soapval extends nusoap_base_colosa { - /** - * The XML element name - * - * @var string - * @access private - */ - var $name; - /** - * The XML type name (string or false) - * - * @var mixed - * @access private - */ - var $type; - /** - * The PHP value - * - * @var mixed - * @access private - */ - var $value; - /** - * The XML element namespace (string or false) - * - * @var mixed - * @access private - */ - var $element_ns; - /** - * The XML type namespace (string or false) - * - * @var mixed - * @access private - */ - var $type_ns; - /** - * The XML element attributes (array or false) - * - * @var mixed - * @access private - */ - var $attributes; - - /** - * constructor - * - * @param string $name optional name - * @param mixed $type optional type name - * @param mixed $value optional value - * @param mixed $element_ns optional namespace of value - * @param mixed $type_ns optional namespace of type - * @param mixed $attributes associative array of attributes to add to element serialization - * @access public - */ - function soapval($name='soapval',$type=false,$value=-1,$element_ns=false,$type_ns=false,$attributes=false) { - parent::nusoap_base_colosa(); - $this->name = $name; - $this->type = $type; - $this->value = $value; - $this->element_ns = $element_ns; - $this->type_ns = $type_ns; - $this->attributes = $attributes; - } - - /** - * return serialized value - * - * @param string $use The WSDL use value (encoded|literal) - * @return string XML data - * @access public - */ - function serialize($use='encoded') { - return $this->serialize_val($this->value,$this->name,$this->type,$this->element_ns,$this->type_ns,$this->attributes,$use); - } - - /** - * decodes a soapval object into a PHP native type - * - * @return mixed - * @access public - */ - function decode(){ - return $this->value; - } -} - - - -?> -* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class soap_transport_http extends nusoap_base_colosa { - - var $url = ''; - var $uri = ''; - var $digest_uri = ''; - var $scheme = ''; - var $host = ''; - var $port = ''; - var $path = ''; - var $request_method = 'POST'; - var $protocol_version = '1.0'; - var $encoding = ''; - var $outgoing_headers = array(); - var $incoming_headers = array(); - var $incoming_cookies = array(); - var $outgoing_payload = ''; - var $incoming_payload = ''; - var $useSOAPAction = true; - var $persistentConnection = false; - var $ch = false; // cURL handle - var $username = ''; - var $password = ''; - var $authtype = ''; - var $digestRequest = array(); - var $certRequest = array(); // keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional) - // cainfofile: certificate authority file, e.g. '$pathToPemFiles/rootca.pem' - // sslcertfile: SSL certificate file, e.g. '$pathToPemFiles/mycert.pem' - // sslkeyfile: SSL key file, e.g. '$pathToPemFiles/mykey.pem' - // passphrase: SSL key password/passphrase - // verifypeer: default is 1 - // verifyhost: default is 1 - - /** - * constructor - */ - function soap_transport_http($url){ - parent::nusoap_base_colosa(); - $this->setURL($url); - ereg('\$Revisio' . 'n: ([^ ]+)', $this->revision, $rev); - $this->outgoing_headers['User-Agent'] = $this->title.'/'.$this->version.' ('.$rev[1].')'; - $this->debug('set User-Agent: ' . $this->outgoing_headers['User-Agent']); - } - - function setURL($url) { - $this->url = $url; - - $u = parse_url($url); - foreach($u as $k => $v){ - $this->debug("$k = $v"); - $this->$k = $v; - } - - // add any GET params to path - if(isset($u['query']) && $u['query'] != ''){ - $this->path .= '?' . $u['query']; - } - - // set default port - if(!isset($u['port'])){ - if($u['scheme'] == 'https'){ - $this->port = 443; - } else { - $this->port = 80; - } - } - - $this->uri = $this->path; - $this->digest_uri = $this->uri; - - // build headers - if (!isset($u['port'])) { - $this->outgoing_headers['Host'] = $this->host; - } else { - $this->outgoing_headers['Host'] = $this->host.':'.$this->port; - } - $this->debug('set Host: ' . $this->outgoing_headers['Host']); - - if (isset($u['user']) && $u['user'] != '') { - $this->setCredentials(urldecode($u['user']), isset($u['pass']) ? urldecode($u['pass']) : ''); - } - } - - function connect($connection_timeout=0,$response_timeout=30){ - // For PHP 4.3 with OpenSSL, change https scheme to ssl, then treat like - // "regular" socket. - // TODO: disabled for now because OpenSSL must be *compiled* in (not just - // loaded), and until PHP5 stream_get_wrappers is not available. -// if ($this->scheme == 'https') { -// if (version_compare(phpversion(), '4.3.0') >= 0) { -// if (extension_loaded('openssl')) { -// $this->scheme = 'ssl'; -// $this->debug('Using SSL over OpenSSL'); -// } -// } -// } - $this->debug("connect connection_timeout $connection_timeout, response_timeout $response_timeout, scheme $this->scheme, host $this->host, port $this->port"); - if ($this->scheme == 'http' || $this->scheme == 'ssl') { - // use persistent connection - if($this->persistentConnection && isset($this->fp) && is_resource($this->fp)){ - if (!feof($this->fp)) { - $this->debug('Re-use persistent connection'); - return true; - } - fclose($this->fp); - $this->debug('Closed persistent connection at EOF'); - } - - // munge host if using OpenSSL - if ($this->scheme == 'ssl') { - $host = 'ssl://' . $this->host; - } else { - $host = $this->host; - } - $this->debug('calling fsockopen with host ' . $host . ' connection_timeout ' . $connection_timeout); - - // open socket - if($connection_timeout > 0){ - $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str, $connection_timeout); - } else { - $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str); - } - - // test pointer - if(!$this->fp) { - $msg = 'Couldn\'t open socket connection to server ' . $this->url; - if ($this->errno) { - $msg .= ', Error ('.$this->errno.'): '.$this->error_str; - } else { - $msg .= ' prior to connect(). This is often a problem looking up the host name.'; - } - $this->debug($msg); - $this->setError($msg); - return false; - } - - // set response timeout - $this->debug('set response timeout to ' . $response_timeout); - socket_set_timeout( $this->fp, $response_timeout); - - $this->debug('socket connected'); - return true; - } else if ($this->scheme == 'https') { - if (!extension_loaded('curl')) { - $this->setError('CURL Extension, or OpenSSL extension w/ PHP version >= 4.3 is required for HTTPS'); - return false; - } - $this->debug('connect using https'); - // init CURL - $this->ch = curl_init(); - // set url - $hostURL = ($this->port != '') ? "https://$this->host:$this->port" : "https://$this->host"; - // add path - $hostURL .= $this->path; - curl_setopt($this->ch, CURLOPT_URL, $hostURL); - // follow location headers (re-directs) - curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 1); - // ask for headers in the response output - curl_setopt($this->ch, CURLOPT_HEADER, 1); - // ask for the response output as the return value - curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1); - // encode - // We manage this ourselves through headers and encoding -// if(function_exists('gzuncompress')){ -// curl_setopt($this->ch, CURLOPT_ENCODING, 'deflate'); -// } - // persistent connection - if ($this->persistentConnection) { - // The way we send data, we cannot use persistent connections, since - // there will be some "junk" at the end of our request. - //curl_setopt($this->ch, CURL_HTTP_VERSION_1_1, true); - $this->persistentConnection = false; - $this->outgoing_headers['Connection'] = 'close'; - $this->debug('set Connection: ' . $this->outgoing_headers['Connection']); - } - // set timeout - if ($connection_timeout != 0) { - curl_setopt($this->ch, CURLOPT_TIMEOUT, $connection_timeout); - } - // TODO: cURL has added a connection timeout separate from the response timeout - //if ($connection_timeout != 0) { - // curl_setopt($this->ch, CURLOPT_CONNECTIONTIMEOUT, $connection_timeout); - //} - //if ($response_timeout != 0) { - // curl_setopt($this->ch, CURLOPT_TIMEOUT, $response_timeout); - //} - - // recent versions of cURL turn on peer/host checking by default, - // while PHP binaries are not compiled with a default location for the - // CA cert bundle, so disable peer/host checking. -//curl_setopt($this->ch, CURLOPT_CAINFO, 'f:\php-4.3.2-win32\extensions\curl-ca-bundle.crt'); - curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0); - curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 0); - - // support client certificates (thanks Tobias Boes, Doug Anarino, Eryan Ariobowo) - if ($this->authtype == 'certificate') { - if (isset($this->certRequest['cainfofile'])) { - curl_setopt($this->ch, CURLOPT_CAINFO, $this->certRequest['cainfofile']); - } - if (isset($this->certRequest['verifypeer'])) { - curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, $this->certRequest['verifypeer']); - } else { - curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 1); - } - if (isset($this->certRequest['verifyhost'])) { - curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, $this->certRequest['verifyhost']); - } else { - curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 1); - } - if (isset($this->certRequest['sslcertfile'])) { - curl_setopt($this->ch, CURLOPT_SSLCERT, $this->certRequest['sslcertfile']); - } - if (isset($this->certRequest['sslkeyfile'])) { - curl_setopt($this->ch, CURLOPT_SSLKEY, $this->certRequest['sslkeyfile']); - } - if (isset($this->certRequest['passphrase'])) { - curl_setopt($this->ch, CURLOPT_SSLKEYPASSWD , $this->certRequest['passphrase']); - } - } - $this->debug('cURL connection set up'); - return true; - } else { - $this->setError('Unknown scheme ' . $this->scheme); - $this->debug('Unknown scheme ' . $this->scheme); - return false; - } - } - - /** - * send the SOAP message via HTTP - * - * @param string $data message data - * @param integer $timeout set connection timeout in seconds - * @param integer $response_timeout set response timeout in seconds - * @param array $cookies cookies to send - * @return string data - * @access public - */ - function send($data, $timeout=0, $response_timeout=30, $cookies=NULL) { - - $this->debug('entered send() with data of length: '.strlen($data)); - - $this->tryagain = true; - $tries = 0; - while ($this->tryagain) { - $this->tryagain = false; - if ($tries++ < 2) { - // make connnection - if (!$this->connect($timeout, $response_timeout)){ - return false; - } - - // send request - if (!$this->sendRequest($data, $cookies)){ - return false; - } - - // get response - $respdata = $this->getResponse(); - } else { - $this->setError('Too many tries to get an OK response'); - } - } - $this->debug('end of send()'); - return $respdata; - } - - - /** - * send the SOAP message via HTTPS 1.0 using CURL - * - * @param string $msg message data - * @param integer $timeout set connection timeout in seconds - * @param integer $response_timeout set response timeout in seconds - * @param array $cookies cookies to send - * @return string data - * @access public - */ - function sendHTTPS($data, $timeout=0, $response_timeout=30, $cookies) { - return $this->send($data, $timeout, $response_timeout, $cookies); - } - - /** - * if authenticating, set user credentials here - * - * @param string $username - * @param string $password - * @param string $authtype (basic, digest, certificate) - * @param array $digestRequest (keys must be nonce, nc, realm, qop) - * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs) - * @access public - */ - function setCredentials($username, $password, $authtype = 'basic', $digestRequest = array(), $certRequest = array()) { - $this->debug("Set credentials for authtype $authtype"); - // cf. RFC 2617 - if ($authtype == 'basic') { - $this->outgoing_headers['Authorization'] = 'Basic '.base64_encode(str_replace(':','',$username).':'.$password); - } elseif ($authtype == 'digest') { - if (isset($digestRequest['nonce'])) { - $digestRequest['nc'] = isset($digestRequest['nc']) ? $digestRequest['nc']++ : 1; - - // calculate the Digest hashes (calculate code based on digest implementation found at: http://www.rassoc.com/gregr/weblog/stories/2002/07/09/webServicesSecurityHttpDigestAuthenticationWithoutActiveDirectory.html) - - // A1 = unq(username-value) ":" unq(realm-value) ":" passwd - $A1 = $username. ':' . (isset($digestRequest['realm']) ? $digestRequest['realm'] : '') . ':' . $password; - - // H(A1) = MD5(A1) - $HA1 = $this->encryptOld($A1); - - // A2 = Method ":" digest-uri-value - $A2 = 'POST:' . $this->digest_uri; - - // H(A2) - $HA2 = $this->encryptOld($A2); - - // KD(secret, data) = H(concat(secret, ":", data)) - // if qop == auth: - // request-digest = <"> < KD ( H(A1), unq(nonce-value) - // ":" nc-value - // ":" unq(cnonce-value) - // ":" unq(qop-value) - // ":" H(A2) - // ) <"> - // if qop is missing, - // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > <"> - - $unhashedDigest = ''; - $nonce = isset($digestRequest['nonce']) ? $digestRequest['nonce'] : ''; - $cnonce = $nonce; - if ($digestRequest['qop'] != '') { - $unhashedDigest = $HA1 . ':' . $nonce . ':' . sprintf("%08d", $digestRequest['nc']) . ':' . $cnonce . ':' . $digestRequest['qop'] . ':' . $HA2; - } else { - $unhashedDigest = $HA1 . ':' . $nonce . ':' . $HA2; - } - - $hashedDigest = $this->encryptOld($unhashedDigest); - - $this->outgoing_headers['Authorization'] = 'Digest username="' . $username . '", realm="' . $digestRequest['realm'] . '", nonce="' . $nonce . '", uri="' . $this->digest_uri . '", cnonce="' . $cnonce . '", nc=' . sprintf("%08x", $digestRequest['nc']) . ', qop="' . $digestRequest['qop'] . '", response="' . $hashedDigest . '"'; - } - } elseif ($authtype == 'certificate') { - $this->certRequest = $certRequest; - } - $this->username = $username; - $this->password = $password; - $this->authtype = $authtype; - $this->digestRequest = $digestRequest; - - if (isset($this->outgoing_headers['Authorization'])) { - $this->debug('set Authorization: ' . substr($this->outgoing_headers['Authorization'], 0, 12) . '...'); - } else { - $this->debug('Authorization header not set'); - } - } - - /** - * set the soapaction value - * - * @param string $soapaction - * @access public - */ - function setSOAPAction($soapaction) { - $this->outgoing_headers['SOAPAction'] = '"' . $soapaction . '"'; - $this->debug('set SOAPAction: ' . $this->outgoing_headers['SOAPAction']); - } - - /** - * use http encoding - * - * @param string $enc encoding style. supported values: gzip, deflate, or both - * @access public - */ - function setEncoding($enc='gzip, deflate') { - if (function_exists('gzdeflate')) { - $this->protocol_version = '1.1'; - $this->outgoing_headers['Accept-Encoding'] = $enc; - $this->debug('set Accept-Encoding: ' . $this->outgoing_headers['Accept-Encoding']); - if (!isset($this->outgoing_headers['Connection'])) { - $this->outgoing_headers['Connection'] = 'close'; - $this->persistentConnection = false; - $this->debug('set Connection: ' . $this->outgoing_headers['Connection']); - } - set_magic_quotes_runtime(0); - // deprecated - $this->encoding = $enc; - } - } - - /** - * set proxy info here - * - * @param string $proxyhost - * @param string $proxyport - * @param string $proxyusername - * @param string $proxypassword - * @access public - */ - function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '') { - $this->uri = $this->url; - $this->host = $proxyhost; - $this->port = $proxyport; - if ($proxyusername != '' && $proxypassword != '') { - $this->outgoing_headers['Proxy-Authorization'] = ' Basic '.base64_encode($proxyusername.':'.$proxypassword); - $this->debug('set Proxy-Authorization: ' . $this->outgoing_headers['Proxy-Authorization']); - } - } - - /** - * decode a string that is encoded w/ "chunked' transfer encoding - * as defined in RFC2068 19.4.6 - * - * @param string $buffer - * @param string $lb - * @returns string - * @access public - * @deprecated - */ - function decodeChunked($buffer, $lb){ - // length := 0 - $length = 0; - $new = ''; - - // read chunk-size, chunk-extension (if any) and CRLF - // get the position of the linebreak - $chunkend = strpos($buffer, $lb); - if ($chunkend == FALSE) { - $this->debug('no linebreak found in decodeChunked'); - return $new; - } - $temp = substr($buffer,0,$chunkend); - $chunk_size = hexdec( trim($temp) ); - $chunkstart = $chunkend + strlen($lb); - // while (chunk-size > 0) { - while ($chunk_size > 0) { - $this->debug("chunkstart: $chunkstart chunk_size: $chunk_size"); - $chunkend = strpos( $buffer, $lb, $chunkstart + $chunk_size); - - // Just in case we got a broken connection - if ($chunkend == FALSE) { - $chunk = substr($buffer,$chunkstart); - // append chunk-data to entity-body - $new .= $chunk; - $length += strlen($chunk); - break; - } - - // read chunk-data and CRLF - $chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart); - // append chunk-data to entity-body - $new .= $chunk; - // length := length + chunk-size - $length += strlen($chunk); - // read chunk-size and CRLF - $chunkstart = $chunkend + strlen($lb); - - $chunkend = strpos($buffer, $lb, $chunkstart) + strlen($lb); - if ($chunkend == FALSE) { - break; //Just in case we got a broken connection - } - $temp = substr($buffer,$chunkstart,$chunkend-$chunkstart); - $chunk_size = hexdec( trim($temp) ); - $chunkstart = $chunkend; - } - return $new; - } - - /* - * Writes payload, including HTTP headers, to $this->outgoing_payload. - */ - function buildPayload($data, $cookie_str = '') { - // add content-length header - $this->outgoing_headers['Content-Length'] = strlen($data); - $this->debug('set Content-Length: ' . $this->outgoing_headers['Content-Length']); - - // start building outgoing payload: - $req = "$this->request_method $this->uri HTTP/$this->protocol_version"; - $this->debug("HTTP request: $req"); - $this->outgoing_payload = "$req\r\n"; - - // loop thru headers, serializing - foreach($this->outgoing_headers as $k => $v){ - $hdr = $k.': '.$v; - $this->debug("HTTP header: $hdr"); - $this->outgoing_payload .= "$hdr\r\n"; - } - - // add any cookies - if ($cookie_str != '') { - $hdr = 'Cookie: '.$cookie_str; - $this->debug("HTTP header: $hdr"); - $this->outgoing_payload .= "$hdr\r\n"; - } - - // header/body separator - $this->outgoing_payload .= "\r\n"; - - // add data - $this->outgoing_payload .= $data; - } - - function sendRequest($data, $cookies = NULL) { - // build cookie string - $cookie_str = $this->getCookiesForRequest($cookies, (($this->scheme == 'ssl') || ($this->scheme == 'https'))); - - // build payload - $this->buildPayload($data, $cookie_str); - - if ($this->scheme == 'http' || $this->scheme == 'ssl') { - // send payload - if(!fputs($this->fp, $this->outgoing_payload, strlen($this->outgoing_payload))) { - $this->setError('couldn\'t write message data to socket'); - $this->debug('couldn\'t write message data to socket'); - return false; - } - $this->debug('wrote data to socket, length = ' . strlen($this->outgoing_payload)); - return true; - } else if ($this->scheme == 'https') { - // set payload - // TODO: cURL does say this should only be the verb, and in fact it - // turns out that the URI and HTTP version are appended to this, which - // some servers refuse to work with - //curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $this->outgoing_payload); - foreach($this->outgoing_headers as $k => $v){ - $curl_headers[] = "$k: $v"; - } - if ($cookie_str != '') { - $curl_headers[] = 'Cookie: ' . $cookie_str; - } - curl_setopt($this->ch, CURLOPT_HTTPHEADER, $curl_headers); - if ($this->request_method == "POST") { - curl_setopt($this->ch, CURLOPT_POST, 1); - curl_setopt($this->ch, CURLOPT_POSTFIELDS, $data); - } else { - } - $this->debug('set cURL payload'); - return true; - } - } - - function getResponse(){ - $this->incoming_payload = ''; - - if ($this->scheme == 'http' || $this->scheme == 'ssl') { - // loop until headers have been retrieved - $data = ''; - while (!isset($lb)){ - - // We might EOF during header read. - if(feof($this->fp)) { - $this->incoming_payload = $data; - $this->debug('found no headers before EOF after length ' . strlen($data)); - $this->debug("received before EOF:\n" . $data); - $this->setError('server failed to send headers'); - return false; - } - - $tmp = fgets($this->fp, 256); - $tmplen = strlen($tmp); - $this->debug("read line of $tmplen bytes: " . trim($tmp)); - - if ($tmplen == 0) { - $this->incoming_payload = $data; - $this->debug('socket read of headers timed out after length ' . strlen($data)); - $this->debug("read before timeout: " . $data); - $this->setError('socket read of headers timed out'); - return false; - } - - $data .= $tmp; - $pos = strpos($data,"\r\n\r\n"); - if($pos > 1){ - $lb = "\r\n"; - } else { - $pos = strpos($data,"\n\n"); - if($pos > 1){ - $lb = "\n"; - } - } - // remove 100 header - if(isset($lb) && ereg('^HTTP/1.1 100',$data)){ - unset($lb); - $data = ''; - }// - } - // store header data - $this->incoming_payload .= $data; - $this->debug('found end of headers after length ' . strlen($data)); - // process headers - $header_data = trim(substr($data,0,$pos)); - $header_array = explode($lb,$header_data); - $this->incoming_headers = array(); - $this->incoming_cookies = array(); - foreach($header_array as $header_line){ - $arr = explode(':',$header_line, 2); - if(count($arr) > 1){ - $header_name = strtolower(trim($arr[0])); - $this->incoming_headers[$header_name] = trim($arr[1]); - if ($header_name == 'set-cookie') { - // TODO: allow multiple cookies from parseCookie - $cookie = $this->parseCookie(trim($arr[1])); - if ($cookie) { - $this->incoming_cookies[] = $cookie; - $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']); - } else { - $this->debug('did not find cookie in ' . trim($arr[1])); - } - } - } else if (isset($header_name)) { - // append continuation line to previous header - $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line; - } - } - - // loop until msg has been received - if (isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked') { - $content_length = 2147483647; // ignore any content-length header - $chunked = true; - $this->debug("want to read chunked content"); - } elseif (isset($this->incoming_headers['content-length'])) { - $content_length = $this->incoming_headers['content-length']; - $chunked = false; - $this->debug("want to read content of length $content_length"); - } else { - $content_length = 2147483647; - $chunked = false; - $this->debug("want to read content to EOF"); - } - $data = ''; - do { - if ($chunked) { - $tmp = fgets($this->fp, 256); - $tmplen = strlen($tmp); - $this->debug("read chunk line of $tmplen bytes"); - if ($tmplen == 0) { - $this->incoming_payload = $data; - $this->debug('socket read of chunk length timed out after length ' . strlen($data)); - $this->debug("read before timeout:\n" . $data); - $this->setError('socket read of chunk length timed out'); - return false; - } - $content_length = hexdec(trim($tmp)); - $this->debug("chunk length $content_length"); - } - $strlen = 0; - while (($strlen < $content_length) && (!feof($this->fp))) { - $readlen = min(8192, $content_length - $strlen); - $tmp = fread($this->fp, $readlen); - $tmplen = strlen($tmp); - $this->debug("read buffer of $tmplen bytes"); - if (($tmplen == 0) && (!feof($this->fp))) { - $this->incoming_payload = $data; - $this->debug('socket read of body timed out after length ' . strlen($data)); - $this->debug("read before timeout:\n" . $data); - $this->setError('socket read of body timed out'); - return false; - } - $strlen += $tmplen; - $data .= $tmp; - } - if ($chunked && ($content_length > 0)) { - $tmp = fgets($this->fp, 256); - $tmplen = strlen($tmp); - $this->debug("read chunk terminator of $tmplen bytes"); - if ($tmplen == 0) { - $this->incoming_payload = $data; - $this->debug('socket read of chunk terminator timed out after length ' . strlen($data)); - $this->debug("read before timeout:\n" . $data); - $this->setError('socket read of chunk terminator timed out'); - return false; - } - } - } while ($chunked && ($content_length > 0) && (!feof($this->fp))); - if (feof($this->fp)) { - $this->debug('read to EOF'); - } - $this->debug('read body of length ' . strlen($data)); - $this->incoming_payload .= $data; - $this->debug('received a total of '.strlen($this->incoming_payload).' bytes of data from server'); - - // close filepointer - if( - (isset($this->incoming_headers['connection']) && strtolower($this->incoming_headers['connection']) == 'close') || - (! $this->persistentConnection) || feof($this->fp)){ - fclose($this->fp); - $this->fp = false; - $this->debug('closed socket'); - } - - // connection was closed unexpectedly - if($this->incoming_payload == ''){ - $this->setError('no response from server'); - return false; - } - - // decode transfer-encoding -// if(isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked'){ -// if(!$data = $this->decodeChunked($data, $lb)){ -// $this->setError('Decoding of chunked data failed'); -// return false; -// } - //print "
\nde-chunked:\n---------------\n$data\n\n---------------\n
"; - // set decoded payload -// $this->incoming_payload = $header_data.$lb.$lb.$data; -// } - - } else if ($this->scheme == 'https') { - // send and receive - $this->debug('send and receive with cURL'); - $this->incoming_payload = curl_exec($this->ch); - $data = $this->incoming_payload; - - $cErr = curl_error($this->ch); - if ($cErr != '') { - $err = 'cURL ERROR: '.curl_errno($this->ch).': '.$cErr.'
'; - // TODO: there is a PHP bug that can cause this to SEGV for CURLINFO_CONTENT_TYPE - foreach(curl_getinfo($this->ch) as $k => $v){ - $err .= "$k: $v
"; - } - $this->debug($err); - $this->setError($err); - curl_close($this->ch); - return false; - } else { - //echo '
';
-			//var_dump(curl_getinfo($this->ch));
-			//echo '
'; - } - // close curl - $this->debug('No cURL error, closing cURL'); - curl_close($this->ch); - - // remove 100 header(s) - while (ereg('^HTTP/1.1 100',$data)) { - if ($pos = strpos($data,"\r\n\r\n")) { - $data = ltrim(substr($data,$pos)); - } elseif($pos = strpos($data,"\n\n") ) { - $data = ltrim(substr($data,$pos)); - } - } - - // separate content from HTTP headers - if ($pos = strpos($data,"\r\n\r\n")) { - $lb = "\r\n"; - } elseif( $pos = strpos($data,"\n\n")) { - $lb = "\n"; - } else { - $this->debug('no proper separation of headers and document'); - $this->setError('no proper separation of headers and document'); - return false; - } - $header_data = trim(substr($data,0,$pos)); - $header_array = explode($lb,$header_data); - $data = ltrim(substr($data,$pos)); - $this->debug('found proper separation of headers and document'); - $this->debug('cleaned data, stringlen: '.strlen($data)); - // clean headers - foreach ($header_array as $header_line) { - $arr = explode(':',$header_line,2); - if(count($arr) > 1){ - $header_name = strtolower(trim($arr[0])); - $this->incoming_headers[$header_name] = trim($arr[1]); - if ($header_name == 'set-cookie') { - // TODO: allow multiple cookies from parseCookie - $cookie = $this->parseCookie(trim($arr[1])); - if ($cookie) { - $this->incoming_cookies[] = $cookie; - $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']); - } else { - $this->debug('did not find cookie in ' . trim($arr[1])); - } - } - } else if (isset($header_name)) { - // append continuation line to previous header - $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line; - } - } - } - - $arr = explode(' ', $header_array[0], 3); - $http_version = $arr[0]; - $http_status = intval($arr[1]); - $http_reason = count($arr) > 2 ? $arr[2] : ''; - - // see if we need to resend the request with http digest authentication - if (isset($this->incoming_headers['location']) && $http_status == 301) { - $this->debug("Got 301 $http_reason with Location: " . $this->incoming_headers['location']); - $this->setURL($this->incoming_headers['location']); - $this->tryagain = true; - return false; - } - - // see if we need to resend the request with http digest authentication - if (isset($this->incoming_headers['www-authenticate']) && $http_status == 401) { - $this->debug("Got 401 $http_reason with WWW-Authenticate: " . $this->incoming_headers['www-authenticate']); - if (strstr($this->incoming_headers['www-authenticate'], "Digest ")) { - $this->debug('Server wants digest authentication'); - // remove "Digest " from our elements - $digestString = str_replace('Digest ', '', $this->incoming_headers['www-authenticate']); - - // parse elements into array - $digestElements = explode(',', $digestString); - foreach ($digestElements as $val) { - $tempElement = explode('=', trim($val), 2); - $digestRequest[$tempElement[0]] = str_replace("\"", '', $tempElement[1]); - } - - // should have (at least) qop, realm, nonce - if (isset($digestRequest['nonce'])) { - $this->setCredentials($this->username, $this->password, 'digest', $digestRequest); - $this->tryagain = true; - return false; - } - } - $this->debug('HTTP authentication failed'); - $this->setError('HTTP authentication failed'); - return false; - } - - if ( - ($http_status >= 300 && $http_status <= 307) || - ($http_status >= 400 && $http_status <= 417) || - ($http_status >= 501 && $http_status <= 505) - ) { - $this->setError("Unsupported HTTP response status $http_status $http_reason (soapclient->response has contents of the response)"); - return false; - } - - // decode content-encoding - if(isset($this->incoming_headers['content-encoding']) && $this->incoming_headers['content-encoding'] != ''){ - if(strtolower($this->incoming_headers['content-encoding']) == 'deflate' || strtolower($this->incoming_headers['content-encoding']) == 'gzip'){ - // if decoding works, use it. else assume data wasn't gzencoded - if(function_exists('gzinflate')){ - //$timer->setMarker('starting decoding of gzip/deflated content'); - // IIS 5 requires gzinflate instead of gzuncompress (similar to IE 5 and gzdeflate v. gzcompress) - // this means there are no Zlib headers, although there should be - $this->debug('The gzinflate function exists'); - $datalen = strlen($data); - if ($this->incoming_headers['content-encoding'] == 'deflate') { - if ($degzdata = @gzinflate($data)) { - $data = $degzdata; - $this->debug('The payload has been inflated to ' . strlen($data) . ' bytes'); - if (strlen($data) < $datalen) { - // test for the case that the payload has been compressed twice - $this->debug('The inflated payload is smaller than the gzipped one; try again'); - if ($degzdata = @gzinflate($data)) { - $data = $degzdata; - $this->debug('The payload has been inflated again to ' . strlen($data) . ' bytes'); - } - } - } else { - $this->debug('Error using gzinflate to inflate the payload'); - $this->setError('Error using gzinflate to inflate the payload'); - } - } elseif ($this->incoming_headers['content-encoding'] == 'gzip') { - if ($degzdata = @gzinflate(substr($data, 10))) { // do our best - $data = $degzdata; - $this->debug('The payload has been un-gzipped to ' . strlen($data) . ' bytes'); - if (strlen($data) < $datalen) { - // test for the case that the payload has been compressed twice - $this->debug('The un-gzipped payload is smaller than the gzipped one; try again'); - if ($degzdata = @gzinflate(substr($data, 10))) { - $data = $degzdata; - $this->debug('The payload has been un-gzipped again to ' . strlen($data) . ' bytes'); - } - } - } else { - $this->debug('Error using gzinflate to un-gzip the payload'); - $this->setError('Error using gzinflate to un-gzip the payload'); - } - } - //$timer->setMarker('finished decoding of gzip/deflated content'); - //print "\nde-inflated:\n---------------\n$data\n-------------\n"; - // set decoded payload - $this->incoming_payload = $header_data.$lb.$lb.$data; - } else { - $this->debug('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.'); - $this->setError('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.'); - } - } else { - $this->debug('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']); - $this->setError('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']); - } - } else { - $this->debug('No Content-Encoding header'); - } - - if(strlen($data) == 0){ - $this->debug('no data after headers!'); - $this->setError('no data present after HTTP headers'); - return false; - } - - return $data; - } - - function setContentType($type, $charset = false) { - $this->outgoing_headers['Content-Type'] = $type . ($charset ? '; charset=' . $charset : ''); - $this->debug('set Content-Type: ' . $this->outgoing_headers['Content-Type']); - } - - function usePersistentConnection(){ - if (isset($this->outgoing_headers['Accept-Encoding'])) { - return false; - } - $this->protocol_version = '1.1'; - $this->persistentConnection = true; - $this->outgoing_headers['Connection'] = 'Keep-Alive'; - $this->debug('set Connection: ' . $this->outgoing_headers['Connection']); - return true; - } - - /** - * parse an incoming Cookie into it's parts - * - * @param string $cookie_str content of cookie - * @return array with data of that cookie - * @access private - */ - /* - * TODO: allow a Set-Cookie string to be parsed into multiple cookies - */ - function parseCookie($cookie_str) { - $cookie_str = str_replace('; ', ';', $cookie_str) . ';'; - $data = explode(';', $cookie_str); - $value_str = $data[0]; - - $cookie_param = 'domain='; - $start = strpos($cookie_str, $cookie_param); - if ($start > 0) { - $domain = substr($cookie_str, $start + strlen($cookie_param)); - $domain = substr($domain, 0, strpos($domain, ';')); - } else { - $domain = ''; - } - - $cookie_param = 'expires='; - $start = strpos($cookie_str, $cookie_param); - if ($start > 0) { - $expires = substr($cookie_str, $start + strlen($cookie_param)); - $expires = substr($expires, 0, strpos($expires, ';')); - } else { - $expires = ''; - } - - $cookie_param = 'path='; - $start = strpos($cookie_str, $cookie_param); - if ( $start > 0 ) { - $path = substr($cookie_str, $start + strlen($cookie_param)); - $path = substr($path, 0, strpos($path, ';')); - } else { - $path = '/'; - } - - $cookie_param = ';secure;'; - if (strpos($cookie_str, $cookie_param) !== FALSE) { - $secure = true; - } else { - $secure = false; - } - - $sep_pos = strpos($value_str, '='); - - if ($sep_pos) { - $name = substr($value_str, 0, $sep_pos); - $value = substr($value_str, $sep_pos + 1); - $cookie= array( 'name' => $name, - 'value' => $value, - 'domain' => $domain, - 'path' => $path, - 'expires' => $expires, - 'secure' => $secure - ); - return $cookie; - } - return false; - } - - /** - * sort out cookies for the current request - * - * @param array $cookies array with all cookies - * @param boolean $secure is the send-content secure or not? - * @return string for Cookie-HTTP-Header - * @access private - */ - function getCookiesForRequest($cookies, $secure=false) { - $cookie_str = ''; - if ((! is_null($cookies)) && (is_array($cookies))) { - foreach ($cookies as $cookie) { - if (! is_array($cookie)) { - continue; - } - $this->debug("check cookie for validity: ".$cookie['name'].'='.$cookie['value']); - if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) { - if (strtotime($cookie['expires']) <= time()) { - $this->debug('cookie has expired'); - continue; - } - } - if ((isset($cookie['domain'])) && (! empty($cookie['domain']))) { - $domain = preg_quote($cookie['domain']); - if (! preg_match("'.*$domain$'i", $this->host)) { - $this->debug('cookie has different domain'); - continue; - } - } - if ((isset($cookie['path'])) && (! empty($cookie['path']))) { - $path = preg_quote($cookie['path']); - if (! preg_match("'^$path.*'i", $this->path)) { - $this->debug('cookie is for a different path'); - continue; - } - } - if ((! $secure) && (isset($cookie['secure'])) && ($cookie['secure'])) { - $this->debug('cookie is secure, transport is not'); - continue; - } - $cookie_str .= $cookie['name'] . '=' . $cookie['value'] . '; '; - $this->debug('add cookie to Cookie-String: ' . $cookie['name'] . '=' . $cookie['value']); - } - } - return $cookie_str; - } - - 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); - } -} - -?> -* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class soap_server_colosa extends nusoap_base_colosa { - /** - * HTTP headers of request - * @var array - * @access private - */ - var $headers = array(); - /** - * HTTP request - * @var string - * @access private - */ - var $request = ''; - /** - * SOAP headers from request (incomplete namespace resolution; special characters not escaped) (text) - * @var string - * @access public - */ - var $requestHeaders = ''; - /** - * SOAP body request portion (incomplete namespace resolution; special characters not escaped) (text) - * @var string - * @access public - */ - var $document = ''; - /** - * SOAP payload for request (text) - * @var string - * @access public - */ - var $requestSOAP = ''; - /** - * requested method namespace URI - * @var string - * @access private - */ - var $methodURI = ''; - /** - * name of method requested - * @var string - * @access private - */ - var $methodname = ''; - /** - * method parameters from request - * @var array - * @access private - */ - var $methodparams = array(); - /** - * SOAP Action from request - * @var string - * @access private - */ - var $SOAPAction = ''; - /** - * character set encoding of incoming (request) messages - * @var string - * @access public - */ - var $xml_encoding = ''; - /** - * toggles whether the parser decodes element content w/ utf8_decode() - * @var boolean - * @access public - */ - var $decode_utf8 = true; - - /** - * HTTP headers of response - * @var array - * @access public - */ - var $outgoing_headers = array(); - /** - * HTTP response - * @var string - * @access private - */ - var $response = ''; - /** - * SOAP headers for response (text) - * @var string - * @access public - */ - var $responseHeaders = ''; - /** - * SOAP payload for response (text) - * @var string - * @access private - */ - var $responseSOAP = ''; - /** - * method return value to place in response - * @var mixed - * @access private - */ - var $methodreturn = false; - /** - * whether $methodreturn is a string of literal XML - * @var boolean - * @access public - */ - var $methodreturnisliteralxml = false; - /** - * SOAP fault for response (or false) - * @var mixed - * @access private - */ - var $fault = false; - /** - * text indication of result (for debugging) - * @var string - * @access private - */ - var $result = 'successful'; - - /** - * assoc array of operations => opData; operations are added by the register() - * method or by parsing an external WSDL definition - * @var array - * @access private - */ - var $operations = array(); - /** - * wsdl instance (if one) - * @var mixed - * @access private - */ - var $wsdl = false; - /** - * URL for WSDL (if one) - * @var mixed - * @access private - */ - var $externalWSDLURL = false; - /** - * whether to append debug to response as XML comment - * @var boolean - * @access public - */ - var $debug_flag = false; - - - /** - * constructor - * the optional parameter is a path to a WSDL file that you'd like to bind the server instance to. - * - * @param mixed $wsdl file path or URL (string), or wsdl instance (object) - * @access public - */ - function soap_server_colosa($wsdl=false){ - parent::nusoap_base_colosa(); - // turn on debugging? - global $debug; - global $HTTP_SERVER_VARS; - - if (isset($_SERVER)) { - $this->debug("_SERVER is defined:"); - $this->appendDebug($this->varDump($_SERVER)); - } elseif (isset($HTTP_SERVER_VARS)) { - $this->debug("HTTP_SERVER_VARS is defined:"); - $this->appendDebug($this->varDump($HTTP_SERVER_VARS)); - } else { - $this->debug("Neither _SERVER nor HTTP_SERVER_VARS is defined."); - } - - if (isset($debug)) { - $this->debug("In soap_server, set debug_flag=$debug based on global flag"); - $this->debug_flag = $debug; - } elseif (isset($_SERVER['QUERY_STRING'])) { - $qs = explode('&', $_SERVER['QUERY_STRING']); - foreach ($qs as $v) { - if (substr($v, 0, 6) == 'debug=') { - $this->debug("In soap_server, set debug_flag=" . substr($v, 6) . " based on query string #1"); - $this->debug_flag = substr($v, 6); - } - } - } elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) { - $qs = explode('&', $HTTP_SERVER_VARS['QUERY_STRING']); - foreach ($qs as $v) { - if (substr($v, 0, 6) == 'debug=') { - $this->debug("In soap_server, set debug_flag=" . substr($v, 6) . " based on query string #2"); - $this->debug_flag = substr($v, 6); - } - } - } - - // wsdl - if($wsdl){ - $this->debug("In soap_server, WSDL is specified"); - if (is_object($wsdl) && (get_class($wsdl) == 'wsdl')) { - $this->wsdl = $wsdl; - $this->externalWSDLURL = $this->wsdl->wsdl; - $this->debug('Use existing wsdl instance from ' . $this->externalWSDLURL); - } else { - $this->debug('Create wsdl from ' . $wsdl); - $this->wsdl = new wsdl($wsdl); - $this->externalWSDLURL = $wsdl; - } - $this->appendDebug($this->wsdl->getDebug()); - $this->wsdl->clearDebug(); - if($err = $this->wsdl->getError()){ - - 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(); - $err = $filter->xssFilterHard($err); - - die('WSDL ERROR: '.$err); - } - } - } - - /** - * processes request and returns response - * - * @param string $data usually is the value of $HTTP_RAW_POST_DATA - * @access public - */ - function service($data){ - global $HTTP_SERVER_VARS; - - if (isset($_SERVER['QUERY_STRING'])) { - $qs = $_SERVER['QUERY_STRING']; - } elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) { - $qs = $HTTP_SERVER_VARS['QUERY_STRING']; - } else { - $qs = ''; - } - $this->debug("In service, query string=$qs"); - - if (ereg('wsdl', $qs) ){ - $this->debug("In service, this is a request for WSDL"); - if($this->externalWSDLURL){ - if (strpos($this->externalWSDLURL,"://")!==false) { // assume URL - header('Location: '.$this->externalWSDLURL); - } else { // assume file - header("Content-Type: text/xml\r\n"); - $fp = fopen($this->externalWSDLURL, 'r'); - fpassthru($fp); - } - } elseif ($this->wsdl) { - header("Content-Type: text/xml; charset=ISO-8859-1\r\n"); - print $this->wsdl->serialize($this->debug_flag); - if ($this->debug_flag) { - $this->debug('wsdl:'); - $this->appendDebug($this->varDump($this->wsdl)); - print $this->getDebugAsXMLComment(); - } - } else { - header("Content-Type: text/html; charset=ISO-8859-1\r\n"); - print "This service does not provide WSDL"; - } - } elseif ($data == '' && $this->wsdl) { - $this->debug("In service, there is no data, so return Web description"); - - 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(); - $webDescription = $filter->xssFilterHard($this->wsdl->webDescription()); - - print $webDescription; - } else { - $this->debug("In service, invoke the request"); - $this->parse_request($data); - if (! $this->fault) { - $this->invoke_method(); - } - if (! $this->fault) { - $this->serialize_return(); - } - $this->send_response(); - } - } - - /** - * parses HTTP request headers. - * - * The following fields are set by this function (when successful) - * - * headers - * request - * xml_encoding - * SOAPAction - * - * @access private - */ - function parse_http_headers() { - global $HTTP_SERVER_VARS; - - $this->request = ''; - $this->SOAPAction = ''; - if(function_exists('getallheaders')){ - $this->debug("In parse_http_headers, use getallheaders"); - $headers = getallheaders(); - foreach($headers as $k=>$v){ - $k = strtolower($k); - $this->headers[$k] = $v; - $this->request .= "$k: $v\r\n"; - $this->debug("$k: $v"); - } - // get SOAPAction header - if(isset($this->headers['soapaction'])){ - $this->SOAPAction = str_replace('"','',$this->headers['soapaction']); - } - // get the character encoding of the incoming request - if(isset($this->headers['content-type']) && strpos($this->headers['content-type'],'=')){ - $enc = str_replace('"','',substr(strstr($this->headers["content-type"],'='),1)); - if(preg_match('/(ISO-8859-1|US-ASCII|UTF-8)/',$enc)){ - $this->xml_encoding = strtoupper($enc); - } else { - $this->xml_encoding = 'US-ASCII'; - } - } else { - // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 - $this->xml_encoding = 'ISO-8859-1'; - } - } elseif(isset($_SERVER) && is_array($_SERVER)){ - $this->debug("In parse_http_headers, use _SERVER"); - foreach ($_SERVER as $k => $v) { - if (substr($k, 0, 5) == 'HTTP_') { - $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5)))); $k = strtolower(substr($k, 5)); - } else { - $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k))); $k = strtolower($k); - } - if ($k == 'soapaction') { - // get SOAPAction header - $k = 'SOAPAction'; - $v = str_replace('"', '', $v); - $v = str_replace('\\', '', $v); - $this->SOAPAction = $v; - } else if ($k == 'content-type') { - // get the character encoding of the incoming request - if (strpos($v, '=')) { - $enc = substr(strstr($v, '='), 1); - $enc = str_replace('"', '', $enc); - $enc = str_replace('\\', '', $enc); - if (preg_match('/(ISO-8859-1|US-ASCII|UTF-8)/', $enc)) { - $this->xml_encoding = strtoupper($enc); - } else { - $this->xml_encoding = 'US-ASCII'; - } - } else { - // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 - $this->xml_encoding = 'ISO-8859-1'; - } - } - $this->headers[$k] = $v; - $this->request .= "$k: $v\r\n"; - $this->debug("$k: $v"); - } - } elseif (is_array($HTTP_SERVER_VARS)) { - $this->debug("In parse_http_headers, use HTTP_SERVER_VARS"); - foreach ($HTTP_SERVER_VARS as $k => $v) { - if (substr($k, 0, 5) == 'HTTP_') { - $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5)))); $k = strtolower(substr($k, 5)); - } else { - $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k))); $k = strtolower($k); - } - if ($k == 'soapaction') { - // get SOAPAction header - $k = 'SOAPAction'; - $v = str_replace('"', '', $v); - $v = str_replace('\\', '', $v); - $this->SOAPAction = $v; - } else if ($k == 'content-type') { - // get the character encoding of the incoming request - if (strpos($v, '=')) { - $enc = substr(strstr($v, '='), 1); - $enc = str_replace('"', '', $enc); - $enc = str_replace('\\', '', $enc); - if (preg_match('/(ISO-8859-1|US-ASCII|UTF-8)/', $enc)) { - $this->xml_encoding = strtoupper($enc); - } else { - $this->xml_encoding = 'US-ASCII'; - } - } else { - // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 - $this->xml_encoding = 'ISO-8859-1'; - } - } - $this->headers[$k] = $v; - $this->request .= "$k: $v\r\n"; - $this->debug("$k: $v"); - } - } else { - $this->debug("In parse_http_headers, HTTP headers not accessible"); - $this->setError("HTTP headers not accessible"); - } - } - - /** - * parses a request - * - * The following fields are set by this function (when successful) - * - * headers - * request - * xml_encoding - * SOAPAction - * request - * requestSOAP - * methodURI - * methodname - * methodparams - * requestHeaders - * document - * - * This sets the fault field on error - * - * @param string $data XML string - * @access private - */ - function parse_request($data='') { - $this->debug('entering parse_request()'); - $this->parse_http_headers(); - $this->debug('got character encoding: '.$this->xml_encoding); - // uncompress if necessary - if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] != '') { - $this->debug('got content encoding: ' . $this->headers['content-encoding']); - if ($this->headers['content-encoding'] == 'deflate' || $this->headers['content-encoding'] == 'gzip') { - // if decoding works, use it. else assume data wasn't gzencoded - if (function_exists('gzuncompress')) { - if ($this->headers['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) { - $data = $degzdata; - } elseif ($this->headers['content-encoding'] == 'gzip' && $degzdata = gzinflate(substr($data, 10))) { - $data = $degzdata; - } else { - $this->fault('Client', 'Errors occurred when trying to decode the data'); - return; - } - } else { - $this->fault('Client', 'This Server does not support compressed data'); - return; - } - } - } - $this->request .= "\r\n".$data; - $data = $this->parseRequest($this->headers, $data); - $this->requestSOAP = $data; - $this->debug('leaving parse_request'); - } - - /** - * invokes a PHP function for the requested SOAP method - * - * The following fields are set by this function (when successful) - * - * methodreturn - * - * Note that the PHP function that is called may also set the following - * fields to affect the response sent to the client - * - * responseHeaders - * outgoing_headers - * - * This sets the fault field on error - * - * @access private - */ - function invoke_method() { - $this->debug('in invoke_method, methodname=' . $this->methodname . ' methodURI=' . $this->methodURI . ' SOAPAction=' . $this->SOAPAction); - - if ($this->wsdl) { - if ($this->opData = $this->wsdl->getOperationData($this->methodname)) { - $this->debug('in invoke_method, found WSDL operation=' . $this->methodname); - $this->appendDebug('opData=' . $this->varDump($this->opData)); - } elseif ($this->opData = $this->wsdl->getOperationDataForSoapAction($this->SOAPAction)) { - // Note: hopefully this case will only be used for doc/lit, since rpc services should have wrapper element - $this->debug('in invoke_method, found WSDL soapAction=' . $this->SOAPAction . ' for operation=' . $this->opData['name']); - $this->appendDebug('opData=' . $this->varDump($this->opData)); - $this->methodname = $this->opData['name']; - } else { - $this->debug('in invoke_method, no WSDL for operation=' . $this->methodname); - $this->fault('Client', "Operation '" . $this->methodname . "' is not defined in the WSDL for this service"); - return; - } - } else { - $this->debug('in invoke_method, no WSDL to validate method'); - } - - // if a . is present in $this->methodname, we see if there is a class in scope, - // which could be referred to. We will also distinguish between two deliminators, - // to allow methods to be called a the class or an instance - $class = ''; - $method = ''; - if (strpos($this->methodname, '..') > 0) { - $delim = '..'; - } else if (strpos($this->methodname, '.') > 0) { - $delim = '.'; - } else { - $delim = ''; - } - - if (strlen($delim) > 0 && substr_count($this->methodname, $delim) == 1 && - class_exists(substr($this->methodname, 0, strpos($this->methodname, $delim)))) { - // get the class and method name - $class = substr($this->methodname, 0, strpos($this->methodname, $delim)); - $method = substr($this->methodname, strpos($this->methodname, $delim) + strlen($delim)); - $this->debug("in invoke_method, class=$class method=$method delim=$delim"); - } - - // does method exist? - if ($class == '') { - if (!function_exists($this->methodname)) { - $this->debug("in invoke_method, function '$this->methodname' not found!"); - $this->result = 'fault: method not found'; - $this->fault('Client',"method '$this->methodname' not defined in service"); - return; - } - } else { - $method_to_compare = (substr(phpversion(), 0, 2) == '4.') ? strtolower($method) : $method; - if (!in_array($method_to_compare, get_class_methods($class))) { - $this->debug("in invoke_method, method '$this->methodname' not found in class '$class'!"); - $this->result = 'fault: method not found'; - $this->fault('Client',"method '$this->methodname' not defined in service"); - return; - } - } - - // evaluate message, getting back parameters - // verify that request parameters match the method's signature - if(! $this->verify_method($this->methodname,$this->methodparams)){ - // debug - $this->debug('ERROR: request not verified against method signature'); - $this->result = 'fault: request failed validation against method signature'; - // return fault - $this->fault('Client',"Operation '$this->methodname' not defined in service."); - return; - } - - // if there are parameters to pass - $this->debug('in invoke_method, params:'); - $this->appendDebug($this->varDump($this->methodparams)); - $this->debug("in invoke_method, calling '$this->methodname'"); - if (!function_exists('call_user_func_array')) { - if ($class == '') { - $this->debug('in invoke_method, calling function using eval()'); - $funcCall = "\$this->methodreturn = $this->methodname("; - } else { - if ($delim == '..') { - $this->debug('in invoke_method, calling class method using eval()'); - $funcCall = "\$this->methodreturn = ".$class."::".$method."("; - } else { - $this->debug('in invoke_method, calling instance method using eval()'); - // generate unique instance name - $instname = "\$inst_".time(); - $funcCall = $instname." = new ".$class."(); "; - $funcCall .= "\$this->methodreturn = ".$instname."->".$method."("; - } - } - if ($this->methodparams) { - foreach ($this->methodparams as $param) { - if (is_array($param)) { - $this->fault('Client', 'NuSOAP does not handle complexType parameters correctly when using eval; call_user_func_array must be available'); - return; - } - $funcCall .= "\"$param\","; - } - $funcCall = substr($funcCall, 0, -1); - } - $funcCall .= ');'; - $this->debug('in invoke_method, function call: '.$funcCall); - @eval($funcCall); - } else { - if ($class == '') { - $this->debug('in invoke_method, calling function using call_user_func_array()'); - $call_arg = "$this->methodname"; // straight assignment changes $this->methodname to lower case after call_user_func_array() - } elseif ($delim == '..') { - $this->debug('in invoke_method, calling class method using call_user_func_array()'); - $call_arg = array ($class, $method); - } else { - $this->debug('in invoke_method, calling instance method using call_user_func_array()'); - $instance = new $class (); - $call_arg = array(&$instance, $method); - } - $this->methodreturn = call_user_func_array($call_arg, $this->methodparams); - } - $this->debug('in invoke_method, methodreturn:'); - $this->appendDebug($this->varDump($this->methodreturn)); - $this->debug("in invoke_method, called method $this->methodname, received $this->methodreturn of type ".gettype($this->methodreturn)); - } - - /** - * serializes the return value from a PHP function into a full SOAP Envelope - * - * The following fields are set by this function (when successful) - * - * responseSOAP - * - * This sets the fault field on error - * - * @access private - */ - function serialize_return() { - $this->debug('Entering serialize_return methodname: ' . $this->methodname . ' methodURI: ' . $this->methodURI); - // if fault - if (isset($this->methodreturn) && (is_object($this->methodreturn) && get_class($this->methodreturn) == 'soap_fault_colosa')) { - $this->debug('got a fault object from method'); - $this->fault = $this->methodreturn; - return; - } elseif ($this->methodreturnisliteralxml) { - $return_val = $this->methodreturn; - // returned value(s) - } else { - $this->debug('got a(n) '.gettype($this->methodreturn).' from method'); - $this->debug('serializing return value'); - if($this->wsdl){ - // weak attempt at supporting multiple output params - if(sizeof($this->opData['output']['parts']) > 1){ - $opParams = $this->methodreturn; - } else { - // TODO: is this really necessary? - $opParams = array($this->methodreturn); - } - $return_val = $this->wsdl->serializeRPCParameters($this->methodname,'output',$opParams); - $this->appendDebug($this->wsdl->getDebug()); - $this->wsdl->clearDebug(); - if($errstr = $this->wsdl->getError()){ - $this->debug('got wsdl error: '.$errstr); - $this->fault('Server', 'unable to serialize result'); - return; - } - } else { - if (isset($this->methodreturn)) { - $return_val = $this->serialize_val($this->methodreturn, 'return'); - } else { - $return_val = ''; - $this->debug('in absence of WSDL, assume void return for backward compatibility'); - } - } - } - $this->debug('return value:'); - $this->appendDebug($this->varDump($return_val)); - - $this->debug('serializing response'); - if ($this->wsdl) { - $this->debug('have WSDL for serialization: style is ' . $this->opData['style']); - if ($this->opData['style'] == 'rpc') { - $this->debug('style is rpc for serialization: use is ' . $this->opData['output']['use']); - if ($this->opData['output']['use'] == 'literal') { - $payload = '<'.$this->methodname.'Response xmlns="'.$this->methodURI.'">'.$return_val.'methodname."Response>"; - } else { - $payload = 'methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'methodname."Response>"; - } - } else { - $this->debug('style is not rpc for serialization: assume document'); - $payload = $return_val; - } - } else { - $this->debug('do not have WSDL for serialization: assume rpc/encoded'); - $payload = 'methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'methodname."Response>"; - } - $this->result = 'successful'; - if($this->wsdl){ - //if($this->debug_flag){ - $this->appendDebug($this->wsdl->getDebug()); - // } - if (isset($opData['output']['encodingStyle'])) { - $encodingStyle = $opData['output']['encodingStyle']; - } else { - $encodingStyle = ''; - } - // Added: In case we use a WSDL, return a serialized env. WITH the usedNamespaces. - $this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders,$this->wsdl->usedNamespaces,$this->opData['style'],$encodingStyle); - } else { - $this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders); - } - $this->debug("Leaving serialize_return"); - } - - /** - * sends an HTTP response - * - * The following fields are set by this function (when successful) - * - * outgoing_headers - * response - * - * @access private - */ - function send_response() { - $this->debug('Enter send_response'); - if ($this->fault) { - $payload = $this->fault->serialize(); - $this->outgoing_headers[] = "HTTP/1.0 500 Internal Server Error"; - $this->outgoing_headers[] = "Status: 500 Internal Server Error"; - } else { - $payload = $this->responseSOAP; - // Some combinations of PHP+Web server allow the Status - // to come through as a header. Since OK is the default - // just do nothing. - // $this->outgoing_headers[] = "HTTP/1.0 200 OK"; - // $this->outgoing_headers[] = "Status: 200 OK"; - } - // add debug data if in debug mode - if(isset($this->debug_flag) && $this->debug_flag){ - $payload .= $this->getDebugAsXMLComment(); - } - $this->outgoing_headers[] = "Server: $this->title Server v$this->version"; - ereg('\$Revisio' . 'n: ([^ ]+)', $this->revision, $rev); - $this->outgoing_headers[] = "X-SOAP-Server: $this->title/$this->version (".$rev[1].")"; - // Let the Web server decide about this - //$this->outgoing_headers[] = "Connection: Close\r\n"; - $payload = $this->getHTTPBody($payload); - $type = $this->getHTTPContentType(); - $charset = $this->getHTTPContentTypeCharset(); - $this->outgoing_headers[] = "Content-Type: $type" . ($charset ? '; charset=' . $charset : ''); - //begin code to compress payload - by John - // NOTE: there is no way to know whether the Web server will also compress - // this data. - if (strlen($payload) > 1024 && isset($this->headers) && isset($this->headers['accept-encoding'])) { - if (strstr($this->headers['accept-encoding'], 'gzip')) { - if (function_exists('gzencode')) { - if (isset($this->debug_flag) && $this->debug_flag) { - $payload .= ""; - } - $this->outgoing_headers[] = "Content-Encoding: gzip"; - $payload = gzencode($payload); - } else { - if (isset($this->debug_flag) && $this->debug_flag) { - $payload .= ""; - } - } - } elseif (strstr($this->headers['accept-encoding'], 'deflate')) { - // Note: MSIE requires gzdeflate output (no Zlib header and checksum), - // instead of gzcompress output, - // which conflicts with HTTP 1.1 spec (http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5) - if (function_exists('gzdeflate')) { - if (isset($this->debug_flag) && $this->debug_flag) { - $payload .= ""; - } - $this->outgoing_headers[] = "Content-Encoding: deflate"; - $payload = gzdeflate($payload); - } else { - if (isset($this->debug_flag) && $this->debug_flag) { - $payload .= ""; - } - } - } - } - //end code - $this->outgoing_headers[] = "Content-Length: ".strlen($payload); - reset($this->outgoing_headers); - foreach($this->outgoing_headers as $hdr){ - header($hdr, false); - } - print $payload; - $this->response = join("\r\n",$this->outgoing_headers)."\r\n\r\n".$payload; - } - - /** - * takes the value that was created by parsing the request - * and compares to the method's signature, if available. - * - * @param string $operation The operation to be invoked - * @param array $request The array of parameter values - * @return boolean Whether the operation was found - * @access private - */ - function verify_method($operation,$request){ - if(isset($this->wsdl) && is_object($this->wsdl)){ - if($this->wsdl->getOperationData($operation)){ - return true; - } - } elseif(isset($this->operations[$operation])){ - return true; - } - return false; - } - - /** - * processes SOAP message received from client - * - * @param array $headers The HTTP headers - * @param string $data unprocessed request data from client - * @return mixed value of the message, decoded into a PHP type - * @access private - */ - function parseRequest($headers, $data) { - $this->debug('Entering parseRequest() for data of length ' . strlen($data) . ' and type ' . $headers['content-type']); - if (!strstr($headers['content-type'], 'text/xml')) { - $this->setError('Request not of type text/xml'); - return false; - } - if (strpos($headers['content-type'], '=')) { - $enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1)); - $this->debug('Got response encoding: ' . $enc); - if(preg_match('/(ISO-8859-1|US-ASCII|UTF-8)/',$enc)){ - $this->xml_encoding = strtoupper($enc); - } else { - $this->xml_encoding = 'US-ASCII'; - } - } else { - // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 - $this->xml_encoding = 'ISO-8859-1'; - } - $this->debug('Use encoding: ' . $this->xml_encoding . ' when creating soap_parser'); - // parse response, get soap parser obj - $parser = new soap_parser_colosa($data,$this->xml_encoding,'',$this->decode_utf8); - // parser debug - $this->debug("parser debug: \n".$parser->getDebug()); - // if fault occurred during message parsing - if($err = $parser->getError()){ - $this->result = 'fault: error in msg parsing: '.$err; - $this->fault('Client',"error in msg parsing:\n".$err); - // else successfully parsed request into soapval object - } else { - // get/set methodname - $this->methodURI = $parser->root_struct_namespace; - $this->methodname = $parser->root_struct_name; - $this->debug('methodname: '.$this->methodname.' methodURI: '.$this->methodURI); - $this->debug('calling parser->get_response()'); - $this->methodparams = $parser->get_response(); - // get SOAP headers - $this->requestHeaders = $parser->getHeaders(); - // add document for doclit support - $this->document = $parser->document; - } - } - - /** - * gets the HTTP body for the current response. - * - * @param string $soapmsg The SOAP payload - * @return string The HTTP body, which includes the SOAP payload - * @access private - */ - function getHTTPBody($soapmsg) { - return $soapmsg; - } - - /** - * gets the HTTP content type for the current response. - * - * Note: getHTTPBody must be called before this. - * - * @return string the HTTP content type for the current response. - * @access private - */ - function getHTTPContentType() { - return 'text/xml'; - } - - /** - * gets the HTTP content type charset for the current response. - * returns false for non-text content types. - * - * Note: getHTTPBody must be called before this. - * - * @return string the HTTP content type charset for the current response. - * @access private - */ - function getHTTPContentTypeCharset() { - return $this->soap_defencoding; - } - - /** - * add a method to the dispatch map (this has been replaced by the register method) - * - * @param string $methodname - * @param string $in array of input values - * @param string $out array of output values - * @access public - * @deprecated - */ - function add_to_map($methodname,$in,$out){ - $this->operations[$methodname] = array('name' => $methodname,'in' => $in,'out' => $out); - } - - /** - * register a service function with the server - * - * @param string $name the name of the PHP function, class.method or class..method - * @param array $in assoc array of input values: key = param name, value = param type - * @param array $out assoc array of output values: key = param name, value = param type - * @param mixed $namespace the element namespace for the method or false - * @param mixed $soapaction the soapaction for the method or false - * @param mixed $style optional (rpc|document) or false Note: when 'document' is specified, parameter and return wrappers are created for you automatically - * @param mixed $use optional (encoded|literal) or false - * @param string $documentation optional Description to include in WSDL - * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded) - * @access public - */ - function register($name,$in=array(),$out=array(),$namespace=false,$soapaction=false,$style=false,$use=false,$documentation='',$encodingStyle=''){ - global $HTTP_SERVER_VARS; - - if($this->externalWSDLURL){ - die('You cannot bind to an external WSDL file, and register methods outside of it! Please choose either WSDL or no WSDL.'); - } - if (! $name) { - die('You must specify a name when you register an operation'); - } - if (!is_array($in)) { - die('You must provide an array for operation inputs'); - } - if (!is_array($out)) { - die('You must provide an array for operation outputs'); - } - if(false == $namespace) { - } - if(false == $soapaction) { - if (isset($_SERVER)) { - $SERVER_NAME = $_SERVER['SERVER_NAME']; - $SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']; - } elseif (isset($HTTP_SERVER_VARS)) { - $SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME']; - $SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME']; - } else { - $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available"); - } - $soapaction = "http://$SERVER_NAME$SCRIPT_NAME/$name"; - } - if(false == $style) { - $style = "rpc"; - } - if(false == $use) { - $use = "encoded"; - } - if ($use == 'encoded' && $encodingStyle = '') { - $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; - } - - $this->operations[$name] = array( - 'name' => $name, - 'in' => $in, - 'out' => $out, - 'namespace' => $namespace, - 'soapaction' => $soapaction, - 'style' => $style); - if($this->wsdl){ - $this->wsdl->addOperation($name,$in,$out,$namespace,$soapaction,$style,$use,$documentation,$encodingStyle); - } - return true; - } - - /** - * Specify a fault to be returned to the client. - * This also acts as a flag to the server that a fault has occured. - * - * @param string $faultcode - * @param string $faultstring - * @param string $faultactor - * @param string $faultdetail - * @access public - */ - function fault($faultcode,$faultstring,$faultactor='',$faultdetail=''){ - if ($faultdetail == '' && $this->debug_flag) { - $faultdetail = $this->getDebug(); - } - $this->fault = new soap_fault_colosa($faultcode,$faultactor,$faultstring,$faultdetail); - $this->fault->soap_defencoding = $this->soap_defencoding; - } - - /** - * Sets up wsdl object. - * Acts as a flag to enable internal WSDL generation - * - * @param string $serviceName, name of the service - * @param mixed $namespace optional 'tns' service namespace or false - * @param mixed $endpoint optional URL of service endpoint or false - * @param string $style optional (rpc|document) WSDL style (also specified by operation) - * @param string $transport optional SOAP transport - * @param mixed $schemaTargetNamespace optional 'types' targetNamespace for service schema or false - */ - function configureWSDL($serviceName,$namespace = false,$endpoint = false,$style='rpc', $transport = 'http://schemas.xmlsoap.org/soap/http', $schemaTargetNamespace = false) - { - global $HTTP_SERVER_VARS; - - if (isset($_SERVER)) { - $SERVER_NAME = $_SERVER['SERVER_NAME']; - $SERVER_PORT = $_SERVER['SERVER_PORT']; - $SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']; - $HTTPS = $_SERVER['HTTPS']; - } elseif (isset($HTTP_SERVER_VARS)) { - $SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME']; - $SERVER_PORT = $HTTP_SERVER_VARS['SERVER_PORT']; - $SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME']; - $HTTPS = $HTTP_SERVER_VARS['HTTPS']; - } else { - $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available"); - } - if ($SERVER_PORT == 80) { - $SERVER_PORT = ''; - } else { - $SERVER_PORT = ':' . $SERVER_PORT; - } - if(false == $namespace) { - $namespace = "http://$SERVER_NAME/soap/$serviceName"; - } - - if(false == $endpoint) { - if ($HTTPS == '1' || $HTTPS == 'on') { - $SCHEME = 'https'; - } else { - $SCHEME = 'http'; - } - $endpoint = "$SCHEME://$SERVER_NAME$SERVER_PORT$SCRIPT_NAME"; - } - - if(false == $schemaTargetNamespace) { - $schemaTargetNamespace = $namespace; - } - - $this->wsdl = new wsdl; - $this->wsdl->serviceName = $serviceName; - $this->wsdl->endpoint = $endpoint; - $this->wsdl->namespaces['tns'] = $namespace; - $this->wsdl->namespaces['soap'] = 'http://schemas.xmlsoap.org/wsdl/soap/'; - $this->wsdl->namespaces['wsdl'] = 'http://schemas.xmlsoap.org/wsdl/'; - if ($schemaTargetNamespace != $namespace) { - $this->wsdl->namespaces['types'] = $schemaTargetNamespace; - } - $this->wsdl->schemas[$schemaTargetNamespace][0] = new xmlschema('', '', $this->wsdl->namespaces); - $this->wsdl->schemas[$schemaTargetNamespace][0]->schemaTargetNamespace = $schemaTargetNamespace; - $this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/soap/encoding/'][0] = array('location' => '', 'loaded' => true); - $this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/wsdl/'][0] = array('location' => '', 'loaded' => true); - $this->wsdl->bindings[$serviceName.'Binding'] = array( - 'name'=>$serviceName.'Binding', - 'style'=>$style, - 'transport'=>$transport, - 'portType'=>$serviceName.'PortType'); - $this->wsdl->ports[$serviceName.'Port'] = array( - 'binding'=>$serviceName.'Binding', - 'location'=>$endpoint, - 'bindingType'=>'http://schemas.xmlsoap.org/wsdl/soap/'); - } -} - - - -?> -* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class wsdl extends nusoap_base_colosa { - // URL or filename of the root of this WSDL - var $wsdl; - // define internal arrays of bindings, ports, operations, messages, etc. - var $schemas = array(); - var $currentSchema; - var $message = array(); - var $complexTypes = array(); - var $messages = array(); - var $currentMessage; - var $currentOperation; - var $portTypes = array(); - var $currentPortType; - var $bindings = array(); - var $currentBinding; - var $ports = array(); - var $currentPort; - var $opData = array(); - var $status = ''; - var $documentation = false; - var $endpoint = ''; - // array of wsdl docs to import - var $import = array(); - // parser vars - var $parser; - var $position = 0; - var $depth = 0; - var $depth_array = array(); - // for getting wsdl - var $proxyhost = ''; - var $proxyport = ''; - var $proxyusername = ''; - var $proxypassword = ''; - var $timeout = 0; - var $response_timeout = 30; - - /** - * constructor - * - * @param string $wsdl WSDL document URL - * @param string $proxyhost - * @param string $proxyport - * @param string $proxyusername - * @param string $proxypassword - * @param integer $timeout set the connection timeout - * @param integer $response_timeout set the response timeout - * @access public - */ - function wsdl($wsdl = '',$proxyhost=false,$proxyport=false,$proxyusername=false,$proxypassword=false,$timeout=0,$response_timeout=30){ - parent::nusoap_base_colosa(); - $this->wsdl = $wsdl; - $this->proxyhost = $proxyhost; - $this->proxyport = $proxyport; - $this->proxyusername = $proxyusername; - $this->proxypassword = $proxypassword; - $this->timeout = $timeout; - $this->response_timeout = $response_timeout; - - // parse wsdl file - if ($wsdl != "") { - $this->debug('initial wsdl URL: ' . $wsdl); - $this->parseWSDL($wsdl); - } - // imports - // TODO: handle imports more properly, grabbing them in-line and nesting them - $imported_urls = array(); - $imported = 1; - while ($imported > 0) { - $imported = 0; - // Schema imports - foreach ($this->schemas as $ns => $list) { - foreach ($list as $xs) { - $wsdlparts = parse_url($this->wsdl); // this is bogusly simple! - foreach ($xs->imports as $ns2 => $list2) { - for ($ii = 0; $ii < count($list2); $ii++) { - if (! $list2[$ii]['loaded']) { - $this->schemas[$ns]->imports[$ns2][$ii]['loaded'] = true; - $url = $list2[$ii]['location']; - if ($url != '') { - $urlparts = parse_url($url); - if (!isset($urlparts['host'])) { - $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' .$wsdlparts['port'] : '') . - substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path']; - } - if (! in_array($url, $imported_urls)) { - $this->parseWSDL($url); - $imported++; - $imported_urls[] = $url; - } - } else { - $this->debug("Unexpected scenario: empty URL for unloaded import"); - } - } - } - } - } - } - // WSDL imports - $wsdlparts = parse_url($this->wsdl); // this is bogusly simple! - foreach ($this->import as $ns => $list) { - for ($ii = 0; $ii < count($list); $ii++) { - if (! $list[$ii]['loaded']) { - $this->import[$ns][$ii]['loaded'] = true; - $url = $list[$ii]['location']; - if ($url != '') { - $urlparts = parse_url($url); - if (!isset($urlparts['host'])) { - $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' . $wsdlparts['port'] : '') . - substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path']; - } - if (! in_array($url, $imported_urls)) { - $this->parseWSDL($url); - $imported++; - $imported_urls[] = $url; - } - } else { - $this->debug("Unexpected scenario: empty URL for unloaded import"); - } - } - } - } - } - // add new data to operation data - foreach($this->bindings as $binding => $bindingData) { - if (isset($bindingData['operations']) && is_array($bindingData['operations'])) { - foreach($bindingData['operations'] as $operation => $data) { - $this->debug('post-parse data gathering for ' . $operation); - $this->bindings[$binding]['operations'][$operation]['input'] = - isset($this->bindings[$binding]['operations'][$operation]['input']) ? - array_merge($this->bindings[$binding]['operations'][$operation]['input'], $this->portTypes[ $bindingData['portType'] ][$operation]['input']) : - $this->portTypes[ $bindingData['portType'] ][$operation]['input']; - $this->bindings[$binding]['operations'][$operation]['output'] = - isset($this->bindings[$binding]['operations'][$operation]['output']) ? - array_merge($this->bindings[$binding]['operations'][$operation]['output'], $this->portTypes[ $bindingData['portType'] ][$operation]['output']) : - $this->portTypes[ $bindingData['portType'] ][$operation]['output']; - if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ])){ - $this->bindings[$binding]['operations'][$operation]['input']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ]; - } - if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ])){ - $this->bindings[$binding]['operations'][$operation]['output']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ]; - } - if (isset($bindingData['style'])) { - $this->bindings[$binding]['operations'][$operation]['style'] = $bindingData['style']; - } - $this->bindings[$binding]['operations'][$operation]['transport'] = isset($bindingData['transport']) ? $bindingData['transport'] : ''; - $this->bindings[$binding]['operations'][$operation]['documentation'] = isset($this->portTypes[ $bindingData['portType'] ][$operation]['documentation']) ? $this->portTypes[ $bindingData['portType'] ][$operation]['documentation'] : ''; - $this->bindings[$binding]['operations'][$operation]['endpoint'] = isset($bindingData['endpoint']) ? $bindingData['endpoint'] : ''; - } - } - } - } - - /** - * parses the wsdl document - * - * @param string $wsdl path or URL - * @access private - */ - function parseWSDL($wsdl = '') - { - if ($wsdl == '') { - $this->debug('no wsdl passed to parseWSDL()!!'); - $this->setError('no wsdl passed to parseWSDL()!!'); - return false; - } - - // parse $wsdl for url format - $wsdl_props = parse_url($wsdl); - - if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'http' || $wsdl_props['scheme'] == 'https')) { - $this->debug('getting WSDL http(s) URL ' . $wsdl); - // get wsdl - $tr = new soap_transport_http($wsdl); - $tr->request_method = 'GET'; - $tr->useSOAPAction = false; - if($this->proxyhost && $this->proxyport){ - $tr->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword); - } - $tr->setEncoding('gzip, deflate'); - $wsdl_string = $tr->send('', $this->timeout, $this->response_timeout); - //$this->debug("WSDL request\n" . $tr->outgoing_payload); - //$this->debug("WSDL response\n" . $tr->incoming_payload); - $this->appendDebug($tr->getDebug()); - // catch errors - if($err = $tr->getError() ){ - $errstr = 'HTTP ERROR: '.$err; - $this->debug($errstr); - $this->setError($errstr); - unset($tr); - return false; - } - unset($tr); - $this->debug("got WSDL URL"); - } else { - // $wsdl is not http(s), so treat it as a file URL or plain file path - if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'file') && isset($wsdl_props['path'])) { - $path = isset($wsdl_props['host']) ? ($wsdl_props['host'] . ':' . $wsdl_props['path']) : $wsdl_props['path']; - } else { - $path = $wsdl; - } - $this->debug('getting WSDL file ' . $path); - if ($fp = @fopen($path, 'r')) { - $wsdl_string = ''; - while ($data = fread($fp, 32768)) { - $wsdl_string .= $data; - } - fclose($fp); - } else { - $errstr = "Bad path to WSDL file $path"; - $this->debug($errstr); - $this->setError($errstr); - return false; - } - } - $this->debug('Parse WSDL'); - // end new code added - // Create an XML parser. - $this->parser = xml_parser_create(); - // Set the options for parsing the XML data. - // xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); - xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); - // Set the object for the parser. - xml_set_object($this->parser, $this); - // Set the element handlers for the parser. - xml_set_element_handler($this->parser, 'start_element', 'end_element'); - xml_set_character_data_handler($this->parser, 'character_data'); - // Parse the XML file. - if (!xml_parse($this->parser, $wsdl_string, true)) { - // Display an error message. - $errstr = sprintf( - 'XML error parsing WSDL from %s on line %d: %s', - $wsdl, - xml_get_current_line_number($this->parser), - xml_error_string(xml_get_error_code($this->parser)) - ); - $this->debug($errstr); - $this->debug("XML payload:\n" . $wsdl_string); - $this->setError($errstr); - return false; - } - // free the parser - xml_parser_free($this->parser); - $this->debug('Parsing WSDL done'); - // catch wsdl parse errors - if($this->getError()){ - return false; - } - return true; - } - - /** - * start-element handler - * - * @param string $parser XML parser object - * @param string $name element name - * @param string $attrs associative array of attributes - * @access private - */ - function start_element($parser, $name, $attrs) - { - if ($this->status == 'schema') { - $this->currentSchema->schemaStartElement($parser, $name, $attrs); - $this->appendDebug($this->currentSchema->getDebug()); - $this->currentSchema->clearDebug(); - } elseif (ereg('schema$', $name)) { - $this->debug('Parsing WSDL schema'); - // $this->debug("startElement for $name ($attrs[name]). status = $this->status (".$this->getLocalPart($name).")"); - $this->status = 'schema'; - $this->currentSchema = new xmlschema('', '', $this->namespaces); - $this->currentSchema->schemaStartElement($parser, $name, $attrs); - $this->appendDebug($this->currentSchema->getDebug()); - $this->currentSchema->clearDebug(); - } else { - // position in the total number of elements, starting from 0 - $pos = $this->position++; - $depth = $this->depth++; - // set self as current value for this depth - $this->depth_array[$depth] = $pos; - $this->message[$pos] = array('cdata' => ''); - // process attributes - if (count($attrs) > 0) { - // register namespace declarations - foreach($attrs as $k => $v) { - if (ereg("^xmlns", $k)) { - if ($ns_prefix = substr(strrchr($k, ':'), 1)) { - $this->namespaces[$ns_prefix] = $v; - } else { - $this->namespaces['ns' . (count($this->namespaces) + 1)] = $v; - } - if ($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema') { - $this->XMLSchemaVersion = $v; - $this->namespaces['xsi'] = $v . '-instance'; - } - } - } - // expand each attribute prefix to its namespace - foreach($attrs as $k => $v) { - $k = strpos($k, ':') ? $this->expandQname($k) : $k; - if ($k != 'location' && $k != 'soapAction' && $k != 'namespace') { - $v = strpos($v, ':') ? $this->expandQname($v) : $v; - } - $eAttrs[$k] = $v; - } - $attrs = $eAttrs; - } else { - $attrs = array(); - } - // get element prefix, namespace and name - if (ereg(':', $name)) { - // get ns prefix - $prefix = substr($name, 0, strpos($name, ':')); - // get ns - $namespace = isset($this->namespaces[$prefix]) ? $this->namespaces[$prefix] : ''; - // get unqualified name - $name = substr(strstr($name, ':'), 1); - } - // process attributes, expanding any prefixes to namespaces - // find status, register data - switch ($this->status) { - case 'message': - if ($name == 'part') { - if (isset($attrs['type'])) { - $this->debug("msg " . $this->currentMessage . ": found part $attrs[name]: " . implode(',', $attrs)); - $this->messages[$this->currentMessage][$attrs['name']] = $attrs['type']; - } - if (isset($attrs['element'])) { - $this->debug("msg " . $this->currentMessage . ": found part $attrs[name]: " . implode(',', $attrs)); - $this->messages[$this->currentMessage][$attrs['name']] = $attrs['element']; - } - } - break; - case 'portType': - switch ($name) { - case 'operation': - $this->currentPortOperation = $attrs['name']; - $this->debug("portType $this->currentPortType operation: $this->currentPortOperation"); - if (isset($attrs['parameterOrder'])) { - $this->portTypes[$this->currentPortType][$attrs['name']]['parameterOrder'] = $attrs['parameterOrder']; - } - break; - case 'documentation': - $this->documentation = true; - break; - // merge input/output data - default: - $m = isset($attrs['message']) ? $this->getLocalPart($attrs['message']) : ''; - $this->portTypes[$this->currentPortType][$this->currentPortOperation][$name]['message'] = $m; - break; - } - break; - case 'binding': - switch ($name) { - case 'binding': - // get ns prefix - if (isset($attrs['style'])) { - $this->bindings[$this->currentBinding]['prefix'] = $prefix; - } - $this->bindings[$this->currentBinding] = array_merge($this->bindings[$this->currentBinding], $attrs); - break; - case 'header': - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus]['headers'][] = $attrs; - break; - case 'operation': - if (isset($attrs['soapAction'])) { - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['soapAction'] = $attrs['soapAction']; - } - if (isset($attrs['style'])) { - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['style'] = $attrs['style']; - } - if (isset($attrs['name'])) { - $this->currentOperation = $attrs['name']; - $this->debug("current binding operation: $this->currentOperation"); - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['name'] = $attrs['name']; - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['binding'] = $this->currentBinding; - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['endpoint'] = isset($this->bindings[$this->currentBinding]['endpoint']) ? $this->bindings[$this->currentBinding]['endpoint'] : ''; - } - break; - case 'input': - $this->opStatus = 'input'; - break; - case 'output': - $this->opStatus = 'output'; - break; - case 'body': - if (isset($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus])) { - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = array_merge($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus], $attrs); - } else { - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = $attrs; - } - break; - } - break; - case 'service': - switch ($name) { - case 'port': - $this->currentPort = $attrs['name']; - $this->debug('current port: ' . $this->currentPort); - $this->ports[$this->currentPort]['binding'] = $this->getLocalPart($attrs['binding']); - - break; - case 'address': - $this->ports[$this->currentPort]['location'] = $attrs['location']; - $this->ports[$this->currentPort]['bindingType'] = $namespace; - $this->bindings[ $this->ports[$this->currentPort]['binding'] ]['bindingType'] = $namespace; - $this->bindings[ $this->ports[$this->currentPort]['binding'] ]['endpoint'] = $attrs['location']; - break; - } - break; - } - // set status - switch ($name) { - case 'import': - if (isset($attrs['location'])) { - $this->import[$attrs['namespace']][] = array('location' => $attrs['location'], 'loaded' => false); - $this->debug('parsing import ' . $attrs['namespace']. ' - ' . $attrs['location'] . ' (' . count($this->import[$attrs['namespace']]).')'); - } else { - $this->import[$attrs['namespace']][] = array('location' => '', 'loaded' => true); - if (! $this->getPrefixFromNamespace($attrs['namespace'])) { - $this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace']; - } - $this->debug('parsing import ' . $attrs['namespace']. ' - [no location] (' . count($this->import[$attrs['namespace']]).')'); - } - break; - //wait for schema - //case 'types': - // $this->status = 'schema'; - // break; - case 'message': - $this->status = 'message'; - $this->messages[$attrs['name']] = array(); - $this->currentMessage = $attrs['name']; - break; - case 'portType': - $this->status = 'portType'; - $this->portTypes[$attrs['name']] = array(); - $this->currentPortType = $attrs['name']; - break; - case "binding": - if (isset($attrs['name'])) { - // get binding name - if (strpos($attrs['name'], ':')) { - $this->currentBinding = $this->getLocalPart($attrs['name']); - } else { - $this->currentBinding = $attrs['name']; - } - $this->status = 'binding'; - $this->bindings[$this->currentBinding]['portType'] = $this->getLocalPart($attrs['type']); - $this->debug("current binding: $this->currentBinding of portType: " . $attrs['type']); - } - break; - case 'service': - $this->serviceName = $attrs['name']; - $this->status = 'service'; - $this->debug('current service: ' . $this->serviceName); - break; - case 'definitions': - foreach ($attrs as $name => $value) { - $this->wsdl_info[$name] = $value; - } - break; - } - } - } - - /** - * end-element handler - * - * @param string $parser XML parser object - * @param string $name element name - * @access private - */ - function end_element($parser, $name){ - // unset schema status - if (/*ereg('types$', $name) ||*/ ereg('schema$', $name)) { - $this->status = ""; - $this->appendDebug($this->currentSchema->getDebug()); - $this->currentSchema->clearDebug(); - $this->schemas[$this->currentSchema->schemaTargetNamespace][] = $this->currentSchema; - $this->debug('Parsing WSDL schema done'); - } - if ($this->status == 'schema') { - $this->currentSchema->schemaEndElement($parser, $name); - } else { - // bring depth down a notch - $this->depth--; - } - // end documentation - if ($this->documentation) { - //TODO: track the node to which documentation should be assigned; it can be a part, message, etc. - //$this->portTypes[$this->currentPortType][$this->currentPortOperation]['documentation'] = $this->documentation; - $this->documentation = false; - } - } - - /** - * element content handler - * - * @param string $parser XML parser object - * @param string $data element content - * @access private - */ - function character_data($parser, $data) - { - $pos = isset($this->depth_array[$this->depth]) ? $this->depth_array[$this->depth] : 0; - if (isset($this->message[$pos]['cdata'])) { - $this->message[$pos]['cdata'] .= $data; - } - if ($this->documentation) { - $this->documentation .= $data; - } - } - - function getBindingData($binding) - { - if (is_array($this->bindings[$binding])) { - return $this->bindings[$binding]; - } - } - - /** - * returns an assoc array of operation names => operation data - * - * @param string $bindingType eg: soap, smtp, dime (only soap is currently supported) - * @return array - * @access public - */ - function getOperations($bindingType = 'soap') - { - $ops = array(); - if ($bindingType == 'soap') { - $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/'; - } - // loop thru ports - foreach($this->ports as $port => $portData) { - // binding type of port matches parameter - if ($portData['bindingType'] == $bindingType) { - //$this->debug("getOperations for port $port"); - //$this->debug("port data: " . $this->varDump($portData)); - //$this->debug("bindings: " . $this->varDump($this->bindings[ $portData['binding'] ])); - // merge bindings - if (isset($this->bindings[ $portData['binding'] ]['operations'])) { - $ops = array_merge ($ops, $this->bindings[ $portData['binding'] ]['operations']); - } - } - } - return $ops; - } - - /** - * returns an associative array of data necessary for calling an operation - * - * @param string $operation , name of operation - * @param string $bindingType , type of binding eg: soap - * @return array - * @access public - */ - function getOperationData($operation, $bindingType = 'soap') - { - if ($bindingType == 'soap') { - $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/'; - } - // loop thru ports - foreach($this->ports as $port => $portData) { - // binding type of port matches parameter - if ($portData['bindingType'] == $bindingType) { - // get binding - //foreach($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) { - foreach(array_keys($this->bindings[ $portData['binding'] ]['operations']) as $bOperation) { - // note that we could/should also check the namespace here - if ($operation == $bOperation) { - $opData = $this->bindings[ $portData['binding'] ]['operations'][$operation]; - return $opData; - } - } - } - } - } - - /** - * returns an associative array of data necessary for calling an operation - * - * @param string $soapAction soapAction for operation - * @param string $bindingType type of binding eg: soap - * @return array - * @access public - */ - function getOperationDataForSoapAction($soapAction, $bindingType = 'soap') { - if ($bindingType == 'soap') { - $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/'; - } - // loop thru ports - foreach($this->ports as $port => $portData) { - // binding type of port matches parameter - if ($portData['bindingType'] == $bindingType) { - // loop through operations for the binding - foreach ($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) { - if ($opData['soapAction'] == $soapAction) { - return $opData; - } - } - } - } - } - - /** - * returns an array of information about a given type - * returns false if no type exists by the given name - * - * typeDef = array( - * 'elements' => array(), // refs to elements array - * 'restrictionBase' => '', - * 'phpType' => '', - * 'order' => '(sequence|all)', - * 'attrs' => array() // refs to attributes array - * ) - * - * @param $type string the type - * @param $ns string namespace (not prefix) of the type - * @return mixed - * @access public - * @see xmlschema - */ - function getTypeDef($type, $ns) { - $this->debug("in getTypeDef: type=$type, ns=$ns"); - if ((! $ns) && isset($this->namespaces['tns'])) { - $ns = $this->namespaces['tns']; - $this->debug("in getTypeDef: type namespace forced to $ns"); - } - if (isset($this->schemas[$ns])) { - $this->debug("in getTypeDef: have schema for namespace $ns"); - for ($i = 0; $i < count($this->schemas[$ns]); $i++) { - $xs = &$this->schemas[$ns][$i]; - $t = $xs->getTypeDef($type); - $this->appendDebug($xs->getDebug()); - $xs->clearDebug(); - if ($t) { - if (!isset($t['phpType'])) { - // get info for type to tack onto the element - $uqType = substr($t['type'], strrpos($t['type'], ':') + 1); - $ns = substr($t['type'], 0, strrpos($t['type'], ':')); - $etype = $this->getTypeDef($uqType, $ns); - if ($etype) { - $this->debug("found type for [element] $type:"); - $this->debug($this->varDump($etype)); - if (isset($etype['phpType'])) { - $t['phpType'] = $etype['phpType']; - } - if (isset($etype['elements'])) { - $t['elements'] = $etype['elements']; - } - if (isset($etype['attrs'])) { - $t['attrs'] = $etype['attrs']; - } - } - } - return $t; - } - } - } else { - $this->debug("in getTypeDef: do not have schema for namespace $ns"); - } - return false; - } - - /** - * prints html description of services - * - * @access private - */ - function webDescription(){ - global $HTTP_SERVER_VARS; - - if (isset($_SERVER)) { - $PHP_SELF = $_SERVER['PHP_SELF']; - } elseif (isset($HTTP_SERVER_VARS)) { - $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF']; - } else { - $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available"); - } - - $b = ' - NuSOAP: '.$this->serviceName.' - - - - -
-

-
'.$this->serviceName.'
- -
'; - return $b; - } - - /** - * serialize the parsed wsdl - * - * @param mixed $debug whether to put debug=1 in endpoint URL - * @return string serialization of WSDL - * @access public - */ - function serialize($debug = 0) - { - $xml = ''; - $xml .= "\nnamespaces as $k => $v) { - $xml .= " xmlns:$k=\"$v\""; - } - // 10.9.02 - add poulter fix for wsdl and tns declarations - if (isset($this->namespaces['wsdl'])) { - $xml .= " xmlns=\"" . $this->namespaces['wsdl'] . "\""; - } - if (isset($this->namespaces['tns'])) { - $xml .= " targetNamespace=\"" . $this->namespaces['tns'] . "\""; - } - $xml .= '>'; - // imports - if (sizeof($this->import) > 0) { - foreach($this->import as $ns => $list) { - foreach ($list as $ii) { - if ($ii['location'] != '') { - $xml .= ''; - } else { - $xml .= ''; - } - } - } - } - // types - if (count($this->schemas)>=1) { - $xml .= "\n"; - foreach ($this->schemas as $ns => $list) { - foreach ($list as $xs) { - $xml .= $xs->serializeSchema(); - } - } - $xml .= ''; - } - // messages - if (count($this->messages) >= 1) { - foreach($this->messages as $msgName => $msgParts) { - $xml .= "\n'; - if(is_array($msgParts)){ - foreach($msgParts as $partName => $partType) { - // print 'serializing '.$partType.', sv: '.$this->XMLSchemaVersion.'
'; - if (strpos($partType, ':')) { - $typePrefix = $this->getPrefixFromNamespace($this->getPrefix($partType)); - } elseif (isset($this->typemap[$this->namespaces['xsd']][$partType])) { - // print 'checking typemap: '.$this->XMLSchemaVersion.'
'; - $typePrefix = 'xsd'; - } else { - foreach($this->typemap as $ns => $types) { - if (isset($types[$partType])) { - $typePrefix = $this->getPrefixFromNamespace($ns); - } - } - if (!isset($typePrefix)) { - die("$partType has no namespace!"); - } - } - $ns = $this->getNamespaceFromPrefix($typePrefix); - $typeDef = $this->getTypeDef($this->getLocalPart($partType), $ns); - if ($typeDef['typeClass'] == 'element') { - $elementortype = 'element'; - } else { - $elementortype = 'type'; - } - $xml .= ''; - } - } - $xml .= '
'; - } - } - // bindings & porttypes - if (count($this->bindings) >= 1) { - $binding_xml = ''; - $portType_xml = ''; - foreach($this->bindings as $bindingName => $attrs) { - $binding_xml .= "\n'; - $binding_xml .= ''; - $portType_xml .= "\n'; - foreach($attrs['operations'] as $opName => $opParts) { - $binding_xml .= ''; - $binding_xml .= ''; - if (isset($opParts['input']['encodingStyle']) && $opParts['input']['encodingStyle'] != '') { - $enc_style = ' encodingStyle="' . $opParts['input']['encodingStyle'] . '"'; - } else { - $enc_style = ''; - } - $binding_xml .= ''; - if (isset($opParts['output']['encodingStyle']) && $opParts['output']['encodingStyle'] != '') { - $enc_style = ' encodingStyle="' . $opParts['output']['encodingStyle'] . '"'; - } else { - $enc_style = ''; - } - $binding_xml .= ''; - $binding_xml .= ''; - $portType_xml .= ''; - } - $portType_xml .= ''; - $portType_xml .= ''; - $portType_xml .= ''; - } - $portType_xml .= ''; - $binding_xml .= ''; - } - $xml .= $portType_xml . $binding_xml; - } - // services - $xml .= "\nserviceName . '">'; - if (count($this->ports) >= 1) { - foreach($this->ports as $pName => $attrs) { - $xml .= ''; - $uri = explode ( '?' , getenv("REQUEST_URI")); - $location = 'http://' . getenv ( 'SERVER_NAME' ) . $uri[0] ; - $xml .= ''; - // $xml .= ''; - $xml .= ''; - } - } - $xml .= ''; - return $xml . "\n"; - } - - /** - * serialize PHP values according to a WSDL message definition - * - * TODO - * - multi-ref serialization - * - validate PHP values against type definitions, return errors if invalid - * - * @param string $operation operation name - * @param string $direction (input|output) - * @param mixed $parameters parameter value(s) - * @return mixed parameters serialized as XML or false on error (e.g. operation not found) - * @access public - */ - function serializeRPCParameters($operation, $direction, $parameters) - { - $this->debug("in serializeRPCParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion"); - $this->appendDebug('parameters=' . $this->varDump($parameters)); - - if ($direction != 'input' && $direction != 'output') { - $this->debug('The value of the \$direction argument needs to be either "input" or "output"'); - $this->setError('The value of the \$direction argument needs to be either "input" or "output"'); - return false; - } - if (!$opData = $this->getOperationData($operation)) { - $this->debug('Unable to retrieve WSDL data for operation: ' . $operation); - $this->setError('Unable to retrieve WSDL data for operation: ' . $operation); - return false; - } - $this->debug('opData:'); - $this->appendDebug($this->varDump($opData)); - - // Get encoding style for output and set to current - $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; - if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) { - $encodingStyle = $opData['output']['encodingStyle']; - $enc_style = $encodingStyle; - } - - // set input params - $xml = ''; - if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) { - - $use = $opData[$direction]['use']; - $this->debug('have ' . count($opData[$direction]['parts']) . ' part(s) to serialize'); - if (is_array($parameters)) { - $parametersArrayType = $this->isArraySimpleOrStruct($parameters); - $this->debug('have ' . count($parameters) . ' parameter(s) provided as ' . $parametersArrayType . ' to serialize'); - foreach($opData[$direction]['parts'] as $name => $type) { - $this->debug('serializing part "'.$name.'" of type "'.$type.'"'); - // Track encoding style - if (isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) { - $encodingStyle = $opData[$direction]['encodingStyle']; - $enc_style = $encodingStyle; - } else { - $enc_style = false; - } - // NOTE: add error handling here - // if serializeType returns false, then catch global error and fault - if ($parametersArrayType == 'arraySimple') { - $p = array_shift($parameters); - $this->debug('calling serializeType w/indexed param'); - $xml .= $this->serializeType($name, $type, $p, $use, $enc_style); - } elseif (isset($parameters[$name])) { - $this->debug('calling serializeType w/named param'); - $xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style); - } else { - // TODO: only send nillable - $this->debug('calling serializeType w/null param'); - $xml .= $this->serializeType($name, $type, null, $use, $enc_style); - } - } - } else { - $this->debug('no parameters passed.'); - } - } - $this->debug("serializeRPCParameters returning: $xml"); - return $xml; - } - - /** - * serialize a PHP value according to a WSDL message definition - * - * TODO - * - multi-ref serialization - * - validate PHP values against type definitions, return errors if invalid - * - * @param string $ type name - * @param mixed $ param value - * @return mixed new param or false if initial value didn't validate - * @access public - * @deprecated - */ - function serializeParameters($operation, $direction, $parameters) - { - $this->debug("in serializeParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion"); - $this->appendDebug('parameters=' . $this->varDump($parameters)); - - if ($direction != 'input' && $direction != 'output') { - $this->debug('The value of the \$direction argument needs to be either "input" or "output"'); - $this->setError('The value of the \$direction argument needs to be either "input" or "output"'); - return false; - } - if (!$opData = $this->getOperationData($operation)) { - $this->debug('Unable to retrieve WSDL data for operation: ' . $operation); - $this->setError('Unable to retrieve WSDL data for operation: ' . $operation); - return false; - } - $this->debug('opData:'); - $this->appendDebug($this->varDump($opData)); - - // Get encoding style for output and set to current - $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; - if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) { - $encodingStyle = $opData['output']['encodingStyle']; - $enc_style = $encodingStyle; - } - - // set input params - $xml = ''; - if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) { - - $use = $opData[$direction]['use']; - $this->debug("use=$use"); - $this->debug('got ' . count($opData[$direction]['parts']) . ' part(s)'); - if (is_array($parameters)) { - $parametersArrayType = $this->isArraySimpleOrStruct($parameters); - $this->debug('have ' . $parametersArrayType . ' parameters'); - foreach($opData[$direction]['parts'] as $name => $type) { - $this->debug('serializing part "'.$name.'" of type "'.$type.'"'); - // Track encoding style - if(isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) { - $encodingStyle = $opData[$direction]['encodingStyle']; - $enc_style = $encodingStyle; - } else { - $enc_style = false; - } - // NOTE: add error handling here - // if serializeType returns false, then catch global error and fault - if ($parametersArrayType == 'arraySimple') { - $p = array_shift($parameters); - $this->debug('calling serializeType w/indexed param'); - $xml .= $this->serializeType($name, $type, $p, $use, $enc_style); - } elseif (isset($parameters[$name])) { - $this->debug('calling serializeType w/named param'); - $xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style); - } else { - // TODO: only send nillable - $this->debug('calling serializeType w/null param'); - $xml .= $this->serializeType($name, $type, null, $use, $enc_style); - } - } - } else { - $this->debug('no parameters passed.'); - } - } - $this->debug("serializeParameters returning: $xml"); - return $xml; - } - - /** - * serializes a PHP value according a given type definition - * - * @param string $name name of value (part or element) - * @param string $type XML schema type of value (type or element) - * @param mixed $value a native PHP value (parameter value) - * @param string $use use for part (encoded|literal) - * @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style) - * @param boolean $unqualified a kludge for what should be XML namespace form handling - * @return string value serialized as an XML string - * @access private - */ - function serializeType($name, $type, $value, $use='encoded', $encodingStyle=false, $unqualified=false) - { - $this->debug("in serializeType: name=$name, type=$type, use=$use, encodingStyle=$encodingStyle, unqualified=" . ($unqualified ? "unqualified" : "qualified")); - $this->appendDebug("value=" . $this->varDump($value)); - if($use == 'encoded' && $encodingStyle) { - $encodingStyle = ' SOAP-ENV:encodingStyle="' . $encodingStyle . '"'; - } - - // if a soapval has been supplied, let its type override the WSDL - if (is_object($value) && get_class($value) == 'soapval') { - if ($value->type_ns) { - $type = $value->type_ns . ':' . $value->type; - $forceType = true; - $this->debug("in serializeType: soapval overrides type to $type"); - } elseif ($value->type) { - $type = $value->type; - $forceType = true; - $this->debug("in serializeType: soapval overrides type to $type"); - } else { - $forceType = false; - $this->debug("in serializeType: soapval does not override type"); - } - $attrs = $value->attributes; - $value = $value->value; - $this->debug("in serializeType: soapval overrides value to $value"); - if ($attrs) { - if (!is_array($value)) { - $value['!'] = $value; - } - foreach ($attrs as $n => $v) { - $value['!' . $n] = $v; - } - $this->debug("in serializeType: soapval provides attributes"); - } - } else { - $forceType = false; - } - - $xml = ''; - if (strpos($type, ':')) { - $uqType = substr($type, strrpos($type, ':') + 1); - $ns = substr($type, 0, strrpos($type, ':')); - $this->debug("in serializeType: got a prefixed type: $uqType, $ns"); - if ($this->getNamespaceFromPrefix($ns)) { - $ns = $this->getNamespaceFromPrefix($ns); - $this->debug("in serializeType: expanded prefixed type: $uqType, $ns"); - } - - if($ns == $this->XMLSchemaVersion || $ns == 'http://schemas.xmlsoap.org/soap/encoding/'){ - $this->debug('in serializeType: type namespace indicates XML Schema or SOAP Encoding type'); - if ($unqualified && $use == 'literal') { - $elementNS = " xmlns=\"\""; - } else { - $elementNS = ''; - } - if (is_null($value)) { - if ($use == 'literal') { - // TODO: depends on minOccurs - $xml = "<$name$elementNS/>"; - } else { - // TODO: depends on nillable, which should be checked before calling this method - $xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>"; - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - if ($uqType == 'boolean') { - if ((is_string($value) && $value == 'false') || (! $value)) { - $value = 'false'; - } else { - $value = 'true'; - } - } - if ($uqType == 'string' && gettype($value) == 'string') { - $value = $this->expandEntities($value); - } - if (($uqType == 'long' || $uqType == 'unsignedLong') && gettype($value) == 'double') { - $value = sprintf("%.0lf", $value); - } - // it's a scalar - // TODO: what about null/nil values? - // check type isn't a custom type extending xmlschema namespace - if (!$this->getTypeDef($uqType, $ns)) { - if ($use == 'literal') { - if ($forceType) { - $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value"; - } else { - $xml = "<$name$elementNS>$value"; - } - } else { - $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value"; - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - $this->debug('custom type extends XML Schema or SOAP Encoding namespace (yuck)'); - } else if ($ns == 'http://xml.apache.org/xml-soap') { - $this->debug('in serializeType: appears to be Apache SOAP type'); - if ($uqType == 'Map') { - $tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap'); - if (! $tt_prefix) { - $this->debug('in serializeType: Add namespace for Apache SOAP type'); - $tt_prefix = 'ns' . rand(1000, 9999); - $this->namespaces[$tt_prefix] = 'http://xml.apache.org/xml-soap'; - // force this to be added to usedNamespaces - $tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap'); - } - $contents = ''; - foreach($value as $k => $v) { - $this->debug("serializing map element: key $k, value $v"); - $contents .= ''; - $contents .= $this->serialize_val($k,'key',false,false,false,false,$use); - $contents .= $this->serialize_val($v,'value',false,false,false,false,$use); - $contents .= ''; - } - if ($use == 'literal') { - if ($forceType) { - $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\">$contents"; - } else { - $xml = "<$name>$contents"; - } - } else { - $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\"$encodingStyle>$contents"; - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - $this->debug('in serializeType: Apache SOAP type, but only support Map'); - } - } else { - // TODO: should the type be compared to types in XSD, and the namespace - // set to XSD if the type matches? - $this->debug("in serializeType: No namespace for type $type"); - $ns = ''; - $uqType = $type; - } - if(!$typeDef = $this->getTypeDef($uqType, $ns)){ - $this->setError("$type ($uqType) is not a supported type."); - $this->debug("in serializeType: $type ($uqType) is not a supported type."); - return false; - } else { - $this->debug("in serializeType: found typeDef"); - $this->appendDebug('typeDef=' . $this->varDump($typeDef)); - } - $phpType = $typeDef['phpType']; - $this->debug("in serializeType: uqType: $uqType, ns: $ns, phptype: $phpType, arrayType: " . (isset($typeDef['arrayType']) ? $typeDef['arrayType'] : '') ); - // if php type == struct, map value to the element names - if ($phpType == 'struct') { - if (isset($typeDef['typeClass']) && $typeDef['typeClass'] == 'element') { - $elementName = $uqType; - if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) { - $elementNS = " xmlns=\"$ns\""; - } else { - $elementNS = " xmlns=\"\""; - } - } else { - $elementName = $name; - if ($unqualified) { - $elementNS = " xmlns=\"\""; - } else { - $elementNS = ''; - } - } - if (is_null($value)) { - if ($use == 'literal') { - // TODO: depends on minOccurs - $xml = "<$elementName$elementNS/>"; - } else { - $xml = "<$elementName$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>"; - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - if (is_object($value)) { - $value = get_object_vars($value); - } - if (is_array($value)) { - $elementAttrs = $this->serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType); - if ($use == 'literal') { - if ($forceType) { - $xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">"; - } else { - $xml = "<$elementName$elementNS$elementAttrs>"; - } - } else { - $xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>"; - } - - $xml .= $this->serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use, $encodingStyle); - $xml .= ""; - } else { - $this->debug("in serializeType: phpType is struct, but value is not an array"); - $this->setError("phpType is struct, but value is not an array: see debug output for details"); - $xml = ''; - } - } elseif ($phpType == 'array') { - if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) { - $elementNS = " xmlns=\"$ns\""; - } else { - if ($unqualified) { - $elementNS = " xmlns=\"\""; - } else { - $elementNS = ''; - } - } - if (is_null($value)) { - if ($use == 'literal') { - // TODO: depends on minOccurs - $xml = "<$name$elementNS/>"; - } else { - $xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" . - $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') . - ":Array\" " . - $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') . - ':arrayType="' . - $this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType'])) . - ':' . - $this->getLocalPart($typeDef['arrayType'])."[0]\"/>"; - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - if (isset($typeDef['multidimensional'])) { - $nv = array(); - foreach($value as $v) { - $cols = ',' . sizeof($v); - $nv = array_merge($nv, $v); - } - $value = $nv; - } else { - $cols = ''; - } - if (is_array($value) && sizeof($value) >= 1) { - $rows = sizeof($value); - $contents = ''; - foreach($value as $k => $v) { - $this->debug("serializing array element: $k, $v of type: $typeDef[arrayType]"); - //if (strpos($typeDef['arrayType'], ':') ) { - if (!in_array($typeDef['arrayType'],$this->typemap['http://www.w3.org/2001/XMLSchema'])) { - $contents .= $this->serializeType('item', $typeDef['arrayType'], $v, $use); - } else { - $contents .= $this->serialize_val($v, 'item', $typeDef['arrayType'], null, $this->XMLSchemaVersion, false, $use); - } - } - } else { - $rows = 0; - $contents = null; - } - // TODO: for now, an empty value will be serialized as a zero element - // array. Revisit this when coding the handling of null/nil values. - if ($use == 'literal') { - $xml = "<$name$elementNS>" - .$contents - .""; - } else { - $xml = "<$name$elementNS xsi:type=\"".$this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/').':Array" '. - $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') - .':arrayType="' - .$this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType'])) - .":".$this->getLocalPart($typeDef['arrayType'])."[$rows$cols]\">" - .$contents - .""; - } - } elseif ($phpType == 'scalar') { - if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) { - $elementNS = " xmlns=\"$ns\""; - } else { - if ($unqualified) { - $elementNS = " xmlns=\"\""; - } else { - $elementNS = ''; - } - } - if ($use == 'literal') { - if ($forceType) { - $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value"; - } else { - $xml = "<$name$elementNS>$value"; - } - } else { - $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value"; - } - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - - /** - * serializes the attributes for a complexType - * - * @param array $typeDef our internal representation of an XML schema type (or element) - * @param mixed $value a native PHP value (parameter value) - * @param string $ns the namespace of the type - * @param string $uqType the local part of the type - * @return string value serialized as an XML string - * @access private - */ - function serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType) { - $xml = ''; - if (isset($typeDef['attrs']) && is_array($typeDef['attrs'])) { - $this->debug("serialize attributes for XML Schema type $ns:$uqType"); - if (is_array($value)) { - $xvalue = $value; - } elseif (is_object($value)) { - $xvalue = get_object_vars($value); - } else { - $this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType"); - $xvalue = array(); - } - foreach ($typeDef['attrs'] as $aName => $attrs) { - if (isset($xvalue['!' . $aName])) { - $xname = '!' . $aName; - $this->debug("value provided for attribute $aName with key $xname"); - } elseif (isset($xvalue[$aName])) { - $xname = $aName; - $this->debug("value provided for attribute $aName with key $xname"); - } elseif (isset($attrs['default'])) { - $xname = '!' . $aName; - $xvalue[$xname] = $attrs['default']; - $this->debug('use default value of ' . $xvalue[$aName] . ' for attribute ' . $aName); - } else { - $xname = ''; - $this->debug("no value provided for attribute $aName"); - } - if ($xname) { - $xml .= " $aName=\"" . $this->expandEntities($xvalue[$xname]) . "\""; - } - } - } else { - $this->debug("no attributes to serialize for XML Schema type $ns:$uqType"); - } - if (isset($typeDef['extensionBase'])) { - $ns = $this->getPrefix($typeDef['extensionBase']); - $uqType = $this->getLocalPart($typeDef['extensionBase']); - if ($this->getNamespaceFromPrefix($ns)) { - $ns = $this->getNamespaceFromPrefix($ns); - } - if ($typeDef = $this->getTypeDef($uqType, $ns)) { - $this->debug("serialize attributes for extension base $ns:$uqType"); - $xml .= $this->serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType); - } else { - $this->debug("extension base $ns:$uqType is not a supported type"); - } - } - return $xml; - } - - /** - * serializes the elements for a complexType - * - * @param array $typeDef our internal representation of an XML schema type (or element) - * @param mixed $value a native PHP value (parameter value) - * @param string $ns the namespace of the type - * @param string $uqType the local part of the type - * @param string $use use for part (encoded|literal) - * @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style) - * @return string value serialized as an XML string - * @access private - */ - function serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use='encoded', $encodingStyle=false) { - $xml = ''; - if (isset($typeDef['elements']) && is_array($typeDef['elements'])) { - $this->debug("in serializeComplexTypeElements, serialize elements for XML Schema type $ns:$uqType"); - if (is_array($value)) { - $xvalue = $value; - } elseif (is_object($value)) { - $xvalue = get_object_vars($value); - } else { - $this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType"); - $xvalue = array(); - } - // toggle whether all elements are present - ideally should validate against schema - if (count($typeDef['elements']) != count($xvalue)){ - $optionals = true; - } - foreach ($typeDef['elements'] as $eName => $attrs) { - if (!isset($xvalue[$eName])) { - if (isset($attrs['default'])) { - $xvalue[$eName] = $attrs['default']; - $this->debug('use default value of ' . $xvalue[$eName] . ' for element ' . $eName); - } - } - // if user took advantage of a minOccurs=0, then only serialize named parameters - if (isset($optionals) - && (!isset($xvalue[$eName])) - && ( (!isset($attrs['nillable'])) || $attrs['nillable'] != 'true') - ){ - if (isset($attrs['minOccurs']) && $attrs['minOccurs'] <> '0') { - $this->debug("apparent error: no value provided for element $eName with minOccurs=" . $attrs['minOccurs']); - } - // do nothing - $this->debug("no value provided for complexType element $eName and element is not nillable, so serialize nothing"); - } else { - // get value - if (isset($xvalue[$eName])) { - $v = $xvalue[$eName]; - } else { - $v = null; - } - if (isset($attrs['form'])) { - $unqualified = ($attrs['form'] == 'unqualified'); - } else { - $unqualified = false; - } - if (isset($attrs['maxOccurs']) && ($attrs['maxOccurs'] == 'unbounded' || $attrs['maxOccurs'] > 1) && isset($v) && is_array($v) && $this->isArraySimpleOrStruct($v) == 'arraySimple') { - $vv = $v; - foreach ($vv as $k => $v) { - if (isset($attrs['type']) || isset($attrs['ref'])) { - // serialize schema-defined type - $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified); - } else { - // serialize generic type (can this ever really happen?) - $this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use"); - $xml .= $this->serialize_val($v, $eName, false, false, false, false, $use); - } - } - } else { - if (isset($attrs['type']) || isset($attrs['ref'])) { - // serialize schema-defined type - $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified); - } else { - // serialize generic type (can this ever really happen?) - $this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use"); - $xml .= $this->serialize_val($v, $eName, false, false, false, false, $use); - } - } - } - } - } else { - $this->debug("no elements to serialize for XML Schema type $ns:$uqType"); - } - if (isset($typeDef['extensionBase'])) { - $ns = $this->getPrefix($typeDef['extensionBase']); - $uqType = $this->getLocalPart($typeDef['extensionBase']); - if ($this->getNamespaceFromPrefix($ns)) { - $ns = $this->getNamespaceFromPrefix($ns); - } - if ($typeDef = $this->getTypeDef($uqType, $ns)) { - $this->debug("serialize elements for extension base $ns:$uqType"); - $xml .= $this->serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use, $encodingStyle); - } else { - $this->debug("extension base $ns:$uqType is not a supported type"); - } - } - return $xml; - } - - /** - * adds an XML Schema complex type to the WSDL types - * - * @param string name - * @param string typeClass (complexType|simpleType|attribute) - * @param string phpType: currently supported are array and struct (php assoc array) - * @param string compositor (all|sequence|choice) - * @param string restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) - * @param array elements = array ( name => array(name=>'',type=>'') ) - * @param array attrs = array(array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'xsd:string[]')) - * @param string arrayType: namespace:name (xsd:string) - * @see xmlschema - * @access public - */ - function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType='') { - if (count($elements) > 0) { - foreach($elements as $n => $e){ - // expand each element - foreach ($e as $k => $v) { - $k = strpos($k,':') ? $this->expandQname($k) : $k; - $v = strpos($v,':') ? $this->expandQname($v) : $v; - $ee[$k] = $v; - } - $eElements[$n] = $ee; - } - $elements = $eElements; - } - - if (count($attrs) > 0) { - foreach($attrs as $n => $a){ - // expand each attribute - foreach ($a as $k => $v) { - $k = strpos($k,':') ? $this->expandQname($k) : $k; - $v = strpos($v,':') ? $this->expandQname($v) : $v; - $aa[$k] = $v; - } - $eAttrs[$n] = $aa; - } - $attrs = $eAttrs; - } - - $restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase; - $arrayType = strpos($arrayType,':') ? $this->expandQname($arrayType) : $arrayType; - - $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns']; - $this->schemas[$typens][0]->addComplexType($name,$typeClass,$phpType,$compositor,$restrictionBase,$elements,$attrs,$arrayType); - } - - /** - * adds an XML Schema simple type to the WSDL types - * - * @param string $name - * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) - * @param string $typeClass (should always be simpleType) - * @param string $phpType (should always be scalar) - * @param array $enumeration array of values - * @see xmlschema - * @access public - */ - function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) { - $restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase; - - $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns']; - $this->schemas[$typens][0]->addSimpleType($name, $restrictionBase, $typeClass, $phpType, $enumeration); - } - - /** - * adds an element to the WSDL types - * - * @param array $attrs attributes that must include name and type - * @see xmlschema - * @access public - */ - function addElement($attrs) { - $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns']; - $this->schemas[$typens][0]->addElement($attrs); - } - - /** - * register an operation with the server - * - * @param string $name operation (method) name - * @param array $in assoc array of input values: key = param name, value = param type - * @param array $out assoc array of output values: key = param name, value = param type - * @param string $namespace optional The namespace for the operation - * @param string $soapaction optional The soapaction for the operation - * @param string $style (rpc|document) optional The style for the operation Note: when 'document' is specified, parameter and return wrappers are created for you automatically - * @param string $use (encoded|literal) optional The use for the parameters (cannot mix right now) - * @param string $documentation optional The description to include in the WSDL - * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded) - * @access public - */ - function addOperation($name, $in = false, $out = false, $namespace = false, $soapaction = false, $style = 'rpc', $use = 'encoded', $documentation = '', $encodingStyle = ''){ - if ($use == 'encoded' && $encodingStyle == '') { - $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; - } - - if ($style == 'document') { - $elements = array(); - foreach ($in as $n => $t) { - $elements[$n] = array('name' => $n, 'type' => $t); - } - $this->addComplexType($name . 'RequestType', 'complexType', 'struct', 'all', '', $elements); - $this->addElement(array('name' => $name, 'type' => $name . 'RequestType')); - $in = array('parameters' => 'tns:' . $name); - - $elements = array(); - foreach ($out as $n => $t) { - $elements[$n] = array('name' => $n, 'type' => $t); - } - $this->addComplexType($name . 'ResponseType', 'complexType', 'struct', 'all', '', $elements); - $this->addElement(array('name' => $name . 'Response', 'type' => $name . 'ResponseType')); - $out = array('parameters' => 'tns:' . $name . 'Response'); - } - - // get binding - $this->bindings[ $this->serviceName . 'Binding' ]['operations'][$name] = - array( - 'name' => $name, - 'binding' => $this->serviceName . 'Binding', - 'endpoint' => $this->endpoint, - 'soapAction' => $soapaction, - 'style' => $style, - 'input' => array( - 'use' => $use, - 'namespace' => $namespace, - 'encodingStyle' => $encodingStyle, - 'message' => $name . 'Request', - 'parts' => $in), - 'output' => array( - 'use' => $use, - 'namespace' => $namespace, - 'encodingStyle' => $encodingStyle, - 'message' => $name . 'Response', - 'parts' => $out), - 'namespace' => $namespace, - 'transport' => 'http://schemas.xmlsoap.org/soap/http', - 'documentation' => $documentation); - // add portTypes - // add messages - if($in) - { - foreach($in as $pName => $pType) - { - if(strpos($pType,':')) { - $pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType); - } - $this->messages[$name.'Request'][$pName] = $pType; - } - } else { - $this->messages[$name.'Request']= '0'; - } - if($out) - { - foreach($out as $pName => $pType) - { - if(strpos($pType,':')) { - $pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType); - } - $this->messages[$name.'Response'][$pName] = $pType; - } - } else { - $this->messages[$name.'Response']= '0'; - } - return true; - } -} -?> -* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class soap_parser_colosa extends nusoap_base_colosa { - - var $xml = ''; - var $xml_encoding = ''; - var $method = ''; - var $root_struct = ''; - var $root_struct_name = ''; - var $root_struct_namespace = ''; - var $root_header = ''; - var $document = ''; // incoming SOAP body (text) - // determines where in the message we are (envelope,header,body,method) - var $status = ''; - var $position = 0; - var $depth = 0; - var $default_namespace = ''; - var $namespaces = array(); - var $message = array(); - var $parent = ''; - var $fault = false; - var $fault_code = ''; - var $fault_str = ''; - var $fault_detail = ''; - var $depth_array = array(); - var $debug_flag = true; - var $soapresponse = NULL; - var $responseHeaders = ''; // incoming SOAP headers (text) - var $body_position = 0; - // for multiref parsing: - // array of id => pos - var $ids = array(); - // array of id => hrefs => pos - var $multirefs = array(); - // toggle for auto-decoding element content - var $decode_utf8 = true; - - /** - * constructor that actually does the parsing - * - * @param string $xml SOAP message - * @param string $encoding character encoding scheme of message - * @param string $method method for which XML is parsed (unused?) - * @param string $decode_utf8 whether to decode UTF-8 to ISO-8859-1 - * @access public - */ - function soap_parser_colosa($xml,$encoding='UTF-8',$method='',$decode_utf8=true){ - parent::nusoap_base_colosa(); - $this->xml = $xml; - $this->xml_encoding = $encoding; - $this->method = $method; - $this->decode_utf8 = $decode_utf8; - - // Check whether content has been read. - if(!empty($xml)){ - // Check XML encoding - $pos_xml = strpos($xml, '', $pos_xml + 2) - $pos_xml + 1); - if (preg_match("/encoding=[\"']([^\"']*)[\"']/", $xml_decl, $res)) { - $xml_encoding = $res[1]; - if (strtoupper($xml_encoding) != $encoding) { - $err = "Charset from HTTP Content-Type '" . $encoding . "' does not match encoding from XML declaration '" . $xml_encoding . "'"; - $this->debug($err); - if ($encoding != 'ISO-8859-1' || strtoupper($xml_encoding) != 'UTF-8') { - $this->setError($err); - return; - } - // when HTTP says ISO-8859-1 (the default) and XML says UTF-8 (the typical), assume the other endpoint is just sloppy and proceed - } else { - $this->debug('Charset from HTTP Content-Type matches encoding from XML declaration'); - } - } else { - $this->debug('No encoding specified in XML declaration'); - } - } else { - $this->debug('No XML declaration'); - } - $this->debug('Entering soap_parser(), length='.strlen($xml).', encoding='.$encoding); - // Create an XML parser - why not xml_parser_create_ns? - $this->parser = xml_parser_create($this->xml_encoding); - // Set the options for parsing the XML data. - //xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); - xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); - xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, $this->xml_encoding); - // Set the object for the parser. - xml_set_object($this->parser, $this); - // Set the element handlers for the parser. - xml_set_element_handler($this->parser, 'start_element','end_element'); - xml_set_character_data_handler($this->parser,'character_data'); - - // Parse the XML file. - if(!xml_parse($this->parser,$xml,true)){ - // Display an error message. - $err = sprintf('XML error parsing SOAP payload on line %d: %s', - xml_get_current_line_number($this->parser), - xml_error_string(xml_get_error_code($this->parser))); - $this->debug($err); - $this->debug("XML payload:\n" . $xml); - $this->setError($err); - } else { - $this->debug('parsed successfully, found root struct: '.$this->root_struct.' of name '.$this->root_struct_name); - // get final value - $this->soapresponse = $this->message[$this->root_struct]['result']; - // get header value: no, because this is documented as XML string -// if($this->root_header != '' && isset($this->message[$this->root_header]['result'])){ -// $this->responseHeaders = $this->message[$this->root_header]['result']; -// } - // resolve hrefs/ids - if(sizeof($this->multirefs) > 0){ - foreach($this->multirefs as $id => $hrefs){ - $this->debug('resolving multirefs for id: '.$id); - $idVal = $this->buildVal($this->ids[$id]); - if (is_array($idVal) && isset($idVal['!id'])) { - unset($idVal['!id']); - } - foreach($hrefs as $refPos => $ref){ - $this->debug('resolving href at pos '.$refPos); - $this->multirefs[$id][$refPos] = $idVal; - } - } - } - } - xml_parser_free($this->parser); - } else { - $this->debug('xml was empty, didn\'t parse!'); - $this->setError('xml was empty, didn\'t parse!'); - } - } - - /** - * start-element handler - * - * @param resource $parser XML parser object - * @param string $name element name - * @param array $attrs associative array of attributes - * @access private - */ - function start_element($parser, $name, $attrs) { - // position in a total number of elements, starting from 0 - // update class level pos - $pos = $this->position++; - // and set mine - $this->message[$pos] = array('pos' => $pos,'children'=>'','cdata'=>''); - // depth = how many levels removed from root? - // set mine as current global depth and increment global depth value - $this->message[$pos]['depth'] = $this->depth++; - - // else add self as child to whoever the current parent is - if($pos != 0){ - $this->message[$this->parent]['children'] .= '|'.$pos; - } - // set my parent - $this->message[$pos]['parent'] = $this->parent; - // set self as current parent - $this->parent = $pos; - // set self as current value for this depth - $this->depth_array[$this->depth] = $pos; - // get element prefix - if(strpos($name,':')){ - // get ns prefix - $prefix = substr($name,0,strpos($name,':')); - // get unqualified name - $name = substr(strstr($name,':'),1); - } - // set status - if($name == 'Envelope'){ - $this->status = 'envelope'; - } elseif($name == 'Header'){ - $this->root_header = $pos; - $this->status = 'header'; - } elseif($name == 'Body'){ - $this->status = 'body'; - $this->body_position = $pos; - // set method - } elseif($this->status == 'body' && $pos == ($this->body_position+1)){ - $this->status = 'method'; - $this->root_struct_name = $name; - $this->root_struct = $pos; - $this->message[$pos]['type'] = 'struct'; - $this->debug("found root struct $this->root_struct_name, pos $this->root_struct"); - } - // set my status - $this->message[$pos]['status'] = $this->status; - // set name - $this->message[$pos]['name'] = htmlspecialchars($name); - // set attrs - $this->message[$pos]['attrs'] = $attrs; - - // loop through atts, logging ns and type declarations - $attstr = ''; - foreach($attrs as $key => $value){ - $key_prefix = $this->getPrefix($key); - $key_localpart = $this->getLocalPart($key); - // if ns declarations, add to class level array of valid namespaces - if($key_prefix == 'xmlns'){ - if(ereg('^http://www.w3.org/[0-9]{4}/XMLSchema$',$value)){ - $this->XMLSchemaVersion = $value; - $this->namespaces['xsd'] = $this->XMLSchemaVersion; - $this->namespaces['xsi'] = $this->XMLSchemaVersion.'-instance'; - } - $this->namespaces[$key_localpart] = $value; - // set method namespace - if($name == $this->root_struct_name){ - $this->methodNamespace = $value; - } - // if it's a type declaration, set type - } elseif($key_localpart == 'type'){ - $value_prefix = $this->getPrefix($value); - $value_localpart = $this->getLocalPart($value); - $this->message[$pos]['type'] = $value_localpart; - $this->message[$pos]['typePrefix'] = $value_prefix; - if(isset($this->namespaces[$value_prefix])){ - $this->message[$pos]['type_namespace'] = $this->namespaces[$value_prefix]; - } else if(isset($attrs['xmlns:'.$value_prefix])) { - $this->message[$pos]['type_namespace'] = $attrs['xmlns:'.$value_prefix]; - } - // should do something here with the namespace of specified type? - } elseif($key_localpart == 'arrayType'){ - $this->message[$pos]['type'] = 'array'; - /* do arrayType ereg here - [1] arrayTypeValue ::= atype asize - [2] atype ::= QName rank* - [3] rank ::= '[' (',')* ']' - [4] asize ::= '[' length~ ']' - [5] length ::= nextDimension* Digit+ - [6] nextDimension ::= Digit+ ',' - */ - $expr = '([A-Za-z0-9_]+):([A-Za-z]+[A-Za-z0-9_]+)\[([0-9]+),?([0-9]*)\]'; - if(ereg($expr,$value,$regs)){ - $this->message[$pos]['typePrefix'] = $regs[1]; - $this->message[$pos]['arrayTypePrefix'] = $regs[1]; - if (isset($this->namespaces[$regs[1]])) { - $this->message[$pos]['arrayTypeNamespace'] = $this->namespaces[$regs[1]]; - } else if (isset($attrs['xmlns:'.$regs[1]])) { - $this->message[$pos]['arrayTypeNamespace'] = $attrs['xmlns:'.$regs[1]]; - } - $this->message[$pos]['arrayType'] = $regs[2]; - $this->message[$pos]['arraySize'] = $regs[3]; - $this->message[$pos]['arrayCols'] = $regs[4]; - } - // specifies nil value (or not) - } elseif ($key_localpart == 'nil'){ - $this->message[$pos]['nil'] = ($value == 'true' || $value == '1'); - // some other attribute - } elseif ($key != 'href' && $key != 'xmlns' && $key_localpart != 'encodingStyle' && $key_localpart != 'root') { - $this->message[$pos]['xattrs']['!' . $key] = $value; - } - - if ($key == 'xmlns') { - $this->default_namespace = $value; - } - // log id - if($key == 'id'){ - $this->ids[$value] = $pos; - } - // root - if($key_localpart == 'root' && $value == 1){ - $this->status = 'method'; - $this->root_struct_name = $name; - $this->root_struct = $pos; - $this->debug("found root struct $this->root_struct_name, pos $pos"); - } - // for doclit - $attstr .= " $key=\"$value\""; - } - // get namespace - must be done after namespace atts are processed - if(isset($prefix)){ - $this->message[$pos]['namespace'] = $this->namespaces[$prefix]; - $this->default_namespace = $this->namespaces[$prefix]; - } else { - $this->message[$pos]['namespace'] = $this->default_namespace; - } - if($this->status == 'header'){ - if ($this->root_header != $pos) { - $this->responseHeaders .= "<" . (isset($prefix) ? $prefix . ':' : '') . "$name$attstr>"; - } - } elseif($this->root_struct_name != ''){ - $this->document .= "<" . (isset($prefix) ? $prefix . ':' : '') . "$name$attstr>"; - } - } - - /** - * end-element handler - * - * @param resource $parser XML parser object - * @param string $name element name - * @access private - */ - function end_element($parser, $name) { - // position of current element is equal to the last value left in depth_array for my depth - $pos = $this->depth_array[$this->depth--]; - - // get element prefix - if(strpos($name,':')){ - // get ns prefix - $prefix = substr($name,0,strpos($name,':')); - // get unqualified name - $name = substr(strstr($name,':'),1); - } - - // build to native type - if(isset($this->body_position) && $pos > $this->body_position){ - // deal w/ multirefs - if(isset($this->message[$pos]['attrs']['href'])){ - // get id - $id = substr($this->message[$pos]['attrs']['href'],1); - // add placeholder to href array - $this->multirefs[$id][$pos] = 'placeholder'; - // add set a reference to it as the result value - $this->message[$pos]['result'] =& $this->multirefs[$id][$pos]; - // build complexType values - } elseif($this->message[$pos]['children'] != ''){ - // if result has already been generated (struct/array) - if(!isset($this->message[$pos]['result'])){ - $this->message[$pos]['result'] = $this->buildVal($pos); - } - // build complexType values of attributes and possibly simpleContent - } elseif (isset($this->message[$pos]['xattrs'])) { - if (isset($this->message[$pos]['nil']) && $this->message[$pos]['nil']) { - $this->message[$pos]['xattrs']['!'] = null; - } elseif (isset($this->message[$pos]['cdata']) && trim($this->message[$pos]['cdata']) != '') { - if (isset($this->message[$pos]['type'])) { - $this->message[$pos]['xattrs']['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : ''); - } else { - $parent = $this->message[$pos]['parent']; - if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) { - $this->message[$pos]['xattrs']['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : ''); - } else { - $this->message[$pos]['xattrs']['!'] = $this->message[$pos]['cdata']; - } - } - } - $this->message[$pos]['result'] = $this->message[$pos]['xattrs']; - // set value of simpleType (or nil complexType) - } else { - //$this->debug('adding data for scalar value '.$this->message[$pos]['name'].' of value '.$this->message[$pos]['cdata']); - if (isset($this->message[$pos]['nil']) && $this->message[$pos]['nil']) { - $this->message[$pos]['xattrs']['!'] = null; - } elseif (isset($this->message[$pos]['type'])) { - $this->message[$pos]['result'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : ''); - } else { - $parent = $this->message[$pos]['parent']; - if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) { - $this->message[$pos]['result'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : ''); - } else { - $this->message[$pos]['result'] = $this->message[$pos]['cdata']; - } - } - - /* add value to parent's result, if parent is struct/array - $parent = $this->message[$pos]['parent']; - if($this->message[$parent]['type'] != 'map'){ - if(strtolower($this->message[$parent]['type']) == 'array'){ - $this->message[$parent]['result'][] = $this->message[$pos]['result']; - } else { - $this->message[$parent]['result'][$this->message[$pos]['name']] = $this->message[$pos]['result']; - } - } - */ - } - } - - // for doclit - if($this->status == 'header'){ - if ($this->root_header != $pos) { - $this->responseHeaders .= ""; - } - } elseif($pos >= $this->root_struct){ - $this->document .= ""; - } - // switch status - if($pos == $this->root_struct){ - $this->status = 'body'; - $this->root_struct_namespace = $this->message[$pos]['namespace']; - } elseif($name == 'Body'){ - $this->status = 'envelope'; - } elseif($name == 'Header'){ - $this->status = 'envelope'; - } elseif($name == 'Envelope'){ - // - } - // set parent back to my parent - $this->parent = $this->message[$pos]['parent']; - } - - /** - * element content handler - * - * @param resource $parser XML parser object - * @param string $data element content - * @access private - */ - function character_data($parser, $data){ - $pos = $this->depth_array[$this->depth]; - if ($this->xml_encoding=='UTF-8'){ - // TODO: add an option to disable this for folks who want - // raw UTF-8 that, e.g., might not map to iso-8859-1 - // TODO: this can also be handled with xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "ISO-8859-1"); - if($this->decode_utf8){ - $data = utf8_decode($data); - } - } - $this->message[$pos]['cdata'] .= $data; - // for doclit - if($this->status == 'header'){ - $this->responseHeaders .= $data; - } else { - $this->document .= $data; - } - } - - /** - * get the parsed message - * - * @return mixed - * @access public - */ - function get_response(){ - return $this->soapresponse; - } - - /** - * get the parsed headers - * - * @return string XML or empty if no headers - * @access public - */ - function getHeaders(){ - return $this->responseHeaders; - } - - /** - * decodes simple types into PHP variables - * - * @param string $value value to decode - * @param string $type XML type to decode - * @param string $typens XML type namespace to decode - * @return mixed PHP value - * @access private - */ - function decodeSimple($value, $type, $typens) { - // TODO: use the namespace! - if ((!isset($type)) || $type == 'string' || $type == 'long' || $type == 'unsignedLong') { - return (string) $value; - } - if ($type == 'int' || $type == 'integer' || $type == 'short' || $type == 'byte') { - return (int) $value; - } - if ($type == 'float' || $type == 'double' || $type == 'decimal') { - return (double) $value; - } - if ($type == 'boolean') { - if (strtolower($value) == 'false' || strtolower($value) == 'f') { - return false; - } - return (boolean) $value; - } - if ($type == 'base64' || $type == 'base64Binary') { - $this->debug('Decode base64 value'); - return base64_decode($value); - } - // obscure numeric types - if ($type == 'nonPositiveInteger' || $type == 'negativeInteger' - || $type == 'nonNegativeInteger' || $type == 'positiveInteger' - || $type == 'unsignedInt' - || $type == 'unsignedShort' || $type == 'unsignedByte') { - return (int) $value; - } - // bogus: parser treats array with no elements as a simple type - if ($type == 'array') { - return array(); - } - // everything else - return (string) $value; - } - - /** - * builds response structures for compound values (arrays/structs) - * and scalars - * - * @param integer $pos position in node tree - * @return mixed PHP value - * @access private - */ - function buildVal($pos){ - if(!isset($this->message[$pos]['type'])){ - $this->message[$pos]['type'] = ''; - } - $this->debug('in buildVal() for '.$this->message[$pos]['name']."(pos $pos) of type ".$this->message[$pos]['type']); - // if there are children... - if($this->message[$pos]['children'] != ''){ - $this->debug('in buildVal, there are children'); - $children = explode('|',$this->message[$pos]['children']); - array_shift($children); // knock off empty - // md array - if(isset($this->message[$pos]['arrayCols']) && $this->message[$pos]['arrayCols'] != ''){ - $r=0; // rowcount - $c=0; // colcount - foreach($children as $child_pos){ - $this->debug("in buildVal, got an MD array element: $r, $c"); - $params[$r][] = $this->message[$child_pos]['result']; - $c++; - if($c == $this->message[$pos]['arrayCols']){ - $c = 0; - $r++; - } - } - // array - } elseif($this->message[$pos]['type'] == 'array' || $this->message[$pos]['type'] == 'Array'){ - $this->debug('in buildVal, adding array '.$this->message[$pos]['name']); - foreach($children as $child_pos){ - $params[] = &$this->message[$child_pos]['result']; - } - // apache Map type: java hashtable - } elseif($this->message[$pos]['type'] == 'Map' && $this->message[$pos]['type_namespace'] == 'http://xml.apache.org/xml-soap'){ - $this->debug('in buildVal, Java Map '.$this->message[$pos]['name']); - foreach($children as $child_pos){ - $kv = explode("|",$this->message[$child_pos]['children']); - $params[$this->message[$kv[1]]['result']] = &$this->message[$kv[2]]['result']; - } - // generic compound type - //} elseif($this->message[$pos]['type'] == 'SOAPStruct' || $this->message[$pos]['type'] == 'struct') { - } else { - // Apache Vector type: treat as an array - $this->debug('in buildVal, adding Java Vector '.$this->message[$pos]['name']); - if ($this->message[$pos]['type'] == 'Vector' && $this->message[$pos]['type_namespace'] == 'http://xml.apache.org/xml-soap') { - $notstruct = 1; - } else { - $notstruct = 0; - } - // - foreach($children as $child_pos){ - if($notstruct){ - $params[] = &$this->message[$child_pos]['result']; - } else { - if (isset($params[$this->message[$child_pos]['name']])) { - // de-serialize repeated element name into an array - if ((!is_array($params[$this->message[$child_pos]['name']])) || (!isset($params[$this->message[$child_pos]['name']][0]))) { - $params[$this->message[$child_pos]['name']] = array($params[$this->message[$child_pos]['name']]); - } - $params[$this->message[$child_pos]['name']][] = &$this->message[$child_pos]['result']; - } else { - $params[$this->message[$child_pos]['name']] = &$this->message[$child_pos]['result']; - } - } - } - } - if (isset($this->message[$pos]['xattrs'])) { - $this->debug('in buildVal, handling attributes'); - foreach ($this->message[$pos]['xattrs'] as $n => $v) { - $params[$n] = $v; - } - } - // handle simpleContent - if (isset($this->message[$pos]['cdata']) && trim($this->message[$pos]['cdata']) != '') { - $this->debug('in buildVal, handling simpleContent'); - if (isset($this->message[$pos]['type'])) { - $params['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : ''); - } else { - $parent = $this->message[$pos]['parent']; - if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) { - $params['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : ''); - } else { - $params['!'] = $this->message[$pos]['cdata']; - } - } - } - return is_array($params) ? $params : array(); - } else { - $this->debug('in buildVal, no children, building scalar'); - $cdata = isset($this->message[$pos]['cdata']) ? $this->message[$pos]['cdata'] : ''; - if (isset($this->message[$pos]['type'])) { - return $this->decodeSimple($cdata, $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : ''); - } - $parent = $this->message[$pos]['parent']; - if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) { - return $this->decodeSimple($cdata, $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : ''); - } - return $this->message[$pos]['cdata']; - } - } -} - - - -?>call( string methodname [ ,array parameters] ); -* -* // bye bye client -* unset($soapclient); -* -* @author Dietrich Ayala -* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class soapclient_colosa extends nusoap_base_colosa { - - var $username = ''; - var $password = ''; - var $authtype = ''; - var $certRequest = array(); - var $requestHeaders = false; // SOAP headers in request (text) - var $responseHeaders = ''; // SOAP headers from response (incomplete namespace resolution) (text) - var $document = ''; // SOAP body response portion (incomplete namespace resolution) (text) - var $endpoint; - var $forceEndpoint = ''; // overrides WSDL endpoint - var $proxyhost = ''; - var $proxyport = ''; - var $proxyusername = ''; - var $proxypassword = ''; - var $xml_encoding = ''; // character set encoding of incoming (response) messages - var $http_encoding = false; - var $timeout = 0; // HTTP connection timeout - var $response_timeout = 30; // HTTP response timeout - var $endpointType = ''; // soap|wsdl, empty for WSDL initialization error - var $persistentConnection = false; - var $defaultRpcParams = false; // This is no longer used - var $request = ''; // HTTP request - var $response = ''; // HTTP response - var $responseData = ''; // SOAP payload of response - var $cookies = array(); // Cookies from response or for request - var $decode_utf8 = true; // toggles whether the parser decodes element content w/ utf8_decode() - var $operations = array(); // WSDL operations, empty for WSDL initialization error - - /* - * fault related variables - */ - /** - * @var fault - * @access public - */ - var $fault; - /** - * @var faultcode - * @access public - */ - var $faultcode; - /** - * @var faultstring - * @access public - */ - var $faultstring; - /** - * @var faultdetail - * @access public - */ - var $faultdetail; - - /** - * constructor - * - * @param mixed $endpoint SOAP server or WSDL URL (string), or wsdl instance (object) - * @param bool $wsdl optional, set to true if using WSDL - * @param int $portName optional portName in WSDL document - * @param string $proxyhost - * @param string $proxyport - * @param string $proxyusername - * @param string $proxypassword - * @param integer $timeout set the connection timeout - * @param integer $response_timeout set the response timeout - * @access public - */ - function soapclient_colosa($endpoint,$wsdl = false,$proxyhost = false,$proxyport = false,$proxyusername = false, $proxypassword = false, $timeout = 0, $response_timeout = 30){ - parent::nusoap_base_colosa(); - $this->endpoint = $endpoint; - $this->proxyhost = $proxyhost; - $this->proxyport = $proxyport; - $this->proxyusername = $proxyusername; - $this->proxypassword = $proxypassword; - $this->timeout = $timeout; - $this->response_timeout = $response_timeout; - - // make values - if($wsdl){ - if (is_object($endpoint) && (get_class($endpoint) == 'wsdl')) { - $this->wsdl = $endpoint; - $this->endpoint = $this->wsdl->wsdl; - $this->wsdlFile = $this->endpoint; - $this->debug('existing wsdl instance created from ' . $this->endpoint); - } else { - $this->wsdlFile = $this->endpoint; - - // instantiate wsdl object and parse wsdl file - $this->debug('instantiating wsdl class with doc: '.$endpoint); - $this->wsdl =& new wsdl($this->wsdlFile,$this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword,$this->timeout,$this->response_timeout); - } - $this->appendDebug($this->wsdl->getDebug()); - $this->wsdl->clearDebug(); - // catch errors - if($errstr = $this->wsdl->getError()){ - $this->debug('got wsdl error: '.$errstr); - $this->setError('wsdl error: '.$errstr); - } elseif($this->operations = $this->wsdl->getOperations()){ - $this->debug( 'got '.count($this->operations).' operations from wsdl '.$this->wsdlFile); - $this->endpointType = 'wsdl'; - } else { - $this->debug( 'getOperations returned false'); - $this->setError('no operations defined in the WSDL document!'); - } - } else { - $this->debug("instantiate SOAP with endpoint at $endpoint"); - $this->endpointType = 'soap'; - } - } - - /** - * calls method, returns PHP native type - * - * @param string $method SOAP server URL or path - * @param mixed $params An array, associative or simple, of the parameters - * for the method call, or a string that is the XML - * for the call. For rpc style, this call will - * wrap the XML in a tag named after the method, as - * well as the SOAP Envelope and Body. For document - * style, this will only wrap with the Envelope and Body. - * IMPORTANT: when using an array with document style, - * in which case there - * is really one parameter, the root of the fragment - * used in the call, which encloses what programmers - * normally think of parameters. A parameter array - * *must* include the wrapper. - * @param string $namespace optional method namespace (WSDL can override) - * @param string $soapAction optional SOAPAction value (WSDL can override) - * @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers - * @param boolean $rpcParams optional (no longer used) - * @param string $style optional (rpc|document) the style to use when serializing parameters (WSDL can override) - * @param string $use optional (encoded|literal) the use when serializing parameters (WSDL can override) - * @return mixed response from SOAP call - * @access public - */ - function call($operation,$params=array(),$namespace='http://tempuri.org',$soapAction='',$headers=false,$rpcParams=null,$style='rpc',$use='encoded'){ - $this->operation = $operation; - $this->fault = false; - $this->setError(''); - $this->request = ''; - $this->response = ''; - $this->responseData = ''; - $this->faultstring = ''; - $this->faultcode = ''; - $this->opData = array(); - - $this->debug("call: operation=$operation, namespace=$namespace, soapAction=$soapAction, rpcParams=$rpcParams, style=$style, use=$use, endpointType=$this->endpointType"); - $this->appendDebug('params=' . $this->varDump($params)); - $this->appendDebug('headers=' . $this->varDump($headers)); - if ($headers) { - $this->requestHeaders = $headers; - } - // serialize parameters - if($this->endpointType == 'wsdl' && $opData = $this->getOperationData($operation)){ - // use WSDL for operation - $this->opData = $opData; - $this->debug("found operation"); - $this->appendDebug('opData=' . $this->varDump($opData)); - if (isset($opData['soapAction'])) { - $soapAction = $opData['soapAction']; - } - if (! $this->forceEndpoint) { - $this->endpoint = $opData['endpoint']; - } else { - $this->endpoint = $this->forceEndpoint; - } - $namespace = isset($opData['input']['namespace']) ? $opData['input']['namespace'] : $namespace; - $style = $opData['style']; - $use = $opData['input']['use']; - // add ns to ns array - if($namespace != '' && !isset($this->wsdl->namespaces[$namespace])){ - $nsPrefix = 'ns' . rand(1000, 9999); - $this->wsdl->namespaces[$nsPrefix] = $namespace; - } - $nsPrefix = $this->wsdl->getPrefixFromNamespace($namespace); - // serialize payload - if (is_string($params)) { - $this->debug("serializing param string for WSDL operation $operation"); - $payload = $params; - } elseif (is_array($params)) { - $this->debug("serializing param array for WSDL operation $operation"); - $payload = $this->wsdl->serializeRPCParameters($operation,'input',$params); - } else { - $this->debug('params must be array or string'); - $this->setError('params must be array or string'); - return false; - } - $usedNamespaces = $this->wsdl->usedNamespaces; - if (isset($opData['input']['encodingStyle'])) { - $encodingStyle = $opData['input']['encodingStyle']; - } else { - $encodingStyle = ''; - } - $this->appendDebug($this->wsdl->getDebug()); - $this->wsdl->clearDebug(); - if ($errstr = $this->wsdl->getError()) { - $this->debug('got wsdl error: '.$errstr); - $this->setError('wsdl error: '.$errstr); - return false; - } - } elseif($this->endpointType == 'wsdl') { - // operation not in WSDL - $this->appendDebug($this->wsdl->getDebug()); - $this->wsdl->clearDebug(); - $this->setError( 'operation '.$operation.' not present.'); - $this->debug("operation '$operation' not present."); - return false; - } else { - // no WSDL - //$this->namespaces['ns1'] = $namespace; - $nsPrefix = 'ns' . rand(1000, 9999); - // serialize - $payload = ''; - if (is_string($params)) { - $this->debug("serializing param string for operation $operation"); - $payload = $params; - } elseif (is_array($params)) { - $this->debug("serializing param array for operation $operation"); - foreach($params as $k => $v){ - $payload .= $this->serialize_val($v,$k,false,false,false,false,$use); - } - } else { - $this->debug('params must be array or string'); - $this->setError('params must be array or string'); - return false; - } - $usedNamespaces = array(); - if ($use == 'encoded') { - $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; - } else { - $encodingStyle = ''; - } - } - // wrap RPC calls with method element - if ($style == 'rpc') { - if ($use == 'literal') { - $this->debug("wrapping RPC request with literal method element"); - if ($namespace) { - $payload = "<$operation xmlns=\"$namespace\">" . $payload . ""; - } else { - $payload = "<$operation>" . $payload . ""; - } - } else { - $this->debug("wrapping RPC request with encoded method element"); - if ($namespace) { - $payload = "<$nsPrefix:$operation xmlns:$nsPrefix=\"$namespace\">" . - $payload . - ""; - } else { - $payload = "<$operation>" . - $payload . - ""; - } - } - } - // serialize envelope - $soapmsg = $this->serializeEnvelope($payload,$this->requestHeaders,$usedNamespaces,$style,$use,$encodingStyle); - $this->debug("endpoint=$this->endpoint, soapAction=$soapAction, namespace=$namespace, style=$style, use=$use, encodingStyle=$encodingStyle"); - $this->debug('SOAP message length=' . strlen($soapmsg) . ' contents (max 1000 bytes)=' . substr($soapmsg, 0, 1000)); - // send - $return = $this->send($this->getHTTPBody($soapmsg),$soapAction,$this->timeout,$this->response_timeout); - if($errstr = $this->getError()){ - $this->debug('Error: '.$errstr); - return false; - } else { - $this->return = $return; - $this->debug('sent message successfully and got a(n) '.gettype($return)); - $this->appendDebug('return=' . $this->varDump($return)); - - // fault? - if(is_array($return) && isset($return['faultcode'])){ - $this->debug('got fault'); - $this->setError($return['faultcode'].': '.$return['faultstring']); - $this->fault = true; - foreach($return as $k => $v){ - $this->$k = $v; - $this->debug("$k = $v
"); - } - return $return; - } elseif ($style == 'document') { - // NOTE: if the response is defined to have multiple parts (i.e. unwrapped), - // we are only going to return the first part here...sorry about that - return $return; - } else { - // array of return values - if(is_array($return)){ - // multiple 'out' parameters, which we return wrapped up - // in the array - if(sizeof($return) > 1){ - return $return; - } - // single 'out' parameter (normally the return value) - $return = array_shift($return); - $this->debug('return shifted value: '); - $this->appendDebug($this->varDump($return)); - return $return; - // nothing returned (ie, echoVoid) - } else { - return ""; - } - } - } - } - - /** - * get available data pertaining to an operation - * - * @param string $operation operation name - * @return array array of data pertaining to the operation - * @access public - */ - function getOperationData($operation){ - if(isset($this->operations[$operation])){ - return $this->operations[$operation]; - } - $this->debug("No data for operation: $operation"); - } - - /** - * send the SOAP message - * - * Note: if the operation has multiple return values - * the return value of this method will be an array - * of those values. - * - * @param string $msg a SOAPx4 soapmsg object - * @param string $soapaction SOAPAction value - * @param integer $timeout set connection timeout in seconds - * @param integer $response_timeout set response timeout in seconds - * @return mixed native PHP types. - * @access private - */ - function send($msg, $soapaction = '', $timeout=0, $response_timeout=30) { - $this->checkCookies(); - // detect transport - switch(true){ - // http(s) - case ereg('^http',$this->endpoint): - $this->debug('transporting via HTTP'); - if($this->persistentConnection == true && is_object($this->persistentConnection)){ - $http =& $this->persistentConnection; - } else { - $http = new soap_transport_http($this->endpoint); - if ($this->persistentConnection) { - $http->usePersistentConnection(); - } - } - $http->setContentType($this->getHTTPContentType(), $this->getHTTPContentTypeCharset()); - $http->setSOAPAction($soapaction); - if($this->proxyhost && $this->proxyport){ - $http->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword); - } - if($this->authtype != '') { - $http->setCredentials($this->username, $this->password, $this->authtype, array(), $this->certRequest); - } - if($this->http_encoding != ''){ - $http->setEncoding($this->http_encoding); - } - $this->debug('sending message, length='.strlen($msg)); - if(ereg('^http:',$this->endpoint)){ - //if(strpos($this->endpoint,'http:')){ - $this->responseData = $http->send($msg,$timeout,$response_timeout,$this->cookies); - } elseif(ereg('^https',$this->endpoint)){ - //} elseif(strpos($this->endpoint,'https:')){ - //if(phpversion() == '4.3.0-dev'){ - //$response = $http->send($msg,$timeout,$response_timeout); - //$this->request = $http->outgoing_payload; - //$this->response = $http->incoming_payload; - //} else - $this->responseData = $http->sendHTTPS($msg,$timeout,$response_timeout,$this->cookies); - } else { - $this->setError('no http/s in endpoint url'); - } - $this->request = $http->outgoing_payload; - $this->response = $http->incoming_payload; - $this->appendDebug($http->getDebug()); - $this->UpdateCookies($http->incoming_cookies); - - // save transport object if using persistent connections - if ($this->persistentConnection) { - $http->clearDebug(); - if (!is_object($this->persistentConnection)) { - $this->persistentConnection = $http; - } - } - - if($err = $http->getError()){ - $this->setError('HTTP Error: '.$err); - return false; - } elseif($this->getError()){ - return false; - } else { - $this->debug('got response, length='. strlen($this->responseData).' type='.$http->incoming_headers['content-type']); - return $this->parseResponse($http->incoming_headers, $this->responseData); - } - break; - default: - $this->setError('no transport found, or selected transport is not yet supported!'); - return false; - break; - } - } - - /** - * processes SOAP message returned from server - * - * @param array $headers The HTTP headers - * @param string $data unprocessed response data from server - * @return mixed value of the message, decoded into a PHP type - * @access private - */ - function parseResponse($headers, $data) { - $this->debug('Entering parseResponse() for data of length ' . strlen($data) . ' and type ' . $headers['content-type']); -//by onti -/* - if (!strstr($headers['content-type'], 'text/xml')) { - $this->setError('Response not of type text/xml'); - return false; - } - */ - if (strpos($headers['content-type'], '=')) { - $enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1)); - $this->debug('Got response encoding: ' . $enc); - if(preg_match('/(ISO-8859-1|US-ASCII|UTF-8)/',$enc)){ - $this->xml_encoding = strtoupper($enc); - } else { - $this->xml_encoding = 'US-ASCII'; - } - } else { - // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 - $this->xml_encoding = 'ISO-8859-1'; - } - $this->debug('Use encoding: ' . $this->xml_encoding . ' when creating soap_parser'); - $parser = new soap_parser_colosa($data,$this->xml_encoding,$this->operation,$this->decode_utf8); - // add parser debug data to our debug - $this->appendDebug($parser->getDebug()); - // if parse errors - if($errstr = $parser->getError()){ - $this->setError( $errstr); - // destroy the parser object - unset($parser); - return false; - } else { - // get SOAP headers - $this->responseHeaders = $parser->getHeaders(); - // get decoded message - $return = $parser->get_response(); - // add document for doclit support - $this->document = $parser->document; - // destroy the parser object - unset($parser); - // return decode message - return $return; - } - } - - /** - * sets the SOAP endpoint, which can override WSDL - * - * @param $endpoint string The endpoint URL to use, or empty string or false to prevent override - * @access public - */ - function setEndpoint($endpoint) { - $this->forceEndpoint = $endpoint; - } - - /** - * set the SOAP headers - * - * @param $headers mixed String of XML with SOAP header content, or array of soapval objects for SOAP headers - * @access public - */ - function setHeaders($headers){ - $this->requestHeaders = $headers; - } - - /** - * get the SOAP response headers (namespace resolution incomplete) - * - * @return string - * @access public - */ - function getHeaders(){ - return $this->responseHeaders; - } - - /** - * set proxy info here - * - * @param string $proxyhost - * @param string $proxyport - * @param string $proxyusername - * @param string $proxypassword - * @access public - */ - function setHTTPProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '') { - $this->proxyhost = $proxyhost; - $this->proxyport = $proxyport; - $this->proxyusername = $proxyusername; - $this->proxypassword = $proxypassword; - } - - /** - * if authenticating, set user credentials here - * - * @param string $username - * @param string $password - * @param string $authtype (basic|digest|certificate) - * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs) - * @access public - */ - function setCredentials($username, $password, $authtype = 'basic', $certRequest = array()) { - $this->username = $username; - $this->password = $password; - $this->authtype = $authtype; - $this->certRequest = $certRequest; - } - - /** - * use HTTP encoding - * - * @param string $enc - * @access public - */ - function setHTTPEncoding($enc='gzip, deflate'){ - $this->http_encoding = $enc; - } - - /** - * use HTTP persistent connections if possible - * - * @access public - */ - function useHTTPPersistentConnection(){ - $this->persistentConnection = true; - } - - /** - * gets the default RPC parameter setting. - * If true, default is that call params are like RPC even for document style. - * Each call() can override this value. - * - * This is no longer used. - * - * @return boolean - * @access public - * @deprecated - */ - function getDefaultRpcParams() { - return $this->defaultRpcParams; - } - - /** - * sets the default RPC parameter setting. - * If true, default is that call params are like RPC even for document style - * Each call() can override this value. - * - * This is no longer used. - * - * @param boolean $rpcParams - * @access public - * @deprecated - */ - function setDefaultRpcParams($rpcParams) { - $this->defaultRpcParams = $rpcParams; - } - - /** - * dynamically creates an instance of a proxy class, - * allowing user to directly call methods from wsdl - * - * @return object soap_proxy object - * @access public - */ - function getProxy(){ - $r = rand(); - $evalStr = $this->_getProxyClassCode($r); - //$this->debug("proxy class: $evalStr"; - // eval the class - eval($evalStr); - // instantiate proxy object - eval("\$proxy = new soap_proxy_$r('');"); - // transfer current wsdl data to the proxy thereby avoiding parsing the wsdl twice - $proxy->endpointType = 'wsdl'; - $proxy->wsdlFile = $this->wsdlFile; - $proxy->wsdl = $this->wsdl; - $proxy->operations = $this->operations; - $proxy->defaultRpcParams = $this->defaultRpcParams; - // transfer other state - $proxy->username = $this->username; - $proxy->password = $this->password; - $proxy->authtype = $this->authtype; - $proxy->proxyhost = $this->proxyhost; - $proxy->proxyport = $this->proxyport; - $proxy->proxyusername = $this->proxyusername; - $proxy->proxypassword = $this->proxypassword; - $proxy->timeout = $this->timeout; - $proxy->response_timeout = $this->response_timeout; - $proxy->http_encoding = $this->http_encoding; - $proxy->persistentConnection = $this->persistentConnection; - $proxy->requestHeaders = $this->requestHeaders; - $proxy->soap_defencoding = $this->soap_defencoding; - $proxy->endpoint = $this->endpoint; - $proxy->forceEndpoint = $this->forceEndpoint; - return $proxy; - } - - /** - * dynamically creates proxy class code - * - * @return string PHP/NuSOAP code for the proxy class - * @access private - */ - function _getProxyClassCode($r) { - if ($this->endpointType != 'wsdl') { - $evalStr = 'A proxy can only be created for a WSDL client'; - $this->setError($evalStr); - return $evalStr; - } - $evalStr = ''; - foreach ($this->operations as $operation => $opData) { - if ($operation != '') { - // create param string and param comment string - if (sizeof($opData['input']['parts']) > 0) { - $paramStr = ''; - $paramArrayStr = ''; - $paramCommentStr = ''; - foreach ($opData['input']['parts'] as $name => $type) { - $paramStr .= "\$$name, "; - $paramArrayStr .= "'$name' => \$$name, "; - $paramCommentStr .= "$type \$$name, "; - } - $paramStr = substr($paramStr, 0, strlen($paramStr)-2); - $paramArrayStr = substr($paramArrayStr, 0, strlen($paramArrayStr)-2); - $paramCommentStr = substr($paramCommentStr, 0, strlen($paramCommentStr)-2); - } else { - $paramStr = ''; - $paramCommentStr = 'void'; - } - $opData['namespace'] = !isset($opData['namespace']) ? 'http://testuri.com' : $opData['namespace']; - $evalStr .= "// $paramCommentStr - function " . str_replace('.', '__', $operation) . "($paramStr) { - \$params = array($paramArrayStr); - return \$this->call('$operation', \$params, '".$opData['namespace']."', '".(isset($opData['soapAction']) ? $opData['soapAction'] : '')."'); - } - "; - unset($paramStr); - unset($paramCommentStr); - } - } - $evalStr = 'class soap_proxy_'.$r.' extends soapclient { - '.$evalStr.' -}'; - return $evalStr; - } - - /** - * dynamically creates proxy class code - * - * @return string PHP/NuSOAP code for the proxy class - * @access public - */ - function getProxyClassCode() { - $r = rand(); - return $this->_getProxyClassCode($r); - } - - /** - * gets the HTTP body for the current request. - * - * @param string $soapmsg The SOAP payload - * @return string The HTTP body, which includes the SOAP payload - * @access private - */ - function getHTTPBody($soapmsg) { - return $soapmsg; - } - - /** - * gets the HTTP content type for the current request. - * - * Note: getHTTPBody must be called before this. - * - * @return string the HTTP content type for the current request. - * @access private - */ - function getHTTPContentType() { - return 'text/xml'; - } - - /** - * gets the HTTP content type charset for the current request. - * returns false for non-text content types. - * - * Note: getHTTPBody must be called before this. - * - * @return string the HTTP content type charset for the current request. - * @access private - */ - function getHTTPContentTypeCharset() { - return $this->soap_defencoding; - } - - /* - * whether or not parser should decode utf8 element content - * - * @return always returns true - * @access public - */ - function decodeUTF8($bool){ - $this->decode_utf8 = $bool; - return true; - } - - /** - * adds a new Cookie into $this->cookies array - * - * @param string $name Cookie Name - * @param string $value Cookie Value - * @return if cookie-set was successful returns true, else false - * @access public - */ - function setCookie($name, $value) { - if (strlen($name) == 0) { - return false; - } - $this->cookies[] = array('name' => $name, 'value' => $value); - return true; - } - - /** - * gets all Cookies - * - * @return array with all internal cookies - * @access public - */ - function getCookies() { - return $this->cookies; - } - - /** - * checks all Cookies and delete those which are expired - * - * @return always return true - * @access private - */ - function checkCookies() { - if (sizeof($this->cookies) == 0) { - return true; - } - $this->debug('checkCookie: check ' . sizeof($this->cookies) . ' cookies'); - $curr_cookies = $this->cookies; - $this->cookies = array(); - foreach ($curr_cookies as $cookie) { - if (! is_array($cookie)) { - $this->debug('Remove cookie that is not an array'); - continue; - } - if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) { - if (strtotime($cookie['expires']) > time()) { - $this->cookies[] = $cookie; - } else { - $this->debug('Remove expired cookie ' . $cookie['name']); - } - } else { - $this->cookies[] = $cookie; - } - } - $this->debug('checkCookie: '.sizeof($this->cookies).' cookies left in array'); - return true; - } - - /** - * updates the current cookies with a new set - * - * @param array $cookies new cookies with which to update current ones - * @return always return true - * @access private - */ - function UpdateCookies($cookies) { - if (sizeof($this->cookies) == 0) { - // no existing cookies: take whatever is new - if (sizeof($cookies) > 0) { - $this->debug('Setting new cookie(s)'); - $this->cookies = $cookies; - } - return true; - } - if (sizeof($cookies) == 0) { - // no new cookies: keep what we've got - return true; - } - // merge - foreach ($cookies as $newCookie) { - if (!is_array($newCookie)) { - continue; - } - if ((!isset($newCookie['name'])) || (!isset($newCookie['value']))) { - continue; - } - $newName = $newCookie['name']; - - $found = false; - for ($i = 0; $i < count($this->cookies); $i++) { - $cookie = $this->cookies[$i]; - if (!is_array($cookie)) { - continue; - } - if (!isset($cookie['name'])) { - continue; - } - if ($newName != $cookie['name']) { - continue; - } - $newDomain = isset($newCookie['domain']) ? $newCookie['domain'] : 'NODOMAIN'; - $domain = isset($cookie['domain']) ? $cookie['domain'] : 'NODOMAIN'; - if ($newDomain != $domain) { - continue; - } - $newPath = isset($newCookie['path']) ? $newCookie['path'] : 'NOPATH'; - $path = isset($cookie['path']) ? $cookie['path'] : 'NOPATH'; - if ($newPath != $path) { - continue; - } - $this->cookies[$i] = $newCookie; - $found = true; - $this->debug('Update cookie ' . $newName . '=' . $newCookie['value']); - break; - } - if (! $found) { - $this->debug('Add cookie ' . $newName . '=' . $newCookie['value']); - $this->cookies[] = $newCookie; - } - } - return true; - } -} -?> diff --git a/gulliver/thirdparty/pear/nusoap.php b/gulliver/thirdparty/pear/nusoap.php deleted file mode 100644 index 32c1f2c30..000000000 --- a/gulliver/thirdparty/pear/nusoap.php +++ /dev/null @@ -1,7302 +0,0 @@ -globalDebugLevel = 9; - -/** -* -* nusoap_base -* -* @author Dietrich Ayala -* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class nusoap_base { - /** - * Identification for HTTP headers. - * - * @var string - * @access private - */ - var $title = 'NuSOAP'; - /** - * Version for HTTP headers. - * - * @var string - * @access private - */ - var $version = '0.7.2'; - /** - * CVS revision for HTTP headers. - * - * @var string - * @access private - */ - var $revision = '$Revision: 1.94 $'; - /** - * Current error string (manipulated by getError/setError) - * - * @var string - * @access private - */ - var $error_str = ''; - /** - * Current debug string (manipulated by debug/appendDebug/clearDebug/getDebug/getDebugAsXMLComment) - * - * @var string - * @access private - */ - var $debug_str = ''; - /** - * toggles automatic encoding of special characters as entities - * (should always be true, I think) - * - * @var boolean - * @access private - */ - var $charencoding = true; - /** - * the debug level for this instance - * - * @var integer - * @access private - */ - var $debugLevel; - - /** - * set schema version - * - * @var string - * @access public - */ - var $XMLSchemaVersion = 'http://www.w3.org/2001/XMLSchema'; - - /** - * charset encoding for outgoing messages - * - * @var string - * @access public - */ - var $soap_defencoding = 'ISO-8859-1'; - //var $soap_defencoding = 'UTF-8'; - - /** - * namespaces in an array of prefix => uri - * - * this is "seeded" by a set of constants, but it may be altered by code - * - * @var array - * @access public - */ - var $namespaces = array( - 'SOAP-ENV' => 'http://schemas.xmlsoap.org/soap/envelope/', - 'xsd' => 'http://www.w3.org/2001/XMLSchema', - 'xsi' => 'http://www.w3.org/2001/XMLSchema-instance', - 'SOAP-ENC' => 'http://schemas.xmlsoap.org/soap/encoding/' - ); - - /** - * namespaces used in the current context, e.g. during serialization - * - * @var array - * @access private - */ - var $usedNamespaces = array(); - - /** - * XML Schema types in an array of uri => (array of xml type => php type) - * is this legacy yet? - * no, this is used by the xmlschema class to verify type => namespace mappings. - * @var array - * @access public - */ - var $typemap = array( - 'http://www.w3.org/2001/XMLSchema' => array( - 'string'=>'string','boolean'=>'boolean','float'=>'double','double'=>'double','decimal'=>'double', - 'duration'=>'','dateTime'=>'string','time'=>'string','date'=>'string','gYearMonth'=>'', - 'gYear'=>'','gMonthDay'=>'','gDay'=>'','gMonth'=>'','hexBinary'=>'string','base64Binary'=>'string', - // abstract "any" types - 'anyType'=>'string','anySimpleType'=>'string', - // derived datatypes - 'normalizedString'=>'string','token'=>'string','language'=>'','NMTOKEN'=>'','NMTOKENS'=>'','Name'=>'','NCName'=>'','ID'=>'', - 'IDREF'=>'','IDREFS'=>'','ENTITY'=>'','ENTITIES'=>'','integer'=>'integer','nonPositiveInteger'=>'integer', - 'negativeInteger'=>'integer','long'=>'integer','int'=>'integer','short'=>'integer','byte'=>'integer','nonNegativeInteger'=>'integer', - 'unsignedLong'=>'','unsignedInt'=>'','unsignedShort'=>'','unsignedByte'=>'','positiveInteger'=>''), - 'http://www.w3.org/2000/10/XMLSchema' => array( - 'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double', - 'float'=>'double','dateTime'=>'string', - 'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'), - 'http://www.w3.org/1999/XMLSchema' => array( - 'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double', - 'float'=>'double','dateTime'=>'string', - 'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'), - 'http://soapinterop.org/xsd' => array('SOAPStruct'=>'struct'), - 'http://schemas.xmlsoap.org/soap/encoding/' => array('base64'=>'string','array'=>'array','Array'=>'array'), - 'http://xml.apache.org/xml-soap' => array('Map') - ); - - /** - * XML entities to convert - * - * @var array - * @access public - * @deprecated - * @see expandEntities - */ - var $xmlEntities = array('quot' => '"','amp' => '&', - 'lt' => '<','gt' => '>','apos' => "'"); - - /** - * constructor - * - * @access public - */ - function nusoap_base() { - $this->debugLevel = $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel; - } - - /** - * gets the global debug level, which applies to future instances - * - * @return integer Debug level 0-9, where 0 turns off - * @access public - */ - function getGlobalDebugLevel() { - return $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel; - } - - /** - * sets the global debug level, which applies to future instances - * - * @param int $level Debug level 0-9, where 0 turns off - * @access public - */ - function setGlobalDebugLevel($level) { - $GLOBALS['_transient']['static']['nusoap_base']->globalDebugLevel = $level; - } - - /** - * gets the debug level for this instance - * - * @return int Debug level 0-9, where 0 turns off - * @access public - */ - function getDebugLevel() { - return $this->debugLevel; - } - - /** - * sets the debug level for this instance - * - * @param int $level Debug level 0-9, where 0 turns off - * @access public - */ - function setDebugLevel($level) { - $this->debugLevel = $level; - } - - /** - * adds debug data to the instance debug string with formatting - * - * @param string $string debug data - * @access private - */ - function debug($string){ - if ($this->debugLevel > 0) { - $this->appendDebug($this->getmicrotime().' '.get_class($this).": $string\n"); - } - } - - /** - * adds debug data to the instance debug string without formatting - * - * @param string $string debug data - * @access public - */ - function appendDebug($string){ - if ($this->debugLevel > 0) { - // it would be nice to use a memory stream here to use - // memory more efficiently - $this->debug_str .= $string; - } - } - - /** - * clears the current debug data for this instance - * - * @access public - */ - function clearDebug() { - // it would be nice to use a memory stream here to use - // memory more efficiently - $this->debug_str = ''; - } - - /** - * gets the current debug data for this instance - * - * @return debug data - * @access public - */ - function &getDebug() { - // it would be nice to use a memory stream here to use - // memory more efficiently - return $this->debug_str; - } - - /** - * gets the current debug data for this instance as an XML comment - * this may change the contents of the debug data - * - * @return debug data as an XML comment - * @access public - */ - function &getDebugAsXMLComment() { - // it would be nice to use a memory stream here to use - // memory more efficiently - while (strpos($this->debug_str, '--')) { - $this->debug_str = str_replace('--', '- -', $this->debug_str); - } - return ""; - } - - /** - * expands entities, e.g. changes '<' to '<'. - * - * @param string $val The string in which to expand entities. - * @access private - */ - function expandEntities($val) { - if ($this->charencoding) { - $val = str_replace('&', '&', $val); - $val = str_replace("'", ''', $val); - $val = str_replace('"', '"', $val); - $val = str_replace('<', '<', $val); - $val = str_replace('>', '>', $val); - } - return $val; - } - - /** - * returns error string if present - * - * @return mixed error string or false - * @access public - */ - function getError(){ - if($this->error_str != ''){ - return $this->error_str; - } - return false; - } - - /** - * sets error string - * - * @return boolean $string error string - * @access private - */ - function setError($str){ - $this->error_str = $str; - } - - /** - * detect if array is a simple array or a struct (associative array) - * - * @param mixed $val The PHP array - * @return string (arraySimple|arrayStruct) - * @access private - */ - function isArraySimpleOrStruct($val) { - $keyList = array_keys($val); - foreach ($keyList as $keyListValue) { - if (!is_int($keyListValue)) { - return 'arrayStruct'; - } - } - return 'arraySimple'; - } - - /** - * serializes PHP values in accordance w/ section 5. Type information is - * not serialized if $use == 'literal'. - * - * @param mixed $val The value to serialize - * @param string $name The name (local part) of the XML element - * @param string $type The XML schema type (local part) for the element - * @param string $name_ns The namespace for the name of the XML element - * @param string $type_ns The namespace for the type of the element - * @param array $attributes The attributes to serialize as name=>value pairs - * @param string $use The WSDL "use" (encoded|literal) - * @return string The serialized element, possibly with child elements - * @access public - */ - function serialize_val($val,$name=false,$type=false,$name_ns=false,$type_ns=false,$attributes=false,$use='encoded'){ - $this->debug("in serialize_val: name=$name, type=$type, name_ns=$name_ns, type_ns=$type_ns, use=$use"); - $this->appendDebug('value=' . $this->varDump($val)); - $this->appendDebug('attributes=' . $this->varDump($attributes)); - - if(is_object($val) && get_class($val) == 'soapval'){ - return $val->serialize($use); - } - // force valid name if necessary - if (is_numeric($name)) { - $name = '__numeric_' . $name; - } elseif (! $name) { - $name = 'noname'; - } - // if name has ns, add ns prefix to name - $xmlns = ''; - if($name_ns){ - $prefix = 'nu'.rand(1000,9999); - $name = $prefix.':'.$name; - $xmlns .= " xmlns:$prefix=\"$name_ns\""; - } - // if type is prefixed, create type prefix - if($type_ns != '' && $type_ns == $this->namespaces['xsd']){ - // need to fix this. shouldn't default to xsd if no ns specified - // w/o checking against typemap - $type_prefix = 'xsd'; - } elseif($type_ns){ - $type_prefix = 'ns'.rand(1000,9999); - $xmlns .= " xmlns:$type_prefix=\"$type_ns\""; - } - // serialize attributes if present - $atts = ''; - if($attributes){ - foreach($attributes as $k => $v){ - $atts .= " $k=\"".$this->expandEntities($v).'"'; - } - } - // serialize null value - if (is_null($val)) { - if ($use == 'literal') { - // TODO: depends on minOccurs - return "<$name$xmlns $atts/>"; - } else { - if (isset($type) && isset($type_prefix)) { - $type_str = " xsi:type=\"$type_prefix:$type\""; - } else { - $type_str = ''; - } - return "<$name$xmlns$type_str $atts xsi:nil=\"true\"/>"; - } - } - // serialize if an xsd built-in primitive type - if($type != '' && isset($this->typemap[$this->XMLSchemaVersion][$type])){ - if (is_bool($val)) { - if ($type == 'boolean') { - $val = $val ? 'true' : 'false'; - } elseif (! $val) { - $val = 0; - } - } else if (is_string($val)) { - $val = $this->expandEntities($val); - } - if ($use == 'literal') { - return "<$name$xmlns $atts>$val"; - } else { - return "<$name$xmlns $atts xsi:type=\"xsd:$type\">$val"; - } - } - // detect type and serialize - $xml = ''; - switch(true) { - case (is_bool($val) || $type == 'boolean'): - if ($type == 'boolean') { - $val = $val ? 'true' : 'false'; - } elseif (! $val) { - $val = 0; - } - if ($use == 'literal') { - $xml .= "<$name$xmlns $atts>$val"; - } else { - $xml .= "<$name$xmlns xsi:type=\"xsd:boolean\"$atts>$val"; - } - break; - case (is_int($val) || is_long($val) || $type == 'int'): - if ($use == 'literal') { - $xml .= "<$name$xmlns $atts>$val"; - } else { - $xml .= "<$name$xmlns xsi:type=\"xsd:int\"$atts>$val"; - } - break; - case (is_float($val)|| is_double($val) || $type == 'float'): - if ($use == 'literal') { - $xml .= "<$name$xmlns $atts>$val"; - } else { - $xml .= "<$name$xmlns xsi:type=\"xsd:float\"$atts>$val"; - } - break; - case (is_string($val) || $type == 'string'): - $val = $this->expandEntities($val); - if ($use == 'literal') { - $xml .= "<$name$xmlns $atts>$val"; - } else { - $xml .= "<$name$xmlns xsi:type=\"xsd:string\"$atts>$val"; - } - break; - case is_object($val): - if (! $name) { - $name = get_class($val); - $this->debug("In serialize_val, used class name $name as element name"); - } else { - $this->debug("In serialize_val, do not override name $name for element name for class " . get_class($val)); - } - foreach(get_object_vars($val) as $k => $v){ - $pXml = isset($pXml) ? $pXml.$this->serialize_val($v,$k,false,false,false,false,$use) : $this->serialize_val($v,$k,false,false,false,false,$use); - } - $xml .= '<'.$name.'>'.$pXml.''; - break; - break; - case (is_array($val) || $type): - // detect if struct or array - $valueType = $this->isArraySimpleOrStruct($val); - if($valueType=='arraySimple' || ereg('^ArrayOf',$type)){ - $i = 0; - if(is_array($val) && count($val)> 0){ - foreach($val as $v){ - if(is_object($v) && get_class($v) == 'soapval'){ - $tt_ns = $v->type_ns; - $tt = $v->type; - } elseif (is_array($v)) { - $tt = $this->isArraySimpleOrStruct($v); - } else { - $tt = gettype($v); - } - $array_types[$tt] = 1; - // TODO: for literal, the name should be $name - $xml .= $this->serialize_val($v,'item',false,false,false,false,$use); - ++$i; - } - if(count($array_types) > 1){ - $array_typename = 'xsd:anyType'; - } elseif(isset($tt) && isset($this->typemap[$this->XMLSchemaVersion][$tt])) { - if ($tt == 'integer') { - $tt = 'int'; - } - $array_typename = 'xsd:'.$tt; - } elseif(isset($tt) && $tt == 'arraySimple'){ - $array_typename = 'SOAP-ENC:Array'; - } elseif(isset($tt) && $tt == 'arrayStruct'){ - $array_typename = 'unnamed_struct_use_soapval'; - } else { - // if type is prefixed, create type prefix - if ($tt_ns != '' && $tt_ns == $this->namespaces['xsd']){ - $array_typename = 'xsd:' . $tt; - } elseif ($tt_ns) { - $tt_prefix = 'ns' . rand(1000, 9999); - $array_typename = "$tt_prefix:$tt"; - $xmlns .= " xmlns:$tt_prefix=\"$tt_ns\""; - } else { - $array_typename = $tt; - } - } - $array_type = $i; - if ($use == 'literal') { - $type_str = ''; - } else if (isset($type) && isset($type_prefix)) { - $type_str = " xsi:type=\"$type_prefix:$type\""; - } else { - $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"".$array_typename."[$array_type]\""; - } - // empty array - } else { - if ($use == 'literal') { - $type_str = ''; - } else if (isset($type) && isset($type_prefix)) { - $type_str = " xsi:type=\"$type_prefix:$type\""; - } else { - $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"xsd:anyType[0]\""; - } - } - // TODO: for array in literal, there is no wrapper here - $xml = "<$name$xmlns$type_str$atts>".$xml.""; - } else { - // got a struct - if(isset($type) && isset($type_prefix)){ - $type_str = " xsi:type=\"$type_prefix:$type\""; - } else { - $type_str = ''; - } - if ($use == 'literal') { - $xml .= "<$name$xmlns $atts>"; - } else { - $xml .= "<$name$xmlns$type_str$atts>"; - } - foreach($val as $k => $v){ - // Apache Map - if ($type == 'Map' && $type_ns == 'http://xml.apache.org/xml-soap') { - $xml .= ''; - $xml .= $this->serialize_val($k,'key',false,false,false,false,$use); - $xml .= $this->serialize_val($v,'value',false,false,false,false,$use); - $xml .= ''; - } else { - $xml .= $this->serialize_val($v,$k,false,false,false,false,$use); - } - } - $xml .= ""; - } - break; - default: - $xml .= 'not detected, got '.gettype($val).' for '.$val; - break; - } - return $xml; - } - - /** - * serializes a message - * - * @param string $body the XML of the SOAP body - * @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers - * @param array $namespaces optional the namespaces used in generating the body and headers - * @param string $style optional (rpc|document) - * @param string $use optional (encoded|literal) - * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded) - * @return string the message - * @access public - */ - function serializeEnvelope($body,$headers=false,$namespaces=array(),$style='rpc',$use='encoded',$encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'){ - // TODO: add an option to automatically run utf8_encode on $body and $headers - // if $this->soap_defencoding is UTF-8. Not doing this automatically allows - // one to send arbitrary UTF-8 characters, not just characters that map to ISO-8859-1 - - $this->debug("In serializeEnvelope length=" . strlen($body) . " body (max 1000 characters)=" . substr($body, 0, 1000) . " style=$style use=$use encodingStyle=$encodingStyle"); - $this->debug("headers:"); - $this->appendDebug($this->varDump($headers)); - $this->debug("namespaces:"); - $this->appendDebug($this->varDump($namespaces)); - - // serialize namespaces - $ns_string = ''; - foreach(array_merge($this->namespaces,$namespaces) as $k => $v){ - $ns_string .= " xmlns:$k=\"$v\""; - } - if($encodingStyle) { - $ns_string = " SOAP-ENV:encodingStyle=\"$encodingStyle\"$ns_string"; - } - - // serialize headers - if($headers){ - if (is_array($headers)) { - $xml = ''; - foreach ($headers as $header) { - $xml .= $this->serialize_val($header, false, false, false, false, false, $use); - } - $headers = $xml; - $this->debug("In serializeEnvelope, serialzied array of headers to $headers"); - } - $headers = "".$headers.""; - } - // serialize envelope - return - 'soap_defencoding .'"?'.">". - '". - $headers. - "". - $body. - "". - ""; - } - - /** - * formats a string to be inserted into an HTML stream - * - * @param string $str The string to format - * @return string The formatted string - * @access public - * @deprecated - */ - function formatDump($str){ - $str = htmlspecialchars($str); - return nl2br($str); - } - - /** - * contracts (changes namespace to prefix) a qualified name - * - * @param string $qname qname - * @return string contracted qname - * @access private - */ - function contractQname($qname){ - // get element namespace - //$this->xdebug("Contract $qname"); - if (strrpos($qname, ':')) { - // get unqualified name - $name = substr($qname, strrpos($qname, ':') + 1); - // get ns - $ns = substr($qname, 0, strrpos($qname, ':')); - $p = $this->getPrefixFromNamespace($ns); - if ($p) { - return $p . ':' . $name; - } - return $qname; - } else { - return $qname; - } - } - - /** - * expands (changes prefix to namespace) a qualified name - * - * @param string $string qname - * @return string expanded qname - * @access private - */ - function expandQname($qname){ - // get element prefix - if(strpos($qname,':') && !ereg('^http://',$qname)){ - // get unqualified name - $name = substr(strstr($qname,':'),1); - // get ns prefix - $prefix = substr($qname,0,strpos($qname,':')); - if(isset($this->namespaces[$prefix])){ - return $this->namespaces[$prefix].':'.$name; - } else { - return $qname; - } - } else { - return $qname; - } - } - - /** - * returns the local part of a prefixed string - * returns the original string, if not prefixed - * - * @param string $str The prefixed string - * @return string The local part - * @access public - */ - function getLocalPart($str){ - if($sstr = strrchr($str,':')){ - // get unqualified name - return substr( $sstr, 1 ); - } else { - return $str; - } - } - - /** - * returns the prefix part of a prefixed string - * returns false, if not prefixed - * - * @param string $str The prefixed string - * @return mixed The prefix or false if there is no prefix - * @access public - */ - function getPrefix($str){ - if($pos = strrpos($str,':')){ - // get prefix - return substr($str,0,$pos); - } - return false; - } - - /** - * pass it a prefix, it returns a namespace - * - * @param string $prefix The prefix - * @return mixed The namespace, false if no namespace has the specified prefix - * @access public - */ - function getNamespaceFromPrefix($prefix){ - if (isset($this->namespaces[$prefix])) { - return $this->namespaces[$prefix]; - } - //$this->setError("No namespace registered for prefix '$prefix'"); - return false; - } - - /** - * returns the prefix for a given namespace (or prefix) - * or false if no prefixes registered for the given namespace - * - * @param string $ns The namespace - * @return mixed The prefix, false if the namespace has no prefixes - * @access public - */ - function getPrefixFromNamespace($ns) { - foreach ($this->namespaces as $p => $n) { - if ($ns == $n || $ns == $p) { - $this->usedNamespaces[$p] = $n; - return $p; - } - } - return false; - } - - /** - * returns the time in ODBC canonical form with microseconds - * - * @return string The time in ODBC canonical form with microseconds - * @access public - */ - function getmicrotime() { - if (function_exists('gettimeofday')) { - $tod = gettimeofday(); - $sec = $tod['sec']; - $usec = $tod['usec']; - } else { - $sec = time(); - $usec = 0; - } - return strftime('%Y-%m-%d %H:%M:%S', $sec) . '.' . sprintf('%06d', $usec); - } - - /** - * Returns a string with the output of var_dump - * - * @param mixed $data The variable to var_dump - * @return string The output of var_dump - * @access public - */ - function varDump($data) { - ob_start(); - - 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(); - $data = $filter->xssFilterHard($data); - - var_dump($data); - $ret_val = ob_get_contents(); - ob_end_clean(); - return $ret_val; - } -} - -// XML Schema Datatype Helper Functions - -//xsd:dateTime helpers - -/** -* convert unix timestamp to ISO 8601 compliant date string -* -* @param string $timestamp Unix time stamp -* @access public -*/ -function timestamp_to_iso8601($timestamp,$utc=true){ - $datestr = date('Y-m-d\TH:i:sO',$timestamp); - if($utc){ - $eregStr = - '([0-9]{4})-'. // centuries & years CCYY- - '([0-9]{2})-'. // months MM- - '([0-9]{2})'. // days DD - 'T'. // separator T - '([0-9]{2}):'. // hours hh: - '([0-9]{2}):'. // minutes mm: - '([0-9]{2})(\.[0-9]*)?'. // seconds ss.ss... - '(Z|[+\-][0-9]{2}:?[0-9]{2})?'; // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's - - if(ereg($eregStr,$datestr,$regs)){ - return sprintf('%04d-%02d-%02dT%02d:%02d:%02dZ',$regs[1],$regs[2],$regs[3],$regs[4],$regs[5],$regs[6]); - } - return false; - } else { - return $datestr; - } -} - -/** -* convert ISO 8601 compliant date string to unix timestamp -* -* @param string $datestr ISO 8601 compliant date string -* @access public -*/ -function iso8601_to_timestamp($datestr){ - $eregStr = - '([0-9]{4})-'. // centuries & years CCYY- - '([0-9]{2})-'. // months MM- - '([0-9]{2})'. // days DD - 'T'. // separator T - '([0-9]{2}):'. // hours hh: - '([0-9]{2}):'. // minutes mm: - '([0-9]{2})(\.[0-9]+)?'. // seconds ss.ss... - '(Z|[+\-][0-9]{2}:?[0-9]{2})?'; // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's - if(ereg($eregStr,$datestr,$regs)){ - // not utc - if($regs[8] != 'Z'){ - $op = substr($regs[8],0,1); - $h = substr($regs[8],1,2); - $m = substr($regs[8],strlen($regs[8])-2,2); - if($op == '-'){ - $regs[4] = $regs[4] + $h; - $regs[5] = $regs[5] + $m; - } elseif($op == '+'){ - $regs[4] = $regs[4] - $h; - $regs[5] = $regs[5] - $m; - } - } - return strtotime("$regs[1]-$regs[2]-$regs[3] $regs[4]:$regs[5]:$regs[6]Z"); - } else { - return false; - } -} - -/** -* sleeps some number of microseconds -* -* @param string $usec the number of microseconds to sleep -* @access public -* @deprecated -*/ -function usleepWindows($usec) -{ - $start = gettimeofday(); - - do - { - $stop = gettimeofday(); - $timePassed = 1000000 * ($stop['sec'] - $start['sec']) - + $stop['usec'] - $start['usec']; - } - while ($timePassed < $usec); -} - -?> -* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class soap_fault extends nusoap_base { - /** - * The fault code (client|server) - * @var string - * @access private - */ - var $faultcode; - /** - * The fault actor - * @var string - * @access private - */ - var $faultactor; - /** - * The fault string, a description of the fault - * @var string - * @access private - */ - var $faultstring; - /** - * The fault detail, typically a string or array of string - * @var mixed - * @access private - */ - var $faultdetail; - - /** - * constructor - * - * @param string $faultcode (client | server) - * @param string $faultactor only used when msg routed between multiple actors - * @param string $faultstring human readable error message - * @param mixed $faultdetail detail, typically a string or array of string - */ - function soap_fault($faultcode,$faultactor='',$faultstring='',$faultdetail=''){ - parent::nusoap_base(); - $this->faultcode = $faultcode; - $this->faultactor = $faultactor; - $this->faultstring = $faultstring; - $this->faultdetail = $faultdetail; - } - - /** - * serialize a fault - * - * @return string The serialization of the fault instance. - * @access public - */ - function serialize(){ - $ns_string = ''; - foreach($this->namespaces as $k => $v){ - $ns_string .= "\n xmlns:$k=\"$v\""; - } - $return_msg = - 'soap_defencoding.'"?>'. - '\n". - ''. - ''. - $this->serialize_val($this->faultcode, 'faultcode'). - $this->serialize_val($this->faultactor, 'faultactor'). - $this->serialize_val($this->faultstring, 'faultstring'). - $this->serialize_val($this->faultdetail, 'detail'). - ''. - ''. - ''; - return $return_msg; - } -} - - - -?> -* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class XMLSchema extends nusoap_base { - - // files - var $schema = ''; - var $xml = ''; - // namespaces - var $enclosingNamespaces; - // schema info - var $schemaInfo = array(); - var $schemaTargetNamespace = ''; - // types, elements, attributes defined by the schema - var $attributes = array(); - var $complexTypes = array(); - var $complexTypeStack = array(); - var $currentComplexType = null; - var $elements = array(); - var $elementStack = array(); - var $currentElement = null; - var $simpleTypes = array(); - var $simpleTypeStack = array(); - var $currentSimpleType = null; - // imports - var $imports = array(); - // parser vars - var $parser; - var $position = 0; - var $depth = 0; - var $depth_array = array(); - var $message = array(); - var $defaultNamespace = array(); - - /** - * constructor - * - * @param string $schema schema document URI - * @param string $xml xml document URI - * @param string $namespaces namespaces defined in enclosing XML - * @access public - */ - function XMLSchema($schema='',$xml='',$namespaces=array()){ - parent::nusoap_base(); - $this->debug('xmlschema class instantiated, inside constructor'); - // files - $this->schema = $schema; - $this->xml = $xml; - - // namespaces - $this->enclosingNamespaces = $namespaces; - $this->namespaces = array_merge($this->namespaces, $namespaces); - - // parse schema file - if($schema != ''){ - $this->debug('initial schema file: '.$schema); - $this->parseFile($schema, 'schema'); - } - - // parse xml file - if($xml != ''){ - $this->debug('initial xml file: '.$xml); - $this->parseFile($xml, 'xml'); - } - - } - - /** - * parse an XML file - * - * @param string $xml, path/URL to XML file - * @param string $type, (schema | xml) - * @return boolean - * @access public - */ - function parseFile($xml,$type){ - // parse xml file - if($xml != ""){ - $xmlStr = @join("",@file($xml)); - if($xmlStr == ""){ - $msg = 'Error reading XML from '.$xml; - $this->setError($msg); - $this->debug($msg); - return false; - } else { - $this->debug("parsing $xml"); - $this->parseString($xmlStr,$type); - $this->debug("done parsing $xml"); - return true; - } - } - return false; - } - - /** - * parse an XML string - * - * @param string $xml path or URL - * @param string $type, (schema|xml) - * @access private - */ - function parseString($xml,$type){ - // parse xml string - if($xml != ""){ - - // Create an XML parser. - $this->parser = xml_parser_create(); - // Set the options for parsing the XML data. - xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); - - // Set the object for the parser. - xml_set_object($this->parser, $this); - - // Set the element handlers for the parser. - if($type == "schema"){ - xml_set_element_handler($this->parser, 'schemaStartElement','schemaEndElement'); - xml_set_character_data_handler($this->parser,'schemaCharacterData'); - } elseif($type == "xml"){ - xml_set_element_handler($this->parser, 'xmlStartElement','xmlEndElement'); - xml_set_character_data_handler($this->parser,'xmlCharacterData'); - } - - // Parse the XML file. - if(!xml_parse($this->parser,$xml,true)){ - // Display an error message. - $errstr = sprintf('XML error parsing XML schema on line %d: %s', - xml_get_current_line_number($this->parser), - xml_error_string(xml_get_error_code($this->parser)) - ); - $this->debug($errstr); - $this->debug("XML payload:\n" . $xml); - $this->setError($errstr); - } - - xml_parser_free($this->parser); - } else{ - $this->debug('no xml passed to parseString()!!'); - $this->setError('no xml passed to parseString()!!'); - } - } - - /** - * start-element handler - * - * @param string $parser XML parser object - * @param string $name element name - * @param string $attrs associative array of attributes - * @access private - */ - function schemaStartElement($parser, $name, $attrs) { - - // position in the total number of elements, starting from 0 - $pos = $this->position++; - $depth = $this->depth++; - // set self as current value for this depth - $this->depth_array[$depth] = $pos; - $this->message[$pos] = array('cdata' => ''); - if ($depth > 0) { - $this->defaultNamespace[$pos] = $this->defaultNamespace[$this->depth_array[$depth - 1]]; - } else { - $this->defaultNamespace[$pos] = false; - } - - // get element prefix - if($prefix = $this->getPrefix($name)){ - // get unqualified name - $name = $this->getLocalPart($name); - } else { - $prefix = ''; - } - - // loop thru attributes, expanding, and registering namespace declarations - if(count($attrs) > 0){ - foreach($attrs as $k => $v){ - // if ns declarations, add to class level array of valid namespaces - if(ereg("^xmlns",$k)){ - //$this->xdebug("$k: $v"); - //$this->xdebug('ns_prefix: '.$this->getPrefix($k)); - if($ns_prefix = substr(strrchr($k,':'),1)){ - //$this->xdebug("Add namespace[$ns_prefix] = $v"); - $this->namespaces[$ns_prefix] = $v; - } else { - $this->defaultNamespace[$pos] = $v; - if (! $this->getPrefixFromNamespace($v)) { - $this->namespaces['ns'.(count($this->namespaces)+1)] = $v; - } - } - if($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema'){ - $this->XMLSchemaVersion = $v; - $this->namespaces['xsi'] = $v.'-instance'; - } - } - } - foreach($attrs as $k => $v){ - // expand each attribute - $k = strpos($k,':') ? $this->expandQname($k) : $k; - $v = strpos($v,':') ? $this->expandQname($v) : $v; - $eAttrs[$k] = $v; - } - $attrs = $eAttrs; - } else { - $attrs = array(); - } - // find status, register data - switch($name){ - case 'all': // (optional) compositor content for a complexType - case 'choice': - case 'group': - case 'sequence': - //$this->xdebug("compositor $name for currentComplexType: $this->currentComplexType and currentElement: $this->currentElement"); - $this->complexTypes[$this->currentComplexType]['compositor'] = $name; - //if($name == 'all' || $name == 'sequence'){ - // $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct'; - //} - break; - case 'attribute': // complexType attribute - //$this->xdebug("parsing attribute $attrs[name] $attrs[ref] of value: ".$attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']); - $this->xdebug("parsing attribute:"); - $this->appendDebug($this->varDump($attrs)); - if (!isset($attrs['form'])) { - $attrs['form'] = $this->schemaInfo['attributeFormDefault']; - } - if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) { - $v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; - if (!strpos($v, ':')) { - // no namespace in arrayType attribute value... - if ($this->defaultNamespace[$pos]) { - // ...so use the default - $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'] = $this->defaultNamespace[$pos] . ':' . $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; - } - } - } - if(isset($attrs['name'])){ - $this->attributes[$attrs['name']] = $attrs; - $aname = $attrs['name']; - } elseif(isset($attrs['ref']) && $attrs['ref'] == 'http://schemas.xmlsoap.org/soap/encoding/:arrayType'){ - if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) { - $aname = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; - } else { - $aname = ''; - } - } elseif(isset($attrs['ref'])){ - $aname = $attrs['ref']; - $this->attributes[$attrs['ref']] = $attrs; - } - - if($this->currentComplexType){ // This should *always* be - $this->complexTypes[$this->currentComplexType]['attrs'][$aname] = $attrs; - } - // arrayType attribute - if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']) || $this->getLocalPart($aname) == 'arrayType'){ - $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; - $prefix = $this->getPrefix($aname); - if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])){ - $v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; - } else { - $v = ''; - } - if(strpos($v,'[,]')){ - $this->complexTypes[$this->currentComplexType]['multidimensional'] = true; - } - $v = substr($v,0,strpos($v,'[')); // clip the [] - if(!strpos($v,':') && isset($this->typemap[$this->XMLSchemaVersion][$v])){ - $v = $this->XMLSchemaVersion.':'.$v; - } - $this->complexTypes[$this->currentComplexType]['arrayType'] = $v; - } - break; - case 'complexContent': // (optional) content for a complexType - break; - case 'complexType': - array_push($this->complexTypeStack, $this->currentComplexType); - if(isset($attrs['name'])){ - $this->xdebug('processing named complexType '.$attrs['name']); - //$this->currentElement = false; - $this->currentComplexType = $attrs['name']; - $this->complexTypes[$this->currentComplexType] = $attrs; - $this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType'; - // This is for constructs like - // - // - // - // - // - if(isset($attrs['base']) && ereg(':Array$',$attrs['base'])){ - $this->xdebug('complexType is unusual array'); - $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; - } else { - $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct'; - } - }else{ - $this->xdebug('processing unnamed complexType for element '.$this->currentElement); - $this->currentComplexType = $this->currentElement . '_ContainedType'; - //$this->currentElement = false; - $this->complexTypes[$this->currentComplexType] = $attrs; - $this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType'; - // This is for constructs like - // - // - // - // - // - if(isset($attrs['base']) && ereg(':Array$',$attrs['base'])){ - $this->xdebug('complexType is unusual array'); - $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; - } else { - $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct'; - } - } - break; - case 'element': - array_push($this->elementStack, $this->currentElement); - // elements defined as part of a complex type should - // not really be added to $this->elements, but for some - // reason, they are - if (!isset($attrs['form'])) { - $attrs['form'] = $this->schemaInfo['elementFormDefault']; - } - if(isset($attrs['type'])){ - $this->xdebug("processing typed element ".$attrs['name']." of type ".$attrs['type']); - if (! $this->getPrefix($attrs['type'])) { - if ($this->defaultNamespace[$pos]) { - $attrs['type'] = $this->defaultNamespace[$pos] . ':' . $attrs['type']; - $this->xdebug('used default namespace to make type ' . $attrs['type']); - } - } - // This is for constructs like - // - // - // - // - // - if ($this->currentComplexType && $this->complexTypes[$this->currentComplexType]['phpType'] == 'array') { - $this->xdebug('arrayType for unusual array is ' . $attrs['type']); - $this->complexTypes[$this->currentComplexType]['arrayType'] = $attrs['type']; - } - $this->currentElement = $attrs['name']; - $this->elements[ $attrs['name'] ] = $attrs; - $this->elements[ $attrs['name'] ]['typeClass'] = 'element'; - $ename = $attrs['name']; - } elseif(isset($attrs['ref'])){ - $this->xdebug("processing element as ref to ".$attrs['ref']); - $this->currentElement = "ref to ".$attrs['ref']; - $ename = $this->getLocalPart($attrs['ref']); - } else { - $this->xdebug("processing untyped element ".$attrs['name']); - $this->currentElement = $attrs['name']; - $this->elements[ $attrs['name'] ] = $attrs; - $this->elements[ $attrs['name'] ]['typeClass'] = 'element'; - $attrs['type'] = $this->schemaTargetNamespace . ':' . $attrs['name'] . '_ContainedType'; - $this->elements[ $attrs['name'] ]['type'] = $attrs['type']; - $ename = $attrs['name']; - } - if(isset($ename) && $this->currentComplexType){ - $this->complexTypes[$this->currentComplexType]['elements'][$ename] = $attrs; - } - break; - case 'enumeration': // restriction value list member - $this->xdebug('enumeration ' . $attrs['value']); - if ($this->currentSimpleType) { - $this->simpleTypes[$this->currentSimpleType]['enumeration'][] = $attrs['value']; - } elseif ($this->currentComplexType) { - $this->complexTypes[$this->currentComplexType]['enumeration'][] = $attrs['value']; - } - break; - case 'extension': // simpleContent or complexContent type extension - $this->xdebug('extension ' . $attrs['base']); - if ($this->currentComplexType) { - $this->complexTypes[$this->currentComplexType]['extensionBase'] = $attrs['base']; - } - break; - case 'import': - if (isset($attrs['schemaLocation'])) { - //$this->xdebug('import namespace ' . $attrs['namespace'] . ' from ' . $attrs['schemaLocation']); - $this->imports[$attrs['namespace']][] = array('location' => $attrs['schemaLocation'], 'loaded' => false); - } else { - //$this->xdebug('import namespace ' . $attrs['namespace']); - $this->imports[$attrs['namespace']][] = array('location' => '', 'loaded' => true); - if (! $this->getPrefixFromNamespace($attrs['namespace'])) { - $this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace']; - } - } - break; - case 'list': // simpleType value list - break; - case 'restriction': // simpleType, simpleContent or complexContent value restriction - $this->xdebug('restriction ' . $attrs['base']); - if($this->currentSimpleType){ - $this->simpleTypes[$this->currentSimpleType]['type'] = $attrs['base']; - } elseif($this->currentComplexType){ - $this->complexTypes[$this->currentComplexType]['restrictionBase'] = $attrs['base']; - if(strstr($attrs['base'],':') == ':Array'){ - $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; - } - } - break; - case 'schema': - $this->schemaInfo = $attrs; - $this->schemaInfo['schemaVersion'] = $this->getNamespaceFromPrefix($prefix); - if (isset($attrs['targetNamespace'])) { - $this->schemaTargetNamespace = $attrs['targetNamespace']; - } - if (!isset($attrs['elementFormDefault'])) { - $this->schemaInfo['elementFormDefault'] = 'unqualified'; - } - if (!isset($attrs['attributeFormDefault'])) { - $this->schemaInfo['attributeFormDefault'] = 'unqualified'; - } - break; - case 'simpleContent': // (optional) content for a complexType - break; - case 'simpleType': - array_push($this->simpleTypeStack, $this->currentSimpleType); - if(isset($attrs['name'])){ - $this->xdebug("processing simpleType for name " . $attrs['name']); - $this->currentSimpleType = $attrs['name']; - $this->simpleTypes[ $attrs['name'] ] = $attrs; - $this->simpleTypes[ $attrs['name'] ]['typeClass'] = 'simpleType'; - $this->simpleTypes[ $attrs['name'] ]['phpType'] = 'scalar'; - } else { - $this->xdebug('processing unnamed simpleType for element '.$this->currentElement); - $this->currentSimpleType = $this->currentElement . '_ContainedType'; - //$this->currentElement = false; - $this->simpleTypes[$this->currentSimpleType] = $attrs; - $this->simpleTypes[$this->currentSimpleType]['phpType'] = 'scalar'; - } - break; - case 'union': // simpleType type list - break; - default: - //$this->xdebug("do not have anything to do for element $name"); - } - } - - /** - * end-element handler - * - * @param string $parser XML parser object - * @param string $name element name - * @access private - */ - function schemaEndElement($parser, $name) { - // bring depth down a notch - $this->depth--; - // position of current element is equal to the last value left in depth_array for my depth - if(isset($this->depth_array[$this->depth])){ - $pos = $this->depth_array[$this->depth]; - } - // get element prefix - if ($prefix = $this->getPrefix($name)){ - // get unqualified name - $name = $this->getLocalPart($name); - } else { - $prefix = ''; - } - // move on... - if($name == 'complexType'){ - $this->xdebug('done processing complexType ' . ($this->currentComplexType ? $this->currentComplexType : '(unknown)')); - $this->currentComplexType = array_pop($this->complexTypeStack); - //$this->currentElement = false; - } - if($name == 'element'){ - $this->xdebug('done processing element ' . ($this->currentElement ? $this->currentElement : '(unknown)')); - $this->currentElement = array_pop($this->elementStack); - } - if($name == 'simpleType'){ - $this->xdebug('done processing simpleType ' . ($this->currentSimpleType ? $this->currentSimpleType : '(unknown)')); - $this->currentSimpleType = array_pop($this->simpleTypeStack); - } - } - - /** - * element content handler - * - * @param string $parser XML parser object - * @param string $data element content - * @access private - */ - function schemaCharacterData($parser, $data){ - $pos = $this->depth_array[$this->depth - 1]; - $this->message[$pos]['cdata'] .= $data; - } - - /** - * serialize the schema - * - * @access public - */ - function serializeSchema(){ - - $schemaPrefix = $this->getPrefixFromNamespace($this->XMLSchemaVersion); - $xml = ''; - // imports - if (sizeof($this->imports) > 0) { - foreach($this->imports as $ns => $list) { - foreach ($list as $ii) { - if ($ii['location'] != '') { - $xml .= " <$schemaPrefix:import location=\"" . $ii['location'] . '" namespace="' . $ns . "\" />\n"; - } else { - $xml .= " <$schemaPrefix:import namespace=\"" . $ns . "\" />\n"; - } - } - } - } - // complex types - foreach($this->complexTypes as $typeName => $attrs){ - $contentStr = ''; - // serialize child elements - if(isset($attrs['elements']) && (count($attrs['elements']) > 0)){ - foreach($attrs['elements'] as $element => $eParts){ - if(isset($eParts['ref'])){ - $contentStr .= " <$schemaPrefix:element ref=\"$element\"/>\n"; - } else { - $contentStr .= " <$schemaPrefix:element name=\"$element\" type=\"" . $this->contractQName($eParts['type']) . "\""; - foreach ($eParts as $aName => $aValue) { - // handle, e.g., abstract, default, form, minOccurs, maxOccurs, nillable - if ($aName != 'name' && $aName != 'type') { - $contentStr .= " $aName=\"$aValue\""; - } - } - $contentStr .= "/>\n"; - } - } - // compositor wraps elements - if (isset($attrs['compositor']) && ($attrs['compositor'] != '')) { - $contentStr = " <$schemaPrefix:$attrs[compositor]>\n".$contentStr." \n"; - } - } - // attributes - if(isset($attrs['attrs']) && (count($attrs['attrs']) >= 1)){ - foreach($attrs['attrs'] as $attr => $aParts){ - $contentStr .= " <$schemaPrefix:attribute"; - foreach ($aParts as $a => $v) { - if ($a == 'ref' || $a == 'type') { - $contentStr .= " $a=\"".$this->contractQName($v).'"'; - } elseif ($a == 'http://schemas.xmlsoap.org/wsdl/:arrayType') { - $this->usedNamespaces['wsdl'] = $this->namespaces['wsdl']; - $contentStr .= ' wsdl:arrayType="'.$this->contractQName($v).'"'; - } else { - $contentStr .= " $a=\"$v\""; - } - } - $contentStr .= "/>\n"; - } - } - // if restriction - if (isset($attrs['restrictionBase']) && $attrs['restrictionBase'] != ''){ - $contentStr = " <$schemaPrefix:restriction base=\"".$this->contractQName($attrs['restrictionBase'])."\">\n".$contentStr." \n"; - // complex or simple content - if ((isset($attrs['elements']) && count($attrs['elements']) > 0) || (isset($attrs['attrs']) && count($attrs['attrs']) > 0)){ - $contentStr = " <$schemaPrefix:complexContent>\n".$contentStr." \n"; - } - } - // finalize complex type - if($contentStr != ''){ - $contentStr = " <$schemaPrefix:complexType name=\"$typeName\">\n".$contentStr." \n"; - } else { - $contentStr = " <$schemaPrefix:complexType name=\"$typeName\"/>\n"; - } - $xml .= $contentStr; - } - // simple types - if(isset($this->simpleTypes) && count($this->simpleTypes) > 0){ - foreach($this->simpleTypes as $typeName => $eParts){ - $xml .= " <$schemaPrefix:simpleType name=\"$typeName\">\n <$schemaPrefix:restriction base=\"".$this->contractQName($eParts['type'])."\"/>\n"; - if (isset($eParts['enumeration'])) { - foreach ($eParts['enumeration'] as $e) { - $xml .= " <$schemaPrefix:enumeration value=\"$e\"/>\n"; - } - } - $xml .= " "; - } - } - // elements - if(isset($this->elements) && count($this->elements) > 0){ - foreach($this->elements as $element => $eParts){ - $xml .= " <$schemaPrefix:element name=\"$element\" type=\"".$this->contractQName($eParts['type'])."\"/>\n"; - } - } - // attributes - if(isset($this->attributes) && count($this->attributes) > 0){ - foreach($this->attributes as $attr => $aParts){ - $xml .= " <$schemaPrefix:attribute name=\"$attr\" type=\"".$this->contractQName($aParts['type'])."\"\n/>"; - } - } - // finish 'er up - $el = "<$schemaPrefix:schema targetNamespace=\"$this->schemaTargetNamespace\"\n"; - foreach (array_diff($this->usedNamespaces, $this->enclosingNamespaces) as $nsp => $ns) { - $el .= " xmlns:$nsp=\"$ns\"\n"; - } - $xml = $el . ">\n".$xml."\n"; - return $xml; - } - - /** - * adds debug data to the clas level debug string - * - * @param string $string debug data - * @access private - */ - function xdebug($string){ - $this->debug('<' . $this->schemaTargetNamespace . '> '.$string); - } - - /** - * get the PHP type of a user defined type in the schema - * PHP type is kind of a misnomer since it actually returns 'struct' for assoc. arrays - * returns false if no type exists, or not w/ the given namespace - * else returns a string that is either a native php type, or 'struct' - * - * @param string $type, name of defined type - * @param string $ns, namespace of type - * @return mixed - * @access public - * @deprecated - */ - function getPHPType($type,$ns){ - if(isset($this->typemap[$ns][$type])){ - //print "found type '$type' and ns $ns in typemap
"; - return $this->typemap[$ns][$type]; - } elseif(isset($this->complexTypes[$type])){ - //print "getting type '$type' and ns $ns from complexTypes array
"; - return $this->complexTypes[$type]['phpType']; - } - return false; - } - - /** - * returns an associative array of information about a given type - * returns false if no type exists by the given name - * - * For a complexType typeDef = array( - * 'restrictionBase' => '', - * 'phpType' => '', - * 'compositor' => '(sequence|all)', - * 'elements' => array(), // refs to elements array - * 'attrs' => array() // refs to attributes array - * ... and so on (see addComplexType) - * ) - * - * For simpleType or element, the array has different keys. - * - * @param string - * @return mixed - * @access public - * @see addComplexType - * @see addSimpleType - * @see addElement - */ - function getTypeDef($type){ - //$this->debug("in getTypeDef for type $type"); - if(isset($this->complexTypes[$type])){ - $this->xdebug("in getTypeDef, found complexType $type"); - return $this->complexTypes[$type]; - } elseif(isset($this->simpleTypes[$type])){ - $this->xdebug("in getTypeDef, found simpleType $type"); - if (!isset($this->simpleTypes[$type]['phpType'])) { - // get info for type to tack onto the simple type - // TODO: can this ever really apply (i.e. what is a simpleType really?) - $uqType = substr($this->simpleTypes[$type]['type'], strrpos($this->simpleTypes[$type]['type'], ':') + 1); - $ns = substr($this->simpleTypes[$type]['type'], 0, strrpos($this->simpleTypes[$type]['type'], ':')); - $etype = $this->getTypeDef($uqType); - if ($etype) { - $this->xdebug("in getTypeDef, found type for simpleType $type:"); - $this->xdebug($this->varDump($etype)); - if (isset($etype['phpType'])) { - $this->simpleTypes[$type]['phpType'] = $etype['phpType']; - } - if (isset($etype['elements'])) { - $this->simpleTypes[$type]['elements'] = $etype['elements']; - } - } - } - return $this->simpleTypes[$type]; - } elseif(isset($this->elements[$type])){ - $this->xdebug("in getTypeDef, found element $type"); - if (!isset($this->elements[$type]['phpType'])) { - // get info for type to tack onto the element - $uqType = substr($this->elements[$type]['type'], strrpos($this->elements[$type]['type'], ':') + 1); - $ns = substr($this->elements[$type]['type'], 0, strrpos($this->elements[$type]['type'], ':')); - $etype = $this->getTypeDef($uqType); - if ($etype) { - $this->xdebug("in getTypeDef, found type for element $type:"); - $this->xdebug($this->varDump($etype)); - if (isset($etype['phpType'])) { - $this->elements[$type]['phpType'] = $etype['phpType']; - } - if (isset($etype['elements'])) { - $this->elements[$type]['elements'] = $etype['elements']; - } - } elseif ($ns == 'http://www.w3.org/2001/XMLSchema') { - $this->xdebug("in getTypeDef, element $type is an XSD type"); - $this->elements[$type]['phpType'] = 'scalar'; - } - } - return $this->elements[$type]; - } elseif(isset($this->attributes[$type])){ - $this->xdebug("in getTypeDef, found attribute $type"); - return $this->attributes[$type]; - } elseif (ereg('_ContainedType$', $type)) { - $this->xdebug("in getTypeDef, have an untyped element $type"); - $typeDef['typeClass'] = 'simpleType'; - $typeDef['phpType'] = 'scalar'; - $typeDef['type'] = 'http://www.w3.org/2001/XMLSchema:string'; - return $typeDef; - } - $this->xdebug("in getTypeDef, did not find $type"); - return false; - } - - /** - * returns a sample serialization of a given type, or false if no type by the given name - * - * @param string $type, name of type - * @return mixed - * @access public - * @deprecated - */ - function serializeTypeDef($type){ - //print "in sTD() for type $type
"; - if($typeDef = $this->getTypeDef($type)){ - $str .= '<'.$type; - if(is_array($typeDef['attrs'])){ - foreach($attrs as $attName => $data){ - $str .= " $attName=\"{type = ".$data['type']."}\""; - } - } - $str .= " xmlns=\"".$this->schema['targetNamespace']."\""; - if(count($typeDef['elements']) > 0){ - $str .= ">"; - foreach($typeDef['elements'] as $element => $eData){ - $str .= $this->serializeTypeDef($element); - } - $str .= ""; - } elseif($typeDef['typeClass'] == 'element') { - $str .= ">"; - } else { - $str .= "/>"; - } - return $str; - } - return false; - } - - /** - * returns HTML form elements that allow a user - * to enter values for creating an instance of the given type. - * - * @param string $name, name for type instance - * @param string $type, name of type - * @return string - * @access public - * @deprecated - */ - function typeToForm($name,$type){ - // get typedef - if($typeDef = $this->getTypeDef($type)){ - // if struct - if($typeDef['phpType'] == 'struct'){ - $buffer .= ''; - foreach($typeDef['elements'] as $child => $childDef){ - $buffer .= " - - "; - } - $buffer .= '
$childDef[name] (type: ".$this->getLocalPart($childDef['type'])."):
'; - // if array - } elseif($typeDef['phpType'] == 'array'){ - $buffer .= ''; - for($i=0;$i < 3; $i++){ - $buffer .= " - - "; - } - $buffer .= '
array item (type: $typeDef[arrayType]):
'; - // if scalar - } else { - $buffer .= ""; - } - } else { - $buffer .= ""; - } - return $buffer; - } - - /** - * adds a complex type to the schema - * - * example: array - * - * addType( - * 'ArrayOfstring', - * 'complexType', - * 'array', - * '', - * 'SOAP-ENC:Array', - * array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'string[]'), - * 'xsd:string' - * ); - * - * example: PHP associative array ( SOAP Struct ) - * - * addType( - * 'SOAPStruct', - * 'complexType', - * 'struct', - * 'all', - * array('myVar'=> array('name'=>'myVar','type'=>'string') - * ); - * - * @param name - * @param typeClass (complexType|simpleType|attribute) - * @param phpType: currently supported are array and struct (php assoc array) - * @param compositor (all|sequence|choice) - * @param restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) - * @param elements = array ( name = array(name=>'',type=>'') ) - * @param attrs = array( - * array( - * 'ref' => "http://schemas.xmlsoap.org/soap/encoding/:arrayType", - * "http://schemas.xmlsoap.org/wsdl/:arrayType" => "string[]" - * ) - * ) - * @param arrayType: namespace:name (http://www.w3.org/2001/XMLSchema:string) - * @access public - * @see getTypeDef - */ - function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType=''){ - $this->complexTypes[$name] = array( - 'name' => $name, - 'typeClass' => $typeClass, - 'phpType' => $phpType, - 'compositor'=> $compositor, - 'restrictionBase' => $restrictionBase, - 'elements' => $elements, - 'attrs' => $attrs, - 'arrayType' => $arrayType - ); - - $this->xdebug("addComplexType $name:"); - $this->appendDebug($this->varDump($this->complexTypes[$name])); - } - - /** - * adds a simple type to the schema - * - * @param string $name - * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) - * @param string $typeClass (should always be simpleType) - * @param string $phpType (should always be scalar) - * @param array $enumeration array of values - * @access public - * @see xmlschema - * @see getTypeDef - */ - function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) { - $this->simpleTypes[$name] = array( - 'name' => $name, - 'typeClass' => $typeClass, - 'phpType' => $phpType, - 'type' => $restrictionBase, - 'enumeration' => $enumeration - ); - - $this->xdebug("addSimpleType $name:"); - $this->appendDebug($this->varDump($this->simpleTypes[$name])); - } - - /** - * adds an element to the schema - * - * @param array $attrs attributes that must include name and type - * @see xmlschema - * @access public - */ - function addElement($attrs) { - if (! $this->getPrefix($attrs['type'])) { - $attrs['type'] = $this->schemaTargetNamespace . ':' . $attrs['type']; - } - $this->elements[ $attrs['name'] ] = $attrs; - $this->elements[ $attrs['name'] ]['typeClass'] = 'element'; - - $this->xdebug("addElement " . $attrs['name']); - $this->appendDebug($this->varDump($this->elements[ $attrs['name'] ])); - } -} - - - -?> -* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class soapval extends nusoap_base { - /** - * The XML element name - * - * @var string - * @access private - */ - var $name; - /** - * The XML type name (string or false) - * - * @var mixed - * @access private - */ - var $type; - /** - * The PHP value - * - * @var mixed - * @access private - */ - var $value; - /** - * The XML element namespace (string or false) - * - * @var mixed - * @access private - */ - var $element_ns; - /** - * The XML type namespace (string or false) - * - * @var mixed - * @access private - */ - var $type_ns; - /** - * The XML element attributes (array or false) - * - * @var mixed - * @access private - */ - var $attributes; - - /** - * constructor - * - * @param string $name optional name - * @param mixed $type optional type name - * @param mixed $value optional value - * @param mixed $element_ns optional namespace of value - * @param mixed $type_ns optional namespace of type - * @param mixed $attributes associative array of attributes to add to element serialization - * @access public - */ - function soapval($name='soapval',$type=false,$value=-1,$element_ns=false,$type_ns=false,$attributes=false) { - parent::nusoap_base(); - $this->name = $name; - $this->type = $type; - $this->value = $value; - $this->element_ns = $element_ns; - $this->type_ns = $type_ns; - $this->attributes = $attributes; - } - - /** - * return serialized value - * - * @param string $use The WSDL use value (encoded|literal) - * @return string XML data - * @access public - */ - function serialize($use='encoded') { - return $this->serialize_val($this->value,$this->name,$this->type,$this->element_ns,$this->type_ns,$this->attributes,$use); - } - - /** - * decodes a soapval object into a PHP native type - * - * @return mixed - * @access public - */ - function decode(){ - return $this->value; - } -} - - - -?> -* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class soap_transport_http extends nusoap_base { - - var $url = ''; - var $uri = ''; - var $digest_uri = ''; - var $scheme = ''; - var $host = ''; - var $port = ''; - var $path = ''; - var $request_method = 'POST'; - var $protocol_version = '1.0'; - var $encoding = ''; - var $outgoing_headers = array(); - var $incoming_headers = array(); - var $incoming_cookies = array(); - var $outgoing_payload = ''; - var $incoming_payload = ''; - var $useSOAPAction = true; - var $persistentConnection = false; - var $ch = false; // cURL handle - var $username = ''; - var $password = ''; - var $authtype = ''; - var $digestRequest = array(); - var $certRequest = array(); // keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional) - // cainfofile: certificate authority file, e.g. '$pathToPemFiles/rootca.pem' - // sslcertfile: SSL certificate file, e.g. '$pathToPemFiles/mycert.pem' - // sslkeyfile: SSL key file, e.g. '$pathToPemFiles/mykey.pem' - // passphrase: SSL key password/passphrase - // verifypeer: default is 1 - // verifyhost: default is 1 - - /** - * constructor - */ - function soap_transport_http($url){ - parent::nusoap_base(); - $this->setURL($url); - ereg('\$Revisio' . 'n: ([^ ]+)', $this->revision, $rev); - $this->outgoing_headers['User-Agent'] = $this->title.'/'.$this->version.' ('.$rev[1].')'; - $this->debug('set User-Agent: ' . $this->outgoing_headers['User-Agent']); - } - - function setURL($url) { - $this->url = $url; - - $u = parse_url($url); - foreach($u as $k => $v){ - $this->debug("$k = $v"); - $this->$k = $v; - } - - // add any GET params to path - if(isset($u['query']) && $u['query'] != ''){ - $this->path .= '?' . $u['query']; - } - - // set default port - if(!isset($u['port'])){ - if($u['scheme'] == 'https'){ - $this->port = 443; - } else { - $this->port = 80; - } - } - - $this->uri = $this->path; - $this->digest_uri = $this->uri; - - // build headers - if (!isset($u['port'])) { - $this->outgoing_headers['Host'] = $this->host; - } else { - $this->outgoing_headers['Host'] = $this->host.':'.$this->port; - } - $this->debug('set Host: ' . $this->outgoing_headers['Host']); - - if (isset($u['user']) && $u['user'] != '') { - $this->setCredentials(urldecode($u['user']), isset($u['pass']) ? urldecode($u['pass']) : ''); - } - } - - function connect($connection_timeout=0,$response_timeout=30){ - // For PHP 4.3 with OpenSSL, change https scheme to ssl, then treat like - // "regular" socket. - // TODO: disabled for now because OpenSSL must be *compiled* in (not just - // loaded), and until PHP5 stream_get_wrappers is not available. -// if ($this->scheme == 'https') { -// if (version_compare(phpversion(), '4.3.0') >= 0) { -// if (extension_loaded('openssl')) { -// $this->scheme = 'ssl'; -// $this->debug('Using SSL over OpenSSL'); -// } -// } -// } - $this->debug("connect connection_timeout $connection_timeout, response_timeout $response_timeout, scheme $this->scheme, host $this->host, port $this->port"); - if ($this->scheme == 'http' || $this->scheme == 'ssl') { - // use persistent connection - if($this->persistentConnection && isset($this->fp) && is_resource($this->fp)){ - if (!feof($this->fp)) { - $this->debug('Re-use persistent connection'); - return true; - } - fclose($this->fp); - $this->debug('Closed persistent connection at EOF'); - } - - // munge host if using OpenSSL - if ($this->scheme == 'ssl') { - $host = 'ssl://' . $this->host; - } else { - $host = $this->host; - } - $this->debug('calling fsockopen with host ' . $host . ' connection_timeout ' . $connection_timeout); - - // open socket - if($connection_timeout > 0){ - $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str, $connection_timeout); - } else { - $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str); - } - - // test pointer - if(!$this->fp) { - $msg = 'Couldn\'t open socket connection to server ' . $this->url; - if ($this->errno) { - $msg .= ', Error ('.$this->errno.'): '.$this->error_str; - } else { - $msg .= ' prior to connect(). This is often a problem looking up the host name.'; - } - $this->debug($msg); - $this->setError($msg); - return false; - } - - // set response timeout - $this->debug('set response timeout to ' . $response_timeout); - socket_set_timeout( $this->fp, $response_timeout); - - $this->debug('socket connected'); - return true; - } else if ($this->scheme == 'https') { - if (!extension_loaded('curl')) { - $this->setError('CURL Extension, or OpenSSL extension w/ PHP version >= 4.3 is required for HTTPS'); - return false; - } - $this->debug('connect using https'); - // init CURL - $this->ch = curl_init(); - // set url - $hostURL = ($this->port != '') ? "https://$this->host:$this->port" : "https://$this->host"; - // add path - $hostURL .= $this->path; - curl_setopt($this->ch, CURLOPT_URL, $hostURL); - // follow location headers (re-directs) - curl_setopt($this->ch, CURLOPT_FOLLOWLOCATION, 1); - // ask for headers in the response output - curl_setopt($this->ch, CURLOPT_HEADER, 1); - // ask for the response output as the return value - curl_setopt($this->ch, CURLOPT_RETURNTRANSFER, 1); - // encode - // We manage this ourselves through headers and encoding -// if(function_exists('gzuncompress')){ -// curl_setopt($this->ch, CURLOPT_ENCODING, 'deflate'); -// } - // persistent connection - if ($this->persistentConnection) { - // The way we send data, we cannot use persistent connections, since - // there will be some "junk" at the end of our request. - //curl_setopt($this->ch, CURL_HTTP_VERSION_1_1, true); - $this->persistentConnection = false; - $this->outgoing_headers['Connection'] = 'close'; - $this->debug('set Connection: ' . $this->outgoing_headers['Connection']); - } - // set timeout - if ($connection_timeout != 0) { - curl_setopt($this->ch, CURLOPT_TIMEOUT, $connection_timeout); - } - // TODO: cURL has added a connection timeout separate from the response timeout - //if ($connection_timeout != 0) { - // curl_setopt($this->ch, CURLOPT_CONNECTIONTIMEOUT, $connection_timeout); - //} - //if ($response_timeout != 0) { - // curl_setopt($this->ch, CURLOPT_TIMEOUT, $response_timeout); - //} - - // recent versions of cURL turn on peer/host checking by default, - // while PHP binaries are not compiled with a default location for the - // CA cert bundle, so disable peer/host checking. -//curl_setopt($this->ch, CURLOPT_CAINFO, 'f:\php-4.3.2-win32\extensions\curl-ca-bundle.crt'); - curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 0); - curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 0); - - // support client certificates (thanks Tobias Boes, Doug Anarino, Eryan Ariobowo) - if ($this->authtype == 'certificate') { - //added by Onti - $this->debug('authtype == certificate'); - if (isset($this->certRequest['cainfofile'])) { - curl_setopt($this->ch, CURLOPT_CAINFO, $this->certRequest['cainfofile']); - } - if (isset($this->certRequest['verifypeer'])) { - curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, $this->certRequest['verifypeer']); - } else { - curl_setopt($this->ch, CURLOPT_SSL_VERIFYPEER, 1); - } - if (isset($this->certRequest['verifyhost'])) { - curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, $this->certRequest['verifyhost']); - } else { - curl_setopt($this->ch, CURLOPT_SSL_VERIFYHOST, 1); - } - if (isset($this->certRequest['sslcertfile'])) { - curl_setopt($this->ch, CURLOPT_SSLCERT, $this->certRequest['sslcertfile']); - } - if (isset($this->certRequest['sslkeyfile'])) { - curl_setopt($this->ch, CURLOPT_SSLKEY, $this->certRequest['sslkeyfile']); - } - if (isset($this->certRequest['passphrase'])) { - curl_setopt($this->ch, CURLOPT_SSLKEYPASSWD , $this->certRequest['passphrase']); - } - curl_setopt($this->ch, CURLOPT_VERBOSE , 1 ); - //$handle = fopen('/home/xfer/curl.log', "ab+"); - //fwrite ($handle, date('Y-m-d H:i:s')."\n\n"); - //curl_setopt($this->ch, CURLOPT_STDERR, $handle ); - } - $this->debug('cURL connection set up'); - return true; - } else { - $this->setError('Unknown scheme ' . $this->scheme); - $this->debug('Unknown scheme ' . $this->scheme); - return false; - } - } - - /** - * send the SOAP message via HTTP - * - * @param string $data message data - * @param integer $timeout set connection timeout in seconds - * @param integer $response_timeout set response timeout in seconds - * @param array $cookies cookies to send - * @return string data - * @access public - */ - function send($data, $timeout=0, $response_timeout=30, $cookies=NULL) { - - $this->debug('entered send() with data of length: '.strlen($data)); - - $this->tryagain = true; - $tries = 0; - while ($this->tryagain) { - $this->tryagain = false; - if ($tries++ < 2) { - // make connnection - if (!$this->connect($timeout, $response_timeout)){ - return false; - } - - // send request - if (!$this->sendRequest($data, $cookies)){ - return false; - } - - // get response - $respdata = $this->getResponse(); - } else { - $this->setError('Too many tries to get an OK response'); - } - } - $this->debug('end of send()'); - return $respdata; - } - - - /** - * send the SOAP message via HTTPS 1.0 using CURL - * - * @param string $msg message data - * @param integer $timeout set connection timeout in seconds - * @param integer $response_timeout set response timeout in seconds - * @param array $cookies cookies to send - * @return string data - * @access public - */ - function sendHTTPS($data, $timeout=0, $response_timeout=30, $cookies) { - return $this->send($data, $timeout, $response_timeout, $cookies); - } - - /** - * if authenticating, set user credentials here - * - * @param string $username - * @param string $password - * @param string $authtype (basic, digest, certificate) - * @param array $digestRequest (keys must be nonce, nc, realm, qop) - * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs) - * @access public - */ - function setCredentials($username, $password, $authtype = 'basic', $digestRequest = array(), $certRequest = array()) { - $this->debug("Set credentials for authtype $authtype"); - // cf. RFC 2617 - if ($authtype == 'basic') { - $this->outgoing_headers['Authorization'] = 'Basic '.base64_encode(str_replace(':','',$username).':'.$password); - } elseif ($authtype == 'digest') { - if (isset($digestRequest['nonce'])) { - $digestRequest['nc'] = isset($digestRequest['nc']) ? $digestRequest['nc']++ : 1; - - // calculate the Digest hashes (calculate code based on digest implementation found at: http://www.rassoc.com/gregr/weblog/stories/2002/07/09/webServicesSecurityHttpDigestAuthenticationWithoutActiveDirectory.html) - - // A1 = unq(username-value) ":" unq(realm-value) ":" passwd - $A1 = $username. ':' . (isset($digestRequest['realm']) ? $digestRequest['realm'] : '') . ':' . $password; - - // H(A1) = MD5(A1) - $HA1 = $this->encryptOld($A1); - - // A2 = Method ":" digest-uri-value - $A2 = 'POST:' . $this->digest_uri; - - // H(A2) - $HA2 = $this->encryptOld($A2); - - // KD(secret, data) = H(concat(secret, ":", data)) - // if qop == auth: - // request-digest = <"> < KD ( H(A1), unq(nonce-value) - // ":" nc-value - // ":" unq(cnonce-value) - // ":" unq(qop-value) - // ":" H(A2) - // ) <"> - // if qop is missing, - // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > <"> - - $unhashedDigest = ''; - $nonce = isset($digestRequest['nonce']) ? $digestRequest['nonce'] : ''; - $cnonce = $nonce; - if ($digestRequest['qop'] != '') { - $unhashedDigest = $HA1 . ':' . $nonce . ':' . sprintf("%08d", $digestRequest['nc']) . ':' . $cnonce . ':' . $digestRequest['qop'] . ':' . $HA2; - } else { - $unhashedDigest = $HA1 . ':' . $nonce . ':' . $HA2; - } - - $hashedDigest = $this->encryptOld($unhashedDigest); - - $this->outgoing_headers['Authorization'] = 'Digest username="' . $username . '", realm="' . $digestRequest['realm'] . '", nonce="' . $nonce . '", uri="' . $this->digest_uri . '", cnonce="' . $cnonce . '", nc=' . sprintf("%08x", $digestRequest['nc']) . ', qop="' . $digestRequest['qop'] . '", response="' . $hashedDigest . '"'; - } - } elseif ($authtype == 'certificate') { - $this->certRequest = $certRequest; - } - $this->username = $username; - $this->password = $password; - $this->authtype = $authtype; - $this->digestRequest = $digestRequest; - - if (isset($this->outgoing_headers['Authorization'])) { - $this->debug('set Authorization: ' . substr($this->outgoing_headers['Authorization'], 0, 12) . '...'); - } else { - $this->debug('Authorization header not set'); - } - } - - /** - * set the soapaction value - * - * @param string $soapaction - * @access public - */ - function setSOAPAction($soapaction) { - $this->outgoing_headers['SOAPAction'] = '"' . $soapaction . '"'; - $this->debug('set SOAPAction: ' . $this->outgoing_headers['SOAPAction']); - } - - /** - * use http encoding - * - * @param string $enc encoding style. supported values: gzip, deflate, or both - * @access public - */ - function setEncoding($enc='gzip, deflate') { - if (function_exists('gzdeflate')) { - $this->protocol_version = '1.1'; - $this->outgoing_headers['Accept-Encoding'] = $enc; - $this->debug('set Accept-Encoding: ' . $this->outgoing_headers['Accept-Encoding']); - if (!isset($this->outgoing_headers['Connection'])) { - $this->outgoing_headers['Connection'] = 'close'; - $this->persistentConnection = false; - $this->debug('set Connection: ' . $this->outgoing_headers['Connection']); - } - set_magic_quotes_runtime(0); - // deprecated - $this->encoding = $enc; - } - } - - /** - * set proxy info here - * - * @param string $proxyhost - * @param string $proxyport - * @param string $proxyusername - * @param string $proxypassword - * @access public - */ - function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '') { - $this->uri = $this->url; - $this->host = $proxyhost; - $this->port = $proxyport; - if ($proxyusername != '' && $proxypassword != '') { - $this->outgoing_headers['Proxy-Authorization'] = ' Basic '.base64_encode($proxyusername.':'.$proxypassword); - $this->debug('set Proxy-Authorization: ' . $this->outgoing_headers['Proxy-Authorization']); - } - } - - /** - * decode a string that is encoded w/ "chunked' transfer encoding - * as defined in RFC2068 19.4.6 - * - * @param string $buffer - * @param string $lb - * @returns string - * @access public - * @deprecated - */ - function decodeChunked($buffer, $lb){ - // length := 0 - $length = 0; - $new = ''; - - // read chunk-size, chunk-extension (if any) and CRLF - // get the position of the linebreak - $chunkend = strpos($buffer, $lb); - if ($chunkend == FALSE) { - $this->debug('no linebreak found in decodeChunked'); - return $new; - } - $temp = substr($buffer,0,$chunkend); - $chunk_size = hexdec( trim($temp) ); - $chunkstart = $chunkend + strlen($lb); - // while (chunk-size > 0) { - while ($chunk_size > 0) { - $this->debug("chunkstart: $chunkstart chunk_size: $chunk_size"); - $chunkend = strpos( $buffer, $lb, $chunkstart + $chunk_size); - - // Just in case we got a broken connection - if ($chunkend == FALSE) { - $chunk = substr($buffer,$chunkstart); - // append chunk-data to entity-body - $new .= $chunk; - $length += strlen($chunk); - break; - } - - // read chunk-data and CRLF - $chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart); - // append chunk-data to entity-body - $new .= $chunk; - // length := length + chunk-size - $length += strlen($chunk); - // read chunk-size and CRLF - $chunkstart = $chunkend + strlen($lb); - - $chunkend = strpos($buffer, $lb, $chunkstart) + strlen($lb); - if ($chunkend == FALSE) { - break; //Just in case we got a broken connection - } - $temp = substr($buffer,$chunkstart,$chunkend-$chunkstart); - $chunk_size = hexdec( trim($temp) ); - $chunkstart = $chunkend; - } - return $new; - } - - /* - * Writes payload, including HTTP headers, to $this->outgoing_payload. - */ - function buildPayload($data, $cookie_str = '') { - // add content-length header - $this->outgoing_headers['Content-Length'] = strlen($data); - $this->debug('set Content-Length: ' . $this->outgoing_headers['Content-Length']); - - // start building outgoing payload: - $req = "$this->request_method $this->uri HTTP/$this->protocol_version"; - $this->debug("HTTP request: $req"); - $this->outgoing_payload = "$req\r\n"; - - // loop thru headers, serializing - foreach($this->outgoing_headers as $k => $v){ - $hdr = $k.': '.$v; - $this->debug("HTTP header: $hdr"); - $this->outgoing_payload .= "$hdr\r\n"; - } - - // add any cookies - if ($cookie_str != '') { - $hdr = 'Cookie: '.$cookie_str; - $this->debug("HTTP header: $hdr"); - $this->outgoing_payload .= "$hdr\r\n"; - } - - // header/body separator - $this->outgoing_payload .= "\r\n"; - - // add data - $this->outgoing_payload .= $data; - } - - function sendRequest($data, $cookies = NULL) { - // build cookie string - $cookie_str = $this->getCookiesForRequest($cookies, (($this->scheme == 'ssl') || ($this->scheme == 'https'))); - - // build payload - $this->buildPayload($data, $cookie_str); - - if ($this->scheme == 'http' || $this->scheme == 'ssl') { - // send payload - if(!fputs($this->fp, $this->outgoing_payload, strlen($this->outgoing_payload))) { - $this->setError('couldn\'t write message data to socket'); - $this->debug('couldn\'t write message data to socket'); - return false; - } - $this->debug('wrote data to socket, length = ' . strlen($this->outgoing_payload)); - return true; - } else if ($this->scheme == 'https') { - // set payload - // TODO: cURL does say this should only be the verb, and in fact it - // turns out that the URI and HTTP version are appended to this, which - // some servers refuse to work with - //curl_setopt($this->ch, CURLOPT_CUSTOMREQUEST, $this->outgoing_payload); - foreach($this->outgoing_headers as $k => $v){ - $curl_headers[] = "$k: $v"; - } - if ($cookie_str != '') { - $curl_headers[] = 'Cookie: ' . $cookie_str; - } - curl_setopt($this->ch, CURLOPT_HTTPHEADER, $curl_headers); - if ($this->request_method == "POST") { - curl_setopt($this->ch, CURLOPT_POST, 1); - curl_setopt($this->ch, CURLOPT_POSTFIELDS, $data); - } else { - } - $this->debug('set cURL payload'); - return true; - } - } - - function getResponse(){ - $this->incoming_payload = ''; - - if ($this->scheme == 'http' || $this->scheme == 'ssl') { - // loop until headers have been retrieved - $data = ''; - while (!isset($lb)){ - - // We might EOF during header read. - if(feof($this->fp)) { - $this->incoming_payload = $data; - $this->debug('found no headers before EOF after length ' . strlen($data)); - $this->debug("received before EOF:\n" . $data); - $this->setError('server failed to send headers'); - return false; - } - - $tmp = fgets($this->fp, 256); - $tmplen = strlen($tmp); - $this->debug("read line of $tmplen bytes: " . trim($tmp)); - - if ($tmplen == 0) { - $this->incoming_payload = $data; - $this->debug('socket read of headers timed out after length ' . strlen($data)); - $this->debug("read before timeout: " . $data); - $this->setError('socket read of headers timed out'); - return false; - } - - $data .= $tmp; - $pos = strpos($data,"\r\n\r\n"); - if($pos > 1){ - $lb = "\r\n"; - } else { - $pos = strpos($data,"\n\n"); - if($pos > 1){ - $lb = "\n"; - } - } - // remove 100 header - if(isset($lb) && ereg('^HTTP/1.1 100',$data)){ - unset($lb); - $data = ''; - }// - } - // store header data - $this->incoming_payload .= $data; - $this->debug('found end of headers after length ' . strlen($data)); - // process headers - $header_data = trim(substr($data,0,$pos)); - $header_array = explode($lb,$header_data); - $this->incoming_headers = array(); - $this->incoming_cookies = array(); - foreach($header_array as $header_line){ - $arr = explode(':',$header_line, 2); - if(count($arr) > 1){ - $header_name = strtolower(trim($arr[0])); - $this->incoming_headers[$header_name] = trim($arr[1]); - if ($header_name == 'set-cookie') { - // TODO: allow multiple cookies from parseCookie - $cookie = $this->parseCookie(trim($arr[1])); - if ($cookie) { - $this->incoming_cookies[] = $cookie; - $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']); - } else { - $this->debug('did not find cookie in ' . trim($arr[1])); - } - } - } else if (isset($header_name)) { - // append continuation line to previous header - $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line; - } - } - - // loop until msg has been received - if (isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked') { - $content_length = 2147483647; // ignore any content-length header - $chunked = true; - $this->debug("want to read chunked content"); - } elseif (isset($this->incoming_headers['content-length'])) { - $content_length = $this->incoming_headers['content-length']; - $chunked = false; - $this->debug("want to read content of length $content_length"); - } else { - $content_length = 2147483647; - $chunked = false; - $this->debug("want to read content to EOF"); - } - $data = ''; - do { - if ($chunked) { - $tmp = fgets($this->fp, 256); - $tmplen = strlen($tmp); - $this->debug("read chunk line of $tmplen bytes"); - if ($tmplen == 0) { - $this->incoming_payload = $data; - $this->debug('socket read of chunk length timed out after length ' . strlen($data)); - $this->debug("read before timeout:\n" . $data); - $this->setError('socket read of chunk length timed out'); - return false; - } - $content_length = hexdec(trim($tmp)); - $this->debug("chunk length $content_length"); - } - $strlen = 0; - while (($strlen < $content_length) && (!feof($this->fp))) { - $readlen = min(8192, $content_length - $strlen); - $tmp = fread($this->fp, $readlen); - $tmplen = strlen($tmp); - $this->debug("read buffer of $tmplen bytes"); - if (($tmplen == 0) && (!feof($this->fp))) { - $this->incoming_payload = $data; - $this->debug('socket read of body timed out after length ' . strlen($data)); - $this->debug("read before timeout:\n" . $data); - $this->setError('socket read of body timed out'); - return false; - } - $strlen += $tmplen; - $data .= $tmp; - } - if ($chunked && ($content_length > 0)) { - $tmp = fgets($this->fp, 256); - $tmplen = strlen($tmp); - $this->debug("read chunk terminator of $tmplen bytes"); - if ($tmplen == 0) { - $this->incoming_payload = $data; - $this->debug('socket read of chunk terminator timed out after length ' . strlen($data)); - $this->debug("read before timeout:\n" . $data); - $this->setError('socket read of chunk terminator timed out'); - return false; - } - } - } while ($chunked && ($content_length > 0) && (!feof($this->fp))); - if (feof($this->fp)) { - $this->debug('read to EOF'); - } - $this->debug('read body of length ' . strlen($data)); - $this->incoming_payload .= $data; - $this->debug('received a total of '.strlen($this->incoming_payload).' bytes of data from server'); - - // close filepointer - if( - (isset($this->incoming_headers['connection']) && strtolower($this->incoming_headers['connection']) == 'close') || - (! $this->persistentConnection) || feof($this->fp)){ - fclose($this->fp); - $this->fp = false; - $this->debug('closed socket'); - } - - // connection was closed unexpectedly - if($this->incoming_payload == ''){ - $this->setError('no response from server'); - return false; - } - - // decode transfer-encoding -// if(isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked'){ -// if(!$data = $this->decodeChunked($data, $lb)){ -// $this->setError('Decoding of chunked data failed'); -// return false; -// } - //print "
\nde-chunked:\n---------------\n$data\n\n---------------\n
"; - // set decoded payload -// $this->incoming_payload = $header_data.$lb.$lb.$data; -// } - - } else if ($this->scheme == 'https') { - // send and receive - $this->debug('send and receive with cURL'); - $this->incoming_payload = curl_exec($this->ch); - $data = $this->incoming_payload; - - $cErr = curl_error($this->ch); - if ($cErr != '') { - $err = 'cURL ERROR: '.curl_errno($this->ch).': '.$cErr.'
'; - // TODO: there is a PHP bug that can cause this to SEGV for CURLINFO_CONTENT_TYPE - foreach(curl_getinfo($this->ch) as $k => $v){ - $err .= "$k: $v
"; - } - $this->debug($err); - $this->setError($err); - curl_close($this->ch); - return false; - } else { - //echo '
';
-			//var_dump(curl_getinfo($this->ch));
-			//echo '
'; - } - // close curl - $this->debug('No cURL error, closing cURL'); - curl_close($this->ch); - - // remove 100 header(s) - while (ereg('^HTTP/1.1 100',$data)) { - if ($pos = strpos($data,"\r\n\r\n")) { - $data = ltrim(substr($data,$pos)); - } elseif($pos = strpos($data,"\n\n") ) { - $data = ltrim(substr($data,$pos)); - } - } - - // separate content from HTTP headers - if ($pos = strpos($data,"\r\n\r\n")) { - $lb = "\r\n"; - } elseif( $pos = strpos($data,"\n\n")) { - $lb = "\n"; - } else { - $this->debug('no proper separation of headers and document'); - $this->setError('no proper separation of headers and document'); - return false; - } - $header_data = trim(substr($data,0,$pos)); - $header_array = explode($lb,$header_data); - $data = ltrim(substr($data,$pos)); - $this->debug('found proper separation of headers and document'); - $this->debug('cleaned data, stringlen: '.strlen($data)); - // clean headers - foreach ($header_array as $header_line) { - $arr = explode(':',$header_line,2); - if(count($arr) > 1){ - $header_name = strtolower(trim($arr[0])); - $this->incoming_headers[$header_name] = trim($arr[1]); - if ($header_name == 'set-cookie') { - // TODO: allow multiple cookies from parseCookie - $cookie = $this->parseCookie(trim($arr[1])); - if ($cookie) { - $this->incoming_cookies[] = $cookie; - $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']); - } else { - $this->debug('did not find cookie in ' . trim($arr[1])); - } - } - } else if (isset($header_name)) { - // append continuation line to previous header - $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line; - } - } - } - - $arr = explode(' ', $header_array[0], 3); - $http_version = $arr[0]; - $http_status = intval($arr[1]); - $http_reason = count($arr) > 2 ? $arr[2] : ''; - - // see if we need to resend the request with http digest authentication - if (isset($this->incoming_headers['location']) && $http_status == 301) { - $this->debug("Got 301 $http_reason with Location: " . $this->incoming_headers['location']); - $this->setURL($this->incoming_headers['location']); - $this->tryagain = true; - return false; - } - - // see if we need to resend the request with http digest authentication - if (isset($this->incoming_headers['www-authenticate']) && $http_status == 401) { - $this->debug("Got 401 $http_reason with WWW-Authenticate: " . $this->incoming_headers['www-authenticate']); - if (strstr($this->incoming_headers['www-authenticate'], "Digest ")) { - $this->debug('Server wants digest authentication'); - // remove "Digest " from our elements - $digestString = str_replace('Digest ', '', $this->incoming_headers['www-authenticate']); - - // parse elements into array - $digestElements = explode(',', $digestString); - foreach ($digestElements as $val) { - $tempElement = explode('=', trim($val), 2); - $digestRequest[$tempElement[0]] = str_replace("\"", '', $tempElement[1]); - } - - // should have (at least) qop, realm, nonce - if (isset($digestRequest['nonce'])) { - $this->setCredentials($this->username, $this->password, 'digest', $digestRequest); - $this->tryagain = true; - return false; - } - } - $this->debug('HTTP authentication failed'); - $this->setError('HTTP authentication failed'); - return false; - } - - if ( - ($http_status >= 300 && $http_status <= 307) || - ($http_status >= 400 && $http_status <= 417) || - ($http_status >= 501 && $http_status <= 505) - ) { - $this->setError("Unsupported HTTP response status $http_status $http_reason (soapclient->response has contents of the response)"); - return false; - } - - // decode content-encoding - if(isset($this->incoming_headers['content-encoding']) && $this->incoming_headers['content-encoding'] != ''){ - if(strtolower($this->incoming_headers['content-encoding']) == 'deflate' || strtolower($this->incoming_headers['content-encoding']) == 'gzip'){ - // if decoding works, use it. else assume data wasn't gzencoded - if(function_exists('gzinflate')){ - //$timer->setMarker('starting decoding of gzip/deflated content'); - // IIS 5 requires gzinflate instead of gzuncompress (similar to IE 5 and gzdeflate v. gzcompress) - // this means there are no Zlib headers, although there should be - $this->debug('The gzinflate function exists'); - $datalen = strlen($data); - if ($this->incoming_headers['content-encoding'] == 'deflate') { - if ($degzdata = @gzinflate($data)) { - $data = $degzdata; - $this->debug('The payload has been inflated to ' . strlen($data) . ' bytes'); - if (strlen($data) < $datalen) { - // test for the case that the payload has been compressed twice - $this->debug('The inflated payload is smaller than the gzipped one; try again'); - if ($degzdata = @gzinflate($data)) { - $data = $degzdata; - $this->debug('The payload has been inflated again to ' . strlen($data) . ' bytes'); - } - } - } else { - $this->debug('Error using gzinflate to inflate the payload'); - $this->setError('Error using gzinflate to inflate the payload'); - } - } elseif ($this->incoming_headers['content-encoding'] == 'gzip') { - if ($degzdata = @gzinflate(substr($data, 10))) { // do our best - $data = $degzdata; - $this->debug('The payload has been un-gzipped to ' . strlen($data) . ' bytes'); - if (strlen($data) < $datalen) { - // test for the case that the payload has been compressed twice - $this->debug('The un-gzipped payload is smaller than the gzipped one; try again'); - if ($degzdata = @gzinflate(substr($data, 10))) { - $data = $degzdata; - $this->debug('The payload has been un-gzipped again to ' . strlen($data) . ' bytes'); - } - } - } else { - $this->debug('Error using gzinflate to un-gzip the payload'); - $this->setError('Error using gzinflate to un-gzip the payload'); - } - } - //$timer->setMarker('finished decoding of gzip/deflated content'); - //print "\nde-inflated:\n---------------\n$data\n-------------\n"; - // set decoded payload - $this->incoming_payload = $header_data.$lb.$lb.$data; - } else { - $this->debug('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.'); - $this->setError('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.'); - } - } else { - $this->debug('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']); - $this->setError('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']); - } - } else { - $this->debug('No Content-Encoding header'); - } - - if(strlen($data) == 0){ - $this->debug('no data after headers!'); - $this->setError('no data present after HTTP headers'); - return false; - } - - return $data; - } - - function setContentType($type, $charset = false) { - $this->outgoing_headers['Content-Type'] = $type . ($charset ? '; charset=' . $charset : ''); - $this->debug('set Content-Type: ' . $this->outgoing_headers['Content-Type']); - } - - function usePersistentConnection(){ - if (isset($this->outgoing_headers['Accept-Encoding'])) { - return false; - } - $this->protocol_version = '1.1'; - $this->persistentConnection = true; - $this->outgoing_headers['Connection'] = 'Keep-Alive'; - $this->debug('set Connection: ' . $this->outgoing_headers['Connection']); - return true; - } - - /** - * parse an incoming Cookie into it's parts - * - * @param string $cookie_str content of cookie - * @return array with data of that cookie - * @access private - */ - /* - * TODO: allow a Set-Cookie string to be parsed into multiple cookies - */ - function parseCookie($cookie_str) { - $cookie_str = str_replace('; ', ';', $cookie_str) . ';'; - $data = explode(';', $cookie_str); - $value_str = $data[0]; - - $cookie_param = 'domain='; - $start = strpos($cookie_str, $cookie_param); - if ($start > 0) { - $domain = substr($cookie_str, $start + strlen($cookie_param)); - $domain = substr($domain, 0, strpos($domain, ';')); - } else { - $domain = ''; - } - - $cookie_param = 'expires='; - $start = strpos($cookie_str, $cookie_param); - if ($start > 0) { - $expires = substr($cookie_str, $start + strlen($cookie_param)); - $expires = substr($expires, 0, strpos($expires, ';')); - } else { - $expires = ''; - } - - $cookie_param = 'path='; - $start = strpos($cookie_str, $cookie_param); - if ( $start > 0 ) { - $path = substr($cookie_str, $start + strlen($cookie_param)); - $path = substr($path, 0, strpos($path, ';')); - } else { - $path = '/'; - } - - $cookie_param = ';secure;'; - if (strpos($cookie_str, $cookie_param) !== FALSE) { - $secure = true; - } else { - $secure = false; - } - - $sep_pos = strpos($value_str, '='); - - if ($sep_pos) { - $name = substr($value_str, 0, $sep_pos); - $value = substr($value_str, $sep_pos + 1); - $cookie= array( 'name' => $name, - 'value' => $value, - 'domain' => $domain, - 'path' => $path, - 'expires' => $expires, - 'secure' => $secure - ); - return $cookie; - } - return false; - } - - /** - * sort out cookies for the current request - * - * @param array $cookies array with all cookies - * @param boolean $secure is the send-content secure or not? - * @return string for Cookie-HTTP-Header - * @access private - */ - function getCookiesForRequest($cookies, $secure=false) { - $cookie_str = ''; - if ((! is_null($cookies)) && (is_array($cookies))) { - foreach ($cookies as $cookie) { - if (! is_array($cookie)) { - continue; - } - $this->debug("check cookie for validity: ".$cookie['name'].'='.$cookie['value']); - if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) { - if (strtotime($cookie['expires']) <= time()) { - $this->debug('cookie has expired'); - continue; - } - } - if ((isset($cookie['domain'])) && (! empty($cookie['domain']))) { - $domain = preg_quote($cookie['domain']); - if (! preg_match("'.*$domain$'i", $this->host)) { - $this->debug('cookie has different domain'); - continue; - } - } - if ((isset($cookie['path'])) && (! empty($cookie['path']))) { - $path = preg_quote($cookie['path']); - if (! preg_match("'^$path.*'i", $this->path)) { - $this->debug('cookie is for a different path'); - continue; - } - } - if ((! $secure) && (isset($cookie['secure'])) && ($cookie['secure'])) { - $this->debug('cookie is secure, transport is not'); - continue; - } - $cookie_str .= $cookie['name'] . '=' . $cookie['value'] . '; '; - $this->debug('add cookie to Cookie-String: ' . $cookie['name'] . '=' . $cookie['value']); - } - } - return $cookie_str; - } - - 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); - } -} - -?> -* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class soap_server extends nusoap_base { - /** - * HTTP headers of request - * @var array - * @access private - */ - var $headers = array(); - /** - * HTTP request - * @var string - * @access private - */ - var $request = ''; - /** - * SOAP headers from request (incomplete namespace resolution; special characters not escaped) (text) - * @var string - * @access public - */ - var $requestHeaders = ''; - /** - * SOAP body request portion (incomplete namespace resolution; special characters not escaped) (text) - * @var string - * @access public - */ - var $document = ''; - /** - * SOAP payload for request (text) - * @var string - * @access public - */ - var $requestSOAP = ''; - /** - * requested method namespace URI - * @var string - * @access private - */ - var $methodURI = ''; - /** - * name of method requested - * @var string - * @access private - */ - var $methodname = ''; - /** - * method parameters from request - * @var array - * @access private - */ - var $methodparams = array(); - /** - * SOAP Action from request - * @var string - * @access private - */ - var $SOAPAction = ''; - /** - * character set encoding of incoming (request) messages - * @var string - * @access public - */ - var $xml_encoding = ''; - /** - * toggles whether the parser decodes element content w/ utf8_decode() - * @var boolean - * @access public - */ - var $decode_utf8 = true; - - /** - * HTTP headers of response - * @var array - * @access public - */ - var $outgoing_headers = array(); - /** - * HTTP response - * @var string - * @access private - */ - var $response = ''; - /** - * SOAP headers for response (text) - * @var string - * @access public - */ - var $responseHeaders = ''; - /** - * SOAP payload for response (text) - * @var string - * @access private - */ - var $responseSOAP = ''; - /** - * method return value to place in response - * @var mixed - * @access private - */ - var $methodreturn = false; - /** - * whether $methodreturn is a string of literal XML - * @var boolean - * @access public - */ - var $methodreturnisliteralxml = false; - /** - * SOAP fault for response (or false) - * @var mixed - * @access private - */ - var $fault = false; - /** - * text indication of result (for debugging) - * @var string - * @access private - */ - var $result = 'successful'; - - /** - * assoc array of operations => opData; operations are added by the register() - * method or by parsing an external WSDL definition - * @var array - * @access private - */ - var $operations = array(); - /** - * wsdl instance (if one) - * @var mixed - * @access private - */ - var $wsdl = false; - /** - * URL for WSDL (if one) - * @var mixed - * @access private - */ - var $externalWSDLURL = false; - /** - * whether to append debug to response as XML comment - * @var boolean - * @access public - */ - var $debug_flag = false; - - - /** - * constructor - * the optional parameter is a path to a WSDL file that you'd like to bind the server instance to. - * - * @param mixed $wsdl file path or URL (string), or wsdl instance (object) - * @access public - */ - function soap_server($wsdl=false){ - parent::nusoap_base(); - // turn on debugging? - global $debug; - global $HTTP_SERVER_VARS; - - if (isset($_SERVER)) { - $this->debug("_SERVER is defined:"); - $this->appendDebug($this->varDump($_SERVER)); - } elseif (isset($HTTP_SERVER_VARS)) { - $this->debug("HTTP_SERVER_VARS is defined:"); - $this->appendDebug($this->varDump($HTTP_SERVER_VARS)); - } else { - $this->debug("Neither _SERVER nor HTTP_SERVER_VARS is defined."); - } - - if (isset($debug)) { - $this->debug("In soap_server, set debug_flag=$debug based on global flag"); - $this->debug_flag = $debug; - } elseif (isset($_SERVER['QUERY_STRING'])) { - $qs = explode('&', $_SERVER['QUERY_STRING']); - foreach ($qs as $v) { - if (substr($v, 0, 6) == 'debug=') { - $this->debug("In soap_server, set debug_flag=" . substr($v, 6) . " based on query string #1"); - $this->debug_flag = substr($v, 6); - } - } - } elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) { - $qs = explode('&', $HTTP_SERVER_VARS['QUERY_STRING']); - foreach ($qs as $v) { - if (substr($v, 0, 6) == 'debug=') { - $this->debug("In soap_server, set debug_flag=" . substr($v, 6) . " based on query string #2"); - $this->debug_flag = substr($v, 6); - } - } - } - - // wsdl - if($wsdl){ - $this->debug("In soap_server, WSDL is specified"); - if (is_object($wsdl) && (get_class($wsdl) == 'wsdl')) { - $this->wsdl = $wsdl; - $this->externalWSDLURL = $this->wsdl->wsdl; - $this->debug('Use existing wsdl instance from ' . $this->externalWSDLURL); - } else { - $this->debug('Create wsdl from ' . $wsdl); - $this->wsdl = new wsdl($wsdl); - $this->externalWSDLURL = $wsdl; - } - $this->appendDebug($this->wsdl->getDebug()); - $this->wsdl->clearDebug(); - if($err = $this->wsdl->getError()){ - - 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(); - $err = $filter->xssFilterHard($err); - - die('WSDL ERROR: '.$err); - } - } - } - - /** - * processes request and returns response - * - * @param string $data usually is the value of $HTTP_RAW_POST_DATA - * @access public - */ - function service($data){ - global $HTTP_SERVER_VARS; - - if (isset($_SERVER['QUERY_STRING'])) { - $qs = $_SERVER['QUERY_STRING']; - } elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) { - $qs = $HTTP_SERVER_VARS['QUERY_STRING']; - } else { - $qs = ''; - } - $this->debug("In service, query string=$qs"); - - if (ereg('wsdl', $qs) ){ - $this->debug("In service, this is a request for WSDL"); - if($this->externalWSDLURL){ - if (strpos($this->externalWSDLURL,"://")!==false) { // assume URL - header('Location: '.$this->externalWSDLURL); - } else { // assume file - header("Content-Type: text/xml\r\n"); - $fp = fopen($this->externalWSDLURL, 'r'); - fpassthru($fp); - } - } elseif ($this->wsdl) { - header("Content-Type: text/xml; charset=ISO-8859-1\r\n"); - print $this->wsdl->serialize($this->debug_flag); - if ($this->debug_flag) { - $this->debug('wsdl:'); - $this->appendDebug($this->varDump($this->wsdl)); - print $this->getDebugAsXMLComment(); - } - } else { - header("Content-Type: text/html; charset=ISO-8859-1\r\n"); - print "This service does not provide WSDL"; - } - } elseif ($data == '' && $this->wsdl) { - $this->debug("In service, there is no data, so return Web description"); - - 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(); - $webDescription = $filter->xssFilterHard($this->wsdl->webDescription()); - - print $webDescription; - } else { - $this->debug("In service, invoke the request"); - $this->parse_request($data); - if (! $this->fault) { - $this->invoke_method(); - } - if (! $this->fault) { - $this->serialize_return(); - } - $this->send_response(); - } - } - - /** - * parses HTTP request headers. - * - * The following fields are set by this function (when successful) - * - * headers - * request - * xml_encoding - * SOAPAction - * - * @access private - */ - function parse_http_headers() { - global $HTTP_SERVER_VARS; - - $this->request = ''; - $this->SOAPAction = ''; - if(function_exists('getallheaders')){ - $this->debug("In parse_http_headers, use getallheaders"); - $headers = getallheaders(); - foreach($headers as $k=>$v){ - $k = strtolower($k); - $this->headers[$k] = $v; - $this->request .= "$k: $v\r\n"; - $this->debug("$k: $v"); - } - // get SOAPAction header - if(isset($this->headers['soapaction'])){ - $this->SOAPAction = str_replace('"','',$this->headers['soapaction']); - } - // get the character encoding of the incoming request - if(isset($this->headers['content-type']) && strpos($this->headers['content-type'],'=')){ - $enc = str_replace('"','',substr(strstr($this->headers["content-type"],'='),1)); - if(preg_match('/(ISO-8859-1|US-ASCII|UTF-8)/',$enc)){ - $this->xml_encoding = strtoupper($enc); - } else { - $this->xml_encoding = 'US-ASCII'; - } - } else { - // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 - $this->xml_encoding = 'ISO-8859-1'; - } - } elseif(isset($_SERVER) && is_array($_SERVER)){ - $this->debug("In parse_http_headers, use _SERVER"); - foreach ($_SERVER as $k => $v) { - if (substr($k, 0, 5) == 'HTTP_') { - $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5)))); $k = strtolower(substr($k, 5)); - } else { - $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k))); $k = strtolower($k); - } - if ($k == 'soapaction') { - // get SOAPAction header - $k = 'SOAPAction'; - $v = str_replace('"', '', $v); - $v = str_replace('\\', '', $v); - $this->SOAPAction = $v; - } else if ($k == 'content-type') { - // get the character encoding of the incoming request - if (strpos($v, '=')) { - $enc = substr(strstr($v, '='), 1); - $enc = str_replace('"', '', $enc); - $enc = str_replace('\\', '', $enc); - if (preg_match('/(ISO-8859-1|US-ASCII|UTF-8)/', $enc)) { - $this->xml_encoding = strtoupper($enc); - } else { - $this->xml_encoding = 'US-ASCII'; - } - } else { - // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 - $this->xml_encoding = 'ISO-8859-1'; - } - } - $this->headers[$k] = $v; - $this->request .= "$k: $v\r\n"; - $this->debug("$k: $v"); - } - } elseif (is_array($HTTP_SERVER_VARS)) { - $this->debug("In parse_http_headers, use HTTP_SERVER_VARS"); - foreach ($HTTP_SERVER_VARS as $k => $v) { - if (substr($k, 0, 5) == 'HTTP_') { - $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5)))); $k = strtolower(substr($k, 5)); - } else { - $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k))); $k = strtolower($k); - } - if ($k == 'soapaction') { - // get SOAPAction header - $k = 'SOAPAction'; - $v = str_replace('"', '', $v); - $v = str_replace('\\', '', $v); - $this->SOAPAction = $v; - } else if ($k == 'content-type') { - // get the character encoding of the incoming request - if (strpos($v, '=')) { - $enc = substr(strstr($v, '='), 1); - $enc = str_replace('"', '', $enc); - $enc = str_replace('\\', '', $enc); - if (preg_match('/(ISO-8859-1|US-ASCII|UTF-8)/', $enc)) { - $this->xml_encoding = strtoupper($enc); - } else { - $this->xml_encoding = 'US-ASCII'; - } - } else { - // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 - $this->xml_encoding = 'ISO-8859-1'; - } - } - $this->headers[$k] = $v; - $this->request .= "$k: $v\r\n"; - $this->debug("$k: $v"); - } - } else { - $this->debug("In parse_http_headers, HTTP headers not accessible"); - $this->setError("HTTP headers not accessible"); - } - } - - /** - * parses a request - * - * The following fields are set by this function (when successful) - * - * headers - * request - * xml_encoding - * SOAPAction - * request - * requestSOAP - * methodURI - * methodname - * methodparams - * requestHeaders - * document - * - * This sets the fault field on error - * - * @param string $data XML string - * @access private - */ - function parse_request($data='') { - $this->debug('entering parse_request()'); - $this->parse_http_headers(); - $this->debug('got character encoding: '.$this->xml_encoding); - // uncompress if necessary - if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] != '') { - $this->debug('got content encoding: ' . $this->headers['content-encoding']); - if ($this->headers['content-encoding'] == 'deflate' || $this->headers['content-encoding'] == 'gzip') { - // if decoding works, use it. else assume data wasn't gzencoded - if (function_exists('gzuncompress')) { - if ($this->headers['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) { - $data = $degzdata; - } elseif ($this->headers['content-encoding'] == 'gzip' && $degzdata = gzinflate(substr($data, 10))) { - $data = $degzdata; - } else { - $this->fault('Client', 'Errors occurred when trying to decode the data'); - return; - } - } else { - $this->fault('Client', 'This Server does not support compressed data'); - return; - } - } - } - $this->request .= "\r\n".$data; - $data = $this->parseRequest($this->headers, $data); - $this->requestSOAP = $data; - $this->debug('leaving parse_request'); - } - - /** - * invokes a PHP function for the requested SOAP method - * - * The following fields are set by this function (when successful) - * - * methodreturn - * - * Note that the PHP function that is called may also set the following - * fields to affect the response sent to the client - * - * responseHeaders - * outgoing_headers - * - * This sets the fault field on error - * - * @access private - */ - function invoke_method() { - $this->debug('in invoke_method, methodname=' . $this->methodname . ' methodURI=' . $this->methodURI . ' SOAPAction=' . $this->SOAPAction); - - if ($this->wsdl) { - if ($this->opData = $this->wsdl->getOperationData($this->methodname)) { - $this->debug('in invoke_method, found WSDL operation=' . $this->methodname); - $this->appendDebug('opData=' . $this->varDump($this->opData)); - } elseif ($this->opData = $this->wsdl->getOperationDataForSoapAction($this->SOAPAction)) { - // Note: hopefully this case will only be used for doc/lit, since rpc services should have wrapper element - $this->debug('in invoke_method, found WSDL soapAction=' . $this->SOAPAction . ' for operation=' . $this->opData['name']); - $this->appendDebug('opData=' . $this->varDump($this->opData)); - $this->methodname = $this->opData['name']; - } else { - $this->debug('in invoke_method, no WSDL for operation=' . $this->methodname); - $this->fault('Client', "Operation '" . $this->methodname . "' is not defined in the WSDL for this service"); - return; - } - } else { - $this->debug('in invoke_method, no WSDL to validate method'); - } - - // if a . is present in $this->methodname, we see if there is a class in scope, - // which could be referred to. We will also distinguish between two deliminators, - // to allow methods to be called a the class or an instance - $class = ''; - $method = ''; - if (strpos($this->methodname, '..') > 0) { - $delim = '..'; - } else if (strpos($this->methodname, '.') > 0) { - $delim = '.'; - } else { - $delim = ''; - } - - if (strlen($delim) > 0 && substr_count($this->methodname, $delim) == 1 && - class_exists(substr($this->methodname, 0, strpos($this->methodname, $delim)))) { - // get the class and method name - $class = substr($this->methodname, 0, strpos($this->methodname, $delim)); - $method = substr($this->methodname, strpos($this->methodname, $delim) + strlen($delim)); - $this->debug("in invoke_method, class=$class method=$method delim=$delim"); - } - - // does method exist? - if ($class == '') { - if (!function_exists($this->methodname)) { - $this->debug("in invoke_method, function '$this->methodname' not found!"); - $this->result = 'fault: method not found'; - $this->fault('Client',"method '$this->methodname' not defined in service"); - return; - } - } else { - $method_to_compare = (substr(phpversion(), 0, 2) == '4.') ? strtolower($method) : $method; - if (!in_array($method_to_compare, get_class_methods($class))) { - $this->debug("in invoke_method, method '$this->methodname' not found in class '$class'!"); - $this->result = 'fault: method not found'; - $this->fault('Client',"method '$this->methodname' not defined in service"); - return; - } - } - - // evaluate message, getting back parameters - // verify that request parameters match the method's signature - if(! $this->verify_method($this->methodname,$this->methodparams)){ - // debug - $this->debug('ERROR: request not verified against method signature'); - $this->result = 'fault: request failed validation against method signature'; - // return fault - $this->fault('Client',"Operation '$this->methodname' not defined in service."); - return; - } - - // if there are parameters to pass - $this->debug('in invoke_method, params:'); - $this->appendDebug($this->varDump($this->methodparams)); - $this->debug("in invoke_method, calling '$this->methodname'"); - if (!function_exists('call_user_func_array')) { - if ($class == '') { - $this->debug('in invoke_method, calling function using eval()'); - $funcCall = "\$this->methodreturn = $this->methodname("; - } else { - if ($delim == '..') { - $this->debug('in invoke_method, calling class method using eval()'); - $funcCall = "\$this->methodreturn = ".$class."::".$method."("; - } else { - $this->debug('in invoke_method, calling instance method using eval()'); - // generate unique instance name - $instname = "\$inst_".time(); - $funcCall = $instname." = new ".$class."(); "; - $funcCall .= "\$this->methodreturn = ".$instname."->".$method."("; - } - } - if ($this->methodparams) { - foreach ($this->methodparams as $param) { - if (is_array($param)) { - $this->fault('Client', 'NuSOAP does not handle complexType parameters correctly when using eval; call_user_func_array must be available'); - return; - } - $funcCall .= "\"$param\","; - } - $funcCall = substr($funcCall, 0, -1); - } - $funcCall .= ');'; - $this->debug('in invoke_method, function call: '.$funcCall); - @eval($funcCall); - } else { - if ($class == '') { - $this->debug('in invoke_method, calling function using call_user_func_array()'); - $call_arg = "$this->methodname"; // straight assignment changes $this->methodname to lower case after call_user_func_array() - } elseif ($delim == '..') { - $this->debug('in invoke_method, calling class method using call_user_func_array()'); - $call_arg = array ($class, $method); - } else { - $this->debug('in invoke_method, calling instance method using call_user_func_array()'); - $instance = new $class (); - $call_arg = array(&$instance, $method); - } - $this->methodreturn = call_user_func_array($call_arg, $this->methodparams); - } - $this->debug('in invoke_method, methodreturn:'); - $this->appendDebug($this->varDump($this->methodreturn)); - $this->debug("in invoke_method, called method $this->methodname, received $this->methodreturn of type ".gettype($this->methodreturn)); - } - - /** - * serializes the return value from a PHP function into a full SOAP Envelope - * - * The following fields are set by this function (when successful) - * - * responseSOAP - * - * This sets the fault field on error - * - * @access private - */ - function serialize_return() { - $this->debug('Entering serialize_return methodname: ' . $this->methodname . ' methodURI: ' . $this->methodURI); - // if fault - if (isset($this->methodreturn) && (get_class($this->methodreturn) == 'soap_fault')) { - $this->debug('got a fault object from method'); - $this->fault = $this->methodreturn; - return; - } elseif ($this->methodreturnisliteralxml) { - $return_val = $this->methodreturn; - // returned value(s) - } else { - $this->debug('got a(n) '.gettype($this->methodreturn).' from method'); - $this->debug('serializing return value'); - if($this->wsdl){ - // weak attempt at supporting multiple output params - if(sizeof($this->opData['output']['parts']) > 1){ - $opParams = $this->methodreturn; - } else { - // TODO: is this really necessary? - $opParams = array($this->methodreturn); - } - $return_val = $this->wsdl->serializeRPCParameters($this->methodname,'output',$opParams); - $this->appendDebug($this->wsdl->getDebug()); - $this->wsdl->clearDebug(); - if($errstr = $this->wsdl->getError()){ - $this->debug('got wsdl error: '.$errstr); - $this->fault('Server', 'unable to serialize result'); - return; - } - } else { - if (isset($this->methodreturn)) { - $return_val = $this->serialize_val($this->methodreturn, 'return'); - } else { - $return_val = ''; - $this->debug('in absence of WSDL, assume void return for backward compatibility'); - } - } - } - $this->debug('return value:'); - $this->appendDebug($this->varDump($return_val)); - - $this->debug('serializing response'); - if ($this->wsdl) { - $this->debug('have WSDL for serialization: style is ' . $this->opData['style']); - if ($this->opData['style'] == 'rpc') { - $this->debug('style is rpc for serialization: use is ' . $this->opData['output']['use']); - if ($this->opData['output']['use'] == 'literal') { - $payload = '<'.$this->methodname.'Response xmlns="'.$this->methodURI.'">'.$return_val.'methodname."Response>"; - } else { - $payload = 'methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'methodname."Response>"; - } - } else { - $this->debug('style is not rpc for serialization: assume document'); - $payload = $return_val; - } - } else { - $this->debug('do not have WSDL for serialization: assume rpc/encoded'); - $payload = 'methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'methodname."Response>"; - } - $this->result = 'successful'; - if($this->wsdl){ - //if($this->debug_flag){ - $this->appendDebug($this->wsdl->getDebug()); - // } - if (isset($opData['output']['encodingStyle'])) { - $encodingStyle = $opData['output']['encodingStyle']; - } else { - $encodingStyle = ''; - } - // Added: In case we use a WSDL, return a serialized env. WITH the usedNamespaces. - $this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders,$this->wsdl->usedNamespaces,$this->opData['style'],$encodingStyle); - } else { - $this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders); - } - $this->debug("Leaving serialize_return"); - } - - /** - * sends an HTTP response - * - * The following fields are set by this function (when successful) - * - * outgoing_headers - * response - * - * @access private - */ - function send_response() { - $this->debug('Enter send_response'); - if ($this->fault) { - $payload = $this->fault->serialize(); - $this->outgoing_headers[] = "HTTP/1.0 500 Internal Server Error"; - $this->outgoing_headers[] = "Status: 500 Internal Server Error"; - } else { - $payload = $this->responseSOAP; - // Some combinations of PHP+Web server allow the Status - // to come through as a header. Since OK is the default - // just do nothing. - // $this->outgoing_headers[] = "HTTP/1.0 200 OK"; - // $this->outgoing_headers[] = "Status: 200 OK"; - } - // add debug data if in debug mode - if(isset($this->debug_flag) && $this->debug_flag){ - $payload .= $this->getDebugAsXMLComment(); - } - $this->outgoing_headers[] = "Server: $this->title Server v$this->version"; - ereg('\$Revisio' . 'n: ([^ ]+)', $this->revision, $rev); - $this->outgoing_headers[] = "X-SOAP-Server: $this->title/$this->version (".$rev[1].")"; - // Let the Web server decide about this - //$this->outgoing_headers[] = "Connection: Close\r\n"; - $payload = $this->getHTTPBody($payload); - $type = $this->getHTTPContentType(); - $charset = $this->getHTTPContentTypeCharset(); - $this->outgoing_headers[] = "Content-Type: $type" . ($charset ? '; charset=' . $charset : ''); - //begin code to compress payload - by John - // NOTE: there is no way to know whether the Web server will also compress - // this data. - if (strlen($payload) > 1024 && isset($this->headers) && isset($this->headers['accept-encoding'])) { - if (strstr($this->headers['accept-encoding'], 'gzip')) { - if (function_exists('gzencode')) { - if (isset($this->debug_flag) && $this->debug_flag) { - $payload .= ""; - } - $this->outgoing_headers[] = "Content-Encoding: gzip"; - $payload = gzencode($payload); - } else { - if (isset($this->debug_flag) && $this->debug_flag) { - $payload .= ""; - } - } - } elseif (strstr($this->headers['accept-encoding'], 'deflate')) { - // Note: MSIE requires gzdeflate output (no Zlib header and checksum), - // instead of gzcompress output, - // which conflicts with HTTP 1.1 spec (http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5) - if (function_exists('gzdeflate')) { - if (isset($this->debug_flag) && $this->debug_flag) { - $payload .= ""; - } - $this->outgoing_headers[] = "Content-Encoding: deflate"; - $payload = gzdeflate($payload); - } else { - if (isset($this->debug_flag) && $this->debug_flag) { - $payload .= ""; - } - } - } - } - //end code - $this->outgoing_headers[] = "Content-Length: ".strlen($payload); - reset($this->outgoing_headers); - foreach($this->outgoing_headers as $hdr){ - header($hdr, false); - } - print $payload; - $this->response = join("\r\n",$this->outgoing_headers)."\r\n\r\n".$payload; - } - - /** - * takes the value that was created by parsing the request - * and compares to the method's signature, if available. - * - * @param string $operation The operation to be invoked - * @param array $request The array of parameter values - * @return boolean Whether the operation was found - * @access private - */ - function verify_method($operation,$request){ - if(isset($this->wsdl) && is_object($this->wsdl)){ - if($this->wsdl->getOperationData($operation)){ - return true; - } - } elseif(isset($this->operations[$operation])){ - return true; - } - return false; - } - - /** - * processes SOAP message received from client - * - * @param array $headers The HTTP headers - * @param string $data unprocessed request data from client - * @return mixed value of the message, decoded into a PHP type - * @access private - */ - function parseRequest($headers, $data) { - $this->debug('Entering parseRequest() for data of length ' . strlen($data) . ' and type ' . $headers['content-type']); - if (!strstr($headers['content-type'], 'text/xml')) { - $this->setError('Request not of type text/xml'); - return false; - } - if (strpos($headers['content-type'], '=')) { - $enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1)); - $this->debug('Got response encoding: ' . $enc); - if(preg_match('/(ISO-8859-1|US-ASCII|UTF-8)/',$enc)){ - $this->xml_encoding = strtoupper($enc); - } else { - $this->xml_encoding = 'US-ASCII'; - } - } else { - // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 - $this->xml_encoding = 'ISO-8859-1'; - } - $this->debug('Use encoding: ' . $this->xml_encoding . ' when creating soap_parser'); - // parse response, get soap parser obj - $parser = new soap_parser($data,$this->xml_encoding,'',$this->decode_utf8); - // parser debug - $this->debug("parser debug: \n".$parser->getDebug()); - // if fault occurred during message parsing - if($err = $parser->getError()){ - $this->result = 'fault: error in msg parsing: '.$err; - $this->fault('Client',"error in msg parsing:\n".$err); - // else successfully parsed request into soapval object - } else { - // get/set methodname - $this->methodURI = $parser->root_struct_namespace; - $this->methodname = $parser->root_struct_name; - $this->debug('methodname: '.$this->methodname.' methodURI: '.$this->methodURI); - $this->debug('calling parser->get_response()'); - $this->methodparams = $parser->get_response(); - // get SOAP headers - $this->requestHeaders = $parser->getHeaders(); - // add document for doclit support - $this->document = $parser->document; - } - } - - /** - * gets the HTTP body for the current response. - * - * @param string $soapmsg The SOAP payload - * @return string The HTTP body, which includes the SOAP payload - * @access private - */ - function getHTTPBody($soapmsg) { - return $soapmsg; - } - - /** - * gets the HTTP content type for the current response. - * - * Note: getHTTPBody must be called before this. - * - * @return string the HTTP content type for the current response. - * @access private - */ - function getHTTPContentType() { - return 'text/xml'; - } - - /** - * gets the HTTP content type charset for the current response. - * returns false for non-text content types. - * - * Note: getHTTPBody must be called before this. - * - * @return string the HTTP content type charset for the current response. - * @access private - */ - function getHTTPContentTypeCharset() { - return $this->soap_defencoding; - } - - /** - * add a method to the dispatch map (this has been replaced by the register method) - * - * @param string $methodname - * @param string $in array of input values - * @param string $out array of output values - * @access public - * @deprecated - */ - function add_to_map($methodname,$in,$out){ - $this->operations[$methodname] = array('name' => $methodname,'in' => $in,'out' => $out); - } - - /** - * register a service function with the server - * - * @param string $name the name of the PHP function, class.method or class..method - * @param array $in assoc array of input values: key = param name, value = param type - * @param array $out assoc array of output values: key = param name, value = param type - * @param mixed $namespace the element namespace for the method or false - * @param mixed $soapaction the soapaction for the method or false - * @param mixed $style optional (rpc|document) or false Note: when 'document' is specified, parameter and return wrappers are created for you automatically - * @param mixed $use optional (encoded|literal) or false - * @param string $documentation optional Description to include in WSDL - * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded) - * @access public - */ - function register($name,$in=array(),$out=array(),$namespace=false,$soapaction=false,$style=false,$use=false,$documentation='',$encodingStyle=''){ - global $HTTP_SERVER_VARS; - - if($this->externalWSDLURL){ - die('You cannot bind to an external WSDL file, and register methods outside of it! Please choose either WSDL or no WSDL.'); - } - if (! $name) { - die('You must specify a name when you register an operation'); - } - if (!is_array($in)) { - die('You must provide an array for operation inputs'); - } - if (!is_array($out)) { - die('You must provide an array for operation outputs'); - } - if(false == $namespace) { - } - if(false == $soapaction) { - if (isset($_SERVER)) { - $SERVER_NAME = $_SERVER['SERVER_NAME']; - $SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']; - } elseif (isset($HTTP_SERVER_VARS)) { - $SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME']; - $SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME']; - } else { - $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available"); - } - $soapaction = "http://$SERVER_NAME$SCRIPT_NAME/$name"; - } - if(false == $style) { - $style = "rpc"; - } - if(false == $use) { - $use = "encoded"; - } - if ($use == 'encoded' && $encodingStyle = '') { - $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; - } - - $this->operations[$name] = array( - 'name' => $name, - 'in' => $in, - 'out' => $out, - 'namespace' => $namespace, - 'soapaction' => $soapaction, - 'style' => $style); - if($this->wsdl){ - $this->wsdl->addOperation($name,$in,$out,$namespace,$soapaction,$style,$use,$documentation,$encodingStyle); - } - return true; - } - - /** - * Specify a fault to be returned to the client. - * This also acts as a flag to the server that a fault has occured. - * - * @param string $faultcode - * @param string $faultstring - * @param string $faultactor - * @param string $faultdetail - * @access public - */ - function fault($faultcode,$faultstring,$faultactor='',$faultdetail=''){ - if ($faultdetail == '' && $this->debug_flag) { - $faultdetail = $this->getDebug(); - } - $this->fault = new soap_fault($faultcode,$faultactor,$faultstring,$faultdetail); - $this->fault->soap_defencoding = $this->soap_defencoding; - } - - /** - * Sets up wsdl object. - * Acts as a flag to enable internal WSDL generation - * - * @param string $serviceName, name of the service - * @param mixed $namespace optional 'tns' service namespace or false - * @param mixed $endpoint optional URL of service endpoint or false - * @param string $style optional (rpc|document) WSDL style (also specified by operation) - * @param string $transport optional SOAP transport - * @param mixed $schemaTargetNamespace optional 'types' targetNamespace for service schema or false - */ - function configureWSDL($serviceName,$namespace = false,$endpoint = false,$style='rpc', $transport = 'http://schemas.xmlsoap.org/soap/http', $schemaTargetNamespace = false) - { - global $HTTP_SERVER_VARS; - - if (isset($_SERVER)) { - $SERVER_NAME = $_SERVER['SERVER_NAME']; - $SERVER_PORT = $_SERVER['SERVER_PORT']; - $SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']; - $HTTPS = $_SERVER['HTTPS']; - } elseif (isset($HTTP_SERVER_VARS)) { - $SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME']; - $SERVER_PORT = $HTTP_SERVER_VARS['SERVER_PORT']; - $SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME']; - $HTTPS = $HTTP_SERVER_VARS['HTTPS']; - } else { - $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available"); - } - if ($SERVER_PORT == 80) { - $SERVER_PORT = ''; - } else { - $SERVER_PORT = ':' . $SERVER_PORT; - } - if(false == $namespace) { - $namespace = "http://$SERVER_NAME/soap/$serviceName"; - } - - if(false == $endpoint) { - if ($HTTPS == '1' || $HTTPS == 'on') { - $SCHEME = 'https'; - } else { - $SCHEME = 'http'; - } - $endpoint = "$SCHEME://$SERVER_NAME$SERVER_PORT$SCRIPT_NAME"; - } - - if(false == $schemaTargetNamespace) { - $schemaTargetNamespace = $namespace; - } - - $this->wsdl = new wsdl; - $this->wsdl->serviceName = $serviceName; - $this->wsdl->endpoint = $endpoint; - $this->wsdl->namespaces['tns'] = $namespace; - $this->wsdl->namespaces['soap'] = 'http://schemas.xmlsoap.org/wsdl/soap/'; - $this->wsdl->namespaces['wsdl'] = 'http://schemas.xmlsoap.org/wsdl/'; - if ($schemaTargetNamespace != $namespace) { - $this->wsdl->namespaces['types'] = $schemaTargetNamespace; - } - $this->wsdl->schemas[$schemaTargetNamespace][0] = new xmlschema('', '', $this->wsdl->namespaces); - $this->wsdl->schemas[$schemaTargetNamespace][0]->schemaTargetNamespace = $schemaTargetNamespace; - $this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/soap/encoding/'][0] = array('location' => '', 'loaded' => true); - $this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/wsdl/'][0] = array('location' => '', 'loaded' => true); - $this->wsdl->bindings[$serviceName.'Binding'] = array( - 'name'=>$serviceName.'Binding', - 'style'=>$style, - 'transport'=>$transport, - 'portType'=>$serviceName.'PortType'); - $this->wsdl->ports[$serviceName.'Port'] = array( - 'binding'=>$serviceName.'Binding', - 'location'=>$endpoint, - 'bindingType'=>'http://schemas.xmlsoap.org/wsdl/soap/'); - } -} - - - -?> -* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class wsdl extends nusoap_base { - // URL or filename of the root of this WSDL - var $wsdl; - // define internal arrays of bindings, ports, operations, messages, etc. - var $schemas = array(); - var $currentSchema; - var $message = array(); - var $complexTypes = array(); - var $messages = array(); - var $currentMessage; - var $currentOperation; - var $portTypes = array(); - var $currentPortType; - var $bindings = array(); - var $currentBinding; - var $ports = array(); - var $currentPort; - var $opData = array(); - var $status = ''; - var $documentation = false; - var $endpoint = ''; - // array of wsdl docs to import - var $import = array(); - // parser vars - var $parser; - var $position = 0; - var $depth = 0; - var $depth_array = array(); - // for getting wsdl - var $proxyhost = ''; - var $proxyport = ''; - var $proxyusername = ''; - var $proxypassword = ''; - var $timeout = 0; - var $response_timeout = 30; - - /** - * constructor - * - * @param string $wsdl WSDL document URL - * @param string $proxyhost - * @param string $proxyport - * @param string $proxyusername - * @param string $proxypassword - * @param integer $timeout set the connection timeout - * @param integer $response_timeout set the response timeout - * @access public - */ - function wsdl($wsdl = '',$proxyhost=false,$proxyport=false,$proxyusername=false,$proxypassword=false,$timeout=0,$response_timeout=30){ - parent::nusoap_base(); - $this->wsdl = $wsdl; - $this->proxyhost = $proxyhost; - $this->proxyport = $proxyport; - $this->proxyusername = $proxyusername; - $this->proxypassword = $proxypassword; - $this->timeout = $timeout; - $this->response_timeout = $response_timeout; - - // parse wsdl file - if ($wsdl != "") { - $this->debug('initial wsdl URL: ' . $wsdl); - $this->parseWSDL($wsdl); - } - // imports - // TODO: handle imports more properly, grabbing them in-line and nesting them - $imported_urls = array(); - $imported = 1; - while ($imported > 0) { - $imported = 0; - // Schema imports - foreach ($this->schemas as $ns => $list) { - foreach ($list as $xs) { - $wsdlparts = parse_url($this->wsdl); // this is bogusly simple! - foreach ($xs->imports as $ns2 => $list2) { - for ($ii = 0; $ii < count($list2); $ii++) { - if (! $list2[$ii]['loaded']) { - $this->schemas[$ns]->imports[$ns2][$ii]['loaded'] = true; - $url = $list2[$ii]['location']; - if ($url != '') { - $urlparts = parse_url($url); - if (!isset($urlparts['host'])) { - $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' .$wsdlparts['port'] : '') . - substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path']; - } - if (! in_array($url, $imported_urls)) { - $this->parseWSDL($url); - $imported++; - $imported_urls[] = $url; - } - } else { - $this->debug("Unexpected scenario: empty URL for unloaded import"); - } - } - } - } - } - } - // WSDL imports - $wsdlparts = parse_url($this->wsdl); // this is bogusly simple! - foreach ($this->import as $ns => $list) { - for ($ii = 0; $ii < count($list); $ii++) { - if (! $list[$ii]['loaded']) { - $this->import[$ns][$ii]['loaded'] = true; - $url = $list[$ii]['location']; - if ($url != '') { - $urlparts = parse_url($url); - if (!isset($urlparts['host'])) { - $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' . $wsdlparts['port'] : '') . - substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path']; - } - if (! in_array($url, $imported_urls)) { - $this->parseWSDL($url); - $imported++; - $imported_urls[] = $url; - } - } else { - $this->debug("Unexpected scenario: empty URL for unloaded import"); - } - } - } - } - } - // add new data to operation data - foreach($this->bindings as $binding => $bindingData) { - if (isset($bindingData['operations']) && is_array($bindingData['operations'])) { - foreach($bindingData['operations'] as $operation => $data) { - $this->debug('post-parse data gathering for ' . $operation); - $this->bindings[$binding]['operations'][$operation]['input'] = - isset($this->bindings[$binding]['operations'][$operation]['input']) ? - array_merge($this->bindings[$binding]['operations'][$operation]['input'], $this->portTypes[ $bindingData['portType'] ][$operation]['input']) : - $this->portTypes[ $bindingData['portType'] ][$operation]['input']; - $this->bindings[$binding]['operations'][$operation]['output'] = - isset($this->bindings[$binding]['operations'][$operation]['output']) ? - array_merge($this->bindings[$binding]['operations'][$operation]['output'], $this->portTypes[ $bindingData['portType'] ][$operation]['output']) : - $this->portTypes[ $bindingData['portType'] ][$operation]['output']; - if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ])){ - $this->bindings[$binding]['operations'][$operation]['input']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ]; - } - if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ])){ - $this->bindings[$binding]['operations'][$operation]['output']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ]; - } - if (isset($bindingData['style'])) { - $this->bindings[$binding]['operations'][$operation]['style'] = $bindingData['style']; - } - $this->bindings[$binding]['operations'][$operation]['transport'] = isset($bindingData['transport']) ? $bindingData['transport'] : ''; - $this->bindings[$binding]['operations'][$operation]['documentation'] = isset($this->portTypes[ $bindingData['portType'] ][$operation]['documentation']) ? $this->portTypes[ $bindingData['portType'] ][$operation]['documentation'] : ''; - $this->bindings[$binding]['operations'][$operation]['endpoint'] = isset($bindingData['endpoint']) ? $bindingData['endpoint'] : ''; - } - } - } - } - - /** - * parses the wsdl document - * - * @param string $wsdl path or URL - * @access private - */ - function parseWSDL($wsdl = '') - { - if ($wsdl == '') { - $this->debug('no wsdl passed to parseWSDL()!!'); - $this->setError('no wsdl passed to parseWSDL()!!'); - return false; - } - - // parse $wsdl for url format - $wsdl_props = parse_url($wsdl); - - if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'http' || $wsdl_props['scheme'] == 'https')) { - $this->debug('getting WSDL http(s) URL ' . $wsdl); - // get wsdl - $tr = new soap_transport_http($wsdl); - $tr->request_method = 'GET'; - $tr->useSOAPAction = false; - if($this->proxyhost && $this->proxyport){ - $tr->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword); - } - $tr->setEncoding('gzip, deflate'); - $wsdl_string = $tr->send('', $this->timeout, $this->response_timeout); - //$this->debug("WSDL request\n" . $tr->outgoing_payload); - //$this->debug("WSDL response\n" . $tr->incoming_payload); - $this->appendDebug($tr->getDebug()); - // catch errors - if($err = $tr->getError() ){ - $errstr = 'HTTP ERROR: '.$err; - $this->debug($errstr); - $this->setError($errstr); - unset($tr); - return false; - } - unset($tr); - $this->debug("got WSDL URL"); - } else { - // $wsdl is not http(s), so treat it as a file URL or plain file path - if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'file') && isset($wsdl_props['path'])) { - $path = isset($wsdl_props['host']) ? ($wsdl_props['host'] . ':' . $wsdl_props['path']) : $wsdl_props['path']; - } else { - $path = $wsdl; - } - $this->debug('getting WSDL file ' . $path); - if ($fp = @fopen($path, 'r')) { - $wsdl_string = ''; - while ($data = fread($fp, 32768)) { - $wsdl_string .= $data; - } - fclose($fp); - } else { - $errstr = "Bad path to WSDL file $path"; - $this->debug($errstr); - $this->setError($errstr); - return false; - } - } - $this->debug('Parse WSDL'); - // end new code added - // Create an XML parser. - $this->parser = xml_parser_create(); - // Set the options for parsing the XML data. - // xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); - xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); - // Set the object for the parser. - xml_set_object($this->parser, $this); - // Set the element handlers for the parser. - xml_set_element_handler($this->parser, 'start_element', 'end_element'); - xml_set_character_data_handler($this->parser, 'character_data'); - // Parse the XML file. - if (!xml_parse($this->parser, $wsdl_string, true)) { - // Display an error message. - $errstr = sprintf( - 'XML error parsing WSDL from %s on line %d: %s', - $wsdl, - xml_get_current_line_number($this->parser), - xml_error_string(xml_get_error_code($this->parser)) - ); - $this->debug($errstr); - $this->debug("XML payload:\n" . $wsdl_string); - $this->setError($errstr); - return false; - } - // free the parser - xml_parser_free($this->parser); - $this->debug('Parsing WSDL done'); - // catch wsdl parse errors - if($this->getError()){ - return false; - } - return true; - } - - /** - * start-element handler - * - * @param string $parser XML parser object - * @param string $name element name - * @param string $attrs associative array of attributes - * @access private - */ - function start_element($parser, $name, $attrs) - { - if ($this->status == 'schema') { - $this->currentSchema->schemaStartElement($parser, $name, $attrs); - $this->appendDebug($this->currentSchema->getDebug()); - $this->currentSchema->clearDebug(); - } elseif (ereg('schema$', $name)) { - $this->debug('Parsing WSDL schema'); - // $this->debug("startElement for $name ($attrs[name]). status = $this->status (".$this->getLocalPart($name).")"); - $this->status = 'schema'; - $this->currentSchema = new xmlschema('', '', $this->namespaces); - $this->currentSchema->schemaStartElement($parser, $name, $attrs); - $this->appendDebug($this->currentSchema->getDebug()); - $this->currentSchema->clearDebug(); - } else { - // position in the total number of elements, starting from 0 - $pos = $this->position++; - $depth = $this->depth++; - // set self as current value for this depth - $this->depth_array[$depth] = $pos; - $this->message[$pos] = array('cdata' => ''); - // process attributes - if (count($attrs) > 0) { - // register namespace declarations - foreach($attrs as $k => $v) { - if (ereg("^xmlns", $k)) { - if ($ns_prefix = substr(strrchr($k, ':'), 1)) { - $this->namespaces[$ns_prefix] = $v; - } else { - $this->namespaces['ns' . (count($this->namespaces) + 1)] = $v; - } - if ($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema') { - $this->XMLSchemaVersion = $v; - $this->namespaces['xsi'] = $v . '-instance'; - } - } - } - // expand each attribute prefix to its namespace - foreach($attrs as $k => $v) { - $k = strpos($k, ':') ? $this->expandQname($k) : $k; - if ($k != 'location' && $k != 'soapAction' && $k != 'namespace') { - $v = strpos($v, ':') ? $this->expandQname($v) : $v; - } - $eAttrs[$k] = $v; - } - $attrs = $eAttrs; - } else { - $attrs = array(); - } - // get element prefix, namespace and name - if (ereg(':', $name)) { - // get ns prefix - $prefix = substr($name, 0, strpos($name, ':')); - // get ns - $namespace = isset($this->namespaces[$prefix]) ? $this->namespaces[$prefix] : ''; - // get unqualified name - $name = substr(strstr($name, ':'), 1); - } - // process attributes, expanding any prefixes to namespaces - // find status, register data - switch ($this->status) { - case 'message': - if ($name == 'part') { - if (isset($attrs['type'])) { - $this->debug("msg " . $this->currentMessage . ": found part $attrs[name]: " . implode(',', $attrs)); - $this->messages[$this->currentMessage][$attrs['name']] = $attrs['type']; - } - if (isset($attrs['element'])) { - $this->debug("msg " . $this->currentMessage . ": found part $attrs[name]: " . implode(',', $attrs)); - $this->messages[$this->currentMessage][$attrs['name']] = $attrs['element']; - } - } - break; - case 'portType': - switch ($name) { - case 'operation': - $this->currentPortOperation = $attrs['name']; - $this->debug("portType $this->currentPortType operation: $this->currentPortOperation"); - if (isset($attrs['parameterOrder'])) { - $this->portTypes[$this->currentPortType][$attrs['name']]['parameterOrder'] = $attrs['parameterOrder']; - } - break; - case 'documentation': - $this->documentation = true; - break; - // merge input/output data - default: - $m = isset($attrs['message']) ? $this->getLocalPart($attrs['message']) : ''; - $this->portTypes[$this->currentPortType][$this->currentPortOperation][$name]['message'] = $m; - break; - } - break; - case 'binding': - switch ($name) { - case 'binding': - // get ns prefix - if (isset($attrs['style'])) { - $this->bindings[$this->currentBinding]['prefix'] = $prefix; - } - $this->bindings[$this->currentBinding] = array_merge($this->bindings[$this->currentBinding], $attrs); - break; - case 'header': - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus]['headers'][] = $attrs; - break; - case 'operation': - if (isset($attrs['soapAction'])) { - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['soapAction'] = $attrs['soapAction']; - } - if (isset($attrs['style'])) { - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['style'] = $attrs['style']; - } - if (isset($attrs['name'])) { - $this->currentOperation = $attrs['name']; - $this->debug("current binding operation: $this->currentOperation"); - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['name'] = $attrs['name']; - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['binding'] = $this->currentBinding; - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['endpoint'] = isset($this->bindings[$this->currentBinding]['endpoint']) ? $this->bindings[$this->currentBinding]['endpoint'] : ''; - } - break; - case 'input': - $this->opStatus = 'input'; - break; - case 'output': - $this->opStatus = 'output'; - break; - case 'body': - if (isset($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus])) { - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = array_merge($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus], $attrs); - } else { - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = $attrs; - } - break; - } - break; - case 'service': - switch ($name) { - case 'port': - $this->currentPort = $attrs['name']; - $this->debug('current port: ' . $this->currentPort); - $this->ports[$this->currentPort]['binding'] = $this->getLocalPart($attrs['binding']); - - break; - case 'address': - $this->ports[$this->currentPort]['location'] = $attrs['location']; - $this->ports[$this->currentPort]['bindingType'] = $namespace; - $this->bindings[ $this->ports[$this->currentPort]['binding'] ]['bindingType'] = $namespace; - $this->bindings[ $this->ports[$this->currentPort]['binding'] ]['endpoint'] = $attrs['location']; - break; - } - break; - } - // set status - switch ($name) { - case 'import': - if (isset($attrs['location'])) { - $this->import[$attrs['namespace']][] = array('location' => $attrs['location'], 'loaded' => false); - $this->debug('parsing import ' . $attrs['namespace']. ' - ' . $attrs['location'] . ' (' . count($this->import[$attrs['namespace']]).')'); - } else { - $this->import[$attrs['namespace']][] = array('location' => '', 'loaded' => true); - if (! $this->getPrefixFromNamespace($attrs['namespace'])) { - $this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace']; - } - $this->debug('parsing import ' . $attrs['namespace']. ' - [no location] (' . count($this->import[$attrs['namespace']]).')'); - } - break; - //wait for schema - //case 'types': - // $this->status = 'schema'; - // break; - case 'message': - $this->status = 'message'; - $this->messages[$attrs['name']] = array(); - $this->currentMessage = $attrs['name']; - break; - case 'portType': - $this->status = 'portType'; - $this->portTypes[$attrs['name']] = array(); - $this->currentPortType = $attrs['name']; - break; - case "binding": - if (isset($attrs['name'])) { - // get binding name - if (strpos($attrs['name'], ':')) { - $this->currentBinding = $this->getLocalPart($attrs['name']); - } else { - $this->currentBinding = $attrs['name']; - } - $this->status = 'binding'; - $this->bindings[$this->currentBinding]['portType'] = $this->getLocalPart($attrs['type']); - $this->debug("current binding: $this->currentBinding of portType: " . $attrs['type']); - } - break; - case 'service': - $this->serviceName = $attrs['name']; - $this->status = 'service'; - $this->debug('current service: ' . $this->serviceName); - break; - case 'definitions': - foreach ($attrs as $name => $value) { - $this->wsdl_info[$name] = $value; - } - break; - } - } - } - - /** - * end-element handler - * - * @param string $parser XML parser object - * @param string $name element name - * @access private - */ - function end_element($parser, $name){ - // unset schema status - if (/*ereg('types$', $name) ||*/ ereg('schema$', $name)) { - $this->status = ""; - $this->appendDebug($this->currentSchema->getDebug()); - $this->currentSchema->clearDebug(); - $this->schemas[$this->currentSchema->schemaTargetNamespace][] = $this->currentSchema; - $this->debug('Parsing WSDL schema done'); - } - if ($this->status == 'schema') { - $this->currentSchema->schemaEndElement($parser, $name); - } else { - // bring depth down a notch - $this->depth--; - } - // end documentation - if ($this->documentation) { - //TODO: track the node to which documentation should be assigned; it can be a part, message, etc. - //$this->portTypes[$this->currentPortType][$this->currentPortOperation]['documentation'] = $this->documentation; - $this->documentation = false; - } - } - - /** - * element content handler - * - * @param string $parser XML parser object - * @param string $data element content - * @access private - */ - function character_data($parser, $data) - { - $pos = isset($this->depth_array[$this->depth]) ? $this->depth_array[$this->depth] : 0; - if (isset($this->message[$pos]['cdata'])) { - $this->message[$pos]['cdata'] .= $data; - } - if ($this->documentation) { - $this->documentation .= $data; - } - } - - function getBindingData($binding) - { - if (is_array($this->bindings[$binding])) { - return $this->bindings[$binding]; - } - } - - /** - * returns an assoc array of operation names => operation data - * - * @param string $bindingType eg: soap, smtp, dime (only soap is currently supported) - * @return array - * @access public - */ - function getOperations($bindingType = 'soap') - { - $ops = array(); - if ($bindingType == 'soap') { - $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/'; - } - // loop thru ports - foreach($this->ports as $port => $portData) { - // binding type of port matches parameter - if ($portData['bindingType'] == $bindingType) { - //$this->debug("getOperations for port $port"); - //$this->debug("port data: " . $this->varDump($portData)); - //$this->debug("bindings: " . $this->varDump($this->bindings[ $portData['binding'] ])); - // merge bindings - if (isset($this->bindings[ $portData['binding'] ]['operations'])) { - $ops = array_merge ($ops, $this->bindings[ $portData['binding'] ]['operations']); - } - } - } - return $ops; - } - - /** - * returns an associative array of data necessary for calling an operation - * - * @param string $operation , name of operation - * @param string $bindingType , type of binding eg: soap - * @return array - * @access public - */ - function getOperationData($operation, $bindingType = 'soap') - { - if ($bindingType == 'soap') { - $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/'; - } - // loop thru ports - foreach($this->ports as $port => $portData) { - // binding type of port matches parameter - if ($portData['bindingType'] == $bindingType) { - // get binding - //foreach($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) { - foreach(array_keys($this->bindings[ $portData['binding'] ]['operations']) as $bOperation) { - // note that we could/should also check the namespace here - if ($operation == $bOperation) { - $opData = $this->bindings[ $portData['binding'] ]['operations'][$operation]; - return $opData; - } - } - } - } - } - - /** - * returns an associative array of data necessary for calling an operation - * - * @param string $soapAction soapAction for operation - * @param string $bindingType type of binding eg: soap - * @return array - * @access public - */ - function getOperationDataForSoapAction($soapAction, $bindingType = 'soap') { - if ($bindingType == 'soap') { - $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/'; - } - // loop thru ports - foreach($this->ports as $port => $portData) { - // binding type of port matches parameter - if ($portData['bindingType'] == $bindingType) { - // loop through operations for the binding - foreach ($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) { - if ($opData['soapAction'] == $soapAction) { - return $opData; - } - } - } - } - } - - /** - * returns an array of information about a given type - * returns false if no type exists by the given name - * - * typeDef = array( - * 'elements' => array(), // refs to elements array - * 'restrictionBase' => '', - * 'phpType' => '', - * 'order' => '(sequence|all)', - * 'attrs' => array() // refs to attributes array - * ) - * - * @param $type string the type - * @param $ns string namespace (not prefix) of the type - * @return mixed - * @access public - * @see xmlschema - */ - function getTypeDef($type, $ns) { - $this->debug("in getTypeDef: type=$type, ns=$ns"); - if ((! $ns) && isset($this->namespaces['tns'])) { - $ns = $this->namespaces['tns']; - $this->debug("in getTypeDef: type namespace forced to $ns"); - } - if (isset($this->schemas[$ns])) { - $this->debug("in getTypeDef: have schema for namespace $ns"); - for ($i = 0; $i < count($this->schemas[$ns]); $i++) { - $xs = &$this->schemas[$ns][$i]; - $t = $xs->getTypeDef($type); - $this->appendDebug($xs->getDebug()); - $xs->clearDebug(); - if ($t) { - if (!isset($t['phpType'])) { - // get info for type to tack onto the element - $uqType = substr($t['type'], strrpos($t['type'], ':') + 1); - $ns = substr($t['type'], 0, strrpos($t['type'], ':')); - $etype = $this->getTypeDef($uqType, $ns); - if ($etype) { - $this->debug("found type for [element] $type:"); - $this->debug($this->varDump($etype)); - if (isset($etype['phpType'])) { - $t['phpType'] = $etype['phpType']; - } - if (isset($etype['elements'])) { - $t['elements'] = $etype['elements']; - } - if (isset($etype['attrs'])) { - $t['attrs'] = $etype['attrs']; - } - } - } - return $t; - } - } - } else { - $this->debug("in getTypeDef: do not have schema for namespace $ns"); - } - return false; - } - - /** - * prints html description of services - * - * @access private - */ - function webDescription(){ - global $HTTP_SERVER_VARS; - - if (isset($_SERVER)) { - $PHP_SELF = $_SERVER['PHP_SELF']; - } elseif (isset($HTTP_SERVER_VARS)) { - $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF']; - } else { - $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available"); - } - - $b = ' - NuSOAP: '.$this->serviceName.' - - - - -
-

-
'.$this->serviceName.'
- -
'; - return $b; - } - - /** - * serialize the parsed wsdl - * - * @param mixed $debug whether to put debug=1 in endpoint URL - * @return string serialization of WSDL - * @access public - */ - function serialize($debug = 0) - { - $xml = ''; - $xml .= "\nnamespaces as $k => $v) { - $xml .= " xmlns:$k=\"$v\""; - } - // 10.9.02 - add poulter fix for wsdl and tns declarations - if (isset($this->namespaces['wsdl'])) { - $xml .= " xmlns=\"" . $this->namespaces['wsdl'] . "\""; - } - if (isset($this->namespaces['tns'])) { - $xml .= " targetNamespace=\"" . $this->namespaces['tns'] . "\""; - } - $xml .= '>'; - // imports - if (sizeof($this->import) > 0) { - foreach($this->import as $ns => $list) { - foreach ($list as $ii) { - if ($ii['location'] != '') { - $xml .= ''; - } else { - $xml .= ''; - } - } - } - } - // types - if (count($this->schemas)>=1) { - $xml .= "\n"; - foreach ($this->schemas as $ns => $list) { - foreach ($list as $xs) { - $xml .= $xs->serializeSchema(); - } - } - $xml .= ''; - } - // messages - if (count($this->messages) >= 1) { - foreach($this->messages as $msgName => $msgParts) { - $xml .= "\n'; - if(is_array($msgParts)){ - foreach($msgParts as $partName => $partType) { - // print 'serializing '.$partType.', sv: '.$this->XMLSchemaVersion.'
'; - if (strpos($partType, ':')) { - $typePrefix = $this->getPrefixFromNamespace($this->getPrefix($partType)); - } elseif (isset($this->typemap[$this->namespaces['xsd']][$partType])) { - // print 'checking typemap: '.$this->XMLSchemaVersion.'
'; - $typePrefix = 'xsd'; - } else { - foreach($this->typemap as $ns => $types) { - if (isset($types[$partType])) { - $typePrefix = $this->getPrefixFromNamespace($ns); - } - } - if (!isset($typePrefix)) { - die("$partType has no namespace!"); - } - } - $ns = $this->getNamespaceFromPrefix($typePrefix); - $typeDef = $this->getTypeDef($this->getLocalPart($partType), $ns); - if ($typeDef['typeClass'] == 'element') { - $elementortype = 'element'; - } else { - $elementortype = 'type'; - } - $xml .= ''; - } - } - $xml .= '
'; - } - } - // bindings & porttypes - if (count($this->bindings) >= 1) { - $binding_xml = ''; - $portType_xml = ''; - foreach($this->bindings as $bindingName => $attrs) { - $binding_xml .= "\n'; - $binding_xml .= ''; - $portType_xml .= "\n'; - foreach($attrs['operations'] as $opName => $opParts) { - $binding_xml .= ''; - $binding_xml .= ''; - if (isset($opParts['input']['encodingStyle']) && $opParts['input']['encodingStyle'] != '') { - $enc_style = ' encodingStyle="' . $opParts['input']['encodingStyle'] . '"'; - } else { - $enc_style = ''; - } - $binding_xml .= ''; - if (isset($opParts['output']['encodingStyle']) && $opParts['output']['encodingStyle'] != '') { - $enc_style = ' encodingStyle="' . $opParts['output']['encodingStyle'] . '"'; - } else { - $enc_style = ''; - } - $binding_xml .= ''; - $binding_xml .= ''; - $portType_xml .= ''; - } - $portType_xml .= ''; - $portType_xml .= ''; - $portType_xml .= ''; - } - $portType_xml .= ''; - $binding_xml .= ''; - } - $xml .= $portType_xml . $binding_xml; - } - // services - $xml .= "\nserviceName . '">'; - if (count($this->ports) >= 1) { - foreach($this->ports as $pName => $attrs) { - $xml .= ''; - $xml .= ''; - $xml .= ''; - } - } - $xml .= ''; - return $xml . "\n"; - } - - /** - * serialize PHP values according to a WSDL message definition - * - * TODO - * - multi-ref serialization - * - validate PHP values against type definitions, return errors if invalid - * - * @param string $operation operation name - * @param string $direction (input|output) - * @param mixed $parameters parameter value(s) - * @return mixed parameters serialized as XML or false on error (e.g. operation not found) - * @access public - */ - function serializeRPCParameters($operation, $direction, $parameters) - { - $this->debug("in serializeRPCParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion"); - $this->appendDebug('parameters=' . $this->varDump($parameters)); - - if ($direction != 'input' && $direction != 'output') { - $this->debug('The value of the \$direction argument needs to be either "input" or "output"'); - $this->setError('The value of the \$direction argument needs to be either "input" or "output"'); - return false; - } - if (!$opData = $this->getOperationData($operation)) { - $this->debug('Unable to retrieve WSDL data for operation: ' . $operation); - $this->setError('Unable to retrieve WSDL data for operation: ' . $operation); - return false; - } - $this->debug('opData:'); - $this->appendDebug($this->varDump($opData)); - - // Get encoding style for output and set to current - $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; - if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) { - $encodingStyle = $opData['output']['encodingStyle']; - $enc_style = $encodingStyle; - } - - // set input params - $xml = ''; - if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) { - - $use = $opData[$direction]['use']; - $this->debug('have ' . count($opData[$direction]['parts']) . ' part(s) to serialize'); - if (is_array($parameters)) { - $parametersArrayType = $this->isArraySimpleOrStruct($parameters); - $this->debug('have ' . count($parameters) . ' parameter(s) provided as ' . $parametersArrayType . ' to serialize'); - foreach($opData[$direction]['parts'] as $name => $type) { - $this->debug('serializing part "'.$name.'" of type "'.$type.'"'); - // Track encoding style - if (isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) { - $encodingStyle = $opData[$direction]['encodingStyle']; - $enc_style = $encodingStyle; - } else { - $enc_style = false; - } - // NOTE: add error handling here - // if serializeType returns false, then catch global error and fault - if ($parametersArrayType == 'arraySimple') { - $p = array_shift($parameters); - $this->debug('calling serializeType w/indexed param'); - $xml .= $this->serializeType($name, $type, $p, $use, $enc_style); - } elseif (isset($parameters[$name])) { - $this->debug('calling serializeType w/named param'); - $xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style); - } else { - // TODO: only send nillable - $this->debug('calling serializeType w/null param'); - $xml .= $this->serializeType($name, $type, null, $use, $enc_style); - } - } - } else { - $this->debug('no parameters passed.'); - } - } - $this->debug("serializeRPCParameters returning: $xml"); - return $xml; - } - - /** - * serialize a PHP value according to a WSDL message definition - * - * TODO - * - multi-ref serialization - * - validate PHP values against type definitions, return errors if invalid - * - * @param string $ type name - * @param mixed $ param value - * @return mixed new param or false if initial value didn't validate - * @access public - * @deprecated - */ - function serializeParameters($operation, $direction, $parameters) - { - $this->debug("in serializeParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion"); - $this->appendDebug('parameters=' . $this->varDump($parameters)); - - if ($direction != 'input' && $direction != 'output') { - $this->debug('The value of the \$direction argument needs to be either "input" or "output"'); - $this->setError('The value of the \$direction argument needs to be either "input" or "output"'); - return false; - } - if (!$opData = $this->getOperationData($operation)) { - $this->debug('Unable to retrieve WSDL data for operation: ' . $operation); - $this->setError('Unable to retrieve WSDL data for operation: ' . $operation); - return false; - } - $this->debug('opData:'); - $this->appendDebug($this->varDump($opData)); - - // Get encoding style for output and set to current - $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; - if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) { - $encodingStyle = $opData['output']['encodingStyle']; - $enc_style = $encodingStyle; - } - - // set input params - $xml = ''; - if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) { - - $use = $opData[$direction]['use']; - $this->debug("use=$use"); - $this->debug('got ' . count($opData[$direction]['parts']) . ' part(s)'); - if (is_array($parameters)) { - $parametersArrayType = $this->isArraySimpleOrStruct($parameters); - $this->debug('have ' . $parametersArrayType . ' parameters'); - foreach($opData[$direction]['parts'] as $name => $type) { - $this->debug('serializing part "'.$name.'" of type "'.$type.'"'); - // Track encoding style - if(isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) { - $encodingStyle = $opData[$direction]['encodingStyle']; - $enc_style = $encodingStyle; - } else { - $enc_style = false; - } - // NOTE: add error handling here - // if serializeType returns false, then catch global error and fault - if ($parametersArrayType == 'arraySimple') { - $p = array_shift($parameters); - $this->debug('calling serializeType w/indexed param'); - $xml .= $this->serializeType($name, $type, $p, $use, $enc_style); - } elseif (isset($parameters[$name])) { - $this->debug('calling serializeType w/named param'); - $xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style); - } else { - // TODO: only send nillable - $this->debug('calling serializeType w/null param'); - $xml .= $this->serializeType($name, $type, null, $use, $enc_style); - } - } - } else { - $this->debug('no parameters passed.'); - } - } - $this->debug("serializeParameters returning: $xml"); - return $xml; - } - - /** - * serializes a PHP value according a given type definition - * - * @param string $name name of value (part or element) - * @param string $type XML schema type of value (type or element) - * @param mixed $value a native PHP value (parameter value) - * @param string $use use for part (encoded|literal) - * @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style) - * @param boolean $unqualified a kludge for what should be XML namespace form handling - * @return string value serialized as an XML string - * @access private - */ - function serializeType($name, $type, $value, $use='encoded', $encodingStyle=false, $unqualified=false) - { - $this->debug("in serializeType: name=$name, type=$type, use=$use, encodingStyle=$encodingStyle, unqualified=" . ($unqualified ? "unqualified" : "qualified")); - $this->appendDebug("value=" . $this->varDump($value)); - if($use == 'encoded' && $encodingStyle) { - $encodingStyle = ' SOAP-ENV:encodingStyle="' . $encodingStyle . '"'; - } - - // if a soapval has been supplied, let its type override the WSDL - if (is_object($value) && get_class($value) == 'soapval') { - if ($value->type_ns) { - $type = $value->type_ns . ':' . $value->type; - $forceType = true; - $this->debug("in serializeType: soapval overrides type to $type"); - } elseif ($value->type) { - $type = $value->type; - $forceType = true; - $this->debug("in serializeType: soapval overrides type to $type"); - } else { - $forceType = false; - $this->debug("in serializeType: soapval does not override type"); - } - $attrs = $value->attributes; - $value = $value->value; - $this->debug("in serializeType: soapval overrides value to $value"); - if ($attrs) { - if (!is_array($value)) { - $value['!'] = $value; - } - foreach ($attrs as $n => $v) { - $value['!' . $n] = $v; - } - $this->debug("in serializeType: soapval provides attributes"); - } - } else { - $forceType = false; - } - - $xml = ''; - if (strpos($type, ':')) { - $uqType = substr($type, strrpos($type, ':') + 1); - $ns = substr($type, 0, strrpos($type, ':')); - $this->debug("in serializeType: got a prefixed type: $uqType, $ns"); - if ($this->getNamespaceFromPrefix($ns)) { - $ns = $this->getNamespaceFromPrefix($ns); - $this->debug("in serializeType: expanded prefixed type: $uqType, $ns"); - } - - if($ns == $this->XMLSchemaVersion || $ns == 'http://schemas.xmlsoap.org/soap/encoding/'){ - $this->debug('in serializeType: type namespace indicates XML Schema or SOAP Encoding type'); - if ($unqualified && $use == 'literal') { - $elementNS = " xmlns=\"\""; - } else { - $elementNS = ''; - } - if (is_null($value)) { - if ($use == 'literal') { - // TODO: depends on minOccurs - $xml = "<$name$elementNS/>"; - } else { - // TODO: depends on nillable, which should be checked before calling this method - $xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>"; - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - if ($uqType == 'boolean') { - if ((is_string($value) && $value == 'false') || (! $value)) { - $value = 'false'; - } else { - $value = 'true'; - } - } - if ($uqType == 'string' && gettype($value) == 'string') { - $value = $this->expandEntities($value); - } - if (($uqType == 'long' || $uqType == 'unsignedLong') && gettype($value) == 'double') { - $value = sprintf("%.0lf", $value); - } - // it's a scalar - // TODO: what about null/nil values? - // check type isn't a custom type extending xmlschema namespace - if (!$this->getTypeDef($uqType, $ns)) { - if ($use == 'literal') { - if ($forceType) { - $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value"; - } else { - $xml = "<$name$elementNS>$value"; - } - } else { - $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value"; - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - $this->debug('custom type extends XML Schema or SOAP Encoding namespace (yuck)'); - } else if ($ns == 'http://xml.apache.org/xml-soap') { - $this->debug('in serializeType: appears to be Apache SOAP type'); - if ($uqType == 'Map') { - $tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap'); - if (! $tt_prefix) { - $this->debug('in serializeType: Add namespace for Apache SOAP type'); - $tt_prefix = 'ns' . rand(1000, 9999); - $this->namespaces[$tt_prefix] = 'http://xml.apache.org/xml-soap'; - // force this to be added to usedNamespaces - $tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap'); - } - $contents = ''; - foreach($value as $k => $v) { - $this->debug("serializing map element: key $k, value $v"); - $contents .= ''; - $contents .= $this->serialize_val($k,'key',false,false,false,false,$use); - $contents .= $this->serialize_val($v,'value',false,false,false,false,$use); - $contents .= ''; - } - if ($use == 'literal') { - if ($forceType) { - $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\">$contents"; - } else { - $xml = "<$name>$contents"; - } - } else { - $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\"$encodingStyle>$contents"; - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - $this->debug('in serializeType: Apache SOAP type, but only support Map'); - } - } else { - // TODO: should the type be compared to types in XSD, and the namespace - // set to XSD if the type matches? - $this->debug("in serializeType: No namespace for type $type"); - $ns = ''; - $uqType = $type; - } - if(!$typeDef = $this->getTypeDef($uqType, $ns)){ - $this->setError("$type ($uqType) is not a supported type."); - $this->debug("in serializeType: $type ($uqType) is not a supported type."); - return false; - } else { - $this->debug("in serializeType: found typeDef"); - $this->appendDebug('typeDef=' . $this->varDump($typeDef)); - } - $phpType = $typeDef['phpType']; - $this->debug("in serializeType: uqType: $uqType, ns: $ns, phptype: $phpType, arrayType: " . (isset($typeDef['arrayType']) ? $typeDef['arrayType'] : '') ); - // if php type == struct, map value to the element names - if ($phpType == 'struct') { - if (isset($typeDef['typeClass']) && $typeDef['typeClass'] == 'element') { - $elementName = $uqType; - if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) { - $elementNS = " xmlns=\"$ns\""; - } else { - $elementNS = " xmlns=\"\""; - } - } else { - $elementName = $name; - if ($unqualified) { - $elementNS = " xmlns=\"\""; - } else { - $elementNS = ''; - } - } - if (is_null($value)) { - if ($use == 'literal') { - // TODO: depends on minOccurs - $xml = "<$elementName$elementNS/>"; - } else { - $xml = "<$elementName$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>"; - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - if (is_object($value)) { - $value = get_object_vars($value); - } - if (is_array($value)) { - $elementAttrs = $this->serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType); - if ($use == 'literal') { - if ($forceType) { - $xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">"; - } else { - $xml = "<$elementName$elementNS$elementAttrs>"; - } - } else { - $xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>"; - } - - $xml .= $this->serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use, $encodingStyle); - $xml .= ""; - } else { - $this->debug("in serializeType: phpType is struct, but value is not an array"); - $this->setError("phpType is struct, but value is not an array: see debug output for details"); - $xml = ''; - } - } elseif ($phpType == 'array') { - if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) { - $elementNS = " xmlns=\"$ns\""; - } else { - if ($unqualified) { - $elementNS = " xmlns=\"\""; - } else { - $elementNS = ''; - } - } - if (is_null($value)) { - if ($use == 'literal') { - // TODO: depends on minOccurs - $xml = "<$name$elementNS/>"; - } else { - $xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" . - $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') . - ":Array\" " . - $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') . - ':arrayType="' . - $this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType'])) . - ':' . - $this->getLocalPart($typeDef['arrayType'])."[0]\"/>"; - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - if (isset($typeDef['multidimensional'])) { - $nv = array(); - foreach($value as $v) { - $cols = ',' . sizeof($v); - $nv = array_merge($nv, $v); - } - $value = $nv; - } else { - $cols = ''; - } - if (is_array($value) && sizeof($value) >= 1) { - $rows = sizeof($value); - $contents = ''; - foreach($value as $k => $v) { - $this->debug("serializing array element: $k, $v of type: $typeDef[arrayType]"); - //if (strpos($typeDef['arrayType'], ':') ) { - if (!in_array($typeDef['arrayType'],$this->typemap['http://www.w3.org/2001/XMLSchema'])) { - $contents .= $this->serializeType('item', $typeDef['arrayType'], $v, $use); - } else { - $contents .= $this->serialize_val($v, 'item', $typeDef['arrayType'], null, $this->XMLSchemaVersion, false, $use); - } - } - } else { - $rows = 0; - $contents = null; - } - // TODO: for now, an empty value will be serialized as a zero element - // array. Revisit this when coding the handling of null/nil values. - if ($use == 'literal') { - $xml = "<$name$elementNS>" - .$contents - .""; - } else { - $xml = "<$name$elementNS xsi:type=\"".$this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/').':Array" '. - $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') - .':arrayType="' - .$this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType'])) - .":".$this->getLocalPart($typeDef['arrayType'])."[$rows$cols]\">" - .$contents - .""; - } - } elseif ($phpType == 'scalar') { - if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) { - $elementNS = " xmlns=\"$ns\""; - } else { - if ($unqualified) { - $elementNS = " xmlns=\"\""; - } else { - $elementNS = ''; - } - } - if ($use == 'literal') { - if ($forceType) { - $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value"; - } else { - $xml = "<$name$elementNS>$value"; - } - } else { - $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value"; - } - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - - /** - * serializes the attributes for a complexType - * - * @param array $typeDef our internal representation of an XML schema type (or element) - * @param mixed $value a native PHP value (parameter value) - * @param string $ns the namespace of the type - * @param string $uqType the local part of the type - * @return string value serialized as an XML string - * @access private - */ - function serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType) { - $xml = ''; - if (isset($typeDef['attrs']) && is_array($typeDef['attrs'])) { - $this->debug("serialize attributes for XML Schema type $ns:$uqType"); - if (is_array($value)) { - $xvalue = $value; - } elseif (is_object($value)) { - $xvalue = get_object_vars($value); - } else { - $this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType"); - $xvalue = array(); - } - foreach ($typeDef['attrs'] as $aName => $attrs) { - if (isset($xvalue['!' . $aName])) { - $xname = '!' . $aName; - $this->debug("value provided for attribute $aName with key $xname"); - } elseif (isset($xvalue[$aName])) { - $xname = $aName; - $this->debug("value provided for attribute $aName with key $xname"); - } elseif (isset($attrs['default'])) { - $xname = '!' . $aName; - $xvalue[$xname] = $attrs['default']; - $this->debug('use default value of ' . $xvalue[$aName] . ' for attribute ' . $aName); - } else { - $xname = ''; - $this->debug("no value provided for attribute $aName"); - } - if ($xname) { - $xml .= " $aName=\"" . $this->expandEntities($xvalue[$xname]) . "\""; - } - } - } else { - $this->debug("no attributes to serialize for XML Schema type $ns:$uqType"); - } - if (isset($typeDef['extensionBase'])) { - $ns = $this->getPrefix($typeDef['extensionBase']); - $uqType = $this->getLocalPart($typeDef['extensionBase']); - if ($this->getNamespaceFromPrefix($ns)) { - $ns = $this->getNamespaceFromPrefix($ns); - } - if ($typeDef = $this->getTypeDef($uqType, $ns)) { - $this->debug("serialize attributes for extension base $ns:$uqType"); - $xml .= $this->serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType); - } else { - $this->debug("extension base $ns:$uqType is not a supported type"); - } - } - return $xml; - } - - /** - * serializes the elements for a complexType - * - * @param array $typeDef our internal representation of an XML schema type (or element) - * @param mixed $value a native PHP value (parameter value) - * @param string $ns the namespace of the type - * @param string $uqType the local part of the type - * @param string $use use for part (encoded|literal) - * @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style) - * @return string value serialized as an XML string - * @access private - */ - function serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use='encoded', $encodingStyle=false) { - $xml = ''; - if (isset($typeDef['elements']) && is_array($typeDef['elements'])) { - $this->debug("in serializeComplexTypeElements, serialize elements for XML Schema type $ns:$uqType"); - if (is_array($value)) { - $xvalue = $value; - } elseif (is_object($value)) { - $xvalue = get_object_vars($value); - } else { - $this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType"); - $xvalue = array(); - } - // toggle whether all elements are present - ideally should validate against schema - if (count($typeDef['elements']) != count($xvalue)){ - $optionals = true; - } - foreach ($typeDef['elements'] as $eName => $attrs) { - if (!isset($xvalue[$eName])) { - if (isset($attrs['default'])) { - $xvalue[$eName] = $attrs['default']; - $this->debug('use default value of ' . $xvalue[$eName] . ' for element ' . $eName); - } - } - // if user took advantage of a minOccurs=0, then only serialize named parameters - if (isset($optionals) - && (!isset($xvalue[$eName])) - && ( (!isset($attrs['nillable'])) || $attrs['nillable'] != 'true') - ){ - if (isset($attrs['minOccurs']) && $attrs['minOccurs'] <> '0') { - $this->debug("apparent error: no value provided for element $eName with minOccurs=" . $attrs['minOccurs']); - } - // do nothing - $this->debug("no value provided for complexType element $eName and element is not nillable, so serialize nothing"); - } else { - // get value - if (isset($xvalue[$eName])) { - $v = $xvalue[$eName]; - } else { - $v = null; - } - if (isset($attrs['form'])) { - $unqualified = ($attrs['form'] == 'unqualified'); - } else { - $unqualified = false; - } - if (isset($attrs['maxOccurs']) && ($attrs['maxOccurs'] == 'unbounded' || $attrs['maxOccurs'] > 1) && isset($v) && is_array($v) && $this->isArraySimpleOrStruct($v) == 'arraySimple') { - $vv = $v; - foreach ($vv as $k => $v) { - if (isset($attrs['type']) || isset($attrs['ref'])) { - // serialize schema-defined type - $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified); - } else { - // serialize generic type (can this ever really happen?) - $this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use"); - $xml .= $this->serialize_val($v, $eName, false, false, false, false, $use); - } - } - } else { - if (isset($attrs['type']) || isset($attrs['ref'])) { - // serialize schema-defined type - $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified); - } else { - // serialize generic type (can this ever really happen?) - $this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use"); - $xml .= $this->serialize_val($v, $eName, false, false, false, false, $use); - } - } - } - } - } else { - $this->debug("no elements to serialize for XML Schema type $ns:$uqType"); - } - if (isset($typeDef['extensionBase'])) { - $ns = $this->getPrefix($typeDef['extensionBase']); - $uqType = $this->getLocalPart($typeDef['extensionBase']); - if ($this->getNamespaceFromPrefix($ns)) { - $ns = $this->getNamespaceFromPrefix($ns); - } - if ($typeDef = $this->getTypeDef($uqType, $ns)) { - $this->debug("serialize elements for extension base $ns:$uqType"); - $xml .= $this->serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use, $encodingStyle); - } else { - $this->debug("extension base $ns:$uqType is not a supported type"); - } - } - return $xml; - } - - /** - * adds an XML Schema complex type to the WSDL types - * - * @param string name - * @param string typeClass (complexType|simpleType|attribute) - * @param string phpType: currently supported are array and struct (php assoc array) - * @param string compositor (all|sequence|choice) - * @param string restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) - * @param array elements = array ( name => array(name=>'',type=>'') ) - * @param array attrs = array(array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'xsd:string[]')) - * @param string arrayType: namespace:name (xsd:string) - * @see xmlschema - * @access public - */ - function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType='') { - if (count($elements) > 0) { - foreach($elements as $n => $e){ - // expand each element - foreach ($e as $k => $v) { - $k = strpos($k,':') ? $this->expandQname($k) : $k; - $v = strpos($v,':') ? $this->expandQname($v) : $v; - $ee[$k] = $v; - } - $eElements[$n] = $ee; - } - $elements = $eElements; - } - - if (count($attrs) > 0) { - foreach($attrs as $n => $a){ - // expand each attribute - foreach ($a as $k => $v) { - $k = strpos($k,':') ? $this->expandQname($k) : $k; - $v = strpos($v,':') ? $this->expandQname($v) : $v; - $aa[$k] = $v; - } - $eAttrs[$n] = $aa; - } - $attrs = $eAttrs; - } - - $restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase; - $arrayType = strpos($arrayType,':') ? $this->expandQname($arrayType) : $arrayType; - - $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns']; - $this->schemas[$typens][0]->addComplexType($name,$typeClass,$phpType,$compositor,$restrictionBase,$elements,$attrs,$arrayType); - } - - /** - * adds an XML Schema simple type to the WSDL types - * - * @param string $name - * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) - * @param string $typeClass (should always be simpleType) - * @param string $phpType (should always be scalar) - * @param array $enumeration array of values - * @see xmlschema - * @access public - */ - function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) { - $restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase; - - $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns']; - $this->schemas[$typens][0]->addSimpleType($name, $restrictionBase, $typeClass, $phpType, $enumeration); - } - - /** - * adds an element to the WSDL types - * - * @param array $attrs attributes that must include name and type - * @see xmlschema - * @access public - */ - function addElement($attrs) { - $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns']; - $this->schemas[$typens][0]->addElement($attrs); - } - - /** - * register an operation with the server - * - * @param string $name operation (method) name - * @param array $in assoc array of input values: key = param name, value = param type - * @param array $out assoc array of output values: key = param name, value = param type - * @param string $namespace optional The namespace for the operation - * @param string $soapaction optional The soapaction for the operation - * @param string $style (rpc|document) optional The style for the operation Note: when 'document' is specified, parameter and return wrappers are created for you automatically - * @param string $use (encoded|literal) optional The use for the parameters (cannot mix right now) - * @param string $documentation optional The description to include in the WSDL - * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded) - * @access public - */ - function addOperation($name, $in = false, $out = false, $namespace = false, $soapaction = false, $style = 'rpc', $use = 'encoded', $documentation = '', $encodingStyle = ''){ - if ($use == 'encoded' && $encodingStyle == '') { - $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; - } - - if ($style == 'document') { - $elements = array(); - foreach ($in as $n => $t) { - $elements[$n] = array('name' => $n, 'type' => $t); - } - $this->addComplexType($name . 'RequestType', 'complexType', 'struct', 'all', '', $elements); - $this->addElement(array('name' => $name, 'type' => $name . 'RequestType')); - $in = array('parameters' => 'tns:' . $name); - - $elements = array(); - foreach ($out as $n => $t) { - $elements[$n] = array('name' => $n, 'type' => $t); - } - $this->addComplexType($name . 'ResponseType', 'complexType', 'struct', 'all', '', $elements); - $this->addElement(array('name' => $name . 'Response', 'type' => $name . 'ResponseType')); - $out = array('parameters' => 'tns:' . $name . 'Response'); - } - - // get binding - $this->bindings[ $this->serviceName . 'Binding' ]['operations'][$name] = - array( - 'name' => $name, - 'binding' => $this->serviceName . 'Binding', - 'endpoint' => $this->endpoint, - 'soapAction' => $soapaction, - 'style' => $style, - 'input' => array( - 'use' => $use, - 'namespace' => $namespace, - 'encodingStyle' => $encodingStyle, - 'message' => $name . 'Request', - 'parts' => $in), - 'output' => array( - 'use' => $use, - 'namespace' => $namespace, - 'encodingStyle' => $encodingStyle, - 'message' => $name . 'Response', - 'parts' => $out), - 'namespace' => $namespace, - 'transport' => 'http://schemas.xmlsoap.org/soap/http', - 'documentation' => $documentation); - // add portTypes - // add messages - if($in) - { - foreach($in as $pName => $pType) - { - if(strpos($pType,':')) { - $pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType); - } - $this->messages[$name.'Request'][$pName] = $pType; - } - } else { - $this->messages[$name.'Request']= '0'; - } - if($out) - { - foreach($out as $pName => $pType) - { - if(strpos($pType,':')) { - $pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType); - } - $this->messages[$name.'Response'][$pName] = $pType; - } - } else { - $this->messages[$name.'Response']= '0'; - } - return true; - } -} -?> -* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class soap_parser extends nusoap_base { - - var $xml = ''; - var $xml_encoding = ''; - var $method = ''; - var $root_struct = ''; - var $root_struct_name = ''; - var $root_struct_namespace = ''; - var $root_header = ''; - var $document = ''; // incoming SOAP body (text) - // determines where in the message we are (envelope,header,body,method) - var $status = ''; - var $position = 0; - var $depth = 0; - var $default_namespace = ''; - var $namespaces = array(); - var $message = array(); - var $parent = ''; - var $fault = false; - var $fault_code = ''; - var $fault_str = ''; - var $fault_detail = ''; - var $depth_array = array(); - var $debug_flag = true; - var $soapresponse = NULL; - var $responseHeaders = ''; // incoming SOAP headers (text) - var $body_position = 0; - // for multiref parsing: - // array of id => pos - var $ids = array(); - // array of id => hrefs => pos - var $multirefs = array(); - // toggle for auto-decoding element content - var $decode_utf8 = true; - - /** - * constructor that actually does the parsing - * - * @param string $xml SOAP message - * @param string $encoding character encoding scheme of message - * @param string $method method for which XML is parsed (unused?) - * @param string $decode_utf8 whether to decode UTF-8 to ISO-8859-1 - * @access public - */ - function soap_parser($xml,$encoding='UTF-8',$method='',$decode_utf8=true){ - parent::nusoap_base(); - $this->xml = $xml; - $this->xml_encoding = $encoding; - $this->method = $method; - $this->decode_utf8 = $decode_utf8; - - // Check whether content has been read. - if(!empty($xml)){ - // Check XML encoding - $pos_xml = strpos($xml, '', $pos_xml + 2) - $pos_xml + 1); - if (preg_match("/encoding=[\"']([^\"']*)[\"']/", $xml_decl, $res)) { - $xml_encoding = $res[1]; - if (strtoupper($xml_encoding) != $encoding) { - $err = "Charset from HTTP Content-Type '" . $encoding . "' does not match encoding from XML declaration '" . $xml_encoding . "'"; - $this->debug($err); - if ($encoding != 'ISO-8859-1' || strtoupper($xml_encoding) != 'UTF-8') { - $this->setError($err); - return; - } - // when HTTP says ISO-8859-1 (the default) and XML says UTF-8 (the typical), assume the other endpoint is just sloppy and proceed - } else { - $this->debug('Charset from HTTP Content-Type matches encoding from XML declaration'); - } - } else { - $this->debug('No encoding specified in XML declaration'); - } - } else { - $this->debug('No XML declaration'); - } - $this->debug('Entering soap_parser(), length='.strlen($xml).', encoding='.$encoding); - // Create an XML parser - why not xml_parser_create_ns? - $this->parser = xml_parser_create($this->xml_encoding); - // Set the options for parsing the XML data. - //xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1); - xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); - xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, $this->xml_encoding); - // Set the object for the parser. - xml_set_object($this->parser, $this); - // Set the element handlers for the parser. - xml_set_element_handler($this->parser, 'start_element','end_element'); - xml_set_character_data_handler($this->parser,'character_data'); - - // Parse the XML file. - if(!xml_parse($this->parser,$xml,true)){ - // Display an error message. - $err = sprintf('XML error parsing SOAP payload on line %d: %s', - xml_get_current_line_number($this->parser), - xml_error_string(xml_get_error_code($this->parser))); - $this->debug($err); - $this->debug("XML payload:\n" . $xml); - $this->setError($err); - } else { - $this->debug('parsed successfully, found root struct: '.$this->root_struct.' of name '.$this->root_struct_name); - // get final value - $this->soapresponse = $this->message[$this->root_struct]['result']; - // get header value: no, because this is documented as XML string -// if($this->root_header != '' && isset($this->message[$this->root_header]['result'])){ -// $this->responseHeaders = $this->message[$this->root_header]['result']; -// } - // resolve hrefs/ids - if(sizeof($this->multirefs) > 0){ - foreach($this->multirefs as $id => $hrefs){ - $this->debug('resolving multirefs for id: '.$id); - $idVal = $this->buildVal($this->ids[$id]); - if (is_array($idVal) && isset($idVal['!id'])) { - unset($idVal['!id']); - } - foreach($hrefs as $refPos => $ref){ - $this->debug('resolving href at pos '.$refPos); - $this->multirefs[$id][$refPos] = $idVal; - } - } - } - } - xml_parser_free($this->parser); - } else { - $this->debug('xml was empty, didn\'t parse!'); - $this->setError('xml was empty, didn\'t parse!'); - } - } - - /** - * start-element handler - * - * @param resource $parser XML parser object - * @param string $name element name - * @param array $attrs associative array of attributes - * @access private - */ - function start_element($parser, $name, $attrs) { - // position in a total number of elements, starting from 0 - // update class level pos - $pos = $this->position++; - // and set mine - $this->message[$pos] = array('pos' => $pos,'children'=>'','cdata'=>''); - // depth = how many levels removed from root? - // set mine as current global depth and increment global depth value - $this->message[$pos]['depth'] = $this->depth++; - - // else add self as child to whoever the current parent is - if($pos != 0){ - $this->message[$this->parent]['children'] .= '|'.$pos; - } - // set my parent - $this->message[$pos]['parent'] = $this->parent; - // set self as current parent - $this->parent = $pos; - // set self as current value for this depth - $this->depth_array[$this->depth] = $pos; - // get element prefix - if(strpos($name,':')){ - // get ns prefix - $prefix = substr($name,0,strpos($name,':')); - // get unqualified name - $name = substr(strstr($name,':'),1); - } - // set status - if($name == 'Envelope'){ - $this->status = 'envelope'; - } elseif($name == 'Header'){ - $this->root_header = $pos; - $this->status = 'header'; - } elseif($name == 'Body'){ - $this->status = 'body'; - $this->body_position = $pos; - // set method - } elseif($this->status == 'body' && $pos == ($this->body_position+1)){ - $this->status = 'method'; - $this->root_struct_name = $name; - $this->root_struct = $pos; - $this->message[$pos]['type'] = 'struct'; - $this->debug("found root struct $this->root_struct_name, pos $this->root_struct"); - } - // set my status - $this->message[$pos]['status'] = $this->status; - // set name - $this->message[$pos]['name'] = htmlspecialchars($name); - // set attrs - $this->message[$pos]['attrs'] = $attrs; - - // loop through atts, logging ns and type declarations - $attstr = ''; - foreach($attrs as $key => $value){ - $key_prefix = $this->getPrefix($key); - $key_localpart = $this->getLocalPart($key); - // if ns declarations, add to class level array of valid namespaces - if($key_prefix == 'xmlns'){ - if(ereg('^http://www.w3.org/[0-9]{4}/XMLSchema$',$value)){ - $this->XMLSchemaVersion = $value; - $this->namespaces['xsd'] = $this->XMLSchemaVersion; - $this->namespaces['xsi'] = $this->XMLSchemaVersion.'-instance'; - } - $this->namespaces[$key_localpart] = $value; - // set method namespace - if($name == $this->root_struct_name){ - $this->methodNamespace = $value; - } - // if it's a type declaration, set type - } elseif($key_localpart == 'type'){ - $value_prefix = $this->getPrefix($value); - $value_localpart = $this->getLocalPart($value); - $this->message[$pos]['type'] = $value_localpart; - $this->message[$pos]['typePrefix'] = $value_prefix; - if(isset($this->namespaces[$value_prefix])){ - $this->message[$pos]['type_namespace'] = $this->namespaces[$value_prefix]; - } else if(isset($attrs['xmlns:'.$value_prefix])) { - $this->message[$pos]['type_namespace'] = $attrs['xmlns:'.$value_prefix]; - } - // should do something here with the namespace of specified type? - } elseif($key_localpart == 'arrayType'){ - $this->message[$pos]['type'] = 'array'; - /* do arrayType ereg here - [1] arrayTypeValue ::= atype asize - [2] atype ::= QName rank* - [3] rank ::= '[' (',')* ']' - [4] asize ::= '[' length~ ']' - [5] length ::= nextDimension* Digit+ - [6] nextDimension ::= Digit+ ',' - */ - $expr = '([A-Za-z0-9_]+):([A-Za-z]+[A-Za-z0-9_]+)\[([0-9]+),?([0-9]*)\]'; - if(ereg($expr,$value,$regs)){ - $this->message[$pos]['typePrefix'] = $regs[1]; - $this->message[$pos]['arrayTypePrefix'] = $regs[1]; - if (isset($this->namespaces[$regs[1]])) { - $this->message[$pos]['arrayTypeNamespace'] = $this->namespaces[$regs[1]]; - } else if (isset($attrs['xmlns:'.$regs[1]])) { - $this->message[$pos]['arrayTypeNamespace'] = $attrs['xmlns:'.$regs[1]]; - } - $this->message[$pos]['arrayType'] = $regs[2]; - $this->message[$pos]['arraySize'] = $regs[3]; - $this->message[$pos]['arrayCols'] = $regs[4]; - } - // specifies nil value (or not) - } elseif ($key_localpart == 'nil'){ - $this->message[$pos]['nil'] = ($value == 'true' || $value == '1'); - // some other attribute - } elseif ($key != 'href' && $key != 'xmlns' && $key_localpart != 'encodingStyle' && $key_localpart != 'root') { - $this->message[$pos]['xattrs']['!' . $key] = $value; - } - - if ($key == 'xmlns') { - $this->default_namespace = $value; - } - // log id - if($key == 'id'){ - $this->ids[$value] = $pos; - } - // root - if($key_localpart == 'root' && $value == 1){ - $this->status = 'method'; - $this->root_struct_name = $name; - $this->root_struct = $pos; - $this->debug("found root struct $this->root_struct_name, pos $pos"); - } - // for doclit - $attstr .= " $key=\"$value\""; - } - // get namespace - must be done after namespace atts are processed - if(isset($prefix)){ - $this->message[$pos]['namespace'] = $this->namespaces[$prefix]; - $this->default_namespace = $this->namespaces[$prefix]; - } else { - $this->message[$pos]['namespace'] = $this->default_namespace; - } - if($this->status == 'header'){ - if ($this->root_header != $pos) { - $this->responseHeaders .= "<" . (isset($prefix) ? $prefix . ':' : '') . "$name$attstr>"; - } - } elseif($this->root_struct_name != ''){ - $this->document .= "<" . (isset($prefix) ? $prefix . ':' : '') . "$name$attstr>"; - } - } - - /** - * end-element handler - * - * @param resource $parser XML parser object - * @param string $name element name - * @access private - */ - function end_element($parser, $name) { - // position of current element is equal to the last value left in depth_array for my depth - $pos = $this->depth_array[$this->depth--]; - - // get element prefix - if(strpos($name,':')){ - // get ns prefix - $prefix = substr($name,0,strpos($name,':')); - // get unqualified name - $name = substr(strstr($name,':'),1); - } - - // build to native type - if(isset($this->body_position) && $pos > $this->body_position){ - // deal w/ multirefs - if(isset($this->message[$pos]['attrs']['href'])){ - // get id - $id = substr($this->message[$pos]['attrs']['href'],1); - // add placeholder to href array - $this->multirefs[$id][$pos] = 'placeholder'; - // add set a reference to it as the result value - $this->message[$pos]['result'] =& $this->multirefs[$id][$pos]; - // build complexType values - } elseif($this->message[$pos]['children'] != ''){ - // if result has already been generated (struct/array) - if(!isset($this->message[$pos]['result'])){ - $this->message[$pos]['result'] = $this->buildVal($pos); - } - // build complexType values of attributes and possibly simpleContent - } elseif (isset($this->message[$pos]['xattrs'])) { - if (isset($this->message[$pos]['nil']) && $this->message[$pos]['nil']) { - $this->message[$pos]['xattrs']['!'] = null; - } elseif (isset($this->message[$pos]['cdata']) && trim($this->message[$pos]['cdata']) != '') { - if (isset($this->message[$pos]['type'])) { - $this->message[$pos]['xattrs']['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : ''); - } else { - $parent = $this->message[$pos]['parent']; - if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) { - $this->message[$pos]['xattrs']['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : ''); - } else { - $this->message[$pos]['xattrs']['!'] = $this->message[$pos]['cdata']; - } - } - } - $this->message[$pos]['result'] = $this->message[$pos]['xattrs']; - // set value of simpleType (or nil complexType) - } else { - //$this->debug('adding data for scalar value '.$this->message[$pos]['name'].' of value '.$this->message[$pos]['cdata']); - if (isset($this->message[$pos]['nil']) && $this->message[$pos]['nil']) { - $this->message[$pos]['xattrs']['!'] = null; - } elseif (isset($this->message[$pos]['type'])) { - $this->message[$pos]['result'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : ''); - } else { - $parent = $this->message[$pos]['parent']; - if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) { - $this->message[$pos]['result'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : ''); - } else { - $this->message[$pos]['result'] = $this->message[$pos]['cdata']; - } - } - - /* add value to parent's result, if parent is struct/array - $parent = $this->message[$pos]['parent']; - if($this->message[$parent]['type'] != 'map'){ - if(strtolower($this->message[$parent]['type']) == 'array'){ - $this->message[$parent]['result'][] = $this->message[$pos]['result']; - } else { - $this->message[$parent]['result'][$this->message[$pos]['name']] = $this->message[$pos]['result']; - } - } - */ - } - } - - // for doclit - if($this->status == 'header'){ - if ($this->root_header != $pos) { - $this->responseHeaders .= ""; - } - } elseif($pos >= $this->root_struct){ - $this->document .= ""; - } - // switch status - if($pos == $this->root_struct){ - $this->status = 'body'; - $this->root_struct_namespace = $this->message[$pos]['namespace']; - } elseif($name == 'Body'){ - $this->status = 'envelope'; - } elseif($name == 'Header'){ - $this->status = 'envelope'; - } elseif($name == 'Envelope'){ - // - } - // set parent back to my parent - $this->parent = $this->message[$pos]['parent']; - } - - /** - * element content handler - * - * @param resource $parser XML parser object - * @param string $data element content - * @access private - */ - function character_data($parser, $data){ - $pos = $this->depth_array[$this->depth]; - if ($this->xml_encoding=='UTF-8'){ - // TODO: add an option to disable this for folks who want - // raw UTF-8 that, e.g., might not map to iso-8859-1 - // TODO: this can also be handled with xml_parser_set_option($this->parser, XML_OPTION_TARGET_ENCODING, "ISO-8859-1"); - if($this->decode_utf8){ - $data = utf8_decode($data); - } - } - $this->message[$pos]['cdata'] .= $data; - // for doclit - if($this->status == 'header'){ - $this->responseHeaders .= $data; - } else { - $this->document .= $data; - } - } - - /** - * get the parsed message - * - * @return mixed - * @access public - */ - function get_response(){ - return $this->soapresponse; - } - - /** - * get the parsed headers - * - * @return string XML or empty if no headers - * @access public - */ - function getHeaders(){ - return $this->responseHeaders; - } - - /** - * decodes simple types into PHP variables - * - * @param string $value value to decode - * @param string $type XML type to decode - * @param string $typens XML type namespace to decode - * @return mixed PHP value - * @access private - */ - function decodeSimple($value, $type, $typens) { - // TODO: use the namespace! - if ((!isset($type)) || $type == 'string' || $type == 'long' || $type == 'unsignedLong') { - return (string) $value; - } - if ($type == 'int' || $type == 'integer' || $type == 'short' || $type == 'byte') { - return (int) $value; - } - if ($type == 'float' || $type == 'double' || $type == 'decimal') { - return (double) $value; - } - if ($type == 'boolean') { - if (strtolower($value) == 'false' || strtolower($value) == 'f') { - return false; - } - return (boolean) $value; - } - if ($type == 'base64' || $type == 'base64Binary') { - $this->debug('Decode base64 value'); - return base64_decode($value); - } - // obscure numeric types - if ($type == 'nonPositiveInteger' || $type == 'negativeInteger' - || $type == 'nonNegativeInteger' || $type == 'positiveInteger' - || $type == 'unsignedInt' - || $type == 'unsignedShort' || $type == 'unsignedByte') { - return (int) $value; - } - // bogus: parser treats array with no elements as a simple type - if ($type == 'array') { - return array(); - } - // everything else - return (string) $value; - } - - /** - * builds response structures for compound values (arrays/structs) - * and scalars - * - * @param integer $pos position in node tree - * @return mixed PHP value - * @access private - */ - function buildVal($pos){ - if(!isset($this->message[$pos]['type'])){ - $this->message[$pos]['type'] = ''; - } - $this->debug('in buildVal() for '.$this->message[$pos]['name']."(pos $pos) of type ".$this->message[$pos]['type']); - // if there are children... - if($this->message[$pos]['children'] != ''){ - $this->debug('in buildVal, there are children'); - $children = explode('|',$this->message[$pos]['children']); - array_shift($children); // knock off empty - // md array - if(isset($this->message[$pos]['arrayCols']) && $this->message[$pos]['arrayCols'] != ''){ - $r=0; // rowcount - $c=0; // colcount - foreach($children as $child_pos){ - $this->debug("in buildVal, got an MD array element: $r, $c"); - $params[$r][] = $this->message[$child_pos]['result']; - $c++; - if($c == $this->message[$pos]['arrayCols']){ - $c = 0; - $r++; - } - } - // array - } elseif($this->message[$pos]['type'] == 'array' || $this->message[$pos]['type'] == 'Array'){ - $this->debug('in buildVal, adding array '.$this->message[$pos]['name']); - foreach($children as $child_pos){ - $params[] = &$this->message[$child_pos]['result']; - } - // apache Map type: java hashtable - } elseif($this->message[$pos]['type'] == 'Map' && $this->message[$pos]['type_namespace'] == 'http://xml.apache.org/xml-soap'){ - $this->debug('in buildVal, Java Map '.$this->message[$pos]['name']); - foreach($children as $child_pos){ - $kv = explode("|",$this->message[$child_pos]['children']); - $params[$this->message[$kv[1]]['result']] = &$this->message[$kv[2]]['result']; - } - // generic compound type - //} elseif($this->message[$pos]['type'] == 'SOAPStruct' || $this->message[$pos]['type'] == 'struct') { - } else { - // Apache Vector type: treat as an array - $this->debug('in buildVal, adding Java Vector '.$this->message[$pos]['name']); - if ($this->message[$pos]['type'] == 'Vector' && $this->message[$pos]['type_namespace'] == 'http://xml.apache.org/xml-soap') { - $notstruct = 1; - } else { - $notstruct = 0; - } - // - foreach($children as $child_pos){ - if($notstruct){ - $params[] = &$this->message[$child_pos]['result']; - } else { - if (isset($params[$this->message[$child_pos]['name']])) { - // de-serialize repeated element name into an array - if ((!is_array($params[$this->message[$child_pos]['name']])) || (!isset($params[$this->message[$child_pos]['name']][0]))) { - $params[$this->message[$child_pos]['name']] = array($params[$this->message[$child_pos]['name']]); - } - $params[$this->message[$child_pos]['name']][] = &$this->message[$child_pos]['result']; - } else { - $params[$this->message[$child_pos]['name']] = &$this->message[$child_pos]['result']; - } - } - } - } - if (isset($this->message[$pos]['xattrs'])) { - $this->debug('in buildVal, handling attributes'); - foreach ($this->message[$pos]['xattrs'] as $n => $v) { - $params[$n] = $v; - } - } - // handle simpleContent - if (isset($this->message[$pos]['cdata']) && trim($this->message[$pos]['cdata']) != '') { - $this->debug('in buildVal, handling simpleContent'); - if (isset($this->message[$pos]['type'])) { - $params['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : ''); - } else { - $parent = $this->message[$pos]['parent']; - if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) { - $params['!'] = $this->decodeSimple($this->message[$pos]['cdata'], $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : ''); - } else { - $params['!'] = $this->message[$pos]['cdata']; - } - } - } - return is_array($params) ? $params : array(); - } else { - $this->debug('in buildVal, no children, building scalar'); - $cdata = isset($this->message[$pos]['cdata']) ? $this->message[$pos]['cdata'] : ''; - if (isset($this->message[$pos]['type'])) { - return $this->decodeSimple($cdata, $this->message[$pos]['type'], isset($this->message[$pos]['type_namespace']) ? $this->message[$pos]['type_namespace'] : ''); - } - $parent = $this->message[$pos]['parent']; - if (isset($this->message[$parent]['type']) && ($this->message[$parent]['type'] == 'array') && isset($this->message[$parent]['arrayType'])) { - return $this->decodeSimple($cdata, $this->message[$parent]['arrayType'], isset($this->message[$parent]['arrayTypeNamespace']) ? $this->message[$parent]['arrayTypeNamespace'] : ''); - } - return $this->message[$pos]['cdata']; - } - } -} - - - -?>call( string methodname [ ,array parameters] ); -* -* // bye bye client -* unset($soapclient); -* -* @author Dietrich Ayala -* @version $Id: nusoap.php,v 1.94 2005/08/04 01:27:42 snichol Exp $ -* @access public -*/ -class soapclient extends nusoap_base { - - var $username = ''; - var $password = ''; - var $authtype = ''; - var $certRequest = array(); - var $requestHeaders = false; // SOAP headers in request (text) - var $responseHeaders = ''; // SOAP headers from response (incomplete namespace resolution) (text) - var $document = ''; // SOAP body response portion (incomplete namespace resolution) (text) - var $endpoint; - var $forceEndpoint = ''; // overrides WSDL endpoint - var $proxyhost = ''; - var $proxyport = ''; - var $proxyusername = ''; - var $proxypassword = ''; - var $xml_encoding = ''; // character set encoding of incoming (response) messages - var $http_encoding = false; - var $timeout = 0; // HTTP connection timeout - var $response_timeout = 30; // HTTP response timeout - var $endpointType = ''; // soap|wsdl, empty for WSDL initialization error - var $persistentConnection = false; - var $defaultRpcParams = false; // This is no longer used - var $request = ''; // HTTP request - var $response = ''; // HTTP response - var $responseData = ''; // SOAP payload of response - var $cookies = array(); // Cookies from response or for request - var $decode_utf8 = true; // toggles whether the parser decodes element content w/ utf8_decode() - var $operations = array(); // WSDL operations, empty for WSDL initialization error - - /* - * fault related variables - */ - /** - * @var fault - * @access public - */ - var $fault; - /** - * @var faultcode - * @access public - */ - var $faultcode; - /** - * @var faultstring - * @access public - */ - var $faultstring; - /** - * @var faultdetail - * @access public - */ - var $faultdetail; - - /** - * constructor - * - * @param mixed $endpoint SOAP server or WSDL URL (string), or wsdl instance (object) - * @param bool $wsdl optional, set to true if using WSDL - * @param int $portName optional portName in WSDL document - * @param string $proxyhost - * @param string $proxyport - * @param string $proxyusername - * @param string $proxypassword - * @param integer $timeout set the connection timeout - * @param integer $response_timeout set the response timeout - * @access public - */ - function soapclient($endpoint,$wsdl = false,$proxyhost = false,$proxyport = false,$proxyusername = false, $proxypassword = false, $timeout = 0, $response_timeout = 30){ - parent::nusoap_base(); - $this->endpoint = $endpoint; - $this->proxyhost = $proxyhost; - $this->proxyport = $proxyport; - $this->proxyusername = $proxyusername; - $this->proxypassword = $proxypassword; - $this->timeout = $timeout; - $this->response_timeout = $response_timeout; - - // make values - if($wsdl){ - if (is_object($endpoint) && (get_class($endpoint) == 'wsdl')) { - $this->wsdl = $endpoint; - $this->endpoint = $this->wsdl->wsdl; - $this->wsdlFile = $this->endpoint; - $this->debug('existing wsdl instance created from ' . $this->endpoint); - } else { - $this->wsdlFile = $this->endpoint; - - // instantiate wsdl object and parse wsdl file - $this->debug('instantiating wsdl class with doc: '.$endpoint); - $this->wsdl =& new wsdl($this->wsdlFile,$this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword,$this->timeout,$this->response_timeout); - } - $this->appendDebug($this->wsdl->getDebug()); - $this->wsdl->clearDebug(); - // catch errors - if($errstr = $this->wsdl->getError()){ - $this->debug('got wsdl error: '.$errstr); - $this->setError('wsdl error: '.$errstr); - } elseif($this->operations = $this->wsdl->getOperations()){ - $this->debug( 'got '.count($this->operations).' operations from wsdl '.$this->wsdlFile); - $this->endpointType = 'wsdl'; - } else { - $this->debug( 'getOperations returned false'); - $this->setError('no operations defined in the WSDL document!'); - } - } else { - $this->debug("instantiate SOAP with endpoint at $endpoint"); - $this->endpointType = 'soap'; - } - } - - /** - * calls method, returns PHP native type - * - * @param string $method SOAP server URL or path - * @param mixed $params An array, associative or simple, of the parameters - * for the method call, or a string that is the XML - * for the call. For rpc style, this call will - * wrap the XML in a tag named after the method, as - * well as the SOAP Envelope and Body. For document - * style, this will only wrap with the Envelope and Body. - * IMPORTANT: when using an array with document style, - * in which case there - * is really one parameter, the root of the fragment - * used in the call, which encloses what programmers - * normally think of parameters. A parameter array - * *must* include the wrapper. - * @param string $namespace optional method namespace (WSDL can override) - * @param string $soapAction optional SOAPAction value (WSDL can override) - * @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers - * @param boolean $rpcParams optional (no longer used) - * @param string $style optional (rpc|document) the style to use when serializing parameters (WSDL can override) - * @param string $use optional (encoded|literal) the use when serializing parameters (WSDL can override) - * @return mixed response from SOAP call - * @access public - */ - function call($operation,$params=array(),$namespace='http://tempuri.org',$soapAction='',$headers=false,$rpcParams=null,$style='rpc',$use='encoded'){ - $this->operation = $operation; - $this->fault = false; - $this->setError(''); - $this->request = ''; - $this->response = ''; - $this->responseData = ''; - $this->faultstring = ''; - $this->faultcode = ''; - $this->opData = array(); - - $this->debug("call: operation=$operation, namespace=$namespace, soapAction=$soapAction, rpcParams=$rpcParams, style=$style, use=$use, endpointType=$this->endpointType"); - $this->appendDebug('params=' . $this->varDump($params)); - $this->appendDebug('headers=' . $this->varDump($headers)); - if ($headers) { - $this->requestHeaders = $headers; - } - // serialize parameters - if($this->endpointType == 'wsdl' && $opData = $this->getOperationData($operation)){ - // use WSDL for operation - $this->opData = $opData; - $this->debug("found operation"); - $this->appendDebug('opData=' . $this->varDump($opData)); - if (isset($opData['soapAction'])) { - $soapAction = $opData['soapAction']; - } - if (! $this->forceEndpoint) { - $this->endpoint = $opData['endpoint']; - } else { - $this->endpoint = $this->forceEndpoint; - } - $namespace = isset($opData['input']['namespace']) ? $opData['input']['namespace'] : $namespace; - $style = $opData['style']; - $use = $opData['input']['use']; - // add ns to ns array - if($namespace != '' && !isset($this->wsdl->namespaces[$namespace])){ - $nsPrefix = 'ns' . rand(1000, 9999); - $this->wsdl->namespaces[$nsPrefix] = $namespace; - } - $nsPrefix = $this->wsdl->getPrefixFromNamespace($namespace); - // serialize payload - if (is_string($params)) { - $this->debug("serializing param string for WSDL operation $operation"); - $payload = $params; - } elseif (is_array($params)) { - $this->debug("serializing param array for WSDL operation $operation"); - $payload = $this->wsdl->serializeRPCParameters($operation,'input',$params); - } else { - $this->debug('params must be array or string'); - $this->setError('params must be array or string'); - return false; - } - $usedNamespaces = $this->wsdl->usedNamespaces; - if (isset($opData['input']['encodingStyle'])) { - $encodingStyle = $opData['input']['encodingStyle']; - } else { - $encodingStyle = ''; - } - $this->appendDebug($this->wsdl->getDebug()); - $this->wsdl->clearDebug(); - if ($errstr = $this->wsdl->getError()) { - $this->debug('got wsdl error: '.$errstr); - $this->setError('wsdl error: '.$errstr); - return false; - } - } elseif($this->endpointType == 'wsdl') { - // operation not in WSDL - $this->appendDebug($this->wsdl->getDebug()); - $this->wsdl->clearDebug(); - $this->setError( 'operation '.$operation.' not present.'); - $this->debug("operation '$operation' not present."); - return false; - } else { - // no WSDL - //$this->namespaces['ns1'] = $namespace; - $nsPrefix = 'ns' . rand(1000, 9999); - // serialize - $payload = ''; - if (is_string($params)) { - $this->debug("serializing param string for operation $operation"); - $payload = $params; - } elseif (is_array($params)) { - $this->debug("serializing param array for operation $operation"); - foreach($params as $k => $v){ - $payload .= $this->serialize_val($v,$k,false,false,false,false,$use); - } - } else { - $this->debug('params must be array or string'); - $this->setError('params must be array or string'); - return false; - } - $usedNamespaces = array(); - if ($use == 'encoded') { - $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; - } else { - $encodingStyle = ''; - } - } - // wrap RPC calls with method element - if ($style == 'rpc') { - if ($use == 'literal') { - $this->debug("wrapping RPC request with literal method element"); - if ($namespace) { - $payload = "<$operation xmlns=\"$namespace\">" . $payload . ""; - } else { - $payload = "<$operation>" . $payload . ""; - } - } else { - $this->debug("wrapping RPC request with encoded method element"); - if ($namespace) { - $payload = "<$nsPrefix:$operation xmlns:$nsPrefix=\"$namespace\">" . - $payload . - ""; - } else { - $payload = "<$operation>" . - $payload . - ""; - } - } - } - // serialize envelope - $soapmsg = $this->serializeEnvelope($payload,$this->requestHeaders,$usedNamespaces,$style,$use,$encodingStyle); - $this->debug("endpoint=$this->endpoint, soapAction=$soapAction, namespace=$namespace, style=$style, use=$use, encodingStyle=$encodingStyle"); - $this->debug('SOAP message length=' . strlen($soapmsg) . ' contents (max 1000 bytes)=' . substr($soapmsg, 0, 1000)); - // send - $return = $this->send($this->getHTTPBody($soapmsg),$soapAction,$this->timeout,$this->response_timeout); - if($errstr = $this->getError()){ - $this->debug('Error: '.$errstr); - return false; - } else { - $this->return = $return; - $this->debug('sent message successfully and got a(n) '.gettype($return)); - $this->appendDebug('return=' . $this->varDump($return)); - - // fault? - if(is_array($return) && isset($return['faultcode'])){ - $this->debug('got fault'); - $this->setError($return['faultcode'].': '.$return['faultstring']); - $this->fault = true; - foreach($return as $k => $v){ - $this->$k = $v; - $this->debug("$k = $v
"); - } - return $return; - } elseif ($style == 'document') { - // NOTE: if the response is defined to have multiple parts (i.e. unwrapped), - // we are only going to return the first part here...sorry about that - return $return; - } else { - // array of return values - if(is_array($return)){ - // multiple 'out' parameters, which we return wrapped up - // in the array - if(sizeof($return) > 1){ - return $return; - } - // single 'out' parameter (normally the return value) - $return = array_shift($return); - $this->debug('return shifted value: '); - $this->appendDebug($this->varDump($return)); - return $return; - // nothing returned (ie, echoVoid) - } else { - return ""; - } - } - } - } - - /** - * get available data pertaining to an operation - * - * @param string $operation operation name - * @return array array of data pertaining to the operation - * @access public - */ - function getOperationData($operation){ - if(isset($this->operations[$operation])){ - return $this->operations[$operation]; - } - $this->debug("No data for operation: $operation"); - } - - /** - * send the SOAP message - * - * Note: if the operation has multiple return values - * the return value of this method will be an array - * of those values. - * - * @param string $msg a SOAPx4 soapmsg object - * @param string $soapaction SOAPAction value - * @param integer $timeout set connection timeout in seconds - * @param integer $response_timeout set response timeout in seconds - * @return mixed native PHP types. - * @access private - */ - function send($msg, $soapaction = '', $timeout=0, $response_timeout=30) { - $this->checkCookies(); - // detect transport - switch(true){ - // http(s) - case ereg('^http',$this->endpoint): - $this->debug('transporting via HTTP'); - if($this->persistentConnection == true && is_object($this->persistentConnection)){ - $http =& $this->persistentConnection; - } else { - $http = new soap_transport_http($this->endpoint); - if ($this->persistentConnection) { - $http->usePersistentConnection(); - } - } - $http->setContentType($this->getHTTPContentType(), $this->getHTTPContentTypeCharset()); - $http->setSOAPAction($soapaction); - if($this->proxyhost && $this->proxyport){ - $http->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword); - } - if($this->authtype != '') { - $http->setCredentials($this->username, $this->password, $this->authtype, array(), $this->certRequest); - } - if($this->http_encoding != ''){ - $http->setEncoding($this->http_encoding); - } - $this->debug('sending message, length='.strlen($msg)); - if(ereg('^http:',$this->endpoint)){ - //if(strpos($this->endpoint,'http:')){ - $this->responseData = $http->send($msg,$timeout,$response_timeout,$this->cookies); - } elseif(ereg('^https',$this->endpoint)){ - //} elseif(strpos($this->endpoint,'https:')){ - //if(phpversion() == '4.3.0-dev'){ - //$response = $http->send($msg,$timeout,$response_timeout); - //$this->request = $http->outgoing_payload; - //$this->response = $http->incoming_payload; - //} else - $this->responseData = $http->sendHTTPS($msg,$timeout,$response_timeout,$this->cookies); - } else { - $this->setError('no http/s in endpoint url'); - } - $this->request = $http->outgoing_payload; - $this->response = $http->incoming_payload; - $this->appendDebug($http->getDebug()); - $this->UpdateCookies($http->incoming_cookies); - - // save transport object if using persistent connections - if ($this->persistentConnection) { - $http->clearDebug(); - if (!is_object($this->persistentConnection)) { - $this->persistentConnection = $http; - } - } - - if($err = $http->getError()){ - $this->setError('HTTP Error: '.$err); - return false; - } elseif($this->getError()){ - return false; - } else { - $this->debug('got response, length='. strlen($this->responseData).' type='.$http->incoming_headers['content-type']); - return $this->parseResponse($http->incoming_headers, $this->responseData); - } - break; - default: - $this->setError('no transport found, or selected transport is not yet supported!'); - return false; - break; - } - } - - /** - * processes SOAP message returned from server - * - * @param array $headers The HTTP headers - * @param string $data unprocessed response data from server - * @return mixed value of the message, decoded into a PHP type - * @access private - */ - function parseResponse($headers, $data) { - $this->debug('Entering parseResponse() for data of length ' . strlen($data) . ' and type ' . $headers['content-type']); - if (!strstr($headers['content-type'], 'text/xml')) { - $this->setError('Response not of type text/xml'); - return false; - } - if (strpos($headers['content-type'], '=')) { - $enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1)); - $this->debug('Got response encoding: ' . $enc); - if(preg_match('/(ISO-8859-1|US-ASCII|UTF-8)/',$enc)){ - $this->xml_encoding = strtoupper($enc); - } else { - $this->xml_encoding = 'US-ASCII'; - } - } else { - // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 - $this->xml_encoding = 'ISO-8859-1'; - } - $this->debug('Use encoding: ' . $this->xml_encoding . ' when creating soap_parser'); - $parser = new soap_parser($data,$this->xml_encoding,$this->operation,$this->decode_utf8); - // add parser debug data to our debug - $this->appendDebug($parser->getDebug()); - // if parse errors - if($errstr = $parser->getError()){ - $this->setError( $errstr); - // destroy the parser object - unset($parser); - return false; - } else { - // get SOAP headers - $this->responseHeaders = $parser->getHeaders(); - // get decoded message - $return = $parser->get_response(); - // add document for doclit support - $this->document = $parser->document; - // destroy the parser object - unset($parser); - // return decode message - return $return; - } - } - - /** - * sets the SOAP endpoint, which can override WSDL - * - * @param $endpoint string The endpoint URL to use, or empty string or false to prevent override - * @access public - */ - function setEndpoint($endpoint) { - $this->forceEndpoint = $endpoint; - } - - /** - * set the SOAP headers - * - * @param $headers mixed String of XML with SOAP header content, or array of soapval objects for SOAP headers - * @access public - */ - function setHeaders($headers){ - $this->requestHeaders = $headers; - } - - /** - * get the SOAP response headers (namespace resolution incomplete) - * - * @return string - * @access public - */ - function getHeaders(){ - return $this->responseHeaders; - } - - /** - * set proxy info here - * - * @param string $proxyhost - * @param string $proxyport - * @param string $proxyusername - * @param string $proxypassword - * @access public - */ - function setHTTPProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '') { - $this->proxyhost = $proxyhost; - $this->proxyport = $proxyport; - $this->proxyusername = $proxyusername; - $this->proxypassword = $proxypassword; - } - - /** - * if authenticating, set user credentials here - * - * @param string $username - * @param string $password - * @param string $authtype (basic|digest|certificate) - * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs) - * @access public - */ - function setCredentials($username, $password, $authtype = 'basic', $certRequest = array()) { - $this->username = $username; - $this->password = $password; - $this->authtype = $authtype; - $this->certRequest = $certRequest; - } - - /** - * use HTTP encoding - * - * @param string $enc - * @access public - */ - function setHTTPEncoding($enc='gzip, deflate'){ - $this->http_encoding = $enc; - } - - /** - * use HTTP persistent connections if possible - * - * @access public - */ - function useHTTPPersistentConnection(){ - $this->persistentConnection = true; - } - - /** - * gets the default RPC parameter setting. - * If true, default is that call params are like RPC even for document style. - * Each call() can override this value. - * - * This is no longer used. - * - * @return boolean - * @access public - * @deprecated - */ - function getDefaultRpcParams() { - return $this->defaultRpcParams; - } - - /** - * sets the default RPC parameter setting. - * If true, default is that call params are like RPC even for document style - * Each call() can override this value. - * - * This is no longer used. - * - * @param boolean $rpcParams - * @access public - * @deprecated - */ - function setDefaultRpcParams($rpcParams) { - $this->defaultRpcParams = $rpcParams; - } - - /** - * dynamically creates an instance of a proxy class, - * allowing user to directly call methods from wsdl - * - * @return object soap_proxy object - * @access public - */ - function getProxy(){ - $r = rand(); - $evalStr = $this->_getProxyClassCode($r); - //$this->debug("proxy class: $evalStr"; - // eval the class - eval($evalStr); - // instantiate proxy object - eval("\$proxy = new soap_proxy_$r('');"); - // transfer current wsdl data to the proxy thereby avoiding parsing the wsdl twice - $proxy->endpointType = 'wsdl'; - $proxy->wsdlFile = $this->wsdlFile; - $proxy->wsdl = $this->wsdl; - $proxy->operations = $this->operations; - $proxy->defaultRpcParams = $this->defaultRpcParams; - // transfer other state - $proxy->username = $this->username; - $proxy->password = $this->password; - $proxy->authtype = $this->authtype; - $proxy->proxyhost = $this->proxyhost; - $proxy->proxyport = $this->proxyport; - $proxy->proxyusername = $this->proxyusername; - $proxy->proxypassword = $this->proxypassword; - $proxy->timeout = $this->timeout; - $proxy->response_timeout = $this->response_timeout; - $proxy->http_encoding = $this->http_encoding; - $proxy->persistentConnection = $this->persistentConnection; - $proxy->requestHeaders = $this->requestHeaders; - $proxy->soap_defencoding = $this->soap_defencoding; - $proxy->endpoint = $this->endpoint; - $proxy->forceEndpoint = $this->forceEndpoint; - return $proxy; - } - - /** - * dynamically creates proxy class code - * - * @return string PHP/NuSOAP code for the proxy class - * @access private - */ - function _getProxyClassCode($r) { - if ($this->endpointType != 'wsdl') { - $evalStr = 'A proxy can only be created for a WSDL client'; - $this->setError($evalStr); - return $evalStr; - } - $evalStr = ''; - foreach ($this->operations as $operation => $opData) { - if ($operation != '') { - // create param string and param comment string - if (sizeof($opData['input']['parts']) > 0) { - $paramStr = ''; - $paramArrayStr = ''; - $paramCommentStr = ''; - foreach ($opData['input']['parts'] as $name => $type) { - $paramStr .= "\$$name, "; - $paramArrayStr .= "'$name' => \$$name, "; - $paramCommentStr .= "$type \$$name, "; - } - $paramStr = substr($paramStr, 0, strlen($paramStr)-2); - $paramArrayStr = substr($paramArrayStr, 0, strlen($paramArrayStr)-2); - $paramCommentStr = substr($paramCommentStr, 0, strlen($paramCommentStr)-2); - } else { - $paramStr = ''; - $paramCommentStr = 'void'; - } - $opData['namespace'] = !isset($opData['namespace']) ? 'http://testuri.com' : $opData['namespace']; - $evalStr .= "// $paramCommentStr - function " . str_replace('.', '__', $operation) . "($paramStr) { - \$params = array($paramArrayStr); - return \$this->call('$operation', \$params, '".$opData['namespace']."', '".(isset($opData['soapAction']) ? $opData['soapAction'] : '')."'); - } - "; - unset($paramStr); - unset($paramCommentStr); - } - } - $evalStr = 'class soap_proxy_'.$r.' extends soapclient { - '.$evalStr.' -}'; - return $evalStr; - } - - /** - * dynamically creates proxy class code - * - * @return string PHP/NuSOAP code for the proxy class - * @access public - */ - function getProxyClassCode() { - $r = rand(); - return $this->_getProxyClassCode($r); - } - - /** - * gets the HTTP body for the current request. - * - * @param string $soapmsg The SOAP payload - * @return string The HTTP body, which includes the SOAP payload - * @access private - */ - function getHTTPBody($soapmsg) { - return $soapmsg; - } - - /** - * gets the HTTP content type for the current request. - * - * Note: getHTTPBody must be called before this. - * - * @return string the HTTP content type for the current request. - * @access private - */ - function getHTTPContentType() { - return 'text/xml'; - } - - /** - * gets the HTTP content type charset for the current request. - * returns false for non-text content types. - * - * Note: getHTTPBody must be called before this. - * - * @return string the HTTP content type charset for the current request. - * @access private - */ - function getHTTPContentTypeCharset() { - return $this->soap_defencoding; - } - - /* - * whether or not parser should decode utf8 element content - * - * @return always returns true - * @access public - */ - function decodeUTF8($bool){ - $this->decode_utf8 = $bool; - return true; - } - - /** - * adds a new Cookie into $this->cookies array - * - * @param string $name Cookie Name - * @param string $value Cookie Value - * @return if cookie-set was successful returns true, else false - * @access public - */ - function setCookie($name, $value) { - if (strlen($name) == 0) { - return false; - } - $this->cookies[] = array('name' => $name, 'value' => $value); - return true; - } - - /** - * gets all Cookies - * - * @return array with all internal cookies - * @access public - */ - function getCookies() { - return $this->cookies; - } - - /** - * checks all Cookies and delete those which are expired - * - * @return always return true - * @access private - */ - function checkCookies() { - if (sizeof($this->cookies) == 0) { - return true; - } - $this->debug('checkCookie: check ' . sizeof($this->cookies) . ' cookies'); - $curr_cookies = $this->cookies; - $this->cookies = array(); - foreach ($curr_cookies as $cookie) { - if (! is_array($cookie)) { - $this->debug('Remove cookie that is not an array'); - continue; - } - if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) { - if (strtotime($cookie['expires']) > time()) { - $this->cookies[] = $cookie; - } else { - $this->debug('Remove expired cookie ' . $cookie['name']); - } - } else { - $this->cookies[] = $cookie; - } - } - $this->debug('checkCookie: '.sizeof($this->cookies).' cookies left in array'); - return true; - } - - /** - * updates the current cookies with a new set - * - * @param array $cookies new cookies with which to update current ones - * @return always return true - * @access private - */ - function UpdateCookies($cookies) { - if (sizeof($this->cookies) == 0) { - // no existing cookies: take whatever is new - if (sizeof($cookies) > 0) { - $this->debug('Setting new cookie(s)'); - $this->cookies = $cookies; - } - return true; - } - if (sizeof($cookies) == 0) { - // no new cookies: keep what we've got - return true; - } - // merge - foreach ($cookies as $newCookie) { - if (!is_array($newCookie)) { - continue; - } - if ((!isset($newCookie['name'])) || (!isset($newCookie['value']))) { - continue; - } - $newName = $newCookie['name']; - - $found = false; - for ($i = 0; $i < count($this->cookies); $i++) { - $cookie = $this->cookies[$i]; - if (!is_array($cookie)) { - continue; - } - if (!isset($cookie['name'])) { - continue; - } - if ($newName != $cookie['name']) { - continue; - } - $newDomain = isset($newCookie['domain']) ? $newCookie['domain'] : 'NODOMAIN'; - $domain = isset($cookie['domain']) ? $cookie['domain'] : 'NODOMAIN'; - if ($newDomain != $domain) { - continue; - } - $newPath = isset($newCookie['path']) ? $newCookie['path'] : 'NOPATH'; - $path = isset($cookie['path']) ? $cookie['path'] : 'NOPATH'; - if ($newPath != $path) { - continue; - } - $this->cookies[$i] = $newCookie; - $found = true; - $this->debug('Update cookie ' . $newName . '=' . $newCookie['value']); - break; - } - if (! $found) { - $this->debug('Add cookie ' . $newName . '=' . $newCookie['value']); - $this->cookies[] = $newCookie; - } - } - return true; - } -} -?> diff --git a/gulliver/thirdparty/pear/nusoapmime.php b/gulliver/thirdparty/pear/nusoapmime.php deleted file mode 100644 index 51adcfefe..000000000 --- a/gulliver/thirdparty/pear/nusoapmime.php +++ /dev/null @@ -1,506 +0,0 @@ - -* @author Thanks to Guillaume and Henning Reich for posting great attachment code to the mail list -* @version $Id: nusoapmime.php,v 1.7 2005/07/27 19:24:42 snichol Exp $ -* @access public -*/ -class soapclientmime extends soapclient { - /** - * @var array Each array element in the return is an associative array with keys - * data, filename, contenttype, cid - * @access private - */ - var $requestAttachments = array(); - /** - * @var array Each array element in the return is an associative array with keys - * data, filename, contenttype, cid - * @access private - */ - var $responseAttachments; - /** - * @var string - * @access private - */ - var $mimeContentType; - - /** - * adds a MIME attachment to the current request. - * - * If the $data parameter contains an empty string, this method will read - * the contents of the file named by the $filename parameter. - * - * If the $cid parameter is false, this method will generate the cid. - * - * @param string $data The data of the attachment - * @param string $filename The filename of the attachment (default is empty string) - * @param string $contenttype The MIME Content-Type of the attachment (default is application/octet-stream) - * @param string $cid The content-id (cid) of the attachment (default is false) - * @return string The content-id (cid) of the attachment - * @access public - */ - function addAttachment($data, $filename = '', $contenttype = 'application/octet-stream', $cid = false) { - if (! $cid) { - $cid = $this->encryptOld(uniqid(time())); - } - - $info['data'] = $data; - $info['filename'] = $filename; - $info['contenttype'] = $contenttype; - $info['cid'] = $cid; - - $this->requestAttachments[] = $info; - - return $cid; - } - - /** - * clears the MIME attachments for the current request. - * - * @access public - */ - function clearAttachments() { - $this->requestAttachments = array(); - } - - /** - * gets the MIME attachments from the current response. - * - * Each array element in the return is an associative array with keys - * data, filename, contenttype, cid. These keys correspond to the parameters - * for addAttachment. - * - * @return array The attachments. - * @access public - */ - function getAttachments() { - return $this->responseAttachments; - } - - /** - * gets the HTTP body for the current request. - * - * @param string $soapmsg The SOAP payload - * @return string The HTTP body, which includes the SOAP payload - * @access private - */ - function getHTTPBody($soapmsg) { - if (count($this->requestAttachments) > 0) { - $params['content_type'] = 'multipart/related; type=text/xml'; - $mimeMessage =& new Mail_mimePart('', $params); - unset($params); - - $params['content_type'] = 'text/xml'; - $params['encoding'] = '8bit'; - $params['charset'] = $this->soap_defencoding; - $mimeMessage->addSubpart($soapmsg, $params); - - foreach ($this->requestAttachments as $att) { - unset($params); - - $params['content_type'] = $att['contenttype']; - $params['encoding'] = 'base64'; - $params['disposition'] = 'attachment'; - $params['dfilename'] = $att['filename']; - $params['cid'] = $att['cid']; - - if ($att['data'] == '' && $att['filename'] <> '') { - if ($fd = fopen($att['filename'], 'rb')) { - $data = fread($fd, filesize($att['filename'])); - fclose($fd); - } else { - $data = ''; - } - $mimeMessage->addSubpart($data, $params); - } else { - $mimeMessage->addSubpart($att['data'], $params); - } - } - - $output = $mimeMessage->encode(); - $mimeHeaders = $output['headers']; - - foreach ($mimeHeaders as $k => $v) { - $this->debug("MIME header $k: $v"); - if (strtolower($k) == 'content-type') { - // PHP header() seems to strip leading whitespace starting - // the second line, so force everything to one line - $this->mimeContentType = str_replace("\r\n", " ", $v); - } - } - - return $output['body']; - } - - return parent::getHTTPBody($soapmsg); - } - - /** - * gets the HTTP content type for the current request. - * - * Note: getHTTPBody must be called before this. - * - * @return string the HTTP content type for the current request. - * @access private - */ - function getHTTPContentType() { - if (count($this->requestAttachments) > 0) { - return $this->mimeContentType; - } - return parent::getHTTPContentType(); - } - - /** - * gets the HTTP content type charset for the current request. - * returns false for non-text content types. - * - * Note: getHTTPBody must be called before this. - * - * @return string the HTTP content type charset for the current request. - * @access private - */ - function getHTTPContentTypeCharset() { - if (count($this->requestAttachments) > 0) { - return false; - } - return parent::getHTTPContentTypeCharset(); - } - - /** - * processes SOAP message returned from server - * - * @param array $headers The HTTP headers - * @param string $data unprocessed response data from server - * @return mixed value of the message, decoded into a PHP type - * @access private - */ - function parseResponse($headers, $data) { - $this->debug('Entering parseResponse() for payload of length ' . strlen($data) . ' and type of ' . $headers['content-type']); - $this->responseAttachments = array(); - if (strstr($headers['content-type'], 'multipart/related')) { - $this->debug('Decode multipart/related'); - $input = ''; - foreach ($headers as $k => $v) { - $input .= "$k: $v\r\n"; - } - $params['input'] = $input . "\r\n" . $data; - $params['include_bodies'] = true; - $params['decode_bodies'] = true; - $params['decode_headers'] = true; - - $structure = Mail_mimeDecode::decode($params); - - foreach ($structure->parts as $part) { - if (!isset($part->disposition)) { - $this->debug('Have root part of type ' . $part->headers['content-type']); - $return = parent::parseResponse($part->headers, $part->body); - } else { - $this->debug('Have an attachment of type ' . $part->headers['content-type']); - $info['data'] = $part->body; - $info['filename'] = isset($part->d_parameters['filename']) ? $part->d_parameters['filename'] : ''; - $info['contenttype'] = $part->headers['content-type']; - $info['cid'] = $part->headers['content-id']; - $this->responseAttachments[] = $info; - } - } - - if (isset($return)) { - return $return; - } - - $this->setError('No root part found in multipart/related content'); - return; - } - $this->debug('Not multipart/related'); - return parent::parseResponse($headers, $data); - } - - 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); - } -} - -/** -* nusoapservermime server supporting MIME attachments defined at -* http://www.w3.org/TR/SOAP-attachments. It depends on the PEAR Mail_MIME library. -* -* @author Scott Nichol -* @author Thanks to Guillaume and Henning Reich for posting great attachment code to the mail list -* @version $Id: nusoapmime.php,v 1.7 2005/07/27 19:24:42 snichol Exp $ -* @access public -*/ -class nusoapservermime extends soap_server { - /** - * @var array Each array element in the return is an associative array with keys - * data, filename, contenttype, cid - * @access private - */ - var $requestAttachments = array(); - /** - * @var array Each array element in the return is an associative array with keys - * data, filename, contenttype, cid - * @access private - */ - var $responseAttachments; - /** - * @var string - * @access private - */ - var $mimeContentType; - - /** - * adds a MIME attachment to the current response. - * - * If the $data parameter contains an empty string, this method will read - * the contents of the file named by the $filename parameter. - * - * If the $cid parameter is false, this method will generate the cid. - * - * @param string $data The data of the attachment - * @param string $filename The filename of the attachment (default is empty string) - * @param string $contenttype The MIME Content-Type of the attachment (default is application/octet-stream) - * @param string $cid The content-id (cid) of the attachment (default is false) - * @return string The content-id (cid) of the attachment - * @access public - */ - function addAttachment($data, $filename = '', $contenttype = 'application/octet-stream', $cid = false) { - if (! $cid) { - $cid = $this->encryptOldNusoap(uniqid(time())); - } - - $info['data'] = $data; - $info['filename'] = $filename; - $info['contenttype'] = $contenttype; - $info['cid'] = $cid; - - $this->responseAttachments[] = $info; - - return $cid; - } - - /** - * clears the MIME attachments for the current response. - * - * @access public - */ - function clearAttachments() { - $this->responseAttachments = array(); - } - - /** - * gets the MIME attachments from the current request. - * - * Each array element in the return is an associative array with keys - * data, filename, contenttype, cid. These keys correspond to the parameters - * for addAttachment. - * - * @return array The attachments. - * @access public - */ - function getAttachments() { - return $this->requestAttachments; - } - - /** - * gets the HTTP body for the current response. - * - * @param string $soapmsg The SOAP payload - * @return string The HTTP body, which includes the SOAP payload - * @access private - */ - function getHTTPBody($soapmsg) { - if (count($this->responseAttachments) > 0) { - $params['content_type'] = 'multipart/related; type=text/xml'; - $mimeMessage =& new Mail_mimePart('', $params); - unset($params); - - $params['content_type'] = 'text/xml'; - $params['encoding'] = '8bit'; - $params['charset'] = $this->soap_defencoding; - $mimeMessage->addSubpart($soapmsg, $params); - - foreach ($this->responseAttachments as $att) { - unset($params); - - $params['content_type'] = $att['contenttype']; - $params['encoding'] = 'base64'; - $params['disposition'] = 'attachment'; - $params['dfilename'] = $att['filename']; - $params['cid'] = $att['cid']; - - if ($att['data'] == '' && $att['filename'] <> '') { - if ($fd = fopen($att['filename'], 'rb')) { - $data = fread($fd, filesize($att['filename'])); - fclose($fd); - } else { - $data = ''; - } - $mimeMessage->addSubpart($data, $params); - } else { - $mimeMessage->addSubpart($att['data'], $params); - } - } - - $output = $mimeMessage->encode(); - $mimeHeaders = $output['headers']; - - foreach ($mimeHeaders as $k => $v) { - $this->debug("MIME header $k: $v"); - if (strtolower($k) == 'content-type') { - // PHP header() seems to strip leading whitespace starting - // the second line, so force everything to one line - $this->mimeContentType = str_replace("\r\n", " ", $v); - } - } - - return $output['body']; - } - - return parent::getHTTPBody($soapmsg); - } - - /** - * gets the HTTP content type for the current response. - * - * Note: getHTTPBody must be called before this. - * - * @return string the HTTP content type for the current response. - * @access private - */ - function getHTTPContentType() { - if (count($this->responseAttachments) > 0) { - return $this->mimeContentType; - } - return parent::getHTTPContentType(); - } - - /** - * gets the HTTP content type charset for the current response. - * returns false for non-text content types. - * - * Note: getHTTPBody must be called before this. - * - * @return string the HTTP content type charset for the current response. - * @access private - */ - function getHTTPContentTypeCharset() { - if (count($this->responseAttachments) > 0) { - return false; - } - return parent::getHTTPContentTypeCharset(); - } - - /** - * processes SOAP message received from client - * - * @param array $headers The HTTP headers - * @param string $data unprocessed request data from client - * @return mixed value of the message, decoded into a PHP type - * @access private - */ - function parseRequest($headers, $data) { - $this->debug('Entering parseRequest() for payload of length ' . strlen($data) . ' and type of ' . $headers['content-type']); - $this->requestAttachments = array(); - if (strstr($headers['content-type'], 'multipart/related')) { - $this->debug('Decode multipart/related'); - $input = ''; - foreach ($headers as $k => $v) { - $input .= "$k: $v\r\n"; - } - $params['input'] = $input . "\r\n" . $data; - $params['include_bodies'] = true; - $params['decode_bodies'] = true; - $params['decode_headers'] = true; - - $structure = Mail_mimeDecode::decode($params); - - foreach ($structure->parts as $part) { - if (!isset($part->disposition)) { - $this->debug('Have root part of type ' . $part->headers['content-type']); - $return = parent::parseRequest($part->headers, $part->body); - } else { - $this->debug('Have an attachment of type ' . $part->headers['content-type']); - $info['data'] = $part->body; - $info['filename'] = isset($part->d_parameters['filename']) ? $part->d_parameters['filename'] : ''; - $info['contenttype'] = $part->headers['content-type']; - $info['cid'] = $part->headers['content-id']; - $this->requestAttachments[] = $info; - } - } - - if (isset($return)) { - return $return; - } - - $this->setError('No root part found in multipart/related content'); - return; - } - $this->debug('Not multipart/related'); - return parent::parseRequest($headers, $data); - } - - public function encryptOldNusoap($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); - } -} -?> diff --git a/gulliver/thirdparty/pear/package-Archive_Tar.xml b/gulliver/thirdparty/pear/package-Archive_Tar.xml deleted file mode 100644 index 64ee07b5c..000000000 --- a/gulliver/thirdparty/pear/package-Archive_Tar.xml +++ /dev/null @@ -1,60 +0,0 @@ - - - - Archive_Tar - Tar file management class - This class provides handling of tar files in PHP. -It supports creating, listing, extracting and adding to tar files. -Gzip support is available if PHP has the zlib extension built-in or -loaded. - - PHP License - - - vblavet - lead - Vincent Blavet - vincent@blavet.net - - - ssb - helper - Stig Sæther Bakken - stig@php.net - - - - 0.9 - 2002-05-27 - - * Auto-detect gzip'ed files - - stable - - - - - - - - - - 0.4 - 2002-05-20 - Windows bugfix: use forward slashes inside archives - stable - - - 0.2 - 2002-02-18 - From initial commit to stable - stable - - - 0.3 - 2002-04-13 - Windows bugfix: used wrong directory separators - stable - - - diff --git a/gulliver/thirdparty/pear/package-Console_Getopt.xml b/gulliver/thirdparty/pear/package-Console_Getopt.xml deleted file mode 100644 index 1bc3eb02d..000000000 --- a/gulliver/thirdparty/pear/package-Console_Getopt.xml +++ /dev/null @@ -1,63 +0,0 @@ - - - - - Console_Getopt - Command-line option parser - This is a PHP implementation of "getopt" supporting both -short and long options. - PHP License - - - andrei - lead - Andrei Zmievski - andrei@php.net - - - ssb - developer - Stig Bakken - stig@php.net - - - - 1.0 - 2002-09-13 - Stable release - stable - - - - - - - - - 0.11 - 2002-05-26 - POSIX getopt compatibility fix: treat first element of args - array as command name - - beta - - - - - - - - 0.10 - 2002-05-12 - Packaging fix - beta - - - 0.9 - 2002-05-12 - Initial release - beta - - - diff --git a/gulliver/thirdparty/pear/package-PEAR.xml b/gulliver/thirdparty/pear/package-PEAR.xml deleted file mode 100644 index ad739feae..000000000 --- a/gulliver/thirdparty/pear/package-PEAR.xml +++ /dev/null @@ -1,342 +0,0 @@ - - - - PEAR - PEAR Base System - The PEAR package contains: - * the PEAR base class - * the PEAR_Error error handling mechanism - * the PEAR installer, for creating, distributing - and installing packages - - PHP License - - - ssb - lead - Stig Sæther Bakken - stig@php.net - - - cox - developer - Tomas V.V.Cox - cox@idecnet.com - - - mj - helper - Martin Jansen - mj@php.net - - - pajoye - developer - Pierre-Alain Joye - pajoye@pearfr.org - - - - 1.1 - stable - 2003-01-10 - -PEAR BASE CLASS: - -* PEAR_Error now supports exceptions when using Zend Engine 2. Set the - error mode to PEAR_ERROR_EXCEPTION to make PEAR_Error throw itself - as an exception (invoke PEAR errors with raiseError() or throwError() - just like before). - -PEAR INSTALLER: - -* Packaging and validation now parses PHP source code (unless - ext/tokenizer is disabled) and does some coding standard conformance - checks. Specifically, the names of classes and functions are - checked to ensure that they are prefixed with the package name. If - your package has symbols that should be without this prefix, you can - override this warning by explicitly adding a "provides" entry in - your package.xml file. See the package.xml file for this release - for an example (OS_Guess, System and md5_file). - - All classes and non-private (not underscore-prefixed) methods and - functions are now registered during "pear package". - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - Archive_Tar - Console_Getopt - - - - - 1.0.1 - stable - 2003-01-10 - - * PEAR_Error class has call backtrace available by - calling getBacktrace(). Available if used with - PHP 4.3 or newer. - - * PEAR_Config class uses getenv() rather than $_ENV - to read environment variables. - - * System::which() Windows fix, now looks for - exe/bat/cmd/com suffixes rather than just exe - - * Added "pear cvsdiff" command - - * Windows output buffering bugfix for "pear" command - - * Multiple drives installation now works on windows - - * pear.bat uses ENV variables, allowing the installation - of many PEAR (windows) - - - - Archive_Tar - Console_Getopt - - - - 1.0 - stable - 2002-12-27 - - * set default cache_ttl to 1 hour - * added "clear-cache" command - - - - Archive_Tar - Console_Getopt - - - - 1.0b3 - stable - 2002-12-13 - - * fixed "info" shortcut (conflicted with "install") - * added "php_bin" config parameter - * all "non-personal" config parameters now use - environment variables for defaults (very useful - to override the default php_dir on Windows!) - - - - Archive_Tar - Console_Getopt - - - - 1.0b2 - stable - 2002-11-26 - -Changes, Installer: -* --force option no longer ignores errors, use - --ignore-errors instead -* installer transactions: failed installs abort - cleanly, without leaving half-installed packages - around - - - - 1.0b1 - stable - 2002-10-12 - -New Features, Installer: -* new command: "pear makerpm" -* new command: "pear search" -* new command: "pear upgrade-all" -* new command: "pear config-help" -* new command: "pear sign" -* Windows support for "pear build" (requires - msdev) -* new dependency type: "zend" -* XML-RPC results may now be cached (see - cache_dir and cache_ttl config) -* HTTP proxy authorization support -* install/upgrade install-root support - -Bugfixes, Installer: -* fix for XML-RPC bug that made some remote - commands fail -* fix problems under Windows with - DIRECTORY_SEPARATOR -* lots of other minor fixes -* --force option did not work for "pear install - Package" -* http downloader used "4.2.1" rather than - "PHP/4.2.1" as user agent -* bending over a little more to figure out how - PHP is installed -* "platform" file attribute was not included - during "pear package" - -New Features, PEAR Library: -* added PEAR::loadExtension($ext) -* added PEAR::delExpect() -* System::mkTemp() now cleans up at shutdown -* defined PEAR_ZE2 constant (boolean) -* added PEAR::throwError() with a simpler API - than raiseError() - -Bugfixes, PEAR Library: -* ZE2 compatibility fixes -* use getenv() as fallback for $_ENV - - - - Archive_Tar - Console_Getopt - - - - 0.90 - beta - 2002-05-28 - -* fix: "help" command was broken -* new command: "info" -* new command: "config-help" -* un-indent multi-line data from xml description files -* new command: "build" -* fix: config-set did not work with "set" parameters -* disable magic_quotes_runtime -* "install" now builds and installs C extensions -* added PEAR::delExpect() -* System class no longer inherits PEAR -* grouped PEAR_Config parameters -* add --nobuild option to install/upgrade commands -* new and more generic Frontend API - - - - Archive_Tar - Console_Getopt - - - - 0.10 - beta - 2002-05-26 - -Lots of stuff this time. 0.9 was not actually self-hosting, even -though it claimed to be. This version finally is self-hosting -(really!), meaning you can upgrade the installer with the command -"pear upgrade PEAR". - -* new config paramers: http_proxy and umask -* HTTP proxy support when downloading packages -* generalized command handling code -* and fixed the bug that would not let commands have the - same options as "pear" itself -* added long options to every command -* added command shortcuts ("pear help shortcuts") -* added stub for Gtk installer -* some phpdoc fixes -* added class dependency detector (using ext/tokenizer) -* dependency handling fixes -* added OS_Guess class for detecting OS -* install files with the "platform" attribute set - only on matching operating systems -* PEAR_Remote now falls back to the XML_RPC package - if xmlrpc-epi is not available -* renamed command: package-list -> list -* new command: package-dependencies -* lots of minor fixes - - - - Archive_Tar - Console_Getopt - - - - 0.9 - beta - 2002-04-07 - -First package release. Commands implemented: - remote-package-info - list-upgrades - list-remote-packages - download - config-show - config-get - config-set - list-installed - shell-test - install - uninstall - upgrade - package - package-list - package-info - login - logout - - - - diff --git a/gulliver/thirdparty/pear/package.dtd b/gulliver/thirdparty/pear/package.dtd deleted file mode 100644 index 3567564a4..000000000 --- a/gulliver/thirdparty/pear/package.dtd +++ /dev/null @@ -1,109 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/gulliver/thirdparty/pear/pear-core-minimal/README.rst b/gulliver/thirdparty/pear/pear-core-minimal/README.rst deleted file mode 100644 index 9e412fbd1..000000000 --- a/gulliver/thirdparty/pear/pear-core-minimal/README.rst +++ /dev/null @@ -1,26 +0,0 @@ -****************************** -Minimal set of PEAR core files -****************************** - -This repository provides a set of files from ``pear-core`` -that are often used in PEAR packages. - -It follows the `pear-core`__ repository and gets updated whenever a new -PEAR version is released. - -It's meant to be used as dependency for composer packages. - -__ https://github.com/pear/pear-core - -============== -Included files -============== -- ``OS/Guess.php`` -- ``PEAR.php`` -- ``PEAR/Error.php`` -- ``PEAR/ErrorStack.php`` -- ``System.php`` - - -``PEAR/Error.php`` is a dummy file that only includes ``PEAR.php``, -to make autoloaders work without problems. diff --git a/gulliver/thirdparty/pear/pear-core-minimal/composer.json b/gulliver/thirdparty/pear/pear-core-minimal/composer.json deleted file mode 100644 index d805f56ae..000000000 --- a/gulliver/thirdparty/pear/pear-core-minimal/composer.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "name": "pear/pear-core-minimal", - "description": "Minimal set of PEAR core files to be used as composer dependency", - "license": "BSD-3-Clause", - "authors": [ - { - "email": "cweiske@php.net", - "name": "Christian Weiske", - "role": "Lead" - } - ], - "autoload": { - "psr-0": { - "": "src/" - } - }, - "include-path": [ - "src/" - ], - "support": { - "issues": "http://pear.php.net/bugs/search.php?cmd=display&package_name[]=PEAR", - "source": "https://github.com/pear/pear-core-minimal" - }, - "type": "library", - "require": { - "pear/console_getopt": "~1.4", - "pear/pear_exception": "~1.0" - }, - "replace": { - "rsky/pear-core-min": "self.version" - } -} diff --git a/gulliver/thirdparty/pear/pear-core-minimal/src/OS/Guess.php b/gulliver/thirdparty/pear/pear-core-minimal/src/OS/Guess.php deleted file mode 100644 index c45e84f15..000000000 --- a/gulliver/thirdparty/pear/pear-core-minimal/src/OS/Guess.php +++ /dev/null @@ -1,337 +0,0 @@ - - * @author Gregory Beaver - * @copyright 1997-2009 The Authors - * @license http://opensource.org/licenses/bsd-license.php New BSD License - * @link http://pear.php.net/package/PEAR - * @since File available since PEAR 0.1 - */ - -// {{{ uname examples - -// php_uname() without args returns the same as 'uname -a', or a PHP-custom -// string for Windows. -// PHP versions prior to 4.3 return the uname of the host where PHP was built, -// as of 4.3 it returns the uname of the host running the PHP code. -// -// PC RedHat Linux 7.1: -// Linux host.example.com 2.4.2-2 #1 Sun Apr 8 20:41:30 EDT 2001 i686 unknown -// -// PC Debian Potato: -// Linux host 2.4.17 #2 SMP Tue Feb 12 15:10:04 CET 2002 i686 unknown -// -// PC FreeBSD 3.3: -// FreeBSD host.example.com 3.3-STABLE FreeBSD 3.3-STABLE #0: Mon Feb 21 00:42:31 CET 2000 root@example.com:/usr/src/sys/compile/CONFIG i386 -// -// PC FreeBSD 4.3: -// FreeBSD host.example.com 4.3-RELEASE FreeBSD 4.3-RELEASE #1: Mon Jun 25 11:19:43 EDT 2001 root@example.com:/usr/src/sys/compile/CONFIG i386 -// -// PC FreeBSD 4.5: -// FreeBSD host.example.com 4.5-STABLE FreeBSD 4.5-STABLE #0: Wed Feb 6 23:59:23 CET 2002 root@example.com:/usr/src/sys/compile/CONFIG i386 -// -// PC FreeBSD 4.5 w/uname from GNU shellutils: -// FreeBSD host.example.com 4.5-STABLE FreeBSD 4.5-STABLE #0: Wed Feb i386 unknown -// -// HP 9000/712 HP-UX 10: -// HP-UX iq B.10.10 A 9000/712 2008429113 two-user license -// -// HP 9000/712 HP-UX 10 w/uname from GNU shellutils: -// HP-UX host B.10.10 A 9000/712 unknown -// -// IBM RS6000/550 AIX 4.3: -// AIX host 3 4 000003531C00 -// -// AIX 4.3 w/uname from GNU shellutils: -// AIX host 3 4 000003531C00 unknown -// -// SGI Onyx IRIX 6.5 w/uname from GNU shellutils: -// IRIX64 host 6.5 01091820 IP19 mips -// -// SGI Onyx IRIX 6.5: -// IRIX64 host 6.5 01091820 IP19 -// -// SparcStation 20 Solaris 8 w/uname from GNU shellutils: -// SunOS host.example.com 5.8 Generic_108528-12 sun4m sparc -// -// SparcStation 20 Solaris 8: -// SunOS host.example.com 5.8 Generic_108528-12 sun4m sparc SUNW,SPARCstation-20 -// -// Mac OS X (Darwin) -// Darwin home-eden.local 7.5.0 Darwin Kernel Version 7.5.0: Thu Aug 5 19:26:16 PDT 2004; root:xnu/xnu-517.7.21.obj~3/RELEASE_PPC Power Macintosh -// -// Mac OS X early versions -// - -// }}} - -/* TODO: - * - define endianness, to allow matchSignature("bigend") etc. - */ - -/** - * Retrieves information about the current operating system - * - * This class uses php_uname() to grok information about the current OS - * - * @category pear - * @package PEAR - * @author Stig Bakken - * @author Gregory Beaver - * @copyright 1997-2009 The Authors - * @license http://opensource.org/licenses/bsd-license.php New BSD License - * @version Release: @package_version@ - * @link http://pear.php.net/package/PEAR - * @since Class available since Release 0.1 - */ -class OS_Guess -{ - var $sysname; - var $nodename; - var $cpu; - var $release; - var $extra; - - function __construct($uname = null) - { - list($this->sysname, - $this->release, - $this->cpu, - $this->extra, - $this->nodename) = $this->parseSignature($uname); - } - - function parseSignature($uname = null) - { - static $sysmap = array( - 'HP-UX' => 'hpux', - 'IRIX64' => 'irix', - ); - static $cpumap = array( - 'i586' => 'i386', - 'i686' => 'i386', - 'ppc' => 'powerpc', - ); - if ($uname === null) { - $uname = php_uname(); - } - $parts = preg_split('/\s+/', trim($uname)); - $n = count($parts); - - $release = $machine = $cpu = ''; - $sysname = $parts[0]; - $nodename = $parts[1]; - $cpu = $parts[$n-1]; - $extra = ''; - if ($cpu == 'unknown') { - $cpu = $parts[$n - 2]; - } - - switch ($sysname) { - case 'AIX' : - $release = "$parts[3].$parts[2]"; - break; - case 'Windows' : - switch ($parts[1]) { - case '95/98': - $release = '9x'; - break; - default: - $release = $parts[1]; - break; - } - $cpu = 'i386'; - break; - case 'Linux' : - $extra = $this->_detectGlibcVersion(); - // use only the first two digits from the kernel version - $release = preg_replace('/^([0-9]+\.[0-9]+).*/', '\1', $parts[2]); - break; - case 'Mac' : - $sysname = 'darwin'; - $nodename = $parts[2]; - $release = $parts[3]; - if ($cpu == 'Macintosh') { - if ($parts[$n - 2] == 'Power') { - $cpu = 'powerpc'; - } - } - break; - case 'Darwin' : - if ($cpu == 'Macintosh') { - if ($parts[$n - 2] == 'Power') { - $cpu = 'powerpc'; - } - } - $release = preg_replace('/^([0-9]+\.[0-9]+).*/', '\1', $parts[2]); - break; - default: - $release = preg_replace('/-.*/', '', $parts[2]); - break; - } - - if (isset($sysmap[$sysname])) { - $sysname = $sysmap[$sysname]; - } else { - $sysname = strtolower($sysname); - } - if (isset($cpumap[$cpu])) { - $cpu = $cpumap[$cpu]; - } - return array($sysname, $release, $cpu, $extra, $nodename); - } - - function _detectGlibcVersion() - { - static $glibc = false; - if ($glibc !== false) { - return $glibc; // no need to run this multiple times - } - $major = $minor = 0; - include_once "System.php"; - // Use glibc's header file to - // get major and minor version number: - if (@file_exists('/usr/include/features.h') && - @is_readable('/usr/include/features.h')) { - if (!@file_exists('/usr/bin/cpp') || !@is_executable('/usr/bin/cpp')) { - $features_file = fopen('/usr/include/features.h', 'rb'); - while (!feof($features_file)) { - $line = fgets($features_file, 8192); - if (!$line || (strpos($line, '#define') === false)) { - continue; - } - if (strpos($line, '__GLIBC__')) { - // major version number #define __GLIBC__ version - $line = preg_split('/\s+/', $line); - $glibc_major = trim($line[2]); - if (isset($glibc_minor)) { - break; - } - continue; - } - - if (strpos($line, '__GLIBC_MINOR__')) { - // got the minor version number - // #define __GLIBC_MINOR__ version - $line = preg_split('/\s+/', $line); - $glibc_minor = trim($line[2]); - if (isset($glibc_major)) { - break; - } - continue; - } - } - fclose($features_file); - if (!isset($glibc_major) || !isset($glibc_minor)) { - return $glibc = ''; - } - return $glibc = 'glibc' . trim($glibc_major) . "." . trim($glibc_minor) ; - } // no cpp - - $tmpfile = System::mktemp("glibctest"); - $fp = fopen($tmpfile, "w"); - fwrite($fp, "#include \n__GLIBC__ __GLIBC_MINOR__\n"); - fclose($fp); - $cpp = popen("/usr/bin/cpp $tmpfile", "r"); - while ($line = fgets($cpp, 1024)) { - if ($line{0} == '#' || trim($line) == '') { - continue; - } - - if (list($major, $minor) = explode(' ', trim($line))) { - break; - } - } - pclose($cpp); - unlink($tmpfile); - } // features.h - - if (!($major && $minor) && @is_link('/lib/libc.so.6')) { - // Let's try reading the libc.so.6 symlink - if (preg_match('/^libc-(.*)\.so$/', basename(readlink('/lib/libc.so.6')), $matches)) { - list($major, $minor) = explode('.', $matches[1]); - } - } - - if (!($major && $minor)) { - return $glibc = ''; - } - - return $glibc = "glibc{$major}.{$minor}"; - } - - function getSignature() - { - if (empty($this->extra)) { - return "{$this->sysname}-{$this->release}-{$this->cpu}"; - } - return "{$this->sysname}-{$this->release}-{$this->cpu}-{$this->extra}"; - } - - function getSysname() - { - return $this->sysname; - } - - function getNodename() - { - return $this->nodename; - } - - function getCpu() - { - return $this->cpu; - } - - function getRelease() - { - return $this->release; - } - - function getExtra() - { - return $this->extra; - } - - function matchSignature($match) - { - $fragments = is_array($match) ? $match : explode('-', $match); - $n = count($fragments); - $matches = 0; - if ($n > 0) { - $matches += $this->_matchFragment($fragments[0], $this->sysname); - } - if ($n > 1) { - $matches += $this->_matchFragment($fragments[1], $this->release); - } - if ($n > 2) { - $matches += $this->_matchFragment($fragments[2], $this->cpu); - } - if ($n > 3) { - $matches += $this->_matchFragment($fragments[3], $this->extra); - } - return ($matches == $n); - } - - function _matchFragment($fragment, $value) - { - if (strcspn($fragment, '*?') < strlen($fragment)) { - $reg = '/^' . str_replace(array('*', '?', '/'), array('.*', '.', '\\/'), $fragment) . '\\z/'; - return preg_match($reg, $value); - } - return ($fragment == '*' || !strcasecmp($fragment, $value)); - } - -} -/* - * Local Variables: - * indent-tabs-mode: nil - * c-basic-offset: 4 - * End: - */ diff --git a/gulliver/thirdparty/pear/pear-core-minimal/src/PEAR.php b/gulliver/thirdparty/pear/pear-core-minimal/src/PEAR.php deleted file mode 100644 index b6bb191e7..000000000 --- a/gulliver/thirdparty/pear/pear-core-minimal/src/PEAR.php +++ /dev/null @@ -1,1113 +0,0 @@ - - * @author Stig Bakken - * @author Tomas V.V.Cox - * @author Greg Beaver - * @copyright 1997-2010 The Authors - * @license http://opensource.org/licenses/bsd-license.php New BSD License - * @link http://pear.php.net/package/PEAR - * @since File available since Release 0.1 - */ - -/**#@+ - * ERROR constants - */ -define('PEAR_ERROR_RETURN', 1); -define('PEAR_ERROR_PRINT', 2); -define('PEAR_ERROR_TRIGGER', 4); -define('PEAR_ERROR_DIE', 8); -define('PEAR_ERROR_CALLBACK', 16); -/** - * WARNING: obsolete - * @deprecated - */ -define('PEAR_ERROR_EXCEPTION', 32); -/**#@-*/ - -if (substr(PHP_OS, 0, 3) == 'WIN') { - define('OS_WINDOWS', true); - define('OS_UNIX', false); - define('PEAR_OS', 'Windows'); -} else { - define('OS_WINDOWS', false); - define('OS_UNIX', true); - define('PEAR_OS', 'Unix'); // blatant assumption -} - -$GLOBALS['_PEAR_default_error_mode'] = PEAR_ERROR_RETURN; -$GLOBALS['_PEAR_default_error_options'] = E_USER_NOTICE; -$GLOBALS['_PEAR_destructor_object_list'] = array(); -$GLOBALS['_PEAR_shutdown_funcs'] = array(); -$GLOBALS['_PEAR_error_handler_stack'] = array(); - -@ini_set('track_errors', true); - -/** - * Base class for other PEAR classes. Provides rudimentary - * emulation of destructors. - * - * If you want a destructor in your class, inherit PEAR and make a - * destructor method called _yourclassname (same name as the - * constructor, but with a "_" prefix). Also, in your constructor you - * have to call the PEAR constructor: $this->PEAR();. - * The destructor method will be called without parameters. Note that - * at in some SAPI implementations (such as Apache), any output during - * the request shutdown (in which destructors are called) seems to be - * discarded. If you need to get any debug information from your - * destructor, use error_log(), syslog() or something similar. - * - * IMPORTANT! To use the emulated destructors you need to create the - * objects by reference: $obj =& new PEAR_child; - * - * @category pear - * @package PEAR - * @author Stig Bakken - * @author Tomas V.V. Cox - * @author Greg Beaver - * @copyright 1997-2006 The PHP Group - * @license http://opensource.org/licenses/bsd-license.php New BSD License - * @version Release: @package_version@ - * @link http://pear.php.net/package/PEAR - * @see PEAR_Error - * @since Class available since PHP 4.0.2 - * @link http://pear.php.net/manual/en/core.pear.php#core.pear.pear - */ -class PEAR -{ - /** - * Whether to enable internal debug messages. - * - * @var bool - * @access private - */ - var $_debug = false; - - /** - * Default error mode for this object. - * - * @var int - * @access private - */ - var $_default_error_mode = null; - - /** - * Default error options used for this object when error mode - * is PEAR_ERROR_TRIGGER. - * - * @var int - * @access private - */ - var $_default_error_options = null; - - /** - * Default error handler (callback) for this object, if error mode is - * PEAR_ERROR_CALLBACK. - * - * @var string - * @access private - */ - var $_default_error_handler = ''; - - /** - * Which class to use for error objects. - * - * @var string - * @access private - */ - var $_error_class = 'PEAR_Error'; - - /** - * An array of expected errors. - * - * @var array - * @access private - */ - var $_expected_errors = array(); - - /** - * List of methods that can be called both statically and non-statically. - * @var array - */ - protected static $bivalentMethods = array( - 'setErrorHandling' => true, - 'raiseError' => true, - 'throwError' => true, - 'pushErrorHandling' => true, - 'popErrorHandling' => true, - ); - - /** - * Constructor. Registers this object in - * $_PEAR_destructor_object_list for destructor emulation if a - * destructor object exists. - * - * @param string $error_class (optional) which class to use for - * error objects, defaults to PEAR_Error. - * @access public - * @return void - */ - function __construct($error_class = null) - { - $classname = strtolower(get_class($this)); - if ($this->_debug) { - print "PEAR constructor called, class=$classname\n"; - } - - if ($error_class !== null) { - $this->_error_class = $error_class; - } - - while ($classname && strcasecmp($classname, "pear")) { - $destructor = "_$classname"; - if (method_exists($this, $destructor)) { - global $_PEAR_destructor_object_list; - $_PEAR_destructor_object_list[] = &$this; - if (!isset($GLOBALS['_PEAR_SHUTDOWN_REGISTERED'])) { - register_shutdown_function("_PEAR_call_destructors"); - $GLOBALS['_PEAR_SHUTDOWN_REGISTERED'] = true; - } - break; - } else { - $classname = get_parent_class($classname); - } - } - } - - /** - * Only here for backwards compatibility. - * E.g. Archive_Tar calls $this->PEAR() in its constructor. - * - * @param string $error_class Which class to use for error objects, - * defaults to PEAR_Error. - */ - public function PEAR($error_class = null) - { - self::__construct($error_class); - } - - /** - * Destructor (the emulated type of...). Does nothing right now, - * but is included for forward compatibility, so subclass - * destructors should always call it. - * - * See the note in the class desciption about output from - * destructors. - * - * @access public - * @return void - */ - function _PEAR() { - if ($this->_debug) { - printf("PEAR destructor called, class=%s\n", strtolower(get_class($this))); - } - } - - public function __call($method, $arguments) - { - if (!isset(self::$bivalentMethods[$method])) { - trigger_error( - 'Call to undefined method PEAR::' . $method . '()', E_USER_ERROR - ); - } - return call_user_func_array( - array(get_class(), '_' . $method), - array_merge(array($this), $arguments) - ); - } - - public static function __callStatic($method, $arguments) - { - if (!isset(self::$bivalentMethods[$method])) { - trigger_error( - 'Call to undefined method PEAR::' . $method . '()', E_USER_ERROR - ); - } - return call_user_func_array( - array(get_class(), '_' . $method), - array_merge(array(null), $arguments) - ); - } - - /** - * If you have a class that's mostly/entirely static, and you need static - * properties, you can use this method to simulate them. Eg. in your method(s) - * do this: $myVar = &PEAR::getStaticProperty('myclass', 'myVar'); - * You MUST use a reference, or they will not persist! - * - * @param string $class The calling classname, to prevent clashes - * @param string $var The variable to retrieve. - * @return mixed A reference to the variable. If not set it will be - * auto initialised to NULL. - */ - public static function &getStaticProperty($class, $var) - { - static $properties; - if (!isset($properties[$class])) { - $properties[$class] = array(); - } - - if (!array_key_exists($var, $properties[$class])) { - $properties[$class][$var] = null; - } - - return $properties[$class][$var]; - } - - /** - * Use this function to register a shutdown method for static - * classes. - * - * @param mixed $func The function name (or array of class/method) to call - * @param mixed $args The arguments to pass to the function - * - * @return void - */ - public static function registerShutdownFunc($func, $args = array()) - { - // if we are called statically, there is a potential - // that no shutdown func is registered. Bug #6445 - if (!isset($GLOBALS['_PEAR_SHUTDOWN_REGISTERED'])) { - register_shutdown_function("_PEAR_call_destructors"); - $GLOBALS['_PEAR_SHUTDOWN_REGISTERED'] = true; - } - $GLOBALS['_PEAR_shutdown_funcs'][] = array($func, $args); - } - - /** - * Tell whether a value is a PEAR error. - * - * @param mixed $data the value to test - * @param int $code if $data is an error object, return true - * only if $code is a string and - * $obj->getMessage() == $code or - * $code is an integer and $obj->getCode() == $code - * - * @return bool true if parameter is an error - */ - public static function isError($data, $code = null) - { - if (!is_a($data, 'PEAR_Error')) { - return false; - } - - if (is_null($code)) { - return true; - } elseif (is_string($code)) { - return $data->getMessage() == $code; - } - - return $data->getCode() == $code; - } - - /** - * Sets how errors generated by this object should be handled. - * Can be invoked both in objects and statically. If called - * statically, setErrorHandling sets the default behaviour for all - * PEAR objects. If called in an object, setErrorHandling sets - * the default behaviour for that object. - * - * @param object $object - * Object the method was called on (non-static mode) - * - * @param int $mode - * One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT, - * PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE, - * PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION. - * - * @param mixed $options - * When $mode is PEAR_ERROR_TRIGGER, this is the error level (one - * of E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR). - * - * When $mode is PEAR_ERROR_CALLBACK, this parameter is expected - * to be the callback function or method. A callback - * function is a string with the name of the function, a - * callback method is an array of two elements: the element - * at index 0 is the object, and the element at index 1 is - * the name of the method to call in the object. - * - * When $mode is PEAR_ERROR_PRINT or PEAR_ERROR_DIE, this is - * a printf format string used when printing the error - * message. - * - * @access public - * @return void - * @see PEAR_ERROR_RETURN - * @see PEAR_ERROR_PRINT - * @see PEAR_ERROR_TRIGGER - * @see PEAR_ERROR_DIE - * @see PEAR_ERROR_CALLBACK - * @see PEAR_ERROR_EXCEPTION - * - * @since PHP 4.0.5 - */ - protected static function _setErrorHandling( - $object, $mode = null, $options = null - ) { - if ($object !== null) { - $setmode = &$object->_default_error_mode; - $setoptions = &$object->_default_error_options; - } else { - $setmode = &$GLOBALS['_PEAR_default_error_mode']; - $setoptions = &$GLOBALS['_PEAR_default_error_options']; - } - - switch ($mode) { - case PEAR_ERROR_EXCEPTION: - case PEAR_ERROR_RETURN: - case PEAR_ERROR_PRINT: - case PEAR_ERROR_TRIGGER: - case PEAR_ERROR_DIE: - case null: - $setmode = $mode; - $setoptions = $options; - break; - - case PEAR_ERROR_CALLBACK: - $setmode = $mode; - // class/object method callback - if (is_callable($options)) { - $setoptions = $options; - } else { - trigger_error("invalid error callback", E_USER_WARNING); - } - break; - - default: - trigger_error("invalid error mode", E_USER_WARNING); - break; - } - } - - /** - * This method is used to tell which errors you expect to get. - * Expected errors are always returned with error mode - * PEAR_ERROR_RETURN. Expected error codes are stored in a stack, - * and this method pushes a new element onto it. The list of - * expected errors are in effect until they are popped off the - * stack with the popExpect() method. - * - * Note that this method can not be called statically - * - * @param mixed $code a single error code or an array of error codes to expect - * - * @return int the new depth of the "expected errors" stack - * @access public - */ - function expectError($code = '*') - { - if (is_array($code)) { - array_push($this->_expected_errors, $code); - } else { - array_push($this->_expected_errors, array($code)); - } - return count($this->_expected_errors); - } - - /** - * This method pops one element off the expected error codes - * stack. - * - * @return array the list of error codes that were popped - */ - function popExpect() - { - return array_pop($this->_expected_errors); - } - - /** - * This method checks unsets an error code if available - * - * @param mixed error code - * @return bool true if the error code was unset, false otherwise - * @access private - * @since PHP 4.3.0 - */ - function _checkDelExpect($error_code) - { - $deleted = false; - foreach ($this->_expected_errors as $key => $error_array) { - if (in_array($error_code, $error_array)) { - unset($this->_expected_errors[$key][array_search($error_code, $error_array)]); - $deleted = true; - } - - // clean up empty arrays - if (0 == count($this->_expected_errors[$key])) { - unset($this->_expected_errors[$key]); - } - } - - return $deleted; - } - - /** - * This method deletes all occurrences of the specified element from - * the expected error codes stack. - * - * @param mixed $error_code error code that should be deleted - * @return mixed list of error codes that were deleted or error - * @access public - * @since PHP 4.3.0 - */ - function delExpect($error_code) - { - $deleted = false; - if ((is_array($error_code) && (0 != count($error_code)))) { - // $error_code is a non-empty array here; we walk through it trying - // to unset all values - foreach ($error_code as $key => $error) { - $deleted = $this->_checkDelExpect($error) ? true : false; - } - - return $deleted ? true : PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME - } elseif (!empty($error_code)) { - // $error_code comes alone, trying to unset it - if ($this->_checkDelExpect($error_code)) { - return true; - } - - return PEAR::raiseError("The expected error you submitted does not exist"); // IMPROVE ME - } - - // $error_code is empty - return PEAR::raiseError("The expected error you submitted is empty"); // IMPROVE ME - } - - /** - * This method is a wrapper that returns an instance of the - * configured error class with this object's default error - * handling applied. If the $mode and $options parameters are not - * specified, the object's defaults are used. - * - * @param mixed $message a text error message or a PEAR error object - * - * @param int $code a numeric error code (it is up to your class - * to define these if you want to use codes) - * - * @param int $mode One of PEAR_ERROR_RETURN, PEAR_ERROR_PRINT, - * PEAR_ERROR_TRIGGER, PEAR_ERROR_DIE, - * PEAR_ERROR_CALLBACK, PEAR_ERROR_EXCEPTION. - * - * @param mixed $options If $mode is PEAR_ERROR_TRIGGER, this parameter - * specifies the PHP-internal error level (one of - * E_USER_NOTICE, E_USER_WARNING or E_USER_ERROR). - * If $mode is PEAR_ERROR_CALLBACK, this - * parameter specifies the callback function or - * method. In other error modes this parameter - * is ignored. - * - * @param string $userinfo If you need to pass along for example debug - * information, this parameter is meant for that. - * - * @param string $error_class The returned error object will be - * instantiated from this class, if specified. - * - * @param bool $skipmsg If true, raiseError will only pass error codes, - * the error message parameter will be dropped. - * - * @return object a PEAR error object - * @see PEAR::setErrorHandling - * @since PHP 4.0.5 - */ - protected static function _raiseError($object, - $message = null, - $code = null, - $mode = null, - $options = null, - $userinfo = null, - $error_class = null, - $skipmsg = false) - { - // The error is yet a PEAR error object - if (is_object($message)) { - $code = $message->getCode(); - $userinfo = $message->getUserInfo(); - $error_class = $message->getType(); - $message->error_message_prefix = ''; - $message = $message->getMessage(); - } - - if ( - $object !== null && - isset($object->_expected_errors) && - count($object->_expected_errors) > 0 && - count($exp = end($object->_expected_errors)) - ) { - if ($exp[0] == "*" || - (is_int(reset($exp)) && in_array($code, $exp)) || - (is_string(reset($exp)) && in_array($message, $exp)) - ) { - $mode = PEAR_ERROR_RETURN; - } - } - - // No mode given, try global ones - if ($mode === null) { - // Class error handler - if ($object !== null && isset($object->_default_error_mode)) { - $mode = $object->_default_error_mode; - $options = $object->_default_error_options; - // Global error handler - } elseif (isset($GLOBALS['_PEAR_default_error_mode'])) { - $mode = $GLOBALS['_PEAR_default_error_mode']; - $options = $GLOBALS['_PEAR_default_error_options']; - } - } - - if ($error_class !== null) { - $ec = $error_class; - } elseif ($object !== null && isset($object->_error_class)) { - $ec = $object->_error_class; - } else { - $ec = 'PEAR_Error'; - } - - if ($skipmsg) { - $a = new $ec($code, $mode, $options, $userinfo); - } else { - $a = new $ec($message, $code, $mode, $options, $userinfo); - } - - return $a; - } - - /** - * Simpler form of raiseError with fewer options. In most cases - * message, code and userinfo are enough. - * - * @param mixed $message a text error message or a PEAR error object - * - * @param int $code a numeric error code (it is up to your class - * to define these if you want to use codes) - * - * @param string $userinfo If you need to pass along for example debug - * information, this parameter is meant for that. - * - * @return object a PEAR error object - * @see PEAR::raiseError - */ - protected static function _throwError($object, $message = null, $code = null, $userinfo = null) - { - if ($object !== null) { - $a = &$object->raiseError($message, $code, null, null, $userinfo); - return $a; - } - - $a = &PEAR::raiseError($message, $code, null, null, $userinfo); - return $a; - } - - public static function staticPushErrorHandling($mode, $options = null) - { - $stack = &$GLOBALS['_PEAR_error_handler_stack']; - $def_mode = &$GLOBALS['_PEAR_default_error_mode']; - $def_options = &$GLOBALS['_PEAR_default_error_options']; - $stack[] = array($def_mode, $def_options); - switch ($mode) { - case PEAR_ERROR_EXCEPTION: - case PEAR_ERROR_RETURN: - case PEAR_ERROR_PRINT: - case PEAR_ERROR_TRIGGER: - case PEAR_ERROR_DIE: - case null: - $def_mode = $mode; - $def_options = $options; - break; - - case PEAR_ERROR_CALLBACK: - $def_mode = $mode; - // class/object method callback - if (is_callable($options)) { - $def_options = $options; - } else { - trigger_error("invalid error callback", E_USER_WARNING); - } - break; - - default: - trigger_error("invalid error mode", E_USER_WARNING); - break; - } - $stack[] = array($mode, $options); - return true; - } - - public static function staticPopErrorHandling() - { - $stack = &$GLOBALS['_PEAR_error_handler_stack']; - $setmode = &$GLOBALS['_PEAR_default_error_mode']; - $setoptions = &$GLOBALS['_PEAR_default_error_options']; - array_pop($stack); - list($mode, $options) = $stack[sizeof($stack) - 1]; - array_pop($stack); - switch ($mode) { - case PEAR_ERROR_EXCEPTION: - case PEAR_ERROR_RETURN: - case PEAR_ERROR_PRINT: - case PEAR_ERROR_TRIGGER: - case PEAR_ERROR_DIE: - case null: - $setmode = $mode; - $setoptions = $options; - break; - - case PEAR_ERROR_CALLBACK: - $setmode = $mode; - // class/object method callback - if (is_callable($options)) { - $setoptions = $options; - } else { - trigger_error("invalid error callback", E_USER_WARNING); - } - break; - - default: - trigger_error("invalid error mode", E_USER_WARNING); - break; - } - return true; - } - - /** - * Push a new error handler on top of the error handler options stack. With this - * you can easily override the actual error handler for some code and restore - * it later with popErrorHandling. - * - * @param mixed $mode (same as setErrorHandling) - * @param mixed $options (same as setErrorHandling) - * - * @return bool Always true - * - * @see PEAR::setErrorHandling - */ - protected static function _pushErrorHandling($object, $mode, $options = null) - { - $stack = &$GLOBALS['_PEAR_error_handler_stack']; - if ($object !== null) { - $def_mode = &$object->_default_error_mode; - $def_options = &$object->_default_error_options; - } else { - $def_mode = &$GLOBALS['_PEAR_default_error_mode']; - $def_options = &$GLOBALS['_PEAR_default_error_options']; - } - $stack[] = array($def_mode, $def_options); - - if ($object !== null) { - $object->setErrorHandling($mode, $options); - } else { - PEAR::setErrorHandling($mode, $options); - } - $stack[] = array($mode, $options); - return true; - } - - /** - * Pop the last error handler used - * - * @return bool Always true - * - * @see PEAR::pushErrorHandling - */ - protected static function _popErrorHandling($object) - { - $stack = &$GLOBALS['_PEAR_error_handler_stack']; - array_pop($stack); - list($mode, $options) = $stack[sizeof($stack) - 1]; - array_pop($stack); - if ($object !== null) { - $object->setErrorHandling($mode, $options); - } else { - PEAR::setErrorHandling($mode, $options); - } - return true; - } - - /** - * OS independent PHP extension load. Remember to take care - * on the correct extension name for case sensitive OSes. - * - * @param string $ext The extension name - * @return bool Success or not on the dl() call - */ - public static function loadExtension($ext) - { - if (extension_loaded($ext)) { - return true; - } - - // if either returns true dl() will produce a FATAL error, stop that - if ( - function_exists('dl') === false || - ini_get('enable_dl') != 1 - ) { - return false; - } - - if (OS_WINDOWS) { - $suffix = '.dll'; - } elseif (PHP_OS == 'HP-UX') { - $suffix = '.sl'; - } elseif (PHP_OS == 'AIX') { - $suffix = '.a'; - } elseif (PHP_OS == 'OSX') { - $suffix = '.bundle'; - } else { - $suffix = '.so'; - } - - return @dl('php_'.$ext.$suffix) || @dl($ext.$suffix); - } -} - -function _PEAR_call_destructors() -{ - global $_PEAR_destructor_object_list; - if (is_array($_PEAR_destructor_object_list) && - sizeof($_PEAR_destructor_object_list)) - { - reset($_PEAR_destructor_object_list); - - $destructLifoExists = PEAR::getStaticProperty('PEAR', 'destructlifo'); - - if ($destructLifoExists) { - $_PEAR_destructor_object_list = array_reverse($_PEAR_destructor_object_list); - } - - while (list($k, $objref) = each($_PEAR_destructor_object_list)) { - $classname = get_class($objref); - while ($classname) { - $destructor = "_$classname"; - if (method_exists($objref, $destructor)) { - $objref->$destructor(); - break; - } else { - $classname = get_parent_class($classname); - } - } - } - // Empty the object list to ensure that destructors are - // not called more than once. - $_PEAR_destructor_object_list = array(); - } - - // Now call the shutdown functions - if ( - isset($GLOBALS['_PEAR_shutdown_funcs']) && - is_array($GLOBALS['_PEAR_shutdown_funcs']) && - !empty($GLOBALS['_PEAR_shutdown_funcs']) - ) { - foreach ($GLOBALS['_PEAR_shutdown_funcs'] as $value) { - call_user_func_array($value[0], $value[1]); - } - } -} - -/** - * Standard PEAR error class for PHP 4 - * - * This class is supserseded by {@link PEAR_Exception} in PHP 5 - * - * @category pear - * @package PEAR - * @author Stig Bakken - * @author Tomas V.V. Cox - * @author Gregory Beaver - * @copyright 1997-2006 The PHP Group - * @license http://opensource.org/licenses/bsd-license.php New BSD License - * @version Release: @package_version@ - * @link http://pear.php.net/manual/en/core.pear.pear-error.php - * @see PEAR::raiseError(), PEAR::throwError() - * @since Class available since PHP 4.0.2 - */ -class PEAR_Error -{ - var $error_message_prefix = ''; - var $mode = PEAR_ERROR_RETURN; - var $level = E_USER_NOTICE; - var $code = -1; - var $message = ''; - var $userinfo = ''; - var $backtrace = null; - - /** - * PEAR_Error constructor - * - * @param string $message message - * - * @param int $code (optional) error code - * - * @param int $mode (optional) error mode, one of: PEAR_ERROR_RETURN, - * PEAR_ERROR_PRINT, PEAR_ERROR_DIE, PEAR_ERROR_TRIGGER, - * PEAR_ERROR_CALLBACK or PEAR_ERROR_EXCEPTION - * - * @param mixed $options (optional) error level, _OR_ in the case of - * PEAR_ERROR_CALLBACK, the callback function or object/method - * tuple. - * - * @param string $userinfo (optional) additional user/debug info - * - * @access public - * - */ - function __construct($message = 'unknown error', $code = null, - $mode = null, $options = null, $userinfo = null) - { - if ($mode === null) { - $mode = PEAR_ERROR_RETURN; - } - $this->message = $message; - $this->code = $code; - $this->mode = $mode; - $this->userinfo = $userinfo; - - $skiptrace = PEAR::getStaticProperty('PEAR_Error', 'skiptrace'); - - if (!$skiptrace) { - $this->backtrace = debug_backtrace(); - if (isset($this->backtrace[0]) && isset($this->backtrace[0]['object'])) { - unset($this->backtrace[0]['object']); - } - } - - if ($mode & PEAR_ERROR_CALLBACK) { - $this->level = E_USER_NOTICE; - $this->callback = $options; - } else { - if ($options === null) { - $options = E_USER_NOTICE; - } - - $this->level = $options; - $this->callback = null; - } - - if ($this->mode & PEAR_ERROR_PRINT) { - if (is_null($options) || is_int($options)) { - $format = "%s"; - } else { - $format = $options; - } - - printf($format, $this->getMessage()); - } - - if ($this->mode & PEAR_ERROR_TRIGGER) { - trigger_error($this->getMessage(), $this->level); - } - - if ($this->mode & PEAR_ERROR_DIE) { - $msg = $this->getMessage(); - if (is_null($options) || is_int($options)) { - $format = "%s"; - if (substr($msg, -1) != "\n") { - $msg .= "\n"; - } - } else { - $format = $options; - } - printf($format, $msg); - exit($code); - } - - if ($this->mode & PEAR_ERROR_CALLBACK && is_callable($this->callback)) { - call_user_func($this->callback, $this); - } - - if ($this->mode & PEAR_ERROR_EXCEPTION) { - trigger_error("PEAR_ERROR_EXCEPTION is obsolete, use class PEAR_Exception for exceptions", E_USER_WARNING); - eval('$e = new Exception($this->message, $this->code);throw($e);'); - } - } - - /** - * Only here for backwards compatibility. - * - * Class "Cache_Error" still uses it, among others. - * - * @param string $message Message - * @param int $code Error code - * @param int $mode Error mode - * @param mixed $options See __construct() - * @param string $userinfo Additional user/debug info - */ - public function PEAR_Error( - $message = 'unknown error', $code = null, $mode = null, - $options = null, $userinfo = null - ) { - self::__construct($message, $code, $mode, $options, $userinfo); - } - - /** - * Get the error mode from an error object. - * - * @return int error mode - * @access public - */ - function getMode() - { - return $this->mode; - } - - /** - * Get the callback function/method from an error object. - * - * @return mixed callback function or object/method array - * @access public - */ - function getCallback() - { - return $this->callback; - } - - /** - * Get the error message from an error object. - * - * @return string full error message - * @access public - */ - function getMessage() - { - return ($this->error_message_prefix . $this->message); - } - - /** - * Get error code from an error object - * - * @return int error code - * @access public - */ - function getCode() - { - return $this->code; - } - - /** - * Get the name of this error/exception. - * - * @return string error/exception name (type) - * @access public - */ - function getType() - { - return get_class($this); - } - - /** - * Get additional user-supplied information. - * - * @return string user-supplied information - * @access public - */ - function getUserInfo() - { - return $this->userinfo; - } - - /** - * Get additional debug information supplied by the application. - * - * @return string debug information - * @access public - */ - function getDebugInfo() - { - return $this->getUserInfo(); - } - - /** - * Get the call backtrace from where the error was generated. - * Supported with PHP 4.3.0 or newer. - * - * @param int $frame (optional) what frame to fetch - * @return array Backtrace, or NULL if not available. - * @access public - */ - function getBacktrace($frame = null) - { - if (defined('PEAR_IGNORE_BACKTRACE')) { - return null; - } - if ($frame === null) { - return $this->backtrace; - } - return $this->backtrace[$frame]; - } - - function addUserInfo($info) - { - if (empty($this->userinfo)) { - $this->userinfo = $info; - } else { - $this->userinfo .= " ** $info"; - } - } - - function __toString() - { - return $this->getMessage(); - } - - /** - * Make a string representation of this object. - * - * @return string a string with an object summary - * @access public - */ - function toString() - { - $modes = array(); - $levels = array(E_USER_NOTICE => 'notice', - E_USER_WARNING => 'warning', - E_USER_ERROR => 'error'); - if ($this->mode & PEAR_ERROR_CALLBACK) { - if (is_array($this->callback)) { - $callback = (is_object($this->callback[0]) ? - strtolower(get_class($this->callback[0])) : - $this->callback[0]) . '::' . - $this->callback[1]; - } else { - $callback = $this->callback; - } - return sprintf('[%s: message="%s" code=%d mode=callback '. - 'callback=%s prefix="%s" info="%s"]', - strtolower(get_class($this)), $this->message, $this->code, - $callback, $this->error_message_prefix, - $this->userinfo); - } - if ($this->mode & PEAR_ERROR_PRINT) { - $modes[] = 'print'; - } - if ($this->mode & PEAR_ERROR_TRIGGER) { - $modes[] = 'trigger'; - } - if ($this->mode & PEAR_ERROR_DIE) { - $modes[] = 'die'; - } - if ($this->mode & PEAR_ERROR_RETURN) { - $modes[] = 'return'; - } - return sprintf('[%s: message="%s" code=%d mode=%s level=%s '. - 'prefix="%s" info="%s"]', - strtolower(get_class($this)), $this->message, $this->code, - implode("|", $modes), $levels[$this->level], - $this->error_message_prefix, - $this->userinfo); - } -} - -/* - * Local Variables: - * mode: php - * tab-width: 4 - * c-basic-offset: 4 - * End: - */ diff --git a/gulliver/thirdparty/pear/pear-core-minimal/src/PEAR/Error.php b/gulliver/thirdparty/pear/pear-core-minimal/src/PEAR/Error.php deleted file mode 100644 index 96efff75d..000000000 --- a/gulliver/thirdparty/pear/pear-core-minimal/src/PEAR/Error.php +++ /dev/null @@ -1,14 +0,0 @@ - - * @license http://opensource.org/licenses/bsd-license.php New BSD License - * @link http://pear.php.net/package/PEAR - */ -require_once __DIR__ . '/../PEAR.php'; -?> \ No newline at end of file diff --git a/gulliver/thirdparty/pear/pear-core-minimal/src/PEAR/ErrorStack.php b/gulliver/thirdparty/pear/pear-core-minimal/src/PEAR/ErrorStack.php deleted file mode 100644 index 7af45bfae..000000000 --- a/gulliver/thirdparty/pear/pear-core-minimal/src/PEAR/ErrorStack.php +++ /dev/null @@ -1,979 +0,0 @@ - - * @copyright 2004-2008 Greg Beaver - * @license http://opensource.org/licenses/bsd-license.php New BSD License - * @link http://pear.php.net/package/PEAR_ErrorStack - */ - -/** - * Singleton storage - * - * Format: - *
- * array(
- *  'package1' => PEAR_ErrorStack object,
- *  'package2' => PEAR_ErrorStack object,
- *  ...
- * )
- * 
- * @access private - * @global array $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'] - */ -$GLOBALS['_PEAR_ERRORSTACK_SINGLETON'] = array(); - -/** - * Global error callback (default) - * - * This is only used if set to non-false. * is the default callback for - * all packages, whereas specific packages may set a default callback - * for all instances, regardless of whether they are a singleton or not. - * - * To exclude non-singletons, only set the local callback for the singleton - * @see PEAR_ErrorStack::setDefaultCallback() - * @access private - * @global array $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK'] - */ -$GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK'] = array( - '*' => false, -); - -/** - * Global Log object (default) - * - * This is only used if set to non-false. Use to set a default log object for - * all stacks, regardless of instantiation order or location - * @see PEAR_ErrorStack::setDefaultLogger() - * @access private - * @global array $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER'] - */ -$GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER'] = false; - -/** - * Global Overriding Callback - * - * This callback will override any error callbacks that specific loggers have set. - * Use with EXTREME caution - * @see PEAR_ErrorStack::staticPushCallback() - * @access private - * @global array $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER'] - */ -$GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array(); - -/**#@+ - * One of four possible return values from the error Callback - * @see PEAR_ErrorStack::_errorCallback() - */ -/** - * If this is returned, then the error will be both pushed onto the stack - * and logged. - */ -define('PEAR_ERRORSTACK_PUSHANDLOG', 1); -/** - * If this is returned, then the error will only be pushed onto the stack, - * and not logged. - */ -define('PEAR_ERRORSTACK_PUSH', 2); -/** - * If this is returned, then the error will only be logged, but not pushed - * onto the error stack. - */ -define('PEAR_ERRORSTACK_LOG', 3); -/** - * If this is returned, then the error is completely ignored. - */ -define('PEAR_ERRORSTACK_IGNORE', 4); -/** - * If this is returned, then the error is logged and die() is called. - */ -define('PEAR_ERRORSTACK_DIE', 5); -/**#@-*/ - -/** - * Error code for an attempt to instantiate a non-class as a PEAR_ErrorStack in - * the singleton method. - */ -define('PEAR_ERRORSTACK_ERR_NONCLASS', 1); - -/** - * Error code for an attempt to pass an object into {@link PEAR_ErrorStack::getMessage()} - * that has no __toString() method - */ -define('PEAR_ERRORSTACK_ERR_OBJTOSTRING', 2); -/** - * Error Stack Implementation - * - * Usage: - * - * // global error stack - * $global_stack = &PEAR_ErrorStack::singleton('MyPackage'); - * // local error stack - * $local_stack = new PEAR_ErrorStack('MyPackage'); - * - * @author Greg Beaver - * @version @package_version@ - * @package PEAR_ErrorStack - * @category Debugging - * @copyright 2004-2008 Greg Beaver - * @license http://opensource.org/licenses/bsd-license.php New BSD License - * @link http://pear.php.net/package/PEAR_ErrorStack - */ -class PEAR_ErrorStack { - /** - * Errors are stored in the order that they are pushed on the stack. - * @since 0.4alpha Errors are no longer organized by error level. - * This renders pop() nearly unusable, and levels could be more easily - * handled in a callback anyway - * @var array - * @access private - */ - var $_errors = array(); - - /** - * Storage of errors by level. - * - * Allows easy retrieval and deletion of only errors from a particular level - * @since PEAR 1.4.0dev - * @var array - * @access private - */ - var $_errorsByLevel = array(); - - /** - * Package name this error stack represents - * @var string - * @access protected - */ - var $_package; - - /** - * Determines whether a PEAR_Error is thrown upon every error addition - * @var boolean - * @access private - */ - var $_compat = false; - - /** - * If set to a valid callback, this will be used to generate the error - * message from the error code, otherwise the message passed in will be - * used - * @var false|string|array - * @access private - */ - var $_msgCallback = false; - - /** - * If set to a valid callback, this will be used to generate the error - * context for an error. For PHP-related errors, this will be a file - * and line number as retrieved from debug_backtrace(), but can be - * customized for other purposes. The error might actually be in a separate - * configuration file, or in a database query. - * @var false|string|array - * @access protected - */ - var $_contextCallback = false; - - /** - * If set to a valid callback, this will be called every time an error - * is pushed onto the stack. The return value will be used to determine - * whether to allow an error to be pushed or logged. - * - * The return value must be one an PEAR_ERRORSTACK_* constant - * @see PEAR_ERRORSTACK_PUSHANDLOG, PEAR_ERRORSTACK_PUSH, PEAR_ERRORSTACK_LOG - * @var false|string|array - * @access protected - */ - var $_errorCallback = array(); - - /** - * PEAR::Log object for logging errors - * @var false|Log - * @access protected - */ - var $_logger = false; - - /** - * Error messages - designed to be overridden - * @var array - * @abstract - */ - var $_errorMsgs = array(); - - /** - * Set up a new error stack - * - * @param string $package name of the package this error stack represents - * @param callback $msgCallback callback used for error message generation - * @param callback $contextCallback callback used for context generation, - * defaults to {@link getFileLine()} - * @param boolean $throwPEAR_Error - */ - function __construct($package, $msgCallback = false, $contextCallback = false, - $throwPEAR_Error = false) - { - $this->_package = $package; - $this->setMessageCallback($msgCallback); - $this->setContextCallback($contextCallback); - $this->_compat = $throwPEAR_Error; - } - - /** - * Return a single error stack for this package. - * - * Note that all parameters are ignored if the stack for package $package - * has already been instantiated - * @param string $package name of the package this error stack represents - * @param callback $msgCallback callback used for error message generation - * @param callback $contextCallback callback used for context generation, - * defaults to {@link getFileLine()} - * @param boolean $throwPEAR_Error - * @param string $stackClass class to instantiate - * - * @return PEAR_ErrorStack - */ - public static function &singleton( - $package, $msgCallback = false, $contextCallback = false, - $throwPEAR_Error = false, $stackClass = 'PEAR_ErrorStack' - ) { - if (isset($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package])) { - return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]; - } - if (!class_exists($stackClass)) { - if (function_exists('debug_backtrace')) { - $trace = debug_backtrace(); - } - PEAR_ErrorStack::staticPush('PEAR_ErrorStack', PEAR_ERRORSTACK_ERR_NONCLASS, - 'exception', array('stackclass' => $stackClass), - 'stack class "%stackclass%" is not a valid class name (should be like PEAR_ErrorStack)', - false, $trace); - } - $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package] = - new $stackClass($package, $msgCallback, $contextCallback, $throwPEAR_Error); - - return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]; - } - - /** - * Internal error handler for PEAR_ErrorStack class - * - * Dies if the error is an exception (and would have died anyway) - * @access private - */ - function _handleError($err) - { - if ($err['level'] == 'exception') { - $message = $err['message']; - if (isset($_SERVER['REQUEST_URI'])) { - echo '
'; - } else { - echo "\n"; - } - var_dump($err['context']); - die($message); - } - } - - /** - * Set up a PEAR::Log object for all error stacks that don't have one - * @param Log $log - */ - public static function setDefaultLogger(&$log) - { - if (is_object($log) && method_exists($log, 'log') ) { - $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER'] = &$log; - } elseif (is_callable($log)) { - $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER'] = &$log; - } - } - - /** - * Set up a PEAR::Log object for this error stack - * @param Log $log - */ - function setLogger(&$log) - { - if (is_object($log) && method_exists($log, 'log') ) { - $this->_logger = &$log; - } elseif (is_callable($log)) { - $this->_logger = &$log; - } - } - - /** - * Set an error code => error message mapping callback - * - * This method sets the callback that can be used to generate error - * messages for any instance - * @param array|string Callback function/method - */ - function setMessageCallback($msgCallback) - { - if (!$msgCallback) { - $this->_msgCallback = array(&$this, 'getErrorMessage'); - } else { - if (is_callable($msgCallback)) { - $this->_msgCallback = $msgCallback; - } - } - } - - /** - * Get an error code => error message mapping callback - * - * This method returns the current callback that can be used to generate error - * messages - * @return array|string|false Callback function/method or false if none - */ - function getMessageCallback() - { - return $this->_msgCallback; - } - - /** - * Sets a default callback to be used by all error stacks - * - * This method sets the callback that can be used to generate error - * messages for a singleton - * @param array|string Callback function/method - * @param string Package name, or false for all packages - */ - public static function setDefaultCallback($callback = false, $package = false) - { - if (!is_callable($callback)) { - $callback = false; - } - $package = $package ? $package : '*'; - $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK'][$package] = $callback; - } - - /** - * Set a callback that generates context information (location of error) for an error stack - * - * This method sets the callback that can be used to generate context - * information for an error. Passing in NULL will disable context generation - * and remove the expensive call to debug_backtrace() - * @param array|string|null Callback function/method - */ - function setContextCallback($contextCallback) - { - if ($contextCallback === null) { - return $this->_contextCallback = false; - } - if (!$contextCallback) { - $this->_contextCallback = array(&$this, 'getFileLine'); - } else { - if (is_callable($contextCallback)) { - $this->_contextCallback = $contextCallback; - } - } - } - - /** - * Set an error Callback - * If set to a valid callback, this will be called every time an error - * is pushed onto the stack. The return value will be used to determine - * whether to allow an error to be pushed or logged. - * - * The return value must be one of the ERRORSTACK_* constants. - * - * This functionality can be used to emulate PEAR's pushErrorHandling, and - * the PEAR_ERROR_CALLBACK mode, without affecting the integrity of - * the error stack or logging - * @see PEAR_ERRORSTACK_PUSHANDLOG, PEAR_ERRORSTACK_PUSH, PEAR_ERRORSTACK_LOG - * @see popCallback() - * @param string|array $cb - */ - function pushCallback($cb) - { - array_push($this->_errorCallback, $cb); - } - - /** - * Remove a callback from the error callback stack - * @see pushCallback() - * @return array|string|false - */ - function popCallback() - { - if (!count($this->_errorCallback)) { - return false; - } - return array_pop($this->_errorCallback); - } - - /** - * Set a temporary overriding error callback for every package error stack - * - * Use this to temporarily disable all existing callbacks (can be used - * to emulate the @ operator, for instance) - * @see PEAR_ERRORSTACK_PUSHANDLOG, PEAR_ERRORSTACK_PUSH, PEAR_ERRORSTACK_LOG - * @see staticPopCallback(), pushCallback() - * @param string|array $cb - */ - public static function staticPushCallback($cb) - { - array_push($GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'], $cb); - } - - /** - * Remove a temporary overriding error callback - * @see staticPushCallback() - * @return array|string|false - */ - public static function staticPopCallback() - { - $ret = array_pop($GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK']); - if (!is_array($GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'])) { - $GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'] = array(); - } - return $ret; - } - - /** - * Add an error to the stack - * - * If the message generator exists, it is called with 2 parameters. - * - the current Error Stack object - * - an array that is in the same format as an error. Available indices - * are 'code', 'package', 'time', 'params', 'level', and 'context' - * - * Next, if the error should contain context information, this is - * handled by the context grabbing method. - * Finally, the error is pushed onto the proper error stack - * @param int $code Package-specific error code - * @param string $level Error level. This is NOT spell-checked - * @param array $params associative array of error parameters - * @param string $msg Error message, or a portion of it if the message - * is to be generated - * @param array $repackage If this error re-packages an error pushed by - * another package, place the array returned from - * {@link pop()} in this parameter - * @param array $backtrace Protected parameter: use this to pass in the - * {@link debug_backtrace()} that should be used - * to find error context - * @return PEAR_Error|array if compatibility mode is on, a PEAR_Error is also - * thrown. If a PEAR_Error is returned, the userinfo - * property is set to the following array: - * - * - * array( - * 'code' => $code, - * 'params' => $params, - * 'package' => $this->_package, - * 'level' => $level, - * 'time' => time(), - * 'context' => $context, - * 'message' => $msg, - * //['repackage' => $err] repackaged error array/Exception class - * ); - * - * - * Normally, the previous array is returned. - */ - function push($code, $level = 'error', $params = array(), $msg = false, - $repackage = false, $backtrace = false) - { - $context = false; - // grab error context - if ($this->_contextCallback) { - if (!$backtrace) { - $backtrace = debug_backtrace(); - } - $context = call_user_func($this->_contextCallback, $code, $params, $backtrace); - } - - // save error - $time = explode(' ', microtime()); - $time = $time[1] + $time[0]; - $err = array( - 'code' => $code, - 'params' => $params, - 'package' => $this->_package, - 'level' => $level, - 'time' => $time, - 'context' => $context, - 'message' => $msg, - ); - - if ($repackage) { - $err['repackage'] = $repackage; - } - - // set up the error message, if necessary - if ($this->_msgCallback) { - $msg = call_user_func_array($this->_msgCallback, - array(&$this, $err)); - $err['message'] = $msg; - } - $push = $log = true; - $die = false; - // try the overriding callback first - $callback = $this->staticPopCallback(); - if ($callback) { - $this->staticPushCallback($callback); - } - if (!is_callable($callback)) { - // try the local callback next - $callback = $this->popCallback(); - if (is_callable($callback)) { - $this->pushCallback($callback); - } else { - // try the default callback - $callback = isset($GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK'][$this->_package]) ? - $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK'][$this->_package] : - $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_CALLBACK']['*']; - } - } - if (is_callable($callback)) { - switch(call_user_func($callback, $err)){ - case PEAR_ERRORSTACK_IGNORE: - return $err; - break; - case PEAR_ERRORSTACK_PUSH: - $log = false; - break; - case PEAR_ERRORSTACK_LOG: - $push = false; - break; - case PEAR_ERRORSTACK_DIE: - $die = true; - break; - // anything else returned has the same effect as pushandlog - } - } - if ($push) { - array_unshift($this->_errors, $err); - if (!isset($this->_errorsByLevel[$err['level']])) { - $this->_errorsByLevel[$err['level']] = array(); - } - $this->_errorsByLevel[$err['level']][] = &$this->_errors[0]; - } - if ($log) { - if ($this->_logger || $GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER']) { - $this->_log($err); - } - } - if ($die) { - die(); - } - if ($this->_compat && $push) { - return $this->raiseError($msg, $code, null, null, $err); - } - return $err; - } - - /** - * Static version of {@link push()} - * - * @param string $package Package name this error belongs to - * @param int $code Package-specific error code - * @param string $level Error level. This is NOT spell-checked - * @param array $params associative array of error parameters - * @param string $msg Error message, or a portion of it if the message - * is to be generated - * @param array $repackage If this error re-packages an error pushed by - * another package, place the array returned from - * {@link pop()} in this parameter - * @param array $backtrace Protected parameter: use this to pass in the - * {@link debug_backtrace()} that should be used - * to find error context - * @return PEAR_Error|array if compatibility mode is on, a PEAR_Error is also - * thrown. see docs for {@link push()} - */ - public static function staticPush( - $package, $code, $level = 'error', $params = array(), - $msg = false, $repackage = false, $backtrace = false - ) { - $s = &PEAR_ErrorStack::singleton($package); - if ($s->_contextCallback) { - if (!$backtrace) { - if (function_exists('debug_backtrace')) { - $backtrace = debug_backtrace(); - } - } - } - return $s->push($code, $level, $params, $msg, $repackage, $backtrace); - } - - /** - * Log an error using PEAR::Log - * @param array $err Error array - * @param array $levels Error level => Log constant map - * @access protected - */ - function _log($err) - { - if ($this->_logger) { - $logger = &$this->_logger; - } else { - $logger = &$GLOBALS['_PEAR_ERRORSTACK_DEFAULT_LOGGER']; - } - if (is_a($logger, 'Log')) { - $levels = array( - 'exception' => PEAR_LOG_CRIT, - 'alert' => PEAR_LOG_ALERT, - 'critical' => PEAR_LOG_CRIT, - 'error' => PEAR_LOG_ERR, - 'warning' => PEAR_LOG_WARNING, - 'notice' => PEAR_LOG_NOTICE, - 'info' => PEAR_LOG_INFO, - 'debug' => PEAR_LOG_DEBUG); - if (isset($levels[$err['level']])) { - $level = $levels[$err['level']]; - } else { - $level = PEAR_LOG_INFO; - } - $logger->log($err['message'], $level, $err); - } else { // support non-standard logs - call_user_func($logger, $err); - } - } - - - /** - * Pop an error off of the error stack - * - * @return false|array - * @since 0.4alpha it is no longer possible to specify a specific error - * level to return - the last error pushed will be returned, instead - */ - function pop() - { - $err = @array_shift($this->_errors); - if (!is_null($err)) { - @array_pop($this->_errorsByLevel[$err['level']]); - if (!count($this->_errorsByLevel[$err['level']])) { - unset($this->_errorsByLevel[$err['level']]); - } - } - return $err; - } - - /** - * Pop an error off of the error stack, static method - * - * @param string package name - * @return boolean - * @since PEAR1.5.0a1 - */ - function staticPop($package) - { - if ($package) { - if (!isset($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package])) { - return false; - } - return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]->pop(); - } - } - - /** - * Determine whether there are any errors on the stack - * @param string|array Level name. Use to determine if any errors - * of level (string), or levels (array) have been pushed - * @return boolean - */ - function hasErrors($level = false) - { - if ($level) { - return isset($this->_errorsByLevel[$level]); - } - return count($this->_errors); - } - - /** - * Retrieve all errors since last purge - * - * @param boolean set in order to empty the error stack - * @param string level name, to return only errors of a particular severity - * @return array - */ - function getErrors($purge = false, $level = false) - { - if (!$purge) { - if ($level) { - if (!isset($this->_errorsByLevel[$level])) { - return array(); - } else { - return $this->_errorsByLevel[$level]; - } - } else { - return $this->_errors; - } - } - if ($level) { - $ret = $this->_errorsByLevel[$level]; - foreach ($this->_errorsByLevel[$level] as $i => $unused) { - // entries are references to the $_errors array - $this->_errorsByLevel[$level][$i] = false; - } - // array_filter removes all entries === false - $this->_errors = array_filter($this->_errors); - unset($this->_errorsByLevel[$level]); - return $ret; - } - $ret = $this->_errors; - $this->_errors = array(); - $this->_errorsByLevel = array(); - return $ret; - } - - /** - * Determine whether there are any errors on a single error stack, or on any error stack - * - * The optional parameter can be used to test the existence of any errors without the need of - * singleton instantiation - * @param string|false Package name to check for errors - * @param string Level name to check for a particular severity - * @return boolean - */ - public static function staticHasErrors($package = false, $level = false) - { - if ($package) { - if (!isset($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package])) { - return false; - } - return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]->hasErrors($level); - } - foreach ($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'] as $package => $obj) { - if ($obj->hasErrors($level)) { - return true; - } - } - return false; - } - - /** - * Get a list of all errors since last purge, organized by package - * @since PEAR 1.4.0dev BC break! $level is now in the place $merge used to be - * @param boolean $purge Set to purge the error stack of existing errors - * @param string $level Set to a level name in order to retrieve only errors of a particular level - * @param boolean $merge Set to return a flat array, not organized by package - * @param array $sortfunc Function used to sort a merged array - default - * sorts by time, and should be good for most cases - * - * @return array - */ - public static function staticGetErrors( - $purge = false, $level = false, $merge = false, - $sortfunc = array('PEAR_ErrorStack', '_sortErrors') - ) { - $ret = array(); - if (!is_callable($sortfunc)) { - $sortfunc = array('PEAR_ErrorStack', '_sortErrors'); - } - foreach ($GLOBALS['_PEAR_ERRORSTACK_SINGLETON'] as $package => $obj) { - $test = $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package]->getErrors($purge, $level); - if ($test) { - if ($merge) { - $ret = array_merge($ret, $test); - } else { - $ret[$package] = $test; - } - } - } - if ($merge) { - usort($ret, $sortfunc); - } - return $ret; - } - - /** - * Error sorting function, sorts by time - * @access private - */ - public static function _sortErrors($a, $b) - { - if ($a['time'] == $b['time']) { - return 0; - } - if ($a['time'] < $b['time']) { - return 1; - } - return -1; - } - - /** - * Standard file/line number/function/class context callback - * - * This function uses a backtrace generated from {@link debug_backtrace()} - * and so will not work at all in PHP < 4.3.0. The frame should - * reference the frame that contains the source of the error. - * @return array|false either array('file' => file, 'line' => line, - * 'function' => function name, 'class' => class name) or - * if this doesn't work, then false - * @param unused - * @param integer backtrace frame. - * @param array Results of debug_backtrace() - */ - public static function getFileLine($code, $params, $backtrace = null) - { - if ($backtrace === null) { - return false; - } - $frame = 0; - $functionframe = 1; - if (!isset($backtrace[1])) { - $functionframe = 0; - } else { - while (isset($backtrace[$functionframe]['function']) && - $backtrace[$functionframe]['function'] == 'eval' && - isset($backtrace[$functionframe + 1])) { - $functionframe++; - } - } - if (isset($backtrace[$frame])) { - if (!isset($backtrace[$frame]['file'])) { - $frame++; - } - $funcbacktrace = $backtrace[$functionframe]; - $filebacktrace = $backtrace[$frame]; - $ret = array('file' => $filebacktrace['file'], - 'line' => $filebacktrace['line']); - // rearrange for eval'd code or create function errors - if (strpos($filebacktrace['file'], '(') && - preg_match(';^(.*?)\((\d+)\) : (.*?)\\z;', $filebacktrace['file'], - $matches)) { - $ret['file'] = $matches[1]; - $ret['line'] = $matches[2] + 0; - } - if (isset($funcbacktrace['function']) && isset($backtrace[1])) { - if ($funcbacktrace['function'] != 'eval') { - if ($funcbacktrace['function'] == '__lambda_func') { - $ret['function'] = 'create_function() code'; - } else { - $ret['function'] = $funcbacktrace['function']; - } - } - } - if (isset($funcbacktrace['class']) && isset($backtrace[1])) { - $ret['class'] = $funcbacktrace['class']; - } - return $ret; - } - return false; - } - - /** - * Standard error message generation callback - * - * This method may also be called by a custom error message generator - * to fill in template values from the params array, simply - * set the third parameter to the error message template string to use - * - * The special variable %__msg% is reserved: use it only to specify - * where a message passed in by the user should be placed in the template, - * like so: - * - * Error message: %msg% - internal error - * - * If the message passed like so: - * - * - * $stack->push(ERROR_CODE, 'error', array(), 'server error 500'); - * - * - * The returned error message will be "Error message: server error 500 - - * internal error" - * @param PEAR_ErrorStack - * @param array - * @param string|false Pre-generated error message template - * - * @return string - */ - public static function getErrorMessage(&$stack, $err, $template = false) - { - if ($template) { - $mainmsg = $template; - } else { - $mainmsg = $stack->getErrorMessageTemplate($err['code']); - } - $mainmsg = str_replace('%__msg%', $err['message'], $mainmsg); - if (is_array($err['params']) && count($err['params'])) { - foreach ($err['params'] as $name => $val) { - if (is_array($val)) { - // @ is needed in case $val is a multi-dimensional array - $val = @implode(', ', $val); - } - if (is_object($val)) { - if (method_exists($val, '__toString')) { - $val = $val->__toString(); - } else { - PEAR_ErrorStack::staticPush('PEAR_ErrorStack', PEAR_ERRORSTACK_ERR_OBJTOSTRING, - 'warning', array('obj' => get_class($val)), - 'object %obj% passed into getErrorMessage, but has no __toString() method'); - $val = 'Object'; - } - } - $mainmsg = str_replace('%' . $name . '%', $val, $mainmsg); - } - } - return $mainmsg; - } - - /** - * Standard Error Message Template generator from code - * @return string - */ - function getErrorMessageTemplate($code) - { - if (!isset($this->_errorMsgs[$code])) { - return '%__msg%'; - } - return $this->_errorMsgs[$code]; - } - - /** - * Set the Error Message Template array - * - * The array format must be: - *
-     * array(error code => 'message template',...)
-     * 
- * - * Error message parameters passed into {@link push()} will be used as input - * for the error message. If the template is 'message %foo% was %bar%', and the - * parameters are array('foo' => 'one', 'bar' => 'six'), the error message returned will - * be 'message one was six' - * @return string - */ - function setErrorMessageTemplate($template) - { - $this->_errorMsgs = $template; - } - - - /** - * emulate PEAR::raiseError() - * - * @return PEAR_Error - */ - function raiseError() - { - require_once 'PEAR.php'; - $args = func_get_args(); - return call_user_func_array(array('PEAR', 'raiseError'), $args); - } -} -$stack = &PEAR_ErrorStack::singleton('PEAR_ErrorStack'); -$stack->pushCallback(array('PEAR_ErrorStack', '_handleError')); -?> diff --git a/gulliver/thirdparty/pear/pear-core-minimal/src/System.php b/gulliver/thirdparty/pear/pear-core-minimal/src/System.php deleted file mode 100644 index 89c53e3c1..000000000 --- a/gulliver/thirdparty/pear/pear-core-minimal/src/System.php +++ /dev/null @@ -1,622 +0,0 @@ - - * @copyright 1997-2009 The Authors - * @license http://opensource.org/licenses/bsd-license.php New BSD License - * @link http://pear.php.net/package/PEAR - * @since File available since Release 0.1 - */ - -/** - * base class - */ -require_once 'PEAR.php'; -require_once 'Console/Getopt.php'; - -$GLOBALS['_System_temp_files'] = array(); - -/** -* System offers cross platform compatible system functions -* -* Static functions for different operations. Should work under -* Unix and Windows. The names and usage has been taken from its respectively -* GNU commands. The functions will return (bool) false on error and will -* trigger the error with the PHP trigger_error() function (you can silence -* the error by prefixing a '@' sign after the function call, but this -* is not recommended practice. Instead use an error handler with -* {@link set_error_handler()}). -* -* Documentation on this class you can find in: -* http://pear.php.net/manual/ -* -* Example usage: -* if (!@System::rm('-r file1 dir1')) { -* print "could not delete file1 or dir1"; -* } -* -* In case you need to to pass file names with spaces, -* pass the params as an array: -* -* System::rm(array('-r', $file1, $dir1)); -* -* @category pear -* @package System -* @author Tomas V.V. Cox -* @copyright 1997-2006 The PHP Group -* @license http://opensource.org/licenses/bsd-license.php New BSD License -* @version Release: @package_version@ -* @link http://pear.php.net/package/PEAR -* @since Class available since Release 0.1 -* @static -*/ -class System -{ - /** - * returns the commandline arguments of a function - * - * @param string $argv the commandline - * @param string $short_options the allowed option short-tags - * @param string $long_options the allowed option long-tags - * @return array the given options and there values - */ - public static function _parseArgs($argv, $short_options, $long_options = null) - { - if (!is_array($argv) && $argv !== null) { - /* - // Quote all items that are a short option - $av = preg_split('/(\A| )--?[a-z0-9]+[ =]?((? $a) { - if (empty($a)) { - continue; - } - $argv[$k] = trim($a) ; - } - } - - return Console_Getopt::getopt2($argv, $short_options, $long_options); - } - - /** - * Output errors with PHP trigger_error(). You can silence the errors - * with prefixing a "@" sign to the function call: @System::mkdir(..); - * - * @param mixed $error a PEAR error or a string with the error message - * @return bool false - */ - protected static function raiseError($error) - { - if (PEAR::isError($error)) { - $error = $error->getMessage(); - } - trigger_error($error, E_USER_WARNING); - return false; - } - - /** - * Creates a nested array representing the structure of a directory - * - * System::_dirToStruct('dir1', 0) => - * Array - * ( - * [dirs] => Array - * ( - * [0] => dir1 - * ) - * - * [files] => Array - * ( - * [0] => dir1/file2 - * [1] => dir1/file3 - * ) - * ) - * @param string $sPath Name of the directory - * @param integer $maxinst max. deep of the lookup - * @param integer $aktinst starting deep of the lookup - * @param bool $silent if true, do not emit errors. - * @return array the structure of the dir - */ - protected static function _dirToStruct($sPath, $maxinst, $aktinst = 0, $silent = false) - { - $struct = array('dirs' => array(), 'files' => array()); - if (($dir = @opendir($sPath)) === false) { - if (!$silent) { - System::raiseError("Could not open dir $sPath"); - } - return $struct; // XXX could not open error - } - - $struct['dirs'][] = $sPath = realpath($sPath); // XXX don't add if '.' or '..' ? - $list = array(); - while (false !== ($file = readdir($dir))) { - if ($file != '.' && $file != '..') { - $list[] = $file; - } - } - - closedir($dir); - natsort($list); - if ($aktinst < $maxinst || $maxinst == 0) { - foreach ($list as $val) { - $path = $sPath . DIRECTORY_SEPARATOR . $val; - if (is_dir($path) && !is_link($path)) { - $tmp = System::_dirToStruct($path, $maxinst, $aktinst+1, $silent); - $struct = array_merge_recursive($struct, $tmp); - } else { - $struct['files'][] = $path; - } - } - } - - return $struct; - } - - /** - * Creates a nested array representing the structure of a directory and files - * - * @param array $files Array listing files and dirs - * @return array - * @static - * @see System::_dirToStruct() - */ - protected static function _multipleToStruct($files) - { - $struct = array('dirs' => array(), 'files' => array()); - settype($files, 'array'); - foreach ($files as $file) { - if (is_dir($file) && !is_link($file)) { - $tmp = System::_dirToStruct($file, 0); - $struct = array_merge_recursive($tmp, $struct); - } else { - if (!in_array($file, $struct['files'])) { - $struct['files'][] = $file; - } - } - } - return $struct; - } - - /** - * The rm command for removing files. - * Supports multiple files and dirs and also recursive deletes - * - * @param string $args the arguments for rm - * @return mixed PEAR_Error or true for success - * @static - * @access public - */ - public static function rm($args) - { - $opts = System::_parseArgs($args, 'rf'); // "f" does nothing but I like it :-) - if (PEAR::isError($opts)) { - return System::raiseError($opts); - } - foreach ($opts[0] as $opt) { - if ($opt[0] == 'r') { - $do_recursive = true; - } - } - $ret = true; - if (isset($do_recursive)) { - $struct = System::_multipleToStruct($opts[1]); - foreach ($struct['files'] as $file) { - if (!@unlink($file)) { - $ret = false; - } - } - - rsort($struct['dirs']); - foreach ($struct['dirs'] as $dir) { - if (!@rmdir($dir)) { - $ret = false; - } - } - } else { - foreach ($opts[1] as $file) { - $delete = (is_dir($file)) ? 'rmdir' : 'unlink'; - if (!@$delete($file)) { - $ret = false; - } - } - } - return $ret; - } - - /** - * Make directories. - * - * The -p option will create parent directories - * @param string $args the name of the director(y|ies) to create - * @return bool True for success - */ - public static function mkDir($args) - { - $opts = System::_parseArgs($args, 'pm:'); - if (PEAR::isError($opts)) { - return System::raiseError($opts); - } - - $mode = 0777; // default mode - foreach ($opts[0] as $opt) { - if ($opt[0] == 'p') { - $create_parents = true; - } elseif ($opt[0] == 'm') { - // if the mode is clearly an octal number (starts with 0) - // convert it to decimal - if (strlen($opt[1]) && $opt[1]{0} == '0') { - $opt[1] = octdec($opt[1]); - } else { - // convert to int - $opt[1] += 0; - } - $mode = $opt[1]; - } - } - - $ret = true; - if (isset($create_parents)) { - foreach ($opts[1] as $dir) { - $dirstack = array(); - while ((!file_exists($dir) || !is_dir($dir)) && - $dir != DIRECTORY_SEPARATOR) { - array_unshift($dirstack, $dir); - $dir = dirname($dir); - } - - while ($newdir = array_shift($dirstack)) { - if (!is_writeable(dirname($newdir))) { - $ret = false; - break; - } - - if (!mkdir($newdir, $mode)) { - $ret = false; - } - } - } - } else { - foreach($opts[1] as $dir) { - if ((@file_exists($dir) || !is_dir($dir)) && !mkdir($dir, $mode)) { - $ret = false; - } - } - } - - return $ret; - } - - /** - * Concatenate files - * - * Usage: - * 1) $var = System::cat('sample.txt test.txt'); - * 2) System::cat('sample.txt test.txt > final.txt'); - * 3) System::cat('sample.txt test.txt >> final.txt'); - * - * Note: as the class use fopen, urls should work also (test that) - * - * @param string $args the arguments - * @return boolean true on success - */ - public static function &cat($args) - { - $ret = null; - $files = array(); - if (!is_array($args)) { - $args = preg_split('/\s+/', $args, -1, PREG_SPLIT_NO_EMPTY); - } - - $count_args = count($args); - for ($i = 0; $i < $count_args; $i++) { - if ($args[$i] == '>') { - $mode = 'wb'; - $outputfile = $args[$i+1]; - break; - } elseif ($args[$i] == '>>') { - $mode = 'ab+'; - $outputfile = $args[$i+1]; - break; - } else { - $files[] = $args[$i]; - } - } - $outputfd = false; - if (isset($mode)) { - if (!$outputfd = fopen($outputfile, $mode)) { - $err = System::raiseError("Could not open $outputfile"); - return $err; - } - $ret = true; - } - foreach ($files as $file) { - if (!$fd = fopen($file, 'r')) { - System::raiseError("Could not open $file"); - continue; - } - while ($cont = fread($fd, 2048)) { - if (is_resource($outputfd)) { - fwrite($outputfd, $cont); - } else { - $ret .= $cont; - } - } - fclose($fd); - } - if (is_resource($outputfd)) { - fclose($outputfd); - } - return $ret; - } - - /** - * Creates temporary files or directories. This function will remove - * the created files when the scripts finish its execution. - * - * Usage: - * 1) $tempfile = System::mktemp("prefix"); - * 2) $tempdir = System::mktemp("-d prefix"); - * 3) $tempfile = System::mktemp(); - * 4) $tempfile = System::mktemp("-t /var/tmp prefix"); - * - * prefix -> The string that will be prepended to the temp name - * (defaults to "tmp"). - * -d -> A temporary dir will be created instead of a file. - * -t -> The target dir where the temporary (file|dir) will be created. If - * this param is missing by default the env vars TMP on Windows or - * TMPDIR in Unix will be used. If these vars are also missing - * c:\windows\temp or /tmp will be used. - * - * @param string $args The arguments - * @return mixed the full path of the created (file|dir) or false - * @see System::tmpdir() - */ - public static function mktemp($args = null) - { - static $first_time = true; - $opts = System::_parseArgs($args, 't:d'); - if (PEAR::isError($opts)) { - return System::raiseError($opts); - } - - foreach ($opts[0] as $opt) { - if ($opt[0] == 'd') { - $tmp_is_dir = true; - } elseif ($opt[0] == 't') { - $tmpdir = $opt[1]; - } - } - - $prefix = (isset($opts[1][0])) ? $opts[1][0] : 'tmp'; - if (!isset($tmpdir)) { - $tmpdir = System::tmpdir(); - } - - if (!System::mkDir(array('-p', $tmpdir))) { - return false; - } - - $tmp = tempnam($tmpdir, $prefix); - if (isset($tmp_is_dir)) { - unlink($tmp); // be careful possible race condition here - if (!mkdir($tmp, 0700)) { - return System::raiseError("Unable to create temporary directory $tmpdir"); - } - } - - $GLOBALS['_System_temp_files'][] = $tmp; - if (isset($tmp_is_dir)) { - //$GLOBALS['_System_temp_files'][] = dirname($tmp); - } - - if ($first_time) { - PEAR::registerShutdownFunc(array('System', '_removeTmpFiles')); - $first_time = false; - } - - return $tmp; - } - - /** - * Remove temporary files created my mkTemp. This function is executed - * at script shutdown time - */ - public static function _removeTmpFiles() - { - if (count($GLOBALS['_System_temp_files'])) { - $delete = $GLOBALS['_System_temp_files']; - array_unshift($delete, '-r'); - System::rm($delete); - $GLOBALS['_System_temp_files'] = array(); - } - } - - /** - * Get the path of the temporal directory set in the system - * by looking in its environments variables. - * Note: php.ini-recommended removes the "E" from the variables_order setting, - * making unavaible the $_ENV array, that s why we do tests with _ENV - * - * @return string The temporary directory on the system - */ - public static function tmpdir() - { - if (OS_WINDOWS) { - if ($var = isset($_ENV['TMP']) ? $_ENV['TMP'] : getenv('TMP')) { - return $var; - } - if ($var = isset($_ENV['TEMP']) ? $_ENV['TEMP'] : getenv('TEMP')) { - return $var; - } - if ($var = isset($_ENV['USERPROFILE']) ? $_ENV['USERPROFILE'] : getenv('USERPROFILE')) { - return $var; - } - if ($var = isset($_ENV['windir']) ? $_ENV['windir'] : getenv('windir')) { - return $var; - } - return getenv('SystemRoot') . '\temp'; - } - if ($var = isset($_ENV['TMPDIR']) ? $_ENV['TMPDIR'] : getenv('TMPDIR')) { - return $var; - } - return realpath('/tmp'); - } - - /** - * The "which" command (show the full path of a command) - * - * @param string $program The command to search for - * @param mixed $fallback Value to return if $program is not found - * - * @return mixed A string with the full path or false if not found - * @author Stig Bakken - */ - public static function which($program, $fallback = false) - { - // enforce API - if (!is_string($program) || '' == $program) { - return $fallback; - } - - // full path given - if (basename($program) != $program) { - $path_elements[] = dirname($program); - $program = basename($program); - } else { - $path = getenv('PATH'); - if (!$path) { - $path = getenv('Path'); // some OSes are just stupid enough to do this - } - - $path_elements = explode(PATH_SEPARATOR, $path); - } - - if (OS_WINDOWS) { - $exe_suffixes = getenv('PATHEXT') - ? explode(PATH_SEPARATOR, getenv('PATHEXT')) - : array('.exe','.bat','.cmd','.com'); - // allow passing a command.exe param - if (strpos($program, '.') !== false) { - array_unshift($exe_suffixes, ''); - } - } else { - $exe_suffixes = array(''); - } - - foreach ($exe_suffixes as $suff) { - foreach ($path_elements as $dir) { - $file = $dir . DIRECTORY_SEPARATOR . $program . $suff; - if (is_executable($file)) { - return $file; - } - } - } - return $fallback; - } - - /** - * The "find" command - * - * Usage: - * - * System::find($dir); - * System::find("$dir -type d"); - * System::find("$dir -type f"); - * System::find("$dir -name *.php"); - * System::find("$dir -name *.php -name *.htm*"); - * System::find("$dir -maxdepth 1"); - * - * Params implemented: - * $dir -> Start the search at this directory - * -type d -> return only directories - * -type f -> return only files - * -maxdepth -> max depth of recursion - * -name -> search pattern (bash style). Multiple -name param allowed - * - * @param mixed Either array or string with the command line - * @return array Array of found files - */ - public static function find($args) - { - if (!is_array($args)) { - $args = preg_split('/\s+/', $args, -1, PREG_SPLIT_NO_EMPTY); - } - $dir = realpath(array_shift($args)); - if (!$dir) { - return array(); - } - $patterns = array(); - $depth = 0; - $do_files = $do_dirs = true; - $args_count = count($args); - for ($i = 0; $i < $args_count; $i++) { - switch ($args[$i]) { - case '-type': - if (in_array($args[$i+1], array('d', 'f'))) { - if ($args[$i+1] == 'd') { - $do_files = false; - } else { - $do_dirs = false; - } - } - $i++; - break; - case '-name': - $name = preg_quote($args[$i+1], '#'); - // our magic characters ? and * have just been escaped, - // so now we change the escaped versions to PCRE operators - $name = strtr($name, array('\?' => '.', '\*' => '.*')); - $patterns[] = '('.$name.')'; - $i++; - break; - case '-maxdepth': - $depth = $args[$i+1]; - break; - } - } - $path = System::_dirToStruct($dir, $depth, 0, true); - if ($do_files && $do_dirs) { - $files = array_merge($path['files'], $path['dirs']); - } elseif ($do_dirs) { - $files = $path['dirs']; - } else { - $files = $path['files']; - } - if (count($patterns)) { - $dsq = preg_quote(DIRECTORY_SEPARATOR, '#'); - $pattern = '#(^|'.$dsq.')'.implode('|', $patterns).'($|'.$dsq.')#'; - $ret = array(); - $files_count = count($files); - for ($i = 0; $i < $files_count; $i++) { - // only search in the part of the file below the current directory - $filepart = basename($files[$i]); - if (preg_match($pattern, $filepart)) { - $ret[] = $files[$i]; - } - } - return $ret; - } - return $files; - } -} \ No newline at end of file diff --git a/gulliver/thirdparty/pear/pear_exception/.gitignore b/gulliver/thirdparty/pear/pear_exception/.gitignore deleted file mode 100644 index 479265b07..000000000 --- a/gulliver/thirdparty/pear/pear_exception/.gitignore +++ /dev/null @@ -1,6 +0,0 @@ -PEAR_Exception*.tgz - -# composer related -composer.lock -composer.phar -vendor diff --git a/gulliver/thirdparty/pear/pear_exception/.travis.yml b/gulliver/thirdparty/pear/pear_exception/.travis.yml deleted file mode 100644 index 18875d993..000000000 --- a/gulliver/thirdparty/pear/pear_exception/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: php -php: - - 5.6 - - 5.5 - - 5.4 -script: - - cd tests && phpunit --coverage-text . diff --git a/gulliver/thirdparty/pear/pear_exception/LICENSE b/gulliver/thirdparty/pear/pear_exception/LICENSE deleted file mode 100644 index a00a2421f..000000000 --- a/gulliver/thirdparty/pear/pear_exception/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 1997-2009, - Stig Bakken , - Gregory Beaver , - Helgi Þormar Þorbjörnsson , - Tomas V.V.Cox , - Martin Jansen . -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. - -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. diff --git a/gulliver/thirdparty/pear/pear_exception/PEAR/Exception.php b/gulliver/thirdparty/pear/pear_exception/PEAR/Exception.php deleted file mode 100644 index 5abf4f84a..000000000 --- a/gulliver/thirdparty/pear/pear_exception/PEAR/Exception.php +++ /dev/null @@ -1,456 +0,0 @@ - - * @author Hans Lellelid - * @author Bertrand Mansion - * @author Greg Beaver - * @copyright 1997-2009 The Authors - * @license http://opensource.org/licenses/bsd-license.php New BSD License - * @link http://pear.php.net/package/PEAR_Exception - * @since File available since Release 1.0.0 - */ - - -/** - * Base PEAR_Exception Class - * - * 1) Features: - * - * - Nestable exceptions (throw new PEAR_Exception($msg, $prev_exception)) - * - Definable triggers, shot when exceptions occur - * - Pretty and informative error messages - * - Added more context info available (like class, method or cause) - * - cause can be a PEAR_Exception or an array of mixed - * PEAR_Exceptions/PEAR_ErrorStack warnings - * - callbacks for specific exception classes and their children - * - * 2) Ideas: - * - * - Maybe a way to define a 'template' for the output - * - * 3) Inherited properties from PHP Exception Class: - * - * protected $message - * protected $code - * protected $line - * protected $file - * private $trace - * - * 4) Inherited methods from PHP Exception Class: - * - * __clone - * __construct - * getMessage - * getCode - * getFile - * getLine - * getTraceSafe - * getTraceSafeAsString - * __toString - * - * 5) Usage example - * - * - * require_once 'PEAR/Exception.php'; - * - * class Test { - * function foo() { - * throw new PEAR_Exception('Error Message', ERROR_CODE); - * } - * } - * - * function myLogger($pear_exception) { - * echo $pear_exception->getMessage(); - * } - * // each time a exception is thrown the 'myLogger' will be called - * // (its use is completely optional) - * PEAR_Exception::addObserver('myLogger'); - * $test = new Test; - * try { - * $test->foo(); - * } catch (PEAR_Exception $e) { - * print $e; - * } - * - * - * @category PEAR - * @package PEAR_Exception - * @author Tomas V.V.Cox - * @author Hans Lellelid - * @author Bertrand Mansion - * @author Greg Beaver - * @copyright 1997-2009 The Authors - * @license http://opensource.org/licenses/bsd-license.php New BSD License - * @version Release: @package_version@ - * @link http://pear.php.net/package/PEAR_Exception - * @since Class available since Release 1.0.0 - */ -class PEAR_Exception extends Exception -{ - const OBSERVER_PRINT = -2; - const OBSERVER_TRIGGER = -4; - const OBSERVER_DIE = -8; - protected $cause; - private static $_observers = array(); - private static $_uniqueid = 0; - private $_trace; - - /** - * Supported signatures: - * - PEAR_Exception(string $message); - * - PEAR_Exception(string $message, int $code); - * - PEAR_Exception(string $message, Exception $cause); - * - PEAR_Exception(string $message, Exception $cause, int $code); - * - PEAR_Exception(string $message, PEAR_Error $cause); - * - PEAR_Exception(string $message, PEAR_Error $cause, int $code); - * - PEAR_Exception(string $message, array $causes); - * - PEAR_Exception(string $message, array $causes, int $code); - * - * @param string $message exception message - * @param int|Exception|PEAR_Error|array|null $p2 exception cause - * @param int|null $p3 exception code or null - */ - public function __construct($message, $p2 = null, $p3 = null) - { - if (is_int($p2)) { - $code = $p2; - $this->cause = null; - } elseif (is_object($p2) || is_array($p2)) { - // using is_object allows both Exception and PEAR_Error - if (is_object($p2) && !($p2 instanceof Exception)) { - if (!class_exists('PEAR_Error') || !($p2 instanceof PEAR_Error)) { - throw new PEAR_Exception( - 'exception cause must be Exception, ' . - 'array, or PEAR_Error' - ); - } - } - $code = $p3; - if (is_array($p2) && isset($p2['message'])) { - // fix potential problem of passing in a single warning - $p2 = array($p2); - } - $this->cause = $p2; - } else { - $code = null; - $this->cause = null; - } - parent::__construct($message, $code); - $this->signal(); - } - - /** - * Add an exception observer - * - * @param mixed $callback - A valid php callback, see php func is_callable() - * - A PEAR_Exception::OBSERVER_* constant - * - An array(const PEAR_Exception::OBSERVER_*, - * mixed $options) - * @param string $label The name of the observer. Use this if you want - * to remove it later with removeObserver() - * - * @return void - */ - public static function addObserver($callback, $label = 'default') - { - self::$_observers[$label] = $callback; - } - - /** - * Remove an exception observer - * - * @param string $label Name of the observer - * - * @return void - */ - public static function removeObserver($label = 'default') - { - unset(self::$_observers[$label]); - } - - /** - * Generate a unique ID for an observer - * - * @return int unique identifier for an observer - */ - public static function getUniqueId() - { - return self::$_uniqueid++; - } - - /** - * Send a signal to all observers - * - * @return void - */ - protected function signal() - { - foreach (self::$_observers as $func) { - if (is_callable($func)) { - call_user_func($func, $this); - continue; - } - settype($func, 'array'); - switch ($func[0]) { - case self::OBSERVER_PRINT : - $f = (isset($func[1])) ? $func[1] : '%s'; - printf($f, $this->getMessage()); - break; - case self::OBSERVER_TRIGGER : - $f = (isset($func[1])) ? $func[1] : E_USER_NOTICE; - trigger_error($this->getMessage(), $f); - break; - case self::OBSERVER_DIE : - $f = (isset($func[1])) ? $func[1] : '%s'; - die(printf($f, $this->getMessage())); - break; - default: - trigger_error('invalid observer type', E_USER_WARNING); - } - } - } - - /** - * Return specific error information that can be used for more detailed - * error messages or translation. - * - * This method may be overridden in child exception classes in order - * to add functionality not present in PEAR_Exception and is a placeholder - * to define API - * - * The returned array must be an associative array of parameter => value like so: - *
-     * array('name' => $name, 'context' => array(...))
-     * 
- * - * @return array - */ - public function getErrorData() - { - return array(); - } - - /** - * Returns the exception that caused this exception to be thrown - * - * @return Exception|array The context of the exception - */ - public function getCause() - { - return $this->cause; - } - - /** - * Function must be public to call on caused exceptions - * - * @param array $causes Array that gets filled. - * - * @return void - */ - public function getCauseMessage(&$causes) - { - $trace = $this->getTraceSafe(); - $cause = array('class' => get_class($this), - 'message' => $this->message, - 'file' => 'unknown', - 'line' => 'unknown'); - if (isset($trace[0])) { - if (isset($trace[0]['file'])) { - $cause['file'] = $trace[0]['file']; - $cause['line'] = $trace[0]['line']; - } - } - $causes[] = $cause; - if ($this->cause instanceof PEAR_Exception) { - $this->cause->getCauseMessage($causes); - } elseif ($this->cause instanceof Exception) { - $causes[] = array('class' => get_class($this->cause), - 'message' => $this->cause->getMessage(), - 'file' => $this->cause->getFile(), - 'line' => $this->cause->getLine()); - } elseif (class_exists('PEAR_Error') && $this->cause instanceof PEAR_Error) { - $causes[] = array('class' => get_class($this->cause), - 'message' => $this->cause->getMessage(), - 'file' => 'unknown', - 'line' => 'unknown'); - } elseif (is_array($this->cause)) { - foreach ($this->cause as $cause) { - if ($cause instanceof PEAR_Exception) { - $cause->getCauseMessage($causes); - } elseif ($cause instanceof Exception) { - $causes[] = array('class' => get_class($cause), - 'message' => $cause->getMessage(), - 'file' => $cause->getFile(), - 'line' => $cause->getLine()); - } elseif (class_exists('PEAR_Error') - && $cause instanceof PEAR_Error - ) { - $causes[] = array('class' => get_class($cause), - 'message' => $cause->getMessage(), - 'file' => 'unknown', - 'line' => 'unknown'); - } elseif (is_array($cause) && isset($cause['message'])) { - // PEAR_ErrorStack warning - $causes[] = array( - 'class' => $cause['package'], - 'message' => $cause['message'], - 'file' => isset($cause['context']['file']) ? - $cause['context']['file'] : - 'unknown', - 'line' => isset($cause['context']['line']) ? - $cause['context']['line'] : - 'unknown', - ); - } - } - } - } - - /** - * Build a backtrace and return it - * - * @return array Backtrace - */ - public function getTraceSafe() - { - if (!isset($this->_trace)) { - $this->_trace = $this->getTrace(); - if (empty($this->_trace)) { - $backtrace = debug_backtrace(); - $this->_trace = array($backtrace[count($backtrace)-1]); - } - } - return $this->_trace; - } - - /** - * Gets the first class of the backtrace - * - * @return string Class name - */ - public function getErrorClass() - { - $trace = $this->getTraceSafe(); - return $trace[0]['class']; - } - - /** - * Gets the first method of the backtrace - * - * @return string Method/function name - */ - public function getErrorMethod() - { - $trace = $this->getTraceSafe(); - return $trace[0]['function']; - } - - /** - * Converts the exception to a string (HTML or plain text) - * - * @return string String representation - * - * @see toHtml() - * @see toText() - */ - public function __toString() - { - if (isset($_SERVER['REQUEST_URI'])) { - return $this->toHtml(); - } - return $this->toText(); - } - - /** - * Generates a HTML representation of the exception - * - * @return string HTML code - */ - public function toHtml() - { - $trace = $this->getTraceSafe(); - $causes = array(); - $this->getCauseMessage($causes); - $html = '' . "\n"; - foreach ($causes as $i => $cause) { - $html .= '\n"; - } - $html .= '' . "\n" - . '' - . '' - . '' . "\n"; - - foreach ($trace as $k => $v) { - $html .= '' - . '' - . '' . "\n"; - } - $html .= '' - . '' - . '' . "\n" - . '
' - . str_repeat('-', $i) . ' ' . $cause['class'] . ': ' - . htmlspecialchars($cause['message']) - . ' in ' . $cause['file'] . ' ' - . 'on line ' . $cause['line'] . '' - . "
Exception trace
#FunctionLocation
' . $k . ''; - if (!empty($v['class'])) { - $html .= $v['class'] . $v['type']; - } - $html .= $v['function']; - $args = array(); - if (!empty($v['args'])) { - foreach ($v['args'] as $arg) { - if (is_null($arg)) { - $args[] = 'null'; - } else if (is_array($arg)) { - $args[] = 'Array'; - } else if (is_object($arg)) { - $args[] = 'Object('.get_class($arg).')'; - } else if (is_bool($arg)) { - $args[] = $arg ? 'true' : 'false'; - } else if (is_int($arg) || is_double($arg)) { - $args[] = $arg; - } else { - $arg = (string)$arg; - $str = htmlspecialchars(substr($arg, 0, 16)); - if (strlen($arg) > 16) { - $str .= '…'; - } - $args[] = "'" . $str . "'"; - } - } - } - $html .= '(' . implode(', ', $args) . ')' - . '' . (isset($v['file']) ? $v['file'] : 'unknown') - . ':' . (isset($v['line']) ? $v['line'] : 'unknown') - . '
' . ($k+1) . '{main} 
'; - return $html; - } - - /** - * Generates text representation of the exception and stack trace - * - * @return string - */ - public function toText() - { - $causes = array(); - $this->getCauseMessage($causes); - $causeMsg = ''; - foreach ($causes as $i => $cause) { - $causeMsg .= str_repeat(' ', $i) . $cause['class'] . ': ' - . $cause['message'] . ' in ' . $cause['file'] - . ' on line ' . $cause['line'] . "\n"; - } - return $causeMsg . $this->getTraceAsString(); - } -} -?> diff --git a/gulliver/thirdparty/pear/pear_exception/composer.json b/gulliver/thirdparty/pear/pear_exception/composer.json deleted file mode 100644 index ce33ed1c8..000000000 --- a/gulliver/thirdparty/pear/pear_exception/composer.json +++ /dev/null @@ -1,43 +0,0 @@ -{ - "name": "pear/pear_exception", - "description": "The PEAR Exception base class.", - "type": "class", - "keywords": [ - "exception" - ], - "homepage": "https://github.com/pear/PEAR_Exception", - "license": "BSD-2-Clause", - "authors": [ - { - "name": "Helgi Thormar", - "email": "dufuz@php.net" - }, - { - "name": "Greg Beaver", - "email": "cellog@php.net" - } - ], - "require": { - "php": ">=4.4.0" - }, - "autoload": { - "psr-0": { - "PEAR": "" - } - }, - "extra": { - "branch-alias": { - "dev-master": "1.0.x-dev" - } - }, - "include-path": [ - "." - ], - "support": { - "issues": "http://pear.php.net/bugs/search.php?cmd=display&package_name[]=PEAR_Exception", - "source": "https://github.com/pear/PEAR_Exception" - }, - "require-dev": { - "phpunit/phpunit": "*" - } -} diff --git a/gulliver/thirdparty/pear/pear_exception/package.xml b/gulliver/thirdparty/pear/pear_exception/package.xml deleted file mode 100644 index 98290c6a8..000000000 --- a/gulliver/thirdparty/pear/pear_exception/package.xml +++ /dev/null @@ -1,120 +0,0 @@ - - - PEAR_Exception - pear.php.net - The PEAR Exception base class - PEAR_Exception PHP5 error handling mechanism - - - Christian Weiske - cweiske - cweiske@php.net - yes - - - Helgi Thormar - dufuz - dufuz@php.net - no - - - Greg Beaver - cellog - cellog@php.net - no - - - 2015-02-10 - - - 1.0.0 - 1.0.0 - - - stable - stable - - New BSD License - - This package was split out from the PEAR package. - If you use PEAR_Exception in your package and use nothing from the PEAR package - then it's better to depend on just PEAR_Exception. - - - - - - - - - - - - - - - - - - 5.4.0 - - - 1.9.5 - - - - - - - - - - 1.0.0 - 1.0.0 - - - stable - stable - - 2015-02-10 - New BSD License - Release stable version - - - - - 1.0.0beta2 - 1.0.0 - - - beta - stable - - 2014-02-21 - New BSD License - Bump up PEAR dependency. - - - - - 1.0.0beta1 - 1.0.0 - - - beta - stable - - 2012-05-10 - New BSD License - -This packge was split out from the PEAR package. If you use PEAR_Exception in your package -and use nothing from the PEAR package then it's better to depend on just PEAR_Exception. - - - - diff --git a/gulliver/thirdparty/pear/pear_exception/tests/PEAR/ExceptionTest.php b/gulliver/thirdparty/pear/pear_exception/tests/PEAR/ExceptionTest.php deleted file mode 100644 index 61d2df4f1..000000000 --- a/gulliver/thirdparty/pear/pear_exception/tests/PEAR/ExceptionTest.php +++ /dev/null @@ -1,78 +0,0 @@ -assertNull($e->getCause()); - } - - public function testGetCauseException() - { - $cause = new Exception('foo bar'); - $e = new PEAR_Exception('I caught an exception', $cause); - $this->assertNotNull($e->getCause()); - $this->assertInstanceOf('Exception', $e->getCause()); - $this->assertEquals($cause, $e->getCause()); - } - - public function testGetCauseMessage() - { - $cause = new Exception('foo bar'); - $e = new PEAR_Exception('I caught an exception', $cause); - - $e->getCauseMessage($causes); - $this->assertEquals('I caught an exception', $causes[0]['message']); - $this->assertEquals('foo bar', $causes[1]['message']); - } - - public function testGetTraceSafe() - { - $e = new PEAR_Exception('oops'); - $this->assertInternalType('array', $e->getTraceSafe()); - } - - public function testGetErrorClass() - { - $e = new PEAR_Exception('oops'); - $this->assertEquals('PEAR_ExceptionTest', $e->getErrorClass()); - } - - public function testGetErrorMethod() - { - $e = new PEAR_Exception('oops'); - $this->assertEquals('testGetErrorMethod', $e->getErrorMethod()); - } - - public function test__toString() - { - $e = new PEAR_Exception('oops'); - $this->assertInternalType('string', (string) $e); - $this->assertContains('oops', (string) $e); - } - - public function testToHtml() - { - $e = new PEAR_Exception('oops'); - $html = $e->toHtml(); - $this->assertInternalType('string', $html); - $this->assertContains('oops', $html); - } -} -?> diff --git a/gulliver/thirdparty/pear/template.spec b/gulliver/thirdparty/pear/template.spec deleted file mode 100644 index dc6c66550..000000000 --- a/gulliver/thirdparty/pear/template.spec +++ /dev/null @@ -1,44 +0,0 @@ -Summary: PEAR: @summary@ -Name: @rpm_package@ -Version: @version@ -Release: 1 -License: @release_license@ -Group: Development/Libraries -Source: http://@master_server@/get/@package@-%{version}.tgz -BuildRoot: %{_tmppath}/%{name}-root -URL: http://@master_server@/ -Prefix: %{_prefix} -Docdir: @doc_dir@/@package@ -BuildArchitectures: @arch@ -@extra_headers@ - -%description -@description@ - -%prep -#rm -rf Console_Getopt-%{version} package.xml -#mkdir -p Console_Getopt-%{version} -#ln -s Console_Getopt-%{version}/package.xml package.xml -%setup -q -D -n @package@-%{version} -mv ../package.xml . - -%build -echo BuildRoot=%{buildroot} - -%post -pear uninstall --nodeps -r @package@ - -%postun -pear install --nodeps -r @rpm_xml_dir@/@package@.xml - -%install -rm -rf %{buildroot}/* -pear -q install -R %{buildroot} -n package.xml -mkdir -p %{buildroot}@rpm_xml_dir@ -cp -p package.xml %{buildroot}@rpm_xml_dir@/@package@.xml - -%files -%defattr(-,root,root) -%doc @doc_files@ -@files@ -@rpm_xml_dir@/@package@.xml diff --git a/workflow/engine/PmBootstrap.php b/workflow/engine/PmBootstrap.php index 728075580..9281cd4cf 100644 --- a/workflow/engine/PmBootstrap.php +++ b/workflow/engine/PmBootstrap.php @@ -25,7 +25,7 @@ class PmBootstrap extends Bootstrap { parent::configure(); - $this->pmConfig = System::getSystemConfiguration(); + $this->pmConfig = PMSystem::getSystemConfiguration(); $e_all = defined('E_DEPRECATED') ? E_ALL & ~E_DEPRECATED : E_ALL; $e_all = defined('E_STRICT') ? $e_all & ~E_STRICT : $e_all; diff --git a/workflow/engine/bin/cron.php b/workflow/engine/bin/cron.php index f0ace7c4b..b75192e7e 100644 --- a/workflow/engine/bin/cron.php +++ b/workflow/engine/bin/cron.php @@ -77,7 +77,7 @@ try { $classLoader->addModelClassPath(PATH_TRUNK . 'workflow' . PATH_SEP . 'engine' . PATH_SEP . 'classes' . PATH_SEP . 'model' . PATH_SEP); //Load classes - $arraySystemConfiguration = System::getSystemConfiguration(); + $arraySystemConfiguration = PMSystem::getSystemConfiguration(); $e_all = (defined('E_DEPRECATED'))? E_ALL & ~E_DEPRECATED : E_ALL; $e_all = (defined('E_STRICT'))? $e_all & ~E_STRICT : $e_all; diff --git a/workflow/engine/bin/cron_single.php b/workflow/engine/bin/cron_single.php index 534f1ca76..33be5a505 100644 --- a/workflow/engine/bin/cron_single.php +++ b/workflow/engine/bin/cron_single.php @@ -64,7 +64,7 @@ try { $classLoader->addModelClassPath(PATH_TRUNK . 'workflow' . PATH_SEP . 'engine' . PATH_SEP . 'classes' . PATH_SEP . 'model' . PATH_SEP); - $arraySystemConfiguration = System::getSystemConfiguration('', '', $workspace); + $arraySystemConfiguration = PMSystem::getSystemConfiguration('', '', $workspace); $e_all = (defined('E_DEPRECATED'))? E_ALL & ~E_DEPRECATED : E_ALL; $e_all = (defined('E_STRICT'))? $e_all & ~E_STRICT : $e_all; diff --git a/workflow/engine/bin/reindex_solr.php b/workflow/engine/bin/reindex_solr.php index 17eb283f6..ae15d4a98 100644 --- a/workflow/engine/bin/reindex_solr.php +++ b/workflow/engine/bin/reindex_solr.php @@ -144,7 +144,7 @@ if (! defined ('SYS_SYS')) { // **************************************** // read initialize file require_once PATH_HOME . 'engine' . PATH_SEP . 'classes' . PATH_SEP . 'class.system.php'; - $config = System::getSystemConfiguration ('', '', SYS_SYS); + $config = PMSystem::getSystemConfiguration ('', '', SYS_SYS); define ('MEMCACHED_ENABLED', $config ['memcached']); define ('MEMCACHED_SERVER', $config ['memcached_server']); define ('TIME_ZONE', $config ['time_zone']); @@ -260,7 +260,7 @@ function processWorkspace() try { - if (($solrConf = System::solrEnv (SYS_SYS)) !== false) { + if (($solrConf = PMSystem::solrEnv (SYS_SYS)) !== false) { print "Solr Configuration file: " . PATH_DATA_SITE . "env.ini\n"; print "solr_enabled: " . $solrConf ['solr_enabled'] . "\n"; print "solr_host: " . $solrConf ['solr_host'] . "\n"; diff --git a/workflow/engine/bin/tasks/cliCommon.php b/workflow/engine/bin/tasks/cliCommon.php index 2e5653d2e..f75c4b0a7 100644 --- a/workflow/engine/bin/tasks/cliCommon.php +++ b/workflow/engine/bin/tasks/cliCommon.php @@ -47,7 +47,7 @@ function get_workspaces_from_args($args, $includeAll = true) { $workspaces[] = new workspaceTools($arg); } if (empty($workspaces) && $includeAll) { - $workspaces = System::listWorkspaces(); + $workspaces = PMSystem::listWorkspaces(); } return $workspaces; } diff --git a/workflow/engine/bin/tasks/cliUpgrade.php b/workflow/engine/bin/tasks/cliUpgrade.php index b06f7ec52..3afba3da3 100644 --- a/workflow/engine/bin/tasks/cliUpgrade.php +++ b/workflow/engine/bin/tasks/cliUpgrade.php @@ -87,7 +87,7 @@ function run_upgrade($command, $args) } $flag = G::isPMUnderUpdating(1, $oneWorkspace); //start to upgrade - $checksum = System::verifyChecksum(); + $checksum = PMSystem::verifyChecksum(); if ($checksum === false) { CLI::logging(CLI::error("checksum.txt not found, integrity check is not possible") . "\n"); if (!CLI::question("Integrity check failed, do you want to continue the upgrade?")) { @@ -177,7 +177,7 @@ function run_upgrade($command, $args) } } } else { - CLI::logging('ProcessMaker ' . System::getVersion(). ' installed', PATH_DATA . 'log/upgrades.log'); + CLI::logging('ProcessMaker ' . PMSystem::getVersion(). ' installed', PATH_DATA . 'log/upgrades.log'); } //Safe upgrade for JavaScript files diff --git a/workflow/engine/bin/verify_solr.php b/workflow/engine/bin/verify_solr.php index a67c12dd4..dbe0352aa 100644 --- a/workflow/engine/bin/verify_solr.php +++ b/workflow/engine/bin/verify_solr.php @@ -119,7 +119,7 @@ if (! defined ('SYS_SYS')) { // **************************************** // read initialize file require_once PATH_HOME . 'engine' . PATH_SEP . 'classes' . PATH_SEP . 'class.system.php'; - $config = System::getSystemConfiguration ('', '', SYS_SYS); + $config = PMSystem::getSystemConfiguration ('', '', SYS_SYS); define ('MEMCACHED_ENABLED', $config ['memcached']); define ('MEMCACHED_SERVER', $config ['memcached_server']); define ('TIME_ZONE', $config ['time_zone']); @@ -337,7 +337,7 @@ function displayMissingCases($aAppUidsDB, $aAppUidsSolr) function getListUids($usrUid, $action) { - if (($solrConf = System::solrEnv (SYS_SYS)) !== false) { + if (($solrConf = PMSystem::solrEnv (SYS_SYS)) !== false) { print "Solr Configuration file: " . PATH_DATA_SITE . "env.ini\n"; print "solr_enabled: " . $solrConf ['solr_enabled'] . "\n"; diff --git a/workflow/engine/classes/class.system.php b/workflow/engine/classes/PMSystem.php similarity index 99% rename from workflow/engine/classes/class.system.php rename to workflow/engine/classes/PMSystem.php index b1fc71b3b..91c6214dc 100644 --- a/workflow/engine/classes/class.system.php +++ b/workflow/engine/classes/PMSystem.php @@ -36,7 +36,7 @@ * */ -class System +class PMSystem { public $sFilename; public $sFilesList; @@ -232,7 +232,7 @@ class System $Fields['IP'] = isset($ipe[0]) ? $ipe[0] : ''; //lookup($ipe[0]); - $Fields['PLUGINS_LIST'] = System::getPlugins(); + $Fields['PLUGINS_LIST'] = PMSystem::getPlugins(); return $Fields; } @@ -723,7 +723,7 @@ class System */ public static function getSystemSchema () { - return System::getSchema( PATH_TRUNK . "workflow/engine/config/schema.xml" ); + return PMSystem::getSchema( PATH_TRUNK . "workflow/engine/config/schema.xml" ); } /** @@ -733,7 +733,7 @@ class System */ public static function getSystemSchemaRbac () { - return System::getSchema( PATH_TRUNK . "rbac/engine/config/schema.xml" ); + return PMSystem::getSchema( PATH_TRUNK . "rbac/engine/config/schema.xml" ); } /** @@ -748,7 +748,7 @@ class System $filter = new InputFilter(); $pathFile = $filter->xssFilterHard(PATH_PLUGINS . $pluginName . "/config/schema.xml", 'path'); if (file_exists( $pathFile )) { - return System::getSchema( $pathFile ); + return PMSystem::getSchema( $pathFile ); } else { return false; } @@ -1231,9 +1231,9 @@ class System public static function solrEnv ($sysName = '') { if (empty( $sysName )) { - $conf = System::getSystemConfiguration(); + $conf = PMSystem::getSystemConfiguration(); } else { - $conf = System::getSystemConfiguration( '', '', $sysName ); + $conf = PMSystem::getSystemConfiguration( '', '', $sysName ); } if (! isset( $conf['solr_enabled'] ) || ! isset( $conf['solr_host'] ) || ! isset( $conf['solr_instance'] )) { @@ -1251,7 +1251,7 @@ class System public static function getInstance() { if (is_null(self::$instance)) { - self::$instance = new System(); + self::$instance = new PMSystem(); } return self::$instance; diff --git a/workflow/engine/classes/class.Upgrade.php b/workflow/engine/classes/class.Upgrade.php index acb269975..1512442bb 100644 --- a/workflow/engine/classes/class.Upgrade.php +++ b/workflow/engine/classes/class.Upgrade.php @@ -123,7 +123,7 @@ class Upgrade G::rm_dir(PATH_C); mkdir(PATH_C, 0777, true); } - $workspaces = System::listWorkspaces(); + $workspaces = PMSystem::listWorkspaces(); $count = count($workspaces); $first = true; $num = 0; diff --git a/workflow/engine/classes/class.case.php b/workflow/engine/classes/class.case.php index f715cfeda..2f550fdf1 100644 --- a/workflow/engine/classes/class.case.php +++ b/workflow/engine/classes/class.case.php @@ -42,7 +42,7 @@ class Cases public function __construct() { //get Solr initialization variables - if (($solrConf = System::solrEnv()) !== false) { + if (($solrConf = PMSystem::solrEnv()) !== false) { $this->appSolr = new AppSolr($solrConf['solr_enabled'], $solrConf['solr_host'], $solrConf['solr_instance']); } } diff --git a/workflow/engine/classes/class.dashletRssReader.php b/workflow/engine/classes/class.dashletRssReader.php index 3fbf024d4..d1ff36974 100644 --- a/workflow/engine/classes/class.dashletRssReader.php +++ b/workflow/engine/classes/class.dashletRssReader.php @@ -54,7 +54,7 @@ class dashletRssReader implements DashletInterface curl_setopt( $pCurl, CURLOPT_VERBOSE, false ); //Apply proxy settings - $sysConf = System::getSystemConfiguration(); + $sysConf = PMSystem::getSystemConfiguration(); if ($sysConf['proxy_host'] != '') { curl_setopt( $pCurl, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '') ); if ($sysConf['proxy_port'] != '') { diff --git a/workflow/engine/classes/class.enterpriseUtils.php b/workflow/engine/classes/class.enterpriseUtils.php index 2c7aceca8..85f543bde 100644 --- a/workflow/engine/classes/class.enterpriseUtils.php +++ b/workflow/engine/classes/class.enterpriseUtils.php @@ -40,7 +40,7 @@ class EnterpriseUtils curl_setopt($ch, CURLOPT_VERBOSE, true); //Apply proxy settings - $sysConf = System::getSystemConfiguration(); + $sysConf = PMSystem::getSystemConfiguration(); if (isset($sysConf['proxy_host'])) { if ($sysConf['proxy_host'] != '') { curl_setopt($ch, CURLOPT_PROXY, $sysConf['proxy_host'] . ($sysConf['proxy_port'] != '' ? ':' . $sysConf['proxy_port'] : '')); diff --git a/workflow/engine/classes/class.license.lib.php b/workflow/engine/classes/class.license.lib.php index fb351ac81..7f1171ce3 100644 --- a/workflow/engine/classes/class.license.lib.php +++ b/workflow/engine/classes/class.license.lib.php @@ -236,7 +236,7 @@ class padl } // Proxy settings - $sysConf = System::getSystemConfiguration(); + $sysConf = PMSystem::getSystemConfiguration(); if ($sysConf['proxy_host'] != '') { if (!is_array($params['http'])) { $params['http'] = array(); diff --git a/workflow/engine/classes/class.patch.php b/workflow/engine/classes/class.patch.php index cd95c37af..9a46bb96b 100644 --- a/workflow/engine/classes/class.patch.php +++ b/workflow/engine/classes/class.patch.php @@ -30,7 +30,7 @@ class p11835 extends patch $rs->next(); while($row = $rs->getRow()) { if ($row ['Field'] == "TAS_GROUP_VARIABLE") { - $version = System::getVersion (); + $version = PMSystem::getVersion (); $version = explode('-',$version); if ($version[0] == '2.5.1') { echo "Version " . $version[0] . " Patch\n"; @@ -98,7 +98,7 @@ class p11835 extends patch $arrayHotfix = $conf->getConfiguration("HOTFIX", ""); $arrayHotfix = (is_array($arrayHotfix))? $arrayHotfix : array($arrayHotfix); - $pmVersion = self::pmVersion(System::getVersion()) . ""; + $pmVersion = self::pmVersion(PMSystem::getVersion()) . ""; if (($pmVersion == "2.5.2.4" || $pmVersion == "2.8") && !in_array("15394", $arrayHotfix)) { $cnn = Propel::getConnection("workflow"); diff --git a/workflow/engine/classes/class.pluginRegistry.php b/workflow/engine/classes/class.pluginRegistry.php index 82fe83a42..cdd0aecfd 100644 --- a/workflow/engine/classes/class.pluginRegistry.php +++ b/workflow/engine/classes/class.pluginRegistry.php @@ -596,7 +596,7 @@ class PMPluginRegistry public function uninstallPluginWorkspaces ($arrayPlugin) { - $workspace = System::listWorkspaces(); + $workspace = PMSystem::listWorkspaces(); foreach ($workspace as $indexWS => $ws) { $wsPathDataSite = PATH_DATA . "sites" . PATH_SEP . $ws->name . PATH_SEP; @@ -1640,7 +1640,7 @@ class PMPluginRegistry if (isset($pluginDetails->aWorkspaces) && is_array($pluginDetails->aWorkspaces) && count($pluginDetails->aWorkspaces) > 0) { $arrayWorkspace = array(); - foreach (System::listWorkspaces() as $value) { + foreach (PMSystem::listWorkspaces() as $value) { $workspaceTools = $value; $arrayWorkspace[] = $workspaceTools->name; diff --git a/workflow/engine/classes/class.pmDynaform.php b/workflow/engine/classes/class.pmDynaform.php index 9a258c469..1f6ecac62 100644 --- a/workflow/engine/classes/class.pmDynaform.php +++ b/workflow/engine/classes/class.pmDynaform.php @@ -1059,7 +1059,7 @@ class pmDynaform $javascript = " "; @@ -1406,7 +1406,7 @@ class pmDynaform $javascrip = "" . "