Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/nextcloud/server.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
path: root/inc
diff options
context:
space:
mode:
authorFrank Karlitschek <karlitschek@kde.org>2011-08-13 17:19:40 +0400
committerFrank Karlitschek <karlitschek@kde.org>2011-08-13 17:19:40 +0400
commit9ac084d0b89b3f2d4a86e1c73a2017bd67c4284d (patch)
tree3a7eb972c3478c0d758423252c8997bded997ce1 /inc
parent93bc69011b7a89a654732496f872a248b69c78c2 (diff)
remove for now. main repository is at projects.kde.org/owncloud
Diffstat (limited to 'inc')
-rw-r--r--inc/Archive/Tar.php1762
-rw-r--r--inc/Console/Getopt.php251
-rw-r--r--inc/HTTP/WebDAV/Server.php2140
-rw-r--r--inc/HTTP/WebDAV/Server/Filesystem.php760
-rw-r--r--inc/HTTP/WebDAV/Tools/_parse_lockinfo.php251
-rw-r--r--inc/HTTP/WebDAV/Tools/_parse_propfind.php191
-rw-r--r--inc/HTTP/WebDAV/Tools/_parse_proppatch.php237
-rw-r--r--inc/Log.php635
-rw-r--r--inc/Log/composite.php196
-rw-r--r--inc/Log/console.php190
-rw-r--r--inc/Log/daemon.php229
-rw-r--r--inc/Log/display.php108
-rw-r--r--inc/Log/error_log.php104
-rw-r--r--inc/Log/file.php286
-rw-r--r--inc/Log/mail.php222
-rw-r--r--inc/Log/mcal.php171
-rw-r--r--inc/Log/null.php68
-rw-r--r--inc/Log/observer.php126
-rw-r--r--inc/Log/sql.php225
-rw-r--r--inc/Log/sqlite.php238
-rw-r--r--inc/Log/syslog.php160
-rw-r--r--inc/Log/win.php256
-rw-r--r--inc/MDB2.php4361
-rw-r--r--inc/MDB2/Date.php183
-rw-r--r--inc/MDB2/Driver/Datatype/Common.php1824
-rw-r--r--inc/MDB2/Driver/Datatype/mysql.php553
-rw-r--r--inc/MDB2/Driver/Datatype/pgsql.php554
-rw-r--r--inc/MDB2/Driver/Datatype/sqlite.php409
-rw-r--r--inc/MDB2/Driver/Function/Common.php293
-rw-r--r--inc/MDB2/Driver/Function/mysql.php136
-rw-r--r--inc/MDB2/Driver/Function/pgsql.php115
-rw-r--r--inc/MDB2/Driver/Function/sqlite.php162
-rw-r--r--inc/MDB2/Driver/Manager/Common.php1014
-rw-r--r--inc/MDB2/Driver/Manager/mysql.php1432
-rw-r--r--inc/MDB2/Driver/Manager/pgsql.php948
-rw-r--r--inc/MDB2/Driver/Manager/sqlite.php1362
-rw-r--r--inc/MDB2/Driver/Native/Common.php61
-rw-r--r--inc/MDB2/Driver/Native/mysql.php60
-rw-r--r--inc/MDB2/Driver/Native/pgsql.php88
-rw-r--r--inc/MDB2/Driver/Native/sqlite.php60
-rw-r--r--inc/MDB2/Driver/Reverse/Common.php517
-rw-r--r--inc/MDB2/Driver/Reverse/mysql.php536
-rw-r--r--inc/MDB2/Driver/Reverse/pgsql.php573
-rw-r--r--inc/MDB2/Driver/Reverse/sqlite.php609
-rw-r--r--inc/MDB2/Driver/mysql.php1700
-rw-r--r--inc/MDB2/Driver/pgsql.php1519
-rw-r--r--inc/MDB2/Driver/sqlite.php1082
-rw-r--r--inc/MDB2/Extended.php721
-rw-r--r--inc/MDB2/Iterator.php259
-rw-r--r--inc/MDB2/LOB.php264
-rw-r--r--inc/MDB2/Schema.php2763
-rw-r--r--inc/MDB2/Schema/Parser.php819
-rw-r--r--inc/MDB2/Schema/Parser2.php624
-rw-r--r--inc/MDB2/Schema/Reserved/ibase.php436
-rw-r--r--inc/MDB2/Schema/Reserved/mssql.php258
-rw-r--r--inc/MDB2/Schema/Reserved/mysql.php284
-rw-r--r--inc/MDB2/Schema/Reserved/oci8.php171
-rw-r--r--inc/MDB2/Schema/Reserved/pgsql.php147
-rw-r--r--inc/MDB2/Schema/Tool.php560
-rw-r--r--inc/MDB2/Schema/Tool/ParameterException.php6
-rw-r--r--inc/MDB2/Schema/Validate.php922
-rw-r--r--inc/MDB2/Schema/Writer.php581
-rw-r--r--inc/Mail.php212
-rw-r--r--inc/Mail/RFC822.php923
-rw-r--r--inc/Mail/mail.php130
-rw-r--r--inc/Mail/mime.php713
-rw-r--r--inc/Mail/mimeDecode.php837
-rw-r--r--inc/Mail/mimePart.php351
-rw-r--r--inc/Mail/null.php60
-rw-r--r--inc/Mail/sendmail.php145
-rw-r--r--inc/Mail/smtp.php223
-rw-r--r--inc/Mail/xmail.dtd19
-rw-r--r--inc/Mail/xmail.xsl70
-rw-r--r--inc/Net/SMTP.php970
-rw-r--r--inc/Net/Socket.php528
-rw-r--r--inc/OS/Guess.php287
-rw-r--r--inc/PEAR.php1055
-rw-r--r--inc/PEAR/Autoloader.php208
-rw-r--r--inc/PEAR/Builder.php426
-rw-r--r--inc/PEAR/Command.php398
-rw-r--r--inc/PEAR/Command/Auth.php155
-rw-r--r--inc/PEAR/Command/Build.php89
-rw-r--r--inc/PEAR/Command/Common.php249
-rw-r--r--inc/PEAR/Command/Config.php225
-rw-r--r--inc/PEAR/Command/Install.php470
-rw-r--r--inc/PEAR/Command/Mirror.php101
-rw-r--r--inc/PEAR/Command/Package.php819
-rw-r--r--inc/PEAR/Command/Registry.php351
-rw-r--r--inc/PEAR/Command/Remote.php435
-rw-r--r--inc/PEAR/Common.php2094
-rw-r--r--inc/PEAR/Config.php1169
-rw-r--r--inc/PEAR/Dependency.php487
-rw-r--r--inc/PEAR/Downloader.php680
-rw-r--r--inc/PEAR/ErrorStack.php981
-rw-r--r--inc/PEAR/Exception.php359
-rw-r--r--inc/PEAR/Frontend/CLI.php509
-rw-r--r--inc/PEAR/Installer.php1068
-rw-r--r--inc/PEAR/Packager.php165
-rw-r--r--inc/PEAR/Registry.php538
-rw-r--r--inc/PEAR/Remote.php394
-rw-r--r--inc/PEAR/RunTest.php363
-rw-r--r--inc/PHPUnit.php83
-rw-r--r--inc/PHPUnit/Assert.php384
-rw-r--r--inc/PHPUnit/GUI/Gtk.php698
-rw-r--r--inc/PHPUnit/GUI/HTML.php210
-rw-r--r--inc/PHPUnit/GUI/SetupDecorator.php167
-rw-r--r--inc/PHPUnit/RepeatedTest.php112
-rw-r--r--inc/PHPUnit/Skeleton.php406
-rw-r--r--inc/PHPUnit/TestCase.php237
-rw-r--r--inc/PHPUnit/TestDecorator.php110
-rw-r--r--inc/PHPUnit/TestFailure.php88
-rw-r--r--inc/PHPUnit/TestListener.php120
-rw-r--r--inc/PHPUnit/TestResult.php300
-rw-r--r--inc/PHPUnit/TestSuite.php220
-rw-r--r--inc/System.php540
-rwxr-xr-xinc/User/backend.php161
-rwxr-xr-xinc/User/database.php417
-rw-r--r--inc/XML/Parser.php683
-rw-r--r--inc/XML/RPC.php1951
-rw-r--r--inc/XML/RPC/Server.php624
-rw-r--r--inc/docs/HTTP_WebDAV_Server/README10
-rw-r--r--inc/docs/HTTP_WebDAV_Server/dav.txt229
-rw-r--r--inc/docs/HTTP_WebDAV_Server/db/Fileserver.sql49
-rw-r--r--inc/lib_base.php728
-rw-r--r--inc/lib_config.php391
-rw-r--r--inc/lib_connect.php300
-rw-r--r--inc/lib_fileobserver.php82
-rwxr-xr-xinc/lib_files.php399
-rw-r--r--inc/lib_filestorage.php430
-rw-r--r--inc/lib_filesystem.php380
-rw-r--r--inc/lib_log.php86
-rw-r--r--inc/lib_ocs.php496
-rw-r--r--inc/lib_plugin.php381
-rw-r--r--inc/lib_remotestorage.php353
-rw-r--r--inc/lib_user.php241
-rw-r--r--inc/package.dtd110
-rw-r--r--inc/packages/Archive_Tar.xml122
-rw-r--r--inc/packages/Console_Getopt.xml69
-rw-r--r--inc/packages/DB.xml348
-rw-r--r--inc/packages/Log.xml315
-rw-r--r--inc/packages/Mail.xml122
-rw-r--r--inc/packages/Mail_Mime.xml113
-rw-r--r--inc/packages/Net_SMTP.xml137
-rw-r--r--inc/packages/Net_Socket.xml84
-rw-r--r--inc/packages/PEAR.xml282
-rw-r--r--inc/packages/PHPUnit.xml224
-rw-r--r--inc/packages/XML_Parser.xml254
-rw-r--r--inc/packages/XML_RPC.xml266
-rw-r--r--inc/pearcmd.php318
-rwxr-xr-xinc/templates/adminform.php193
-rw-r--r--inc/templates/configform.php36
-rw-r--r--inc/templates/footer.php26
-rw-r--r--inc/templates/header.php90
-rw-r--r--inc/templates/loginform.php9
-rw-r--r--inc/templates/pluginform.php77
-rwxr-xr-xinc/templates/settings.php50
-rw-r--r--inc/templates/userform.php126
157 files changed, 0 insertions, 72465 deletions
diff --git a/inc/Archive/Tar.php b/inc/Archive/Tar.php
deleted file mode 100644
index d6e6e29350e..00000000000
--- a/inc/Archive/Tar.php
+++ /dev/null
@@ -1,1762 +0,0 @@
-<?php
-/* vim: set ts=4 sw=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Vincent Blavet <vincent@phpconcept.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Tar.php,v 1.29 2005/03/17 21:02:31 vblavet Exp $
-
-require_once 'PEAR.php';
-
-
-define ('ARCHIVE_TAR_ATT_SEPARATOR', 90001);
-
-/**
-* Creates a (compressed) Tar archive
-*
-* @author Vincent Blavet <vincent@phpconcept.net>
-* @version $Revision: 1.29 $
-* @package Archive
-*/
-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='';
-
- // {{{ 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 {
- die("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)) {
- die("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='')
- {
- return $this->extractModify($p_path, '');
- }
- // }}}
-
- // {{{ 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.
- * @return true on success, false on error.
- * @access public
- */
- function addString($p_filename, $p_string)
- {
- $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);
-
- $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.
- * @return boolean true on success, false on error.
- * @access public
- * @see extractList()
- */
- function extractModify($p_path, $p_remove_path)
- {
- $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);
- $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.
- * @return true on success, false on error.
- * @access public
- * @see extractModify()
- */
- function extractList($p_filelist, $p_path='', $p_remove_path='')
- {
- $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);
- $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;
- }
- // }}}
-
- // {{{ _error()
- function _error($p_message)
- {
- // ----- To be completed
- $this->raiseError($p_message);
- }
- // }}}
-
- // {{{ _warning()
- function _warning($p_message)
- {
- // ----- To be completed
- $this->raiseError($p_message);
- }
- // }}}
-
- // {{{ _isArchive()
- function _isArchive($p_filename=NULL)
- {
- if ($p_filename == NULL) {
- $p_filename = $this->_tarname;
- }
- clearstatcache();
- return @is_file($p_filename);
- }
- // }}}
-
- // {{{ _openWrite()
- function _openWrite()
- {
- if ($this->_compress_type == 'gz')
- $this->_file = @gzopen($this->_tarname, "wb9");
- else if ($this->_compress_type == 'bz2')
- $this->_file = @bzopen($this->_tarname, "wb");
- else if ($this->_compress_type == 'none')
- $this->_file = @fopen($this->_tarname, "wb");
- else
- $this->_error('Unknown or missing compression type ('
- .$this->_compress_type.')');
-
- 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')
- $this->_file = @gzopen($v_filename, "rb");
- else if ($this->_compress_type == 'bz2')
- $this->_file = @bzopen($v_filename, "rb");
- else if ($this->_compress_type == 'none')
- $this->_file = @fopen($v_filename, "rb");
- else
- $this->_error('Unknown or missing compression type ('
- .$this->_compress_type.')');
-
- 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->_file = @bzopen($this->_tarname, "r+b");
- else if ($this->_compress_type == 'none')
- $this->_file = @fopen($this->_tarname, "r+b");
- else
- $this->_error('Unknown or missing compression type ('
- .$this->_compress_type.')');
-
- 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, @ftell($this->_file)+($p_len*512));
- 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("a512", '');
- $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;
-
- if (!file_exists($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)) {
- 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)
- {
- 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 (!$this->_writeHeaderBlock($p_filename, strlen($p_string),
- 0, 0, "", 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 = stat($p_filename);
- $v_uid = sprintf("%6s ", DecOct($v_info[4]));
- $v_gid = sprintf("%6s ", DecOct($v_info[5]));
- $v_perms = sprintf("%6s ", DecOct(fileperms($p_filename)));
-
- $v_mtime = sprintf("%11s", DecOct(filemtime($p_filename)));
-
- if (@is_dir($p_filename)) {
- $v_typeflag = "5";
- $v_size = sprintf("%11s ", DecOct(0));
- } else {
- $v_typeflag = '';
- clearstatcache();
- $v_size = sprintf("%11s ", DecOct(filesize($p_filename)));
- }
-
- $v_linkname = '';
-
- $v_magic = '';
-
- $v_version = '';
-
- $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("%6s ", 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("%11s ", DecOct(0));
- } else {
- $v_size = sprintf("%11s ", DecOct($p_size));
- }
-
- $v_uid = sprintf("%6s ", DecOct($p_uid));
- $v_gid = sprintf("%6s ", DecOct($p_gid));
- $v_perms = sprintf("%6s ", DecOct($p_perms));
-
- $v_mtime = sprintf("%11s", DecOct($p_mtime));
-
- $v_linkname = '';
-
- $v_magic = '';
-
- $v_version = '';
-
- $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("%6s ", 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("%6s ", 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;
- }
-
- // ----- 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));
-
- $v_data = unpack("a100filename/a8mode/a8uid/a8gid/a12size/a12mtime/"
- ."a8checksum/a1typeflag/a100link/a6magic/a2version/"
- ."a32uname/a32gname/a8devmajor/a8devminor",
- $v_binary_data);
-
- // ----- 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'] = trim($v_data['filename']);
- $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;
- }
- /* ----- All these fields are removed form the header because
- they do not carry interesting info
- $v_header[link] = trim($v_data[link]);
- $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;
- }
- // }}}
-
- // {{{ _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 .= $v_content;
- }
-
- // ----- Read the next header
- $v_binary_data = $this->_readBlock();
-
- if (!$this->_readHeader($v_binary_data, $v_header))
- return false;
-
- $v_header['filename'] = $v_filename;
-
- 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)
- {
- $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<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 (($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;
- }
- }
- } 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);
-
- // ----- Change the file mode, mtime
- @touch($v_header['filename'], $v_header['mtime']);
- // To be completed
- //chmod($v_header[filename], DecOct($v_header[mode]));
- }
-
- // ----- Check the file size
- clearstatcache();
- if (filesize($v_header['filename']) != $v_header['size']) {
- $this->_error('Extracted file '.$v_header['filename']
- .' does not have the correct file size \''
- .filesize($v_header['filename'])
- .'\' ('.$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;
- }
- }
-
- 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", "rb");
-
- 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') {
- $v_buffer = @gzread($v_temp_tar, 512);
-
- // ----- Read the following blocks but not the last one
- if (!@gzeof($v_temp_tar)) {
- do{
- $v_binary_data = pack("a512", $v_buffer);
- $this->_writeBlock($v_binary_data);
- $v_buffer = @gzread($v_temp_tar, 512);
-
- } while (!@gzeof($v_temp_tar));
- }
-
- @gzclose($v_temp_tar);
- }
- elseif ($this->_compress_type == 'bz2') {
- $v_buffered_lines = array();
- $v_buffered_lines[] = @bzread($v_temp_tar, 512);
-
- // ----- Read the following blocks but not the last one
- while (strlen($v_buffered_lines[]
- = @bzread($v_temp_tar, 512)) > 0) {
- $v_binary_data = pack("a512",
- array_shift($v_buffered_lines));
- $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
- // 512 bytes block
- if (!$this->_openReadWrite())
- return false;
-
- clearstatcache();
- $v_size = filesize($this->_tarname);
- 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)
- {
- 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:'');
- }
- }
- }
- $v_result = strtr($v_result, '\\', '/');
- return $v_result;
- }
-
- // }}}
-
- // {{{ _translateWinPath()
- function _translateWinPath($p_path, $p_remove_disk_letter=true)
- {
- if (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/inc/Console/Getopt.php b/inc/Console/Getopt.php
deleted file mode 100644
index 6f2f9c73079..00000000000
--- a/inc/Console/Getopt.php
+++ /dev/null
@@ -1,251 +0,0 @@
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Andrei Zmievski <andrei@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Getopt.php,v 1.21.4.7 2003/12/05 21:57:01 andrei Exp $
-
-oc_require_once( 'PEAR.php');
-
-/**
- * Command-line options parsing class.
- *
- * @author Andrei Zmievski <andrei@php.net>
- *
- */
-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/inc/HTTP/WebDAV/Server.php b/inc/HTTP/WebDAV/Server.php
deleted file mode 100644
index c407d74c89f..00000000000
--- a/inc/HTTP/WebDAV/Server.php
+++ /dev/null
@@ -1,2140 +0,0 @@
-<?php
-/*
- +----------------------------------------------------------------------+
- | Copyright (c) 2002-2007 Christian Stocker, Hartmut Holzgraefe |
- | 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. |
- | 3. The names of the authors may not be used to endorse or promote |
- | products derived from this software without specific prior |
- | written permission. |
- | |
- | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
- | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
- | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
- | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
- | COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
- | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
- | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
- | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
- | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
- | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN |
- | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
- | POSSIBILITY OF SUCH DAMAGE. |
- +----------------------------------------------------------------------+
-*/
-
-oc_require_once("HTTP/WebDAV/Tools/_parse_propfind.php");
-oc_require_once("HTTP/WebDAV/Tools/_parse_proppatch.php");
-oc_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 <hholzgra@php.net>
- * @version @package_version@
- */
-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";
-
- /**
- * Copy of $_SERVER superglobal array
- *
- * Derived classes may extend the constructor to
- * modify its contents
- *
- * @var array
- */
- var $_SERVER;
-
- // }}}
-
- // {{{ Constructor
-
- /**
- * Constructor
- *
- * @param void
- */
- function HTTP_WebDAV_Server()
- {
- // PHP messages destroy XML output -> switch them off
- ini_set("display_errors", 0);
-
- // copy $_SERVER variables to local _SERVER array
- // so that derived classes can simply modify these
- $this->_SERVER = $_SERVER;
- }
-
- // }}}
-
- // {{{ 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($this->_SERVER["REQUEST_URI"], '#')) {
- $this->http_status("400 Bad Request");
- return;
- }
-
- // default uri is the complete request uri
- $uri = "http";
- if (isset($this->_SERVER["HTTPS"]) && $this->_SERVER["HTTPS"] === "on") {
- $uri = "https";
- }
- $uri.= "://".$this->_SERVER["HTTP_HOST"].$this->_SERVER["SCRIPT_NAME"];
-
- // WebDAV has no concept of a query string and clients (including cadaver)
- // seem to pass '?' unencoded, so we need to extract the path info out
- // of the request URI ourselves
- $path_info = substr($this->_SERVER["REQUEST_URI"], strlen($this->_SERVER["SCRIPT_NAME"]));
-
- // just in case the path came in empty ...
- if (empty($path_info)) {
- $path_info = "/";
- }
-
- $this->base_uri = $uri;
- $this->uri = $uri . $path_info;
-
- // set path
- $this->path = $this->_urldecode($path_info);
- if (!strlen($this->path)) {
- if ($this->_SERVER["REQUEST_METHOD"] == "GET") {
- // redirect clients that try to GET a collection
- // WebDAV clients should never try this while
- // regular HTTP clients might ...
- 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 ( ( !(($this->_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($this->_SERVER["REQUEST_METHOD"]);
- error_log("serving $method request");
- $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 ($this->_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
- * <br>
- *
- *
- * @abstract
- * @param array &$params Array of input and output parameters
- * <br><b>input</b><ul>
- * <li> path -
- * </ul>
- * <br><b>output</b><ul>
- * <li> size -
- * </ul>
- * @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: headers
- * 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();
- $files = Array();
-
- $options["path"] = $this->path;
-
- // search depth from header (default is "infinity)
- if (isset($this->_SERVER['HTTP_DEPTH'])) {
- $options["depth"] = $this->_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)) {
- $files = array("files" => array());
- if (method_exists($this, "checkLock")) {
- // is locked?
- $lock = $this->checkLock($this->path);
-
- if (is_array($lock) && count($lock)) {
- $created = isset($lock['created']) ? $lock['created'] : time();
- $modified = isset($lock['modified']) ? $lock['modified'] : time();
- $files['files'][] = array("path" => $this->_slashify($this->path),
- "props" => array($this->mkprop("displayname", $this->path),
- $this->mkprop("creationdate", $created),
- $this->mkprop("getlastmodified", $modified),
- $this->mkprop("resourcetype", ""),
- $this->mkprop("getcontenttype", ""),
- $this->mkprop("getcontentlength", 0))
- );
- }
- }
-
- if (empty($files['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 (!isset($reqprop["xmlns"])) {
- $reqprop["xmlns"] = "";
- }
- 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;
-
- if (!isset($reqprop["xmlns"])) {
- $reqprop["xmlns"] = "";
- }
-
- // 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 "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
- echo "<D:multistatus xmlns:D=\"DAV:\">\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;
-
- echo " <D:response $ns_defs>\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->_mergePaths($this->_SERVER['SCRIPT_NAME'], $path);
-
- /* minimal urlencoding is needed for the resource path */
- $href = $this->_urlencode($href);
-
- echo " <D:href>$href</D:href>\n";
-
- // report all found properties and their values (if any)
- if (isset($file["props"]) && is_array($file["props"])) {
- echo " <D:propstat>\n";
- echo " <D:prop>\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 " <D:$prop[name]/>\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 " <D:creationdate ns0:dt=\"dateTime.tz\">"
- . gmdate("Y-m-d\\TH:i:s\\Z", $prop['val'])
- . "</D:creationdate>\n";
- break;
- case "getlastmodified":
- echo " <D:getlastmodified ns0:dt=\"dateTime.rfc1123\">"
- . gmdate("D, d M Y H:i:s ", $prop['val'])
- . "GMT</D:getlastmodified>\n";
- break;
- case "resourcetype":
- echo " <D:resourcetype><D:$prop[val]/></D:resourcetype>\n";
- break;
- case "supportedlock":
- echo " <D:supportedlock>$prop[val]</D:supportedlock>\n";
- break;
- case "lockdiscovery":
- echo " <D:lockdiscovery>\n";
- echo $prop["val"];
- echo " </D:lockdiscovery>\n";
- break;
- // the following are non-standard Microsoft extensions to the DAV namespace
- case "lastaccessed":
- echo " <D:lastaccessed ns0:dt=\"dateTime.rfc1123\">"
- . gmdate("D, d M Y H:i:s ", $prop['val'])
- . "GMT</D:lastaccessed>\n";
- break;
- case "ishidden":
- echo " <D:ishidden>"
- . is_string($prop['val']) ? $prop['val'] : ($prop['val'] ? 'true' : 'false')
- . "</D:ishidden>\n";
- break;
- default:
- echo " <D:$prop[name]>"
- . $this->_prop_encode(htmlspecialchars($prop['val']))
- . "</D:$prop[name]>\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']))
- . "</" . $ns_hash[$prop["ns"]] . ":$prop[name]>\n";
- } else {
- echo " <$prop[name] xmlns=\"\">"
- . $this->_prop_encode(htmlspecialchars($prop['val']))
- . "</$prop[name]>\n";
- }
- }
- }
-
- echo " </D:prop>\n";
- echo " <D:status>HTTP/1.1 200 OK</D:status>\n";
- echo " </D:propstat>\n";
- }
-
- // now report all properties requested but not found
- if (isset($file["noprops"])) {
- echo " <D:propstat>\n";
- echo " <D:prop>\n";
-
- foreach ($file["noprops"] as $key => $prop) {
- if ($prop["ns"] == "DAV:") {
- echo " <D:$prop[name]/>\n";
- } else if ($prop["ns"] == "") {
- echo " <$prop[name] xmlns=\"\"/>\n";
- } else {
- echo " <" . $ns_hash[$prop["ns"]] . ":$prop[name]/>\n";
- }
- }
-
- echo " </D:prop>\n";
- echo " <D:status>HTTP/1.1 404 Not Found</D:status>\n";
- echo " </D:propstat>\n";
- }
-
- echo " </D:response>\n";
- }
-
- echo "</D:multistatus>\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"');
-
- echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
-
- echo "<D:multistatus xmlns:D=\"DAV:\">\n";
- echo " <D:response>\n";
- echo " <D:href>".$this->_urlencode($this->_mergePaths($this->_SERVER["SCRIPT_NAME"], $this->path))."</D:href>\n";
-
- foreach ($options["props"] as $prop) {
- echo " <D:propstat>\n";
- echo " <D:prop><$prop[name] xmlns=\"$prop[ns]\"/></D:prop>\n";
- echo " <D:status>HTTP/1.1 $prop[status]</D:status>\n";
- echo " </D:propstat>\n";
- }
-
- if ($responsedescr) {
- echo " <D:responsedescription>".
- $this->_prop_encode(htmlspecialchars($responsedescr)).
- "</D:responsedescription>\n";
- }
-
- echo " </D:response>\n";
- echo "</D:multistatus>\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 -= $this->bytes($buffer);
- echo $buffer;
- }
- } else {
- $this->http_status("206 partial");
- if (isset($options['size'])) {
- header("Content-length: ".($options['size'] - $range['start']));
- header("Content-range: ".$range['start']."-".$range['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'], $from, SEEK_SET);
- while ($size && !feof($options['stream'])) {
- $buffer = fread($options['stream'], 4096);
- $size -= $this->bytes($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: ".$this->bytes($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 paths 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($this->_SERVER['HTTP_RANGE'])) {
-
- // we only support standard "bytes" range specifications for now
- if (preg_match('/bytes\s*=\s*(.+)/', $this->_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_".md5(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['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['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"] = $this->_SERVER["CONTENT_LENGTH"];
-
- // get the Content-type
- if (isset($this->_SERVER["CONTENT_TYPE"])) {
- // for now we do not support any sort of multipart requests
- if (!strncmp($this->_SERVER["CONTENT_TYPE"], "multipart/", 10)) {
- $this->http_status("501 not implemented");
- echo "The service does not support mulipart PUT requests";
- return;
- }
- $options["content_type"] = $this->_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 ($this->_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");
- 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"] = $val;
- break;
-
- case 'HTTP_CONTENT_LENGTH':
- // defined on IIS and has the same value as CONTENT_LENGTH
- 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_TYPE':
- // defined on IIS and has the same value as CONTENT_TYPE
- 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");
- 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($this->_SERVER["HTTP_DEPTH"])) {
- if ($this->_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($this->_SERVER['HTTP_DEPTH'])) {
- $options["depth"] = $this->_SERVER["HTTP_DEPTH"];
- } else {
- $options["depth"] = "infinity";
- }
-
- if (isset($this->_SERVER["HTTP_TIMEOUT"])) {
- $options["timeout"] = explode(",", $this->_SERVER["HTTP_TIMEOUT"]);
- }
-
- if (empty($this->_SERVER['CONTENT_LENGTH']) && !empty($this->_SERVER['HTTP_IF'])) {
- // check if locking is possible
- if (!$this->_check_lock_status($this->path)) {
- $this->http_status("423 Locked");
- return;
- }
-
- // refresh lock
- $options["locktoken"] = substr($this->_SERVER['HTTP_IF'], 2, -2);
- $options["update"] = $options["locktoken"];
-
- // setting defaults for required fields, LOCK() SHOULD overwrite these
- $options['owner'] = "unknown";
- $options['scope'] = "exclusive";
- $options['type'] = "write";
-
-
- $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 = (string)$stat;
- }
- $this->http_status($http_stat);
-
- if ($http_stat{0} == 2) { // 2xx states are ok
- if ($options["timeout"]) {
- // if multiple timeout values were given we take the first only
- if (is_array($options["timeout"])) {
- reset($options["timeout"]);
- $options["timeout"] = current($options["timeout"]);
- }
- // if the timeout is numeric only we need to reformat it
- if (is_numeric($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 {
- // non-numeric values are passed on verbatim,
- // no error checking is performed here in this case
- // TODO: send "Infinite" on invalid timeout strings?
- $timeout = $options["timeout"];
- }
- } else {
- $timeout = "Infinite";
- }
-
- header('Content-Type: text/xml; charset="utf-8"');
- header("Lock-Token: <$options[locktoken]>");
- echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n";
- echo "<D:prop xmlns:D=\"DAV:\">\n";
- echo " <D:lockdiscovery>\n";
- echo " <D:activelock>\n";
- echo " <D:lockscope><D:$options[scope]/></D:lockscope>\n";
- echo " <D:locktype><D:$options[type]/></D:locktype>\n";
- echo " <D:depth>$options[depth]</D:depth>\n";
- echo " <D:owner>$options[owner]</D:owner>\n";
- echo " <D:timeout>$timeout</D:timeout>\n";
- echo " <D:locktoken><D:href>$options[locktoken]</D:href></D:locktoken>\n";
- echo " </D:activelock>\n";
- echo " </D:lockdiscovery>\n";
- echo "</D:prop>\n\n";
- }
- }
-
-
- // }}}
-
- // {{{ http_UNLOCK()
-
- /**
- * UNLOCK method handler
- *
- * @param void
- * @return void
- */
- function http_UNLOCK()
- {
- $options = Array();
- $options["path"] = $this->path;
-
- if (isset($this->_SERVER['HTTP_DEPTH'])) {
- $options["depth"] = $this->_SERVER["HTTP_DEPTH"];
- } else {
- $options["depth"] = "infinity";
- }
-
- // strip surrounding <>
- $options["token"] = substr(trim($this->_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($this->_SERVER["HTTP_DEPTH"])) {
- $options["depth"] = $this->_SERVER["HTTP_DEPTH"];
- } else {
- $options["depth"] = "infinity";
- }
-
- $http_header_host = preg_replace("/:80$/", "", $this->_SERVER["HTTP_HOST"]);
-
- $url = parse_url($this->_SERVER["HTTP_DESTINATION"]);
- $path = urldecode($url["path"]);
-
- if (isset($url["host"])) {
- // TODO check url scheme, too
- $http_host = $url["host"];
- if (isset($url["port"]) && $url["port"] != 80)
- $http_host.= ":".$url["port"];
- } else {
- // only path given, set host to self
- $http_host == $http_header_host;
- }
-
- if ($http_host == $http_header_host &&
- !strncmp($this->_SERVER["SCRIPT_NAME"], $path,
- strlen($this->_SERVER["SCRIPT_NAME"]))) {
- $options["dest"] = substr($path, strlen($this->_SERVER["SCRIPT_NAME"]));
- if (!$this->_check_lock_status($options["dest"])) {
- $this->http_status("423 Locked");
- return;
- }
-
- } else {
- $options["dest_url"] = $this->_SERVER["HTTP_DESTINATION"];
- }
-
- // see RFC 2518 Sections 9.6, 8.8.4 and 8.9.3
- if (isset($this->_SERVER["HTTP_OVERWRITE"])) {
- $options["overwrite"] = $this->_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()
- {
- $auth_type = isset($this->_SERVER["AUTH_TYPE"])
- ? $this->_SERVER["AUTH_TYPE"]
- : null;
-
- $auth_user = isset($this->_SERVER["PHP_AUTH_USER"])
- ? $this->_SERVER["PHP_AUTH_USER"]
- : null;
-
- $auth_pw = isset($this->_SERVER["PHP_AUTH_PW"])
- ? $this->_SERVER["PHP_AUTH_PW"]
- : null;
-
- if (method_exists($this, "checkAuth")) {
- // PEAR style method name
- return $this->checkAuth($auth_type, $auth_user, $auth_pw);
- } else if (method_exists($this, "check_auth")) {
- // old (pre 1.0) method name
- return $this->check_auth($auth_type, $auth_user, $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 = md5(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 (isset($uris[$uri]) && 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($this->_SERVER["HTTP_IF"])) {
- $this->_if_header_uris =
- $this->_if_header_parser($this->_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, "<opaquelocktoken:", strlen("<opaquelocktoken"))) {
- if (!preg_match('/^<opaquelocktoken:[[:xdigit:]]{8}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{4}-[[:xdigit:]]{12}>$/', $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
-
- // a lock token can never be from the DAV: scheme
- // litmus uses DAV:no-lock in some tests
- if (!strncmp("<DAV:", $condition, 5)) {
- return false;
- }
-
- 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($this->_SERVER["HTTP_IF"]) || !strstr($this->_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 <activelock> 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.= "
- <D:activelock>
- <D:lockscope><D:$lock[scope]/></D:lockscope>
- <D:locktype><D:$lock[type]/></D:locktype>
- <D:depth>$lock[depth]</D:depth>
- <D:owner>$lock[owner]</D:owner>
- <D:timeout>$timeout</D:timeout>
- <D:locktoken><D:href>$lock[token]</D:href></D:locktoken>
- </D:activelock>
- ";
- }
-
- // 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, percent 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",
- "%"=>"%25",
- "&"=>"%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 rawurldecode($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) -1);
- }
- return $path;
- }
-
- /**
- * Merge two paths, make sure there is exactly one slash between them
- *
- * @param string parent path
- * @param string child path
- * @return string merged path
- */
- function _mergePaths($parent, $child)
- {
- if ($child{0} == '/') {
- return $this->_unslashify($parent).$child;
- } else {
- return $this->_slashify($parent).$child;
- }
- }
-
- /**
- * mbstring.func_overload save strlen version: counting the bytes not the chars
- *
- * @param string $str
- * @return int
- */
- function bytes($str)
- {
- static $func_overload;
-
- if (is_null($func_overload))
- {
- $func_overload = @extension_loaded('mbstring') ? ini_get('mbstring.func_overload') : 0;
- }
- return $func_overload & 2 ? mb_strlen($str,'ascii') : strlen($str);
- }
-}
-?>
diff --git a/inc/HTTP/WebDAV/Server/Filesystem.php b/inc/HTTP/WebDAV/Server/Filesystem.php
deleted file mode 100644
index 30c19fd29a6..00000000000
--- a/inc/HTTP/WebDAV/Server/Filesystem.php
+++ /dev/null
@@ -1,760 +0,0 @@
-<?php
-/*
- +----------------------------------------------------------------------+
- | Copyright (c) 2002-2007 Christian Stocker, Hartmut Holzgraefe |
- | 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. |
- | 3. The names of the authors may not be used to endorse or promote |
- | products derived from this software without specific prior |
- | written permission. |
- | |
- | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
- | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
- | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
- | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
- | COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
- | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
- | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
- | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
- | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
- | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN |
- | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
- | POSSIBILITY OF SUCH DAMAGE. |
- +----------------------------------------------------------------------+
- --- modified for ownCloud ---
-*/
- require_once("../inc/lib_base.php");
- oc_require_once("HTTP/WebDAV/Server.php");
- oc_require_once("System.php");
-
- /**
- * Filesystem access using WebDAV
- *
- * @access public
- * @author Hartmut Holzgraefe <hartmut@php.net>
- * @version @package-version@
- */
- class HTTP_WebDAV_Server_Filesystem extends HTTP_WebDAV_Server
- {
- /**
- * Root directory for WebDAV access
- *
- * Defaults to webserver document root (set by ServeRequest)
- *
- * @access private
- * @var string
- */
- var $base = "";
-
- /**
- * Serve a webdav request
- *
- * @access public
- * @param string
- */
- function ServeRequest($base = false)
- {
- // special treatment for litmus compliance test
- // reply on its identifier header
- // not needed for the test itself but eases debugging
- if (isset($this->_SERVER['HTTP_X_LITMUS'])) {
- error_log("Litmus test ".$this->_SERVER['HTTP_X_LITMUS']);
- header("X-Litmus-reply: ".$this->_SERVER['HTTP_X_LITMUS']);
- }
-
- // 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 = $this->_SERVER['DOCUMENT_ROOT'];
- }
-
- // 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 = $options["path"];
-
- // sanity check
- if (!OC_FILESYSTEM::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"]) && OC_FILESYSTEM::is_dir($fspath) && OC_FILESYSTEM::is_readable($fspath)) {
- // make sure path ends with '/'
- $options["path"] = $this->_slashify($options["path"]);
-
- // try to open directory
- $handle = @OC_FILESYSTEM::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)
- {
- global $CONFIG_DBTABLEPREFIX;
-
- // map URI path to filesystem path
- $fspath =$path;
-
- // create result array
- $info = array();
- // TODO remove slash append code when base clase is able to do it itself
- $info["path"] = OC_FILESYSTEM::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", OC_FILESYSTEM::filectime($fspath));
- $info["props"][] = $this->mkprop("getlastmodified", OC_FILESYSTEM::filemtime($fspath));
- // Microsoft extensions: last access time and 'hidden' status
- $info["props"][] = $this->mkprop("lastaccessed", OC_FILESYSTEM::fileatime($fspath));
- $info["props"][] = $this->mkprop("ishidden", ('.' === substr(basename($fspath), 0, 1)));
- // type and size (caller already made sure that path exists)
- if ( OC_FILESYSTEM::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 ( OC_FILESYSTEM::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", OC_FILESYSTEM::filesize($fspath));
- }
- // get additional properties from database
- $query = "SELECT ns, name, value FROM {$CONFIG_DBTABLEPREFIX}properties WHERE path = '$path'";
- $res = OC_DB::select($query);
- foreach($res as $row){
- $info["props"][] = $this->mkprop($row["ns"], $row["name"], $row["value"]);
- }
- return $info;
- }
-
- /**
- * try to detect the mime type of a file
- *
- * @param string file path
- * @return string guessed mime type
- */
- function _mimetype($fspath)
- {
- return OC_FILESYSTEM::getMimeType($fspath);
- }
-
- /**
- * HEAD method handler
- *
- * @param array parameter passing array
- * @return bool true on success
- */
- function HEAD(&$options)
- {
- // get absolute fs path to requested resource
- $fspath = $options["path"];
-
- // sanity check
- if (! OC_FILESYSTEM::file_exists($fspath)) return false;
-
- // 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'] = OC_FILESYSTEM::filemtime($fspath);
-
- // detect resource size
- $options['size'] = OC_FILESYSTEM::filesize($fspath);
-
- return true;
- }
-
- /**
- * GET method handler
- *
- * @param array parameter passing array
- * @return bool true on success
- */
- function GET(&$options)
- {
- // get absolute fs path to requested resource)
- $fspath = $options["path"];
- // is this a collection?
- if (OC_FILESYSTEM::is_dir($fspath)) {
- return $this->GetDir($fspath, $options);
- }
-
- // the header output is the same as for HEAD
- if (!$this->HEAD($options)) {
- return false;
- }
-
- // no need to check result here, it is handled by the base class
- $options['stream'] = OC_FILESYSTEM::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";
-
- if (!OC_FILESYSTEM::is_readable($fspath)) {
- return false;
- }
-
- $handle = OC_FILESYSTEM::opendir($fspath);
- if (!$handle) {
- return false;
- }
-
- echo "<html><head><title>Index of ".htmlspecialchars($options['path'])."</title></head>\n";
-
- echo "<h1>Index of ".htmlspecialchars($options['path'])."</h1>\n";
-
- echo "<pre>";
- printf($format, "Size", "Last modified", "Filename");
- echo "<hr>";
-
- 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)),
- "<a href='$name'>$name</a>");
- }
- }
-
- echo "</pre>";
-
- closedir($handle);
-
- echo "</html>\n";
-
- exit;
- }
-
- /**
- * PUT method handler
- *
- * @param array parameter passing array
- * @return bool true on success
- */
- function PUT(&$options)
- {
- $fspath = $options["path"];
- $dir = dirname($fspath);
- if (!OC_FILESYSTEM::file_exists($dir) || !OC_FILESYSTEM::is_dir($dir)) {
- return "409 Conflict"; // TODO right status code for both?
- }
-
- $options["new"] = ! OC_FILESYSTEM::file_exists($fspath);
-
- if ($options["new"] && !OC_FILESYSTEM::is_writeable($dir)) {
- return "403 Forbidden";
- }
- if (!$options["new"] && !OC_FILESYSTEM::is_writeable($fspath)) {
- return "403 Forbidden";
- }
- if (!$options["new"] && OC_FILESYSTEM::is_dir($fspath)) {
- return "403 Forbidden";
- }
- $fp = OC_FILESYSTEM::fopen($fspath, "w");
-
- return $fp;
- }
-
-
- /**
- * MKCOL method handler
- *
- * @param array general parameter passing array
- * @return bool true on success
- */
- function MKCOL($options)
- {
- $path = $options["path"];
- $parent = dirname($path);
- $name = basename($path);
- if (!OC_FILESYSTEM::file_exists($parent)) {
- return "409 Conflict";
- }
-
- if (!OC_FILESYSTEM::is_dir($parent)) {
- return "403 Forbidden";
- }
-
- if ( OC_FILESYSTEM::file_exists($parent."/".$name) ) {
- return "405 Method not allowed";
- }
-
- if (!empty($this->_SERVER["CONTENT_LENGTH"])) { // no body parsing yet
- return "415 Unsupported media type";
- }
-
- $stat = OC_FILESYSTEM::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)
- {
- global $CONFIG_DBTABLEPREFIX;
- $path =$options["path"];
- if (!OC_FILESYSTEM::file_exists($path)) {
- return "404 Not found";
- }
- $lock=self::checkLock($path);
- if(is_array($lock)){
- $owner=$options['owner'];
- $lockOwner=$lock['owner'];
- if($owner==$lockOwner){
- return "423 Locked";
- }
- }
- if (OC_FILESYSTEM::is_dir($path)) {
- $query = "DELETE FROM {$CONFIG_DBTABLEPREFIX}properties WHERE path LIKE '".$this->_slashify($options["path"])."%'";
- OC_DB::query($query);
- OC_FILESYSTEM::delTree($path);
- } else {
- OC_FILESYSTEM::unlink($path);
- }
- $query = "DELETE FROM {$CONFIG_DBTABLEPREFIX}properties WHERE path = '$options[path]'";
- OC_DB::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?)
- global $CONFIG_DBTABLEPREFIX;
-
- if (!empty($this->_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 = $options["path"];
- if (!OC_FILESYSTEM::file_exists($source)) {
- return "404 Not found";
- }
-
- if (OC_FILESYSTEM::is_dir($source)) { // resource is a collection
- switch ($options["depth"]) {
- case "infinity": // valid
- break;
- case "0": // valid for COPY only
- if ($del) { // MOVE?
- return "400 Bad request";
- }
- break;
- case "1": // invalid for both COPY and MOVE
- default:
- return "400 Bad request";
- }
- }
-
- $dest = $options["dest"];
- $destdir = dirname($dest);
-
- if (!OC_FILESYSTEM::file_exists($destdir) || !OC_FILESYSTEM::is_dir($destdir)) {
- return "409 Conflict";
- }
-
-
- $new = !OC_FILESYSTEM::file_exists($dest);
- $existing_col = false;
-
- if (!$new) {
- if ($del && OC_FILESYSTEM::is_dir($dest)) {
- if (!$options["overwrite"]) {
- return "412 precondition failed";
- }
- $dest .= basename($source);
- if (OC_FILESYSTEM::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 ($del) {
- if (!OC_FILESYSTEM::rename($source, $dest)) {
- return "500 Internal server error";
- }
- $destpath = $this->_unslashify($options["dest"]);
- if (is_dir($source)) {
- $dpath=OC_DB::escape($destpath);
- $path=OC_DB::escape($options["path"]);
- $query = "UPDATE {$CONFIG_DBTABLEPREFIX}properties
- SET path = REPLACE(path, '$path', '$dpath')
- WHERE path LIKE '$path%'";
- OC_DB::query($query);
- }
-
- $query = "UPDATE {$CONFIG_DBTABLEPREFIX}properties
- SET path = '$dpath'
- WHERE path = '$path'";
- OC_DB::query($query);
- } else {
- if (OC_FILESYSTEM::is_dir($source)) {
- $files = OC_FILESYSTEM::getTree($source);
- } else {
- $files = array($source);
- }
-
- if (!is_array($files) || empty($files)) {
- return "500 Internal server error";
- }
-
-
- foreach ($files as $file) {
- if (OC_FILESYSTEM::is_dir($file)) {
- $file = $this->_slashify($file);
- }
- $destfile = str_replace($source, $dest, $file);
-
- if (OC_FILESYSTEM::is_dir($file)) {
- if (!OC_FILESYSTEM::file_exists($destfile)) {
- if (!OC_FILESYSTEM::is_writeable(dirname($destfile))) {
- return "403 Forbidden";
- }
- if (!OC_FILESYSTEM::mkdir($destfile)) {
- return "409 Conflict";
- }
- } else if (!OC_FILESYSTEM::is_dir($destfile)) {
- return "409 Conflict";
- }
- } else {
- if (!OC_FILESYSTEM::copy($file, $destfile)) {
- return "409 Conflict($source) $file --> $destfile ".implode('::',$files);
- }
- }
- }
- }
- return ($new && !$existing_col) ? "201 Created" : "204 No Content";
- }
-
- /**
- * PROPPATCH method handler
- *
- * @param array general parameter passing array
- * @return bool true on success
- */
- function PROPPATCH(&$options)
- {
- global $prefs, $tab;
- global $CONFIG_DBTABLEPREFIX;
-
- $msg = "";
- $path = $options["path"];
- $dir = dirname($path)."/";
- $base = basename($path);
-
- foreach ($options["props"] as $key => $prop) {
- if ($prop["ns"] == "DAV:") {
- $options["props"][$key]['status'] = "403 Forbidden";
- } else {
- $path=OC_DB::escape($options['path']);
- $name=OC_DB::escape($prop['name']);
- $ns=OC_DB::escape($prop['ns']);
- $val=OC_DB::escape($prop['val']);
- if (isset($prop["val"])) {
- $query = "REPLACE INTO {$CONFIG_DBTABLEPREFIX}properties (path,name,ns,value) VALUES('$path','$name','$ns','$val')";
- } else {
- $query = "DELETE FROM {$CONFIG_DBTABLEPREFIX}properties WHERE path = '$path' AND name = '$name' AND ns = '$ns'";
- }
- OC_DB::query($query);
- }
- }
-
- return "";
- }
-
-
- /**
- * LOCK method handler
- *
- * @param array general parameter passing array
- * @return bool true on success
- */
- function LOCK(&$options)
- {
- global $CONFIG_DBTABLEPREFIX;
-
- // get absolute fs path to requested resource
- $fspath = $options["path"];
- // TODO recursive locks on directories not supported yet
- // makes litmus test "32. lock_collection" fail
- if (OC_FILESYSTEM::is_dir($fspath) && !empty($options["depth"])) {
- switch($options["depth"]){
- case 'infinity':
- $recursion=1;
- break;
- case '0':
- $recursion=0;
- break;
- }
- }else{
- $recursion=0;
- }
-
- $options["timeout"] = time()+300; // 5min. hardcoded
-
- if (isset($options["update"])) { // Lock Update
- $where = "WHERE path = '$options[path]' AND token = '$options[update]'";
-
- $query = "SELECT owner, exclusivelock FROM {$CONFIG_DBTABLEPREFIX}locks $where";
- $res = OC_DB::select($query);
-
- if (is_array($res) and isset($res[0])) {
- $row=$res[0];
- $query = "UPDATE `{$CONFIG_DBTABLEPREFIX}locks` SET `expires` = '$options[timeout]', `modified` = ".time()." $where";
- OC_DB::query($query);
-
- $options['owner'] = $row['owner'];
- $options['scope'] = $row["exclusivelock"] ? "exclusive" : "shared";
- $options['type'] = $row["exclusivelock"] ? "write" : "read";
-
- return true;
- } else {//check for indirect refresh
- $query = "SELECT *
- FROM {$CONFIG_DBTABLEPREFIX}locks
- WHERE recursive = 1
- ";
- $res = OC_DB::select($query);
- foreach($res as $row){
- if(strpos($options['path'],$row['path'])==0){//are we a child of a folder with an recursive lock
- $where = "WHERE path = '$row[path]' AND token = '$options[update]'";
- $query = "UPDATE `{$CONFIG_DBTABLEPREFIX}locks` SET `expires` = '$options[timeout]', `modified` = ".time()." $where";
- OC_DB::query($query);
- $options['owner'] = $row['owner'];
- $options['scope'] = $row["exclusivelock"] ? "exclusive" : "shared";
- $options['type'] = $row["exclusivelock"] ? "write" : "read";
- return true;
- }
- }
- }
- }
-
- $locktoken=OC_DB::escape($options['locktoken']);
- $path=OC_DB::escape($options['path']);
- $time=time();
- $owner=OC_DB::escape($options['owner']);
- $timeout=OC_DB::escape($options['timeout']);
- $exclusive=($options['scope'] === "exclusive" ? "1" : "0");
- $query = "INSERT INTO `{$CONFIG_DBTABLEPREFIX}locks`
-(`token`,`path`,`created`,`modified`,`owner`,`expires`,`exclusivelock`,`recursive`)
-VALUES ('$locktoken','$path',$time,$time,'$owner','timeout',$exclusive,$recursion)";
- OC_DB::query($query);
- $rows=OC_DB::affected_rows();
- if(!OC_FILESYSTEM::file_exists($fspath) and $rows>0) {
- return "201 Created";
- }
- return OC_DB::affected_rows($rows) ? "200 OK" : "409 Conflict";
- }
-
- /**
- * UNLOCK method handler
- *
- * @param array general parameter passing array
- * @return bool true on success
- */
- function UNLOCK(&$options)
- {
- global $CONFIG_DBTABLEPREFIX;
- $query = "DELETE FROM {$CONFIG_DBTABLEPREFIX}locks
- WHERE path = '$options[path]'
- AND token = '$options[token]'";
- OC_DB::query($query);
-
- return OC_DB::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)
- {
- global $CONFIG_DBTABLEPREFIX;
-
- $result = false;
- $query = "SELECT *
- FROM {$CONFIG_DBTABLEPREFIX}locks
- WHERE path = '$path'
- ";
- $res = OC_DB::select($query);
- if (is_array($res) and isset($res[0])) {
- $row=$res[0];
-
- if ($row) {
- $result = array( "type" => "write",
- "scope" => $row["exclusivelock"] ? "exclusive" : "shared",
- "depth" => 0,
- "owner" => $row['owner'],
- "token" => $row['token'],
- "created" => $row['created'],
- "modified" => $row['modified'],
- "expires" => $row['expires'],
- "recursive" => $row['recursive']
- );
- }
- }else{
- //check for recursive locks;
- $query = "SELECT *
- FROM {$CONFIG_DBTABLEPREFIX}locks
- WHERE recursive = 1
- ";
- $res = OC_DB::select($query);
- foreach($res as $row){
- if(strpos($path,$row['path'])==0){//are we a child of a folder with an recursive lock
- $result = array( "type" => "write",
- "scope" => $row["exclusivelock"] ? "exclusive" : "shared",
- "depth" => 0,
- "owner" => $row['owner'],
- "token" => $row['token'],
- "created" => $row['created'],
- "modified" => $row['modified'],
- "expires" => $row['expires'],
- "recursive" => $row['recursive']
- );
- }
- }
- }
-
- return $result;
- }
-}
-
-?> \ No newline at end of file
diff --git a/inc/HTTP/WebDAV/Tools/_parse_lockinfo.php b/inc/HTTP/WebDAV/Tools/_parse_lockinfo.php
deleted file mode 100644
index 6319f0d5200..00000000000
--- a/inc/HTTP/WebDAV/Tools/_parse_lockinfo.php
+++ /dev/null
@@ -1,251 +0,0 @@
-<?php // $Id$
-/*
- +----------------------------------------------------------------------+
- | Copyright (c) 2002-2007 Christian Stocker, Hartmut Holzgraefe |
- | 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. |
- | 3. The names of the authors may not be used to endorse or promote |
- | products derived from this software without specific prior |
- | written permission. |
- | |
- | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
- | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
- | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
- | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
- | COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
- | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
- | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
- | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
- | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
- | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN |
- | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
- | POSSIBILITY OF SUCH DAMAGE. |
- +----------------------------------------------------------------------+
-*/
-
-
-/**
- * helper class for parsing LOCK request bodies
- *
- * @package HTTP_WebDAV_Server
- * @author Hartmut Holzgraefe <hholzgra@php.net>
- * @version @package-version@
- */
-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 <owner> 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 <owner> 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;
- }
-
- // <owner> finished?
- if (($ns == "DAV:") && ($tag == "owner")) {
- $this->collect_owner = false;
- }
-
- // within <owner> 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 .= "</$ns_short$tag$ns_attr>";
- }
- }
-}
-
-?>
diff --git a/inc/HTTP/WebDAV/Tools/_parse_propfind.php b/inc/HTTP/WebDAV/Tools/_parse_propfind.php
deleted file mode 100644
index cf72b529d97..00000000000
--- a/inc/HTTP/WebDAV/Tools/_parse_propfind.php
+++ /dev/null
@@ -1,191 +0,0 @@
-<?php // $Id$
-/*
- +----------------------------------------------------------------------+
- | Copyright (c) 2002-2007 Christian Stocker, Hartmut Holzgraefe |
- | 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. |
- | 3. The names of the authors may not be used to endorse or promote |
- | products derived from this software without specific prior |
- | written permission. |
- | |
- | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
- | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
- | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
- | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
- | COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
- | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
- | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
- | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
- | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
- | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN |
- | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
- | POSSIBILITY OF SUCH DAMAGE. |
- +----------------------------------------------------------------------+
-*/
-
-/**
- * helper class for parsing PROPFIND request bodies
- *
- * @package HTTP_WebDAV_Server
- * @author Hartmut Holzgraefe <hholzgra@php.net>
- * @version @package-version@
- */
-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: <allprop> and <propname>
- 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--;
- }
-}
-
-
-?>
diff --git a/inc/HTTP/WebDAV/Tools/_parse_proppatch.php b/inc/HTTP/WebDAV/Tools/_parse_proppatch.php
deleted file mode 100644
index fb0e595ddf7..00000000000
--- a/inc/HTTP/WebDAV/Tools/_parse_proppatch.php
+++ /dev/null
@@ -1,237 +0,0 @@
-<?php // $Id$
-/*
- +----------------------------------------------------------------------+
- | Copyright (c) 2002-2007 Christian Stocker, Hartmut Holzgraefe |
- | 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. |
- | 3. The names of the authors may not be used to endorse or promote |
- | products derived from this software without specific prior |
- | written permission. |
- | |
- | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
- | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
- | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
- | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
- | COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
- | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
- | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; |
- | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER |
- | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
- | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN |
- | ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
- | POSSIBILITY OF SUCH DAMAGE. |
- +----------------------------------------------------------------------+
-*/
-
-
-/**
- * helper class for parsing PROPPATCH request bodies
- *
- * @package HTTP_WebDAV_Server
- * @author Hartmut Holzgraefe <hholzgra@php.net>
- * @version @package-version@
- */
-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";
- if (isset($attr)) {
- foreach ($attr as $key => $val) {
- $this->current["val"] .= ' '.$key.'="'.str_replace('"','&quot;', $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"] .= "</$tag>";
- }
-
- 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;
- }
- }
-}
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * indent-tabs-mode:nil
- * End:
- */
diff --git a/inc/Log.php b/inc/Log.php
deleted file mode 100644
index 8f084640bc9..00000000000
--- a/inc/Log.php
+++ /dev/null
@@ -1,635 +0,0 @@
-<?php
-/**
- * $Header: /repository/pear/Log/Log.php,v 1.46 2004/09/09 02:42:22 jon Exp $
- * $Horde: horde/lib/Log.php,v 1.15 2000/06/29 23:39:45 jon Exp $
- *
- * @version $Revision: 1.46 $
- * @package Log
- */
-
-define('PEAR_LOG_EMERG', 0); /** System is unusable */
-define('PEAR_LOG_ALERT', 1); /** Immediate action required */
-define('PEAR_LOG_CRIT', 2); /** Critical conditions */
-define('PEAR_LOG_ERR', 3); /** Error conditions */
-define('PEAR_LOG_WARNING', 4); /** Warning conditions */
-define('PEAR_LOG_NOTICE', 5); /** Normal but significant */
-define('PEAR_LOG_INFO', 6); /** Informational */
-define('PEAR_LOG_DEBUG', 7); /** Debug-level messages */
-
-define('PEAR_LOG_ALL', bindec('11111111')); /** All messages */
-define('PEAR_LOG_NONE', bindec('00000000')); /** No message */
-
-/* Log types for PHP's native error_log() function. */
-define('PEAR_LOG_TYPE_SYSTEM', 0); /** Use PHP's system logger */
-define('PEAR_LOG_TYPE_MAIL', 1); /** Use PHP's mail() function */
-define('PEAR_LOG_TYPE_DEBUG', 2); /** Use PHP's debugging connection */
-define('PEAR_LOG_TYPE_FILE', 3); /** Append to a file */
-
-/**
- * The Log:: class implements both an abstraction for various logging
- * mechanisms and the Subject end of a Subject-Observer pattern.
- *
- * @author Chuck Hagenbuch <chuck@horde.org>
- * @author Jon Parise <jon@php.net>
- * @since Horde 1.3
- * @package Log
- */
-class Log
-{
- /**
- * Indicates whether or not the log can been opened / connected.
- *
- * @var boolean
- * @access private
- */
- var $_opened = false;
-
- /**
- * Instance-specific unique identification number.
- *
- * @var integer
- * @access private
- */
- var $_id = 0;
-
- /**
- * The label that uniquely identifies this set of log messages.
- *
- * @var string
- * @access private
- */
- var $_ident = '';
-
- /**
- * The default priority to use when logging an event.
- *
- * @var integer
- * @access private
- */
- var $_priority = PEAR_LOG_INFO;
-
- /**
- * The bitmask of allowed log levels.
- * @var integer
- * @access private
- */
- var $_mask = PEAR_LOG_ALL;
-
- /**
- * Holds all Log_observer objects that wish to be notified of new messages.
- *
- * @var array
- * @access private
- */
- var $_listeners = array();
-
-
- /**
- * 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 an
- * false 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.
- */
- @include_once $classfile;
-
- /* If the class exists, return a new instance of it. */
- if (class_exists($class)) {
- return new $class($name, $ident, $conf, $level);
- }
-
- return false;
- }
-
- /**
- * 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.
- *
- * <b>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.</b>
- *
- * @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 an
- * false 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 private
- */
- 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')) {
- $message = (string)$message;
- } 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;
- }
-
- /**
- * 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.
- *
- * @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 $levels[$priority];
- }
-
- /**
- * Calculate the log mask for the given priority.
- *
- * @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.
- *
- * @param integer $priority The maximum priority covered by this mask.
- *
- * @return integer The calculated log mask.
- *
- * @access public
- * @since Log 1.7.0
- */
- function UPTO($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 private
- * @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 private
- */
- 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/inc/Log/composite.php b/inc/Log/composite.php
deleted file mode 100644
index 104c8966c42..00000000000
--- a/inc/Log/composite.php
+++ /dev/null
@@ -1,196 +0,0 @@
-<?php
-/**
- * $Header: /repository/pear/Log/Log/composite.php,v 1.23 2004/08/09 06:04:11 jon Exp $
- * $Horde: horde/lib/Log/composite.php,v 1.2 2000/06/28 21:36:13 jon Exp $
- *
- * @version $Revision: 1.23 $
- * @package Log
- */
-
-/**
- * The Log_composite:: class implements a Composite pattern which
- * allows multiple Log implementations to receive the same events.
- *
- * @author Chuck Hagenbuch <chuck@horde.org>
- * @author Jon Parise <jon@php.net>
- *
- * @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 = false, $ident = false, $conf = false,
- $level = PEAR_LOG_DEBUG)
- {
- }
-
- /**
- * Opens the child connections.
- *
- * @access public
- */
- function open()
- {
- if (!$this->_opened) {
- foreach ($this->_children as $id => $child) {
- $this->_children[$id]->open();
- }
- $this->_opened = true;
- }
- }
-
- /**
- * Closes any child instances.
- *
- * @access public
- */
- function close()
- {
- if ($this->_opened) {
- foreach ($this->_children as $id => $child) {
- $this->_children[$id]->close();
- }
- $this->_opened = false;
- }
- }
-
- /**
- * Flushes all open child instances.
- *
- * @access public
- * @since Log 1.8.2
- */
- function flush()
- {
- if ($this->_opened) {
- foreach ($this->_children as $id => $child) {
- $this->_children[$id]->flush();
- }
- }
- }
-
- /**
- * Sends $message and $priority to each child of this composite.
- *
- * @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;
- }
-
- foreach ($this->_children as $id => $child) {
- $this->_children[$id]->log($message, $priority);
- }
-
- $this->_announce(array('priority' => $priority, 'message' => $message));
-
- return true;
- }
-
- /**
- * 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)
- {
- 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/inc/Log/console.php b/inc/Log/console.php
deleted file mode 100644
index 62032e79644..00000000000
--- a/inc/Log/console.php
+++ /dev/null
@@ -1,190 +0,0 @@
-<?php
-/**
- * $Header: /repository/pear/Log/Log/console.php,v 1.19 2004/01/19 08:02:40 jon Exp $
- *
- * @version $Revision: 1.19 $
- * @package Log
- */
-
-/**
- * The Log_console class is a concrete implementation of the Log::
- * abstract class which writes message to the text console.
- *
- * @author Jon Parise <jon@php.net>
- * @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';
-
- /**
- * Hash that maps canonical format keys to position arguments for the
- * "line format" string.
- * @var array
- * @access private
- */
- var $_formatMap = array('%{timestamp}' => '%1$s',
- '%{ident}' => '%2$s',
- '%{priority}' => '%3$s',
- '%{message}' => '%4$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)
- {
- $this->_id = md5(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->flush();
- }
-
- /**
- * 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 = '';
- }
-
- return fflush($this->_stream);
- }
-
- /**
- * 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 = sprintf($this->_lineFormat, strftime($this->_timeFormat),
- $this->_ident, $this->priorityToString($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/inc/Log/daemon.php b/inc/Log/daemon.php
deleted file mode 100644
index 739270c9a32..00000000000
--- a/inc/Log/daemon.php
+++ /dev/null
@@ -1,229 +0,0 @@
-<?php
-// $Id: daemon.php,v 1.1 2004/12/21 06:55:38 jon Exp $
-
-/**
- * The Log_daemon class is a concrete implementation of the Log::
- * abstract class which sends messages to syslog daemon on UNIX-like machines.
- * This class uses the syslog protocol: http://www.ietf.org/rfc/rfc3164.txt
- *
- * @author Bart van der Schans <schans@dds.nl>
- * @version $Revision: 1.1 $
- * @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;
- }
-
- $this->_id = md5(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/inc/Log/display.php b/inc/Log/display.php
deleted file mode 100644
index 0d5a93d79da..00000000000
--- a/inc/Log/display.php
+++ /dev/null
@@ -1,108 +0,0 @@
-<?php
-/**
- * $Header: /repository/pear/Log/Log/display.php,v 1.6 2004/11/27 21:46:50 jon Exp $
- *
- * @version $Revision: 1.6 $
- * @package Log
- */
-
-/**
- * The Log_display class is a concrete implementation of the Log::
- * abstract class which writes message into browser in usual PHP maner.
- * This may be useful because when you use PEAR::setErrorHandling in
- * PEAR_ERROR_CALLBACK mode error messages are not displayed by
- * PHP error handler.
- *
- * @author Paul Yanchenko <pusher@inaco.ru>
- * @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 = '';
-
-
- /**
- * 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)
- {
- $this->_id = md5(microtime());
- $this->_ident = $ident;
- $this->_mask = Log::UPTO($level);
-
- if (!empty($conf['error_prepend'])) {
- $this->_error_prepend = $conf['error_prepend'];
- } else {
- $this->_error_prepend = ini_get('error_prepend_string');
- }
-
- if (!empty($conf['error_append'])) {
- $this->_error_append = $conf['error_append'];
- } else {
- $this->_error_append = ini_get('error_append_string');
- }
- }
-
- /**
- * 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. */
- echo $this->_error_prepend .
- '<b>' . ucfirst($this->priorityToString($priority)) . '</b>: '.
- nl2br(htmlspecialchars($message)) .
- $this->_error_append . "<br />\n";
-
- /* Notify observers about this log message. */
- $this->_announce(array('priority' => $priority, 'message' => $message));
-
- return true;
- }
-}
-
-?>
diff --git a/inc/Log/error_log.php b/inc/Log/error_log.php
deleted file mode 100644
index 04c0952cd7a..00000000000
--- a/inc/Log/error_log.php
+++ /dev/null
@@ -1,104 +0,0 @@
-<?php
-/**
- * $Header: /repository/pear/Log/Log/error_log.php,v 1.6 2004/01/19 08:02:40 jon Exp $
- *
- * @version $Revision: 1.6 $
- * @package Log
- */
-
-/**
- * The Log_error_log class is a concrete implementation of the Log abstract
- * class that logs messages using PHP's error_log() function.
- *
- * @author Jon Parise <jon@php.net>
- * @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)
- {
- $this->_id = md5(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'];
- }
- }
-
- /**
- * 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/inc/Log/file.php b/inc/Log/file.php
deleted file mode 100644
index 36f30b42978..00000000000
--- a/inc/Log/file.php
+++ /dev/null
@@ -1,286 +0,0 @@
-<?php
-/**
- * $Header: /repository/pear/Log/Log/file.php,v 1.37 2004/01/19 08:02:40 jon Exp $
- *
- * @version $Revision: 1.37 $
- * @package Log
- */
-
-/**
- * The Log_file class is a concrete implementation of the Log abstract
- * class that logs messages to a text file.
- *
- * @author Jon Parise <jon@php.net>
- * @author Roman Neuhauser <neuhauser@bellavista.cz>
- * @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;
-
- /**
- * Integer (in octal) containing the log file's permissions mode.
- * @var integer
- * @access private
- */
- var $_mode = 0644;
-
- /**
- * 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';
-
- /**
- * Hash that maps canonical format keys to position arguments for the
- * "line format" string.
- * @var array
- * @access private
- */
- var $_formatMap = array('%{timestamp}' => '%1$s',
- '%{ident}' => '%2$s',
- '%{priority}' => '%3$s',
- '%{message}' => '%4$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)
- {
- $this->_id = md5(microtime());
- $this->_filename = $name;
- $this->_ident = $ident;
- $this->_mask = Log::UPTO($level);
-
- if (isset($conf['append'])) {
- $this->_append = $conf['append'];
- }
-
- if (!empty($conf['mode'])) {
- $this->_mode = $conf['mode'];
- }
-
- 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.
- *
- * @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)
- {
- static $depth = 0;
-
- /* Guard against potentially infinite recursion. */
- if ($depth++ > 25) {
- trigger_error("_mkpath(): Maximum recursion depth (25) exceeded",
- E_USER_WARNING);
- return false;
- }
-
- /* We're only interested in the directory component of the path. */
- $path = dirname($path);
-
- /* If the directory already exists, return success immediately. */
- if (is_dir($path)) {
- $depth = 0;
- return true;
- }
-
- /*
- * In order to understand recursion, you must first understand
- * recursion ...
- */
- if ($this->_mkpath($path, $mode) === false) {
- return false;
- }
-
- return @mkdir($path, $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);
- }
-
- /* Obtain a handle to the log file. */
- $this->_fp = fopen($this->_filename, ($this->_append) ? 'a' : 'w');
-
- $this->_opened = ($this->_fp !== false);
-
- /* Attempt to set the log file's mode. */
- @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()
- {
- return fflush($this->_fp);
- }
-
- /**
- * 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;
- }
-
- /* 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);
-
- /* Build the string containing the complete log line. */
- $line = sprintf($this->_lineFormat, strftime($this->_timeFormat),
- $this->_ident, $this->priorityToString($priority),
- $message) . $this->_eol;
-
- /* Write the log line to the log file. */
- $success = (fwrite($this->_fp, $line) !== false);
-
- /* Notify observers about this log message. */
- $this->_announce(array('priority' => $priority, 'message' => $message));
-
- return $success;
- }
-}
-
-?>
diff --git a/inc/Log/mail.php b/inc/Log/mail.php
deleted file mode 100644
index 064f13c0ed5..00000000000
--- a/inc/Log/mail.php
+++ /dev/null
@@ -1,222 +0,0 @@
-<?php
-/**
- * $Header: /repository/pear/Log/Log/mail.php,v 1.21 2004/01/19 08:02:40 jon Exp $
- *
- * @version $Revision: 1.21 $
- * @package Log
- */
-
-/**
- * The Log_mail class is a concrete implementation of the Log:: abstract class
- * which sends log messages to a mailbox.
- * The mail is actually sent when you close() the logger, or when the destructor
- * is called (when the script is terminated).
- *
- * PLEASE NOTE that you must create a Log_mail object using =&, like this :
- * $logger =& Log::factory("mail", "recipient@example.com", ...)
- *
- * This is a PEAR requirement for destructors to work properly.
- * See http://pear.php.net/manual/en/class.pear.php
- *
- * @author Ronnie Garcia <ronnie@mk2.net>
- * @author Jon Parise <jon@php.net>
- * @since Log 1.3
- * @package Log
- *
- * @example mail.php Using the mail handler.
- */
-class Log_mail extends Log
-{
- /**
- * String holding the recipient's email address.
- * @var string
- * @access private
- */
- var $_recipient = '';
-
- /**
- * 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 holding the mail message body.
- * @var string
- * @access private
- */
- var $_message = '';
-
-
- /**
- * 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 filename of the logfile.
- * @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)
- {
- $this->_id = md5(microtime());
- $this->_recipient = $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'];
- }
-
- /* 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 . "\n\n";
- }
- $this->_opened = true;
- }
-
- 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 (!empty($this->_message)) {
- $headers = "From: $this->_from\n";
- $headers .= "User-Agent: Log_mail";
-
- if (mail($this->_recipient, $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->_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);
-
- $entry = sprintf("%s %s [%s] %s\n", strftime('%b %d %H:%M:%S'),
- $this->_ident, Log::priorityToString($priority),
- $message);
-
- $this->_message .= $entry;
-
- $this->_announce(array('priority' => $priority, 'message' => $message));
-
- return true;
- }
-}
-
-?>
diff --git a/inc/Log/mcal.php b/inc/Log/mcal.php
deleted file mode 100644
index a5c46f3dfc6..00000000000
--- a/inc/Log/mcal.php
+++ /dev/null
@@ -1,171 +0,0 @@
-<?php
-/**
- * $Header: /repository/pear/Log/Log/mcal.php,v 1.17 2004/01/19 08:02:40 jon Exp $
- * $Horde: horde/lib/Log/mcal.php,v 1.2 2000/06/28 21:36:13 jon Exp $
- *
- * @version $Revision: 1.17 $
- * @package Log
- */
-
-/**
- * The Log_mcal class is a concrete implementation of the Log::
- * abstract class which sends messages to a local or remote calendar
- * store accessed through MCAL.
- *
- * @author Chuck Hagenbuch <chuck@horde.org>
- * @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)
- {
- $this->_id = md5(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/inc/Log/null.php b/inc/Log/null.php
deleted file mode 100644
index 23de3f1a9e5..00000000000
--- a/inc/Log/null.php
+++ /dev/null
@@ -1,68 +0,0 @@
-<?php
-/**
- * $Header: /repository/pear/Log/Log/null.php,v 1.3 2004/01/19 08:02:40 jon Exp $
- *
- * @version $Revision: 1.3 $
- * @package Log
- */
-
-/**
- * The Log_null class is a concrete implementation of the Log:: abstract
- * class. It simply consumes log events.
- *
- * @author Jon Parise <jon@php.net>
- * @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)
- {
- $this->_id = md5(microtime());
- $this->_ident = $ident;
- $this->_mask = Log::UPTO($level);
- }
-
- /**
- * 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/inc/Log/observer.php b/inc/Log/observer.php
deleted file mode 100644
index 187d5070f74..00000000000
--- a/inc/Log/observer.php
+++ /dev/null
@@ -1,126 +0,0 @@
-<?php
-/**
- * $Header: /repository/pear/Log/Log/observer.php,v 1.12 2004/01/11 20:49:49 jon Exp $
- * $Horde: horde/lib/Log/observer.php,v 1.5 2000/06/28 21:36:13 jon Exp $
- *
- * @version $Revision: 1.12 $
- * @package Log
- */
-
-/**
- * The Log_observer:: class implements the Observer end of a Subject-Observer
- * pattern for watching log activity and taking actions on exceptional events.
- *
- * @author Chuck Hagenbuch <chuck@horde.org>
- * @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 = md5(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 an false on an error.
- */
- function &factory($type, $priority = PEAR_LOG_INFO, $conf = array())
- {
- $type = strtolower($type);
- $class = 'Log_observer_' . $type;
-
- /* Support both the new-style and old-style file naming conventions. */
- if (file_exists(dirname(__FILE__) . '/observer_' . $type . '.php')) {
- $classfile = 'Log/observer_' . $type . '.php';
- $newstyle = true;
- } else {
- $classfile = 'Log/' . $type . '.php';
- $newstyle = false;
- }
-
- /* Issue a warning if the old-style conventions are being used. */
- if (!$newstyle)
- {
- trigger_error('Using old-style Log_observer conventions',
- E_USER_WARNING);
- }
-
- /*
- * 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) {
- return new $class($priority, $conf);
- } else {
- return new $class($priority);
- }
- }
-
- return false;
- }
-
- /**
- * 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);
- }
-}
-
-?>
diff --git a/inc/Log/sql.php b/inc/Log/sql.php
deleted file mode 100644
index 3a20a0e2faf..00000000000
--- a/inc/Log/sql.php
+++ /dev/null
@@ -1,225 +0,0 @@
-<?php
-/**
- * $Header: /repository/pear/Log/Log/sql.php,v 1.34 2004/08/19 06:35:57 jon Exp $
- * $Horde: horde/lib/Log/sql.php,v 1.12 2000/08/16 20:27:34 chuck Exp $
- *
- * @version $Revision: 1.34 $
- * @package Log
- */
-
-/** PEAR's DB package */
-require_once 'DB.php';
-
-/**
- * The Log_sql class is a concrete implementation of the Log::
- * abstract class which sends messages to an SQL server. Each entry
- * occupies a separate row in the database.
- *
- * This implementation uses PHP's PEAR database abstraction layer.
- *
- * CREATE TABLE log_table (
- * id INT NOT NULL,
- * logtime TIMESTAMP NOT NULL,
- * ident CHAR(16) NOT NULL,
- * priority INT NOT NULL,
- * message VARCHAR(200),
- * PRIMARY KEY (id)
- * );
- *
- * @author Jon Parise <jon@php.net>
- * @since Horde 1.3
- * @since Log 1.0
- * @package Log
- *
- * @example sql.php Using the SQL handler.
- */
-class Log_sql extends Log {
-
- /**
- * Array containing the dsn information.
- * @var string
- * @access private
- */
- var $_dsn = '';
-
- /**
- * 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';
-
- /**
- * 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 = md5(microtime());
- $this->_table = $name;
- $this->_mask = Log::UPTO($level);
-
- /* 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) {
- $this->_db = &DB::connect($this->_dsn, true);
- if (DB::isError($this->_db)) {
- return false;
- }
- $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;
- 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;
- }
-
- /* Extract the string representation of the message. */
- $message = $this->_extractMessage($message);
-
- /* Build the SQL query for this log entry insertion. */
- $id = $this->_db->nextId($this->_sequence);
- $q = sprintf('insert into %s (id, logtime, ident, priority, message)' .
- 'values(%d, CURRENT_TIMESTAMP, %s, %d, %s)',
- $this->_table, $id, $this->_db->quote($this->_ident),
- $priority, $this->_db->quote($message));
-
- $result = $this->_db->query($q);
- if (DB::isError($result)) {
- return false;
- }
-
- $this->_announce(array('priority' => $priority, 'message' => $message));
-
- return true;
- }
-}
-
-?>
diff --git a/inc/Log/sqlite.php b/inc/Log/sqlite.php
deleted file mode 100644
index 83b908a9396..00000000000
--- a/inc/Log/sqlite.php
+++ /dev/null
@@ -1,238 +0,0 @@
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP version 4.0 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Bertrand Mansion <bmansion@mamasam.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: sqlite.php,v 1.3 2004/01/19 08:02:40 jon Exp $
-
-/**
- * The Log_sqlite class is a concrete implementation of the Log::
- * abstract class which sends messages to an Sqlite database.
- * Each entry occupies a separate row in the database.
- *
- * This implementation uses PHP native Sqlite functions.
- *
- * CREATE TABLE log_table (
- * id INTEGER PRIMARY KEY NOT NULL,
- * logtime NOT NULL,
- * ident CHAR(16) NOT NULL,
- * priority INT NOT NULL,
- * message
- * );
- *
- * @author Bertrand Mansion <bmansion@mamasam.com>
- * @author Jon Parise <jon@php.net>
- * @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 = md5(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;
- }
-}
-
-?>
diff --git a/inc/Log/syslog.php b/inc/Log/syslog.php
deleted file mode 100644
index 4bafbaa2d9a..00000000000
--- a/inc/Log/syslog.php
+++ /dev/null
@@ -1,160 +0,0 @@
-<?php
-/**
- * $Header: /repository/pear/Log/Log/syslog.php,v 1.22 2004/01/19 08:02:40 jon Exp $
- * $Horde: horde/lib/Log/syslog.php,v 1.6 2000/06/28 21:36:13 jon Exp $
- *
- * @version $Revision: 1.22 $
- * @package Log
- */
-
-/**
- * The Log_syslog class is a concrete implementation of the Log::
- * abstract class which sends messages to syslog on UNIX-like machines
- * (PHP emulates this with the Event Log on Windows machines).
- *
- * @author Chuck Hagenbuch <chuck@horde.org>
- * @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 string
- * @access private
- */
- var $_name = LOG_SYSLOG;
-
- /**
- * 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;
- }
-
- $this->_id = md5(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) {
- openlog($this->_ident, LOG_PID, $this->_name);
- $this->_opened = true;
- }
-
- return $this->_opened;
- }
-
- /**
- * Closes the connection to the system logger, if it is open.
- * @access public
- */
- function close()
- {
- if ($this->_opened) {
- closelog();
- $this->_opened = false;
- }
-
- return ($this->_opened === false);
- }
-
- /**
- * 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);
-
- if (!syslog($this->_toSyslog($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];
- }
-}
-?>
diff --git a/inc/Log/win.php b/inc/Log/win.php
deleted file mode 100644
index e8a09d16e81..00000000000
--- a/inc/Log/win.php
+++ /dev/null
@@ -1,256 +0,0 @@
-<?php
-/**
- * $Header: /repository/pear/Log/Log/win.php,v 1.16 2004/09/08 23:35:53 jon Exp $
- *
- * @version $Revision: 1.16 $
- * @package Log
- */
-
-/**
- * The Log_win class is a concrete implementation of the Log abstract
- * class that logs messages to a separate browser window.
- *
- * The concept for this log handler is based on part by Craig Davis' article
- * entitled "JavaScript Power PHP Debugging:
- *
- * http://www.zend.com/zend/tut/tutorial-DebugLib.php
- *
- * @author Jon Parise <jon@php.net>
- * @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 colors.
- * @var array
- * @access private
- */
- var $_colors = array(
- PEAR_LOG_EMERG => 'red',
- PEAR_LOG_ALERT => 'orange',
- PEAR_LOG_CRIT => 'yellow',
- PEAR_LOG_ERR => 'green',
- PEAR_LOG_WARNING => 'blue',
- PEAR_LOG_NOTICE => 'indigo',
- PEAR_LOG_INFO => 'violet',
- PEAR_LOG_DEBUG => '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 = md5(microtime());
- $this->_name = $name;
- $this->_ident = $ident;
- $this->_mask = Log::UPTO($level);
-
- if (isset($conf['title'])) {
- $this->_title = $conf['title'];
- }
- if (isset($conf['colors']) && is_array($conf['colors'])) {
- $this->_colors = $conf['colors'];
- }
-
- 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;
-
- if (!empty($this->_ident)) {
- $identHeader = "$win.document.writeln('<th>Ident</th>')";
- } else {
- $identHeader = '';
- }
-
- echo <<< END_OF_SCRIPT
-<script language="JavaScript">
-$win = window.open('', '{$this->_name}', 'toolbar=no,scrollbars,width=600,height=400');
-$win.document.writeln('<html>');
-$win.document.writeln('<head>');
-$win.document.writeln('<title>{$this->_title}</title>');
-$win.document.writeln('<style type="text/css">');
-$win.document.writeln('body { font-family: monospace; font-size: 8pt; }');
-$win.document.writeln('td,th { font-size: 8pt; }');
-$win.document.writeln('td,th { border-bottom: #999999 solid 1px; }');
-$win.document.writeln('td,th { border-right: #999999 solid 1px; }');
-$win.document.writeln('</style>');
-$win.document.writeln('</head>');
-$win.document.writeln('<body>');
-$win.document.writeln('<table border="0" cellpadding="2" cellspacing="0">');
-$win.document.writeln('<tr><th>Time</th>');
-$identHeader
-$win.document.writeln('<th>Priority</th><th width="100%">Message</th></tr>');
-</script>
-END_OF_SCRIPT;
- $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('</table>');
- $this->_writeln('</body></html>');
- $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 "<script language='JavaScript'>\n";
- echo "$win.document.writeln('" . addslashes($line) . "');\n";
- echo "self.focus();\n";
- echo "</script>\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);
-
- list($usec, $sec) = explode(' ', microtime());
-
- /* Build the output line that contains the log entry row. */
- $line = '<tr align="left" valign="top">';
- $line .= sprintf('<td>%s.%s</td>',
- strftime('%T', $sec), substr($usec, 2, 2));
- if (!empty($this->_ident)) {
- $line .= '<td>' . $this->_ident . '</td>';
- }
- $line .= '<td>' . ucfirst($this->priorityToString($priority)) . '</td>';
- $line .= sprintf('<td style="color: %s">%s</td>',
- $this->_colors[$priority],
- preg_replace('/\r\n|\n|\r/', '<br />', $message));
- $line .= '</tr>';
-
- $this->_writeln($line);
-
- $this->_announce(array('priority' => $priority, 'message' => $message));
-
- return true;
- }
-}
-
-?>
diff --git a/inc/MDB2.php b/inc/MDB2.php
deleted file mode 100644
index faf405b4112..00000000000
--- a/inc/MDB2.php
+++ /dev/null
@@ -1,4361 +0,0 @@
-<?php
-// vim: set et ts=4 sw=4 fdm=marker:
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: MDB2.php,v 1.335 2008/11/29 14:57:01 afz Exp $
-//
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-
-oc_require_once('PEAR.php');
-
-// {{{ Error constants
-
-/**
- * The method mapErrorCode in each MDB2_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 MDB2::errorMessage().
- */
-
-define('MDB2_OK', true);
-define('MDB2_ERROR', -1);
-define('MDB2_ERROR_SYNTAX', -2);
-define('MDB2_ERROR_CONSTRAINT', -3);
-define('MDB2_ERROR_NOT_FOUND', -4);
-define('MDB2_ERROR_ALREADY_EXISTS', -5);
-define('MDB2_ERROR_UNSUPPORTED', -6);
-define('MDB2_ERROR_MISMATCH', -7);
-define('MDB2_ERROR_INVALID', -8);
-define('MDB2_ERROR_NOT_CAPABLE', -9);
-define('MDB2_ERROR_TRUNCATED', -10);
-define('MDB2_ERROR_INVALID_NUMBER', -11);
-define('MDB2_ERROR_INVALID_DATE', -12);
-define('MDB2_ERROR_DIVZERO', -13);
-define('MDB2_ERROR_NODBSELECTED', -14);
-define('MDB2_ERROR_CANNOT_CREATE', -15);
-define('MDB2_ERROR_CANNOT_DELETE', -16);
-define('MDB2_ERROR_CANNOT_DROP', -17);
-define('MDB2_ERROR_NOSUCHTABLE', -18);
-define('MDB2_ERROR_NOSUCHFIELD', -19);
-define('MDB2_ERROR_NEED_MORE_DATA', -20);
-define('MDB2_ERROR_NOT_LOCKED', -21);
-define('MDB2_ERROR_VALUE_COUNT_ON_ROW', -22);
-define('MDB2_ERROR_INVALID_DSN', -23);
-define('MDB2_ERROR_CONNECT_FAILED', -24);
-define('MDB2_ERROR_EXTENSION_NOT_FOUND',-25);
-define('MDB2_ERROR_NOSUCHDB', -26);
-define('MDB2_ERROR_ACCESS_VIOLATION', -27);
-define('MDB2_ERROR_CANNOT_REPLACE', -28);
-define('MDB2_ERROR_CONSTRAINT_NOT_NULL',-29);
-define('MDB2_ERROR_DEADLOCK', -30);
-define('MDB2_ERROR_CANNOT_ALTER', -31);
-define('MDB2_ERROR_MANAGER', -32);
-define('MDB2_ERROR_MANAGER_PARSE', -33);
-define('MDB2_ERROR_LOADMODULE', -34);
-define('MDB2_ERROR_INSUFFICIENT_DATA', -35);
-define('MDB2_ERROR_NO_PERMISSION', -36);
-define('MDB2_ERROR_DISCONNECT_FAILED', -37);
-
-// }}}
-// {{{ Verbose constants
-/**
- * These are just helper constants to more verbosely express parameters to prepare()
- */
-
-define('MDB2_PREPARE_MANIP', false);
-define('MDB2_PREPARE_RESULT', null);
-
-// }}}
-// {{{ Fetchmode constants
-
-/**
- * This is a special constant that tells MDB2 the user hasn't specified
- * any particular get mode, so the default should be used.
- */
-define('MDB2_FETCHMODE_DEFAULT', 0);
-
-/**
- * Column data indexed by numbers, ordered from 0 and up
- */
-define('MDB2_FETCHMODE_ORDERED', 1);
-
-/**
- * Column data indexed by column names
- */
-define('MDB2_FETCHMODE_ASSOC', 2);
-
-/**
- * Column data as object properties
- */
-define('MDB2_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.
- * MDB2_FETCHMODE_FLIPPED switches this order, so the first level of arrays
- * is the column name, and the second level the row number.
- */
-define('MDB2_FETCHMODE_FLIPPED', 4);
-
-// }}}
-// {{{ Portability mode constants
-
-/**
- * Portability: turn off all portability features.
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_NONE', 0);
-
-/**
- * Portability: convert names of tables and fields to case defined in the
- * "field_case" option when using the query*(), fetch*() and tableInfo() methods.
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_FIX_CASE', 1);
-
-/**
- * Portability: right trim the data output by query*() and fetch*().
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_RTRIM', 2);
-
-/**
- * Portability: force reporting the number of rows deleted.
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_DELETE_COUNT', 4);
-
-/**
- * Portability: not needed in MDB2 (just left here for compatibility to DB)
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_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
- * MDB2_ERROR_ALREADY_EXISTS -> MDB2_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 MDB2_ERROR_NOSUCHFIELD.
- *
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_ERRORS', 16);
-
-/**
- * Portability: convert empty values to null strings in data output by
- * query*() and fetch*().
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_EMPTY_TO_NULL', 32);
-
-/**
- * Portability: removes database/table qualifiers from associative indexes
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES', 64);
-
-/**
- * Portability: turn on all portability features.
- * @see MDB2_Driver_Common::setOption()
- */
-define('MDB2_PORTABILITY_ALL', 127);
-
-// }}}
-// {{{ Globals for class instance tracking
-
-/**
- * These are global variables that are used to track the various class instances
- */
-
-$GLOBALS['_MDB2_databases'] = array();
-$GLOBALS['_MDB2_dsninfo_default'] = array(
- 'phptype' => false,
- 'dbsyntax' => false,
- 'username' => false,
- 'password' => false,
- 'protocol' => false,
- 'hostspec' => false,
- 'port' => false,
- 'socket' => false,
- 'database' => false,
- 'mode' => false,
-);
-
-// }}}
-// {{{ class MDB2
-
-/**
- * The main 'MDB2' 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 MDB2 is as follows (indentation means inheritance):
- *
- * MDB2 The main MDB2 class. This is simply a utility class
- * with some 'static' methods for creating MDB2 objects as
- * well as common utility functions for other MDB2 classes.
- *
- * MDB2_Driver_Common The base for each MDB2 implementation. Provides default
- * | implementations (in OO lingo virtual methods) for
- * | the actual DB implementations as well as a bunch of
- * | query utility functions.
- * |
- * +-MDB2_Driver_mysql The MDB2 implementation for MySQL. Inherits MDB2_Driver_Common.
- * When calling MDB2::factory or MDB2::connect for MySQL
- * connections, the object returned is an instance of this
- * class.
- * +-MDB2_Driver_pgsql The MDB2 implementation for PostGreSQL. Inherits MDB2_Driver_Common.
- * When calling MDB2::factory or MDB2::connect for PostGreSQL
- * connections, the object returned is an instance of this
- * class.
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2
-{
- // {{{ function setOptions(&$db, $options)
-
- /**
- * set option array in an exiting database object
- *
- * @param MDB2_Driver_Common MDB2 object
- * @param array An associative array of option names and their values.
- *
- * @return mixed MDB2_OK or a PEAR Error object
- *
- * @access public
- */
- function setOptions(&$db, $options)
- {
- if (is_array($options)) {
- foreach ($options as $option => $value) {
- $test = $db->setOption($option, $value);
- if (PEAR::isError($test)) {
- return $test;
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function classExists($classname)
-
- /**
- * Checks if a class exists without triggering __autoload
- *
- * @param string classname
- *
- * @return bool true success and false on error
- * @static
- * @access public
- */
- function classExists($classname)
- {
- if (version_compare(phpversion(), "5.0", ">=")) {
- return class_exists($classname, false);
- }
- return class_exists($classname);
- }
-
- // }}}
- // {{{ function loadClass($class_name, $debug)
-
- /**
- * Loads a PEAR class.
- *
- * @param string classname to load
- * @param bool if errors should be suppressed
- *
- * @return mixed true success or PEAR_Error on failure
- *
- * @access public
- */
- function loadClass($class_name, $debug)
- {
- if (!MDB2::classExists($class_name)) {
- $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
- if ($debug) {
- $include = oc_include_once($file_name);
- } else {
- $include = oc_include_once($file_name);
- }
- if (!$include) {
- if (!MDB2::fileExists($file_name)) {
- $msg = "unable to find package '$class_name' file '$file_name'";
- } else {
- $msg = "unable to load class '$class_name' from file '$file_name'";
- }
- $err =& MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null, $msg);
- return $err;
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function &factory($dsn, $options = false)
-
- /**
- * Create a new MDB2 object for the specified database type
- *
- * IMPORTANT: In order for MDB2 to work properly it is necessary that
- * you make sure that you work with a reference of the original
- * object instead of a copy (this is a PHP4 quirk).
- *
- * For example:
- * $db =& MDB2::factory($dsn);
- * ^^
- * And not:
- * $db = MDB2::factory($dsn);
- *
- * @param mixed 'data source name', see the MDB2::parseDSN
- * method for a description of the dsn format.
- * Can also be specified as an array of the
- * format returned by MDB2::parseDSN.
- * @param array An associative array of option names and
- * their values.
- *
- * @return mixed a newly created MDB2 object, or false on error
- *
- * @access public
- */
- function &factory($dsn, $options = false)
- {
- $dsninfo = MDB2::parseDSN($dsn);
- if (empty($dsninfo['phptype'])) {
- $err =& MDB2::raiseError(MDB2_ERROR_NOT_FOUND,
- null, null, 'no RDBMS driver specified');
- return $err;
- }
- $class_name = 'MDB2_Driver_'.$dsninfo['phptype'];
-
- $debug = (!empty($options['debug']));
- $err = MDB2::loadClass($class_name, $debug);
- if (PEAR::isError($err)) {
- return $err;
- }
-
- $db =& new $class_name();
- $db->setDSN($dsninfo);
- $err = MDB2::setOptions($db, $options);
- if (PEAR::isError($err)) {
- return $err;
- }
-
- return $db;
- }
-
- // }}}
- // {{{ function &connect($dsn, $options = false)
-
- /**
- * Create a new MDB2_Driver_* connection object and connect to the specified
- * database
- *
- * IMPORTANT: In order for MDB2 to work properly it is necessary that
- * you make sure that you work with a reference of the original
- * object instead of a copy (this is a PHP4 quirk).
- *
- * For example:
- * $db =& MDB2::connect($dsn);
- * ^^
- * And not:
- * $db = MDB2::connect($dsn);
- * ^^
- *
- * @param mixed $dsn 'data source name', see the MDB2::parseDSN
- * method for a description of the dsn format.
- * Can also be specified as an array of the
- * format returned by MDB2::parseDSN.
- * @param array $options An associative array of option names and
- * their values.
- *
- * @return mixed a newly created MDB2 connection object, or a MDB2
- * error object on error
- *
- * @access public
- * @see MDB2::parseDSN
- */
- function &connect($dsn, $options = false)
- {
- $db =& MDB2::factory($dsn, $options);
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $err = $db->connect();
- if (PEAR::isError($err)) {
- $dsn = $db->getDSN('string', 'xxx');
- $db->disconnect();
- $err->addUserInfo($dsn);
- return $err;
- }
-
- return $db;
- }
-
- // }}}
- // {{{ function &singleton($dsn = null, $options = false)
-
- /**
- * Returns a MDB2 connection with the requested DSN.
- * A new MDB2 connection object is only created if no object with the
- * requested DSN exists yet.
- *
- * IMPORTANT: In order for MDB2 to work properly it is necessary that
- * you make sure that you work with a reference of the original
- * object instead of a copy (this is a PHP4 quirk).
- *
- * For example:
- * $db =& MDB2::singleton($dsn);
- * ^^
- * And not:
- * $db = MDB2::singleton($dsn);
- * ^^
- *
- * @param mixed 'data source name', see the MDB2::parseDSN
- * method for a description of the dsn format.
- * Can also be specified as an array of the
- * format returned by MDB2::parseDSN.
- * @param array An associative array of option names and
- * their values.
- *
- * @return mixed a newly created MDB2 connection object, or a MDB2
- * error object on error
- *
- * @access public
- * @see MDB2::parseDSN
- */
- function &singleton($dsn = null, $options = false)
- {
- if ($dsn) {
- $dsninfo = MDB2::parseDSN($dsn);
- $dsninfo = array_merge($GLOBALS['_MDB2_dsninfo_default'], $dsninfo);
- $keys = array_keys($GLOBALS['_MDB2_databases']);
- for ($i=0, $j=count($keys); $i<$j; ++$i) {
- if (isset($GLOBALS['_MDB2_databases'][$keys[$i]])) {
- $tmp_dsn = $GLOBALS['_MDB2_databases'][$keys[$i]]->getDSN('array');
- if (count(array_diff_assoc($tmp_dsn, $dsninfo)) == 0) {
- MDB2::setOptions($GLOBALS['_MDB2_databases'][$keys[$i]], $options);
- return $GLOBALS['_MDB2_databases'][$keys[$i]];
- }
- }
- }
- } elseif (is_array($GLOBALS['_MDB2_databases']) && reset($GLOBALS['_MDB2_databases'])) {
- $db =& $GLOBALS['_MDB2_databases'][key($GLOBALS['_MDB2_databases'])];
- return $db;
- }
- $db =& MDB2::factory($dsn, $options);
- return $db;
- }
-
- // }}}
- // {{{ function areEquals()
-
- /**
- * It looks like there's a memory leak in array_diff() in PHP 5.1.x,
- * so use this method instead.
- * @see http://pear.php.net/bugs/bug.php?id=11790
- *
- * @param array $arr1
- * @param array $arr2
- * @return boolean
- */
- function areEquals($arr1, $arr2)
- {
- if (count($arr1) != count($arr2)) {
- return false;
- }
- foreach (array_keys($arr1) as $k) {
- if (!array_key_exists($k, $arr2) || $arr1[$k] != $arr2[$k]) {
- return false;
- }
- }
- return true;
- }
-
- // }}}
- // {{{ function loadFile($file)
-
- /**
- * load a file (like 'Date')
- *
- * @param string name of the file in the MDB2 directory (without '.php')
- *
- * @return string name of the file that was included
- *
- * @access public
- */
- function loadFile($file)
- {
- $file_name = 'MDB2'.DIRECTORY_SEPARATOR.$file.'.php';
- if (!MDB2::fileExists($file_name)) {
- return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'unable to find: '.$file_name);
- }
- if (!include_once($file_name)) {
- return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'unable to load driver class: '.$file_name);
- }
- return $file_name;
- }
-
- // }}}
- // {{{ function apiVersion()
-
- /**
- * Return the MDB2 API version
- *
- * @return string the MDB2 API version number
- *
- * @access public
- */
- function apiVersion()
- {
- return '2.5.0b2';
- }
-
- // }}}
- // {{{ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
-
- /**
- * This method is used to communicate an error and invoke error
- * callbacks etc. Basically a wrapper for PEAR::raiseError
- * without the message string.
- *
- * @param mixed int error code
- *
- * @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.
- *
- * @return PEAR_Error instance of a PEAR Error object
- *
- * @access private
- * @see PEAR_Error
- */
- function &raiseError($code = null,
- $mode = null,
- $options = null,
- $userinfo = null,
- $dummy1 = null,
- $dummy2 = null,
- $dummy3 = false)
- {
- $err =& PEAR::raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);
- return $err;
- }
-
- // }}}
- // {{{ function isError($data, $code = null)
-
- /**
- * Tell whether a value is a MDB2 error.
- *
- * @param mixed the value to test
- * @param int if is an error object, return true
- * only if $code is a string and
- * $db->getMessage() == $code or
- * $code is an integer and $db->getCode() == $code
- *
- * @return bool true if parameter is an error
- *
- * @access public
- */
- function isError($data, $code = null)
- {
- if (is_a($data, 'MDB2_Error')) {
- if (is_null($code)) {
- return true;
- } elseif (is_string($code)) {
- return $data->getMessage() === $code;
- } else {
- $code = (array)$code;
- return in_array($data->getCode(), $code);
- }
- }
- return false;
- }
-
- // }}}
- // {{{ function isConnection($value)
-
- /**
- * Tell whether a value is a MDB2 connection
- *
- * @param mixed value to test
- *
- * @return bool whether $value is a MDB2 connection
- *
- * @access public
- */
- function isConnection($value)
- {
- return is_a($value, 'MDB2_Driver_Common');
- }
-
- // }}}
- // {{{ function isResult($value)
-
- /**
- * Tell whether a value is a MDB2 result
- *
- * @param mixed value to test
- *
- * @return bool whether $value is a MDB2 result
- *
- * @access public
- */
- function isResult($value)
- {
- return is_a($value, 'MDB2_Result');
- }
-
- // }}}
- // {{{ function isResultCommon($value)
-
- /**
- * Tell whether a value is a MDB2 result implementing the common interface
- *
- * @param mixed value to test
- *
- * @return bool whether $value is a MDB2 result implementing the common interface
- *
- * @access public
- */
- function isResultCommon($value)
- {
- return is_a($value, 'MDB2_Result_Common');
- }
-
- // }}}
- // {{{ function isStatement($value)
-
- /**
- * Tell whether a value is a MDB2 statement interface
- *
- * @param mixed value to test
- *
- * @return bool whether $value is a MDB2 statement interface
- *
- * @access public
- */
- function isStatement($value)
- {
- return is_a($value, 'MDB2_Statement_Common');
- }
-
- // }}}
- // {{{ function errorMessage($value = null)
-
- /**
- * Return a textual error message for a MDB2 error code
- *
- * @param int|array integer error code,
- null to get the current error code-message map,
- or an array with a new error code-message map
- *
- * @return string error message, or false if the error code was
- * not recognized
- *
- * @access public
- */
- function errorMessage($value = null)
- {
- static $errorMessages;
-
- if (is_array($value)) {
- $errorMessages = $value;
- return MDB2_OK;
- }
-
- if (!isset($errorMessages)) {
- $errorMessages = array(
- MDB2_OK => 'no error',
- MDB2_ERROR => 'unknown error',
- MDB2_ERROR_ALREADY_EXISTS => 'already exists',
- MDB2_ERROR_CANNOT_CREATE => 'can not create',
- MDB2_ERROR_CANNOT_ALTER => 'can not alter',
- MDB2_ERROR_CANNOT_REPLACE => 'can not replace',
- MDB2_ERROR_CANNOT_DELETE => 'can not delete',
- MDB2_ERROR_CANNOT_DROP => 'can not drop',
- MDB2_ERROR_CONSTRAINT => 'constraint violation',
- MDB2_ERROR_CONSTRAINT_NOT_NULL=> 'null value violates not-null constraint',
- MDB2_ERROR_DIVZERO => 'division by zero',
- MDB2_ERROR_INVALID => 'invalid',
- MDB2_ERROR_INVALID_DATE => 'invalid date or time',
- MDB2_ERROR_INVALID_NUMBER => 'invalid number',
- MDB2_ERROR_MISMATCH => 'mismatch',
- MDB2_ERROR_NODBSELECTED => 'no database selected',
- MDB2_ERROR_NOSUCHFIELD => 'no such field',
- MDB2_ERROR_NOSUCHTABLE => 'no such table',
- MDB2_ERROR_NOT_CAPABLE => 'MDB2 backend not capable',
- MDB2_ERROR_NOT_FOUND => 'not found',
- MDB2_ERROR_NOT_LOCKED => 'not locked',
- MDB2_ERROR_SYNTAX => 'syntax error',
- MDB2_ERROR_UNSUPPORTED => 'not supported',
- MDB2_ERROR_VALUE_COUNT_ON_ROW => 'value count on row',
- MDB2_ERROR_INVALID_DSN => 'invalid DSN',
- MDB2_ERROR_CONNECT_FAILED => 'connect failed',
- MDB2_ERROR_NEED_MORE_DATA => 'insufficient data supplied',
- MDB2_ERROR_EXTENSION_NOT_FOUND=> 'extension not found',
- MDB2_ERROR_NOSUCHDB => 'no such database',
- MDB2_ERROR_ACCESS_VIOLATION => 'insufficient permissions',
- MDB2_ERROR_LOADMODULE => 'error while including on demand module',
- MDB2_ERROR_TRUNCATED => 'truncated',
- MDB2_ERROR_DEADLOCK => 'deadlock detected',
- MDB2_ERROR_NO_PERMISSION => 'no permission',
- MDB2_ERROR_DISCONNECT_FAILED => 'disconnect failed',
- );
- }
-
- if (is_null($value)) {
- return $errorMessages;
- }
-
- if (PEAR::isError($value)) {
- $value = $value->getCode();
- }
-
- return isset($errorMessages[$value]) ?
- $errorMessages[$value] : $errorMessages[MDB2_ERROR];
- }
-
- // }}}
- // {{{ function parseDSN($dsn)
-
- /**
- * 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:
- * <code>
- * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true
- * </code>
- *
- * Most variations are allowed:
- * <code>
- * 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
- * </code>
- *
- * @param string 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
- *
- * @access public
- * @author Tomas V.V.Cox <cox@idecnet.com>
- */
- function parseDSN($dsn)
- {
- $parsed = $GLOBALS['_MDB2_dsninfo_default'];
-
- 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, '//') === 0
- && strpos($dsn, '/', 2) !== false
- && $parsed['phptype'] == 'oci8'
- ) {
- //oracle's "Easy Connect" syntax:
- //"username/password@[//]host[:port][/service_name]"
- //e.g. "scott/tiger@//mymachine:1521/oracle"
- $proto_opts = $dsn;
- $dsn = substr($proto_opts, strrpos($proto_opts, '/') + 1);
- } elseif (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 (strpos($proto_opts, ':') !== false) {
- list($proto_opts, $parsed['port']) = explode(':', $proto_opts);
- }
- if ($parsed['protocol'] == 'tcp') {
- $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'] = $dsn;
- // /database?param1=value1&param2=value2
- } else {
- $parsed['database'] = 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;
- }
-
- // }}}
- // {{{ function fileExists($file)
-
- /**
- * Checks if a file exists in the include path
- *
- * @param string filename
- *
- * @return bool true success and false on error
- *
- * @access public
- */
- function fileExists($file)
- {
- // safe_mode does notwork with is_readable()
- global $SERVERROOT;
- if (!@ini_get('safe_mode')) {
- $dirs = explode(PATH_SEPARATOR, ini_get('include_path'));
- array_unshift($dirs,$SERVERROOT);
- array_unshift($dirs,$SERVERROOT. DIRECTORY_SEPARATOR .'inc');
-// print_r($dirs);die();
- foreach ($dirs as $dir) {
- if (is_readable($dir . DIRECTORY_SEPARATOR . $file)) {
- return true;
- }
- }
- } else {
- $fp = @fopen($file, 'r', true);
- if (is_resource($fp)) {
- @fclose($fp);
- return true;
- }
- }
- return false;
- }
- // }}}
-}
-
-// }}}
-// {{{ class MDB2_Error extends PEAR_Error
-
-/**
- * MDB2_Error implements a class for reporting portable database error
- * messages.
- *
- * @package MDB2
- * @category Database
- * @author Stig Bakken <ssb@fast.no>
- */
-class MDB2_Error extends PEAR_Error
-{
- // {{{ constructor: function MDB2_Error($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN, $level = E_USER_NOTICE, $debuginfo = null)
-
- /**
- * MDB2_Error constructor.
- *
- * @param mixed MDB2 error code, or string with error message.
- * @param int what 'error mode' to operate in
- * @param int what error level to use for $mode & PEAR_ERROR_TRIGGER
- * @param mixed additional debug info, such as the last query
- */
- function MDB2_Error($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN,
- $level = E_USER_NOTICE, $debuginfo = null, $dummy = null)
- {
- if (is_null($code)) {
- $code = MDB2_ERROR;
- }
- $this->PEAR_Error('MDB2 Error: '.MDB2::errorMessage($code), $code,
- $mode, $level, $debuginfo);
- }
-
- // }}}
-}
-
-// }}}
-// {{{ class MDB2_Driver_Common extends PEAR
-
-/**
- * MDB2_Driver_Common: Base class that is extended by each MDB2 driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Common extends PEAR
-{
- // {{{ Variables (Properties)
-
- /**
- * index of the MDB2 object within the $GLOBALS['_MDB2_databases'] array
- * @var int
- * @access public
- */
- var $db_index = 0;
-
- /**
- * DSN used for the next query
- * @var array
- * @access protected
- */
- var $dsn = array();
-
- /**
- * DSN that was used to create the current connection
- * @var array
- * @access protected
- */
- var $connected_dsn = array();
-
- /**
- * connection resource
- * @var mixed
- * @access protected
- */
- var $connection = 0;
-
- /**
- * if the current opened connection is a persistent connection
- * @var bool
- * @access protected
- */
- var $opened_persistent;
-
- /**
- * the name of the database for the next query
- * @var string
- * @access protected
- */
- var $database_name = '';
-
- /**
- * the name of the database currently selected
- * @var string
- * @access protected
- */
- var $connected_database_name = '';
-
- /**
- * server version information
- * @var string
- * @access protected
- */
- var $connected_server_info = '';
-
- /**
- * list of all supported features of the given driver
- * @var array
- * @access public
- */
- var $supported = array(
- 'sequences' => false,
- 'indexes' => false,
- 'affected_rows' => false,
- 'summary_functions' => false,
- 'order_by_text' => false,
- 'transactions' => false,
- 'savepoints' => false,
- 'current_id' => false,
- 'limit_queries' => false,
- 'LOBs' => false,
- 'replace' => false,
- 'sub_selects' => false,
- 'triggers' => false,
- 'auto_increment' => false,
- 'primary_key' => false,
- 'result_introspection' => false,
- 'prepared_statements' => false,
- 'identifier_quoting' => false,
- 'pattern_escaping' => false,
- 'new_link' => false,
- );
-
- /**
- * Array of supported options that can be passed to the MDB2 instance.
- *
- * The options can be set during object creation, using
- * MDB2::connect(), MDB2::factory() or MDB2::singleton(). The options can
- * also be set after the object is created, using MDB2::setOptions() or
- * MDB2_Driver_Common::setOption().
- * The list of available option includes:
- * <ul>
- * <li>$options['ssl'] -> boolean: determines if ssl should be used for connections</li>
- * <li>$options['field_case'] -> CASE_LOWER|CASE_UPPER: determines what case to force on field/table names</li>
- * <li>$options['disable_query'] -> boolean: determines if queries should be executed</li>
- * <li>$options['result_class'] -> string: class used for result sets</li>
- * <li>$options['buffered_result_class'] -> string: class used for buffered result sets</li>
- * <li>$options['result_wrap_class'] -> string: class used to wrap result sets into</li>
- * <li>$options['result_buffering'] -> boolean should results be buffered or not?</li>
- * <li>$options['fetch_class'] -> string: class to use when fetch mode object is used</li>
- * <li>$options['persistent'] -> boolean: persistent connection?</li>
- * <li>$options['debug'] -> integer: numeric debug level</li>
- * <li>$options['debug_handler'] -> string: function/method that captures debug messages</li>
- * <li>$options['debug_expanded_output'] -> bool: BC option to determine if more context information should be send to the debug handler</li>
- * <li>$options['default_text_field_length'] -> integer: default text field length to use</li>
- * <li>$options['lob_buffer_length'] -> integer: LOB buffer length</li>
- * <li>$options['log_line_break'] -> string: line-break format</li>
- * <li>$options['idxname_format'] -> string: pattern for index name</li>
- * <li>$options['seqname_format'] -> string: pattern for sequence name</li>
- * <li>$options['savepoint_format'] -> string: pattern for auto generated savepoint names</li>
- * <li>$options['statement_format'] -> string: pattern for prepared statement names</li>
- * <li>$options['seqcol_name'] -> string: sequence column name</li>
- * <li>$options['quote_identifier'] -> boolean: if identifier quoting should be done when check_option is used</li>
- * <li>$options['use_transactions'] -> boolean: if transaction use should be enabled</li>
- * <li>$options['decimal_places'] -> integer: number of decimal places to handle</li>
- * <li>$options['portability'] -> integer: portability constant</li>
- * <li>$options['modules'] -> array: short to long module name mapping for __call()</li>
- * <li>$options['emulate_prepared'] -> boolean: force prepared statements to be emulated</li>
- * <li>$options['datatype_map'] -> array: map user defined datatypes to other primitive datatypes</li>
- * <li>$options['datatype_map_callback'] -> array: callback function/method that should be called</li>
- * <li>$options['bindname_format'] -> string: regular expression pattern for named parameters</li>
- * <li>$options['multi_query'] -> boolean: determines if queries returning multiple result sets should be executed</li>
- * <li>$options['max_identifiers_length'] -> integer: max identifier length</li>
- * <li>$options['default_fk_action_onupdate'] -> string: default FOREIGN KEY ON UPDATE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']</li>
- * <li>$options['default_fk_action_ondelete'] -> string: default FOREIGN KEY ON DELETE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']</li>
- * </ul>
- *
- * @var array
- * @access public
- * @see MDB2::connect()
- * @see MDB2::factory()
- * @see MDB2::singleton()
- * @see MDB2_Driver_Common::setOption()
- */
- var $options = array(
- 'ssl' => false,
- 'field_case' => CASE_LOWER,
- 'disable_query' => false,
- 'result_class' => 'MDB2_Result_%s',
- 'buffered_result_class' => 'MDB2_BufferedResult_%s',
- 'result_wrap_class' => false,
- 'result_buffering' => true,
- 'fetch_class' => 'stdClass',
- 'persistent' => false,
- 'debug' => 0,
- 'debug_handler' => 'MDB2_defaultDebugOutput',
- 'debug_expanded_output' => false,
- 'default_text_field_length' => 4096,
- 'lob_buffer_length' => 8192,
- 'log_line_break' => "\n",
- 'idxname_format' => '%s_idx',
- 'seqname_format' => '%s_seq',
- 'savepoint_format' => 'MDB2_SAVEPOINT_%s',
- 'statement_format' => 'MDB2_STATEMENT_%1$s_%2$s',
- 'seqcol_name' => 'sequence',
- 'quote_identifier' => false,
- 'use_transactions' => true,
- 'decimal_places' => 2,
- 'portability' => MDB2_PORTABILITY_ALL,
- 'modules' => array(
- 'ex' => 'Extended',
- 'dt' => 'Datatype',
- 'mg' => 'Manager',
- 'rv' => 'Reverse',
- 'na' => 'Native',
- 'fc' => 'Function',
- ),
- 'emulate_prepared' => false,
- 'datatype_map' => array(),
- 'datatype_map_callback' => array(),
- 'nativetype_map_callback' => array(),
- 'lob_allow_url_include' => false,
- 'bindname_format' => '(?:\d+)|(?:[a-zA-Z][a-zA-Z0-9_]*)',
- 'max_identifiers_length' => 30,
- 'default_fk_action_onupdate' => 'RESTRICT',
- 'default_fk_action_ondelete' => 'RESTRICT',
- );
-
- /**
- * string array
- * @var string
- * @access protected
- */
- var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => false, 'escape_pattern' => false);
-
- /**
- * identifier quoting
- * @var array
- * @access protected
- */
- var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
-
- /**
- * sql comments
- * @var array
- * @access protected
- */
- var $sql_comments = array(
- array('start' => '--', 'end' => "\n", 'escape' => false),
- array('start' => '/*', 'end' => '*/', 'escape' => false),
- );
-
- /**
- * comparision wildcards
- * @var array
- * @access protected
- */
- var $wildcards = array('%', '_');
-
- /**
- * column alias keyword
- * @var string
- * @access protected
- */
- var $as_keyword = ' AS ';
-
- /**
- * warnings
- * @var array
- * @access protected
- */
- var $warnings = array();
-
- /**
- * string with the debugging information
- * @var string
- * @access public
- */
- var $debug_output = '';
-
- /**
- * determine if there is an open transaction
- * @var bool
- * @access protected
- */
- var $in_transaction = false;
-
- /**
- * the smart transaction nesting depth
- * @var int
- * @access protected
- */
- var $nested_transaction_counter = null;
-
- /**
- * the first error that occured inside a nested transaction
- * @var MDB2_Error|bool
- * @access protected
- */
- var $has_transaction_error = false;
-
- /**
- * result offset used in the next query
- * @var int
- * @access protected
- */
- var $offset = 0;
-
- /**
- * result limit used in the next query
- * @var int
- * @access protected
- */
- var $limit = 0;
-
- /**
- * Database backend used in PHP (mysql, odbc etc.)
- * @var string
- * @access public
- */
- var $phptype;
-
- /**
- * Database used with regards to SQL syntax etc.
- * @var string
- * @access public
- */
- var $dbsyntax;
-
- /**
- * the last query sent to the driver
- * @var string
- * @access public
- */
- var $last_query;
-
- /**
- * the default fetchmode used
- * @var int
- * @access protected
- */
- var $fetchmode = MDB2_FETCHMODE_ORDERED;
-
- /**
- * array of module instances
- * @var array
- * @access protected
- */
- var $modules = array();
-
- /**
- * determines of the PHP4 destructor emulation has been enabled yet
- * @var array
- * @access protected
- */
- var $destructor_registered = true;
-
- // }}}
- // {{{ constructor: function __construct()
-
- /**
- * Constructor
- */
- function __construct()
- {
- end($GLOBALS['_MDB2_databases']);
- $db_index = key($GLOBALS['_MDB2_databases']) + 1;
- $GLOBALS['_MDB2_databases'][$db_index] = &$this;
- $this->db_index = $db_index;
- }
-
- // }}}
- // {{{ function MDB2_Driver_Common()
-
- /**
- * PHP 4 Constructor
- */
- function MDB2_Driver_Common()
- {
- $this->destructor_registered = false;
- $this->__construct();
- }
-
- // }}}
- // {{{ destructor: function __destruct()
-
- /**
- * Destructor
- */
- function __destruct()
- {
- $this->disconnect(false);
- }
-
- // }}}
- // {{{ function free()
-
- /**
- * Free the internal references so that the instance can be destroyed
- *
- * @return bool true on success, false if result is invalid
- *
- * @access public
- */
- function free()
- {
- unset($GLOBALS['_MDB2_databases'][$this->db_index]);
- unset($this->db_index);
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function __toString()
-
- /**
- * String conversation
- *
- * @return string representation of the object
- *
- * @access public
- */
- function __toString()
- {
- $info = get_class($this);
- $info.= ': (phptype = '.$this->phptype.', dbsyntax = '.$this->dbsyntax.')';
- if ($this->connection) {
- $info.= ' [connected]';
- }
- return $info;
- }
-
- // }}}
- // {{{ function errorInfo($error = null)
-
- /**
- * This method is used to collect information about an error
- *
- * @param mixed error code or resource
- *
- * @return array with MDB2 errorcode, native error code, native message
- *
- * @access public
- */
- function errorInfo($error = null)
- {
- return array($error, null, null);
- }
-
- // }}}
- // {{{ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
-
- /**
- * This method is used to communicate an error and invoke error
- * callbacks etc. Basically a wrapper for PEAR::raiseError
- * without the message string.
- *
- * @param mixed $code integer error code, or a PEAR error object (all
- * other parameters are ignored if this parameter is
- * an object
- * @param int $mode error mode, see PEAR_Error docs
- * @param mixed $options 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 $userinfo Extra debug information. Defaults to the last
- * query and native error code.
- * @param string $method name of the method that triggered the error
- * @param string $dummy1 not used
- * @param bool $dummy2 not used
- *
- * @return PEAR_Error instance of a PEAR Error object
- * @access public
- * @see PEAR_Error
- */
- function &raiseError($code = null,
- $mode = null,
- $options = null,
- $userinfo = null,
- $method = null,
- $dummy1 = null,
- $dummy2 = false
- ) {
- $userinfo = "[Error message: $userinfo]\n";
- // The error is yet a MDB2 error object
- if (PEAR::isError($code)) {
- // because we use the static PEAR::raiseError, our global
- // handler should be used if it is set
- if (is_null($mode) && !empty($this->_default_error_mode)) {
- $mode = $this->_default_error_mode;
- $options = $this->_default_error_options;
- }
- if (is_null($userinfo)) {
- $userinfo = $code->getUserinfo();
- }
- $code = $code->getCode();
- } elseif ($code == MDB2_ERROR_NOT_FOUND) {
- // extension not loaded: don't call $this->errorInfo() or the script
- // will die
- } elseif (isset($this->connection)) {
- if (!empty($this->last_query)) {
- $userinfo.= "[Last executed query: {$this->last_query}]\n";
- }
- $native_errno = $native_msg = null;
- list($code, $native_errno, $native_msg) = $this->errorInfo($code);
- if (!is_null($native_errno) && $native_errno !== '') {
- $userinfo.= "[Native code: $native_errno]\n";
- }
- if (!is_null($native_msg) && $native_msg !== '') {
- $userinfo.= "[Native message: ". strip_tags($native_msg) ."]\n";
- }
- if (!is_null($method)) {
- $userinfo = $method.': '.$userinfo;
- }
- }
-
- $err =& PEAR::raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Error', true);
- if ($err->getMode() !== PEAR_ERROR_RETURN
- && isset($this->nested_transaction_counter) && !$this->has_transaction_error) {
- $this->has_transaction_error =& $err;
- }
- return $err;
- }
-
- // }}}
- // {{{ function resetWarnings()
-
- /**
- * reset the warning array
- *
- * @return void
- *
- * @access public
- */
- function resetWarnings()
- {
- $this->warnings = array();
- }
-
- // }}}
- // {{{ function getWarnings()
-
- /**
- * Get all warnings in reverse order.
- * This means that the last warning is the first element in the array
- *
- * @return array with warnings
- *
- * @access public
- * @see resetWarnings()
- */
- function getWarnings()
- {
- return array_reverse($this->warnings);
- }
-
- // }}}
- // {{{ function setFetchMode($fetchmode, $object_class = 'stdClass')
-
- /**
- * Sets which fetch mode should be used by default on queries
- * on this connection
- *
- * @param int MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC
- * or MDB2_FETCHMODE_OBJECT
- * @param string the class name of the object to be returned
- * by the fetch methods when the
- * MDB2_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 possibility to use
- * and extend the 'MDB2_row' class.
- *
- * @return mixed MDB2_OK or MDB2 Error Object
- *
- * @access public
- * @see MDB2_FETCHMODE_ORDERED, MDB2_FETCHMODE_ASSOC, MDB2_FETCHMODE_OBJECT
- */
- function setFetchMode($fetchmode, $object_class = 'stdClass')
- {
- switch ($fetchmode) {
- case MDB2_FETCHMODE_OBJECT:
- $this->options['fetch_class'] = $object_class;
- case MDB2_FETCHMODE_ORDERED:
- case MDB2_FETCHMODE_ASSOC:
- $this->fetchmode = $fetchmode;
- break;
- default:
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'invalid fetchmode mode', __FUNCTION__);
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function setOption($option, $value)
-
- /**
- * set the option for the db class
- *
- * @param string option name
- * @param mixed value for the option
- *
- * @return mixed MDB2_OK or MDB2 Error Object
- *
- * @access public
- */
- function setOption($option, $value)
- {
- if (array_key_exists($option, $this->options)) {
- $this->options[$option] = $value;
- return MDB2_OK;
- }
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- "unknown option $option", __FUNCTION__);
- }
-
- // }}}
- // {{{ function getOption($option)
-
- /**
- * Returns the value of an option
- *
- * @param string option name
- *
- * @return mixed the option value or error object
- *
- * @access public
- */
- function getOption($option)
- {
- if (array_key_exists($option, $this->options)) {
- return $this->options[$option];
- }
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- "unknown option $option", __FUNCTION__);
- }
-
- // }}}
- // {{{ function debug($message, $scope = '', $is_manip = null)
-
- /**
- * set a debug message
- *
- * @param string message that should be appended to the debug variable
- * @param string usually the method name that triggered the debug call:
- * for example 'query', 'prepare', 'execute', 'parameters',
- * 'beginTransaction', 'commit', 'rollback'
- * @param array contains context information about the debug() call
- * common keys are: is_manip, time, result etc.
- *
- * @return void
- *
- * @access public
- */
- function debug($message, $scope = '', $context = array())
- {
- if ($this->options['debug'] && $this->options['debug_handler']) {
- if (!$this->options['debug_expanded_output']) {
- if (!empty($context['when']) && $context['when'] !== 'pre') {
- return null;
- }
- $context = empty($context['is_manip']) ? false : $context['is_manip'];
- }
- return call_user_func_array($this->options['debug_handler'], array(&$this, $scope, $message, $context));
- }
- return null;
- }
-
- // }}}
- // {{{ function getDebugOutput()
-
- /**
- * output debug info
- *
- * @return string content of the debug_output class variable
- *
- * @access public
- */
- function getDebugOutput()
- {
- return $this->debug_output;
- }
-
- // }}}
- // {{{ function escape($text)
-
- /**
- * Quotes a string so it can be safely used in a query. It will quote
- * the text so it can safely be used within a query.
- *
- * @param string the input string to quote
- * @param bool escape wildcards
- *
- * @return string quoted string
- *
- * @access public
- */
- function escape($text, $escape_wildcards = false)
- {
- if ($escape_wildcards) {
- $text = $this->escapePattern($text);
- }
-
- $text = str_replace($this->string_quoting['end'], $this->string_quoting['escape'] . $this->string_quoting['end'], $text);
- return $text;
- }
-
- // }}}
- // {{{ function escapePattern($text)
-
- /**
- * Quotes pattern (% and _) characters in a string)
- *
- * @param string the input string to quote
- *
- * @return string quoted string
- *
- * @access public
- */
- function escapePattern($text)
- {
- if ($this->string_quoting['escape_pattern']) {
- $text = str_replace($this->string_quoting['escape_pattern'], $this->string_quoting['escape_pattern'] . $this->string_quoting['escape_pattern'], $text);
- foreach ($this->wildcards as $wildcard) {
- $text = str_replace($wildcard, $this->string_quoting['escape_pattern'] . $wildcard, $text);
- }
- }
- return $text;
- }
-
- // }}}
- // {{{ function quoteIdentifier($str, $check_option = false)
-
- /**
- * 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.
- *
- * NOTE: if you have table names containing periods, don't use this method
- * (@see bug #11906)
- *
- * Portability is broken by using the following characters inside
- * delimited identifiers:
- * + backtick (<kbd>`</kbd>) -- due to MySQL
- * + double quote (<kbd>"</kbd>) -- due to Oracle
- * + brackets (<kbd>[</kbd> or <kbd>]</kbd>) -- due to Access
- *
- * Delimited identifiers are known to generally work correctly under
- * the following drivers:
- * + mssql
- * + mysql
- * + mysqli
- * + oci8
- * + pgsql
- * + sqlite
- *
- * InterBase doesn't seem to be able to use delimited identifiers
- * via PHP 4. They work fine under PHP 5.
- *
- * @param string identifier name to be quoted
- * @param bool check the 'quote_identifier' option
- *
- * @return string quoted identifier string
- *
- * @access public
- */
- function quoteIdentifier($str, $check_option = false)
- {
- if ($check_option && !$this->options['quote_identifier']) {
- return $str;
- }
- $str = str_replace($this->identifier_quoting['end'], $this->identifier_quoting['escape'] . $this->identifier_quoting['end'], $str);
- $parts = explode('.', $str);
- foreach (array_keys($parts) as $k) {
- $parts[$k] = $this->identifier_quoting['start'] . $parts[$k] . $this->identifier_quoting['end'];
- }
- return implode('.', $parts);
- }
-
- // }}}
- // {{{ function getAsKeyword()
-
- /**
- * Gets the string to alias column
- *
- * @return string to use when aliasing a column
- */
- function getAsKeyword()
- {
- return $this->as_keyword;
- }
-
- // }}}
- // {{{ function getConnection()
-
- /**
- * Returns a native connection
- *
- * @return mixed a valid MDB2 connection object,
- * or a MDB2 error object on error
- *
- * @access public
- */
- function getConnection()
- {
- $result = $this->connect();
- if (PEAR::isError($result)) {
- return $result;
- }
- return $this->connection;
- }
-
- // }}}
- // {{{ function _fixResultArrayValues(&$row, $mode)
-
- /**
- * Do all necessary conversions on result arrays to fix DBMS quirks
- *
- * @param array the array to be fixed (passed by reference)
- * @param array bit-wise addition of the required portability modes
- *
- * @return void
- *
- * @access protected
- */
- function _fixResultArrayValues(&$row, $mode)
- {
- switch ($mode) {
- case MDB2_PORTABILITY_EMPTY_TO_NULL:
- foreach ($row as $key => $value) {
- if ($value === '') {
- $row[$key] = null;
- }
- }
- break;
- case MDB2_PORTABILITY_RTRIM:
- foreach ($row as $key => $value) {
- if (is_string($value)) {
- $row[$key] = rtrim($value);
- }
- }
- break;
- case MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES:
- $tmp_row = array();
- foreach ($row as $key => $value) {
- $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
- }
- $row = $tmp_row;
- break;
- case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL):
- foreach ($row as $key => $value) {
- if ($value === '') {
- $row[$key] = null;
- } elseif (is_string($value)) {
- $row[$key] = rtrim($value);
- }
- }
- break;
- case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
- $tmp_row = array();
- foreach ($row as $key => $value) {
- if (is_string($value)) {
- $value = rtrim($value);
- }
- $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
- }
- $row = $tmp_row;
- break;
- case (MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
- $tmp_row = array();
- foreach ($row as $key => $value) {
- if ($value === '') {
- $value = null;
- }
- $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
- }
- $row = $tmp_row;
- break;
- case (MDB2_PORTABILITY_RTRIM + MDB2_PORTABILITY_EMPTY_TO_NULL + MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES):
- $tmp_row = array();
- foreach ($row as $key => $value) {
- if ($value === '') {
- $value = null;
- } elseif (is_string($value)) {
- $value = rtrim($value);
- }
- $tmp_row[preg_replace('/^(?:.*\.)?([^.]+)$/', '\\1', $key)] = $value;
- }
- $row = $tmp_row;
- break;
- }
- }
-
- // }}}
- // {{{ function &loadModule($module, $property = null, $phptype_specific = null)
-
- /**
- * loads a module
- *
- * @param string name of the module that should be loaded
- * (only used for error messages)
- * @param string name of the property into which the class will be loaded
- * @param bool if the class to load for the module is specific to the
- * phptype
- *
- * @return object on success a reference to the given module is returned
- * and on failure a PEAR error
- *
- * @access public
- */
- function &loadModule($module, $property = null, $phptype_specific = null)
- {
- if (!$property) {
- $property = strtolower($module);
- }
-
- if (!isset($this->{$property})) {
- $version = $phptype_specific;
- if ($phptype_specific !== false) {
- $version = true;
- $class_name = 'MDB2_Driver_'.$module.'_'.$this->phptype;
- $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
- }
- if ($phptype_specific === false
- || (!MDB2::classExists($class_name) && !MDB2::fileExists($file_name))
- ) {
- $version = false;
- $class_name = 'MDB2_'.$module;
- $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php';
- }
-
- $err = MDB2::loadClass($class_name, $this->getOption('debug'));
- if (PEAR::isError($err)) {
- return $err;
- }
- // load module in a specific version
- if ($version) {
- if (method_exists($class_name, 'getClassName')) {
- $class_name_new = call_user_func(array($class_name, 'getClassName'), $this->db_index);
- if ($class_name != $class_name_new) {
- $class_name = $class_name_new;
- $err = MDB2::loadClass($class_name, $this->getOption('debug'));
- if (PEAR::isError($err)) {
- return $err;
- }
- }
- }
- }
-
- if (!MDB2::classExists($class_name)) {
- $err =& $this->raiseError(MDB2_ERROR_LOADMODULE, null, null,
- "unable to load module '$module' into property '$property'", __FUNCTION__);
- return $err;
- }
- $this->{$property} = new $class_name($this->db_index);
- $this->modules[$module] =& $this->{$property};
- if ($version) {
- // this will be used in the connect method to determine if the module
- // needs to be loaded with a different version if the server
- // version changed in between connects
- $this->loaded_version_modules[] = $property;
- }
- }
-
- return $this->{$property};
- }
-
- // }}}
- // {{{ function __call($method, $params)
-
- /**
- * Calls a module method using the __call magic method
- *
- * @param string Method name.
- * @param array Arguments.
- *
- * @return mixed Returned value.
- */
- function __call($method, $params)
- {
- $module = null;
- if (preg_match('/^([a-z]+)([A-Z])(.*)$/', $method, $match)
- && isset($this->options['modules'][$match[1]])
- ) {
- $module = $this->options['modules'][$match[1]];
- $method = strtolower($match[2]).$match[3];
- if (!isset($this->modules[$module]) || !is_object($this->modules[$module])) {
- $result =& $this->loadModule($module);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- } else {
- foreach ($this->modules as $key => $foo) {
- if (is_object($this->modules[$key])
- && method_exists($this->modules[$key], $method)
- ) {
- $module = $key;
- break;
- }
- }
- }
- if (!is_null($module)) {
- return call_user_func_array(array(&$this->modules[$module], $method), $params);
- }
- trigger_error(sprintf('Call to undefined function: %s::%s().', get_class($this), $method), E_USER_ERROR);
- }
-
- // }}}
- // {{{ function beginTransaction($savepoint = null)
-
- /**
- * Start a transaction or set a savepoint.
- *
- * @param string name of a savepoint to set
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function beginTransaction($savepoint = null)
- {
- $this->debug('Starting transaction', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'transactions are not supported', __FUNCTION__);
- }
-
- // }}}
- // {{{ function commit($savepoint = null)
-
- /**
- * Commit the database changes done during a transaction that is in
- * progress or release a savepoint. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after committing the pending changes.
- *
- * @param string name of a savepoint to release
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function commit($savepoint = null)
- {
- $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'commiting transactions is not supported', __FUNCTION__);
- }
-
- // }}}
- // {{{ function rollback($savepoint = null)
-
- /**
- * Cancel any database changes done during a transaction or since a specific
- * savepoint that is in progress. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after canceling the pending changes.
- *
- * @param string name of a savepoint to rollback to
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function rollback($savepoint = null)
- {
- $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'rolling back transactions is not supported', __FUNCTION__);
- }
-
- // }}}
- // {{{ function inTransaction($ignore_nested = false)
-
- /**
- * If a transaction is currently open.
- *
- * @param bool if the nested transaction count should be ignored
- * @return int|bool - an integer with the nesting depth is returned if a
- * nested transaction is open
- * - true is returned for a normal open transaction
- * - false is returned if no transaction is open
- *
- * @access public
- */
- function inTransaction($ignore_nested = false)
- {
- if (!$ignore_nested && isset($this->nested_transaction_counter)) {
- return $this->nested_transaction_counter;
- }
- return $this->in_transaction;
- }
-
- // }}}
- // {{{ function setTransactionIsolation($isolation)
-
- /**
- * Set the transacton isolation level.
- *
- * @param string standard isolation level
- * READ UNCOMMITTED (allows dirty reads)
- * READ COMMITTED (prevents dirty reads)
- * REPEATABLE READ (prevents nonrepeatable reads)
- * SERIALIZABLE (prevents phantom reads)
- * @param array some transaction options:
- * 'wait' => 'WAIT' | 'NO WAIT'
- * 'rw' => 'READ WRITE' | 'READ ONLY'
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- * @since 2.1.1
- */
- function setTransactionIsolation($isolation, $options = array())
- {
- $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'isolation level setting is not supported', __FUNCTION__);
- }
-
- // }}}
- // {{{ function beginNestedTransaction($savepoint = false)
-
- /**
- * Start a nested transaction.
- *
- * @return mixed MDB2_OK on success/savepoint name, a MDB2 error on failure
- *
- * @access public
- * @since 2.1.1
- */
- function beginNestedTransaction()
- {
- if ($this->in_transaction) {
- ++$this->nested_transaction_counter;
- $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);
- if ($this->supports('savepoints') && $savepoint) {
- return $this->beginTransaction($savepoint);
- }
- return MDB2_OK;
- }
- $this->has_transaction_error = false;
- $result = $this->beginTransaction();
- $this->nested_transaction_counter = 1;
- return $result;
- }
-
- // }}}
- // {{{ function completeNestedTransaction($force_rollback = false, $release = false)
-
- /**
- * Finish a nested transaction by rolling back if an error occured or
- * committing otherwise.
- *
- * @param bool if the transaction should be rolled back regardless
- * even if no error was set within the nested transaction
- * @return mixed MDB_OK on commit/counter decrementing, false on rollback
- * and a MDB2 error on failure
- *
- * @access public
- * @since 2.1.1
- */
- function completeNestedTransaction($force_rollback = false)
- {
- if ($this->nested_transaction_counter > 1) {
- $savepoint = sprintf($this->options['savepoint_format'], $this->nested_transaction_counter);
- if ($this->supports('savepoints') && $savepoint) {
- if ($force_rollback || $this->has_transaction_error) {
- $result = $this->rollback($savepoint);
- if (!PEAR::isError($result)) {
- $result = false;
- $this->has_transaction_error = false;
- }
- } else {
- $result = $this->commit($savepoint);
- }
- } else {
- $result = MDB2_OK;
- }
- --$this->nested_transaction_counter;
- return $result;
- }
-
- $this->nested_transaction_counter = null;
- $result = MDB2_OK;
-
- // transaction has not yet been rolled back
- if ($this->in_transaction) {
- if ($force_rollback || $this->has_transaction_error) {
- $result = $this->rollback();
- if (!PEAR::isError($result)) {
- $result = false;
- }
- } else {
- $result = $this->commit();
- }
- }
- $this->has_transaction_error = false;
- return $result;
- }
-
- // }}}
- // {{{ function failNestedTransaction($error = null, $immediately = false)
-
- /**
- * Force setting nested transaction to failed.
- *
- * @param mixed value to return in getNestededTransactionError()
- * @param bool if the transaction should be rolled back immediately
- * @return bool MDB2_OK
- *
- * @access public
- * @since 2.1.1
- */
- function failNestedTransaction($error = null, $immediately = false)
- {
- if (is_null($error)) {
- $error = $this->has_transaction_error ? $this->has_transaction_error : true;
- } elseif (!$error) {
- $error = true;
- }
- $this->has_transaction_error = $error;
- if (!$immediately) {
- return MDB2_OK;
- }
- return $this->rollback();
- }
-
- // }}}
- // {{{ function getNestedTransactionError()
-
- /**
- * The first error that occured since the transaction start.
- *
- * @return MDB2_Error|bool MDB2 error object if an error occured or false.
- *
- * @access public
- * @since 2.1.1
- */
- function getNestedTransactionError()
- {
- return $this->has_transaction_error;
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to the database
- *
- * @return true on success, MDB2 Error Object on failure
- */
- function connect()
- {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ databaseExists()
-
- /**
- * check if given database name is exists?
- *
- * @param string $name name of the database that should be checked
- *
- * @return mixed true/false on success, a MDB2 error on failure
- * @access public
- */
- function databaseExists($name)
- {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ setCharset($charset, $connection = null)
-
- /**
- * Set the charset on the current connection
- *
- * @param string charset
- * @param resource connection handle
- *
- * @return true on success, MDB2 Error Object on failure
- */
- function setCharset($charset, $connection = null)
- {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function disconnect($force = true)
-
- /**
- * Log out and disconnect from the database.
- *
- * @param boolean $force whether the disconnect should be forced even if the
- * connection is opened persistently
- *
- * @return mixed true on success, false if not connected and error object on error
- *
- * @access public
- */
- function disconnect($force = true)
- {
- $this->connection = 0;
- $this->connected_dsn = array();
- $this->connected_database_name = '';
- $this->opened_persistent = null;
- $this->connected_server_info = '';
- $this->in_transaction = null;
- $this->nested_transaction_counter = null;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function setDatabase($name)
-
- /**
- * Select a different database
- *
- * @param string name of the database that should be selected
- *
- * @return string name of the database previously connected to
- *
- * @access public
- */
- function setDatabase($name)
- {
- $previous_database_name = (isset($this->database_name)) ? $this->database_name : '';
- $this->database_name = $name;
- if (!empty($this->connected_database_name) && ($this->connected_database_name != $this->database_name)) {
- $this->disconnect(false);
- }
- return $previous_database_name;
- }
-
- // }}}
- // {{{ function getDatabase()
-
- /**
- * Get the current database
- *
- * @return string name of the database
- *
- * @access public
- */
- function getDatabase()
- {
- return $this->database_name;
- }
-
- // }}}
- // {{{ function setDSN($dsn)
-
- /**
- * set the DSN
- *
- * @param mixed DSN string or array
- *
- * @return MDB2_OK
- *
- * @access public
- */
- function setDSN($dsn)
- {
- $dsn_default = $GLOBALS['_MDB2_dsninfo_default'];
- $dsn = MDB2::parseDSN($dsn);
- if (array_key_exists('database', $dsn)) {
- $this->database_name = $dsn['database'];
- unset($dsn['database']);
- }
- $this->dsn = array_merge($dsn_default, $dsn);
- return $this->disconnect(false);
- }
-
- // }}}
- // {{{ function getDSN($type = 'string', $hidepw = false)
-
- /**
- * return the DSN as a string
- *
- * @param string format to return ("array", "string")
- * @param string string to hide the password with
- *
- * @return mixed DSN in the chosen type
- *
- * @access public
- */
- function getDSN($type = 'string', $hidepw = false)
- {
- $dsn = array_merge($GLOBALS['_MDB2_dsninfo_default'], $this->dsn);
- $dsn['phptype'] = $this->phptype;
- $dsn['database'] = $this->database_name;
- if ($hidepw) {
- $dsn['password'] = $hidepw;
- }
- switch ($type) {
- // expand to include all possible options
- case 'string':
- $dsn = $dsn['phptype'].
- ($dsn['dbsyntax'] ? ('('.$dsn['dbsyntax'].')') : '').
- '://'.$dsn['username'].':'.
- $dsn['password'].'@'.$dsn['hostspec'].
- ($dsn['port'] ? (':'.$dsn['port']) : '').
- '/'.$dsn['database'];
- break;
- case 'array':
- default:
- break;
- }
- return $dsn;
- }
-
- // }}}
- // {{{ _isNewLinkSet()
-
- /**
- * Check if the 'new_link' option is set
- *
- * @return boolean
- *
- * @access protected
- */
- function _isNewLinkSet()
- {
- return (isset($this->dsn['new_link'])
- && ($this->dsn['new_link'] === true
- || (is_string($this->dsn['new_link']) && preg_match('/^true$/i', $this->dsn['new_link']))
- || (is_numeric($this->dsn['new_link']) && 0 != (int)$this->dsn['new_link'])
- )
- );
- }
-
- // }}}
- // {{{ function &standaloneQuery($query, $types = null, $is_manip = false)
-
- /**
- * execute a query as database administrator
- *
- * @param string the SQL query
- * @param mixed array that contains the types of the columns in
- * the result set
- * @param bool if the query is a manipulation query
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function &standaloneQuery($query, $types = null, $is_manip = false)
- {
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
-
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $result =& $this->_doQuery($query, $is_manip, $connection, false);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if ($is_manip) {
- $affected_rows = $this->_affectedRows($connection, $result);
- return $affected_rows;
- }
- $result =& $this->_wrapResult($result, $types, true, false, $limit, $offset);
- return $result;
- }
-
- // }}}
- // {{{ function _modifyQuery($query, $is_manip, $limit, $offset)
-
- /**
- * Changes a query string for various DBMS specific reasons
- *
- * @param string query to modify
- * @param bool if it is a DML query
- * @param int limit the number of rows
- * @param int start reading from given offset
- *
- * @return string modified query
- *
- * @access protected
- */
- function _modifyQuery($query, $is_manip, $limit, $offset)
- {
- return $query;
- }
-
- // }}}
- // {{{ function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
-
- /**
- * Execute a query
- * @param string query
- * @param bool if the query is a manipulation query
- * @param resource connection handle
- * @param string database name
- *
- * @return result or error object
- *
- * @access protected
- */
- function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
- {
- $this->last_query = $query;
- $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- $err =& $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- return $err;
- }
-
- // }}}
- // {{{ function _affectedRows($connection, $result = null)
-
- /**
- * Returns the number of rows affected
- *
- * @param resource result handle
- * @param resource connection handle
- *
- * @return mixed MDB2 Error Object or the number of rows affected
- *
- * @access private
- */
- function _affectedRows($connection, $result = null)
- {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function &exec($query)
-
- /**
- * Execute a manipulation query to the database and return the number of affected rows
- *
- * @param string the SQL query
- *
- * @return mixed number of affected rows on success, a MDB2 error on failure
- *
- * @access public
- */
- function &exec($query)
- {
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $query = $this->_modifyQuery($query, true, $limit, $offset);
-
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $result =& $this->_doQuery($query, true, $connection, $this->database_name);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $affectedRows = $this->_affectedRows($connection, $result);
- return $affectedRows;
- }
-
- // }}}
- // {{{ function &query($query, $types = null, $result_class = true, $result_wrap_class = false)
-
- /**
- * Send a query to the database and return any results
- *
- * @param string the SQL query
- * @param mixed array that contains the types of the columns in
- * the result set
- * @param mixed string which specifies which result class to use
- * @param mixed string which specifies which class to wrap results in
- *
- * @return mixed an MDB2_Result handle on success, a MDB2 error on failure
- *
- * @access public
- */
- function &query($query, $types = null, $result_class = true, $result_wrap_class = false)
- {
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $query = $this->_modifyQuery($query, false, $limit, $offset);
-
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $result =& $this->_doQuery($query, false, $connection, $this->database_name);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $result =& $this->_wrapResult($result, $types, $result_class, $result_wrap_class, $limit, $offset);
- return $result;
- }
-
- // }}}
- // {{{ function &_wrapResult($result, $types = array(), $result_class = true, $result_wrap_class = false, $limit = null, $offset = null)
-
- /**
- * wrap a result set into the correct class
- *
- * @param resource result handle
- * @param mixed array that contains the types of the columns in
- * the result set
- * @param mixed string which specifies which result class to use
- * @param mixed string which specifies which class to wrap results in
- * @param string number of rows to select
- * @param string first row to select
- *
- * @return mixed an MDB2_Result, a MDB2 error on failure
- *
- * @access protected
- */
- function &_wrapResult($result, $types = array(), $result_class = true,
- $result_wrap_class = false, $limit = null, $offset = null)
- {
- if ($types === true) {
- if ($this->supports('result_introspection')) {
- $this->loadModule('Reverse', null, true);
- $tableInfo = $this->reverse->tableInfo($result);
- if (PEAR::isError($tableInfo)) {
- return $tableInfo;
- }
- $types = array();
- foreach ($tableInfo as $field) {
- $types[] = $field['mdb2type'];
- }
- } else {
- $types = null;
- }
- }
-
- if ($result_class === true) {
- $result_class = $this->options['result_buffering']
- ? $this->options['buffered_result_class'] : $this->options['result_class'];
- }
-
- if ($result_class) {
- $class_name = sprintf($result_class, $this->phptype);
- if (!MDB2::classExists($class_name)) {
- $err =& $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'result class does not exist '.$class_name, __FUNCTION__);
- return $err;
- }
- $result =& new $class_name($this, $result, $limit, $offset);
- if (!MDB2::isResultCommon($result)) {
- $err =& $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'result class is not extended from MDB2_Result_Common', __FUNCTION__);
- return $err;
- }
- if (!empty($types)) {
- $err = $result->setResultTypes($types);
- if (PEAR::isError($err)) {
- $result->free();
- return $err;
- }
- }
- }
- if ($result_wrap_class === true) {
- $result_wrap_class = $this->options['result_wrap_class'];
- }
- if ($result_wrap_class) {
- if (!MDB2::classExists($result_wrap_class)) {
- $err =& $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'result wrap class does not exist '.$result_wrap_class, __FUNCTION__);
- return $err;
- }
- $result = new $result_wrap_class($result, $this->fetchmode);
- }
- return $result;
- }
-
- // }}}
- // {{{ function getServerVersion($native = false)
-
- /**
- * return version information about the server
- *
- * @param bool determines if the raw version string should be returned
- *
- * @return mixed array with version information or row string
- *
- * @access public
- */
- function getServerVersion($native = false)
- {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function setLimit($limit, $offset = null)
-
- /**
- * set the range of the next query
- *
- * @param string number of rows to select
- * @param string first row to select
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function setLimit($limit, $offset = null)
- {
- if (!$this->supports('limit_queries')) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'limit is not supported by this driver', __FUNCTION__);
- }
- $limit = (int)$limit;
- if ($limit < 0) {
- return $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'it was not specified a valid selected range row limit', __FUNCTION__);
- }
- $this->limit = $limit;
- if (!is_null($offset)) {
- $offset = (int)$offset;
- if ($offset < 0) {
- return $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'it was not specified a valid first selected range row', __FUNCTION__);
- }
- $this->offset = $offset;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function subSelect($query, $type = false)
-
- /**
- * simple subselect emulation: leaves the query untouched for all RDBMS
- * that support subselects
- *
- * @param string the SQL query for the subselect that may only
- * return a column
- * @param string determines type of the field
- *
- * @return string the query
- *
- * @access public
- */
- function subSelect($query, $type = false)
- {
- if ($this->supports('sub_selects') === true) {
- return $query;
- }
-
- if (!$this->supports('sub_selects')) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- $col = $this->queryCol($query, $type);
- if (PEAR::isError($col)) {
- return $col;
- }
- if (!is_array($col) || count($col) == 0) {
- return 'NULL';
- }
- if ($type) {
- $this->loadModule('Datatype', null, true);
- return $this->datatype->implodeArray($col, $type);
- }
- return implode(', ', $col);
- }
-
- // }}}
- // {{{ function replace($table, $fields)
-
- /**
- * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
- * query, except that if there is already a row in the table with the same
- * key field values, the old row is deleted before the new row is inserted.
- *
- * The REPLACE type of query does not make part of the SQL standards. Since
- * practically only MySQL and SQLite implement it natively, this type of
- * query isemulated through this method for other DBMS using standard types
- * of queries inside a transaction to assure the atomicity of the operation.
- *
- * @param string name of the table on which the REPLACE query will
- * be executed.
- * @param array associative array that describes the fields and the
- * values that will be inserted or updated in the specified table. The
- * indexes of the array are the names of all the fields of the table.
- * The values of the array are also associative arrays that describe
- * the values and other properties of the table fields.
- *
- * Here follows a list of field properties that need to be specified:
- *
- * value
- * Value to be assigned to the specified field. This value may be
- * of specified in database independent type format as this
- * function can perform the necessary datatype conversions.
- *
- * Default: this property is required unless the Null property is
- * set to 1.
- *
- * type
- * Name of the type of the field. Currently, all types MDB2
- * are supported except for clob and blob.
- *
- * Default: no type conversion
- *
- * null
- * bool property that indicates that the value for this field
- * should be set to null.
- *
- * The default value for fields missing in INSERT queries may be
- * specified the definition of a table. Often, the default value
- * is already null, but since the REPLACE may be emulated using
- * an UPDATE query, make sure that all fields of the table are
- * listed in this function argument array.
- *
- * Default: 0
- *
- * key
- * bool property that indicates that this field should be
- * handled as a primary key or at least as part of the compound
- * unique index of the table that will determine the row that will
- * updated if it exists or inserted a new row otherwise.
- *
- * This function will fail if no key field is specified or if the
- * value of a key field is set to null because fields that are
- * part of unique index they may not be null.
- *
- * Default: 0
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function replace($table, $fields)
- {
- if (!$this->supports('replace')) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'replace query is not supported', __FUNCTION__);
- }
- $count = count($fields);
- $condition = $values = array();
- for ($colnum = 0, reset($fields); $colnum < $count; next($fields), $colnum++) {
- $name = key($fields);
- if (isset($fields[$name]['null']) && $fields[$name]['null']) {
- $value = 'NULL';
- } else {
- $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
- $value = $this->quote($fields[$name]['value'], $type);
- }
- $values[$name] = $value;
- if (isset($fields[$name]['key']) && $fields[$name]['key']) {
- if ($value === 'NULL') {
- return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
- 'key value '.$name.' may not be NULL', __FUNCTION__);
- }
- $condition[] = $this->quoteIdentifier($name, true) . '=' . $value;
- }
- }
- if (empty($condition)) {
- return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
- 'not specified which fields are keys', __FUNCTION__);
- }
-
- $result = null;
- $in_transaction = $this->in_transaction;
- if (!$in_transaction && PEAR::isError($result = $this->beginTransaction())) {
- return $result;
- }
-
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $condition = ' WHERE '.implode(' AND ', $condition);
- $query = 'DELETE FROM ' . $this->quoteIdentifier($table, true) . $condition;
- $result =& $this->_doQuery($query, true, $connection);
- if (!PEAR::isError($result)) {
- $affected_rows = $this->_affectedRows($connection, $result);
- $insert = '';
- foreach ($values as $key => $value) {
- $insert .= ($insert?', ':'') . $this->quoteIdentifier($key, true);
- }
- $values = implode(', ', $values);
- $query = 'INSERT INTO '. $this->quoteIdentifier($table, true) . "($insert) VALUES ($values)";
- $result =& $this->_doQuery($query, true, $connection);
- if (!PEAR::isError($result)) {
- $affected_rows += $this->_affectedRows($connection, $result);;
- }
- }
-
- if (!$in_transaction) {
- if (PEAR::isError($result)) {
- $this->rollback();
- } else {
- $result = $this->commit();
- }
- }
-
- if (PEAR::isError($result)) {
- return $result;
- }
-
- return $affected_rows;
- }
-
- // }}}
- // {{{ function &prepare($query, $types = null, $result_types = null, $lobs = array())
-
- /**
- * Prepares a query for multiple execution with execute().
- * With some database backends, this is emulated.
- * prepare() requires a generic query as string like
- * 'INSERT INTO numbers VALUES(?,?)' or
- * 'INSERT INTO numbers VALUES(:foo,:bar)'.
- * The ? and :name and are placeholders which can be set using
- * bindParam() and the query can be sent off using the execute() method.
- * The allowed format for :name can be set with the 'bindname_format' option.
- *
- * @param string the query to prepare
- * @param mixed array that contains the types of the placeholders
- * @param mixed array that contains the types of the columns in
- * the result set or MDB2_PREPARE_RESULT, if set to
- * MDB2_PREPARE_MANIP the query is handled as a manipulation query
- * @param mixed key (field) value (parameter) pair for all lob placeholders
- *
- * @return mixed resource handle for the prepared query on success,
- * a MDB2 error on failure
- *
- * @access public
- * @see bindParam, execute
- */
- function &prepare($query, $types = null, $result_types = null, $lobs = array())
- {
- $is_manip = ($result_types === MDB2_PREPARE_MANIP);
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- $placeholder_type_guess = $placeholder_type = null;
- $question = '?';
- $colon = ':';
- $positions = array();
- $position = 0;
- while ($position < strlen($query)) {
- $q_position = strpos($query, $question, $position);
- $c_position = strpos($query, $colon, $position);
- if ($q_position && $c_position) {
- $p_position = min($q_position, $c_position);
- } elseif ($q_position) {
- $p_position = $q_position;
- } elseif ($c_position) {
- $p_position = $c_position;
- } else {
- break;
- }
- if (is_null($placeholder_type)) {
- $placeholder_type_guess = $query[$p_position];
- }
-
- $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
- if (PEAR::isError($new_pos)) {
- return $new_pos;
- }
- if ($new_pos != $position) {
- $position = $new_pos;
- continue; //evaluate again starting from the new position
- }
-
- if ($query[$position] == $placeholder_type_guess) {
- if (is_null($placeholder_type)) {
- $placeholder_type = $query[$p_position];
- $question = $colon = $placeholder_type;
- if (!empty($types) && is_array($types)) {
- if ($placeholder_type == ':') {
- if (is_int(key($types))) {
- $types_tmp = $types;
- $types = array();
- $count = -1;
- }
- } else {
- $types = array_values($types);
- }
- }
- }
- if ($placeholder_type == ':') {
- $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
- $parameter = preg_replace($regexp, '\\1', $query);
- if ($parameter === '') {
- $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'named parameter name must match "bindname_format" option', __FUNCTION__);
- return $err;
- }
- $positions[$p_position] = $parameter;
- $query = substr_replace($query, '?', $position, strlen($parameter)+1);
- // use parameter name in type array
- if (isset($count) && isset($types_tmp[++$count])) {
- $types[$parameter] = $types_tmp[$count];
- }
- } else {
- $positions[$p_position] = count($positions);
- }
- $position = $p_position + 1;
- } else {
- $position = $p_position;
- }
- }
- $class_name = 'MDB2_Statement_'.$this->phptype;
- $statement = null;
- $obj = new $class_name($this, $statement, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
- $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
- return $obj;
- }
-
- // }}}
- // {{{ function _skipDelimitedStrings($query, $position, $p_position)
-
- /**
- * Utility method, used by prepare() to avoid replacing placeholders within delimited strings.
- * Check if the placeholder is contained within a delimited string.
- * If so, skip it and advance the position, otherwise return the current position,
- * which is valid
- *
- * @param string $query
- * @param integer $position current string cursor position
- * @param integer $p_position placeholder position
- *
- * @return mixed integer $new_position on success
- * MDB2_Error on failure
- *
- * @access protected
- */
- function _skipDelimitedStrings($query, $position, $p_position)
- {
- $ignores = $this->string_quoting;
- $ignores[] = $this->identifier_quoting;
- $ignores = array_merge($ignores, $this->sql_comments);
-
- foreach ($ignores as $ignore) {
- if (!empty($ignore['start'])) {
- if (is_int($start_quote = strpos($query, $ignore['start'], $position)) && $start_quote < $p_position) {
- $end_quote = $start_quote;
- do {
- if (!is_int($end_quote = strpos($query, $ignore['end'], $end_quote + 1))) {
- if ($ignore['end'] === "\n") {
- $end_quote = strlen($query) - 1;
- } else {
- $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'query with an unterminated text string specified', __FUNCTION__);
- return $err;
- }
- }
- } while ($ignore['escape']
- && $end_quote-1 != $start_quote
- && $query[($end_quote - 1)] == $ignore['escape']
- && ( $ignore['escape_pattern'] !== $ignore['escape']
- || $query[($end_quote - 2)] != $ignore['escape'])
- );
-
- $position = $end_quote + 1;
- return $position;
- }
- }
- }
- return $position;
- }
-
- // }}}
- // {{{ function quote($value, $type = null, $quote = true)
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string text string value that is intended to be converted.
- * @param string type to which the value should be converted to
- * @param bool quote
- * @param bool escape wildcards
- *
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- *
- * @access public
- */
- function quote($value, $type = null, $quote = true, $escape_wildcards = false)
- {
- $result = $this->loadModule('Datatype', null, true);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- return $this->datatype->quote($value, $type, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ function getDeclaration($type, $name, $field)
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare
- * of the given type
- *
- * @param string type to which the value should be converted to
- * @param string name the field to be declared.
- * @param string definition of the field
- *
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- *
- * @access public
- */
- function getDeclaration($type, $name, $field)
- {
- $result = $this->loadModule('Datatype', null, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- return $this->datatype->getDeclaration($type, $name, $field);
- }
-
- // }}}
- // {{{ function compareDefinition($current, $previous)
-
- /**
- * Obtain an array of changes that may need to applied
- *
- * @param array new definition
- * @param array old definition
- *
- * @return array containing all changes that will need to be applied
- *
- * @access public
- */
- function compareDefinition($current, $previous)
- {
- $result = $this->loadModule('Datatype', null, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- return $this->datatype->compareDefinition($current, $previous);
- }
-
- // }}}
- // {{{ function supports($feature)
-
- /**
- * Tell whether a DB implementation or its backend extension
- * supports a given feature.
- *
- * @param string name of the feature (see the MDB2 class doc)
- *
- * @return bool|string if this DB implementation supports a given feature
- * false means no, true means native,
- * 'emulated' means emulated
- *
- * @access public
- */
- function supports($feature)
- {
- if (array_key_exists($feature, $this->supported)) {
- return $this->supported[$feature];
- }
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- "unknown support feature $feature", __FUNCTION__);
- }
-
- // }}}
- // {{{ function getSequenceName($sqn)
-
- /**
- * adds sequence name formatting to a sequence name
- *
- * @param string name of the sequence
- *
- * @return string formatted sequence name
- *
- * @access public
- */
- function getSequenceName($sqn)
- {
- return sprintf($this->options['seqname_format'],
- preg_replace('/[^a-z0-9_\-\$.]/i', '_', $sqn));
- }
-
- // }}}
- // {{{ function getIndexName($idx)
-
- /**
- * adds index name formatting to a index name
- *
- * @param string name of the index
- *
- * @return string formatted index name
- *
- * @access public
- */
- function getIndexName($idx)
- {
- return sprintf($this->options['idxname_format'],
- preg_replace('/[^a-z0-9_\-\$.]/i', '_', $idx));
- }
-
- // }}}
- // {{{ function nextID($seq_name, $ondemand = true)
-
- /**
- * Returns the next free id of a sequence
- *
- * @param string name of the sequence
- * @param bool when true missing sequences are automatic created
- *
- * @return mixed MDB2 Error Object or id
- *
- * @access public
- */
- function nextID($seq_name, $ondemand = true)
- {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function lastInsertID($table = null, $field = null)
-
- /**
- * Returns the autoincrement ID if supported or $id or fetches the current
- * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
- *
- * @param string name of the table into which a new row was inserted
- * @param string name of the field into which a new row was inserted
- *
- * @return mixed MDB2 Error Object or id
- *
- * @access public
- */
- function lastInsertID($table = null, $field = null)
- {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function currID($seq_name)
-
- /**
- * Returns the current id of a sequence
- *
- * @param string name of the sequence
- *
- * @return mixed MDB2 Error Object or id
- *
- * @access public
- */
- function currID($seq_name)
- {
- $this->warnings[] = 'database does not support getting current
- sequence value, the sequence value was incremented';
- return $this->nextID($seq_name);
- }
-
- // }}}
- // {{{ function queryOne($query, $type = null, $colnum = 0)
-
- /**
- * Execute the specified query, fetch the value from the first column of
- * the first row of the result set and then frees
- * the result set.
- *
- * @param string $query the SELECT query statement to be executed.
- * @param string $type optional argument that specifies the expected
- * datatype of the result set field, so that an eventual
- * conversion may be performed. The default datatype is
- * text, meaning that no conversion is performed
- * @param mixed $colnum the column number (or name) to fetch
- *
- * @return mixed MDB2_OK or field value on success, a MDB2 error on failure
- *
- * @access public
- */
- function queryOne($query, $type = null, $colnum = 0)
- {
- $result = $this->query($query, $type);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $one = $result->fetchOne($colnum);
- $result->free();
- return $one;
- }
-
- // }}}
- // {{{ function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
-
- /**
- * Execute the specified query, fetch the values from the first
- * row of the result set into an array and then frees
- * the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param array optional array argument that specifies a list of
- * expected datatypes of the result set columns, so that the eventual
- * conversions may be performed. The default list of datatypes is
- * empty, meaning that no conversion is performed.
- * @param int how the array data should be indexed
- *
- * @return mixed MDB2_OK or data array on success, a MDB2 error on failure
- *
- * @access public
- */
- function queryRow($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
- {
- $result = $this->query($query, $types);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $row = $result->fetchRow($fetchmode);
- $result->free();
- return $row;
- }
-
- // }}}
- // {{{ function queryCol($query, $type = null, $colnum = 0)
-
- /**
- * Execute the specified query, fetch the value from the first column of
- * each row of the result set into an array and then frees the result set.
- *
- * @param string $query the SELECT query statement to be executed.
- * @param string $type optional argument that specifies the expected
- * datatype of the result set field, so that an eventual
- * conversion may be performed. The default datatype is text,
- * meaning that no conversion is performed
- * @param mixed $colnum the column number (or name) to fetch
- *
- * @return mixed MDB2_OK or data array on success, a MDB2 error on failure
- * @access public
- */
- function queryCol($query, $type = null, $colnum = 0)
- {
- $result = $this->query($query, $type);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $col = $result->fetchCol($colnum);
- $result->free();
- return $col;
- }
-
- // }}}
- // {{{ function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)
-
- /**
- * Execute the specified query, fetch all the rows of the result set into
- * a two dimensional array and then frees the result set.
- *
- * @param string the SELECT query statement to be executed.
- * @param array optional array argument that specifies a list of
- * expected datatypes of the result set columns, so that the eventual
- * conversions may be performed. The default list of datatypes is
- * empty, meaning that no conversion is performed.
- * @param int how the array data should be indexed
- * @param bool if set to true, the $all will have the first
- * column as its first dimension
- * @param bool 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 bool 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 mixed MDB2_OK or data array on success, a MDB2 error on failure
- *
- * @access public
- */
- function queryAll($query, $types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT,
- $rekey = false, $force_array = false, $group = false)
- {
- $result = $this->query($query, $types);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $all = $result->fetchAll($fetchmode, $rekey, $force_array, $group);
- $result->free();
- return $all;
- }
-
- // }}}
-}
-
-// }}}
-// {{{ class MDB2_Result
-
-/**
- * The dummy class that all user space result classes should extend from
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Result
-{
-}
-
-// }}}
-// {{{ class MDB2_Result_Common extends MDB2_Result
-
-/**
- * The common result class for MDB2 result objects
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Result_Common extends MDB2_Result
-{
- // {{{ Variables (Properties)
-
- var $db;
- var $result;
- var $rownum = -1;
- var $types = array();
- var $values = array();
- var $offset;
- var $offset_count = 0;
- var $limit;
- var $column_names;
-
- // }}}
- // {{{ constructor: function __construct(&$db, &$result, $limit = 0, $offset = 0)
-
- /**
- * Constructor
- */
- function __construct(&$db, &$result, $limit = 0, $offset = 0)
- {
- $this->db =& $db;
- $this->result =& $result;
- $this->offset = $offset;
- $this->limit = max(0, $limit - 1);
- }
-
- // }}}
- // {{{ function MDB2_Result_Common(&$db, &$result, $limit = 0, $offset = 0)
-
- /**
- * PHP 4 Constructor
- */
- function MDB2_Result_Common(&$db, &$result, $limit = 0, $offset = 0)
- {
- $this->__construct($db, $result, $limit, $offset);
- }
-
- // }}}
- // {{{ function setResultTypes($types)
-
- /**
- * Define the list of types to be associated with the columns of a given
- * result set.
- *
- * This function may be called before invoking fetchRow(), fetchOne(),
- * fetchCol() and fetchAll() so that the necessary data type
- * conversions are performed on the data to be retrieved by them. If this
- * function is not called, the type of all result set columns is assumed
- * to be text, thus leading to not perform any conversions.
- *
- * @param array variable that lists the
- * data types to be expected in the result set columns. If this array
- * contains less types than the number of columns that are returned
- * in the result set, the remaining columns are assumed to be of the
- * type text. Currently, the types clob and blob are not fully
- * supported.
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function setResultTypes($types)
- {
- $load = $this->db->loadModule('Datatype', null, true);
- if (PEAR::isError($load)) {
- return $load;
- }
- $types = $this->db->datatype->checkResultTypes($types);
- if (PEAR::isError($types)) {
- return $types;
- }
- $this->types = $types;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function seek($rownum = 0)
-
- /**
- * Seek to a specific row in a result set
- *
- * @param int number of the row where the data can be found
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function seek($rownum = 0)
- {
- $target_rownum = $rownum - 1;
- if ($this->rownum > $target_rownum) {
- return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'seeking to previous rows not implemented', __FUNCTION__);
- }
- while ($this->rownum < $target_rownum) {
- $this->fetchRow();
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
-
- /**
- * Fetch and return a row of data
- *
- * @param int how the array data should be indexed
- * @param int number of the row where the data can be found
- *
- * @return int data array on success, a MDB2 error on failure
- *
- * @access public
- */
- function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
- {
- $err =& $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- return $err;
- }
-
- // }}}
- // {{{ function fetchOne($colnum = 0)
-
- /**
- * fetch single column from the next row from a result set
- *
- * @param int|string the column number (or name) to fetch
- * @param int number of the row where the data can be found
- *
- * @return string data on success, a MDB2 error on failure
- * @access public
- */
- function fetchOne($colnum = 0, $rownum = null)
- {
- $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;
- $row = $this->fetchRow($fetchmode, $rownum);
- if (!is_array($row) || PEAR::isError($row)) {
- return $row;
- }
- if (!array_key_exists($colnum, $row)) {
- return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,
- 'column is not defined in the result set: '.$colnum, __FUNCTION__);
- }
- return $row[$colnum];
- }
-
- // }}}
- // {{{ function fetchCol($colnum = 0)
-
- /**
- * Fetch and return a column from the current row pointer position
- *
- * @param int|string the column number (or name) to fetch
- *
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function fetchCol($colnum = 0)
- {
- $column = array();
- $fetchmode = is_numeric($colnum) ? MDB2_FETCHMODE_ORDERED : MDB2_FETCHMODE_ASSOC;
- $row = $this->fetchRow($fetchmode);
- if (is_array($row)) {
- if (!array_key_exists($colnum, $row)) {
- return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,
- 'column is not defined in the result set: '.$colnum, __FUNCTION__);
- }
- do {
- $column[] = $row[$colnum];
- } while (is_array($row = $this->fetchRow($fetchmode)));
- }
- if (PEAR::isError($row)) {
- return $row;
- }
- return $column;
- }
-
- // }}}
- // {{{ function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false, $force_array = false, $group = false)
-
- /**
- * Fetch and return all rows from the current row pointer position
- *
- * @param int $fetchmode the fetch mode to use:
- * + MDB2_FETCHMODE_ORDERED
- * + MDB2_FETCHMODE_ASSOC
- * + MDB2_FETCHMODE_ORDERED | MDB2_FETCHMODE_FLIPPED
- * + MDB2_FETCHMODE_ASSOC | MDB2_FETCHMODE_FLIPPED
- * @param bool if set to true, the $all will have the first
- * column as its first dimension
- * @param bool 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 bool 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 mixed data array on success, a MDB2 error on failure
- *
- * @access public
- * @see getAssoc()
- */
- function fetchAll($fetchmode = MDB2_FETCHMODE_DEFAULT, $rekey = false,
- $force_array = false, $group = false)
- {
- $all = array();
- $row = $this->fetchRow($fetchmode);
- if (PEAR::isError($row)) {
- return $row;
- } elseif (!$row) {
- return $all;
- }
-
- $shift_array = $rekey ? false : null;
- if (!is_null($shift_array)) {
- if (is_object($row)) {
- $colnum = count(get_object_vars($row));
- } else {
- $colnum = count($row);
- }
- if ($colnum < 2) {
- return $this->db->raiseError(MDB2_ERROR_TRUNCATED, null, null,
- 'rekey feature requires atleast 2 column', __FUNCTION__);
- }
- $shift_array = (!$force_array && $colnum == 2);
- }
-
- if ($rekey) {
- do {
- if (is_object($row)) {
- $arr = get_object_vars($row);
- $key = reset($arr);
- unset($row->{$key});
- } else {
- if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
- $key = reset($row);
- unset($row[key($row)]);
- } else {
- $key = array_shift($row);
- }
- if ($shift_array) {
- $row = array_shift($row);
- }
- }
- if ($group) {
- $all[$key][] = $row;
- } else {
- $all[$key] = $row;
- }
- } while (($row = $this->fetchRow($fetchmode)));
- } elseif ($fetchmode & MDB2_FETCHMODE_FLIPPED) {
- do {
- foreach ($row as $key => $val) {
- $all[$key][] = $val;
- }
- } while (($row = $this->fetchRow($fetchmode)));
- } else {
- do {
- $all[] = $row;
- } while (($row = $this->fetchRow($fetchmode)));
- }
-
- return $all;
- }
-
- // }}}
- // {{{ function rowCount()
- /**
- * Returns the actual row number that was last fetched (count from 0)
- * @return int
- *
- * @access public
- */
- function rowCount()
- {
- return $this->rownum + 1;
- }
-
- // }}}
- // {{{ function numRows()
-
- /**
- * Returns the number of rows in a result object
- *
- * @return mixed MDB2 Error Object or the number of rows
- *
- * @access public
- */
- function numRows()
- {
- return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function nextResult()
-
- /**
- * Move the internal result pointer to the next available result
- *
- * @return true on success, false if there is no more result set or an error object on failure
- *
- * @access public
- */
- function nextResult()
- {
- return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function getColumnNames()
-
- /**
- * Retrieve the names of columns returned by the DBMS in a query result or
- * from the cache.
- *
- * @param bool If set to true the values are the column names,
- * otherwise the names of the columns are the keys.
- * @return mixed Array variable that holds the names of columns or an
- * MDB2 error on failure.
- * Some DBMS may not return any columns when the result set
- * does not contain any rows.
- *
- * @access public
- */
- function getColumnNames($flip = false)
- {
- if (!isset($this->column_names)) {
- $result = $this->_getColumnNames();
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->column_names = $result;
- }
- if ($flip) {
- return array_flip($this->column_names);
- }
- return $this->column_names;
- }
-
- // }}}
- // {{{ function _getColumnNames()
-
- /**
- * Retrieve the names of columns returned by the DBMS in a query result.
- *
- * @return mixed Array variable that holds the names of columns as keys
- * or an MDB2 error on failure.
- * Some DBMS may not return any columns when the result set
- * does not contain any rows.
- *
- * @access private
- */
- function _getColumnNames()
- {
- return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function numCols()
-
- /**
- * Count the number of columns returned by the DBMS in a query result.
- *
- * @return mixed integer value with the number of columns, a MDB2 error
- * on failure
- *
- * @access public
- */
- function numCols()
- {
- return $this->db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ function getResource()
-
- /**
- * return the resource associated with the result object
- *
- * @return resource
- *
- * @access public
- */
- function getResource()
- {
- return $this->result;
- }
-
- // }}}
- // {{{ function bindColumn($column, &$value, $type = null)
-
- /**
- * Set bind variable to a column.
- *
- * @param int column number or name
- * @param mixed variable reference
- * @param string specifies the type of the field
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function bindColumn($column, &$value, $type = null)
- {
- if (!is_numeric($column)) {
- $column_names = $this->getColumnNames();
- if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($this->db->options['field_case'] == CASE_LOWER) {
- $column = strtolower($column);
- } else {
- $column = strtoupper($column);
- }
- }
- $column = $column_names[$column];
- }
- $this->values[$column] =& $value;
- if (!is_null($type)) {
- $this->types[$column] = $type;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function _assignBindColumns($row)
-
- /**
- * Bind a variable to a value in the result row.
- *
- * @param array row data
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access private
- */
- function _assignBindColumns($row)
- {
- $row = array_values($row);
- foreach ($row as $column => $value) {
- if (array_key_exists($column, $this->values)) {
- $this->values[$column] = $value;
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function free()
-
- /**
- * Free the internal resources associated with result.
- *
- * @return bool true on success, false if result is invalid
- *
- * @access public
- */
- function free()
- {
- $this->result = false;
- return MDB2_OK;
- }
-
- // }}}
-}
-
-// }}}
-// {{{ class MDB2_Row
-
-/**
- * The simple class that accepts row data as an array
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Row
-{
- // {{{ constructor: function __construct(&$row)
-
- /**
- * constructor
- *
- * @param resource row data as array
- */
- function __construct(&$row)
- {
- foreach ($row as $key => $value) {
- $this->$key = &$row[$key];
- }
- }
-
- // }}}
- // {{{ function MDB2_Row(&$row)
-
- /**
- * PHP 4 Constructor
- *
- * @param resource row data as array
- */
- function MDB2_Row(&$row)
- {
- $this->__construct($row);
- }
-
- // }}}
-}
-
-// }}}
-// {{{ class MDB2_Statement_Common
-
-/**
- * The common statement class for MDB2 statement objects
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Statement_Common
-{
- // {{{ Variables (Properties)
-
- var $db;
- var $statement;
- var $query;
- var $result_types;
- var $types;
- var $values = array();
- var $limit;
- var $offset;
- var $is_manip;
-
- // }}}
- // {{{ constructor: function __construct(&$db, &$statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
-
- /**
- * Constructor
- */
- function __construct(&$db, &$statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
- {
- $this->db =& $db;
- $this->statement =& $statement;
- $this->positions = $positions;
- $this->query = $query;
- $this->types = (array)$types;
- $this->result_types = (array)$result_types;
- $this->limit = $limit;
- $this->is_manip = $is_manip;
- $this->offset = $offset;
- }
-
- // }}}
- // {{{ function MDB2_Statement_Common(&$db, &$statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
-
- /**
- * PHP 4 Constructor
- */
- function MDB2_Statement_Common(&$db, &$statement, $positions, $query, $types, $result_types, $is_manip = false, $limit = null, $offset = null)
- {
- $this->__construct($db, $statement, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
- }
-
- // }}}
- // {{{ function bindValue($parameter, &$value, $type = null)
-
- /**
- * Set the value of a parameter of a prepared query.
- *
- * @param int the order number of the parameter in the query
- * statement. The order number of the first parameter is 1.
- * @param mixed value that is meant to be assigned to specified
- * parameter. The type of the value depends on the $type argument.
- * @param string specifies the type of the field
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function bindValue($parameter, $value, $type = null)
- {
- if (!is_numeric($parameter)) {
- $parameter = preg_replace('/^:(.*)$/', '\\1', $parameter);
- }
- if (!in_array($parameter, $this->positions)) {
- return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
- }
- $this->values[$parameter] = $value;
- if (!is_null($type)) {
- $this->types[$parameter] = $type;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function bindValueArray($values, $types = null)
-
- /**
- * Set the values of multiple a parameter of a prepared query in bulk.
- *
- * @param array specifies all necessary information
- * for bindValue() the array elements must use keys corresponding to
- * the number of the position of the parameter.
- * @param array specifies the types of the fields
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- * @see bindParam()
- */
- function bindValueArray($values, $types = null)
- {
- $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);
- $parameters = array_keys($values);
- foreach ($parameters as $key => $parameter) {
- $this->db->pushErrorHandling(PEAR_ERROR_RETURN);
- $this->db->expectError(MDB2_ERROR_NOT_FOUND);
- $err = $this->bindValue($parameter, $values[$parameter], $types[$key]);
- $this->db->popExpect();
- $this->db->popErrorHandling();
- if (PEAR::isError($err)) {
- if ($err->getCode() == MDB2_ERROR_NOT_FOUND) {
- //ignore (extra value for missing placeholder)
- continue;
- }
- return $err;
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function bindParam($parameter, &$value, $type = null)
-
- /**
- * Bind a variable to a parameter of a prepared query.
- *
- * @param int the order number of the parameter in the query
- * statement. The order number of the first parameter is 1.
- * @param mixed variable that is meant to be bound to specified
- * parameter. The type of the value depends on the $type argument.
- * @param string specifies the type of the field
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function bindParam($parameter, &$value, $type = null)
- {
- if (!is_numeric($parameter)) {
- $parameter = preg_replace('/^:(.*)$/', '\\1', $parameter);
- }
- if (!in_array($parameter, $this->positions)) {
- return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
- }
- $this->values[$parameter] =& $value;
- if (!is_null($type)) {
- $this->types[$parameter] = $type;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function bindParamArray(&$values, $types = null)
-
- /**
- * Bind the variables of multiple a parameter of a prepared query in bulk.
- *
- * @param array specifies all necessary information
- * for bindParam() the array elements must use keys corresponding to
- * the number of the position of the parameter.
- * @param array specifies the types of the fields
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- * @see bindParam()
- */
- function bindParamArray(&$values, $types = null)
- {
- $types = is_array($types) ? array_values($types) : array_fill(0, count($values), null);
- $parameters = array_keys($values);
- foreach ($parameters as $key => $parameter) {
- $err = $this->bindParam($parameter, $values[$parameter], $types[$key]);
- if (PEAR::isError($err)) {
- return $err;
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function &execute($values = null, $result_class = true, $result_wrap_class = false)
-
- /**
- * Execute a prepared query statement.
- *
- * @param array specifies all necessary information
- * for bindParam() the array elements must use keys corresponding
- * to the number of the position of the parameter.
- * @param mixed specifies which result class to use
- * @param mixed specifies which class to wrap results in
- *
- * @return mixed MDB2_Result or integer (affected rows) on success,
- * a MDB2 error on failure
- * @access public
- */
- function &execute($values = null, $result_class = true, $result_wrap_class = false)
- {
- if (is_null($this->positions)) {
- return $this->db->raiseError(MDB2_ERROR, null, null,
- 'Prepared statement has already been freed', __FUNCTION__);
- }
-
- $values = (array)$values;
- if (!empty($values)) {
- $err = $this->bindValueArray($values);
- if (PEAR::isError($err)) {
- return $this->db->raiseError(MDB2_ERROR, null, null,
- 'Binding Values failed with message: ' . $err->getMessage(), __FUNCTION__);
- }
- }
- $result =& $this->_execute($result_class, $result_wrap_class);
- return $result;
- }
-
- // }}}
- // {{{ function &_execute($result_class = true, $result_wrap_class = false)
-
- /**
- * Execute a prepared query statement helper method.
- *
- * @param mixed specifies which result class to use
- * @param mixed specifies which class to wrap results in
- *
- * @return mixed MDB2_Result or integer (affected rows) on success,
- * a MDB2 error on failure
- * @access private
- */
- function &_execute($result_class = true, $result_wrap_class = false)
- {
- $this->last_query = $this->query;
- $query = '';
- $last_position = 0;
- foreach ($this->positions as $current_position => $parameter) {
- if (!array_key_exists($parameter, $this->values)) {
- return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
- }
- $value = $this->values[$parameter];
- $query.= substr($this->query, $last_position, $current_position - $last_position);
- if (!isset($value)) {
- $value_quoted = 'NULL';
- } else {
- $type = !empty($this->types[$parameter]) ? $this->types[$parameter] : null;
- $value_quoted = $this->db->quote($value, $type);
- if (PEAR::isError($value_quoted)) {
- return $value_quoted;
- }
- }
- $query.= $value_quoted;
- $last_position = $current_position + 1;
- }
- $query.= substr($this->query, $last_position);
-
- $this->db->offset = $this->offset;
- $this->db->limit = $this->limit;
- if ($this->is_manip) {
- $result = $this->db->exec($query);
- } else {
- $result =& $this->db->query($query, $this->result_types, $result_class, $result_wrap_class);
- }
- return $result;
- }
-
- // }}}
- // {{{ function free()
-
- /**
- * Release resources allocated for the specified prepared query.
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function free()
- {
- if (is_null($this->positions)) {
- return $this->db->raiseError(MDB2_ERROR, null, null,
- 'Prepared statement has already been freed', __FUNCTION__);
- }
-
- $this->statement = null;
- $this->positions = null;
- $this->query = null;
- $this->types = null;
- $this->result_types = null;
- $this->limit = null;
- $this->is_manip = null;
- $this->offset = null;
- $this->values = null;
-
- return MDB2_OK;
- }
-
- // }}}
-}
-
-// }}}
-// {{{ class MDB2_Module_Common
-
-/**
- * The common modules class for MDB2 module objects
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Module_Common
-{
- // {{{ Variables (Properties)
-
- /**
- * contains the key to the global MDB2 instance array of the associated
- * MDB2 instance
- *
- * @var int
- * @access protected
- */
- var $db_index;
-
- // }}}
- // {{{ constructor: function __construct($db_index)
-
- /**
- * Constructor
- */
- function __construct($db_index)
- {
- $this->db_index = $db_index;
- }
-
- // }}}
- // {{{ function MDB2_Module_Common($db_index)
-
- /**
- * PHP 4 Constructor
- */
- function MDB2_Module_Common($db_index)
- {
- $this->__construct($db_index);
- }
-
- // }}}
- // {{{ function &getDBInstance()
-
- /**
- * Get the instance of MDB2 associated with the module instance
- *
- * @return object MDB2 instance or a MDB2 error on failure
- *
- * @access public
- */
- function &getDBInstance()
- {
- if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- $result =& $GLOBALS['_MDB2_databases'][$this->db_index];
- } else {
- $result =& MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'could not find MDB2 instance');
- }
- return $result;
- }
-
- // }}}
-}
-
-// }}}
-// {{{ function MDB2_closeOpenTransactions()
-
-/**
- * Close any open transactions form persistent connections
- *
- * @return void
- *
- * @access public
- */
-
-function MDB2_closeOpenTransactions()
-{
- reset($GLOBALS['_MDB2_databases']);
- while (next($GLOBALS['_MDB2_databases'])) {
- $key = key($GLOBALS['_MDB2_databases']);
- if ($GLOBALS['_MDB2_databases'][$key]->opened_persistent
- && $GLOBALS['_MDB2_databases'][$key]->in_transaction
- ) {
- $GLOBALS['_MDB2_databases'][$key]->rollback();
- }
- }
-}
-
-// }}}
-// {{{ function MDB2_defaultDebugOutput(&$db, $scope, $message, $is_manip = null)
-
-/**
- * default debug output handler
- *
- * @param object reference to an MDB2 database object
- * @param string usually the method name that triggered the debug call:
- * for example 'query', 'prepare', 'execute', 'parameters',
- * 'beginTransaction', 'commit', 'rollback'
- * @param string message that should be appended to the debug variable
- * @param array contains context information about the debug() call
- * common keys are: is_manip, time, result etc.
- *
- * @return void|string optionally return a modified message, this allows
- * rewriting a query before being issued or prepared
- *
- * @access public
- */
-function MDB2_defaultDebugOutput(&$db, $scope, $message, $context = array())
-{
- $db->debug_output.= $scope.'('.$db->db_index.'): ';
- $db->debug_output.= $message.$db->getOption('log_line_break');
- return $message;
-}
-
-// }}}
-?> \ No newline at end of file
diff --git a/inc/MDB2/Date.php b/inc/MDB2/Date.php
deleted file mode 100644
index ce846543a50..00000000000
--- a/inc/MDB2/Date.php
+++ /dev/null
@@ -1,183 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Date.php,v 1.10 2006/03/01 12:15:32 lsmith Exp $
-//
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-
-/**
- * Several methods to convert the MDB2 native timestamp format (ISO based)
- * to and from data structures that are convenient to worth with in side of php.
- * For more complex date arithmetic please take a look at the Date package in PEAR
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Date
-{
- // {{{ mdbNow()
-
- /**
- * return the current datetime
- *
- * @return string current datetime in the MDB2 format
- * @access public
- */
- function mdbNow()
- {
- return date('Y-m-d H:i:s');
- }
- // }}}
-
- // {{{ mdbToday()
-
- /**
- * return the current date
- *
- * @return string current date in the MDB2 format
- * @access public
- */
- function mdbToday()
- {
- return date('Y-m-d');
- }
- // }}}
-
- // {{{ mdbTime()
-
- /**
- * return the current time
- *
- * @return string current time in the MDB2 format
- * @access public
- */
- function mdbTime()
- {
- return date('H:i:s');
- }
- // }}}
-
- // {{{ date2Mdbstamp()
-
- /**
- * convert a date into a MDB2 timestamp
- *
- * @param int hour of the date
- * @param int minute of the date
- * @param int second of the date
- * @param int month of the date
- * @param int day of the date
- * @param int year of the date
- *
- * @return string a valid MDB2 timestamp
- * @access public
- */
- function date2Mdbstamp($hour = null, $minute = null, $second = null,
- $month = null, $day = null, $year = null)
- {
- return MDB2_Date::unix2Mdbstamp(mktime($hour, $minute, $second, $month, $day, $year, -1));
- }
- // }}}
-
- // {{{ unix2Mdbstamp()
-
- /**
- * convert a unix timestamp into a MDB2 timestamp
- *
- * @param int a valid unix timestamp
- *
- * @return string a valid MDB2 timestamp
- * @access public
- */
- function unix2Mdbstamp($unix_timestamp)
- {
- return date('Y-m-d H:i:s', $unix_timestamp);
- }
- // }}}
-
- // {{{ mdbstamp2Unix()
-
- /**
- * convert a MDB2 timestamp into a unix timestamp
- *
- * @param int a valid MDB2 timestamp
- * @return string unix timestamp with the time stored in the MDB2 format
- *
- * @access public
- */
- function mdbstamp2Unix($mdb_timestamp)
- {
- $arr = MDB2_Date::mdbstamp2Date($mdb_timestamp);
-
- return mktime($arr['hour'], $arr['minute'], $arr['second'], $arr['month'], $arr['day'], $arr['year'], -1);
- }
- // }}}
-
- // {{{ mdbstamp2Date()
-
- /**
- * convert a MDB2 timestamp into an array containing all
- * values necessary to pass to php's date() function
- *
- * @param int a valid MDB2 timestamp
- *
- * @return array with the time split
- * @access public
- */
- function mdbstamp2Date($mdb_timestamp)
- {
- list($arr['year'], $arr['month'], $arr['day'], $arr['hour'], $arr['minute'], $arr['second']) =
- sscanf($mdb_timestamp, "%04u-%02u-%02u %02u:%02u:%02u");
- return $arr;
- }
- // }}}
-}
-
-?>
diff --git a/inc/MDB2/Driver/Datatype/Common.php b/inc/MDB2/Driver/Datatype/Common.php
deleted file mode 100644
index 750dbb24772..00000000000
--- a/inc/MDB2/Driver/Datatype/Common.php
+++ /dev/null
@@ -1,1824 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Common.php,v 1.139 2008/12/04 11:50:42 afz Exp $
-
-oc_require_once('MDB2/LOB.php');
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-
-/**
- * MDB2_Driver_Common: Base class that is extended by each MDB2 driver
- *
- * To load this module in the MDB2 object:
- * $mdb->loadModule('Datatype');
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Datatype_Common extends MDB2_Module_Common
-{
- var $valid_default_values = array(
- 'text' => '',
- 'boolean' => true,
- 'integer' => 0,
- 'decimal' => 0.0,
- 'float' => 0.0,
- 'timestamp' => '1970-01-01 00:00:00',
- 'time' => '00:00:00',
- 'date' => '1970-01-01',
- 'clob' => '',
- 'blob' => '',
- );
-
- /**
- * contains all LOB objects created with this MDB2 instance
- * @var array
- * @access protected
- */
- var $lobs = array();
-
- // }}}
- // {{{ getValidTypes()
-
- /**
- * Get the list of valid types
- *
- * This function returns an array of valid types as keys with the values
- * being possible default values for all native datatypes and mapped types
- * for custom datatypes.
- *
- * @return mixed array on success, a MDB2 error on failure
- * @access public
- */
- function getValidTypes()
- {
- $types = $this->valid_default_values;
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (!empty($db->options['datatype_map'])) {
- foreach ($db->options['datatype_map'] as $type => $mapped_type) {
- if (array_key_exists($mapped_type, $types)) {
- $types[$type] = $types[$mapped_type];
- } elseif (!empty($db->options['datatype_map_callback'][$type])) {
- $parameter = array('type' => $type, 'mapped_type' => $mapped_type);
- $default = call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
- $types[$type] = $default;
- }
- }
- }
- return $types;
- }
-
- // }}}
- // {{{ checkResultTypes()
-
- /**
- * Define the list of types to be associated with the columns of a given
- * result set.
- *
- * This function may be called before invoking fetchRow(), fetchOne()
- * fetchCole() and fetchAll() so that the necessary data type
- * conversions are performed on the data to be retrieved by them. If this
- * function is not called, the type of all result set columns is assumed
- * to be text, thus leading to not perform any conversions.
- *
- * @param array $types array variable that lists the
- * data types to be expected in the result set columns. If this array
- * contains less types than the number of columns that are returned
- * in the result set, the remaining columns are assumed to be of the
- * type text. Currently, the types clob and blob are not fully
- * supported.
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function checkResultTypes($types)
- {
- $types = is_array($types) ? $types : array($types);
- foreach ($types as $key => $type) {
- if (!isset($this->valid_default_values[$type])) {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (empty($db->options['datatype_map'][$type])) {
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- $type.' for '.$key.' is not a supported column type', __FUNCTION__);
- }
- }
- }
- return $types;
- }
-
- // }}}
- // {{{ _baseConvertResult()
-
- /**
- * General type conversion method
- *
- * @param mixed $value reference to a value to be converted
- * @param string $type specifies which type to convert to
- * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text
- * @return object an MDB2 error on failure
- * @access protected
- */
- function _baseConvertResult($value, $type, $rtrim = true)
- {
- switch ($type) {
- case 'text':
- if ($rtrim) {
- $value = rtrim($value);
- }
- return $value;
- case 'integer':
- return intval($value);
- case 'boolean':
- return !empty($value);
- case 'decimal':
- return $value;
- case 'float':
- return doubleval($value);
- case 'date':
- return $value;
- case 'time':
- return $value;
- case 'timestamp':
- return $value;
- case 'clob':
- case 'blob':
- $this->lobs[] = array(
- 'buffer' => null,
- 'position' => 0,
- 'lob_index' => null,
- 'endOfLOB' => false,
- 'resource' => $value,
- 'value' => null,
- 'loaded' => false,
- );
- end($this->lobs);
- $lob_index = key($this->lobs);
- $this->lobs[$lob_index]['lob_index'] = $lob_index;
- return fopen('MDB2LOB://'.$lob_index.'@'.$this->db_index, 'r+');
- }
-
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_INVALID, null, null,
- 'attempt to convert result value to an unknown type :' . $type, __FUNCTION__);
- }
-
- // }}}
- // {{{ convertResult()
-
- /**
- * Convert a value to a RDBMS indipendent MDB2 type
- *
- * @param mixed $value value to be converted
- * @param string $type specifies which type to convert to
- * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text
- * @return mixed converted value
- * @access public
- */
- function convertResult($value, $type, $rtrim = true)
- {
- if (is_null($value)) {
- return null;
- }
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (!empty($db->options['datatype_map'][$type])) {
- $type = $db->options['datatype_map'][$type];
- if (!empty($db->options['datatype_map_callback'][$type])) {
- $parameter = array('type' => $type, 'value' => $value, 'rtrim' => $rtrim);
- return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
- }
- }
- return $this->_baseConvertResult($value, $type, $rtrim);
- }
-
- // }}}
- // {{{ convertResultRow()
-
- /**
- * Convert a result row
- *
- * @param array $types
- * @param array $row specifies the types to convert to
- * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text
- * @return mixed MDB2_OK on success, an MDB2 error on failure
- * @access public
- */
- function convertResultRow($types, $row, $rtrim = true)
- {
- $types = $this->_sortResultFieldTypes(array_keys($row), $types);
- foreach ($row as $key => $value) {
- if (empty($types[$key])) {
- continue;
- }
- $value = $this->convertResult($row[$key], $types[$key], $rtrim);
- if (PEAR::isError($value)) {
- return $value;
- }
- $row[$key] = $value;
- }
- return $row;
- }
-
- // }}}
- // {{{ _sortResultFieldTypes()
-
- /**
- * convert a result row
- *
- * @param array $types
- * @param array $row specifies the types to convert to
- * @param bool $rtrim if to rtrim text values or not
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function _sortResultFieldTypes($columns, $types)
- {
- $n_cols = count($columns);
- $n_types = count($types);
- if ($n_cols > $n_types) {
- for ($i= $n_cols - $n_types; $i >= 0; $i--) {
- $types[] = null;
- }
- }
- $sorted_types = array();
- foreach ($columns as $col) {
- $sorted_types[$col] = null;
- }
- foreach ($types as $name => $type) {
- if (array_key_exists($name, $sorted_types)) {
- $sorted_types[$name] = $type;
- unset($types[$name]);
- }
- }
- // if there are left types in the array, fill the null values of the
- // sorted array with them, in order.
- if (count($types)) {
- reset($types);
- foreach (array_keys($sorted_types) as $k) {
- if (is_null($sorted_types[$k])) {
- $sorted_types[$k] = current($types);
- next($types);
- }
- }
- }
- return $sorted_types;
- }
-
- // }}}
- // {{{ getDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare
- * of the given type
- *
- * @param string $type type to which the value should be converted to
- * @param string $name name the field to be declared.
- * @param string $field definition of the field
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access public
- */
- function getDeclaration($type, $name, $field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!empty($db->options['datatype_map'][$type])) {
- $type = $db->options['datatype_map'][$type];
- if (!empty($db->options['datatype_map_callback'][$type])) {
- $parameter = array('type' => $type, 'name' => $name, 'field' => $field);
- return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
- }
- $field['type'] = $type;
- }
-
- if (!method_exists($this, "_get{$type}Declaration")) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'type not defined: '.$type, __FUNCTION__);
- }
- return $this->{"_get{$type}Declaration"}($name, $field);
- }
-
- // }}}
- // {{{ getTypeDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an text type
- * field to be used in statements like CREATE TABLE.
- *
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the text
- * field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * default
- * Text value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access public
- */
- function getTypeDeclaration($field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- switch ($field['type']) {
- case 'text':
- $length = !empty($field['length']) ? $field['length'] : $db->options['default_text_field_length'];
- $fixed = !empty($field['fixed']) ? $field['fixed'] : false;
- return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')')
- : ($length ? 'VARCHAR('.$length.')' : 'TEXT');
- case 'clob':
- return 'TEXT';
- case 'blob':
- return 'TEXT';
- case 'integer':
- return 'INT';
- case 'boolean':
- return 'INT';
- case 'date':
- return 'CHAR ('.strlen('YYYY-MM-DD').')';
- case 'time':
- return 'CHAR ('.strlen('HH:MM:SS').')';
- case 'timestamp':
- return 'CHAR ('.strlen('YYYY-MM-DD HH:MM:SS').')';
- case 'float':
- return 'TEXT';
- case 'decimal':
- return 'TEXT';
- }
- return '';
- }
-
- // }}}
- // {{{ _getDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a generic type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the text
- * field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * default
- * Text value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * charset
- * Text value with the default CHARACTER SET for this field.
- * collation
- * Text value with the default COLLATION for this field.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field, or a MDB2_Error on failure
- * @access protected
- */
- function _getDeclaration($name, $field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- $declaration_options = $db->datatype->_getDeclarationOptions($field);
- if (PEAR::isError($declaration_options)) {
- return $declaration_options;
- }
- return $name.' '.$this->getTypeDeclaration($field).$declaration_options;
- }
-
- // }}}
- // {{{ _getDeclarationOptions()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a generic type
- * field to be used in statement like CREATE TABLE, without the field name
- * and type values (ie. just the character set, default value, if the
- * field is permitted to be NULL or not, and the collation options).
- *
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Text value to be used as default for this field.
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * charset
- * Text value with the default CHARACTER SET for this field.
- * collation
- * Text value with the default COLLATION for this field.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field's options.
- * @access protected
- */
- function _getDeclarationOptions($field)
- {
- $charset = empty($field['charset']) ? '' :
- ' '.$this->_getCharsetFieldDeclaration($field['charset']);
-
- $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
- $default = '';
- if (array_key_exists('default', $field)) {
- if ($field['default'] === '') {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $valid_default_values = $this->getValidTypes();
- $field['default'] = $valid_default_values[$field['type']];
- if ($field['default'] === ''&& ($db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL)) {
- $field['default'] = ' ';
- }
- }
- if (!is_null($field['default'])) {
- $default = ' DEFAULT ' . $this->quote($field['default'], $field['type']);
- }
- }
-
- $collation = empty($field['collation']) ? '' :
- ' '.$this->_getCollationFieldDeclaration($field['collation']);
-
- return $charset.$default.$notnull.$collation;
- }
-
- // }}}
- // {{{ _getCharsetFieldDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to set the CHARACTER SET
- * of a field declaration to be used in statements like CREATE TABLE.
- *
- * @param string $charset name of the charset
- * @return string DBMS specific SQL code portion needed to set the CHARACTER SET
- * of a field declaration.
- */
- function _getCharsetFieldDeclaration($charset)
- {
- return '';
- }
-
- // }}}
- // {{{ _getCollationFieldDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to set the COLLATION
- * of a field declaration to be used in statements like CREATE TABLE.
- *
- * @param string $collation name of the collation
- * @return string DBMS specific SQL code portion needed to set the COLLATION
- * of a field declaration.
- */
- function _getCollationFieldDeclaration($collation)
- {
- return '';
- }
-
- // }}}
- // {{{ _getIntegerDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an integer type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * unsigned
- * Boolean flag that indicates whether the field should be
- * declared as unsigned integer if possible.
- *
- * default
- * Integer value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getIntegerDeclaration($name, $field)
- {
- if (!empty($field['unsigned'])) {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $db->warnings[] = "unsigned integer field \"$name\" is being declared as signed integer";
- }
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getTextDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an text type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the text
- * field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * default
- * Text value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getTextDeclaration($name, $field)
- {
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getCLOBDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an character
- * large object type field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the large
- * object field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access public
- */
- function _getCLOBDeclaration($name, $field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
- $name = $db->quoteIdentifier($name, true);
- return $name.' '.$this->getTypeDeclaration($field).$notnull;
- }
-
- // }}}
- // {{{ _getBLOBDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an binary large
- * object type field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the large
- * object field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getBLOBDeclaration($name, $field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
- $name = $db->quoteIdentifier($name, true);
- return $name.' '.$this->getTypeDeclaration($field).$notnull;
- }
-
- // }}}
- // {{{ _getBooleanDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a boolean type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Boolean value to be used as default for this field.
- *
- * notnullL
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getBooleanDeclaration($name, $field)
- {
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getDateDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a date type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Date value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getDateDeclaration($name, $field)
- {
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getTimestampDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a timestamp
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Timestamp value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getTimestampDeclaration($name, $field)
- {
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getTimeDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a time
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Time value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getTimeDeclaration($name, $field)
- {
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getFloatDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a float type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Float value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getFloatDeclaration($name, $field)
- {
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getDecimalDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare a decimal type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Decimal value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getDecimalDeclaration($name, $field)
- {
- return $this->_getDeclaration($name, $field);
- }
-
- // }}}
- // {{{ compareDefinition()
-
- /**
- * Obtain an array of changes that may need to applied
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access public
- */
- function compareDefinition($current, $previous)
- {
- $type = !empty($current['type']) ? $current['type'] : null;
-
- if (!method_exists($this, "_compare{$type}Definition")) {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (!empty($db->options['datatype_map_callback'][$type])) {
- $parameter = array('current' => $current, 'previous' => $previous);
- $change = call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
- return $change;
- }
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'type "'.$current['type'].'" is not yet supported', __FUNCTION__);
- }
-
- if (empty($previous['type']) || $previous['type'] != $type) {
- return $current;
- }
-
- $change = $this->{"_compare{$type}Definition"}($current, $previous);
-
- if ($previous['type'] != $type) {
- $change['type'] = true;
- }
-
- $previous_notnull = !empty($previous['notnull']) ? $previous['notnull'] : false;
- $notnull = !empty($current['notnull']) ? $current['notnull'] : false;
- if ($previous_notnull != $notnull) {
- $change['notnull'] = true;
- }
-
- $previous_default = array_key_exists('default', $previous) ? $previous['default'] :
- ($previous_notnull ? '' : null);
- $default = array_key_exists('default', $current) ? $current['default'] :
- ($notnull ? '' : null);
- if ($previous_default !== $default) {
- $change['default'] = true;
- }
-
- return $change;
- }
-
- // }}}
- // {{{ _compareIntegerDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an integer field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareIntegerDefinition($current, $previous)
- {
- $change = array();
- $previous_unsigned = !empty($previous['unsigned']) ? $previous['unsigned'] : false;
- $unsigned = !empty($current['unsigned']) ? $current['unsigned'] : false;
- if ($previous_unsigned != $unsigned) {
- $change['unsigned'] = true;
- }
- $previous_autoincrement = !empty($previous['autoincrement']) ? $previous['autoincrement'] : false;
- $autoincrement = !empty($current['autoincrement']) ? $current['autoincrement'] : false;
- if ($previous_autoincrement != $autoincrement) {
- $change['autoincrement'] = true;
- }
- return $change;
- }
-
- // }}}
- // {{{ _compareTextDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an text field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareTextDefinition($current, $previous)
- {
- $change = array();
- $previous_length = !empty($previous['length']) ? $previous['length'] : 0;
- $length = !empty($current['length']) ? $current['length'] : 0;
- if ($previous_length != $length) {
- $change['length'] = true;
- }
- $previous_fixed = !empty($previous['fixed']) ? $previous['fixed'] : 0;
- $fixed = !empty($current['fixed']) ? $current['fixed'] : 0;
- if ($previous_fixed != $fixed) {
- $change['fixed'] = true;
- }
- return $change;
- }
-
- // }}}
- // {{{ _compareCLOBDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an CLOB field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareCLOBDefinition($current, $previous)
- {
- return $this->_compareTextDefinition($current, $previous);
- }
-
- // }}}
- // {{{ _compareBLOBDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an BLOB field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareBLOBDefinition($current, $previous)
- {
- return $this->_compareTextDefinition($current, $previous);
- }
-
- // }}}
- // {{{ _compareDateDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an date field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareDateDefinition($current, $previous)
- {
- return array();
- }
-
- // }}}
- // {{{ _compareTimeDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an time field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareTimeDefinition($current, $previous)
- {
- return array();
- }
-
- // }}}
- // {{{ _compareTimestampDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an timestamp field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareTimestampDefinition($current, $previous)
- {
- return array();
- }
-
- // }}}
- // {{{ _compareBooleanDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an boolean field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareBooleanDefinition($current, $previous)
- {
- return array();
- }
-
- // }}}
- // {{{ _compareFloatDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an float field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareFloatDefinition($current, $previous)
- {
- return array();
- }
-
- // }}}
- // {{{ _compareDecimalDefinition()
-
- /**
- * Obtain an array of changes that may need to applied to an decimal field
- *
- * @param array $current new definition
- * @param array $previous old definition
- * @return array containing all changes that will need to be applied
- * @access protected
- */
- function _compareDecimalDefinition($current, $previous)
- {
- return array();
- }
-
- // }}}
- // {{{ quote()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param string $type type to which the value should be converted to
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access public
- */
- function quote($value, $type = null, $quote = true, $escape_wildcards = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (is_null($value)
- || ($value === '' && $db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL)
- ) {
- if (!$quote) {
- return null;
- }
- return 'NULL';
- }
-
- if (is_null($type)) {
- switch (gettype($value)) {
- case 'integer':
- $type = 'integer';
- break;
- case 'double':
- // todo: default to decimal as float is quite unusual
- // $type = 'float';
- $type = 'decimal';
- break;
- case 'boolean':
- $type = 'boolean';
- break;
- case 'array':
- $value = serialize($value);
- case 'object':
- $type = 'text';
- break;
- default:
- if (preg_match('/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/', $value)) {
- $type = 'timestamp';
- } elseif (preg_match('/^\d{2}:\d{2}$/', $value)) {
- $type = 'time';
- } elseif (preg_match('/^\d{4}-\d{2}-\d{2}$/', $value)) {
- $type = 'date';
- } else {
- $type = 'text';
- }
- break;
- }
- } elseif (!empty($db->options['datatype_map'][$type])) {
- $type = $db->options['datatype_map'][$type];
- if (!empty($db->options['datatype_map_callback'][$type])) {
- $parameter = array('type' => $type, 'value' => $value, 'quote' => $quote, 'escape_wildcards' => $escape_wildcards);
- return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
- }
- }
-
- if (!method_exists($this, "_quote{$type}")) {
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'type not defined: '.$type, __FUNCTION__);
- }
- $value = $this->{"_quote{$type}"}($value, $quote, $escape_wildcards);
- if ($quote && $escape_wildcards && $db->string_quoting['escape_pattern']
- && $db->string_quoting['escape'] !== $db->string_quoting['escape_pattern']
- ) {
- $value.= $this->patternEscapeString();
- }
- return $value;
- }
-
- // }}}
- // {{{ _quoteInteger()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteInteger($value, $quote, $escape_wildcards)
- {
- return (int)$value;
- }
-
- // }}}
- // {{{ _quoteText()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that already contains any DBMS specific
- * escaped character sequences.
- * @access protected
- */
- function _quoteText($value, $quote, $escape_wildcards)
- {
- if (!$quote) {
- return $value;
- }
-
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $value = $db->escape($value, $escape_wildcards);
- if (PEAR::isError($value)) {
- return $value;
- }
- return "'".$value."'";
- }
-
- // }}}
- // {{{ _readFile()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _readFile($value)
- {
- $close = false;
- if (preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
- $close = true;
- if ($match[1] == 'file://') {
- $value = $match[2];
- }
- $value = @fopen($value, 'r');
- }
-
- if (is_resource($value)) {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $fp = $value;
- $value = '';
- while (!@feof($fp)) {
- $value.= @fread($fp, $db->options['lob_buffer_length']);
- }
- if ($close) {
- @fclose($fp);
- }
- }
-
- return $value;
- }
-
- // }}}
- // {{{ _quoteLOB()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteLOB($value, $quote, $escape_wildcards)
- {
- $value = $this->_readFile($value);
- if (PEAR::isError($value)) {
- return $value;
- }
- return $this->_quoteText($value, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteCLOB()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteCLOB($value, $quote, $escape_wildcards)
- {
- return $this->_quoteLOB($value, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteBLOB()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteBLOB($value, $quote, $escape_wildcards)
- {
- return $this->_quoteLOB($value, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteBoolean()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteBoolean($value, $quote, $escape_wildcards)
- {
- return ($value ? 1 : 0);
- }
-
- // }}}
- // {{{ _quoteDate()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteDate($value, $quote, $escape_wildcards)
- {
- if ($value === 'CURRENT_DATE') {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (isset($db->function) && is_a($db->function, 'MDB2_Driver_Function_Common')) {
- return $db->function->now('date');
- }
- return 'CURRENT_DATE';
- }
- return $this->_quoteText($value, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteTimestamp()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteTimestamp($value, $quote, $escape_wildcards)
- {
- if ($value === 'CURRENT_TIMESTAMP') {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (isset($db->function) && is_a($db->function, 'MDB2_Driver_Function_Common')) {
- return $db->function->now('timestamp');
- }
- return 'CURRENT_TIMESTAMP';
- }
- return $this->_quoteText($value, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteTime()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteTime($value, $quote, $escape_wildcards)
- {
- if ($value === 'CURRENT_TIME') {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if (isset($db->function) && is_a($db->function, 'MDB2_Driver_Function_Common')) {
- return $db->function->now('time');
- }
- return 'CURRENT_TIME';
- }
- return $this->_quoteText($value, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteFloat()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteFloat($value, $quote, $escape_wildcards)
- {
- if (preg_match('/^(.*)e([-+])(\d+)$/i', $value, $matches)) {
- $decimal = $this->_quoteDecimal($matches[1], $quote, $escape_wildcards);
- $sign = $matches[2];
- $exponent = str_pad($matches[3], 2, '0', STR_PAD_LEFT);
- $value = $decimal.'E'.$sign.$exponent;
- } else {
- $value = $this->_quoteDecimal($value, $quote, $escape_wildcards);
- }
- return $value;
- }
-
- // }}}
- // {{{ _quoteDecimal()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteDecimal($value, $quote, $escape_wildcards)
- {
- $value = (string)$value;
- $value = preg_replace('/[^\d\.,\-+eE]/', '', $value);
- if (preg_match('/[^\.\d]/', $value)) {
- if (strpos($value, ',')) {
- // 1000,00
- if (!strpos($value, '.')) {
- // convert the last "," to a "."
- $value = strrev(str_replace(',', '.', strrev($value)));
- // 1.000,00
- } elseif (strpos($value, '.') && strpos($value, '.') < strpos($value, ',')) {
- $value = str_replace('.', '', $value);
- // convert the last "," to a "."
- $value = strrev(str_replace(',', '.', strrev($value)));
- // 1,000.00
- } else {
- $value = str_replace(',', '', $value);
- }
- }
- }
- return $value;
- }
-
- // }}}
- // {{{ writeLOBToFile()
-
- /**
- * retrieve LOB from the database
- *
- * @param resource $lob stream handle
- * @param string $file name of the file into which the LOb should be fetched
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access protected
- */
- function writeLOBToFile($lob, $file)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (preg_match('/^(\w+:\/\/)(.*)$/', $file, $match)) {
- if ($match[1] == 'file://') {
- $file = $match[2];
- }
- }
-
- $fp = @fopen($file, 'wb');
- while (!@feof($lob)) {
- $result = @fread($lob, $db->options['lob_buffer_length']);
- $read = strlen($result);
- if (@fwrite($fp, $result, $read) != $read) {
- @fclose($fp);
- return $db->raiseError(MDB2_ERROR, null, null,
- 'could not write to the output file', __FUNCTION__);
- }
- }
- @fclose($fp);
- return MDB2_OK;
- }
-
- // }}}
- // {{{ _retrieveLOB()
-
- /**
- * retrieve LOB from the database
- *
- * @param array $lob array
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access protected
- */
- function _retrieveLOB(&$lob)
- {
- if (is_null($lob['value'])) {
- $lob['value'] = $lob['resource'];
- }
- $lob['loaded'] = true;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ readLOB()
-
- /**
- * Read data from large object input stream.
- *
- * @param resource $lob stream handle
- * @param string $data reference to a variable that will hold data
- * to be read from the large object input stream
- * @param integer $length value that indicates the largest ammount ofdata
- * to be read from the large object input stream.
- * @return mixed the effective number of bytes read from the large object
- * input stream on sucess or an MDB2 error object.
- * @access public
- * @see endOfLOB()
- */
- function _readLOB($lob, $length)
- {
- return substr($lob['value'], $lob['position'], $length);
- }
-
- // }}}
- // {{{ _endOfLOB()
-
- /**
- * Determine whether it was reached the end of the large object and
- * therefore there is no more data to be read for the its input stream.
- *
- * @param array $lob array
- * @return mixed true or false on success, a MDB2 error on failure
- * @access protected
- */
- function _endOfLOB($lob)
- {
- return $lob['endOfLOB'];
- }
-
- // }}}
- // {{{ destroyLOB()
-
- /**
- * Free any resources allocated during the lifetime of the large object
- * handler object.
- *
- * @param resource $lob stream handle
- * @access public
- */
- function destroyLOB($lob)
- {
- $lob_data = stream_get_meta_data($lob);
- $lob_index = $lob_data['wrapper_data']->lob_index;
- fclose($lob);
- if (isset($this->lobs[$lob_index])) {
- $this->_destroyLOB($this->lobs[$lob_index]);
- unset($this->lobs[$lob_index]);
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ _destroyLOB()
-
- /**
- * Free any resources allocated during the lifetime of the large object
- * handler object.
- *
- * @param array $lob array
- * @access private
- */
- function _destroyLOB(&$lob)
- {
- return MDB2_OK;
- }
-
- // }}}
- // {{{ implodeArray()
-
- /**
- * apply a type to all values of an array and return as a comma seperated string
- * useful for generating IN statements
- *
- * @access public
- *
- * @param array $array data array
- * @param string $type determines type of the field
- *
- * @return string comma seperated values
- */
- function implodeArray($array, $type = false)
- {
- if (!is_array($array) || empty($array)) {
- return 'NULL';
- }
- if ($type) {
- foreach ($array as $value) {
- $return[] = $this->quote($value, $type);
- }
- } else {
- $return = $array;
- }
- return implode(', ', $return);
- }
-
- // }}}
- // {{{ matchPattern()
-
- /**
- * build a pattern matching string
- *
- * @access public
- *
- * @param array $pattern even keys are strings, odd are patterns (% and _)
- * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future)
- * @param string $field optional field name that is being matched against
- * (might be required when emulating ILIKE)
- *
- * @return string SQL pattern
- */
- function matchPattern($pattern, $operator = null, $field = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $match = '';
- if (!is_null($operator)) {
- $operator = strtoupper($operator);
- switch ($operator) {
- // case insensitive
- case 'ILIKE':
- if (is_null($field)) {
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'case insensitive LIKE matching requires passing the field name', __FUNCTION__);
- }
- $db->loadModule('Function', null, true);
- $match = $db->function->lower($field).' LIKE ';
- break;
- // case sensitive
- case 'LIKE':
- $match = is_null($field) ? 'LIKE ' : $field.' LIKE ';
- break;
- default:
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'not a supported operator type:'. $operator, __FUNCTION__);
- }
- }
- $match.= "'";
- foreach ($pattern as $key => $value) {
- if ($key % 2) {
- $match.= $value;
- } else {
- if ($operator === 'ILIKE') {
- $value = strtolower($value);
- }
- $escaped = $db->escape($value);
- if (PEAR::isError($escaped)) {
- return $escaped;
- }
- $match.= $db->escapePattern($escaped);
- }
- }
- $match.= "'";
- $match.= $this->patternEscapeString();
- return $match;
- }
-
- // }}}
- // {{{ patternEscapeString()
-
- /**
- * build string to define pattern escape character
- *
- * @access public
- *
- * @return string define pattern escape character
- */
- function patternEscapeString()
- {
- return '';
- }
-
- // }}}
- // {{{ mapNativeDatatype()
-
- /**
- * Maps a native array description of a field to a MDB2 datatype and length
- *
- * @param array $field native field description
- * @return array containing the various possible types, length, sign, fixed
- * @access public
- */
- function mapNativeDatatype($field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- // If the user has specified an option to map the native field
- // type to a custom MDB2 datatype...
- $db_type = strtok($field['type'], '(), ');
- if (!empty($db->options['nativetype_map_callback'][$db_type])) {
- return call_user_func_array($db->options['nativetype_map_callback'][$db_type], array($db, $field));
- }
-
- // Otherwise perform the built-in (i.e. normal) MDB2 native type to
- // MDB2 datatype conversion
- return $this->_mapNativeDatatype($field);
- }
-
- // }}}
- // {{{ _mapNativeDatatype()
-
- /**
- * Maps a native array description of a field to a MDB2 datatype and length
- *
- * @param array $field native field description
- * @return array containing the various possible types, length, sign, fixed
- * @access public
- */
- function _mapNativeDatatype($field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ mapPrepareDatatype()
-
- /**
- * Maps an mdb2 datatype to mysqli prepare type
- *
- * @param string $type
- * @return string
- * @access public
- */
- function mapPrepareDatatype($type)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!empty($db->options['datatype_map'][$type])) {
- $type = $db->options['datatype_map'][$type];
- if (!empty($db->options['datatype_map_callback'][$type])) {
- $parameter = array('type' => $type);
- return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
- }
- }
-
- return $type;
- }
-}
-?>
diff --git a/inc/MDB2/Driver/Datatype/mysql.php b/inc/MDB2/Driver/Datatype/mysql.php
deleted file mode 100644
index 944248f57c3..00000000000
--- a/inc/MDB2/Driver/Datatype/mysql.php
+++ /dev/null
@@ -1,553 +0,0 @@
-<?php
-// vim: set et ts=4 sw=4 fdm=marker:
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: mysql.php,v 1.65 2008/02/22 19:23:49 quipo Exp $
-//
-
-oc_require_once('MDB2/Driver/Datatype/Common.php');
-
-/**
- * MDB2 MySQL driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Datatype_mysql extends MDB2_Driver_Datatype_Common
-{
- // {{{ _getCharsetFieldDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to set the CHARACTER SET
- * of a field declaration to be used in statements like CREATE TABLE.
- *
- * @param string $charset name of the charset
- * @return string DBMS specific SQL code portion needed to set the CHARACTER SET
- * of a field declaration.
- */
- function _getCharsetFieldDeclaration($charset)
- {
- return 'CHARACTER SET '.$charset;
- }
-
- // }}}
- // {{{ _getCollationFieldDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to set the COLLATION
- * of a field declaration to be used in statements like CREATE TABLE.
- *
- * @param string $collation name of the collation
- * @return string DBMS specific SQL code portion needed to set the COLLATION
- * of a field declaration.
- */
- function _getCollationFieldDeclaration($collation)
- {
- return 'COLLATE '.$collation;
- }
-
- // }}}
- // {{{ getTypeDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an text type
- * field to be used in statements like CREATE TABLE.
- *
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the text
- * field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * default
- * Text value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access public
- */
- function getTypeDeclaration($field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- switch ($field['type']) {
- case 'text':
- if (empty($field['length']) && array_key_exists('default', $field)) {
- $field['length'] = $db->varchar_max_length;
- }
- $length = !empty($field['length']) ? $field['length'] : false;
- $fixed = !empty($field['fixed']) ? $field['fixed'] : false;
- return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR(255)')
- : ($length ? 'VARCHAR('.$length.')' : 'TEXT');
- case 'clob':
- if (!empty($field['length'])) {
- $length = $field['length'];
- if ($length <= 255) {
- return 'TINYTEXT';
- } elseif ($length <= 65532) {
- return 'TEXT';
- } elseif ($length <= 16777215) {
- return 'MEDIUMTEXT';
- }
- }
- return 'LONGTEXT';
- case 'blob':
- if (!empty($field['length'])) {
- $length = $field['length'];
- if ($length <= 255) {
- return 'TINYBLOB';
- } elseif ($length <= 65532) {
- return 'BLOB';
- } elseif ($length <= 16777215) {
- return 'MEDIUMBLOB';
- }
- }
- return 'LONGBLOB';
- case 'integer':
- if (!empty($field['length'])) {
- $length = $field['length'];
- if ($length <= 1) {
- return 'TINYINT';
- } elseif ($length == 2) {
- return 'SMALLINT';
- } elseif ($length == 3) {
- return 'MEDIUMINT';
- } elseif ($length == 4) {
- return 'INT';
- } elseif ($length > 4) {
- return 'BIGINT';
- }
- }
- return 'INT';
- case 'boolean':
- return 'TINYINT(1)';
- case 'date':
- return 'DATE';
- case 'time':
- return 'TIME';
- case 'timestamp':
- return 'DATETIME';
- case 'float':
- return 'DOUBLE';
- case 'decimal':
- $length = !empty($field['length']) ? $field['length'] : 18;
- $scale = !empty($field['scale']) ? $field['scale'] : $db->options['decimal_places'];
- return 'DECIMAL('.$length.','.$scale.')';
- }
- return '';
- }
-
- // }}}
- // {{{ _getIntegerDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an integer type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param string $field associative array with the name of the properties
- * of the field being declared as array indexes.
- * Currently, the types of supported field
- * properties are as follows:
- *
- * unsigned
- * Boolean flag that indicates whether the field
- * should be declared as unsigned integer if
- * possible.
- *
- * default
- * Integer value to be used as default for this
- * field.
- *
- * notnull
- * Boolean flag that indicates whether this field is
- * constrained to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getIntegerDeclaration($name, $field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $default = $autoinc = '';
- if (!empty($field['autoincrement'])) {
- $autoinc = ' AUTO_INCREMENT PRIMARY KEY';
- } elseif (array_key_exists('default', $field)) {
- if ($field['default'] === '') {
- $field['default'] = empty($field['notnull']) ? null : 0;
- }
- $default = ' DEFAULT '.$this->quote($field['default'], 'integer');
- }
-
- $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
- $unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED';
- $name = $db->quoteIdentifier($name, true);
- return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull.$autoinc;
- }
-
- // }}}
- // {{{ _getFloatDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an float type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param string $field associative array with the name of the properties
- * of the field being declared as array indexes.
- * Currently, the types of supported field
- * properties are as follows:
- *
- * unsigned
- * Boolean flag that indicates whether the field
- * should be declared as unsigned float if
- * possible.
- *
- * default
- * float value to be used as default for this
- * field.
- *
- * notnull
- * Boolean flag that indicates whether this field is
- * constrained to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getFloatDeclaration($name, $field)
- {
- // Since AUTO_INCREMENT can be used for integer or floating-point types,
- // reuse the INTEGER declaration
- // @see http://bugs.mysql.com/bug.php?id=31032
- return $this->_getIntegerDeclaration($name, $field);
- }
-
- // }}}
- // {{{ _getDecimalDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an decimal type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param string $field associative array with the name of the properties
- * of the field being declared as array indexes.
- * Currently, the types of supported field
- * properties are as follows:
- *
- * unsigned
- * Boolean flag that indicates whether the field
- * should be declared as unsigned integer if
- * possible.
- *
- * default
- * Decimal value to be used as default for this
- * field.
- *
- * notnull
- * Boolean flag that indicates whether this field is
- * constrained to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getDecimalDeclaration($name, $field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $default = '';
- if (array_key_exists('default', $field)) {
- if ($field['default'] === '') {
- $field['default'] = empty($field['notnull']) ? null : 0;
- }
- $default = ' DEFAULT '.$this->quote($field['default'], 'integer');
- } elseif (empty($field['notnull'])) {
- $default = ' DEFAULT NULL';
- }
-
- $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
- $unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED';
- $name = $db->quoteIdentifier($name, true);
- return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull;
- }
-
- // }}}
- // {{{ matchPattern()
-
- /**
- * build a pattern matching string
- *
- * @access public
- *
- * @param array $pattern even keys are strings, odd are patterns (% and _)
- * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future)
- * @param string $field optional field name that is being matched against
- * (might be required when emulating ILIKE)
- *
- * @return string SQL pattern
- */
- function matchPattern($pattern, $operator = null, $field = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $match = '';
- if (!is_null($operator)) {
- $field = is_null($field) ? '' : $field.' ';
- $operator = strtoupper($operator);
- switch ($operator) {
- // case insensitive
- case 'ILIKE':
- $match = $field.'LIKE ';
- break;
- // case sensitive
- case 'LIKE':
- $match = $field.'LIKE BINARY ';
- break;
- default:
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'not a supported operator type:'. $operator, __FUNCTION__);
- }
- }
- $match.= "'";
- foreach ($pattern as $key => $value) {
- if ($key % 2) {
- $match.= $value;
- } else {
- $match.= $db->escapePattern($db->escape($value));
- }
- }
- $match.= "'";
- $match.= $this->patternEscapeString();
- return $match;
- }
-
- // }}}
- // {{{ _mapNativeDatatype()
-
- /**
- * Maps a native array description of a field to a MDB2 datatype and length
- *
- * @param array $field native field description
- * @return array containing the various possible types, length, sign, fixed
- * @access public
- */
- function _mapNativeDatatype($field)
- {
- $db_type = strtolower($field['type']);
- $db_type = strtok($db_type, '(), ');
- if ($db_type == 'national') {
- $db_type = strtok('(), ');
- }
- if (!empty($field['length'])) {
- $length = strtok($field['length'], ', ');
- $decimal = strtok(', ');
- } else {
- $length = strtok('(), ');
- $decimal = strtok('(), ');
- }
- $type = array();
- $unsigned = $fixed = null;
- switch ($db_type) {
- case 'tinyint':
- $type[] = 'integer';
- $type[] = 'boolean';
- if (preg_match('/^(is|has)/', $field['name'])) {
- $type = array_reverse($type);
- }
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- $length = 1;
- break;
- case 'smallint':
- $type[] = 'integer';
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- $length = 2;
- break;
- case 'mediumint':
- $type[] = 'integer';
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- $length = 3;
- break;
- case 'int':
- case 'integer':
- $type[] = 'integer';
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- $length = 4;
- break;
- case 'bigint':
- $type[] = 'integer';
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- $length = 8;
- break;
- case 'tinytext':
- case 'mediumtext':
- case 'longtext':
- case 'text':
- case 'varchar':
- $fixed = false;
- case 'string':
- case 'char':
- $type[] = 'text';
- if ($length == '1') {
- $type[] = 'boolean';
- if (preg_match('/^(is|has)/', $field['name'])) {
- $type = array_reverse($type);
- }
- } elseif (strstr($db_type, 'text')) {
- $type[] = 'clob';
- if ($decimal == 'binary') {
- $type[] = 'blob';
- }
- $type = array_reverse($type);
- }
- if ($fixed !== false) {
- $fixed = true;
- }
- break;
- case 'enum':
- $type[] = 'text';
- preg_match_all('/\'.+\'/U', $field['type'], $matches);
- $length = 0;
- $fixed = false;
- if (is_array($matches)) {
- foreach ($matches[0] as $value) {
- $length = max($length, strlen($value)-2);
- }
- if ($length == '1' && count($matches[0]) == 2) {
- $type[] = 'boolean';
- if (preg_match('/^(is|has)/', $field['name'])) {
- $type = array_reverse($type);
- }
- }
- }
- $type[] = 'integer';
- case 'set':
- $fixed = false;
- $type[] = 'text';
- $type[] = 'integer';
- break;
- case 'date':
- $type[] = 'date';
- $length = null;
- break;
- case 'datetime':
- case 'timestamp':
- $type[] = 'timestamp';
- $length = null;
- break;
- case 'time':
- $type[] = 'time';
- $length = null;
- break;
- case 'float':
- case 'double':
- case 'real':
- $type[] = 'float';
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- break;
- case 'unknown':
- case 'decimal':
- case 'numeric':
- $type[] = 'decimal';
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- if ($decimal !== false) {
- $length = $length.','.$decimal;
- }
- break;
- case 'tinyblob':
- case 'mediumblob':
- case 'longblob':
- case 'blob':
- $type[] = 'blob';
- $length = null;
- break;
- case 'binary':
- case 'varbinary':
- $type[] = 'blob';
- break;
- case 'year':
- $type[] = 'integer';
- $type[] = 'date';
- $length = null;
- break;
- default:
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'unknown database attribute type: '.$db_type, __FUNCTION__);
- }
-
- if ((int)$length <= 0) {
- $length = null;
- }
-
- return array($type, $length, $unsigned, $fixed);
- }
-
- // }}}
-}
-
-?> \ No newline at end of file
diff --git a/inc/MDB2/Driver/Datatype/pgsql.php b/inc/MDB2/Driver/Datatype/pgsql.php
deleted file mode 100644
index fe18729c84f..00000000000
--- a/inc/MDB2/Driver/Datatype/pgsql.php
+++ /dev/null
@@ -1,554 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Paul Cooper <pgc@ucecom.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: pgsql.php,v 1.93 2008/08/28 20:32:57 afz Exp $
-
-oc_require_once('MDB2/Driver/Datatype/Common.php');
-
-/**
- * MDB2 PostGreSQL driver
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper <pgc@ucecom.com>
- */
-class MDB2_Driver_Datatype_pgsql extends MDB2_Driver_Datatype_Common
-{
- // {{{ _baseConvertResult()
-
- /**
- * General type conversion method
- *
- * @param mixed $value refernce to a value to be converted
- * @param string $type specifies which type to convert to
- * @param boolean $rtrim [optional] when TRUE [default], apply rtrim() to text
- * @return object a MDB2 error on failure
- * @access protected
- */
- function _baseConvertResult($value, $type, $rtrim = true)
- {
- if (is_null($value)) {
- return null;
- }
- switch ($type) {
- case 'boolean':
- return $value == 't';
- case 'float':
- return doubleval($value);
- case 'date':
- return $value;
- case 'time':
- return substr($value, 0, strlen('HH:MM:SS'));
- case 'timestamp':
- return substr($value, 0, strlen('YYYY-MM-DD HH:MM:SS'));
- case 'blob':
- $value = pg_unescape_bytea($value);
- return parent::_baseConvertResult($value, $type, $rtrim);
- }
- return parent::_baseConvertResult($value, $type, $rtrim);
- }
-
- // }}}
- // {{{ getTypeDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an text type
- * field to be used in statements like CREATE TABLE.
- *
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the text
- * field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * default
- * Text value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access public
- */
- function getTypeDeclaration($field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- switch ($field['type']) {
- case 'text':
- $length = !empty($field['length']) ? $field['length'] : false;
- $fixed = !empty($field['fixed']) ? $field['fixed'] : false;
- return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')')
- : ($length ? 'VARCHAR('.$length.')' : 'TEXT');
- case 'clob':
- return 'TEXT';
- case 'blob':
- return 'BYTEA';
- case 'integer':
- if (!empty($field['autoincrement'])) {
- if (!empty($field['length'])) {
- $length = $field['length'];
- if ($length > 4) {
- return 'BIGSERIAL PRIMARY KEY';
- }
- }
- return 'SERIAL PRIMARY KEY';
- }
- if (!empty($field['length'])) {
- $length = $field['length'];
- if ($length <= 2) {
- return 'SMALLINT';
- } elseif ($length == 3 || $length == 4) {
- return 'INT';
- } elseif ($length > 4) {
- return 'BIGINT';
- }
- }
- return 'INT';
- case 'boolean':
- return 'BOOLEAN';
- case 'date':
- return 'DATE';
- case 'time':
- return 'TIME without time zone';
- case 'timestamp':
- return 'TIMESTAMP without time zone';
- case 'float':
- return 'FLOAT8';
- case 'decimal':
- $length = !empty($field['length']) ? $field['length'] : 18;
- $scale = !empty($field['scale']) ? $field['scale'] : $db->options['decimal_places'];
- return 'NUMERIC('.$length.','.$scale.')';
- }
- }
-
- // }}}
- // {{{ _getIntegerDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an integer type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * unsigned
- * Boolean flag that indicates whether the field should be
- * declared as unsigned integer if possible.
- *
- * default
- * Integer value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getIntegerDeclaration($name, $field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!empty($field['unsigned'])) {
- $db->warnings[] = "unsigned integer field \"$name\" is being declared as signed integer";
- }
- if (!empty($field['autoincrement'])) {
- $name = $db->quoteIdentifier($name, true);
- return $name.' '.$this->getTypeDeclaration($field);
- }
- $default = '';
- if (array_key_exists('default', $field)) {
- if ($field['default'] === '') {
- $field['default'] = empty($field['notnull']) ? null : 0;
- }
- $default = ' DEFAULT '.$this->quote($field['default'], 'integer');
- }
-
- $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
- $name = $db->quoteIdentifier($name, true);
- return $name.' '.$this->getTypeDeclaration($field).$default.$notnull;
- }
-
- // }}}
- // {{{ _quoteCLOB()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteCLOB($value, $quote, $escape_wildcards)
- {
- return $this->_quoteText($value, $quote, $escape_wildcards);
- }
-
- // }}}
- // {{{ _quoteBLOB()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteBLOB($value, $quote, $escape_wildcards)
- {
- if (!$quote) {
- return $value;
- }
- if (version_compare(PHP_VERSION, '5.2.0RC6', '>=')) {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $connection = $db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- $value = @pg_escape_bytea($connection, $value);
- } else {
- $value = @pg_escape_bytea($value);
- }
- return "'".$value."'";
- }
-
- // }}}
- // {{{ _quoteBoolean()
-
- /**
- * Convert a text value into a DBMS specific format that is suitable to
- * compose query statements.
- *
- * @param string $value text string value that is intended to be converted.
- * @param bool $quote determines if the value should be quoted and escaped
- * @param bool $escape_wildcards if to escape escape wildcards
- * @return string text string that represents the given argument value in
- * a DBMS specific format.
- * @access protected
- */
- function _quoteBoolean($value, $quote, $escape_wildcards)
- {
- $value = $value ? 't' : 'f';
- if (!$quote) {
- return $value;
- }
- return "'".$value."'";
- }
-
- // }}}
- // {{{ matchPattern()
-
- /**
- * build a pattern matching string
- *
- * @access public
- *
- * @param array $pattern even keys are strings, odd are patterns (% and _)
- * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future)
- * @param string $field optional field name that is being matched against
- * (might be required when emulating ILIKE)
- *
- * @return string SQL pattern
- */
- function matchPattern($pattern, $operator = null, $field = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $match = '';
- if (!is_null($operator)) {
- $field = is_null($field) ? '' : $field.' ';
- $operator = strtoupper($operator);
- switch ($operator) {
- // case insensitive
- case 'ILIKE':
- $match = $field.'ILIKE ';
- break;
- // case sensitive
- case 'LIKE':
- $match = $field.'LIKE ';
- break;
- default:
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'not a supported operator type:'. $operator, __FUNCTION__);
- }
- }
- $match.= "'";
- foreach ($pattern as $key => $value) {
- if ($key % 2) {
- $match.= $value;
- } else {
- $match.= $db->escapePattern($db->escape($value));
- }
- }
- $match.= "'";
- $match.= $this->patternEscapeString();
- return $match;
- }
-
- // }}}
- // {{{ patternEscapeString()
-
- /**
- * build string to define escape pattern string
- *
- * @access public
- *
- *
- * @return string define escape pattern
- */
- function patternEscapeString()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- return ' ESCAPE '.$this->quote($db->string_quoting['escape_pattern']);
- }
-
- // }}}
- // {{{ _mapNativeDatatype()
-
- /**
- * Maps a native array description of a field to a MDB2 datatype and length
- *
- * @param array $field native field description
- * @return array containing the various possible types, length, sign, fixed
- * @access public
- */
- function _mapNativeDatatype($field)
- {
- $db_type = strtolower($field['type']);
- $length = $field['length'];
- $type = array();
- $unsigned = $fixed = null;
- switch ($db_type) {
- case 'smallint':
- case 'int2':
- $type[] = 'integer';
- $unsigned = false;
- $length = 2;
- if ($length == '2') {
- $type[] = 'boolean';
- if (preg_match('/^(is|has)/', $field['name'])) {
- $type = array_reverse($type);
- }
- }
- break;
- case 'int':
- case 'int4':
- case 'integer':
- case 'serial':
- case 'serial4':
- $type[] = 'integer';
- $unsigned = false;
- $length = 4;
- break;
- case 'bigint':
- case 'int8':
- case 'bigserial':
- case 'serial8':
- $type[] = 'integer';
- $unsigned = false;
- $length = 8;
- break;
- case 'bool':
- case 'boolean':
- $type[] = 'boolean';
- $length = null;
- break;
- case 'text':
- case 'varchar':
- $fixed = false;
- case 'unknown':
- case 'char':
- case 'bpchar':
- $type[] = 'text';
- if ($length == '1') {
- $type[] = 'boolean';
- if (preg_match('/^(is|has)/', $field['name'])) {
- $type = array_reverse($type);
- }
- } elseif (strstr($db_type, 'text')) {
- $type[] = 'clob';
- $type = array_reverse($type);
- }
- if ($fixed !== false) {
- $fixed = true;
- }
- break;
- case 'date':
- $type[] = 'date';
- $length = null;
- break;
- case 'datetime':
- case 'timestamp':
- case 'timestamptz':
- $type[] = 'timestamp';
- $length = null;
- break;
- case 'time':
- $type[] = 'time';
- $length = null;
- break;
- case 'float':
- case 'float4':
- case 'float8':
- case 'double':
- case 'real':
- $type[] = 'float';
- break;
- case 'decimal':
- case 'money':
- case 'numeric':
- $type[] = 'decimal';
- if (isset($field['scale'])) {
- $length = $length.','.$field['scale'];
- }
- break;
- case 'tinyblob':
- case 'mediumblob':
- case 'longblob':
- case 'blob':
- case 'bytea':
- $type[] = 'blob';
- $length = null;
- break;
- case 'oid':
- $type[] = 'blob';
- $type[] = 'clob';
- $length = null;
- break;
- case 'year':
- $type[] = 'integer';
- $type[] = 'date';
- $length = null;
- break;
- default:
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'unknown database attribute type: '.$db_type, __FUNCTION__);
- }
-
- if ((int)$length <= 0) {
- $length = null;
- }
-
- return array($type, $length, $unsigned, $fixed);
- }
-
- // }}}
- // {{{ mapPrepareDatatype()
-
- /**
- * Maps an mdb2 datatype to native prepare type
- *
- * @param string $type
- * @return string
- * @access public
- */
- function mapPrepareDatatype($type)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!empty($db->options['datatype_map'][$type])) {
- $type = $db->options['datatype_map'][$type];
- if (!empty($db->options['datatype_map_callback'][$type])) {
- $parameter = array('type' => $type);
- return call_user_func_array($db->options['datatype_map_callback'][$type], array(&$db, __FUNCTION__, $parameter));
- }
- }
-
- switch ($type) {
- case 'integer':
- return 'int';
- case 'boolean':
- return 'bool';
- case 'decimal':
- case 'float':
- return 'numeric';
- case 'clob':
- return 'text';
- case 'blob':
- return 'bytea';
- default:
- break;
- }
- return $type;
- }
- // }}}
-}
-?> \ No newline at end of file
diff --git a/inc/MDB2/Driver/Datatype/sqlite.php b/inc/MDB2/Driver/Datatype/sqlite.php
deleted file mode 100644
index 533d0e9510b..00000000000
--- a/inc/MDB2/Driver/Datatype/sqlite.php
+++ /dev/null
@@ -1,409 +0,0 @@
-<?php
-// vim: set et ts=4 sw=4 fdm=marker:
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: sqlite.php,v 1.67 2008/02/22 19:58:06 quipo Exp $
-//
-
-oc_require_once('MDB2/Driver/Datatype/Common.php');
-
-/**
- * MDB2 SQLite driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Datatype_sqlite extends MDB2_Driver_Datatype_Common
-{
- // {{{ _getCollationFieldDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to set the COLLATION
- * of a field declaration to be used in statements like CREATE TABLE.
- *
- * @param string $collation name of the collation
- *
- * @return string DBMS specific SQL code portion needed to set the COLLATION
- * of a field declaration.
- */
- function _getCollationFieldDeclaration($collation)
- {
- return 'COLLATE '.$collation;
- }
-
- // }}}
- // {{{ getTypeDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an text type
- * field to be used in statements like CREATE TABLE.
- *
- * @param array $field associative array with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * length
- * Integer value that determines the maximum length of the text
- * field. If this argument is missing the field should be
- * declared to have the longest length allowed by the DBMS.
- *
- * default
- * Text value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access public
- */
- function getTypeDeclaration($field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- switch ($field['type']) {
- case 'text':
- $length = !empty($field['length'])
- ? $field['length'] : false;
- $fixed = !empty($field['fixed']) ? $field['fixed'] : false;
- return $fixed ? ($length ? 'CHAR('.$length.')' : 'CHAR('.$db->options['default_text_field_length'].')')
- : ($length ? 'VARCHAR('.$length.')' : 'TEXT');
- case 'clob':
- if (!empty($field['length'])) {
- $length = $field['length'];
- if ($length <= 255) {
- return 'TINYTEXT';
- } elseif ($length <= 65532) {
- return 'TEXT';
- } elseif ($length <= 16777215) {
- return 'MEDIUMTEXT';
- }
- }
- return 'LONGTEXT';
- case 'blob':
- if (!empty($field['length'])) {
- $length = $field['length'];
- if ($length <= 255) {
- return 'TINYBLOB';
- } elseif ($length <= 65532) {
- return 'BLOB';
- } elseif ($length <= 16777215) {
- return 'MEDIUMBLOB';
- }
- }
- return 'LONGBLOB';
- case 'integer':
- if (!empty($field['length'])) {
- $length = $field['length'];
- if ($length <= 2) {
- return 'SMALLINT';
- } elseif ($length == 3 || $length == 4) {
- return 'INTEGER';
- } elseif ($length > 4) {
- return 'BIGINT';
- }
- }
- return 'INTEGER';
- case 'boolean':
- return 'BOOLEAN';
- case 'date':
- return 'DATE';
- case 'time':
- return 'TIME';
- case 'timestamp':
- return 'DATETIME';
- case 'float':
- return 'DOUBLE'.($db->options['fixed_float'] ? '('.
- ($db->options['fixed_float']+2).','.$db->options['fixed_float'].')' : '');
- case 'decimal':
- $length = !empty($field['length']) ? $field['length'] : 18;
- $scale = !empty($field['scale']) ? $field['scale'] : $db->options['decimal_places'];
- return 'DECIMAL('.$length.','.$scale.')';
- }
- return '';
- }
-
- // }}}
- // {{{ _getIntegerDeclaration()
-
- /**
- * Obtain DBMS specific SQL code portion needed to declare an integer type
- * field to be used in statements like CREATE TABLE.
- *
- * @param string $name name the field to be declared.
- * @param string $field associative array with the name of the properties
- * of the field being declared as array indexes.
- * Currently, the types of supported field
- * properties are as follows:
- *
- * unsigned
- * Boolean flag that indicates whether the field
- * should be declared as unsigned integer if
- * possible.
- *
- * default
- * Integer value to be used as default for this
- * field.
- *
- * notnull
- * Boolean flag that indicates whether this field is
- * constrained to not be set to null.
- * @return string DBMS specific SQL code portion that should be used to
- * declare the specified field.
- * @access protected
- */
- function _getIntegerDeclaration($name, $field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $default = $autoinc = '';
- if (!empty($field['autoincrement'])) {
- $autoinc = ' PRIMARY KEY';
- } elseif (array_key_exists('default', $field)) {
- if ($field['default'] === '') {
- $field['default'] = empty($field['notnull']) ? null : 0;
- }
- $default = ' DEFAULT '.$this->quote($field['default'], 'integer');
- }
-
- $notnull = empty($field['notnull']) ? '' : ' NOT NULL';
- $unsigned = empty($field['unsigned']) ? '' : ' UNSIGNED';
- $name = $db->quoteIdentifier($name, true);
- return $name.' '.$this->getTypeDeclaration($field).$unsigned.$default.$notnull.$autoinc;
- }
-
- // }}}
- // {{{ matchPattern()
-
- /**
- * build a pattern matching string
- *
- * @access public
- *
- * @param array $pattern even keys are strings, odd are patterns (% and _)
- * @param string $operator optional pattern operator (LIKE, ILIKE and maybe others in the future)
- * @param string $field optional field name that is being matched against
- * (might be required when emulating ILIKE)
- *
- * @return string SQL pattern
- */
- function matchPattern($pattern, $operator = null, $field = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $match = '';
- if (!is_null($operator)) {
- $field = is_null($field) ? '' : $field.' ';
- $operator = strtoupper($operator);
- switch ($operator) {
- // case insensitive
- case 'ILIKE':
- $match = $field.'LIKE ';
- break;
- // case sensitive
- case 'LIKE':
- $match = $field.'LIKE ';
- break;
- default:
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'not a supported operator type:'. $operator, __FUNCTION__);
- }
- }
- $match.= "'";
- foreach ($pattern as $key => $value) {
- if ($key % 2) {
- $match.= $value;
- } else {
- $match.= $db->escapePattern($db->escape($value));
- }
- }
- $match.= "'";
- $match.= $this->patternEscapeString();
- return $match;
- }
-
- // }}}
- // {{{ _mapNativeDatatype()
-
- /**
- * Maps a native array description of a field to a MDB2 datatype and length
- *
- * @param array $field native field description
- * @return array containing the various possible types, length, sign, fixed
- * @access public
- */
- function _mapNativeDatatype($field)
- {
- $db_type = strtolower($field['type']);
- $length = !empty($field['length']) ? $field['length'] : null;
- $unsigned = !empty($field['unsigned']) ? $field['unsigned'] : null;
- $fixed = null;
- $type = array();
- switch ($db_type) {
- case 'boolean':
- $type[] = 'boolean';
- break;
- case 'tinyint':
- $type[] = 'integer';
- $type[] = 'boolean';
- if (preg_match('/^(is|has)/', $field['name'])) {
- $type = array_reverse($type);
- }
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- $length = 1;
- break;
- case 'smallint':
- $type[] = 'integer';
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- $length = 2;
- break;
- case 'mediumint':
- $type[] = 'integer';
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- $length = 3;
- break;
- case 'int':
- case 'integer':
- case 'serial':
- $type[] = 'integer';
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- $length = 4;
- break;
- case 'bigint':
- case 'bigserial':
- $type[] = 'integer';
- $unsigned = preg_match('/ unsigned/i', $field['type']);
- $length = 8;
- break;
- case 'clob':
- $type[] = 'clob';
- $fixed = false;
- break;
- case 'tinytext':
- case 'mediumtext':
- case 'longtext':
- case 'text':
- case 'varchar':
- case 'varchar2':
- $fixed = false;
- case 'char':
- $type[] = 'text';
- if ($length == '1') {
- $type[] = 'boolean';
- if (preg_match('/^(is|has)/', $field['name'])) {
- $type = array_reverse($type);
- }
- } elseif (strstr($db_type, 'text')) {
- $type[] = 'clob';
- $type = array_reverse($type);
- }
- if ($fixed !== false) {
- $fixed = true;
- }
- break;
- case 'date':
- $type[] = 'date';
- $length = null;
- break;
- case 'datetime':
- case 'timestamp':
- $type[] = 'timestamp';
- $length = null;
- break;
- case 'time':
- $type[] = 'time';
- $length = null;
- break;
- case 'float':
- case 'double':
- case 'real':
- $type[] = 'float';
- break;
- case 'decimal':
- case 'numeric':
- $type[] = 'decimal';
- $length = $length.','.$field['decimal'];
- break;
- case 'tinyblob':
- case 'mediumblob':
- case 'longblob':
- case 'blob':
- $type[] = 'blob';
- $length = null;
- break;
- case 'year':
- $type[] = 'integer';
- $type[] = 'date';
- $length = null;
- break;
- default:
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'unknown database attribute type: '.$db_type, __FUNCTION__);
- }
-
- if ((int)$length <= 0) {
- $length = null;
- }
-
- return array($type, $length, $unsigned, $fixed);
- }
-
- // }}}
-}
-
-?> \ No newline at end of file
diff --git a/inc/MDB2/Driver/Function/Common.php b/inc/MDB2/Driver/Function/Common.php
deleted file mode 100644
index 731f06882ce..00000000000
--- a/inc/MDB2/Driver/Function/Common.php
+++ /dev/null
@@ -1,293 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Common.php,v 1.21 2008/02/17 18:51:39 quipo Exp $
-//
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-
-/**
- * Base class for the function modules that is extended by each MDB2 driver
- *
- * To load this module in the MDB2 object:
- * $mdb->loadModule('Function');
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Function_Common extends MDB2_Module_Common
-{
- // {{{ executeStoredProc()
-
- /**
- * Execute a stored procedure and return any results
- *
- * @param string $name string that identifies the function to execute
- * @param mixed $params array that contains the paramaters to pass the stored proc
- * @param mixed $types array that contains the types of the columns in
- * the result set
- * @param mixed $result_class string which specifies which result class to use
- * @param mixed $result_wrap_class string which specifies which class to wrap results in
- *
- * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function &executeStoredProc($name, $params = null, $types = null, $result_class = true, $result_wrap_class = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $error =& $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- return $error;
- }
-
- // }}}
- // {{{ functionTable()
-
- /**
- * return string for internal table used when calling only a function
- *
- * @return string for internal table used when calling only a function
- * @access public
- */
- function functionTable()
- {
- return '';
- }
-
- // }}}
- // {{{ now()
-
- /**
- * Return string to call a variable with the current timestamp inside an SQL statement
- * There are three special variables for current date and time:
- * - CURRENT_TIMESTAMP (date and time, TIMESTAMP type)
- * - CURRENT_DATE (date, DATE type)
- * - CURRENT_TIME (time, TIME type)
- *
- * @param string $type 'timestamp' | 'time' | 'date'
- *
- * @return string to call a variable with the current timestamp
- * @access public
- */
- function now($type = 'timestamp')
- {
- switch ($type) {
- case 'time':
- return 'CURRENT_TIME';
- case 'date':
- return 'CURRENT_DATE';
- case 'timestamp':
- default:
- return 'CURRENT_TIMESTAMP';
- }
- }
-
- // }}}
- // {{{ unixtimestamp()
-
- /**
- * return string to call a function to get the unix timestamp from a iso timestamp
- *
- * @param string $expression
- *
- * @return string to call a variable with the timestamp
- * @access public
- */
- function unixtimestamp($expression)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $error =& $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- return $error;
- }
-
- // }}}
- // {{{ substring()
-
- /**
- * return string to call a function to get a substring inside an SQL statement
- *
- * @return string to call a function to get a substring
- * @access public
- */
- function substring($value, $position = 1, $length = null)
- {
- if (!is_null($length)) {
- return "SUBSTRING($value FROM $position FOR $length)";
- }
- return "SUBSTRING($value FROM $position)";
- }
-
- // }}}
- // {{{ replace()
-
- /**
- * return string to call a function to get replace inside an SQL statement.
- *
- * @return string to call a function to get a replace
- * @access public
- */
- function replace($str, $from_str, $to_str)
- {
- return "REPLACE($str, $from_str , $to_str)";
- }
-
- // }}}
- // {{{ concat()
-
- /**
- * Returns string to concatenate two or more string parameters
- *
- * @param string $value1
- * @param string $value2
- * @param string $values...
- *
- * @return string to concatenate two strings
- * @access public
- */
- function concat($value1, $value2)
- {
- $args = func_get_args();
- return "(".implode(' || ', $args).")";
- }
-
- // }}}
- // {{{ random()
-
- /**
- * return string to call a function to get random value inside an SQL statement
- *
- * @return return string to generate float between 0 and 1
- * @access public
- */
- function random()
- {
- return 'RAND()';
- }
-
- // }}}
- // {{{ lower()
-
- /**
- * return string to call a function to lower the case of an expression
- *
- * @param string $expression
- *
- * @return return string to lower case of an expression
- * @access public
- */
- function lower($expression)
- {
- return "LOWER($expression)";
- }
-
- // }}}
- // {{{ upper()
-
- /**
- * return string to call a function to upper the case of an expression
- *
- * @param string $expression
- *
- * @return return string to upper case of an expression
- * @access public
- */
- function upper($expression)
- {
- return "UPPER($expression)";
- }
-
- // }}}
- // {{{ length()
-
- /**
- * return string to call a function to get the length of a string expression
- *
- * @param string $expression
- *
- * @return return string to get the string expression length
- * @access public
- */
- function length($expression)
- {
- return "LENGTH($expression)";
- }
-
- // }}}
- // {{{ guid()
-
- /**
- * Returns global unique identifier
- *
- * @return string to get global unique identifier
- * @access public
- */
- function guid()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $error =& $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- return $error;
- }
-
- // }}}
-}
-?> \ No newline at end of file
diff --git a/inc/MDB2/Driver/Function/mysql.php b/inc/MDB2/Driver/Function/mysql.php
deleted file mode 100644
index aff531c9f3a..00000000000
--- a/inc/MDB2/Driver/Function/mysql.php
+++ /dev/null
@@ -1,136 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: mysql.php,v 1.12 2008/02/17 18:54:08 quipo Exp $
-//
-
-oc_require_once('MDB2/Driver/Function/Common.php');
-
-/**
- * MDB2 MySQL driver for the function modules
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Function_mysql extends MDB2_Driver_Function_Common
-{
- // }}}
- // {{{ executeStoredProc()
-
- /**
- * Execute a stored procedure and return any results
- *
- * @param string $name string that identifies the function to execute
- * @param mixed $params array that contains the paramaters to pass the stored proc
- * @param mixed $types array that contains the types of the columns in
- * the result set
- * @param mixed $result_class string which specifies which result class to use
- * @param mixed $result_wrap_class string which specifies which class to wrap results in
- * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function &executeStoredProc($name, $params = null, $types = null, $result_class = true, $result_wrap_class = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'CALL '.$name;
- $query .= $params ? '('.implode(', ', $params).')' : '()';
- return $db->query($query, $types, $result_class, $result_wrap_class);
- }
-
- // }}}
- // {{{ unixtimestamp()
-
- /**
- * return string to call a function to get the unix timestamp from a iso timestamp
- *
- * @param string $expression
- *
- * @return string to call a variable with the timestamp
- * @access public
- */
- function unixtimestamp($expression)
- {
- return 'UNIX_TIMESTAMP('. $expression.')';
- }
-
- // }}}
- // {{{ concat()
-
- /**
- * Returns string to concatenate two or more string parameters
- *
- * @param string $value1
- * @param string $value2
- * @param string $values...
- * @return string to concatenate two strings
- * @access public
- **/
- function concat($value1, $value2)
- {
- $args = func_get_args();
- return "CONCAT(".implode(', ', $args).")";
- }
-
- // }}}
- // {{{ guid()
-
- /**
- * Returns global unique identifier
- *
- * @return string to get global unique identifier
- * @access public
- */
- function guid()
- {
- return 'UUID()';
- }
-
- // }}}
-}
-?> \ No newline at end of file
diff --git a/inc/MDB2/Driver/Function/pgsql.php b/inc/MDB2/Driver/Function/pgsql.php
deleted file mode 100644
index cb47ea57d9f..00000000000
--- a/inc/MDB2/Driver/Function/pgsql.php
+++ /dev/null
@@ -1,115 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Paul Cooper <pgc@ucecom.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: pgsql.php,v 1.11 2008/11/09 19:46:50 quipo Exp $
-
-oc_require_once('MDB2/Driver/Function/Common.php');
-
-/**
- * MDB2 MySQL driver for the function modules
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Function_pgsql extends MDB2_Driver_Function_Common
-{
- // {{{ executeStoredProc()
-
- /**
- * Execute a stored procedure and return any results
- *
- * @param string $name string that identifies the function to execute
- * @param mixed $params array that contains the paramaters to pass the stored proc
- * @param mixed $types array that contains the types of the columns in
- * the result set
- * @param mixed $result_class string which specifies which result class to use
- * @param mixed $result_wrap_class string which specifies which class to wrap results in
- * @return mixed a result handle or MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function &executeStoredProc($name, $params = null, $types = null, $result_class = true, $result_wrap_class = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SELECT * FROM '.$name;
- $query .= $params ? '('.implode(', ', $params).')' : '()';
- return $db->query($query, $types, $result_class, $result_wrap_class);
- }
- // }}}
- // {{{ unixtimestamp()
-
- /**
- * return string to call a function to get the unix timestamp from a iso timestamp
- *
- * @param string $expression
- *
- * @return string to call a variable with the timestamp
- * @access public
- */
- function unixtimestamp($expression)
- {
- return 'EXTRACT(EPOCH FROM DATE_TRUNC(\'seconds\', CAST ((' . $expression . ') AS TIMESTAMP)))';
- }
-
- // }}}
- // {{{ random()
-
- /**
- * return string to call a function to get random value inside an SQL statement
- *
- * @return return string to generate float between 0 and 1
- * @access public
- */
- function random()
- {
- return 'RANDOM()';
- }
-
- // }}}
-}
-?> \ No newline at end of file
diff --git a/inc/MDB2/Driver/Function/sqlite.php b/inc/MDB2/Driver/Function/sqlite.php
deleted file mode 100644
index f5499599dd5..00000000000
--- a/inc/MDB2/Driver/Function/sqlite.php
+++ /dev/null
@@ -1,162 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: sqlite.php,v 1.10 2008/02/17 18:54:08 quipo Exp $
-//
-
-oc_require_once('MDB2/Driver/Function/Common.php');
-
-/**
- * MDB2 SQLite driver for the function modules
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Function_sqlite extends MDB2_Driver_Function_Common
-{
- // {{{ constructor
-
- /**
- * Constructor
- */
- function __construct($db_index)
- {
- parent::__construct($db_index);
- // create all sorts of UDFs
- }
-
- // {{{ now()
-
- /**
- * Return string to call a variable with the current timestamp inside an SQL statement
- * There are three special variables for current date and time.
- *
- * @return string to call a variable with the current timestamp
- * @access public
- */
- function now($type = 'timestamp')
- {
- switch ($type) {
- case 'time':
- return 'time(\'now\')';
- case 'date':
- return 'date(\'now\')';
- case 'timestamp':
- default:
- return 'datetime(\'now\')';
- }
- }
-
- // }}}
- // {{{ unixtimestamp()
-
- /**
- * return string to call a function to get the unix timestamp from a iso timestamp
- *
- * @param string $expression
- *
- * @return string to call a variable with the timestamp
- * @access public
- */
- function unixtimestamp($expression)
- {
- return 'strftime("%s",'. $expression.', "utc")';
- }
-
- // }}}
- // {{{ substring()
-
- /**
- * return string to call a function to get a substring inside an SQL statement
- *
- * @return string to call a function to get a substring
- * @access public
- */
- function substring($value, $position = 1, $length = null)
- {
- if (!is_null($length)) {
- return "substr($value,$position,$length)";
- }
- return "substr($value,$position,length($value))";
- }
-
- // }}}
- // {{{ random()
-
- /**
- * return string to call a function to get random value inside an SQL statement
- *
- * @return return string to generate float between 0 and 1
- * @access public
- */
- function random()
- {
- return '((RANDOM()+2147483648)/4294967296)';
- }
-
- // }}}
- // {{{ replace()
-
- /**
- * return string to call a function to get a replacement inside an SQL statement.
- *
- * @return string to call a function to get a replace
- * @access public
- */
- function replace($str, $from_str, $to_str)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $error =& $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- return $error;
- }
-
- // }}}
-}
-?>
diff --git a/inc/MDB2/Driver/Manager/Common.php b/inc/MDB2/Driver/Manager/Common.php
deleted file mode 100644
index d7154d4eac0..00000000000
--- a/inc/MDB2/Driver/Manager/Common.php
+++ /dev/null
@@ -1,1014 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS 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. |
-// +----------------------------------------------------------------------+
-// | Authors: Lukas Smith <smith@pooteeweet.org> |
-// | Lorenzo Alberton <l.alberton@quipo.it> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Common.php,v 1.72 2009/01/14 15:00:40 quipo Exp $
-//
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Lorenzo Alberton <l.alberton@quipo.it>
- */
-
-/**
- * Base class for the management modules that is extended by each MDB2 driver
- *
- * To load this module in the MDB2 object:
- * $mdb->loadModule('Manager');
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Manager_Common extends MDB2_Module_Common
-{
- // {{{ splitTableSchema()
-
- /**
- * Split the "[owner|schema].table" notation into an array
- *
- * @param string $table [schema and] table name
- *
- * @return array array(schema, table)
- * @access private
- */
- function splitTableSchema($table)
- {
- $ret = array();
- if (strpos($table, '.') !== false) {
- return explode('.', $table);
- }
- return array(null, $table);
- }
-
- // }}}
- // {{{ getFieldDeclarationList()
-
- /**
- * Get declaration of a number of field in bulk
- *
- * @param array $fields a multidimensional associative array.
- * The first dimension determines the field name, while the second
- * dimension is keyed with the name of the properties
- * of the field being declared as array indexes. Currently, the types
- * of supported field properties are as follows:
- *
- * default
- * Boolean value to be used as default for this field.
- *
- * notnull
- * Boolean flag that indicates whether this field is constrained
- * to not be set to null.
- *
- * @return mixed string on success, a MDB2 error on failure
- * @access public
- */
- function getFieldDeclarationList($fields)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!is_array($fields) || empty($fields)) {
- return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'missing any fields', __FUNCTION__);
- }
- foreach ($fields as $field_name => $field) {
- $query = $db->getDeclaration($field['type'], $field_name, $field);
- if (PEAR::isError($query)) {
- return $query;
- }
- $query_fields[] = $query;
- }
- return implode(', ', $query_fields);
- }
-
- // }}}
- // {{{ _fixSequenceName()
-
- /**
- * Removes any formatting in an sequence name using the 'seqname_format' option
- *
- * @param string $sqn string that containts name of a potential sequence
- * @param bool $check if only formatted sequences should be returned
- * @return string name of the sequence with possible formatting removed
- * @access protected
- */
- function _fixSequenceName($sqn, $check = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $seq_pattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $db->options['seqname_format']).'$/i';
- $seq_name = preg_replace($seq_pattern, '\\1', $sqn);
- if ($seq_name && !strcasecmp($sqn, $db->getSequenceName($seq_name))) {
- return $seq_name;
- }
- if ($check) {
- return false;
- }
- return $sqn;
- }
-
- // }}}
- // {{{ _fixIndexName()
-
- /**
- * Removes any formatting in an index name using the 'idxname_format' option
- *
- * @param string $idx string that containts name of anl index
- * @return string name of the index with eventual formatting removed
- * @access protected
- */
- function _fixIndexName($idx)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $idx_pattern = '/^'.preg_replace('/%s/', '([a-z0-9_]+)', $db->options['idxname_format']).'$/i';
- $idx_name = preg_replace($idx_pattern, '\\1', $idx);
- if ($idx_name && !strcasecmp($idx, $db->getIndexName($idx_name))) {
- return $idx_name;
- }
- return $idx;
- }
-
- // }}}
- // {{{ createDatabase()
-
- /**
- * create a new database
- *
- * @param string $name name of the database that should be created
- * @param array $options array with charset, collation info
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createDatabase($database, $options = array())
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ alterDatabase()
-
- /**
- * alter an existing database
- *
- * @param string $name name of the database that should be created
- * @param array $options array with charset, collation info
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function alterDatabase($database, $options = array())
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ dropDatabase()
-
- /**
- * drop an existing database
- *
- * @param string $name name of the database that should be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropDatabase($database)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ _getCreateTableQuery()
-
- /**
- * Create a basic SQL query for a new table creation
- *
- * @param string $name Name of the database that should be created
- * @param array $fields Associative array that contains the definition of each field of the new table
- * @param array $options An associative array of table options
- *
- * @return mixed string (the SQL query) on success, a MDB2 error on failure
- * @see createTable()
- */
- function _getCreateTableQuery($name, $fields, $options = array())
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!$name) {
- return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,
- 'no valid table name specified', __FUNCTION__);
- }
- if (empty($fields)) {
- return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,
- 'no fields specified for table "'.$name.'"', __FUNCTION__);
- }
- $query_fields = $this->getFieldDeclarationList($fields);
- if (PEAR::isError($query_fields)) {
- return $query_fields;
- }
- if (!empty($options['primary'])) {
- $query_fields.= ', PRIMARY KEY ('.implode(', ', array_keys($options['primary'])).')';
- }
-
- $name = $db->quoteIdentifier($name, true);
- $result = 'CREATE ';
- if (!empty($options['temporary'])) {
- $result .= $this->_getTemporaryTableQuery();
- }
- $result .= " TABLE $name ($query_fields)";
- return $result;
- }
-
- // }}}
- // {{{ _getTemporaryTableQuery()
-
- /**
- * A method to return the required SQL string that fits between CREATE ... TABLE
- * to create the table as a temporary table.
- *
- * Should be overridden in driver classes to return the correct string for the
- * specific database type.
- *
- * The default is to return the string "TEMPORARY" - this will result in a
- * SQL error for any database that does not support temporary tables, or that
- * requires a different SQL command from "CREATE TEMPORARY TABLE".
- *
- * @return string The string required to be placed between "CREATE" and "TABLE"
- * to generate a temporary table, if possible.
- */
- function _getTemporaryTableQuery()
- {
- return 'TEMPORARY';
- }
-
- // }}}
- // {{{ createTable()
-
- /**
- * create a new table
- *
- * @param string $name Name of the database that should be created
- * @param array $fields Associative array that contains the definition of each field of the new table
- * The indexes of the array entries are the names of the fields of the table an
- * the array entry values are associative arrays like those that are meant to be
- * passed with the field definitions to get[Type]Declaration() functions.
- * array(
- * 'id' => array(
- * 'type' => 'integer',
- * 'unsigned' => 1
- * 'notnull' => 1
- * 'default' => 0
- * ),
- * 'name' => array(
- * 'type' => 'text',
- * 'length' => 12
- * ),
- * 'password' => array(
- * 'type' => 'text',
- * 'length' => 12
- * )
- * );
- * @param array $options An associative array of table options:
- * array(
- * 'comment' => 'Foo',
- * 'temporary' => true|false,
- * );
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createTable($name, $fields, $options = array())
- {
- $query = $this->_getCreateTableQuery($name, $fields, $options);
- if (PEAR::isError($query)) {
- return $query;
- }
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $result = $db->exec($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ dropTable()
-
- /**
- * drop an existing table
- *
- * @param string $name name of the table that should be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropTable($name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- return $db->exec("DROP TABLE $name");
- }
-
- // }}}
- // {{{ truncateTable()
-
- /**
- * Truncate an existing table (if the TRUNCATE TABLE syntax is not supported,
- * it falls back to a DELETE FROM TABLE query)
- *
- * @param string $name name of the table that should be truncated
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function truncateTable($name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- return $db->exec("DELETE FROM $name");
- }
-
- // }}}
- // {{{ vacuum()
-
- /**
- * Optimize (vacuum) all the tables in the db (or only the specified table)
- * and optionally run ANALYZE.
- *
- * @param string $table table name (all the tables if empty)
- * @param array $options an array with driver-specific options:
- * - timeout [int] (in seconds) [mssql-only]
- * - analyze [boolean] [pgsql and mysql]
- * - full [boolean] [pgsql-only]
- * - freeze [boolean] [pgsql-only]
- *
- * @return mixed MDB2_OK success, a MDB2 error on failure
- * @access public
- */
- function vacuum($table = null, $options = array())
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ alterTable()
-
- /**
- * alter an existing table
- *
- * @param string $name name of the table that is intended to be changed.
- * @param array $changes associative array that contains the details of each type
- * of change that is intended to be performed. The types of
- * changes that are currently supported are defined as follows:
- *
- * name
- *
- * New name for the table.
- *
- * add
- *
- * Associative array with the names of fields to be added as
- * indexes of the array. The value of each entry of the array
- * should be set to another associative array with the properties
- * of the fields to be added. The properties of the fields should
- * be the same as defined by the MDB2 parser.
- *
- *
- * remove
- *
- * Associative array with the names of fields to be removed as indexes
- * of the array. Currently the values assigned to each entry are ignored.
- * An empty array should be used for future compatibility.
- *
- * rename
- *
- * Associative array with the names of fields to be renamed as indexes
- * of the array. The value of each entry of the array should be set to
- * another associative array with the entry named name with the new
- * field name and the entry named Declaration that is expected to contain
- * the portion of the field declaration already in DBMS specific SQL code
- * as it is used in the CREATE TABLE statement.
- *
- * change
- *
- * Associative array with the names of the fields to be changed as indexes
- * of the array. Keep in mind that if it is intended to change either the
- * name of a field and any other properties, the change array entries
- * should have the new names of the fields as array indexes.
- *
- * The value of each entry of the array should be set to another associative
- * array with the properties of the fields to that are meant to be changed as
- * array entries. These entries should be assigned to the new values of the
- * respective properties. The properties of the fields should be the same
- * as defined by the MDB2 parser.
- *
- * Example
- * array(
- * 'name' => 'userlist',
- * 'add' => array(
- * 'quota' => array(
- * 'type' => 'integer',
- * 'unsigned' => 1
- * )
- * ),
- * 'remove' => array(
- * 'file_limit' => array(),
- * 'time_limit' => array()
- * ),
- * 'change' => array(
- * 'name' => array(
- * 'length' => '20',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 20,
- * ),
- * )
- * ),
- * 'rename' => array(
- * 'sex' => array(
- * 'name' => 'gender',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 1,
- * 'default' => 'M',
- * ),
- * )
- * )
- * )
- *
- * @param boolean $check indicates whether the function should just check if the DBMS driver
- * can perform the requested table alterations if the value is true or
- * actually perform them otherwise.
- * @access public
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- */
- function alterTable($name, $changes, $check)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listDatabases()
-
- /**
- * list all databases
- *
- * @return mixed array of database names on success, a MDB2 error on failure
- * @access public
- */
- function listDatabases()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implementedd', __FUNCTION__);
- }
-
- // }}}
- // {{{ listUsers()
-
- /**
- * list all users
- *
- * @return mixed array of user names on success, a MDB2 error on failure
- * @access public
- */
- function listUsers()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listViews()
-
- /**
- * list all views in the current database
- *
- * @param string database, the current is default
- * NB: not all the drivers can get the view names from
- * a database other than the current one
- * @return mixed array of view names on success, a MDB2 error on failure
- * @access public
- */
- function listViews($database = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listTableViews()
-
- /**
- * list the views in the database that reference a given table
- *
- * @param string table for which all referenced views should be found
- * @return mixed array of view names on success, a MDB2 error on failure
- * @access public
- */
- function listTableViews($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listTableTriggers()
-
- /**
- * list all triggers in the database that reference a given table
- *
- * @param string table for which all referenced triggers should be found
- * @return mixed array of trigger names on success, a MDB2 error on failure
- * @access public
- */
- function listTableTriggers($table = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listFunctions()
-
- /**
- * list all functions in the current database
- *
- * @return mixed array of function names on success, a MDB2 error on failure
- * @access public
- */
- function listFunctions()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listTables()
-
- /**
- * list all tables in the current database
- *
- * @param string database, the current is default.
- * NB: not all the drivers can get the table names from
- * a database other than the current one
- * @return mixed array of table names on success, a MDB2 error on failure
- * @access public
- */
- function listTables($database = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listTableFields()
-
- /**
- * list all fields in a table in the current database
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of field names on success, a MDB2 error on failure
- * @access public
- */
- function listTableFields($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ createIndex()
-
- /**
- * Get the stucture of a field into an array
- *
- * @param string $table name of the table on which the index is to be created
- * @param string $name name of the index to be created
- * @param array $definition associative array that defines properties of the index to be created.
- * Currently, only one property named FIELDS is supported. This property
- * is also an associative with the names of the index fields as array
- * indexes. Each entry of this array is set to another type of associative
- * array that specifies properties of the index that are specific to
- * each field.
- *
- * Currently, only the sorting property is supported. It should be used
- * to define the sorting direction of the index. It may be set to either
- * ascending or descending.
- *
- * Not all DBMS support index sorting direction configuration. The DBMS
- * drivers of those that do not support it ignore this property. Use the
- * function supports() to determine whether the DBMS driver can manage indexes.
- *
- * Example
- * array(
- * 'fields' => array(
- * 'user_name' => array(
- * 'sorting' => 'ascending'
- * ),
- * 'last_login' => array()
- * )
- * )
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createIndex($table, $name, $definition)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = $db->quoteIdentifier($table, true);
- $name = $db->quoteIdentifier($db->getIndexName($name), true);
- $query = "CREATE INDEX $name ON $table";
- $fields = array();
- foreach (array_keys($definition['fields']) as $field) {
- $fields[] = $db->quoteIdentifier($field, true);
- }
- $query .= ' ('. implode(', ', $fields) . ')';
- return $db->exec($query);
- }
-
- // }}}
- // {{{ dropIndex()
-
- /**
- * drop existing index
- *
- * @param string $table name of table that should be used in method
- * @param string $name name of the index to be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropIndex($table, $name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($db->getIndexName($name), true);
- return $db->exec("DROP INDEX $name");
- }
-
- // }}}
- // {{{ listTableIndexes()
-
- /**
- * list all indexes in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of index names on success, a MDB2 error on failure
- * @access public
- */
- function listTableIndexes($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ _getAdvancedFKOptions()
-
- /**
- * Return the FOREIGN KEY query section dealing with non-standard options
- * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
- *
- * @param array $definition
- * @return string
- * @access protected
- */
- function _getAdvancedFKOptions($definition)
- {
- return '';
- }
-
- // }}}
- // {{{ createConstraint()
-
- /**
- * create a constraint on a table
- *
- * @param string $table name of the table on which the constraint is to be created
- * @param string $name name of the constraint to be created
- * @param array $definition associative array that defines properties of the constraint to be created.
- * The full structure of the array looks like this:
- * <pre>
- * array (
- * [primary] => 0
- * [unique] => 0
- * [foreign] => 1
- * [check] => 0
- * [fields] => array (
- * [field1name] => array() // one entry per each field covered
- * [field2name] => array() // by the index
- * [field3name] => array(
- * [sorting] => ascending
- * [position] => 3
- * )
- * )
- * [references] => array(
- * [table] => name
- * [fields] => array(
- * [field1name] => array( //one entry per each referenced field
- * [position] => 1
- * )
- * )
- * )
- * [deferrable] => 0
- * [initiallydeferred] => 0
- * [onupdate] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
- * [ondelete] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
- * [match] => SIMPLE|PARTIAL|FULL
- * );
- * </pre>
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createConstraint($table, $name, $definition)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $table = $db->quoteIdentifier($table, true);
- $name = $db->quoteIdentifier($db->getIndexName($name), true);
- $query = "ALTER TABLE $table ADD CONSTRAINT $name";
- if (!empty($definition['primary'])) {
- $query.= ' PRIMARY KEY';
- } elseif (!empty($definition['unique'])) {
- $query.= ' UNIQUE';
- } elseif (!empty($definition['foreign'])) {
- $query.= ' FOREIGN KEY';
- }
- $fields = array();
- foreach (array_keys($definition['fields']) as $field) {
- $fields[] = $db->quoteIdentifier($field, true);
- }
- $query .= ' ('. implode(', ', $fields) . ')';
- if (!empty($definition['foreign'])) {
- $query.= ' REFERENCES ' . $db->quoteIdentifier($definition['references']['table'], true);
- $referenced_fields = array();
- foreach (array_keys($definition['references']['fields']) as $field) {
- $referenced_fields[] = $db->quoteIdentifier($field, true);
- }
- $query .= ' ('. implode(', ', $referenced_fields) . ')';
- $query .= $this->_getAdvancedFKOptions($definition);
- }
- return $db->exec($query);
- }
-
- // }}}
- // {{{ dropConstraint()
-
- /**
- * drop existing constraint
- *
- * @param string $table name of table that should be used in method
- * @param string $name name of the constraint to be dropped
- * @param string $primary hint if the constraint is primary
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropConstraint($table, $name, $primary = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = $db->quoteIdentifier($table, true);
- $name = $db->quoteIdentifier($db->getIndexName($name), true);
- return $db->exec("ALTER TABLE $table DROP CONSTRAINT $name");
- }
-
- // }}}
- // {{{ listTableConstraints()
-
- /**
- * list all constraints in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of constraint names on success, a MDB2 error on failure
- * @access public
- */
- function listTableConstraints($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ createSequence()
-
- /**
- * create sequence
- *
- * @param string $seq_name name of the sequence to be created
- * @param string $start start value of the sequence; default is 1
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createSequence($seq_name, $start = 1)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * drop existing sequence
- *
- * @param string $seq_name name of the sequence to be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropSequence($name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ listSequences()
-
- /**
- * list all sequences in the current database
- *
- * @param string database, the current is default
- * NB: not all the drivers can get the sequence names from
- * a database other than the current one
- * @return mixed array of sequence names on success, a MDB2 error on failure
- * @access public
- */
- function listSequences($database = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
-}
-?> \ No newline at end of file
diff --git a/inc/MDB2/Driver/Manager/mysql.php b/inc/MDB2/Driver/Manager/mysql.php
deleted file mode 100644
index 7bd6a3623a3..00000000000
--- a/inc/MDB2/Driver/Manager/mysql.php
+++ /dev/null
@@ -1,1432 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: mysql.php,v 1.113 2008/11/23 20:30:29 quipo Exp $
-//
-
-oc_require_once('MDB2/Driver/Manager/Common.php');
-
-/**
- * MDB2 MySQL driver for the management modules
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Manager_mysql extends MDB2_Driver_Manager_Common
-{
-
- // }}}
- // {{{ createDatabase()
-
- /**
- * create a new database
- *
- * @param string $name name of the database that should be created
- * @param array $options array with charset, collation info
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createDatabase($name, $options = array())
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- $query = 'CREATE DATABASE ' . $name;
- if (!empty($options['charset'])) {
- $query .= ' DEFAULT CHARACTER SET ' . $db->quote($options['charset'], 'text');
- }
- if (!empty($options['collation'])) {
- $query .= ' COLLATE ' . $db->quote($options['collation'], 'text');
- }
- return $db->standaloneQuery($query, null, true);
- }
-
- // }}}
- // {{{ alterDatabase()
-
- /**
- * alter an existing database
- *
- * @param string $name name of the database that is intended to be changed
- * @param array $options array with charset, collation info
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function alterDatabase($name, $options = array())
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'ALTER DATABASE '. $db->quoteIdentifier($name, true);
- if (!empty($options['charset'])) {
- $query .= ' DEFAULT CHARACTER SET ' . $db->quote($options['charset'], 'text');
- }
- if (!empty($options['collation'])) {
- $query .= ' COLLATE ' . $db->quote($options['collation'], 'text');
- }
- return $db->standaloneQuery($query, null, true);
- }
-
- // }}}
- // {{{ dropDatabase()
-
- /**
- * drop an existing database
- *
- * @param string $name name of the database that should be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropDatabase($name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- $query = "DROP DATABASE $name";
- return $db->standaloneQuery($query, null, true);
- }
-
- // }}}
- // {{{ _getAdvancedFKOptions()
-
- /**
- * Return the FOREIGN KEY query section dealing with non-standard options
- * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
- *
- * @param array $definition
- * @return string
- * @access protected
- */
- function _getAdvancedFKOptions($definition)
- {
- $query = '';
- if (!empty($definition['match'])) {
- $query .= ' MATCH '.$definition['match'];
- }
- if (!empty($definition['onupdate'])) {
- $query .= ' ON UPDATE '.$definition['onupdate'];
- }
- if (!empty($definition['ondelete'])) {
- $query .= ' ON DELETE '.$definition['ondelete'];
- }
- return $query;
- }
-
- // }}}
- // {{{ createTable()
-
- /**
- * create a new table
- *
- * @param string $name Name of the database that should be created
- * @param array $fields Associative array that contains the definition of each field of the new table
- * The indexes of the array entries are the names of the fields of the table an
- * the array entry values are associative arrays like those that are meant to be
- * passed with the field definitions to get[Type]Declaration() functions.
- * array(
- * 'id' => array(
- * 'type' => 'integer',
- * 'unsigned' => 1
- * 'notnull' => 1
- * 'default' => 0
- * ),
- * 'name' => array(
- * 'type' => 'text',
- * 'length' => 12
- * ),
- * 'password' => array(
- * 'type' => 'text',
- * 'length' => 12
- * )
- * );
- * @param array $options An associative array of table options:
- * array(
- * 'comment' => 'Foo',
- * 'charset' => 'utf8',
- * 'collate' => 'utf8_unicode_ci',
- * 'type' => 'innodb',
- * );
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createTable($name, $fields, $options = array())
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- // if we have an AUTO_INCREMENT column and a PK on more than one field,
- // we have to handle it differently...
- $autoincrement = null;
- if (empty($options['primary'])) {
- $pk_fields = array();
- foreach ($fields as $fieldname => $def) {
- if (!empty($def['primary'])) {
- $pk_fields[$fieldname] = true;
- }
- if (!empty($def['autoincrement'])) {
- $autoincrement = $fieldname;
- }
- }
- if (!is_null($autoincrement) && count($pk_fields) > 1) {
- $options['primary'] = $pk_fields;
- } else {
- // the PK constraint is on max one field => OK
- $autoincrement = null;
- }
- }
-
- $query = $this->_getCreateTableQuery($name, $fields, $options);
- if (PEAR::isError($query)) {
- return $query;
- }
-
- if (!is_null($autoincrement)) {
- // we have to remove the PK clause added by _getIntegerDeclaration()
- $query = str_replace('AUTO_INCREMENT PRIMARY KEY', 'AUTO_INCREMENT', $query);
- }
-
- $options_strings = array();
-
- if (!empty($options['comment'])) {
- $options_strings['comment'] = 'COMMENT = '.$db->quote($options['comment'], 'text');
- }
-
- if (!empty($options['charset'])) {
- $options_strings['charset'] = 'DEFAULT CHARACTER SET '.$options['charset'];
- if (!empty($options['collate'])) {
- $options_strings['charset'].= ' COLLATE '.$options['collate'];
- }
- }
-
- $type = false;
- if (!empty($options['type'])) {
- $type = $options['type'];
- } elseif ($db->options['default_table_type']) {
- $type = $db->options['default_table_type'];
- }
- if ($type) {
- $options_strings[] = "ENGINE = $type";
- }
-
- if (!empty($options_strings)) {
- $query .= ' '.implode(' ', $options_strings);
- }
- $result = $db->exec($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ dropTable()
-
- /**
- * drop an existing table
- *
- * @param string $name name of the table that should be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropTable($name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- //delete the triggers associated to existing FK constraints
- $constraints = $this->listTableConstraints($name);
- if (!PEAR::isError($constraints) && !empty($constraints)) {
- $db->loadModule('Reverse', null, true);
- foreach ($constraints as $constraint) {
- $definition = $db->reverse->getTableConstraintDefinition($name, $constraint);
- if (!PEAR::isError($definition) && !empty($definition['foreign'])) {
- $result = $this->_dropFKTriggers($name, $constraint, $definition['references']['table']);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- }
-
- return parent::dropTable($name);
- }
-
- // }}}
- // {{{ truncateTable()
-
- /**
- * Truncate an existing table (if the TRUNCATE TABLE syntax is not supported,
- * it falls back to a DELETE FROM TABLE query)
- *
- * @param string $name name of the table that should be truncated
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function truncateTable($name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- return $db->exec("TRUNCATE TABLE $name");
- }
-
- // }}}
- // {{{ vacuum()
-
- /**
- * Optimize (vacuum) all the tables in the db (or only the specified table)
- * and optionally run ANALYZE.
- *
- * @param string $table table name (all the tables if empty)
- * @param array $options an array with driver-specific options:
- * - timeout [int] (in seconds) [mssql-only]
- * - analyze [boolean] [pgsql and mysql]
- * - full [boolean] [pgsql-only]
- * - freeze [boolean] [pgsql-only]
- *
- * @return mixed MDB2_OK success, a MDB2 error on failure
- * @access public
- */
- function vacuum($table = null, $options = array())
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (empty($table)) {
- $table = $this->listTables();
- if (PEAR::isError($table)) {
- return $table;
- }
- }
- if (is_array($table)) {
- foreach (array_keys($table) as $k) {
- $table[$k] = $db->quoteIdentifier($table[$k], true);
- }
- $table = implode(', ', $table);
- } else {
- $table = $db->quoteIdentifier($table, true);
- }
-
- $result = $db->exec('OPTIMIZE TABLE '.$table);
- if (PEAR::isError($result)) {
- return $result;
- }
- if (!empty($options['analyze'])) {
- return $db->exec('ANALYZE TABLE '.$table);
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ alterTable()
-
- /**
- * alter an existing table
- *
- * @param string $name name of the table that is intended to be changed.
- * @param array $changes associative array that contains the details of each type
- * of change that is intended to be performed. The types of
- * changes that are currently supported are defined as follows:
- *
- * name
- *
- * New name for the table.
- *
- * add
- *
- * Associative array with the names of fields to be added as
- * indexes of the array. The value of each entry of the array
- * should be set to another associative array with the properties
- * of the fields to be added. The properties of the fields should
- * be the same as defined by the MDB2 parser.
- *
- *
- * remove
- *
- * Associative array with the names of fields to be removed as indexes
- * of the array. Currently the values assigned to each entry are ignored.
- * An empty array should be used for future compatibility.
- *
- * rename
- *
- * Associative array with the names of fields to be renamed as indexes
- * of the array. The value of each entry of the array should be set to
- * another associative array with the entry named name with the new
- * field name and the entry named Declaration that is expected to contain
- * the portion of the field declaration already in DBMS specific SQL code
- * as it is used in the CREATE TABLE statement.
- *
- * change
- *
- * Associative array with the names of the fields to be changed as indexes
- * of the array. Keep in mind that if it is intended to change either the
- * name of a field and any other properties, the change array entries
- * should have the new names of the fields as array indexes.
- *
- * The value of each entry of the array should be set to another associative
- * array with the properties of the fields to that are meant to be changed as
- * array entries. These entries should be assigned to the new values of the
- * respective properties. The properties of the fields should be the same
- * as defined by the MDB2 parser.
- *
- * Example
- * array(
- * 'name' => 'userlist',
- * 'add' => array(
- * 'quota' => array(
- * 'type' => 'integer',
- * 'unsigned' => 1
- * )
- * ),
- * 'remove' => array(
- * 'file_limit' => array(),
- * 'time_limit' => array()
- * ),
- * 'change' => array(
- * 'name' => array(
- * 'length' => '20',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 20,
- * ),
- * )
- * ),
- * 'rename' => array(
- * 'sex' => array(
- * 'name' => 'gender',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 1,
- * 'default' => 'M',
- * ),
- * )
- * )
- * )
- *
- * @param boolean $check indicates whether the function should just check if the DBMS driver
- * can perform the requested table alterations if the value is true or
- * actually perform them otherwise.
- * @access public
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- */
- function alterTable($name, $changes, $check)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- foreach ($changes as $change_name => $change) {
- switch ($change_name) {
- case 'add':
- case 'remove':
- case 'change':
- case 'rename':
- case 'name':
- break;
- default:
- return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,
- 'change type "'.$change_name.'" not yet supported', __FUNCTION__);
- }
- }
-
- if ($check) {
- return MDB2_OK;
- }
-
- $query = '';
- if (!empty($changes['name'])) {
- $change_name = $db->quoteIdentifier($changes['name'], true);
- $query .= 'RENAME TO ' . $change_name;
- }
-
- if (!empty($changes['add']) && is_array($changes['add'])) {
- foreach ($changes['add'] as $field_name => $field) {
- if ($query) {
- $query.= ', ';
- }
- $query.= 'ADD ' . $db->getDeclaration($field['type'], $field_name, $field);
- }
- }
-
- if (!empty($changes['remove']) && is_array($changes['remove'])) {
- foreach ($changes['remove'] as $field_name => $field) {
- if ($query) {
- $query.= ', ';
- }
- $field_name = $db->quoteIdentifier($field_name, true);
- $query.= 'DROP ' . $field_name;
- }
- }
-
- $rename = array();
- if (!empty($changes['rename']) && is_array($changes['rename'])) {
- foreach ($changes['rename'] as $field_name => $field) {
- $rename[$field['name']] = $field_name;
- }
- }
-
- if (!empty($changes['change']) && is_array($changes['change'])) {
- foreach ($changes['change'] as $field_name => $field) {
- if ($query) {
- $query.= ', ';
- }
- if (isset($rename[$field_name])) {
- $old_field_name = $rename[$field_name];
- unset($rename[$field_name]);
- } else {
- $old_field_name = $field_name;
- }
- $old_field_name = $db->quoteIdentifier($old_field_name, true);
- $query.= "CHANGE $old_field_name " . $db->getDeclaration($field['definition']['type'], $field_name, $field['definition']);
- }
- }
-
- if (!empty($rename) && is_array($rename)) {
- foreach ($rename as $rename_name => $renamed_field) {
- if ($query) {
- $query.= ', ';
- }
- $field = $changes['rename'][$renamed_field];
- $renamed_field = $db->quoteIdentifier($renamed_field, true);
- $query.= 'CHANGE ' . $renamed_field . ' ' . $db->getDeclaration($field['definition']['type'], $field['name'], $field['definition']);
- }
- }
-
- if (!$query) {
- return MDB2_OK;
- }
-
- $name = $db->quoteIdentifier($name, true);
- return $db->exec("ALTER TABLE $name $query");
- }
-
- // }}}
- // {{{ listDatabases()
-
- /**
- * list all databases
- *
- * @return mixed array of database names on success, a MDB2 error on failure
- * @access public
- */
- function listDatabases()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $result = $db->queryCol('SHOW DATABASES');
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listUsers()
-
- /**
- * list all users
- *
- * @return mixed array of user names on success, a MDB2 error on failure
- * @access public
- */
- function listUsers()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->queryCol('SELECT DISTINCT USER FROM mysql.USER');
- }
-
- // }}}
- // {{{ listFunctions()
-
- /**
- * list all functions in the current database
- *
- * @return mixed array of function names on success, a MDB2 error on failure
- * @access public
- */
- function listFunctions()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT name FROM mysql.proc";
- /*
- SELECT ROUTINE_NAME
- FROM INFORMATION_SCHEMA.ROUTINES
- WHERE ROUTINE_TYPE = 'FUNCTION'
- */
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTableTriggers()
-
- /**
- * list all triggers in the database that reference a given table
- *
- * @param string table for which all referenced triggers should be found
- * @return mixed array of trigger names on success, a MDB2 error on failure
- * @access public
- */
- function listTableTriggers($table = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SHOW TRIGGERS';
- if (!is_null($table)) {
- $table = $db->quote($table, 'text');
- $query .= " LIKE $table";
- }
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTables()
-
- /**
- * list all tables in the current database
- *
- * @param string database, the current is default
- * @return mixed array of table names on success, a MDB2 error on failure
- * @access public
- */
- function listTables($database = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SHOW /*!50002 FULL*/ TABLES";
- if (!is_null($database)) {
- $query .= " FROM $database";
- }
- $query.= "/*!50002 WHERE Table_type = 'BASE TABLE'*/";
-
- $table_names = $db->queryAll($query, null, MDB2_FETCHMODE_ORDERED);
- if (PEAR::isError($table_names)) {
- return $table_names;
- }
-
- $result = array();
- foreach ($table_names as $table) {
- if (!$this->_fixSequenceName($table[0], true)) {
- $result[] = $table[0];
- }
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listViews()
-
- /**
- * list all views in the current database
- *
- * @param string database, the current is default
- * @return mixed array of view names on success, a MDB2 error on failure
- * @access public
- */
- function listViews($database = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SHOW FULL TABLES';
- if (!is_null($database)) {
- $query.= " FROM $database";
- }
- $query.= " WHERE Table_type = 'VIEW'";
-
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTableFields()
-
- /**
- * list all fields in a table in the current database
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of field names on success, a MDB2 error on failure
- * @access public
- */
- function listTableFields($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = $db->quoteIdentifier($table, true);
- $result = $db->queryCol("SHOW COLUMNS FROM $table");
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ createIndex()
-
- /**
- * Get the stucture of a field into an array
- *
- * @author Leoncx
- * @param string $table name of the table on which the index is to be created
- * @param string $name name of the index to be created
- * @param array $definition associative array that defines properties of the index to be created.
- * Currently, only one property named FIELDS is supported. This property
- * is also an associative with the names of the index fields as array
- * indexes. Each entry of this array is set to another type of associative
- * array that specifies properties of the index that are specific to
- * each field.
- *
- * Currently, only the sorting property is supported. It should be used
- * to define the sorting direction of the index. It may be set to either
- * ascending or descending.
- *
- * Not all DBMS support index sorting direction configuration. The DBMS
- * drivers of those that do not support it ignore this property. Use the
- * function supports() to determine whether the DBMS driver can manage indexes.
- *
- * Example
- * array(
- * 'fields' => array(
- * 'user_name' => array(
- * 'sorting' => 'ascending'
- * 'length' => 10
- * ),
- * 'last_login' => array()
- * )
- * )
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createIndex($table, $name, $definition)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = $db->quoteIdentifier($table, true);
- $name = $db->quoteIdentifier($db->getIndexName($name), true);
- $query = "CREATE INDEX $name ON $table";
- $fields = array();
- foreach ($definition['fields'] as $field => $fieldinfo) {
- if (!empty($fieldinfo['length'])) {
- $fields[] = $db->quoteIdentifier($field, true) . '(' . $fieldinfo['length'] . ')';
- } else {
- $fields[] = $db->quoteIdentifier($field, true);
- }
- }
- $query .= ' ('. implode(', ', $fields) . ')';
- return $db->exec($query);
- }
-
- // }}}
- // {{{ dropIndex()
-
- /**
- * drop existing index
- *
- * @param string $table name of table that should be used in method
- * @param string $name name of the index to be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropIndex($table, $name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = $db->quoteIdentifier($table, true);
- $name = $db->quoteIdentifier($db->getIndexName($name), true);
- return $db->exec("DROP INDEX $name ON $table");
- }
-
- // }}}
- // {{{ listTableIndexes()
-
- /**
- * list all indexes in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of index names on success, a MDB2 error on failure
- * @access public
- */
- function listTableIndexes($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $key_name = 'Key_name';
- $non_unique = 'Non_unique';
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $key_name = strtolower($key_name);
- $non_unique = strtolower($non_unique);
- } else {
- $key_name = strtoupper($key_name);
- $non_unique = strtoupper($non_unique);
- }
- }
-
- $table = $db->quoteIdentifier($table, true);
- $query = "SHOW INDEX FROM $table";
- $indexes = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($indexes)) {
- return $indexes;
- }
-
- $result = array();
- foreach ($indexes as $index_data) {
- if ($index_data[$non_unique] && ($index = $this->_fixIndexName($index_data[$key_name]))) {
- $result[$index] = true;
- }
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_change_key_case($result, $db->options['field_case']);
- }
- return array_keys($result);
- }
-
- // }}}
- // {{{ createConstraint()
-
- /**
- * create a constraint on a table
- *
- * @param string $table name of the table on which the constraint is to be created
- * @param string $name name of the constraint to be created
- * @param array $definition associative array that defines properties of the constraint to be created.
- * Currently, only one property named FIELDS is supported. This property
- * is also an associative with the names of the constraint fields as array
- * constraints. Each entry of this array is set to another type of associative
- * array that specifies properties of the constraint that are specific to
- * each field.
- *
- * Example
- * array(
- * 'fields' => array(
- * 'user_name' => array(),
- * 'last_login' => array()
- * )
- * )
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createConstraint($table, $name, $definition)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $type = '';
- $idx_name = $db->quoteIdentifier($db->getIndexName($name), true);
- if (!empty($definition['primary'])) {
- $type = 'PRIMARY';
- $idx_name = 'KEY';
- } elseif (!empty($definition['unique'])) {
- $type = 'UNIQUE';
- } elseif (!empty($definition['foreign'])) {
- $type = 'CONSTRAINT';
- }
- if (empty($type)) {
- return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'invalid definition, could not create constraint', __FUNCTION__);
- }
-
- $table_quoted = $db->quoteIdentifier($table, true);
- $query = "ALTER TABLE $table_quoted ADD $type $idx_name";
- if (!empty($definition['foreign'])) {
- $query .= ' FOREIGN KEY';
- }
- $fields = array();
- foreach ($definition['fields'] as $field => $fieldinfo) {
- $quoted = $db->quoteIdentifier($field, true);
- if (!empty($fieldinfo['length'])) {
- $quoted .= '(' . $fieldinfo['length'] . ')';
- }
- $fields[] = $quoted;
- }
- $query .= ' ('. implode(', ', $fields) . ')';
- if (!empty($definition['foreign'])) {
- $query.= ' REFERENCES ' . $db->quoteIdentifier($definition['references']['table'], true);
- $referenced_fields = array();
- foreach (array_keys($definition['references']['fields']) as $field) {
- $referenced_fields[] = $db->quoteIdentifier($field, true);
- }
- $query .= ' ('. implode(', ', $referenced_fields) . ')';
- $query .= $this->_getAdvancedFKOptions($definition);
-
- // add index on FK column(s) or we can't add a FK constraint
- // @see http://forums.mysql.com/read.php?22,19755,226009
- $result = $this->createIndex($table, $name.'_fkidx', $definition);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- $res = $db->exec($query);
- if (PEAR::isError($res)) {
- return $res;
- }
- if (!empty($definition['foreign'])) {
- return $this->_createFKTriggers($table, array($name => $definition));
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ dropConstraint()
-
- /**
- * drop existing constraint
- *
- * @param string $table name of table that should be used in method
- * @param string $name name of the constraint to be dropped
- * @param string $primary hint if the constraint is primary
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropConstraint($table, $name, $primary = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if ($primary || strtolower($name) == 'primary') {
- $query = 'ALTER TABLE '. $db->quoteIdentifier($table, true) .' DROP PRIMARY KEY';
- return $db->exec($query);
- }
-
- //is it a FK constraint? If so, also delete the associated triggers
- $db->loadModule('Reverse', null, true);
- $definition = $db->reverse->getTableConstraintDefinition($table, $name);
- if (!PEAR::isError($definition) && !empty($definition['foreign'])) {
- //first drop the FK enforcing triggers
- $result = $this->_dropFKTriggers($table, $name, $definition['references']['table']);
- if (PEAR::isError($result)) {
- return $result;
- }
- //then drop the constraint itself
- $table = $db->quoteIdentifier($table, true);
- $name = $db->quoteIdentifier($db->getIndexName($name), true);
- $query = "ALTER TABLE $table DROP FOREIGN KEY $name";
- return $db->exec($query);
- }
-
- $table = $db->quoteIdentifier($table, true);
- $name = $db->quoteIdentifier($db->getIndexName($name), true);
- $query = "ALTER TABLE $table DROP INDEX $name";
- return $db->exec($query);
- }
-
- // }}}
- // {{{ _createFKTriggers()
-
- /**
- * Create triggers to enforce the FOREIGN KEY constraint on the table
- *
- * NB: since there's no RAISE_APPLICATION_ERROR facility in mysql,
- * we call a non-existent procedure to raise the FK violation message.
- * @see http://forums.mysql.com/read.php?99,55108,71877#msg-71877
- *
- * @param string $table table name
- * @param array $foreign_keys FOREIGN KEY definitions
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access private
- */
- function _createFKTriggers($table, $foreign_keys)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- // create triggers to enforce FOREIGN KEY constraints
- if ($db->supports('triggers') && !empty($foreign_keys)) {
- $table_quoted = $db->quoteIdentifier($table, true);
- foreach ($foreign_keys as $fkname => $fkdef) {
- if (empty($fkdef)) {
- continue;
- }
- //set actions to default if not set
- $fkdef['onupdate'] = empty($fkdef['onupdate']) ? $db->options['default_fk_action_onupdate'] : strtoupper($fkdef['onupdate']);
- $fkdef['ondelete'] = empty($fkdef['ondelete']) ? $db->options['default_fk_action_ondelete'] : strtoupper($fkdef['ondelete']);
-
- $trigger_names = array(
- 'insert' => $fkname.'_insert_trg',
- 'update' => $fkname.'_update_trg',
- 'pk_update' => $fkname.'_pk_update_trg',
- 'pk_delete' => $fkname.'_pk_delete_trg',
- );
- $table_fields = array_keys($fkdef['fields']);
- $referenced_fields = array_keys($fkdef['references']['fields']);
-
- //create the ON [UPDATE|DELETE] triggers on the primary table
- $restrict_action = ' IF (SELECT ';
- $aliased_fields = array();
- foreach ($table_fields as $field) {
- $aliased_fields[] = $table_quoted .'.'.$field .' AS '.$field;
- }
- $restrict_action .= implode(',', $aliased_fields)
- .' FROM '.$table_quoted
- .' WHERE ';
- $conditions = array();
- $new_values = array();
- $null_values = array();
- for ($i=0; $i<count($table_fields); $i++) {
- $conditions[] = $table_fields[$i] .' = OLD.'.$referenced_fields[$i];
- $new_values[] = $table_fields[$i] .' = NEW.'.$referenced_fields[$i];
- $null_values[] = $table_fields[$i] .' = NULL';
- }
- $conditions2 = array();
- for ($i=0; $i<count($referenced_fields); $i++) {
- $conditions2[] = 'NEW.'.$referenced_fields[$i] .' <> OLD.'.$referenced_fields[$i];
- }
- $restrict_action .= implode(' AND ', $conditions).') IS NOT NULL'
- .' AND (' .implode(' OR ', $conditions2) .')'
- .' THEN CALL %s_ON_TABLE_'.$table.'_VIOLATES_FOREIGN_KEY_CONSTRAINT();'
- .' END IF;';
-
- $cascade_action_update = 'UPDATE '.$table_quoted.' SET '.implode(', ', $new_values) .' WHERE '.implode(' AND ', $conditions). ';';
- $cascade_action_delete = 'DELETE FROM '.$table_quoted.' WHERE '.implode(' AND ', $conditions). ';';
- $setnull_action = 'UPDATE '.$table_quoted.' SET '.implode(', ', $null_values).' WHERE '.implode(' AND ', $conditions). ';';
-
- if ('SET DEFAULT' == $fkdef['onupdate'] || 'SET DEFAULT' == $fkdef['ondelete']) {
- $db->loadModule('Reverse', null, true);
- $default_values = array();
- foreach ($table_fields as $table_field) {
- $field_definition = $db->reverse->getTableFieldDefinition($table, $field);
- if (PEAR::isError($field_definition)) {
- return $field_definition;
- }
- $default_values[] = $table_field .' = '. $field_definition[0]['default'];
- }
- $setdefault_action = 'UPDATE '.$table_quoted.' SET '.implode(', ', $default_values).' WHERE '.implode(' AND ', $conditions). ';';
- }
-
- $query = 'CREATE TRIGGER %s'
- .' %s ON '.$fkdef['references']['table']
- .' FOR EACH ROW BEGIN '
- .' SET FOREIGN_KEY_CHECKS = 0; '; //only really needed for ON UPDATE CASCADE
-
- if ('CASCADE' == $fkdef['onupdate']) {
- $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $cascade_action_update;
- } elseif ('SET NULL' == $fkdef['onupdate']) {
- $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setnull_action;
- } elseif ('SET DEFAULT' == $fkdef['onupdate']) {
- $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setdefault_action;
- } elseif ('NO ACTION' == $fkdef['onupdate']) {
- $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'AFTER UPDATE', 'update');
- } elseif ('RESTRICT' == $fkdef['onupdate']) {
- $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update');
- }
- if ('CASCADE' == $fkdef['ondelete']) {
- $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $cascade_action_delete;
- } elseif ('SET NULL' == $fkdef['ondelete']) {
- $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setnull_action;
- } elseif ('SET DEFAULT' == $fkdef['ondelete']) {
- $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setdefault_action;
- } elseif ('NO ACTION' == $fkdef['ondelete']) {
- $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'AFTER DELETE', 'delete');
- } elseif ('RESTRICT' == $fkdef['ondelete']) {
- $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete');
- }
- $sql_update .= ' SET FOREIGN_KEY_CHECKS = 1; END;';
- $sql_delete .= ' SET FOREIGN_KEY_CHECKS = 1; END;';
-
- $db->pushErrorHandling(PEAR_ERROR_RETURN);
- $db->expectError(MDB2_ERROR_CANNOT_CREATE);
- $result = $db->exec($sql_delete);
- $expected_errmsg = 'This MySQL version doesn\'t support multiple triggers with the same action time and event for one table';
- $db->popExpect();
- $db->popErrorHandling();
- if (PEAR::isError($result)) {
- if ($result->getCode() != MDB2_ERROR_CANNOT_CREATE) {
- return $result;
- }
- $db->warnings[] = $expected_errmsg;
- }
- $db->pushErrorHandling(PEAR_ERROR_RETURN);
- $db->expectError(MDB2_ERROR_CANNOT_CREATE);
- $result = $db->exec($sql_update);
- $db->popExpect();
- $db->popErrorHandling();
- if (PEAR::isError($result) && $result->getCode() != MDB2_ERROR_CANNOT_CREATE) {
- if ($result->getCode() != MDB2_ERROR_CANNOT_CREATE) {
- return $result;
- }
- $db->warnings[] = $expected_errmsg;
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ _dropFKTriggers()
-
- /**
- * Drop the triggers created to enforce the FOREIGN KEY constraint on the table
- *
- * @param string $table table name
- * @param string $fkname FOREIGN KEY constraint name
- * @param string $referenced_table referenced table name
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access private
- */
- function _dropFKTriggers($table, $fkname, $referenced_table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $triggers = $this->listTableTriggers($table);
- $triggers2 = $this->listTableTriggers($referenced_table);
- if (!PEAR::isError($triggers2) && !PEAR::isError($triggers)) {
- $triggers = array_merge($triggers, $triggers2);
- $pattern = '/^'.$fkname.'(_pk)?_(insert|update|delete)_trg$/i';
- foreach ($triggers as $trigger) {
- if (preg_match($pattern, $trigger)) {
- $result = $db->exec('DROP TRIGGER '.$trigger);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ listTableConstraints()
-
- /**
- * list all constraints in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of constraint names on success, a MDB2 error on failure
- * @access public
- */
- function listTableConstraints($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $key_name = 'Key_name';
- $non_unique = 'Non_unique';
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $key_name = strtolower($key_name);
- $non_unique = strtolower($non_unique);
- } else {
- $key_name = strtoupper($key_name);
- $non_unique = strtoupper($non_unique);
- }
- }
-
- $query = 'SHOW INDEX FROM ' . $db->quoteIdentifier($table, true);
- $indexes = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($indexes)) {
- return $indexes;
- }
-
- $result = array();
- foreach ($indexes as $index_data) {
- if (!$index_data[$non_unique]) {
- if ($index_data[$key_name] !== 'PRIMARY') {
- $index = $this->_fixIndexName($index_data[$key_name]);
- } else {
- $index = 'PRIMARY';
- }
- if (!empty($index)) {
- $result[$index] = true;
- }
- }
- }
-
- //list FOREIGN KEY constraints...
- $query = 'SHOW CREATE TABLE '. $db->escape($table);
- $definition = $db->queryOne($query, 'text', 1);
- if (!PEAR::isError($definition) && !empty($definition)) {
- $pattern = '/\bCONSTRAINT\b\s+([^\s]+)\s+\bFOREIGN KEY\b/Uims';
- if (preg_match_all($pattern, str_replace('`', '', $definition), $matches) > 0) {
- foreach ($matches[1] as $constraint) {
- $result[$constraint] = true;
- }
- }
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_change_key_case($result, $db->options['field_case']);
- }
- return array_keys($result);
- }
-
- // }}}
- // {{{ createSequence()
-
- /**
- * create sequence
- *
- * @param string $seq_name name of the sequence to be created
- * @param string $start start value of the sequence; default is 1
- * @param array $options An associative array of table options:
- * array(
- * 'comment' => 'Foo',
- * 'charset' => 'utf8',
- * 'collate' => 'utf8_unicode_ci',
- * 'type' => 'innodb',
- * );
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createSequence($seq_name, $start = 1, $options = array())
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
- $seqcol_name = $db->quoteIdentifier($db->options['seqcol_name'], true);
-
- $options_strings = array();
-
- if (!empty($options['comment'])) {
- $options_strings['comment'] = 'COMMENT = '.$db->quote($options['comment'], 'text');
- }
-
- if (!empty($options['charset'])) {
- $options_strings['charset'] = 'DEFAULT CHARACTER SET '.$options['charset'];
- if (!empty($options['collate'])) {
- $options_strings['charset'].= ' COLLATE '.$options['collate'];
- }
- }
-
- $type = false;
- if (!empty($options['type'])) {
- $type = $options['type'];
- } elseif ($db->options['default_table_type']) {
- $type = $db->options['default_table_type'];
- }
- if ($type) {
- $options_strings[] = "ENGINE = $type";
- }
-
- $query = "CREATE TABLE $sequence_name ($seqcol_name INT NOT NULL AUTO_INCREMENT, PRIMARY KEY ($seqcol_name))";
- if (!empty($options_strings)) {
- $query .= ' '.implode(' ', $options_strings);
- }
- $res = $db->exec($query);
- if (PEAR::isError($res)) {
- return $res;
- }
-
- if ($start == 1) {
- return MDB2_OK;
- }
-
- $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (".($start-1).')';
- $res = $db->exec($query);
- if (!PEAR::isError($res)) {
- return MDB2_OK;
- }
-
- // Handle error
- $result = $db->exec("DROP TABLE $sequence_name");
- if (PEAR::isError($result)) {
- return $db->raiseError($result, null, null,
- 'could not drop inconsistent sequence table', __FUNCTION__);
- }
-
- return $db->raiseError($res, null, null,
- 'could not create sequence table', __FUNCTION__);
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * drop existing sequence
- *
- * @param string $seq_name name of the sequence to be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropSequence($seq_name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
- return $db->exec("DROP TABLE $sequence_name");
- }
-
- // }}}
- // {{{ listSequences()
-
- /**
- * list all sequences in the current database
- *
- * @param string database, the current is default
- * @return mixed array of sequence names on success, a MDB2 error on failure
- * @access public
- */
- function listSequences($database = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SHOW TABLES";
- if (!is_null($database)) {
- $query .= " FROM $database";
- }
- $table_names = $db->queryCol($query);
- if (PEAR::isError($table_names)) {
- return $table_names;
- }
-
- $result = array();
- foreach ($table_names as $table_name) {
- if ($sqn = $this->_fixSequenceName($table_name, true)) {
- $result[] = $sqn;
- }
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
-}
-?> \ No newline at end of file
diff --git a/inc/MDB2/Driver/Manager/pgsql.php b/inc/MDB2/Driver/Manager/pgsql.php
deleted file mode 100644
index 1a7e851897c..00000000000
--- a/inc/MDB2/Driver/Manager/pgsql.php
+++ /dev/null
@@ -1,948 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Paul Cooper <pgc@ucecom.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: pgsql.php,v 1.87 2008/11/29 14:09:59 afz Exp $
-
-oc_require_once('MDB2/Driver/Manager/Common.php');
-
-/**
- * MDB2 MySQL driver for the management modules
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper <pgc@ucecom.com>
- */
-class MDB2_Driver_Manager_pgsql extends MDB2_Driver_Manager_Common
-{
- // {{{ createDatabase()
-
- /**
- * create a new database
- *
- * @param string $name name of the database that should be created
- * @param array $options array with charset info
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createDatabase($name, $options = array())
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- $query = 'CREATE DATABASE ' . $name;
- if (!empty($options['charset'])) {
- $query .= ' WITH ENCODING ' . $db->quote($options['charset'], 'text');
- }
- return $db->standaloneQuery($query, null, true);
- }
-
- // }}}
- // {{{ alterDatabase()
-
- /**
- * alter an existing database
- *
- * @param string $name name of the database that is intended to be changed
- * @param array $options array with name, owner info
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function alterDatabase($name, $options = array())
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'ALTER DATABASE '. $db->quoteIdentifier($name, true);
- if (!empty($options['name'])) {
- $query .= ' RENAME TO ' . $options['name'];
- }
- if (!empty($options['owner'])) {
- $query .= ' OWNER TO ' . $options['owner'];
- }
- return $db->standaloneQuery($query, null, true);
- }
-
- // }}}
- // {{{ dropDatabase()
-
- /**
- * drop an existing database
- *
- * @param string $name name of the database that should be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropDatabase($name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- $query = "DROP DATABASE $name";
- return $db->standaloneQuery($query, null, true);
- }
-
- // }}}
- // {{{ _getAdvancedFKOptions()
-
- /**
- * Return the FOREIGN KEY query section dealing with non-standard options
- * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
- *
- * @param array $definition
- * @return string
- * @access protected
- */
- function _getAdvancedFKOptions($definition)
- {
- $query = '';
- if (!empty($definition['match'])) {
- $query .= ' MATCH '.$definition['match'];
- }
- if (!empty($definition['onupdate'])) {
- $query .= ' ON UPDATE '.$definition['onupdate'];
- }
- if (!empty($definition['ondelete'])) {
- $query .= ' ON DELETE '.$definition['ondelete'];
- }
- if (!empty($definition['deferrable'])) {
- $query .= ' DEFERRABLE';
- } else {
- $query .= ' NOT DEFERRABLE';
- }
- if (!empty($definition['initiallydeferred'])) {
- $query .= ' INITIALLY DEFERRED';
- } else {
- $query .= ' INITIALLY IMMEDIATE';
- }
- return $query;
- }
-
- // }}}
- // {{{ truncateTable()
-
- /**
- * Truncate an existing table (if the TRUNCATE TABLE syntax is not supported,
- * it falls back to a DELETE FROM TABLE query)
- *
- * @param string $name name of the table that should be truncated
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function truncateTable($name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->quoteIdentifier($name, true);
- return $db->exec("TRUNCATE TABLE $name");
- }
-
- // }}}
- // {{{ vacuum()
-
- /**
- * Optimize (vacuum) all the tables in the db (or only the specified table)
- * and optionally run ANALYZE.
- *
- * @param string $table table name (all the tables if empty)
- * @param array $options an array with driver-specific options:
- * - timeout [int] (in seconds) [mssql-only]
- * - analyze [boolean] [pgsql and mysql]
- * - full [boolean] [pgsql-only]
- * - freeze [boolean] [pgsql-only]
- *
- * @return mixed MDB2_OK success, a MDB2 error on failure
- * @access public
- */
- function vacuum($table = null, $options = array())
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $query = 'VACUUM';
-
- if (!empty($options['full'])) {
- $query .= ' FULL';
- }
- if (!empty($options['freeze'])) {
- $query .= ' FREEZE';
- }
- if (!empty($options['analyze'])) {
- $query .= ' ANALYZE';
- }
-
- if (!empty($table)) {
- $query .= ' '.$db->quoteIdentifier($table, true);
- }
- return $db->exec($query);
- }
-
- // }}}
- // {{{ alterTable()
-
- /**
- * alter an existing table
- *
- * @param string $name name of the table that is intended to be changed.
- * @param array $changes associative array that contains the details of each type
- * of change that is intended to be performed. The types of
- * changes that are currently supported are defined as follows:
- *
- * name
- *
- * New name for the table.
- *
- * add
- *
- * Associative array with the names of fields to be added as
- * indexes of the array. The value of each entry of the array
- * should be set to another associative array with the properties
- * of the fields to be added. The properties of the fields should
- * be the same as defined by the MDB2 parser.
- *
- *
- * remove
- *
- * Associative array with the names of fields to be removed as indexes
- * of the array. Currently the values assigned to each entry are ignored.
- * An empty array should be used for future compatibility.
- *
- * rename
- *
- * Associative array with the names of fields to be renamed as indexes
- * of the array. The value of each entry of the array should be set to
- * another associative array with the entry named name with the new
- * field name and the entry named Declaration that is expected to contain
- * the portion of the field declaration already in DBMS specific SQL code
- * as it is used in the CREATE TABLE statement.
- *
- * change
- *
- * Associative array with the names of the fields to be changed as indexes
- * of the array. Keep in mind that if it is intended to change either the
- * name of a field and any other properties, the change array entries
- * should have the new names of the fields as array indexes.
- *
- * The value of each entry of the array should be set to another associative
- * array with the properties of the fields to that are meant to be changed as
- * array entries. These entries should be assigned to the new values of the
- * respective properties. The properties of the fields should be the same
- * as defined by the MDB2 parser.
- *
- * Example
- * array(
- * 'name' => 'userlist',
- * 'add' => array(
- * 'quota' => array(
- * 'type' => 'integer',
- * 'unsigned' => 1
- * )
- * ),
- * 'remove' => array(
- * 'file_limit' => array(),
- * 'time_limit' => array()
- * ),
- * 'change' => array(
- * 'name' => array(
- * 'length' => '20',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 20,
- * ),
- * )
- * ),
- * 'rename' => array(
- * 'sex' => array(
- * 'name' => 'gender',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 1,
- * 'default' => 'M',
- * ),
- * )
- * )
- * )
- *
- * @param boolean $check indicates whether the function should just check if the DBMS driver
- * can perform the requested table alterations if the value is true or
- * actually perform them otherwise.
- * @access public
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- */
- function alterTable($name, $changes, $check)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- foreach ($changes as $change_name => $change) {
- switch ($change_name) {
- case 'add':
- case 'remove':
- case 'change':
- case 'name':
- case 'rename':
- break;
- default:
- return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,
- 'change type "'.$change_name.'\" not yet supported', __FUNCTION__);
- }
- }
-
- if ($check) {
- return MDB2_OK;
- }
-
- $name = $db->quoteIdentifier($name, true);
-
- if (!empty($changes['remove']) && is_array($changes['remove'])) {
- foreach ($changes['remove'] as $field_name => $field) {
- $field_name = $db->quoteIdentifier($field_name, true);
- $query = 'DROP ' . $field_name;
- $result = $db->exec("ALTER TABLE $name $query");
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
-
- if (!empty($changes['rename']) && is_array($changes['rename'])) {
- foreach ($changes['rename'] as $field_name => $field) {
- $field_name = $db->quoteIdentifier($field_name, true);
- $result = $db->exec("ALTER TABLE $name RENAME COLUMN $field_name TO ".$db->quoteIdentifier($field['name'], true));
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
-
- if (!empty($changes['add']) && is_array($changes['add'])) {
- foreach ($changes['add'] as $field_name => $field) {
- $query = 'ADD ' . $db->getDeclaration($field['type'], $field_name, $field);
- $result = $db->exec("ALTER TABLE $name $query");
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
-
- if (!empty($changes['change']) && is_array($changes['change'])) {
- foreach ($changes['change'] as $field_name => $field) {
- $field_name = $db->quoteIdentifier($field_name, true);
- if (!empty($field['definition']['type'])) {
- $server_info = $db->getServerVersion();
- if (PEAR::isError($server_info)) {
- return $server_info;
- }
- if (is_array($server_info) && $server_info['major'] < 8) {
- return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,
- 'changing column type for "'.$change_name.'\" requires PostgreSQL 8.0 or above', __FUNCTION__);
- }
- $db->loadModule('Datatype', null, true);
- $type = $db->datatype->getTypeDeclaration($field['definition']);
- $query = "ALTER $field_name TYPE $type USING CAST($field_name AS $type)";
- $result = $db->exec("ALTER TABLE $name $query");
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- if (array_key_exists('default', $field['definition'])) {
- $query = "ALTER $field_name SET DEFAULT ".$db->quote($field['definition']['default'], $field['definition']['type']);
- $result = $db->exec("ALTER TABLE $name $query");
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- if (!empty($field['definition']['notnull'])) {
- $query = "ALTER $field_name ".($field['definition']['notnull'] ? 'SET' : 'DROP').' NOT NULL';
- $result = $db->exec("ALTER TABLE $name $query");
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- }
-
- if (!empty($changes['name'])) {
- $change_name = $db->quoteIdentifier($changes['name'], true);
- $result = $db->exec("ALTER TABLE $name RENAME TO ".$change_name);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ listDatabases()
-
- /**
- * list all databases
- *
- * @return mixed array of database names on success, a MDB2 error on failure
- * @access public
- */
- function listDatabases()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SELECT datname FROM pg_database';
- $result2 = $db->standaloneQuery($query, array('text'), false);
- if (!MDB2::isResultCommon($result2)) {
- return $result2;
- }
-
- $result = $result2->fetchCol();
- $result2->free();
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listUsers()
-
- /**
- * list all users
- *
- * @return mixed array of user names on success, a MDB2 error on failure
- * @access public
- */
- function listUsers()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SELECT usename FROM pg_user';
- $result2 = $db->standaloneQuery($query, array('text'), false);
- if (!MDB2::isResultCommon($result2)) {
- return $result2;
- }
-
- $result = $result2->fetchCol();
- $result2->free();
- return $result;
- }
-
- // }}}
- // {{{ listViews()
-
- /**
- * list all views in the current database
- *
- * @return mixed array of view names on success, a MDB2 error on failure
- * @access public
- */
- function listViews()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT viewname
- FROM pg_views
- WHERE schemaname NOT IN ('pg_catalog', 'information_schema')
- AND viewname !~ '^pg_'";
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTableViews()
-
- /**
- * list the views in the database that reference a given table
- *
- * @param string table for which all referenced views should be found
- * @return mixed array of view names on success, a MDB2 error on failure
- * @access public
- */
- function listTableViews($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SELECT viewname FROM pg_views NATURAL JOIN pg_tables';
- $query.= ' WHERE tablename ='.$db->quote($table, 'text');
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listFunctions()
-
- /**
- * list all functions in the current database
- *
- * @return mixed array of function names on success, a MDB2 error on failure
- * @access public
- */
- function listFunctions()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "
- SELECT
- proname
- FROM
- pg_proc pr,
- pg_type tp
- WHERE
- tp.oid = pr.prorettype
- AND pr.proisagg = FALSE
- AND tp.typname <> 'trigger'
- AND pr.pronamespace IN
- (SELECT oid FROM pg_namespace WHERE nspname NOT LIKE 'pg_%' AND nspname != 'information_schema')";
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTableTriggers()
-
- /**
- * list all triggers in the database that reference a given table
- *
- * @param string table for which all referenced triggers should be found
- * @return mixed array of trigger names on success, a MDB2 error on failure
- * @access public
- */
- function listTableTriggers($table = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SELECT trg.tgname AS trigger_name
- FROM pg_trigger trg,
- pg_class tbl
- WHERE trg.tgrelid = tbl.oid';
- if (!is_null($table)) {
- $table = $db->quote(strtoupper($table), 'text');
- $query .= " AND tbl.relname = $table";
- }
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTables()
-
- /**
- * list all tables in the current database
- *
- * @return mixed array of table names on success, a MDB2 error on failure
- * @access public
- */
- function listTables()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- // gratuitously stolen from PEAR DB _getSpecialQuery in pgsql.php
- $query = '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_'";
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTableFields()
-
- /**
- * list all fields in a table in the current database
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of field names on success, a MDB2 error on failure
- * @access public
- */
- function listTableFields($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table);
-
- $table = $db->quoteIdentifier($table, true);
- if (!empty($schema)) {
- $table = $db->quoteIdentifier($schema, true) . '.' .$table;
- }
- $db->setLimit(1);
- $result2 = $db->query("SELECT * FROM $table");
- if (PEAR::isError($result2)) {
- return $result2;
- }
- $result = $result2->getColumnNames();
- $result2->free();
- if (PEAR::isError($result)) {
- return $result;
- }
- return array_flip($result);
- }
-
- // }}}
- // {{{ listTableIndexes()
-
- /**
- * list all indexes in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of index names on success, a MDB2 error on failure
- * @access public
- */
- function listTableIndexes($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table);
-
- $table = $db->quote($table, 'text');
- $subquery = "SELECT indexrelid
- FROM pg_index
- LEFT JOIN pg_class ON pg_class.oid = pg_index.indrelid
- LEFT JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid
- WHERE pg_class.relname = $table
- AND indisunique != 't'
- AND indisprimary != 't'";
- if (!empty($schema)) {
- $subquery .= ' AND pg_namespace.nspname = '.$db->quote($schema, 'text');
- }
- $query = "SELECT relname FROM pg_class WHERE oid IN ($subquery)";
- $indexes = $db->queryCol($query, 'text');
- if (PEAR::isError($indexes)) {
- return $indexes;
- }
-
- $result = array();
- foreach ($indexes as $index) {
- $index = $this->_fixIndexName($index);
- if (!empty($index)) {
- $result[$index] = true;
- }
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_change_key_case($result, $db->options['field_case']);
- }
- return array_keys($result);
- }
-
- // }}}
- // {{{ dropConstraint()
-
- /**
- * drop existing constraint
- *
- * @param string $table name of table that should be used in method
- * @param string $name name of the constraint to be dropped
- * @param string $primary hint if the constraint is primary
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropConstraint($table, $name, $primary = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- // is it an UNIQUE index?
- $query = 'SELECT relname
- FROM pg_class
- WHERE oid IN (
- SELECT indexrelid
- FROM pg_index, pg_class
- WHERE pg_class.relname = '.$db->quote($table, 'text').'
- AND pg_class.oid = pg_index.indrelid
- AND indisunique = \'t\')
- EXCEPT
- SELECT conname
- FROM pg_constraint, pg_class
- WHERE pg_constraint.conrelid = pg_class.oid
- AND relname = '. $db->quote($table, 'text');
- $unique = $db->queryCol($query, 'text');
- if (PEAR::isError($unique) || empty($unique)) {
- // not an UNIQUE index, maybe a CONSTRAINT
- return parent::dropConstraint($table, $name, $primary);
- }
-
- if (in_array($name, $unique)) {
- return $db->exec('DROP INDEX '.$db->quoteIdentifier($name, true));
- }
- $idxname = $db->getIndexName($name);
- if (in_array($idxname, $unique)) {
- return $db->exec('DROP INDEX '.$db->quoteIdentifier($idxname, true));
- }
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $name . ' is not an existing constraint for table ' . $table, __FUNCTION__);
- }
-
- // }}}
- // {{{ listTableConstraints()
-
- /**
- * list all constraints in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of constraint names on success, a MDB2 error on failure
- * @access public
- */
- function listTableConstraints($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table);
-
- $table = $db->quote($table, 'text');
- $query = 'SELECT conname
- FROM pg_constraint
- LEFT JOIN pg_class ON pg_constraint.conrelid = pg_class.oid
- LEFT JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid
- WHERE relname = ' .$table;
- if (!empty($schema)) {
- $query .= ' AND pg_namespace.nspname = ' . $db->quote($schema, 'text');
- }
- $query .= '
- UNION DISTINCT
- SELECT relname
- FROM pg_class
- WHERE oid IN (
- SELECT indexrelid
- FROM pg_index
- LEFT JOIN pg_class ON pg_class.oid = pg_index.indrelid
- LEFT JOIN pg_namespace ON pg_class.relnamespace = pg_namespace.oid
- WHERE pg_class.relname = '.$table.'
- AND indisunique = \'t\'';
- if (!empty($schema)) {
- $query .= ' AND pg_namespace.nspname = ' . $db->quote($schema, 'text');
- }
- $query .= ')';
- $constraints = $db->queryCol($query);
- if (PEAR::isError($constraints)) {
- return $constraints;
- }
-
- $result = array();
- foreach ($constraints as $constraint) {
- $constraint = $this->_fixIndexName($constraint);
- if (!empty($constraint)) {
- $result[$constraint] = true;
- }
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
- && $db->options['field_case'] == CASE_LOWER
- ) {
- $result = array_change_key_case($result, $db->options['field_case']);
- }
- return array_keys($result);
- }
-
- // }}}
- // {{{ createSequence()
-
- /**
- * create sequence
- *
- * @param string $seq_name name of the sequence to be created
- * @param string $start start value of the sequence; default is 1
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createSequence($seq_name, $start = 1)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
- return $db->exec("CREATE SEQUENCE $sequence_name INCREMENT 1".
- ($start < 1 ? " MINVALUE $start" : '')." START $start");
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * drop existing sequence
- *
- * @param string $seq_name name of the sequence to be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropSequence($seq_name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
- return $db->exec("DROP SEQUENCE $sequence_name");
- }
-
- // }}}
- // {{{ listSequences()
-
- /**
- * list all sequences in the current database
- *
- * @return mixed array of sequence names on success, a MDB2 error on failure
- * @access public
- */
- function listSequences()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT relname FROM pg_class WHERE relkind = 'S' AND relnamespace IN";
- $query.= "(SELECT oid FROM pg_namespace WHERE nspname NOT LIKE 'pg_%' AND nspname != 'information_schema')";
- $table_names = $db->queryCol($query);
- if (PEAR::isError($table_names)) {
- return $table_names;
- }
- $result = array();
- foreach ($table_names as $table_name) {
- $result[] = $this->_fixSequenceName($table_name);
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-}
-?> \ No newline at end of file
diff --git a/inc/MDB2/Driver/Manager/sqlite.php b/inc/MDB2/Driver/Manager/sqlite.php
deleted file mode 100644
index 85751d39a3f..00000000000
--- a/inc/MDB2/Driver/Manager/sqlite.php
+++ /dev/null
@@ -1,1362 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith, Lorenzo Alberton |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS 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. |
-// +----------------------------------------------------------------------+
-// | Authors: Lukas Smith <smith@pooteeweet.org> |
-// | Lorenzo Alberton <l.alberton@quipo.it> |
-// +----------------------------------------------------------------------+
-//
-// $Id: sqlite.php,v 1.76 2008/05/31 11:48:48 quipo Exp $
-//
-
-oc_require_once('MDB2/Driver/Manager/Common.php');
-
-/**
- * MDB2 SQLite driver for the management modules
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Lorenzo Alberton <l.alberton@quipo.it>
- */
-class MDB2_Driver_Manager_sqlite extends MDB2_Driver_Manager_Common
-{
- // {{{ createDatabase()
-
- /**
- * create a new database
- *
- * @param string $name name of the database that should be created
- * @param array $options array with charset info
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createDatabase($name, $options = array())
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $database_file = $db->_getDatabaseFile($name);
- if (file_exists($database_file)) {
- return $db->raiseError(MDB2_ERROR_ALREADY_EXISTS, null, null,
- 'database already exists', __FUNCTION__);
- }
- $php_errormsg = '';
- $handle = @sqlite_open($database_file, $db->dsn['mode'], $php_errormsg);
- if (!$handle) {
- return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,
- (isset($php_errormsg) ? $php_errormsg : 'could not create the database file'), __FUNCTION__);
- }
- if (!empty($options['charset'])) {
- $query = 'PRAGMA encoding = ' . $db->quote($options['charset'], 'text');
- @sqlite_query($query, $handle);
- }
- @sqlite_close($handle);
- return MDB2_OK;
- }
-
- // }}}
- // {{{ dropDatabase()
-
- /**
- * drop an existing database
- *
- * @param string $name name of the database that should be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropDatabase($name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $database_file = $db->_getDatabaseFile($name);
- if (!@file_exists($database_file)) {
- return $db->raiseError(MDB2_ERROR_CANNOT_DROP, null, null,
- 'database does not exist', __FUNCTION__);
- }
- $result = @unlink($database_file);
- if (!$result) {
- return $db->raiseError(MDB2_ERROR_CANNOT_DROP, null, null,
- (isset($php_errormsg) ? $php_errormsg : 'could not remove the database file'), __FUNCTION__);
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ _getAdvancedFKOptions()
-
- /**
- * Return the FOREIGN KEY query section dealing with non-standard options
- * as MATCH, INITIALLY DEFERRED, ON UPDATE, ...
- *
- * @param array $definition
- * @return string
- * @access protected
- */
- function _getAdvancedFKOptions($definition)
- {
- $query = '';
- if (!empty($definition['match'])) {
- $query .= ' MATCH '.$definition['match'];
- }
- if (!empty($definition['onupdate']) && (strtoupper($definition['onupdate']) != 'NO ACTION')) {
- $query .= ' ON UPDATE '.$definition['onupdate'];
- }
- if (!empty($definition['ondelete']) && (strtoupper($definition['ondelete']) != 'NO ACTION')) {
- $query .= ' ON DELETE '.$definition['ondelete'];
- }
- if (!empty($definition['deferrable'])) {
- $query .= ' DEFERRABLE';
- } else {
- $query .= ' NOT DEFERRABLE';
- }
- if (!empty($definition['initiallydeferred'])) {
- $query .= ' INITIALLY DEFERRED';
- } else {
- $query .= ' INITIALLY IMMEDIATE';
- }
- return $query;
- }
-
- // }}}
- // {{{ _getCreateTableQuery()
-
- /**
- * Create a basic SQL query for a new table creation
- * @param string $name Name of the database that should be created
- * @param array $fields Associative array that contains the definition of each field of the new table
- * @param array $options An associative array of table options
- * @return mixed string (the SQL query) on success, a MDB2 error on failure
- * @see createTable()
- */
- function _getCreateTableQuery($name, $fields, $options = array())
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!$name) {
- return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,
- 'no valid table name specified', __FUNCTION__);
- }
- if (empty($fields)) {
- return $db->raiseError(MDB2_ERROR_CANNOT_CREATE, null, null,
- 'no fields specified for table "'.$name.'"', __FUNCTION__);
- }
- $query_fields = $this->getFieldDeclarationList($fields);
- if (PEAR::isError($query_fields)) {
- return $query_fields;
- }
- if (!empty($options['primary'])) {
- $query_fields.= ', PRIMARY KEY ('.implode(', ', array_keys($options['primary'])).')';
- }
- if (!empty($options['foreign_keys'])) {
- foreach ($options['foreign_keys'] as $fkname => $fkdef) {
- if (empty($fkdef)) {
- continue;
- }
- $query_fields.= ', CONSTRAINT '.$fkname.' FOREIGN KEY ('.implode(', ', array_keys($fkdef['fields'])).')';
- $query_fields.= ' REFERENCES '.$fkdef['references']['table'].' ('.implode(', ', array_keys($fkdef['references']['fields'])).')';
- $query_fields.= $this->_getAdvancedFKOptions($fkdef);
- }
- }
-
- $name = $db->quoteIdentifier($name, true);
- $result = 'CREATE ';
- if (!empty($options['temporary'])) {
- $result .= $this->_getTemporaryTableQuery();
- }
- $result .= " TABLE $name ($query_fields)";
- return $result;
- }
-
- // }}}
- // {{{ createTable()
-
- /**
- * create a new table
- *
- * @param string $name Name of the database that should be created
- * @param array $fields Associative array that contains the definition
- * of each field of the new table
- * @param array $options An associative array of table options
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createTable($name, $fields, $options = array())
- {
- $result = parent::createTable($name, $fields, $options);
- if (PEAR::isError($result)) {
- return $result;
- }
- // create triggers to enforce FOREIGN KEY constraints
- if (!empty($options['foreign_keys'])) {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- foreach ($options['foreign_keys'] as $fkname => $fkdef) {
- if (empty($fkdef)) {
- continue;
- }
- //set actions to default if not set
- $fkdef['onupdate'] = empty($fkdef['onupdate']) ? $db->options['default_fk_action_onupdate'] : strtoupper($fkdef['onupdate']);
- $fkdef['ondelete'] = empty($fkdef['ondelete']) ? $db->options['default_fk_action_ondelete'] : strtoupper($fkdef['ondelete']);
-
- $trigger_names = array(
- 'insert' => $fkname.'_insert_trg',
- 'update' => $fkname.'_update_trg',
- 'pk_update' => $fkname.'_pk_update_trg',
- 'pk_delete' => $fkname.'_pk_delete_trg',
- );
-
- //create the [insert|update] triggers on the FK table
- $table_fields = array_keys($fkdef['fields']);
- $referenced_fields = array_keys($fkdef['references']['fields']);
- $query = 'CREATE TRIGGER %s BEFORE %s ON '.$name
- .' FOR EACH ROW BEGIN'
- .' SELECT RAISE(ROLLBACK, \'%s on table "'.$name.'" violates FOREIGN KEY constraint "'.$fkname.'"\')'
- .' WHERE (SELECT ';
- $aliased_fields = array();
- foreach ($referenced_fields as $field) {
- $aliased_fields[] = $fkdef['references']['table'] .'.'.$field .' AS '.$field;
- }
- $query .= implode(',', $aliased_fields)
- .' FROM '.$fkdef['references']['table']
- .' WHERE ';
- $conditions = array();
- for ($i=0; $i<count($table_fields); $i++) {
- $conditions[] = $referenced_fields[$i] .' = NEW.'.$table_fields[$i];
- }
- $query .= implode(' AND ', $conditions).') IS NULL; END;';
- $result = $db->exec(sprintf($query, $trigger_names['insert'], 'INSERT', 'insert'));
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $result = $db->exec(sprintf($query, $trigger_names['update'], 'UPDATE', 'update'));
- if (PEAR::isError($result)) {
- return $result;
- }
-
- //create the ON [UPDATE|DELETE] triggers on the primary table
- $restrict_action = 'SELECT RAISE(ROLLBACK, \'%s on table "'.$name.'" violates FOREIGN KEY constraint "'.$fkname.'"\')'
- .' WHERE (SELECT ';
- $aliased_fields = array();
- foreach ($table_fields as $field) {
- $aliased_fields[] = $name .'.'.$field .' AS '.$field;
- }
- $restrict_action .= implode(',', $aliased_fields)
- .' FROM '.$name
- .' WHERE ';
- $conditions = array();
- $new_values = array();
- $null_values = array();
- for ($i=0; $i<count($table_fields); $i++) {
- $conditions[] = $table_fields[$i] .' = OLD.'.$referenced_fields[$i];
- $new_values[] = $table_fields[$i] .' = NEW.'.$referenced_fields[$i];
- $null_values[] = $table_fields[$i] .' = NULL';
- }
- $conditions2 = array();
- for ($i=0; $i<count($referenced_fields); $i++) {
- $conditions2[] = 'NEW.'.$referenced_fields[$i] .' <> OLD.'.$referenced_fields[$i];
- }
- $restrict_action .= implode(' AND ', $conditions).') IS NOT NULL'
- .' AND (' .implode(' OR ', $conditions2) .')';
-
- $cascade_action_update = 'UPDATE '.$name.' SET '.implode(', ', $new_values) .' WHERE '.implode(' AND ', $conditions);
- $cascade_action_delete = 'DELETE FROM '.$name.' WHERE '.implode(' AND ', $conditions);
- $setnull_action = 'UPDATE '.$name.' SET '.implode(', ', $null_values).' WHERE '.implode(' AND ', $conditions);
-
- if ('SET DEFAULT' == $fkdef['onupdate'] || 'SET DEFAULT' == $fkdef['ondelete']) {
- $db->loadModule('Reverse', null, true);
- $default_values = array();
- foreach ($table_fields as $table_field) {
- $field_definition = $db->reverse->getTableFieldDefinition($name, $field);
- if (PEAR::isError($field_definition)) {
- return $field_definition;
- }
- $default_values[] = $table_field .' = '. $field_definition[0]['default'];
- }
- $setdefault_action = 'UPDATE '.$name.' SET '.implode(', ', $default_values).' WHERE '.implode(' AND ', $conditions);
- }
-
- $query = 'CREATE TRIGGER %s'
- .' %s ON '.$fkdef['references']['table']
- .' FOR EACH ROW BEGIN ';
-
- if ('CASCADE' == $fkdef['onupdate']) {
- $sql_update = sprintf($query, $trigger_names['pk_update'], 'AFTER UPDATE', 'update') . $cascade_action_update. '; END;';
- } elseif ('SET NULL' == $fkdef['onupdate']) {
- $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setnull_action. '; END;';
- } elseif ('SET DEFAULT' == $fkdef['onupdate']) {
- $sql_update = sprintf($query, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . $setdefault_action. '; END;';
- } elseif ('NO ACTION' == $fkdef['onupdate']) {
- $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'AFTER UPDATE', 'update') . '; END;';
- } elseif ('RESTRICT' == $fkdef['onupdate']) {
- $sql_update = sprintf($query.$restrict_action, $trigger_names['pk_update'], 'BEFORE UPDATE', 'update') . '; END;';
- }
- if ('CASCADE' == $fkdef['ondelete']) {
- $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'AFTER DELETE', 'delete') . $cascade_action_delete. '; END;';
- } elseif ('SET NULL' == $fkdef['ondelete']) {
- $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setnull_action. '; END;';
- } elseif ('SET DEFAULT' == $fkdef['ondelete']) {
- $sql_delete = sprintf($query, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . $setdefault_action. '; END;';
- } elseif ('NO ACTION' == $fkdef['ondelete']) {
- $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'AFTER DELETE', 'delete') . '; END;';
- } elseif ('RESTRICT' == $fkdef['ondelete']) {
- $sql_delete = sprintf($query.$restrict_action, $trigger_names['pk_delete'], 'BEFORE DELETE', 'delete') . '; END;';
- }
-
- if (PEAR::isError($result)) {
- return $result;
- }
- $result = $db->exec($sql_delete);
- if (PEAR::isError($result)) {
- return $result;
- }
- $result = $db->exec($sql_update);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- if (PEAR::isError($result)) {
- return $result;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ dropTable()
-
- /**
- * drop an existing table
- *
- * @param string $name name of the table that should be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropTable($name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- //delete the triggers associated to existing FK constraints
- $constraints = $this->listTableConstraints($name);
- if (!PEAR::isError($constraints) && !empty($constraints)) {
- $db->loadModule('Reverse', null, true);
- foreach ($constraints as $constraint) {
- $definition = $db->reverse->getTableConstraintDefinition($name, $constraint);
- if (!PEAR::isError($definition) && !empty($definition['foreign'])) {
- $result = $this->_dropFKTriggers($name, $constraint, $definition['references']['table']);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- }
-
- $name = $db->quoteIdentifier($name, true);
- return $db->exec("DROP TABLE $name");
- }
-
- // }}}
- // {{{ vacuum()
-
- /**
- * Optimize (vacuum) all the tables in the db (or only the specified table)
- * and optionally run ANALYZE.
- *
- * @param string $table table name (all the tables if empty)
- * @param array $options an array with driver-specific options:
- * - timeout [int] (in seconds) [mssql-only]
- * - analyze [boolean] [pgsql and mysql]
- * - full [boolean] [pgsql-only]
- * - freeze [boolean] [pgsql-only]
- *
- * @return mixed MDB2_OK success, a MDB2 error on failure
- * @access public
- */
- function vacuum($table = null, $options = array())
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'VACUUM';
- if (!empty($table)) {
- $query .= ' '.$db->quoteIdentifier($table, true);
- }
- return $db->exec($query);
- }
-
- // }}}
- // {{{ alterTable()
-
- /**
- * alter an existing table
- *
- * @param string $name name of the table that is intended to be changed.
- * @param array $changes associative array that contains the details of each type
- * of change that is intended to be performed. The types of
- * changes that are currently supported are defined as follows:
- *
- * name
- *
- * New name for the table.
- *
- * add
- *
- * Associative array with the names of fields to be added as
- * indexes of the array. The value of each entry of the array
- * should be set to another associative array with the properties
- * of the fields to be added. The properties of the fields should
- * be the same as defined by the MDB2 parser.
- *
- *
- * remove
- *
- * Associative array with the names of fields to be removed as indexes
- * of the array. Currently the values assigned to each entry are ignored.
- * An empty array should be used for future compatibility.
- *
- * rename
- *
- * Associative array with the names of fields to be renamed as indexes
- * of the array. The value of each entry of the array should be set to
- * another associative array with the entry named name with the new
- * field name and the entry named Declaration that is expected to contain
- * the portion of the field declaration already in DBMS specific SQL code
- * as it is used in the CREATE TABLE statement.
- *
- * change
- *
- * Associative array with the names of the fields to be changed as indexes
- * of the array. Keep in mind that if it is intended to change either the
- * name of a field and any other properties, the change array entries
- * should have the new names of the fields as array indexes.
- *
- * The value of each entry of the array should be set to another associative
- * array with the properties of the fields to that are meant to be changed as
- * array entries. These entries should be assigned to the new values of the
- * respective properties. The properties of the fields should be the same
- * as defined by the MDB2 parser.
- *
- * Example
- * array(
- * 'name' => 'userlist',
- * 'add' => array(
- * 'quota' => array(
- * 'type' => 'integer',
- * 'unsigned' => 1
- * )
- * ),
- * 'remove' => array(
- * 'file_limit' => array(),
- * 'time_limit' => array()
- * ),
- * 'change' => array(
- * 'name' => array(
- * 'length' => '20',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 20,
- * ),
- * )
- * ),
- * 'rename' => array(
- * 'sex' => array(
- * 'name' => 'gender',
- * 'definition' => array(
- * 'type' => 'text',
- * 'length' => 1,
- * 'default' => 'M',
- * ),
- * )
- * )
- * )
- *
- * @param boolean $check indicates whether the function should just check if the DBMS driver
- * can perform the requested table alterations if the value is true or
- * actually perform them otherwise.
- * @access public
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- */
- function alterTable($name, $changes, $check, $options = array())
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- foreach ($changes as $change_name => $change) {
- switch ($change_name) {
- case 'add':
- case 'remove':
- case 'change':
- case 'name':
- case 'rename':
- break;
- default:
- return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,
- 'change type "'.$change_name.'" not yet supported', __FUNCTION__);
- }
- }
-
- if ($check) {
- return MDB2_OK;
- }
-
- $db->loadModule('Reverse', null, true);
-
- // actually sqlite 2.x supports no ALTER TABLE at all .. so we emulate it
- $fields = $db->manager->listTableFields($name);
- if (PEAR::isError($fields)) {
- return $fields;
- }
-
- $fields = array_flip($fields);
- foreach ($fields as $field => $value) {
- $definition = $db->reverse->getTableFieldDefinition($name, $field);
- if (PEAR::isError($definition)) {
- return $definition;
- }
- $fields[$field] = $definition[0];
- }
-
- $indexes = $db->manager->listTableIndexes($name);
- if (PEAR::isError($indexes)) {
- return $indexes;
- }
-
- $indexes = array_flip($indexes);
- foreach ($indexes as $index => $value) {
- $definition = $db->reverse->getTableIndexDefinition($name, $index);
- if (PEAR::isError($definition)) {
- return $definition;
- }
- $indexes[$index] = $definition;
- }
-
- $constraints = $db->manager->listTableConstraints($name);
- if (PEAR::isError($constraints)) {
- return $constraints;
- }
-
- if (!array_key_exists('foreign_keys', $options)) {
- $options['foreign_keys'] = array();
- }
- $constraints = array_flip($constraints);
- foreach ($constraints as $constraint => $value) {
- if (!empty($definition['primary'])) {
- if (!array_key_exists('primary', $options)) {
- $options['primary'] = $definition['fields'];
- //remove from the $constraint array, it's already handled by createTable()
- unset($constraints[$constraint]);
- }
- } else {
- $c_definition = $db->reverse->getTableConstraintDefinition($name, $constraint);
- if (PEAR::isError($c_definition)) {
- return $c_definition;
- }
- if (!empty($c_definition['foreign'])) {
- if (!array_key_exists($constraint, $options['foreign_keys'])) {
- $options['foreign_keys'][$constraint] = $c_definition;
- }
- //remove from the $constraint array, it's already handled by createTable()
- unset($constraints[$constraint]);
- } else {
- $constraints[$constraint] = $c_definition;
- }
- }
- }
-
- $name_new = $name;
- $create_order = $select_fields = array_keys($fields);
- foreach ($changes as $change_name => $change) {
- switch ($change_name) {
- case 'add':
- foreach ($change as $field_name => $field) {
- $fields[$field_name] = $field;
- $create_order[] = $field_name;
- }
- break;
- case 'remove':
- foreach ($change as $field_name => $field) {
- unset($fields[$field_name]);
- $select_fields = array_diff($select_fields, array($field_name));
- $create_order = array_diff($create_order, array($field_name));
- }
- break;
- case 'change':
- foreach ($change as $field_name => $field) {
- $fields[$field_name] = $field['definition'];
- }
- break;
- case 'name':
- $name_new = $change;
- break;
- case 'rename':
- foreach ($change as $field_name => $field) {
- unset($fields[$field_name]);
- $fields[$field['name']] = $field['definition'];
- $create_order[array_search($field_name, $create_order)] = $field['name'];
- }
- break;
- default:
- return $db->raiseError(MDB2_ERROR_CANNOT_ALTER, null, null,
- 'change type "'.$change_name.'" not yet supported', __FUNCTION__);
- }
- }
-
- $data = null;
- if (!empty($select_fields)) {
- $query = 'SELECT '.implode(', ', $select_fields).' FROM '.$db->quoteIdentifier($name, true);
- $data = $db->queryAll($query, null, MDB2_FETCHMODE_ORDERED);
- }
-
- $result = $this->dropTable($name);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $result = $this->createTable($name_new, $fields, $options);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- foreach ($indexes as $index => $definition) {
- $this->createIndex($name_new, $index, $definition);
- }
-
- foreach ($constraints as $constraint => $definition) {
- $this->createConstraint($name_new, $constraint, $definition);
- }
-
- if (!empty($select_fields) && !empty($data)) {
- $query = 'INSERT INTO '.$db->quoteIdentifier($name_new, true);
- $query.= '('.implode(', ', array_slice(array_keys($fields), 0, count($select_fields))).')';
- $query.=' VALUES (?'.str_repeat(', ?', (count($select_fields) - 1)).')';
- $stmt =& $db->prepare($query, null, MDB2_PREPARE_MANIP);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
- foreach ($data as $row) {
- $result = $stmt->execute($row);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ listDatabases()
-
- /**
- * list all databases
- *
- * @return mixed array of database names on success, a MDB2 error on failure
- * @access public
- */
- function listDatabases()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'list databases is not supported', __FUNCTION__);
- }
-
- // }}}
- // {{{ listUsers()
-
- /**
- * list all users
- *
- * @return mixed array of user names on success, a MDB2 error on failure
- * @access public
- */
- function listUsers()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'list databases is not supported', __FUNCTION__);
- }
-
- // }}}
- // {{{ listViews()
-
- /**
- * list all views in the current database
- *
- * @return mixed array of view names on success, a MDB2 error on failure
- * @access public
- */
- function listViews()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT name FROM sqlite_master WHERE type='view' AND sql NOT NULL";
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTableViews()
-
- /**
- * list the views in the database that reference a given table
- *
- * @param string table for which all referenced views should be found
- * @return mixed array of view names on success, a MDB2 error on failure
- * @access public
- */
- function listTableViews($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT name, sql FROM sqlite_master WHERE type='view' AND sql NOT NULL";
- $views = $db->queryAll($query, array('text', 'text'), MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($views)) {
- return $views;
- }
- $result = array();
- foreach ($views as $row) {
- if (preg_match("/^create view .* \bfrom\b\s+\b{$table}\b /i", $row['sql'])) {
- if (!empty($row['name'])) {
- $result[$row['name']] = true;
- }
- }
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_change_key_case($result, $db->options['field_case']);
- }
- return array_keys($result);
- }
-
- // }}}
- // {{{ listTables()
-
- /**
- * list all tables in the current database
- *
- * @return mixed array of table names on success, a MDB2 error on failure
- * @access public
- */
- function listTables()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name";
- $table_names = $db->queryCol($query);
- if (PEAR::isError($table_names)) {
- return $table_names;
- }
- $result = array();
- foreach ($table_names as $table_name) {
- if (!$this->_fixSequenceName($table_name, true)) {
- $result[] = $table_name;
- }
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ listTableFields()
-
- /**
- * list all fields in a table in the current database
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of field names on success, a MDB2 error on failure
- * @access public
- */
- function listTableFields($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $result = $db->loadModule('Reverse', null, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text');
- } else {
- $query.= 'name='.$db->quote($table, 'text');
- }
- $sql = $db->queryOne($query);
- if (PEAR::isError($sql)) {
- return $sql;
- }
- $columns = $db->reverse->_getTableColumns($sql);
- $fields = array();
- foreach ($columns as $column) {
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $column['name'] = strtolower($column['name']);
- } else {
- $column['name'] = strtoupper($column['name']);
- }
- } else {
- $column = array_change_key_case($column, $db->options['field_case']);
- }
- $fields[] = $column['name'];
- }
- return $fields;
- }
-
- // }}}
- // {{{ listTableTriggers()
-
- /**
- * list all triggers in the database that reference a given table
- *
- * @param string table for which all referenced triggers should be found
- * @return mixed array of trigger names on success, a MDB2 error on failure
- * @access public
- */
- function listTableTriggers($table = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT name FROM sqlite_master WHERE type='trigger' AND sql NOT NULL";
- if (!is_null($table)) {
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= ' AND LOWER(tbl_name)='.$db->quote(strtolower($table), 'text');
- } else {
- $query.= ' AND tbl_name='.$db->quote($table, 'text');
- }
- }
- $result = $db->queryCol($query);
- if (PEAR::isError($result)) {
- return $result;
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
- // {{{ createIndex()
-
- /**
- * Get the stucture of a field into an array
- *
- * @param string $table name of the table on which the index is to be created
- * @param string $name name of the index to be created
- * @param array $definition associative array that defines properties of the index to be created.
- * Currently, only one property named FIELDS is supported. This property
- * is also an associative with the names of the index fields as array
- * indexes. Each entry of this array is set to another type of associative
- * array that specifies properties of the index that are specific to
- * each field.
- *
- * Currently, only the sorting property is supported. It should be used
- * to define the sorting direction of the index. It may be set to either
- * ascending or descending.
- *
- * Not all DBMS support index sorting direction configuration. The DBMS
- * drivers of those that do not support it ignore this property. Use the
- * function support() to determine whether the DBMS driver can manage indexes.
-
- * Example
- * array(
- * 'fields' => array(
- * 'user_name' => array(
- * 'sorting' => 'ascending'
- * ),
- * 'last_login' => array()
- * )
- * )
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createIndex($table, $name, $definition)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = $db->quoteIdentifier($table, true);
- $name = $db->getIndexName($name);
- $query = "CREATE INDEX $name ON $table";
- $fields = array();
- foreach ($definition['fields'] as $field_name => $field) {
- $field_string = $field_name;
- if (!empty($field['sorting'])) {
- switch ($field['sorting']) {
- case 'ascending':
- $field_string.= ' ASC';
- break;
- case 'descending':
- $field_string.= ' DESC';
- break;
- }
- }
- $fields[] = $field_string;
- }
- $query .= ' ('.implode(', ', $fields) . ')';
- return $db->exec($query);
- }
-
- // }}}
- // {{{ dropIndex()
-
- /**
- * drop existing index
- *
- * @param string $table name of table that should be used in method
- * @param string $name name of the index to be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropIndex($table, $name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $name = $db->getIndexName($name);
- return $db->exec("DROP INDEX $name");
- }
-
- // }}}
- // {{{ listTableIndexes()
-
- /**
- * list all indexes in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of index names on success, a MDB2 error on failure
- * @access public
- */
- function listTableIndexes($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = $db->quote($table, 'text');
- $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= 'LOWER(tbl_name)='.strtolower($table);
- } else {
- $query.= "tbl_name=$table";
- }
- $query.= " AND sql NOT NULL ORDER BY name";
- $indexes = $db->queryCol($query, 'text');
- if (PEAR::isError($indexes)) {
- return $indexes;
- }
-
- $result = array();
- foreach ($indexes as $sql) {
- if (preg_match("/^create index ([^ ]+) on /i", $sql, $tmp)) {
- $index = $this->_fixIndexName($tmp[1]);
- if (!empty($index)) {
- $result[$index] = true;
- }
- }
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_change_key_case($result, $db->options['field_case']);
- }
- return array_keys($result);
- }
-
- // }}}
- // {{{ createConstraint()
-
- /**
- * create a constraint on a table
- *
- * @param string $table name of the table on which the constraint is to be created
- * @param string $name name of the constraint to be created
- * @param array $definition associative array that defines properties of the constraint to be created.
- * Currently, only one property named FIELDS is supported. This property
- * is also an associative with the names of the constraint fields as array
- * constraints. Each entry of this array is set to another type of associative
- * array that specifies properties of the constraint that are specific to
- * each field.
- *
- * Example
- * array(
- * 'fields' => array(
- * 'user_name' => array(),
- * 'last_login' => array()
- * )
- * )
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createConstraint($table, $name, $definition)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!empty($definition['primary'])) {
- return $db->manager->alterTable($table, array(), false, array('primary' => $definition['fields']));
- }
-
- if (!empty($definition['foreign'])) {
- return $db->manager->alterTable($table, array(), false, array('foreign_keys' => array($name => $definition)));
- }
-
- $table = $db->quoteIdentifier($table, true);
- $name = $db->getIndexName($name);
- $query = "CREATE UNIQUE INDEX $name ON $table";
- $fields = array();
- foreach ($definition['fields'] as $field_name => $field) {
- $field_string = $field_name;
- if (!empty($field['sorting'])) {
- switch ($field['sorting']) {
- case 'ascending':
- $field_string.= ' ASC';
- break;
- case 'descending':
- $field_string.= ' DESC';
- break;
- }
- }
- $fields[] = $field_string;
- }
- $query .= ' ('.implode(', ', $fields) . ')';
- return $db->exec($query);
- }
-
- // }}}
- // {{{ dropConstraint()
-
- /**
- * drop existing constraint
- *
- * @param string $table name of table that should be used in method
- * @param string $name name of the constraint to be dropped
- * @param string $primary hint if the constraint is primary
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropConstraint($table, $name, $primary = false)
- {
- if ($primary || $name == 'PRIMARY') {
- return $this->alterTable($table, array(), false, array('primary' => null));
- }
-
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- //is it a FK constraint? If so, also delete the associated triggers
- $db->loadModule('Reverse', null, true);
- $definition = $db->reverse->getTableConstraintDefinition($table, $name);
- if (!PEAR::isError($definition) && !empty($definition['foreign'])) {
- //first drop the FK enforcing triggers
- $result = $this->_dropFKTriggers($table, $name, $definition['references']['table']);
- if (PEAR::isError($result)) {
- return $result;
- }
- //then drop the constraint itself
- return $this->alterTable($table, array(), false, array('foreign_keys' => array($name => null)));
- }
-
- $name = $db->getIndexName($name);
- return $db->exec("DROP INDEX $name");
- }
-
- // }}}
- // {{{ _dropFKTriggers()
-
- /**
- * Drop the triggers created to enforce the FOREIGN KEY constraint on the table
- *
- * @param string $table table name
- * @param string $fkname FOREIGN KEY constraint name
- * @param string $referenced_table referenced table name
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access private
- */
- function _dropFKTriggers($table, $fkname, $referenced_table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $triggers = $this->listTableTriggers($table);
- $triggers2 = $this->listTableTriggers($referenced_table);
- if (!PEAR::isError($triggers2) && !PEAR::isError($triggers)) {
- $triggers = array_merge($triggers, $triggers2);
- $pattern = '/^'.$fkname.'(_pk)?_(insert|update|delete)_trg$/i';
- foreach ($triggers as $trigger) {
- if (preg_match($pattern, $trigger)) {
- $result = $db->exec('DROP TRIGGER '.$trigger);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ listTableConstraints()
-
- /**
- * list all constraints in a table
- *
- * @param string $table name of table that should be used in method
- * @return mixed array of constraint names on success, a MDB2 error on failure
- * @access public
- */
- function listTableConstraints($table)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $table = $db->quote($table, 'text');
- $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= 'LOWER(tbl_name)='.strtolower($table);
- } else {
- $query.= "tbl_name=$table";
- }
- $query.= " AND sql NOT NULL ORDER BY name";
- $indexes = $db->queryCol($query, 'text');
- if (PEAR::isError($indexes)) {
- return $indexes;
- }
-
- $result = array();
- foreach ($indexes as $sql) {
- if (preg_match("/^create unique index ([^ ]+) on /i", $sql, $tmp)) {
- $index = $this->_fixIndexName($tmp[1]);
- if (!empty($index)) {
- $result[$index] = true;
- }
- }
- }
-
- // also search in table definition for PRIMARY KEYs...
- $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= 'LOWER(name)='.strtolower($table);
- } else {
- $query.= "name=$table";
- }
- $query.= " AND sql NOT NULL ORDER BY name";
- $table_def = $db->queryOne($query, 'text');
- if (PEAR::isError($table_def)) {
- return $table_def;
- }
- if (preg_match("/\bPRIMARY\s+KEY\b/i", $table_def, $tmp)) {
- $result['primary'] = true;
- }
-
- // ...and for FOREIGN KEYs
- if (preg_match_all("/\bCONSTRAINT\b\s+([^\s]+)\s+\bFOREIGN\s+KEY/imsx", $table_def, $tmp)) {
- foreach ($tmp[1] as $fk) {
- $result[$fk] = true;
- }
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_change_key_case($result, $db->options['field_case']);
- }
- return array_keys($result);
- }
-
- // }}}
- // {{{ createSequence()
-
- /**
- * create sequence
- *
- * @param string $seq_name name of the sequence to be created
- * @param string $start start value of the sequence; default is 1
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function createSequence($seq_name, $start = 1)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
- $seqcol_name = $db->quoteIdentifier($db->options['seqcol_name'], true);
- $query = "CREATE TABLE $sequence_name ($seqcol_name INTEGER PRIMARY KEY DEFAULT 0 NOT NULL)";
- $res = $db->exec($query);
- if (PEAR::isError($res)) {
- return $res;
- }
- if ($start == 1) {
- return MDB2_OK;
- }
- $res = $db->exec("INSERT INTO $sequence_name ($seqcol_name) VALUES (".($start-1).')');
- if (!PEAR::isError($res)) {
- return MDB2_OK;
- }
- // Handle error
- $result = $db->exec("DROP TABLE $sequence_name");
- if (PEAR::isError($result)) {
- return $db->raiseError($result, null, null,
- 'could not drop inconsistent sequence table', __FUNCTION__);
- }
- return $db->raiseError($res, null, null,
- 'could not create sequence table', __FUNCTION__);
- }
-
- // }}}
- // {{{ dropSequence()
-
- /**
- * drop existing sequence
- *
- * @param string $seq_name name of the sequence to be dropped
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function dropSequence($seq_name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $sequence_name = $db->quoteIdentifier($db->getSequenceName($seq_name), true);
- return $db->exec("DROP TABLE $sequence_name");
- }
-
- // }}}
- // {{{ listSequences()
-
- /**
- * list all sequences in the current database
- *
- * @return mixed array of sequence names on success, a MDB2 error on failure
- * @access public
- */
- function listSequences()
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT name FROM sqlite_master WHERE type='table' AND sql NOT NULL ORDER BY name";
- $table_names = $db->queryCol($query);
- if (PEAR::isError($table_names)) {
- return $table_names;
- }
- $result = array();
- foreach ($table_names as $table_name) {
- if ($sqn = $this->_fixSequenceName($table_name, true)) {
- $result[] = $sqn;
- }
- }
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $result = array_map(($db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper'), $result);
- }
- return $result;
- }
-
- // }}}
-}
-?> \ No newline at end of file
diff --git a/inc/MDB2/Driver/Native/Common.php b/inc/MDB2/Driver/Native/Common.php
deleted file mode 100644
index c01caa35b71..00000000000
--- a/inc/MDB2/Driver/Native/Common.php
+++ /dev/null
@@ -1,61 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Common.php,v 1.2 2007/09/09 13:47:36 quipo Exp $
-//
-
-/**
- * Base class for the natuve modules that is extended by each MDB2 driver
- *
- * To load this module in the MDB2 object:
- * $mdb->loadModule('Native');
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Native_Common extends MDB2_Module_Common
-{
-}
-?> \ No newline at end of file
diff --git a/inc/MDB2/Driver/Native/mysql.php b/inc/MDB2/Driver/Native/mysql.php
deleted file mode 100644
index 90ff068e6ff..00000000000
--- a/inc/MDB2/Driver/Native/mysql.php
+++ /dev/null
@@ -1,60 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: mysql.php,v 1.9 2006/06/18 21:59:05 lsmith Exp $
-//
-
-require_once 'MDB2/Driver/Native/Common.php';
-
-/**
- * MDB2 MySQL driver for the native module
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Native_mysql extends MDB2_Driver_Native_Common
-{
-}
-?> \ No newline at end of file
diff --git a/inc/MDB2/Driver/Native/pgsql.php b/inc/MDB2/Driver/Native/pgsql.php
deleted file mode 100644
index acab8389c89..00000000000
--- a/inc/MDB2/Driver/Native/pgsql.php
+++ /dev/null
@@ -1,88 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Paul Cooper <pgc@ucecom.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: pgsql.php,v 1.12 2006/07/15 13:07:15 lsmith Exp $
-
-require_once 'MDB2/Driver/Native/Common.php';
-
-/**
- * MDB2 PostGreSQL driver for the native module
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper <pgc@ucecom.com>
- */
-class MDB2_Driver_Native_pgsql extends MDB2_Driver_Native_Common
-{
- // }}}
- // {{{ deleteOID()
-
- /**
- * delete an OID
- *
- * @param integer $OID
- * @return mixed MDB2_OK on success or MDB2 Error Object on failure
- * @access public
- */
- function deleteOID($OID)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $connection = $db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- if (!@pg_lo_unlink($connection, $OID)) {
- return $db->raiseError(null, null, null,
- 'Unable to unlink OID: '.$OID, __FUNCTION__);
- }
- return MDB2_OK;
- }
-
-}
-?> \ No newline at end of file
diff --git a/inc/MDB2/Driver/Native/sqlite.php b/inc/MDB2/Driver/Native/sqlite.php
deleted file mode 100644
index 0213293a50a..00000000000
--- a/inc/MDB2/Driver/Native/sqlite.php
+++ /dev/null
@@ -1,60 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: sqlite.php,v 1.9 2006/06/18 21:59:05 lsmith Exp $
-//
-
-require_once 'MDB2/Driver/Native/Common.php';
-
-/**
- * MDB2 SQLite driver for the native module
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Native_sqlite extends MDB2_Driver_Native_Common
-{
-}
-?> \ No newline at end of file
diff --git a/inc/MDB2/Driver/Reverse/Common.php b/inc/MDB2/Driver/Reverse/Common.php
deleted file mode 100644
index 4a411fea6d2..00000000000
--- a/inc/MDB2/Driver/Reverse/Common.php
+++ /dev/null
@@ -1,517 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Common.php,v 1.43 2009/01/14 15:01:21 quipo Exp $
-//
-
-/**
- * @package MDB2
- * @category Database
- */
-
-/**
- * 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 MDB2_TABLEINFO_FULL accordingly
- */
-
-define('MDB2_TABLEINFO_ORDER', 1);
-define('MDB2_TABLEINFO_ORDERTABLE', 2);
-define('MDB2_TABLEINFO_FULL', 3);
-
-/**
- * Base class for the schema reverse engineering module that is extended by each MDB2 driver
- *
- * To load this module in the MDB2 object:
- * $mdb->loadModule('Reverse');
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Reverse_Common extends MDB2_Module_Common
-{
- // {{{ splitTableSchema()
-
- /**
- * Split the "[owner|schema].table" notation into an array
- *
- * @param string $table [schema and] table name
- *
- * @return array array(schema, table)
- * @access private
- */
- function splitTableSchema($table)
- {
- $ret = array();
- if (strpos($table, '.') !== false) {
- return explode('.', $table);
- }
- return array(null, $table);
- }
-
- // }}}
- // {{{ getTableFieldDefinition()
-
- /**
- * Get the structure of a field into an array
- *
- * @param string $table name of table that should be used in method
- * @param string $field name of field that should be used in method
- * @return mixed data array on success, a MDB2 error on failure.
- * The returned array contains an array for each field definition,
- * with all or some of these indices, depending on the field data type:
- * [notnull] [nativetype] [length] [fixed] [default] [type] [mdb2type]
- * @access public
- */
- function getTableFieldDefinition($table, $field)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ getTableIndexDefinition()
-
- /**
- * Get the structure of an index into an array
- *
- * @param string $table name of table that should be used in method
- * @param string $index name of index that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * The returned array has this structure:
- * </pre>
- * array (
- * [fields] => array (
- * [field1name] => array() // one entry per each field covered
- * [field2name] => array() // by the index
- * [field3name] => array(
- * [sorting] => ascending
- * )
- * )
- * );
- * </pre>
- * @access public
- */
- function getTableIndexDefinition($table, $index)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ getTableConstraintDefinition()
-
- /**
- * Get the structure of an constraints into an array
- *
- * @param string $table name of table that should be used in method
- * @param string $index name of index that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * The returned array has this structure:
- * <pre>
- * array (
- * [primary] => 0
- * [unique] => 0
- * [foreign] => 1
- * [check] => 0
- * [fields] => array (
- * [field1name] => array() // one entry per each field covered
- * [field2name] => array() // by the index
- * [field3name] => array(
- * [sorting] => ascending
- * [position] => 3
- * )
- * )
- * [references] => array(
- * [table] => name
- * [fields] => array(
- * [field1name] => array( //one entry per each referenced field
- * [position] => 1
- * )
- * )
- * )
- * [deferrable] => 0
- * [initiallydeferred] => 0
- * [onupdate] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
- * [ondelete] => CASCADE|RESTRICT|SET NULL|SET DEFAULT|NO ACTION
- * [match] => SIMPLE|PARTIAL|FULL
- * );
- * </pre>
- * @access public
- */
- function getTableConstraintDefinition($table, $index)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ getSequenceDefinition()
-
- /**
- * Get the structure of a sequence into an array
- *
- * @param string $sequence name of sequence that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * The returned array has this structure:
- * <pre>
- * array (
- * [start] => n
- * );
- * </pre>
- * @access public
- */
- function getSequenceDefinition($sequence)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $start = $db->currId($sequence);
- if (PEAR::isError($start)) {
- return $start;
- }
- if ($db->supports('current_id')) {
- $start++;
- } else {
- $db->warnings[] = 'database does not support getting current
- sequence value, the sequence value was incremented';
- }
- $definition = array();
- if ($start != 1) {
- $definition = array('start' => $start);
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTriggerDefinition()
-
- /**
- * Get the structure of a trigger into an array
- *
- * EXPERIMENTAL
- *
- * WARNING: this function is experimental and may change the returned value
- * at any time until labelled as non-experimental
- *
- * @param string $trigger name of trigger that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * The returned array has this structure:
- * <pre>
- * array (
- * [trigger_name] => 'trigger name',
- * [table_name] => 'table name',
- * [trigger_body] => 'trigger body definition',
- * [trigger_type] => 'BEFORE' | 'AFTER',
- * [trigger_event] => 'INSERT' | 'UPDATE' | 'DELETE'
- * //or comma separated list of multiple events, when supported
- * [trigger_enabled] => true|false
- * [trigger_comment] => 'trigger comment',
- * );
- * </pre>
- * The oci8 driver also returns a [when_clause] index.
- * @access public
- */
- function getTriggerDefinition($trigger)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set
- *
- * The format of the resulting array depends on which <var>$mode</var>
- * you select. The sample output below is based on this query:
- * <pre>
- * SELECT tblFoo.fldID, tblFoo.fldPhone, tblBar.fldId
- * FROM tblFoo
- * JOIN tblBar ON tblFoo.fldId = tblBar.fldId
- * </pre>
- *
- * <ul>
- * <li>
- *
- * <kbd>null</kbd> (default)
- * <pre>
- * [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
- * )
- * </pre>
- *
- * </li><li>
- *
- * <kbd>MDB2_TABLEINFO_ORDER</kbd>
- *
- * <p>In addition to the information found in the default output,
- * a notation of the number of columns is provided by the
- * <samp>num_fields</samp> element while the <samp>order</samp>
- * 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.</p>
- *
- * <p>If a result set has identical field names, the last one is
- * used.</p>
- *
- * <pre>
- * [num_fields] => 3
- * [order] => Array (
- * [fldId] => 2
- * [fldTrans] => 1
- * )
- * </pre>
- *
- * </li><li>
- *
- * <kbd>MDB2_TABLEINFO_ORDERTABLE</kbd>
- *
- * <p>Similar to <kbd>MDB2_TABLEINFO_ORDER</kbd> 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.</p>
- *
- * <pre>
- * [num_fields] => 3
- * [ordertable] => Array (
- * [tblFoo] => Array (
- * [fldId] => 0
- * [fldPhone] => 1
- * )
- * [tblBar] => Array (
- * [fldId] => 2
- * )
- * )
- * </pre>
- *
- * </li>
- * </ul>
- *
- * The <samp>flags</samp> 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.
- * + <samp>primary_key</samp>
- * + <samp>unique_key</samp>
- * + <samp>multiple_key</samp>
- * + <samp>not_null</samp>
- *
- * Most DBMS's only provide the <samp>table</samp> and <samp>flags</samp>
- * elements if <var>$result</var> is a table name. The following DBMS's
- * provide full information from queries:
- * + fbsql
- * + mysql
- *
- * If the 'portability' option has <samp>MDB2_PORTABILITY_FIX_CASE</samp>
- * turned on, the names of tables and fields will be lower or upper cased.
- *
- * @param object|string $result MDB2_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:
- * <kbd>MDB2_TABLEINFO_ORDERTABLE</kbd>,
- * <kbd>MDB2_TABLEINFO_ORDER</kbd> or
- * <kbd>MDB2_TABLEINFO_FULL</kbd> (which does both).
- * These are bitwise, so the first two can be
- * combined using <kbd>|</kbd>.
- *
- * @return array an associative array with the information requested.
- * A MDB2_Error object on failure.
- *
- * @see MDB2_Driver_Common::setOption()
- */
- function tableInfo($result, $mode = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if (!is_string($result)) {
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'method not implemented', __FUNCTION__);
- }
-
- $db->loadModule('Manager', null, true);
- $fields = $db->manager->listTableFields($result);
- if (PEAR::isError($fields)) {
- return $fields;
- }
-
- $flags = array();
-
- $idxname_format = $db->getOption('idxname_format');
- $db->setOption('idxname_format', '%s');
-
- $indexes = $db->manager->listTableIndexes($result);
- if (PEAR::isError($indexes)) {
- $db->setOption('idxname_format', $idxname_format);
- return $indexes;
- }
-
- foreach ($indexes as $index) {
- $definition = $this->getTableIndexDefinition($result, $index);
- if (PEAR::isError($definition)) {
- $db->setOption('idxname_format', $idxname_format);
- return $definition;
- }
- if (count($definition['fields']) > 1) {
- foreach ($definition['fields'] as $field => $sort) {
- $flags[$field] = 'multiple_key';
- }
- }
- }
-
- $constraints = $db->manager->listTableConstraints($result);
- if (PEAR::isError($constraints)) {
- return $constraints;
- }
-
- foreach ($constraints as $constraint) {
- $definition = $this->getTableConstraintDefinition($result, $constraint);
- if (PEAR::isError($definition)) {
- $db->setOption('idxname_format', $idxname_format);
- return $definition;
- }
- $flag = !empty($definition['primary'])
- ? 'primary_key' : (!empty($definition['unique'])
- ? 'unique_key' : false);
- if ($flag) {
- foreach ($definition['fields'] as $field => $sort) {
- if (empty($flags[$field]) || $flags[$field] != 'primary_key') {
- $flags[$field] = $flag;
- }
- }
- }
- }
-
- $res = array();
-
- if ($mode) {
- $res['num_fields'] = count($fields);
- }
-
- foreach ($fields as $i => $field) {
- $definition = $this->getTableFieldDefinition($result, $field);
- if (PEAR::isError($definition)) {
- $db->setOption('idxname_format', $idxname_format);
- return $definition;
- }
- $res[$i] = $definition[0];
- $res[$i]['name'] = $field;
- $res[$i]['table'] = $result;
- $res[$i]['type'] = preg_replace('/^([a-z]+).*$/i', '\\1', trim($definition[0]['nativetype']));
- // 'primary_key', 'unique_key', 'multiple_key'
- $res[$i]['flags'] = empty($flags[$field]) ? '' : $flags[$field];
- // not_null', 'unsigned', 'auto_increment', 'default_[rawencodedvalue]'
- if (!empty($res[$i]['notnull'])) {
- $res[$i]['flags'].= ' not_null';
- }
- if (!empty($res[$i]['unsigned'])) {
- $res[$i]['flags'].= ' unsigned';
- }
- if (!empty($res[$i]['auto_increment'])) {
- $res[$i]['flags'].= ' autoincrement';
- }
- if (!empty($res[$i]['default'])) {
- $res[$i]['flags'].= ' default_'.rawurlencode($res[$i]['default']);
- }
-
- if ($mode & MDB2_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- }
-
- $db->setOption('idxname_format', $idxname_format);
- return $res;
- }
-}
-?> \ No newline at end of file
diff --git a/inc/MDB2/Driver/Reverse/mysql.php b/inc/MDB2/Driver/Reverse/mysql.php
deleted file mode 100644
index 40c62da3baa..00000000000
--- a/inc/MDB2/Driver/Reverse/mysql.php
+++ /dev/null
@@ -1,536 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: mysql.php,v 1.80 2008/03/26 21:15:37 quipo Exp $
-//
-
-oc_require_once('MDB2/Driver/Reverse/Common.php');
-
-/**
- * MDB2 MySQL driver for the schema reverse engineering module
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Lorenzo Alberton <l.alberton@quipo.it>
- */
-class MDB2_Driver_Reverse_mysql extends MDB2_Driver_Reverse_Common
-{
- // {{{ getTableFieldDefinition()
-
- /**
- * Get the structure of a field into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $field_name name of field that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableFieldDefinition($table_name, $field_name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $result = $db->loadModule('Datatype', null, true);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $table = $db->quoteIdentifier($table, true);
- $query = "SHOW FULL COLUMNS FROM $table LIKE ".$db->quote($field_name);
- $columns = $db->queryAll($query, null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($columns)) {
- return $columns;
- }
- foreach ($columns as $column) {
- $column = array_change_key_case($column, CASE_LOWER);
- $column['name'] = $column['field'];
- unset($column['field']);
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $column['name'] = strtolower($column['name']);
- } else {
- $column['name'] = strtoupper($column['name']);
- }
- } else {
- $column = array_change_key_case($column, $db->options['field_case']);
- }
- if ($field_name == $column['name']) {
- $mapped_datatype = $db->datatype->mapNativeDatatype($column);
- if (PEAR::isError($mapped_datatype)) {
- return $mapped_datatype;
- }
- list($types, $length, $unsigned, $fixed) = $mapped_datatype;
- $notnull = false;
- if (empty($column['null']) || $column['null'] !== 'YES') {
- $notnull = true;
- }
- $default = false;
- if (array_key_exists('default', $column)) {
- $default = $column['default'];
- if (is_null($default) && $notnull) {
- $default = '';
- }
- }
- $autoincrement = false;
- if (!empty($column['extra']) && $column['extra'] == 'auto_increment') {
- $autoincrement = true;
- }
- $collate = null;
- if (!empty($column['collation'])) {
- $collate = $column['collation'];
- $charset = preg_replace('/(.+?)(_.+)?/', '$1', $collate);
- }
-
- $definition[0] = array(
- 'notnull' => $notnull,
- 'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $column['type'])
- );
- if (!is_null($length)) {
- $definition[0]['length'] = $length;
- }
- if (!is_null($unsigned)) {
- $definition[0]['unsigned'] = $unsigned;
- }
- if (!is_null($fixed)) {
- $definition[0]['fixed'] = $fixed;
- }
- if ($default !== false) {
- $definition[0]['default'] = $default;
- }
- if ($autoincrement !== false) {
- $definition[0]['autoincrement'] = $autoincrement;
- }
- if (!is_null($collate)) {
- $definition[0]['collate'] = $collate;
- $definition[0]['charset'] = $charset;
- }
- foreach ($types as $key => $type) {
- $definition[$key] = $definition[0];
- if ($type == 'clob' || $type == 'blob') {
- unset($definition[$key]['default']);
- } elseif ($type == 'timestamp' && $notnull && empty($definition[$key]['default'])) {
- $definition[$key]['default'] = '0000-00-00 00:00:00';
- }
- $definition[$key]['type'] = $type;
- $definition[$key]['mdb2type'] = $type;
- }
- return $definition;
- }
- }
-
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table column', __FUNCTION__);
- }
-
- // }}}
- // {{{ getTableIndexDefinition()
-
- /**
- * Get the structure of an index into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $index_name name of index that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableIndexDefinition($table_name, $index_name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $table = $db->quoteIdentifier($table, true);
- $query = "SHOW INDEX FROM $table /*!50002 WHERE Key_name = %s */";
- $index_name_mdb2 = $db->getIndexName($index_name);
- $result = $db->queryRow(sprintf($query, $db->quote($index_name_mdb2)));
- if (!PEAR::isError($result) && !is_null($result)) {
- // apply 'idxname_format' only if the query succeeded, otherwise
- // fallback to the given $index_name, without transformation
- $index_name = $index_name_mdb2;
- }
- $result = $db->query(sprintf($query, $db->quote($index_name)));
- if (PEAR::isError($result)) {
- return $result;
- }
- $colpos = 1;
- $definition = array();
- while (is_array($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC))) {
- $row = array_change_key_case($row, CASE_LOWER);
- $key_name = $row['key_name'];
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $key_name = strtolower($key_name);
- } else {
- $key_name = strtoupper($key_name);
- }
- }
- if ($index_name == $key_name) {
- if (!$row['non_unique']) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $index_name . ' is not an existing table index', __FUNCTION__);
- }
- $column_name = $row['column_name'];
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $column_name = strtolower($column_name);
- } else {
- $column_name = strtoupper($column_name);
- }
- }
- $definition['fields'][$column_name] = array(
- 'position' => $colpos++
- );
- if (!empty($row['collation'])) {
- $definition['fields'][$column_name]['sorting'] = ($row['collation'] == 'A'
- ? 'ascending' : 'descending');
- }
- }
- }
- $result->free();
- if (empty($definition['fields'])) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $index_name . ' is not an existing table index', __FUNCTION__);
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTableConstraintDefinition()
-
- /**
- * Get the structure of a constraint into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $constraint_name name of constraint that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableConstraintDefinition($table_name, $constraint_name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
- $constraint_name_original = $constraint_name;
-
- $table = $db->quoteIdentifier($table, true);
- $query = "SHOW INDEX FROM $table /*!50002 WHERE Key_name = %s */";
- if (strtolower($constraint_name) != 'primary') {
- $constraint_name_mdb2 = $db->getIndexName($constraint_name);
- $result = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2)));
- if (!PEAR::isError($result) && !is_null($result)) {
- // apply 'idxname_format' only if the query succeeded, otherwise
- // fallback to the given $index_name, without transformation
- $constraint_name = $constraint_name_mdb2;
- }
- }
- $result = $db->query(sprintf($query, $db->quote($constraint_name)));
- if (PEAR::isError($result)) {
- return $result;
- }
- $colpos = 1;
- //default values, eventually overridden
- $definition = array(
- 'primary' => false,
- 'unique' => false,
- 'foreign' => false,
- 'check' => false,
- 'fields' => array(),
- 'references' => array(
- 'table' => '',
- 'fields' => array(),
- ),
- 'onupdate' => '',
- 'ondelete' => '',
- 'match' => '',
- 'deferrable' => false,
- 'initiallydeferred' => false,
- );
- while (is_array($row = $result->fetchRow(MDB2_FETCHMODE_ASSOC))) {
- $row = array_change_key_case($row, CASE_LOWER);
- $key_name = $row['key_name'];
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $key_name = strtolower($key_name);
- } else {
- $key_name = strtoupper($key_name);
- }
- }
- if ($constraint_name == $key_name) {
- if ($row['non_unique']) {
- //FOREIGN KEY?
- return $this->_getTableFKConstraintDefinition($table, $constraint_name_original, $definition);
- }
- if ($row['key_name'] == 'PRIMARY') {
- $definition['primary'] = true;
- } elseif (!$row['non_unique']) {
- $definition['unique'] = true;
- }
- $column_name = $row['column_name'];
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $column_name = strtolower($column_name);
- } else {
- $column_name = strtoupper($column_name);
- }
- }
- $definition['fields'][$column_name] = array(
- 'position' => $colpos++
- );
- if (!empty($row['collation'])) {
- $definition['fields'][$column_name]['sorting'] = ($row['collation'] == 'A'
- ? 'ascending' : 'descending');
- }
- }
- }
- $result->free();
- if (empty($definition['fields'])) {
- return $this->_getTableFKConstraintDefinition($table, $constraint_name_original, $definition);
- }
- return $definition;
- }
-
- // }}}
- // {{{ _getTableFKConstraintDefinition()
-
- /**
- * Get the FK definition from the CREATE TABLE statement
- *
- * @param string $table table name
- * @param string $constraint_name constraint name
- * @param array $definition default values for constraint definition
- *
- * @return array|PEAR_Error
- * @access private
- */
- function _getTableFKConstraintDefinition($table, $constraint_name, $definition)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $query = 'SHOW CREATE TABLE '. $db->escape($table);
- $constraint = $db->queryOne($query, 'text', 1);
- if (!PEAR::isError($constraint) && !empty($constraint)) {
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $constraint = strtolower($constraint);
- } else {
- $constraint = strtoupper($constraint);
- }
- }
- $constraint_name_original = $constraint_name;
- $constraint_name = $db->getIndexName($constraint_name);
- $pattern = '/\bCONSTRAINT\s+'.$constraint_name.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^ ]+) \(([^\)]+)\)/i';
- if (!preg_match($pattern, str_replace('`', '', $constraint), $matches)) {
- //fallback to original constraint name
- $pattern = '/\bCONSTRAINT\s+'.$constraint_name_original.'\s+FOREIGN KEY\s+\(([^\)]+)\) \bREFERENCES\b ([^ ]+) \(([^\)]+)\)/i';
- }
- if (preg_match($pattern, str_replace('`', '', $constraint), $matches)) {
- $definition['foreign'] = true;
- $column_names = explode(',', $matches[1]);
- $referenced_cols = explode(',', $matches[3]);
- $definition['references'] = array(
- 'table' => $matches[2],
- 'fields' => array(),
- );
- $colpos = 1;
- foreach ($column_names as $column_name) {
- $definition['fields'][trim($column_name)] = array(
- 'position' => $colpos++
- );
- }
- $colpos = 1;
- foreach ($referenced_cols as $column_name) {
- $definition['references']['fields'][trim($column_name)] = array(
- 'position' => $colpos++
- );
- }
- $definition['onupdate'] = 'NO ACTION';
- $definition['ondelete'] = 'NO ACTION';
- $definition['match'] = 'SIMPLE';
- return $definition;
- }
- }
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $constraint_name . ' is not an existing table constraint', __FUNCTION__);
- }
-
- // }}}
- // {{{ getTriggerDefinition()
-
- /**
- * Get the structure of a trigger into an array
- *
- * EXPERIMENTAL
- *
- * WARNING: this function is experimental and may change the returned value
- * at any time until labelled as non-experimental
- *
- * @param string $trigger name of trigger that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTriggerDefinition($trigger)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = 'SELECT trigger_name,
- event_object_table AS table_name,
- action_statement AS trigger_body,
- action_timing AS trigger_type,
- event_manipulation AS trigger_event
- FROM information_schema.triggers
- WHERE trigger_name = '. $db->quote($trigger, 'text');
- $types = array(
- 'trigger_name' => 'text',
- 'table_name' => 'text',
- 'trigger_body' => 'text',
- 'trigger_type' => 'text',
- 'trigger_event' => 'text',
- );
- $def = $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($def)) {
- return $def;
- }
- $def['trigger_comment'] = '';
- $def['trigger_enabled'] = true;
- return $def;
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set
- *
- * @param object|string $result MDB2_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 a valid tableInfo mode
- *
- * @return array an associative array with the information requested.
- * A MDB2_Error object on failure.
- *
- * @see MDB2_Driver_Common::setOption()
- */
- function tableInfo($result, $mode = null)
- {
- if (is_string($result)) {
- return parent::tableInfo($result, $mode);
- }
-
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $resource = MDB2::isResultCommon($result) ? $result->getResource() : $result;
- if (!is_resource($resource)) {
- return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'Could not generate result resource', __FUNCTION__);
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $case_func = 'strtolower';
- } else {
- $case_func = 'strtoupper';
- }
- } else {
- $case_func = 'strval';
- }
-
- $count = @mysql_num_fields($resource);
- $res = array();
- if ($mode) {
- $res['num_fields'] = $count;
- }
-
- $db->loadModule('Datatype', null, true);
- for ($i = 0; $i < $count; $i++) {
- $res[$i] = array(
- 'table' => $case_func(@mysql_field_table($resource, $i)),
- 'name' => $case_func(@mysql_field_name($resource, $i)),
- 'type' => @mysql_field_type($resource, $i),
- 'length' => @mysql_field_len($resource, $i),
- 'flags' => @mysql_field_flags($resource, $i),
- );
- if ($res[$i]['type'] == 'string') {
- $res[$i]['type'] = 'char';
- } elseif ($res[$i]['type'] == 'unknown') {
- $res[$i]['type'] = 'decimal';
- }
- $mdb2type_info = $db->datatype->mapNativeDatatype($res[$i]);
- if (PEAR::isError($mdb2type_info)) {
- return $mdb2type_info;
- }
- $res[$i]['mdb2type'] = $mdb2type_info[0][0];
- if ($mode & MDB2_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- }
-
- return $res;
- }
-}
-?> \ No newline at end of file
diff --git a/inc/MDB2/Driver/Reverse/pgsql.php b/inc/MDB2/Driver/Reverse/pgsql.php
deleted file mode 100644
index d010292cd8c..00000000000
--- a/inc/MDB2/Driver/Reverse/pgsql.php
+++ /dev/null
@@ -1,573 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS 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. |
-// +----------------------------------------------------------------------+
-// | Authors: Paul Cooper <pgc@ucecom.com> |
-// | Lorenzo Alberton <l.alberton@quipo.it> |
-// +----------------------------------------------------------------------+
-//
-// $Id: pgsql.php,v 1.75 2008/08/22 16:36:20 quipo Exp $
-
-oc_require_once('MDB2/Driver/Reverse/Common.php');
-
-/**
- * MDB2 PostGreSQL driver for the schema reverse engineering module
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper <pgc@ucecom.com>
- * @author Lorenzo Alberton <l.alberton@quipo.it>
- */
-class MDB2_Driver_Reverse_pgsql extends MDB2_Driver_Reverse_Common
-{
- // {{{ getTableFieldDefinition()
-
- /**
- * Get the structure of a field into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $field_name name of field that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableFieldDefinition($table_name, $field_name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $result = $db->loadModule('Datatype', null, true);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $query = "SELECT a.attname AS name,
- t.typname AS type,
- CASE a.attlen
- WHEN -1 THEN
- CASE t.typname
- WHEN 'numeric' THEN (a.atttypmod / 65536)
- WHEN 'decimal' THEN (a.atttypmod / 65536)
- WHEN 'money' THEN (a.atttypmod / 65536)
- ELSE CASE a.atttypmod
- WHEN -1 THEN NULL
- ELSE a.atttypmod - 4
- END
- END
- ELSE a.attlen
- END AS length,
- CASE t.typname
- WHEN 'numeric' THEN (a.atttypmod % 65536) - 4
- WHEN 'decimal' THEN (a.atttypmod % 65536) - 4
- WHEN 'money' THEN (a.atttypmod % 65536) - 4
- ELSE 0
- END AS scale,
- a.attnotnull,
- a.atttypmod,
- a.atthasdef,
- (SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128)
- FROM pg_attrdef d
- WHERE d.adrelid = a.attrelid
- AND d.adnum = a.attnum
- AND a.atthasdef
- ) as default
- FROM pg_attribute a,
- pg_class c,
- pg_type t
- WHERE c.relname = ".$db->quote($table, 'text')."
- AND a.atttypid = t.oid
- AND c.oid = a.attrelid
- AND NOT a.attisdropped
- AND a.attnum > 0
- AND a.attname = ".$db->quote($field_name, 'text')."
- ORDER BY a.attnum";
- $column = $db->queryRow($query, null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($column)) {
- return $column;
- }
-
- if (empty($column)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table column', __FUNCTION__);
- }
-
- $column = array_change_key_case($column, CASE_LOWER);
- $mapped_datatype = $db->datatype->mapNativeDatatype($column);
- if (PEAR::isError($mapped_datatype)) {
- return $mapped_datatype;
- }
- list($types, $length, $unsigned, $fixed) = $mapped_datatype;
- $notnull = false;
- if (!empty($column['attnotnull']) && $column['attnotnull'] == 't') {
- $notnull = true;
- }
- $default = null;
- if ($column['atthasdef'] === 't'
- && !preg_match("/nextval\('([^']+)'/", $column['default'])
- ) {
- $pattern = '/^\'(.*)\'::[\w ]+$/i';
- $default = $column['default'];#substr($column['adsrc'], 1, -1);
- if (is_null($default) && $notnull) {
- $default = '';
- } elseif (!empty($default) && preg_match($pattern, $default)) {
- //remove data type cast
- $default = preg_replace ($pattern, '\\1', $default);
- }
- }
- $autoincrement = false;
- if (preg_match("/nextval\('([^']+)'/", $column['default'], $nextvals)) {
- $autoincrement = true;
- }
- $definition[0] = array('notnull' => $notnull, 'nativetype' => $column['type']);
- if (!is_null($length)) {
- $definition[0]['length'] = $length;
- }
- if (!is_null($unsigned)) {
- $definition[0]['unsigned'] = $unsigned;
- }
- if (!is_null($fixed)) {
- $definition[0]['fixed'] = $fixed;
- }
- if ($default !== false) {
- $definition[0]['default'] = $default;
- }
- if ($autoincrement !== false) {
- $definition[0]['autoincrement'] = $autoincrement;
- }
- foreach ($types as $key => $type) {
- $definition[$key] = $definition[0];
- if ($type == 'clob' || $type == 'blob') {
- unset($definition[$key]['default']);
- }
- $definition[$key]['type'] = $type;
- $definition[$key]['mdb2type'] = $type;
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTableIndexDefinition()
-
- /**
- * Get the structure of an index into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $index_name name of index that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableIndexDefinition($table_name, $index_name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $query = 'SELECT relname, indkey FROM pg_index, pg_class';
- $query.= ' WHERE pg_class.oid = pg_index.indexrelid';
- $query.= " AND indisunique != 't' AND indisprimary != 't'";
- $query.= ' AND pg_class.relname = %s';
- $index_name_mdb2 = $db->getIndexName($index_name);
- $row = $db->queryRow(sprintf($query, $db->quote($index_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($row) || empty($row)) {
- // fallback to the given $index_name, without transformation
- $row = $db->queryRow(sprintf($query, $db->quote($index_name, 'text')), null, MDB2_FETCHMODE_ASSOC);
- }
- if (PEAR::isError($row)) {
- return $row;
- }
-
- if (empty($row)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table index', __FUNCTION__);
- }
-
- $row = array_change_key_case($row, CASE_LOWER);
-
- $db->loadModule('Manager', null, true);
- $columns = $db->manager->listTableFields($table_name);
-
- $definition = array();
-
- $index_column_numbers = explode(' ', $row['indkey']);
-
- $colpos = 1;
- foreach ($index_column_numbers as $number) {
- $definition['fields'][$columns[($number - 1)]] = array(
- 'position' => $colpos++,
- 'sorting' => 'ascending',
- );
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTableConstraintDefinition()
-
- /**
- * Get the structure of a constraint into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $constraint_name name of constraint that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableConstraintDefinition($table_name, $constraint_name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $query = "SELECT c.oid,
- c.conname AS constraint_name,
- CASE WHEN c.contype = 'c' THEN 1 ELSE 0 END AS \"check\",
- CASE WHEN c.contype = 'f' THEN 1 ELSE 0 END AS \"foreign\",
- CASE WHEN c.contype = 'p' THEN 1 ELSE 0 END AS \"primary\",
- CASE WHEN c.contype = 'u' THEN 1 ELSE 0 END AS \"unique\",
- CASE WHEN c.condeferrable = 'f' THEN 0 ELSE 1 END AS deferrable,
- CASE WHEN c.condeferred = 'f' THEN 0 ELSE 1 END AS initiallydeferred,
- --array_to_string(c.conkey, ' ') AS constraint_key,
- t.relname AS table_name,
- t2.relname AS references_table,
- CASE confupdtype
- WHEN 'a' THEN 'NO ACTION'
- WHEN 'r' THEN 'RESTRICT'
- WHEN 'c' THEN 'CASCADE'
- WHEN 'n' THEN 'SET NULL'
- WHEN 'd' THEN 'SET DEFAULT'
- END AS onupdate,
- CASE confdeltype
- WHEN 'a' THEN 'NO ACTION'
- WHEN 'r' THEN 'RESTRICT'
- WHEN 'c' THEN 'CASCADE'
- WHEN 'n' THEN 'SET NULL'
- WHEN 'd' THEN 'SET DEFAULT'
- END AS ondelete,
- CASE confmatchtype
- WHEN 'u' THEN 'UNSPECIFIED'
- WHEN 'f' THEN 'FULL'
- WHEN 'p' THEN 'PARTIAL'
- END AS match,
- --array_to_string(c.confkey, ' ') AS fk_constraint_key,
- consrc
- FROM pg_constraint c
- LEFT JOIN pg_class t ON c.conrelid = t.oid
- LEFT JOIN pg_class t2 ON c.confrelid = t2.oid
- WHERE c.conname = %s
- AND t.relname = " . $db->quote($table, 'text');
- $constraint_name_mdb2 = $db->getIndexName($constraint_name);
- $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($row) || empty($row)) {
- // fallback to the given $index_name, without transformation
- $constraint_name_mdb2 = $constraint_name;
- $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
- }
- if (PEAR::isError($row)) {
- return $row;
- }
- $uniqueIndex = false;
- if (empty($row)) {
- // We might be looking for a UNIQUE index that was not created
- // as a constraint but should be treated as such.
- $query = 'SELECT relname AS constraint_name,
- indkey,
- 0 AS "check",
- 0 AS "foreign",
- 0 AS "primary",
- 1 AS "unique",
- 0 AS deferrable,
- 0 AS initiallydeferred,
- NULL AS references_table,
- NULL AS onupdate,
- NULL AS ondelete,
- NULL AS match
- FROM pg_index, pg_class
- WHERE pg_class.oid = pg_index.indexrelid
- AND indisunique = \'t\'
- AND pg_class.relname = %s';
- $constraint_name_mdb2 = $db->getIndexName($constraint_name);
- $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($row) || empty($row)) {
- // fallback to the given $index_name, without transformation
- $constraint_name_mdb2 = $constraint_name;
- $row = $db->queryRow(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null, MDB2_FETCHMODE_ASSOC);
- }
- if (PEAR::isError($row)) {
- return $row;
- }
- if (empty($row)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $constraint_name . ' is not an existing table constraint', __FUNCTION__);
- }
- $uniqueIndex = true;
- }
-
- $row = array_change_key_case($row, CASE_LOWER);
-
- $definition = array(
- 'primary' => (boolean)$row['primary'],
- 'unique' => (boolean)$row['unique'],
- 'foreign' => (boolean)$row['foreign'],
- 'check' => (boolean)$row['check'],
- 'fields' => array(),
- 'references' => array(
- 'table' => $row['references_table'],
- 'fields' => array(),
- ),
- 'deferrable' => (boolean)$row['deferrable'],
- 'initiallydeferred' => (boolean)$row['initiallydeferred'],
- 'onupdate' => $row['onupdate'],
- 'ondelete' => $row['ondelete'],
- 'match' => $row['match'],
- );
-
- if ($uniqueIndex) {
- $db->loadModule('Manager', null, true);
- $columns = $db->manager->listTableFields($table_name);
- $index_column_numbers = explode(' ', $row['indkey']);
- $colpos = 1;
- foreach ($index_column_numbers as $number) {
- $definition['fields'][$columns[($number - 1)]] = array(
- 'position' => $colpos++,
- 'sorting' => 'ascending',
- );
- }
- return $definition;
- }
-
- $query = 'SELECT a.attname
- FROM pg_constraint c
- LEFT JOIN pg_class t ON c.conrelid = t.oid
- LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(c.conkey)
- WHERE c.conname = %s
- AND t.relname = ' . $db->quote($table, 'text');
- $fields = $db->queryCol(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null);
- if (PEAR::isError($fields)) {
- return $fields;
- }
- $colpos = 1;
- foreach ($fields as $field) {
- $definition['fields'][$field] = array(
- 'position' => $colpos++,
- 'sorting' => 'ascending',
- );
- }
-
- if ($definition['foreign']) {
- $query = 'SELECT a.attname
- FROM pg_constraint c
- LEFT JOIN pg_class t ON c.confrelid = t.oid
- LEFT JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = ANY(c.confkey)
- WHERE c.conname = %s
- AND t.relname = ' . $db->quote($definition['references']['table'], 'text');
- $foreign_fields = $db->queryCol(sprintf($query, $db->quote($constraint_name_mdb2, 'text')), null);
- if (PEAR::isError($foreign_fields)) {
- return $foreign_fields;
- }
- $colpos = 1;
- foreach ($foreign_fields as $foreign_field) {
- $definition['references']['fields'][$foreign_field] = array(
- 'position' => $colpos++,
- );
- }
- }
-
- if ($definition['check']) {
- $check_def = $db->queryOne("SELECT pg_get_constraintdef(" . $row['oid'] . ", 't')");
- // ...
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTriggerDefinition()
-
- /**
- * Get the structure of a trigger into an array
- *
- * EXPERIMENTAL
- *
- * WARNING: this function is experimental and may change the returned value
- * at any time until labelled as non-experimental
- *
- * @param string $trigger name of trigger that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- *
- * @TODO: add support for plsql functions and functions with args
- */
- function getTriggerDefinition($trigger)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT trg.tgname AS trigger_name,
- tbl.relname AS table_name,
- CASE
- WHEN p.proname IS NOT NULL THEN 'EXECUTE PROCEDURE ' || p.proname || '();'
- ELSE ''
- END AS trigger_body,
- CASE trg.tgtype & cast(2 as int2)
- WHEN 0 THEN 'AFTER'
- ELSE 'BEFORE'
- END AS trigger_type,
- CASE trg.tgtype & cast(28 as int2)
- WHEN 16 THEN 'UPDATE'
- WHEN 8 THEN 'DELETE'
- WHEN 4 THEN 'INSERT'
- WHEN 20 THEN 'INSERT, UPDATE'
- WHEN 28 THEN 'INSERT, UPDATE, DELETE'
- WHEN 24 THEN 'UPDATE, DELETE'
- WHEN 12 THEN 'INSERT, DELETE'
- END AS trigger_event,
- CASE trg.tgenabled
- WHEN 'O' THEN 't'
- ELSE trg.tgenabled
- END AS trigger_enabled,
- obj_description(trg.oid, 'pg_trigger') AS trigger_comment
- FROM pg_trigger trg,
- pg_class tbl,
- pg_proc p
- WHERE trg.tgrelid = tbl.oid
- AND trg.tgfoid = p.oid
- AND trg.tgname = ". $db->quote($trigger, 'text');
- $types = array(
- 'trigger_name' => 'text',
- 'table_name' => 'text',
- 'trigger_body' => 'text',
- 'trigger_type' => 'text',
- 'trigger_event' => 'text',
- 'trigger_comment' => 'text',
- 'trigger_enabled' => 'boolean',
- );
- return $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table or a result set
- *
- * NOTE: only supports 'table' and 'flags' if <var>$result</var>
- * is a table name.
- *
- * @param object|string $result MDB2_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 a valid tableInfo mode
- *
- * @return array an associative array with the information requested.
- * A MDB2_Error object on failure.
- *
- * @see MDB2_Driver_Common::tableInfo()
- */
- function tableInfo($result, $mode = null)
- {
- if (is_string($result)) {
- return parent::tableInfo($result, $mode);
- }
-
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $resource = MDB2::isResultCommon($result) ? $result->getResource() : $result;
- if (!is_resource($resource)) {
- return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'Could not generate result resource', __FUNCTION__);
- }
-
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $case_func = 'strtolower';
- } else {
- $case_func = 'strtoupper';
- }
- } else {
- $case_func = 'strval';
- }
-
- $count = @pg_num_fields($resource);
- $res = array();
-
- if ($mode) {
- $res['num_fields'] = $count;
- }
-
- $db->loadModule('Datatype', null, true);
- for ($i = 0; $i < $count; $i++) {
- $res[$i] = array(
- 'table' => function_exists('pg_field_table') ? @pg_field_table($resource, $i) : '',
- 'name' => $case_func(@pg_field_name($resource, $i)),
- 'type' => @pg_field_type($resource, $i),
- 'length' => @pg_field_size($resource, $i),
- 'flags' => '',
- );
- $mdb2type_info = $db->datatype->mapNativeDatatype($res[$i]);
- if (PEAR::isError($mdb2type_info)) {
- return $mdb2type_info;
- }
- $res[$i]['mdb2type'] = $mdb2type_info[0][0];
- if ($mode & MDB2_TABLEINFO_ORDER) {
- $res['order'][$res[$i]['name']] = $i;
- }
- if ($mode & MDB2_TABLEINFO_ORDERTABLE) {
- $res['ordertable'][$res[$i]['table']][$res[$i]['name']] = $i;
- }
- }
-
- return $res;
- }
-}
-?> \ No newline at end of file
diff --git a/inc/MDB2/Driver/Reverse/sqlite.php b/inc/MDB2/Driver/Reverse/sqlite.php
deleted file mode 100644
index 1b85aa71f9a..00000000000
--- a/inc/MDB2/Driver/Reverse/sqlite.php
+++ /dev/null
@@ -1,609 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2007 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith, Lorenzo Alberton |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS 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. |
-// +----------------------------------------------------------------------+
-// | Authors: Lukas Smith <smith@pooteeweet.org> |
-// | Lorenzo Alberton <l.alberton@quipo.it> |
-// +----------------------------------------------------------------------+
-//
-// $Id: sqlite.php,v 1.80 2008/05/03 10:30:14 quipo Exp $
-//
-
-oc_require_once('MDB2/Driver/Reverse/Common.php');
-
-/**
- * MDB2 SQlite driver for the schema reverse engineering module
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_Reverse_sqlite extends MDB2_Driver_Reverse_Common
-{
- /**
- * Remove SQL comments from the field definition
- *
- * @access private
- */
- function _removeComments($sql) {
- $lines = split("\n", $sql);
- foreach ($lines as $k => $line) {
- $pieces = explode('--', $line);
- if (count($pieces) > 1 && (substr_count($pieces[0], '\'') % 2) == 0) {
- $lines[$k] = substr($line, 0, strpos($line, '--'));
- }
- }
- return implode("\n", $lines);
- }
-
- /**
- *
- */
- function _getTableColumns($sql)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $start_pos = strpos($sql, '(');
- $end_pos = strrpos($sql, ')');
- $column_def = substr($sql, $start_pos+1, $end_pos-$start_pos-1);
- // replace the decimal length-places-separator with a colon
- $column_def = preg_replace('/(\d),(\d)/', '\1:\2', $column_def);
- $column_def = $this->_removeComments($column_def);
- $column_sql = split(',', $column_def);
- $columns = array();
- $count = count($column_sql);
- if ($count == 0) {
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'unexpected empty table column definition list', __FUNCTION__);
- }
- $regexp = '/^\s*([^\s]+) +(CHAR|VARCHAR|VARCHAR2|TEXT|BOOLEAN|SMALLINT|INT|INTEGER|DECIMAL|BIGINT|DOUBLE|FLOAT|DATETIME|DATE|TIME|LONGTEXT|LONGBLOB)( ?\(([1-9][0-9]*)(:([1-9][0-9]*))?\))?( NULL| NOT NULL)?( UNSIGNED)?( NULL| NOT NULL)?( PRIMARY KEY)?( DEFAULT (\'[^\']*\'|[^ ]+))?( NULL| NOT NULL)?( PRIMARY KEY)?(\s*\-\-.*)?$/i';
- $regexp2 = '/^\s*([^ ]+) +(PRIMARY|UNIQUE|CHECK)$/i';
- for ($i=0, $j=0; $i<$count; ++$i) {
- if (!preg_match($regexp, trim($column_sql[$i]), $matches)) {
- if (!preg_match($regexp2, trim($column_sql[$i]))) {
- continue;
- }
- return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'unexpected table column SQL definition: "'.$column_sql[$i].'"', __FUNCTION__);
- }
- $columns[$j]['name'] = trim($matches[1], implode('', $db->identifier_quoting));
- $columns[$j]['type'] = strtolower($matches[2]);
- if (isset($matches[4]) && strlen($matches[4])) {
- $columns[$j]['length'] = $matches[4];
- }
- if (isset($matches[6]) && strlen($matches[6])) {
- $columns[$j]['decimal'] = $matches[6];
- }
- if (isset($matches[8]) && strlen($matches[8])) {
- $columns[$j]['unsigned'] = true;
- }
- if (isset($matches[9]) && strlen($matches[9])) {
- $columns[$j]['autoincrement'] = true;
- }
- if (isset($matches[12]) && strlen($matches[12])) {
- $default = $matches[12];
- if (strlen($default) && $default[0]=="'") {
- $default = str_replace("''", "'", substr($default, 1, strlen($default)-2));
- }
- if ($default === 'NULL') {
- $default = null;
- }
- $columns[$j]['default'] = $default;
- }
- if (isset($matches[7]) && strlen($matches[7])) {
- $columns[$j]['notnull'] = ($matches[7] === ' NOT NULL');
- } else if (isset($matches[9]) && strlen($matches[9])) {
- $columns[$j]['notnull'] = ($matches[9] === ' NOT NULL');
- } else if (isset($matches[13]) && strlen($matches[13])) {
- $columns[$j]['notnull'] = ($matches[13] === ' NOT NULL');
- }
- ++$j;
- }
- return $columns;
- }
-
- // {{{ getTableFieldDefinition()
-
- /**
- * Get the stucture of a field into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $field_name name of field that should be used in method
- * @return mixed data array on success, a MDB2 error on failure.
- * The returned array contains an array for each field definition,
- * with (some of) these indices:
- * [notnull] [nativetype] [length] [fixed] [default] [type] [mdb2type]
- * @access public
- */
- function getTableFieldDefinition($table_name, $field_name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $result = $db->loadModule('Datatype', null, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text');
- } else {
- $query.= 'name='.$db->quote($table, 'text');
- }
- $sql = $db->queryOne($query);
- if (PEAR::isError($sql)) {
- return $sql;
- }
- $columns = $this->_getTableColumns($sql);
- foreach ($columns as $column) {
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- if ($db->options['field_case'] == CASE_LOWER) {
- $column['name'] = strtolower($column['name']);
- } else {
- $column['name'] = strtoupper($column['name']);
- }
- } else {
- $column = array_change_key_case($column, $db->options['field_case']);
- }
- if ($field_name == $column['name']) {
- $mapped_datatype = $db->datatype->mapNativeDatatype($column);
- if (PEAR::isError($mapped_datatype)) {
- return $mapped_datatype;
- }
- list($types, $length, $unsigned, $fixed) = $mapped_datatype;
- $notnull = false;
- if (!empty($column['notnull'])) {
- $notnull = $column['notnull'];
- }
- $default = false;
- if (array_key_exists('default', $column)) {
- $default = $column['default'];
- if (is_null($default) && $notnull) {
- $default = '';
- }
- }
- $autoincrement = false;
- if (!empty($column['autoincrement'])) {
- $autoincrement = true;
- }
-
- $definition[0] = array(
- 'notnull' => $notnull,
- 'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $column['type'])
- );
- if (!is_null($length)) {
- $definition[0]['length'] = $length;
- }
- if (!is_null($unsigned)) {
- $definition[0]['unsigned'] = $unsigned;
- }
- if (!is_null($fixed)) {
- $definition[0]['fixed'] = $fixed;
- }
- if ($default !== false) {
- $definition[0]['default'] = $default;
- }
- if ($autoincrement !== false) {
- $definition[0]['autoincrement'] = $autoincrement;
- }
- foreach ($types as $key => $type) {
- $definition[$key] = $definition[0];
- if ($type == 'clob' || $type == 'blob') {
- unset($definition[$key]['default']);
- }
- $definition[$key]['type'] = $type;
- $definition[$key]['mdb2type'] = $type;
- }
- return $definition;
- }
- }
-
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table column', __FUNCTION__);
- }
-
- // }}}
- // {{{ getTableIndexDefinition()
-
- /**
- * Get the stucture of an index into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $index_name name of index that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableIndexDefinition($table_name, $index_name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' . $db->quote(strtolower($table), 'text');
- } else {
- $query.= 'name=%s AND tbl_name=' . $db->quote($table, 'text');
- }
- $query.= ' AND sql NOT NULL ORDER BY name';
- $index_name_mdb2 = $db->getIndexName($index_name);
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $qry = sprintf($query, $db->quote(strtolower($index_name_mdb2), 'text'));
- } else {
- $qry = sprintf($query, $db->quote($index_name_mdb2, 'text'));
- }
- $sql = $db->queryOne($qry, 'text');
- if (PEAR::isError($sql) || empty($sql)) {
- // fallback to the given $index_name, without transformation
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $qry = sprintf($query, $db->quote(strtolower($index_name), 'text'));
- } else {
- $qry = sprintf($query, $db->quote($index_name, 'text'));
- }
- $sql = $db->queryOne($qry, 'text');
- }
- if (PEAR::isError($sql)) {
- return $sql;
- }
- if (!$sql) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table index', __FUNCTION__);
- }
-
- $sql = strtolower($sql);
- $start_pos = strpos($sql, '(');
- $end_pos = strrpos($sql, ')');
- $column_names = substr($sql, $start_pos+1, $end_pos-$start_pos-1);
- $column_names = split(',', $column_names);
-
- if (preg_match("/^create unique/", $sql)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table index', __FUNCTION__);
- }
-
- $definition = array();
- $count = count($column_names);
- for ($i=0; $i<$count; ++$i) {
- $column_name = strtok($column_names[$i], ' ');
- $collation = strtok(' ');
- $definition['fields'][$column_name] = array(
- 'position' => $i+1
- );
- if (!empty($collation)) {
- $definition['fields'][$column_name]['sorting'] =
- ($collation=='ASC' ? 'ascending' : 'descending');
- }
- }
-
- if (empty($definition['fields'])) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing table index', __FUNCTION__);
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTableConstraintDefinition()
-
- /**
- * Get the stucture of a constraint into an array
- *
- * @param string $table_name name of table that should be used in method
- * @param string $constraint_name name of constraint that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTableConstraintDefinition($table_name, $constraint_name)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- list($schema, $table) = $this->splitTableSchema($table_name);
-
- $query = "SELECT sql FROM sqlite_master WHERE type='index' AND ";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= 'LOWER(name)=%s AND LOWER(tbl_name)=' . $db->quote(strtolower($table), 'text');
- } else {
- $query.= 'name=%s AND tbl_name=' . $db->quote($table, 'text');
- }
- $query.= ' AND sql NOT NULL ORDER BY name';
- $constraint_name_mdb2 = $db->getIndexName($constraint_name);
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $qry = sprintf($query, $db->quote(strtolower($constraint_name_mdb2), 'text'));
- } else {
- $qry = sprintf($query, $db->quote($constraint_name_mdb2, 'text'));
- }
- $sql = $db->queryOne($qry, 'text');
- if (PEAR::isError($sql) || empty($sql)) {
- // fallback to the given $index_name, without transformation
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $qry = sprintf($query, $db->quote(strtolower($constraint_name), 'text'));
- } else {
- $qry = sprintf($query, $db->quote($constraint_name, 'text'));
- }
- $sql = $db->queryOne($qry, 'text');
- }
- if (PEAR::isError($sql)) {
- return $sql;
- }
- //default values, eventually overridden
- $definition = array(
- 'primary' => false,
- 'unique' => false,
- 'foreign' => false,
- 'check' => false,
- 'fields' => array(),
- 'references' => array(
- 'table' => '',
- 'fields' => array(),
- ),
- 'onupdate' => '',
- 'ondelete' => '',
- 'match' => '',
- 'deferrable' => false,
- 'initiallydeferred' => false,
- );
- if (!$sql) {
- $query = "SELECT sql FROM sqlite_master WHERE type='table' AND ";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= 'LOWER(name)='.$db->quote(strtolower($table), 'text');
- } else {
- $query.= 'name='.$db->quote($table, 'text');
- }
- $query.= " AND sql NOT NULL ORDER BY name";
- $sql = $db->queryOne($query, 'text');
- if (PEAR::isError($sql)) {
- return $sql;
- }
- if ($constraint_name == 'primary') {
- // search in table definition for PRIMARY KEYs
- if (preg_match("/\bPRIMARY\s+KEY\b\s*\(([^)]+)/i", $sql, $tmp)) {
- $definition['primary'] = true;
- $definition['fields'] = array();
- $column_names = split(',', $tmp[1]);
- $colpos = 1;
- foreach ($column_names as $column_name) {
- $definition['fields'][trim($column_name)] = array(
- 'position' => $colpos++
- );
- }
- return $definition;
- }
- if (preg_match("/\"([^\"]+)\"[^\,\"]+\bPRIMARY\s+KEY\b[^\,\)]*/i", $sql, $tmp)) {
- $definition['primary'] = true;
- $definition['fields'] = array();
- $column_names = split(',', $tmp[1]);
- $colpos = 1;
- foreach ($column_names as $column_name) {
- $definition['fields'][trim($column_name)] = array(
- 'position' => $colpos++
- );
- }
- return $definition;
- }
- } else {
- // search in table definition for FOREIGN KEYs
- $pattern = "/\bCONSTRAINT\b\s+%s\s+
- \bFOREIGN\s+KEY\b\s*\(([^\)]+)\)\s*
- \bREFERENCES\b\s+([^\s]+)\s*\(([^\)]+)\)\s*
- (?:\bMATCH\s*([^\s]+))?\s*
- (?:\bON\s+UPDATE\s+([^\s,\)]+))?\s*
- (?:\bON\s+DELETE\s+([^\s,\)]+))?\s*
- /imsx";
- $found_fk = false;
- if (preg_match(sprintf($pattern, $constraint_name_mdb2), $sql, $tmp)) {
- $found_fk = true;
- } elseif (preg_match(sprintf($pattern, $constraint_name), $sql, $tmp)) {
- $found_fk = true;
- }
- if ($found_fk) {
- $definition['foreign'] = true;
- $definition['match'] = 'SIMPLE';
- $definition['onupdate'] = 'NO ACTION';
- $definition['ondelete'] = 'NO ACTION';
- $definition['references']['table'] = $tmp[2];
- $column_names = split(',', $tmp[1]);
- $colpos = 1;
- foreach ($column_names as $column_name) {
- $definition['fields'][trim($column_name)] = array(
- 'position' => $colpos++
- );
- }
- $referenced_cols = split(',', $tmp[3]);
- $colpos = 1;
- foreach ($referenced_cols as $column_name) {
- $definition['references']['fields'][trim($column_name)] = array(
- 'position' => $colpos++
- );
- }
- if (isset($tmp[4])) {
- $definition['match'] = $tmp[4];
- }
- if (isset($tmp[5])) {
- $definition['onupdate'] = $tmp[5];
- }
- if (isset($tmp[6])) {
- $definition['ondelete'] = $tmp[6];
- }
- return $definition;
- }
- }
- $sql = false;
- }
- if (!$sql) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $constraint_name . ' is not an existing table constraint', __FUNCTION__);
- }
-
- $sql = strtolower($sql);
- $start_pos = strpos($sql, '(');
- $end_pos = strrpos($sql, ')');
- $column_names = substr($sql, $start_pos+1, $end_pos-$start_pos-1);
- $column_names = split(',', $column_names);
-
- if (!preg_match("/^create unique/", $sql)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $constraint_name . ' is not an existing table constraint', __FUNCTION__);
- }
-
- $definition['unique'] = true;
- $count = count($column_names);
- for ($i=0; $i<$count; ++$i) {
- $column_name = strtok($column_names[$i]," ");
- $collation = strtok(" ");
- $definition['fields'][$column_name] = array(
- 'position' => $i+1
- );
- if (!empty($collation)) {
- $definition['fields'][$column_name]['sorting'] =
- ($collation=='ASC' ? 'ascending' : 'descending');
- }
- }
-
- if (empty($definition['fields'])) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- $constraint_name . ' is not an existing table constraint', __FUNCTION__);
- }
- return $definition;
- }
-
- // }}}
- // {{{ getTriggerDefinition()
-
- /**
- * Get the structure of a trigger into an array
- *
- * EXPERIMENTAL
- *
- * WARNING: this function is experimental and may change the returned value
- * at any time until labelled as non-experimental
- *
- * @param string $trigger name of trigger that should be used in method
- * @return mixed data array on success, a MDB2 error on failure
- * @access public
- */
- function getTriggerDefinition($trigger)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $query = "SELECT name as trigger_name,
- tbl_name AS table_name,
- sql AS trigger_body,
- NULL AS trigger_type,
- NULL AS trigger_event,
- NULL AS trigger_comment,
- 1 AS trigger_enabled
- FROM sqlite_master
- WHERE type='trigger'";
- if ($db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $query.= ' AND LOWER(name)='.$db->quote(strtolower($trigger), 'text');
- } else {
- $query.= ' AND name='.$db->quote($trigger, 'text');
- }
- $types = array(
- 'trigger_name' => 'text',
- 'table_name' => 'text',
- 'trigger_body' => 'text',
- 'trigger_type' => 'text',
- 'trigger_event' => 'text',
- 'trigger_comment' => 'text',
- 'trigger_enabled' => 'boolean',
- );
- $def = $db->queryRow($query, $types, MDB2_FETCHMODE_ASSOC);
- if (PEAR::isError($def)) {
- return $def;
- }
- if (empty($def)) {
- return $db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'it was not specified an existing trigger', __FUNCTION__);
- }
- if (preg_match("/^create\s+(?:temp|temporary)?trigger\s+(?:if\s+not\s+exists\s+)?.*(before|after)?\s+(insert|update|delete)/Uims", $def['trigger_body'], $tmp)) {
- $def['trigger_type'] = strtoupper($tmp[1]);
- $def['trigger_event'] = strtoupper($tmp[2]);
- }
- return $def;
- }
-
- // }}}
- // {{{ tableInfo()
-
- /**
- * Returns information about a table
- *
- * @param string $result a string containing the name of a table
- * @param int $mode a valid tableInfo mode
- *
- * @return array an associative array with the information requested.
- * A MDB2_Error object on failure.
- *
- * @see MDB2_Driver_Common::tableInfo()
- * @since Method available since Release 1.7.0
- */
- function tableInfo($result, $mode = null)
- {
- if (is_string($result)) {
- return parent::tableInfo($result, $mode);
- }
-
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- return $db->raiseError(MDB2_ERROR_NOT_CAPABLE, null, null,
- 'This DBMS can not obtain tableInfo from result sets', __FUNCTION__);
- }
-}
-
-?> \ No newline at end of file
diff --git a/inc/MDB2/Driver/mysql.php b/inc/MDB2/Driver/mysql.php
deleted file mode 100644
index 091c479d194..00000000000
--- a/inc/MDB2/Driver/mysql.php
+++ /dev/null
@@ -1,1700 +0,0 @@
-<?php
-// vim: set et ts=4 sw=4 fdm=marker:
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: mysql.php,v 1.214 2008/11/16 21:45:08 quipo Exp $
-//
-
-/**
- * MDB2 MySQL driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_mysql extends MDB2_Driver_Common
-{
- // {{{ properties
-
- var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => '\\', 'escape_pattern' => '\\');
-
- var $identifier_quoting = array('start' => '`', 'end' => '`', 'escape' => '`');
-
- var $sql_comments = array(
- array('start' => '-- ', 'end' => "\n", 'escape' => false),
- array('start' => '#', 'end' => "\n", 'escape' => false),
- array('start' => '/*', 'end' => '*/', 'escape' => false),
- );
-
- var $server_capabilities_checked = false;
-
- var $start_transaction = false;
-
- var $varchar_max_length = 255;
-
- // }}}
- // {{{ constructor
-
- /**
- * Constructor
- */
- function __construct()
- {
- parent::__construct();
-
- $this->phptype = 'mysql';
- $this->dbsyntax = 'mysql';
-
- $this->supported['sequences'] = 'emulated';
- $this->supported['indexes'] = true;
- $this->supported['affected_rows'] = true;
- $this->supported['transactions'] = false;
- $this->supported['savepoints'] = false;
- $this->supported['summary_functions'] = true;
- $this->supported['order_by_text'] = true;
- $this->supported['current_id'] = 'emulated';
- $this->supported['limit_queries'] = true;
- $this->supported['LOBs'] = true;
- $this->supported['replace'] = true;
- $this->supported['sub_selects'] = 'emulated';
- $this->supported['triggers'] = false;
- $this->supported['auto_increment'] = true;
- $this->supported['primary_key'] = true;
- $this->supported['result_introspection'] = true;
- $this->supported['prepared_statements'] = 'emulated';
- $this->supported['identifier_quoting'] = true;
- $this->supported['pattern_escaping'] = true;
- $this->supported['new_link'] = true;
-
- $this->options['DBA_username'] = false;
- $this->options['DBA_password'] = false;
- $this->options['default_table_type'] = '';
- $this->options['max_identifiers_length'] = 64;
-
- $this->_reCheckSupportedOptions();
- }
-
- // }}}
- // {{{ _reCheckSupportedOptions()
-
- /**
- * If the user changes certain options, other capabilities may depend
- * on the new settings, so we need to check them (again).
- *
- * @access private
- */
- function _reCheckSupportedOptions()
- {
- $this->supported['transactions'] = $this->options['use_transactions'];
- $this->supported['savepoints'] = $this->options['use_transactions'];
- if ($this->options['default_table_type']) {
- switch (strtoupper($this->options['default_table_type'])) {
- case 'BLACKHOLE':
- case 'MEMORY':
- case 'ARCHIVE':
- case 'CSV':
- case 'HEAP':
- case 'ISAM':
- case 'MERGE':
- case 'MRG_ISAM':
- case 'ISAM':
- case 'MRG_MYISAM':
- case 'MYISAM':
- $this->supported['savepoints'] = false;
- $this->supported['transactions'] = false;
- $this->warnings[] = $this->options['default_table_type'] .
- ' is not a supported default table type';
- break;
- }
- }
- }
-
- // }}}
- // {{{ function setOption($option, $value)
-
- /**
- * set the option for the db class
- *
- * @param string option name
- * @param mixed value for the option
- *
- * @return mixed MDB2_OK or MDB2 Error Object
- *
- * @access public
- */
- function setOption($option, $value)
- {
- $res = parent::setOption($option, $value);
- $this->_reCheckSupportedOptions();
- }
-
- // }}}
- // {{{ errorInfo()
-
- /**
- * This method is used to collect information about an error
- *
- * @param integer $error
- * @return array
- * @access public
- */
- function errorInfo($error = null)
- {
- if ($this->connection) {
- $native_code = @mysql_errno($this->connection);
- $native_msg = @mysql_error($this->connection);
- } else {
- $native_code = @mysql_errno();
- $native_msg = @mysql_error();
- }
- if (is_null($error)) {
- static $ecode_map;
- if (empty($ecode_map)) {
- $ecode_map = array(
- 1000 => MDB2_ERROR_INVALID, //hashchk
- 1001 => MDB2_ERROR_INVALID, //isamchk
- 1004 => MDB2_ERROR_CANNOT_CREATE,
- 1005 => MDB2_ERROR_CANNOT_CREATE,
- 1006 => MDB2_ERROR_CANNOT_CREATE,
- 1007 => MDB2_ERROR_ALREADY_EXISTS,
- 1008 => MDB2_ERROR_CANNOT_DROP,
- 1009 => MDB2_ERROR_CANNOT_DROP,
- 1010 => MDB2_ERROR_CANNOT_DROP,
- 1011 => MDB2_ERROR_CANNOT_DELETE,
- 1022 => MDB2_ERROR_ALREADY_EXISTS,
- 1029 => MDB2_ERROR_NOT_FOUND,
- 1032 => MDB2_ERROR_NOT_FOUND,
- 1044 => MDB2_ERROR_ACCESS_VIOLATION,
- 1045 => MDB2_ERROR_ACCESS_VIOLATION,
- 1046 => MDB2_ERROR_NODBSELECTED,
- 1048 => MDB2_ERROR_CONSTRAINT,
- 1049 => MDB2_ERROR_NOSUCHDB,
- 1050 => MDB2_ERROR_ALREADY_EXISTS,
- 1051 => MDB2_ERROR_NOSUCHTABLE,
- 1054 => MDB2_ERROR_NOSUCHFIELD,
- 1060 => MDB2_ERROR_ALREADY_EXISTS,
- 1061 => MDB2_ERROR_ALREADY_EXISTS,
- 1062 => MDB2_ERROR_ALREADY_EXISTS,
- 1064 => MDB2_ERROR_SYNTAX,
- 1067 => MDB2_ERROR_INVALID,
- 1072 => MDB2_ERROR_NOT_FOUND,
- 1086 => MDB2_ERROR_ALREADY_EXISTS,
- 1091 => MDB2_ERROR_NOT_FOUND,
- 1100 => MDB2_ERROR_NOT_LOCKED,
- 1109 => MDB2_ERROR_NOT_FOUND,
- 1125 => MDB2_ERROR_ALREADY_EXISTS,
- 1136 => MDB2_ERROR_VALUE_COUNT_ON_ROW,
- 1138 => MDB2_ERROR_INVALID,
- 1142 => MDB2_ERROR_ACCESS_VIOLATION,
- 1143 => MDB2_ERROR_ACCESS_VIOLATION,
- 1146 => MDB2_ERROR_NOSUCHTABLE,
- 1149 => MDB2_ERROR_SYNTAX,
- 1169 => MDB2_ERROR_CONSTRAINT,
- 1176 => MDB2_ERROR_NOT_FOUND,
- 1177 => MDB2_ERROR_NOSUCHTABLE,
- 1213 => MDB2_ERROR_DEADLOCK,
- 1216 => MDB2_ERROR_CONSTRAINT,
- 1217 => MDB2_ERROR_CONSTRAINT,
- 1227 => MDB2_ERROR_ACCESS_VIOLATION,
- 1235 => MDB2_ERROR_CANNOT_CREATE,
- 1299 => MDB2_ERROR_INVALID_DATE,
- 1300 => MDB2_ERROR_INVALID,
- 1304 => MDB2_ERROR_ALREADY_EXISTS,
- 1305 => MDB2_ERROR_NOT_FOUND,
- 1306 => MDB2_ERROR_CANNOT_DROP,
- 1307 => MDB2_ERROR_CANNOT_CREATE,
- 1334 => MDB2_ERROR_CANNOT_ALTER,
- 1339 => MDB2_ERROR_NOT_FOUND,
- 1356 => MDB2_ERROR_INVALID,
- 1359 => MDB2_ERROR_ALREADY_EXISTS,
- 1360 => MDB2_ERROR_NOT_FOUND,
- 1363 => MDB2_ERROR_NOT_FOUND,
- 1365 => MDB2_ERROR_DIVZERO,
- 1451 => MDB2_ERROR_CONSTRAINT,
- 1452 => MDB2_ERROR_CONSTRAINT,
- 1542 => MDB2_ERROR_CANNOT_DROP,
- 1546 => MDB2_ERROR_CONSTRAINT,
- 1582 => MDB2_ERROR_CONSTRAINT,
- 2003 => MDB2_ERROR_CONNECT_FAILED,
- 2019 => MDB2_ERROR_INVALID,
- );
- }
- if ($this->options['portability'] & MDB2_PORTABILITY_ERRORS) {
- $ecode_map[1022] = MDB2_ERROR_CONSTRAINT;
- $ecode_map[1048] = MDB2_ERROR_CONSTRAINT_NOT_NULL;
- $ecode_map[1062] = MDB2_ERROR_CONSTRAINT;
- } else {
- // Doing this in case mode changes during runtime.
- $ecode_map[1022] = MDB2_ERROR_ALREADY_EXISTS;
- $ecode_map[1048] = MDB2_ERROR_CONSTRAINT;
- $ecode_map[1062] = MDB2_ERROR_ALREADY_EXISTS;
- }
- if (isset($ecode_map[$native_code])) {
- $error = $ecode_map[$native_code];
- }
- }
- return array($error, $native_code, $native_msg);
- }
-
- // }}}
- // {{{ escape()
-
- /**
- * Quotes a string so it can be safely used in a query. It will quote
- * the text so it can safely be used within a query.
- *
- * @param string the input string to quote
- * @param bool escape wildcards
- *
- * @return string quoted string
- *
- * @access public
- */
- function escape($text, $escape_wildcards = false)
- {
- if ($escape_wildcards) {
- $text = $this->escapePattern($text);
- }
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- $text = @mysql_real_escape_string($text, $connection);
- return $text;
- }
-
- // }}}
- // {{{ beginTransaction()
-
- /**
- * Start a transaction or set a savepoint.
- *
- * @param string name of a savepoint to set
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function beginTransaction($savepoint = null)
- {
- $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- $this->_getServerCapabilities();
- if (!is_null($savepoint)) {
- if (!$this->supports('savepoints')) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'savepoints are not supported', __FUNCTION__);
- }
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
- }
- $query = 'SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- } elseif ($this->in_transaction) {
- return MDB2_OK; //nothing to do
- }
- if (!$this->destructor_registered && $this->opened_persistent) {
- $this->destructor_registered = true;
- register_shutdown_function('MDB2_closeOpenTransactions');
- }
- $query = $this->start_transaction ? 'START TRANSACTION' : 'SET AUTOCOMMIT = 0';
- $result =& $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = true;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ commit()
-
- /**
- * Commit the database changes done during a transaction that is in
- * progress or release a savepoint. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after committing the pending changes.
- *
- * @param string name of a savepoint to release
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function commit($savepoint = null)
- {
- $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
- }
- if (!is_null($savepoint)) {
- if (!$this->supports('savepoints')) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'savepoints are not supported', __FUNCTION__);
- }
- $server_info = $this->getServerVersion();
- if (version_compare($server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'], '5.0.3', '<')) {
- return MDB2_OK;
- }
- $query = 'RELEASE SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- }
-
- if (!$this->supports('transactions')) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'transactions are not supported', __FUNCTION__);
- }
-
- $result =& $this->_doQuery('COMMIT', true);
- if (PEAR::isError($result)) {
- return $result;
- }
- if (!$this->start_transaction) {
- $query = 'SET AUTOCOMMIT = 1';
- $result =& $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ rollback()
-
- /**
- * Cancel any database changes done during a transaction or since a specific
- * savepoint that is in progress. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after canceling the pending changes.
- *
- * @param string name of a savepoint to rollback to
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function rollback($savepoint = null)
- {
- $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'rollback cannot be done changes are auto committed', __FUNCTION__);
- }
- if (!is_null($savepoint)) {
- if (!$this->supports('savepoints')) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'savepoints are not supported', __FUNCTION__);
- }
- $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- }
-
- $query = 'ROLLBACK';
- $result =& $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- if (!$this->start_transaction) {
- $query = 'SET AUTOCOMMIT = 1';
- $result =& $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function setTransactionIsolation()
-
- /**
- * Set the transacton isolation level.
- *
- * @param string standard isolation level
- * READ UNCOMMITTED (allows dirty reads)
- * READ COMMITTED (prevents dirty reads)
- * REPEATABLE READ (prevents nonrepeatable reads)
- * SERIALIZABLE (prevents phantom reads)
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- * @since 2.1.1
- */
- function setTransactionIsolation($isolation)
- {
- $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
- if (!$this->supports('transactions')) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'transactions are not supported', __FUNCTION__);
- }
- switch ($isolation) {
- case 'READ UNCOMMITTED':
- case 'READ COMMITTED':
- case 'REPEATABLE READ':
- case 'SERIALIZABLE':
- break;
- default:
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'isolation level is not supported: '.$isolation, __FUNCTION__);
- }
-
- $query = "SET SESSION TRANSACTION ISOLATION LEVEL $isolation";
- return $this->_doQuery($query, true);
- }
-
- // }}}
- // {{{ _doConnect()
-
- /**
- * do the grunt work of the connect
- *
- * @return connection on success or MDB2 Error Object on failure
- * @access protected
- */
- function _doConnect($username, $password, $persistent = false)
- {
- if (!PEAR::loadExtension($this->phptype)) {
- return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
- }
-
- $params = array();
- if ($this->dsn['protocol'] && $this->dsn['protocol'] == 'unix') {
- $params[0] = ':' . $this->dsn['socket'];
- } else {
- $params[0] = $this->dsn['hostspec'] ? $this->dsn['hostspec']
- : 'localhost';
- if ($this->dsn['port']) {
- $params[0].= ':' . $this->dsn['port'];
- }
- }
- $params[] = $username ? $username : null;
- $params[] = $password ? $password : null;
- if (!$persistent) {
- if ($this->_isNewLinkSet()) {
- $params[] = true;
- } else {
- $params[] = false;
- }
- }
- if (version_compare(phpversion(), '4.3.0', '>=')) {
- $params[] = isset($this->dsn['client_flags'])
- ? $this->dsn['client_flags'] : null;
- }
- $connect_function = $persistent ? 'mysql_pconnect' : 'mysql_connect';
-
- $connection = @call_user_func_array($connect_function, $params);
- if (!$connection) {
- if (($err = @mysql_error()) != '') {
- return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
- $err, __FUNCTION__);
- } else {
- return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
- 'unable to establish a connection', __FUNCTION__);
- }
- }
-
- if (!empty($this->dsn['charset'])) {
- $result = $this->setCharset($this->dsn['charset'], $connection);
- if (PEAR::isError($result)) {
- $this->disconnect(false);
- return $result;
- }
- }
-
- return $connection;
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to the database
- *
- * @return MDB2_OK on success, MDB2 Error Object on failure
- * @access public
- */
- function connect()
- {
- if (is_resource($this->connection)) {
- //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
- if (MDB2::areEquals($this->connected_dsn, $this->dsn)
- && $this->opened_persistent == $this->options['persistent']
- ) {
- return MDB2_OK;
- }
- $this->disconnect(false);
- }
-
- $connection = $this->_doConnect(
- $this->dsn['username'],
- $this->dsn['password'],
- $this->options['persistent']
- );
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $this->connection = $connection;
- $this->connected_dsn = $this->dsn;
- $this->connected_database_name = '';
- $this->opened_persistent = $this->options['persistent'];
- $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
-
- if ($this->database_name) {
- if ($this->database_name != $this->connected_database_name) {
- if (!@mysql_select_db($this->database_name, $connection)) {
- $err = $this->raiseError(null, null, null,
- 'Could not select the database: '.$this->database_name, __FUNCTION__);
- return $err;
- }
- $this->connected_database_name = $this->database_name;
- }
- }
-
- $this->_getServerCapabilities();
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ setCharset()
-
- /**
- * Set the charset on the current connection
- *
- * @param string charset (or array(charset, collation))
- * @param resource connection handle
- *
- * @return true on success, MDB2 Error Object on failure
- */
- function setCharset($charset, $connection = null)
- {
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
- $collation = null;
- if (is_array($charset) && 2 == count($charset)) {
- $collation = array_pop($charset);
- $charset = array_pop($charset);
- }
- $client_info = mysql_get_client_info();
- if (function_exists('mysql_set_charset') && version_compare($client_info, '5.0.6')) {
- if (!$result = mysql_set_charset($charset, $connection)) {
- $err =& $this->raiseError(null, null, null,
- 'Could not set client character set', __FUNCTION__);
- return $err;
- }
- return $result;
- }
- $query = "SET NAMES '".mysql_real_escape_string($charset, $connection)."'";
- if (!is_null($collation)) {
- $query .= " COLLATE '".mysqli_real_escape_string($connection, $collation)."'";
- }
- return $this->_doQuery($query, true, $connection);
- }
-
- // }}}
- // {{{ databaseExists()
-
- /**
- * check if given database name is exists?
- *
- * @param string $name name of the database that should be checked
- *
- * @return mixed true/false on success, a MDB2 error on failure
- * @access public
- */
- function databaseExists($name)
- {
- $connection = $this->_doConnect($this->dsn['username'],
- $this->dsn['password'],
- $this->options['persistent']);
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $result = @mysql_select_db($name, $connection);
- @mysql_close($connection);
-
- return $result;
- }
-
- // }}}
- // {{{ disconnect()
-
- /**
- * Log out and disconnect from the database.
- *
- * @param boolean $force if the disconnect should be forced even if the
- * connection is opened persistently
- * @return mixed true on success, false if not connected and error
- * object on error
- * @access public
- */
- function disconnect($force = true)
- {
- if (is_resource($this->connection)) {
- if ($this->in_transaction) {
- $dsn = $this->dsn;
- $database_name = $this->database_name;
- $persistent = $this->options['persistent'];
- $this->dsn = $this->connected_dsn;
- $this->database_name = $this->connected_database_name;
- $this->options['persistent'] = $this->opened_persistent;
- $this->rollback();
- $this->dsn = $dsn;
- $this->database_name = $database_name;
- $this->options['persistent'] = $persistent;
- }
-
- if (!$this->opened_persistent || $force) {
- $ok = @mysql_close($this->connection);
- if (!$ok) {
- return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,
- null, null, null, __FUNCTION__);
- }
- }
- } else {
- return false;
- }
- return parent::disconnect($force);
- }
-
- // }}}
- // {{{ standaloneQuery()
-
- /**
- * execute a query as DBA
- *
- * @param string $query the SQL query
- * @param mixed $types array that contains the types of the columns in
- * the result set
- * @param boolean $is_manip if the query is a manipulation query
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function &standaloneQuery($query, $types = null, $is_manip = false)
- {
- $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];
- $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];
- $connection = $this->_doConnect($user, $pass, $this->options['persistent']);
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
-
- $result =& $this->_doQuery($query, $is_manip, $connection, $this->database_name);
- if (!PEAR::isError($result)) {
- $result = $this->_affectedRows($connection, $result);
- }
-
- @mysql_close($connection);
- return $result;
- }
-
- // }}}
- // {{{ _doQuery()
-
- /**
- * Execute a query
- * @param string $query query
- * @param boolean $is_manip if the query is a manipulation query
- * @param resource $connection
- * @param string $database_name
- * @return result or error object
- * @access protected
- */
- function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
- {
- $this->last_query = $query;
- $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- if ($this->options['disable_query']) {
- $result = $is_manip ? 0 : null;
- return $result;
- }
-
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
- if (is_null($database_name)) {
- $database_name = $this->database_name;
- }
-
- if ($database_name) {
- if ($database_name != $this->connected_database_name) {
- if (!@mysql_select_db($database_name, $connection)) {
- $err = $this->raiseError(null, null, null,
- 'Could not select the database: '.$database_name, __FUNCTION__);
- return $err;
- }
- $this->connected_database_name = $database_name;
- }
- }
-
- $function = $this->options['result_buffering']
- ? 'mysql_query' : 'mysql_unbuffered_query';
- $result = @$function($query, $connection);
- if (!$result) {
- $err =& $this->raiseError(null, null, null,
- 'Could not execute statement', __FUNCTION__);
- return $err;
- }
-
- $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
- return $result;
- }
-
- // }}}
- // {{{ _affectedRows()
-
- /**
- * Returns the number of rows affected
- *
- * @param resource $result
- * @param resource $connection
- * @return mixed MDB2 Error Object or the number of rows affected
- * @access private
- */
- function _affectedRows($connection, $result = null)
- {
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
- return @mysql_affected_rows($connection);
- }
-
- // }}}
- // {{{ _modifyQuery()
-
- /**
- * Changes a query string for various DBMS specific reasons
- *
- * @param string $query query to modify
- * @param boolean $is_manip if it is a DML query
- * @param integer $limit limit the number of rows
- * @param integer $offset start reading from given offset
- * @return string modified query
- * @access protected
- */
- function _modifyQuery($query, $is_manip, $limit, $offset)
- {
- if ($this->options['portability'] & MDB2_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);
- }
- }
- if ($limit > 0
- && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
- ) {
- $query = rtrim($query);
- if (substr($query, -1) == ';') {
- $query = substr($query, 0, -1);
- }
-
- // LIMIT doesn't always come last in the query
- // @see http://dev.mysql.com/doc/refman/5.0/en/select.html
- $after = '';
- if (preg_match('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', $query, $matches)) {
- $after = $matches[0];
- $query = preg_replace('/(\s+INTO\s+(?:OUT|DUMP)FILE\s.*)$/ims', '', $query);
- } elseif (preg_match('/(\s+FOR\s+UPDATE\s*)$/i', $query, $matches)) {
- $after = $matches[0];
- $query = preg_replace('/(\s+FOR\s+UPDATE\s*)$/im', '', $query);
- } elseif (preg_match('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', $query, $matches)) {
- $after = $matches[0];
- $query = preg_replace('/(\s+LOCK\s+IN\s+SHARE\s+MODE\s*)$/im', '', $query);
- }
-
- if ($is_manip) {
- return $query . " LIMIT $limit" . $after;
- } else {
- return $query . " LIMIT $offset, $limit" . $after;
- }
- }
- return $query;
- }
-
- // }}}
- // {{{ getServerVersion()
-
- /**
- * return version information about the server
- *
- * @param bool $native determines if the raw version string should be returned
- * @return mixed array/string with version information or MDB2 error object
- * @access public
- */
- function getServerVersion($native = false)
- {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- if ($this->connected_server_info) {
- $server_info = $this->connected_server_info;
- } else {
- $server_info = @mysql_get_server_info($connection);
- }
- if (!$server_info) {
- return $this->raiseError(null, null, null,
- 'Could not get server information', __FUNCTION__);
- }
- // cache server_info
- $this->connected_server_info = $server_info;
- if (!$native) {
- $tmp = explode('.', $server_info, 3);
- if (isset($tmp[2]) && strpos($tmp[2], '-')) {
- $tmp2 = explode('-', @$tmp[2], 2);
- } else {
- $tmp2[0] = isset($tmp[2]) ? $tmp[2] : null;
- $tmp2[1] = null;
- }
- $server_info = array(
- 'major' => isset($tmp[0]) ? $tmp[0] : null,
- 'minor' => isset($tmp[1]) ? $tmp[1] : null,
- 'patch' => $tmp2[0],
- 'extra' => $tmp2[1],
- 'native' => $server_info,
- );
- }
- return $server_info;
- }
-
- // }}}
- // {{{ _getServerCapabilities()
-
- /**
- * Fetch some information about the server capabilities
- * (transactions, subselects, prepared statements, etc).
- *
- * @access private
- */
- function _getServerCapabilities()
- {
- if (!$this->server_capabilities_checked) {
- $this->server_capabilities_checked = true;
-
- //set defaults
- $this->supported['sub_selects'] = 'emulated';
- $this->supported['prepared_statements'] = 'emulated';
- $this->supported['triggers'] = false;
- $this->start_transaction = false;
- $this->varchar_max_length = 255;
-
- $server_info = $this->getServerVersion();
- if (is_array($server_info)) {
- $server_version = $server_info['major'].'.'.$server_info['minor'].'.'.$server_info['patch'];
-
- if (!version_compare($server_version, '4.1.0', '<')) {
- $this->supported['sub_selects'] = true;
- $this->supported['prepared_statements'] = true;
- }
-
- // SAVEPOINTs were introduced in MySQL 4.0.14 and 4.1.1 (InnoDB)
- if (version_compare($server_version, '4.1.0', '>=')) {
- if (version_compare($server_version, '4.1.1', '<')) {
- $this->supported['savepoints'] = false;
- }
- } elseif (version_compare($server_version, '4.0.14', '<')) {
- $this->supported['savepoints'] = false;
- }
-
- if (!version_compare($server_version, '4.0.11', '<')) {
- $this->start_transaction = true;
- }
-
- if (!version_compare($server_version, '5.0.3', '<')) {
- $this->varchar_max_length = 65532;
- }
-
- if (!version_compare($server_version, '5.0.2', '<')) {
- $this->supported['triggers'] = true;
- }
- }
- }
- }
-
- // }}}
- // {{{ function _skipUserDefinedVariable($query, $position)
-
- /**
- * Utility method, used by prepare() to avoid misinterpreting MySQL user
- * defined variables (SELECT @x:=5) for placeholders.
- * Check if the placeholder is a false positive, i.e. if it is an user defined
- * variable instead. If so, skip it and advance the position, otherwise
- * return the current position, which is valid
- *
- * @param string $query
- * @param integer $position current string cursor position
- * @return integer $new_position
- * @access protected
- */
- function _skipUserDefinedVariable($query, $position)
- {
- $found = strpos(strrev(substr($query, 0, $position)), '@');
- if ($found === false) {
- return $position;
- }
- $pos = strlen($query) - strlen(substr($query, $position)) - $found - 1;
- $substring = substr($query, $pos, $position - $pos + 2);
- if (preg_match('/^@\w+\s*:=$/', $substring)) {
- return $position + 1; //found an user defined variable: skip it
- }
- return $position;
- }
-
- // }}}
- // {{{ prepare()
-
- /**
- * Prepares a query for multiple execution with execute().
- * With some database backends, this is emulated.
- * prepare() requires a generic query as string like
- * 'INSERT INTO numbers VALUES(?,?)' or
- * 'INSERT INTO numbers VALUES(:foo,:bar)'.
- * The ? and :name and are placeholders which can be set using
- * bindParam() and the query can be sent off using the execute() method.
- * The allowed format for :name can be set with the 'bindname_format' option.
- *
- * @param string $query the query to prepare
- * @param mixed $types array that contains the types of the placeholders
- * @param mixed $result_types array that contains the types of the columns in
- * the result set or MDB2_PREPARE_RESULT, if set to
- * MDB2_PREPARE_MANIP the query is handled as a manipulation query
- * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
- * @return mixed resource handle for the prepared query on success, a MDB2
- * error on failure
- * @access public
- * @see bindParam, execute
- */
- function &prepare($query, $types = null, $result_types = null, $lobs = array())
- {
- if ($this->options['emulate_prepared']
- || $this->supported['prepared_statements'] !== true
- ) {
- $obj =& parent::prepare($query, $types, $result_types, $lobs);
- return $obj;
- }
- $is_manip = ($result_types === MDB2_PREPARE_MANIP);
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
- $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- $placeholder_type_guess = $placeholder_type = null;
- $question = '?';
- $colon = ':';
- $positions = array();
- $position = 0;
- while ($position < strlen($query)) {
- $q_position = strpos($query, $question, $position);
- $c_position = strpos($query, $colon, $position);
- if ($q_position && $c_position) {
- $p_position = min($q_position, $c_position);
- } elseif ($q_position) {
- $p_position = $q_position;
- } elseif ($c_position) {
- $p_position = $c_position;
- } else {
- break;
- }
- if (is_null($placeholder_type)) {
- $placeholder_type_guess = $query[$p_position];
- }
-
- $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
- if (PEAR::isError($new_pos)) {
- return $new_pos;
- }
- if ($new_pos != $position) {
- $position = $new_pos;
- continue; //evaluate again starting from the new position
- }
-
- //make sure this is not part of an user defined variable
- $new_pos = $this->_skipUserDefinedVariable($query, $position);
- if ($new_pos != $position) {
- $position = $new_pos;
- continue; //evaluate again starting from the new position
- }
-
- if ($query[$position] == $placeholder_type_guess) {
- if (is_null($placeholder_type)) {
- $placeholder_type = $query[$p_position];
- $question = $colon = $placeholder_type;
- }
- if ($placeholder_type == ':') {
- $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
- $parameter = preg_replace($regexp, '\\1', $query);
- if ($parameter === '') {
- $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'named parameter name must match "bindname_format" option', __FUNCTION__);
- return $err;
- }
- $positions[$p_position] = $parameter;
- $query = substr_replace($query, '?', $position, strlen($parameter)+1);
- } else {
- $positions[$p_position] = count($positions);
- }
- $position = $p_position + 1;
- } else {
- $position = $p_position;
- }
- }
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- static $prep_statement_counter = 1;
- $statement_name = sprintf($this->options['statement_format'], $this->phptype, $prep_statement_counter++ . sha1(microtime() + mt_rand()));
- $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']);
- $query = "PREPARE $statement_name FROM ".$this->quote($query, 'text');
- $statement =& $this->_doQuery($query, true, $connection);
- if (PEAR::isError($statement)) {
- return $statement;
- }
-
- $class_name = 'MDB2_Statement_'.$this->phptype;
- $obj = new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
- $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
- return $obj;
- }
-
- // }}}
- // {{{ replace()
-
- /**
- * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
- * query, except that if there is already a row in the table with the same
- * key field values, the old row is deleted before the new row is inserted.
- *
- * The REPLACE type of query does not make part of the SQL standards. Since
- * practically only MySQL implements it natively, this type of query is
- * emulated through this method for other DBMS using standard types of
- * queries inside a transaction to assure the atomicity of the operation.
- *
- * @access public
- *
- * @param string $table name of the table on which the REPLACE query will
- * be executed.
- * @param array $fields associative array that describes the fields and the
- * values that will be inserted or updated in the specified table. The
- * indexes of the array are the names of all the fields of the table. The
- * values of the array are also associative arrays that describe the
- * values and other properties of the table fields.
- *
- * Here follows a list of field properties that need to be specified:
- *
- * value:
- * Value to be assigned to the specified field. This value may be
- * of specified in database independent type format as this
- * function can perform the necessary datatype conversions.
- *
- * Default:
- * this property is required unless the Null property
- * is set to 1.
- *
- * type
- * Name of the type of the field. Currently, all types Metabase
- * are supported except for clob and blob.
- *
- * Default: no type conversion
- *
- * null
- * Boolean property that indicates that the value for this field
- * should be set to null.
- *
- * The default value for fields missing in INSERT queries may be
- * specified the definition of a table. Often, the default value
- * is already null, but since the REPLACE may be emulated using
- * an UPDATE query, make sure that all fields of the table are
- * listed in this function argument array.
- *
- * Default: 0
- *
- * key
- * Boolean property that indicates that this field should be
- * handled as a primary key or at least as part of the compound
- * unique index of the table that will determine the row that will
- * updated if it exists or inserted a new row otherwise.
- *
- * This function will fail if no key field is specified or if the
- * value of a key field is set to null because fields that are
- * part of unique index they may not be null.
- *
- * Default: 0
- *
- * @see http://dev.mysql.com/doc/refman/5.0/en/replace.html
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- */
- function replace($table, $fields)
- {
- $count = count($fields);
- $query = $values = '';
- $keys = $colnum = 0;
- for (reset($fields); $colnum < $count; next($fields), $colnum++) {
- $name = key($fields);
- if ($colnum > 0) {
- $query .= ',';
- $values.= ',';
- }
- $query.= $this->quoteIdentifier($name, true);
- if (isset($fields[$name]['null']) && $fields[$name]['null']) {
- $value = 'NULL';
- } else {
- $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
- $value = $this->quote($fields[$name]['value'], $type);
- if (PEAR::isError($value)) {
- return $value;
- }
- }
- $values.= $value;
- if (isset($fields[$name]['key']) && $fields[$name]['key']) {
- if ($value === 'NULL') {
- return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
- 'key value '.$name.' may not be NULL', __FUNCTION__);
- }
- $keys++;
- }
- }
- if ($keys == 0) {
- return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
- 'not specified which fields are keys', __FUNCTION__);
- }
-
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $table = $this->quoteIdentifier($table, true);
- $query = "REPLACE INTO $table ($query) VALUES ($values)";
- $result =& $this->_doQuery($query, true, $connection);
- if (PEAR::isError($result)) {
- return $result;
- }
- return $this->_affectedRows($connection, $result);
- }
-
- // }}}
- // {{{ nextID()
-
- /**
- * Returns the next free id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true the sequence is
- * automatic created, if it
- * not exists
- *
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function nextID($seq_name, $ondemand = true)
- {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
- $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
- $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $this->expectError(MDB2_ERROR_NOSUCHTABLE);
- $result =& $this->_doQuery($query, true);
- $this->popExpect();
- $this->popErrorHandling();
- if (PEAR::isError($result)) {
- if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
- $this->loadModule('Manager', null, true);
- $result = $this->manager->createSequence($seq_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result, null, null,
- 'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);
- } else {
- return $this->nextID($seq_name, false);
- }
- }
- return $result;
- }
- $value = $this->lastInsertID();
- if (is_numeric($value)) {
- $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
- $result =& $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
- }
- }
- return $value;
- }
-
- // }}}
- // {{{ lastInsertID()
-
- /**
- * Returns the autoincrement ID if supported or $id or fetches the current
- * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
- *
- * @param string $table name of the table into which a new row was inserted
- * @param string $field name of the field into which a new row was inserted
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function lastInsertID($table = null, $field = null)
- {
- // not using mysql_insert_id() due to http://pear.php.net/bugs/bug.php?id=8051
- return $this->queryOne('SELECT LAST_INSERT_ID()', 'integer');
- }
-
- // }}}
- // {{{ currID()
-
- /**
- * Returns the current id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function currID($seq_name)
- {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
- $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
- $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
- return $this->queryOne($query, 'integer');
- }
-}
-
-/**
- * MDB2 MySQL result driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Result_mysql extends MDB2_Result_Common
-{
- // }}}
- // {{{ fetchRow()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * @param int $fetchmode how the array data should be indexed
- * @param int $rownum number of the row where the data can be found
- * @return int data array on success, a MDB2 error on failure
- * @access public
- */
- function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
- {
- if (!is_null($rownum)) {
- $seek = $this->seek($rownum);
- if (PEAR::isError($seek)) {
- return $seek;
- }
- }
- if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
- $fetchmode = $this->db->fetchmode;
- }
- if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
- $row = @mysql_fetch_assoc($this->result);
- if (is_array($row)
- && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
- ) {
- $row = array_change_key_case($row, $this->db->options['field_case']);
- }
- } else {
- $row = @mysql_fetch_row($this->result);
- }
-
- if (!$row) {
- if ($this->result === false) {
- $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- return $err;
- }
- $null = null;
- return $null;
- }
- $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
- $rtrim = false;
- if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
- if (empty($this->types)) {
- $mode += MDB2_PORTABILITY_RTRIM;
- } else {
- $rtrim = true;
- }
- }
- if ($mode) {
- $this->db->_fixResultArrayValues($row, $mode);
- }
- if (!empty($this->types)) {
- $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
- }
- if (!empty($this->values)) {
- $this->_assignBindColumns($row);
- }
- if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
- $object_class = $this->db->options['fetch_class'];
- if ($object_class == 'stdClass') {
- $row = (object) $row;
- } else {
- $row = new $object_class($row);
- }
- }
- ++$this->rownum;
- return $row;
- }
-
- // }}}
- // {{{ _getColumnNames()
-
- /**
- * Retrieve the names of columns returned by the DBMS in a query result.
- *
- * @return mixed Array variable that holds the names of columns as keys
- * or an MDB2 error on failure.
- * Some DBMS may not return any columns when the result set
- * does not contain any rows.
- * @access private
- */
- function _getColumnNames()
- {
- $columns = array();
- $numcols = $this->numCols();
- if (PEAR::isError($numcols)) {
- return $numcols;
- }
- for ($column = 0; $column < $numcols; $column++) {
- $column_name = @mysql_field_name($this->result, $column);
- $columns[$column_name] = $column;
- }
- if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $columns = array_change_key_case($columns, $this->db->options['field_case']);
- }
- return $columns;
- }
-
- // }}}
- // {{{ numCols()
-
- /**
- * Count the number of columns returned by the DBMS in a query result.
- *
- * @return mixed integer value with the number of columns, a MDB2 error
- * on failure
- * @access public
- */
- function numCols()
- {
- $cols = @mysql_num_fields($this->result);
- if (is_null($cols)) {
- if ($this->result === false) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return count($this->types);
- }
- return $this->db->raiseError(null, null, null,
- 'Could not get column count', __FUNCTION__);
- }
- return $cols;
- }
-
- // }}}
- // {{{ free()
-
- /**
- * Free the internal resources associated with result.
- *
- * @return boolean true on success, false if result is invalid
- * @access public
- */
- function free()
- {
- if (is_resource($this->result) && $this->db->connection) {
- $free = @mysql_free_result($this->result);
- if ($free === false) {
- return $this->db->raiseError(null, null, null,
- 'Could not free result', __FUNCTION__);
- }
- }
- $this->result = false;
- return MDB2_OK;
- }
-}
-
-/**
- * MDB2 MySQL buffered result driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_BufferedResult_mysql extends MDB2_Result_mysql
-{
- // }}}
- // {{{ seek()
-
- /**
- * Seek to a specific row in a result set
- *
- * @param int $rownum number of the row where the data can be found
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function seek($rownum = 0)
- {
- if ($this->rownum != ($rownum - 1) && !@mysql_data_seek($this->result, $rownum)) {
- if ($this->result === false) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return MDB2_OK;
- }
- return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
- 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
- }
- $this->rownum = $rownum - 1;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ valid()
-
- /**
- * Check if the end of the result set has been reached
- *
- * @return mixed true or false on sucess, a MDB2 error on failure
- * @access public
- */
- function valid()
- {
- $numrows = $this->numRows();
- if (PEAR::isError($numrows)) {
- return $numrows;
- }
- return $this->rownum < ($numrows - 1);
- }
-
- // }}}
- // {{{ numRows()
-
- /**
- * Returns the number of rows in a result object
- *
- * @return mixed MDB2 Error Object or the number of rows
- * @access public
- */
- function numRows()
- {
- $rows = @mysql_num_rows($this->result);
- if (false === $rows) {
- if (false === $this->result) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return 0;
- }
- return $this->db->raiseError(null, null, null,
- 'Could not get row count', __FUNCTION__);
- }
- return $rows;
- }
-}
-
-/**
- * MDB2 MySQL statement driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Statement_mysql extends MDB2_Statement_Common
-{
- // {{{ _execute()
-
- /**
- * Execute a prepared query statement helper method.
- *
- * @param mixed $result_class string which specifies which result class to use
- * @param mixed $result_wrap_class string which specifies which class to wrap results in
- *
- * @return mixed MDB2_Result or integer (affected rows) on success,
- * a MDB2 error on failure
- * @access private
- */
- function &_execute($result_class = true, $result_wrap_class = false)
- {
- if (is_null($this->statement)) {
- $result =& parent::_execute($result_class, $result_wrap_class);
- return $result;
- }
- $this->db->last_query = $this->query;
- $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
- if ($this->db->getOption('disable_query')) {
- $result = $this->is_manip ? 0 : null;
- return $result;
- }
-
- $connection = $this->db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $query = 'EXECUTE '.$this->statement;
- if (!empty($this->positions)) {
- $parameters = array();
- foreach ($this->positions as $parameter) {
- if (!array_key_exists($parameter, $this->values)) {
- return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
- }
- $value = $this->values[$parameter];
- $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
- if (is_resource($value) || $type == 'clob' || $type == 'blob' && $this->db->options['lob_allow_url_include']) {
- if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
- if ($match[1] == 'file://') {
- $value = $match[2];
- }
- $value = @fopen($value, 'r');
- $close = true;
- }
- if (is_resource($value)) {
- $data = '';
- while (!@feof($value)) {
- $data.= @fread($value, $this->db->options['lob_buffer_length']);
- }
- if ($close) {
- @fclose($value);
- }
- $value = $data;
- }
- }
- $quoted = $this->db->quote($value, $type);
- if (PEAR::isError($quoted)) {
- return $quoted;
- }
- $param_query = 'SET @'.$parameter.' = '.$quoted;
- $result = $this->db->_doQuery($param_query, true, $connection);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- $query.= ' USING @'.implode(', @', array_values($this->positions));
- }
-
- $result = $this->db->_doQuery($query, $this->is_manip, $connection);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if ($this->is_manip) {
- $affected_rows = $this->db->_affectedRows($connection, $result);
- return $affected_rows;
- }
-
- $result =& $this->db->_wrapResult($result, $this->result_types,
- $result_class, $result_wrap_class, $this->limit, $this->offset);
- $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
- return $result;
- }
-
- // }}}
- // {{{ free()
-
- /**
- * Release resources allocated for the specified prepared query.
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function free()
- {
- if (is_null($this->positions)) {
- return $this->db->raiseError(MDB2_ERROR, null, null,
- 'Prepared statement has already been freed', __FUNCTION__);
- }
- $result = MDB2_OK;
-
- if (!is_null($this->statement)) {
- $connection = $this->db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- $query = 'DEALLOCATE PREPARE '.$this->statement;
- $result = $this->db->_doQuery($query, true, $connection);
- }
-
- parent::free();
- return $result;
- }
-}
-?> \ No newline at end of file
diff --git a/inc/MDB2/Driver/pgsql.php b/inc/MDB2/Driver/pgsql.php
deleted file mode 100644
index 00a64865a72..00000000000
--- a/inc/MDB2/Driver/pgsql.php
+++ /dev/null
@@ -1,1519 +0,0 @@
-<?php
-// vim: set et ts=4 sw=4 fdm=marker:
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Paul Cooper <pgc@ucecom.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: pgsql.php,v 1.203 2008/11/29 14:04:46 afz Exp $
-
-/**
- * MDB2 PostGreSQL driver
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper <pgc@ucecom.com>
- */
-class MDB2_Driver_pgsql extends MDB2_Driver_Common
-{
- // {{{ properties
- var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => '\\');
-
- var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
- // }}}
- // {{{ constructor
-
- /**
- * Constructor
- */
- function __construct()
- {
- parent::__construct();
-
- $this->phptype = 'pgsql';
- $this->dbsyntax = 'pgsql';
-
- $this->supported['sequences'] = true;
- $this->supported['indexes'] = true;
- $this->supported['affected_rows'] = true;
- $this->supported['summary_functions'] = true;
- $this->supported['order_by_text'] = true;
- $this->supported['transactions'] = true;
- $this->supported['savepoints'] = true;
- $this->supported['current_id'] = true;
- $this->supported['limit_queries'] = true;
- $this->supported['LOBs'] = true;
- $this->supported['replace'] = 'emulated';
- $this->supported['sub_selects'] = true;
- $this->supported['triggers'] = true;
- $this->supported['auto_increment'] = 'emulated';
- $this->supported['primary_key'] = true;
- $this->supported['result_introspection'] = true;
- $this->supported['prepared_statements'] = true;
- $this->supported['identifier_quoting'] = true;
- $this->supported['pattern_escaping'] = true;
- $this->supported['new_link'] = true;
-
- $this->options['DBA_username'] = false;
- $this->options['DBA_password'] = false;
- $this->options['multi_query'] = false;
- $this->options['disable_smart_seqname'] = true;
- $this->options['max_identifiers_length'] = 63;
- }
-
- // }}}
- // {{{ errorInfo()
-
- /**
- * This method is used to collect information about an error
- *
- * @param integer $error
- * @return array
- * @access public
- */
- function errorInfo($error = null)
- {
- // Fall back to MDB2_ERROR if there was no mapping.
- $error_code = MDB2_ERROR;
-
- $native_msg = '';
- if (is_resource($error)) {
- $native_msg = @pg_result_error($error);
- } elseif ($this->connection) {
- $native_msg = @pg_last_error($this->connection);
- if (!$native_msg && @pg_connection_status($this->connection) === PGSQL_CONNECTION_BAD) {
- $native_msg = 'Database connection has been lost.';
- $error_code = MDB2_ERROR_CONNECT_FAILED;
- }
- } else {
- $native_msg = @pg_last_error();
- }
-
- static $error_regexps;
- if (empty($error_regexps)) {
- $error_regexps = array(
- '/column .* (of relation .*)?does not exist/i'
- => MDB2_ERROR_NOSUCHFIELD,
- '/(relation|sequence|table).*does not exist|class .* not found/i'
- => MDB2_ERROR_NOSUCHTABLE,
- '/database .* does not exist/'
- => MDB2_ERROR_NOT_FOUND,
- '/constraint .* does not exist/'
- => MDB2_ERROR_NOT_FOUND,
- '/index .* does not exist/'
- => MDB2_ERROR_NOT_FOUND,
- '/database .* already exists/i'
- => MDB2_ERROR_ALREADY_EXISTS,
- '/relation .* already exists/i'
- => MDB2_ERROR_ALREADY_EXISTS,
- '/(divide|division) by zero$/i'
- => MDB2_ERROR_DIVZERO,
- '/pg_atoi: error in .*: can\'t parse /i'
- => MDB2_ERROR_INVALID_NUMBER,
- '/invalid input syntax for( type)? (integer|numeric)/i'
- => MDB2_ERROR_INVALID_NUMBER,
- '/value .* is out of range for type \w*int/i'
- => MDB2_ERROR_INVALID_NUMBER,
- '/integer out of range/i'
- => MDB2_ERROR_INVALID_NUMBER,
- '/value too long for type character/i'
- => MDB2_ERROR_INVALID,
- '/attribute .* not found|relation .* does not have attribute/i'
- => MDB2_ERROR_NOSUCHFIELD,
- '/column .* specified in USING clause does not exist in (left|right) table/i'
- => MDB2_ERROR_NOSUCHFIELD,
- '/parser: parse error at or near/i'
- => MDB2_ERROR_SYNTAX,
- '/syntax error at/'
- => MDB2_ERROR_SYNTAX,
- '/column reference .* is ambiguous/i'
- => MDB2_ERROR_SYNTAX,
- '/permission denied/'
- => MDB2_ERROR_ACCESS_VIOLATION,
- '/violates not-null constraint/'
- => MDB2_ERROR_CONSTRAINT_NOT_NULL,
- '/violates [\w ]+ constraint/'
- => MDB2_ERROR_CONSTRAINT,
- '/referential integrity violation/'
- => MDB2_ERROR_CONSTRAINT,
- '/more expressions than target columns/i'
- => MDB2_ERROR_VALUE_COUNT_ON_ROW,
- );
- }
- if (is_numeric($error) && $error < 0) {
- $error_code = $error;
- } else {
- foreach ($error_regexps as $regexp => $code) {
- if (preg_match($regexp, $native_msg)) {
- $error_code = $code;
- break;
- }
- }
- }
- return array($error_code, null, $native_msg);
- }
-
- // }}}
- // {{{ escape()
-
- /**
- * Quotes a string so it can be safely used in a query. It will quote
- * the text so it can safely be used within a query.
- *
- * @param string the input string to quote
- * @param bool escape wildcards
- *
- * @return string quoted string
- *
- * @access public
- */
- function escape($text, $escape_wildcards = false)
- {
- if ($escape_wildcards) {
- $text = $this->escapePattern($text);
- }
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- if (is_resource($connection) && version_compare(PHP_VERSION, '5.2.0RC5', '>=')) {
- $text = @pg_escape_string($connection, $text);
- } else {
- $text = @pg_escape_string($text);
- }
- return $text;
- }
-
- // }}}
- // {{{ beginTransaction()
-
- /**
- * Start a transaction or set a savepoint.
- *
- * @param string name of a savepoint to set
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function beginTransaction($savepoint = null)
- {
- $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!is_null($savepoint)) {
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'savepoint cannot be released when changes are auto committed', __FUNCTION__);
- }
- $query = 'SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- } elseif ($this->in_transaction) {
- return MDB2_OK; //nothing to do
- }
- if (!$this->destructor_registered && $this->opened_persistent) {
- $this->destructor_registered = true;
- register_shutdown_function('MDB2_closeOpenTransactions');
- }
- $result =& $this->_doQuery('BEGIN', true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = true;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ commit()
-
- /**
- * Commit the database changes done during a transaction that is in
- * progress or release a savepoint. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after committing the pending changes.
- *
- * @param string name of a savepoint to release
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function commit($savepoint = null)
- {
- $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
- }
- if (!is_null($savepoint)) {
- $query = 'RELEASE SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- }
-
- $result =& $this->_doQuery('COMMIT', true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ rollback()
-
- /**
- * Cancel any database changes done during a transaction or since a specific
- * savepoint that is in progress. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after canceling the pending changes.
- *
- * @param string name of a savepoint to rollback to
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function rollback($savepoint = null)
- {
- $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'rollback cannot be done changes are auto committed', __FUNCTION__);
- }
- if (!is_null($savepoint)) {
- $query = 'ROLLBACK TO SAVEPOINT '.$savepoint;
- return $this->_doQuery($query, true);
- }
-
- $query = 'ROLLBACK';
- $result =& $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function setTransactionIsolation()
-
- /**
- * Set the transacton isolation level.
- *
- * @param string standard isolation level
- * READ UNCOMMITTED (allows dirty reads)
- * READ COMMITTED (prevents dirty reads)
- * REPEATABLE READ (prevents nonrepeatable reads)
- * SERIALIZABLE (prevents phantom reads)
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- * @since 2.1.1
- */
- function setTransactionIsolation($isolation)
- {
- $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
- switch ($isolation) {
- case 'READ UNCOMMITTED':
- case 'READ COMMITTED':
- case 'REPEATABLE READ':
- case 'SERIALIZABLE':
- break;
- default:
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'isolation level is not supported: '.$isolation, __FUNCTION__);
- }
-
- $query = "SET SESSION CHARACTERISTICS AS TRANSACTION ISOLATION LEVEL $isolation";
- return $this->_doQuery($query, true);
- }
-
- // }}}
- // {{{ _doConnect()
-
- /**
- * Do the grunt work of connecting to the database
- *
- * @return mixed connection resource on success, MDB2 Error Object on failure
- * @access protected
- */
- function _doConnect($username, $password, $database_name, $persistent = false)
- {
- if (!PEAR::loadExtension($this->phptype)) {
- return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
- }
-
- if ($database_name == '') {
- $database_name = 'template1';
- }
-
- $protocol = $this->dsn['protocol'] ? $this->dsn['protocol'] : 'tcp';
-
- $params = array('');
- if ($protocol == 'tcp') {
- if ($this->dsn['hostspec']) {
- $params[0].= 'host=' . $this->dsn['hostspec'];
- }
- if ($this->dsn['port']) {
- $params[0].= ' port=' . $this->dsn['port'];
- }
- } elseif ($protocol == 'unix') {
- // Allow for pg socket in non-standard locations.
- if ($this->dsn['socket']) {
- $params[0].= 'host=' . $this->dsn['socket'];
- }
- if ($this->dsn['port']) {
- $params[0].= ' port=' . $this->dsn['port'];
- }
- }
- if ($database_name) {
- $params[0].= ' dbname=\'' . addslashes($database_name) . '\'';
- }
- if ($username) {
- $params[0].= ' user=\'' . addslashes($username) . '\'';
- }
- if ($password) {
- $params[0].= ' password=\'' . addslashes($password) . '\'';
- }
- if (!empty($this->dsn['options'])) {
- $params[0].= ' options=' . $this->dsn['options'];
- }
- if (!empty($this->dsn['tty'])) {
- $params[0].= ' tty=' . $this->dsn['tty'];
- }
- if (!empty($this->dsn['connect_timeout'])) {
- $params[0].= ' connect_timeout=' . $this->dsn['connect_timeout'];
- }
- if (!empty($this->dsn['sslmode'])) {
- $params[0].= ' sslmode=' . $this->dsn['sslmode'];
- }
- if (!empty($this->dsn['service'])) {
- $params[0].= ' service=' . $this->dsn['service'];
- }
-
- if ($this->_isNewLinkSet()) {
- if (version_compare(phpversion(), '4.3.0', '>=')) {
- $params[] = PGSQL_CONNECT_FORCE_NEW;
- }
- }
-
- $connect_function = $persistent ? 'pg_pconnect' : 'pg_connect';
- $connection = @call_user_func_array($connect_function, $params);
- if (!$connection) {
- return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
- 'unable to establish a connection', __FUNCTION__);
- }
-
- if (empty($this->dsn['disable_iso_date'])) {
- if (!@pg_query($connection, "SET SESSION DATESTYLE = 'ISO'")) {
- return $this->raiseError(null, null, null,
- 'Unable to set date style to iso', __FUNCTION__);
- }
- }
-
- if (!empty($this->dsn['charset'])) {
- $result = $this->setCharset($this->dsn['charset'], $connection);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- return $connection;
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to the database
- *
- * @return true on success, MDB2 Error Object on failure
- * @access public
- */
- function connect()
- {
- if (is_resource($this->connection)) {
- //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
- if (MDB2::areEquals($this->connected_dsn, $this->dsn)
- && $this->connected_database_name == $this->database_name
- && ($this->opened_persistent == $this->options['persistent'])
- ) {
- return MDB2_OK;
- }
- $this->disconnect(false);
- }
-
- if ($this->database_name) {
- $connection = $this->_doConnect($this->dsn['username'],
- $this->dsn['password'],
- $this->database_name,
- $this->options['persistent']);
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $this->connection = $connection;
- $this->connected_dsn = $this->dsn;
- $this->connected_database_name = $this->database_name;
- $this->opened_persistent = $this->options['persistent'];
- $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ setCharset()
-
- /**
- * Set the charset on the current connection
- *
- * @param string charset
- * @param resource connection handle
- *
- * @return true on success, MDB2 Error Object on failure
- */
- function setCharset($charset, $connection = null)
- {
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
- if (is_array($charset)) {
- $charset = array_shift($charset);
- $this->warnings[] = 'postgresql does not support setting client collation';
- }
- $result = @pg_set_client_encoding($connection, $charset);
- if ($result == -1) {
- return $this->raiseError(null, null, null,
- 'Unable to set client charset: '.$charset, __FUNCTION__);
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ databaseExists()
-
- /**
- * check if given database name is exists?
- *
- * @param string $name name of the database that should be checked
- *
- * @return mixed true/false on success, a MDB2 error on failure
- * @access public
- */
- function databaseExists($name)
- {
- $res = $this->_doConnect($this->dsn['username'],
- $this->dsn['password'],
- $this->escape($name),
- $this->options['persistent']);
- if (!PEAR::isError($res)) {
- return true;
- }
-
- return false;
- }
-
- // }}}
- // {{{ disconnect()
-
- /**
- * Log out and disconnect from the database.
- *
- * @param boolean $force if the disconnect should be forced even if the
- * connection is opened persistently
- * @return mixed true on success, false if not connected and error
- * object on error
- * @access public
- */
- function disconnect($force = true)
- {
- if (is_resource($this->connection)) {
- if ($this->in_transaction) {
- $dsn = $this->dsn;
- $database_name = $this->database_name;
- $persistent = $this->options['persistent'];
- $this->dsn = $this->connected_dsn;
- $this->database_name = $this->connected_database_name;
- $this->options['persistent'] = $this->opened_persistent;
- $this->rollback();
- $this->dsn = $dsn;
- $this->database_name = $database_name;
- $this->options['persistent'] = $persistent;
- }
-
- if (!$this->opened_persistent || $force) {
- $ok = @pg_close($this->connection);
- if (!$ok) {
- return $this->raiseError(MDB2_ERROR_DISCONNECT_FAILED,
- null, null, null, __FUNCTION__);
- }
- }
- } else {
- return false;
- }
- return parent::disconnect($force);
- }
-
- // }}}
- // {{{ standaloneQuery()
-
- /**
- * execute a query as DBA
- *
- * @param string $query the SQL query
- * @param mixed $types array that contains the types of the columns in
- * the result set
- * @param boolean $is_manip if the query is a manipulation query
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function &standaloneQuery($query, $types = null, $is_manip = false)
- {
- $user = $this->options['DBA_username']? $this->options['DBA_username'] : $this->dsn['username'];
- $pass = $this->options['DBA_password']? $this->options['DBA_password'] : $this->dsn['password'];
- $connection = $this->_doConnect($user, $pass, $this->database_name, $this->options['persistent']);
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
-
- $result =& $this->_doQuery($query, $is_manip, $connection, $this->database_name);
- if (!PEAR::isError($result)) {
- if ($is_manip) {
- $result = $this->_affectedRows($connection, $result);
- } else {
- $result =& $this->_wrapResult($result, $types, true, false, $limit, $offset);
- }
- }
-
- @pg_close($connection);
- return $result;
- }
-
- // }}}
- // {{{ _doQuery()
-
- /**
- * Execute a query
- * @param string $query query
- * @param boolean $is_manip if the query is a manipulation query
- * @param resource $connection
- * @param string $database_name
- * @return result or error object
- * @access protected
- */
- function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
- {
- $this->last_query = $query;
- $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- if ($this->options['disable_query']) {
- $result = $is_manip ? 0 : null;
- return $result;
- }
-
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
-
- $function = $this->options['multi_query'] ? 'pg_send_query' : 'pg_query';
- $result = @$function($connection, $query);
- if (!$result) {
- $err =& $this->raiseError(null, null, null,
- 'Could not execute statement', __FUNCTION__);
- return $err;
- } elseif ($this->options['multi_query']) {
- if (!($result = @pg_get_result($connection))) {
- $err =& $this->raiseError(null, null, null,
- 'Could not get the first result from a multi query', __FUNCTION__);
- return $err;
- }
- }
-
- $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
- return $result;
- }
-
- // }}}
- // {{{ _affectedRows()
-
- /**
- * Returns the number of rows affected
- *
- * @param resource $result
- * @param resource $connection
- * @return mixed MDB2 Error Object or the number of rows affected
- * @access private
- */
- function _affectedRows($connection, $result = null)
- {
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
- return @pg_affected_rows($result);
- }
-
- // }}}
- // {{{ _modifyQuery()
-
- /**
- * Changes a query string for various DBMS specific reasons
- *
- * @param string $query query to modify
- * @param boolean $is_manip if it is a DML query
- * @param integer $limit limit the number of rows
- * @param integer $offset start reading from given offset
- * @return string modified query
- * @access protected
- */
- function _modifyQuery($query, $is_manip, $limit, $offset)
- {
- if ($limit > 0
- && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
- ) {
- $query = rtrim($query);
- if (substr($query, -1) == ';') {
- $query = substr($query, 0, -1);
- }
- if ($is_manip) {
- $query = $this->_modifyManipQuery($query, $limit);
- } else {
- $query.= " LIMIT $limit OFFSET $offset";
- }
- }
- return $query;
- }
-
- // }}}
- // {{{ _modifyManipQuery()
-
- /**
- * Changes a manip query string for various DBMS specific reasons
- *
- * @param string $query query to modify
- * @param integer $limit limit the number of rows
- * @return string modified query
- * @access protected
- */
- function _modifyManipQuery($query, $limit)
- {
- $pos = strpos(strtolower($query), 'where');
- $where = $pos ? substr($query, $pos) : '';
-
- $manip_clause = '(\bDELETE\b\s+(?:\*\s+)?\bFROM\b|\bUPDATE\b)';
- $from_clause = '([\w\.]+)';
- $where_clause = '(?:(.*)\bWHERE\b\s+(.*))|(.*)';
- $pattern = '/^'. $manip_clause . '\s+' . $from_clause .'(?:\s)*(?:'. $where_clause .')?$/i';
- $matches = preg_match($pattern, $query, $match);
- if ($matches) {
- $manip = $match[1];
- $from = $match[2];
- $what = (count($matches) == 6) ? $match[5] : $match[3];
- return $manip.' '.$from.' '.$what.' WHERE ctid=(SELECT ctid FROM '.$from.' '.$where.' LIMIT '.$limit.')';
- }
- //return error?
- return $query;
- }
-
- // }}}
- // {{{ getServerVersion()
-
- /**
- * return version information about the server
- *
- * @param bool $native determines if the raw version string should be returned
- * @return mixed array/string with version information or MDB2 error object
- * @access public
- */
- function getServerVersion($native = false)
- {
- $query = 'SHOW SERVER_VERSION';
- if ($this->connected_server_info) {
- $server_info = $this->connected_server_info;
- } else {
- $server_info = $this->queryOne($query, 'text');
- if (PEAR::isError($server_info)) {
- return $server_info;
- }
- }
- // cache server_info
- $this->connected_server_info = $server_info;
- if (!$native && !PEAR::isError($server_info)) {
- $tmp = explode('.', $server_info, 3);
- if (empty($tmp[2])
- && isset($tmp[1])
- && preg_match('/(\d+)(.*)/', $tmp[1], $tmp2)
- ) {
- $server_info = array(
- 'major' => $tmp[0],
- 'minor' => $tmp2[1],
- 'patch' => null,
- 'extra' => $tmp2[2],
- 'native' => $server_info,
- );
- } else {
- $server_info = array(
- 'major' => isset($tmp[0]) ? $tmp[0] : null,
- 'minor' => isset($tmp[1]) ? $tmp[1] : null,
- 'patch' => isset($tmp[2]) ? $tmp[2] : null,
- 'extra' => null,
- 'native' => $server_info,
- );
- }
- }
- return $server_info;
- }
-
- // }}}
- // {{{ prepare()
-
- /**
- * Prepares a query for multiple execution with execute().
- * With some database backends, this is emulated.
- * prepare() requires a generic query as string like
- * 'INSERT INTO numbers VALUES(?,?)' or
- * 'INSERT INTO numbers VALUES(:foo,:bar)'.
- * The ? and :name and are placeholders which can be set using
- * bindParam() and the query can be sent off using the execute() method.
- * The allowed format for :name can be set with the 'bindname_format' option.
- *
- * @param string $query the query to prepare
- * @param mixed $types array that contains the types of the placeholders
- * @param mixed $result_types array that contains the types of the columns in
- * the result set or MDB2_PREPARE_RESULT, if set to
- * MDB2_PREPARE_MANIP the query is handled as a manipulation query
- * @param mixed $lobs key (field) value (parameter) pair for all lob placeholders
- * @return mixed resource handle for the prepared query on success, a MDB2
- * error on failure
- * @access public
- * @see bindParam, execute
- */
- function &prepare($query, $types = null, $result_types = null, $lobs = array())
- {
- if ($this->options['emulate_prepared']) {
- $obj =& parent::prepare($query, $types, $result_types, $lobs);
- return $obj;
- }
- $is_manip = ($result_types === MDB2_PREPARE_MANIP);
- $offset = $this->offset;
- $limit = $this->limit;
- $this->offset = $this->limit = 0;
- $result = $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- $pgtypes = function_exists('pg_prepare') ? false : array();
- if ($pgtypes !== false && !empty($types)) {
- $this->loadModule('Datatype', null, true);
- }
- $query = $this->_modifyQuery($query, $is_manip, $limit, $offset);
- $placeholder_type_guess = $placeholder_type = null;
- $question = '?';
- $colon = ':';
- $positions = array();
- $position = $parameter = 0;
- while ($position < strlen($query)) {
- $q_position = strpos($query, $question, $position);
- $c_position = strpos($query, $colon, $position);
- //skip "::type" cast ("select id::varchar(20) from sometable where name=?")
- $doublecolon_position = strpos($query, '::', $position);
- if ($doublecolon_position !== false && $doublecolon_position == $c_position) {
- $c_position = strpos($query, $colon, $position+2);
- }
- if ($q_position && $c_position) {
- $p_position = min($q_position, $c_position);
- } elseif ($q_position) {
- $p_position = $q_position;
- } elseif ($c_position) {
- $p_position = $c_position;
- } else {
- break;
- }
- if (is_null($placeholder_type)) {
- $placeholder_type_guess = $query[$p_position];
- }
-
- $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position);
- if (PEAR::isError($new_pos)) {
- return $new_pos;
- }
- if ($new_pos != $position) {
- $position = $new_pos;
- continue; //evaluate again starting from the new position
- }
-
- if ($query[$position] == $placeholder_type_guess) {
- if (is_null($placeholder_type)) {
- $placeholder_type = $query[$p_position];
- $question = $colon = $placeholder_type;
- if (!empty($types) && is_array($types)) {
- if ($placeholder_type == ':') {
- } else {
- $types = array_values($types);
- }
- }
- }
- if ($placeholder_type_guess == '?') {
- $length = 1;
- $name = $parameter;
- } else {
- $regexp = '/^.{'.($position+1).'}('.$this->options['bindname_format'].').*$/s';
- $param = preg_replace($regexp, '\\1', $query);
- if ($param === '') {
- $err =& $this->raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'named parameter name must match "bindname_format" option', __FUNCTION__);
- return $err;
- }
- $length = strlen($param) + 1;
- $name = $param;
- }
- if ($pgtypes !== false) {
- if (is_array($types) && array_key_exists($name, $types)) {
- $pgtypes[] = $this->datatype->mapPrepareDatatype($types[$name]);
- } elseif (is_array($types) && array_key_exists($parameter, $types)) {
- $pgtypes[] = $this->datatype->mapPrepareDatatype($types[$parameter]);
- } else {
- $pgtypes[] = 'text';
- }
- }
- if (($key_parameter = array_search($name, $positions))) {
- $next_parameter = 1;
- foreach ($positions as $key => $value) {
- if ($key_parameter == $key) {
- break;
- }
- ++$next_parameter;
- }
- } else {
- ++$parameter;
- $next_parameter = $parameter;
- $positions[] = $name;
- }
- $query = substr_replace($query, '$'.$parameter, $position, $length);
- $position = $p_position + strlen($parameter);
- } else {
- $position = $p_position;
- }
- }
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- static $prep_statement_counter = 1;
- $statement_name = sprintf($this->options['statement_format'], $this->phptype, $prep_statement_counter++ . sha1(microtime() + mt_rand()));
- $statement_name = substr(strtolower($statement_name), 0, $this->options['max_identifiers_length']);
- if ($pgtypes === false) {
- $result = @pg_prepare($connection, $statement_name, $query);
- if (!$result) {
- $err =& $this->raiseError(null, null, null,
- 'Unable to create prepared statement handle', __FUNCTION__);
- return $err;
- }
- } else {
- $types_string = '';
- if ($pgtypes) {
- $types_string = ' ('.implode(', ', $pgtypes).') ';
- }
- $query = 'PREPARE '.$statement_name.$types_string.' AS '.$query;
- $statement =& $this->_doQuery($query, true, $connection);
- if (PEAR::isError($statement)) {
- return $statement;
- }
- }
-
- $class_name = 'MDB2_Statement_'.$this->phptype;
- $obj = new $class_name($this, $statement_name, $positions, $query, $types, $result_types, $is_manip, $limit, $offset);
- $this->debug($query, __FUNCTION__, array('is_manip' => $is_manip, 'when' => 'post', 'result' => $obj));
- return $obj;
- }
-
- // }}}
- // {{{ function getSequenceName($sqn)
-
- /**
- * adds sequence name formatting to a sequence name
- *
- * @param string name of the sequence
- *
- * @return string formatted sequence name
- *
- * @access public
- */
- function getSequenceName($sqn)
- {
- if (false === $this->options['disable_smart_seqname']) {
- if (strpos($sqn, '_') !== false) {
- list($table, $field) = explode('_', $sqn, 2);
- }
- $schema_list = $this->queryOne("SELECT array_to_string(current_schemas(false), ',')");
- if (PEAR::isError($schema_list) || empty($schema_list) || count($schema_list) < 2) {
- $order_by = ' a.attnum';
- $schema_clause = ' AND n.nspname=current_schema()';
- } else {
- $schemas = explode(',', $schema_list);
- $schema_clause = ' AND n.nspname IN ('.$schema_list.')';
- $counter = 1;
- $order_by = ' CASE ';
- foreach ($schemas as $schema) {
- $order_by .= ' WHEN n.nspname='.$schema.' THEN '.$counter++;
- }
- $order_by .= ' ELSE '.$counter.' END, a.attnum';
- }
-
- $query = "SELECT substring((SELECT substring(pg_get_expr(d.adbin, d.adrelid) for 128)
- FROM pg_attrdef d
- WHERE d.adrelid = a.attrelid
- AND d.adnum = a.attnum
- AND a.atthasdef
- ) FROM 'nextval[^'']*''([^'']*)')
- FROM pg_attribute a
- LEFT JOIN pg_class c ON c.oid = a.attrelid
- LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum AND a.atthasdef
- LEFT JOIN pg_namespace n ON c.relnamespace = n.oid
- WHERE (c.relname = ".$this->quote($sqn, 'text');
- if (!empty($field)) {
- $query .= " OR (c.relname = ".$this->quote($table, 'text')." AND a.attname = ".$this->quote($field, 'text').")";
- }
- $query .= " )"
- .$schema_clause."
- AND NOT a.attisdropped
- AND a.attnum > 0
- AND pg_get_expr(d.adbin, d.adrelid) LIKE 'nextval%'
- ORDER BY ".$order_by;
- $seqname = $this->queryOne($query);
- if (!PEAR::isError($seqname) && !empty($seqname) && is_string($seqname)) {
- return $seqname;
- }
- }
-
- return parent::getSequenceName($sqn);
- }
-
- // }}}
- // {{{ nextID()
-
- /**
- * Returns the next free id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true the sequence is
- * automatic created, if it
- * not exists
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function nextID($seq_name, $ondemand = true)
- {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
- $query = "SELECT NEXTVAL('$sequence_name')";
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $this->expectError(MDB2_ERROR_NOSUCHTABLE);
- $result = $this->queryOne($query, 'integer');
- $this->popExpect();
- $this->popErrorHandling();
- if (PEAR::isError($result)) {
- if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
- $this->loadModule('Manager', null, true);
- $result = $this->manager->createSequence($seq_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result, null, null,
- 'on demand sequence could not be created', __FUNCTION__);
- }
- return $this->nextId($seq_name, false);
- }
- }
- return $result;
- }
-
- // }}}
- // {{{ lastInsertID()
-
- /**
- * Returns the autoincrement ID if supported or $id or fetches the current
- * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
- *
- * @param string $table name of the table into which a new row was inserted
- * @param string $field name of the field into which a new row was inserted
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function lastInsertID($table = null, $field = null)
- {
- if (empty($table) && empty($field)) {
- return $this->queryOne('SELECT lastval()', 'integer');
- }
- $seq = $table.(empty($field) ? '' : '_'.$field);
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq), true);
- return $this->queryOne("SELECT currval('$sequence_name')", 'integer');
- }
-
- // }}}
- // {{{ currID()
-
- /**
- * Returns the current id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function currID($seq_name)
- {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
- return $this->queryOne("SELECT last_value FROM $sequence_name", 'integer');
- }
-}
-
-/**
- * MDB2 PostGreSQL result driver
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper <pgc@ucecom.com>
- */
-class MDB2_Result_pgsql extends MDB2_Result_Common
-{
- // }}}
- // {{{ fetchRow()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * @param int $fetchmode how the array data should be indexed
- * @param int $rownum number of the row where the data can be found
- * @return int data array on success, a MDB2 error on failure
- * @access public
- */
- function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
- {
- if (!is_null($rownum)) {
- $seek = $this->seek($rownum);
- if (PEAR::isError($seek)) {
- return $seek;
- }
- }
- if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
- $fetchmode = $this->db->fetchmode;
- }
- if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
- $row = @pg_fetch_array($this->result, null, PGSQL_ASSOC);
- if (is_array($row)
- && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
- ) {
- $row = array_change_key_case($row, $this->db->options['field_case']);
- }
- } else {
- $row = @pg_fetch_row($this->result);
- }
- if (!$row) {
- if ($this->result === false) {
- $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- return $err;
- }
- $null = null;
- return $null;
- }
- $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
- $rtrim = false;
- if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
- if (empty($this->types)) {
- $mode += MDB2_PORTABILITY_RTRIM;
- } else {
- $rtrim = true;
- }
- }
- if ($mode) {
- $this->db->_fixResultArrayValues($row, $mode);
- }
- if (!empty($this->types)) {
- $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
- }
- if (!empty($this->values)) {
- $this->_assignBindColumns($row);
- }
- if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
- $object_class = $this->db->options['fetch_class'];
- if ($object_class == 'stdClass') {
- $row = (object) $row;
- } else {
- $row = &new $object_class($row);
- }
- }
- ++$this->rownum;
- return $row;
- }
-
- // }}}
- // {{{ _getColumnNames()
-
- /**
- * Retrieve the names of columns returned by the DBMS in a query result.
- *
- * @return mixed Array variable that holds the names of columns as keys
- * or an MDB2 error on failure.
- * Some DBMS may not return any columns when the result set
- * does not contain any rows.
- * @access private
- */
- function _getColumnNames()
- {
- $columns = array();
- $numcols = $this->numCols();
- if (PEAR::isError($numcols)) {
- return $numcols;
- }
- for ($column = 0; $column < $numcols; $column++) {
- $column_name = @pg_field_name($this->result, $column);
- $columns[$column_name] = $column;
- }
- if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $columns = array_change_key_case($columns, $this->db->options['field_case']);
- }
- return $columns;
- }
-
- // }}}
- // {{{ numCols()
-
- /**
- * Count the number of columns returned by the DBMS in a query result.
- *
- * @access public
- * @return mixed integer value with the number of columns, a MDB2 error
- * on failure
- */
- function numCols()
- {
- $cols = @pg_num_fields($this->result);
- if (is_null($cols)) {
- if ($this->result === false) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return count($this->types);
- }
- return $this->db->raiseError(null, null, null,
- 'Could not get column count', __FUNCTION__);
- }
- return $cols;
- }
-
- // }}}
- // {{{ nextResult()
-
- /**
- * Move the internal result pointer to the next available result
- *
- * @return true on success, false if there is no more result set or an error object on failure
- * @access public
- */
- function nextResult()
- {
- $connection = $this->db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- if (!($this->result = @pg_get_result($connection))) {
- return false;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ free()
-
- /**
- * Free the internal resources associated with result.
- *
- * @return boolean true on success, false if result is invalid
- * @access public
- */
- function free()
- {
- if (is_resource($this->result) && $this->db->connection) {
- $free = @pg_free_result($this->result);
- if ($free === false) {
- return $this->db->raiseError(null, null, null,
- 'Could not free result', __FUNCTION__);
- }
- }
- $this->result = false;
- return MDB2_OK;
- }
-}
-
-/**
- * MDB2 PostGreSQL buffered result driver
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper <pgc@ucecom.com>
- */
-class MDB2_BufferedResult_pgsql extends MDB2_Result_pgsql
-{
- // {{{ seek()
-
- /**
- * Seek to a specific row in a result set
- *
- * @param int $rownum number of the row where the data can be found
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function seek($rownum = 0)
- {
- if ($this->rownum != ($rownum - 1) && !@pg_result_seek($this->result, $rownum)) {
- if ($this->result === false) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return MDB2_OK;
- }
- return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
- 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
- }
- $this->rownum = $rownum - 1;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ valid()
-
- /**
- * Check if the end of the result set has been reached
- *
- * @return mixed true or false on sucess, a MDB2 error on failure
- * @access public
- */
- function valid()
- {
- $numrows = $this->numRows();
- if (PEAR::isError($numrows)) {
- return $numrows;
- }
- return $this->rownum < ($numrows - 1);
- }
-
- // }}}
- // {{{ numRows()
-
- /**
- * Returns the number of rows in a result object
- *
- * @return mixed MDB2 Error Object or the number of rows
- * @access public
- */
- function numRows()
- {
- $rows = @pg_num_rows($this->result);
- if (is_null($rows)) {
- if ($this->result === false) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return 0;
- }
- return $this->db->raiseError(null, null, null,
- 'Could not get row count', __FUNCTION__);
- }
- return $rows;
- }
-}
-
-/**
- * MDB2 PostGreSQL statement driver
- *
- * @package MDB2
- * @category Database
- * @author Paul Cooper <pgc@ucecom.com>
- */
-class MDB2_Statement_pgsql extends MDB2_Statement_Common
-{
- // {{{ _execute()
-
- /**
- * Execute a prepared query statement helper method.
- *
- * @param mixed $result_class string which specifies which result class to use
- * @param mixed $result_wrap_class string which specifies which class to wrap results in
- *
- * @return mixed MDB2_Result or integer (affected rows) on success,
- * a MDB2 error on failure
- * @access private
- */
- function &_execute($result_class = true, $result_wrap_class = false)
- {
- if (is_null($this->statement)) {
- $result =& parent::_execute($result_class, $result_wrap_class);
- return $result;
- }
- $this->db->last_query = $this->query;
- $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'pre', 'parameters' => $this->values));
- if ($this->db->getOption('disable_query')) {
- $result = $this->is_manip ? 0 : null;
- return $result;
- }
-
- $connection = $this->db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $query = false;
- $parameters = array();
- // todo: disabled until pg_execute() bytea issues are cleared up
- if (true || !function_exists('pg_execute')) {
- $query = 'EXECUTE '.$this->statement;
- }
- if (!empty($this->positions)) {
- foreach ($this->positions as $parameter) {
- if (!array_key_exists($parameter, $this->values)) {
- return $this->db->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__);
- }
- $value = $this->values[$parameter];
- $type = array_key_exists($parameter, $this->types) ? $this->types[$parameter] : null;
- if (is_resource($value) || $type == 'clob' || $type == 'blob' || $this->db->options['lob_allow_url_include']) {
- if (!is_resource($value) && preg_match('/^(\w+:\/\/)(.*)$/', $value, $match)) {
- if ($match[1] == 'file://') {
- $value = $match[2];
- }
- $value = @fopen($value, 'r');
- $close = true;
- }
- if (is_resource($value)) {
- $data = '';
- while (!@feof($value)) {
- $data.= @fread($value, $this->db->options['lob_buffer_length']);
- }
- if ($close) {
- @fclose($value);
- }
- $value = $data;
- }
- }
- $quoted = $this->db->quote($value, $type, $query);
- if (PEAR::isError($quoted)) {
- return $quoted;
- }
- $parameters[] = $quoted;
- }
- if ($query) {
- $query.= ' ('.implode(', ', $parameters).')';
- }
- }
-
- if (!$query) {
- $result = @pg_execute($connection, $this->statement, $parameters);
- if (!$result) {
- $err =& $this->db->raiseError(null, null, null,
- 'Unable to execute statement', __FUNCTION__);
- return $err;
- }
- } else {
- $result = $this->db->_doQuery($query, $this->is_manip, $connection);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- if ($this->is_manip) {
- $affected_rows = $this->db->_affectedRows($connection, $result);
- return $affected_rows;
- }
-
- $result =& $this->db->_wrapResult($result, $this->result_types,
- $result_class, $result_wrap_class, $this->limit, $this->offset);
- $this->db->debug($this->query, 'execute', array('is_manip' => $this->is_manip, 'when' => 'post', 'result' => $result));
- return $result;
- }
-
- // }}}
- // {{{ free()
-
- /**
- * Release resources allocated for the specified prepared query.
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function free()
- {
- if (is_null($this->positions)) {
- return $this->db->raiseError(MDB2_ERROR, null, null,
- 'Prepared statement has already been freed', __FUNCTION__);
- }
- $result = MDB2_OK;
-
- if (!is_null($this->statement)) {
- $connection = $this->db->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- $query = 'DEALLOCATE PREPARE '.$this->statement;
- $result = $this->db->_doQuery($query, true, $connection);
- }
-
- parent::free();
- return $result;
- }
-}
-?> \ No newline at end of file
diff --git a/inc/MDB2/Driver/sqlite.php b/inc/MDB2/Driver/sqlite.php
deleted file mode 100644
index abde86d596b..00000000000
--- a/inc/MDB2/Driver/sqlite.php
+++ /dev/null
@@ -1,1082 +0,0 @@
-<?php
-// vim: set et ts=4 sw=4 fdm=marker:
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: sqlite.php,v 1.165 2008/11/30 14:28:01 afz Exp $
-//
-
-/**
- * MDB2 SQLite driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Driver_sqlite extends MDB2_Driver_Common
-{
- // {{{ properties
- var $string_quoting = array('start' => "'", 'end' => "'", 'escape' => "'", 'escape_pattern' => false);
-
- var $identifier_quoting = array('start' => '"', 'end' => '"', 'escape' => '"');
-
- var $_lasterror = '';
-
- var $fix_assoc_fields_names = false;
-
- // }}}
- // {{{ constructor
-
- /**
- * Constructor
- */
- function __construct()
- {
- parent::__construct();
-
- $this->phptype = 'sqlite';
- $this->dbsyntax = 'sqlite';
-
- $this->supported['sequences'] = 'emulated';
- $this->supported['indexes'] = true;
- $this->supported['affected_rows'] = true;
- $this->supported['summary_functions'] = true;
- $this->supported['order_by_text'] = true;
- $this->supported['current_id'] = 'emulated';
- $this->supported['limit_queries'] = true;
- $this->supported['LOBs'] = true;
- $this->supported['replace'] = true;
- $this->supported['transactions'] = true;
- $this->supported['savepoints'] = false;
- $this->supported['sub_selects'] = true;
- $this->supported['triggers'] = true;
- $this->supported['auto_increment'] = true;
- $this->supported['primary_key'] = false; // requires alter table implementation
- $this->supported['result_introspection'] = false; // not implemented
- $this->supported['prepared_statements'] = 'emulated';
- $this->supported['identifier_quoting'] = true;
- $this->supported['pattern_escaping'] = false;
- $this->supported['new_link'] = false;
-
- $this->options['DBA_username'] = false;
- $this->options['DBA_password'] = false;
- $this->options['base_transaction_name'] = '___php_MDB2_sqlite_auto_commit_off';
- $this->options['fixed_float'] = 0;
- $this->options['database_path'] = '';
- $this->options['database_extension'] = '';
- $this->options['server_version'] = '';
- $this->options['max_identifiers_length'] = 128; //no real limit
- }
-
- // }}}
- // {{{ errorInfo()
-
- /**
- * This method is used to collect information about an error
- *
- * @param integer $error
- * @return array
- * @access public
- */
- function errorInfo($error = null)
- {
- $native_code = null;
- if ($this->connection) {
- $native_code = @sqlite_last_error($this->connection);
- }
- $native_msg = $this->_lasterror
- ? html_entity_decode($this->_lasterror) : @sqlite_error_string($native_code);
-
- // PHP 5.2+ prepends the function name to $php_errormsg, so we need
- // this hack to work around it, per bug #9599.
- $native_msg = preg_replace('/^sqlite[a-z_]+\(\)[^:]*: /', '', $native_msg);
-
- if (is_null($error)) {
- static $error_regexps;
- if (empty($error_regexps)) {
- $error_regexps = array(
- '/^no such table:/' => MDB2_ERROR_NOSUCHTABLE,
- '/^no such index:/' => MDB2_ERROR_NOT_FOUND,
- '/^(table|index) .* already exists$/' => MDB2_ERROR_ALREADY_EXISTS,
- '/PRIMARY KEY must be unique/i' => MDB2_ERROR_CONSTRAINT,
- '/is not unique/' => MDB2_ERROR_CONSTRAINT,
- '/columns .* are not unique/i' => MDB2_ERROR_CONSTRAINT,
- '/uniqueness constraint failed/' => MDB2_ERROR_CONSTRAINT,
- '/may not be NULL/' => MDB2_ERROR_CONSTRAINT_NOT_NULL,
- '/^no such column:/' => MDB2_ERROR_NOSUCHFIELD,
- '/no column named/' => MDB2_ERROR_NOSUCHFIELD,
- '/column not present in both tables/i' => MDB2_ERROR_NOSUCHFIELD,
- '/^near ".*": syntax error$/' => MDB2_ERROR_SYNTAX,
- '/[0-9]+ values for [0-9]+ columns/i' => MDB2_ERROR_VALUE_COUNT_ON_ROW,
- );
- }
- foreach ($error_regexps as $regexp => $code) {
- if (preg_match($regexp, $native_msg)) {
- $error = $code;
- break;
- }
- }
- }
- return array($error, $native_code, $native_msg);
- }
-
- // }}}
- // {{{ escape()
-
- /**
- * Quotes a string so it can be safely used in a query. It will quote
- * the text so it can safely be used within a query.
- *
- * @param string the input string to quote
- * @param bool escape wildcards
- *
- * @return string quoted string
- *
- * @access public
- */
- function escape($text, $escape_wildcards = false)
- {
- $text = @sqlite_escape_string($text);
- return $text;
- }
-
- // }}}
- // {{{ beginTransaction()
-
- /**
- * Start a transaction or set a savepoint.
- *
- * @param string name of a savepoint to set
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function beginTransaction($savepoint = null)
- {
- $this->debug('Starting transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!is_null($savepoint)) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'savepoints are not supported', __FUNCTION__);
- } elseif ($this->in_transaction) {
- return MDB2_OK; //nothing to do
- }
- if (!$this->destructor_registered && $this->opened_persistent) {
- $this->destructor_registered = true;
- register_shutdown_function('MDB2_closeOpenTransactions');
- }
- $query = 'BEGIN TRANSACTION '.$this->options['base_transaction_name'];
- $result =& $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = true;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ commit()
-
- /**
- * Commit the database changes done during a transaction that is in
- * progress or release a savepoint. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after committing the pending changes.
- *
- * @param string name of a savepoint to release
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function commit($savepoint = null)
- {
- $this->debug('Committing transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'commit/release savepoint cannot be done changes are auto committed', __FUNCTION__);
- }
- if (!is_null($savepoint)) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'savepoints are not supported', __FUNCTION__);
- }
-
- $query = 'COMMIT TRANSACTION '.$this->options['base_transaction_name'];
- $result =& $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{
-
- /**
- * Cancel any database changes done during a transaction or since a specific
- * savepoint that is in progress. This function may only be called when
- * auto-committing is disabled, otherwise it will fail. Therefore, a new
- * transaction is implicitly started after canceling the pending changes.
- *
- * @param string name of a savepoint to rollback to
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- */
- function rollback($savepoint = null)
- {
- $this->debug('Rolling back transaction/savepoint', __FUNCTION__, array('is_manip' => true, 'savepoint' => $savepoint));
- if (!$this->in_transaction) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'rollback cannot be done changes are auto committed', __FUNCTION__);
- }
- if (!is_null($savepoint)) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'savepoints are not supported', __FUNCTION__);
- }
-
- $query = 'ROLLBACK TRANSACTION '.$this->options['base_transaction_name'];
- $result =& $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->in_transaction = false;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ function setTransactionIsolation()
-
- /**
- * Set the transacton isolation level.
- *
- * @param string standard isolation level
- * READ UNCOMMITTED (allows dirty reads)
- * READ COMMITTED (prevents dirty reads)
- * REPEATABLE READ (prevents nonrepeatable reads)
- * SERIALIZABLE (prevents phantom reads)
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- *
- * @access public
- * @since 2.1.1
- */
- function setTransactionIsolation($isolation)
- {
- $this->debug('Setting transaction isolation level', __FUNCTION__, array('is_manip' => true));
- switch ($isolation) {
- case 'READ UNCOMMITTED':
- $isolation = 0;
- break;
- case 'READ COMMITTED':
- case 'REPEATABLE READ':
- case 'SERIALIZABLE':
- $isolation = 1;
- break;
- default:
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'isolation level is not supported: '.$isolation, __FUNCTION__);
- }
-
- $query = "PRAGMA read_uncommitted=$isolation";
- return $this->_doQuery($query, true);
- }
-
- // }}}
- // {{{ getDatabaseFile()
-
- /**
- * Builds the string with path+dbname+extension
- *
- * @return string full database path+file
- * @access protected
- */
- function _getDatabaseFile($database_name)
- {
- if ($database_name === '' || $database_name === ':memory:') {
- return $database_name;
- }
- return $this->options['database_path'].$database_name.$this->options['database_extension'];
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Connect to the database
- *
- * @return true on success, MDB2 Error Object on failure
- **/
- function connect()
- {
- $database_file = $this->_getDatabaseFile($this->database_name);
- if (is_resource($this->connection)) {
- //if (count(array_diff($this->connected_dsn, $this->dsn)) == 0
- if (MDB2::areEquals($this->connected_dsn, $this->dsn)
- && $this->connected_database_name == $database_file
- && $this->opened_persistent == $this->options['persistent']
- ) {
- return MDB2_OK;
- }
- $this->disconnect(false);
- }
-
- if (!PEAR::loadExtension($this->phptype)) {
- return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'extension '.$this->phptype.' is not compiled into PHP', __FUNCTION__);
- }
-
- if (empty($this->database_name)) {
- return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
- 'unable to establish a connection', __FUNCTION__);
- }
-
- if ($database_file !== ':memory:') {
- if (!file_exists($database_file)) {
- if (!touch($database_file)) {
- return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Could not create database file', __FUNCTION__);
- }
- if (!isset($this->dsn['mode'])
- || !is_numeric($this->dsn['mode'])
- ) {
- $mode = 0644;
- } else {
- $mode = octdec($this->dsn['mode']);
- }
- if (!chmod($database_file, $mode)) {
- return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Could not be chmodded database file', __FUNCTION__);
- }
- if (!file_exists($database_file)) {
- return $this->raiseError(MDB2_ERROR_NOT_FOUND, null, null,
- 'Could not be found database file', __FUNCTION__);
- }
- }
- if (!is_file($database_file)) {
- return $this->raiseError(MDB2_ERROR_INVALID, null, null,
- 'Database is a directory name', __FUNCTION__);
- }
- if (!is_readable($database_file)) {
- return $this->raiseError(MDB2_ERROR_ACCESS_VIOLATION, null, null,
- 'Could not read database file', __FUNCTION__);
- }
- }
-
- $connect_function = ($this->options['persistent'] ? 'sqlite_popen' : 'sqlite_open');
- $php_errormsg = '';
- if (version_compare('5.1.0', PHP_VERSION, '>')) {
- @ini_set('track_errors', true);
- $connection = @$connect_function($database_file);
- @ini_restore('track_errors');
- } else {
- $connection = @$connect_function($database_file, 0666, $php_errormsg);
- }
- $this->_lasterror = $php_errormsg;
- if (!$connection) {
- return $this->raiseError(MDB2_ERROR_CONNECT_FAILED, null, null,
- 'unable to establish a connection', __FUNCTION__);
- }
-
- if ($this->fix_assoc_fields_names ||
- $this->options['portability'] & MDB2_PORTABILITY_FIX_ASSOC_FIELD_NAMES)
- {
- @sqlite_query("PRAGMA short_column_names = 1", $connection);
- $this->fix_assoc_fields_names = true;
- }
-
- $this->connection = $connection;
- $this->connected_dsn = $this->dsn;
- $this->connected_database_name = $database_file;
- $this->opened_persistent = $this->getoption('persistent');
- $this->dbsyntax = $this->dsn['dbsyntax'] ? $this->dsn['dbsyntax'] : $this->phptype;
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ databaseExists()
-
- /**
- * check if given database name is exists?
- *
- * @param string $name name of the database that should be checked
- *
- * @return mixed true/false on success, a MDB2 error on failure
- * @access public
- */
- function databaseExists($name)
- {
- $database_file = $this->_getDatabaseFile($name);
- $result = file_exists($database_file);
- return $result;
- }
-
- // }}}
- // {{{ disconnect()
-
- /**
- * Log out and disconnect from the database.
- *
- * @param boolean $force if the disconnect should be forced even if the
- * connection is opened persistently
- * @return mixed true on success, false if not connected and error
- * object on error
- * @access public
- */
- function disconnect($force = true)
- {
- if (is_resource($this->connection)) {
- if ($this->in_transaction) {
- $dsn = $this->dsn;
- $database_name = $this->database_name;
- $persistent = $this->options['persistent'];
- $this->dsn = $this->connected_dsn;
- $this->database_name = $this->connected_database_name;
- $this->options['persistent'] = $this->opened_persistent;
- $this->rollback();
- $this->dsn = $dsn;
- $this->database_name = $database_name;
- $this->options['persistent'] = $persistent;
- }
-
- if (!$this->opened_persistent || $force) {
- @sqlite_close($this->connection);
- }
- } else {
- return false;
- }
- return parent::disconnect($force);
- }
-
- // }}}
- // {{{ _doQuery()
-
- /**
- * Execute a query
- * @param string $query query
- * @param boolean $is_manip if the query is a manipulation query
- * @param resource $connection
- * @param string $database_name
- * @return result or error object
- * @access protected
- */
- function &_doQuery($query, $is_manip = false, $connection = null, $database_name = null)
- {
- $this->last_query = $query;
- $result = $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'pre'));
- if ($result) {
- if (PEAR::isError($result)) {
- return $result;
- }
- $query = $result;
- }
- if ($this->options['disable_query']) {
- $result = $is_manip ? 0 : null;
- return $result;
- }
-
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
-
- $function = $this->options['result_buffering']
- ? 'sqlite_query' : 'sqlite_unbuffered_query';
- $php_errormsg = '';
- if (version_compare('5.1.0', PHP_VERSION, '>')) {
- @ini_set('track_errors', true);
- do {
- $result = @$function($query.';', $connection);
- } while (sqlite_last_error($connection) == SQLITE_SCHEMA);
- @ini_restore('track_errors');
- } else {
- do {
- $result = @$function($query.';', $connection, SQLITE_BOTH, $php_errormsg);
- } while (sqlite_last_error($connection) == SQLITE_SCHEMA);
- }
- $this->_lasterror = $php_errormsg;
-
- if (!$result) {
- $err =& $this->raiseError(null, null, null,
- 'Could not execute statement', __FUNCTION__);
- return $err;
- }
-
- $this->debug($query, 'query', array('is_manip' => $is_manip, 'when' => 'post', 'result' => $result));
- return $result;
- }
-
- // }}}
- // {{{ _affectedRows()
-
- /**
- * Returns the number of rows affected
- *
- * @param resource $result
- * @param resource $connection
- * @return mixed MDB2 Error Object or the number of rows affected
- * @access private
- */
- function _affectedRows($connection, $result = null)
- {
- if (is_null($connection)) {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- }
- return @sqlite_changes($connection);
- }
-
- // }}}
- // {{{ _modifyQuery()
-
- /**
- * Changes a query string for various DBMS specific reasons
- *
- * @param string $query query to modify
- * @param boolean $is_manip if it is a DML query
- * @param integer $limit limit the number of rows
- * @param integer $offset start reading from given offset
- * @return string modified query
- * @access protected
- */
- function _modifyQuery($query, $is_manip, $limit, $offset)
- {
- if ($this->options['portability'] & MDB2_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);
- }
- }
- if ($limit > 0
- && !preg_match('/LIMIT\s*\d(?:\s*(?:,|OFFSET)\s*\d+)?(?:[^\)]*)?$/i', $query)
- ) {
- $query = rtrim($query);
- if (substr($query, -1) == ';') {
- $query = substr($query, 0, -1);
- }
- if ($is_manip) {
- $query.= " LIMIT $limit";
- } else {
- $query.= " LIMIT $offset,$limit";
- }
- }
- return $query;
- }
-
- // }}}
- // {{{ getServerVersion()
-
- /**
- * return version information about the server
- *
- * @param bool $native determines if the raw version string should be returned
- * @return mixed array/string with version information or MDB2 error object
- * @access public
- */
- function getServerVersion($native = false)
- {
- $server_info = false;
- if ($this->connected_server_info) {
- $server_info = $this->connected_server_info;
- } elseif ($this->options['server_version']) {
- $server_info = $this->options['server_version'];
- } elseif (function_exists('sqlite_libversion')) {
- $server_info = @sqlite_libversion();
- }
- if (!$server_info) {
- return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null,
- 'Requires either the "server_version" option or the sqlite_libversion() function', __FUNCTION__);
- }
- // cache server_info
- $this->connected_server_info = $server_info;
- if (!$native) {
- $tmp = explode('.', $server_info, 3);
- $server_info = array(
- 'major' => isset($tmp[0]) ? $tmp[0] : null,
- 'minor' => isset($tmp[1]) ? $tmp[1] : null,
- 'patch' => isset($tmp[2]) ? $tmp[2] : null,
- 'extra' => null,
- 'native' => $server_info,
- );
- }
- return $server_info;
- }
-
- // }}}
- // {{{ replace()
-
- /**
- * Execute a SQL REPLACE query. A REPLACE query is identical to a INSERT
- * query, except that if there is already a row in the table with the same
- * key field values, the old row is deleted before the new row is inserted.
- *
- * The REPLACE type of query does not make part of the SQL standards. Since
- * practically only SQLite implements it natively, this type of query is
- * emulated through this method for other DBMS using standard types of
- * queries inside a transaction to assure the atomicity of the operation.
- *
- * @access public
- *
- * @param string $table name of the table on which the REPLACE query will
- * be executed.
- * @param array $fields associative array that describes the fields and the
- * values that will be inserted or updated in the specified table. The
- * indexes of the array are the names of all the fields of the table. The
- * values of the array are also associative arrays that describe the
- * values and other properties of the table fields.
- *
- * Here follows a list of field properties that need to be specified:
- *
- * value:
- * Value to be assigned to the specified field. This value may be
- * of specified in database independent type format as this
- * function can perform the necessary datatype conversions.
- *
- * Default:
- * this property is required unless the Null property
- * is set to 1.
- *
- * type
- * Name of the type of the field. Currently, all types Metabase
- * are supported except for clob and blob.
- *
- * Default: no type conversion
- *
- * null
- * Boolean property that indicates that the value for this field
- * should be set to null.
- *
- * The default value for fields missing in INSERT queries may be
- * specified the definition of a table. Often, the default value
- * is already null, but since the REPLACE may be emulated using
- * an UPDATE query, make sure that all fields of the table are
- * listed in this function argument array.
- *
- * Default: 0
- *
- * key
- * Boolean property that indicates that this field should be
- * handled as a primary key or at least as part of the compound
- * unique index of the table that will determine the row that will
- * updated if it exists or inserted a new row otherwise.
- *
- * This function will fail if no key field is specified or if the
- * value of a key field is set to null because fields that are
- * part of unique index they may not be null.
- *
- * Default: 0
- *
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- */
- function replace($table, $fields)
- {
- $count = count($fields);
- $query = $values = '';
- $keys = $colnum = 0;
- for (reset($fields); $colnum < $count; next($fields), $colnum++) {
- $name = key($fields);
- if ($colnum > 0) {
- $query .= ',';
- $values.= ',';
- }
- $query.= $this->quoteIdentifier($name, true);
- if (isset($fields[$name]['null']) && $fields[$name]['null']) {
- $value = 'NULL';
- } else {
- $type = isset($fields[$name]['type']) ? $fields[$name]['type'] : null;
- $value = $this->quote($fields[$name]['value'], $type);
- if (PEAR::isError($value)) {
- return $value;
- }
- }
- $values.= $value;
- if (isset($fields[$name]['key']) && $fields[$name]['key']) {
- if ($value === 'NULL') {
- return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
- 'key value '.$name.' may not be NULL', __FUNCTION__);
- }
- $keys++;
- }
- }
- if ($keys == 0) {
- return $this->raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null,
- 'not specified which fields are keys', __FUNCTION__);
- }
-
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
-
- $table = $this->quoteIdentifier($table, true);
- $query = "REPLACE INTO $table ($query) VALUES ($values)";
- $result =& $this->_doQuery($query, true, $connection);
- if (PEAR::isError($result)) {
- return $result;
- }
- return $this->_affectedRows($connection, $result);
- }
-
- // }}}
- // {{{ nextID()
-
- /**
- * Returns the next free id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @param boolean $ondemand when true the sequence is
- * automatic created, if it
- * not exists
- *
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function nextID($seq_name, $ondemand = true)
- {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
- $seqcol_name = $this->options['seqcol_name'];
- $query = "INSERT INTO $sequence_name ($seqcol_name) VALUES (NULL)";
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $this->expectError(MDB2_ERROR_NOSUCHTABLE);
- $result =& $this->_doQuery($query, true);
- $this->popExpect();
- $this->popErrorHandling();
- if (PEAR::isError($result)) {
- if ($ondemand && $result->getCode() == MDB2_ERROR_NOSUCHTABLE) {
- $this->loadModule('Manager', null, true);
- $result = $this->manager->createSequence($seq_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result, null, null,
- 'on demand sequence '.$seq_name.' could not be created', __FUNCTION__);
- } else {
- return $this->nextID($seq_name, false);
- }
- }
- return $result;
- }
- $value = $this->lastInsertID();
- if (is_numeric($value)) {
- $query = "DELETE FROM $sequence_name WHERE $seqcol_name < $value";
- $result =& $this->_doQuery($query, true);
- if (PEAR::isError($result)) {
- $this->warnings[] = 'nextID: could not delete previous sequence table values from '.$seq_name;
- }
- }
- return $value;
- }
-
- // }}}
- // {{{ lastInsertID()
-
- /**
- * Returns the autoincrement ID if supported or $id or fetches the current
- * ID in a sequence called: $table.(empty($field) ? '' : '_'.$field)
- *
- * @param string $table name of the table into which a new row was inserted
- * @param string $field name of the field into which a new row was inserted
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function lastInsertID($table = null, $field = null)
- {
- $connection = $this->getConnection();
- if (PEAR::isError($connection)) {
- return $connection;
- }
- $value = @sqlite_last_insert_rowid($connection);
- if (!$value) {
- return $this->raiseError(null, null, null,
- 'Could not get last insert ID', __FUNCTION__);
- }
- return $value;
- }
-
- // }}}
- // {{{ currID()
-
- /**
- * Returns the current id of a sequence
- *
- * @param string $seq_name name of the sequence
- * @return mixed MDB2 Error Object or id
- * @access public
- */
- function currID($seq_name)
- {
- $sequence_name = $this->quoteIdentifier($this->getSequenceName($seq_name), true);
- $seqcol_name = $this->quoteIdentifier($this->options['seqcol_name'], true);
- $query = "SELECT MAX($seqcol_name) FROM $sequence_name";
- return $this->queryOne($query, 'integer');
- }
-}
-
-/**
- * MDB2 SQLite result driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Result_sqlite extends MDB2_Result_Common
-{
- // }}}
- // {{{ fetchRow()
-
- /**
- * Fetch a row and insert the data into an existing array.
- *
- * @param int $fetchmode how the array data should be indexed
- * @param int $rownum number of the row where the data can be found
- * @return int data array on success, a MDB2 error on failure
- * @access public
- */
- function &fetchRow($fetchmode = MDB2_FETCHMODE_DEFAULT, $rownum = null)
- {
- if (!is_null($rownum)) {
- $seek = $this->seek($rownum);
- if (PEAR::isError($seek)) {
- return $seek;
- }
- }
- if ($fetchmode == MDB2_FETCHMODE_DEFAULT) {
- $fetchmode = $this->db->fetchmode;
- }
- if ($fetchmode & MDB2_FETCHMODE_ASSOC) {
- $row = @sqlite_fetch_array($this->result, SQLITE_ASSOC);
- if (is_array($row)
- && $this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE
- ) {
- $row = array_change_key_case($row, $this->db->options['field_case']);
- }
- } else {
- $row = @sqlite_fetch_array($this->result, SQLITE_NUM);
- }
- if (!$row) {
- if ($this->result === false) {
- $err =& $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- return $err;
- }
- $null = null;
- return $null;
- }
- $mode = $this->db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL;
- $rtrim = false;
- if ($this->db->options['portability'] & MDB2_PORTABILITY_RTRIM) {
- if (empty($this->types)) {
- $mode += MDB2_PORTABILITY_RTRIM;
- } else {
- $rtrim = true;
- }
- }
- if ($mode) {
- $this->db->_fixResultArrayValues($row, $mode);
- }
- if (!empty($this->types)) {
- $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim);
- }
- if (!empty($this->values)) {
- $this->_assignBindColumns($row);
- }
- if ($fetchmode === MDB2_FETCHMODE_OBJECT) {
- $object_class = $this->db->options['fetch_class'];
- if ($object_class == 'stdClass') {
- $row = (object) $row;
- } else {
- $row = new $object_class($row);
- }
- }
- ++$this->rownum;
- return $row;
- }
-
- // }}}
- // {{{ _getColumnNames()
-
- /**
- * Retrieve the names of columns returned by the DBMS in a query result.
- *
- * @return mixed Array variable that holds the names of columns as keys
- * or an MDB2 error on failure.
- * Some DBMS may not return any columns when the result set
- * does not contain any rows.
- * @access private
- */
- function _getColumnNames()
- {
- $columns = array();
- $numcols = $this->numCols();
- if (PEAR::isError($numcols)) {
- return $numcols;
- }
- for ($column = 0; $column < $numcols; $column++) {
- $column_name = @sqlite_field_name($this->result, $column);
- $columns[$column_name] = $column;
- }
- if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $columns = array_change_key_case($columns, $this->db->options['field_case']);
- }
- return $columns;
- }
-
- // }}}
- // {{{ numCols()
-
- /**
- * Count the number of columns returned by the DBMS in a query result.
- *
- * @access public
- * @return mixed integer value with the number of columns, a MDB2 error
- * on failure
- */
- function numCols()
- {
- $cols = @sqlite_num_fields($this->result);
- if (is_null($cols)) {
- if ($this->result === false) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return count($this->types);
- }
- return $this->db->raiseError(null, null, null,
- 'Could not get column count', __FUNCTION__);
- }
- return $cols;
- }
-}
-
-/**
- * MDB2 SQLite buffered result driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_BufferedResult_sqlite extends MDB2_Result_sqlite
-{
- // {{{ seek()
-
- /**
- * Seek to a specific row in a result set
- *
- * @param int $rownum number of the row where the data can be found
- * @return mixed MDB2_OK on success, a MDB2 error on failure
- * @access public
- */
- function seek($rownum = 0)
- {
- if (!@sqlite_seek($this->result, $rownum)) {
- if ($this->result === false) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return MDB2_OK;
- }
- return $this->db->raiseError(MDB2_ERROR_INVALID, null, null,
- 'tried to seek to an invalid row number ('.$rownum.')', __FUNCTION__);
- }
- $this->rownum = $rownum - 1;
- return MDB2_OK;
- }
-
- // }}}
- // {{{ valid()
-
- /**
- * Check if the end of the result set has been reached
- *
- * @return mixed true or false on sucess, a MDB2 error on failure
- * @access public
- */
- function valid()
- {
- $numrows = $this->numRows();
- if (PEAR::isError($numrows)) {
- return $numrows;
- }
- return $this->rownum < ($numrows - 1);
- }
-
- // }}}
- // {{{ numRows()
-
- /**
- * Returns the number of rows in a result object
- *
- * @return mixed MDB2 Error Object or the number of rows
- * @access public
- */
- function numRows()
- {
- $rows = @sqlite_num_rows($this->result);
- if (is_null($rows)) {
- if ($this->result === false) {
- return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'resultset has already been freed', __FUNCTION__);
- } elseif (is_null($this->result)) {
- return 0;
- }
- return $this->db->raiseError(null, null, null,
- 'Could not get row count', __FUNCTION__);
- }
- return $rows;
- }
-}
-
-/**
- * MDB2 SQLite statement driver
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Statement_sqlite extends MDB2_Statement_Common
-{
-
-}
-
-?> \ No newline at end of file
diff --git a/inc/MDB2/Extended.php b/inc/MDB2/Extended.php
deleted file mode 100644
index 864ab923543..00000000000
--- a/inc/MDB2/Extended.php
+++ /dev/null
@@ -1,721 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Extended.php,v 1.60 2007/11/28 19:49:34 quipo Exp $
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-
-/**
- * Used by autoPrepare()
- */
-define('MDB2_AUTOQUERY_INSERT', 1);
-define('MDB2_AUTOQUERY_UPDATE', 2);
-define('MDB2_AUTOQUERY_DELETE', 3);
-define('MDB2_AUTOQUERY_SELECT', 4);
-
-/**
- * MDB2_Extended: class which adds several high level methods to MDB2
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Extended extends MDB2_Module_Common
-{
- // {{{ autoPrepare()
-
- /**
- * Generate an insert, update or delete query and call prepare() on it
- *
- * @param string table
- * @param array the fields names
- * @param int type of query to build
- * MDB2_AUTOQUERY_INSERT
- * MDB2_AUTOQUERY_UPDATE
- * MDB2_AUTOQUERY_DELETE
- * MDB2_AUTOQUERY_SELECT
- * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)
- * @param array that contains the types of the placeholders
- * @param mixed array that contains the types of the columns in
- * the result set or MDB2_PREPARE_RESULT, if set to
- * MDB2_PREPARE_MANIP the query is handled as a manipulation query
- *
- * @return resource handle for the query
- * @see buildManipSQL
- * @access public
- */
- function autoPrepare($table, $table_fields, $mode = MDB2_AUTOQUERY_INSERT,
- $where = false, $types = null, $result_types = MDB2_PREPARE_MANIP)
- {
- $query = $this->buildManipSQL($table, $table_fields, $mode, $where);
- if (PEAR::isError($query)) {
- return $query;
- }
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- $lobs = array();
- foreach ((array)$types as $param => $type) {
- if (($type == 'clob') || ($type == 'blob')) {
- $lobs[$param] = $table_fields[$param];
- }
- }
- return $db->prepare($query, $types, $result_types, $lobs);
- }
-
- // }}}
- // {{{ autoExecute()
-
- /**
- * Generate an insert, update or delete query and call prepare() and execute() on it
- *
- * @param string name of the table
- * @param array assoc ($key=>$value) where $key is a field name and $value its value
- * @param int type of query to build
- * MDB2_AUTOQUERY_INSERT
- * MDB2_AUTOQUERY_UPDATE
- * MDB2_AUTOQUERY_DELETE
- * MDB2_AUTOQUERY_SELECT
- * @param string (in case of update and delete queries, this string will be put after the sql WHERE statement)
- * @param array that contains the types of the placeholders
- * @param string which specifies which result class to use
- * @param mixed array that contains the types of the columns in
- * the result set or MDB2_PREPARE_RESULT, if set to
- * MDB2_PREPARE_MANIP the query is handled as a manipulation query
- *
- * @return bool|MDB2_Error true on success, a MDB2 error on failure
- * @see buildManipSQL
- * @see autoPrepare
- * @access public
- */
- function &autoExecute($table, $fields_values, $mode = MDB2_AUTOQUERY_INSERT,
- $where = false, $types = null, $result_class = true, $result_types = MDB2_PREPARE_MANIP)
- {
- $fields_values = (array)$fields_values;
- if ($mode == MDB2_AUTOQUERY_SELECT) {
- if (is_array($result_types)) {
- $keys = array_keys($result_types);
- } elseif (!empty($fields_values)) {
- $keys = $fields_values;
- } else {
- $keys = array();
- }
- } else {
- $keys = array_keys($fields_values);
- }
- $params = array_values($fields_values);
- if (empty($params)) {
- $query = $this->buildManipSQL($table, $keys, $mode, $where);
-
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
- if ($mode == MDB2_AUTOQUERY_SELECT) {
- $result =& $db->query($query, $result_types, $result_class);
- } else {
- $result = $db->exec($query);
- }
- } else {
- $stmt = $this->autoPrepare($table, $keys, $mode, $where, $types, $result_types);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
- $result =& $stmt->execute($params, $result_class);
- $stmt->free();
- }
- return $result;
- }
-
- // }}}
- // {{{ buildManipSQL()
-
- /**
- * Make automaticaly an sql query for prepare()
- *
- * Example : buildManipSQL('table_sql', array('field1', 'field2', 'field3'), MDB2_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/DELETE query, all
- * the records of the table will be updated/deleted !
- *
- * @param string name of the table
- * @param ordered array containing the fields names
- * @param int type of query to build
- * MDB2_AUTOQUERY_INSERT
- * MDB2_AUTOQUERY_UPDATE
- * MDB2_AUTOQUERY_DELETE
- * MDB2_AUTOQUERY_SELECT
- * @param string (in case of update and delete 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)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if ($db->options['quote_identifier']) {
- $table = $db->quoteIdentifier($table);
- }
-
- if (!empty($table_fields) && $db->options['quote_identifier']) {
- foreach ($table_fields as $key => $field) {
- $table_fields[$key] = $db->quoteIdentifier($field);
- }
- }
-
- if ($where !== false && !is_null($where)) {
- if (is_array($where)) {
- $where = implode(' AND ', $where);
- }
- $where = ' WHERE '.$where;
- }
-
- switch ($mode) {
- case MDB2_AUTOQUERY_INSERT:
- if (empty($table_fields)) {
- return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'Insert requires table fields', __FUNCTION__);
- }
- $cols = implode(', ', $table_fields);
- $values = '?'.str_repeat(', ?', (count($table_fields) - 1));
- return 'INSERT INTO '.$table.' ('.$cols.') VALUES ('.$values.')';
- break;
- case MDB2_AUTOQUERY_UPDATE:
- if (empty($table_fields)) {
- return $db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null,
- 'Update requires table fields', __FUNCTION__);
- }
- $set = implode(' = ?, ', $table_fields).' = ?';
- $sql = 'UPDATE '.$table.' SET '.$set.$where;
- return $sql;
- break;
- case MDB2_AUTOQUERY_DELETE:
- $sql = 'DELETE FROM '.$table.$where;
- return $sql;
- break;
- case MDB2_AUTOQUERY_SELECT:
- $cols = !empty($table_fields) ? implode(', ', $table_fields) : '*';
- $sql = 'SELECT '.$cols.' FROM '.$table.$where;
- return $sql;
- break;
- }
- return $db->raiseError(MDB2_ERROR_SYNTAX, null, null,
- 'Non existant mode', __FUNCTION__);
- }
-
- // }}}
- // {{{ limitQuery()
-
- /**
- * Generates a limited query
- *
- * @param string query
- * @param array that contains the types of the columns in the result set
- * @param integer the numbers of rows to fetch
- * @param integer the row to start to fetching
- * @param string which specifies which result class to use
- * @param mixed string which specifies which class to wrap results in
- *
- * @return MDB2_Result|MDB2_Error result set on success, a MDB2 error on failure
- * @access public
- */
- function &limitQuery($query, $types, $limit, $offset = 0, $result_class = true,
- $result_wrap_class = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- $result = $db->setLimit($limit, $offset);
- if (PEAR::isError($result)) {
- return $result;
- }
- $result =& $db->query($query, $types, $result_class, $result_wrap_class);
- return $result;
- }
-
- // }}}
- // {{{ execParam()
-
- /**
- * Execute a parameterized DML statement.
- *
- * @param string the SQL query
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- *
- * @return int|MDB2_Error affected rows on success, a MDB2 error on failure
- * @access public
- */
- function execParam($query, $params = array(), $param_types = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- if (empty($params)) {
- return $db->exec($query);
- }
-
- $stmt = $db->prepare($query, $param_types, MDB2_PREPARE_MANIP);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $stmt->free();
- 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 the SQL query
- * @param string that contains the type of the column in the result set
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- * @param int|string which column to return
- *
- * @return scalar|MDB2_Error data on success, a MDB2 error on failure
- * @access public
- */
- function getOne($query, $type = null, $params = array(),
- $param_types = null, $colnum = 0)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- settype($type, 'array');
- if (empty($params)) {
- return $db->queryOne($query, $type, $colnum);
- }
-
- $stmt = $db->prepare($query, $param_types, $type);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $one = $result->fetchOne($colnum);
- $stmt->free();
- $result->free();
- return $one;
- }
-
- // }}}
- // {{{ 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 the SQL query
- * @param array that contains the types of the columns in the result set
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- * @param int the fetch mode to use
- *
- * @return array|MDB2_Error data on success, a MDB2 error on failure
- * @access public
- */
- function getRow($query, $types = null, $params = array(),
- $param_types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- if (empty($params)) {
- return $db->queryRow($query, $types, $fetchmode);
- }
-
- $stmt = $db->prepare($query, $param_types, $types);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $row = $result->fetchRow($fetchmode);
- $stmt->free();
- $result->free();
- return $row;
- }
-
- // }}}
- // {{{ getCol()
-
- /**
- * Fetch a single column from a result set and return it as an
- * indexed array.
- *
- * @param string the SQL query
- * @param string that contains the type of the column in the result set
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- * @param int|string which column to return
- *
- * @return array|MDB2_Error data on success, a MDB2 error on failure
- * @access public
- */
- function getCol($query, $type = null, $params = array(),
- $param_types = null, $colnum = 0)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- settype($type, 'array');
- if (empty($params)) {
- return $db->queryCol($query, $type, $colnum);
- }
-
- $stmt = $db->prepare($query, $param_types, $type);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $col = $result->fetchCol($colnum);
- $stmt->free();
- $result->free();
- return $col;
- }
-
- // }}}
- // {{{ getAll()
-
- /**
- * Fetch all the rows returned from a query.
- *
- * @param string the SQL query
- * @param array that contains the types of the columns in the result set
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- * @param int the fetch mode to use
- * @param bool if set to true, the $all will have the first
- * column as its first dimension
- * @param bool $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 bool $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|MDB2_Error data on success, a MDB2 error on failure
- * @access public
- */
- function getAll($query, $types = null, $params = array(),
- $param_types = null, $fetchmode = MDB2_FETCHMODE_DEFAULT,
- $rekey = false, $force_array = false, $group = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- if (empty($params)) {
- return $db->queryAll($query, $types, $fetchmode, $rekey, $force_array, $group);
- }
-
- $stmt = $db->prepare($query, $param_types, $types);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $all = $result->fetchAll($fetchmode, $rekey, $force_array, $group);
- $stmt->free();
- $result->free();
- return $all;
- }
-
- // }}}
- // {{{ 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 MDB2 error code is
- * returned on errors. If the result set contains fewer than two
- * columns, a MDB2_ERROR_TRUNCATED error is returned.
- *
- * For example, if the table 'mytable' contains:
- * <pre>
- * ID TEXT DATE
- * --------------------------------
- * 1 'one' 944679408
- * 2 'two' 944679408
- * 3 'three' 944679408
- * </pre>
- * Then the call getAssoc('SELECT id,text FROM mytable') returns:
- * <pre>
- * array(
- * '1' => 'one',
- * '2' => 'two',
- * '3' => 'three',
- * )
- * </pre>
- * ...while the call getAssoc('SELECT id,text,date FROM mytable') returns:
- * <pre>
- * array(
- * '1' => array('one', '944679408'),
- * '2' => array('two', '944679408'),
- * '3' => array('three', '944679408')
- * )
- * </pre>
- *
- * 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:
- * <pre>
- * getAssoc('SELECT category,id,name FROM mytable', null, null
- * MDB2_FETCHMODE_ASSOC, false, 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')
- * )
- * )
- * </pre>
- *
- * Keep in mind that database functions in PHP usually return string
- * values for results regardless of the database's internal type.
- *
- * @param string the SQL query
- * @param array that contains the types of the columns in the result set
- * @param array if supplied, prepare/execute will be used
- * with this array as execute parameters
- * @param array that contains the types of the values defined in $params
- * @param bool $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 bool $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|MDB2_Error data on success, a MDB2 error on failure
- * @access public
- */
- function getAssoc($query, $types = null, $params = array(), $param_types = null,
- $fetchmode = MDB2_FETCHMODE_DEFAULT, $force_array = false, $group = false)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- settype($params, 'array');
- if (empty($params)) {
- return $db->queryAll($query, $types, $fetchmode, true, $force_array, $group);
- }
-
- $stmt = $db->prepare($query, $param_types, $types);
- if (PEAR::isError($stmt)) {
- return $stmt;
- }
-
- $result = $stmt->execute($params);
- if (!MDB2::isResultCommon($result)) {
- return $result;
- }
-
- $all = $result->fetchAll($fetchmode, true, $force_array, $group);
- $stmt->free();
- $result->free();
- return $all;
- }
-
- // }}}
- // {{{ executeMultiple()
-
- /**
- * This function does several execute() calls on the same statement handle.
- * $params 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 query handle from prepare()
- * @param array numeric array containing the data to insert into the query
- *
- * @return bool|MDB2_Error true on success, a MDB2 error on failure
- * @access public
- * @see prepare(), execute()
- */
- function executeMultiple(&$stmt, $params = null)
- {
- for ($i = 0, $j = count($params); $i < $j; $i++) {
- $result = $stmt->execute($params[$i]);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ getBeforeID()
-
- /**
- * Returns the next free id of a sequence if the RDBMS
- * does not support auto increment
- *
- * @param string name of the table into which a new row was inserted
- * @param string name of the field into which a new row was inserted
- * @param bool when true the sequence is automatic created, if it not exists
- * @param bool if the returned value should be quoted
- *
- * @return int|MDB2_Error id on success, a MDB2 error on failure
- * @access public
- */
- function getBeforeID($table, $field = null, $ondemand = true, $quote = true)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if ($db->supports('auto_increment') !== true) {
- $seq = $table.(empty($field) ? '' : '_'.$field);
- $id = $db->nextID($seq, $ondemand);
- if (!$quote || PEAR::isError($id)) {
- return $id;
- }
- return $db->quote($id, 'integer');
- } elseif (!$quote) {
- return null;
- }
- return 'NULL';
- }
-
- // }}}
- // {{{ getAfterID()
-
- /**
- * Returns the autoincrement ID if supported or $id
- *
- * @param mixed value as returned by getBeforeId()
- * @param string name of the table into which a new row was inserted
- * @param string name of the field into which a new row was inserted
- *
- * @return int|MDB2_Error id on success, a MDB2 error on failure
- * @access public
- */
- function getAfterID($id, $table, $field = null)
- {
- $db =& $this->getDBInstance();
- if (PEAR::isError($db)) {
- return $db;
- }
-
- if ($db->supports('auto_increment') !== true) {
- return $id;
- }
- return $db->lastInsertID($table, $field);
- }
-
- // }}}
-}
-?> \ No newline at end of file
diff --git a/inc/MDB2/Iterator.php b/inc/MDB2/Iterator.php
deleted file mode 100644
index ca5e7b69c27..00000000000
--- a/inc/MDB2/Iterator.php
+++ /dev/null
@@ -1,259 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Iterator.php,v 1.22 2006/05/06 14:03:41 lsmith Exp $
-
-/**
- * PHP5 Iterator
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_Iterator implements Iterator
-{
- protected $fetchmode;
- protected $result;
- protected $row;
-
- // {{{ constructor
-
- /**
- * Constructor
- */
- public function __construct($result, $fetchmode = MDB2_FETCHMODE_DEFAULT)
- {
- $this->result = $result;
- $this->fetchmode = $fetchmode;
- }
- // }}}
-
- // {{{ seek()
-
- /**
- * Seek forward to a specific row in a result set
- *
- * @param int number of the row where the data can be found
- *
- * @return void
- * @access public
- */
- public function seek($rownum)
- {
- $this->row = null;
- if ($this->result) {
- $this->result->seek($rownum);
- }
- }
- // }}}
-
- // {{{ next()
-
- /**
- * Fetch next row of data
- *
- * @return void
- * @access public
- */
- public function next()
- {
- $this->row = null;
- }
- // }}}
-
- // {{{ current()
-
- /**
- * return a row of data
- *
- * @return void
- * @access public
- */
- public function current()
- {
- if (is_null($this->row)) {
- $row = $this->result->fetchRow($this->fetchmode);
- if (PEAR::isError($row)) {
- $row = false;
- }
- $this->row = $row;
- }
- return $this->row;
- }
- // }}}
-
- // {{{ valid()
-
- /**
- * Check if the end of the result set has been reached
- *
- * @return bool true/false, false is also returned on failure
- * @access public
- */
- public function valid()
- {
- return (bool)$this->current();
- }
- // }}}
-
- // {{{ free()
-
- /**
- * Free the internal resources associated with result.
- *
- * @return bool|MDB2_Error true on success, false|MDB2_Error if result is invalid
- * @access public
- */
- public function free()
- {
- if ($this->result) {
- return $this->result->free();
- }
- $this->result = false;
- $this->row = null;
- return false;
- }
- // }}}
-
- // {{{ key()
-
- /**
- * Returns the row number
- *
- * @return int|bool|MDB2_Error true on success, false|MDB2_Error if result is invalid
- * @access public
- */
- public function key()
- {
- if ($this->result) {
- return $this->result->rowCount();
- }
- return false;
- }
- // }}}
-
- // {{{ rewind()
-
- /**
- * Seek to the first row in a result set
- *
- * @return void
- * @access public
- */
- public function rewind()
- {
- }
- // }}}
-
- // {{{ destructor
-
- /**
- * Destructor
- */
- public function __destruct()
- {
- $this->free();
- }
- // }}}
-}
-
-/**
- * PHP5 buffered Iterator
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_BufferedIterator extends MDB2_Iterator implements SeekableIterator
-{
- // {{{ valid()
-
- /**
- * Check if the end of the result set has been reached
- *
- * @return bool|MDB2_Error true on success, false|MDB2_Error if result is invalid
- * @access public
- */
- public function valid()
- {
- if ($this->result) {
- return $this->result->valid();
- }
- return false;
- }
- // }}}
-
- // {{{count()
-
- /**
- * Returns the number of rows in a result object
- *
- * @return int|MDB2_Error number of rows, false|MDB2_Error if result is invalid
- * @access public
- */
- public function count()
- {
- if ($this->result) {
- return $this->result->numRows();
- }
- return false;
- }
- // }}}
-
- // {{{ rewind()
-
- /**
- * Seek to the first row in a result set
- *
- * @return void
- * @access public
- */
- public function rewind()
- {
- $this->seek(0);
- }
- // }}}
-}
-
-?> \ No newline at end of file
diff --git a/inc/MDB2/LOB.php b/inc/MDB2/LOB.php
deleted file mode 100644
index 2cdf67afa92..00000000000
--- a/inc/MDB2/LOB.php
+++ /dev/null
@@ -1,264 +0,0 @@
-<?php
-// +----------------------------------------------------------------------+
-// | PHP version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lukas Smith <smith@pooteeweet.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: LOB.php,v 1.34 2006/10/25 11:52:21 lsmith Exp $
-
-/**
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-
-oc_require_once('MDB2.php');
-
-/**
- * MDB2_LOB: user land stream wrapper implementation for LOB support
- *
- * @package MDB2
- * @category Database
- * @author Lukas Smith <smith@pooteeweet.org>
- */
-class MDB2_LOB
-{
- /**
- * contains the key to the global MDB2 instance array of the associated
- * MDB2 instance
- *
- * @var integer
- * @access protected
- */
- var $db_index;
-
- /**
- * contains the key to the global MDB2_LOB instance array of the associated
- * MDB2_LOB instance
- *
- * @var integer
- * @access protected
- */
- var $lob_index;
-
- // {{{ stream_open()
-
- /**
- * open stream
- *
- * @param string specifies the URL that was passed to fopen()
- * @param string the mode used to open the file
- * @param int holds additional flags set by the streams API
- * @param string not used
- *
- * @return bool
- * @access public
- */
- function stream_open($path, $mode, $options, &$opened_path)
- {
- if (!preg_match('/^rb?\+?$/', $mode)) {
- return false;
- }
- $url = parse_url($path);
- if (empty($url['host'])) {
- return false;
- }
- $this->db_index = (int)$url['host'];
- if (!isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- return false;
- }
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- $this->lob_index = (int)$url['user'];
- if (!isset($db->datatype->lobs[$this->lob_index])) {
- return false;
- }
- return true;
- }
- // }}}
-
- // {{{ stream_read()
-
- /**
- * read stream
- *
- * @param int number of bytes to read
- *
- * @return string
- * @access public
- */
- function stream_read($count)
- {
- if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- $db->datatype->_retrieveLOB($db->datatype->lobs[$this->lob_index]);
-
- $data = $db->datatype->_readLOB($db->datatype->lobs[$this->lob_index], $count);
- $length = strlen($data);
- if ($length == 0) {
- $db->datatype->lobs[$this->lob_index]['endOfLOB'] = true;
- }
- $db->datatype->lobs[$this->lob_index]['position'] += $length;
- return $data;
- }
- }
- // }}}
-
- // {{{ stream_write()
-
- /**
- * write stream, note implemented
- *
- * @param string data
- *
- * @return int
- * @access public
- */
- function stream_write($data)
- {
- return 0;
- }
- // }}}
-
- // {{{ stream_tell()
-
- /**
- * return the current position
- *
- * @return int current position
- * @access public
- */
- function stream_tell()
- {
- if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- return $db->datatype->lobs[$this->lob_index]['position'];
- }
- }
- // }}}
-
- // {{{ stream_eof()
-
- /**
- * Check if stream reaches EOF
- *
- * @return bool
- * @access public
- */
- function stream_eof()
- {
- if (!isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- return true;
- }
-
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- $result = $db->datatype->_endOfLOB($db->datatype->lobs[$this->lob_index]);
- if (version_compare(phpversion(), "5.0", ">=")
- && version_compare(phpversion(), "5.1", "<")
- ) {
- return !$result;
- }
- return $result;
- }
- // }}}
-
- // {{{ stream_seek()
-
- /**
- * Seek stream, not implemented
- *
- * @param int offset
- * @param int whence
- *
- * @return bool
- * @access public
- */
- function stream_seek($offset, $whence)
- {
- return false;
- }
- // }}}
-
- // {{{ stream_stat()
-
- /**
- * return information about stream
- *
- * @access public
- */
- function stream_stat()
- {
- if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- return array(
- 'db_index' => $this->db_index,
- 'lob_index' => $this->lob_index,
- );
- }
- }
- // }}}
-
- // {{{ stream_close()
-
- /**
- * close stream
- *
- * @access public
- */
- function stream_close()
- {
- if (isset($GLOBALS['_MDB2_databases'][$this->db_index])) {
- $db =& $GLOBALS['_MDB2_databases'][$this->db_index];
- if (isset($db->datatype->lobs[$this->lob_index])) {
- $db->datatype->_destroyLOB($db->datatype->lobs[$this->lob_index]);
- unset($db->datatype->lobs[$this->lob_index]);
- }
- }
- }
- // }}}
-}
-
-// register streams wrapper
-if (!stream_wrapper_register("MDB2LOB", "MDB2_LOB")) {
- MDB2::raiseError();
- return false;
-}
-
-?>
diff --git a/inc/MDB2/Schema.php b/inc/MDB2/Schema.php
deleted file mode 100644
index 44518b32658..00000000000
--- a/inc/MDB2/Schema.php
+++ /dev/null
@@ -1,2763 +0,0 @@
-<?php
-/**
- * PHP version 4, 5
- *
- * Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,
- * Stig. S. Bakken, Lukas Smith, Igor Feghali
- * All rights reserved.
- *
- * MDB2_Schema enables users to maintain RDBMS independant schema files
- * in XML that can be used to manipulate both data and database schemas
- * This LICENSE is in the BSD license style.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,
- * Lukas Smith, Igor Feghali nor the names of his contributors may be
- * used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
- * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- * Author: Lukas Smith <smith@pooteeweet.org>
- * Author: Igor Feghali <ifeghali@php.net>
- *
- * @category Database
- * @package MDB2_Schema
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Igor Feghali <ifeghali@php.net>
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @version CVS: $Id: Schema.php,v 1.132 2009/02/22 21:43:22 ifeghali Exp $
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-
-// require_once('MDB2.php');
-
-define('MDB2_SCHEMA_DUMP_ALL', 0);
-define('MDB2_SCHEMA_DUMP_STRUCTURE', 1);
-define('MDB2_SCHEMA_DUMP_CONTENT', 2);
-
-/**
- * If you add an error code here, make sure you also add a textual
- * version of it in MDB2_Schema::errorMessage().
- */
-
-define('MDB2_SCHEMA_ERROR', -1);
-define('MDB2_SCHEMA_ERROR_PARSE', -2);
-define('MDB2_SCHEMA_ERROR_VALIDATE', -3);
-define('MDB2_SCHEMA_ERROR_UNSUPPORTED', -4); // Driver does not support this function
-define('MDB2_SCHEMA_ERROR_INVALID', -5); // Invalid attribute value
-define('MDB2_SCHEMA_ERROR_WRITER', -6);
-
-/**
- * The database manager is a class that provides a set of database
- * management services like installing, altering and dumping the data
- * structures of databases.
- *
- * @category Database
- * @package MDB2_Schema
- * @author Lukas Smith <smith@pooteeweet.org>
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-class MDB2_Schema extends PEAR
-{
- // {{{ properties
-
- var $db;
-
- var $warnings = array();
-
- var $options = array(
- 'fail_on_invalid_names' => true,
- 'dtd_file' => false,
- 'valid_types' => array(),
- 'force_defaults' => true,
- 'parser' => 'MDB2_Schema_Parser',
- 'writer' => 'MDB2_Schema_Writer',
- 'validate' => 'MDB2_Schema_Validate',
- 'drop_missing_tables' => false
- );
-
- // }}}
- // {{{ apiVersion()
-
- /**
- * Return the MDB2 API version
- *
- * @return string the MDB2 API version number
- * @access public
- */
- function apiVersion()
- {
- return '0.4.3';
- }
-
- // }}}
- // {{{ arrayMergeClobber()
-
- /**
- * Clobbers two arrays together
- *
- * @param array $a1 array that should be clobbered
- * @param array $a2 array that should be clobbered
- *
- * @return array|false array on success and false on error
- *
- * @access public
- * @author kc@hireability.com
- */
- function arrayMergeClobber($a1, $a2)
- {
- if (!is_array($a1) || !is_array($a2)) {
- return false;
- }
- foreach ($a2 as $key => $val) {
- if (is_array($val) && array_key_exists($key, $a1) && is_array($a1[$key])) {
- $a1[$key] = MDB2_Schema::arrayMergeClobber($a1[$key], $val);
- } else {
- $a1[$key] = $val;
- }
- }
- return $a1;
- }
-
- // }}}
- // {{{ resetWarnings()
-
- /**
- * reset the warning array
- *
- * @access public
- * @return void
- */
- function resetWarnings()
- {
- $this->warnings = array();
- }
-
- // }}}
- // {{{ getWarnings()
-
- /**
- * Get all warnings in reverse order
- *
- * This means that the last warning is the first element in the array
- *
- * @return array with warnings
- * @access public
- * @see resetWarnings()
- */
- function getWarnings()
- {
- return array_reverse($this->warnings);
- }
-
- // }}}
- // {{{ setOption()
-
- /**
- * Sets the option for the db class
- *
- * @param string $option option name
- * @param mixed $value value for the option
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function setOption($option, $value)
- {
- if (isset($this->options[$option])) {
- if (is_null($value)) {
- return $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
- 'may not set an option to value null');
- }
- $this->options[$option] = $value;
- return MDB2_OK;
- }
- return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null,
- "unknown option $option");
- }
-
- // }}}
- // {{{ getOption()
-
- /**
- * returns the value of an option
- *
- * @param string $option option name
- *
- * @return mixed the option value or error object
- * @access public
- */
- function getOption($option)
- {
- if (isset($this->options[$option])) {
- return $this->options[$option];
- }
- return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED,
- null, null, "unknown option $option");
- }
-
- // }}}
- // {{{ factory()
-
- /**
- * Create a new MDB2 object for the specified database type
- * type
- *
- * @param string|array|MDB2_Driver_Common &$db 'data source name', see the
- * MDB2::parseDSN method for a description of the dsn format.
- * Can also be specified as an array of the
- * format returned by @see MDB2::parseDSN.
- * Finally you can also pass an existing db object to be used.
- * @param array $options An associative array of option names and their values.
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- * @see MDB2::parseDSN
- */
- function &factory(&$db, $options = array())
- {
- $obj =new MDB2_Schema();
- $result = $obj->connect($db, $options);
- if (PEAR::isError($result)) {
- return $result;
- }
- return $obj;
- }
-
- // }}}
- // {{{ connect()
-
- /**
- * Create a new MDB2 connection object and connect to the specified
- * database
- *
- * @param string|array|MDB2_Driver_Common &$db 'data source name', see the
- * MDB2::parseDSN method for a description of the dsn format.
- * Can also be specified as an array of the
- * format returned by MDB2::parseDSN.
- * Finally you can also pass an existing db object to be used.
- * @param array $options An associative array of option names and their values.
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- * @see MDB2::parseDSN
- */
- function connect(&$db, $options = array())
- {
- $db_options = array();
- if (is_array($options)) {
- foreach ($options as $option => $value) {
- if (array_key_exists($option, $this->options)) {
- $result = $this->setOption($option, $value);
- if (PEAR::isError($result)) {
- return $result;
- }
- } else {
- $db_options[$option] = $value;
- }
- }
- }
- $this->disconnect();
- if (!MDB2::isConnection($db)) {
- $db =& MDB2::factory($db, $db_options);
- }
-
- if (PEAR::isError($db)) {
- return $db;
- }
- $this->db =& $db;
- $this->db->loadModule('Datatype');
- $this->db->loadModule('Manager');
- $this->db->loadModule('Reverse');
- $this->db->loadModule('Function');
- if (empty($this->options['valid_types'])) {
- $this->options['valid_types'] = $this->db->datatype->getValidTypes();
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ disconnect()
-
- /**
- * Log out and disconnect from the database.
- *
- * @access public
- * @return void
- */
- function disconnect()
- {
- if (MDB2::isConnection($this->db)) {
- $this->db->disconnect();
- unset($this->db);
- }
- }
-
- // }}}
- // {{{ parseDatabaseDefinition()
-
- /**
- * Parse a database definition from a file or an array
- *
- * @param string|array $schema the database schema array or file name
- * @param bool $skip_unreadable if non readable files should be skipped
- * @param array $variables associative array that the defines the text string values
- * that are meant to be used to replace the variables that are
- * used in the schema description.
- * @param bool $fail_on_invalid_names make function fail on invalid names
- * @param array $structure database structure definition
- *
- * @access public
- * @return array
- */
- function parseDatabaseDefinition($schema, $skip_unreadable = false, $variables = array(),
- $fail_on_invalid_names = true, $structure = false)
- {
- $database_definition = false;
- if (is_string($schema)) {
- // if $schema is not readable then we just skip it
- // and simply copy the $current_schema file to that file name
- if (is_readable($schema)) {
- $database_definition = $this->parseDatabaseDefinitionFile($schema, $variables, $fail_on_invalid_names, $structure);
- }
- } elseif (is_array($schema)) {
- $database_definition = $schema;
- }
- if (!$database_definition && !$skip_unreadable) {
- $database_definition = $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
- 'invalid data type of schema or unreadable data source');
- }
- return $database_definition;
- }
-
- // }}}
- // {{{ parseDatabaseDefinitionFile()
-
- /**
- * Parse a database definition file by creating a schema format
- * parser object and passing the file contents as parser input data stream.
- *
- * @param string $input_file the database schema file.
- * @param array $variables associative array that the defines the text string values
- * that are meant to be used to replace the variables that are
- * used in the schema description.
- * @param bool $fail_on_invalid_names make function fail on invalid names
- * @param array $structure database structure definition
- *
- * @access public
- * @return array
- */
- function parseDatabaseDefinitionFile($input_file, $variables = array(),
- $fail_on_invalid_names = true, $structure = false)
- {
- $dtd_file = $this->options['dtd_file'];
- if ($dtd_file) {
- include_once 'XML/DTD/XmlValidator.php';
- $dtd =new XML_DTD_XmlValidator;
- if (!$dtd->isValid($dtd_file, $input_file)) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_PARSE, null, null, $dtd->getMessage());
- }
- }
-
- $class_name = $this->options['parser'];
-
- $result = MDB2::loadClass($class_name, $this->db->getOption('debug'));
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $parser =new $class_name($variables, $fail_on_invalid_names, $structure, $this->options['valid_types'], $this->options['force_defaults']);
- $result = $parser->setInputFile($input_file);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $result = $parser->parse();
- if (PEAR::isError($result)) {
- return $result;
- }
- if (PEAR::isError($parser->error)) {
- return $parser->error;
- }
-
- return $parser->database_definition;
- }
-
- // }}}
- // {{{ getDefinitionFromDatabase()
-
- /**
- * Attempt to reverse engineer a schema structure from an existing MDB2
- * This method can be used if no xml schema file exists yet.
- * The resulting xml schema file may need some manual adjustments.
- *
- * @return array|MDB2_Error array with definition or error object
- * @access public
- */
- function getDefinitionFromDatabase()
- {
- $database = $this->db->database_name;
- if (empty($database)) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
- 'it was not specified a valid database name');
- }
- $class_name = $this->options['validate'];
-
- $result = MDB2::loadClass($class_name, $this->db->getOption('debug'));
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $val =new $class_name($this->options['fail_on_invalid_names'], $this->options['valid_types'], $this->options['force_defaults']);
-
- $database_definition = array(
- 'name' => $database,
- 'create' => true,
- 'overwrite' => false,
- 'charset' => 'utf8',
- 'description' => '',
- 'comments' => '',
- 'tables' => array(),
- 'sequences' => array(),
- );
-
- $tables = $this->db->manager->listTables();
- if (PEAR::isError($tables)) {
- return $tables;
- }
-
- foreach ($tables as $table_name) {
- $fields = $this->db->manager->listTableFields($table_name);
- if (PEAR::isError($fields)) {
- return $fields;
- }
-
- $database_definition['tables'][$table_name] = array(
- 'was' => '',
- 'description' => '',
- 'comments' => '',
- 'fields' => array(),
- 'indexes' => array(),
- 'constraints' => array(),
- 'initialization' => array()
- );
-
- $table_definition =& $database_definition['tables'][$table_name];
- foreach ($fields as $field_name) {
- $definition = $this->db->reverse->getTableFieldDefinition($table_name, $field_name);
- if (PEAR::isError($definition)) {
- return $definition;
- }
-
- if (!empty($definition[0]['autoincrement'])) {
- $definition[0]['default'] = '0';
- }
-
- $table_definition['fields'][$field_name] = $definition[0];
-
- $field_choices = count($definition);
- if ($field_choices > 1) {
- $warning = "There are $field_choices type choices in the table $table_name field $field_name (#1 is the default): ";
-
- $field_choice_cnt = 1;
-
- $table_definition['fields'][$field_name]['choices'] = array();
- foreach ($definition as $field_choice) {
- $table_definition['fields'][$field_name]['choices'][] = $field_choice;
-
- $warning .= 'choice #'.($field_choice_cnt).': '.serialize($field_choice);
- $field_choice_cnt++;
- }
- $this->warnings[] = $warning;
- }
-
- /**
- * The first parameter is used to verify if there are duplicated
- * fields which we can guarantee that won't happen when reverse engineering
- */
- $result = $val->validateField(array(), $table_definition['fields'][$field_name], $field_name);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- $keys = array();
-
- $indexes = $this->db->manager->listTableIndexes($table_name);
- if (PEAR::isError($indexes)) {
- return $indexes;
- }
-
- if (is_array($indexes)) {
- foreach ($indexes as $index_name) {
- $this->db->expectError(MDB2_ERROR_NOT_FOUND);
- $definition = $this->db->reverse->getTableIndexDefinition($table_name, $index_name);
- $this->db->popExpect();
- if (PEAR::isError($definition)) {
- if (PEAR::isError($definition, MDB2_ERROR_NOT_FOUND)) {
- continue;
- }
- return $definition;
- }
-
- $keys[$index_name] = $definition;
- }
- }
-
- $constraints = $this->db->manager->listTableConstraints($table_name);
- if (PEAR::isError($constraints)) {
- return $constraints;
- }
-
- if (is_array($constraints)) {
- foreach ($constraints as $constraint_name) {
- $this->db->expectError(MDB2_ERROR_NOT_FOUND);
- $definition = $this->db->reverse->getTableConstraintDefinition($table_name, $constraint_name);
- $this->db->popExpect();
- if (PEAR::isError($definition)) {
- if (PEAR::isError($definition, MDB2_ERROR_NOT_FOUND)) {
- continue;
- }
- return $definition;
- }
-
- $keys[$constraint_name] = $definition;
- }
- }
-
- foreach ($keys as $key_name => $definition) {
- if (array_key_exists('foreign', $definition)
- && $definition['foreign']
- ) {
- /**
- * The first parameter is used to verify if there are duplicated
- * foreign keys which we can guarantee that won't happen when reverse engineering
- */
- $result = $val->validateConstraint(array(), $definition, $key_name);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- foreach ($definition['fields'] as $field_name => $field) {
- /**
- * The first parameter is used to verify if there are duplicated
- * referencing fields which we can guarantee that won't happen when reverse engineering
- */
- $result = $val->validateConstraintField(array(), $field_name);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $definition['fields'][$field_name] = '';
- }
-
- foreach ($definition['references']['fields'] as $field_name => $field) {
- /**
- * The first parameter is used to verify if there are duplicated
- * referenced fields which we can guarantee that won't happen when reverse engineering
- */
- $result = $val->validateConstraintReferencedField(array(), $field_name);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $definition['references']['fields'][$field_name] = '';
- }
-
- $table_definition['constraints'][$key_name] = $definition;
- } else {
- /**
- * The first parameter is used to verify if there are duplicated
- * indices which we can guarantee that won't happen when reverse engineering
- */
- $result = $val->validateIndex(array(), $definition, $key_name);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- foreach ($definition['fields'] as $field_name => $field) {
- /**
- * The first parameter is used to verify if there are duplicated
- * index fields which we can guarantee that won't happen when reverse engineering
- */
- $result = $val->validateIndexField(array(), $field, $field_name);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $definition['fields'][$field_name] = $field;
- }
-
- $table_definition['indexes'][$key_name] = $definition;
- }
- }
-
- /**
- * The first parameter is used to verify if there are duplicated
- * tables which we can guarantee that won't happen when reverse engineering
- */
- $result = $val->validateTable(array(), $table_definition, $table_name);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- }
-
- $sequences = $this->db->manager->listSequences();
- if (PEAR::isError($sequences)) {
- return $sequences;
- }
-
- if (is_array($sequences)) {
- foreach ($sequences as $sequence_name) {
- $definition = $this->db->reverse->getSequenceDefinition($sequence_name);
- if (PEAR::isError($definition)) {
- return $definition;
- }
- if (isset($database_definition['tables'][$sequence_name])
- && isset($database_definition['tables'][$sequence_name]['indexes'])
- ) {
- foreach ($database_definition['tables'][$sequence_name]['indexes'] as $index) {
- if (isset($index['primary']) && $index['primary']
- && count($index['fields'] == 1)
- ) {
- $definition['on'] = array(
- 'table' => $sequence_name,
- 'field' => key($index['fields']),
- );
- break;
- }
- }
- }
-
- /**
- * The first parameter is used to verify if there are duplicated
- * sequences which we can guarantee that won't happen when reverse engineering
- */
- $result = $val->validateSequence(array(), $definition, $sequence_name);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- $database_definition['sequences'][$sequence_name] = $definition;
- }
- }
-
- $result = $val->validateDatabase($database_definition);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- return $database_definition;
- }
-
- // }}}
- // {{{ createTableIndexes()
-
- /**
- * A method to create indexes for an existing table
- *
- * @param string $table_name Name of the table
- * @param array $indexes An array of indexes to be created
- * @param boolean $overwrite If the table/index should be overwritten if it already exists
- *
- * @return mixed MDB2_Error if there is an error creating an index, MDB2_OK otherwise
- * @access public
- */
- function createTableIndexes($table_name, $indexes, $overwrite = false)
- {
- if (!$this->db->supports('indexes')) {
- $this->db->debug('Indexes are not supported', __FUNCTION__);
- return MDB2_OK;
- }
-
- $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE);
- foreach ($indexes as $index_name => $index) {
-
- // Does the index already exist, and if so, should it be overwritten?
- $create_index = true;
- $this->db->expectError($errorcodes);
- if (!empty($index['primary']) || !empty($index['unique'])) {
- $current_indexes = $this->db->manager->listTableConstraints($table_name);
- } else {
- $current_indexes = $this->db->manager->listTableIndexes($table_name);
- }
-
- $this->db->popExpect();
- if (PEAR::isError($current_indexes)) {
- if (!MDB2::isError($current_indexes, $errorcodes)) {
- return $current_indexes;
- }
- } elseif (is_array($current_indexes) && in_array($index_name, $current_indexes)) {
- if (!$overwrite) {
- $this->db->debug('Index already exists: '.$index_name, __FUNCTION__);
- $create_index = false;
- } else {
- $this->db->debug('Preparing to overwrite index: '.$index_name, __FUNCTION__);
-
- $this->db->expectError(MDB2_ERROR_NOT_FOUND);
- if (!empty($index['primary']) || !empty($index['unique'])) {
- $result = $this->db->manager->dropConstraint($table_name, $index_name);
- } else {
- $result = $this->db->manager->dropIndex($table_name, $index_name);
- }
- $this->db->popExpect();
- if (PEAR::isError($result) && !MDB2::isError($result, MDB2_ERROR_NOT_FOUND)) {
- return $result;
- }
- }
- }
-
- // Check if primary is being used and if it's supported
- if (!empty($index['primary']) && !$this->db->supports('primary_key')) {
-
- // Primary not supported so we fallback to UNIQUE and making the field NOT NULL
- $index['unique'] = true;
-
- $changes = array();
-
- foreach ($index['fields'] as $field => $empty) {
- $field_info = $this->db->reverse->getTableFieldDefinition($table_name, $field);
- if (PEAR::isError($field_info)) {
- return $field_info;
- }
- if (!$field_info[0]['notnull']) {
- $changes['change'][$field] = $field_info[0];
-
- $changes['change'][$field]['notnull'] = true;
- }
- }
- if (!empty($changes)) {
- $this->db->manager->alterTable($table_name, $changes, false);
- }
- }
-
- // Should the index be created?
- if ($create_index) {
- if (!empty($index['primary']) || !empty($index['unique'])) {
- $result = $this->db->manager->createConstraint($table_name, $index_name, $index);
- } else {
- $result = $this->db->manager->createIndex($table_name, $index_name, $index);
- }
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ createTableConstraints()
-
- /**
- * A method to create foreign keys for an existing table
- *
- * @param string $table_name Name of the table
- * @param array $constraints An array of foreign keys to be created
- * @param boolean $overwrite If the foreign key should be overwritten if it already exists
- *
- * @return mixed MDB2_Error if there is an error creating a foreign key, MDB2_OK otherwise
- * @access public
- */
- function createTableConstraints($table_name, $constraints, $overwrite = false)
- {
- if (!$this->db->supports('indexes')) {
- $this->db->debug('Indexes are not supported', __FUNCTION__);
- return MDB2_OK;
- }
-
- $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE);
- foreach ($constraints as $constraint_name => $constraint) {
-
- // Does the foreign key already exist, and if so, should it be overwritten?
- $create_constraint = true;
- $this->db->expectError($errorcodes);
- $current_constraints = $this->db->manager->listTableConstraints($table_name);
- $this->db->popExpect();
- if (PEAR::isError($current_constraints)) {
- if (!MDB2::isError($current_constraints, $errorcodes)) {
- return $current_constraints;
- }
- } elseif (is_array($current_constraints) && in_array($constraint_name, $current_constraints)) {
- if (!$overwrite) {
- $this->db->debug('Foreign key already exists: '.$constraint_name, __FUNCTION__);
- $create_constraint = false;
- } else {
- $this->db->debug('Preparing to overwrite foreign key: '.$constraint_name, __FUNCTION__);
- $result = $this->db->manager->dropConstraint($table_name, $constraint_name);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
-
- // Should the foreign key be created?
- if ($create_constraint) {
- $result = $this->db->manager->createConstraint($table_name, $constraint_name, $constraint);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ createTable()
-
- /**
- * Create a table and inititialize the table if data is available
- *
- * @param string $table_name name of the table to be created
- * @param array $table multi dimensional array that contains the
- * structure and optional data of the table
- * @param bool $overwrite if the table/index should be overwritten if it already exists
- * @param array $options an array of options to be passed to the database specific driver
- * version of MDB2_Driver_Manager_Common::createTable().
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function createTable($table_name, $table, $overwrite = false, $options = array())
- {
- $create = true;
-
- $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE);
-
- $this->db->expectError($errorcodes);
-
- $tables = $this->db->manager->listTables();
-
- $this->db->popExpect();
- if (PEAR::isError($tables)) {
- if (!MDB2::isError($tables, $errorcodes)) {
- return $tables;
- }
- } elseif (is_array($tables) && in_array($table_name, $tables)) {
- if (!$overwrite) {
- $create = false;
- $this->db->debug('Table already exists: '.$table_name, __FUNCTION__);
- } else {
- $result = $this->db->manager->dropTable($table_name);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->db->debug('Overwritting table: '.$table_name, __FUNCTION__);
- }
- }
-
- if ($create) {
- $result = $this->db->manager->createTable($table_name, $table['fields'], $options);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- if (!empty($table['initialization']) && is_array($table['initialization'])) {
- $result = $this->initializeTable($table_name, $table);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- if (!empty($table['indexes']) && is_array($table['indexes'])) {
- $result = $this->createTableIndexes($table_name, $table['indexes'], $overwrite);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- if (!empty($table['constraints']) && is_array($table['constraints'])) {
- $result = $this->createTableConstraints($table_name, $table['constraints'], $overwrite);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ initializeTable()
-
- /**
- * Inititialize the table with data
- *
- * @param string $table_name name of the table
- * @param array $table multi dimensional array that contains the
- * structure and optional data of the table
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function initializeTable($table_name, $table)
- {
- $query_insertselect = 'INSERT INTO %s (%s) (SELECT %s FROM %s %s)';
-
- $query_insert = 'INSERT INTO %s (%s) VALUES (%s)';
- $query_update = 'UPDATE %s SET %s %s';
- $query_delete = 'DELETE FROM %s %s';
-
- $table_name = $this->db->quoteIdentifier($table_name, true);
-
- $result = MDB2_OK;
-
- $support_transactions = $this->db->supports('transactions');
-
- foreach ($table['initialization'] as $instruction) {
- $query = '';
- switch ($instruction['type']) {
- case 'insert':
- if (!isset($instruction['data']['select'])) {
- $data = $this->getInstructionFields($instruction['data'], $table['fields']);
- if (!empty($data)) {
- $fields = implode(', ', array_keys($data));
- $values = implode(', ', array_values($data));
-
- $query = sprintf($query_insert, $table_name, $fields, $values);
- }
- } else {
- $data = $this->getInstructionFields($instruction['data']['select'], $table['fields']);
- $where = $this->getInstructionWhere($instruction['data']['select'], $table['fields']);
-
- $select_table_name = $this->db->quoteIdentifier($instruction['data']['select']['table'], true);
- if (!empty($data)) {
- $fields = implode(', ', array_keys($data));
- $values = implode(', ', array_values($data));
-
- $query = sprintf($query_insertselect, $table_name, $fields, $values, $select_table_name, $where);
- }
- }
- break;
- case 'update':
- $data = $this->getInstructionFields($instruction['data'], $table['fields']);
- $where = $this->getInstructionWhere($instruction['data'], $table['fields']);
- if (!empty($data)) {
- array_walk($data, array($this, 'buildFieldValue'));
- $fields_values = implode(', ', $data);
-
- $query = sprintf($query_update, $table_name, $fields_values, $where);
- }
- break;
- case 'delete':
- $where = $this->getInstructionWhere($instruction['data'], $table['fields']);
- $query = sprintf($query_delete, $table_name, $where);
- break;
- }
- if ($query) {
- if ($support_transactions && PEAR::isError($res = $this->db->beginNestedTransaction())) {
- return $res;
- }
-
- $result = $this->db->exec($query);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if ($support_transactions && PEAR::isError($res = $this->db->completeNestedTransaction())) {
- return $res;
- }
- }
- }
- return $result;
- }
-
- // }}}
- // {{{ buildFieldValue()
-
- /**
- * Appends the contents of second argument + '=' to the beginning of first
- * argument.
- *
- * Used with array_walk() in initializeTable() for UPDATEs.
- *
- * @param string &$element value of array's element
- * @param string $key key of array's element
- *
- * @return void
- *
- * @access public
- * @see MDB2_Schema::initializeTable()
- */
- function buildFieldValue(&$element, $key)
- {
- $element = $key."=$element";
- }
-
- // }}}
- // {{{ getExpression()
-
- /**
- * Generates a string that represents a value that would be associated
- * with a column in a DML instruction.
- *
- * @param array $element multi dimensional array that contains the
- * structure of the current DML instruction.
- * @param array $fields_definition multi dimensional array that contains the
- * definition for current table's fields
- * @param string $type type of given field
- *
- * @return string
- *
- * @access public
- * @see MDB2_Schema::getInstructionFields(), MDB2_Schema::getInstructionWhere()
- */
- function getExpression($element, $fields_definition = array(), $type = null)
- {
- $str = '';
- switch ($element['type']) {
- case 'null':
- $str .= 'NULL';
- break;
- case 'value':
- $str .= $this->db->quote($element['data'], $type);
- break;
- case 'column':
- $str .= $this->db->quoteIdentifier($element['data'], true);
- break;
- case 'function':
- $arguments = array();
- if (!empty($element['data']['arguments'])
- && is_array($element['data']['arguments'])
- ) {
- foreach ($element['data']['arguments'] as $v) {
- $arguments[] = $this->getExpression($v, $fields_definition);
- }
- }
- if (method_exists($this->db->function, $element['data']['name'])) {
- $user_func = array(&$this->db->function, $element['data']['name']);
-
- $str .= call_user_func_array($user_func, $arguments);
- } else {
- $str .= $element['data']['name'].'(';
- $str .= implode(', ', $arguments);
- $str .= ')';
- }
- break;
- case 'expression':
- $type0 = $type1 = null;
- if ($element['data']['operants'][0]['type'] == 'column'
- && array_key_exists($element['data']['operants'][0]['data'], $fields_definition)
- ) {
- $type0 = $fields_definition[$element['data']['operants'][0]['data']]['type'];
- }
-
- if ($element['data']['operants'][1]['type'] == 'column'
- && array_key_exists($element['data']['operants'][1]['data'], $fields_definition)
- ) {
- $type1 = $fields_definition[$element['data']['operants'][1]['data']]['type'];
- }
-
- $str .= '(';
- $str .= $this->getExpression($element['data']['operants'][0], $fields_definition, $type1);
- $str .= $this->getOperator($element['data']['operator']);
- $str .= $this->getExpression($element['data']['operants'][1], $fields_definition, $type0);
- $str .= ')';
- break;
- }
-
- return $str;
- }
-
- // }}}
- // {{{ getOperator()
-
- /**
- * Returns the matching SQL operator
- *
- * @param string $op parsed descriptive operator
- *
- * @return string matching SQL operator
- *
- * @access public
- * @static
- * @see MDB2_Schema::getExpression()
- */
- function getOperator($op)
- {
- switch ($op) {
- case 'PLUS':
- return ' + ';
- case 'MINUS':
- return ' - ';
- case 'TIMES':
- return ' * ';
- case 'DIVIDED':
- return ' / ';
- case 'EQUAL':
- return ' = ';
- case 'NOT EQUAL':
- return ' != ';
- case 'LESS THAN':
- return ' < ';
- case 'GREATER THAN':
- return ' > ';
- case 'LESS THAN OR EQUAL':
- return ' <= ';
- case 'GREATER THAN OR EQUAL':
- return ' >= ';
- default:
- return ' '.$op.' ';
- }
- }
-
- // }}}
- // {{{ getInstructionFields()
-
- /**
- * Walks the parsed DML instruction array, field by field,
- * storing them and their processed values inside a new array.
- *
- * @param array $instruction multi dimensional array that contains the
- * structure of the current DML instruction.
- * @param array $fields_definition multi dimensional array that contains the
- * definition for current table's fields
- *
- * @return array array of strings in the form 'field_name' => 'value'
- *
- * @access public
- * @static
- * @see MDB2_Schema::initializeTable()
- */
- function getInstructionFields($instruction, $fields_definition = array())
- {
- $fields = array();
- if (!empty($instruction['field']) && is_array($instruction['field'])) {
- foreach ($instruction['field'] as $field) {
- $field_name = $this->db->quoteIdentifier($field['name'], true);
-
- $fields[$field_name] = $this->getExpression($field['group'], $fields_definition);
- }
- }
- return $fields;
- }
-
- // }}}
- // {{{ getInstructionWhere()
-
- /**
- * Translates the parsed WHERE expression of a DML instruction
- * (array structure) to a SQL WHERE clause (string).
- *
- * @param array $instruction multi dimensional array that contains the
- * structure of the current DML instruction.
- * @param array $fields_definition multi dimensional array that contains the
- * definition for current table's fields.
- *
- * @return string SQL WHERE clause
- *
- * @access public
- * @static
- * @see MDB2_Schema::initializeTable()
- */
- function getInstructionWhere($instruction, $fields_definition = array())
- {
- $where = '';
- if (!empty($instruction['where'])) {
- $where = 'WHERE '.$this->getExpression($instruction['where'], $fields_definition);
- }
- return $where;
- }
-
- // }}}
- // {{{ createSequence()
-
- /**
- * Create a sequence
- *
- * @param string $sequence_name name of the sequence to be created
- * @param array $sequence multi dimensional array that contains the
- * structure and optional data of the table
- * @param bool $overwrite if the sequence should be overwritten if it already exists
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function createSequence($sequence_name, $sequence, $overwrite = false)
- {
- if (!$this->db->supports('sequences')) {
- $this->db->debug('Sequences are not supported', __FUNCTION__);
- return MDB2_OK;
- }
-
- $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE);
- $this->db->expectError($errorcodes);
- $sequences = $this->db->manager->listSequences();
- $this->db->popExpect();
- if (PEAR::isError($sequences)) {
- if (!MDB2::isError($sequences, $errorcodes)) {
- return $sequences;
- }
- } elseif (is_array($sequence) && in_array($sequence_name, $sequences)) {
- if (!$overwrite) {
- $this->db->debug('Sequence already exists: '.$sequence_name, __FUNCTION__);
- return MDB2_OK;
- }
-
- $result = $this->db->manager->dropSequence($sequence_name);
- if (PEAR::isError($result)) {
- return $result;
- }
- $this->db->debug('Overwritting sequence: '.$sequence_name, __FUNCTION__);
- }
-
- $start = 1;
- $field = '';
- if (!empty($sequence['on'])) {
- $table = $sequence['on']['table'];
- $field = $sequence['on']['field'];
-
- $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NOT_CAPABLE);
- $this->db->expectError($errorcodes);
- $tables = $this->db->manager->listTables();
- $this->db->popExpect();
- if (PEAR::isError($tables) && !MDB2::isError($tables, $errorcodes)) {
- return $tables;
- }
-
- if (!PEAR::isError($tables) && is_array($tables) && in_array($table, $tables)) {
- if ($this->db->supports('summary_functions')) {
- $query = "SELECT MAX($field) FROM ".$this->db->quoteIdentifier($table, true);
- } else {
- $query = "SELECT $field FROM ".$this->db->quoteIdentifier($table, true)." ORDER BY $field DESC";
- }
- $start = $this->db->queryOne($query, 'integer');
- if (PEAR::isError($start)) {
- return $start;
- }
- ++$start;
- } else {
- $this->warnings[] = 'Could not sync sequence: '.$sequence_name;
- }
- } elseif (!empty($sequence['start']) && is_numeric($sequence['start'])) {
- $start = $sequence['start'];
- $table = '';
- }
-
- $result = $this->db->manager->createSequence($sequence_name, $start);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ createDatabase()
-
- /**
- * Create a database space within which may be created database objects
- * like tables, indexes and sequences. The implementation of this function
- * is highly DBMS specific and may require special permissions to run
- * successfully. Consult the documentation or the DBMS drivers that you
- * use to be aware of eventual configuration requirements.
- *
- * @param array $database_definition multi dimensional array that contains the current definition
- * @param array $options an array of options to be passed to the
- * database specific driver version of
- * MDB2_Driver_Manager_Common::createTable().
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function createDatabase($database_definition, $options = array())
- {
- if (!isset($database_definition['name']) || !$database_definition['name']) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
- 'no valid database name specified');
- }
-
- $create = (isset($database_definition['create']) && $database_definition['create']);
- $overwrite = (isset($database_definition['overwrite']) && $database_definition['overwrite']);
-
- /**
- *
- * We need to clean up database name before any query to prevent
- * database driver from using a inexistent database
- *
- */
- $previous_database_name = $this->db->setDatabase('');
-
- // Lower / Upper case the db name if the portability deems so.
- if ($this->db->options['portability'] & MDB2_PORTABILITY_FIX_CASE) {
- $func = $this->db->options['field_case'] == CASE_LOWER ? 'strtolower' : 'strtoupper';
-
- $db_name = $func($database_definition['name']);
- } else {
- $db_name = $database_definition['name'];
- }
-
- if ($create) {
-
- $dbExists = $this->db->databaseExists($db_name);
- if (PEAR::isError($dbExists)) {
- return $dbExists;
- }
-
- if ($dbExists && $overwrite) {
- $this->db->expectError(MDB2_ERROR_CANNOT_DROP);
- $result = $this->db->manager->dropDatabase($db_name);
- $this->db->popExpect();
- if (PEAR::isError($result) && !MDB2::isError($result, MDB2_ERROR_CANNOT_DROP)) {
- return $result;
- }
- $dbExists = false;
- $this->db->debug('Overwritting database: ' . $db_name, __FUNCTION__);
- }
-
- $dbOptions = array();
- if (array_key_exists('charset', $database_definition)
- && !empty($database_definition['charset'])) {
- $dbOptions['charset'] = $database_definition['charset'];
- }
-
- if ($dbExists) {
- $this->db->debug('Database already exists: ' . $db_name, __FUNCTION__);
- if (!empty($dbOptions)) {
- $errorcodes = array(MDB2_ERROR_UNSUPPORTED, MDB2_ERROR_NO_PERMISSION);
- $this->db->expectError($errorcodes);
- $result = $this->db->manager->alterDatabase($db_name, $dbOptions);
- $this->db->popExpect();
- if (PEAR::isError($result) && !MDB2::isError($result, $errorcodes)) {
- return $result;
- }
- }
- $create = false;
- } else {
- $this->db->expectError(MDB2_ERROR_UNSUPPORTED);
- $result = $this->db->manager->createDatabase($db_name, $dbOptions);
- $this->db->popExpect();
- if (PEAR::isError($result) && !MDB2::isError($result, MDB2_ERROR_UNSUPPORTED)) {
- return $result;
- }
- $this->db->debug('Creating database: ' . $db_name, __FUNCTION__);
- }
- }
-
- $this->db->setDatabase($db_name);
- if (($support_transactions = $this->db->supports('transactions'))
- && PEAR::isError($result = $this->db->beginNestedTransaction())
- ) {
- return $result;
- }
-
- $created_objects = 0;
- if (isset($database_definition['tables'])
- && is_array($database_definition['tables'])
- ) {
- foreach ($database_definition['tables'] as $table_name => $table) {
- $result = $this->createTable($table_name, $table, $overwrite, $options);
- if (PEAR::isError($result)) {
- break;
- }
- $created_objects++;
- }
- }
- if (!PEAR::isError($result)
- && isset($database_definition['sequences'])
- && is_array($database_definition['sequences'])
- ) {
- foreach ($database_definition['sequences'] as $sequence_name => $sequence) {
- $result = $this->createSequence($sequence_name, $sequence, false, $overwrite);
-
- if (PEAR::isError($result)) {
- break;
- }
- $created_objects++;
- }
- }
-
- if ($support_transactions) {
- $res = $this->db->completeNestedTransaction();
- if (PEAR::isError($res)) {
- $result = $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
- 'Could not end transaction ('.
- $res->getMessage().' ('.$res->getUserinfo().'))');
- }
- } elseif (PEAR::isError($result) && $created_objects) {
- $result = $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
- 'the database was only partially created ('.
- $result->getMessage().' ('.$result->getUserinfo().'))');
- }
-
- $this->db->setDatabase($previous_database_name);
-
- if (PEAR::isError($result) && $create
- && PEAR::isError($result2 = $this->db->manager->dropDatabase($db_name))
- ) {
- if (!MDB2::isError($result2, MDB2_ERROR_UNSUPPORTED)) {
- return $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
- 'Could not drop the created database after unsuccessful creation attempt ('.
- $result2->getMessage().' ('.$result2->getUserinfo().'))');
- }
- }
-
- return $result;
- }
-
- // }}}
- // {{{ compareDefinitions()
-
- /**
- * Compare a previous definition with the currently parsed definition
- *
- * @param array $current_definition multi dimensional array that contains the current definition
- * @param array $previous_definition multi dimensional array that contains the previous definition
- *
- * @return array|MDB2_Error array of changes on success, or a error object
- * @access public
- */
- function compareDefinitions($current_definition, $previous_definition)
- {
- $changes = array();
-
- if (!empty($current_definition['tables']) && is_array($current_definition['tables'])) {
- $changes['tables'] = $defined_tables = array();
- foreach ($current_definition['tables'] as $table_name => $table) {
- $previous_tables = array();
- if (!empty($previous_definition) && is_array($previous_definition)) {
- $previous_tables = $previous_definition['tables'];
- }
- $change = $this->compareTableDefinitions($table_name, $table, $previous_tables, $defined_tables);
- if (PEAR::isError($change)) {
- return $change;
- }
- if (!empty($change)) {
- $changes['tables'] = MDB2_Schema::arrayMergeClobber($changes['tables'], $change);
- }
- }
-
- if (!empty($previous_definition['tables'])
- && is_array($previous_definition['tables'])) {
- foreach ($previous_definition['tables'] as $table_name => $table) {
- if (empty($defined_tables[$table_name])) {
- $changes['tables']['remove'][$table_name] = true;
- }
- }
- }
- }
- if (!empty($current_definition['sequences']) && is_array($current_definition['sequences'])) {
- $changes['sequences'] = $defined_sequences = array();
- foreach ($current_definition['sequences'] as $sequence_name => $sequence) {
- $previous_sequences = array();
- if (!empty($previous_definition) && is_array($previous_definition)) {
- $previous_sequences = $previous_definition['sequences'];
- }
-
- $change = $this->compareSequenceDefinitions($sequence_name,
- $sequence,
- $previous_sequences,
- $defined_sequences);
- if (PEAR::isError($change)) {
- return $change;
- }
- if (!empty($change)) {
- $changes['sequences'] = MDB2_Schema::arrayMergeClobber($changes['sequences'], $change);
- }
- }
- if (!empty($previous_definition['sequences']) && is_array($previous_definition['sequences'])) {
- foreach ($previous_definition['sequences'] as $sequence_name => $sequence) {
- if (empty($defined_sequences[$sequence_name])) {
- $changes['sequences']['remove'][$sequence_name] = true;
- }
- }
- }
- }
- return $changes;
- }
-
- // }}}
- // {{{ compareTableFieldsDefinitions()
-
- /**
- * Compare a previous definition with the currently parsed definition
- *
- * @param string $table_name name of the table
- * @param array $current_definition multi dimensional array that contains the current definition
- * @param array $previous_definition multi dimensional array that contains the previous definition
- *
- * @return array|MDB2_Error array of changes on success, or a error object
- * @access public
- */
- function compareTableFieldsDefinitions($table_name, $current_definition,
- $previous_definition)
- {
- $changes = $defined_fields = array();
-
- if (is_array($current_definition)) {
- foreach ($current_definition as $field_name => $field) {
- $was_field_name = $field['was'];
- if (!empty($previous_definition[$field_name])
- && (
- (isset($previous_definition[$field_name]['was'])
- && $previous_definition[$field_name]['was'] == $was_field_name)
- || !isset($previous_definition[$was_field_name])
- )) {
- $was_field_name = $field_name;
- }
-
- if (!empty($previous_definition[$was_field_name])) {
- if ($was_field_name != $field_name) {
- $changes['rename'][$was_field_name] = array('name' => $field_name, 'definition' => $field);
- }
-
- if (!empty($defined_fields[$was_field_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
- 'the field "'.$was_field_name.
- '" was specified for more than one field of table');
- }
-
- $defined_fields[$was_field_name] = true;
-
- $change = $this->db->compareDefinition($field, $previous_definition[$was_field_name]);
- if (PEAR::isError($change)) {
- return $change;
- }
-
- if (!empty($change)) {
- if (array_key_exists('default', $change)
- && $change['default']
- && !array_key_exists('default', $field)) {
- $field['default'] = null;
- }
-
- $change['definition'] = $field;
-
- $changes['change'][$field_name] = $change;
- }
- } else {
- if ($field_name != $was_field_name) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
- 'it was specified a previous field name ("'.
- $was_field_name.'") for field "'.$field_name.'" of table "'.
- $table_name.'" that does not exist');
- }
-
- $changes['add'][$field_name] = $field;
- }
- }
- }
-
- if (isset($previous_definition) && is_array($previous_definition)) {
- foreach ($previous_definition as $field_previous_name => $field_previous) {
- if (empty($defined_fields[$field_previous_name])) {
- $changes['remove'][$field_previous_name] = true;
- }
- }
- }
-
- return $changes;
- }
-
- // }}}
- // {{{ compareTableIndexesDefinitions()
-
- /**
- * Compare a previous definition with the currently parsed definition
- *
- * @param string $table_name name of the table
- * @param array $current_definition multi dimensional array that contains the current definition
- * @param array $previous_definition multi dimensional array that contains the previous definition
- *
- * @return array|MDB2_Error array of changes on success, or a error object
- * @access public
- */
- function compareTableIndexesDefinitions($table_name, $current_definition,
- $previous_definition)
- {
- $changes = $defined_indexes = array();
-
- if (is_array($current_definition)) {
- foreach ($current_definition as $index_name => $index) {
- $was_index_name = $index['was'];
- if (!empty($previous_definition[$index_name])
- && isset($previous_definition[$index_name]['was'])
- && $previous_definition[$index_name]['was'] == $was_index_name
- ) {
- $was_index_name = $index_name;
- }
- if (!empty($previous_definition[$was_index_name])) {
- $change = array();
- if ($was_index_name != $index_name) {
- $change['name'] = $was_index_name;
- }
-
- if (!empty($defined_indexes[$was_index_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
- 'the index "'.$was_index_name.'" was specified for'.
- ' more than one index of table "'.$table_name.'"');
- }
- $defined_indexes[$was_index_name] = true;
-
- $previous_unique = array_key_exists('unique', $previous_definition[$was_index_name])
- ? $previous_definition[$was_index_name]['unique'] : false;
-
- $unique = array_key_exists('unique', $index) ? $index['unique'] : false;
- if ($previous_unique != $unique) {
- $change['unique'] = $unique;
- }
-
- $previous_primary = array_key_exists('primary', $previous_definition[$was_index_name])
- ? $previous_definition[$was_index_name]['primary'] : false;
-
- $primary = array_key_exists('primary', $index) ? $index['primary'] : false;
- if ($previous_primary != $primary) {
- $change['primary'] = $primary;
- }
-
- $defined_fields = array();
- $previous_fields = $previous_definition[$was_index_name]['fields'];
- if (!empty($index['fields']) && is_array($index['fields'])) {
- foreach ($index['fields'] as $field_name => $field) {
- if (!empty($previous_fields[$field_name])) {
- $defined_fields[$field_name] = true;
-
- $previous_sorting = array_key_exists('sorting', $previous_fields[$field_name])
- ? $previous_fields[$field_name]['sorting'] : '';
-
- $sorting = array_key_exists('sorting', $field) ? $field['sorting'] : '';
- if ($previous_sorting != $sorting) {
- $change['change'] = true;
- }
- } else {
- $change['change'] = true;
- }
- }
- }
- if (isset($previous_fields) && is_array($previous_fields)) {
- foreach ($previous_fields as $field_name => $field) {
- if (empty($defined_fields[$field_name])) {
- $change['change'] = true;
- }
- }
- }
- if (!empty($change)) {
- $changes['change'][$index_name] = $current_definition[$index_name];
- }
- } else {
- if ($index_name != $was_index_name) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
- 'it was specified a previous index name ("'.$was_index_name.
- ') for index "'.$index_name.'" of table "'.$table_name.'" that does not exist');
- }
- $changes['add'][$index_name] = $current_definition[$index_name];
- }
- }
- }
- foreach ($previous_definition as $index_previous_name => $index_previous) {
- if (empty($defined_indexes[$index_previous_name])) {
- $changes['remove'][$index_previous_name] = $index_previous;
- }
- }
- return $changes;
- }
-
- // }}}
- // {{{ compareTableDefinitions()
-
- /**
- * Compare a previous definition with the currently parsed definition
- *
- * @param string $table_name name of the table
- * @param array $current_definition multi dimensional array that contains the current definition
- * @param array $previous_definition multi dimensional array that contains the previous definition
- * @param array &$defined_tables table names in the schema
- *
- * @return array|MDB2_Error array of changes on success, or a error object
- * @access public
- */
- function compareTableDefinitions($table_name, $current_definition,
- $previous_definition, &$defined_tables)
- {
- $changes = array();
-
- if (is_array($current_definition)) {
- $was_table_name = $table_name;
- if (!empty($current_definition['was'])) {
- $was_table_name = $current_definition['was'];
- }
- if (!empty($previous_definition[$was_table_name])) {
- $changes['change'][$was_table_name] = array();
- if ($was_table_name != $table_name) {
- $changes['change'][$was_table_name] = array('name' => $table_name);
- }
- if (!empty($defined_tables[$was_table_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
- 'the table "'.$was_table_name.
- '" was specified for more than one table of the database');
- }
- $defined_tables[$was_table_name] = true;
- if (!empty($current_definition['fields']) && is_array($current_definition['fields'])) {
- $previous_fields = array();
- if (isset($previous_definition[$was_table_name]['fields'])
- && is_array($previous_definition[$was_table_name]['fields'])) {
- $previous_fields = $previous_definition[$was_table_name]['fields'];
- }
-
- $change = $this->compareTableFieldsDefinitions($table_name,
- $current_definition['fields'],
- $previous_fields);
-
- if (PEAR::isError($change)) {
- return $change;
- }
- if (!empty($change)) {
- $changes['change'][$was_table_name] =
- MDB2_Schema::arrayMergeClobber($changes['change'][$was_table_name], $change);
- }
- }
- if (!empty($current_definition['indexes']) && is_array($current_definition['indexes'])) {
- $previous_indexes = array();
- if (isset($previous_definition[$was_table_name]['indexes'])
- && is_array($previous_definition[$was_table_name]['indexes'])) {
- $previous_indexes = $previous_definition[$was_table_name]['indexes'];
- }
- $change = $this->compareTableIndexesDefinitions($table_name,
- $current_definition['indexes'],
- $previous_indexes);
-
- if (PEAR::isError($change)) {
- return $change;
- }
- if (!empty($change)) {
- $changes['change'][$was_table_name]['indexes'] = $change;
- }
- }
- if (empty($changes['change'][$was_table_name])) {
- unset($changes['change'][$was_table_name]);
- }
- if (empty($changes['change'])) {
- unset($changes['change']);
- }
- } else {
- if ($table_name != $was_table_name) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
- 'it was specified a previous table name ("'.$was_table_name.
- '") for table "'.$table_name.'" that does not exist');
- }
- $changes['add'][$table_name] = true;
- }
- }
-
- return $changes;
- }
-
- // }}}
- // {{{ compareSequenceDefinitions()
-
- /**
- * Compare a previous definition with the currently parsed definition
- *
- * @param string $sequence_name name of the sequence
- * @param array $current_definition multi dimensional array that contains the current definition
- * @param array $previous_definition multi dimensional array that contains the previous definition
- * @param array &$defined_sequences names in the schema
- *
- * @return array|MDB2_Error array of changes on success, or a error object
- * @access public
- */
- function compareSequenceDefinitions($sequence_name, $current_definition,
- $previous_definition, &$defined_sequences)
- {
- $changes = array();
-
- if (is_array($current_definition)) {
- $was_sequence_name = $sequence_name;
- if (!empty($previous_definition[$sequence_name])
- && isset($previous_definition[$sequence_name]['was'])
- && $previous_definition[$sequence_name]['was'] == $was_sequence_name
- ) {
- $was_sequence_name = $sequence_name;
- } elseif (!empty($current_definition['was'])) {
- $was_sequence_name = $current_definition['was'];
- }
- if (!empty($previous_definition[$was_sequence_name])) {
- if ($was_sequence_name != $sequence_name) {
- $changes['change'][$was_sequence_name]['name'] = $sequence_name;
- }
-
- if (!empty($defined_sequences[$was_sequence_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
- 'the sequence "'.$was_sequence_name.'" was specified as base'.
- ' of more than of sequence of the database');
- }
-
- $defined_sequences[$was_sequence_name] = true;
-
- $change = array();
- if (!empty($current_definition['start'])
- && isset($previous_definition[$was_sequence_name]['start'])
- && $current_definition['start'] != $previous_definition[$was_sequence_name]['start']
- ) {
- $change['start'] = $previous_definition[$sequence_name]['start'];
- }
- if (isset($current_definition['on']['table'])
- && isset($previous_definition[$was_sequence_name]['on']['table'])
- && $current_definition['on']['table'] != $previous_definition[$was_sequence_name]['on']['table']
- && isset($current_definition['on']['field'])
- && isset($previous_definition[$was_sequence_name]['on']['field'])
- && $current_definition['on']['field'] != $previous_definition[$was_sequence_name]['on']['field']
- ) {
- $change['on'] = $current_definition['on'];
- }
- if (!empty($change)) {
- $changes['change'][$was_sequence_name][$sequence_name] = $change;
- }
- } else {
- if ($sequence_name != $was_sequence_name) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_INVALID, null, null,
- 'it was specified a previous sequence name ("'.$was_sequence_name.
- '") for sequence "'.$sequence_name.'" that does not exist');
- }
- $changes['add'][$sequence_name] = true;
- }
- }
- return $changes;
- }
- // }}}
- // {{{ verifyAlterDatabase()
-
- /**
- * Verify that the changes requested are supported
- *
- * @param array $changes associative array that contains the definition of the changes
- * that are meant to be applied to the database structure.
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function verifyAlterDatabase($changes)
- {
- if (!empty($changes['tables']['change']) && is_array($changes['tables']['change'])) {
- foreach ($changes['tables']['change'] as $table_name => $table) {
- if (!empty($table['indexes']) && is_array($table['indexes'])) {
- if (!$this->db->supports('indexes')) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null,
- 'indexes are not supported');
- }
- $table_changes = count($table['indexes']);
- if (!empty($table['indexes']['add'])) {
- $table_changes--;
- }
- if (!empty($table['indexes']['remove'])) {
- $table_changes--;
- }
- if (!empty($table['indexes']['change'])) {
- $table_changes--;
- }
- if ($table_changes) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null,
- 'index alteration not yet supported: '.implode(', ', array_keys($table['indexes'])));
- }
- }
- unset($table['indexes']);
- $result = $this->db->manager->alterTable($table_name, $table, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- if (!empty($changes['sequences']) && is_array($changes['sequences'])) {
- if (!$this->db->supports('sequences')) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null,
- 'sequences are not supported');
- }
- $sequence_changes = count($changes['sequences']);
- if (!empty($changes['sequences']['add'])) {
- $sequence_changes--;
- }
- if (!empty($changes['sequences']['remove'])) {
- $sequence_changes--;
- }
- if (!empty($changes['sequences']['change'])) {
- $sequence_changes--;
- }
- if ($sequence_changes) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null,
- 'sequence alteration not yet supported: '.implode(', ', array_keys($changes['sequences'])));
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ alterDatabaseIndexes()
-
- /**
- * Execute the necessary actions to implement the requested changes
- * in the indexes inside a database structure.
- *
- * @param string $table_name name of the table
- * @param array $changes associative array that contains the definition of the changes
- * that are meant to be applied to the database structure.
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function alterDatabaseIndexes($table_name, $changes)
- {
- $alterations = 0;
- if (empty($changes)) {
- return $alterations;
- }
-
- if (!empty($changes['remove']) && is_array($changes['remove'])) {
- foreach ($changes['remove'] as $index_name => $index) {
- $this->db->expectError(MDB2_ERROR_NOT_FOUND);
- if (!empty($index['primary']) || !empty($index['unique'])) {
- $result = $this->db->manager->dropConstraint($table_name, $index_name, !empty($index['primary']));
- } else {
- $result = $this->db->manager->dropIndex($table_name, $index_name);
- }
- $this->db->popExpect();
- if (PEAR::isError($result) && !MDB2::isError($result, MDB2_ERROR_NOT_FOUND)) {
- return $result;
- }
- $alterations++;
- }
- }
- if (!empty($changes['change']) && is_array($changes['change'])) {
- foreach ($changes['change'] as $index_name => $index) {
- /**
- * Drop existing index/constraint first.
- * Since $changes doesn't tell us whether it's an index or a constraint before the change,
- * we have to find out and call the appropriate method.
- */
- if (in_array($index_name, $this->db->manager->listTableIndexes($table_name))) {
- $result = $this->db->manager->dropIndex($table_name, $index_name);
- } elseif (in_array($index_name, $this->db->manager->listTableConstraints($table_name))) {
- $result = $this->db->manager->dropConstraint($table_name, $index_name);
- }
- if (!empty($result) && PEAR::isError($result)) {
- return $result;
- }
-
- if (!empty($index['primary']) || !empty($index['unique'])) {
- $result = $this->db->manager->createConstraint($table_name, $index_name, $index);
- } else {
- $result = $this->db->manager->createIndex($table_name, $index_name, $index);
- }
- if (PEAR::isError($result)) {
- return $result;
- }
- $alterations++;
- }
- }
- if (!empty($changes['add']) && is_array($changes['add'])) {
- foreach ($changes['add'] as $index_name => $index) {
- if (!empty($index['primary']) || !empty($index['unique'])) {
- $result = $this->db->manager->createConstraint($table_name, $index_name, $index);
- } else {
- $result = $this->db->manager->createIndex($table_name, $index_name, $index);
- }
- if (PEAR::isError($result)) {
- return $result;
- }
- $alterations++;
- }
- }
-
- return $alterations;
- }
-
- // }}}
- // {{{ alterDatabaseTables()
-
- /**
- * Execute the necessary actions to implement the requested changes
- * in the tables inside a database structure.
- *
- * @param array $current_definition multi dimensional array that contains the current definition
- * @param array $previous_definition multi dimensional array that contains the previous definition
- * @param array $changes associative array that contains the definition of the changes
- * that are meant to be applied to the database structure.
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function alterDatabaseTables($current_definition, $previous_definition, $changes)
- {
- /* FIXME: tables marked to be added are initialized by createTable(), others don't */
- $alterations = 0;
- if (empty($changes)) {
- return $alterations;
- }
-
- if (!empty($changes['add']) && is_array($changes['add'])) {
- foreach ($changes['add'] as $table_name => $table) {
- $result = $this->createTable($table_name, $current_definition[$table_name]);
- if (PEAR::isError($result)) {
- return $result;
- }
- $alterations++;
- }
- }
-
- if ($this->options['drop_missing_tables']
- && !empty($changes['remove'])
- && is_array($changes['remove'])) {
- foreach ($changes['remove'] as $table_name => $table) {
- $result = $this->db->manager->dropTable($table_name);
- if (PEAR::isError($result)) {
- return $result;
- }
- $alterations++;
- }
- }
-
- if (!empty($changes['change']) && is_array($changes['change'])) {
- foreach ($changes['change'] as $table_name => $table) {
- $indexes = array();
- if (!empty($table['indexes'])) {
- $indexes = $table['indexes'];
- unset($table['indexes']);
- }
- if (!empty($indexes['remove'])) {
- $result = $this->alterDatabaseIndexes($table_name, array('remove' => $indexes['remove']));
- if (PEAR::isError($result)) {
- return $result;
- }
- unset($indexes['remove']);
- $alterations += $result;
- }
- $result = $this->db->manager->alterTable($table_name, $table, false);
- if (PEAR::isError($result)) {
- return $result;
- }
- $alterations++;
-
- // table may be renamed at this point
- if (!empty($table['name'])) {
- $table_name = $table['name'];
- }
-
- if (!empty($indexes)) {
- $result = $this->alterDatabaseIndexes($table_name, $indexes);
- if (PEAR::isError($result)) {
- return $result;
- }
- $alterations += $result;
- }
- }
- }
-
- return $alterations;
- }
-
- // }}}
- // {{{ alterDatabaseSequences()
-
- /**
- * Execute the necessary actions to implement the requested changes
- * in the sequences inside a database structure.
- *
- * @param array $current_definition multi dimensional array that contains the current definition
- * @param array $previous_definition multi dimensional array that contains the previous definition
- * @param array $changes associative array that contains the definition of the changes
- * that are meant to be applied to the database structure.
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function alterDatabaseSequences($current_definition, $previous_definition, $changes)
- {
- $alterations = 0;
- if (empty($changes)) {
- return $alterations;
- }
-
- if (!empty($changes['add']) && is_array($changes['add'])) {
- foreach ($changes['add'] as $sequence_name => $sequence) {
- $result = $this->createSequence($sequence_name, $current_definition[$sequence_name]);
- if (PEAR::isError($result)) {
- return $result;
- }
- $alterations++;
- }
- }
-
- if (!empty($changes['remove']) && is_array($changes['remove'])) {
- foreach ($changes['remove'] as $sequence_name => $sequence) {
- $result = $this->db->manager->dropSequence($sequence_name);
- if (PEAR::isError($result)) {
- return $result;
- }
- $alterations++;
- }
- }
-
- if (!empty($changes['change']) && is_array($changes['change'])) {
- foreach ($changes['change'] as $sequence_name => $sequence) {
- $result = $this->db->manager->dropSequence($previous_definition[$sequence_name]['was']);
- if (PEAR::isError($result)) {
- return $result;
- }
- $result = $this->createSequence($sequence_name, $sequence);
- if (PEAR::isError($result)) {
- return $result;
- }
- $alterations++;
- }
- }
-
- return $alterations;
- }
-
- // }}}
- // {{{ alterDatabase()
-
- /**
- * Execute the necessary actions to implement the requested changes
- * in a database structure.
- *
- * @param array $current_definition multi dimensional array that contains the current definition
- * @param array $previous_definition multi dimensional array that contains the previous definition
- * @param array $changes associative array that contains the definition of the changes
- * that are meant to be applied to the database structure.
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function alterDatabase($current_definition, $previous_definition, $changes)
- {
- $alterations = 0;
- if (empty($changes)) {
- return $alterations;
- }
-
- $result = $this->verifyAlterDatabase($changes);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if (!empty($current_definition['name'])) {
- $previous_database_name = $this->db->setDatabase($current_definition['name']);
- }
-
- if (($support_transactions = $this->db->supports('transactions'))
- && PEAR::isError($result = $this->db->beginNestedTransaction())
- ) {
- return $result;
- }
-
- if (!empty($changes['tables']) && !empty($current_definition['tables'])) {
- $current_tables = isset($current_definition['tables']) ? $current_definition['tables'] : array();
- $previous_tables = isset($previous_definition['tables']) ? $previous_definition['tables'] : array();
-
- $result = $this->alterDatabaseTables($current_tables, $previous_tables, $changes['tables']);
- if (is_numeric($result)) {
- $alterations += $result;
- }
- }
-
- if (!PEAR::isError($result) && !empty($changes['sequences'])) {
- $current_sequences = isset($current_definition['sequences']) ? $current_definition['sequences'] : array();
- $previous_sequences = isset($previous_definition['sequences']) ? $previous_definition['sequences'] : array();
-
- $result = $this->alterDatabaseSequences($current_sequences, $previous_sequences, $changes['sequences']);
- if (is_numeric($result)) {
- $alterations += $result;
- }
- }
-
- if ($support_transactions) {
- $res = $this->db->completeNestedTransaction();
- if (PEAR::isError($res)) {
- $result = $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
- 'Could not end transaction ('.
- $res->getMessage().' ('.$res->getUserinfo().'))');
- }
- } elseif (PEAR::isError($result) && $alterations) {
- $result = $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
- 'the requested database alterations were only partially implemented ('.
- $result->getMessage().' ('.$result->getUserinfo().'))');
- }
-
- if (isset($previous_database_name)) {
- $this->db->setDatabase($previous_database_name);
- }
- return $result;
- }
-
- // }}}
- // {{{ dumpDatabaseChanges()
-
- /**
- * Dump the changes between two database definitions.
- *
- * @param array $changes associative array that specifies the list of database
- * definitions changes as returned by the _compareDefinitions
- * manager class function.
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function dumpDatabaseChanges($changes)
- {
- if (!empty($changes['tables'])) {
- if (!empty($changes['tables']['add']) && is_array($changes['tables']['add'])) {
- foreach ($changes['tables']['add'] as $table_name => $table) {
- $this->db->debug("$table_name:", __FUNCTION__);
- $this->db->debug("\tAdded table '$table_name'", __FUNCTION__);
- }
- }
-
- if (!empty($changes['tables']['remove']) && is_array($changes['tables']['remove'])) {
- if ($this->options['drop_missing_tables']) {
- foreach ($changes['tables']['remove'] as $table_name => $table) {
- $this->db->debug("$table_name:", __FUNCTION__);
- $this->db->debug("\tRemoved table '$table_name'", __FUNCTION__);
- }
- } else {
- foreach ($changes['tables']['remove'] as $table_name => $table) {
- $this->db->debug("\tObsolete table '$table_name' left as is", __FUNCTION__);
- }
- }
- }
-
- if (!empty($changes['tables']['change']) && is_array($changes['tables']['change'])) {
- foreach ($changes['tables']['change'] as $table_name => $table) {
- if (array_key_exists('name', $table)) {
- $this->db->debug("\tRenamed table '$table_name' to '".$table['name']."'", __FUNCTION__);
- }
- if (!empty($table['add']) && is_array($table['add'])) {
- foreach ($table['add'] as $field_name => $field) {
- $this->db->debug("\tAdded field '".$field_name."'", __FUNCTION__);
- }
- }
- if (!empty($table['remove']) && is_array($table['remove'])) {
- foreach ($table['remove'] as $field_name => $field) {
- $this->db->debug("\tRemoved field '".$field_name."'", __FUNCTION__);
- }
- }
- if (!empty($table['rename']) && is_array($table['rename'])) {
- foreach ($table['rename'] as $field_name => $field) {
- $this->db->debug("\tRenamed field '".$field_name."' to '".$field['name']."'", __FUNCTION__);
- }
- }
- if (!empty($table['change']) && is_array($table['change'])) {
- foreach ($table['change'] as $field_name => $field) {
- $field = $field['definition'];
- if (array_key_exists('type', $field)) {
- $this->db->debug("\tChanged field '$field_name' type to '".$field['type']."'", __FUNCTION__);
- }
-
- if (array_key_exists('unsigned', $field)) {
- $this->db->debug("\tChanged field '$field_name' type to '".
- (!empty($field['unsigned']) && $field['unsigned'] ? '' : 'not ')."unsigned'",
- __FUNCTION__);
- }
-
- if (array_key_exists('length', $field)) {
- $this->db->debug("\tChanged field '$field_name' length to '".
- (!empty($field['length']) ? $field['length']: 'no length')."'", __FUNCTION__);
- }
- if (array_key_exists('default', $field)) {
- $this->db->debug("\tChanged field '$field_name' default to ".
- (isset($field['default']) ? "'".$field['default']."'" : 'NULL'), __FUNCTION__);
- }
-
- if (array_key_exists('notnull', $field)) {
- $this->db->debug("\tChanged field '$field_name' notnull to ".
- (!empty($field['notnull']) && $field['notnull'] ? 'true' : 'false'),
- __FUNCTION__);
- }
- }
- }
- if (!empty($table['indexes']) && is_array($table['indexes'])) {
- if (!empty($table['indexes']['add']) && is_array($table['indexes']['add'])) {
- foreach ($table['indexes']['add'] as $index_name => $index) {
- $this->db->debug("\tAdded index '".$index_name.
- "' of table '$table_name'", __FUNCTION__);
- }
- }
- if (!empty($table['indexes']['remove']) && is_array($table['indexes']['remove'])) {
- foreach ($table['indexes']['remove'] as $index_name => $index) {
- $this->db->debug("\tRemoved index '".$index_name.
- "' of table '$table_name'", __FUNCTION__);
- }
- }
- if (!empty($table['indexes']['change']) && is_array($table['indexes']['change'])) {
- foreach ($table['indexes']['change'] as $index_name => $index) {
- if (array_key_exists('name', $index)) {
- $this->db->debug("\tRenamed index '".$index_name."' to '".$index['name'].
- "' on table '$table_name'", __FUNCTION__);
- }
- if (array_key_exists('unique', $index)) {
- $this->db->debug("\tChanged index '".$index_name."' unique to '".
- !empty($index['unique'])."' on table '$table_name'", __FUNCTION__);
- }
- if (array_key_exists('primary', $index)) {
- $this->db->debug("\tChanged index '".$index_name."' primary to '".
- !empty($index['primary'])."' on table '$table_name'", __FUNCTION__);
- }
- if (array_key_exists('change', $index)) {
- $this->db->debug("\tChanged index '".$index_name.
- "' on table '$table_name'", __FUNCTION__);
- }
- }
- }
- }
- }
- }
- }
- if (!empty($changes['sequences'])) {
- if (!empty($changes['sequences']['add']) && is_array($changes['sequences']['add'])) {
- foreach ($changes['sequences']['add'] as $sequence_name => $sequence) {
- $this->db->debug("$sequence_name:", __FUNCTION__);
- $this->db->debug("\tAdded sequence '$sequence_name'", __FUNCTION__);
- }
- }
- if (!empty($changes['sequences']['remove']) && is_array($changes['sequences']['remove'])) {
- foreach ($changes['sequences']['remove'] as $sequence_name => $sequence) {
- $this->db->debug("$sequence_name:", __FUNCTION__);
- $this->db->debug("\tAdded sequence '$sequence_name'", __FUNCTION__);
- }
- }
- if (!empty($changes['sequences']['change']) && is_array($changes['sequences']['change'])) {
- foreach ($changes['sequences']['change'] as $sequence_name => $sequence) {
- if (array_key_exists('name', $sequence)) {
- $this->db->debug("\tRenamed sequence '$sequence_name' to '".
- $sequence['name']."'", __FUNCTION__);
- }
- if (!empty($sequence['change']) && is_array($sequence['change'])) {
- foreach ($sequence['change'] as $sequence_name => $sequence) {
- if (array_key_exists('start', $sequence)) {
- $this->db->debug("\tChanged sequence '$sequence_name' start to '".
- $sequence['start']."'", __FUNCTION__);
- }
- }
- }
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ dumpDatabase()
-
- /**
- * Dump a previously parsed database structure in the Metabase schema
- * XML based format suitable for the Metabase parser. This function
- * may optionally dump the database definition with initialization
- * commands that specify the data that is currently present in the tables.
- *
- * @param array $database_definition multi dimensional array that contains the current definition
- * @param array $arguments associative array that takes pairs of tag
- * names and values that define dump options.
- * <pre>array (
- * 'output_mode' => String
- * 'file' : dump into a file
- * default: dump using a function
- * 'output' => String
- * depending on the 'Output_Mode'
- * name of the file
- * name of the function
- * 'end_of_line' => String
- * end of line delimiter that should be used
- * default: "\n"
- * );</pre>
- * @param int $dump Int that determines what data to dump
- * + MDB2_SCHEMA_DUMP_ALL : the entire db
- * + MDB2_SCHEMA_DUMP_STRUCTURE : only the structure of the db
- * + MDB2_SCHEMA_DUMP_CONTENT : only the content of the db
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function dumpDatabase($database_definition, $arguments, $dump = MDB2_SCHEMA_DUMP_ALL)
- {
- $class_name = $this->options['writer'];
-
- $result = MDB2::loadClass($class_name, $this->db->getOption('debug'));
- if (PEAR::isError($result)) {
- return $result;
- }
-
- // get initialization data
- if (isset($database_definition['tables']) && is_array($database_definition['tables'])
- && $dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_CONTENT
- ) {
- foreach ($database_definition['tables'] as $table_name => $table) {
- $fields = array();
- $fieldsq = array();
- foreach ($table['fields'] as $field_name => $field) {
- $fields[$field_name] = $field['type'];
-
- $fieldsq[] = $this->db->quoteIdentifier($field_name, true);
- }
-
- $query = 'SELECT '.implode(', ', $fieldsq).' FROM ';
- $query .= $this->db->quoteIdentifier($table_name, true);
-
- $data = $this->db->queryAll($query, $fields, MDB2_FETCHMODE_ASSOC);
-
- if (PEAR::isError($data)) {
- return $data;
- }
-
- if (!empty($data)) {
- $initialization = array();
- $lob_buffer_length = $this->db->getOption('lob_buffer_length');
- foreach ($data as $row) {
- $rows = array();
- foreach ($row as $key => $lob) {
- if (is_resource($lob)) {
- $value = '';
- while (!feof($lob)) {
- $value .= fread($lob, $lob_buffer_length);
- }
- $row[$key] = $value;
- }
- $rows[] = array('name' => $key, 'group' => array('type' => 'value', 'data' => $row[$key]));
- }
- $initialization[] = array('type' => 'insert', 'data' => array('field' => $rows));
- }
- $database_definition['tables'][$table_name]['initialization'] = $initialization;
- }
- }
- }
-
- $writer = new $class_name($this->options['valid_types']);
- return $writer->dumpDatabase($database_definition, $arguments, $dump);
- }
-
- // }}}
- // {{{ writeInitialization()
-
- /**
- * Write initialization and sequences
- *
- * @param string|array $data data file or data array
- * @param string|array $structure structure file or array
- * @param array $variables associative array that is passed to the argument
- * of the same name to the parseDatabaseDefinitionFile function. (there third
- * param)
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function writeInitialization($data, $structure = false, $variables = array())
- {
- if ($structure) {
- $structure = $this->parseDatabaseDefinition($structure, false, $variables);
- if (PEAR::isError($structure)) {
- return $structure;
- }
- }
-
- $data = $this->parseDatabaseDefinition($data, false, $variables, false, $structure);
- if (PEAR::isError($data)) {
- return $data;
- }
-
- $previous_database_name = null;
- if (!empty($data['name'])) {
- $previous_database_name = $this->db->setDatabase($data['name']);
- } elseif (!empty($structure['name'])) {
- $previous_database_name = $this->db->setDatabase($structure['name']);
- }
-
- if (!empty($data['tables']) && is_array($data['tables'])) {
- foreach ($data['tables'] as $table_name => $table) {
- if (empty($table['initialization'])) {
- continue;
- }
- $result = $this->initializeTable($table_name, $table);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
-
- if (!empty($structure['sequences']) && is_array($structure['sequences'])) {
- foreach ($structure['sequences'] as $sequence_name => $sequence) {
- if (isset($data['sequences'][$sequence_name])
- || !isset($sequence['on']['table'])
- || !isset($data['tables'][$sequence['on']['table']])
- ) {
- continue;
- }
- $result = $this->createSequence($sequence_name, $sequence, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- if (!empty($data['sequences']) && is_array($data['sequences'])) {
- foreach ($data['sequences'] as $sequence_name => $sequence) {
- $result = $this->createSequence($sequence_name, $sequence, true);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
-
- if (isset($previous_database_name)) {
- $this->db->setDatabase($previous_database_name);
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ updateDatabase()
-
- /**
- * Compare the correspondent files of two versions of a database schema
- * definition: the previously installed and the one that defines the schema
- * that is meant to update the database.
- * If the specified previous definition file does not exist, this function
- * will create the database from the definition specified in the current
- * schema file.
- * If both files exist, the function assumes that the database was previously
- * installed based on the previous schema file and will update it by just
- * applying the changes.
- * If this function succeeds, the contents of the current schema file are
- * copied to replace the previous schema file contents. Any subsequent schema
- * changes should only be done on the file specified by the $current_schema_file
- * to let this function make a consistent evaluation of the exact changes that
- * need to be applied.
- *
- * @param string|array $current_schema filename or array of the updated database schema definition.
- * @param string|array $previous_schema filename or array of the previously installed database schema definition.
- * @param array $variables associative array that is passed to the argument of the same
- * name to the parseDatabaseDefinitionFile function. (there third param)
- * @param bool $disable_query determines if the disable_query option should be set to true
- * for the alterDatabase() or createDatabase() call
- * @param bool $overwrite_old_schema_file Overwrite?
- *
- * @return bool|MDB2_Error MDB2_OK or error object
- * @access public
- */
- function updateDatabase($current_schema, $previous_schema = false,
- $variables = array(), $disable_query = false,
- $overwrite_old_schema_file = false)
- {
- $current_definition = $this->parseDatabaseDefinition($current_schema, false, $variables,
- $this->options['fail_on_invalid_names']);
-
- if (PEAR::isError($current_definition)) {
- return $current_definition;
- }
-
- $previous_definition = false;
- if ($previous_schema) {
- $previous_definition = $this->parseDatabaseDefinition($previous_schema, true, $variables,
- $this->options['fail_on_invalid_names']);
- if (PEAR::isError($previous_definition)) {
- return $previous_definition;
- }
- }
-
- if ($previous_definition) {
- $dbExists = $this->db->databaseExists($current_definition['name']);
- if (PEAR::isError($dbExists)) {
- return $dbExists;
- }
-
- if (!$dbExists) {
- return $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
- 'database to update does not exist: '.$current_definition['name']);
- }
-
- $changes = $this->compareDefinitions($current_definition, $previous_definition);
- if (PEAR::isError($changes)) {
- return $changes;
- }
-
- if (is_array($changes)) {
- $this->db->setOption('disable_query', $disable_query);
- $result = $this->alterDatabase($current_definition, $previous_definition, $changes);
- $this->db->setOption('disable_query', false);
- if (PEAR::isError($result)) {
- return $result;
- }
- $copy = true;
- if ($this->db->options['debug']) {
- $result = $this->dumpDatabaseChanges($changes);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
- }
- } else {
- $this->db->setOption('disable_query', $disable_query);
- $result = $this->createDatabase($current_definition);
- $this->db->setOption('disable_query', false);
- if (PEAR::isError($result)) {
- return $result;
- }
- }
-
- if ($overwrite_old_schema_file
- && !$disable_query
- && is_string($previous_schema) && is_string($current_schema)
- && !copy($current_schema, $previous_schema)) {
-
- return $this->raiseError(MDB2_SCHEMA_ERROR, null, null,
- 'Could not copy the new database definition file to the current file');
- }
-
- return MDB2_OK;
- }
- // }}}
- // {{{ errorMessage()
-
- /**
- * Return a textual error message for a MDB2 error code
- *
- * @param int|array $value integer error code, <code>null</code> to get the
- * current error code-message map,
- * or an array with a new error code-message map
- *
- * @return string error message, or false if the error code was not recognized
- * @access public
- */
- function errorMessage($value = null)
- {
- static $errorMessages;
- if (is_array($value)) {
- $errorMessages = $value;
- return MDB2_OK;
- } elseif (!isset($errorMessages)) {
- $errorMessages = array(
- MDB2_SCHEMA_ERROR => 'unknown error',
- MDB2_SCHEMA_ERROR_PARSE => 'schema parse error',
- MDB2_SCHEMA_ERROR_VALIDATE => 'schema validation error',
- MDB2_SCHEMA_ERROR_INVALID => 'invalid',
- MDB2_SCHEMA_ERROR_UNSUPPORTED => 'not supported',
- MDB2_SCHEMA_ERROR_WRITER => 'schema writer error',
- );
- }
-
- if (is_null($value)) {
- return $errorMessages;
- }
-
- if (PEAR::isError($value)) {
- $value = $value->getCode();
- }
-
- return !empty($errorMessages[$value]) ?
- $errorMessages[$value] : $errorMessages[MDB2_SCHEMA_ERROR];
- }
-
- // }}}
- // {{{ raiseError()
-
- /**
- * This method is used to communicate an error and invoke error
- * callbacks etc. Basically a wrapper for PEAR::raiseError
- * without the message string.
- *
- * @param int|PEAR_Error $code integer error code or and PEAR_Error instance
- * @param int $mode error mode, see PEAR_Error docs
- * 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 array $options Options, depending on the mode, @see PEAR::setErrorHandling
- * @param string $userinfo Extra debug information. Defaults to the last
- * query and native error code.
- *
- * @return object a PEAR error object
- * @access public
- * @see PEAR_Error
- */
- function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
- {
- $err =& PEAR::raiseError(null, $code, $mode, $options,
- $userinfo, 'MDB2_Schema_Error', true);
- return $err;
- }
-
- // }}}
- // {{{ isError()
-
- /**
- * Tell whether a value is an MDB2_Schema 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 $db->getMessage() == $code or
- * $code is an integer and $db->getCode() == $code
- *
- * @return bool true if parameter is an error
- * @access public
- */
- function isError($data, $code = null)
- {
- if (is_a($data, 'MDB2_Schema_Error')) {
- if (is_null($code)) {
- return true;
- } elseif (is_string($code)) {
- return $data->getMessage() === $code;
- } else {
- $code = (array)$code;
- return in_array($data->getCode(), $code);
- }
- }
- return false;
- }
-
- // }}}
-}
-
-/**
- * MDB2_Schema_Error implements a class for reporting portable database error
- * messages.
- *
- * @category Database
- * @package MDB2_Schema
- * @author Stig Bakken <ssb@fast.no>
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-class MDB2_Schema_Error extends PEAR_Error
-{
- /**
- * MDB2_Schema_Error constructor.
- *
- * @param mixed $code error code, or string with error message.
- * @param int $mode what 'error mode' to operate in
- * @param int $level what error level to use for $mode & PEAR_ERROR_TRIGGER
- * @param mixed $debuginfo additional debug info, such as the last query
- *
- * @access public
- */
- function MDB2_Schema_Error($code = MDB2_SCHEMA_ERROR, $mode = PEAR_ERROR_RETURN,
- $level = E_USER_NOTICE, $debuginfo = null)
- {
- $this->PEAR_Error('MDB2_Schema Error: ' . MDB2_Schema::errorMessage($code), $code,
- $mode, $level, $debuginfo);
- }
-}
-?>
diff --git a/inc/MDB2/Schema/Parser.php b/inc/MDB2/Schema/Parser.php
deleted file mode 100644
index ed31ba03bdf..00000000000
--- a/inc/MDB2/Schema/Parser.php
+++ /dev/null
@@ -1,819 +0,0 @@
-<?php
-/**
- * PHP versions 4 and 5
- *
- * Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,
- * Stig. S. Bakken, Lukas Smith, Igor Feghali
- * All rights reserved.
- *
- * MDB2_Schema enables users to maintain RDBMS independant schema files
- * in XML that can be used to manipulate both data and database schemas
- * This LICENSE is in the BSD license style.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,
- * Lukas Smith, Igor Feghali nor the names of his contributors may be
- * used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
- * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- * Author: Christian Dickmann <dickmann@php.net>
- * Author: Igor Feghali <ifeghali@php.net>
- *
- * $Id: Parser.php,v 1.68 2008/11/30 03:34:00 clockwerx Exp $
- *
- * @category Database
- * @package MDB2_Schema
- * @author Christian Dickmann <dickmann@php.net>
- * @author Igor Feghali <ifeghali@php.net>
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @version CVS: $Id: Parser.php,v 1.68 2008/11/30 03:34:00 clockwerx Exp $
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-
-
-oc_require_once('XML/Parser.php');
-oc_require_once('MDB2/Schema/Validate.php');
-
-/**
- * Parses an XML schema file
- *
- * @category Database
- * @package MDB2_Schema
- * @author Christian Dickmann <dickmann@php.net>
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-class MDB2_Schema_Parser extends XML_Parser
-{
- var $database_definition = array();
-
- var $elements = array();
-
- var $element = '';
-
- var $count = 0;
-
- var $table = array();
-
- var $table_name = '';
-
- var $field = array();
-
- var $field_name = '';
-
- var $init = array();
-
- var $init_function = array();
-
- var $init_expression = array();
-
- var $init_field = array();
-
- var $index = array();
-
- var $index_name = '';
-
- var $constraint = array();
-
- var $constraint_name = '';
-
- var $var_mode = false;
-
- var $variables = array();
-
- var $sequence = array();
-
- var $sequence_name = '';
-
- var $error;
-
- var $structure = false;
-
- var $val;
-
- function __construct($variables, $fail_on_invalid_names = true,
- $structure = false, $valid_types = array(),
- $force_defaults = true)
- {
- // force ISO-8859-1 due to different defaults for PHP4 and PHP5
- // todo: this probably needs to be investigated some more andcleaned up
- parent::XML_Parser('ISO-8859-1');
-
- $this->variables = $variables;
- $this->structure = $structure;
- $this->val =new MDB2_Schema_Validate($fail_on_invalid_names, $valid_types, $force_defaults);
- }
-
- function MDB2_Schema_Parser($variables, $fail_on_invalid_names = true,
- $structure = false, $valid_types = array(),
- $force_defaults = true)
- {
- $this->__construct($variables, $fail_on_invalid_names, $structure, $valid_types, $force_defaults);
- }
-
- function startHandler($xp, $element, $attribs)
- {
- if (strtolower($element) == 'variable') {
- $this->var_mode = true;
- return;
- }
-
- $this->elements[$this->count++] = strtolower($element);
-
- $this->element = implode('-', $this->elements);
-
- switch ($this->element) {
- /* Initialization */
- case 'database-table-initialization':
- $this->table['initialization'] = array();
- break;
-
- /* Insert */
- /* insert: field+ */
- case 'database-table-initialization-insert':
- $this->init = array('type' => 'insert', 'data' => array('field' => array()));
- break;
- /* insert-select: field+, table, where? */
- case 'database-table-initialization-insert-select':
- $this->init['data']['table'] = '';
- break;
-
- /* Update */
- /* update: field+, where? */
- case 'database-table-initialization-update':
- $this->init = array('type' => 'update', 'data' => array('field' => array()));
- break;
-
- /* Delete */
- /* delete: where */
- case 'database-table-initialization-delete':
- $this->init = array('type' => 'delete', 'data' => array('where' => array()));
- break;
-
- /* Insert and Update */
- case 'database-table-initialization-insert-field':
- case 'database-table-initialization-insert-select-field':
- case 'database-table-initialization-update-field':
- $this->init_field = array('name' => '', 'group' => array());
- break;
- case 'database-table-initialization-insert-field-value':
- case 'database-table-initialization-insert-select-field-value':
- case 'database-table-initialization-update-field-value':
- /* if value tag is empty cdataHandler is not called so we must force value element creation here */
- $this->init_field['group'] = array('type' => 'value', 'data' => '');
- break;
- case 'database-table-initialization-insert-field-null':
- case 'database-table-initialization-insert-select-field-null':
- case 'database-table-initialization-update-field-null':
- $this->init_field['group'] = array('type' => 'null');
- break;
- case 'database-table-initialization-insert-field-function':
- case 'database-table-initialization-insert-select-field-function':
- case 'database-table-initialization-update-field-function':
- $this->init_function = array('name' => '');
- break;
- case 'database-table-initialization-insert-field-expression':
- case 'database-table-initialization-insert-select-field-expression':
- case 'database-table-initialization-update-field-expression':
- $this->init_expression = array();
- break;
-
- /* All */
- case 'database-table-initialization-insert-select-where':
- case 'database-table-initialization-update-where':
- case 'database-table-initialization-delete-where':
- $this->init['data']['where'] = array('type' => '', 'data' => array());
- break;
- case 'database-table-initialization-insert-select-where-expression':
- case 'database-table-initialization-update-where-expression':
- case 'database-table-initialization-delete-where-expression':
- $this->init_expression = array();
- break;
-
- /* One level simulation of expression-function recursion */
- case 'database-table-initialization-insert-field-expression-function':
- case 'database-table-initialization-insert-select-field-expression-function':
- case 'database-table-initialization-insert-select-where-expression-function':
- case 'database-table-initialization-update-field-expression-function':
- case 'database-table-initialization-update-where-expression-function':
- case 'database-table-initialization-delete-where-expression-function':
- $this->init_function = array('name' => '');
- break;
-
- /* One level simulation of function-expression recursion */
- case 'database-table-initialization-insert-field-function-expression':
- case 'database-table-initialization-insert-select-field-function-expression':
- case 'database-table-initialization-insert-select-where-function-expression':
- case 'database-table-initialization-update-field-function-expression':
- case 'database-table-initialization-update-where-function-expression':
- case 'database-table-initialization-delete-where-function-expression':
- $this->init_expression = array();
- break;
-
- /* Definition */
- case 'database':
- $this->database_definition = array(
- 'name' => '',
- 'create' => '',
- 'overwrite' => '',
- 'charset' => '',
- 'description' => '',
- 'comments' => '',
- 'tables' => array(),
- 'sequences' => array()
- );
- break;
- case 'database-table':
- $this->table_name = '';
-
- $this->table = array(
- 'was' => '',
- 'description' => '',
- 'comments' => '',
- 'fields' => array(),
- 'indexes' => array(),
- 'constraints' => array(),
- 'initialization' => array()
- );
- break;
- case 'database-table-declaration-field':
- case 'database-table-declaration-foreign-field':
- case 'database-table-declaration-foreign-references-field':
- $this->field_name = '';
-
- $this->field = array();
- break;
- case 'database-table-declaration-index-field':
- $this->field_name = '';
-
- $this->field = array('sorting' => '', 'length' => '');
- break;
- /* force field attributes to be initialized when the tag is empty in the XML */
- case 'database-table-declaration-field-was':
- $this->field['was'] = '';
- break;
- case 'database-table-declaration-field-type':
- $this->field['type'] = '';
- break;
- case 'database-table-declaration-field-fixed':
- $this->field['fixed'] = '';
- break;
- case 'database-table-declaration-field-default':
- $this->field['default'] = '';
- break;
- case 'database-table-declaration-field-notnull':
- $this->field['notnull'] = '';
- break;
- case 'database-table-declaration-field-autoincrement':
- $this->field['autoincrement'] = '';
- break;
- case 'database-table-declaration-field-unsigned':
- $this->field['unsigned'] = '';
- break;
- case 'database-table-declaration-field-length':
- $this->field['length'] = '';
- break;
- case 'database-table-declaration-field-description':
- $this->field['description'] = '';
- break;
- case 'database-table-declaration-field-comments':
- $this->field['comments'] = '';
- break;
- case 'database-table-declaration-index':
- $this->index_name = '';
-
- $this->index = array(
- 'was' => '',
- 'unique' =>'',
- 'primary' => '',
- 'fields' => array()
- );
- break;
- case 'database-table-declaration-foreign':
- $this->constraint_name = '';
-
- $this->constraint = array(
- 'was' => '',
- 'match' => '',
- 'ondelete' => '',
- 'onupdate' => '',
- 'deferrable' => '',
- 'initiallydeferred' => '',
- 'foreign' => true,
- 'fields' => array(),
- 'references' => array('table' => '', 'fields' => array())
- );
- break;
- case 'database-sequence':
- $this->sequence_name = '';
-
- $this->sequence = array(
- 'was' => '',
- 'start' => '',
- 'description' => '',
- 'comments' => '',
- 'on' => array('table' => '', 'field' => '')
- );
- break;
- }
- }
-
- function endHandler($xp, $element)
- {
- if (strtolower($element) == 'variable') {
- $this->var_mode = false;
- return;
- }
-
- switch ($this->element) {
- /* Initialization */
-
- /* Insert */
- case 'database-table-initialization-insert-select':
- $this->init['data'] = array('select' => $this->init['data']);
- break;
-
- /* Insert and Delete */
- case 'database-table-initialization-insert-field':
- case 'database-table-initialization-insert-select-field':
- case 'database-table-initialization-update-field':
- $result = $this->val->validateDataField($this->table['fields'], $this->init['data']['field'], $this->init_field);
- if (PEAR::isError($result)) {
- $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode());
- } else {
- $this->init['data']['field'][] = $this->init_field;
- }
- break;
- case 'database-table-initialization-insert-field-function':
- case 'database-table-initialization-insert-select-field-function':
- case 'database-table-initialization-update-field-function':
- $this->init_field['group'] = array('type' => 'function', 'data' => $this->init_function);
- break;
- case 'database-table-initialization-insert-field-expression':
- case 'database-table-initialization-insert-select-field-expression':
- case 'database-table-initialization-update-field-expression':
- $this->init_field['group'] = array('type' => 'expression', 'data' => $this->init_expression);
- break;
-
- /* All */
- case 'database-table-initialization-insert-select-where-expression':
- case 'database-table-initialization-update-where-expression':
- case 'database-table-initialization-delete-where-expression':
- $this->init['data']['where']['type'] = 'expression';
- $this->init['data']['where']['data'] = $this->init_expression;
- break;
- case 'database-table-initialization-insert':
- case 'database-table-initialization-delete':
- case 'database-table-initialization-update':
- $this->table['initialization'][] = $this->init;
- break;
-
- /* One level simulation of expression-function recursion */
- case 'database-table-initialization-insert-field-expression-function':
- case 'database-table-initialization-insert-select-field-expression-function':
- case 'database-table-initialization-insert-select-where-expression-function':
- case 'database-table-initialization-update-field-expression-function':
- case 'database-table-initialization-update-where-expression-function':
- case 'database-table-initialization-delete-where-expression-function':
- $this->init_expression['operants'][] = array('type' => 'function', 'data' => $this->init_function);
- break;
-
- /* One level simulation of function-expression recursion */
- case 'database-table-initialization-insert-field-function-expression':
- case 'database-table-initialization-insert-select-field-function-expression':
- case 'database-table-initialization-insert-select-where-function-expression':
- case 'database-table-initialization-update-field-function-expression':
- case 'database-table-initialization-update-where-function-expression':
- case 'database-table-initialization-delete-where-function-expression':
- $this->init_function['arguments'][] = array('type' => 'expression', 'data' => $this->init_expression);
- break;
-
- /* Table definition */
- case 'database-table':
- $result = $this->val->validateTable($this->database_definition['tables'], $this->table, $this->table_name);
- if (PEAR::isError($result)) {
- $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode());
- } else {
- $this->database_definition['tables'][$this->table_name] = $this->table;
- }
- break;
- case 'database-table-name':
- if (isset($this->structure['tables'][$this->table_name])) {
- $this->table = $this->structure['tables'][$this->table_name];
- }
- break;
-
- /* Field declaration */
- case 'database-table-declaration-field':
- $result = $this->val->validateField($this->table['fields'], $this->field, $this->field_name);
- if (PEAR::isError($result)) {
- $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode());
- } else {
- $this->table['fields'][$this->field_name] = $this->field;
- }
- break;
-
- /* Index declaration */
- case 'database-table-declaration-index':
- $result = $this->val->validateIndex($this->table['indexes'], $this->index, $this->index_name);
- if (PEAR::isError($result)) {
- $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode());
- } else {
- $this->table['indexes'][$this->index_name] = $this->index;
- }
- break;
- case 'database-table-declaration-index-field':
- $result = $this->val->validateIndexField($this->index['fields'], $this->field, $this->field_name);
- if (PEAR::isError($result)) {
- $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode());
- } else {
- $this->index['fields'][$this->field_name] = $this->field;
- }
- break;
-
- /* Foreign Key declaration */
- case 'database-table-declaration-foreign':
- $result = $this->val->validateConstraint($this->table['constraints'], $this->constraint, $this->constraint_name);
- if (PEAR::isError($result)) {
- $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode());
- } else {
- $this->table['constraints'][$this->constraint_name] = $this->constraint;
- }
- break;
- case 'database-table-declaration-foreign-field':
- $result = $this->val->validateConstraintField($this->constraint['fields'], $this->field_name);
- if (PEAR::isError($result)) {
- $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode());
- } else {
- $this->constraint['fields'][$this->field_name] = '';
- }
- break;
- case 'database-table-declaration-foreign-references-field':
- $result = $this->val->validateConstraintReferencedField($this->constraint['references']['fields'], $this->field_name);
- if (PEAR::isError($result)) {
- $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode());
- } else {
- $this->constraint['references']['fields'][$this->field_name] = '';
- }
- break;
-
- /* Sequence declaration */
- case 'database-sequence':
- $result = $this->val->validateSequence($this->database_definition['sequences'], $this->sequence, $this->sequence_name);
- if (PEAR::isError($result)) {
- $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode());
- } else {
- $this->database_definition['sequences'][$this->sequence_name] = $this->sequence;
- }
- break;
-
- /* End of File */
- case 'database':
- $result = $this->val->validateDatabase($this->database_definition);
- if (PEAR::isError($result)) {
- $this->raiseError($result->getUserinfo(), 0, $xp, $result->getCode());
- }
- break;
- }
-
- unset($this->elements[--$this->count]);
- $this->element = implode('-', $this->elements);
- }
-
- function &raiseError($msg = null, $xmlecode = 0, $xp = null, $ecode = MDB2_SCHEMA_ERROR_PARSE)
- {
- if (is_null($this->error)) {
- $error = '';
- if (is_resource($msg)) {
- $error .= 'Parser error: '.xml_error_string(xml_get_error_code($msg));
- $xp = $msg;
- } else {
- $error .= 'Parser error: '.$msg;
- if (!is_resource($xp)) {
- $xp = $this->parser;
- }
- }
-
- if ($error_string = xml_error_string($xmlecode)) {
- $error .= ' - '.$error_string;
- }
-
- if (is_resource($xp)) {
- $byte = @xml_get_current_byte_index($xp);
- $line = @xml_get_current_line_number($xp);
- $column = @xml_get_current_column_number($xp);
- $error .= " - Byte: $byte; Line: $line; Col: $column";
- }
-
- $error .= "\n";
-
- $this->error =& MDB2_Schema::raiseError($ecode, null, null, $error);
- }
- return $this->error;
- }
-
- function cdataHandler($xp, $data)
- {
- if ($this->var_mode == true) {
- if (!isset($this->variables[$data])) {
- $this->raiseError('variable "'.$data.'" not found', null, $xp);
- return;
- }
- $data = $this->variables[$data];
- }
-
- switch ($this->element) {
- /* Initialization */
-
- /* Insert */
- case 'database-table-initialization-insert-select-table':
- $this->init['data']['table'] = $data;
- break;
-
- /* Insert and Update */
- case 'database-table-initialization-insert-field-name':
- case 'database-table-initialization-insert-select-field-name':
- case 'database-table-initialization-update-field-name':
- $this->init_field['name'] .= $data;
- break;
- case 'database-table-initialization-insert-field-value':
- case 'database-table-initialization-insert-select-field-value':
- case 'database-table-initialization-update-field-value':
- $this->init_field['group']['data'] .= $data;
- break;
- case 'database-table-initialization-insert-field-function-name':
- case 'database-table-initialization-insert-select-field-function-name':
- case 'database-table-initialization-update-field-function-name':
- $this->init_function['name'] .= $data;
- break;
- case 'database-table-initialization-insert-field-function-value':
- case 'database-table-initialization-insert-select-field-function-value':
- case 'database-table-initialization-update-field-function-value':
- $this->init_function['arguments'][] = array('type' => 'value', 'data' => $data);
- break;
- case 'database-table-initialization-insert-field-function-column':
- case 'database-table-initialization-insert-select-field-function-column':
- case 'database-table-initialization-update-field-function-column':
- $this->init_function['arguments'][] = array('type' => 'column', 'data' => $data);
- break;
- case 'database-table-initialization-insert-field-column':
- case 'database-table-initialization-insert-select-field-column':
- case 'database-table-initialization-update-field-column':
- $this->init_field['group'] = array('type' => 'column', 'data' => $data);
- break;
-
- /* All */
- case 'database-table-initialization-insert-field-expression-operator':
- case 'database-table-initialization-insert-select-field-expression-operator':
- case 'database-table-initialization-insert-select-where-expression-operator':
- case 'database-table-initialization-update-field-expression-operator':
- case 'database-table-initialization-update-where-expression-operator':
- case 'database-table-initialization-delete-where-expression-operator':
- $this->init_expression['operator'] = $data;
- break;
- case 'database-table-initialization-insert-field-expression-value':
- case 'database-table-initialization-insert-select-field-expression-value':
- case 'database-table-initialization-insert-select-where-expression-value':
- case 'database-table-initialization-update-field-expression-value':
- case 'database-table-initialization-update-where-expression-value':
- case 'database-table-initialization-delete-where-expression-value':
- $this->init_expression['operants'][] = array('type' => 'value', 'data' => $data);
- break;
- case 'database-table-initialization-insert-field-expression-column':
- case 'database-table-initialization-insert-select-field-expression-column':
- case 'database-table-initialization-insert-select-where-expression-column':
- case 'database-table-initialization-update-field-expression-column':
- case 'database-table-initialization-update-where-expression-column':
- case 'database-table-initialization-delete-where-expression-column':
- $this->init_expression['operants'][] = array('type' => 'column', 'data' => $data);
- break;
-
- case 'database-table-initialization-insert-field-function-function':
- case 'database-table-initialization-insert-field-function-expression':
- case 'database-table-initialization-insert-field-expression-expression':
- case 'database-table-initialization-update-field-function-function':
- case 'database-table-initialization-update-field-function-expression':
- case 'database-table-initialization-update-field-expression-expression':
- case 'database-table-initialization-update-where-expression-expression':
- case 'database-table-initialization-delete-where-expression-expression':
- /* Recursion to be implemented yet */
- break;
-
- /* One level simulation of expression-function recursion */
- case 'database-table-initialization-insert-field-expression-function-name':
- case 'database-table-initialization-insert-select-field-expression-function-name':
- case 'database-table-initialization-insert-select-where-expression-function-name':
- case 'database-table-initialization-update-field-expression-function-name':
- case 'database-table-initialization-update-where-expression-function-name':
- case 'database-table-initialization-delete-where-expression-function-name':
- $this->init_function['name'] .= $data;
- break;
- case 'database-table-initialization-insert-field-expression-function-value':
- case 'database-table-initialization-insert-select-field-expression-function-value':
- case 'database-table-initialization-insert-select-where-expression-function-value':
- case 'database-table-initialization-update-field-expression-function-value':
- case 'database-table-initialization-update-where-expression-function-value':
- case 'database-table-initialization-delete-where-expression-function-value':
- $this->init_function['arguments'][] = array('type' => 'value', 'data' => $data);
- break;
- case 'database-table-initialization-insert-field-expression-function-column':
- case 'database-table-initialization-insert-select-field-expression-function-column':
- case 'database-table-initialization-insert-select-where-expression-function-column':
- case 'database-table-initialization-update-field-expression-function-column':
- case 'database-table-initialization-update-where-expression-function-column':
- case 'database-table-initialization-delete-where-expression-function-column':
- $this->init_function['arguments'][] = array('type' => 'column', 'data' => $data);
- break;
-
- /* One level simulation of function-expression recursion */
- case 'database-table-initialization-insert-field-function-expression-operator':
- case 'database-table-initialization-insert-select-field-function-expression-operator':
- case 'database-table-initialization-update-field-function-expression-operator':
- $this->init_expression['operator'] = $data;
- break;
- case 'database-table-initialization-insert-field-function-expression-value':
- case 'database-table-initialization-insert-select-field-function-expression-value':
- case 'database-table-initialization-update-field-function-expression-value':
- $this->init_expression['operants'][] = array('type' => 'value', 'data' => $data);
- break;
- case 'database-table-initialization-insert-field-function-expression-column':
- case 'database-table-initialization-insert-select-field-function-expression-column':
- case 'database-table-initialization-update-field-function-expression-column':
- $this->init_expression['operants'][] = array('type' => 'column', 'data' => $data);
- break;
-
- /* Database */
- case 'database-name':
- $this->database_definition['name'] .= $data;
- break;
- case 'database-create':
- $this->database_definition['create'] .= $data;
- break;
- case 'database-overwrite':
- $this->database_definition['overwrite'] .= $data;
- break;
- case 'database-charset':
- $this->database_definition['charset'] .= $data;
- break;
- case 'database-description':
- $this->database_definition['description'] .= $data;
- break;
- case 'database-comments':
- $this->database_definition['comments'] .= $data;
- break;
-
- /* Table declaration */
- case 'database-table-name':
- $this->table_name .= $data;
- break;
- case 'database-table-was':
- $this->table['was'] .= $data;
- break;
- case 'database-table-description':
- $this->table['description'] .= $data;
- break;
- case 'database-table-comments':
- $this->table['comments'] .= $data;
- break;
-
- /* Field declaration */
- case 'database-table-declaration-field-name':
- $this->field_name .= $data;
- break;
- case 'database-table-declaration-field-was':
- $this->field['was'] .= $data;
- break;
- case 'database-table-declaration-field-type':
- $this->field['type'] .= $data;
- break;
- case 'database-table-declaration-field-fixed':
- $this->field['fixed'] .= $data;
- break;
- case 'database-table-declaration-field-default':
- $this->field['default'] .= $data;
- break;
- case 'database-table-declaration-field-notnull':
- $this->field['notnull'] .= $data;
- break;
- case 'database-table-declaration-field-autoincrement':
- $this->field['autoincrement'] .= $data;
- break;
- case 'database-table-declaration-field-unsigned':
- $this->field['unsigned'] .= $data;
- break;
- case 'database-table-declaration-field-length':
- $this->field['length'] .= $data;
- break;
- case 'database-table-declaration-field-description':
- $this->field['description'] .= $data;
- break;
- case 'database-table-declaration-field-comments':
- $this->field['comments'] .= $data;
- break;
-
- /* Index declaration */
- case 'database-table-declaration-index-name':
- $this->index_name .= $data;
- break;
- case 'database-table-declaration-index-was':
- $this->index['was'] .= $data;
- break;
- case 'database-table-declaration-index-unique':
- $this->index['unique'] .= $data;
- break;
- case 'database-table-declaration-index-primary':
- $this->index['primary'] .= $data;
- break;
- case 'database-table-declaration-index-field-name':
- $this->field_name .= $data;
- break;
- case 'database-table-declaration-index-field-sorting':
- $this->field['sorting'] .= $data;
- break;
- /* Add by Leoncx */
- case 'database-table-declaration-index-field-length':
- $this->field['length'] .= $data;
- break;
-
- /* Foreign Key declaration */
- case 'database-table-declaration-foreign-name':
- $this->constraint_name .= $data;
- break;
- case 'database-table-declaration-foreign-was':
- $this->constraint['was'] .= $data;
- break;
- case 'database-table-declaration-foreign-match':
- $this->constraint['match'] .= $data;
- break;
- case 'database-table-declaration-foreign-ondelete':
- $this->constraint['ondelete'] .= $data;
- break;
- case 'database-table-declaration-foreign-onupdate':
- $this->constraint['onupdate'] .= $data;
- break;
- case 'database-table-declaration-foreign-deferrable':
- $this->constraint['deferrable'] .= $data;
- break;
- case 'database-table-declaration-foreign-initiallydeferred':
- $this->constraint['initiallydeferred'] .= $data;
- break;
- case 'database-table-declaration-foreign-field':
- $this->field_name .= $data;
- break;
- case 'database-table-declaration-foreign-references-table':
- $this->constraint['references']['table'] .= $data;
- break;
- case 'database-table-declaration-foreign-references-field':
- $this->field_name .= $data;
- break;
-
- /* Sequence declaration */
- case 'database-sequence-name':
- $this->sequence_name .= $data;
- break;
- case 'database-sequence-was':
- $this->sequence['was'] .= $data;
- break;
- case 'database-sequence-start':
- $this->sequence['start'] .= $data;
- break;
- case 'database-sequence-description':
- $this->sequence['description'] .= $data;
- break;
- case 'database-sequence-comments':
- $this->sequence['comments'] .= $data;
- break;
- case 'database-sequence-on-table':
- $this->sequence['on']['table'] .= $data;
- break;
- case 'database-sequence-on-field':
- $this->sequence['on']['field'] .= $data;
- break;
- }
- }
-}
-
-?>
diff --git a/inc/MDB2/Schema/Parser2.php b/inc/MDB2/Schema/Parser2.php
deleted file mode 100644
index 01318473fdd..00000000000
--- a/inc/MDB2/Schema/Parser2.php
+++ /dev/null
@@ -1,624 +0,0 @@
-<?php
-/**
- * PHP versions 4 and 5
- *
- * Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,
- * Stig. S. Bakken, Lukas Smith, Igor Feghali
- * All rights reserved.
- *
- * MDB2_Schema enables users to maintain RDBMS independant schema files
- * in XML that can be used to manipulate both data and database schemas
- * This LICENSE is in the BSD license style.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,
- * Lukas Smith, Igor Feghali nor the names of his contributors may be
- * used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
- * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- * Author: Igor Feghali <ifeghali@php.net>
- *
- * @category Database
- * @package MDB2_Schema
- * @author Igor Feghali <ifeghali@php.net>
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @version CVS: $Id: Parser2.php,v 1.12 2008/11/30 03:34:00 clockwerx Exp $
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-
-require_once 'XML/Unserializer.php';
-require_once 'MDB2/Schema/Validate.php';
-
-/**
- * Parses an XML schema file
- *
- * @category Database
- * @package MDB2_Schema
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Igor Feghali <ifeghali@php.net>
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-class MDB2_Schema_Parser2 extends XML_Unserializer
-{
- var $database_definition = array();
-
- var $database_loaded = array();
-
- var $variables = array();
-
- var $error;
-
- var $structure = false;
-
- var $val;
-
- var $options = array();
-
- var $table = array();
-
- var $table_name = '';
-
- var $field = array();
-
- var $field_name = '';
-
- var $index = array();
-
- var $index_name = '';
-
- var $constraint = array();
-
- var $constraint_name = '';
-
- var $sequence = array();
-
- var $sequence_name = '';
-
- var $init = array();
-
- function __construct($variables, $fail_on_invalid_names = true, $structure = false, $valid_types = array(), $force_defaults = true)
- {
- // force ISO-8859-1 due to different defaults for PHP4 and PHP5
- // todo: this probably needs to be investigated some more and cleaned up
- $this->options['encoding'] = 'ISO-8859-1';
-
- $this->options['XML_UNSERIALIZER_OPTION_ATTRIBUTES_PARSE'] = true;
- $this->options['XML_UNSERIALIZER_OPTION_ATTRIBUTES_ARRAYKEY'] = false;
-
- $this->options['forceEnum'] = array('table', 'field', 'index', 'foreign', 'insert', 'update', 'delete', 'sequence');
-
- /*
- * todo: find a way to force the following items not to be parsed as arrays
- * as it cause problems in functions with multiple arguments
- */
- //$this->options['forceNEnum'] = array('value', 'column');
- $this->variables = $variables;
- $this->structure = $structure;
-
- $this->val =& new MDB2_Schema_Validate($fail_on_invalid_names, $valid_types, $force_defaults);
- parent::XML_Unserializer($this->options);
- }
-
- function MDB2_Schema_Parser2($variables, $fail_on_invalid_names = true, $structure = false, $valid_types = array(), $force_defaults = true)
- {
- $this->__construct($variables, $fail_on_invalid_names, $structure, $valid_types, $force_defaults);
- }
-
- function parse()
- {
- $result = $this->unserialize($this->filename, true);
-
- if (PEAR::isError($result)) {
- return $result;
- } else {
- $this->database_loaded = $this->getUnserializedData();
- return $this->fixDatabaseKeys($this->database_loaded);
- }
- }
-
- function setInputFile($filename)
- {
- $this->filename = $filename;
- return MDB2_OK;
- }
-
- function renameKey(&$arr, $oKey, $nKey)
- {
- $arr[$nKey] = &$arr[$oKey];
- unset($arr[$oKey]);
- }
-
- function fixDatabaseKeys($database)
- {
- $this->database_definition = array(
- 'name' => '',
- 'create' => '',
- 'overwrite' => '',
- 'charset' => '',
- 'description' => '',
- 'comments' => '',
- 'tables' => array(),
- 'sequences' => array()
- );
-
- if (!empty($database['name'])) {
- $this->database_definition['name'] = $database['name'];
- }
- if (!empty($database['create'])) {
- $this->database_definition['create'] = $database['create'];
- }
- if (!empty($database['overwrite'])) {
- $this->database_definition['overwrite'] = $database['overwrite'];
- }
- if (!empty($database['charset'])) {
- $this->database_definition['charset'] = $database['charset'];
- }
- if (!empty($database['description'])) {
- $this->database_definition['description'] = $database['description'];
- }
- if (!empty($database['comments'])) {
- $this->database_definition['comments'] = $database['comments'];
- }
-
- if (!empty($database['table']) && is_array($database['table'])) {
- foreach ($database['table'] as $table) {
- $this->fixTableKeys($table);
- }
- }
-
- if (!empty($database['sequence']) && is_array($database['sequence'])) {
- foreach ($database['sequence'] as $sequence) {
- $this->fixSequenceKeys($sequence);
- }
- }
-
- $result = $this->val->validateDatabase($this->database_definition);
- if (PEAR::isError($result)) {
- return $this->raiseError($result->getUserinfo());
- }
-
- return MDB2_OK;
- }
-
- function fixTableKeys($table)
- {
- $this->table = array(
- 'was' => '',
- 'description' => '',
- 'comments' => '',
- 'fields' => array(),
- 'indexes' => array(),
- 'constraints' => array(),
- 'initialization' => array()
- );
-
- if (!empty($table['name'])) {
- $this->table_name = $table['name'];
- } else {
- $this->table_name = '';
- }
- if (!empty($table['was'])) {
- $this->table['was'] = $table['was'];
- }
- if (!empty($table['description'])) {
- $this->table['description'] = $table['description'];
- }
- if (!empty($table['comments'])) {
- $this->table['comments'] = $table['comments'];
- }
-
- if (!empty($table['declaration']) && is_array($table['declaration'])) {
- if (!empty($table['declaration']['field']) && is_array($table['declaration']['field'])) {
- foreach ($table['declaration']['field'] as $field) {
- $this->fixTableFieldKeys($field);
- }
- }
-
- if (!empty($table['declaration']['index']) && is_array($table['declaration']['index'])) {
- foreach ($table['declaration']['index'] as $index) {
- $this->fixTableIndexKeys($index);
- }
- }
-
- if (!empty($table['declaration']['foreign']) && is_array($table['declaration']['foreign'])) {
- foreach ($table['declaration']['foreign'] as $constraint) {
- $this->fixTableConstraintKeys($constraint);
- }
- }
- }
-
- if (!empty($table['initialization']) && is_array($table['initialization'])) {
- if (!empty($table['initialization']['insert']) && is_array($table['initialization']['insert'])) {
- foreach ($table['initialization']['insert'] as $init) {
- $this->fixTableInitializationKeys($init, 'insert');
- }
- }
- if (!empty($table['initialization']['update']) && is_array($table['initialization']['update'])) {
- foreach ($table['initialization']['update'] as $init) {
- $this->fixTableInitializationKeys($init, 'update');
- }
- }
- if (!empty($table['initialization']['delete']) && is_array($table['initialization']['delete'])) {
- foreach ($table['initialization']['delete'] as $init) {
- $this->fixTableInitializationKeys($init, 'delete');
- }
- }
- }
-
- $result = $this->val->validateTable($this->database_definition['tables'], $this->table, $this->table_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result->getUserinfo());
- } else {
- $this->database_definition['tables'][$this->table_name] = $this->table;
- }
-
- return MDB2_OK;
- }
-
- function fixTableFieldKeys($field)
- {
- $this->field = array();
- if (!empty($field['name'])) {
- $this->field_name = $field['name'];
- } else {
- $this->field_name = '';
- }
- if (!empty($field['was'])) {
- $this->field['was'] = $field['was'];
- }
- if (!empty($field['type'])) {
- $this->field['type'] = $field['type'];
- }
- if (!empty($field['fixed'])) {
- $this->field['fixed'] = $field['fixed'];
- }
- if (isset($field['default'])) {
- $this->field['default'] = $field['default'];
- }
- if (!empty($field['notnull'])) {
- $this->field['notnull'] = $field['notnull'];
- }
- if (!empty($field['autoincrement'])) {
- $this->field['autoincrement'] = $field['autoincrement'];
- }
- if (!empty($field['unsigned'])) {
- $this->field['unsigned'] = $field['unsigned'];
- }
- if (!empty($field['length'])) {
- $this->field['length'] = $field['length'];
- }
- if (!empty($field['description'])) {
- $this->field['description'] = $field['description'];
- }
- if (!empty($field['comments'])) {
- $this->field['comments'] = $field['comments'];
- }
-
- $result = $this->val->validateField($this->table['fields'], $this->field, $this->field_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result->getUserinfo());
- } else {
- $this->table['fields'][$this->field_name] = $this->field;
- }
-
- return MDB2_OK;
- }
-
- function fixTableIndexKeys($index)
- {
- $this->index = array(
- 'was' => '',
- 'unique' =>'',
- 'primary' => '',
- 'fields' => array()
- );
-
- if (!empty($index['name'])) {
- $this->index_name = $index['name'];
- } else {
- $this->index_name = '';
- }
- if (!empty($index['was'])) {
- $this->index['was'] = $index['was'];
- }
- if (!empty($index['unique'])) {
- $this->index['unique'] = $index['unique'];
- }
- if (!empty($index['primary'])) {
- $this->index['primary'] = $index['primary'];
- }
- if (!empty($index['field'])) {
- foreach ($index['field'] as $field) {
- if (!empty($field['name'])) {
- $this->field_name = $field['name'];
- } else {
- $this->field_name = '';
- }
- $this->field = array(
- 'sorting' => '',
- 'length' => ''
- );
-
- if (!empty($field['sorting'])) {
- $this->field['sorting'] = $field['sorting'];
- }
- if (!empty($field['length'])) {
- $this->field['length'] = $field['length'];
- }
-
- $result = $this->val->validateIndexField($this->index['fields'], $this->field, $this->field_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result->getUserinfo());
- }
-
- $this->index['fields'][$this->field_name] = $this->field;
- }
- }
-
- $result = $this->val->validateIndex($this->table['indexes'], $this->index, $this->index_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result->getUserinfo());
- } else {
- $this->table['indexes'][$this->index_name] = $this->index;
- }
-
- return MDB2_OK;
- }
-
- function fixTableConstraintKeys($constraint)
- {
- $this->constraint = array(
- 'was' => '',
- 'match' => '',
- 'ondelete' => '',
- 'onupdate' => '',
- 'deferrable' => '',
- 'initiallydeferred' => '',
- 'foreign' => true,
- 'fields' => array(),
- 'references' => array('table' => '', 'fields' => array())
- );
-
- if (!empty($constraint['name'])) {
- $this->constraint_name = $constraint['name'];
- } else {
- $this->constraint_name = '';
- }
- if (!empty($constraint['was'])) {
- $this->constraint['was'] = $constraint['was'];
- }
- if (!empty($constraint['match'])) {
- $this->constraint['match'] = $constraint['match'];
- }
- if (!empty($constraint['ondelete'])) {
- $this->constraint['ondelete'] = $constraint['ondelete'];
- }
- if (!empty($constraint['onupdate'])) {
- $this->constraint['onupdate'] = $constraint['onupdate'];
- }
- if (!empty($constraint['deferrable'])) {
- $this->constraint['deferrable'] = $constraint['deferrable'];
- }
- if (!empty($constraint['initiallydeferred'])) {
- $this->constraint['initiallydeferred'] = $constraint['initiallydeferred'];
- }
- if (!empty($constraint['field']) && is_array($constraint['field'])) {
- foreach ($constraint['field'] as $field) {
- $result = $this->val->validateConstraintField($this->constraint['fields'], $field);
- if (PEAR::isError($result)) {
- return $this->raiseError($result->getUserinfo());
- }
-
- $this->constraint['fields'][$field] = '';
- }
- }
-
- if (!empty($constraint['references']) && is_array($constraint['references'])) {
- /**
- * As we forced 'table' to be enumerated
- * we have to fix it on the foreign-references-table context
- */
- if (!empty($constraint['references']['table']) && is_array($constraint['references']['table'])) {
- $this->constraint['references']['table'] = $constraint['references']['table'][0];
- }
-
- if (!empty($constraint['references']['field']) && is_array($constraint['references']['field'])) {
- foreach ($constraint['references']['field'] as $field) {
- $result = $this->val->validateConstraintReferencedField($this->constraint['references']['fields'], $field);
- if (PEAR::isError($result)) {
- return $this->raiseError($result->getUserinfo());
- }
-
- $this->constraint['references']['fields'][$field] = '';
- }
- }
- }
-
- $result = $this->val->validateConstraint($this->table['constraints'], $this->constraint, $this->constraint_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result->getUserinfo());
- } else {
- $this->table['constraints'][$this->constraint_name] = $this->constraint;
- }
-
- return MDB2_OK;
- }
-
- function fixTableInitializationKeys($element, $type = '')
- {
- if (!empty($element['select']) && is_array($element['select'])) {
- $this->fixTableInitializationDataKeys($element['select']);
- $this->init = array( 'select' => $this->init );
- } else {
- $this->fixTableInitializationDataKeys($element);
- }
-
- $this->table['initialization'][] = array( 'type' => $type, 'data' => $this->init );
- }
-
- function fixTableInitializationDataKeys($element)
- {
- $this->init = array();
- if (!empty($element['field']) && is_array($element['field'])) {
- foreach ($element['field'] as $field) {
- $name = $field['name'];
- unset($field['name']);
-
- $this->setExpression($field);
- $this->init['field'][] = array( 'name' => $name, 'group' => $field );
- }
- }
- /**
- * As we forced 'table' to be enumerated
- * we have to fix it on the insert-select context
- */
- if (!empty($element['table']) && is_array($element['table'])) {
- $this->init['table'] = $element['table'][0];
- }
- if (!empty($element['where']) && is_array($element['where'])) {
- $this->init['where'] = $element['where'];
- $this->setExpression($this->init['where']);
- }
- }
-
- function setExpression(&$arr)
- {
- $element = each($arr);
-
- $arr = array( 'type' => $element['key'] );
-
- $element = $element['value'];
-
- switch ($arr['type']) {
- case 'null':
- break;
- case 'value':
- case 'column':
- $arr['data'] = $element;
- break;
- case 'function':
- if (!empty($element)
- && is_array($element)
- ) {
- $arr['data'] = array( 'name' => $element['name'] );
- unset($element['name']);
-
- foreach ($element as $type => $value) {
- if (!empty($value)) {
- if (is_array($value)) {
- foreach ($value as $argument) {
- $argument = array( $type => $argument );
- $this->setExpression($argument);
- $arr['data']['arguments'][] = $argument;
- }
- } else {
- $arr['data']['arguments'][] = array( 'type' => $type, 'data' => $value );
- }
- }
- }
- }
- break;
- case 'expression':
- $arr['data'] = array( 'operants' => array(), 'operator' => $element['operator'] );
- unset($element['operator']);
-
- foreach ($element as $k => $v) {
- $argument = array( $k => $v );
- $this->setExpression($argument);
- $arr['data']['operants'][] = $argument;
- }
- break;
- }
- }
-
- function fixSequenceKeys($sequence)
- {
- $this->sequence = array(
- 'was' => '',
- 'start' => '',
- 'description' => '',
- 'comments' => '',
- 'on' => array('table' => '', 'field' => '')
- );
-
- if (!empty($sequence['name'])) {
- $this->sequence_name = $sequence['name'];
- } else {
- $this->sequence_name = '';
- }
- if (!empty($sequence['was'])) {
- $this->sequence['was'] = $sequence['was'];
- }
- if (!empty($sequence['start'])) {
- $this->sequence['start'] = $sequence['start'];
- }
- if (!empty($sequence['description'])) {
- $this->sequence['description'] = $sequence['description'];
- }
- if (!empty($sequence['comments'])) {
- $this->sequence['comments'] = $sequence['comments'];
- }
- if (!empty($sequence['on']) && is_array($sequence['on'])) {
- /**
- * As we forced 'table' to be enumerated
- * we have to fix it on the sequence-on-table context
- */
- if (!empty($sequence['on']['table']) && is_array($sequence['on']['table'])) {
- $this->sequence['on']['table'] = $sequence['on']['table'][0];
- }
-
- /**
- * As we forced 'field' to be enumerated
- * we have to fix it on the sequence-on-field context
- */
- if (!empty($sequence['on']['field']) && is_array($sequence['on']['field'])) {
- $this->sequence['on']['field'] = $sequence['on']['field'][0];
- }
- }
-
- $result = $this->val->validateSequence($this->database_definition['sequences'], $this->sequence, $this->sequence_name);
- if (PEAR::isError($result)) {
- return $this->raiseError($result->getUserinfo());
- } else {
- $this->database_definition['sequences'][$this->sequence_name] = $this->sequence;
- }
-
- return MDB2_OK;
- }
-
- function &raiseError($msg = null, $ecode = MDB2_SCHEMA_ERROR_PARSE)
- {
- if (is_null($this->error)) {
- $error = 'Parser error: '.$msg."\n";
-
- $this->error =& MDB2_Schema::raiseError($ecode, null, null, $error);
- }
- return $this->error;
- }
-}
-
-?>
diff --git a/inc/MDB2/Schema/Reserved/ibase.php b/inc/MDB2/Schema/Reserved/ibase.php
deleted file mode 100644
index b208abc83a3..00000000000
--- a/inc/MDB2/Schema/Reserved/ibase.php
+++ /dev/null
@@ -1,436 +0,0 @@
-<?php
-// {{{ Disclaimer, Licence, copyrights
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Lorenzo Alberton <l.alberton@quipo.it> |
-// +----------------------------------------------------------------------+
-//
-// }}}
-// {{{ $GLOBALS['_MDB2_Schema_Reserved']['ibase']
-/**
- * Has a list of reserved words of Interbase/Firebird
- *
- * @package MDB2_Schema
- * @category Database
- * @access protected
- * @author Lorenzo Alberton <l.alberton@quipo.it>
- */
-$GLOBALS['_MDB2_Schema_Reserved']['ibase'] = array(
- 'ABS',
- 'ABSOLUTE',
- 'ACTION',
- 'ACTIVE',
- 'ADD',
- 'ADMIN',
- 'AFTER',
- 'ALL',
- 'ALLOCATE',
- 'ALTER',
- 'AND',
- 'ANY',
- 'ARE',
- 'AS',
- 'ASC',
- 'ASCENDING',
- 'ASSERTION',
- 'AT',
- 'AUTHORIZATION',
- 'AUTO',
- 'AUTODDL',
- 'AVG',
- 'BACKUP',
- 'BASE_NAME',
- 'BASED',
- 'BASENAME',
- 'BEFORE',
- 'BEGIN',
- 'BETWEEN',
- 'BIGINT',
- 'BIT',
- 'BIT_LENGTH',
- 'BLOB',
- 'BLOCK',
- 'BLOBEDIT',
- 'BOOLEAN',
- 'BOTH',
- 'BOTH',
- 'BREAK',
- 'BUFFER',
- 'BY',
- 'CACHE',
- 'CASCADE',
- 'CASCADED',
- 'CASE',
- 'CASE',
- 'CAST',
- 'CATALOG',
- 'CHAR',
- 'CHAR_LENGTH',
- 'CHARACTER',
- 'CHARACTER_LENGTH',
- 'CHECK',
- 'CHECK_POINT_LEN',
- 'CHECK_POINT_LENGTH',
- 'CLOSE',
- 'COALESCE',
- 'COLLATE',
- 'COLLATION',
- 'COLUMN',
- 'COMMENT',
- 'COMMIT',
- 'COMMITTED',
- 'COMPILETIME',
- 'COMPUTED',
- 'CONDITIONAL',
- 'CONNECT',
- 'CONNECTION',
- 'CONSTRAINT',
- 'CONSTRAINTS',
- 'CONTAINING',
- 'CONTINUE',
- 'CONVERT',
- 'CORRESPONDING',
- 'COUNT',
- 'CREATE',
- 'CROSS',
- 'CSTRING',
- 'CURRENT',
- 'CURRENT_CONNECTION',
- 'CURRENT_DATE',
- 'CURRENT_ROLE',
- 'CURRENT_TIME',
- 'CURRENT_TIMESTAMP',
- 'CURRENT_TRANSACTION',
- 'CURRENT_USER',
- 'DATABASE',
- 'DATE',
- 'DAY',
- 'DB_KEY',
- 'DEALLOCATE',
- 'DEBUG',
- 'DEC',
- 'DECIMAL',
- 'DECLARE',
- 'DEFAULT',
- 'DEFERRABLE',
- 'DEFERRED',
- 'DELETE',
- 'DELETING',
- 'DESC',
- 'DESCENDING',
- 'DESCRIBE',
- 'DESCRIPTOR',
- 'DIAGNOSTICS',
- 'DIFFERENCE',
- 'DISCONNECT',
- 'DISPLAY',
- 'DISTINCT',
- 'DO',
- 'DOMAIN',
- 'DOUBLE',
- 'DROP',
- 'ECHO',
- 'EDIT',
- 'ELSE',
- 'END',
- 'END-EXEC',
- 'ENTRY_POINT',
- 'ESCAPE',
- 'EVENT',
- 'EXCEPT',
- 'EXCEPTION',
- 'EXEC',
- 'EXECUTE',
- 'EXISTS',
- 'EXIT',
- 'EXTERN',
- 'EXTERNAL',
- 'EXTRACT',
- 'FALSE',
- 'FETCH',
- 'FILE',
- 'FILTER',
- 'FIRST',
- 'FLOAT',
- 'FOR',
- 'FOREIGN',
- 'FOUND',
- 'FREE_IT',
- 'FROM',
- 'FULL',
- 'FUNCTION',
- 'GDSCODE',
- 'GEN_ID',
- 'GENERATOR',
- 'GET',
- 'GLOBAL',
- 'GO',
- 'GOTO',
- 'GRANT',
- 'GROUP',
- 'GROUP_COMMIT_WAIT',
- 'GROUP_COMMIT_WAIT_TIME',
- 'HAVING',
- 'HELP',
- 'HOUR',
- 'IDENTITY',
- 'IF',
- 'IIF',
- 'IMMEDIATE',
- 'IN',
- 'INACTIVE',
- 'INDEX',
- 'INDICATOR',
- 'INIT',
- 'INITIALLY',
- 'INNER',
- 'INPUT',
- 'INPUT_TYPE',
- 'INSENSITIVE',
- 'INSERT',
- 'INSERTING',
- 'INT',
- 'INTEGER',
- 'INTERSECT',
- 'INTERVAL',
- 'INTO',
- 'IS',
- 'ISOLATION',
- 'ISQL',
- 'JOIN',
- 'KEY',
- 'LANGUAGE',
- 'LAST',
- 'LC_MESSAGES',
- 'LC_TYPE',
- 'LEADING',
- 'LEADING',
- 'LEADING',
- 'LEAVE',
- 'LEFT',
- 'LENGTH',
- 'LEV',
- 'LEVEL',
- 'LIKE',
- 'LOCAL',
- 'LOCK',
- 'LOG_BUF_SIZE',
- 'LOG_BUFFER_SIZE',
- 'LOGFILE',
- 'LONG',
- 'LOWER',
- 'MANUAL',
- 'MATCH',
- 'MAX',
- 'MAX_SEGMENT',
- 'MAXIMUM',
- 'MAXIMUM_SEGMENT',
- 'MERGE',
- 'MESSAGE',
- 'MIN',
- 'MINIMUM',
- 'MINUTE',
- 'MODULE',
- 'MODULE_NAME',
- 'MONTH',
- 'NAMES',
- 'NATIONAL',
- 'NATURAL',
- 'NCHAR',
- 'NEXT',
- 'NO',
- 'NOAUTO',
- 'NOT',
- 'NULL',
- 'NULLIF',
- 'NULLS',
- 'NUM_LOG_BUFFERS',
- 'NUM_LOG_BUFS',
- 'NUMERIC',
- 'OCTET_LENGTH',
- 'OF',
- 'ON',
- 'ONLY',
- 'OPEN',
- 'OPTION',
- 'OR',
- 'ORDER',
- 'OUTER',
- 'OUTPUT',
- 'OUTPUT_TYPE',
- 'OVERFLOW',
- 'OVERLAPS',
- 'PAD',
- 'PAGE',
- 'PAGE_SIZE',
- 'PAGELENGTH',
- 'PAGES',
- 'PARAMETER',
- 'PARTIAL',
- 'PASSWORD',
- 'PERCENT',
- 'PLAN',
- 'POSITION',
- 'POST_EVENT',
- 'PRECISION',
- 'PREPARE',
- 'PRESERVE',
- 'PRIMARY',
- 'PRIOR',
- 'PRIVILEGES',
- 'PROCEDURE',
- 'PUBLIC',
- 'QUIT',
- 'RAW_PARTITIONS',
- 'RDB$DB_KEY',
- 'READ',
- 'REAL',
- 'RECORD_VERSION',
- 'RECREATE',
- 'RECREATE ROW_COUNT',
- 'REFERENCES',
- 'RELATIVE',
- 'RELEASE',
- 'RESERV',
- 'RESERVING',
- 'RESTART',
- 'RESTRICT',
- 'RETAIN',
- 'RETURN',
- 'RETURNING',
- 'RETURNING_VALUES',
- 'RETURNS',
- 'REVOKE',
- 'RIGHT',
- 'ROLE',
- 'ROLLBACK',
- 'ROW_COUNT',
- 'ROWS',
- 'RUNTIME',
- 'SAVEPOINT',
- 'SCALAR_ARRAY',
- 'SCHEMA',
- 'SCROLL',
- 'SECOND',
- 'SECTION',
- 'SELECT',
- 'SEQUENCE',
- 'SESSION',
- 'SESSION_USER',
- 'SET',
- 'SHADOW',
- 'SHARED',
- 'SHELL',
- 'SHOW',
- 'SINGULAR',
- 'SIZE',
- 'SKIP',
- 'SMALLINT',
- 'SNAPSHOT',
- 'SOME',
- 'SORT',
- 'SPACE',
- 'SQL',
- 'SQLCODE',
- 'SQLERROR',
- 'SQLSTATE',
- 'SQLWARNING',
- 'STABILITY',
- 'STARTING',
- 'STARTS',
- 'STATEMENT',
- 'STATIC',
- 'STATISTICS',
- 'SUB_TYPE',
- 'SUBSTRING',
- 'SUM',
- 'SUSPEND',
- 'SYSTEM_USER',
- 'TABLE',
- 'TEMPORARY',
- 'TERMINATOR',
- 'THEN',
- 'TIES',
- 'TIME',
- 'TIMESTAMP',
- 'TIMEZONE_HOUR',
- 'TIMEZONE_MINUTE',
- 'TO',
- 'TRAILING',
- 'TRANSACTION',
- 'TRANSLATE',
- 'TRANSLATION',
- 'TRIGGER',
- 'TRIM',
- 'TRUE',
- 'TYPE',
- 'UNCOMMITTED',
- 'UNION',
- 'UNIQUE',
- 'UNKNOWN',
- 'UPDATE',
- 'UPDATING',
- 'UPPER',
- 'USAGE',
- 'USER',
- 'USING',
- 'VALUE',
- 'VALUES',
- 'VARCHAR',
- 'VARIABLE',
- 'VARYING',
- 'VERSION',
- 'VIEW',
- 'WAIT',
- 'WEEKDAY',
- 'WHEN',
- 'WHENEVER',
- 'WHERE',
- 'WHILE',
- 'WITH',
- 'WORK',
- 'WRITE',
- 'YEAR',
- 'YEARDAY',
- 'ZONE',
-);
-// }}}
-?> \ No newline at end of file
diff --git a/inc/MDB2/Schema/Reserved/mssql.php b/inc/MDB2/Schema/Reserved/mssql.php
deleted file mode 100644
index 74ac6885780..00000000000
--- a/inc/MDB2/Schema/Reserved/mssql.php
+++ /dev/null
@@ -1,258 +0,0 @@
-<?php
-// {{{ Disclaimer, Licence, copyrights
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: David Coallier <davidc@php.net> |
-// +----------------------------------------------------------------------+
-// }}}
-// {{{ $GLOBALS['_MDB2_Schema_Reserved']['mssql']
-/**
- * Has a list of all the reserved words for mssql.
- *
- * @package MDB2_Schema
- * @category Database
- * @access protected
- * @author David Coallier <davidc@php.net>
- */
-$GLOBALS['_MDB2_Schema_Reserved']['mssql'] = array(
- 'ADD',
- 'CURRENT_TIMESTAMP',
- 'GROUP',
- 'OPENQUERY',
- 'SERIALIZABLE',
- 'ALL',
- 'CURRENT_USER',
- 'HAVING',
- 'OPENROWSET',
- 'SESSION_USER',
- 'ALTER',
- 'CURSOR',
- 'HOLDLOCK',
- 'OPTION',
- 'SET',
- 'AND',
- 'DATABASE',
- 'IDENTITY',
- 'OR',
- 'SETUSER',
- 'ANY',
- 'DBCC',
- 'IDENTITYCOL',
- 'ORDER',
- 'SHUTDOWN',
- 'AS',
- 'DEALLOCATE',
- 'IDENTITY_INSERT',
- 'OUTER',
- 'SOME',
- 'ASC',
- 'DECLARE',
- 'IF',
- 'OVER',
- 'STATISTICS',
- 'AUTHORIZATION',
- 'DEFAULT',
- 'IN',
- 'PERCENT',
- 'SUM',
- 'AVG',
- 'DELETE',
- 'INDEX',
- 'PERM',
- 'SYSTEM_USER',
- 'BACKUP',
- 'DENY',
- 'INNER',
- 'PERMANENT',
- 'TABLE',
- 'BEGIN',
- 'DESC',
- 'INSERT',
- 'PIPE',
- 'TAPE',
- 'BETWEEN',
- 'DISK',
- 'INTERSECT',
- 'PLAN',
- 'TEMP',
- 'BREAK',
- 'DISTINCT',
- 'INTO',
- 'PRECISION',
- 'TEMPORARY',
- 'BROWSE',
- 'DISTRIBUTED',
- 'IS',
- 'PREPARE',
- 'TEXTSIZE',
- 'BULK',
- 'DOUBLE',
- 'ISOLATION',
- 'PRIMARY',
- 'THEN',
- 'BY',
- 'DROP',
- 'JOIN',
- 'PRINT',
- 'TO',
- 'CASCADE',
- 'DUMMY',
- 'KEY',
- 'PRIVILEGES',
- 'TOP',
- 'CASE',
- 'DUMP',
- 'KILL',
- 'PROC',
- 'TRAN',
- 'CHECK',
- 'ELSE',
- 'LEFT',
- 'PROCEDURE',
- 'TRANSACTION',
- 'CHECKPOINT',
- 'END',
- 'LEVEL',
- 'PROCESSEXIT',
- 'TRIGGER',
- 'CLOSE',
- 'ERRLVL',
- 'LIKE',
- 'PUBLIC',
- 'TRUNCATE',
- 'CLUSTERED',
- 'ERROREXIT',
- 'LINENO',
- 'RAISERROR',
- 'TSEQUAL',
- 'COALESCE',
- 'ESCAPE',
- 'LOAD',
- 'READ',
- 'UNCOMMITTED',
- 'COLUMN',
- 'EXCEPT',
- 'MAX',
- 'READTEXT',
- 'UNION',
- 'COMMIT',
- 'EXEC',
- 'MIN',
- 'RECONFIGURE',
- 'UNIQUE',
- 'COMMITTED',
- 'EXECUTE',
- 'MIRROREXIT',
- 'REFERENCES',
- 'UPDATE',
- 'COMPUTE',
- 'EXISTS',
- 'NATIONAL',
- 'REPEATABLE',
- 'UPDATETEXT',
- 'CONFIRM',
- 'EXIT',
- 'NOCHECK',
- 'REPLICATION',
- 'USE',
- 'CONSTRAINT',
- 'FETCH',
- 'NONCLUSTERED',
- 'RESTORE',
- 'USER',
- 'CONTAINS',
- 'FILE',
- 'NOT',
- 'RESTRICT',
- 'VALUES',
- 'CONTAINSTABLE',
- 'FILLFACTOR',
- 'NULL',
- 'RETURN',
- 'VARYING',
- 'CONTINUE',
- 'FLOPPY',
- 'NULLIF',
- 'REVOKE',
- 'VIEW',
- 'CONTROLROW',
- 'FOR',
- 'OF',
- 'RIGHT',
- 'WAITFOR',
- 'CONVERT',
- 'FOREIGN',
- 'OFF',
- 'ROLLBACK',
- 'WHEN',
- 'COUNT',
- 'FREETEXT',
- 'OFFSETS',
- 'ROWCOUNT',
- 'WHERE',
- 'CREATE',
- 'FREETEXTTABLE',
- 'ON',
- 'ROWGUIDCOL',
- 'WHILE',
- 'CROSS',
- 'FROM',
- 'ONCE',
- 'RULE',
- 'WITH',
- 'CURRENT',
- 'FULL',
- 'ONLY',
- 'SAVE',
- 'WORK',
- 'CURRENT_DATE',
- 'GOTO',
- 'OPEN',
- 'SCHEMA',
- 'WRITETEXT',
- 'CURRENT_TIME',
- 'GRANT',
- 'OPENDATASOURCE',
- 'SELECT',
-);
-//}}}
-
-?>
diff --git a/inc/MDB2/Schema/Reserved/mysql.php b/inc/MDB2/Schema/Reserved/mysql.php
deleted file mode 100644
index 4f0575e0bb1..00000000000
--- a/inc/MDB2/Schema/Reserved/mysql.php
+++ /dev/null
@@ -1,284 +0,0 @@
-<?php
-// {{{ Disclaimer, Licence, copyrights
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: David Coallier <davidc@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: mysql.php,v 1.3 2006/03/01 12:16:40 lsmith Exp $
-// }}}
-// {{{ $GLOBALS['_MDB2_Schema_Reserved']['mysql']
-/**
- * Has a list of reserved words of mysql
- *
- * @package MDB2_Schema
- * @category Database
- * @access protected
- * @author David Coalier <davidc@php.net>
- */
-$GLOBALS['_MDB2_Schema_Reserved']['mysql'] = array(
- 'ADD',
- 'ALL',
- 'ALTER',
- 'ANALYZE',
- 'AND',
- 'AS',
- 'ASC',
- 'ASENSITIVE',
- 'BEFORE',
- 'BETWEEN',
- 'BIGINT',
- 'BINARY',
- 'BLOB',
- 'BOTH',
- 'BY',
- 'CALL',
- 'CASCADE',
- 'CASE',
- 'CHANGE',
- 'CHAR',
- 'CHARACTER',
- 'CHECK',
- 'COLLATE',
- 'COLUMN',
- 'CONDITION',
- 'CONNECTION',
- 'CONSTRAINT',
- 'CONTINUE',
- 'CONVERT',
- 'CREATE',
- 'CROSS',
- 'CURRENT_DATE',
- 'CURRENT_TIME',
- 'CURRENT_TIMESTAMP',
- 'CURRENT_USER',
- 'CURSOR',
- 'DATABASE',
- 'DATABASES',
- 'DAY_HOUR',
- 'DAY_MICROSECOND',
- 'DAY_MINUTE',
- 'DAY_SECOND',
- 'DEC',
- 'DECIMAL',
- 'DECLARE',
- 'DEFAULT',
- 'DELAYED',
- 'DELETE',
- 'DESC',
- 'DESCRIBE',
- 'DETERMINISTIC',
- 'DISTINCT',
- 'DISTINCTROW',
- 'DIV',
- 'DOUBLE',
- 'DROP',
- 'DUAL',
- 'EACH',
- 'ELSE',
- 'ELSEIF',
- 'ENCLOSED',
- 'ESCAPED',
- 'EXISTS',
- 'EXIT',
- 'EXPLAIN',
- 'FALSE',
- 'FETCH',
- 'FLOAT',
- 'FLOAT4',
- 'FLOAT8',
- 'FOR',
- 'FORCE',
- 'FOREIGN',
- 'FROM',
- 'FULLTEXT',
- 'GOTO',
- 'GRANT',
- 'GROUP',
- 'HAVING',
- 'HIGH_PRIORITY',
- 'HOUR_MICROSECOND',
- 'HOUR_MINUTE',
- 'HOUR_SECOND',
- 'IF',
- 'IGNORE',
- 'IN',
- 'INDEX',
- 'INFILE',
- 'INNER',
- 'INOUT',
- 'INSENSITIVE',
- 'INSERT',
- 'INT',
- 'INT1',
- 'INT2',
- 'INT3',
- 'INT4',
- 'INT8',
- 'INTEGER',
- 'INTERVAL',
- 'INTO',
- 'IS',
- 'ITERATE',
- 'JOIN',
- 'KEY',
- 'KEYS',
- 'KILL',
- 'LABEL',
- 'LEADING',
- 'LEAVE',
- 'LEFT',
- 'LIKE',
- 'LIMIT',
- 'LINES',
- 'LOAD',
- 'LOCALTIME',
- 'LOCALTIMESTAMP',
- 'LOCK',
- 'LONG',
- 'LONGBLOB',
- 'LONGTEXT',
- 'LOOP',
- 'LOW_PRIORITY',
- 'MATCH',
- 'MEDIUMBLOB',
- 'MEDIUMINT',
- 'MEDIUMTEXT',
- 'MIDDLEINT',
- 'MINUTE_MICROSECOND',
- 'MINUTE_SECOND',
- 'MOD',
- 'MODIFIES',
- 'NATURAL',
- 'NOT',
- 'NO_WRITE_TO_BINLOG',
- 'NULL',
- 'NUMERIC',
- 'ON',
- 'OPTIMIZE',
- 'OPTION',
- 'OPTIONALLY',
- 'OR',
- 'ORDER',
- 'OUT',
- 'OUTER',
- 'OUTFILE',
- 'PRECISION',
- 'PRIMARY',
- 'PROCEDURE',
- 'PURGE',
- 'RAID0',
- 'READ',
- 'READS',
- 'REAL',
- 'REFERENCES',
- 'REGEXP',
- 'RELEASE',
- 'RENAME',
- 'REPEAT',
- 'REPLACE',
- 'REQUIRE',
- 'RESTRICT',
- 'RETURN',
- 'REVOKE',
- 'RIGHT',
- 'RLIKE',
- 'SCHEMA',
- 'SCHEMAS',
- 'SECOND_MICROSECOND',
- 'SELECT',
- 'SENSITIVE',
- 'SEPARATOR',
- 'SET',
- 'SHOW',
- 'SMALLINT',
- 'SONAME',
- 'SPATIAL',
- 'SPECIFIC',
- 'SQL',
- 'SQLEXCEPTION',
- 'SQLSTATE',
- 'SQLWARNING',
- 'SQL_BIG_RESULT',
- 'SQL_CALC_FOUND_ROWS',
- 'SQL_SMALL_RESULT',
- 'SSL',
- 'STARTING',
- 'STRAIGHT_JOIN',
- 'TABLE',
- 'TERMINATED',
- 'THEN',
- 'TINYBLOB',
- 'TINYINT',
- 'TINYTEXT',
- 'TO',
- 'TRAILING',
- 'TRIGGER',
- 'TRUE',
- 'UNDO',
- 'UNION',
- 'UNIQUE',
- 'UNLOCK',
- 'UNSIGNED',
- 'UPDATE',
- 'USAGE',
- 'USE',
- 'USING',
- 'UTC_DATE',
- 'UTC_TIME',
- 'UTC_TIMESTAMP',
- 'VALUES',
- 'VARBINARY',
- 'VARCHAR',
- 'VARCHARACTER',
- 'VARYING',
- 'WHEN',
- 'WHERE',
- 'WHILE',
- 'WITH',
- 'WRITE',
- 'X509',
- 'XOR',
- 'YEAR_MONTH',
- 'ZEROFILL',
- );
- // }}}
-?>
diff --git a/inc/MDB2/Schema/Reserved/oci8.php b/inc/MDB2/Schema/Reserved/oci8.php
deleted file mode 100644
index 57fe12ddcab..00000000000
--- a/inc/MDB2/Schema/Reserved/oci8.php
+++ /dev/null
@@ -1,171 +0,0 @@
-<?php
-// {{{ Disclaimer, Licence, copyrights
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: David Coallier <davidc@php.net> |
-// +----------------------------------------------------------------------+
-// }}}
-// {{{ $GLOBALS['_MDB2_Schema_Reserved']['oci8']
-/**
- * Has a list of all the reserved words for oracle.
- *
- * @package MDB2_Schema
- * @category Database
- * @access protected
- * @author David Coallier <davidc@php.net>
- */
-$GLOBALS['_MDB2_Schema_Reserved']['oci8'] = array(
- 'ACCESS',
- 'ELSE',
- 'MODIFY',
- 'START',
- 'ADD',
- 'EXCLUSIVE',
- 'NOAUDIT',
- 'SELECT',
- 'ALL',
- 'EXISTS',
- 'NOCOMPRESS',
- 'SESSION',
- 'ALTER',
- 'FILE',
- 'NOT',
- 'SET',
- 'AND',
- 'FLOAT',
- 'NOTFOUND ',
- 'SHARE',
- 'ANY',
- 'FOR',
- 'NOWAIT',
- 'SIZE',
- 'ARRAYLEN',
- 'FROM',
- 'NULL',
- 'SMALLINT',
- 'AS',
- 'GRANT',
- 'NUMBER',
- 'SQLBUF',
- 'ASC',
- 'GROUP',
- 'OF',
- 'SUCCESSFUL',
- 'AUDIT',
- 'HAVING',
- 'OFFLINE ',
- 'SYNONYM',
- 'BETWEEN',
- 'IDENTIFIED',
- 'ON',
- 'SYSDATE',
- 'BY',
- 'IMMEDIATE',
- 'ONLINE',
- 'TABLE',
- 'CHAR',
- 'IN',
- 'OPTION',
- 'THEN',
- 'CHECK',
- 'INCREMENT',
- 'OR',
- 'TO',
- 'CLUSTER',
- 'INDEX',
- 'ORDER',
- 'TRIGGER',
- 'COLUMN',
- 'INITIAL',
- 'PCTFREE',
- 'UID',
- 'COMMENT',
- 'INSERT',
- 'PRIOR',
- 'UNION',
- 'COMPRESS',
- 'INTEGER',
- 'PRIVILEGES',
- 'UNIQUE',
- 'CONNECT',
- 'INTERSECT',
- 'PUBLIC',
- 'UPDATE',
- 'CREATE',
- 'INTO',
- 'RAW',
- 'USER',
- 'CURRENT',
- 'IS',
- 'RENAME',
- 'VALIDATE',
- 'DATE',
- 'LEVEL',
- 'RESOURCE',
- 'VALUES',
- 'DECIMAL',
- 'LIKE',
- 'REVOKE',
- 'VARCHAR',
- 'DEFAULT',
- 'LOCK',
- 'ROW',
- 'VARCHAR2',
- 'DELETE',
- 'LONG',
- 'ROWID',
- 'VIEW',
- 'DESC',
- 'MAXEXTENTS',
- 'ROWLABEL',
- 'WHENEVER',
- 'DISTINCT',
- 'MINUS',
- 'ROWNUM',
- 'WHERE',
- 'DROP',
- 'MODE',
- 'ROWS',
- 'WITH',
-);
-// }}}
-
-?>
diff --git a/inc/MDB2/Schema/Reserved/pgsql.php b/inc/MDB2/Schema/Reserved/pgsql.php
deleted file mode 100644
index d358e9c12f0..00000000000
--- a/inc/MDB2/Schema/Reserved/pgsql.php
+++ /dev/null
@@ -1,147 +0,0 @@
-<?php
-// {{{ Disclaimer, Licence, copyrights
-// +----------------------------------------------------------------------+
-// | PHP versions 4 and 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1998-2006 Manuel Lemos, Tomas V.V.Cox, |
-// | Stig. S. Bakken, Lukas Smith |
-// | All rights reserved. |
-// +----------------------------------------------------------------------+
-// | MDB2 is a merge of PEAR DB and Metabases that provides a unified DB |
-// | API as well as database abstraction for PHP applications. |
-// | This LICENSE is in the BSD license style. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | |
-// | Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution. |
-// | |
-// | Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken, |
-// | Lukas Smith nor the names of his contributors may be used to endorse |
-// | or promote products derived from this software without specific prior|
-// | written permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS |
-// | FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE |
-// | REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, |
-// | INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, |
-// | BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS|
-// | OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED |
-// | AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT |
-// | LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY|
-// | WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE |
-// | POSSIBILITY OF SUCH DAMAGE. |
-// +----------------------------------------------------------------------+
-// | Author: Marcelo Santos Araujo <msaraujo@php.net> |
-// +----------------------------------------------------------------------+
-//
-// }}}
-// {{{ $GLOBALS['_MDB2_Schema_Reserved']['pgsql']
-/**
- * Has a list of reserved words of pgsql
- *
- * @package MDB2_Schema
- * @category Database
- * @access protected
- * @author Marcelo Santos Araujo <msaraujo@php.net>
- */
-$GLOBALS['_MDB2_Schema_Reserved']['pgsql'] = array(
- 'ALL',
- 'ANALYSE',
- 'ANALYZE',
- 'AND',
- 'ANY',
- 'AS',
- 'ASC',
- 'AUTHORIZATION',
- 'BETWEEN',
- 'BINARY',
- 'BOTH',
- 'CASE',
- 'CAST',
- 'CHECK',
- 'COLLATE',
- 'COLUMN',
- 'CONSTRAINT',
- 'CREATE',
- 'CURRENT_DATE',
- 'CURRENT_TIME',
- 'CURRENT_TIMESTAMP',
- 'CURRENT_USER',
- 'DEFAULT',
- 'DEFERRABLE',
- 'DESC',
- 'DISTINCT',
- 'DO',
- 'ELSE',
- 'END',
- 'EXCEPT',
- 'FALSE',
- 'FOR',
- 'FOREIGN',
- 'FREEZE',
- 'FROM',
- 'FULL',
- 'GRANT',
- 'GROUP',
- 'HAVING',
- 'ILIKE',
- 'IN',
- 'INITIALLY',
- 'INNER',
- 'INTERSECT',
- 'INTO',
- 'IS',
- 'ISNULL',
- 'JOIN',
- 'LEADING',
- 'LEFT',
- 'LIKE',
- 'LIMIT',
- 'LOCALTIME',
- 'LOCALTIMESTAMP',
- 'NATURAL',
- 'NEW',
- 'NOT',
- 'NOTNULL',
- 'NULL',
- 'OFF',
- 'OFFSET',
- 'OLD',
- 'ON',
- 'ONLY',
- 'OR',
- 'ORDER',
- 'OUTER',
- 'OVERLAPS',
- 'PLACING',
- 'PRIMARY',
- 'REFERENCES',
- 'SELECT',
- 'SESSION_USER',
- 'SIMILAR',
- 'SOME',
- 'TABLE',
- 'THEN',
- 'TO',
- 'TRAILING',
- 'TRUE',
- 'UNION',
- 'UNIQUE',
- 'USER',
- 'USING',
- 'VERBOSE',
- 'WHEN',
- 'WHERE'
-);
-// }}}
-?>
-
diff --git a/inc/MDB2/Schema/Tool.php b/inc/MDB2/Schema/Tool.php
deleted file mode 100644
index 9689a0f6d73..00000000000
--- a/inc/MDB2/Schema/Tool.php
+++ /dev/null
@@ -1,560 +0,0 @@
-<?php
-/**
- * PHP versions 4 and 5
- *
- * Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,
- * Stig. S. Bakken, Lukas Smith, Igor Feghali
- * All rights reserved.
- *
- * MDB2_Schema enables users to maintain RDBMS independant schema files
- * in XML that can be used to manipulate both data and database schemas
- * This LICENSE is in the BSD license style.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,
- * Lukas Smith, Igor Feghali nor the names of his contributors may be
- * used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
- * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- * Author: Christian Weiske <cweiske@php.net>
- * $Id: Tool.php,v 1.6 2008/12/13 00:26:07 clockwerx Exp $
- *
- * @category Database
- * @package MDB2_Schema
- * @author Christian Weiske <cweiske@php.net>
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @version CVS: $Id: Tool.php,v 1.6 2008/12/13 00:26:07 clockwerx Exp $
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-
-require_once 'MDB2/Schema.php';
-require_once 'MDB2/Schema/Tool/ParameterException.php';
-
-/**
-* Command line tool to work with database schemas
-*
-* Functionality:
-* - dump a database schema to stdout
-* - import schema into database
-* - create a diff between two schemas
-* - apply diff to database
-*
- * @category Database
- * @package MDB2_Schema
- * @author Christian Weiske <cweiske@php.net>
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-class MDB2_Schema_Tool
-{
- /**
- * Run the schema tool
- *
- * @param array $args Array of command line arguments
- */
- public function __construct($args)
- {
- $strAction = $this->getAction($args);
- try {
- $this->{'do' . ucfirst($strAction)}($args);
- } catch (MDB2_Schema_Tool_ParameterException $e) {
- $this->{'doHelp' . ucfirst($strAction)}($e->getMessage());
- }
- }//public function __construct($args)
-
-
-
- /**
- * Runs the tool with command line arguments
- *
- * @return void
- */
- public static function run()
- {
- $args = $GLOBALS['argv'];
- array_shift($args);
-
- try {
- $tool = new MDB2_Schema_Tool($args);
- } catch (Exception $e) {
- self::toStdErr($e->getMessage() . "\n");
- }
- }//public static function run()
-
-
-
- /**
- * Reads the first parameter from the argument array and
- * returns the action.
- *
- * @param array &$args Command line parameters
- *
- * @return string Action to execute
- */
- protected function getAction(&$args)
- {
- if (count($args) == 0) {
- return 'help';
- }
- $arg = array_shift($args);
- switch ($arg) {
- case 'h':
- case 'help':
- case '-h':
- case '--help':
- return 'help';
- case 'd':
- case 'dump':
- case '-d':
- case '--dump':
- return 'dump';
- case 'l':
- case 'load':
- case '-l':
- case '--load':
- return 'load';
- case 'i':
- case 'diff':
- case '-i':
- case '--diff':
- return 'diff';
- case 'a':
- case 'apply':
- case '-a':
- case '--apply':
- return 'apply';
- case 'n':
- case 'init':
- case '-i':
- case '--init':
- return 'init';
- default:
- throw new MDB2_Schema_Tool_ParameterException("Unknown mode \"$arg\"");
- }
- }//protected function getAction(&$args)
-
-
-
- /**
- * Writes the message to stderr
- *
- * @param string $msg Message to print
- *
- * @return void
- */
- protected static function toStdErr($msg)
- {
- file_put_contents('php://stderr', $msg);
- }//protected static function toStdErr($msg)
-
-
-
- /**
- * Displays generic help to stdout
- *
- * @return void
- */
- protected function doHelp()
- {
- self::toStdErr(<<<EOH
-Usage: mdb2_schematool mode parameters
-
-Works with database schemas
-
-mode: (- and -- are optional)
- h, help Show this help screen
- d, dump Dump a schema to stdout
- l, load Load a schema into database
- i, diff Create a diff between two schemas and dump it to stdout
- a, apply Apply a diff to a database
- n, init Initialize a database with data
-
-EOH
- );
- }//protected function doHelp()
-
-
-
- /**
- * Displays the help screen for "dump" command
- *
- * @return void
- */
- protected function doHelpDump()
- {
- self::toStdErr( <<<EOH
-Usage: mdb2_schematool dump [all|data|schema] [-p] DSN
-
-Dumps a database schema to stdout
-
-If dump type is not specified, defaults to "schema".
-
-DSN: Data source name in the form of
- driver://user:password@host/database
-
-User and password may be omitted.
-Using -p reads password from stdin which is more secure than passing it in the parameter.
-
-EOH
- );
- }//protected function doHelpDump()
-
-
-
- /**
- * Displays the help screen for "init" command
- *
- * @return void
- */
- protected function doHelpInit()
- {
- self::toStdErr( <<<EOH
-Usage: mdb2_schematool init source [-p] destination
-
-Initializes a database with data
- (Inserts data on a previous created database at destination)
-
-source should be a schema file containing data,
-destination should be a DSN
-
-DSN: Data source name in the form of
- driver://user:password@host/database
-
-User and password may be omitted.
-Using -p reads password from stdin which is more secure than passing it in the parameter.
-
-EOH
- );
- }//protected function doHelpInit()
-
-
-
- /**
- * Displays the help screen for "load" command
- *
- * @return void
- */
- protected function doHelpLoad()
- {
- self::toStdErr( <<<EOH
-Usage: mdb2_schematool load [-p] source [-p] destination
-
-Loads a database schema from source to destination
- (Creates the database schema at destination)
-
-source can be a DSN or a schema file,
-destination should be a DSN
-
-DSN: Data source name in the form of
- driver://user:password@host/database
-
-User and password may be omitted.
-Using -p reads password from stdin which is more secure than passing it in the parameter.
-
-EOH
- );
- }//protected function doHelpLoad()
-
-
-
- /**
- * Returns an array of options for MDB2_Schema constructor
- *
- * @return array Options for MDB2_Schema constructor
- */
- protected function getSchemaOptions()
- {
- $options = array(
- 'log_line_break' => '<br>',
- 'idxname_format' => '%s',
- 'debug' => true,
- 'quote_identifier' => true,
- 'force_defaults' => false,
- 'portability' => true,
- 'use_transactions' => false,
- );
- return $options;
- }//protected function getSchemaOptions()
-
-
-
- /**
- * Checks if the passed parameter is a PEAR_Error object
- * and throws an exception in that case.
- *
- * @param mixed $object Some variable to check
- * @param string $location Where the error occured
- *
- * @return void
- */
- protected function throwExceptionOnError($object, $location = '')
- {
- if (PEAR::isError($object)) {
- //FIXME: exception class
- //debug_print_backtrace();
- throw new Exception('Error ' . $location
- . "\n" . $object->getMessage()
- . "\n" . $object->getUserInfo()
- );
- }
- }//protected function throwExceptionOnError($object, $location = '')
-
-
-
- /**
- * Loads a file or a dsn from the arguments
- *
- * @param array &$args Array of arguments to the program
- *
- * @return array Array of ('file'|'dsn', $value)
- */
- protected function getFileOrDsn(&$args)
- {
- if (count($args) == 0) {
- throw new MDB2_Schema_Tool_ParameterException('File or DSN expected');
- }
-
- $arg = array_shift($args);
- if ($arg == '-p') {
- $bAskPassword = true;
- $arg = array_shift($args);
- } else {
- $bAskPassword = false;
- }
-
- if (strpos($arg, '://') === false) {
- if (file_exists($arg)) {
- //File
- return array('file', $arg);
- } else {
- throw new Exception('Schema file does not exist');
- }
- }
-
- //read password if necessary
- if ($bAskPassword) {
- $password = $this->readPasswordFromStdin($arg);
- $arg = self::setPasswordIntoDsn($arg, $password);
- self::toStdErr($arg);
- }
- return array('dsn', $arg);
- }//protected function getFileOrDsn(&$args)
-
-
-
- /**
- * Takes a DSN data source name and integrates the given
- * password into it.
- *
- * @param string $dsn Data source name
- * @param string $password Password
- *
- * @return string DSN with password
- */
- protected function setPasswordIntoDsn($dsn, $password)
- {
- //simple try to integrate password
- if (strpos($dsn, '@') === false) {
- //no @ -> no user and no password
- return str_replace('://', '://:' . $password . '@', $dsn);
- } else if (preg_match('|://[^:]+@|', $dsn)) {
- //user only, no password
- return str_replace('@', ':' . $password . '@', $dsn);
- } else if (strpos($dsn, ':@') !== false) {
- //abstract version
- return str_replace(':@', ':' . $password . '@', $dsn);
- }
-
- return $dsn;
- }//protected function setPasswordIntoDsn($dsn, $password)
-
-
-
- /**
- * Reads a password from stdin
- *
- * @param string $dsn DSN name to put into the message
- *
- * @return string Password
- */
- protected function readPasswordFromStdin($dsn)
- {
- $stdin = fopen('php://stdin', 'r');
- self::toStdErr('Please insert password for ' . $dsn . "\n");
- $password = '';
- $breakme = false;
- while (false !== ($char = fgetc($stdin))) {
- if (ord($char) == 10 || $char == "\n" || $char == "\r") {
- break;
- }
- $password .= $char;
- }
- fclose($stdin);
-
- return trim($password);
- }//protected function readPasswordFromStdin()
-
-
-
- /**
- * Creates a database schema dump and sends it to stdout
- *
- * @param array $args Command line arguments
- *
- * @return void
- */
- protected function doDump($args)
- {
- $dump_what = MDB2_SCHEMA_DUMP_STRUCTURE;
- $arg = '';
- if (count($args)) {
- $arg = $args[0];
- }
-
- switch (strtolower($arg)) {
- case 'all':
- $dump_what = MDB2_SCHEMA_DUMP_ALL;
- array_shift($args);
- break;
- case 'data':
- $dump_what = MDB2_SCHEMA_DUMP_CONTENT;
- array_shift($args);
- break;
- case 'schema':
- array_shift($args);
- }
-
- list($type, $dsn) = $this->getFileOrDsn($args);
- if ($type == 'file') {
- throw new MDB2_Schema_Tool_ParameterException(
- 'Dumping a schema file as a schema file does not make much sense'
- );
- }
-
- $schema = MDB2_Schema::factory($dsn, $this->getSchemaOptions());
- $this->throwExceptionOnError($schema);
-
- $definition = $schema->getDefinitionFromDatabase();
- $this->throwExceptionOnError($definition);
-
-
- $dump_options = array(
- 'output_mode' => 'file',
- 'output' => 'php://stdout',
- 'end_of_line' => "\r\n"
- );
- $op = $schema->dumpDatabase(
- $definition, $dump_options, $dump_what
- );
- $this->throwExceptionOnError($op);
-
- $schema->disconnect();
- }//protected function doDump($args)
-
-
-
- /**
- * Loads a database schema
- *
- * @param array $args Command line arguments
- *
- * @return void
- */
- protected function doLoad($args)
- {
- list($typeSource, $dsnSource) = $this->getFileOrDsn($args);
- list($typeDest, $dsnDest) = $this->getFileOrDsn($args);
-
- if ($typeDest == 'file') {
- throw new MDB2_Schema_Tool_ParameterException(
- 'A schema can only be loaded into a database, not a file'
- );
- }
-
-
- $schemaDest = MDB2_Schema::factory($dsnDest, $this->getSchemaOptions());
- $this->throwExceptionOnError($schemaDest);
-
- //load definition
- if ($typeSource == 'file') {
- $definition = $schemaDest->parseDatabaseDefinitionFile($dsnSource);
- $where = 'loading schema file';
- } else {
- $schemaSource = MDB2_Schema::factory($dsnSource, $this->getSchemaOptions());
- $this->throwExceptionOnError($schemaSource, 'connecting to source database');
-
- $definition = $schemaSource->getDefinitionFromDatabase();
- $where = 'loading definition from database';
- }
- $this->throwExceptionOnError($definition, $where);
-
-
- //create destination database from definition
- $simulate = false;
- $op = $schemaDest->createDatabase($definition, array(), $simulate);
- $this->throwExceptionOnError($op, 'creating the database');
- }//protected function doLoad($args)
-
-
-
- /**
- * Initializes a database with data
- *
- * @param array $args Command line arguments
- *
- * @return void
- */
- protected function doInit($args)
- {
- list($typeSource, $dsnSource) = $this->getFileOrDsn($args);
- list($typeDest, $dsnDest) = $this->getFileOrDsn($args);
-
- if ($typeSource != 'file') {
- throw new MDB2_Schema_Tool_ParameterException(
- 'Data must come from a source file'
- );
- }
-
- if ($typeDest != 'dsn') {
- throw new MDB2_Schema_Tool_ParameterException(
- 'A schema can only be loaded into a database, not a file'
- );
- }
-
- $schemaDest = MDB2_Schema::factory($dsnDest, $this->getSchemaOptions());
- $this->throwExceptionOnError($schemaDest, 'connecting to destination database');
-
- $definition = $schemaDest->getDefinitionFromDatabase();
- $this->throwExceptionOnError($definition, 'loading definition from database');
-
- $op = $schemaDest->writeInitialization($dsnSource, $definition);
- $this->throwExceptionOnError($op, 'initializing database');
- }//protected function doInit($args)
-
-
-}//class MDB2_Schema_Tool
-
-?>
diff --git a/inc/MDB2/Schema/Tool/ParameterException.php b/inc/MDB2/Schema/Tool/ParameterException.php
deleted file mode 100644
index fab1e03e250..00000000000
--- a/inc/MDB2/Schema/Tool/ParameterException.php
+++ /dev/null
@@ -1,6 +0,0 @@
-<?php
-
-class MDB2_Schema_Tool_ParameterException extends Exception
-{}
-
-?> \ No newline at end of file
diff --git a/inc/MDB2/Schema/Validate.php b/inc/MDB2/Schema/Validate.php
deleted file mode 100644
index 21be024ce9f..00000000000
--- a/inc/MDB2/Schema/Validate.php
+++ /dev/null
@@ -1,922 +0,0 @@
-<?php
-/**
- * PHP versions 4 and 5
- *
- * Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,
- * Stig. S. Bakken, Lukas Smith, Igor Feghali
- * All rights reserved.
- *
- * MDB2_Schema enables users to maintain RDBMS independant schema files
- * in XML that can be used to manipulate both data and database schemas
- * This LICENSE is in the BSD license style.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,
- * Lukas Smith, Igor Feghali nor the names of his contributors may be
- * used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
- * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- * Author: Christian Dickmann <dickmann@php.net>
- * Author: Igor Feghali <ifeghali@php.net>
- *
- * @category Database
- * @package MDB2_Schema
- * @author Christian Dickmann <dickmann@php.net>
- * @author Igor Feghali <ifeghali@php.net>
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @version CVS: $Id: Validate.php,v 1.42 2008/11/30 03:34:00 clockwerx Exp $
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-
-/**
- * Validates an XML schema file
- *
- * @category Database
- * @package MDB2_Schema
- * @author Igor Feghali <ifeghali@php.net>
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-class MDB2_Schema_Validate
-{
- // {{{ properties
-
- var $fail_on_invalid_names = true;
-
- var $valid_types = array();
-
- var $force_defaults = true;
-
- // }}}
- // {{{ constructor
-
- function __construct($fail_on_invalid_names = true, $valid_types = array(), $force_defaults = true)
- {
- if (empty($GLOBALS['_MDB2_Schema_Reserved'])) {
- $GLOBALS['_MDB2_Schema_Reserved'] = array();
- }
-
- if (is_array($fail_on_invalid_names)) {
- $this->fail_on_invalid_names = array_intersect($fail_on_invalid_names,
- array_keys($GLOBALS['_MDB2_Schema_Reserved']));
- } elseif ($fail_on_invalid_names === true) {
- $this->fail_on_invalid_names = array_keys($GLOBALS['_MDB2_Schema_Reserved']);
- } else {
- $this->fail_on_invalid_names = array();
- }
- $this->valid_types = $valid_types;
- $this->force_defaults = $force_defaults;
- }
-
- function MDB2_Schema_Validate($fail_on_invalid_names = true, $valid_types = array(), $force_defaults = true)
- {
- $this->__construct($fail_on_invalid_names, $valid_types, $force_defaults);
- }
-
- // }}}
- // {{{ raiseError()
-
- function &raiseError($ecode, $msg = null)
- {
- $error =& MDB2_Schema::raiseError($ecode, null, null, $msg);
- return $error;
- }
-
- // }}}
- // {{{ isBoolean()
-
- /**
- * Verifies if a given value can be considered boolean. If yes, set value
- * to true or false according to its actual contents and return true. If
- * not, keep its contents untouched and return false.
- *
- * @param mixed &$value value to be checked
- *
- * @return bool
- *
- * @access public
- * @static
- */
- function isBoolean(&$value)
- {
- if (is_bool($value)) {
- return true;
- }
-
- if ($value === 0 || $value === 1 || $value === '') {
- $value = (bool)$value;
- return true;
- }
-
- if (!is_string($value)) {
- return false;
- }
-
- switch ($value) {
- case '0':
- case 'N':
- case 'n':
- case 'no':
- case 'false':
- $value = false;
- break;
- case '1':
- case 'Y':
- case 'y':
- case 'yes':
- case 'true':
- $value = true;
- break;
- default:
- return false;
- }
- return true;
- }
-
- // }}}
- // {{{ validateTable()
-
- /* Definition */
- /**
- * Checks whether the definition of a parsed table is valid. Modify table
- * definition when necessary.
- *
- * @param array $tables multi dimensional array that contains the
- * tables of current database.
- * @param array &$table multi dimensional array that contains the
- * structure and optional data of the table.
- * @param string $table_name name of the parsed table
- *
- * @return bool|error object
- *
- * @access public
- */
- function validateTable($tables, &$table, $table_name)
- {
- /* Have we got a name? */
- if (!$table_name) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'a table has to have a name');
- }
-
- /* Table name duplicated? */
- if (is_array($tables) && isset($tables[$table_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'table "'.$table_name.'" already exists');
- }
-
- /* Table name reserved? */
- if (is_array($this->fail_on_invalid_names)) {
- $name = strtoupper($table_name);
- foreach ($this->fail_on_invalid_names as $rdbms) {
- if (in_array($name, $GLOBALS['_MDB2_Schema_Reserved'][$rdbms])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'table name "'.$table_name.'" is a reserved word in: '.$rdbms);
- }
- }
- }
-
- /* Was */
- if (empty($table['was'])) {
- $table['was'] = $table_name;
- }
-
- /* Have we got fields? */
- if (empty($table['fields']) || !is_array($table['fields'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'tables need one or more fields');
- }
-
- /* Autoincrement */
- $autoinc = $primary = false;
- foreach ($table['fields'] as $field_name => $field) {
- if (!empty($field['autoincrement'])) {
- if ($autoinc) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'there was already an autoincrement field in "'.$table_name.'" before "'.$field_name.'"');
- }
- $autoinc = $field_name;
- }
- }
-
- /*
- * Checking Indexes
- * this have to be done here otherwise we can't
- * guarantee that all table fields were already
- * defined in the moment we are parsing indexes
- */
- if (!empty($table['indexes']) && is_array($table['indexes'])) {
- foreach ($table['indexes'] as $name => $index) {
- $skip_index = false;
- if (!empty($index['primary'])) {
- /*
- * Lets see if we should skip this index since there is
- * already an auto increment on this field this implying
- * a primary key index.
- */
- if (count($index['fields']) == '1'
- && $autoinc
- && array_key_exists($autoinc, $index['fields'])) {
- $skip_index = true;
- } elseif ($autoinc || $primary) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'there was already an primary index or autoincrement field in "'.$table_name.'" before "'.$name.'"');
- } else {
- $primary = true;
- }
- }
-
- if (!$skip_index && is_array($index['fields'])) {
- foreach ($index['fields'] as $field_name => $field) {
- if (!isset($table['fields'][$field_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'index field "'.$field_name.'" does not exist');
- }
- if (!empty($index['primary'])
- && !$table['fields'][$field_name]['notnull']
- ) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'all primary key fields must be defined notnull in "'.$table_name.'"');
- }
- }
- } else {
- unset($table['indexes'][$name]);
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ validateField()
-
- /**
- * Checks whether the definition of a parsed field is valid. Modify field
- * definition when necessary.
- *
- * @param array $fields multi dimensional array that contains the
- * fields of current table.
- * @param array &$field multi dimensional array that contains the
- * structure of the parsed field.
- * @param string $field_name name of the parsed field
- *
- * @return bool|error object
- *
- * @access public
- */
- function validateField($fields, &$field, $field_name)
- {
- /* Have we got a name? */
- if (!$field_name) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'field name missing');
- }
-
- /* Field name duplicated? */
- if (is_array($fields) && isset($fields[$field_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'field "'.$field_name.'" already exists');
- }
-
- /* Field name reserverd? */
- if (is_array($this->fail_on_invalid_names)) {
- $name = strtoupper($field_name);
- foreach ($this->fail_on_invalid_names as $rdbms) {
- if (in_array($name, $GLOBALS['_MDB2_Schema_Reserved'][$rdbms])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'field name "'.$field_name.'" is a reserved word in: '.$rdbms);
- }
- }
- }
-
- /* Type check */
- if (empty($field['type'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'no field type specified');
- }
- if (!empty($this->valid_types) && !array_key_exists($field['type'], $this->valid_types)) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'no valid field type ("'.$field['type'].'") specified');
- }
-
- /* Unsigned */
- if (array_key_exists('unsigned', $field) && !$this->isBoolean($field['unsigned'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'unsigned has to be a boolean value');
- }
-
- /* Fixed */
- if (array_key_exists('fixed', $field) && !$this->isBoolean($field['fixed'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'fixed has to be a boolean value');
- }
-
- /* Length */
- if (array_key_exists('length', $field) && $field['length'] <= 0) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'length has to be an integer greater 0');
- }
-
- // if it's a DECIMAL datatype, check if a 'scale' value is provided:
- // <length>8,4</length> should be translated to DECIMAL(8,4)
- if (is_float($this->valid_types[$field['type']])
- && !empty($field['length'])
- && strpos($field['length'], ',') !== false
- ) {
- list($field['length'], $field['scale']) = explode(',', $field['length']);
- }
-
- /* Was */
- if (empty($field['was'])) {
- $field['was'] = $field_name;
- }
-
- /* Notnull */
- if (empty($field['notnull'])) {
- $field['notnull'] = false;
- }
- if (!$this->isBoolean($field['notnull'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'field "notnull" has to be a boolean value');
- }
-
- /* Default */
- if ($this->force_defaults
- && !array_key_exists('default', $field)
- && $field['type'] != 'clob' && $field['type'] != 'blob'
- ) {
- $field['default'] = $this->valid_types[$field['type']];
- }
- if (array_key_exists('default', $field)) {
- if ($field['type'] == 'clob' || $field['type'] == 'blob') {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field['type'].'"-fields are not allowed to have a default value');
- }
- if ($field['default'] === '' && !$field['notnull']) {
- $field['default'] = null;
- }
- }
- if (isset($field['default'])
- && PEAR::isError($result = $this->validateDataFieldValue($field, $field['default'], $field_name))
- ) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'default value of "'.$field_name.'" is incorrect: '.$result->getUserinfo());
- }
-
- /* Autoincrement */
- if (!empty($field['autoincrement'])) {
- if (!$field['notnull']) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'all autoincrement fields must be defined notnull');
- }
-
- if (empty($field['default'])) {
- $field['default'] = '0';
- } elseif ($field['default'] !== '0' && $field['default'] !== 0) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'all autoincrement fields must be defined default "0"');
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ validateIndex()
-
- /**
- * Checks whether a parsed index is valid. Modify index definition when
- * necessary.
- *
- * @param array $table_indexes multi dimensional array that contains the
- * indexes of current table.
- * @param array &$index multi dimensional array that contains the
- * structure of the parsed index.
- * @param string $index_name name of the parsed index
- *
- * @return bool|error object
- *
- * @access public
- */
- function validateIndex($table_indexes, &$index, $index_name)
- {
- if (!$index_name) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'an index has to have a name');
- }
- if (is_array($table_indexes) && isset($table_indexes[$index_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'index "'.$index_name.'" already exists');
- }
- if (array_key_exists('unique', $index) && !$this->isBoolean($index['unique'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'field "unique" has to be a boolean value');
- }
- if (array_key_exists('primary', $index) && !$this->isBoolean($index['primary'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'field "primary" has to be a boolean value');
- }
-
- /* Have we got fields? */
- if (empty($index['fields']) || !is_array($index['fields'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'indexes need one or more fields');
- }
-
- if (empty($index['was'])) {
- $index['was'] = $index_name;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ validateIndexField()
-
- /**
- * Checks whether a parsed index-field is valid. Modify its definition when
- * necessary.
- *
- * @param array $index_fields multi dimensional array that contains the
- * fields of current index.
- * @param array &$field multi dimensional array that contains the
- * structure of the parsed index-field.
- * @param string $field_name name of the parsed index-field
- *
- * @return bool|error object
- *
- * @access public
- */
- function validateIndexField($index_fields, &$field, $field_name)
- {
- if (is_array($index_fields) && isset($index_fields[$field_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'index field "'.$field_name.'" already exists');
- }
- if (!$field_name) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'the index-field-name is required');
- }
- if (empty($field['sorting'])) {
- $field['sorting'] = 'ascending';
- } elseif ($field['sorting'] !== 'ascending' && $field['sorting'] !== 'descending') {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'sorting type unknown');
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ validateConstraint()
-
- /**
- * Checks whether a parsed foreign key is valid. Modify its definition when
- * necessary.
- *
- * @param array $table_constraints multi dimensional array that contains the
- * constraints of current table.
- * @param array &$constraint multi dimensional array that contains the
- * structure of the parsed foreign key.
- * @param string $constraint_name name of the parsed foreign key
- *
- * @return bool|error object
- *
- * @access public
- */
- function validateConstraint($table_constraints, &$constraint, $constraint_name)
- {
- if (!$constraint_name) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'a foreign key has to have a name');
- }
- if (is_array($table_constraints) && isset($table_constraints[$constraint_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'foreign key "'.$constraint_name.'" already exists');
- }
-
- /* Have we got fields? */
- if (empty($constraint['fields']) || !is_array($constraint['fields'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'foreign key "'.$constraint_name.'" need one or more fields');
- }
-
- /* Have we got referenced fields? */
- if (empty($constraint['references']) || !is_array($constraint['references'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'foreign key "'.$constraint_name.'" need to reference one or more fields');
- }
-
- /* Have we got referenced table? */
- if (empty($constraint['references']['table'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'foreign key "'.$constraint_name.'" need to reference a table');
- }
-
- if (empty($constraint['was'])) {
- $constraint['was'] = $constraint_name;
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ validateConstraintField()
-
- /**
- * Checks whether a foreign-field is valid.
- *
- * @param array $constraint_fields multi dimensional array that contains the
- * fields of current foreign key.
- * @param string $field_name name of the parsed foreign-field
- *
- * @return bool|error object
- *
- * @access public
- */
- function validateConstraintField($constraint_fields, $field_name)
- {
- if (!$field_name) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'empty value for foreign-field');
- }
- if (is_array($constraint_fields) && isset($constraint_fields[$field_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'foreign field "'.$field_name.'" already exists');
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ validateConstraintReferencedField()
-
- /**
- * Checks whether a foreign-referenced field is valid.
- *
- * @param array $referenced_fields multi dimensional array that contains the
- * fields of current foreign key.
- * @param string $field_name name of the parsed foreign-field
- *
- * @return bool|error object
- *
- * @access public
- */
- function validateConstraintReferencedField($referenced_fields, $field_name)
- {
- if (!$field_name) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'empty value for referenced foreign-field');
- }
- if (is_array($referenced_fields) && isset($referenced_fields[$field_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'foreign field "'.$field_name.'" already referenced');
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ validateSequence()
-
- /**
- * Checks whether the definition of a parsed sequence is valid. Modify
- * sequence definition when necessary.
- *
- * @param array $sequences multi dimensional array that contains the
- * sequences of current database.
- * @param array &$sequence multi dimensional array that contains the
- * structure of the parsed sequence.
- * @param string $sequence_name name of the parsed sequence
- *
- * @return bool|error object
- *
- * @access public
- */
- function validateSequence($sequences, &$sequence, $sequence_name)
- {
- if (!$sequence_name) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'a sequence has to have a name');
- }
-
- if (is_array($sequences) && isset($sequences[$sequence_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'sequence "'.$sequence_name.'" already exists');
- }
-
- if (is_array($this->fail_on_invalid_names)) {
- $name = strtoupper($sequence_name);
- foreach ($this->fail_on_invalid_names as $rdbms) {
- if (in_array($name, $GLOBALS['_MDB2_Schema_Reserved'][$rdbms])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'sequence name "'.$sequence_name.'" is a reserved word in: '.$rdbms);
- }
- }
- }
-
- if (empty($sequence['was'])) {
- $sequence['was'] = $sequence_name;
- }
-
- if (!empty($sequence['on'])
- && (empty($sequence['on']['table']) || empty($sequence['on']['field']))
- ) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'sequence "'.$sequence_name.'" on a table was not properly defined');
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ validateDatabase()
-
- /**
- * Checks whether a parsed database is valid. Modify its structure and
- * data when necessary.
- *
- * @param array &$database multi dimensional array that contains the
- * structure and optional data of the database.
- *
- * @return bool|error object
- *
- * @access public
- */
- function validateDatabase(&$database)
- {
- /* Have we got a name? */
- if (!is_array($database) || !isset($database['name']) || !$database['name']) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'a database has to have a name');
- }
-
- /* Database name reserved? */
- if (is_array($this->fail_on_invalid_names)) {
- $name = strtoupper($database['name']);
- foreach ($this->fail_on_invalid_names as $rdbms) {
- if (in_array($name, $GLOBALS['_MDB2_Schema_Reserved'][$rdbms])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'database name "'.$database['name'].'" is a reserved word in: '.$rdbms);
- }
- }
- }
-
- /* Create */
- if (isset($database['create'])
- && !$this->isBoolean($database['create'])
- ) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'field "create" has to be a boolean value');
- }
-
- /* Overwrite */
- if (isset($database['overwrite'])
- && $database['overwrite'] !== ''
- && !$this->isBoolean($database['overwrite'])
- ) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'field "overwrite" has to be a boolean value');
- }
-
- /*
- * This have to be done here otherwise we can't guarantee that all
- * tables were already defined in the moment we are parsing constraints
- */
- if (isset($database['tables'])) {
- foreach ($database['tables'] as $table_name => $table) {
- if (!empty($table['constraints'])) {
- foreach ($table['constraints'] as $constraint_name => $constraint) {
- $referenced_table_name = $constraint['references']['table'];
-
- if (!isset($database['tables'][$referenced_table_name])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'referenced table "'.$referenced_table_name.'" of foreign key "'.$constraint_name.'" of table "'.$table_name.'" does not exist');
- }
-
- if (empty($constraint['references']['fields'])) {
- $referenced_table = $database['tables'][$referenced_table_name];
-
- $primary = false;
-
- if (!empty($referenced_table['indexes'])) {
- foreach ($referenced_table['indexes'] as $index_name => $index) {
- if (array_key_exists('primary', $index)
- && $index['primary']
- ) {
- $primary = array();
- foreach ($index['fields'] as $field_name => $field) {
- $primary[$field_name] = '';
- }
- break;
- }
- }
- }
-
- if (!$primary) {
- foreach ($referenced_table['fields'] as $field_name => $field) {
- if (array_key_exists('autoincrement', $field)
- && $field['autoincrement']
- ) {
- $primary = array( $field_name => '' );
- break;
- }
- }
- }
-
- if (!$primary) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'referenced table "'.$referenced_table_name.'" has no primary key and no referenced field was specified for foreign key "'.$constraint_name.'" of table "'.$table_name.'"');
- }
-
- $constraint['references']['fields'] = $primary;
- }
-
- /* the same number of referencing and referenced fields ? */
- if (count($constraint['fields']) != count($constraint['references']['fields'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'The number of fields in the referenced key must match those of the foreign key "'.$constraint_name.'"');
- }
-
- $database['tables'][$table_name]['constraints'][$constraint_name]['references']['fields'] = $constraint['references']['fields'];
- }
- }
- }
- }
-
- /*
- * This have to be done here otherwise we can't guarantee that all
- * tables were already defined in the moment we are parsing sequences
- */
- if (isset($database['sequences'])) {
- foreach ($database['sequences'] as $seq_name => $seq) {
- if (!empty($seq['on'])
- && empty($database['tables'][$seq['on']['table']]['fields'][$seq['on']['field']])
- ) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'sequence "'.$seq_name.'" was assigned on unexisting field/table');
- }
- }
- }
- return MDB2_OK;
- }
-
- // }}}
- // {{{ validateDataField()
-
- /* Data Manipulation */
- /**
- * Checks whether a parsed DML-field is valid. Modify its structure when
- * necessary. This is called when validating INSERT and
- * UPDATE.
- *
- * @param array $table_fields multi dimensional array that contains the
- * definition for current table's fields.
- * @param array $instruction_fields multi dimensional array that contains the
- * parsed fields of the current DML instruction.
- * @param string &$field array that contains the parsed instruction field
- *
- * @return bool|error object
- *
- * @access public
- */
- function validateDataField($table_fields, $instruction_fields, &$field)
- {
- if (!$field['name']) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'field-name has to be specified');
- }
-
- if (is_array($instruction_fields) && isset($instruction_fields[$field['name']])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'field "'.$field['name'].'" already initialized');
- }
-
- if (is_array($table_fields) && !isset($table_fields[$field['name']])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field['name'].'" is not defined');
- }
-
- if (!isset($field['group']['type'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field['name'].'" has no initial value');
- }
-
- if (isset($field['group']['data'])
- && $field['group']['type'] == 'value'
- && $field['group']['data'] !== ''
- && PEAR::isError($result = $this->validateDataFieldValue($table_fields[$field['name']], $field['group']['data'], $field['name']))
- ) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- 'value of "'.$field['name'].'" is incorrect: '.$result->getUserinfo());
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ validateDataFieldValue()
-
- /**
- * Checks whether a given value is compatible with a table field. This is
- * done when parsing a field for a INSERT or UPDATE instruction.
- *
- * @param array $field_def multi dimensional array that contains the
- * definition for current table's fields.
- * @param string &$field_value value to fill the parsed field
- * @param string $field_name name of the parsed field
- *
- * @return bool|error object
- *
- * @access public
- * @see MDB2_Schema_Validate::validateInsertField()
- */
- function validateDataFieldValue($field_def, &$field_value, $field_name)
- {
- switch ($field_def['type']) {
- case 'text':
- case 'clob':
- if (!empty($field_def['length']) && strlen($field_value) > $field_def['length']) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field_value.'" is larger than "'.$field_def['length'].'"');
- }
- break;
- case 'blob':
- $field_value = pack('H*', $field_value);
- if (!empty($field_def['length']) && strlen($field_value) > $field_def['length']) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field_value.'" is larger than "'.$field_def['type'].'"');
- }
- break;
- case 'integer':
- if ($field_value != ((int)$field_value)) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field_value.'" is not of type "'.$field_def['type'].'"');
- }
- //$field_value = (int)$field_value;
- if (!empty($field_def['unsigned']) && $field_def['unsigned'] && $field_value < 0) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field_value.'" signed instead of unsigned');
- }
- break;
- case 'boolean':
- if (!$this->isBoolean($field_value)) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field_value.'" is not of type "'.$field_def['type'].'"');
- }
- break;
- case 'date':
- if (!preg_match('/([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})/', $field_value)
- && $field_value !== 'CURRENT_DATE'
- ) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field_value.'" is not of type "'.$field_def['type'].'"');
- }
- break;
- case 'timestamp':
- if (!preg_match('/([0-9]{4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})/', $field_value)
- && strcasecmp($field_value, 'now()') != 0
- && $field_value !== 'CURRENT_TIMESTAMP'
- ) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field_value.'" is not of type "'.$field_def['type'].'"');
- }
- break;
- case 'time':
- if (!preg_match("/([0-9]{2}):([0-9]{2}):([0-9]{2})/", $field_value)
- && $field_value !== 'CURRENT_TIME'
- ) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field_value.'" is not of type "'.$field_def['type'].'"');
- }
- break;
- case 'float':
- case 'double':
- if ($field_value != (double)$field_value) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE,
- '"'.$field_value.'" is not of type "'.$field_def['type'].'"');
- }
- //$field_value = (double)$field_value;
- break;
- }
- return MDB2_OK;
- }
-}
-
-?>
diff --git a/inc/MDB2/Schema/Writer.php b/inc/MDB2/Schema/Writer.php
deleted file mode 100644
index 5ae4918dc1d..00000000000
--- a/inc/MDB2/Schema/Writer.php
+++ /dev/null
@@ -1,581 +0,0 @@
-<?php
-/**
- * PHP versions 4 and 5
- *
- * Copyright (c) 1998-2008 Manuel Lemos, Tomas V.V.Cox,
- * Stig. S. Bakken, Lukas Smith, Igor Feghali
- * All rights reserved.
- *
- * MDB2_Schema enables users to maintain RDBMS independant schema files
- * in XML that can be used to manipulate both data and database schemas
- * This LICENSE is in the BSD license style.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * Neither the name of Manuel Lemos, Tomas V.V.Cox, Stig. S. Bakken,
- * Lukas Smith, Igor Feghali nor the names of his contributors may be
- * used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
- * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
- * REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
- * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
- * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
- * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
- * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- *
- * Author: Lukas Smith <smith@pooteeweet.org>
- * Author: Igor Feghali <ifeghali@php.net>
- *
- * @category Database
- * @package MDB2_Schema
- * @author Lukas Smith <smith@pooteeweet.org>
- * @author Igor Feghali <ifeghali@php.net>
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @version CVS: $Id: Writer.php,v 1.40 2008/11/30 03:34:00 clockwerx Exp $
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-
-/**
- * Writes an XML schema file
- *
- * @category Database
- * @package MDB2_Schema
- * @author Lukas Smith <smith@pooteeweet.org>
- * @license BSD http://www.opensource.org/licenses/bsd-license.php
- * @link http://pear.php.net/packages/MDB2_Schema
- */
-class MDB2_Schema_Writer
-{
- // {{{ properties
-
- var $valid_types = array();
-
- // }}}
- // {{{ constructor
-
- function __construct($valid_types = array())
- {
- $this->valid_types = $valid_types;
- }
-
- function MDB2_Schema_Writer($valid_types = array())
- {
- $this->__construct($valid_types);
- }
-
- // }}}
- // {{{ raiseError()
-
- /**
- * This method is used to communicate an error and invoke error
- * callbacks etc. Basically a wrapper for PEAR::raiseError
- * without the message string.
- *
- * @param int|PEAR_Error $code integer error code or and PEAR_Error instance
- * @param int $mode error mode, see PEAR_Error docs
- * 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 $options Extra debug information. Defaults to the last
- * query and native error code.
- *
- * @return object a PEAR error object
- * @access public
- * @see PEAR_Error
- */
- function &raiseError($code = null, $mode = null, $options = null, $userinfo = null)
- {
- $error =& MDB2_Schema::raiseError($code, $mode, $options, $userinfo);
- return $error;
- }
-
- // }}}
- // {{{ _escapeSpecialChars()
-
- /**
- * add escapecharacters to all special characters in a string
- *
- * @param string $string string that should be escaped
- *
- * @return string escaped string
- * @access protected
- */
- function _escapeSpecialChars($string)
- {
- if (!is_string($string)) {
- $string = strval($string);
- }
-
- $escaped = '';
- for ($char = 0, $count = strlen($string); $char < $count; $char++) {
- switch ($string[$char]) {
- case '&':
- $escaped .= '&amp;';
- break;
- case '>':
- $escaped .= '&gt;';
- break;
- case '<':
- $escaped .= '&lt;';
- break;
- case '"':
- $escaped .= '&quot;';
- break;
- case '\'':
- $escaped .= '&apos;';
- break;
- default:
- $code = ord($string[$char]);
- if ($code < 32 || $code > 127) {
- $escaped .= "&#$code;";
- } else {
- $escaped .= $string[$char];
- }
- break;
- }
- }
- return $escaped;
- }
-
- // }}}
- // {{{ _dumpBoolean()
-
- /**
- * dump the structure of a sequence
- *
- * @param string $boolean boolean value or variable definition
- *
- * @return string with xml boolea definition
- * @access private
- */
- function _dumpBoolean($boolean)
- {
- if (is_string($boolean)) {
- if ($boolean !== 'true' || $boolean !== 'false'
- || preg_match('/<variable>.*</variable>/', $boolean)
- ) {
- return $boolean;
- }
- }
- return $boolean ? 'true' : 'false';
- }
-
- // }}}
- // {{{ dumpSequence()
-
- /**
- * dump the structure of a sequence
- *
- * @param string $sequence_definition sequence definition
- * @param string $sequence_name sequence name
- * @param string $eol end of line characters
- * @param integer $dump determines what data to dump
- * MDB2_SCHEMA_DUMP_ALL : the entire db
- * MDB2_SCHEMA_DUMP_STRUCTURE : only the structure of the db
- * MDB2_SCHEMA_DUMP_CONTENT : only the content of the db
- *
- * @return mixed string xml sequence definition on success, or a error object
- * @access public
- */
- function dumpSequence($sequence_definition, $sequence_name, $eol, $dump = MDB2_SCHEMA_DUMP_ALL)
- {
- $buffer = "$eol <sequence>$eol <name>$sequence_name</name>$eol";
- if ($dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_CONTENT) {
- if (!empty($sequence_definition['start'])) {
- $start = $sequence_definition['start'];
- $buffer .= " <start>$start</start>$eol";
- }
- }
-
- if (!empty($sequence_definition['on'])) {
- $buffer .= " <on>$eol";
- $buffer .= " <table>".$sequence_definition['on']['table'];
- $buffer .= "</table>$eol <field>".$sequence_definition['on']['field'];
- $buffer .= "</field>$eol </on>$eol";
- }
- $buffer .= " </sequence>$eol";
-
- return $buffer;
- }
-
- // }}}
- // {{{ dumpDatabase()
-
- /**
- * Dump a previously parsed database structure in the Metabase schema
- * XML based format suitable for the Metabase parser. This function
- * may optionally dump the database definition with initialization
- * commands that specify the data that is currently present in the tables.
- *
- * @param array $database_definition unknown
- * @param array $arguments associative array that takes pairs of tag
- * names and values that define dump options.
- * array (
- * 'output_mode' => String
- * 'file' : dump into a file
- * default: dump using a function
- * 'output' => String
- * depending on the 'Output_Mode'
- * name of the file
- * name of the function
- * 'end_of_line' => String
- * end of line delimiter that should be used
- * default: "\n"
- * );
- * @param integer $dump determines what data to dump
- * MDB2_SCHEMA_DUMP_ALL : the entire db
- * MDB2_SCHEMA_DUMP_STRUCTURE : only the structure of the db
- * MDB2_SCHEMA_DUMP_CONTENT : only the content of the db
- *
- * @return mixed MDB2_OK on success, or a error object
- * @access public
- */
- function dumpDatabase($database_definition, $arguments, $dump = MDB2_SCHEMA_DUMP_ALL)
- {
- if (!empty($arguments['output'])) {
- if (!empty($arguments['output_mode']) && $arguments['output_mode'] == 'file') {
- $fp = fopen($arguments['output'], 'w');
- if ($fp === false) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_WRITER, null, null,
- 'it was not possible to open output file');
- }
-
- $output = false;
- } elseif (is_callable($arguments['output'])) {
- $output = $arguments['output'];
- } else {
- return $this->raiseError(MDB2_SCHEMA_ERROR_WRITER, null, null,
- 'no valid output function specified');
- }
- } else {
- return $this->raiseError(MDB2_SCHEMA_ERROR_WRITER, null, null,
- 'no output method specified');
- }
-
- $eol = isset($arguments['end_of_line']) ? $arguments['end_of_line'] : "\n";
-
- $sequences = array();
- if (!empty($database_definition['sequences'])
- && is_array($database_definition['sequences'])
- ) {
- foreach ($database_definition['sequences'] as $sequence_name => $sequence) {
- $table = !empty($sequence['on']) ? $sequence['on']['table'] :'';
-
- $sequences[$table][] = $sequence_name;
- }
- }
-
- $buffer = '<?xml version="1.0" encoding="ISO-8859-1" ?>'.$eol;
- $buffer .= "<database>$eol$eol <name>".$database_definition['name']."</name>";
- $buffer .= "$eol <create>".$this->_dumpBoolean($database_definition['create'])."</create>";
- $buffer .= "$eol <overwrite>".$this->_dumpBoolean($database_definition['overwrite'])."</overwrite>$eol";
- $buffer .= "$eol <charset>".$database_definition['charset']."</charset>$eol";
-
- if ($output) {
- call_user_func($output, $buffer);
- } else {
- fwrite($fp, $buffer);
- }
-
- if (!empty($database_definition['tables']) && is_array($database_definition['tables'])) {
- foreach ($database_definition['tables'] as $table_name => $table) {
- $buffer = "$eol <table>$eol$eol <name>$table_name</name>$eol";
- if ($dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_STRUCTURE) {
- $buffer .= "$eol <declaration>$eol";
- if (!empty($table['fields']) && is_array($table['fields'])) {
- foreach ($table['fields'] as $field_name => $field) {
- if (empty($field['type'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, null, null,
- 'it was not specified the type of the field "'.
- $field_name.'" of the table "'.$table_name.'"');
- }
- if (!empty($this->valid_types) && !array_key_exists($field['type'], $this->valid_types)) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_UNSUPPORTED, null, null,
- 'type "'.$field['type'].'" is not yet supported');
- }
- $buffer .= "$eol <field>$eol <name>$field_name</name>$eol <type>";
- $buffer .= $field['type']."</type>$eol";
- if (!empty($field['fixed']) && $field['type'] === 'text') {
- $buffer .= " <fixed>".$this->_dumpBoolean($field['fixed'])."</fixed>$eol";
- }
- if (array_key_exists('default', $field)
- && $field['type'] !== 'clob' && $field['type'] !== 'blob'
- ) {
- $buffer .= ' <default>'.$this->_escapeSpecialChars($field['default'])."</default>$eol";
- }
- if (!empty($field['notnull'])) {
- $buffer .= " <notnull>".$this->_dumpBoolean($field['notnull'])."</notnull>$eol";
- } else {
- $buffer .= " <notnull>false</notnull>$eol";
- }
- if (!empty($field['autoincrement'])) {
- $buffer .= " <autoincrement>" . $field['autoincrement'] ."</autoincrement>$eol";
- }
- if (!empty($field['unsigned'])) {
- $buffer .= " <unsigned>".$this->_dumpBoolean($field['unsigned'])."</unsigned>$eol";
- }
- if (!empty($field['length'])) {
- $buffer .= ' <length>'.$field['length']."</length>$eol";
- }
- $buffer .= " </field>$eol";
- }
- }
-
- if (!empty($table['indexes']) && is_array($table['indexes'])) {
- foreach ($table['indexes'] as $index_name => $index) {
- if (strtolower($index_name) === 'primary') {
- $index_name = $table_name . '_pKey';
- }
- $buffer .= "$eol <index>$eol <name>$index_name</name>$eol";
- if (!empty($index['unique'])) {
- $buffer .= " <unique>".$this->_dumpBoolean($index['unique'])."</unique>$eol";
- }
-
- if (!empty($index['primary'])) {
- $buffer .= " <primary>".$this->_dumpBoolean($index['primary'])."</primary>$eol";
- }
-
- foreach ($index['fields'] as $field_name => $field) {
- $buffer .= " <field>$eol <name>$field_name</name>$eol";
- if (!empty($field) && is_array($field)) {
- $buffer .= ' <sorting>'.$field['sorting']."</sorting>$eol";
- }
- $buffer .= " </field>$eol";
- }
- $buffer .= " </index>$eol";
- }
- }
-
- if (!empty($table['constraints']) && is_array($table['constraints'])) {
- foreach ($table['constraints'] as $constraint_name => $constraint) {
- $buffer .= "$eol <foreign>$eol <name>$constraint_name</name>$eol";
- if (empty($constraint['fields']) || !is_array($constraint['fields'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, null, null,
- 'it was not specified a field for the foreign key "'.
- $constraint_name.'" of the table "'.$table_name.'"');
- }
- if (!is_array($constraint['references']) || empty($constraint['references']['table'])) {
- return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, null, null,
- 'it was not specified the referenced table of the foreign key "'.
- $constraint_name.'" of the table "'.$table_name.'"');
- }
- if (!empty($constraint['match'])) {
- $buffer .= " <match>".$constraint['match']."</match>$eol";
- }
- if (!empty($constraint['ondelete'])) {
- $buffer .= " <ondelete>".$constraint['ondelete']."</ondelete>$eol";
- }
- if (!empty($constraint['onupdate'])) {
- $buffer .= " <onupdate>".$constraint['onupdate']."</onupdate>$eol";
- }
- if (!empty($constraint['deferrable'])) {
- $buffer .= " <deferrable>".$constraint['deferrable']."</deferrable>$eol";
- }
- if (!empty($constraint['initiallydeferred'])) {
- $buffer .= " <initiallydeferred>".$constraint['initiallydeferred']."</initiallydeferred>$eol";
- }
- foreach ($constraint['fields'] as $field_name => $field) {
- $buffer .= " <field>$field_name</field>$eol";
- }
- $buffer .= " <references>$eol <table>".$constraint['references']['table']."</table>$eol";
- foreach ($constraint['references']['fields'] as $field_name => $field) {
- $buffer .= " <field>$field_name</field>$eol";
- }
- $buffer .= " </references>$eol";
-
- $buffer .= " </foreign>$eol";
- }
- }
-
- $buffer .= "$eol </declaration>$eol";
- }
-
- if ($output) {
- call_user_func($output, $buffer);
- } else {
- fwrite($fp, $buffer);
- }
-
- $buffer = '';
- if ($dump == MDB2_SCHEMA_DUMP_ALL || $dump == MDB2_SCHEMA_DUMP_CONTENT) {
- if (!empty($table['initialization']) && is_array($table['initialization'])) {
- $buffer = "$eol <initialization>$eol";
- foreach ($table['initialization'] as $instruction) {
- switch ($instruction['type']) {
- case 'insert':
- $buffer .= "$eol <insert>$eol";
- foreach ($instruction['data']['field'] as $field) {
- $field_name = $field['name'];
-
- $buffer .= "$eol <field>$eol <name>$field_name</name>$eol";
- $buffer .= $this->writeExpression($field['group'], 5, $arguments);
- $buffer .= " </field>$eol";
- }
- $buffer .= "$eol </insert>$eol";
- break;
- case 'update':
- $buffer .= "$eol <update>$eol";
- foreach ($instruction['data']['field'] as $field) {
- $field_name = $field['name'];
-
- $buffer .= "$eol <field>$eol <name>$field_name</name>$eol";
- $buffer .= $this->writeExpression($field['group'], 5, $arguments);
- $buffer .= " </field>$eol";
- }
-
- if (!empty($instruction['data']['where'])
- && is_array($instruction['data']['where'])
- ) {
- $buffer .= " <where>$eol";
- $buffer .= $this->writeExpression($instruction['data']['where'], 5, $arguments);
- $buffer .= " </where>$eol";
- }
-
- $buffer .= "$eol </update>$eol";
- break;
- case 'delete':
- $buffer .= "$eol <delete>$eol$eol";
- if (!empty($instruction['data']['where'])
- && is_array($instruction['data']['where'])
- ) {
- $buffer .= " <where>$eol";
- $buffer .= $this->writeExpression($instruction['data']['where'], 5, $arguments);
- $buffer .= " </where>$eol";
- }
- $buffer .= "$eol </delete>$eol";
- break;
- }
- }
- $buffer .= "$eol </initialization>$eol";
- }
- }
- $buffer .= "$eol </table>$eol";
- if ($output) {
- call_user_func($output, $buffer);
- } else {
- fwrite($fp, $buffer);
- }
-
- if (isset($sequences[$table_name])) {
- foreach ($sequences[$table_name] as $sequence) {
- $result = $this->dumpSequence($database_definition['sequences'][$sequence],
- $sequence, $eol, $dump);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if ($output) {
- call_user_func($output, $result);
- } else {
- fwrite($fp, $result);
- }
- }
- }
- }
- }
-
- if (isset($sequences[''])) {
- foreach ($sequences[''] as $sequence) {
- $result = $this->dumpSequence($database_definition['sequences'][$sequence],
- $sequence, $eol, $dump);
- if (PEAR::isError($result)) {
- return $result;
- }
-
- if ($output) {
- call_user_func($output, $result);
- } else {
- fwrite($fp, $result);
- }
- }
- }
-
- $buffer = "$eol</database>$eol";
- if ($output) {
- call_user_func($output, $buffer);
- } else {
- fwrite($fp, $buffer);
- fclose($fp);
- }
-
- return MDB2_OK;
- }
-
- // }}}
- // {{{ writeExpression()
-
- /**
- * Dumps the structure of an element. Elements can be value, column,
- * function or expression.
- *
- * @param array $element multi dimensional array that represents the parsed element
- * of a DML instruction.
- * @param integer $offset base indentation width
- * @param array $arguments associative array that takes pairs of tag
- * names and values that define dump options.
- *
- * @return string
- *
- * @access public
- * @see MDB2_Schema_Writer::dumpDatabase()
- */
- function writeExpression($element, $offset = 0, $arguments = null)
- {
- $eol = isset($arguments['end_of_line']) ? $arguments['end_of_line'] : "\n";
- $str = '';
-
- $indent = str_repeat(' ', $offset);
- $noffset = $offset + 1;
-
- switch ($element['type']) {
- case 'value':
- $str .= "$indent<value>".$this->_escapeSpecialChars($element['data'])."</value>$eol";
- break;
- case 'column':
- $str .= "$indent<column>".$this->_escapeSpecialChars($element['data'])."</column>$eol";
- break;
- case 'function':
- $str .= "$indent<function>$eol$indent <name>".$this->_escapeSpecialChars($element['data']['name'])."</name>$eol";
-
- if (!empty($element['data']['arguments'])
- && is_array($element['data']['arguments'])
- ) {
- foreach ($element['data']['arguments'] as $v) {
- $str .= $this->writeExpression($v, $noffset, $arguments);
- }
- }
-
- $str .= "$indent</function>$eol";
- break;
- case 'expression':
- $str .= "$indent<expression>$eol";
- $str .= $this->writeExpression($element['data']['operants'][0], $noffset, $arguments);
- $str .= "$indent <operator>".$element['data']['operator']."</operator>$eol";
- $str .= $this->writeExpression($element['data']['operants'][1], $noffset, $arguments);
- $str .= "$indent</expression>$eol";
- break;
- }
- return $str;
- }
-
- // }}}
-}
-?>
diff --git a/inc/Mail.php b/inc/Mail.php
deleted file mode 100644
index c9f480fd488..00000000000
--- a/inc/Mail.php
+++ /dev/null
@@ -1,212 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Chuck Hagenbuch <chuck@horde.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Mail.php,v 1.11 2005/06/26 23:37:18 jon Exp $
-
-require_once 'PEAR.php';
-
-/**
- * PEAR's Mail:: interface. Defines the interface for implementing
- * mailers under the PEAR hierarchy, and provides supporting functions
- * useful in multiple mailer backends.
- *
- * @access public
- * @version $Revision: 1.11 $
- * @package Mail
- */
-class Mail
-{
- /**
- * Line terminator used for separating header lines.
- * @var string
- */
- var $sep = "\r\n";
-
- /**
- * Provides an interface for generating Mail:: objects of various
- * types
- *
- * @param string $driver The kind of Mail:: object to instantiate.
- * @param array $params The parameters to pass to the Mail:: object.
- * @return object Mail a instance of the driver class or if fails a PEAR Error
- * @access public
- */
- function &factory($driver, $params = array())
- {
- $driver = strtolower($driver);
- @include_once 'Mail/' . $driver . '.php';
- $class = 'Mail_' . $driver;
- if (class_exists($class)) {
- $mailer = &new $class($params);
- } else {
- $mailer = PEAR::raiseError('Unable to find class for driver ' . $driver);
- }
-
- return $mailer;
- }
-
- /**
- * Implements Mail::send() function using php's built-in mail()
- * command.
- *
- * @param mixed $recipients Either a comma-seperated list of recipients
- * (RFC822 compliant), or an array of recipients,
- * each RFC822 valid. This may contain recipients not
- * specified in the headers, for Bcc:, resending
- * messages, etc.
- *
- * @param array $headers The array of headers to send with the mail, in an
- * associative array, where the array key is the
- * header name (ie, 'Subject'), and the array value
- * is the header value (ie, 'test'). The header
- * produced from those values would be 'Subject:
- * test'.
- *
- * @param string $body The full text of the message body, including any
- * Mime parts, etc.
- *
- * @return mixed Returns true on success, or a PEAR_Error
- * containing a descriptive error message on
- * failure.
- * @access public
- * @deprecated use Mail_mail::send instead
- */
- function send($recipients, $headers, $body)
- {
- // if we're passed an array of recipients, implode it.
- if (is_array($recipients)) {
- $recipients = implode(', ', $recipients);
- }
-
- // get the Subject out of the headers array so that we can
- // pass it as a seperate argument to mail().
- $subject = '';
- if (isset($headers['Subject'])) {
- $subject = $headers['Subject'];
- unset($headers['Subject']);
- }
-
- // flatten the headers out.
- list(,$text_headers) = Mail::prepareHeaders($headers);
-
- return mail($recipients, $subject, $body, $text_headers);
-
- }
-
- /**
- * Take an array of mail headers and return a string containing
- * text usable in sending a message.
- *
- * @param array $headers The array of headers to prepare, in an associative
- * array, where the array key is the header name (ie,
- * 'Subject'), and the array value is the header
- * value (ie, 'test'). The header produced from those
- * values would be 'Subject: test'.
- *
- * @return mixed Returns false if it encounters a bad address,
- * otherwise returns an array containing two
- * elements: Any From: address found in the headers,
- * and the plain text version of the headers.
- * @access private
- */
- function prepareHeaders($headers)
- {
- $lines = array();
- $from = null;
-
- foreach ($headers as $key => $value) {
- if (strcasecmp($key, 'From') === 0) {
- include_once 'Mail/RFC822.php';
- $parser = &new Mail_RFC822();
- $addresses = $parser->parseAddressList($value, 'localhost', false);
- if (PEAR::isError($addresses)) {
- return $addresses;
- }
-
- $from = $addresses[0]->mailbox . '@' . $addresses[0]->host;
-
- // Reject envelope From: addresses with spaces.
- if (strstr($from, ' ')) {
- return false;
- }
-
- $lines[] = $key . ': ' . $value;
- } elseif (strcasecmp($key, 'Received') === 0) {
- $received = array();
- if (is_array($value)) {
- foreach ($value as $line) {
- $received[] = $key . ': ' . $line;
- }
- }
- else {
- $received[] = $key . ': ' . $value;
- }
- // Put Received: headers at the top. Spam detectors often
- // flag messages with Received: headers after the Subject:
- // as spam.
- $lines = array_merge($received, $lines);
- } else {
- // If $value is an array (i.e., a list of addresses), convert
- // it to a comma-delimited string of its elements (addresses).
- if (is_array($value)) {
- $value = implode(', ', $value);
- }
- $lines[] = $key . ': ' . $value;
- }
- }
-
- return array($from, join($this->sep, $lines) . $this->sep);
- }
-
- /**
- * Take a set of recipients and parse them, returning an array of
- * bare addresses (forward paths) that can be passed to sendmail
- * or an smtp server with the rcpt to: command.
- *
- * @param mixed Either a comma-seperated list of recipients
- * (RFC822 compliant), or an array of recipients,
- * each RFC822 valid.
- *
- * @return array An array of forward paths (bare addresses).
- * @access private
- */
- function parseRecipients($recipients)
- {
- include_once 'Mail/RFC822.php';
-
- // if we're passed an array, assume addresses are valid and
- // implode them before parsing.
- if (is_array($recipients)) {
- $recipients = implode(', ', $recipients);
- }
-
- // Parse recipients, leaving out all personal info. This is
- // for smtp recipients, etc. All relevant personal information
- // should already be in the headers.
- $addresses = Mail_RFC822::parseAddressList($recipients, 'localhost', false);
- $recipients = array();
- if (is_array($addresses)) {
- foreach ($addresses as $ob) {
- $recipients[] = $ob->mailbox . '@' . $ob->host;
- }
- }
-
- return $recipients;
- }
-
-}
diff --git a/inc/Mail/RFC822.php b/inc/Mail/RFC822.php
deleted file mode 100644
index 47e84f83b26..00000000000
--- a/inc/Mail/RFC822.php
+++ /dev/null
@@ -1,923 +0,0 @@
-<?php
-// +-----------------------------------------------------------------------+
-// | Copyright (c) 2001-2002, Richard Heyes |
-// | All rights reserved. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | o Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | o Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution.|
-// | o The names of the authors may not be used to endorse or promote |
-// | products derived from this software without specific prior written |
-// | permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
-// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
-// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
-// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
-// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
-// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
-// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
-// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
-// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
-// | |
-// +-----------------------------------------------------------------------+
-// | Authors: Richard Heyes <richard@phpguru.org> |
-// | Chuck Hagenbuch <chuck@horde.org> |
-// +-----------------------------------------------------------------------+
-
-/**
- * RFC 822 Email address list validation Utility
- *
- * What is it?
- *
- * This class will take an address string, and parse it into it's consituent
- * parts, be that either addresses, groups, or combinations. Nested groups
- * are not supported. The structure it returns is pretty straight forward,
- * and is similar to that provided by the imap_rfc822_parse_adrlist(). Use
- * print_r() to view the structure.
- *
- * How do I use it?
- *
- * $address_string = 'My Group: "Richard" <richard@localhost> (A comment), ted@example.com (Ted Bloggs), Barney;';
- * $structure = Mail_RFC822::parseAddressList($address_string, 'example.com', true)
- * print_r($structure);
- *
- * @author Richard Heyes <richard@phpguru.org>
- * @author Chuck Hagenbuch <chuck@horde.org>
- * @version $Revision: 1.21 $
- * @license BSD
- * @package Mail
- */
-class Mail_RFC822 {
-
- /**
- * The address being parsed by the RFC822 object.
- * @var string $address
- */
- var $address = '';
-
- /**
- * The default domain to use for unqualified addresses.
- * @var string $default_domain
- */
- var $default_domain = 'localhost';
-
- /**
- * Should we return a nested array showing groups, or flatten everything?
- * @var boolean $nestGroups
- */
- var $nestGroups = true;
-
- /**
- * Whether or not to validate atoms for non-ascii characters.
- * @var boolean $validate
- */
- var $validate = true;
-
- /**
- * The array of raw addresses built up as we parse.
- * @var array $addresses
- */
- var $addresses = array();
-
- /**
- * The final array of parsed address information that we build up.
- * @var array $structure
- */
- var $structure = array();
-
- /**
- * The current error message, if any.
- * @var string $error
- */
- var $error = null;
-
- /**
- * An internal counter/pointer.
- * @var integer $index
- */
- var $index = null;
-
- /**
- * The number of groups that have been found in the address list.
- * @var integer $num_groups
- * @access public
- */
- var $num_groups = 0;
-
- /**
- * A variable so that we can tell whether or not we're inside a
- * Mail_RFC822 object.
- * @var boolean $mailRFC822
- */
- var $mailRFC822 = true;
-
- /**
- * A limit after which processing stops
- * @var int $limit
- */
- var $limit = null;
-
- /**
- * Sets up the object. The address must either be set here or when
- * calling parseAddressList(). One or the other.
- *
- * @access public
- * @param string $address The address(es) to validate.
- * @param string $default_domain Default domain/host etc. If not supplied, will be set to localhost.
- * @param boolean $nest_groups Whether to return the structure with groups nested for easier viewing.
- * @param boolean $validate Whether to validate atoms. Turn this off if you need to run addresses through before encoding the personal names, for instance.
- *
- * @return object Mail_RFC822 A new Mail_RFC822 object.
- */
- function Mail_RFC822($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
- {
- if (isset($address)) $this->address = $address;
- if (isset($default_domain)) $this->default_domain = $default_domain;
- if (isset($nest_groups)) $this->nestGroups = $nest_groups;
- if (isset($validate)) $this->validate = $validate;
- if (isset($limit)) $this->limit = $limit;
- }
-
- /**
- * Starts the whole process. The address must either be set here
- * or when creating the object. One or the other.
- *
- * @access public
- * @param string $address The address(es) to validate.
- * @param string $default_domain Default domain/host etc.
- * @param boolean $nest_groups Whether to return the structure with groups nested for easier viewing.
- * @param boolean $validate Whether to validate atoms. Turn this off if you need to run addresses through before encoding the personal names, for instance.
- *
- * @return array A structured array of addresses.
- */
- function parseAddressList($address = null, $default_domain = null, $nest_groups = null, $validate = null, $limit = null)
- {
- if (!isset($this) || !isset($this->mailRFC822)) {
- $obj = new Mail_RFC822($address, $default_domain, $nest_groups, $validate, $limit);
- return $obj->parseAddressList();
- }
-
- if (isset($address)) $this->address = $address;
- if (isset($default_domain)) $this->default_domain = $default_domain;
- if (isset($nest_groups)) $this->nestGroups = $nest_groups;
- if (isset($validate)) $this->validate = $validate;
- if (isset($limit)) $this->limit = $limit;
-
- $this->structure = array();
- $this->addresses = array();
- $this->error = null;
- $this->index = null;
-
- // Unfold any long lines in $this->address.
- $this->address = preg_replace('/\r?\n/', "\r\n", $this->address);
- $this->address = preg_replace('/\r\n(\t| )+/', ' ', $this->address);
-
- while ($this->address = $this->_splitAddresses($this->address));
-
- if ($this->address === false || isset($this->error)) {
- require_once 'PEAR.php';
- return PEAR::raiseError($this->error);
- }
-
- // Validate each address individually. If we encounter an invalid
- // address, stop iterating and return an error immediately.
- foreach ($this->addresses as $address) {
- $valid = $this->_validateAddress($address);
-
- if ($valid === false || isset($this->error)) {
- require_once 'PEAR.php';
- return PEAR::raiseError($this->error);
- }
-
- if (!$this->nestGroups) {
- $this->structure = array_merge($this->structure, $valid);
- } else {
- $this->structure[] = $valid;
- }
- }
-
- return $this->structure;
- }
-
- /**
- * Splits an address into separate addresses.
- *
- * @access private
- * @param string $address The addresses to split.
- * @return boolean Success or failure.
- */
- function _splitAddresses($address)
- {
- if (!empty($this->limit) && count($this->addresses) == $this->limit) {
- return '';
- }
-
- if ($this->_isGroup($address) && !isset($this->error)) {
- $split_char = ';';
- $is_group = true;
- } elseif (!isset($this->error)) {
- $split_char = ',';
- $is_group = false;
- } elseif (isset($this->error)) {
- return false;
- }
-
- // Split the string based on the above ten or so lines.
- $parts = explode($split_char, $address);
- $string = $this->_splitCheck($parts, $split_char);
-
- // If a group...
- if ($is_group) {
- // If $string does not contain a colon outside of
- // brackets/quotes etc then something's fubar.
-
- // First check there's a colon at all:
- if (strpos($string, ':') === false) {
- $this->error = 'Invalid address: ' . $string;
- return false;
- }
-
- // Now check it's outside of brackets/quotes:
- if (!$this->_splitCheck(explode(':', $string), ':')) {
- return false;
- }
-
- // We must have a group at this point, so increase the counter:
- $this->num_groups++;
- }
-
- // $string now contains the first full address/group.
- // Add to the addresses array.
- $this->addresses[] = array(
- 'address' => trim($string),
- 'group' => $is_group
- );
-
- // Remove the now stored address from the initial line, the +1
- // is to account for the explode character.
- $address = trim(substr($address, strlen($string) + 1));
-
- // If the next char is a comma and this was a group, then
- // there are more addresses, otherwise, if there are any more
- // chars, then there is another address.
- if ($is_group && substr($address, 0, 1) == ','){
- $address = trim(substr($address, 1));
- return $address;
-
- } elseif (strlen($address) > 0) {
- return $address;
-
- } else {
- return '';
- }
-
- // If you got here then something's off
- return false;
- }
-
- /**
- * Checks for a group at the start of the string.
- *
- * @access private
- * @param string $address The address to check.
- * @return boolean Whether or not there is a group at the start of the string.
- */
- function _isGroup($address)
- {
- // First comma not in quotes, angles or escaped:
- $parts = explode(',', $address);
- $string = $this->_splitCheck($parts, ',');
-
- // Now we have the first address, we can reliably check for a
- // group by searching for a colon that's not escaped or in
- // quotes or angle brackets.
- if (count($parts = explode(':', $string)) > 1) {
- $string2 = $this->_splitCheck($parts, ':');
- return ($string2 !== $string);
- } else {
- return false;
- }
- }
-
- /**
- * A common function that will check an exploded string.
- *
- * @access private
- * @param array $parts The exloded string.
- * @param string $char The char that was exploded on.
- * @return mixed False if the string contains unclosed quotes/brackets, or the string on success.
- */
- function _splitCheck($parts, $char)
- {
- $string = $parts[0];
-
- for ($i = 0; $i < count($parts); $i++) {
- if ($this->_hasUnclosedQuotes($string)
- || $this->_hasUnclosedBrackets($string, '<>')
- || $this->_hasUnclosedBrackets($string, '[]')
- || $this->_hasUnclosedBrackets($string, '()')
- || substr($string, -1) == '\\') {
- if (isset($parts[$i + 1])) {
- $string = $string . $char . $parts[$i + 1];
- } else {
- $this->error = 'Invalid address spec. Unclosed bracket or quotes';
- return false;
- }
- } else {
- $this->index = $i;
- break;
- }
- }
-
- return $string;
- }
-
- /**
- * Checks if a string has an unclosed quotes or not.
- *
- * @access private
- * @param string $string The string to check.
- * @return boolean True if there are unclosed quotes inside the string, false otherwise.
- */
- function _hasUnclosedQuotes($string)
- {
- $string = explode('"', $string);
- $string_cnt = count($string);
-
- for ($i = 0; $i < (count($string) - 1); $i++)
- if (substr($string[$i], -1) == '\\')
- $string_cnt--;
-
- return ($string_cnt % 2 === 0);
- }
-
- /**
- * Checks if a string has an unclosed brackets or not. IMPORTANT:
- * This function handles both angle brackets and square brackets;
- *
- * @access private
- * @param string $string The string to check.
- * @param string $chars The characters to check for.
- * @return boolean True if there are unclosed brackets inside the string, false otherwise.
- */
- function _hasUnclosedBrackets($string, $chars)
- {
- $num_angle_start = substr_count($string, $chars[0]);
- $num_angle_end = substr_count($string, $chars[1]);
-
- $this->_hasUnclosedBracketsSub($string, $num_angle_start, $chars[0]);
- $this->_hasUnclosedBracketsSub($string, $num_angle_end, $chars[1]);
-
- if ($num_angle_start < $num_angle_end) {
- $this->error = 'Invalid address spec. Unmatched quote or bracket (' . $chars . ')';
- return false;
- } else {
- return ($num_angle_start > $num_angle_end);
- }
- }
-
- /**
- * Sub function that is used only by hasUnclosedBrackets().
- *
- * @access private
- * @param string $string The string to check.
- * @param integer &$num The number of occurences.
- * @param string $char The character to count.
- * @return integer The number of occurences of $char in $string, adjusted for backslashes.
- */
- function _hasUnclosedBracketsSub($string, &$num, $char)
- {
- $parts = explode($char, $string);
- for ($i = 0; $i < count($parts); $i++){
- if (substr($parts[$i], -1) == '\\' || $this->_hasUnclosedQuotes($parts[$i]))
- $num--;
- if (isset($parts[$i + 1]))
- $parts[$i + 1] = $parts[$i] . $char . $parts[$i + 1];
- }
-
- return $num;
- }
-
- /**
- * Function to begin checking the address.
- *
- * @access private
- * @param string $address The address to validate.
- * @return mixed False on failure, or a structured array of address information on success.
- */
- function _validateAddress($address)
- {
- $is_group = false;
- $addresses = array();
-
- if ($address['group']) {
- $is_group = true;
-
- // Get the group part of the name
- $parts = explode(':', $address['address']);
- $groupname = $this->_splitCheck($parts, ':');
- $structure = array();
-
- // And validate the group part of the name.
- if (!$this->_validatePhrase($groupname)){
- $this->error = 'Group name did not validate.';
- return false;
- } else {
- // Don't include groups if we are not nesting
- // them. This avoids returning invalid addresses.
- if ($this->nestGroups) {
- $structure = new stdClass;
- $structure->groupname = $groupname;
- }
- }
-
- $address['address'] = ltrim(substr($address['address'], strlen($groupname . ':')));
- }
-
- // If a group then split on comma and put into an array.
- // Otherwise, Just put the whole address in an array.
- if ($is_group) {
- while (strlen($address['address']) > 0) {
- $parts = explode(',', $address['address']);
- $addresses[] = $this->_splitCheck($parts, ',');
- $address['address'] = trim(substr($address['address'], strlen(end($addresses) . ',')));
- }
- } else {
- $addresses[] = $address['address'];
- }
-
- // Check that $addresses is set, if address like this:
- // Groupname:;
- // Then errors were appearing.
- if (!count($addresses)){
- $this->error = 'Empty group.';
- return false;
- }
-
- // Trim the whitespace from all of the address strings.
- array_map('trim', $addresses);
-
- // Validate each mailbox.
- // Format could be one of: name <geezer@domain.com>
- // geezer@domain.com
- // geezer
- // ... or any other format valid by RFC 822.
- for ($i = 0; $i < count($addresses); $i++) {
- if (!$this->validateMailbox($addresses[$i])) {
- if (empty($this->error)) {
- $this->error = 'Validation failed for: ' . $addresses[$i];
- }
- return false;
- }
- }
-
- // Nested format
- if ($this->nestGroups) {
- if ($is_group) {
- $structure->addresses = $addresses;
- } else {
- $structure = $addresses[0];
- }
-
- // Flat format
- } else {
- if ($is_group) {
- $structure = array_merge($structure, $addresses);
- } else {
- $structure = $addresses;
- }
- }
-
- return $structure;
- }
-
- /**
- * Function to validate a phrase.
- *
- * @access private
- * @param string $phrase The phrase to check.
- * @return boolean Success or failure.
- */
- function _validatePhrase($phrase)
- {
- // Splits on one or more Tab or space.
- $parts = preg_split('/[ \\x09]+/', $phrase, -1, PREG_SPLIT_NO_EMPTY);
-
- $phrase_parts = array();
- while (count($parts) > 0){
- $phrase_parts[] = $this->_splitCheck($parts, ' ');
- for ($i = 0; $i < $this->index + 1; $i++)
- array_shift($parts);
- }
-
- foreach ($phrase_parts as $part) {
- // If quoted string:
- if (substr($part, 0, 1) == '"') {
- if (!$this->_validateQuotedString($part)) {
- return false;
- }
- continue;
- }
-
- // Otherwise it's an atom:
- if (!$this->_validateAtom($part)) return false;
- }
-
- return true;
- }
-
- /**
- * Function to validate an atom which from rfc822 is:
- * atom = 1*<any CHAR except specials, SPACE and CTLs>
- *
- * If validation ($this->validate) has been turned off, then
- * validateAtom() doesn't actually check anything. This is so that you
- * can split a list of addresses up before encoding personal names
- * (umlauts, etc.), for example.
- *
- * @access private
- * @param string $atom The string to check.
- * @return boolean Success or failure.
- */
- function _validateAtom($atom)
- {
- if (!$this->validate) {
- // Validation has been turned off; assume the atom is okay.
- return true;
- }
-
- // Check for any char from ASCII 0 - ASCII 127
- if (!preg_match('/^[\\x00-\\x7E]+$/i', $atom, $matches)) {
- return false;
- }
-
- // Check for specials:
- if (preg_match('/[][()<>@,;\\:". ]/', $atom)) {
- return false;
- }
-
- // Check for control characters (ASCII 0-31):
- if (preg_match('/[\\x00-\\x1F]+/', $atom)) {
- return false;
- }
-
- return true;
- }
-
- /**
- * Function to validate quoted string, which is:
- * quoted-string = <"> *(qtext/quoted-pair) <">
- *
- * @access private
- * @param string $qstring The string to check
- * @return boolean Success or failure.
- */
- function _validateQuotedString($qstring)
- {
- // Leading and trailing "
- $qstring = substr($qstring, 1, -1);
-
- // Perform check, removing quoted characters first.
- return !preg_match('/[\x0D\\\\"]/', preg_replace('/\\\\./', '', $qstring));
- }
-
- /**
- * Function to validate a mailbox, which is:
- * mailbox = addr-spec ; simple address
- * / phrase route-addr ; name and route-addr
- *
- * @access public
- * @param string &$mailbox The string to check.
- * @return boolean Success or failure.
- */
- function validateMailbox(&$mailbox)
- {
- // A couple of defaults.
- $phrase = '';
- $comment = '';
- $comments = array();
-
- // Catch any RFC822 comments and store them separately.
- $_mailbox = $mailbox;
- while (strlen(trim($_mailbox)) > 0) {
- $parts = explode('(', $_mailbox);
- $before_comment = $this->_splitCheck($parts, '(');
- if ($before_comment != $_mailbox) {
- // First char should be a (.
- $comment = substr(str_replace($before_comment, '', $_mailbox), 1);
- $parts = explode(')', $comment);
- $comment = $this->_splitCheck($parts, ')');
- $comments[] = $comment;
-
- // +1 is for the trailing )
- $_mailbox = substr($_mailbox, strpos($_mailbox, $comment)+strlen($comment)+1);
- } else {
- break;
- }
- }
-
- foreach ($comments as $comment) {
- $mailbox = str_replace("($comment)", '', $mailbox);
- }
-
- $mailbox = trim($mailbox);
-
- // Check for name + route-addr
- if (substr($mailbox, -1) == '>' && substr($mailbox, 0, 1) != '<') {
- $parts = explode('<', $mailbox);
- $name = $this->_splitCheck($parts, '<');
-
- $phrase = trim($name);
- $route_addr = trim(substr($mailbox, strlen($name.'<'), -1));
-
- if ($this->_validatePhrase($phrase) === false || ($route_addr = $this->_validateRouteAddr($route_addr)) === false) {
- return false;
- }
-
- // Only got addr-spec
- } else {
- // First snip angle brackets if present.
- if (substr($mailbox, 0, 1) == '<' && substr($mailbox, -1) == '>') {
- $addr_spec = substr($mailbox, 1, -1);
- } else {
- $addr_spec = $mailbox;
- }
-
- if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
- return false;
- }
- }
-
- // Construct the object that will be returned.
- $mbox = new stdClass();
-
- // Add the phrase (even if empty) and comments
- $mbox->personal = $phrase;
- $mbox->comment = isset($comments) ? $comments : array();
-
- if (isset($route_addr)) {
- $mbox->mailbox = $route_addr['local_part'];
- $mbox->host = $route_addr['domain'];
- $route_addr['adl'] !== '' ? $mbox->adl = $route_addr['adl'] : '';
- } else {
- $mbox->mailbox = $addr_spec['local_part'];
- $mbox->host = $addr_spec['domain'];
- }
-
- $mailbox = $mbox;
- return true;
- }
-
- /**
- * This function validates a route-addr which is:
- * route-addr = "<" [route] addr-spec ">"
- *
- * Angle brackets have already been removed at the point of
- * getting to this function.
- *
- * @access private
- * @param string $route_addr The string to check.
- * @return mixed False on failure, or an array containing validated address/route information on success.
- */
- function _validateRouteAddr($route_addr)
- {
- // Check for colon.
- if (strpos($route_addr, ':') !== false) {
- $parts = explode(':', $route_addr);
- $route = $this->_splitCheck($parts, ':');
- } else {
- $route = $route_addr;
- }
-
- // If $route is same as $route_addr then the colon was in
- // quotes or brackets or, of course, non existent.
- if ($route === $route_addr){
- unset($route);
- $addr_spec = $route_addr;
- if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
- return false;
- }
- } else {
- // Validate route part.
- if (($route = $this->_validateRoute($route)) === false) {
- return false;
- }
-
- $addr_spec = substr($route_addr, strlen($route . ':'));
-
- // Validate addr-spec part.
- if (($addr_spec = $this->_validateAddrSpec($addr_spec)) === false) {
- return false;
- }
- }
-
- if (isset($route)) {
- $return['adl'] = $route;
- } else {
- $return['adl'] = '';
- }
-
- $return = array_merge($return, $addr_spec);
- return $return;
- }
-
- /**
- * Function to validate a route, which is:
- * route = 1#("@" domain) ":"
- *
- * @access private
- * @param string $route The string to check.
- * @return mixed False on failure, or the validated $route on success.
- */
- function _validateRoute($route)
- {
- // Split on comma.
- $domains = explode(',', trim($route));
-
- foreach ($domains as $domain) {
- $domain = str_replace('@', '', trim($domain));
- if (!$this->_validateDomain($domain)) return false;
- }
-
- return $route;
- }
-
- /**
- * Function to validate a domain, though this is not quite what
- * you expect of a strict internet domain.
- *
- * domain = sub-domain *("." sub-domain)
- *
- * @access private
- * @param string $domain The string to check.
- * @return mixed False on failure, or the validated domain on success.
- */
- function _validateDomain($domain)
- {
- // Note the different use of $subdomains and $sub_domains
- $subdomains = explode('.', $domain);
-
- while (count($subdomains) > 0) {
- $sub_domains[] = $this->_splitCheck($subdomains, '.');
- for ($i = 0; $i < $this->index + 1; $i++)
- array_shift($subdomains);
- }
-
- foreach ($sub_domains as $sub_domain) {
- if (!$this->_validateSubdomain(trim($sub_domain)))
- return false;
- }
-
- // Managed to get here, so return input.
- return $domain;
- }
-
- /**
- * Function to validate a subdomain:
- * subdomain = domain-ref / domain-literal
- *
- * @access private
- * @param string $subdomain The string to check.
- * @return boolean Success or failure.
- */
- function _validateSubdomain($subdomain)
- {
- if (preg_match('|^\[(.*)]$|', $subdomain, $arr)){
- if (!$this->_validateDliteral($arr[1])) return false;
- } else {
- if (!$this->_validateAtom($subdomain)) return false;
- }
-
- // Got here, so return successful.
- return true;
- }
-
- /**
- * Function to validate a domain literal:
- * domain-literal = "[" *(dtext / quoted-pair) "]"
- *
- * @access private
- * @param string $dliteral The string to check.
- * @return boolean Success or failure.
- */
- function _validateDliteral($dliteral)
- {
- return !preg_match('/(.)[][\x0D\\\\]/', $dliteral, $matches) && $matches[1] != '\\';
- }
-
- /**
- * Function to validate an addr-spec.
- *
- * addr-spec = local-part "@" domain
- *
- * @access private
- * @param string $addr_spec The string to check.
- * @return mixed False on failure, or the validated addr-spec on success.
- */
- function _validateAddrSpec($addr_spec)
- {
- $addr_spec = trim($addr_spec);
-
- // Split on @ sign if there is one.
- if (strpos($addr_spec, '@') !== false) {
- $parts = explode('@', $addr_spec);
- $local_part = $this->_splitCheck($parts, '@');
- $domain = substr($addr_spec, strlen($local_part . '@'));
-
- // No @ sign so assume the default domain.
- } else {
- $local_part = $addr_spec;
- $domain = $this->default_domain;
- }
-
- if (($local_part = $this->_validateLocalPart($local_part)) === false) return false;
- if (($domain = $this->_validateDomain($domain)) === false) return false;
-
- // Got here so return successful.
- return array('local_part' => $local_part, 'domain' => $domain);
- }
-
- /**
- * Function to validate the local part of an address:
- * local-part = word *("." word)
- *
- * @access private
- * @param string $local_part
- * @return mixed False on failure, or the validated local part on success.
- */
- function _validateLocalPart($local_part)
- {
- $parts = explode('.', $local_part);
- $words = array();
-
- // Split the local_part into words.
- while (count($parts) > 0){
- $words[] = $this->_splitCheck($parts, '.');
- for ($i = 0; $i < $this->index + 1; $i++) {
- array_shift($parts);
- }
- }
-
- // Validate each word.
- foreach ($words as $word) {
- // If this word contains an unquoted space, it is invalid. (6.2.4)
- if (strpos($word, ' ') && $word[0] !== '"')
- {
- return false;
- }
-
- if ($this->_validatePhrase(trim($word)) === false) return false;
- }
-
- // Managed to get here, so return the input.
- return $local_part;
- }
-
- /**
- * Returns an approximate count of how many addresses are in the
- * given string. This is APPROXIMATE as it only splits based on a
- * comma which has no preceding backslash. Could be useful as
- * large amounts of addresses will end up producing *large*
- * structures when used with parseAddressList().
- *
- * @param string $data Addresses to count
- * @return int Approximate count
- */
- function approximateCount($data)
- {
- return count(preg_split('/(?<!\\\\),/', $data));
- }
-
- /**
- * This is a email validating function separate to the rest of the
- * class. It simply validates whether an email is of the common
- * internet form: <user>@<domain>. This can be sufficient for most
- * people. Optional stricter mode can be utilised which restricts
- * mailbox characters allowed to alphanumeric, full stop, hyphen
- * and underscore.
- *
- * @param string $data Address to check
- * @param boolean $strict Optional stricter mode
- * @return mixed False if it fails, an indexed array
- * username/domain if it matches
- */
- function isValidInetAddress($data, $strict = false)
- {
- $regex = $strict ? '/^([.0-9a-z_-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,4})$/i' : '/^([*+!.&#$|\'\\%\/0-9a-z^_`{}=?~:-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,4})$/i';
- if (preg_match($regex, trim($data), $matches)) {
- return array($matches[1], $matches[2]);
- } else {
- return false;
- }
- }
-
-}
diff --git a/inc/Mail/mail.php b/inc/Mail/mail.php
deleted file mode 100644
index 9135fa2363b..00000000000
--- a/inc/Mail/mail.php
+++ /dev/null
@@ -1,130 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Chuck Hagenbuch <chuck@horde.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: mail.php,v 1.13 2004/09/09 02:08:55 jon Exp $
-
-/**
- * internal PHP-mail() implementation of the PEAR Mail:: interface.
- * @package Mail
- * @version $Revision: 1.13 $
- */
-class Mail_mail extends Mail {
-
- /**
- * Any arguments to pass to the mail() function.
- * @var string
- */
- var $_params = '';
-
- /**
- * Constructor.
- *
- * Instantiates a new Mail_mail:: object based on the parameters
- * passed in.
- *
- * @param array $params Extra arguments for the mail() function.
- */
- function Mail_mail($params = null)
- {
- /* The other mail implementations accept parameters as arrays.
- * In the interest of being consistent, explode an array into
- * a string of parameter arguments. */
- if (is_array($params)) {
- $this->_params = join(' ', $params);
- } else {
- $this->_params = $params;
- }
-
- /* Because the mail() function may pass headers as command
- * line arguments, we can't guarantee the use of the standard
- * "\r\n" separator. Instead, we use the system's native line
- * separator. */
- $this->sep = (strstr(PHP_OS, 'WIN')) ? "\r\n" : "\n";
- }
-
- /**
- * Implements Mail_mail::send() function using php's built-in mail()
- * command.
- *
- * @param mixed $recipients Either a comma-seperated list of recipients
- * (RFC822 compliant), or an array of recipients,
- * each RFC822 valid. This may contain recipients not
- * specified in the headers, for Bcc:, resending
- * messages, etc.
- *
- * @param array $headers The array of headers to send with the mail, in an
- * associative array, where the array key is the
- * header name (ie, 'Subject'), and the array value
- * is the header value (ie, 'test'). The header
- * produced from those values would be 'Subject:
- * test'.
- *
- * @param string $body The full text of the message body, including any
- * Mime parts, etc.
- *
- * @return mixed Returns true on success, or a PEAR_Error
- * containing a descriptive error message on
- * failure.
- *
- * @access public
- */
- function send($recipients, $headers, $body)
- {
- // If we're passed an array of recipients, implode it.
- if (is_array($recipients)) {
- $recipients = implode(', ', $recipients);
- }
-
- // Get the Subject out of the headers array so that we can
- // pass it as a seperate argument to mail().
- $subject = '';
- if (isset($headers['Subject'])) {
- $subject = $headers['Subject'];
- unset($headers['Subject']);
- }
-
- // Flatten the headers out.
- $headerElements = $this->prepareHeaders($headers);
- if (PEAR::isError($headerElements)) {
- return $headerElements;
- }
- list(, $text_headers) = $headerElements;
-
- /*
- * We only use mail()'s optional fifth parameter if the additional
- * parameters have been provided and we're not running in safe mode.
- */
- if (empty($this->_params) || ini_get('safe_mode')) {
- $result = mail($recipients, $subject, $body, $text_headers);
- } else {
- $result = mail($recipients, $subject, $body, $text_headers,
- $this->_params);
- }
-
- /*
- * If the mail() function returned failure, we need to create a
- * PEAR_Error object and return it instead of the boolean result.
- */
- if ($result === false) {
- $result = PEAR::raiseError('mail() returned failure');
- }
-
- return $result;
- }
-
-}
diff --git a/inc/Mail/mime.php b/inc/Mail/mime.php
deleted file mode 100644
index 302a2120d78..00000000000
--- a/inc/Mail/mime.php
+++ /dev/null
@@ -1,713 +0,0 @@
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-// +-----------------------------------------------------------------------+
-// | Copyright (c) 2002-2003 Richard Heyes |
-// | Copyright (c) 2003-2005 The PHP Group |
-// | All rights reserved. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | o Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | o Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution.|
-// | o The names of the authors may not be used to endorse or promote |
-// | products derived from this software without specific prior written |
-// | permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
-// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
-// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
-// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
-// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
-// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
-// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
-// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
-// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
-// | |
-// +-----------------------------------------------------------------------+
-// | Author: Richard Heyes <richard@phpguru.org> |
-// | Tomas V.V.Cox <cox@idecnet.com> (port to PEAR) |
-// +-----------------------------------------------------------------------+
-//
-// $Id: mime.php,v 1.39 2005/06/13 21:24:16 cipri Exp $
-
-require_once('PEAR.php');
-require_once('Mail/mimePart.php');
-
-/**
- * Mime mail composer class. Can handle: text and html bodies, embedded html
- * images and attachments.
- * Documentation and examples of this class are avaible here:
- * http://pear.php.net/manual/
- *
- * @notes This class is based on HTML Mime Mail class from
- * Richard Heyes <richard@phpguru.org> which was based also
- * in the mime_mail.class by Tobias Ratschiller <tobias@dnet.it> and
- * Sascha Schumann <sascha@schumann.cx>
- *
- * @author Richard Heyes <richard.heyes@heyes-computing.net>
- * @author Tomas V.V.Cox <cox@idecnet.com>
- * @package Mail
- * @access public
- */
-class Mail_mime
-{
- /**
- * Contains the plain text part of the email
- * @var string
- */
- var $_txtbody;
- /**
- * Contains the html part of the email
- * @var string
- */
- var $_htmlbody;
- /**
- * contains the mime encoded text
- * @var string
- */
- var $_mime;
- /**
- * contains the multipart content
- * @var string
- */
- var $_multipart;
- /**
- * list of the attached images
- * @var array
- */
- var $_html_images = array();
- /**
- * list of the attachements
- * @var array
- */
- var $_parts = array();
- /**
- * Build parameters
- * @var array
- */
- var $_build_params = array();
- /**
- * Headers for the mail
- * @var array
- */
- var $_headers = array();
- /**
- * End Of Line sequence (for serialize)
- * @var string
- */
- var $_eol;
-
-
- /**
- * Constructor function
- *
- * @access public
- */
- function Mail_mime($crlf = "\r\n")
- {
- $this->_setEOL($crlf);
- $this->_build_params = array(
- 'text_encoding' => '7bit',
- 'html_encoding' => 'quoted-printable',
- '7bit_wrap' => 998,
- 'html_charset' => 'ISO-8859-1',
- 'text_charset' => 'ISO-8859-1',
- 'head_charset' => 'ISO-8859-1'
- );
- }
-
- /**
- * Wakeup (unserialize) - re-sets EOL constant
- *
- * @access private
- */
- function __wakeup()
- {
- $this->_setEOL($this->_eol);
- }
-
- /**
- * Accessor function to set the body text. Body text is used if
- * it's not an html mail being sent or else is used to fill the
- * text/plain part that emails clients who don't support
- * html should show.
- *
- * @param string $data Either a string or
- * the file name with the contents
- * @param bool $isfile If true the first param should be treated
- * as a file name, else as a string (default)
- * @param bool $append If true the text or file is appended to
- * the existing body, else the old body is
- * overwritten
- * @return mixed true on success or PEAR_Error object
- * @access public
- */
- function setTXTBody($data, $isfile = false, $append = false)
- {
- if (!$isfile) {
- if (!$append) {
- $this->_txtbody = $data;
- } else {
- $this->_txtbody .= $data;
- }
- } else {
- $cont = $this->_file2str($data);
- if (PEAR::isError($cont)) {
- return $cont;
- }
- if (!$append) {
- $this->_txtbody = $cont;
- } else {
- $this->_txtbody .= $cont;
- }
- }
- return true;
- }
-
- /**
- * Adds a html part to the mail
- *
- * @param string $data Either a string or the file name with the
- * contents
- * @param bool $isfile If true the first param should be treated
- * as a file name, else as a string (default)
- * @return mixed true on success or PEAR_Error object
- * @access public
- */
- function setHTMLBody($data, $isfile = false)
- {
- if (!$isfile) {
- $this->_htmlbody = $data;
- } else {
- $cont = $this->_file2str($data);
- if (PEAR::isError($cont)) {
- return $cont;
- }
- $this->_htmlbody = $cont;
- }
-
- return true;
- }
-
- /**
- * Adds an image to the list of embedded images.
- *
- * @param string $file The image file name OR image data itself
- * @param string $c_type The content type
- * @param string $name The filename of the image.
- * Only use if $file is the image data
- * @param bool $isfilename Whether $file is a filename or not
- * Defaults to true
- * @return mixed true on success or PEAR_Error object
- * @access public
- */
- function addHTMLImage($file, $c_type='application/octet-stream',
- $name = '', $isfilename = true)
- {
- $filedata = ($isfilename === true) ? $this->_file2str($file)
- : $file;
- if ($isfilename === true) {
- $filename = ($name == '' ? basename($file) : basename($name));
- } else {
- $filename = basename($name);
- }
- if (PEAR::isError($filedata)) {
- return $filedata;
- }
- $this->_html_images[] = array(
- 'body' => $filedata,
- 'name' => $filename,
- 'c_type' => $c_type,
- 'cid' => md5(uniqid(time()))
- );
- return true;
- }
-
- /**
- * Adds a file to the list of attachments.
- *
- * @param string $file The file name of the file to attach
- * OR the file data itself
- * @param string $c_type The content type
- * @param string $name The filename of the attachment
- * Only use if $file is the file data
- * @param bool $isFilename Whether $file is a filename or not
- * Defaults to true
- * @return mixed true on success or PEAR_Error object
- * @access public
- */
- function addAttachment($file, $c_type = 'application/octet-stream',
- $name = '', $isfilename = true,
- $encoding = 'base64')
- {
- $filedata = ($isfilename === true) ? $this->_file2str($file)
- : $file;
- if ($isfilename === true) {
- // Force the name the user supplied, otherwise use $file
- $filename = (!empty($name)) ? $name : $file;
- } else {
- $filename = $name;
- }
- if (empty($filename)) {
- return PEAR::raiseError(
- 'The supplied filename for the attachment can\'t be empty'
- );
- }
- $filename = basename($filename);
- if (PEAR::isError($filedata)) {
- return $filedata;
- }
-
- $this->_parts[] = array(
- 'body' => $filedata,
- 'name' => $filename,
- 'c_type' => $c_type,
- 'encoding' => $encoding
- );
- return true;
- }
-
- /**
- * Get the contents of the given file name as string
- *
- * @param string $file_name path of file to process
- * @return string contents of $file_name
- * @access private
- */
- function &_file2str($file_name)
- {
- if (!is_readable($file_name)) {
- return PEAR::raiseError('File is not readable ' . $file_name);
- }
- if (!$fd = fopen($file_name, 'rb')) {
- return PEAR::raiseError('Could not open ' . $file_name);
- }
- $filesize = filesize($file_name);
- if ($filesize == 0){
- $cont = "";
- }else{
- $cont = fread($fd, $filesize);
- }
- fclose($fd);
- return $cont;
- }
-
- /**
- * Adds a text subpart to the mimePart object and
- * returns it during the build process.
- *
- * @param mixed The object to add the part to, or
- * null if a new object is to be created.
- * @param string The text to add.
- * @return object The text mimePart object
- * @access private
- */
- function &_addTextPart(&$obj, $text)
- {
- $params['content_type'] = 'text/plain';
- $params['encoding'] = $this->_build_params['text_encoding'];
- $params['charset'] = $this->_build_params['text_charset'];
- if (is_object($obj)) {
- return $obj->addSubpart($text, $params);
- } else {
- return new Mail_mimePart($text, $params);
- }
- }
-
- /**
- * Adds a html subpart to the mimePart object and
- * returns it during the build process.
- *
- * @param mixed The object to add the part to, or
- * null if a new object is to be created.
- * @return object The html mimePart object
- * @access private
- */
- function &_addHtmlPart(&$obj)
- {
- $params['content_type'] = 'text/html';
- $params['encoding'] = $this->_build_params['html_encoding'];
- $params['charset'] = $this->_build_params['html_charset'];
- if (is_object($obj)) {
- return $obj->addSubpart($this->_htmlbody, $params);
- } else {
- return new Mail_mimePart($this->_htmlbody, $params);
- }
- }
-
- /**
- * Creates a new mimePart object, using multipart/mixed as
- * the initial content-type and returns it during the
- * build process.
- *
- * @return object The multipart/mixed mimePart object
- * @access private
- */
- function &_addMixedPart()
- {
- $params['content_type'] = 'multipart/mixed';
- return new Mail_mimePart('', $params);
- }
-
- /**
- * Adds a multipart/alternative part to a mimePart
- * object (or creates one), and returns it during
- * the build process.
- *
- * @param mixed The object to add the part to, or
- * null if a new object is to be created.
- * @return object The multipart/mixed mimePart object
- * @access private
- */
- function &_addAlternativePart(&$obj)
- {
- $params['content_type'] = 'multipart/alternative';
- if (is_object($obj)) {
- return $obj->addSubpart('', $params);
- } else {
- return new Mail_mimePart('', $params);
- }
- }
-
- /**
- * Adds a multipart/related part to a mimePart
- * object (or creates one), and returns it during
- * the build process.
- *
- * @param mixed The object to add the part to, or
- * null if a new object is to be created
- * @return object The multipart/mixed mimePart object
- * @access private
- */
- function &_addRelatedPart(&$obj)
- {
- $params['content_type'] = 'multipart/related';
- if (is_object($obj)) {
- return $obj->addSubpart('', $params);
- } else {
- return new Mail_mimePart('', $params);
- }
- }
-
- /**
- * Adds an html image subpart to a mimePart object
- * and returns it during the build process.
- *
- * @param object The mimePart to add the image to
- * @param array The image information
- * @return object The image mimePart object
- * @access private
- */
- function &_addHtmlImagePart(&$obj, $value)
- {
- $params['content_type'] = $value['c_type'];
- $params['encoding'] = 'base64';
- $params['disposition'] = 'inline';
- $params['dfilename'] = $value['name'];
- $params['cid'] = $value['cid'];
- $obj->addSubpart($value['body'], $params);
- }
-
- /**
- * Adds an attachment subpart to a mimePart object
- * and returns it during the build process.
- *
- * @param object The mimePart to add the image to
- * @param array The attachment information
- * @return object The image mimePart object
- * @access private
- */
- function &_addAttachmentPart(&$obj, $value)
- {
- $params['content_type'] = $value['c_type'];
- $params['encoding'] = $value['encoding'];
- $params['disposition'] = 'attachment';
- $params['dfilename'] = $value['name'];
- $obj->addSubpart($value['body'], $params);
- }
-
- /**
- * Builds the multipart message from the list ($this->_parts) and
- * returns the mime content.
- *
- * @param array Build parameters that change the way the email
- * is built. Should be associative. Can contain:
- * text_encoding - What encoding to use for plain text
- * Default is 7bit
- * html_encoding - What encoding to use for html
- * Default is quoted-printable
- * 7bit_wrap - Number of characters before text is
- * wrapped in 7bit encoding
- * Default is 998
- * html_charset - The character set to use for html.
- * Default is iso-8859-1
- * text_charset - The character set to use for text.
- * Default is iso-8859-1
- * head_charset - The character set to use for headers.
- * Default is iso-8859-1
- * @return string The mime content
- * @access public
- */
- function &get($build_params = null)
- {
- if (isset($build_params)) {
- while (list($key, $value) = each($build_params)) {
- $this->_build_params[$key] = $value;
- }
- }
-
- if (!empty($this->_html_images) AND isset($this->_htmlbody)) {
- foreach ($this->_html_images as $value) {
- $regex = '#(\s)((?i)src|background|href(?-i))\s*=\s*(["\']?)' . preg_quote($value['name'], '#') .
- '\3#';
- $rep = '\1\2=\3cid:' . $value['cid'] .'\3';
- $this->_htmlbody = preg_replace($regex, $rep,
- $this->_htmlbody
- );
- }
- }
-
- $null = null;
- $attachments = !empty($this->_parts) ? true : false;
- $html_images = !empty($this->_html_images) ? true : false;
- $html = !empty($this->_htmlbody) ? true : false;
- $text = (!$html AND !empty($this->_txtbody)) ? true : false;
-
- switch (true) {
- case $text AND !$attachments:
- $message =& $this->_addTextPart($null, $this->_txtbody);
- break;
-
- case !$text AND !$html AND $attachments:
- $message =& $this->_addMixedPart();
- for ($i = 0; $i < count($this->_parts); $i++) {
- $this->_addAttachmentPart($message, $this->_parts[$i]);
- }
- break;
-
- case $text AND $attachments:
- $message =& $this->_addMixedPart();
- $this->_addTextPart($message, $this->_txtbody);
- for ($i = 0; $i < count($this->_parts); $i++) {
- $this->_addAttachmentPart($message, $this->_parts[$i]);
- }
- break;
-
- case $html AND !$attachments AND !$html_images:
- if (isset($this->_txtbody)) {
- $message =& $this->_addAlternativePart($null);
- $this->_addTextPart($message, $this->_txtbody);
- $this->_addHtmlPart($message);
- } else {
- $message =& $this->_addHtmlPart($null);
- }
- break;
-
- case $html AND !$attachments AND $html_images:
- if (isset($this->_txtbody)) {
- $message =& $this->_addAlternativePart($null);
- $this->_addTextPart($message, $this->_txtbody);
- $related =& $this->_addRelatedPart($message);
- } else {
- $message =& $this->_addRelatedPart($null);
- $related =& $message;
- }
- $this->_addHtmlPart($related);
- for ($i = 0; $i < count($this->_html_images); $i++) {
- $this->_addHtmlImagePart($related, $this->_html_images[$i]);
- }
- break;
-
- case $html AND $attachments AND !$html_images:
- $message =& $this->_addMixedPart();
- if (isset($this->_txtbody)) {
- $alt =& $this->_addAlternativePart($message);
- $this->_addTextPart($alt, $this->_txtbody);
- $this->_addHtmlPart($alt);
- } else {
- $this->_addHtmlPart($message);
- }
- for ($i = 0; $i < count($this->_parts); $i++) {
- $this->_addAttachmentPart($message, $this->_parts[$i]);
- }
- break;
-
- case $html AND $attachments AND $html_images:
- $message =& $this->_addMixedPart();
- if (isset($this->_txtbody)) {
- $alt =& $this->_addAlternativePart($message);
- $this->_addTextPart($alt, $this->_txtbody);
- $rel =& $this->_addRelatedPart($alt);
- } else {
- $rel =& $this->_addRelatedPart($message);
- }
- $this->_addHtmlPart($rel);
- for ($i = 0; $i < count($this->_html_images); $i++) {
- $this->_addHtmlImagePart($rel, $this->_html_images[$i]);
- }
- for ($i = 0; $i < count($this->_parts); $i++) {
- $this->_addAttachmentPart($message, $this->_parts[$i]);
- }
- break;
-
- }
-
- if (isset($message)) {
- $output = $message->encode();
- $this->_headers = array_merge($this->_headers,
- $output['headers']);
- return $output['body'];
-
- } else {
- return false;
- }
- }
-
- /**
- * Returns an array with the headers needed to prepend to the email
- * (MIME-Version and Content-Type). Format of argument is:
- * $array['header-name'] = 'header-value';
- *
- * @param array $xtra_headers Assoc array with any extra headers.
- * Optional.
- * @return array Assoc array with the mime headers
- * @access public
- */
- function &headers($xtra_headers = null)
- {
- // Content-Type header should already be present,
- // So just add mime version header
- $headers['MIME-Version'] = '1.0';
- if (isset($xtra_headers)) {
- $headers = array_merge($headers, $xtra_headers);
- }
- $this->_headers = array_merge($headers, $this->_headers);
-
- return $this->_encodeHeaders($this->_headers);
- }
-
- /**
- * Get the text version of the headers
- * (usefull if you want to use the PHP mail() function)
- *
- * @param array $xtra_headers Assoc array with any extra headers.
- * Optional.
- * @return string Plain text headers
- * @access public
- */
- function txtHeaders($xtra_headers = null)
- {
- $headers = $this->headers($xtra_headers);
- $ret = '';
- foreach ($headers as $key => $val) {
- $ret .= "$key: $val" . MAIL_MIME_CRLF;
- }
- return $ret;
- }
-
- /**
- * Sets the Subject header
- *
- * @param string $subject String to set the subject to
- * access public
- */
- function setSubject($subject)
- {
- $this->_headers['Subject'] = $subject;
- }
-
- /**
- * Set an email to the From (the sender) header
- *
- * @param string $email The email direction to add
- * @access public
- */
- function setFrom($email)
- {
- $this->_headers['From'] = $email;
- }
-
- /**
- * Add an email to the Cc (carbon copy) header
- * (multiple calls to this method are allowed)
- *
- * @param string $email The email direction to add
- * @access public
- */
- function addCc($email)
- {
- if (isset($this->_headers['Cc'])) {
- $this->_headers['Cc'] .= ", $email";
- } else {
- $this->_headers['Cc'] = $email;
- }
- }
-
- /**
- * Add an email to the Bcc (blank carbon copy) header
- * (multiple calls to this method are allowed)
- *
- * @param string $email The email direction to add
- * @access public
- */
- function addBcc($email)
- {
- if (isset($this->_headers['Bcc'])) {
- $this->_headers['Bcc'] .= ", $email";
- } else {
- $this->_headers['Bcc'] = $email;
- }
- }
-
- /**
- * Encodes a header as per RFC2047
- *
- * @param string $input The header data to encode
- * @return string Encoded data
- * @access private
- */
- function _encodeHeaders($input)
- {
- foreach ($input as $hdr_name => $hdr_value) {
- preg_match_all('/(\w*[\x80-\xFF]+\w*)/', $hdr_value, $matches);
- foreach ($matches[1] as $value) {
- $replacement = preg_replace('/([\x80-\xFF])/e',
- '"=" .
- strtoupper(dechex(ord("\1")))',
- $value);
- $hdr_value = str_replace($value, '=?' .
- $this->_build_params['head_charset'] .
- '?Q?' . $replacement . '?=',
- $hdr_value);
- }
- $input[$hdr_name] = $hdr_value;
- }
-
- return $input;
- }
-
- /**
- * Set the object's end-of-line and define the constant if applicable
- *
- * @param string $eol End Of Line sequence
- * @access private
- */
- function _setEOL($eol)
- {
- $this->_eol = $eol;
- if (!defined('MAIL_MIME_CRLF')) {
- define('MAIL_MIME_CRLF', $this->_eol, true);
- }
- }
-
-
-
-} // End of class
-?>
diff --git a/inc/Mail/mimeDecode.php b/inc/Mail/mimeDecode.php
deleted file mode 100644
index d5187d9b7aa..00000000000
--- a/inc/Mail/mimeDecode.php
+++ /dev/null
@@ -1,837 +0,0 @@
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-// +-----------------------------------------------------------------------+
-// | Copyright (c) 2002-2003 Richard Heyes |
-// | Copyright (c) 2003-2005 The PHP Group |
-// | All rights reserved. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | o Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | o Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution.|
-// | o The names of the authors may not be used to endorse or promote |
-// | products derived from this software without specific prior written |
-// | permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
-// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
-// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
-// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
-// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
-// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
-// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
-// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
-// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
-// | |
-// +-----------------------------------------------------------------------+
-// | Author: Richard Heyes <richard@phpguru.org> |
-// +-----------------------------------------------------------------------+
-
-require_once 'PEAR.php';
-
-/**
-* +----------------------------- IMPORTANT ------------------------------+
-* | Usage of this class compared to native php extensions such as |
-* | mailparse or imap, is slow and may be feature deficient. If available|
-* | you are STRONGLY recommended to use the php extensions. |
-* +----------------------------------------------------------------------+
-*
-* Mime Decoding class
-*
-* This class will parse a raw mime email and return
-* the structure. Returned structure is similar to
-* that returned by imap_fetchstructure().
-*
-* USAGE: (assume $input is your raw email)
-*
-* $decode = new Mail_mimeDecode($input, "\r\n");
-* $structure = $decode->decode();
-* print_r($structure);
-*
-* Or statically:
-*
-* $params['input'] = $input;
-* $structure = Mail_mimeDecode::decode($params);
-* print_r($structure);
-*
-* TODO:
-* o Implement multipart/appledouble
-* o UTF8: ???
-
- > 4. We have also found a solution for decoding the UTF-8
- > headers. Therefore I made the following function:
- >
- > function decode_utf8($txt) {
- > $trans=array("Å&#8216;"=>"õ","ű"=>"û","Å"=>"Ã&#8226;","Å°"
- =>"Ã&#8250;");
- > $txt=strtr($txt,$trans);
- > return(utf8_decode($txt));
- > }
- >
- > And I have inserted the following line to the class:
- >
- > if (strtolower($charset)=="utf-8") $text=decode_utf8($text);
- >
- > ... before the following one in the "_decodeHeader" function:
- >
- > $input = str_replace($encoded, $text, $input);
- >
- > This way from now on it can easily decode the UTF-8 headers too.
-
-*
-* @author Richard Heyes <richard@phpguru.org>
-* @version $Revision: 1.46 $
-* @package Mail
-*/
-class Mail_mimeDecode extends PEAR
-{
- /**
- * The raw email to decode
- * @var string
- */
- var $_input;
-
- /**
- * The header part of the input
- * @var string
- */
- var $_header;
-
- /**
- * The body part of the input
- * @var string
- */
- var $_body;
-
- /**
- * If an error occurs, this is used to store the message
- * @var string
- */
- var $_error;
-
- /**
- * Flag to determine whether to include bodies in the
- * returned object.
- * @var boolean
- */
- var $_include_bodies;
-
- /**
- * Flag to determine whether to decode bodies
- * @var boolean
- */
- var $_decode_bodies;
-
- /**
- * Flag to determine whether to decode headers
- * @var boolean
- */
- var $_decode_headers;
-
- /**
- * Constructor.
- *
- * Sets up the object, initialise the variables, and splits and
- * stores the header and body of the input.
- *
- * @param string The input to decode
- * @access public
- */
- function Mail_mimeDecode($input)
- {
- list($header, $body) = $this->_splitBodyHeader($input);
-
- $this->_input = $input;
- $this->_header = $header;
- $this->_body = $body;
- $this->_decode_bodies = false;
- $this->_include_bodies = true;
- }
-
- /**
- * Begins the decoding process. If called statically
- * it will create an object and call the decode() method
- * of it.
- *
- * @param array An array of various parameters that determine
- * various things:
- * include_bodies - Whether to include the body in the returned
- * object.
- * decode_bodies - Whether to decode the bodies
- * of the parts. (Transfer encoding)
- * decode_headers - Whether to decode headers
- * input - If called statically, this will be treated
- * as the input
- * @return object Decoded results
- * @access public
- */
- function decode($params = null)
- {
- // determine if this method has been called statically
- $isStatic = !(isset($this) && get_class($this) == __CLASS__);
-
- // Have we been called statically?
- // If so, create an object and pass details to that.
- if ($isStatic AND isset($params['input'])) {
-
- $obj = new Mail_mimeDecode($params['input']);
- $structure = $obj->decode($params);
-
- // Called statically but no input
- } elseif ($isStatic) {
- return PEAR::raiseError('Called statically and no input given');
-
- // Called via an object
- } else {
- $this->_include_bodies = isset($params['include_bodies']) ?
- $params['include_bodies'] : false;
- $this->_decode_bodies = isset($params['decode_bodies']) ?
- $params['decode_bodies'] : false;
- $this->_decode_headers = isset($params['decode_headers']) ?
- $params['decode_headers'] : false;
-
- $structure = $this->_decode($this->_header, $this->_body);
- if ($structure === false) {
- $structure = $this->raiseError($this->_error);
- }
- }
-
- return $structure;
- }
-
- /**
- * Performs the decoding. Decodes the body string passed to it
- * If it finds certain content-types it will call itself in a
- * recursive fashion
- *
- * @param string Header section
- * @param string Body section
- * @return object Results of decoding process
- * @access private
- */
- function _decode($headers, $body, $default_ctype = 'text/plain')
- {
- $return = new stdClass;
- $return->headers = array();
- $headers = $this->_parseHeaders($headers);
-
- foreach ($headers as $value) {
- if (isset($return->headers[strtolower($value['name'])]) AND !is_array($return->headers[strtolower($value['name'])])) {
- $return->headers[strtolower($value['name'])] = array($return->headers[strtolower($value['name'])]);
- $return->headers[strtolower($value['name'])][] = $value['value'];
-
- } elseif (isset($return->headers[strtolower($value['name'])])) {
- $return->headers[strtolower($value['name'])][] = $value['value'];
-
- } else {
- $return->headers[strtolower($value['name'])] = $value['value'];
- }
- }
-
- reset($headers);
- while (list($key, $value) = each($headers)) {
- $headers[$key]['name'] = strtolower($headers[$key]['name']);
- switch ($headers[$key]['name']) {
-
- case 'content-type':
- $content_type = $this->_parseHeaderValue($headers[$key]['value']);
-
- if (preg_match('/([0-9a-z+.-]+)\/([0-9a-z+.-]+)/i', $content_type['value'], $regs)) {
- $return->ctype_primary = $regs[1];
- $return->ctype_secondary = $regs[2];
- }
-
- if (isset($content_type['other'])) {
- while (list($p_name, $p_value) = each($content_type['other'])) {
- $return->ctype_parameters[$p_name] = $p_value;
- }
- }
- break;
-
- case 'content-disposition':
- $content_disposition = $this->_parseHeaderValue($headers[$key]['value']);
- $return->disposition = $content_disposition['value'];
- if (isset($content_disposition['other'])) {
- while (list($p_name, $p_value) = each($content_disposition['other'])) {
- $return->d_parameters[$p_name] = $p_value;
- }
- }
- break;
-
- case 'content-transfer-encoding':
- $content_transfer_encoding = $this->_parseHeaderValue($headers[$key]['value']);
- break;
- }
- }
-
- if (isset($content_type)) {
- switch (strtolower($content_type['value'])) {
- case 'text/plain':
- $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
- $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding) : $body) : null;
- break;
-
- case 'text/html':
- $encoding = isset($content_transfer_encoding) ? $content_transfer_encoding['value'] : '7bit';
- $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $encoding) : $body) : null;
- break;
-
- case 'multipart/parallel':
- case 'multipart/report': // RFC1892
- case 'multipart/signed': // PGP
- case 'multipart/digest':
- case 'multipart/alternative':
- case 'multipart/related':
- case 'multipart/mixed':
- if(!isset($content_type['other']['boundary'])){
- $this->_error = 'No boundary found for ' . $content_type['value'] . ' part';
- return false;
- }
-
- $default_ctype = (strtolower($content_type['value']) === 'multipart/digest') ? 'message/rfc822' : 'text/plain';
-
- $parts = $this->_boundarySplit($body, $content_type['other']['boundary']);
- for ($i = 0; $i < count($parts); $i++) {
- list($part_header, $part_body) = $this->_splitBodyHeader($parts[$i]);
- $part = $this->_decode($part_header, $part_body, $default_ctype);
- if($part === false)
- $part = $this->raiseError($this->_error);
- $return->parts[] = $part;
- }
- break;
-
- case 'message/rfc822':
- $obj = &new Mail_mimeDecode($body);
- $return->parts[] = $obj->decode(array('include_bodies' => $this->_include_bodies,
- 'decode_bodies' => $this->_decode_bodies,
- 'decode_headers' => $this->_decode_headers));
- unset($obj);
- break;
-
- default:
- if(!isset($content_transfer_encoding['value']))
- $content_transfer_encoding['value'] = '7bit';
- $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body, $content_transfer_encoding['value']) : $body) : null;
- break;
- }
-
- } else {
- $ctype = explode('/', $default_ctype);
- $return->ctype_primary = $ctype[0];
- $return->ctype_secondary = $ctype[1];
- $this->_include_bodies ? $return->body = ($this->_decode_bodies ? $this->_decodeBody($body) : $body) : null;
- }
-
- return $return;
- }
-
- /**
- * Given the output of the above function, this will return an
- * array of references to the parts, indexed by mime number.
- *
- * @param object $structure The structure to go through
- * @param string $mime_number Internal use only.
- * @return array Mime numbers
- */
- function &getMimeNumbers(&$structure, $no_refs = false, $mime_number = '', $prepend = '')
- {
- $return = array();
- if (!empty($structure->parts)) {
- if ($mime_number != '') {
- $structure->mime_id = $prepend . $mime_number;
- $return[$prepend . $mime_number] = &$structure;
- }
- for ($i = 0; $i < count($structure->parts); $i++) {
-
-
- if (!empty($structure->headers['content-type']) AND substr(strtolower($structure->headers['content-type']), 0, 8) == 'message/') {
- $prepend = $prepend . $mime_number . '.';
- $_mime_number = '';
- } else {
- $_mime_number = ($mime_number == '' ? $i + 1 : sprintf('%s.%s', $mime_number, $i + 1));
- }
-
- $arr = &Mail_mimeDecode::getMimeNumbers($structure->parts[$i], $no_refs, $_mime_number, $prepend);
- foreach ($arr as $key => $val) {
- $no_refs ? $return[$key] = '' : $return[$key] = &$arr[$key];
- }
- }
- } else {
- if ($mime_number == '') {
- $mime_number = '1';
- }
- $structure->mime_id = $prepend . $mime_number;
- $no_refs ? $return[$prepend . $mime_number] = '' : $return[$prepend . $mime_number] = &$structure;
- }
-
- return $return;
- }
-
- /**
- * Given a string containing a header and body
- * section, this function will split them (at the first
- * blank line) and return them.
- *
- * @param string Input to split apart
- * @return array Contains header and body section
- * @access private
- */
- function _splitBodyHeader($input)
- {
- if (preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $input, $match)) {
- return array($match[1], $match[2]);
- }
- $this->_error = 'Could not split header and body';
- return false;
- }
-
- /**
- * Parse headers given in $input and return
- * as assoc array.
- *
- * @param string Headers to parse
- * @return array Contains parsed headers
- * @access private
- */
- function _parseHeaders($input)
- {
-
- if ($input !== '') {
- // Unfold the input
- $input = preg_replace("/\r?\n/", "\r\n", $input);
- $input = preg_replace("/\r\n(\t| )+/", ' ', $input);
- $headers = explode("\r\n", trim($input));
-
- foreach ($headers as $value) {
- $hdr_name = substr($value, 0, $pos = strpos($value, ':'));
- $hdr_value = substr($value, $pos+1);
- if($hdr_value[0] == ' ')
- $hdr_value = substr($hdr_value, 1);
-
- $return[] = array(
- 'name' => $hdr_name,
- 'value' => $this->_decode_headers ? $this->_decodeHeader($hdr_value) : $hdr_value
- );
- }
- } else {
- $return = array();
- }
-
- return $return;
- }
-
- /**
- * Function to parse a header value,
- * extract first part, and any secondary
- * parts (after ;) This function is not as
- * robust as it could be. Eg. header comments
- * in the wrong place will probably break it.
- *
- * @param string Header value to parse
- * @return array Contains parsed result
- * @access private
- */
- function _parseHeaderValue($input)
- {
-
- if (($pos = strpos($input, ';')) !== false) {
-
- $return['value'] = trim(substr($input, 0, $pos));
- $input = trim(substr($input, $pos+1));
-
- if (strlen($input) > 0) {
-
- // This splits on a semi-colon, if there's no preceeding backslash
- // Now works with quoted values; had to glue the \; breaks in PHP
- // the regex is already bordering on incomprehensible
- $splitRegex = '/([^;\'"]*[\'"]([^\'"]*([^\'"]*)*)[\'"][^;\'"]*|([^;]+))(;|$)/';
- preg_match_all($splitRegex, $input, $matches);
- $parameters = array();
- for ($i=0; $i<count($matches[0]); $i++) {
- $param = $matches[0][$i];
- while (substr($param, -2) == '\;') {
- $param .= $matches[0][++$i];
- }
- $parameters[] = $param;
- }
-
- for ($i = 0; $i < count($parameters); $i++) {
- $param_name = trim(substr($parameters[$i], 0, $pos = strpos($parameters[$i], '=')), "'\";\t\\ ");
- $param_value = trim(str_replace('\;', ';', substr($parameters[$i], $pos + 1)), "'\";\t\\ ");
- if ($param_value[0] == '"') {
- $param_value = substr($param_value, 1, -1);
- }
- $return['other'][$param_name] = $param_value;
- $return['other'][strtolower($param_name)] = $param_value;
- }
- }
- } else {
- $return['value'] = trim($input);
- }
-
- return $return;
- }
-
- /**
- * This function splits the input based
- * on the given boundary
- *
- * @param string Input to parse
- * @return array Contains array of resulting mime parts
- * @access private
- */
- function _boundarySplit($input, $boundary)
- {
- $parts = array();
-
- $bs_possible = substr($boundary, 2, -2);
- $bs_check = '\"' . $bs_possible . '\"';
-
- if ($boundary == $bs_check) {
- $boundary = $bs_possible;
- }
-
- $tmp = explode('--' . $boundary, $input);
-
- for ($i = 1; $i < count($tmp) - 1; $i++) {
- $parts[] = $tmp[$i];
- }
-
- return $parts;
- }
-
- /**
- * Given a header, this function will decode it
- * according to RFC2047. Probably not *exactly*
- * conformant, but it does pass all the given
- * examples (in RFC2047).
- *
- * @param string Input header value to decode
- * @return string Decoded header value
- * @access private
- */
- function _decodeHeader($input)
- {
- // Remove white space between encoded-words
- $input = preg_replace('/(=\?[^?]+\?(q|b)\?[^?]*\?=)(\s)+=\?/i', '\1=?', $input);
-
- // For each encoded-word...
- while (preg_match('/(=\?([^?]+)\?(q|b)\?([^?]*)\?=)/i', $input, $matches)) {
-
- $encoded = $matches[1];
- $charset = $matches[2];
- $encoding = $matches[3];
- $text = $matches[4];
-
- switch (strtolower($encoding)) {
- case 'b':
- $text = base64_decode($text);
- break;
-
- case 'q':
- $text = str_replace('_', ' ', $text);
- preg_match_all('/=([a-f0-9]{2})/i', $text, $matches);
- foreach($matches[1] as $value)
- $text = str_replace('='.$value, chr(hexdec($value)), $text);
- break;
- }
-
- $input = str_replace($encoded, $text, $input);
- }
-
- return $input;
- }
-
- /**
- * Given a body string and an encoding type,
- * this function will decode and return it.
- *
- * @param string Input body to decode
- * @param string Encoding type to use.
- * @return string Decoded body
- * @access private
- */
- function _decodeBody($input, $encoding = '7bit')
- {
- switch (strtolower($encoding)) {
- case '7bit':
- return $input;
- break;
-
- case 'quoted-printable':
- return $this->_quotedPrintableDecode($input);
- break;
-
- case 'base64':
- return base64_decode($input);
- break;
-
- default:
- return $input;
- }
- }
-
- /**
- * Given a quoted-printable string, this
- * function will decode and return it.
- *
- * @param string Input body to decode
- * @return string Decoded body
- * @access private
- */
- function _quotedPrintableDecode($input)
- {
- // Remove soft line breaks
- $input = preg_replace("/=\r?\n/", '', $input);
-
- // Replace encoded characters
- $input = preg_replace('/=([a-f0-9]{2})/ie', "chr(hexdec('\\1'))", $input);
-
- return $input;
- }
-
- /**
- * Checks the input for uuencoded files and returns
- * an array of them. Can be called statically, eg:
- *
- * $files =& Mail_mimeDecode::uudecode($some_text);
- *
- * It will check for the begin 666 ... end syntax
- * however and won't just blindly decode whatever you
- * pass it.
- *
- * @param string Input body to look for attahcments in
- * @return array Decoded bodies, filenames and permissions
- * @access public
- * @author Unknown
- */
- function &uudecode($input)
- {
- // Find all uuencoded sections
- preg_match_all("/begin ([0-7]{3}) (.+)\r?\n(.+)\r?\nend/Us", $input, $matches);
-
- for ($j = 0; $j < count($matches[3]); $j++) {
-
- $str = $matches[3][$j];
- $filename = $matches[2][$j];
- $fileperm = $matches[1][$j];
-
- $file = '';
- $str = preg_split("/\r?\n/", trim($str));
- $strlen = count($str);
-
- for ($i = 0; $i < $strlen; $i++) {
- $pos = 1;
- $d = 0;
- $len=(int)(((ord(substr($str[$i],0,1)) -32) - ' ') & 077);
-
- while (($d + 3 <= $len) AND ($pos + 4 <= strlen($str[$i]))) {
- $c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);
- $c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);
- $c2 = (ord(substr($str[$i],$pos+2,1)) ^ 0x20);
- $c3 = (ord(substr($str[$i],$pos+3,1)) ^ 0x20);
- $file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));
-
- $file .= chr(((($c1 - ' ') & 077) << 4) | ((($c2 - ' ') & 077) >> 2));
-
- $file .= chr(((($c2 - ' ') & 077) << 6) | (($c3 - ' ') & 077));
-
- $pos += 4;
- $d += 3;
- }
-
- if (($d + 2 <= $len) && ($pos + 3 <= strlen($str[$i]))) {
- $c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);
- $c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);
- $c2 = (ord(substr($str[$i],$pos+2,1)) ^ 0x20);
- $file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));
-
- $file .= chr(((($c1 - ' ') & 077) << 4) | ((($c2 - ' ') & 077) >> 2));
-
- $pos += 3;
- $d += 2;
- }
-
- if (($d + 1 <= $len) && ($pos + 2 <= strlen($str[$i]))) {
- $c0 = (ord(substr($str[$i],$pos,1)) ^ 0x20);
- $c1 = (ord(substr($str[$i],$pos+1,1)) ^ 0x20);
- $file .= chr(((($c0 - ' ') & 077) << 2) | ((($c1 - ' ') & 077) >> 4));
-
- }
- }
- $files[] = array('filename' => $filename, 'fileperm' => $fileperm, 'filedata' => $file);
- }
-
- return $files;
- }
-
- /**
- * getSendArray() returns the arguments required for Mail::send()
- * used to build the arguments for a mail::send() call
- *
- * Usage:
- * $mailtext = Full email (for example generated by a template)
- * $decoder = new Mail_mimeDecode($mailtext);
- * $parts = $decoder->getSendArray();
- * if (!PEAR::isError($parts) {
- * list($recipents,$headers,$body) = $parts;
- * $mail = Mail::factory('smtp');
- * $mail->send($recipents,$headers,$body);
- * } else {
- * echo $parts->message;
- * }
- * @return mixed array of recipeint, headers,body or Pear_Error
- * @access public
- * @author Alan Knowles <alan@akbkhome.com>
- */
- function getSendArray()
- {
- // prevent warning if this is not set
- $this->_decode_headers = FALSE;
- $headerlist =$this->_parseHeaders($this->_header);
- $to = "";
- if (!$headerlist) {
- return $this->raiseError("Message did not contain headers");
- }
- foreach($headerlist as $item) {
- $header[$item['name']] = $item['value'];
- switch (strtolower($item['name'])) {
- case "to":
- case "cc":
- case "bcc":
- $to = ",".$item['value'];
- default:
- break;
- }
- }
- if ($to == "") {
- return $this->raiseError("Message did not contain any recipents");
- }
- $to = substr($to,1);
- return array($to,$header,$this->_body);
- }
-
- /**
- * Returns a xml copy of the output of
- * Mail_mimeDecode::decode. Pass the output in as the
- * argument. This function can be called statically. Eg:
- *
- * $output = $obj->decode();
- * $xml = Mail_mimeDecode::getXML($output);
- *
- * The DTD used for this should have been in the package. Or
- * alternatively you can get it from cvs, or here:
- * http://www.phpguru.org/xmail/xmail.dtd.
- *
- * @param object Input to convert to xml. This should be the
- * output of the Mail_mimeDecode::decode function
- * @return string XML version of input
- * @access public
- */
- function getXML($input)
- {
- $crlf = "\r\n";
- $output = '<?xml version=\'1.0\'?>' . $crlf .
- '<!DOCTYPE email SYSTEM "http://www.phpguru.org/xmail/xmail.dtd">' . $crlf .
- '<email>' . $crlf .
- Mail_mimeDecode::_getXML($input) .
- '</email>';
-
- return $output;
- }
-
- /**
- * Function that does the actual conversion to xml. Does a single
- * mimepart at a time.
- *
- * @param object Input to convert to xml. This is a mimepart object.
- * It may or may not contain subparts.
- * @param integer Number of tabs to indent
- * @return string XML version of input
- * @access private
- */
- function _getXML($input, $indent = 1)
- {
- $htab = "\t";
- $crlf = "\r\n";
- $output = '';
- $headers = @(array)$input->headers;
-
- foreach ($headers as $hdr_name => $hdr_value) {
-
- // Multiple headers with this name
- if (is_array($headers[$hdr_name])) {
- for ($i = 0; $i < count($hdr_value); $i++) {
- $output .= Mail_mimeDecode::_getXML_helper($hdr_name, $hdr_value[$i], $indent);
- }
-
- // Only one header of this sort
- } else {
- $output .= Mail_mimeDecode::_getXML_helper($hdr_name, $hdr_value, $indent);
- }
- }
-
- if (!empty($input->parts)) {
- for ($i = 0; $i < count($input->parts); $i++) {
- $output .= $crlf . str_repeat($htab, $indent) . '<mimepart>' . $crlf .
- Mail_mimeDecode::_getXML($input->parts[$i], $indent+1) .
- str_repeat($htab, $indent) . '</mimepart>' . $crlf;
- }
- } elseif (isset($input->body)) {
- $output .= $crlf . str_repeat($htab, $indent) . '<body><![CDATA[' .
- $input->body . ']]></body>' . $crlf;
- }
-
- return $output;
- }
-
- /**
- * Helper function to _getXML(). Returns xml of a header.
- *
- * @param string Name of header
- * @param string Value of header
- * @param integer Number of tabs to indent
- * @return string XML version of input
- * @access private
- */
- function _getXML_helper($hdr_name, $hdr_value, $indent)
- {
- $htab = "\t";
- $crlf = "\r\n";
- $return = '';
-
- $new_hdr_value = ($hdr_name != 'received') ? Mail_mimeDecode::_parseHeaderValue($hdr_value) : array('value' => $hdr_value);
- $new_hdr_name = str_replace(' ', '-', ucwords(str_replace('-', ' ', $hdr_name)));
-
- // Sort out any parameters
- if (!empty($new_hdr_value['other'])) {
- foreach ($new_hdr_value['other'] as $paramname => $paramvalue) {
- $params[] = str_repeat($htab, $indent) . $htab . '<parameter>' . $crlf .
- str_repeat($htab, $indent) . $htab . $htab . '<paramname>' . htmlspecialchars($paramname) . '</paramname>' . $crlf .
- str_repeat($htab, $indent) . $htab . $htab . '<paramvalue>' . htmlspecialchars($paramvalue) . '</paramvalue>' . $crlf .
- str_repeat($htab, $indent) . $htab . '</parameter>' . $crlf;
- }
-
- $params = implode('', $params);
- } else {
- $params = '';
- }
-
- $return = str_repeat($htab, $indent) . '<header>' . $crlf .
- str_repeat($htab, $indent) . $htab . '<headername>' . htmlspecialchars($new_hdr_name) . '</headername>' . $crlf .
- str_repeat($htab, $indent) . $htab . '<headervalue>' . htmlspecialchars($new_hdr_value['value']) . '</headervalue>' . $crlf .
- $params .
- str_repeat($htab, $indent) . '</header>' . $crlf;
-
- return $return;
- }
-
-} // End of class
-?>
diff --git a/inc/Mail/mimePart.php b/inc/Mail/mimePart.php
deleted file mode 100644
index c0050d41127..00000000000
--- a/inc/Mail/mimePart.php
+++ /dev/null
@@ -1,351 +0,0 @@
-<?php
-// +-----------------------------------------------------------------------+
-// | Copyright (c) 2002-2003 Richard Heyes |
-// | All rights reserved. |
-// | |
-// | Redistribution and use in source and binary forms, with or without |
-// | modification, are permitted provided that the following conditions |
-// | are met: |
-// | |
-// | o Redistributions of source code must retain the above copyright |
-// | notice, this list of conditions and the following disclaimer. |
-// | o Redistributions in binary form must reproduce the above copyright |
-// | notice, this list of conditions and the following disclaimer in the |
-// | documentation and/or other materials provided with the distribution.|
-// | o The names of the authors may not be used to endorse or promote |
-// | products derived from this software without specific prior written |
-// | permission. |
-// | |
-// | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS |
-// | "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT |
-// | LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR |
-// | A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT |
-// | OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, |
-// | SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT |
-// | LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, |
-// | DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY |
-// | THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT |
-// | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE |
-// | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. |
-// | |
-// +-----------------------------------------------------------------------+
-// | Author: Richard Heyes <richard@phpguru.org> |
-// +-----------------------------------------------------------------------+
-
-/**
-*
-* Raw mime encoding class
-*
-* What is it?
-* This class enables you to manipulate and build
-* a mime email from the ground up.
-*
-* Why use this instead of mime.php?
-* mime.php is a userfriendly api to this class for
-* people who aren't interested in the internals of
-* mime mail. This class however allows full control
-* over the email.
-*
-* Eg.
-*
-* // Since multipart/mixed has no real body, (the body is
-* // the subpart), we set the body argument to blank.
-*
-* $params['content_type'] = 'multipart/mixed';
-* $email = new Mail_mimePart('', $params);
-*
-* // Here we add a text part to the multipart we have
-* // already. Assume $body contains plain text.
-*
-* $params['content_type'] = 'text/plain';
-* $params['encoding'] = '7bit';
-* $text = $email->addSubPart($body, $params);
-*
-* // Now add an attachment. Assume $attach is
-* the contents of the attachment
-*
-* $params['content_type'] = 'application/zip';
-* $params['encoding'] = 'base64';
-* $params['disposition'] = 'attachment';
-* $params['dfilename'] = 'example.zip';
-* $attach =& $email->addSubPart($body, $params);
-*
-* // Now build the email. Note that the encode
-* // function returns an associative array containing two
-* // elements, body and headers. You will need to add extra
-* // headers, (eg. Mime-Version) before sending.
-*
-* $email = $message->encode();
-* $email['headers'][] = 'Mime-Version: 1.0';
-*
-*
-* Further examples are available at http://www.phpguru.org
-*
-* TODO:
-* - Set encode() to return the $obj->encoded if encode()
-* has already been run. Unless a flag is passed to specifically
-* re-build the message.
-*
-* @author Richard Heyes <richard@phpguru.org>
-* @version $Revision: 1.13 $
-* @package Mail
-*/
-
-class Mail_mimePart {
-
- /**
- * The encoding type of this part
- * @var string
- */
- var $_encoding;
-
- /**
- * An array of subparts
- * @var array
- */
- var $_subparts;
-
- /**
- * The output of this part after being built
- * @var string
- */
- var $_encoded;
-
- /**
- * Headers for this part
- * @var array
- */
- var $_headers;
-
- /**
- * The body of this part (not encoded)
- * @var string
- */
- var $_body;
-
- /**
- * Constructor.
- *
- * Sets up the object.
- *
- * @param $body - The body of the mime part if any.
- * @param $params - An associative array of parameters:
- * content_type - The content type for this part eg multipart/mixed
- * encoding - The encoding to use, 7bit, 8bit, base64, or quoted-printable
- * cid - Content ID to apply
- * disposition - Content disposition, inline or attachment
- * dfilename - Optional filename parameter for content disposition
- * description - Content description
- * charset - Character set to use
- * @access public
- */
- function Mail_mimePart($body = '', $params = array())
- {
- if (!defined('MAIL_MIMEPART_CRLF')) {
- define('MAIL_MIMEPART_CRLF', defined('MAIL_MIME_CRLF') ? MAIL_MIME_CRLF : "\r\n", TRUE);
- }
-
- foreach ($params as $key => $value) {
- switch ($key) {
- case 'content_type':
- $headers['Content-Type'] = $value . (isset($charset) ? '; charset="' . $charset . '"' : '');
- break;
-
- case 'encoding':
- $this->_encoding = $value;
- $headers['Content-Transfer-Encoding'] = $value;
- break;
-
- case 'cid':
- $headers['Content-ID'] = '<' . $value . '>';
- break;
-
- case 'disposition':
- $headers['Content-Disposition'] = $value . (isset($dfilename) ? '; filename="' . $dfilename . '"' : '');
- break;
-
- case 'dfilename':
- if (isset($headers['Content-Disposition'])) {
- $headers['Content-Disposition'] .= '; filename="' . $value . '"';
- } else {
- $dfilename = $value;
- }
- break;
-
- case 'description':
- $headers['Content-Description'] = $value;
- break;
-
- case 'charset':
- if (isset($headers['Content-Type'])) {
- $headers['Content-Type'] .= '; charset="' . $value . '"';
- } else {
- $charset = $value;
- }
- break;
- }
- }
-
- // Default content-type
- if (!isset($headers['Content-Type'])) {
- $headers['Content-Type'] = 'text/plain';
- }
-
- //Default encoding
- if (!isset($this->_encoding)) {
- $this->_encoding = '7bit';
- }
-
- // Assign stuff to member variables
- $this->_encoded = array();
- $this->_headers = $headers;
- $this->_body = $body;
- }
-
- /**
- * encode()
- *
- * Encodes and returns the email. Also stores
- * it in the encoded member variable
- *
- * @return An associative array containing two elements,
- * body and headers. The headers element is itself
- * an indexed array.
- * @access public
- */
- function encode()
- {
- $encoded =& $this->_encoded;
-
- if (!empty($this->_subparts)) {
- srand((double)microtime()*1000000);
- $boundary = '=_' . md5(rand() . microtime());
- $this->_headers['Content-Type'] .= ';' . MAIL_MIMEPART_CRLF . "\t" . 'boundary="' . $boundary . '"';
-
- // Add body parts to $subparts
- for ($i = 0; $i < count($this->_subparts); $i++) {
- $headers = array();
- $tmp = $this->_subparts[$i]->encode();
- foreach ($tmp['headers'] as $key => $value) {
- $headers[] = $key . ': ' . $value;
- }
- $subparts[] = implode(MAIL_MIMEPART_CRLF, $headers) . MAIL_MIMEPART_CRLF . MAIL_MIMEPART_CRLF . $tmp['body'];
- }
-
- $encoded['body'] = '--' . $boundary . MAIL_MIMEPART_CRLF .
- implode('--' . $boundary . MAIL_MIMEPART_CRLF, $subparts) .
- '--' . $boundary.'--' . MAIL_MIMEPART_CRLF;
-
- } else {
- $encoded['body'] = $this->_getEncodedData($this->_body, $this->_encoding) . MAIL_MIMEPART_CRLF;
- }
-
- // Add headers to $encoded
- $encoded['headers'] =& $this->_headers;
-
- return $encoded;
- }
-
- /**
- * &addSubPart()
- *
- * Adds a subpart to current mime part and returns
- * a reference to it
- *
- * @param $body The body of the subpart, if any.
- * @param $params The parameters for the subpart, same
- * as the $params argument for constructor.
- * @return A reference to the part you just added. It is
- * crucial if using multipart/* in your subparts that
- * you use =& in your script when calling this function,
- * otherwise you will not be able to add further subparts.
- * @access public
- */
- function &addSubPart($body, $params)
- {
- $this->_subparts[] = new Mail_mimePart($body, $params);
- return $this->_subparts[count($this->_subparts) - 1];
- }
-
- /**
- * _getEncodedData()
- *
- * Returns encoded data based upon encoding passed to it
- *
- * @param $data The data to encode.
- * @param $encoding The encoding type to use, 7bit, base64,
- * or quoted-printable.
- * @access private
- */
- function _getEncodedData($data, $encoding)
- {
- switch ($encoding) {
- case '8bit':
- case '7bit':
- return $data;
- break;
-
- case 'quoted-printable':
- return $this->_quotedPrintableEncode($data);
- break;
-
- case 'base64':
- return rtrim(chunk_split(base64_encode($data), 76, MAIL_MIMEPART_CRLF));
- break;
-
- default:
- return $data;
- }
- }
-
- /**
- * quoteadPrintableEncode()
- *
- * Encodes data to quoted-printable standard.
- *
- * @param $input The data to encode
- * @param $line_max Optional max line length. Should
- * not be more than 76 chars
- *
- * @access private
- */
- function _quotedPrintableEncode($input , $line_max = 76)
- {
- $lines = preg_split("/\r?\n/", $input);
- $eol = MAIL_MIMEPART_CRLF;
- $escape = '=';
- $output = '';
-
- while(list(, $line) = each($lines)){
-
- $linlen = strlen($line);
- $newline = '';
-
- for ($i = 0; $i < $linlen; $i++) {
- $char = substr($line, $i, 1);
- $dec = ord($char);
-
- if (($dec == 32) AND ($i == ($linlen - 1))){ // convert space at eol only
- $char = '=20';
-
- } elseif(($dec == 9) AND ($i == ($linlen - 1))) { // convert tab at eol only
- $char = '=09';
- } elseif($dec == 9) {
- ; // Do nothing if a tab.
- } elseif(($dec == 61) OR ($dec < 32 ) OR ($dec > 126)) {
- $char = $escape . strtoupper(sprintf('%02s', dechex($dec)));
- }
-
- if ((strlen($newline) + strlen($char)) >= $line_max) { // MAIL_MIMEPART_CRLF is not counted
- $output .= $newline . $escape . $eol; // soft line break; " =\r\n" is okay
- $newline = '';
- }
- $newline .= $char;
- } // end of for
- $output .= $newline . $eol;
- }
- $output = substr($output, 0, -1 * strlen($eol)); // Don't want last crlf
- return $output;
- }
-} // End of class
-?>
diff --git a/inc/Mail/null.php b/inc/Mail/null.php
deleted file mode 100644
index 982bfa45b6d..00000000000
--- a/inc/Mail/null.php
+++ /dev/null
@@ -1,60 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Phil Kernick <philk@rotfl.com.au> |
-// +----------------------------------------------------------------------+
-//
-// $Id: null.php,v 1.2 2004/04/06 05:19:03 jon Exp $
-//
-
-/**
- * Null implementation of the PEAR Mail:: interface.
- * @access public
- * @package Mail
- * @version $Revision: 1.2 $
- */
-class Mail_null extends Mail {
-
- /**
- * Implements Mail_null::send() function. Silently discards all
- * mail.
- *
- * @param mixed $recipients Either a comma-seperated list of recipients
- * (RFC822 compliant), or an array of recipients,
- * each RFC822 valid. This may contain recipients not
- * specified in the headers, for Bcc:, resending
- * messages, etc.
- *
- * @param array $headers The array of headers to send with the mail, in an
- * associative array, where the array key is the
- * header name (ie, 'Subject'), and the array value
- * is the header value (ie, 'test'). The header
- * produced from those values would be 'Subject:
- * test'.
- *
- * @param string $body The full text of the message body, including any
- * Mime parts, etc.
- *
- * @return mixed Returns true on success, or a PEAR_Error
- * containing a descriptive error message on
- * failure.
- * @access public
- */
- function send($recipients, $headers, $body)
- {
- return true;
- }
-
-}
diff --git a/inc/Mail/sendmail.php b/inc/Mail/sendmail.php
deleted file mode 100644
index 39a43c25062..00000000000
--- a/inc/Mail/sendmail.php
+++ /dev/null
@@ -1,145 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Chuck Hagenbuch <chuck@horde.org> |
-// +----------------------------------------------------------------------+
-
-/**
- * Sendmail implementation of the PEAR Mail:: interface.
- * @access public
- * @package Mail
- * @version $Revision: 1.10 $
- */
-class Mail_sendmail extends Mail {
-
- /**
- * The location of the sendmail or sendmail wrapper binary on the
- * filesystem.
- * @var string
- */
- var $sendmail_path = '/usr/sbin/sendmail';
-
- /**
- * Any extra command-line parameters to pass to the sendmail or
- * sendmail wrapper binary.
- * @var string
- */
- var $sendmail_args = '';
-
- /**
- * Constructor.
- *
- * Instantiates a new Mail_sendmail:: object based on the parameters
- * passed in. It looks for the following parameters:
- * sendmail_path The location of the sendmail binary on the
- * filesystem. Defaults to '/usr/sbin/sendmail'.
- *
- * sendmail_args Any extra parameters to pass to the sendmail
- * or sendmail wrapper binary.
- *
- * If a parameter is present in the $params array, it replaces the
- * default.
- *
- * @param array $params Hash containing any parameters different from the
- * defaults.
- * @access public
- */
- function Mail_sendmail($params)
- {
- if (isset($params['sendmail_path'])) $this->sendmail_path = $params['sendmail_path'];
- if (isset($params['sendmail_args'])) $this->sendmail_args = $params['sendmail_args'];
-
- /*
- * Because we need to pass message headers to the sendmail program on
- * the commandline, we can't guarantee the use of the standard "\r\n"
- * separator. Instead, we use the system's native line separator.
- */
- $this->sep = (strstr(PHP_OS, 'WIN')) ? "\r\n" : "\n";
- }
-
- /**
- * Implements Mail::send() function using the sendmail
- * command-line binary.
- *
- * @param mixed $recipients Either a comma-seperated list of recipients
- * (RFC822 compliant), or an array of recipients,
- * each RFC822 valid. This may contain recipients not
- * specified in the headers, for Bcc:, resending
- * messages, etc.
- *
- * @param array $headers The array of headers to send with the mail, in an
- * associative array, where the array key is the
- * header name (ie, 'Subject'), and the array value
- * is the header value (ie, 'test'). The header
- * produced from those values would be 'Subject:
- * test'.
- *
- * @param string $body The full text of the message body, including any
- * Mime parts, etc.
- *
- * @return mixed Returns true on success, or a PEAR_Error
- * containing a descriptive error message on
- * failure.
- * @access public
- */
- function send($recipients, $headers, $body)
- {
- $recipients = $this->parseRecipients($recipients);
- if (PEAR::isError($recipients)) {
- return $recipients;
- }
- $recipients = escapeShellCmd(implode(' ', $recipients));
-
- $headerElements = $this->prepareHeaders($headers);
- if (PEAR::isError($headerElements)) {
- return $headerElements;
- }
- list($from, $text_headers) = $headerElements;
-
- if (!isset($from)) {
- return PEAR::raiseError('No from address given.');
- } elseif (strstr($from, ' ') ||
- strstr($from, ';') ||
- strstr($from, '&') ||
- strstr($from, '`')) {
- return PEAR::raiseError('From address specified with dangerous characters.');
- }
-
- $result = 0;
- if (@is_file($this->sendmail_path)) {
- $from = escapeShellCmd($from);
- $mail = popen($this->sendmail_path . (!empty($this->sendmail_args) ? ' ' . $this->sendmail_args : '') . " -f$from -- $recipients", 'w');
- fputs($mail, $text_headers);
- fputs($mail, $this->sep); // newline to end the headers section
- fputs($mail, $body);
- $result = pclose($mail);
- if (version_compare(phpversion(), '4.2.3') == -1) {
- // With older php versions, we need to shift the
- // pclose result to get the exit code.
- $result = $result >> 8 & 0xFF;
- }
- } else {
- return PEAR::raiseError('sendmail [' . $this->sendmail_path . '] is not a valid file');
- }
-
- if ($result != 0) {
- return PEAR::raiseError('sendmail returned error code ' . $result,
- $result);
- }
-
- return true;
- }
-
-}
diff --git a/inc/Mail/smtp.php b/inc/Mail/smtp.php
deleted file mode 100644
index 40686a61689..00000000000
--- a/inc/Mail/smtp.php
+++ /dev/null
@@ -1,223 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Chuck Hagenbuch <chuck@horde.org> |
-// | Jon Parise <jon@php.net> |
-// +----------------------------------------------------------------------+
-
-/**
- * SMTP implementation of the PEAR Mail:: interface. Requires the PEAR
- * Net_SMTP:: class.
- * @access public
- * @package Mail
- * @version $Revision: 1.20 $
- */
-class Mail_smtp extends Mail {
-
- /**
- * The SMTP host to connect to.
- * @var string
- */
- var $host = 'localhost';
-
- /**
- * The port the SMTP server is on.
- * @var integer
- */
- var $port = 25;
-
- /**
- * Should SMTP authentication be used?
- *
- * This value may be set to true, false or the name of a specific
- * authentication method.
- *
- * If the value is set to true, the Net_SMTP package will attempt to use
- * the best authentication method advertised by the remote SMTP server.
- *
- * @var mixed
- */
- var $auth = false;
-
- /**
- * The username to use if the SMTP server requires authentication.
- * @var string
- */
- var $username = '';
-
- /**
- * The password to use if the SMTP server requires authentication.
- * @var string
- */
- var $password = '';
-
- /**
- * Hostname or domain that will be sent to the remote SMTP server in the
- * HELO / EHLO message.
- *
- * @var string
- */
- var $localhost = 'localhost';
-
- /**
- * SMTP connection timeout value. NULL indicates no timeout.
- *
- * @var integer
- */
- var $timeout = null;
-
- /**
- * Whether to use VERP or not. If not a boolean, the string value
- * will be used as the VERP separators.
- *
- * @var mixed boolean or string
- */
- var $verp = false;
-
- /**
- * Turn on Net_SMTP debugging?
- *
- * @var boolean $debug
- */
- var $debug = false;
-
- /**
- * Constructor.
- *
- * Instantiates a new Mail_smtp:: object based on the parameters
- * passed in. It looks for the following parameters:
- * host The server to connect to. Defaults to localhost.
- * port The port to connect to. Defaults to 25.
- * auth SMTP authentication. Defaults to none.
- * username The username to use for SMTP auth. No default.
- * password The password to use for SMTP auth. No default.
- * localhost The local hostname / domain. Defaults to localhost.
- * timeout The SMTP connection timeout. Defaults to none.
- * verp Whether to use VERP or not. Defaults to false.
- * debug Activate SMTP debug mode? Defaults to false.
- *
- * If a parameter is present in the $params array, it replaces the
- * default.
- *
- * @param array Hash containing any parameters different from the
- * defaults.
- * @access public
- */
- function Mail_smtp($params)
- {
- if (isset($params['host'])) $this->host = $params['host'];
- if (isset($params['port'])) $this->port = $params['port'];
- if (isset($params['auth'])) $this->auth = $params['auth'];
- if (isset($params['username'])) $this->username = $params['username'];
- if (isset($params['password'])) $this->password = $params['password'];
- if (isset($params['localhost'])) $this->localhost = $params['localhost'];
- if (isset($params['timeout'])) $this->timeout = $params['timeout'];
- if (isset($params['verp'])) $this->verp = $params['verp'];
- if (isset($params['debug'])) $this->debug = (boolean)$params['debug'];
- }
-
- /**
- * Implements Mail::send() function using SMTP.
- *
- * @param mixed $recipients Either a comma-seperated list of recipients
- * (RFC822 compliant), or an array of recipients,
- * each RFC822 valid. This may contain recipients not
- * specified in the headers, for Bcc:, resending
- * messages, etc.
- *
- * @param array $headers The array of headers to send with the mail, in an
- * associative array, where the array key is the
- * header name (e.g., 'Subject'), and the array value
- * is the header value (e.g., 'test'). The header
- * produced from those values would be 'Subject:
- * test'.
- *
- * @param string $body The full text of the message body, including any
- * Mime parts, etc.
- *
- * @return mixed Returns true on success, or a PEAR_Error
- * containing a descriptive error message on
- * failure.
- * @access public
- */
- function send($recipients, $headers, $body)
- {
- include_once 'Net/SMTP.php';
-
- if (!($smtp = &new Net_SMTP($this->host, $this->port, $this->localhost))) {
- return PEAR::raiseError('unable to instantiate Net_SMTP object');
- }
-
- if ($this->debug) {
- $smtp->setDebug(true);
- }
-
- if (PEAR::isError($smtp->connect($this->timeout))) {
- return PEAR::raiseError('unable to connect to smtp server ' .
- $this->host . ':' . $this->port);
- }
-
- if ($this->auth) {
- $method = is_string($this->auth) ? $this->auth : '';
-
- if (PEAR::isError($smtp->auth($this->username, $this->password,
- $method))) {
- return PEAR::raiseError('unable to authenticate to smtp server');
- }
- }
-
- $headerElements = $this->prepareHeaders($headers);
- if (PEAR::isError($headerElements)) {
- return $headerElements;
- }
- list($from, $text_headers) = $headerElements;
-
- /* Since few MTAs are going to allow this header to be forged
- * unless it's in the MAIL FROM: exchange, we'll use
- * Return-Path instead of From: if it's set. */
- if (!empty($headers['Return-Path'])) {
- $from = $headers['Return-Path'];
- }
-
- if (!isset($from)) {
- return PEAR::raiseError('No from address given');
- }
-
- $args['verp'] = $this->verp;
- if (PEAR::isError($smtp->mailFrom($from, $args))) {
- return PEAR::raiseError('unable to set sender to [' . $from . ']');
- }
-
- $recipients = $this->parseRecipients($recipients);
- if (PEAR::isError($recipients)) {
- return $recipients;
- }
-
- foreach ($recipients as $recipient) {
- if (PEAR::isError($res = $smtp->rcptTo($recipient))) {
- return PEAR::raiseError('unable to add recipient [' .
- $recipient . ']: ' . $res->getMessage());
- }
- }
-
- if (PEAR::isError($smtp->data($text_headers . "\r\n" . $body))) {
- return PEAR::raiseError('unable to send data');
- }
-
- $smtp->disconnect();
- return true;
- }
-
-}
diff --git a/inc/Mail/xmail.dtd b/inc/Mail/xmail.dtd
deleted file mode 100644
index 9f42ca8b331..00000000000
--- a/inc/Mail/xmail.dtd
+++ /dev/null
@@ -1,19 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-
-<!ENTITY lt "&#38;#60;">
-<!ENTITY gt "&#62;">
-<!ENTITY amp "&#38;#38;">
-<!ENTITY apos "&#39;">
-<!ENTITY quot "&#34;">
-<!ENTITY crlf "&#13;&#10;">
-
-<!ELEMENT email (header+, (body | mimepart+))>
-<!ELEMENT mimepart (header+, (body | mimepart+))>
-<!ELEMENT body (#PCDATA)>
-<!ELEMENT header ((headername|headervalue|parameter)*)>
-<!ELEMENT headername (#PCDATA)>
-<!ELEMENT headervalue (#PCDATA)>
-<!ELEMENT parameter ((paramname|paramvalue)+)>
-<!ELEMENT paramvalue (#PCDATA)>
-<!ELEMENT paramname (#PCDATA)>
-
diff --git a/inc/Mail/xmail.xsl b/inc/Mail/xmail.xsl
deleted file mode 100644
index 0b948913f84..00000000000
--- a/inc/Mail/xmail.xsl
+++ /dev/null
@@ -1,70 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
-<xsl:output method="text" omit-xml-declaration="yes" indent="no"/>
-<xsl:preserve-space elements="headervalue paramvalue body"/>
-
- <xsl:template name="mimepart">
-
- <xsl:variable name="boundary">
- <xsl:for-each select="./header">
- <xsl:if test="string(./headername) = 'Content-Type'">
- <xsl:for-each select="./parameter">
- <xsl:if test="string(./paramname) = 'boundary'">
- <xsl:value-of select="paramvalue"/>
- </xsl:if>
- </xsl:for-each>
- </xsl:if>
- </xsl:for-each>
- </xsl:variable>
-
- <xsl:for-each select="header">
-
- <xsl:value-of select="headername"/>
- <xsl:text>: </xsl:text>
- <xsl:value-of select="headervalue"/>
-
- <xsl:if test="count(./parameter) = 0">
- <xsl:text>&#13;&#10;</xsl:text>
- </xsl:if>
-
- <xsl:for-each select="parameter">
- <xsl:text>;&#13;&#10;&#09;</xsl:text>
- <xsl:value-of select="paramname"/>
- <xsl:text>="</xsl:text>
- <xsl:value-of select="paramvalue"/>
- <xsl:text>"</xsl:text>
- </xsl:for-each>
-
- <xsl:if test="count(./parameter) > 0">
- <xsl:text>&#13;&#10;</xsl:text>
- </xsl:if>
-
- </xsl:for-each>
-
- <xsl:text>&#13;&#10;</xsl:text>
-
- <!-- Which to do, print a body or process subparts? -->
- <xsl:choose>
- <xsl:when test="count(./mimepart) = 0">
- <xsl:value-of select="body"/>
- <xsl:text>&#13;&#10;</xsl:text>
- </xsl:when>
-
- <xsl:otherwise>
- <xsl:for-each select="mimepart">
- <xsl:text>--</xsl:text><xsl:value-of select="$boundary"/><xsl:text>&#13;&#10;</xsl:text>
- <xsl:call-template name="mimepart"/>
- </xsl:for-each>
-
- <xsl:text>--</xsl:text><xsl:value-of select="$boundary"/><xsl:text>--&#13;&#10;</xsl:text>
-
- </xsl:otherwise>
- </xsl:choose>
- </xsl:template>
-
-<!-- This is where the stylesheet really starts, matching the top level email element -->
- <xsl:template match="email">
- <xsl:call-template name="mimepart"/>
- </xsl:template>
-
-</xsl:stylesheet> \ No newline at end of file
diff --git a/inc/Net/SMTP.php b/inc/Net/SMTP.php
deleted file mode 100644
index 71dcb5e9bef..00000000000
--- a/inc/Net/SMTP.php
+++ /dev/null
@@ -1,970 +0,0 @@
-<?php
-/* vim: set expandtab softtabstop=4 tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.02 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Chuck Hagenbuch <chuck@horde.org> |
-// | Jon Parise <jon@php.net> |
-// | Damian Alejandro Fernandez Sosa <damlists@cnba.uba.ar> |
-// +----------------------------------------------------------------------+
-
-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 <chuck@horde.org>
- * @author Jon Parise <jon@php.net>
- * @author Damian Alejandro Fernandez Sosa <damlists@cnba.uba.ar>
- *
- * @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');
-
- /**
- * 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.
- *
- * @param string The server to connect to.
- * @param int The port to connect to.
- * @param string The value to give when sending EHLO or HELO.
- *
- * @access public
- * @since 1.0
- */
- function Net_SMTP($host = null, $port = null, $localhost = null)
- {
- if (isset($host)) $this->host = $host;
- if (isset($port)) $this->port = $port;
- if (isset($localhost)) $this->localhost = $localhost;
-
- $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 new PEAR_Error('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.
- *
- * @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)) {
- return $this->_send($command . ' ' . $args . "\r\n");
- }
-
- 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.
- *
- * @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)
- {
- $this->_code = -1;
- $this->_arguments = array();
-
- 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 new PEAR_Error("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;
- }
- }
-
- /* Compare the server's response code with the valid code. */
- if (is_int($valid) && ($this->_code === $valid)) {
- return true;
- }
-
- /* If we were given an array of valid response codes, check each one. */
- if (is_array($valid)) {
- foreach ($valid as $valid_code) {
- if ($this->_code === $valid_code) {
- return true;
- }
- }
- }
-
- return new PEAR_Error("Invalid response code received from server");
- }
-
- /**
- * 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 new PEAR_Error('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 new PEAR_Error('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 new PEAR_Error('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;
- }
-
- 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 new PEAR_Error('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'])) {
- return new PEAR_Error('SMTP server does no 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 new PEAR_Error("$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 = new PEAR_Error("$method is not a supported authentication method");
- break;
- }
-
- /* If an error was encountered, return the PEAR_Error object. */
- if (PEAR::isError($result)) {
- return $result;
- }
-
- /* RFC-2554 requires us to re-negotiate ESMTP after an AUTH. */
- if (PEAR::isError($error = $this->_negotiate())) {
- return $error;
- }
-
- 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;
- }
-
- /**
- * Send the MAIL FROM: command.
- *
- * @param string The sender (reverse path) to set.
- *
- * @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)
- {
- if (PEAR::isError($error = $this->_put('MAIL', "FROM:<$sender>"))) {
- return $error;
- }
- if (PEAR::isError($error = $this->_parseResponse(250))) {
- return $error;
- }
-
- return true;
- }
-
- /**
- * Send the RCPT TO: command.
- *
- * @param string The recipient (forward path) to add.
- *
- * @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)
- {
- if (PEAR::isError($error = $this->_put('RCPT', "TO:<$recipient>"))) {
- return $error;
- }
- if (PEAR::isError($error = $this->_parseResponse(array(250, 251)))) {
- 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 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("/([^\r]{1})\n/", "\\1\r\n", $data);
- $data = preg_replace("/\n\n/", "\n\r\n", $data);
-
- /*
- * Because a single leading period (.) signifies an end to the data,
- * legitimate leading periods need to be "doubled" (e.g. '..').
- */
- $data = preg_replace("/\n\./", "\n..", $data);
- }
-
- /**
- * Send the DATA command.
- *
- * @param string The message body 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
- */
- function data($data)
- {
- /*
- * RFC 1870, section 3, subsection 3 states "a value of zero indicates
- * that no fixed maximum message size is in force". Furthermore, it
- * says that if "the parameter is omitted no information is conveyed
- * about the server's fixed maximum message size".
- */
- if (isset($this->_esmtp['SIZE']) && ($this->_esmtp['SIZE'] > 0)) {
- if (strlen($data) >= $this->_esmtp['SIZE']) {
- $this->disconnect();
- return new PEAR_Error('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($this->_send($data . "\r\n.\r\n"))) {
- return new PEAR_Error('write to socket failed');
- }
- if (PEAR::isError($error = $this->_parseResponse(250))) {
- 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))) {
- 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))) {
- 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))) {
- 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))) {
- 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(250))) {
- 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/inc/Net/Socket.php b/inc/Net/Socket.php
deleted file mode 100644
index 7c4ff1d4e21..00000000000
--- a/inc/Net/Socket.php
+++ /dev/null
@@ -1,528 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 2.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/2_02.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stig Bakken <ssb@php.net> |
-// | Chuck Hagenbuch <chuck@horde.org> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Socket.php,v 1.24 2005/02/03 20:40:16 chagenbu Exp $
-
-require_once 'PEAR.php';
-
-define('NET_SOCKET_READ', 1);
-define('NET_SOCKET_WRITE', 2);
-define('NET_SOCKET_ERROR', 3);
-
-/**
- * Generalized Socket class.
- *
- * @version 1.1
- * @author Stig Bakken <ssb@php.net>
- * @author Chuck Hagenbuch <chuck@horde.org>
- */
-class Net_Socket extends PEAR {
-
- /**
- * Socket file pointer.
- * @var resource $fp
- */
- var $fp = null;
-
- /**
- * Whether the socket is blocking. Defaults to true.
- * @var boolean $blocking
- */
- var $blocking = true;
-
- /**
- * Whether the socket is persistent. Defaults to false.
- * @var boolean $persistent
- */
- var $persistent = false;
-
- /**
- * The IP address to connect to.
- * @var string $addr
- */
- var $addr = '';
-
- /**
- * The port number to connect to.
- * @var integer $port
- */
- var $port = 0;
-
- /**
- * Number of seconds to wait on socket connections before assuming
- * there's no more data. Defaults to no timeout.
- * @var integer $timeout
- */
- var $timeout = false;
-
- /**
- * Number of bytes to read at a time in readLine() and
- * readAll(). Defaults to 2048.
- * @var integer $lineLength
- */
- var $lineLength = 2048;
-
- /**
- * Connect to the specified port. If called when the socket is
- * already connected, it disconnects and connects again.
- *
- * @param string $addr IP address or host name.
- * @param integer $port TCP port number.
- * @param boolean $persistent (optional) Whether the connection is
- * persistent (kept open between requests
- * by the web server).
- * @param integer $timeout (optional) How long to wait for data.
- * @param array $options See options for stream_context_create.
- *
- * @access public
- *
- * @return boolean | PEAR_Error True on success or a PEAR_Error on failure.
- */
- function connect($addr, $port = 0, $persistent = null, $timeout = null, $options = null)
- {
- if (is_resource($this->fp)) {
- @fclose($this->fp);
- $this->fp = null;
- }
-
- if (!$addr) {
- return $this->raiseError('$addr cannot be empty');
- } elseif (strspn($addr, '.0123456789') == strlen($addr) ||
- strstr($addr, '/') !== false) {
- $this->addr = $addr;
- } else {
- $this->addr = @gethostbyname($addr);
- }
-
- $this->port = $port % 65536;
-
- if ($persistent !== null) {
- $this->persistent = $persistent;
- }
-
- if ($timeout !== null) {
- $this->timeout = $timeout;
- }
-
- $openfunc = $this->persistent ? 'pfsockopen' : 'fsockopen';
- $errno = 0;
- $errstr = '';
- if ($options && function_exists('stream_context_create')) {
- if ($this->timeout) {
- $timeout = $this->timeout;
- } else {
- $timeout = 0;
- }
- $context = stream_context_create($options);
- $fp = @$openfunc($this->addr, $this->port, $errno, $errstr, $timeout, $context);
- } else {
- if ($this->timeout) {
- $fp = @$openfunc($this->addr, $this->port, $errno, $errstr, $this->timeout);
- } else {
- $fp = @$openfunc($this->addr, $this->port, $errno, $errstr);
- }
- }
-
- if (!$fp) {
- return $this->raiseError($errstr, $errno);
- }
-
- $this->fp = $fp;
-
- return $this->setBlocking($this->blocking);
- }
-
- /**
- * Disconnects from the peer, closes the socket.
- *
- * @access public
- * @return mixed true on success or an error object otherwise
- */
- function disconnect()
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- @fclose($this->fp);
- $this->fp = null;
- return true;
- }
-
- /**
- * Find out if the socket is in blocking mode.
- *
- * @access public
- * @return boolean The current blocking mode.
- */
- function isBlocking()
- {
- return $this->blocking;
- }
-
- /**
- * Sets whether the socket connection should be blocking or
- * not. A read call to a non-blocking socket will return immediately
- * if there is no data available, whereas it will block until there
- * is data for blocking sockets.
- *
- * @param boolean $mode True for blocking sockets, false for nonblocking.
- * @access public
- * @return mixed true on success or an error object otherwise
- */
- function setBlocking($mode)
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- $this->blocking = $mode;
- socket_set_blocking($this->fp, $this->blocking);
- return true;
- }
-
- /**
- * Sets the timeout value on socket descriptor,
- * expressed in the sum of seconds and microseconds
- *
- * @param integer $seconds Seconds.
- * @param integer $microseconds Microseconds.
- * @access public
- * @return mixed true on success or an error object otherwise
- */
- function setTimeout($seconds, $microseconds)
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- return socket_set_timeout($this->fp, $seconds, $microseconds);
- }
-
- /**
- * Returns information about an existing socket resource.
- * Currently returns four entries in the result array:
- *
- * <p>
- * timed_out (bool) - The socket timed out waiting for data<br>
- * blocked (bool) - The socket was blocked<br>
- * eof (bool) - Indicates EOF event<br>
- * unread_bytes (int) - Number of bytes left in the socket buffer<br>
- * </p>
- *
- * @access public
- * @return mixed Array containing information about existing socket resource or an error object otherwise
- */
- function getStatus()
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- return socket_get_status($this->fp);
- }
-
- /**
- * Get a specified line of data
- *
- * @access public
- * @return $size bytes of data from the socket, or a PEAR_Error if
- * not connected.
- */
- function gets($size)
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- return @fgets($this->fp, $size);
- }
-
- /**
- * Read a specified amount of data. This is guaranteed to return,
- * and has the added benefit of getting everything in one fread()
- * chunk; if you know the size of the data you're getting
- * beforehand, this is definitely the way to go.
- *
- * @param integer $size The number of bytes to read from the socket.
- * @access public
- * @return $size bytes of data from the socket, or a PEAR_Error if
- * not connected.
- */
- function read($size)
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- return @fread($this->fp, $size);
- }
-
- /**
- * Write a specified amount of data.
- *
- * @param string $data Data to write.
- * @param integer $blocksize Amount of data to write at once.
- * NULL means all at once.
- *
- * @access public
- * @return mixed true on success or an error object otherwise
- */
- function write($data, $blocksize = null)
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- if (is_null($blocksize) && !OS_WINDOWS) {
- return fwrite($this->fp, $data);
- } else {
- if (is_null($blocksize)) {
- $blocksize = 1024;
- }
-
- $pos = 0;
- $size = strlen($data);
- while ($pos < $size) {
- $written = @fwrite($this->fp, substr($data, $pos, $blocksize));
- if ($written === false) {
- return false;
- }
- $pos += $written;
- }
-
- return $pos;
- }
- }
-
- /**
- * Write a line of data to the socket, followed by a trailing "\r\n".
- *
- * @access public
- * @return mixed fputs result, or an error
- */
- function writeLine($data)
- {
- if (!is_resource($this->fp)) {
- return $this->raiseError('not connected');
- }
-
- return fwrite($this->fp, $data . "\r\n");
- }
-
- /**
- * Tests for end-of-file on a socket descriptor.
- *
- * @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;
- }
-
-}
diff --git a/inc/OS/Guess.php b/inc/OS/Guess.php
deleted file mode 100644
index a85bf360ebc..00000000000
--- a/inc/OS/Guess.php
+++ /dev/null
@@ -1,287 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stig Bakken <ssb@php.net> |
-// | |
-// +----------------------------------------------------------------------+
-//
-// $Id: Guess.php,v 1.13.4.1 2004/10/19 04:15:56 cellog 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
-//
-// 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.
- */
-
-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',
- );
- static $cpumap = array(
- 'i586' => 'i386',
- 'i686' => 'i386',
- 'ppc' => 'powerpc',
- );
- if ($uname === null) {
- $uname = php_uname();
- }
- $parts = split('[[: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;
- 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 = 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 <features.h> header file to
- // get major and minor version number:
- include_once "System.php";
- $tmpfile = System::mktemp("glibctest");
- $fp = fopen($tmpfile, "w");
- fwrite($fp, "#include <features.h>\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} == '#' || trim($line) == '') {
- continue;
- }
- if (list($major, $minor) = explode(' ', trim($line))) {
- break;
- }
- }
- pclose($cpp);
- unlink($tmpfile);
- if (!($major && $minor) && is_link('/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 eregi($reg, $value);
- }
- return ($fragment == '*' || !strcasecmp($fragment, $value));
- }
-
-}
-/*
- * Local Variables:
- * indent-tabs-mode: nil
- * c-basic-offset: 4
- * End:
- */
-?>
diff --git a/inc/PEAR.php b/inc/PEAR.php
deleted file mode 100644
index d5c9635a501..00000000000
--- a/inc/PEAR.php
+++ /dev/null
@@ -1,1055 +0,0 @@
-<?php
-//
-// +--------------------------------------------------------------------+
-// | PEAR, the PHP Extension and Application Repository |
-// +--------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +--------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +--------------------------------------------------------------------+
-// | Authors: Sterling Hughes <sterling@php.net> |
-// | Stig Bakken <ssb@php.net> |
-// | Tomas V.V.Cox <cox@idecnet.com> |
-// +--------------------------------------------------------------------+
-//
-// $Id: PEAR.php,v 1.82.2.6 2005/01/01 05:24:51 cellog Exp $
-//
-
-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 <ssb@php.net>
- * @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;
- if (!isset($GLOBALS['_PEAR_SHUTDOWN_REGISTERED'])) {
- register_shutdown_function("_PEAR_call_destructors");
- $GLOBALS['_PEAR_SHUTDOWN_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/inc/PEAR/Autoloader.php b/inc/PEAR/Autoloader.php
deleted file mode 100644
index de0278d6191..00000000000
--- a/inc/PEAR/Autoloader.php
+++ /dev/null
@@ -1,208 +0,0 @@
-<?php
-// /* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Stig Bakken <ssb@php.net> |
-// | |
-// +----------------------------------------------------------------------+
-//
-// $Id: Autoloader.php,v 1.11 2004/02/27 02:21:29 cellog 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 <ssb@php.net>
- */
-class PEAR_Autoloader extends PEAR
-{
- // {{{ properties
-
- /**
- * 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();
-
- // }}}
- // {{{ addAutoload()
-
- /**
- * 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)) {
- array_walk($method, create_function('$a,&$b', '$b = strtolower($b);'));
- $this->_autoload_map = array_merge($this->_autoload_map, $method);
- } else {
- $this->_autoload_map[strtolower($method)] = $classname;
- }
- }
-
- // }}}
- // {{{ removeAutoload()
-
- /**
- * 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)
- {
- $method = strtolower($method);
- $ok = isset($this->_autoload_map[$method]);
- unset($this->_autoload_map[$method]);
- return $ok;
- }
-
- // }}}
- // {{{ addAggregateObject()
-
- /**
- * 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;
- }
- }
- }
-
- // }}}
- // {{{ removeAggregateObject()
-
- /**
- * 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_a($obj, $classname)) {
- unset($this->_method_map[$method]);
- $ok = true;
- }
- }
- return $ok;
- }
-
- // }}}
- // {{{ __call()
-
- /**
- * 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)
- {
- $method = strtolower($method);
- 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/inc/PEAR/Builder.php b/inc/PEAR/Builder.php
deleted file mode 100644
index 4f6cc135d1e..00000000000
--- a/inc/PEAR/Builder.php
+++ /dev/null
@@ -1,426 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stig Sæther Bakken <ssb@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Builder.php,v 1.16.2.3 2005/02/17 17:55:01 cellog Exp $
-
-require_once 'PEAR/Common.php';
-
-/**
- * Class to handle building (compiling) extensions.
- *
- * @author Stig Sæther Bakken <ssb@php.net>
- */
-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.");
- }
-
- // 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;
- }
- // }}}
-
- // {{{ _harventInstDir
- /**
- * @param string
- * @param string
- * @param array
- * @access private
- */
- function _harvestInstDir($dest_prefix, $dirname, &$built_files)
- {
- $d = opendir($dirname);
- if (!$d)
- return false;
-
- $ret = true;
- while (($ent = readdir($d)) !== false) {
- if ($ent{0} == '.')
- continue;
-
- $full = $dirname . DIRECTORY_SEPARATOR . $ent;
- if (is_dir($full)) {
- if (!$this->_harvestInstDir(
- $dest_prefix . DIRECTORY_SEPARATOR . $ent,
- $full, $built_files)) {
- $ret = false;
- break;
- }
- } else {
- $dest = $dest_prefix . DIRECTORY_SEPARATOR . $ent;
- $built_files[] = array(
- 'file' => $full,
- 'dest' => $dest,
- 'php_api' => $this->php_api_version,
- 'zend_mod_api' => $this->zend_module_api_no,
- 'zend_ext_api' => $this->zend_extension_api_no,
- );
- }
- }
- closedir($d);
- return $ret;
- }
-
- // }}}
-
- // {{{ 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;
- putenv('PATH=' . $this->config->get('bin_dir') . ':' . getenv('PATH'));
- $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]=".trim($r);
- }
- }
- }
- // }}} end of interactive part
-
- // FIXME make configurable
- if(!$user=getenv('USER')){
- $user='defaultuser';
- }
- $build_basedir = "/var/tmp/pear-build-$user";
- $build_dir = "$build_basedir/$info[package]-$info[version]";
- $inst_dir = "$build_basedir/install-$info[package]-$info[version]";
- $this->log(1, "building in $build_dir");
- if (is_dir($build_dir)) {
- System::rm('-rf', $build_dir);
- }
- if (!System::mkDir(array('-p', $build_dir))) {
- return $this->raiseError("could not create build dir: $build_dir");
- }
- $this->addTempFile($build_dir);
- if (!System::mkDir(array('-p', $inst_dir))) {
- return $this->raiseError("could not create temporary install dir: $inst_dir");
- }
- $this->addTempFile($inst_dir);
-
- if (getenv('MAKE')) {
- $make_command = getenv('MAKE');
- } else {
- $make_command = 'make';
- }
- $to_run = array(
- $configure_command,
- $make_command,
- "$make_command INSTALL_ROOT=\"$inst_dir\" install",
- "find \"$inst_dir\" -ls"
- );
- if (!@chdir($build_dir)) {
- return $this->raiseError("could not chdir to $build_dir");
- }
- putenv('PHP_PEAR_VERSION=@PEAR-VER@');
- 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();
- $prefix = exec("php-config --prefix");
- $this->_harvestInstDir($prefix, $inst_dir . DIRECTORY_SEPARATOR . $prefix, $built_files);
- 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(1, 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)
- {
- $this->log(1, "running: $command");
- $pp = @popen("$command 2>&1", "r");
- if (!$pp) {
- return $this->raiseError("failed to run `$command'");
- }
- if ($callback && $callback[0]->debug == 1) {
- $olddbg = $callback[0]->debug;
- $callback[0]->debug = 2;
- }
-
- while ($line = fgets($pp, 1024)) {
- if ($callback) {
- call_user_func($callback, 'cmdoutput', $line);
- } else {
- $this->log(2, rtrim($line));
- }
- }
- if ($callback && isset($olddbg)) {
- $callback[0]->debug = $olddbg;
- }
- $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/inc/PEAR/Command.php b/inc/PEAR/Command.php
deleted file mode 100644
index 2ea68743d20..00000000000
--- a/inc/PEAR/Command.php
+++ /dev/null
@@ -1,398 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Stig Bakken <ssb@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Command.php,v 1.24 2004/05/16 15:43:30 pajoye 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
-{
- // {{{ factory()
-
- /**
- * 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
- * @static
- */
- 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];
- }
- if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) {
- return PEAR::raiseError("unknown command `$command'");
- }
- $class = $GLOBALS['_PEAR_Command_commandlist'][$command];
- if (!class_exists($class)) {
- return PEAR::raiseError("unknown command `$command'");
- }
- $ui =& PEAR_Command::getFrontendObject();
- $obj = &new $class($ui, $config);
- return $obj;
- }
-
- // }}}
- // {{{ & getFrontendObject()
-
- /**
- * Get instance of frontend object.
- *
- * @return object
- * @static
- */
- function &getFrontendObject()
- {
- if (empty($GLOBALS['_PEAR_Command_uiobject'])) {
- $GLOBALS['_PEAR_Command_uiobject'] = &new $GLOBALS['_PEAR_Command_uiclass'];
- }
- return $GLOBALS['_PEAR_Command_uiobject'];
- }
-
- // }}}
- // {{{ & setFrontendClass()
-
- /**
- * Load current frontend class.
- *
- * @param string $uiclass Name of class implementing the frontend
- *
- * @return object the frontend object, or a PEAR error
- * @static
- */
- function &setFrontendClass($uiclass)
- {
- if (is_object($GLOBALS['_PEAR_Command_uiobject']) &&
- is_a($GLOBALS['_PEAR_Command_uiobject'], $uiclass)) {
- return $GLOBALS['_PEAR_Command_uiobject'];
- }
- if (!class_exists($uiclass)) {
- $file = str_replace('_', '/', $uiclass) . '.php';
- if (PEAR_Command::isIncludeable($file)) {
- include_once $file;
- }
- }
- if (class_exists($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 {
- $err = PEAR::raiseError("not a frontend class: $uiclass");
- return $err;
- }
- }
- $err = PEAR::raiseError("no such class: $uiclass");
- return $err;
- }
-
- // }}}
- // {{{ setFrontendType()
-
- // }}}
- // {{{ isIncludeable()
-
- /**
- * @param string $path relative or absolute include path
- * @return boolean
- * @static
- */
- function isIncludeable($path)
- {
- if (file_exists($path) && is_readable($path)) {
- return true;
- }
- $ipath = explode(PATH_SEPARATOR, ini_get('include_path'));
- foreach ($ipath as $include) {
- $test = realpath($include . DIRECTORY_SEPARATOR . $path);
- if (file_exists($test) && is_readable($test)) {
- return true;
- }
- }
- return false;
- }
-
- /**
- * Set current frontend.
- *
- * @param string $uitype Name of the frontend type (for example "CLI")
- *
- * @return object the frontend object, or a PEAR error
- * @static
- */
- function setFrontendType($uitype)
- {
- $uiclass = 'PEAR_Frontend_' . $uitype;
- return PEAR_Command::setFrontendClass($uiclass);
- }
-
- // }}}
- // {{{ registerCommands()
-
- /**
- * 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
- * @static
- */
- 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;
- }
- }
- @closedir($dp);
- return true;
- }
-
- // }}}
- // {{{ getCommands()
-
- /**
- * Get the list of currently supported commands, and what
- * classes implement them.
- *
- * @return array command => implementing class
- *
- * @access public
- * @static
- */
- function getCommands()
- {
- if (empty($GLOBALS['_PEAR_Command_commandlist'])) {
- PEAR_Command::registerCommands();
- }
- return $GLOBALS['_PEAR_Command_commandlist'];
- }
-
- // }}}
- // {{{ getShortcuts()
-
- /**
- * Get the list of command shortcuts.
- *
- * @return array shortcut => command
- *
- * @access public
- * @static
- */
- function getShortcuts()
- {
- if (empty($GLOBALS['_PEAR_Command_shortcuts'])) {
- PEAR_Command::registerCommands();
- }
- return $GLOBALS['_PEAR_Command_shortcuts'];
- }
-
- // }}}
- // {{{ getGetoptArgs()
-
- /**
- * 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
- * @static
- */
- function getGetoptArgs($command, &$short_args, &$long_args)
- {
- if (empty($GLOBALS['_PEAR_Command_commandlist'])) {
- PEAR_Command::registerCommands();
- }
- if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) {
- return null;
- }
- $class = $GLOBALS['_PEAR_Command_commandlist'][$command];
- $obj = &$GLOBALS['_PEAR_Command_objects'][$class];
- return $obj->getGetoptArgs($command, $short_args, $long_args);
- }
-
- // }}}
- // {{{ getDescription()
-
- /**
- * Get description for a command.
- *
- * @param string $command Name of the command
- *
- * @return string command description
- *
- * @access public
- * @static
- */
- function getDescription($command)
- {
- if (!isset($GLOBALS['_PEAR_Command_commanddesc'][$command])) {
- return null;
- }
- return $GLOBALS['_PEAR_Command_commanddesc'][$command];
- }
-
- // }}}
- // {{{ getHelp()
-
- /**
- * Get help for command.
- *
- * @param string $command Name of the command to return help for
- *
- * @access public
- * @static
- */
- 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/inc/PEAR/Command/Auth.php b/inc/PEAR/Command/Auth.php
deleted file mode 100644
index 0b9d3d3965d..00000000000
--- a/inc/PEAR/Command/Auth.php
+++ /dev/null
@@ -1,155 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Stig Bakken <ssb@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Auth.php,v 1.15 2004/01/08 17:33:13 sniper 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/inc/PEAR/Command/Build.php b/inc/PEAR/Command/Build.php
deleted file mode 100644
index 2ecbbc92f5f..00000000000
--- a/inc/PEAR/Command/Build.php
+++ /dev/null
@@ -1,89 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Stig Bakken <ssb@php.net> |
-// | Tomas V.V.Cox <cox@idecnet.com> |
-// | |
-// +----------------------------------------------------------------------+
-//
-// $Id: Build.php,v 1.9 2004/01/08 17:33:13 sniper 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->debug = $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->debug > 1) ||
- ($what == 'output' && $this->debug > 0)) {
- $this->ui->outputData(rtrim($data), 'build');
- }
- }
-
- // }}}
-}
diff --git a/inc/PEAR/Command/Common.php b/inc/PEAR/Command/Common.php
deleted file mode 100644
index c6ace694caf..00000000000
--- a/inc/PEAR/Command/Common.php
+++ /dev/null
@@ -1,249 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Stig Sæther Bakken <ssb@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Common.php,v 1.24 2004/01/08 17:33:13 sniper 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/inc/PEAR/Command/Config.php b/inc/PEAR/Command/Config.php
deleted file mode 100644
index 474a2345170..00000000000
--- a/inc/PEAR/Command/Config.php
+++ /dev/null
@@ -1,225 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Stig Bakken <ssb@php.net> |
-// | Tomas V.V.Cox <cox@idecnet.com> |
-// | |
-// +----------------------------------------------------------------------+
-//
-// $Id: Config.php,v 1.27 2004/06/15 16:48:49 pajoye 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' => '<parameter> [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' => '<parameter> <value> [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($this->config->get($params[0]), $command);
- } else {
- $data = $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;
- }
-
- // }}}
-}
-
-?>
diff --git a/inc/PEAR/Command/Install.php b/inc/PEAR/Command/Install.php
deleted file mode 100644
index dce52f017e2..00000000000
--- a/inc/PEAR/Command/Install.php
+++ /dev/null
@@ -1,470 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Stig Sæther Bakken <ssb@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Install.php,v 1.53.2.1 2004/10/19 04:08:42 cellog Exp $
-
-require_once "PEAR/Command/Common.php";
-require_once "PEAR/Installer.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',
- ),
- 'alldeps' => array(
- 'shortopt' => 'a',
- 'doc' => 'install all required and optional dependencies',
- ),
- 'onlyreqdeps' => array(
- 'shortopt' => 'o',
- 'doc' => 'install all required dependencies',
- ),
- ),
- 'doc' => '<package> ...
-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',
- ),
- 'alldeps' => array(
- 'shortopt' => 'a',
- 'doc' => 'install all required and optional dependencies',
- ),
- 'onlyreqdeps' => array(
- 'shortopt' => 'o',
- 'doc' => 'install all required dependencies',
- ),
- ),
- 'doc' => '<package> ...
-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' => '<package> ...
-Uninstalls one or more PEAR packages. More than one package may be
-specified at once.
-'),
- 'bundle' => array(
- 'summary' => 'Unpacks a Pecl Package',
- 'function' => 'doBundle',
- 'shortcut' => 'bun',
- 'options' => array(
- 'destination' => array(
- 'shortopt' => 'd',
- 'arg' => 'DIR',
- 'doc' => 'Optional destination directory for unpacking (defaults to current path or "ext" if exists)',
- ),
- 'force' => array(
- 'shortopt' => 'f',
- 'doc' => 'Force the unpacking even if there were errors in the package',
- ),
- ),
- 'doc' => '<package>
-Unpacks a Pecl Package into the selected location. It will download the
-package if needed.
-'),
- );
-
- // }}}
- // {{{ 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)
- {
- require_once 'PEAR/Downloader.php';
- if (empty($this->installer)) {
- $this->installer = &new PEAR_Installer($this->ui);
- }
- if ($command == 'upgrade') {
- $options['upgrade'] = 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) {
- $package = strtolower($package);
- 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(array('data' => "Will upgrade $package"), $command);
- }
- }
- $this->downloader = &new PEAR_Downloader($this->ui, $options, $this->config);
- $errors = array();
- $downloaded = array();
- $this->downloader->download($params);
- $errors = $this->downloader->getErrorMsgs();
- if (count($errors)) {
- $err['data'] = array($errors);
- $err['headline'] = 'Install Errors';
- $this->ui->outputData($err);
- return $this->raiseError("$command failed");
- }
- $downloaded = $this->downloader->getDownloadedPackages();
- $this->installer->sortPkgDeps($downloaded);
- foreach ($downloaded as $pkg) {
- PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
- $info = $this->installer->install($pkg['file'], $options, $this->config);
- PEAR::popErrorHandling();
- if (PEAR::isError($info)) {
- $this->ui->outputData('ERROR: ' .$info->getMessage());
- continue;
- }
- 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");
- }
- include_once 'PEAR/Registry.php';
- $reg = new PEAR_Registry($this->config->get('php_dir'));
- $newparams = array();
- $badparams = array();
- foreach ($params as $pkg) {
- $info = $reg->packageInfo($pkg);
- if ($info === null) {
- $badparams[] = $pkg;
- } else {
- $newparams[] = $info;
- }
- }
- $this->installer->sortPkgDeps($newparams, true);
- $params = array();
- foreach($newparams as $info) {
- $params[] = $info['info']['package'];
- }
- $params = array_merge($params, $badparams);
- 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;
- }
-
- // }}}
-
-
- // }}}
- // {{{ doBundle()
- /*
- (cox) It just downloads and untars the package, does not do
- any check that the PEAR_Installer::_installFile() does.
- */
-
- function doBundle($command, $options, $params)
- {
- if (empty($this->installer)) {
- $this->installer = &new PEAR_Downloader($this->ui);
- }
- $installer = &$this->installer;
- if (sizeof($params) < 1) {
- return $this->raiseError("Please supply the package you want to bundle");
- }
- $pkgfile = $params[0];
- $need_download = false;
- if (preg_match('#^(http|ftp)://#', $pkgfile)) {
- $need_download = true;
- } elseif (!@is_file($pkgfile)) {
- if ($installer->validPackageName($pkgfile)) {
- $pkgfile = $installer->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 = $installer->config->get('download_dir');
- if (empty($downloaddir)) {
- if (PEAR::isError($downloaddir = System::mktemp('-d'))) {
- return $downloaddir;
- }
- $installer->log(2, '+ tmp dir created at ' . $downloaddir);
- }
- $callback = $this->ui ? array(&$installer, '_downloadCallback') : null;
- $file = $installer->downloadHttp($pkgfile, $this->ui, $downloaddir, $callback);
- if (PEAR::isError($file)) {
- return $this->raiseError($file);
- }
- $pkgfile = $file;
- }
-
- // Parse xml file -----------------------------------------------
- $pkginfo = $installer->infoFromTgzFile($pkgfile);
- if (PEAR::isError($pkginfo)) {
- return $this->raiseError($pkginfo);
- }
- $installer->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:\n".
- implode("\n", $errors));
- } else {
- $this->log(0, "warning : the following errors were found:\n".
- implode("\n", $errors));
- }
- }
- $pkgname = $pkginfo['package'];
-
- // Unpacking -------------------------------------------------
-
- if (isset($options['destination'])) {
- if (!is_dir($options['destination'])) {
- System::mkdir('-p ' . $options['destination']);
- }
- $dest = realpath($options['destination']);
- } else {
- $pwd = getcwd();
- if (is_dir($pwd . DIRECTORY_SEPARATOR . 'ext')) {
- $dest = $pwd . DIRECTORY_SEPARATOR . 'ext';
- } else {
- $dest = $pwd;
- }
- }
- $dest .= DIRECTORY_SEPARATOR . $pkgname;
- $orig = $pkgname . '-' . $pkginfo['version'];
-
- $tar = new Archive_Tar($pkgfile);
- if (!@$tar->extractModify($dest, $orig)) {
- return $this->raiseError("unable to unpack $pkgfile");
- }
- $this->ui->outputData("Package ready at '$dest'");
- // }}}
- }
-
- // }}}
-
-}
-?>
diff --git a/inc/PEAR/Command/Mirror.php b/inc/PEAR/Command/Mirror.php
deleted file mode 100644
index bf56c3db640..00000000000
--- a/inc/PEAR/Command/Mirror.php
+++ /dev/null
@@ -1,101 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Alexander Merz <alexmerz@php.net> |
-// | |
-// +----------------------------------------------------------------------+
-//
-// $Id: Mirror.php,v 1.5 2004/03/18 12:23:57 mj 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 available package from master_server',
- 'function' => 'doDownloadAll',
- 'shortcut' => 'da',
- 'options' => array(),
- 'doc' => '
- Requests a list of available packages from the package server
- (master_server) and downloads them to current working directory'
- ),
- );
-
- // }}}
-
- // {{{ 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/inc/PEAR/Command/Package.php b/inc/PEAR/Command/Package.php
deleted file mode 100644
index aca87111118..00000000000
--- a/inc/PEAR/Command/Package.php
+++ /dev/null
@@ -1,819 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stig Bakken <ssb@php.net> |
-// | Martin Jansen <mj@php.net> |
-// | Greg Beaver <cellog@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Package.php,v 1.61.2.7 2005/02/17 17:47:55 cellog 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' => '<package.xml>
-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' => '<package.xml>
-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.
-',
- ),
- 'run-tests' => array(
- 'summary' => 'Run Regression Tests',
- 'function' => 'doRunTests',
- 'shortcut' => 'rt',
- 'options' => array(
- 'recur' => array(
- 'shortopt' => 'r',
- 'doc' => 'Run tests in child directories, recursively. 4 dirs deep maximum',
- ),
- 'ini' => array(
- 'shortopt' => 'i',
- 'doc' => 'actual string of settings to pass to php in format " -d setting=blah"',
- 'arg' => 'SETTINGS'
- ),
- 'realtimelog' => array(
- 'shortopt' => 'l',
- 'doc' => 'Log test runs/results as they are run',
- ),
- ),
- 'doc' => '[testfile|dir ...]
-Run regression tests with PHP\'s regression testing script (run-tests.php).',
- ),
- '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' => '<package-file>
-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' => '<package-file>
-
-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';
- if (sizeof($params) < 1) {
- $params[0] = "package.xml";
- }
- $pkginfofile = isset($params[0]) ? $params[0] : 'package.xml';
- $packager =& new PEAR_Packager();
- $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;
- }
- 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 == "<?xml") {
- $info = $obj->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 (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;
- }
-
- // }}}
- // {{{ doRunTests()
-
- function doRunTests($command, $options, $params)
- {
- include_once 'PEAR/RunTest.php';
- $log = new PEAR_Common;
- $log->ui = &$this->ui; // slightly hacky, but it will work
- $run = new PEAR_RunTest($log);
- $tests = array();
- if (isset($options['recur'])) {
- $depth = 4;
- } else {
- $depth = 1;
- }
- if (!count($params)) {
- $params[] = '.';
- }
- foreach ($params as $p) {
- if (is_dir($p)) {
- $dir = System::find(array($p, '-type', 'f',
- '-maxdepth', $depth,
- '-name', '*.phpt'));
- $tests = array_merge($tests, $dir);
- } else {
- if (!@file_exists($p)) {
- if (!preg_match('/\.phpt$/', $p)) {
- $p .= '.phpt';
- }
- $dir = System::find(array(dirname($p), '-type', 'f',
- '-maxdepth', $depth,
- '-name', $p));
- $tests = array_merge($tests, $dir);
- } else {
- $tests[] = $p;
- }
- }
- }
- $ini_settings = '';
- if (isset($options['ini'])) {
- $ini_settings .= $options['ini'];
- }
- if (isset($_ENV['TEST_PHP_INCLUDE_PATH'])) {
- $ini_settings .= " -d include_path={$_ENV['TEST_PHP_INCLUDE_PATH']}";
- }
- if ($ini_settings) {
- $this->ui->outputData('Using INI settings: "' . $ini_settings . '"');
- }
- $skipped = $passed = $failed = array();
- $this->ui->outputData('Running ' . count($tests) . ' tests', $command);
- $start = time();
- if (isset($options['realtimelog'])) {
- @unlink('run-tests.log');
- }
- foreach ($tests as $t) {
- if (isset($options['realtimelog'])) {
- $fp = @fopen('run-tests.log', 'a');
- if ($fp) {
- fwrite($fp, "Running test $t...");
- fclose($fp);
- }
- }
- $result = $run->run($t, $ini_settings);
- if (OS_WINDOWS) {
- for($i=0;$i<2000;$i++) {
- $i = $i; // delay - race conditions on windows
- }
- }
- if (isset($options['realtimelog'])) {
- $fp = @fopen('run-tests.log', 'a');
- if ($fp) {
- fwrite($fp, "$result\n");
- fclose($fp);
- }
- }
- if ($result == 'FAILED') {
- $failed[] = $t;
- }
- if ($result == 'PASSED') {
- $passed[] = $t;
- }
- if ($result == 'SKIPPED') {
- $skipped[] = $t;
- }
- }
- $total = date('i:s', time() - $start);
- if (count($failed)) {
- $output = "TOTAL TIME: $total\n";
- $output .= count($passed) . " PASSED TESTS\n";
- $output .= count($skipped) . " SKIPPED TESTS\n";
- $output .= count($failed) . " FAILED TESTS:\n";
- foreach ($failed as $failure) {
- $output .= $failure . "\n";
- }
- if (isset($options['realtimelog'])) {
- $fp = @fopen('run-tests.log', 'a');
- } else {
- $fp = @fopen('run-tests.log', 'w');
- }
- if ($fp) {
- fwrite($fp, $output, strlen($output));
- fclose($fp);
- $this->ui->outputData('wrote log to "' . realpath('run-tests.log') . '"', $command);
- }
- } elseif (@file_exists('run-tests.log') && !@is_dir('run-tests.log')) {
- @unlink('run-tests.log');
- }
- $this->ui->outputData('TOTAL TIME: ' . $total);
- $this->ui->outputData(count($passed) . ' PASSED TESTS', $command);
- $this->ui->outputData(count($skipped) . ' SKIPPED TESTS', $command);
- if (count($failed)) {
- $this->ui->outputData(count($failed) . ' FAILED TESTS:', $command);
- foreach ($failed as $failure) {
- $this->ui->outputData($failure, $command);
- }
- }
-
- return true;
- }
-
- // }}}
- // {{{ doPackageDependencies()
-
- function doPackageDependencies($command, $options, $params)
- {
- // $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()
-
- /*
-
- (cox)
-
- TODO:
-
- - Fill the rpm dependencies in the template file.
-
- IDEAS:
-
- - Instead of mapping the role to rpm vars, perhaps it's better
-
- to use directly the pear cmd to install the files by itself
-
- in %postrun so:
-
- pear -d php_dir=%{_libdir}/php/pear -d test_dir=.. <package>
-
- */
-
- 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]";
- $info['rpm_xml_dir'] = '/var/lib/pear';
- $this->config->set('verbose', $tmp);
- if (!$tar->extractList("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]");
- }
- 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 (!isset($attr['role'])) {
- continue;
- }
- $name = preg_replace('![/:\\\\]!', '/', $name);
- if ($attr['role'] == 'doc') {
- $info['doc_files'] .= " $name";
-
- // Map role to the rpm vars
- } else {
-
- $c_prefix = '%{_libdir}/php/pear';
-
- switch ($attr['role']) {
-
- case 'php':
-
- $prefix = $c_prefix; break;
-
- case 'ext':
-
- $prefix = '%{_libdir}/php'; break; // XXX good place?
-
- case 'src':
-
- $srcfiles++;
-
- $prefix = '%{_includedir}/php'; break; // XXX good place?
-
- case 'test':
-
- $prefix = "$c_prefix/tests/" . $info['package']; break;
-
- case 'data':
-
- $prefix = "$c_prefix/data/" . $info['package']; break;
-
- case 'script':
-
- $prefix = '%{_bindir}'; break;
-
- }
-
- $name = str_replace('\\', '/', $name);
- $info['files'] .= "$prefix/$name\n";
-
- }
- }
- if ($srcfiles > 0) {
- include_once "OS/Guess.php";
- $os = new OS_Guess;
- $arch = $os->getCpu();
- } else {
- $arch = 'noarch';
- }
- $cfg = 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, "wb");
- 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/inc/PEAR/Command/Registry.php b/inc/PEAR/Command/Registry.php
deleted file mode 100644
index 62cb4b00e28..00000000000
--- a/inc/PEAR/Command/Registry.php
+++ /dev/null
@@ -1,351 +0,0 @@
-<?php
-// /* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Stig Bakken <ssb@php.net> |
-// | |
-// +----------------------------------------------------------------------+
-//
-// $Id: Registry.php,v 1.36 2004/01/08 17:33:13 sniper 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' => '<package> [[relation] version]
-Tests if a package is installed in the system. Will exit(1) if it is not.
- <relation> The version comparison operator. One of:
- <, lt, <=, le, >, gt, >=, ge, ==, =, eq, !=, <>, ne
- <version> The version to compare with
-'),
- 'info' => array(
- 'summary' => 'Display information about a package',
- 'function' => 'doInfo',
- 'shortcut' => 'in',
- 'options' => array(),
- 'doc' => '<package>
-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->raiseError("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;
- }
- case 'provides' : {
- $debug = $this->config->get('verbose');
- if ($debug < 2) {
- $pstr = 'Classes: ';
- } else {
- $pstr = '';
- }
- $i = 0;
- foreach ($info[$key] as $p) {
- if ($debug < 2 && $p['type'] != "class") {
- continue;
- }
- // Only print classes when verbosity mode is < 2
- if ($debug < 2) {
- if ($i++ > 0) {
- $pstr .= ", ";
- }
- $pstr .= $p['name'];
- } else {
- if ($i++ > 0) {
- $pstr .= "\n";
- }
- $pstr .= ucfirst($p['type']) . " " . $p['name'];
- if (isset($p['explicit']) && $p['explicit'] == 1) {
- $pstr .= " (explicit)";
- }
- }
- }
- $info[$key] = $pstr;
- 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);
- }
- $data['raw'] = $info;
-
- $this->ui->outputData($data, 'package-info');
- }
-
- // }}}
-}
-
-?>
diff --git a/inc/PEAR/Command/Remote.php b/inc/PEAR/Command/Remote.php
deleted file mode 100644
index bbd16093f5d..00000000000
--- a/inc/PEAR/Command/Remote.php
+++ /dev/null
@@ -1,435 +0,0 @@
-<?php
-// /* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Stig Bakken <ssb@php.net> |
-// | |
-// +----------------------------------------------------------------------+
-//
-// $Id: Remote.php,v 1.39 2004/04/03 15:56:00 cellog 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' => '<package>
-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'),
- );
- $local_pkgs = $reg->listPackages();
-
- 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;
- }
- }
- $pos = array_search(strtolower($name), $local_pkgs);
- if ($pos !== false) {
- unset($local_pkgs[$pos]);
- }
-
- $data['data'][$info['category']][] = array(
- $name,
- @$info['stable'],
- @$installed['version'],
- @$desc,
- @$info['deps'],
- );
- }
-
- foreach ($local_pkgs as $name) {
- $info = $reg->packageInfo($name);
- $data['data']['Local'][] = array(
- $info['package'],
- '',
- $info['version'],
- $info['summary'],
- @$info['release_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, false);
- if (PEAR::isError($available)) {
- return $this->raiseError($available);
- }
- $data = array(
- 'caption' => 'Matched packages:',
- 'border' => true,
- 'headline' => array('Package', 'Stable/(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'];
-
- $unstable = '';
- if ($info['unstable']) {
- $unstable = '/(' . $info['unstable'] . $info['state'] . ')';
- }
- if (!isset($info['stable']) || !$info['stable']) {
- $info['stable'] = 'none';
- }
- $data['data'][$info['category']][] = array(
- $name,
- $info['stable'] . $unstable,
- $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])) {
- $getoption = isset($options['nocompress'])&&$options['nocompress']==1?'?uncompress=on':'';
- $pkgfile = "http://$server/get/$params[0]".$getoption;
- } 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 .= ' (' . implode(', ', PEAR_Common::betterStates($state, true)) . ')';
- }
- $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', 'Local', 'Remote', 'Size'),
- );
- foreach ((array)$latest as $pkg => $info) {
- $package = strtolower($pkg);
- if (!isset($inst[$package])) {
- // skip packages we don't have installed
- continue;
- }
- extract($info);
- $pkginfo = $reg->packageInfo($package);
- $inst_version = $pkginfo['version'];
- $inst_state = $pkginfo['release_state'];
- 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($pkg, "$inst_version ($inst_state)", "$version ($state)", $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/inc/PEAR/Common.php b/inc/PEAR/Common.php
deleted file mode 100644
index fba53a37799..00000000000
--- a/inc/PEAR/Common.php
+++ /dev/null
@@ -1,2094 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2003 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stig Bakken <ssb@php.net> |
-// | Tomas V.V.Cox <cox@idecnet.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Common.php,v 1.126.2.2 2004/12/27 07:04:19 cellog Exp $
-
-require_once 'PEAR.php';
-require_once 'Archive/Tar.php';
-require_once 'System.php';
-require_once 'PEAR/Config.php';
-
-// {{{ constants and globals
-
-/**
- * PEAR_Common error when an invalid PHP file is passed to PEAR_Common::analyzeSourceCode()
- */
-define('PEAR_COMMON_ERROR_INVALIDPHP', 1);
-define('_PEAR_COMMON_PACKAGE_NAME_PREG', '[A-Za-z][a-zA-Z0-9_]+');
-define('PEAR_COMMON_PACKAGE_NAME_PREG', '/^' . _PEAR_COMMON_PACKAGE_NAME_PREG . '$/');
-
-// this should allow: 1, 1.0, 1.0RC1, 1.0dev, 1.0dev123234234234, 1.0a1, 1.0b1, 1.0pl1
-define('_PEAR_COMMON_PACKAGE_VERSION_PREG', '\d+(?:\.\d+)*(?:[a-zA-Z]+\d*)?');
-define('PEAR_COMMON_PACKAGE_VERSION_PREG', '/^' . _PEAR_COMMON_PACKAGE_VERSION_PREG . '$/i');
-
-// XXX far from perfect :-)
-define('PEAR_COMMON_PACKAGE_DOWNLOAD_PREG', '/^(' . _PEAR_COMMON_PACKAGE_NAME_PREG . ')(-([.0-9a-zA-Z]+))?$/');
-
-/**
- * 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','not', 'ne');
-
-/**
- * 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 administration classes.
- * @deprecated This class will disappear, and its components will be spread
- * into smaller classes, like the AT&T breakup
- */
-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;
- /**
- * Flag variable used to mark a valid package file
- * @var boolean
- * @access private
- */
- var $_validPackageFile;
-
- // }}}
-
- // {{{ 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(array('-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(array('-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, $append_crlf = true)
- {
- if ($this->debug >= $level) {
- if (is_object($this->ui)) {
- $this->ui->log($msg, $append_crlf);
- } 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 = array('-t', $tmpdir);
- } else {
- $topt = array();
- }
- $topt = array_merge($topt, array('-d', 'pear'));
- if (!$tmpdir = System::mktemp($topt)) {
- 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': {
- $this->_validPackageFile = true;
- 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;
- if (!method_exists($this, $elem_start) ||
- !method_exists($this, $elem_end) ||
- !method_exists($this, $cdata)) {
- $this->raiseError("No handlers for package.xml version $attribs[version]");
- return;
- }
- 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':
- if ($this->in_changelog) {
- $this->current_release['release_license'] = $data;
- } else {
- $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;
- }
- 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);
- if ($this->debug <= 1) {
- $tar->pushErrorHandling(PEAR_ERROR_RETURN);
- }
- $content = $tar->listContent();
- if ($this->debug <= 1) {
- $tar->popErrorHandling();
- }
- if (!is_array($content)) {
- $file = realpath($file);
- return $this->raiseError("Could not get contents of package \"$file\"".
- '. Invalid tgz 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(array('-d', 'pear'));
- $this->addTempFile($tmpdir);
- if (!$xml || !$tar->extractList(array($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 = '';
- $this->_validPackageFile = false;
-
- 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);
-
- if (!$this->_validPackageFile) {
- return $this->raiseError('Invalid Package File, no <package> tag');
- }
- 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', '<package>.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 == "<?xml") {
- $info = $this->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 = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n";
- $ret .= "<!DOCTYPE package SYSTEM \"http://pear.php.net/dtd/package-1.0\">\n";
- $ret .= "<package version=\"1.0\">
- <name>$pkginfo[package]</name>
- <summary>".htmlspecialchars($pkginfo['summary'])."</summary>
- <description>".htmlspecialchars($pkginfo['description'])."</description>
- <maintainers>
-";
- foreach ($pkginfo['maintainers'] as $maint) {
- $ret .= " <maintainer>\n";
- foreach ($maint_map as $idx => $elm) {
- $ret .= " <$elm>";
- $ret .= htmlspecialchars($maint[$idx]);
- $ret .= "</$elm>\n";
- }
- $ret .= " </maintainer>\n";
- }
- $ret .= " </maintainers>\n";
- $ret .= $this->_makeReleaseXml($pkginfo);
- if (@sizeof($pkginfo['changelog']) > 0) {
- $ret .= " <changelog>\n";
- foreach ($pkginfo['changelog'] as $oldrelease) {
- $ret .= $this->_makeReleaseXml($oldrelease, true);
- }
- $ret .= " </changelog>\n";
- }
- $ret .= "</package>\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 <release>\n";
- if (!empty($pkginfo['version'])) {
- $ret .= "$indent <version>$pkginfo[version]</version>\n";
- }
- if (!empty($pkginfo['release_date'])) {
- $ret .= "$indent <date>$pkginfo[release_date]</date>\n";
- }
- if (!empty($pkginfo['release_license'])) {
- $ret .= "$indent <license>$pkginfo[release_license]</license>\n";
- }
- if (!empty($pkginfo['release_state'])) {
- $ret .= "$indent <state>$pkginfo[release_state]</state>\n";
- }
- if (!empty($pkginfo['release_notes'])) {
- $ret .= "$indent <notes>".htmlspecialchars($pkginfo['release_notes'])."</notes>\n";
- }
- if (!empty($pkginfo['release_warnings'])) {
- $ret .= "$indent <warnings>".htmlspecialchars($pkginfo['release_warnings'])."</warnings>\n";
- }
- if (isset($pkginfo['release_deps']) && sizeof($pkginfo['release_deps']) > 0) {
- $ret .= "$indent <deps>\n";
- foreach ($pkginfo['release_deps'] as $dep) {
- $ret .= "$indent <dep type=\"$dep[type]\" rel=\"$dep[rel]\"";
- if (isset($dep['version'])) {
- $ret .= " version=\"$dep[version]\"";
- }
- if (isset($dep['optional'])) {
- $ret .= " optional=\"$dep[optional]\"";
- }
- if (isset($dep['name'])) {
- $ret .= ">$dep[name]</dep>\n";
- } else {
- $ret .= "/>\n";
- }
- }
- $ret .= "$indent </deps>\n";
- }
- if (isset($pkginfo['configure_options'])) {
- $ret .= "$indent <configureoptions>\n";
- foreach ($pkginfo['configure_options'] as $c) {
- $ret .= "$indent <configureoption name=\"".
- htmlspecialchars($c['name']) . "\"";
- if (isset($c['default'])) {
- $ret .= " default=\"" . htmlspecialchars($c['default']) . "\"";
- }
- $ret .= " prompt=\"" . htmlspecialchars($c['prompt']) . "\"";
- $ret .= "/>\n";
- }
- $ret .= "$indent </configureoptions>\n";
- }
- if (isset($pkginfo['provides'])) {
- foreach ($pkginfo['provides'] as $key => $what) {
- $ret .= "$indent <provides type=\"$what[type]\" ";
- $ret .= "name=\"$what[name]\" ";
- if (isset($what['extends'])) {
- $ret .= "extends=\"$what[extends]\" ";
- }
- $ret .= "/>\n";
- }
- }
- if (isset($pkginfo['filelist'])) {
- $ret .= "$indent <filelist>\n";
- foreach ($pkginfo['filelist'] as $file => $fa) {
- @$ret .= "$indent <file role=\"$fa[role]\"";
- if (isset($fa['baseinstalldir'])) {
- $ret .= ' baseinstalldir="' .
- htmlspecialchars($fa['baseinstalldir']) . '"';
- }
- if (isset($fa['md5sum'])) {
- $ret .= " md5sum=\"$fa[md5sum]\"";
- }
- if (isset($fa['platform'])) {
- $ret .= " platform=\"$fa[platform]\"";
- }
- if (!empty($fa['install-as'])) {
- $ret .= ' install-as="' .
- htmlspecialchars($fa['install-as']) . '"';
- }
- $ret .= ' name="' . htmlspecialchars($file) . '"';
- if (empty($fa['replacements'])) {
- $ret .= "/>\n";
- } else {
- $ret .= ">\n";
- foreach ($fa['replacements'] as $r) {
- $ret .= "$indent <replace";
- foreach ($r as $k => $v) {
- $ret .= " $k=\"" . htmlspecialchars($v) .'"';
- }
- $ret .= "/>\n";
- }
- @$ret .= "$indent </file>\n";
- }
- }
- $ret .= "$indent </filelist>\n";
- }
- $ret .= "$indent </release>\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 = '')
- {
- if (PEAR::isError($info = $this->infoFromAny($info))) {
- return $this->raiseError($info);
- }
- if (!is_array($info)) {
- return false;
- }
-
- $errors = array();
- $warnings = array();
- if (!isset($info['package'])) {
- $errors[] = 'missing package name';
- } elseif (!$this->validPackageName($info['package'])) {
- $errors[] = 'invalid package name';
- }
- $this->_packageName = $pn = $info['package'];
-
- 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 (!isset($info['version'])) {
- $errors[] = 'missing version';
- } elseif (!$this->validPackageVersion($info['version'])) {
- $errors[] = 'invalid package release version';
- }
- if (empty($info['release_state'])) {
- $errors[] = 'missing release state';
- } elseif (!in_array($info['release_state'], PEAR_Common::getReleaseStates())) {
- $errors[] = "invalid release state `$info[release_state]', should be one of: "
- . implode(' ', PEAR_Common::getReleaseStates());
- }
- 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::getUserRoles())) {
- $errors[] = "maintainer $i: invalid role `$m[role]', should be one of: "
- . implode(' ', PEAR_Common::getUserRoles());
- }
- if (empty($m['name'])) {
- $errors[] = "maintainer $i: missing name";
- }
- if (empty($m['email'])) {
- $errors[] = "maintainer $i: missing email";
- }
- $i++;
- }
- }
- if (!empty($info['release_deps'])) {
- $i = 1;
- foreach ($info['release_deps'] as $d) {
- if (empty($d['type'])) {
- $errors[] = "dependency $i: missing type";
- } elseif (!in_array($d['type'], PEAR_Common::getDependencyTypes())) {
- $errors[] = "dependency $i: invalid type '$d[type]', should be one of: " .
- implode(' ', PEAR_Common::getDependencyTypes());
- }
- if (empty($d['rel'])) {
- $errors[] = "dependency $i: missing relation";
- } elseif (!in_array($d['rel'], PEAR_Common::getDependencyRelations())) {
- $errors[] = "dependency $i: invalid relation '$d[rel]', should be one of: "
- . implode(' ', PEAR_Common::getDependencyRelations());
- }
- if (!empty($d['optional'])) {
- if (!in_array($d['optional'], array('yes', 'no'))) {
- $errors[] = "dependency $i: invalid relation optional attribute '$d[optional]', should be one of: yes no";
- } else {
- if (($d['rel'] == 'not' || $d['rel'] == 'ne') && $d['optional'] == 'yes') {
- $errors[] = "dependency $i: 'not' and 'ne' dependencies cannot be " .
- "optional";
- }
- }
- }
- if ($d['rel'] != 'not' && $d['rel'] != 'has' && empty($d['version'])) {
- $warnings[] = "dependency $i: missing version";
- } elseif (($d['rel'] == 'not' || $d['rel'] == 'has') && !empty($d['version'])) {
- $warnings[] = "dependency $i: version ignored for `$d[rel]' dependencies";
- }
- if ($d['rel'] == 'not' && !empty($d['version'])) {
- $warnings[] = "dependency $i: 'not' defines a total conflict, to exclude " .
- "specific versions, use 'ne'";
- }
- 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";
- }
- if ($d['type'] == 'php' && $d['rel'] == 'not') {
- $errors[] = "dependency $i: PHP dependencies cannot use 'not' " .
- "rel, use 'ne' to exclude versions";
- }
- $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";
- }
- $i++;
- }
- }
- 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::getFileRoles())) {
- $errors[] = "file $file: invalid role, should be one of: "
- . implode(' ', PEAR_Common::getFileRoles());
- }
- 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 "../../"
- }
- }
- $this->_packageName = $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\"";
- }
- }
-
-
- 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)
- {
- $file = basename($srcinfo['source_file']);
- $pn = '';
- if (isset($this->_packageName)) {
- $pn = $this->_packageName;
- }
- $pnl = strlen($pn);
- foreach ($srcinfo['declared_classes'] as $class) {
- $key = "class;$class";
- if (isset($this->pkginfo['provides'][$key])) {
- continue;
- }
- $this->pkginfo['provides'][$key] =
- array('file'=> $file, '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('file'=> $file, 'type' => 'function', 'name' => $function);
- }
- }
-
- foreach ($srcinfo['declared_functions'] as $function) {
- $key = "function;$function";
- if ($function{0} == '_' || isset($this->pkginfo['provides'][$key])) {
- continue;
- }
- if (!strstr($function, '::') && strncasecmp($function, $pn, $pnl)) {
- $warnings[] = "in1 " . $file . ": function \"$function\" not prefixed with package name \"$pn\"";
- }
- $this->pkginfo['provides'][$key] =
- array('file'=> $file, '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 (!function_exists("token_get_all")) {
- return false;
- }
- if (!defined('T_DOC_COMMENT')) {
- define('T_DOC_COMMENT', T_COMMENT);
- }
- if (!defined('T_INTERFACE')) {
- define('T_INTERFACE', -1);
- }
- if (!defined('T_IMPLEMENTS')) {
- define('T_IMPLEMENTS', -1);
- }
- 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_interface = '';
- $current_class_level = -1;
- $current_function = '';
- $current_function_level = -1;
- $declared_classes = array();
- $declared_interfaces = array();
- $declared_functions = array();
- $declared_methods = array();
- $used_classes = array();
- $used_functions = array();
- $extends = array();
- $implements = array();
- $nodeps = array();
- $inquote = false;
- $interface = false;
- for ($i = 0; $i < sizeof($tokens); $i++) {
- if (is_array($tokens[$i])) {
- list($token, $data) = $tokens[$i];
- } else {
- $token = $tokens[$i];
- $data = '';
- }
- if ($inquote) {
- if ($token != '"') {
- continue;
- } else {
- $inquote = false;
- }
- }
- switch ($token) {
- case T_WHITESPACE:
- continue;
- case ';':
- if ($interface) {
- $current_function = '';
- $current_function_level = -1;
- }
- break;
- case '"':
- $inquote = true;
- break;
- 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_INTERFACE:
- $interface = true;
- case T_CLASS:
- if (($current_class_level != -1) || ($current_function_level != -1)) {
- PEAR::raiseError("Parser error: Invalid PHP file $file",
- PEAR_COMMON_ERROR_INVALIDPHP);
- return false;
- }
- case T_FUNCTION:
- case T_NEW:
- case T_EXTENDS:
- case T_IMPLEMENTS:
- $look_for = $token;
- continue 2;
- case T_STRING:
- if (version_compare(zend_version(), '2.0', '<')) {
- if (in_array(strtolower($data),
- array('public', 'private', 'protected', 'abstract',
- 'interface', 'implements', 'clone', 'throw')
- )) {
- PEAR::raiseError('Error: PHP5 packages must be packaged by php 5 PEAR');
- return false;
- }
- }
- if ($look_for == T_CLASS) {
- $current_class = $data;
- $current_class_level = $brace_level;
- $declared_classes[] = $current_class;
- } elseif ($look_for == T_INTERFACE) {
- $current_interface = $data;
- $current_class_level = $brace_level;
- $declared_interfaces[] = $current_interface;
- } elseif ($look_for == T_IMPLEMENTS) {
- $implements[$current_class] = $data;
- } 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;
- } elseif ($current_interface) {
- $current_function = "$current_interface::$data";
- $declared_methods[$current_interface][] = $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_DOC_COMMENT:
- 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:
- if (!($tokens[$i - 1][0] == T_WHITESPACE || $tokens[$i - 1][0] == T_STRING)) {
- PEAR::raiseError("Parser error: Invalid PHP file $file",
- PEAR_COMMON_ERROR_INVALIDPHP);
- return false;
- }
- $class = $tokens[$i - 1][1];
- if (strtolower($class) != 'parent') {
- $used_classes[$class] = true;
- }
- continue 2;
- }
- }
- return array(
- "source_file" => $file,
- "declared_classes" => $declared_classes,
- "declared_interfaces" => $declared_interfaces,
- "declared_methods" => $declared_methods,
- "declared_functions" => $declared_functions,
- "used_classes" => array_diff(array_keys($used_classes), $nodeps),
- "inheritance" => $extends,
- "implements" => $implements,
- );
- }
-
- // }}}
- // {{{ betterStates()
-
- /**
- * Return an array containing all of the states that are more stable than
- * or equal to the passed in state
- *
- * @param string Release state
- * @param boolean Determines whether to include $state in the list
- * @return false|array False if $state is not a valid release state
- */
- function betterStates($state, $include = false)
- {
- static $states = array('snapshot', 'devel', 'alpha', 'beta', 'stable');
- $i = array_search($state, $states);
- if ($i === false) {
- return false;
- }
- if ($include) {
- $i--;
- }
- return array_slice($states, $i + 1);
- }
-
- // }}}
- // {{{ 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);
- }
-
-
- // }}}
- // {{{ validPackageVersion()
-
- /**
- * Test whether a string contains a valid package version.
- *
- * @param string $ver the package version to test
- *
- * @return bool
- *
- * @access public
- */
- function validPackageVersion($ver)
- {
- return (bool)preg_match(PEAR_COMMON_PACKAGE_VERSION_PREG, $ver);
- }
-
-
- // }}}
-
- // {{{ 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 (!$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', array(basename($dest_file), $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;
- }
-
- // }}}
- // {{{ sortPkgDeps()
-
- /**
- * Sort a list of arrays of array(downloaded packagefilename) by dependency.
- *
- * It also removes duplicate dependencies
- * @param array
- * @param boolean Sort packages in reverse order if true
- * @return array array of array(packagefilename, package.xml contents)
- */
- function sortPkgDeps(&$packages, $uninstall = false)
- {
- $ret = array();
- if ($uninstall) {
- foreach($packages as $packageinfo) {
- $ret[] = array('info' => $packageinfo);
- }
- } else {
- foreach($packages as $packagefile) {
- if (!is_array($packagefile)) {
- $ret[] = array('file' => $packagefile,
- 'info' => $a = $this->infoFromAny($packagefile),
- 'pkg' => $a['package']);
- } else {
- $ret[] = $packagefile;
- }
- }
- }
- $checkdupes = array();
- $newret = array();
- foreach($ret as $i => $p) {
- if (!isset($checkdupes[$p['info']['package']])) {
- $checkdupes[$p['info']['package']][] = $i;
- $newret[] = $p;
- }
- }
- $this->_packageSortTree = $this->_getPkgDepTree($newret);
-
- $func = $uninstall ? '_sortPkgDepsRev' : '_sortPkgDeps';
- usort($newret, array(&$this, $func));
- $this->_packageSortTree = null;
- $packages = $newret;
- }
-
- // }}}
- // {{{ _sortPkgDeps()
-
- /**
- * Compare two package's package.xml, and sort
- * so that dependencies are installed first
- *
- * This is a crude compare, real dependency checking is done on install.
- * The only purpose this serves is to make the command-line
- * order-independent (you can list a dependent package first, and
- * installation occurs in the order required)
- * @access private
- */
- function _sortPkgDeps($p1, $p2)
- {
- $p1name = $p1['info']['package'];
- $p2name = $p2['info']['package'];
- $p1deps = $this->_getPkgDeps($p1);
- $p2deps = $this->_getPkgDeps($p2);
- if (!count($p1deps) && !count($p2deps)) {
- return 0; // order makes no difference
- }
- if (!count($p1deps)) {
- return -1; // package 2 has dependencies, package 1 doesn't
- }
- if (!count($p2deps)) {
- return 1; // package 1 has dependencies, package 2 doesn't
- }
- // both have dependencies
- if (in_array($p1name, $p2deps)) {
- return -1; // put package 1 first: package 2 depends on package 1
- }
- if (in_array($p2name, $p1deps)) {
- return 1; // put package 2 first: package 1 depends on package 2
- }
- if ($this->_removedDependency($p1name, $p2name)) {
- return -1; // put package 1 first: package 2 depends on packages that depend on package 1
- }
- if ($this->_removedDependency($p2name, $p1name)) {
- return 1; // put package 2 first: package 1 depends on packages that depend on package 2
- }
- // doesn't really matter if neither depends on the other
- return 0;
- }
-
- // }}}
- // {{{ _sortPkgDepsRev()
-
- /**
- * Compare two package's package.xml, and sort
- * so that dependencies are uninstalled last
- *
- * This is a crude compare, real dependency checking is done on uninstall.
- * The only purpose this serves is to make the command-line
- * order-independent (you can list a dependency first, and
- * uninstallation occurs in the order required)
- * @access private
- */
- function _sortPkgDepsRev($p1, $p2)
- {
- $p1name = $p1['info']['package'];
- $p2name = $p2['info']['package'];
- $p1deps = $this->_getRevPkgDeps($p1);
- $p2deps = $this->_getRevPkgDeps($p2);
- if (!count($p1deps) && !count($p2deps)) {
- return 0; // order makes no difference
- }
- if (!count($p1deps)) {
- return 1; // package 2 has dependencies, package 1 doesn't
- }
- if (!count($p2deps)) {
- return -1; // package 2 has dependencies, package 1 doesn't
- }
- // both have dependencies
- if (in_array($p1name, $p2deps)) {
- return 1; // put package 1 last
- }
- if (in_array($p2name, $p1deps)) {
- return -1; // put package 2 last
- }
- if ($this->_removedDependency($p1name, $p2name)) {
- return 1; // put package 1 last: package 2 depends on packages that depend on package 1
- }
- if ($this->_removedDependency($p2name, $p1name)) {
- return -1; // put package 2 last: package 1 depends on packages that depend on package 2
- }
- // doesn't really matter if neither depends on the other
- return 0;
- }
-
- // }}}
- // {{{ _getPkgDeps()
-
- /**
- * get an array of package dependency names
- * @param array
- * @return array
- * @access private
- */
- function _getPkgDeps($p)
- {
- if (!isset($p['info']['releases'])) {
- return $this->_getRevPkgDeps($p);
- }
- $rel = array_shift($p['info']['releases']);
- if (!isset($rel['deps'])) {
- return array();
- }
- $ret = array();
- foreach($rel['deps'] as $dep) {
- if ($dep['type'] == 'pkg') {
- $ret[] = $dep['name'];
- }
- }
- return $ret;
- }
-
- // }}}
- // {{{ _getPkgDeps()
-
- /**
- * get an array representation of the package dependency tree
- * @return array
- * @access private
- */
- function _getPkgDepTree($packages)
- {
- $tree = array();
- foreach ($packages as $p) {
- $package = $p['info']['package'];
- $deps = $this->_getPkgDeps($p);
- $tree[$package] = $deps;
- }
- return $tree;
- }
-
- // }}}
- // {{{ _removedDependency($p1, $p2)
-
- /**
- * get an array of package dependency names for uninstall
- * @param string package 1 name
- * @param string package 2 name
- * @return bool
- * @access private
- */
- function _removedDependency($p1, $p2)
- {
- if (empty($this->_packageSortTree[$p2])) {
- return false;
- }
- if (!in_array($p1, $this->_packageSortTree[$p2])) {
- foreach ($this->_packageSortTree[$p2] as $potential) {
- if ($this->_removedDependency($p1, $potential)) {
- return true;
- }
- }
- return false;
- }
- return true;
- }
-
- // }}}
- // {{{ _getRevPkgDeps()
-
- /**
- * get an array of package dependency names for uninstall
- * @param array
- * @return array
- * @access private
- */
- function _getRevPkgDeps($p)
- {
- if (!isset($p['info']['release_deps'])) {
- return array();
- }
- $ret = array();
- foreach($p['info']['release_deps'] as $dep) {
- if ($dep['type'] == 'pkg') {
- $ret[] = $dep['name'];
- }
- }
- return $ret;
- }
-
- // }}}
-}
-
-?>
diff --git a/inc/PEAR/Config.php b/inc/PEAR/Config.php
deleted file mode 100644
index ba641735250..00000000000
--- a/inc/PEAR/Config.php
+++ /dev/null
@@ -1,1169 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Stig Bakken <ssb@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Config.php,v 1.52 2004/01/08 17:33:12 sniper Exp $
-
-require_once 'PEAR.php';
-require_once 'System.php';
-
-/**
- * Last created PEAR_Config instance.
- * @var object
- */
-$GLOBALS['_PEAR_Config_instance'] = null;
-if (!defined('PEAR_INSTALL_DIR') || !PEAR_INSTALL_DIR) {
- $PEAR_INSTALL_DIR = PHP_LIBDIR . DIRECTORY_SEPARATOR . 'pear';
-} else {
- $PEAR_INSTALL_DIR = PEAR_INSTALL_DIR;
-}
-
-// 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)) {
- define('PEAR_CONFIG_DEFAULT_PHP_DIR',
- $PEAR_INSTALL_DIR);
- } 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 {
- if (ini_get('extension_dir')) {
- define('PEAR_CONFIG_DEFAULT_EXT_DIR', ini_get('extension_dir'));
- } elseif (defined('PEAR_EXTENSION_DIR') && @is_dir(PEAR_EXTENSION_DIR)) {
- define('PEAR_CONFIG_DEFAULT_EXT_DIR', PEAR_EXTENSION_DIR);
- } elseif (defined('PHP_EXTENSION_DIR')) {
- define('PEAR_CONFIG_DEFAULT_EXT_DIR', PHP_EXTENSION_DIR);
- } else {
- define('PEAR_CONFIG_DEFAULT_EXT_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', $data = null)
- {
- if ($layer == 'both' || $layer == 'all') {
- foreach ($this->files as $type => $file) {
- $err = $this->writeConfigFile($file, $type, $data);
- 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 = ($data === null) ? $this->configuration[$layer] : $data;
- $this->_encodeOutput($data);
- $opt = array('-p', dirname($file));
- if (!@System::mkDir($opt)) {
- 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);
- $rt = get_magic_quotes_runtime();
- set_magic_quotes_runtime(0);
- $contents = fread($fp, $size);
- set_magic_quotes_runtime($rt);
- 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;
- }
-
- // }}}
- // {{{ getConfFile(layer)
- /**
- * Gets the file used for storing the config for a layer
- *
- * @param string $layer 'user' or 'system'
- */
-
- function getConfFile($layer)
- {
- return $this->files[$layer];
- }
-
- // }}}
- // {{{ _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])) {
- $this->configuration[$layer] = array();
- 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', $data = null)
- {
- return $this->writeConfigFile(null, $layer, $data);
- }
-
- // }}}
- // {{{ 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 <config key> 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 <config layer> 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/inc/PEAR/Dependency.php b/inc/PEAR/Dependency.php
deleted file mode 100644
index 705167aa70f..00000000000
--- a/inc/PEAR/Dependency.php
+++ /dev/null
@@ -1,487 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Tomas V.V.Cox <cox@idecnet.com> |
-// | Stig Bakken <ssb@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Dependency.php,v 1.36.4.1 2004/12/27 07:04:19 cellog 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);
-define('PEAR_DEPENDENCY_MISSING_OPTIONAL', -6);
-define('PEAR_DEPENDENCY_CONFLICT_OPTIONAL', -7);
-define('PEAR_DEPENDENCY_UPGRADE_MINOR_OPTIONAL', -8);
-define('PEAR_DEPENDENCY_UPGRADE_MAJOR_OPTIONAL', -9);
-
-/**
- * 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 <cox@idecnet.com>
- * @author Stig Bakken <ssb@php.net>
- */
-class PEAR_Dependency
-{
- // {{{ constructor
- /**
- * Constructor
- *
- * @access public
- * @param object Registry object
- * @return void
- */
- function PEAR_Dependency(&$registry)
- {
- $this->registry = &$registry;
- }
-
- // }}}
- // {{{ callCheckMethod()
-
- /**
- * This method maps the XML dependency definition to the
- * corresponding one from PEAR_Dependency
- *
- * <pre>
- * $opts => Array
- * (
- * [type] => pkg
- * [rel] => ge
- * [version] => 3.4
- * [name] => HTML_Common
- * [optional] => false
- * )
- * </pre>
- *
- * @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;
- $opt = (isset($opts['optional']) && $opts['optional'] == 'yes') ?
- $opts['optional'] : null;
- $errmsg = '';
- switch ($opts['type']) {
- case 'pkg':
- return $this->checkPackage($errmsg, $name, $req, $rel, $opt);
- break;
- case 'ext':
- return $this->checkExtension($errmsg, $name, $req, $rel, $opt);
- 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";
- }
- }
-
- // }}}
- // {{{ checkPackage()
-
- /**
- * Package dependencies check method
- *
- * @param string $errmsg Empty string, it will be populated with an error message, if any
- * @param string $name Name of the package to test
- * @param string $req The package version required
- * @param string $relation How to compare versions with each other
- * @param bool $opt Whether the relationship is optional
- *
- * @return mixed bool false if no error or the error string
- */
- function checkPackage(&$errmsg, $name, $req = null, $relation = 'has',
- $opt = false)
- {
- if (is_string($req) && substr($req, 0, 2) == 'v.') {
- $req = substr($req, 2);
- }
- switch ($relation) {
- case 'has':
- if (!$this->registry->packageExists($name)) {
- if ($opt) {
- $errmsg = "package `$name' is recommended to utilize some features.";
- return PEAR_DEPENDENCY_MISSING_OPTIONAL;
- }
- $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))
- {
- $code = $this->codeFromRelation($relation, $version, $req, $opt);
- if ($opt) {
- $errmsg = "package `$name' version " . $this->signOperator($relation) .
- " $req is recommended to utilize some features.";
- if ($version) {
- $errmsg .= " Installed version is $version";
- }
- return $code;
- }
- $errmsg = "requires package `$name' " .
- $this->signOperator($relation) . " $req";
- return $code;
- }
- return false;
- }
- $errmsg = "relation '$relation' with requirement '$req' is not supported (name=$name)";
- return PEAR_DEPENDENCY_BAD_DEPENDENCY;
- }
-
- // }}}
- // {{{ checkPackageUninstall()
-
- /**
- * Check package dependencies on uninstall
- *
- * @param string $error The resultant error string
- * @param string $warning The resultant warning string
- * @param string $name Name of the package to test
- *
- * @return bool true if there were errors
- */
- function checkPackageUninstall(&$error, &$warning, $package)
- {
- $error = null;
- $packages = $this->registry->listPackages();
- foreach ($packages as $pkg) {
- if ($pkg == $package) {
- continue;
- }
- $deps = $this->registry->packageInfo($pkg, 'release_deps');
- if (empty($deps)) {
- continue;
- }
- foreach ($deps as $dep) {
- if ($dep['type'] == 'pkg' && strcasecmp($dep['name'], $package) == 0) {
- if ($dep['rel'] == 'ne' || $dep['rel'] == 'not') {
- continue;
- }
- if (isset($dep['optional']) && $dep['optional'] == 'yes') {
- $warning .= "\nWarning: Package '$pkg' optionally depends on '$package'";
- } else {
- $error .= "Package '$pkg' depends on '$package'\n";
- }
- }
- }
- }
- return ($error) ? true : false;
- }
-
- // }}}
- // {{{ checkExtension()
-
- /**
- * 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
- * @param bool $opt Whether the relationship is optional
- *
- * @return mixed bool false if no error or the error string
- */
- function checkExtension(&$errmsg, $name, $req = null, $relation = 'has',
- $opt = false)
- {
- if ($relation == 'not') {
- if (extension_loaded($name)) {
- $errmsg = "conflicts with PHP extension '$name'";
- return PEAR_DEPENDENCY_CONFLICT;
- } else {
- return false;
- }
- }
-
- if (!extension_loaded($name)) {
- if ($relation == 'not') {
- return false;
- }
- if ($opt) {
- $errmsg = "'$name' PHP extension is recommended to utilize some features";
- return PEAR_DEPENDENCY_MISSING_OPTIONAL;
- }
- $errmsg = "'$name' PHP extension is not installed";
- return PEAR_DEPENDENCY_MISSING;
- }
- if ($relation == 'has') {
- return false;
- }
- $code = false;
- if (is_string($req) && substr($req, 0, 2) == 'v.') {
- $req = substr($req, 2);
- }
- $ext_ver = phpversion($name);
- $operator = $relation;
- // Force params to be strings, otherwise the comparation will fail (ex. 0.9==0.90)
- if (!version_compare("$ext_ver", "$req", $operator)) {
- $errmsg = "'$name' PHP extension version " .
- $this->signOperator($operator) . " $req is required";
- $code = $this->codeFromRelation($relation, $ext_ver, $req, $opt);
- if ($opt) {
- $errmsg = "'$name' PHP extension version " . $this->signOperator($operator) .
- " $req is recommended to utilize some features";
- return $code;
- }
- }
- return $code;
- }
-
- // }}}
- // {{{ checkOS()
-
- /**
- * 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;
- }
-
- // }}}
- // {{{ checkPHP()
-
- /**
- * 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')
- {
- // this would be a bit stupid, but oh well :)
- if ($relation == 'has') {
- return false;
- }
- if ($relation == 'not') {
- $errmsg = 'Invalid dependency - "not" is not allowed for php dependencies, ' .
- 'php cannot conflict with itself';
- return PEAR_DEPENDENCY_BAD_DEPENDENCY;
- }
- if (substr($req, 0, 2) == 'v.') {
- $req = substr($req,2, strlen($req) - 2);
- }
- $php_ver = phpversion();
- $operator = $relation;
- if (!version_compare("$php_ver", "$req", $operator)) {
- $errmsg = "PHP version " . $this->signOperator($operator) .
- " $req is required";
- return PEAR_DEPENDENCY_CONFLICT;
- }
- return false;
- }
-
- // }}}
- // {{{ checkProgram()
-
- /**
- * 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
- $exe_suffix = OS_WINDOWS ? '.exe' : '';
- $path_elements = explode(PATH_SEPARATOR, 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;
- }
-
- // }}}
- // {{{ checkSAPI()
-
- /**
- * 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;
- }
-
- // }}}
- // {{{ checkZend()
-
- /**
- * 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;
- }
-
- // }}}
- // {{{ signOperator()
-
- /**
- * 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;
- }
- }
-
- // }}}
- // {{{ codeFromRelation()
-
- /**
- * Convert relation into corresponding code
- *
- * @access public
- * @param string Relation
- * @param string Version
- * @param string Requirement
- * @param bool Optional dependency indicator
- * @return integer
- */
- function codeFromRelation($relation, $version, $req, $opt = false)
- {
- $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 = $opt ? PEAR_DEPENDENCY_UPGRADE_MAJOR_OPTIONAL :
- PEAR_DEPENDENCY_UPGRADE_MAJOR;
- } else {
- $code = $opt ? PEAR_DEPENDENCY_UPGRADE_MINOR_OPTIONAL :
- PEAR_DEPENDENCY_UPGRADE_MINOR;
- }
- break;
- case 'lt': case 'le': case 'ne':
- $code = $opt ? PEAR_DEPENDENCY_CONFLICT_OPTIONAL :
- PEAR_DEPENDENCY_CONFLICT;
- break;
- }
- return $code;
- }
-
- // }}}
-}
-?>
diff --git a/inc/PEAR/Downloader.php b/inc/PEAR/Downloader.php
deleted file mode 100644
index 5e16dc5ffb1..00000000000
--- a/inc/PEAR/Downloader.php
+++ /dev/null
@@ -1,680 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stig Bakken <ssb@php.net> |
-// | Tomas V.V.Cox <cox@idecnet.com> |
-// | Martin Jansen <mj@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Downloader.php,v 1.17.2.1 2004/10/22 22:54:03 cellog Exp $
-
-require_once 'PEAR/Common.php';
-require_once 'PEAR/Registry.php';
-require_once 'PEAR/Dependency.php';
-require_once 'PEAR/Remote.php';
-require_once 'System.php';
-
-
-define('PEAR_INSTALLER_OK', 1);
-define('PEAR_INSTALLER_FAILED', 0);
-define('PEAR_INSTALLER_SKIPPED', -1);
-define('PEAR_INSTALLER_ERROR_NO_PREF_STATE', 2);
-
-/**
- * Administration class used to download PEAR packages and maintain the
- * installed package database.
- *
- * @since PEAR 1.4
- * @author Greg Beaver <cellog@php.net>
- */
-class PEAR_Downloader extends PEAR_Common
-{
- /**
- * @var PEAR_Config
- * @access private
- */
- var $_config;
-
- /**
- * @var PEAR_Registry
- * @access private
- */
- var $_registry;
-
- /**
- * @var PEAR_Remote
- * @access private
- */
- var $_remote;
-
- /**
- * Preferred Installation State (snapshot, devel, alpha, beta, stable)
- * @var string|null
- * @access private
- */
- var $_preferredState;
-
- /**
- * Options from command-line passed to Install.
- *
- * Recognized options:<br />
- * - onlyreqdeps : install all required dependencies as well
- * - alldeps : install all dependencies, including optional
- * - installroot : base relative path to install files in
- * - force : force a download even if warnings would prevent it
- * @see PEAR_Command_Install
- * @access private
- * @var array
- */
- var $_options;
-
- /**
- * Downloaded Packages after a call to download().
- *
- * Format of each entry:
- *
- * <code>
- * array('pkg' => 'package_name', 'file' => '/path/to/local/file',
- * 'info' => array() // parsed package.xml
- * );
- * </code>
- * @access private
- * @var array
- */
- var $_downloadedPackages = array();
-
- /**
- * Packages slated for download.
- *
- * This is used to prevent downloading a package more than once should it be a dependency
- * for two packages to be installed.
- * Format of each entry:
- *
- * <pre>
- * array('package_name1' => parsed package.xml, 'package_name2' => parsed package.xml,
- * );
- * </pre>
- * @access private
- * @var array
- */
- var $_toDownload = array();
-
- /**
- * Array of every package installed, with names lower-cased.
- *
- * Format:
- * <code>
- * array('package1' => 0, 'package2' => 1, );
- * </code>
- * @var array
- */
- var $_installed = array();
-
- /**
- * @var array
- * @access private
- */
- var $_errorStack = array();
-
- // {{{ PEAR_Downloader()
-
- function PEAR_Downloader(&$ui, $options, &$config)
- {
- $this->_options = $options;
- $this->_config = &$config;
- $this->_preferredState = $this->_config->get('preferred_state');
- $this->ui = &$ui;
- if (!$this->_preferredState) {
- // don't inadvertantly use a non-set preferred_state
- $this->_preferredState = null;
- }
-
- $php_dir = $this->_config->get('php_dir');
- if (isset($this->_options['installroot'])) {
- if (substr($this->_options['installroot'], -1) == DIRECTORY_SEPARATOR) {
- $this->_options['installroot'] = substr($this->_options['installroot'], 0, -1);
- }
- $php_dir = $this->_prependPath($php_dir, $this->_options['installroot']);
- }
- $this->_registry = &new PEAR_Registry($php_dir);
- $this->_remote = &new PEAR_Remote($config);
-
- if (isset($this->_options['alldeps']) || isset($this->_options['onlyreqdeps'])) {
- $this->_installed = $this->_registry->listPackages();
- array_walk($this->_installed, create_function('&$v,$k','$v = strtolower($v);'));
- $this->_installed = array_flip($this->_installed);
- }
- parent::PEAR_Common();
- }
-
- // }}}
- // {{{ configSet()
- function configSet($key, $value, $layer = 'user')
- {
- $this->_config->set($key, $value, $layer);
- $this->_preferredState = $this->_config->get('preferred_state');
- if (!$this->_preferredState) {
- // don't inadvertantly use a non-set preferred_state
- $this->_preferredState = null;
- }
- }
-
- // }}}
- // {{{ setOptions()
- function setOptions($options)
- {
- $this->_options = $options;
- }
-
- // }}}
- // {{{ _downloadFile()
- /**
- * @param string filename to download
- * @param string version/state
- * @param string original value passed to command-line
- * @param string|null preferred state (snapshot/devel/alpha/beta/stable)
- * Defaults to configuration preferred state
- * @return null|PEAR_Error|string
- * @access private
- */
- function _downloadFile($pkgfile, $version, $origpkgfile, $state = null)
- {
- if (is_null($state)) {
- $state = $this->_preferredState;
- }
- // {{{ check the package filename, and whether it's already installed
- $need_download = false;
- if (preg_match('#^(http|ftp)://#', $pkgfile)) {
- $need_download = true;
- } elseif (!@is_file($pkgfile)) {
- if ($this->validPackageName($pkgfile)) {
- if ($this->_registry->packageExists($pkgfile)) {
- if (empty($this->_options['upgrade']) && empty($this->_options['force'])) {
- $errors[] = "$pkgfile already installed";
- return;
- }
- }
- $pkgfile = $this->getPackageDownloadUrl($pkgfile, $version);
- $need_download = true;
- } else {
- if (strlen($pkgfile)) {
- $errors[] = "Could not open the package file: $pkgfile";
- } else {
- $errors[] = "No package file given";
- }
- return;
- }
- }
- // }}}
-
- // {{{ 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(3, '+ tmp dir created at ' . $downloaddir);
- }
- $callback = $this->ui ? array(&$this, '_downloadCallback') : null;
- $this->pushErrorHandling(PEAR_ERROR_RETURN);
- $file = $this->downloadHttp($pkgfile, $this->ui, $downloaddir, $callback);
- $this->popErrorHandling();
- if (PEAR::isError($file)) {
- if ($this->validPackageName($origpkgfile)) {
- if (!PEAR::isError($info = $this->_remote->call('package.info',
- $origpkgfile))) {
- if (!count($info['releases'])) {
- return $this->raiseError('Package ' . $origpkgfile .
- ' has no releases');
- } else {
- return $this->raiseError('No releases of preferred state "'
- . $state . '" exist for package ' . $origpkgfile .
- '. Use ' . $origpkgfile . '-state to install another' .
- ' state (like ' . $origpkgfile .'-beta)',
- PEAR_INSTALLER_ERROR_NO_PREF_STATE);
- }
- } else {
- return $pkgfile;
- }
- } else {
- return $this->raiseError($file);
- }
- }
- $pkgfile = $file;
- }
- // }}}
- return $pkgfile;
- }
- // }}}
- // {{{ getPackageDownloadUrl()
-
- function getPackageDownloadUrl($package, $version = null)
- {
- if ($version) {
- $package .= "-$version";
- }
- 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;
- }
-
- // }}}
- // {{{ extractDownloadFileName($pkgfile, &$version)
-
- function extractDownloadFileName($pkgfile, &$version)
- {
- if (@is_file($pkgfile)) {
- return $pkgfile;
- }
- // regex defined in Common.php
- if (preg_match(PEAR_COMMON_PACKAGE_DOWNLOAD_PREG, $pkgfile, $m)) {
- $version = (isset($m[3])) ? $m[3] : null;
- return $m[1];
- }
- $version = null;
- return $pkgfile;
- }
-
- // }}}
-
- // }}}
- // {{{ getDownloadedPackages()
-
- /**
- * Retrieve a list of downloaded packages after a call to {@link download()}.
- *
- * Also resets the list of downloaded packages.
- * @return array
- */
- function getDownloadedPackages()
- {
- $ret = $this->_downloadedPackages;
- $this->_downloadedPackages = array();
- $this->_toDownload = array();
- return $ret;
- }
-
- // }}}
- // {{{ download()
-
- /**
- * Download any files and their dependencies, if necessary
- *
- * BC-compatible method name
- * @param array a mixed list of package names, local files, or package.xml
- */
- function download($packages)
- {
- return $this->doDownload($packages);
- }
-
- // }}}
- // {{{ doDownload()
-
- /**
- * Download any files and their dependencies, if necessary
- *
- * @param array a mixed list of package names, local files, or package.xml
- */
- function doDownload($packages)
- {
- $mywillinstall = array();
- $state = $this->_preferredState;
-
- // {{{ download files in this list if necessary
- foreach($packages as $pkgfile) {
- $need_download = false;
- if (!is_file($pkgfile)) {
- if (preg_match('#^(http|ftp)://#', $pkgfile)) {
- $need_download = true;
- }
- $pkgfile = $this->_downloadNonFile($pkgfile);
- if (PEAR::isError($pkgfile)) {
- return $pkgfile;
- }
- if ($pkgfile === false) {
- continue;
- }
- } // end is_file()
-
- $tempinfo = $this->infoFromAny($pkgfile);
- if ($need_download) {
- $this->_toDownload[] = $tempinfo['package'];
- }
- if (isset($this->_options['alldeps']) || isset($this->_options['onlyreqdeps'])) {
- // ignore dependencies if there are any errors
- if (!PEAR::isError($tempinfo)) {
- $mywillinstall[strtolower($tempinfo['package'])] = @$tempinfo['release_deps'];
- }
- }
- $this->_downloadedPackages[] = array('pkg' => $tempinfo['package'],
- 'file' => $pkgfile, 'info' => $tempinfo);
- } // end foreach($packages)
- // }}}
-
- // {{{ extract dependencies from downloaded files and then download
- // them if necessary
- if (isset($this->_options['alldeps']) || isset($this->_options['onlyreqdeps'])) {
- $deppackages = array();
- foreach ($mywillinstall as $package => $alldeps) {
- if (!is_array($alldeps)) {
- // there are no dependencies
- continue;
- }
- $fail = false;
- foreach ($alldeps as $info) {
- if ($info['type'] != 'pkg') {
- continue;
- }
- $ret = $this->_processDependency($package, $info, $mywillinstall);
- if ($ret === false) {
- continue;
- }
- if ($ret === 0) {
- $fail = true;
- continue;
- }
- if (PEAR::isError($ret)) {
- return $ret;
- }
- $deppackages[] = $ret;
- } // foreach($alldeps
- if ($fail) {
- $deppackages = array();
- }
- }
-
- if (count($deppackages)) {
- $this->doDownload($deppackages);
- }
- } // }}} if --alldeps or --onlyreqdeps
- }
-
- // }}}
- // {{{ _downloadNonFile($pkgfile)
-
- /**
- * @return false|PEAR_Error|string false if loop should be broken out of,
- * string if the file was downloaded,
- * PEAR_Error on exception
- * @access private
- */
- function _downloadNonFile($pkgfile)
- {
- $origpkgfile = $pkgfile;
- $state = null;
- $pkgfile = $this->extractDownloadFileName($pkgfile, $version);
- if (preg_match('#^(http|ftp)://#', $pkgfile)) {
- return $this->_downloadFile($pkgfile, $version, $origpkgfile);
- }
- if (!$this->validPackageName($pkgfile)) {
- return $this->raiseError("Package name '$pkgfile' not valid");
- }
- // ignore packages that are installed unless we are upgrading
- $curinfo = $this->_registry->packageInfo($pkgfile);
- if ($this->_registry->packageExists($pkgfile)
- && empty($this->_options['upgrade']) && empty($this->_options['force'])) {
- $this->log(0, "Package '{$curinfo['package']}' already installed, skipping");
- return false;
- }
- if (in_array($pkgfile, $this->_toDownload)) {
- return false;
- }
- $releases = $this->_remote->call('package.info', $pkgfile, 'releases', true);
- if (!count($releases)) {
- return $this->raiseError("No releases found for package '$pkgfile'");
- }
- // Want a specific version/state
- if ($version !== null) {
- // Passed Foo-1.2
- if ($this->validPackageVersion($version)) {
- if (!isset($releases[$version])) {
- return $this->raiseError("No release with version '$version' found for '$pkgfile'");
- }
- // Passed Foo-alpha
- } elseif (in_array($version, $this->getReleaseStates())) {
- $state = $version;
- $version = 0;
- foreach ($releases as $ver => $inf) {
- if ($inf['state'] == $state && version_compare("$version", "$ver") < 0) {
- $version = $ver;
- break;
- }
- }
- if ($version == 0) {
- return $this->raiseError("No release with state '$state' found for '$pkgfile'");
- }
- // invalid suffix passed
- } else {
- return $this->raiseError("Invalid suffix '-$version', be sure to pass a valid PEAR ".
- "version number or release state");
- }
- // Guess what to download
- } else {
- $states = $this->betterStates($this->_preferredState, true);
- $possible = false;
- $version = 0;
- $higher_version = 0;
- $prev_hi_ver = 0;
- foreach ($releases as $ver => $inf) {
- if (in_array($inf['state'], $states) && version_compare("$version", "$ver") < 0) {
- $version = $ver;
- break;
- } else {
- $ver = (string)$ver;
- if (version_compare($prev_hi_ver, $ver) < 0) {
- $prev_hi_ver = $higher_version = $ver;
- }
- }
- }
- if ($version === 0 && !isset($this->_options['force'])) {
- return $this->raiseError('No release with state equal to: \'' . implode(', ', $states) .
- "' found for '$pkgfile'");
- } elseif ($version === 0) {
- $this->log(0, "Warning: $pkgfile is state '" . $releases[$higher_version]['state'] . "' which is less stable " .
- "than state '$this->_preferredState'");
- }
- }
- // Check if we haven't already the version
- if (empty($this->_options['force']) && !is_null($curinfo)) {
- if ($curinfo['version'] == $version) {
- $this->log(0, "Package '{$curinfo['package']}-{$curinfo['version']}' already installed, skipping");
- return false;
- } elseif (version_compare("$version", "{$curinfo['version']}") < 0) {
- $this->log(0, "Package '{$curinfo['package']}' version '{$curinfo['version']}' " .
- " is installed and {$curinfo['version']} is > requested '$version', skipping");
- return false;
- }
- }
- $this->_toDownload[] = $pkgfile;
- return $this->_downloadFile($pkgfile, $version, $origpkgfile, $state);
- }
-
- // }}}
- // {{{ _processDependency($package, $info, $mywillinstall)
-
- /**
- * Process a dependency, download if necessary
- * @param array dependency information from PEAR_Remote call
- * @param array packages that will be installed in this iteration
- * @return false|string|PEAR_Error
- * @access private
- * @todo Add test for relation 'lt'/'le' -> make sure that the dependency requested is
- * in fact lower than the required value. This will be very important for BC dependencies
- */
- function _processDependency($package, $info, $mywillinstall)
- {
- $state = $this->_preferredState;
- if (!isset($this->_options['alldeps']) && isset($info['optional']) &&
- $info['optional'] == 'yes') {
- // skip optional deps
- $this->log(0, "skipping Package '$package' optional dependency '$info[name]'");
- return false;
- }
- // {{{ get releases
- $releases = $this->_remote->call('package.info', $info['name'], 'releases', true);
- if (PEAR::isError($releases)) {
- return $releases;
- }
- if (!count($releases)) {
- if (!isset($this->_installed[strtolower($info['name'])])) {
- $this->pushError("Package '$package' dependency '$info[name]' ".
- "has no releases");
- }
- return false;
- }
- $found = false;
- $save = $releases;
- while(count($releases) && !$found) {
- if (!empty($state) && $state != 'any') {
- list($release_version, $release) = each($releases);
- if ($state != $release['state'] &&
- !in_array($release['state'], $this->betterStates($state)))
- {
- // drop this release - it ain't stable enough
- array_shift($releases);
- } else {
- $found = true;
- }
- } else {
- $found = true;
- }
- }
- if (!count($releases) && !$found) {
- $get = array();
- foreach($save as $release) {
- $get = array_merge($get,
- $this->betterStates($release['state'], true));
- }
- $savestate = array_shift($get);
- $this->pushError( "Release for '$package' dependency '$info[name]' " .
- "has state '$savestate', requires '$state'");
- return 0;
- }
- if (in_array(strtolower($info['name']), $this->_toDownload) ||
- isset($mywillinstall[strtolower($info['name'])])) {
- // skip upgrade check for packages we will install
- return false;
- }
- if (!isset($this->_installed[strtolower($info['name'])])) {
- // check to see if we can install the specific version required
- if ($info['rel'] == 'eq') {
- return $info['name'] . '-' . $info['version'];
- }
- // skip upgrade check for packages we don't have installed
- return $info['name'];
- }
- // }}}
-
- // {{{ see if a dependency must be upgraded
- $inst_version = $this->_registry->packageInfo($info['name'], 'version');
- if (!isset($info['version'])) {
- // this is a rel='has' dependency, check against latest
- if (version_compare($release_version, $inst_version, 'le')) {
- return false;
- } else {
- return $info['name'];
- }
- }
- if (version_compare($info['version'], $inst_version, 'le')) {
- // installed version is up-to-date
- return false;
- }
- return $info['name'];
- }
-
- // }}}
- // {{{ _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;
- case 'bytesread':
- static $bytes;
- if (empty($bytes)) {
- $bytes = 0;
- }
- if (!($bytes % 10240)) {
- $this->log(1, '.', false);
- }
- $bytes += $params;
- break;
- case 'start':
- $this->log(1, "Starting to download {$params[0]} (".number_format($params[1], 0, '', ',')." bytes)");
- break;
- }
- if (method_exists($this->ui, '_downloadCallback'))
- $this->ui->_downloadCallback($msg, $params);
- }
-
- // }}}
- // {{{ _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;
- }
- // }}}
- // {{{ pushError($errmsg, $code)
-
- /**
- * @param string
- * @param integer
- */
- function pushError($errmsg, $code = -1)
- {
- array_push($this->_errorStack, array($errmsg, $code));
- }
-
- // }}}
- // {{{ getErrorMsgs()
-
- function getErrorMsgs()
- {
- $msgs = array();
- $errs = $this->_errorStack;
- foreach ($errs as $err) {
- $msgs[] = $err[0];
- }
- $this->_errorStack = array();
- return $msgs;
- }
-
- // }}}
-}
-// }}}
-
-?>
diff --git a/inc/PEAR/ErrorStack.php b/inc/PEAR/ErrorStack.php
deleted file mode 100644
index da52f08d345..00000000000
--- a/inc/PEAR/ErrorStack.php
+++ /dev/null
@@ -1,981 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Gregory Beaver <cellog@php.net> |
-// | |
-// +----------------------------------------------------------------------+
-//
-// $Id: ErrorStack.php,v 1.7.2.5 2005/01/01 21:26:51 cellog Exp $
-
-/**
- * Error Stack Implementation
- *
- * This is an incredibly simple implementation of a very complex error handling
- * facility. It contains the ability
- * to track multiple errors from multiple packages simultaneously. In addition,
- * it can track errors of many levels, save data along with the error, context
- * information such as the exact file, line number, class and function that
- * generated the error, and if necessary, it can raise a traditional PEAR_Error.
- * It has built-in support for PEAR::Log, to log errors as they occur
- *
- * Since version 0.2alpha, it is also possible to selectively ignore errors,
- * through the use of an error callback, see {@link pushCallback()}
- *
- * Since version 0.3alpha, it is possible to specify the exception class
- * returned from {@link push()}
- *
- * Since version PEAR1.3.2, ErrorStack no longer instantiates an exception class. This can
- * still be done quite handily in an error callback or by manipulating the returned array
- * @author Greg Beaver <cellog@php.net>
- * @version PEAR1.3.2 (beta)
- * @package PEAR_ErrorStack
- * @category Debugging
- * @license http://www.php.net/license/3_0.txt PHP License v3.0
- */
-
-/**
- * Singleton storage
- *
- * Format:
- * <pre>
- * array(
- * 'package1' => PEAR_ErrorStack object,
- * 'package2' => PEAR_ErrorStack object,
- * ...
- * )
- * </pre>
- * @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:
- * <code>
- * // global error stack
- * $global_stack = &PEAR_ErrorStack::singleton('MyPackage');
- * // local error stack
- * $local_stack = new PEAR_ErrorStack('MyPackage');
- * </code>
- * @copyright 2004 Gregory Beaver
- * @package PEAR_ErrorStack
- * @license http://www.php.net/license/3_0.txt PHP License
- */
-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 PEAR_ErrorStack($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
- * @static
- * @return PEAR_ErrorStack
- */
- 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);
- }
- return $GLOBALS['_PEAR_ERRORSTACK_SINGLETON'][$package] =
- &new $stackClass($package, $msgCallback, $contextCallback, $throwPEAR_Error);
- }
-
- /**
- * 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 '<br />';
- } 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
- * @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
- * @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
- * @static
- */
- function staticPushCallback($cb)
- {
- array_push($GLOBALS['_PEAR_ERRORSTACK_OVERRIDE_CALLBACK'], $cb);
- }
-
- /**
- * Remove a temporary overriding error callback
- * @see staticPushCallback()
- * @return array|string|false
- * @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|Exception
- * if compatibility mode is on, a PEAR_Error is also
- * thrown. If the class Exception exists, then one
- * is returned to allow code like:
- * <code>
- * throw ($stack->push(MY_ERROR_CODE, 'error', array('username' => 'grob')));
- * </code>
- *
- * The errorData property of the exception class will be set to the array
- * that would normally be returned. If a PEAR_Error is returned, the userinfo
- * property is set to the array
- *
- * Otherwise, an array is returned in this format:
- * <code>
- * array(
- * 'code' => $code,
- * 'params' => $params,
- * 'package' => $this->_package,
- * 'level' => $level,
- * 'time' => time(),
- * 'context' => $context,
- * 'message' => $msg,
- * //['repackage' => $err] repackaged error array/Exception class
- * );
- * </code>
- */
- 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,
- );
-
- // set up the error message, if necessary
- if ($this->_msgCallback) {
- $msg = call_user_func_array($this->_msgCallback,
- array(&$this, $err));
- $err['message'] = $msg;
- }
-
- if ($repackage) {
- $err['repackage'] = $repackage;
- }
- $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);
- $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|null|Exception
- * if compatibility mode is on, a PEAR_Error is also
- * thrown. If the class Exception exists, then one
- * is returned to allow code like:
- * <code>
- * throw ($stack->push(MY_ERROR_CODE, 'error', array('username' => 'grob')));
- * </code>
- * @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()
- {
- return @array_shift($this->_errors);
- }
-
- /**
- * 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
- * @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
- * @static
- * @return array
- */
- 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
- */
- 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()
- * @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+)\) : (.*?)$;', $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:
- *
- * <code>
- * $stack->push(ERROR_CODE, 'error', array(), 'server error 500');
- * </code>
- *
- * 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
- * @static
- * @return string
- */
- function getErrorMessage(&$stack, $err, $template = false)
- {
- if ($template) {
- $mainmsg = $template;
- } else {
- $mainmsg = $stack->getErrorMessageTemplate($err['code']);
- }
- $mainmsg = str_replace('%__msg%', $err['message'], $mainmsg);
- if (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:
- * <pre>
- * array(error code => 'message template',...)
- * </pre>
- *
- * 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'));
-?> \ No newline at end of file
diff --git a/inc/PEAR/Exception.php b/inc/PEAR/Exception.php
deleted file mode 100644
index c735c16b398..00000000000
--- a/inc/PEAR/Exception.php
+++ /dev/null
@@ -1,359 +0,0 @@
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4 foldmethod=marker: */
-// +----------------------------------------------------------------------+
-// | PEAR_Exception |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 2004 The PEAR Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Tomas V.V.Cox <cox@idecnet.com> |
-// | Hans Lellelid <hans@velum.net> |
-// | Bertrand Mansion <bmansion@mamasam.com> |
-// | Greg Beaver <cellog@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Exception.php,v 1.4.2.2 2004/12/31 19:01:52 cellog Exp $
-
-
-/**
- * Base PEAR_Exception Class
- *
- * WARNING: This code should be considered stable, but the API is
- * subject to immediate and drastic change, so API stability is
- * at best alpha
- *
- * 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
- *
- * <code>
- * 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;
- * }
- * </code>
- *
- * @since PHP 5
- * @package PEAR
- * @version $Revision: 1.4.2.2 $
- * @author Tomas V.V.Cox <cox@idecnet.com>
- * @author Hans Lellelid <hans@velum.net>
- * @author Bertrand Mansion <bmansion@mamasam.com>
- *
- */
-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, array $causes);
- * PEAR_Exception(string $message, array $causes, int $code);
- */
- public function __construct($message, $p2 = null, $p3 = null)
- {
- if (is_int($p2)) {
- $code = $p2;
- $this->cause = null;
- } elseif ($p2 instanceof Exception || is_array($p2)) {
- $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();
- }
-
- /**
- * @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()
- */
- public static function addObserver($callback, $label = 'default')
- {
- self::$_observers[$label] = $callback;
- }
-
- public static function removeObserver($label = 'default')
- {
- unset(self::$_observers[$label]);
- }
-
- /**
- * @return int unique identifier for an observer
- */
- public static function getUniqueId()
- {
- return self::$_uniqueid++;
- }
-
- private 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:
- * <pre>
- * array('name' => $name, 'context' => array(...))
- * </pre>
- * @return array
- */
- public function getErrorData()
- {
- return array();
- }
-
- /**
- * Returns the exception that caused this exception to be thrown
- * @access public
- * @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
- */
- 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'];
- }
- }
- if ($this->cause instanceof PEAR_Exception) {
- $this->cause->getCauseMessage($causes);
- }
- if (is_array($this->cause)) {
- foreach ($this->cause as $cause) {
- if ($cause instanceof PEAR_Exception) {
- $cause->getCauseMessage($causes);
- } 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',
- );
- }
- }
- }
- }
-
- 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;
- }
-
- public function getErrorClass()
- {
- $trace = $this->getTraceSafe();
- return $trace[0]['class'];
- }
-
- public function getErrorMethod()
- {
- $trace = $this->getTraceSafe();
- return $trace[0]['function'];
- }
-
- public function __toString()
- {
- if (isset($_SERVER['REQUEST_URI'])) {
- return $this->toHtml();
- }
- return $this->toText();
- }
-
- public function toHtml()
- {
- $trace = $this->getTraceSafe();
- $causes = array();
- $this->getCauseMessage($causes);
- $html = '<table border="1" cellspacing="0">' . "\n";
- foreach ($causes as $i => $cause) {
- $html .= '<tr><td colspan="3" bgcolor="#ff9999">'
- . str_repeat('-', $i) . ' <b>' . $cause['class'] . '</b>: '
- . htmlspecialchars($cause['message']) . ' in <b>' . $cause['file'] . '</b> '
- . 'on line <b>' . $cause['line'] . '</b>'
- . "</td></tr>\n";
- }
- $html .= '<tr><td colspan="3" bgcolor="#aaaaaa" align="center"><b>Exception trace</b></td></tr>' . "\n"
- . '<tr><td align="center" bgcolor="#cccccc" width="20"><b>#</b></td>'
- . '<td align="center" bgcolor="#cccccc"><b>Function</b></td>'
- . '<td align="center" bgcolor="#cccccc"><b>Location</b></td></tr>' . "\n";
-
- foreach ($trace as $k => $v) {
- $html .= '<tr><td align="center">' . $k . '</td>'
- . '<td>';
- 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';
- elseif (is_array($arg)) $args[] = 'Array';
- elseif (is_object($arg)) $args[] = 'Object('.get_class($arg).')';
- elseif (is_bool($arg)) $args[] = $arg ? 'true' : 'false';
- elseif (is_int($arg) || is_double($arg)) $args[] = $arg;
- else {
- $arg = (string)$arg;
- $str = htmlspecialchars(substr($arg, 0, 16));
- if (strlen($arg) > 16) $str .= '&hellip;';
- $args[] = "'" . $str . "'";
- }
- }
- }
- $html .= '(' . implode(', ',$args) . ')'
- . '</td>'
- . '<td>' . $v['file'] . ':' . $v['line'] . '</td></tr>' . "\n";
- }
- $html .= '<tr><td align="center">' . ($k+1) . '</td>'
- . '<td>{main}</td>'
- . '<td>&nbsp;</td></tr>' . "\n"
- . '</table>';
- return $html;
- }
-
- 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();
- }
-}
-
-?> \ No newline at end of file
diff --git a/inc/PEAR/Frontend/CLI.php b/inc/PEAR/Frontend/CLI.php
deleted file mode 100644
index 832ddf09b3f..00000000000
--- a/inc/PEAR/Frontend/CLI.php
+++ /dev/null
@@ -1,509 +0,0 @@
-<?php
-/*
- +----------------------------------------------------------------------+
- | PHP Version 5 |
- +----------------------------------------------------------------------+
- | Copyright (c) 1997-2004 The PHP Group |
- +----------------------------------------------------------------------+
- | This source file is subject to version 3.0 of the PHP license, |
- | that is bundled with this package in the file LICENSE, and is |
- | available through the world-wide-web at the following url: |
- | http://www.php.net/license/3_0.txt. |
- | If you did not receive a copy of the PHP license and are unable to |
- | obtain it through the world-wide-web, please send a note to |
- | license@php.net so we can mail you a copy immediately. |
- +----------------------------------------------------------------------+
- | Author: Stig Sæther Bakken <ssb@php.net> |
- +----------------------------------------------------------------------+
-
- $Id: CLI.php,v 1.41 2004/02/17 05:49:16 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 (function_exists('posix_isatty') && !posix_isatty(1)) {
- // output is being redirected to a file or through a pipe
- } elseif ($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)
- {
- 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)
-
- /**
- * @param object PEAR_Error object
- */
- function displayError($eobj)
- {
- return $this->_displayLine($eobj->getMessage());
- }
-
- // }}}
- // {{{ displayFatalError(eobj)
-
- /**
- * @param object PEAR_Error object
- */
- 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())
- {
- $result = array();
- if (is_array($prompts)) {
- $fp = fopen("php://stdin", "r");
- foreach ($prompts as $key => $prompt) {
- $type = $types[$key];
- $default = @$defaults[$key];
- if ($type == 'password') {
- system('stty -echo');
- }
- 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", 0);
- }
- 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]);
- if (!is_array($rowparams)) {
- $rowparams = array();
- }
- if (!is_array($colparams)) {
- $colparams = array();
- }
- $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;
- }
- if (!$border) {
- $rowtext = rtrim($rowtext);
- }
- $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] = "<not set>";
- }
- $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' => 30),
- 1 => array('wrap' => 20),
- 2 => array('wrap' => 35)
- );
- } else {
- $opts = null;
- }
- 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, $append_crlf = true)
- {
- if ($append_crlf) {
- return $this->_displayLine($text);
- }
- return $this->_display($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/inc/PEAR/Installer.php b/inc/PEAR/Installer.php
deleted file mode 100644
index 31e2cff81ee..00000000000
--- a/inc/PEAR/Installer.php
+++ /dev/null
@@ -1,1068 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stig Bakken <ssb@php.net> |
-// | Tomas V.V.Cox <cox@idecnet.com> |
-// | Martin Jansen <mj@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Installer.php,v 1.150.2.2 2005/02/17 17:47:55 cellog Exp $
-
-require_once 'PEAR/Downloader.php';
-
-/**
- * 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 <ssb@php.net>
- * @author Martin Jansen <mj@php.net>
- * @author Greg Beaver <cellog@php.net>
- */
-class PEAR_Installer extends PEAR_Downloader
-{
- // {{{ 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, does not 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()
-
- /**
- * @param string filename
- * @param array attributes from <file> tag in package.xml
- * @param string path to install the file in
- * @param array options from command-line
- * @access private
- */
- function _installFile($file, $atts, $tmp_path, $options)
- {
- // {{{ return if this file is meant for another platform
- static $os;
- if (isset($atts['platform'])) {
- if (empty($os)) {
- include_once "OS/Guess.php";
- $os = new OS_Guess();
- }
- if (strlen($atts['platform']) && $atts['platform']{0} == '!') {
- $negate = true;
- $platform = substr($atts['platform'], 1);
- } else {
- $negate = false;
- $platform = $atts['platform'];
- }
- if ((bool) $os->matchSignature($platform) === $negate) {
- $this->log(3, "skipped $file (meant for $atts[platform], we are ".$os->getSignature().")");
- return PEAR_INSTALLER_SKIPPED;
- }
- }
- // }}}
-
- // {{{ assemble the destination paths
- 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");
- }
- $save_destdir = $dest_dir;
- 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 (!file_exists($orig_file)) {
- return $this->raiseError("file does not exist",
- PEAR_INSTALLER_FAILED);
- }
- 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 {
- // {{{ file with replacements
- if (!file_exists($orig_file)) {
- return $this->raiseError("file does not exist",
- PEAR_INSTALLER_FAILED);
- }
- $fp = fopen($orig_file, "r");
- $contents = fread($fp, filesize($orig_file));
- fclose($fp);
- if (isset($atts['md5sum'])) {
- $md5sum = md5($contents);
- }
- $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'])) {
- 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']);
- if (is_null($to)) {
- $this->log(0, "invalid pear-config replacement: $a[to]");
- continue;
- }
- } elseif ($a['type'] == 'package-info') {
- if (isset($this->pkginfo[$a['to']]) && is_string($this->pkginfo[$a['to']])) {
- $to = $this->pkginfo[$a['to']];
- } else {
- $this->log(0, "invalid package-info replacement: $a[to]");
- continue;
- }
- }
- if (!is_null($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, "wb");
- 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);
- // }}}
- }
- // {{{ check the md5
- if (isset($md5sum)) {
- if (strtolower($md5sum) == strtolower($atts['md5sum'])) {
- $this->log(2, "md5sum ok: $final_dest_file");
- } else {
- if (empty($options['force'])) {
- // delete the file
- @unlink($dest_file);
- return $this->raiseError("bad md5sum for file $final_dest_file",
- PEAR_INSTALLER_FAILED);
- } else {
- $this->log(0, "warning : bad md5sum for file $final_dest_file");
- }
- }
- }
- // }}}
- // {{{ set file permissions
- 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));
- // Store the full path where the file was installed for easy unistall
- $this->addFileOperation("installed_as", array($file, $installed_as,
- $save_destdir, dirname(substr($dest_file, strlen($save_destdir)))));
-
- //$this->log(2, "installed: $dest_file");
- return PEAR_INSTALLER_OK;
- }
-
- // }}}
- // {{{ addFileOperation()
-
- /**
- * Add a file operation to the current file transaction.
- *
- * @see startFileTransaction()
- * @var string $type This can be one of:
- * - rename: rename a file ($data has 2 values)
- * - chmod: change permissions on a file ($data has 2 values)
- * - delete: delete a file ($data has 1 value)
- * - rmdir: delete a directory if empty ($data has 1 value)
- * - installed_as: mark a file as installed ($data has 4 values).
- * @var array $data For all file operations, this array must contain the
- * full path to the file or directory that is being operated on. For
- * the rename command, the first parameter must be the file to rename,
- * the second its new name.
- *
- * The installed_as operation contains 4 elements in this order:
- * 1. Filename as listed in the filelist element from package.xml
- * 2. Full path to the installed file
- * 3. Full path from the php_dir configuration variable used in this
- * installation
- * 4. Relative path from the php_dir that this file is installed in
- */
- function addFileOperation($type, $data)
- {
- if (!is_array($data)) {
- return $this->raiseError('Internal Error: $data in addFileOperation'
- . ' must be an array, was ' . gettype($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':
- if (!file_exists($data[0])) {
- $errors[] = "cannot rename file $data[0], doesn't exist";
- }
- // 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] " . decoct($data[0]);
- }
- break;
- case 'delete':
- if (!file_exists($data[0])) {
- $this->log(2, "warning: file $data[0] doesn't exist, can't be deleted");
- }
- // 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':
- @unlink($data[1]);
- @rename($data[0], $data[1]);
- $this->log(3, "+ mv $data[0] $data[1]");
- break;
- case 'chmod':
- @chmod($data[1], $data[0]);
- $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;
- case 'installed_as':
- $this->pkginfo['filelist'][$data[0]]['installed_as'] = $data[1];
- if (!isset($this->pkginfo['filelist']['dirtree'][dirname($data[1])])) {
- $this->pkginfo['filelist']['dirtree'][dirname($data[1])] = true;
- while(!empty($data[3]) && $data[3] != '/' && $data[3] != '\\'
- && $data[3] != '.') {
- $this->pkginfo['filelist']['dirtree']
- [$this->_prependPath($data[3], $data[2])] = true;
- $data[3] = dirname($data[3]);
- }
- }
- break;
- }
- }
- // }}}
- $this->log(2, "successfully committed $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;
- case 'installed_as':
- if (isset($this->pkginfo['filelist'])) {
- unset($this->pkginfo['filelist'][$data[0]]['installed_as']);
- }
- if (isset($this->pkginfo['filelist']['dirtree'][dirname($data[1])])) {
- unset($this->pkginfo['filelist']['dirtree'][dirname($data[1])]);
- while(!empty($data[3]) && $data[3] != '/' && $data[3] != '\\'
- && $data[3] != '.') {
- unset($this->pkginfo['filelist']['dirtree']
- [$this->_prependPath($data[3], $data[2])]);
- $data[3] = dirname($data[3]);
- }
- }
- if (isset($this->pkginfo['filelist']['dirtree'])
- && !count($this->pkginfo['filelist']['dirtree'])) {
- unset($this->pkginfo['filelist']['dirtree']);
- }
- break;
- }
- }
- $this->file_operations = array();
- }
-
- // }}}
- // {{{ mkDirHier($dir)
-
- function mkDirHier($dir)
- {
- $this->addFileOperation('mkdir', array($dir));
- return parent::mkDirHier($dir);
- }
-
- // }}}
- // {{{ download()
-
- /**
- * Download any files and their dependencies, if necessary
- *
- * @param array a mixed list of package names, local files, or package.xml
- * @param PEAR_Config
- * @param array options from the command line
- * @param array this is the array that will be populated with packages to
- * install. Format of each entry:
- *
- * <code>
- * array('pkg' => 'package_name', 'file' => '/path/to/local/file',
- * 'info' => array() // parsed package.xml
- * );
- * </code>
- * @param array this will be populated with any error messages
- * @param false private recursion variable
- * @param false private recursion variable
- * @param false private recursion variable
- * @deprecated in favor of PEAR_Downloader
- */
- function download($packages, $options, &$config, &$installpackages,
- &$errors, $installed = false, $willinstall = false, $state = false)
- {
- // trickiness: initialize here
- parent::PEAR_Downloader($this->ui, $options, $config);
- $ret = parent::download($packages);
- $errors = $this->getErrorMsgs();
- $installpackages = $this->getDownloadedPackages();
- trigger_error("PEAR Warning: PEAR_Installer::download() is deprecated " .
- "in favor of PEAR_Downloader class", E_USER_WARNING);
- return $ret;
- }
-
- // }}}
- // {{{ install()
-
- /**
- * Installs the files within the package file specified.
- *
- * @param string $pkgfile path to the package file
- * @param array $options
- * recognized options:
- * - installroot : optional prefix directory for installation
- * - force : force installation
- * - register-only : update registry but don't install files
- * - upgrade : upgrade existing install
- * - soft : fail silently
- * - nodeps : ignore dependency conflicts/missing dependencies
- * - alldeps : install all dependencies
- * - onlyreqdeps : install only required dependencies
- *
- * @return array|PEAR_Error package info if successful
- */
-
- function install($pkgfile, $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);
- }
- $php_dir = $this->_prependPath($php_dir, $options['installroot']);
- $this->installroot = $options['installroot'];
- } else {
- $this->installroot = '';
- }
- $this->registry = &new PEAR_Registry($php_dir);
- // ==> XXX should be removed later on
- $flag_old_format = false;
-
- if (substr($pkgfile, -4) == '.xml') {
- $descfile = $pkgfile;
- } else {
- // {{{ Decompress pack in tmp dir -------------------------------------
-
- // To allow relative package file names
- $pkgfile = realpath($pkgfile);
-
- if (PEAR::isError($tmpdir = System::mktemp('-d'))) {
- return $tmpdir;
- }
- $this->log(3, '+ 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'])) {
- $dep_errors = '';
- $error = $this->checkDeps($pkginfo, $dep_errors);
- if ($error == true) {
- if (empty($options['soft'])) {
- $this->log(0, substr($dep_errors, 1));
- }
- return $this->raiseError("$pkgname: Dependencies failed");
- } else if (!empty($dep_errors)) {
- // Print optional dependencies
- if (empty($options['soft'])) {
- $this->log(0, $dep_errors);
- }
- }
- }
- // }}}
-
- // {{{ checks to do when not in "force" mode
- if (empty($options['force'])) {
- $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);
- }
- }
- }
- // }}}
-
- $this->startFileTransaction();
-
- 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 {
- if ($this->registry->packageExists($pkgname)) {
- $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);
- }
-
- $tmp_path = dirname($descfile);
- if (substr($pkgfile, -4) != '.xml') {
- $tmp_path .= DIRECTORY_SEPARATOR . $pkgname . '-' . $pkginfo['version'];
- }
-
- // ==> XXX This part should be removed later on
- if ($flag_old_format) {
- $tmp_path = dirname($descfile);
- }
- // <== XXX This part should be removed later on
-
- // {{{ install files
- foreach ($pkginfo['filelist'] as $file => $atts) {
- $this->expectError(PEAR_INSTALLER_FAILED);
- $res = $this->_installFile($file, $atts, $tmp_path, $options);
- $this->popExpect();
- if (PEAR::isError($res)) {
- if (empty($options['ignore-errors'])) {
- $this->rollbackFileTransaction();
- if ($res->getMessage() == "file does not exist") {
- $this->raiseError("file $file in package.xml does not exist");
- }
- 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]);
- }
- }
- // }}}
-
- // {{{ compile and install source files
- 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;
- }
- $this->log(1, "\nBuild process completed successfully");
- foreach ($built as $ext) {
- $bn = basename($ext['file']);
- list($_ext_name, $_ext_suff) = explode('.', $bn);
- if ($_ext_suff == '.so' || $_ext_suff == '.dll') {
- if (extension_loaded($_ext_name)) {
- $this->raiseError("Extension '$_ext_name' already loaded. " .
- 'Please unload it in your php.ini file ' .
- 'prior to install or upgrade');
- }
- $role = 'ext';
- } else {
- $role = 'src';
- }
- $dest = $ext['dest'];
- $this->log(1, "Installing '$ext[file]'");
- $copyto = $this->_prependPath($dest, $this->installroot);
- $copydir = dirname($copyto);
- if (!@is_dir($copydir)) {
- if (!$this->mkDirHier($copydir)) {
- return $this->raiseError("failed to mkdir $copydir",
- PEAR_INSTALLER_FAILED);
- }
- $this->log(3, "+ mkdir $copydir");
- }
- if (!@copy($ext['file'], $copyto)) {
- return $this->raiseError("failed to write $copyto", PEAR_INSTALLER_FAILED);
- }
- $this->log(3, "+ cp $ext[file] $copyto");
- if (!OS_WINDOWS) {
- $mode = 0666 & ~(int)octdec($this->config->get('umask'));
- $this->addFileOperation('chmod', array($mode, $copyto));
- if (!@chmod($copyto, $mode)) {
- $this->log(0, "failed to change mode of $copyto");
- }
- }
- $this->addFileOperation('rename', array($ext['file'], $copyto));
-
- $pkginfo['filelist'][$bn] = array(
- 'role' => $role,
- '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);
- }
- // }}}
-
- $ret = false;
- // {{{ 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 {
- // new: upgrade installs a package if it isn't installed
- if (!$this->registry->packageExists($pkgname)) {
- $ret = $this->registry->addPackage($pkgname, $pkginfo);
- } else {
- $ret = $this->registry->updatePackage($pkgname, $pkginfo, false);
- }
- }
- if (!$ret) {
- return $this->raiseError("Adding package $pkgname to registry failed");
- }
- // }}}
- return $pkginfo;
- }
-
- // }}}
- // {{{ uninstall()
-
- /**
- * Uninstall a package
- *
- * This method removes all files installed by the application, and then
- * removes any empty directories.
- * @param string package name
- * @param array Command-line options. Possibilities include:
- *
- * - installroot: base installation dir, if not the default
- * - nodeps: do not process dependencies of other packages to ensure
- * uninstallation does not break things
- */
- 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);
- $filelist = $this->registry->packageInfo($package, 'filelist');
- if ($filelist == null) {
- return $this->raiseError("$package not installed");
- }
- if (empty($options['nodeps'])) {
- $depchecker = &new PEAR_Dependency($this->registry);
- $error = $depchecker->checkPackageUninstall($errors, $warning, $package);
- if ($error) {
- return $this->raiseError($errors . 'uninstall failed');
- }
- if ($warning) {
- $this->log(0, $warning);
- }
- }
- // {{{ Delete the files
- $this->startFileTransaction();
- if (PEAR::isError($err = $this->_deletePackageFiles($package))) {
- $this->rollbackFileTransaction();
- return $this->raiseError($err);
- }
- if (!$this->commitFileTransaction()) {
- $this->rollbackFileTransaction();
- return $this->raiseError("uninstall failed");
- } else {
- $this->startFileTransaction();
- if (!isset($filelist['dirtree']) || !count($filelist['dirtree'])) {
- return $this->registry->deletePackage($package);
- }
- // attempt to delete empty directories
- uksort($filelist['dirtree'], array($this, '_sortDirs'));
- foreach($filelist['dirtree'] as $dir => $notused) {
- $this->addFileOperation('rmdir', array($dir));
- }
- if (!$this->commitFileTransaction()) {
- $this->rollbackFileTransaction();
- }
- }
- // }}}
-
- // Register that the package is no longer installed
- return $this->registry->deletePackage($package);
- }
-
- // }}}
- // {{{ _sortDirs()
- function _sortDirs($a, $b)
- {
- if (strnatcmp($a, $b) == -1) return 1;
- if (strnatcmp($a, $b) == 1) return -1;
- return 0;
- }
-
- // }}}
- // {{{ checkDeps()
-
- /**
- * Check if the package meets all dependencies
- *
- * @param array Package information (passed by reference)
- * @param string Error message (passed by reference)
- * @return boolean False when no error occured, otherwise true
- */
- function checkDeps(&$pkginfo, &$errors)
- {
- if (empty($this->registry)) {
- $this->registry = &new PEAR_Registry($this->config->get('php_dir'));
- }
- $depchecker = &new PEAR_Dependency($this->registry);
- $error = $errors = '';
- $failed_deps = $optional_deps = array();
- if (is_array($pkginfo['release_deps'])) {
- foreach($pkginfo['release_deps'] as $dep) {
- $code = $depchecker->callCheckMethod($error, $dep);
- if ($code) {
- if (isset($dep['optional']) && $dep['optional'] == 'yes') {
- $optional_deps[] = array($dep, $code, $error);
- } else {
- $failed_deps[] = array($dep, $code, $error);
- }
- }
- }
- // {{{ failed dependencies
- $n = count($failed_deps);
- if ($n > 0) {
- 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 true;
- }
- // }}}
-
- // {{{ optional dependencies
- $count_optional = count($optional_deps);
- if ($count_optional > 0) {
- $errors = "Optional dependencies:";
-
- for ($i = 0; $i < $count_optional; $i++) {
- if (isset($optional_deps[$i]['type'])) {
- $type = $optional_deps[$i]['type'];
- } else {
- $type = 'pkg';
- }
- switch ($optional_deps[$i][1]) {
- case PEAR_DEPENDENCY_MISSING:
- case PEAR_DEPENDENCY_UPGRADE_MINOR:
- default:
- $errors .= "\n" . $optional_deps[$i][2];
- break;
- }
- }
- return false;
- }
- // }}}
- }
- return false;
- }
-
- // }}}
- // {{{ _buildCallback()
-
- function _buildCallback($what, $data)
- {
- if (($what == 'cmdoutput' && $this->debug > 1) ||
- ($what == 'output' && $this->debug > 0)) {
- $this->ui->outputData(rtrim($data), 'build');
- }
- }
-
- // }}}
-}
-
-// {{{ md5_file() utility function
-if (!function_exists("md5_file")) {
- function md5_file($filename) {
- $fp = fopen($filename, "r");
- if (!$fp) return null;
- $contents = fread($fp, filesize($filename));
- fclose($fp);
- return md5($contents);
- }
-}
-// }}}
-
-?>
diff --git a/inc/PEAR/Packager.php b/inc/PEAR/Packager.php
deleted file mode 100644
index 3ed209be8b2..00000000000
--- a/inc/PEAR/Packager.php
+++ /dev/null
@@ -1,165 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stig Bakken <ssb@php.net> |
-// | Tomas V.V.Cox <cox@idecnet.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Packager.php,v 1.53 2004/06/13 14:06:01 pajoye 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 <ssb@php.net>
- */
-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)
- {
- // {{{ validate supplied package.xml file
- if (empty($pkgfile)) {
- $pkgfile = 'package.xml';
- }
- // $this->pkginfo gets populated inside
- $pkginfo = $this->infoFromDescriptionFile($pkgfile);
- if (PEAR::isError($pkginfo)) {
- return $this->raiseError($pkginfo);
- }
-
- $pkgdir = dirname(realpath($pkgfile));
- $pkgfile = basename($pkgfile);
-
- $errors = $warnings = array();
- $this->validatePackageInfo($pkginfo, $errors, $warnings, $pkgdir);
- foreach ($warnings as $w) {
- $this->log(1, "Warning: $w");
- }
- foreach ($errors as $e) {
- $this->log(0, "Error: $e");
- }
- if (sizeof($errors) > 0) {
- return $this->raiseError('Errors in package');
- }
- // }}}
-
- $pkgver = $pkginfo['package'] . '-' . $pkginfo['version'];
-
- // {{{ Create the package file list
- $filelist = array();
- $i = 0;
-
- foreach ($pkginfo['filelist'] as $fname => $atts) {
- $file = $pkgdir . DIRECTORY_SEPARATOR . $fname;
- if (!file_exists($file)) {
- return $this->raiseError("File does not exist: $fname");
- } else {
- $filelist[$i++] = $file;
- if (empty($pkginfo['filelist'][$fname]['md5sum'])) {
- $md5sum = md5_file($file);
- $pkginfo['filelist'][$fname]['md5sum'] = $md5sum;
- }
- $this->log(2, "Adding file $fname");
- }
- }
- // }}}
-
- // {{{ regenerate package.xml
- $new_xml = $this->xmlFromInfo($pkginfo);
- if (PEAR::isError($new_xml)) {
- return $this->raiseError($new_xml);
- }
- if (!($tmpdir = System::mktemp(array('-d')))) {
- return $this->raiseError("PEAR_Packager: mktemp failed");
- }
- $newpkgfile = $tmpdir . DIRECTORY_SEPARATOR . 'package.xml';
- $np = @fopen($newpkgfile, 'wb');
- if (!$np) {
- 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 = getcwd() . 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(array($newpkgfile), '', $tmpdir);
- if (PEAR::isError($ok)) {
- return $this->raiseError($ok);
- } elseif (!$ok) {
- return $this->raiseError('PEAR_Packager: tarball creation failed');
- }
- // ----- Add the content of the package
- if (!$tar->addModify($filelist, $pkgver, $pkgdir)) {
- return $this->raiseError('PEAR_Packager: tarball creation failed');
- }
- $this->log(1, "Package $dest_package done");
- if (file_exists("$pkgdir/CVS/Root")) {
- $cvsversion = preg_replace('/[^a-z0-9]/i', '_', $pkginfo['version']);
- $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)");
- }
- // }}}
-
- return $dest_package;
- }
-
- // }}}
-}
-
-// {{{ md5_file() utility function
-if (!function_exists('md5_file')) {
- function md5_file($file) {
- if (!$fd = @fopen($file, 'r')) {
- return false;
- }
- $md5 = md5(fread($fd, filesize($file)));
- fclose($fd);
- return $md5;
- }
-}
-// }}}
-
-?>
diff --git a/inc/PEAR/Registry.php b/inc/PEAR/Registry.php
deleted file mode 100644
index f2510a38f15..00000000000
--- a/inc/PEAR/Registry.php
+++ /dev/null
@@ -1,538 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Stig Bakken <ssb@php.net> |
-// | Tomas V.V.Cox <cox@idecnet.com> |
-// | |
-// +----------------------------------------------------------------------+
-//
-// $Id: Registry.php,v 1.50.4.3 2004/10/26 19:19:56 cellog 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';
-
- // XXX Compatibility code should be removed in the future
- // rename all registry files if any to lowercase
- if (!OS_WINDOWS && $handle = @opendir($this->statedir)) {
- $dest = $this->statedir . DIRECTORY_SEPARATOR;
- while (false !== ($file = readdir($handle))) {
- if (preg_match('/^.*[A-Z].*\.reg$/', $file)) {
- rename($dest . $file, $dest . strtolower($file));
- }
- }
- closedir($handle);
- }
- 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(array('-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 . DIRECTORY_SEPARATOR . strtolower($package) . '.reg';
- }
-
- // }}}
- // {{{ _openPackageFile()
-
- function _openPackageFile($package, $mode)
- {
- $this->_assertStateDir();
- $file = $this->_packageFileName($package);
- $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, 'wb');
- 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);
- $rt = get_magic_quotes_runtime();
- set_magic_quotes_runtime(0);
- $data = fread($fp, $fsize);
- set_magic_quotes_runtime($rt);
- 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 (!eregi('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 || $mode === LOCK_UN) {
- if (@!is_file($this->lockfile)) {
- touch($this->lockfile);
- }
- $open_mode = 'r';
- }
-
- if (!is_resource($this->lock_fp)) {
- $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);
- if (is_resource($this->lock_fp)) {
- fclose($this->lock_fp);
- }
- $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;
- }
- $rt = get_magic_quotes_runtime();
- set_magic_quotes_runtime(0);
- $data = fread($fp, filesize($this->_packageFileName($package)));
- set_magic_quotes_runtime($rt);
- $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, 'wb');
- 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);
- $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 '';
- }
-
- // }}}
-
-}
-
-?>
diff --git a/inc/PEAR/Remote.php b/inc/PEAR/Remote.php
deleted file mode 100644
index 7b1e314f903..00000000000
--- a/inc/PEAR/Remote.php
+++ /dev/null
@@ -1,394 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Stig Bakken <ssb@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Remote.php,v 1.50 2004/06/08 18:03:46 cellog 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 = md5(serialize($args));
- $cachedir = $this->config->get('cache_dir');
- $filename = $cachedir . DIRECTORY_SEPARATOR . 'xmlrpc_cache_' . $id;
- if (!file_exists($filename)) {
- return null;
- };
-
- $fp = fopen($filename, 'rb');
- if (!$fp) {
- 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 = md5(serialize($args));
- $cachedir = $this->config->get('cache_dir');
- if (!file_exists($cachedir)) {
- System::mkdir(array('-p', $cachedir));
- }
- $filename = $cachedir.'/xmlrpc_cache_'.$id;
-
- $fp = @fopen($filename, "wb");
- if ($fp) {
- 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 = @urldecode(@$proxy['user']);
- $proxy_pass = @urldecode(@$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;
- if ($http_proxy = $this->config->get('http_proxy')) {
- $proxy = parse_url($http_proxy);
- $proxy_host = $proxy_port = $proxy_user = $proxy_pass = '';
- $proxy_host = @$proxy['host'];
- $proxy_port = @$proxy['port'];
- $proxy_user = @urldecode(@$proxy['user']);
- $proxy_pass = @urldecode(@$proxy['pass']);
- $fp = @fsockopen($proxy_host, $proxy_port);
- $use_proxy = true;
- } else {
- $use_proxy = false;
- $fp = @fsockopen($server_host, $server_port);
- }
- if (!$fp && $http_proxy) {
- return $this->raiseError("PEAR_Remote::call: fsockopen(`$proxy_host', $proxy_port) failed");
- } elseif (!$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 ($use_proxy && $proxy_host != '' && $proxy_user != '') {
- $req_headers .= 'Proxy-Authorization: Basic '
- .base64_encode($proxy_user.':'.$proxy_pass)
- ."\r\n";
- }
-
- if ($this->config->get('verbose') > 3) {
- print "XMLRPC REQUEST HEADERS:\n";
- var_dump($req_headers);
- print "XMLRPC REQUEST BODY:\n";
- var_dump($request);
- }
-
- if ($use_proxy && $proxy_host != '') {
- $post_string = "POST http://".$server_host;
- if ($proxy_port > '') {
- $post_string .= ':'.$server_port;
- }
- } else {
- $post_string = "POST ";
- }
-
- fwrite($fp, ($post_string."/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 && isset($ret[0])
- && 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;
- }
-
- // }}}
-
-}
-
-?>
diff --git a/inc/PEAR/RunTest.php b/inc/PEAR/RunTest.php
deleted file mode 100644
index 1aa02aab9df..00000000000
--- a/inc/PEAR/RunTest.php
+++ /dev/null
@@ -1,363 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Tomas V.V.Cox <cox@idecnet.com> |
-// | Greg Beaver <cellog@php.net> |
-// | |
-// +----------------------------------------------------------------------+
-//
-// $Id: RunTest.php,v 1.3.2.4 2005/02/17 17:47:55 cellog Exp $
-//
-
-/**
- * Simplified version of PHP's test suite
- * -- EXPERIMENTAL --
-
- Try it with:
-
- $ php -r 'include "../PEAR/RunTest.php"; $t=new PEAR_RunTest; $o=$t->run("./pear_system.phpt");print_r($o);'
-
-
-TODO:
-
-Actually finish the development and testing
-
- */
-
-require_once 'PEAR.php';
-require_once 'PEAR/Config.php';
-
-define('DETAILED', 1);
-putenv("PHP_PEAR_RUNTESTS=1");
-
-class PEAR_RunTest
-{
- var $_logger;
-
- /**
- * An object that supports the PEAR_Common->log() signature, or null
- * @param PEAR_Common|null
- */
- function PEAR_RunTest($logger = null)
- {
- $this->_logger = $logger;
- }
-
- //
- // Run an individual test case.
- //
-
- function run($file, $ini_settings = '')
- {
- $cwd = getcwd();
- $conf = &PEAR_Config::singleton();
- $php = $conf->get('php_bin');
- //var_dump($php);exit;
- global $log_format, $info_params, $ini_overwrites;
-
- $info_params = '';
- $log_format = 'LEOD';
-
- // Load the sections of the test file.
- $section_text = array(
- 'TEST' => '(unnamed test)',
- 'SKIPIF' => '',
- 'GET' => '',
- 'ARGS' => '',
- );
-
- if (!is_file($file) || !$fp = fopen($file, "r")) {
- return PEAR::raiseError("Cannot open test file: $file");
- }
-
- $section = '';
- while (!feof($fp)) {
- $line = fgets($fp);
-
- // Match the beginning of a section.
- if (ereg('^--([A-Z]+)--',$line,$r)) {
- $section = $r[1];
- $section_text[$section] = '';
- continue;
- }
-
- // Add to the section text.
- $section_text[$section] .= $line;
- }
- fclose($fp);
-
- $shortname = str_replace($cwd.'/', '', $file);
- $tested = trim($section_text['TEST'])." [$shortname]";
-
- $tmp = realpath(dirname($file));
- $tmp_skipif = $tmp . uniqid('/phpt.');
- $tmp_file = ereg_replace('\.phpt$','.php',$file);
- $tmp_post = $tmp . uniqid('/phpt.');
-
- @unlink($tmp_skipif);
- @unlink($tmp_file);
- @unlink($tmp_post);
-
- // unlink old test results
- @unlink(ereg_replace('\.phpt$','.diff',$file));
- @unlink(ereg_replace('\.phpt$','.log',$file));
- @unlink(ereg_replace('\.phpt$','.exp',$file));
- @unlink(ereg_replace('\.phpt$','.out',$file));
-
- // Check if test should be skipped.
- $info = '';
- $warn = false;
- if (array_key_exists('SKIPIF', $section_text)) {
- if (trim($section_text['SKIPIF'])) {
- $this->save_text($tmp_skipif, $section_text['SKIPIF']);
- //$extra = substr(PHP_OS, 0, 3) !== "WIN" ?
- // "unset REQUEST_METHOD;": "";
-
- //$output = `$extra $php $info_params -f $tmp_skipif`;
- $output = `$php $info_params -f $tmp_skipif`;
- unlink($tmp_skipif);
- if (eregi("^skip", trim($output))) {
- $skipreason = "SKIP $tested";
- $reason = (eregi("^skip[[:space:]]*(.+)\$", trim($output))) ? eregi_replace("^skip[[:space:]]*(.+)\$", "\\1", trim($output)) : FALSE;
- if ($reason) {
- $skipreason .= " (reason: $reason)";
- }
- $this->_logger->log(0, $skipreason);
- if (isset($old_php)) {
- $php = $old_php;
- }
- return 'SKIPPED';
- }
- if (eregi("^info", trim($output))) {
- $reason = (ereg("^info[[:space:]]*(.+)\$", trim($output))) ? ereg_replace("^info[[:space:]]*(.+)\$", "\\1", trim($output)) : FALSE;
- if ($reason) {
- $info = " (info: $reason)";
- }
- }
- if (eregi("^warn", trim($output))) {
- $reason = (ereg("^warn[[:space:]]*(.+)\$", trim($output))) ? ereg_replace("^warn[[:space:]]*(.+)\$", "\\1", trim($output)) : FALSE;
- if ($reason) {
- $warn = true; /* only if there is a reason */
- $info = " (warn: $reason)";
- }
- }
- }
- }
-
- // We've satisfied the preconditions - run the test!
- $this->save_text($tmp_file,$section_text['FILE']);
-
- $args = $section_text['ARGS'] ? ' -- '.$section_text['ARGS'] : '';
-
- $cmd = "$php$ini_settings -f $tmp_file$args 2>&1";
- if (isset($this->_logger)) {
- $this->_logger->log(2, 'Running command "' . $cmd . '"');
- }
-
- $savedir = getcwd(); // in case the test moves us around
- if (isset($section_text['RETURNS'])) {
- ob_start();
- system($cmd, $return_value);
- $out = ob_get_contents();
- ob_end_clean();
- @unlink($tmp_post);
- $section_text['RETURNS'] = (int) trim($section_text['RETURNS']);
- $returnfail = ($return_value != $section_text['RETURNS']);
- } else {
- $out = `$cmd`;
- $returnfail = false;
- }
- chdir($savedir);
- // Does the output match what is expected?
- $output = trim($out);
- $output = preg_replace('/\r\n/', "\n", $output);
-
- if (isset($section_text['EXPECTF']) || isset($section_text['EXPECTREGEX'])) {
- if (isset($section_text['EXPECTF'])) {
- $wanted = trim($section_text['EXPECTF']);
- } else {
- $wanted = trim($section_text['EXPECTREGEX']);
- }
- $wanted_re = preg_replace('/\r\n/',"\n",$wanted);
- if (isset($section_text['EXPECTF'])) {
- $wanted_re = preg_quote($wanted_re, '/');
- // Stick to basics
- $wanted_re = str_replace("%s", ".+?", $wanted_re); //not greedy
- $wanted_re = str_replace("%i", "[+\-]?[0-9]+", $wanted_re);
- $wanted_re = str_replace("%d", "[0-9]+", $wanted_re);
- $wanted_re = str_replace("%x", "[0-9a-fA-F]+", $wanted_re);
- $wanted_re = str_replace("%f", "[+\-]?\.?[0-9]+\.?[0-9]*(E-?[0-9]+)?", $wanted_re);
- $wanted_re = str_replace("%c", ".", $wanted_re);
- // %f allows two points "-.0.0" but that is the best *simple* expression
- }
- /* DEBUG YOUR REGEX HERE
- var_dump($wanted_re);
- print(str_repeat('=', 80) . "\n");
- var_dump($output);
- */
- if (!$returnfail && preg_match("/^$wanted_re\$/s", $output)) {
- @unlink($tmp_file);
- $this->_logger->log(0, "PASS $tested$info");
- if (isset($old_php)) {
- $php = $old_php;
- }
- return 'PASSED';
- }
-
- } else {
- $wanted = trim($section_text['EXPECT']);
- $wanted = preg_replace('/\r\n/',"\n",$wanted);
- // compare and leave on success
- $ok = (0 == strcmp($output,$wanted));
- if (!$returnfail && $ok) {
- @unlink($tmp_file);
- $this->_logger->log(0, "PASS $tested$info");
- if (isset($old_php)) {
- $php = $old_php;
- }
- return 'PASSED';
- }
- }
-
- // Test failed so we need to report details.
- if ($warn) {
- $this->_logger->log(0, "WARN $tested$info");
- } else {
- $this->_logger->log(0, "FAIL $tested$info");
- }
-
- if (isset($section_text['RETURNS'])) {
- $GLOBALS['__PHP_FAILED_TESTS__'][] = array(
- 'name' => $file,
- 'test_name' => $tested,
- 'output' => ereg_replace('\.phpt$','.log', $file),
- 'diff' => ereg_replace('\.phpt$','.diff', $file),
- 'info' => $info,
- 'return' => $return_value
- );
- } else {
- $GLOBALS['__PHP_FAILED_TESTS__'][] = array(
- 'name' => $file,
- 'test_name' => $tested,
- 'output' => ereg_replace('\.phpt$','.log', $file),
- 'diff' => ereg_replace('\.phpt$','.diff', $file),
- 'info' => $info,
- );
- }
-
- // write .exp
- if (strpos($log_format,'E') !== FALSE) {
- $logname = ereg_replace('\.phpt$','.exp',$file);
- if (!$log = fopen($logname,'w')) {
- return PEAR::raiseError("Cannot create test log - $logname");
- }
- fwrite($log,$wanted);
- fclose($log);
- }
-
- // write .out
- if (strpos($log_format,'O') !== FALSE) {
- $logname = ereg_replace('\.phpt$','.out',$file);
- if (!$log = fopen($logname,'w')) {
- return PEAR::raiseError("Cannot create test log - $logname");
- }
- fwrite($log,$output);
- fclose($log);
- }
-
- // write .diff
- if (strpos($log_format,'D') !== FALSE) {
- $logname = ereg_replace('\.phpt$','.diff',$file);
- if (!$log = fopen($logname,'w')) {
- return PEAR::raiseError("Cannot create test log - $logname");
- }
- fwrite($log, $this->generate_diff($wanted, $output,
- isset($section_text['RETURNS']) ? array(trim($section_text['RETURNS']),
- $return_value) : null));
- fclose($log);
- }
-
- // write .log
- if (strpos($log_format,'L') !== FALSE) {
- $logname = ereg_replace('\.phpt$','.log',$file);
- if (!$log = fopen($logname,'w')) {
- return PEAR::raiseError("Cannot create test log - $logname");
- }
- fwrite($log,"
----- EXPECTED OUTPUT
-$wanted
----- ACTUAL OUTPUT
-$output
----- FAILED
-");
- if ($returnfail) {
- fwrite($log,"
----- EXPECTED RETURN
-$section_text[RETURNS]
----- ACTUAL RETURN
-$return_value
-");
- }
- fclose($log);
- //error_report($file,$logname,$tested);
- }
-
- if (isset($old_php)) {
- $php = $old_php;
- }
-
- return $warn ? 'WARNED' : 'FAILED';
- }
-
- function generate_diff($wanted, $output, $return_value)
- {
- $w = explode("\n", $wanted);
- $o = explode("\n", $output);
- $w1 = array_diff_assoc($w,$o);
- $o1 = array_diff_assoc($o,$w);
- $w2 = array();
- $o2 = array();
- foreach($w1 as $idx => $val) $w2[sprintf("%03d<",$idx)] = sprintf("%03d- ", $idx+1).$val;
- foreach($o1 as $idx => $val) $o2[sprintf("%03d>",$idx)] = sprintf("%03d+ ", $idx+1).$val;
- $diff = array_merge($w2, $o2);
- ksort($diff);
- if ($return_value) {
- $extra = "##EXPECTED: $return_value[0]\r\n##RETURNED: $return_value[1]";
- } else {
- $extra = '';
- }
- return implode("\r\n", $diff) . $extra;
- }
-
- //
- // Write the given text to a temporary file, and return the filename.
- //
-
- function save_text($filename, $text)
- {
- if (!$fp = fopen($filename, 'w')) {
- return PEAR::raiseError("Cannot open file '" . $filename . "' (save_text)");
- }
- fwrite($fp,$text);
- fclose($fp);
- if (1 < DETAILED) echo "
-FILE $filename {{{
-$text
-}}}
-";
- }
-
-}
-?> \ No newline at end of file
diff --git a/inc/PHPUnit.php b/inc/PHPUnit.php
deleted file mode 100644
index de4da858eb9..00000000000
--- a/inc/PHPUnit.php
+++ /dev/null
@@ -1,83 +0,0 @@
-<?php
-//
-// +------------------------------------------------------------------------+
-// | PEAR :: PHPUnit |
-// +------------------------------------------------------------------------+
-// | Copyright (c) 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>. |
-// +------------------------------------------------------------------------+
-// | This source file is subject to version 3.00 of the PHP License, |
-// | that is available at http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +------------------------------------------------------------------------+
-//
-// $Id: PHPUnit.php,v 1.14 2004/12/22 08:06:11 sebastian Exp $
-//
-
-require_once 'PHPUnit/TestCase.php';
-require_once 'PHPUnit/TestResult.php';
-require_once 'PHPUnit/TestSuite.php';
-
-/**
- * PHPUnit runs a TestSuite and returns a TestResult object.
- *
- * Here is an example:
- *
- * <code>
- * <?php
- * require_once 'PHPUnit.php';
- *
- * class MathTest extends PHPUnit_TestCase {
- * var $fValue1;
- * var $fValue2;
- *
- * function MathTest($name) {
- * $this->PHPUnit_TestCase($name);
- * }
- *
- * function setUp() {
- * $this->fValue1 = 2;
- * $this->fValue2 = 3;
- * }
- *
- * function testAdd() {
- * $this->assertTrue($this->fValue1 + $this->fValue2 == 5);
- * }
- * }
- *
- * $suite = new PHPUnit_TestSuite();
- * $suite->addTest(new MathTest('testAdd'));
- *
- * $result = PHPUnit::run($suite);
- * print $result->toHTML();
- * ?>
- * </code>
- *
- * Alternatively, you can pass a class name to the PHPUnit_TestSuite()
- * constructor and let it automatically add all methods of that class
- * that start with 'test' to the suite:
- *
- * <code>
- * <?php
- * $suite = new PHPUnit_TestSuite('MathTest');
- * $result = PHPUnit::run($suite);
- * print $result->toHTML();
- * ?>
- * </code>
- *
- * @author Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @copyright Copyright &copy; 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @license http://www.php.net/license/3_0.txt The PHP License, Version 3.0
- * @category Testing
- * @package PHPUnit
- */
-class PHPUnit {
- function &run(&$suite) {
- $result = new PHPUnit_TestResult();
- $suite->run($result);
-
- return $result;
- }
-}
-?>
diff --git a/inc/PHPUnit/Assert.php b/inc/PHPUnit/Assert.php
deleted file mode 100644
index 74806458bd3..00000000000
--- a/inc/PHPUnit/Assert.php
+++ /dev/null
@@ -1,384 +0,0 @@
-<?php
-//
-// +------------------------------------------------------------------------+
-// | PEAR :: PHPUnit |
-// +------------------------------------------------------------------------+
-// | Copyright (c) 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>. |
-// +------------------------------------------------------------------------+
-// | This source file is subject to version 3.00 of the PHP License, |
-// | that is available at http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +------------------------------------------------------------------------+
-//
-// $Id: Assert.php,v 1.25 2005/01/31 04:57:16 sebastian Exp $
-//
-
-/**
- * A set of assert methods.
- *
- * @author Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @copyright Copyright &copy; 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @license http://www.php.net/license/3_0.txt The PHP License, Version 3.0
- * @category Testing
- * @package PHPUnit
- */
-class PHPUnit_Assert {
- /**
- * @var boolean
- * @access private
- */
- var $_looselyTyped = FALSE;
-
- /**
- * Asserts that a haystack contains a needle.
- *
- * @param mixed
- * @param mixed
- * @param string
- * @access public
- * @since 1.1.0
- */
- function assertContains($needle, $haystack, $message = '') {
- if (is_string($needle) && is_string($haystack)) {
- $this->assertTrue(strpos($haystack, $needle) !== FALSE ? TRUE : FALSE);
- }
-
- else if (is_array($haystack) && !is_object($needle)) {
- $this->assertTrue(in_array($needle, $haystack), $message);
- }
-
- else {
- $this->fail('Unsupported parameter passed to assertContains().');
- }
- }
-
- /**
- * Asserts that a haystack does not contain a needle.
- *
- * @param mixed
- * @param mixed
- * @param string
- * @access public
- * @since 1.1.0
- */
- function assertNotContains($needle, $haystack, $message = '') {
- if (is_string($needle) && is_string($haystack)) {
- $this->assertFalse(strpos($haystack, $needle) !== FALSE ? TRUE : FALSE);
- }
-
- else if (is_array($haystack) && !is_object($needle)) {
- $this->assertFalse(in_array($needle, $haystack), $message);
- }
-
- else {
- $this->fail('Unsupported parameter passed to assertNotContains().');
- }
- }
-
- /**
- * Asserts that two variables are equal.
- *
- * @param mixed
- * @param mixed
- * @param string
- * @param mixed
- * @access public
- */
- function assertEquals($expected, $actual, $message = '', $delta = 0) {
- if ((is_array($actual) && is_array($expected)) ||
- (is_object($actual) && is_object($expected))) {
- if (is_array($actual) && is_array($expected)) {
- ksort($actual);
- ksort($expected);
- }
-
- if ($this->_looselyTyped) {
- $actual = $this->_convertToString($actual);
- $expected = $this->_convertToString($expected);
- }
-
- $actual = serialize($actual);
- $expected = serialize($expected);
-
- $message = sprintf(
- '%sexpected %s, actual %s',
-
- !empty($message) ? $message . ' ' : '',
- $expected,
- $actual
- );
-
- if ($actual !== $expected) {
- return $this->fail($message);
- }
- }
-
- elseif (is_numeric($actual) && is_numeric($expected)) {
- $message = sprintf(
- '%sexpected %s%s, actual %s',
-
- !empty($message) ? $message . ' ' : '',
- $expected,
- ($delta != 0) ? ('+/- ' . $delta) : '',
- $actual
- );
-
- if (!($actual >= ($expected - $delta) && $actual <= ($expected + $delta))) {
- return $this->fail($message);
- }
- }
-
- else {
- $message = sprintf(
- '%sexpected %s, actual %s',
-
- !empty($message) ? $message . ' ' : '',
- $expected,
- $actual
- );
-
- if ($actual !== $expected) {
- return $this->fail($message);
- }
- }
- }
-
- /**
- * Asserts that two variables reference the same object.
- * This requires the Zend Engine 2 to work.
- *
- * @param object
- * @param object
- * @param string
- * @access public
- * @deprecated
- */
- function assertSame($expected, $actual, $message = '') {
- if (!version_compare(phpversion(), '5.0.0', '>=')) {
- $this->fail('assertSame() only works with PHP >= 5.0.0.');
- }
-
- if ((is_object($expected) || is_null($expected)) &&
- (is_object($actual) || is_null($actual))) {
- $message = sprintf(
- '%sexpected two variables to reference the same object',
-
- !empty($message) ? $message . ' ' : ''
- );
-
- if ($expected !== $actual) {
- return $this->fail($message);
- }
- } else {
- $this->fail('Unsupported parameter passed to assertSame().');
- }
- }
-
- /**
- * Asserts that two variables do not reference the same object.
- * This requires the Zend Engine 2 to work.
- *
- * @param object
- * @param object
- * @param string
- * @access public
- * @deprecated
- */
- function assertNotSame($expected, $actual, $message = '') {
- if (!version_compare(phpversion(), '5.0.0', '>=')) {
- $this->fail('assertNotSame() only works with PHP >= 5.0.0.');
- }
-
- if ((is_object($expected) || is_null($expected)) &&
- (is_object($actual) || is_null($actual))) {
- $message = sprintf(
- '%sexpected two variables to reference different objects',
-
- !empty($message) ? $message . ' ' : ''
- );
-
- if ($expected === $actual) {
- return $this->fail($message);
- }
- } else {
- $this->fail('Unsupported parameter passed to assertNotSame().');
- }
- }
-
- /**
- * Asserts that a variable is not NULL.
- *
- * @param mixed
- * @param string
- * @access public
- */
- function assertNotNull($actual, $message = '') {
- $message = sprintf(
- '%sexpected NOT NULL, actual NULL',
-
- !empty($message) ? $message . ' ' : ''
- );
-
- if (is_null($actual)) {
- return $this->fail($message);
- }
- }
-
- /**
- * Asserts that a variable is NULL.
- *
- * @param mixed
- * @param string
- * @access public
- */
- function assertNull($actual, $message = '') {
- $message = sprintf(
- '%sexpected NULL, actual NOT NULL',
-
- !empty($message) ? $message . ' ' : ''
- );
-
- if (!is_null($actual)) {
- return $this->fail($message);
- }
- }
-
- /**
- * Asserts that a condition is true.
- *
- * @param boolean
- * @param string
- * @access public
- */
- function assertTrue($condition, $message = '') {
- $message = sprintf(
- '%sexpected TRUE, actual FALSE',
-
- !empty($message) ? $message . ' ' : ''
- );
-
- if (!$condition) {
- return $this->fail($message);
- }
- }
-
- /**
- * Asserts that a condition is false.
- *
- * @param boolean
- * @param string
- * @access public
- */
- function assertFalse($condition, $message = '') {
- $message = sprintf(
- '%sexpected FALSE, actual TRUE',
-
- !empty($message) ? $message . ' ' : ''
- );
-
- if ($condition) {
- return $this->fail($message);
- }
- }
-
- /**
- * Asserts that a string matches a given regular expression.
- *
- * @param string
- * @param string
- * @param string
- * @access public
- */
- function assertRegExp($pattern, $string, $message = '') {
- $message = sprintf(
- '%s"%s" does not match pattern "%s"',
-
- !empty($message) ? $message . ' ' : '',
- $string,
- $pattern
- );
-
- if (!preg_match($pattern, $string)) {
- return $this->fail($message);
- }
- }
-
- /**
- * Asserts that a string does not match a given regular expression.
- *
- * @param string
- * @param string
- * @param string
- * @access public
- * @since 1.1.0
- */
- function assertNotRegExp($pattern, $string, $message = '') {
- $message = sprintf(
- '%s"%s" matches pattern "%s"',
-
- !empty($message) ? $message . ' ' : '',
- $string,
- $pattern
- );
-
- if (preg_match($pattern, $string)) {
- return $this->fail($message);
- }
- }
-
- /**
- * Asserts that a variable is of a given type.
- *
- * @param string $expected
- * @param mixed $actual
- * @param optional string $message
- * @access public
- */
- function assertType($expected, $actual, $message = '') {
- return $this->assertEquals(
- $expected,
- gettype($actual),
- $message
- );
- }
-
- /**
- * Converts a value to a string.
- *
- * @param mixed $value
- * @access private
- */
- function _convertToString($value) {
- foreach ($value as $k => $v) {
- if (is_array($v)) {
- $value[$k] = $this->_convertToString($value[$k]);
- } else {
- settype($value[$k], 'string');
- }
- }
-
- return $value;
- }
-
- /**
- * @param boolean $looselyTyped
- * @access public
- */
- function setLooselyTyped($looselyTyped) {
- if (is_bool($looselyTyped)) {
- $this->_looselyTyped = $looselyTyped;
- }
- }
-
- /**
- * Fails a test with the given message.
- *
- * @param string
- * @access protected
- * @abstract
- */
- function fail($message = '') { /* abstract */ }
-}
-?>
diff --git a/inc/PHPUnit/GUI/Gtk.php b/inc/PHPUnit/GUI/Gtk.php
deleted file mode 100644
index fdd3a9931e5..00000000000
--- a/inc/PHPUnit/GUI/Gtk.php
+++ /dev/null
@@ -1,698 +0,0 @@
-<?php
-/* vim: set expandtab tabstop=4 shiftwidth=4: */
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 2004 Scott Mattocks |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Scott Mattocks <scottmattocks@php.net> |
-// +----------------------------------------------------------------------+
-//
-// $Id: Gtk.php,v 1.2 2004/11/25 09:06:55 sebastian Exp $
-/**
- * GTK GUI interface for PHPUnit.
- *
- * This class is a PHP port of junit.awtui.testrunner. Documentation
- * for junit.awtui.testrunner can be found at
- * http://junit.sourceforge.net
- *
- * Due to the limitations of PHP4 and PHP-Gtk, this class can not
- * duplicate all of the functionality of the JUnit GUI. Some of the
- * things this class cannot do include:
- * - Reloading the class for each run
- * - Stopping the test in progress
- *
- * To use simply intantiate the class and call main()
- * $gtk =& new PHPUnit_GUI_Gtk;
- * $gtk->main();
- *
- * Once the window has finished loading, you can enter the name of
- * a class that has been loaded (include/require some where in your
- * code, or you can pass the name of the file containing the class.
- *
- * You can also load classes using the SetupDecorator class.
- * require_once 'PHPUnit/GUI/SetupDecorator.php';
- * require_once 'PHPUnit/GUI/Gtk.php';
- * $gui = new PHPUnit_GUI_SetupDecorator(new PHPUnit_GUI_Gtk());
- * $gui->getSuitesFromDir('/path/to/test','.*\.php$',array('index.php','sql.php'));
- * $gui->show();
- *
- * @todo Allow file drop. (Gtk_FileDrop)
- *
- * @author Scott Mattocks
- * @copyright Copyright &copy; 2004 Scott Mattocks
- * @license PHP 3.0
- * @version @VER@
- * @category PHP
- * @package PHPUnit
- * @subpackage GUI
- */
-class PHPUnit_GUI_Gtk {
-
- /**
- * The main gtk window
- * @var object
- */
- var $gui;
- /**
- * The text entry that contains the name of the
- * file that holds the test(s)/suite(s).
- * @var object
- */
- var $suiteField;
- /**
- * The label that shows the number of tests that
- * were run.
- * @var object
- */
- var $numberOfRuns;
- /**
- * The label that shows the number of errors that
- * were encountered.
- * @var object
- */
- var $numberOfErrors;
- /**
- * The label that shows the number of failures
- * that were encountered.
- * @var object
- */
- var $numberOfFailures;
- /**
- * The label for reporting user messages.
- * @var object
- */
- var $statusLine;
- /**
- * The text area for reporting messages from successful
- * test runs. (not necessarily successful tests)
- * @var object
- */
- var $reportArea;
- /**
- * The text area for reporting errors encountered when
- * running tests.
- * @var object
- */
- var $dumpArea;
- /**
- * The progress bar indicator. Shows the percentage of
- * passed tests.
- * @var object
- */
- var $progress;
- /**
- * A checkbox for the user to indicate whether or not they
- * would like to see results from all tests or just failures.
- * @object
- */
- var $showPassed;
-
- /**
- * Constructor.
- *
- * The constructor checks for the gtk extension and loads it
- * if needed. Then it creates the GUI. The GUI is not shown
- * nor is the main gtk loop started until main() is called.
- *
- * @access public
- * @param none
- * @return void
- */
- function PHPUnit_GUI_Gtk()
- {
- // Check for php-gtk extension.
- if (!extension_loaded('gtk')) {
- dl( 'php_gtk.' . PHP_SHLIB_SUFFIX);
- }
-
- // Create the interface but don't start the loop
- $this->_createUI();
- }
- /**
- * Start the main gtk loop.
- *
- * main() first sets the default state of the showPassed
- * check box. Next all widgets that are part of the GUI
- * are shown. Finally the main gtk loop is started.
- *
- * @access public
- * @param boolean $showPassed
- * @return void
- */
- function main($showPassed = true)
- {
- $this->showPassed->set_active($showPassed);
- $this->gui->show_all();
-
- gtk::main();
- }
- /**
- * Create the user interface.
- *
- * The user interface is pretty simple. It consists of a
- * menu, text entry, run button, some labels, a progress
- * indicator, and a couple of areas for notification of
- * any messages.
- *
- * @access private
- * @param none
- * @return void
- */
- function _createUI()
- {
- // Create a window.
- $window =& new GtkWindow;
- $window->set_title('PHPUnit Gtk');
- $window->set_usize(400, -1);
-
- // Create the main box.
- $mainBox =& new GtkVBox;
- $window->add($mainBox);
-
- // Start with the menu.
- $mainBox->pack_start($this->_createMenu());
-
- // Then add the suite field entry.
- $mainBox->pack_start($this->_createSuiteEntry());
-
- // Then add the report labels.
- $mainBox->pack_start($this->_createReportLabels());
-
- // Next add the progress bar.
- $mainBox->pack_start($this->_createProgressBar());
-
- // Then add the report area and the dump area.
- $mainBox->pack_start($this->_createReportAreas());
-
- // Finish off with the status line.
- $mainBox->pack_start($this->_createStatusLine());
-
- // Connect the destroy signal.
- $window->connect_object('destroy', array('gtk', 'main_quit'));
-
- // Assign the member.
- $this->gui =& $window;
- }
- /**
- * Create the menu.
- *
- * The menu is very simple. It an exit menu item, which exits
- * the application, and an about menu item, which shows some
- * basic information about the application itself.
- *
- * @access private
- * @param none
- * @return &object The GtkMenuBar
- */
- function &_createMenu()
- {
- // Create the menu bar.
- $menuBar =& new GtkMenuBar;
-
- // Create the main (only) menu item.
- $phpHeader =& new GtkMenuItem('PHPUnit');
-
- // Add the menu item to the menu bar.
- $menuBar->append($phpHeader);
-
- // Create the PHPUnit menu.
- $phpMenu =& new GtkMenu;
-
- // Add the menu items
- $about =& new GtkMenuItem('About...');
- $about->connect('activate', array(&$this, 'about'));
- $phpMenu->append($about);
-
- $exit =& new GtkMenuItem('Exit');
- $exit->connect_object('activate', array('gtk', 'main_quit'));
- $phpMenu->append($exit);
-
- // Complete the menu.
- $phpHeader->set_submenu($phpMenu);
-
- return $menuBar;
- }
- /**
- * Create the suite entry and related widgets.
- *
- * The suite entry has some supporting components such as a
- * label, the show passed check box and the run button. All
- * of these items are packed into two nested boxes.
- *
- * @access private
- * @param none
- * @return &object A box that contains all of the suite entry pieces.
- */
- function &_createSuiteEntry()
- {
- // Create the outermost box.
- $outerBox =& new GtkVBox;
-
- // Create the suite label, box, and field.
- $suiteLabel =& new GtkLabel('Test class name:');
- $suiteBox =& new GtkHBox;
- $this->suiteField =& new GtkEntry;
- $this->suiteField->set_text($suiteName != NULL ? $suiteName : '');
-
- // Create the button the user will use to start the test.
- $runButton =& new GtkButton('Run');
- $runButton->connect_object('clicked', array(&$this, 'run'));
-
- // Create the check box that lets the user show only failures.
- $this->showPassed =& new GtkCheckButton('Show passed tests');
-
- // Add the components to their respective boxes.
- $suiteLabel->set_alignment(0, 0);
- $outerBox->pack_start($suiteLabel);
- $outerBox->pack_start($suiteBox);
- $outerBox->pack_start($this->showPassed);
-
- $suiteBox->pack_start($this->suiteField);
- $suiteBox->pack_start($runButton);
-
- return $outerBox;
- }
-
- /**
- * Create the labels that tell the user what has happened.
- *
- * There are three labels, one each for total runs, errors and
- * failures. There is also one label for each of these that
- * describes what the label is. It could be done with one label
- * instead of two but that would make updates much harder.
- *
- * @access private
- * @param none
- * @return &object A box containing the labels.
- */
- function &_createReportLabels()
- {
- // Create a box to hold everything.
- $labelBox =& new GtkHBox;
-
- // Create the non-updated labels.
- $numberOfRuns =& new GtkLabel('Runs:');
- $numberOfErrors =& new GtkLabel('Errors:');
- $numberOfFailures =& new GtkLabel('Failures:');
-
- // Create the labels that will be updated.
- // These are asssigned to members to make it easier to
- // set their values later.
- $this->numberOfRuns =& new GtkLabel(0);
- $this->numberOfErrors =& new GtkLabel(0);
- $this->numberOfFailures =& new GtkLabel(0);
-
- // Pack everything in.
- $labelBox->pack_start($numberOfRuns);
- $labelBox->pack_start($this->numberOfRuns);
- $labelBox->pack_start($numberOfErrors);
- $labelBox->pack_start($this->numberOfErrors);
- $labelBox->pack_start($numberOfFailures);
- $labelBox->pack_start($this->numberOfFailures);
-
- return $labelBox;
- }
-
- /**
- * Create the success/failure indicator.
- *
- * A GtkProgressBar is used to visually indicate how many
- * tests were successful compared to how many were not. The
- * progress bar shows the percentage of success and will
- * change from green to red if there are any failures.
- *
- * @access private
- * @param none
- * @return &object The progress bar
- */
- function &_createProgressBar()
- {
- // Create the progress bar.
- $this->progress =& new GtkProgressBar(new GtkAdjustment(0, 0, 1, .1, 1, 0));
-
- // Set the progress bar to print the percentage.
- $this->progress->set_show_text(true);
-
- return $this->progress;
- }
-
- /**
- * Create the report text areas.
- *
- * The report area consists of one text area for failures, one
- * text area for errors and one label for identification purposes.
- * All three widgets are packed into a box.
- *
- * @access private
- * @param none
- * @return &object The box containing the report areas.
- */
- function &_createReportAreas()
- {
- // Create the containing box.
- $reportBox =& new GtkVBox;
-
- // Create the identification label
- $reportLabel =& new GtkLabel('Errors and Failures:');
- $reportLabel->set_alignment(0, 0);
-
- // Create the scrolled windows for the text areas.
- $reportScroll =& new GtkScrolledWindow;
- $dumpScroll =& new GtkScrolledWindow;
-
- // Make the scroll areas big enough.
- $reportScroll->set_usize(-1, 150);
- $dumpScroll->set_usize(-1, 150);
-
- // Only show the vertical scroll bar when needed.
- // Never show the horizontal scroll bar.
- $reportScroll->set_policy(GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
- $dumpScroll->set_policy(GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
-
- // Create the text areas.
- $this->reportArea =& new GtkText;
- $this->dumpArea =& new GtkText;
-
- // Don't let words get broken.
- $this->reportArea->set_word_wrap(true);
- $this->dumpArea->set_word_wrap(true);
-
- // Pack everything in.
- $reportBox->pack_start($reportLabel);
- $reportScroll->add($this->reportArea);
- $reportBox->pack_start($reportScroll);
- $dumpScroll->add($this->dumpArea);
- $reportBox->pack_start($dumpScroll);
-
- return $reportBox;
- }
-
- /**
- * Create a status label.
- *
- * A status line at the bottom of the application is used
- * to notify the user of non-test related messages such as
- * failures loading a test suite.
- *
- * @access private
- * @param none
- * @return &object The status label.
- */
- function &_createStatusLine()
- {
- // Create the status label.
- $this->statusLine =& new GtkLabel('');
- $this->statusLine->set_alignment(0, 0);
-
- return $this->statusLine;
- }
-
- /**
- * Show a popup with information about the application.
- *
- * The popup should show information about the version,
- * the author, the license, where to get the latest
- * version and a short description.
- *
- * @access public
- * @param none
- * @return void
- */
- function about()
- {
- // Create the new window.
- $about =& new GtkWindow;
- $about->set_title('About PHPUnit GUI Gtk');
- $about->set_usize(250, -1);
-
- // Put two vboxes in the hbox.
- $vBox =& new GtkVBox;
- $about->add($vBox);
-
- // Create the labels.
- $version =& new GtkLabel(" Version: 1.0");
- $license =& new GtkLabel(" License: PHP License v3.0");
- $where =& new GtkLabel(" Download from: http://pear.php.net/PHPUnit/");
- $unitAuth =& new GtkLabel(" PHPUnit Author: Sebastian Bergman");
- $gtkAuth =& new GtkLabel(" Gtk GUI Author: Scott Mattocks");
-
- // Align everything to the left
- $where->set_alignment(0, .5);
- $version->set_alignment(0, .5);
- $license->set_alignment(0, .5);
- $gtkAuth->set_alignment(0, .5);
- $unitAuth->set_alignment(0, .5);
-
- // Pack everything into the vBox;
- $vBox->pack_start($version);
- $vBox->pack_start($license);
- $vBox->pack_start($where);
- $vBox->pack_start($unitAuth);
- $vBox->pack_start($gtkAuth);
-
- // Connect the destroy signal.
- $about->connect('destroy', array('gtk', 'true'));
-
- // Show the goods.
- $about->show_all();
- }
-
- /**
- * Load the test suite.
- *
- * This method tries to load test suite based on the user
- * info. If the user passes the name of a tests suite, it
- * is instantiated and a new object is returned. If the
- * user passes a file that contains a test suite, the class
- * is instantiated and a new object is returned. If the user
- * passes a file that contains a test case, the test case is
- * passed to a new test suite and the new suite object is
- * returned.
- *
- * @access public
- * @param string The file that contains a test case/suite or the classname.
- * @return &object The new test suite.
- */
- function &loadTest(&$file)
- {
- // Check to see if a class name was given.
- if (is_a($file, 'PHPUnit_TestSuite')) {
- return $file;
- } elseif (class_exists($file)) {
- require_once 'PHPUnit/TestSuite.php';
- return new PHPUnit_TestSuite($file);
- }
-
- // Check that the file exists.
- if (!@is_readable($file)) {
- $this->_showStatus('Cannot find file: ' . $file);
- return false;
- }
-
- $this->_showStatus('Loading test suite...');
-
- // Instantiate the class.
- // If the path is /path/to/test/TestClass.php
- // the class name should be test_TestClass
- require_once $file;
- $className = str_replace(DIRECTORY_SEPARATOR, '_', $file);
- $className = substr($className, 0, strpos($className, '.'));
-
- require_once 'PHPUnit/TestSuite.php';
- return new PHPUnit_TestSuite($className);
- }
-
- /**
- * Run the test suite.
- *
- * This method runs the test suite and updates the messages
- * for the user. When finished it changes the status line
- * to 'Test Complete'
- *
- * @access public
- * @param none
- * @return void
- */
- function runTest()
- {
- // Notify the user that the test is running.
- $this->_showStatus('Running Test...');
-
- // Run the test.
- $result = PHPUnit::run($this->suite);
-
- // Update the labels.
- $this->_setLabelValue($this->numberOfRuns, $result->runCount());
- $this->_setLabelValue($this->numberOfErrors, $result->errorCount());
- $this->_setLabelValue($this->numberOfFailures, $result->failureCount());
-
- // Update the progress bar.
- $this->_updateProgress($result->runCount(),
- $result->errorCount(),
- $result->failureCount()
- );
-
- // Show the errors.
- $this->_showFailures($result->errors(), $this->dumpArea);
-
- // Show the messages from the tests.
- if ($this->showPassed->get_active()) {
- // Show failures and success.
- $this->_showAll($result, $this->reportArea);
- } else {
- // Show only failures.
- $this->_showFailures($result->failures(), $this->reportArea);
- }
-
- // Update the status message.
- $this->_showStatus('Test complete');
- }
-
- /**
- * Set the text of a label.
- *
- * Change the text of a given label.
- *
- * @access private
- * @param widget &$label The label whose value is to be changed.
- * @param string $value The new text of the label.
- * @return void
- */
- function _setLabelValue(&$label, $value)
- {
- $label->set_text($value);
- }
-
- /**
- * The main work of the application.
- *
- * Load the test suite and then execute the tests.
- *
- * @access public
- * @param none
- * @return void
- */
- function run()
- {
- // Load the test suite.
- $this->suite =& $this->loadTest($this->suiteField->get_text());
-
- // Check to make sure the suite was loaded properly.
- if (!is_object($this->suite)) {
- // Raise an error.
- $this->_showStatus('Could not load test suite.');
- return false;
- }
-
- // Run the tests.
- $this->runTest();
- }
-
- /**
- * Update the status message.
- *
- * @access private
- * @param string $status The new message.
- * @return void
- */
- function _showStatus($status)
- {
- $this->statusLine->set_text($status);
- }
-
- /**
- * Alias for main()
- *
- * @see main
- */
- function show($showPassed = true)
- {
- $this->main($showPassed);
- }
-
- /**
- * Add a suite to the tests.
- *
- * This method is require by SetupDecorator. It adds a
- * suite to the the current set of suites.
- *
- * @access public
- * @param object $testSuite The suite to add.
- * @return void
- */
- function addSuites($testSuite)
- {
- if (!is_array($testSuite)) {
- settype($testSuite, 'array');
- }
-
- foreach ($testSuite as $suite) {
-
- if (is_a($this->suite, 'PHPUnit_TestSuite')) {
- $this->suite->addTestSuite($suite->getName());
- } else {
- $this->suite =& $this->loadTest($suite);
- }
-
- // Set the suite field.
- $text = $this->suiteField->get_text();
- if (empty($text)) {
- $this->suiteField->set_text($this->suite->getName());
- }
- }
- }
-
- /**
- * Show all test messages.
- *
- * @access private
- * @param object The TestResult from the test suite.
- * @return void
- */
- function _showAll(&$result)
- {
- // Clear the area first.
- $this->reportArea->delete_text(0, -1);
- $this->reportArea->insert_text($result->toString(), 0);
- }
-
- /**
- * Show failure/error messages in the given text area.
- *
- * @access private
- * @param object &$results The results of the test.
- * @param widget &$area The area to show the results in.
- */
- function _showFailures(&$results, &$area)
- {
- $area->delete_text(0, -1);
- foreach (array_reverse($results, true) as $result) {
- $area->insert_text($result->toString(), 0);
- }
- }
-
- /**
- * Update the progress indicator.
- *
- * @access private
- * @param integer $runs
- * @param integer $errors
- * @param integer $failures
- * @return void
- */
- function _updateProgress($runs, $errors, $failures)
- {
- $percentage = 1 - (($errors + $failures) / $runs);
- $this->progress->set_percentage($percentage);
- }
-}
-?> \ No newline at end of file
diff --git a/inc/PHPUnit/GUI/HTML.php b/inc/PHPUnit/GUI/HTML.php
deleted file mode 100644
index 773ab9af9f3..00000000000
--- a/inc/PHPUnit/GUI/HTML.php
+++ /dev/null
@@ -1,210 +0,0 @@
-<?php
-//
-// +------------------------------------------------------------------------+
-// | PEAR :: PHPUnit |
-// +------------------------------------------------------------------------+
-// | Copyright (c) 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>. |
-// +------------------------------------------------------------------------+
-// | This source file is subject to version 3.00 of the PHP License, |
-// | that is available at http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +------------------------------------------------------------------------+
-//
-// $Id: HTML.php,v 1.17 2005/01/07 07:34:05 sebastian Exp $
-//
-
-/**
- * This class provides a HTML GUI.
- *
- * @author Wolfram Kriesing <wolfram@kriesing.de>
- * @license http://www.php.net/license/3_0.txt The PHP License, Version 3.0
- * @category Testing
- * @package PHPUnit
- * @subpackage GUI
- */
-class PHPUnit_GUI_HTML
-{
- var $_suites = array();
-
- /**
- * the current implementation of PHPUnit is designed
- * this way that adding a suite to another suite only
- * grabs all the tests and adds them to the suite, so you
- * have no chance to find out which test goes with which suite
- * therefore you can simply pass an array of suites to this constructor here
- *
- * @param array The suites to be tested. If not given, then you might
- * be using the SetupDecorator, which detects them automatically
- * when calling getSuitesFromDir()
- */
- function PHPUnit_GUI_HTML($suites = array())
- {
- if (!is_array($suites)) {
- $this->_suites = array($suites);
- } else {
- $this->_suites = $suites;
- }
- }
-
- /**
- * Add suites to the GUI
- *
- * @param object this should be an instance of PHPUnit_TestSuite
- */
- function addSuites($suites)
- {
- $this->_suites = array_merge($this->_suites,$suites);
- }
-
- /**
- * this prints the HTML code straight out
- *
- */
- function show()
- {
- $request = $_REQUEST;
- $showPassed = FALSE;
- $submitted = @$request['submitted'];
-
- if ($submitted) {
- $showPassed = @$request['showOK'] ? TRUE : FALSE;
- }
-
- $suiteResults = array();
-
- foreach ($this->_suites as $aSuite) {
- $aSuiteResult = array();
-
- // remove the first directory's name from the test-suite name, since it
- // mostly is something like 'tests' or alike
- $removablePrefix = explode('_',$aSuite->getName());
- $aSuiteResult['name'] = str_replace($removablePrefix[0].'_', '', $aSuite->getName());
-
- if ($submitted && isset($request[$aSuiteResult['name']])) {
- $result = PHPUnit::run($aSuite);
-
- $aSuiteResult['counts']['run'] = $result->runCount();
- $aSuiteResult['counts']['error'] = $result->errorCount();
- $aSuiteResult['counts']['failure'] = $result->failureCount();
-
- $aSuiteResult['results'] = $this->_prepareResult($result,$showPassed);
-
- $per = 100/$result->runCount();
- $failed = ($per*$result->errorCount())+($per*$result->failureCount());
- $aSuiteResult['percent'] = round(100-$failed,2);
- } else {
- $aSuiteResult['addInfo'] = 'NOT EXECUTED';
- }
-
- $suiteResults[] = $aSuiteResult;
- }
-
- $final['name'] = 'OVERALL RESULT';
- $final['counts'] = array();
- $final['percent'] = 0;
- $numExecutedTests = 0;
-
- foreach ($suiteResults as $aSuiteResult) {
- if (sizeof(@$aSuiteResult['counts'])) {
- foreach ($aSuiteResult['counts'] as $key=>$aCount) {
- if (!isset($final['counts'][$key])) {
- $final['counts'][$key] = 0;
- }
-
- $final['counts'][$key] += $aCount;
- }
- }
- }
-
- if (isset($final['counts']['run'])) {
- $per = 100/$final['counts']['run'];
- $failed = ($per*$final['counts']['error'])+($per*$final['counts']['failure']);
- $final['percent'] = round(100-$failed,2);
- } else {
- $final['percent'] = 0;
- }
-
- array_unshift($suiteResults,$final);
-
- include 'PHPUnit/GUI/HTML.tpl';
- }
-
- function _prepareResult($result,$showPassed)
- {
- $ret = array();
- $failures = $result->failures();
-
- foreach($failures as $aFailure) {
- $ret['failures'][] = $this->_prepareFailure($aFailure);
- }
-
- $errors = $result->errors();
-
- foreach($errors as $aError) {
- $ret['errors'][] = $this->_prepareErrors($aError);
- }
-
- if ($showPassed) {
- $passed = $result->passedTests();
-
- foreach($passed as $aPassed) {
- $ret['passed'][] = $this->_preparePassedTests($aPassed);
- }
- }
-
- return $ret;
- }
-
- function _prepareFailure($failure)
- {
- $test = $failure->failedTest();
- $ret['testName'] = $test->getName();
- $exception = $failure->thrownException();
-
- // a serialized string starts with a 'character:decimal:{'
- // if so we try to unserialize it
- // this piece of the regular expression is for detecting a serialized
- // type like 'a:3:' for an array with three element or an object i.e. 'O:12:"class":3'
- $serialized = '(\w:\d+:(?:"[^"]+":\d+:)?\{.*\})';
-
- // Spaces might make a diff, so we shall show them properly (since a
- // user agent ignores them).
- if (preg_match('/^(.*)expected ' . $serialized . ', actual ' . $serialized . '$/sU', $exception, $matches)) {
- ob_start();
- print_r(unserialize($matches[2]));
- $ret['expected'] = htmlspecialchars($matches[1]) . "<pre>" . htmlspecialchars(rtrim(ob_get_contents())) . "</pre>";
- // Improved compatibility, ob_clean() would be PHP >= 4.2.0 only.
- ob_end_clean();
-
- ob_start();
- print_r(unserialize($matches[3]));
- $ret['actual'] = htmlspecialchars($matches[1]) . "<pre>" . htmlspecialchars(rtrim(ob_get_contents())) . "</pre>";
- ob_end_clean();
- }
-
- else if (preg_match('/^(.*)expected (.*), actual (.*)$/sU', $exception, $matches)) {
- $ret['expected'] = nl2br(str_replace(" ", "&nbsp;", htmlspecialchars($matches[1] . $matches[2])));
- $ret['actual'] = nl2br(str_replace(" ", "&nbsp;", htmlspecialchars($matches[1] . $matches[3])));
- } else {
- $ret['message'] = nl2br(str_replace(" ", "&nbsp;", htmlspecialchars($exception)));
- }
-
- return $ret;
- }
-
- function _preparePassedTests($passed)
- {
- $ret['testName'] = $passed->getName();
- return $ret;
- }
-
- function _prepareError($error)
- {
- $ret['testName'] = $error->getName();
- $ret['message'] = $error->toString();
- return $ret;
- }
-}
-?>
diff --git a/inc/PHPUnit/GUI/SetupDecorator.php b/inc/PHPUnit/GUI/SetupDecorator.php
deleted file mode 100644
index 73c3d8298e2..00000000000
--- a/inc/PHPUnit/GUI/SetupDecorator.php
+++ /dev/null
@@ -1,167 +0,0 @@
-<?php
-//
-// +------------------------------------------------------------------------+
-// | PEAR :: PHPUnit |
-// +------------------------------------------------------------------------+
-// | Copyright (c) 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>. |
-// +------------------------------------------------------------------------+
-// | This source file is subject to version 3.00 of the PHP License, |
-// | that is available at http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +------------------------------------------------------------------------+
-//
-// $Id: SetupDecorator.php,v 1.12 2005/05/14 05:58:38 sebastian Exp $
-//
-
-/**
- * This decorator actually just adds the functionality to read the
- * test-suite classes from a given directory and instanciate them
- * automatically, use it as given in the example below.
- *
- * <code>
- * <?php
- * $gui = new PHPUnit_GUI_SetupDecorator(new PHPUnit_GUI_HTML());
- * $gui->getSuitesFromDir('/path/to/dir/tests','.*\.php$',array('index.php','sql.php'));
- * $gui->show();
- * ?>
- * </code>
- *
- * The example calls this class and tells it to:
- *
- * - find all file under the directory /path/to/dir/tests
- * - for files, which end with '.php' (this is a piece of a regexp, that's why the . is escaped)
- * - and to exclude the files 'index.php' and 'sql.php'
- * - and include all the files that are left in the tests.
- *
- * Given that the path (the first parameter) ends with 'tests' it will be assumed
- * that the classes are named tests_* where * is the directory plus the filename,
- * according to PEAR standards.
- *
- * So that:
- *
- * - 'testMe.php' in the dir 'tests' bill be assumed to contain a class tests_testMe
- * - '/moretests/aTest.php' should contain a class 'tests_moretests_aTest'
- *
- * @author Wolfram Kriesing <wolfram@kriesing.de>
- * @license http://www.php.net/license/3_0.txt The PHP License, Version 3.0
- * @category Testing
- * @package PHPUnit
- * @subpackage GUI
- */
-class PHPUnit_GUI_SetupDecorator
-{
- /**
- *
- *
- */
- function PHPUnit_GUI_SetupDecorator(&$gui)
- {
- $this->_gui = &$gui;
- }
-
- /**
- * just forwarding the action to the decorated class.
- *
- */
- function show($showPassed=TRUE)
- {
- $this->_gui->show($showPassed);
- }
-
- /**
- * Setup test suites that can be found in the given directory
- * Using the second parameter you can also choose a subsets of the files found
- * in the given directory. I.e. only all the files that contain '_UnitTest_',
- * in order to do this simply call it like this:
- * <code>getSuitesFromDir($dir,'.*_UnitTest_.*')</code>.
- * There you can already see that the pattern is built for the use within a regular expression.
- *
- * @param string the directory where to search for test-suite files
- * @param string the pattern (a regexp) by which to find the files
- * @param array an array of file names that shall be excluded
- */
- function getSuitesFromDir($dir, $filenamePattern = '', $exclude = array())
- {
- if ($dir{strlen($dir)-1} == DIRECTORY_SEPARATOR) {
- $dir = substr($dir, 0, -1);
- }
-
- $files = $this->_getFiles($dir, $filenamePattern, $exclude, realpath($dir . '/..'));
- asort($files);
-
- foreach ($files as $className => $aFile) {
- include_once($aFile);
-
- if (class_exists($className)) {
- $suites[] =& new PHPUnit_TestSuite($className);
- } else {
- trigger_error("$className could not be found in $dir$aFile!");
- }
- }
-
- $this->_gui->addSuites($suites);
- }
-
- /**
- * This method searches recursively through the directories
- * to find all the files that shall be added to the be visible.
- *
- * @param string the path where find the files
- * @param srting the string pattern by which to find the files
- * @param string the file names to be excluded
- * @param string the root directory, which serves as the prefix to the fully qualified filename
- * @access private
- */
- function _getFiles($dir, $filenamePattern, $exclude, $rootDir)
- {
- $files = array();
-
- if ($dp = opendir($dir)) {
- while (FALSE !== ($file = readdir($dp))) {
- $filename = $dir . DIRECTORY_SEPARATOR . $file;
- $match = TRUE;
-
- if ($filenamePattern && !preg_match("~$filenamePattern~", $file)) {
- $match = FALSE;
- }
-
- if (sizeof($exclude)) {
- foreach ($exclude as $aExclude) {
- if (strpos($file, $aExclude) !== FALSE) {
- $match = FALSE;
- break;
- }
- }
- }
-
- if (is_file($filename) && $match) {
- $tmp = str_replace($rootDir, '', $filename);
-
- if (strpos($tmp, DIRECTORY_SEPARATOR) === 0) {
- $tmp = substr($tmp, 1);
- }
-
- if (strpos($tmp, '/') === 0) {
- $tmp = substr($tmp, 1);
- }
-
- $className = str_replace(DIRECTORY_SEPARATOR, '_', $tmp);
- $className = basename($className, '.php');
-
- $files[$className] = $filename;
- }
-
- if ($file != '.' && $file != '..' && is_dir($filename)) {
- $files = array_merge($files, $this->_getFiles($filename, $filenamePattern, $exclude, $rootDir));
- }
- }
-
- closedir($dp);
- }
-
- return $files;
- }
-}
-?>
diff --git a/inc/PHPUnit/RepeatedTest.php b/inc/PHPUnit/RepeatedTest.php
deleted file mode 100644
index f8cbbc640f6..00000000000
--- a/inc/PHPUnit/RepeatedTest.php
+++ /dev/null
@@ -1,112 +0,0 @@
-<?php
-//
-// +------------------------------------------------------------------------+
-// | PEAR :: PHPUnit |
-// +------------------------------------------------------------------------+
-// | Copyright (c) 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>. |
-// +------------------------------------------------------------------------+
-// | This source file is subject to version 3.00 of the PHP License, |
-// | that is available at http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +------------------------------------------------------------------------+
-//
-// $Id: RepeatedTest.php,v 1.10 2004/12/22 08:06:11 sebastian Exp $
-//
-
-require_once 'PHPUnit/TestDecorator.php';
-
-/**
- * A Decorator that runs a test repeatedly.
- *
- * Here is an example:
- *
- * <code>
- * <?php
- * require_once 'PHPUnit.php';
- * require_once 'PHPUnit/RepeatedTest.php';
- *
- * class MathTest extends PHPUnit_TestCase {
- * var $fValue1;
- * var $fValue2;
- *
- * function MathTest($name) {
- * $this->PHPUnit_TestCase($name);
- * }
- *
- * function setUp() {
- * $this->fValue1 = 2;
- * $this->fValue2 = 3;
- * }
- *
- * function testAdd() {
- * $this->assertTrue($this->fValue1 + $this->fValue2 == 5);
- * }
- * }
- *
- * $suite = new PHPUnit_TestSuite;
- *
- * $suite->addTest(
- * new PHPUnit_RepeatedTest(
- * new MathTest('testAdd'),
- * 10
- * )
- * );
- *
- * $result = PHPUnit::run($suite);
- * print $result->toString();
- * ?>
- * </code>
- *
- * @author Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @copyright Copyright &copy; 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @license http://www.php.net/license/3_0.txt The PHP License, Version 3.0
- * @category Testing
- * @package PHPUnit
- */
-class PHPUnit_RepeatedTest extends PHPUnit_TestDecorator {
- /**
- * @var integer
- * @access private
- */
- var $_timesRepeat = 1;
-
- /**
- * Constructor.
- *
- * @param object
- * @param integer
- * @access public
- */
- function PHPUnit_RepeatedTest(&$test, $timesRepeat = 1) {
- $this->PHPUnit_TestDecorator($test);
- $this->_timesRepeat = $timesRepeat;
- }
-
- /**
- * Counts the number of test cases that
- * will be run by this test.
- *
- * @return integer
- * @access public
- */
- function countTestCases() {
- return $this->_timesRepeat * $this->_test->countTestCases();
- }
-
- /**
- * Runs the decorated test and collects the
- * result in a TestResult.
- *
- * @param object
- * @access public
- * @abstract
- */
- function run(&$result) {
- for ($i = 0; $i < $this->_timesRepeat; $i++) {
- $this->_test->run($result);
- }
- }
-}
-?>
diff --git a/inc/PHPUnit/Skeleton.php b/inc/PHPUnit/Skeleton.php
deleted file mode 100644
index 81fe3149066..00000000000
--- a/inc/PHPUnit/Skeleton.php
+++ /dev/null
@@ -1,406 +0,0 @@
-<?php
-//
-// +------------------------------------------------------------------------+
-// | PEAR :: PHPUnit |
-// +------------------------------------------------------------------------+
-// | Copyright (c) 2002-2004 Sebastian Bergmann <sb@sebastian-bergmann.de>. |
-// +------------------------------------------------------------------------+
-// | This source file is subject to version 3.00 of the PHP License, |
-// | that is available at http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +------------------------------------------------------------------------+
-//
-// $Id: Skeleton.php,v 1.6 2004/12/22 08:06:11 sebastian Exp $
-//
-
-/**
- * Class for creating a PHPUnit_TestCase skeleton file.
- *
- * This class will take a classname as a parameter on construction and will
- * create a PHP file that contains the skeleton of a PHPUnit_TestCase
- * subclass. The test case will contain a test foreach method of the class.
- * Methods of the parent class will, by default, be excluded from the test
- * class. Passing and optional construction parameter will include them.
- *
- * Example
- *
- * <?php
- * require_once 'PHPUnit/Skeleton.php';
- * $ps = new PHPUnit_Skeleton('PHPUnit_Skeleton', 'PHPUnit/Skeleton.php');
- *
- * // Generate the test class.
- * // Default settings will not include any parent class methods, but
- * // will include private methods.
- * $ps->createTestClass();
- *
- * // Write the new test class to file.
- * // By default, code to run the test will be included.
- * $ps->writeTestClass();
- * ?>
- *
- * Now open the skeleton class and fill in the details.
- * If you run the test as is, all tests will fail and
- * you will see plenty of undefined constant errors.
- *
- * @author Scott Mattocks <scott@crisscott.com>
- * @copyright Copyright &copy; 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @license http://www.php.net/license/3_0.txt The PHP License, Version 3.0
- * @category Testing
- * @package PHPUnit
- */
-class PHPUnit_Skeleton {
- /**
- * Path to the class file to create a skeleton for.
- * @var string
- */
- var $classPath;
-
- /**
- * The name of the class
- * @var string
- */
- var $className;
-
- /**
- * Path to the configuration file needed by class to test.
- * @var string
- */
- var $configFile;
-
- /**
- * Whether or not to include the methods of the parent class when testing.
- * @var boolean
- */
- var $includeParents;
-
- /**
- * Whether or not to test private methods.
- * @var boolean
- */
- var $includePrivate;
-
- /**
- * The test class that will be created.
- * @var string
- */
- var $testClass;
-
- /**
- * Constructor. Sets the class members and check that the class
- * to test is accessible.
- *
- * @access public
- * @param string $className
- * @param string $classPath
- * @param boolean $includeParents Wheter to include the parent's methods in the test.
- * @return void
- */
- function PHPUnit_Skeleton($className, $classPath, $includeParents = FALSE, $includePrivate = TRUE) {
- // Set up the members.
- if (@is_readable($classPath)) {
- $this->className = $className;
- $this->classPath = $classPath;
- } else {
- $this->_handleErrors($classPath . ' is not readable. Cannot create test class.');
- }
-
- // Do we want to include parent methods?
- $this->includeParents = $includeParents;
-
- // Do we want to allow private methods?
- $this->includePrivate = $includePrivate;
- }
-
- /**
- * The class to test may require a special config file before it can be
- * instantiated. This method lets you set that file.
- *
- * @access public
- * @param string $configPath
- * @return void
- */
- function setConfigFile($configFile) {
- // Check that the file is readable
- if (@is_readable($configFile)) {
- $this->configFile = $configFile;
- } else {
- $this->_handleErrors($configFile . ' is not readable. Cannot create test class.');
- }
- }
-
- /**
- * Create the code that will be the skeleton of the test case.
- *
- * The test case must have a clss definition, one var, a constructor
- * setUp, tearDown, and methods. Optionally and by default the code
- * to run the test is added when the class is written to file.
- *
- * @access public
- * @param none
- * @return void
- */
- function createTestClass() {
- // Instantiate the object.
- if (isset($this->configFile)) {
- require_once $this->configFile;
- }
-
- require_once $this->classPath;
-
- // Get the methods.
- $classMethods = get_class_methods($this->className);
-
- // Remove the parent methods if needed.
- if (!$this->includeParents) {
- $parentMethods = get_class_methods(get_parent_class($this->className));
-
- if (count($parentMethods)) {
- $classMethods = array_diff($classMethods, $parentMethods);
- }
- }
-
- // Create the class definition, constructor, setUp and tearDown.
- $this->_createDefinition();
- $this->_createConstructor();
- $this->_createSetUpTearDown();
-
- if (count($classMethods)) {
- // Foreach method create a test case.
- foreach ($classMethods as $method) {
- // Unless it is the constructor.
- if (strcasecmp($this->className, $method) !== 0) {
- // Check for private methods.
- if (!$this->includePrivate && strpos($method, '_') === 0) {
- continue;
- } else {
- $this->_createMethod($method);
- }
- }
- }
- }
-
- // Finis off the class.
- $this->_finishClass();
- }
-
- /**
- * Create the class definition.
- *
- * The definition consist of a header comment, require statment
- * for getting the PHPUnit file, the actual class definition,
- * and the definition of the class member variable.
- *
- * All of the code needed for the new class is stored in the
- * testClass member.
- *
- * @access private
- * @param none
- * @return void
- */
- function _createDefinition() {
- // Create header comment.
- $this->testClass =
- "/**\n" .
- " * PHPUnit test case for " . $this->className . "\n" .
- " * \n" .
- " * The method skeletons below need to be filled in with \n" .
- " * real data so that the tests will run correctly. Replace \n" .
- " * all EXPECTED_VAL and PARAM strings with real data. \n" .
- " * \n" .
- " * Created with PHPUnit_Skeleton on " . date('Y-m-d') . "\n" .
- " */\n";
-
- // Add the require statements.
- $this->testClass .= "require_once 'PHPUnit.php';\n";
-
- // Add the class definition and variable definition.
- $this->testClass .=
- "class " . $this->className . "Test extends PHPUnit_TestCase {\n\n" .
- " var \$" . $this->className . ";\n\n";
- }
-
- /**
- * Create the class constructor. (PHP4 style)
- *
- * The constructor simply calls the PHPUnit_TestCase method.
- * This code is taken from the PHPUnit documentation.
- *
- * All of the code needed for the new class is stored in the
- * testClass member.
- *
- * @access private
- * @param none
- * @return void
- */
- function _createConstructor() {
- // Create the test class constructor.
- $this->testClass.=
- " function " . $this->className . "Test(\$name)\n" .
- " {\n" .
- " \$this->PHPUnit_TestCase(\$name);\n" .
- " }\n\n";
- }
-
- /**
- * Create setUp and tearDown methods.
- *
- * The setUp method creates the instance of the object to test.
- * The tearDown method releases the instance.
- * This code is taken from the PHPUnit documentation.
- *
- * All of the code needed for the new class is stored in the
- * testClass member.
- *
- * @access private
- * @param none
- * @return void
- */
- function _createSetUpTearDown() {
- // Create the setUp method.
- $this->testClass .=
- " function setUp()\n" .
- " {\n";
-
- if (isset($this->configFile)) {
- $this->testClass .=
- " require_once '" . $this->configFile . "';\n";
- }
-
- $this->testClass .=
- " require_once '" . $this->classPath . "';\n" .
- " \$this->" . $this->className . " =& new " . $this->className . "(PARAM);\n" .
- " }\n\n";
-
- // Create the tearDown method.
- $this->testClass .=
- " function tearDown()\n" .
- " {\n" .
- " unset(\$this->" . $this->className . ");\n" .
- " }\n\n";
- }
-
- /**
- * Create a basic skeleton for test methods.
- *
- * This code is taken from the PHPUnit documentation.
- *
- * All of the code needed for the new class is stored in the
- * testClass member.
- *
- * @access private
- * @param none
- * @return void
- */
- function _createMethod($methodName) {
- // Create a test method.
- $this->testClass .=
- " function test" . $methodName . "()\n" .
- " {\n" .
- " \$result = \$this->" . $this->className . "->" . $methodName . "(PARAM);\n" .
- " \$expected = EXPECTED_VAL;\n" .
- " \$this->assertEquals(\$expected, \$result);\n" .
- " }\n\n";
- }
-
- /**
- * Add the closing brace needed for a proper class definition.
- *
- * All of the code needed for the new class is stored in the
- * testClass member.
- *
- * @access private
- * @param none
- * @return void
- */
- function _finishClass() {
- // Close off the class.
- $this->testClass.= "}\n";
- }
-
- /**
- * Create the code that will actually run the test.
- *
- * This code is added by default so that the test can be run
- * just by running the file. To have it not added pass false
- * as the second parameter to the writeTestClass method.
- * This code is taken from the PHPUnit documentation.
- *
- * All of the code needed for the new class is stored in the
- * testClass member.
- *
- * @access private
- * @param none
- * @return void
- */
- function _createTest() {
- // Create a call to the test.
- $test =
- "// Running the test.\n" .
- "\$suite = new PHPUnit_TestSuite('" . $this->className . "Test');\n" .
- "\$result = PHPUnit::run(\$suite);\n" .
- "echo \$result->toString();\n";
-
- return $test;
- }
-
- /**
- * Write the test class to file.
- *
- * This will write the test class created using the createTestClass
- * method to a file called <className>Test.php. By default the file
- * is written to the current directory and will have code to run
- * the test appended to the bottom of the file.
- *
- * @access public
- * @param string $destination The directory to write the file to.
- * @param boolean $addTest Wheter to add the test running code.
- * @return void
- */
- function writeTestClass($destination = './', $addTest = TRUE) {
- // Check for something to write to file.
- if (!isset($this->testClass)) {
- $this->_handleErrors('Noting to write.', PHPUS_WARNING);
- return;
- }
-
- // Open the destination file.
- $fp = fopen($destination . $this->className . 'Test.php', 'w');
- fwrite($fp, "<?php\n");
-
- // Write the test class.
- fwrite($fp, $this->testClass);
-
- // Add the call to test the class in the file if we were asked to.
- if ($addTest) {
- fwrite($fp, $this->_createTest());
- }
-
- // Close the file.
- fwrite($fp, "?>\n");
- fclose($fp);
- }
-
- /**
- * Error handler.
- *
- * This method should be rewritten to use the prefered error
- * handling method. (PEAR_ErrorStack)
- *
- * @access private
- * @param string $message The error message.
- * @param integer $type An indication of the severity of the error.
- * @return void Code may cause PHP to exit.
- */
- function _handleErrors($message, $type = E_USER_ERROR) {
- // For now just echo the message.
- echo $message;
-
- // Check to see if we should quit.
- if ($type == E_USER_ERROR) {
- exit;
- }
- }
-}
-?>
diff --git a/inc/PHPUnit/TestCase.php b/inc/PHPUnit/TestCase.php
deleted file mode 100644
index 69594ed2f8e..00000000000
--- a/inc/PHPUnit/TestCase.php
+++ /dev/null
@@ -1,237 +0,0 @@
-<?php
-//
-// +------------------------------------------------------------------------+
-// | PEAR :: PHPUnit |
-// +------------------------------------------------------------------------+
-// | Copyright (c) 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>. |
-// +------------------------------------------------------------------------+
-// | This source file is subject to version 3.00 of the PHP License, |
-// | that is available at http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +------------------------------------------------------------------------+
-//
-// $Id: TestCase.php,v 1.16 2004/12/22 08:06:11 sebastian Exp $
-//
-
-require_once 'PHPUnit/Assert.php';
-require_once 'PHPUnit/TestResult.php';
-
-/**
- * A TestCase defines the fixture to run multiple tests.
- *
- * To define a TestCase
- *
- * 1) Implement a subclass of PHPUnit_TestCase.
- * 2) Define instance variables that store the state of the fixture.
- * 3) Initialize the fixture state by overriding setUp().
- * 4) Clean-up after a test by overriding tearDown().
- *
- * Each test runs in its own fixture so there can be no side effects
- * among test runs.
- *
- * Here is an example:
- *
- * <code>
- * <?php
- * class MathTest extends PHPUnit_TestCase {
- * var $fValue1;
- * var $fValue2;
- *
- * function MathTest($name) {
- * $this->PHPUnit_TestCase($name);
- * }
- *
- * function setUp() {
- * $this->fValue1 = 2;
- * $this->fValue2 = 3;
- * }
- * }
- * ?>
- * </code>
- *
- * For each test implement a method which interacts with the fixture.
- * Verify the expected results with assertions specified by calling
- * assert with a boolean.
- *
- * <code>
- * <?php
- * function testPass() {
- * $this->assertTrue($this->fValue1 + $this->fValue2 == 5);
- * }
- * ?>
- * </code>
- *
- * @author Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @copyright Copyright &copy; 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @license http://www.php.net/license/3_0.txt The PHP License, Version 3.0
- * @category Testing
- * @package PHPUnit
- */
-class PHPUnit_TestCase extends PHPUnit_Assert {
- /**
- * @var boolean
- * @access private
- */
- var $_failed = FALSE;
-
- /**
- * The name of the test case.
- *
- * @var string
- * @access private
- */
- var $_name = '';
-
- /**
- * PHPUnit_TestResult object
- *
- * @var object
- * @access private
- */
- var $_result;
-
- /**
- * Constructs a test case with the given name.
- *
- * @param string
- * @access public
- */
- function PHPUnit_TestCase($name = FALSE) {
- if ($name !== FALSE) {
- $this->setName($name);
- }
- }
-
- /**
- * Counts the number of test cases executed by run(TestResult result).
- *
- * @return integer
- * @access public
- */
- function countTestCases() {
- return 1;
- }
-
- /**
- * Gets the name of a TestCase.
- *
- * @return string
- * @access public
- */
- function getName() {
- return $this->_name;
- }
-
- /**
- * Runs the test case and collects the results in a given TestResult object.
- *
- * @param object
- * @return object
- * @access public
- */
- function run(&$result) {
- $this->_result = &$result;
- $this->_result->run($this);
-
- return $this->_result;
- }
-
- /**
- * Runs the bare test sequence.
- *
- * @access public
- */
- function runBare() {
- $this->setUp();
- $this->runTest();
- $this->tearDown();
- $this->pass();
- }
-
- /**
- * Override to run the test and assert its state.
- *
- * @access protected
- */
- function runTest() {
- call_user_func(
- array(
- &$this,
- $this->_name
- )
- );
- }
-
- /**
- * Sets the name of a TestCase.
- *
- * @param string
- * @access public
- */
- function setName($name) {
- $this->_name = $name;
- }
-
- /**
- * Returns a string representation of the test case.
- *
- * @return string
- * @access public
- */
- function toString() {
- return '';
- }
-
- /**
- * Creates a default TestResult object.
- *
- * @return object
- * @access protected
- */
- function &createResult() {
- return new PHPUnit_TestResult;
- }
-
- /**
- * Fails a test with the given message.
- *
- * @param string
- * @access protected
- */
- function fail($message = '') {
- $this->_result->addFailure($this, $message);
- $this->_failed = TRUE;
- }
-
- /**
- * Passes a test.
- *
- * @access protected
- */
- function pass() {
- if (!$this->_failed) {
- $this->_result->addPassedTest($this);
- }
- }
-
- /**
- * Sets up the fixture, for example, open a network connection.
- * This method is called before a test is executed.
- *
- * @access protected
- * @abstract
- */
- function setUp() { /* abstract */ }
-
- /**
- * Tears down the fixture, for example, close a network connection.
- * This method is called after a test is executed.
- *
- * @access protected
- * @abstract
- */
- function tearDown() { /* abstract */ }
-}
-?>
diff --git a/inc/PHPUnit/TestDecorator.php b/inc/PHPUnit/TestDecorator.php
deleted file mode 100644
index 6486309a70b..00000000000
--- a/inc/PHPUnit/TestDecorator.php
+++ /dev/null
@@ -1,110 +0,0 @@
-<?php
-//
-// +------------------------------------------------------------------------+
-// | PEAR :: PHPUnit |
-// +------------------------------------------------------------------------+
-// | Copyright (c) 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>. |
-// +------------------------------------------------------------------------+
-// | This source file is subject to version 3.00 of the PHP License, |
-// | that is available at http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +------------------------------------------------------------------------+
-//
-// $Id: TestDecorator.php,v 1.12 2005/05/14 05:58:38 sebastian Exp $
-//
-
-require_once 'PHPUnit/TestCase.php';
-require_once 'PHPUnit/TestSuite.php';
-
-/**
- * A Decorator for Tests.
- *
- * Use TestDecorator as the base class for defining new
- * test decorators. Test decorator subclasses can be introduced
- * to add behaviour before or after a test is run.
- *
- * @author Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @copyright Copyright &copy; 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @license http://www.php.net/license/3_0.txt The PHP License, Version 3.0
- * @category Testing
- * @package PHPUnit
- */
-class PHPUnit_TestDecorator {
- /**
- * The Test to be decorated.
- *
- * @var object
- * @access protected
- */
- var $_test = NULL;
-
- /**
- * Constructor.
- *
- * @param object
- * @access public
- */
- function PHPUnit_TestDecorator(&$test) {
- if (is_object($test) &&
- (is_a($test, 'PHPUnit_TestCase') ||
- is_a($test, 'PHPUnit_TestSuite'))) {
-
- $this->_test = &$test;
- }
- }
-
- /**
- * Runs the test and collects the
- * result in a TestResult.
- *
- * @param object
- * @access public
- */
- function basicRun(&$result) {
- $this->_test->run($result);
- }
-
- /**
- * Counts the number of test cases that
- * will be run by this test.
- *
- * @return integer
- * @access public
- */
- function countTestCases() {
- return $this->_test->countTestCases();
- }
-
- /**
- * Returns the test to be run.
- *
- * @return object
- * @access public
- */
- function &getTest() {
- return $this->_test;
- }
-
- /**
- * Runs the decorated test and collects the
- * result in a TestResult.
- *
- * @param object
- * @access public
- * @abstract
- */
- function run(&$result) { /* abstract */ }
-
- /**
- * Returns a string representation of the test.
- *
- * @return string
- * @access public
- */
- function toString() {
- return $this->_test->toString();
- }
-}
-?>
diff --git a/inc/PHPUnit/TestFailure.php b/inc/PHPUnit/TestFailure.php
deleted file mode 100644
index 69c8b80bcbb..00000000000
--- a/inc/PHPUnit/TestFailure.php
+++ /dev/null
@@ -1,88 +0,0 @@
-<?php
-//
-// +------------------------------------------------------------------------+
-// | PEAR :: PHPUnit |
-// +------------------------------------------------------------------------+
-// | Copyright (c) 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>. |
-// +------------------------------------------------------------------------+
-// | This source file is subject to version 3.00 of the PHP License, |
-// | that is available at http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +------------------------------------------------------------------------+
-//
-// $Id: TestFailure.php,v 1.10 2005/05/14 05:58:38 sebastian Exp $
-//
-
-/**
- * A TestFailure collects a failed test together with the caught exception.
- *
- * @author Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @copyright Copyright &copy; 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @license http://www.php.net/license/3_0.txt The PHP License, Version 3.0
- * @category Testing
- * @package PHPUnit
- */
-class PHPUnit_TestFailure {
- /**
- * @var object
- * @access private
- */
- var $_failedTest;
-
- /**
- * @var string
- * @access private
- */
- var $_thrownException;
-
- /**
- * Constructs a TestFailure with the given test and exception.
- *
- * @param object
- * @param string
- * @access public
- */
- function PHPUnit_TestFailure(&$failedTest, &$thrownException) {
- $this->_failedTest = &$failedTest;
- $this->_thrownException = &$thrownException;
- }
-
- /**
- * Gets the failed test.
- *
- * @return object
- * @access public
- */
- function &failedTest() {
- return $this->_failedTest;
- }
-
- /**
- * Gets the thrown exception.
- *
- * @return object
- * @access public
- */
- function &thrownException() {
- return $this->_thrownException;
- }
-
- /**
- * Returns a short description of the failure.
- *
- * @return string
- * @access public
- */
- function toString() {
- return sprintf(
- "TestCase %s->%s() failed: %s\n",
-
- get_class($this->_failedTest),
- $this->_failedTest->getName(),
- $this->_thrownException
- );
- }
-}
-?>
diff --git a/inc/PHPUnit/TestListener.php b/inc/PHPUnit/TestListener.php
deleted file mode 100644
index 7685df46792..00000000000
--- a/inc/PHPUnit/TestListener.php
+++ /dev/null
@@ -1,120 +0,0 @@
-<?php
-//
-// +------------------------------------------------------------------------+
-// | PEAR :: PHPUnit |
-// +------------------------------------------------------------------------+
-// | Copyright (c) 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>. |
-// +------------------------------------------------------------------------+
-// | This source file is subject to version 3.00 of the PHP License, |
-// | that is available at http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +------------------------------------------------------------------------+
-//
-// $Id: TestListener.php,v 1.9 2004/12/22 08:06:11 sebastian Exp $
-//
-
-/**
- * A Listener for test progress.
- *
- * Here is an example:
- *
- * <code>
- * <?php
- * require_once 'PHPUnit.php';
- * require_once 'PHPUnit/TestListener.php';
- *
- * class MathTest extends PHPUnit_TestCase {
- * var $fValue1;
- * var $fValue2;
- *
- * function MathTest($name) {
- * $this->PHPUnit_TestCase($name);
- * }
- *
- * function setUp() {
- * $this->fValue1 = 2;
- * $this->fValue2 = 3;
- * }
- *
- * function testAdd() {
- * $this->assertTrue($this->fValue1 + $this->fValue2 == 4);
- * }
- * }
- *
- * class MyListener extends PHPUnit_TestListener {
- * function addError(&$test, &$t) {
- * print "MyListener::addError() called.\n";
- * }
- *
- * function addFailure(&$test, &$t) {
- * print "MyListener::addFailure() called.\n";
- * }
- *
- * function endTest(&$test) {
- * print "MyListener::endTest() called.\n";
- * }
- *
- * function startTest(&$test) {
- * print "MyListener::startTest() called.\n";
- * }
- * }
- *
- * $suite = new PHPUnit_TestSuite;
- * $suite->addTest(new MathTest('testAdd'));
- *
- * $result = new PHPUnit_TestResult;
- * $result->addListener(new MyListener);
- *
- * $suite->run($result);
- * print $result->toString();
- * ?>
- * </code>
- *
- * @author Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @copyright Copyright &copy; 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @license http://www.php.net/license/3_0.txt The PHP License, Version 3.0
- * @category Testing
- * @package PHPUnit
- */
-class PHPUnit_TestListener {
- /**
- * An error occurred.
- *
- * @param object
- * @param object
- * @access public
- * @abstract
- */
- function addError(&$test, &$t) { /*abstract */ }
-
- /**
- * A failure occurred.
- *
- * @param object
- * @param object
- * @access public
- * @abstract
- */
- function addFailure(&$test, &$t) { /*abstract */ }
-
- /**
- * A test ended.
- *
- * @param object
- * @access public
- * @abstract
- */
- function endTest(&$test) { /*abstract */ }
-
- /**
- * A test started.
- *
- * @param object
- * @access public
- * @abstract
- */
- function startTest(&$test) { /*abstract */ }
-}
-?>
diff --git a/inc/PHPUnit/TestResult.php b/inc/PHPUnit/TestResult.php
deleted file mode 100644
index ee60b2c5b50..00000000000
--- a/inc/PHPUnit/TestResult.php
+++ /dev/null
@@ -1,300 +0,0 @@
-<?php
-//
-// +------------------------------------------------------------------------+
-// | PEAR :: PHPUnit |
-// +------------------------------------------------------------------------+
-// | Copyright (c) 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>. |
-// +------------------------------------------------------------------------+
-// | This source file is subject to version 3.00 of the PHP License, |
-// | that is available at http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +------------------------------------------------------------------------+
-//
-// $Id: TestResult.php,v 1.13 2005/05/14 05:58:38 sebastian Exp $
-//
-
-require_once 'PHPUnit/TestFailure.php';
-require_once 'PHPUnit/TestListener.php';
-
-/**
- * A TestResult collects the results of executing a test case.
- *
- * @author Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @copyright Copyright &copy; 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @license http://www.php.net/license/3_0.txt The PHP License, Version 3.0
- * @category Testing
- * @package PHPUnit
- */
-class PHPUnit_TestResult {
- /**
- * @var array
- * @access protected
- */
- var $_errors = array();
-
- /**
- * @var array
- * @access protected
- */
- var $_failures = array();
-
- /**
- * @var array
- * @access protected
- */
- var $_listeners = array();
-
- /**
- * @var array
- * @access protected
- */
- var $_passedTests = array();
-
- /**
- * @var integer
- * @access protected
- */
- var $_runTests = 0;
-
- /**
- * @var boolean
- * @access private
- */
- var $_stop = FALSE;
-
- /**
- * Adds an error to the list of errors.
- * The passed in exception caused the error.
- *
- * @param object
- * @param object
- * @access public
- */
- function addError(&$test, &$t) {
- $this->_errors[] = new PHPUnit_TestFailure($test, $t);
-
- for ($i = 0; $i < sizeof($this->_listeners); $i++) {
- $this->_listeners[$i]->addError($test, $t);
- }
- }
-
- /**
- * Adds a failure to the list of failures.
- * The passed in exception caused the failure.
- *
- * @param object
- * @param object
- * @access public
- */
- function addFailure(&$test, &$t) {
- $this->_failures[] = new PHPUnit_TestFailure($test, $t);
-
- for ($i = 0; $i < sizeof($this->_listeners); $i++) {
- $this->_listeners[$i]->addFailure($test, $t);
- }
- }
-
- /**
- * Registers a TestListener.
- *
- * @param object
- * @access public
- */
- function addListener(&$listener) {
- if (is_object($listener) &&
- is_a($listener, 'PHPUnit_TestListener')) {
- $this->_listeners[] = &$listener;
- }
- }
-
- /**
- * Adds a passed test to the list of passed tests.
- *
- * @param object
- * @access public
- */
- function addPassedTest(&$test) {
- $this->_passedTests[] = &$test;
- }
-
- /**
- * Informs the result that a test was completed.
- *
- * @param object
- * @access public
- */
- function endTest(&$test) {
- for ($i = 0; $i < sizeof($this->_listeners); $i++) {
- $this->_listeners[$i]->endTest($test);
- }
- }
-
- /**
- * Gets the number of detected errors.
- *
- * @return integer
- * @access public
- */
- function errorCount() {
- return sizeof($this->_errors);
- }
-
- /**
- * Returns an Enumeration for the errors.
- *
- * @return array
- * @access public
- */
- function &errors() {
- return $this->_errors;
- }
-
- /**
- * Gets the number of detected failures.
- *
- * @return integer
- * @access public
- */
- function failureCount() {
- return sizeof($this->_failures);
- }
-
- /**
- * Returns an Enumeration for the failures.
- *
- * @return array
- * @access public
- */
- function &failures() {
- return $this->_failures;
- }
-
- /**
- * Returns an Enumeration for the passed tests.
- *
- * @return array
- * @access public
- */
- function &passedTests() {
- return $this->_passedTests;
- }
-
- /**
- * Unregisters a TestListener.
- * This requires the Zend Engine 2 (to work properly).
- *
- * @param object
- * @access public
- */
- function removeListener(&$listener) {
- for ($i = 0; $i < sizeof($this->_listeners); $i++) {
- if ($this->_listeners[$i] === $listener) {
- unset($this->_listeners[$i]);
- }
- }
- }
-
- /**
- * Runs a TestCase.
- *
- * @param object
- * @access public
- */
- function run(&$test) {
- $this->startTest($test);
- $this->_runTests++;
- $test->runBare();
- $this->endTest($test);
- }
-
- /**
- * Gets the number of run tests.
- *
- * @return integer
- * @access public
- */
- function runCount() {
- return $this->_runTests;
- }
-
- /**
- * Checks whether the test run should stop.
- *
- * @access public
- */
- function shouldStop() {
- return $this->_stop;
- }
-
- /**
- * Informs the result that a test will be started.
- *
- * @param object
- * @access public
- */
- function startTest(&$test) {
- for ($i = 0; $i < sizeof($this->_listeners); $i++) {
- $this->_listeners[$i]->startTest($test);
- }
- }
-
- /**
- * Marks that the test run should stop.
- *
- * @access public
- */
- function stop() {
- $this->_stop = TRUE;
- }
-
- /**
- * Returns a HTML representation of the test result.
- *
- * @return string
- * @access public
- */
- function toHTML() {
- return '<pre>' . htmlspecialchars($this->toString()) . '</pre>';
- }
-
- /**
- * Returns a text representation of the test result.
- *
- * @return string
- * @access public
- */
- function toString() {
- $result = '';
-
- foreach ($this->_passedTests as $passedTest) {
- $result .= sprintf(
- "TestCase %s->%s() passed\n",
-
- get_class($passedTest),
- $passedTest->getName()
- );
- }
-
- foreach ($this->_failures as $failedTest) {
- $result .= $failedTest->toString();
- }
-
- return $result;
- }
- /**
- * Returns whether the entire test was successful or not.
- *
- * @return boolean
- * @access public
- */
- function wasSuccessful() {
- if (empty($this->_errors) && empty($this->_failures)) {
- return TRUE;
- } else {
- return FALSE;
- }
- }
-}
-?>
diff --git a/inc/PHPUnit/TestSuite.php b/inc/PHPUnit/TestSuite.php
deleted file mode 100644
index f2396748ba3..00000000000
--- a/inc/PHPUnit/TestSuite.php
+++ /dev/null
@@ -1,220 +0,0 @@
-<?php
-//
-// +------------------------------------------------------------------------+
-// | PEAR :: PHPUnit |
-// +------------------------------------------------------------------------+
-// | Copyright (c) 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>. |
-// +------------------------------------------------------------------------+
-// | This source file is subject to version 3.00 of the PHP License, |
-// | that is available at http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +------------------------------------------------------------------------+
-//
-// $Id: TestSuite.php,v 1.14 2005/05/14 05:58:38 sebastian Exp $
-//
-
-require_once 'PHPUnit/TestCase.php';
-
-/**
- * A TestSuite is a Composite of Tests. It runs a collection of test cases.
- *
- * Here is an example using the dynamic test definition.
- *
- * <code>
- * <?php
- * $suite = new PHPUnit_TestSuite();
- * $suite->addTest(new MathTest('testPass'));
- * ?>
- * </code>
- *
- * Alternatively, a TestSuite can extract the tests to be run automatically.
- * To do so you pass the classname of your TestCase class to the TestSuite
- * constructor.
- *
- * <code>
- * <?php
- * $suite = new TestSuite('classname');
- * ?>
- * </code>
- *
- * This constructor creates a suite with all the methods starting with
- * "test" that take no arguments.
- *
- * @author Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @copyright Copyright &copy; 2002-2005 Sebastian Bergmann <sb@sebastian-bergmann.de>
- * @license http://www.php.net/license/3_0.txt The PHP License, Version 3.0
- * @category Testing
- * @package PHPUnit
- */
-class PHPUnit_TestSuite {
- /**
- * The name of the test suite.
- *
- * @var string
- * @access private
- */
- var $_name = '';
-
- /**
- * The tests in the test suite.
- *
- * @var array
- * @access private
- */
- var $_tests = array();
-
- /**
- * Constructs a TestSuite.
- *
- * @param mixed
- * @access public
- */
- function PHPUnit_TestSuite($test = FALSE) {
- if ($test !== FALSE) {
- $this->setName($test);
- $this->addTestSuite($test);
- }
- }
-
- /**
- * Adds a test to the suite.
- *
- * @param object
- * @access public
- */
- function addTest(&$test) {
- $this->_tests[] = &$test;
- }
-
- /**
- * Adds the tests from the given class to the suite.
- *
- * @param string
- * @access public
- */
- function addTestSuite($testClass) {
- if (class_exists($testClass)) {
- $methods = get_class_methods($testClass);
- $parentClasses = array(strtolower($testClass));
- $parentClass = $testClass;
-
- while(is_string($parentClass = get_parent_class($parentClass))) {
- $parentClasses[] = $parentClass;
- }
-
- foreach ($methods as $method) {
- if (substr($method, 0, 4) == 'test' &&
- !in_array($method, $parentClasses)) {
- $this->addTest(new $testClass($method));
- }
- }
- }
- }
-
- /**
- * Counts the number of test cases that will be run by this test.
- *
- * @return integer
- * @access public
- */
- function countTestCases() {
- $count = 0;
-
- foreach ($this->_tests as $test) {
- $count += $test->countTestCases();
- }
-
- return $count;
- }
-
- /**
- * Returns the name of the suite.
- *
- * @return string
- * @access public
- */
- function getName() {
- return $this->_name;
- }
-
- /**
- * Runs the tests and collects their result in a TestResult.
- *
- * @param object
- * @access public
- */
- function run(&$result) {
- for ($i = 0; $i < sizeof($this->_tests) && !$result->shouldStop(); $i++) {
- $this->_tests[$i]->run($result);
- }
- }
-
- /**
- * Runs a test.
- *
- * @param object
- * @param object
- * @access public
- */
- function runTest(&$test, &$result) {
- $test->run($result);
- }
-
- /**
- * Sets the name of the suite.
- *
- * @param string
- * @access public
- */
- function setName($name) {
- $this->_name = $name;
- }
-
- /**
- * Returns the test at the given index.
- *
- * @param integer
- * @return object
- * @access public
- */
- function &testAt($index) {
- if (isset($this->_tests[$index])) {
- return $this->_tests[$index];
- } else {
- return FALSE;
- }
- }
-
- /**
- * Returns the number of tests in this suite.
- *
- * @return integer
- * @access public
- */
- function testCount() {
- return sizeof($this->_tests);
- }
-
- /**
- * Returns the tests as an enumeration.
- *
- * @return array
- * @access public
- */
- function &tests() {
- return $this->_tests;
- }
-
- /**
- * Returns a string representation of the test suite.
- *
- * @return string
- * @access public
- */
- function toString() {
- return '';
- }
-}
-?>
diff --git a/inc/System.php b/inc/System.php
deleted file mode 100644
index a9279ff687d..00000000000
--- a/inc/System.php
+++ /dev/null
@@ -1,540 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Tomas V.V.Cox <cox@idecnet.com> |
-// +----------------------------------------------------------------------+
-//
-// $Id: System.php,v 1.36 2004/06/15 16:33:46 pajoye Exp $
-//
-
-oc_require_once( 'PEAR.php');
-oc_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 <cox@idecnet.com>
-* @version $Revision: 1.36 $
-* @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 <ssb@php.net>
- */
- 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 <n> -> max depth of recursion
- * -name <pattern> -> 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/inc/User/backend.php b/inc/User/backend.php
deleted file mode 100755
index 9d10adefd40..00000000000
--- a/inc/User/backend.php
+++ /dev/null
@@ -1,161 +0,0 @@
-<?php
-
-/**
-* ownCloud
-*
-* @author Frank Karlitschek
-* @copyright 2010 Frank Karlitschek karlitschek@kde.org
-*
-* This library is free software; you can redistribute it and/or
-* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
-* License as published by the Free Software Foundation; either
-* version 3 of the License, or 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 AFFERO 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, see <http://www.gnu.org/licenses/>.
-*
-*/
-
-
-
-/**
- * Base class for user management
- *
- */
-abstract class OC_USER_BACKEND {
-
- /**
- * Check if the login button is pressed and log the user in
- *
- */
- abstract public static function loginListener();
-
- /**
- * Try to create a new user
- *
- * @param string $username The username of the user to create
- * @param string $password The password of the new user
- */
- abstract public static function createUser($username, $password);
-
- /**
- * Try to login a user
- *
- * @param string $username The username of the user to log in
- * @param string $password The password of the user
- */
- abstract public static function login($username, $password);
-
- /**
- * Check if the logout button is pressed and logout the user
- *
- */
- abstract public static function logoutListener();
-
- /**
- * Check if some user is logged in
- *
- */
- abstract public static function isLoggedIn();
-
- /**
- * Try to create a new group
- *
- * @param string $groupName The name of the group to create
- */
- abstract public static function createGroup($groupName);
-
- /**
- * Get the ID of a user
- *
- * @param string $username Name of the user to find the ID
- * @param boolean $noCache If false the cache is used to find the ID
- */
- abstract public static function getUserId($username, $noCache=false);
-
- /**
- * Get the ID of a group
- *
- * @param string $groupName Name of the group to find the ID
- * @param boolean $noCache If false the cache is used to find the ID
- */
- abstract public static function getGroupId($groupName, $noCache=false);
-
- /**
- * Get the name of a group
- *
- * @param string $groupId ID of the group
- * @param boolean $noCache If false the cache is used to find the name of the group
- */
- abstract public static function getGroupName($groupId, $noCache=false);
-
- /**
- * Check if a user belongs to a group
- *
- * @param string $username Name of the user to check
- * @param string $groupName Name of the group
- */
- abstract public static function inGroup($username, $groupName);
-
- /**
- * Add a user to a group
- *
- * @param string $username Name of the user to add to group
- * @param string $groupName Name of the group in which add the user
- */
- abstract public static function addToGroup($username, $groupName);
-
- /**
- * Remove a user from a group
- *
- * @param string $username Name of the user to remove from group
- * @param string $groupName Name of the group from which remove the user
- */
- abstract public static function removeFromGroup($username,$groupName);
-
- /**
- * Generate a random password
- */
- abstract public static function generatePassword();
-
- /**
- * Get all groups the user belongs to
- *
- * @param string $username Name of the user
- */
- abstract public static function getUserGroups($username);
-
- /**
- * Set the password of a user
- *
- * @param string $username User who password will be changed
- * @param string $password The new password for the user
- */
- abstract public static function setPassword($username, $password);
-
- /**
- * Check if the password of the user is correct
- *
- * @param string $username Name of the user
- * @param string $password Password of the user
- */
- abstract public static function checkPassword($username, $password);
-
-
- /**
- * get a list of all users
- *
- */
- abstract public static function getUsers();
-
- /**
- * get a list of all groups
- *
- */
- abstract public static function getGroups();
-}
diff --git a/inc/User/database.php b/inc/User/database.php
deleted file mode 100755
index bd33ba6b6e9..00000000000
--- a/inc/User/database.php
+++ /dev/null
@@ -1,417 +0,0 @@
-<?php
-
-/**
-* ownCloud
-*
-* @author Frank Karlitschek
-* @copyright 2010 Frank Karlitschek karlitschek@kde.org
-*
-* This library is free software; you can redistribute it and/or
-* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
-* License as published by the Free Software Foundation; either
-* version 3 of the License, or 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 AFFERO 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, see <http://www.gnu.org/licenses/>.
-*
-*/
-
-oc_require_once('inc/User/backend.php');
-
-
-
-/**
- * Class for user management in a SQL Database (e.g. MySQL, SQLite)
- *
- */
-class OC_USER_DATABASE extends OC_USER_BACKEND {
- static private $userGroupCache=array();
-
- /**
- * Check if the login button is pressed and log the user in
- *
- */
- public static function loginListener(){
- if ( isset($_POST['loginbutton']) AND isset($_POST['password']) AND isset($_POST['login']) ) {
- if ( OC_USER::login($_POST['login'], $_POST['password']) ) {
- echo 1;
- OC_LOG::event($_SESSION['username'], 1, '');
- echo 2;
- if ( (isset($CONFIG_HTTPFORCESSL) AND $CONFIG_HTTPFORCESSL)
- OR (isset($_SERVER['HTTPS']) AND ('on' == $_SERVER['HTTPS'])) ) {
- $url = 'https://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
- } else {
- $url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
- }
- header("Location: $url");
- die();
- } else {
- return('error');
- }
- }
- return('');
- }
-
- /**
- * Try to create a new user
- *
- * @param string $username The username of the user to create
- * @param string $password The password of the new user
- */
- public static function createUser($username, $password) {
- self::clearCache();
- global $CONFIG_DBTABLEPREFIX;
- // Check if the user already exists
- if ( 0 != OC_USER::getUserId($username, true) ) {
- return false;
- } else {
- $usernameClean = strToLower($username);
- $password = sha1($password);
- $username = OC_DB::escape($username);
- $usernameClean = OC_DB::escape($usernameClean);
- $query = "INSERT INTO `{$CONFIG_DBTABLEPREFIX}users` (`user_name` ,`user_name_clean` ,`user_password`) "
- . "VALUES ('$username', '$usernameClean', '$password')";
- $result = OC_DB::query($query);
- return $result ? true : false;
- }
- }
-
- /**
- * Try to login a user
- *
- * @param string $username The username of the user to log in
- * @param string $password The password of the user
- */
- public static function login($username,$password){
- global $CONFIG_DBTABLEPREFIX;
-
- $password = sha1($password);
- $usernameClean = strtolower($username);
- $username = OC_DB::escape($username);
- $usernameClean = OC_DB::escape($usernameClean);
- $query = "SELECT user_id FROM {$CONFIG_DBTABLEPREFIX}users "
- . "WHERE user_name_clean = '$usernameClean' AND user_password = '$password' LIMIT 1";
- $result = OC_DB::select($query);
- if ( isset($result[0]) AND isset($result[0]['user_id']) ) {
- $_SESSION['user_id'] = $result[0]['user_id'];
- $_SESSION['username'] = $username;
- $_SESSION['username_clean'] = $usernameClean;
- return true;
- } else {
- return false;
- }
- }
-
- /**
- * Check if the logout button is pressed and logout the user
- *
- */
- public static function logoutListener() {
- global $WEBROOT;
- if ( isset($_GET['logoutbutton']) AND isset($_SESSION['username']) ) {
- OC_LOG::event($_SESSION['username'], 2, '');
- $_SESSION['user_id'] = false;
- $_SESSION['username'] = '';
- $_SESSION['username_clean'] = '';
-
- header("location: $WEBROOT");
- }
- }
-
- /**
- * Check if the user is logged in
- *
- */
- public static function isLoggedIn() {
- if ( isset($_SESSION['user_id']) AND $_SESSION['user_id'] ) {
- return true;
- } else {
- return false;
- }
- }
-
- /**
- * Try to create a new group
- *
- * @param string $groupName The name of the group to create
- */
- public static function createGroup($groupName) {
- self::clearCache();
- global $CONFIG_DBTABLEPREFIX;
- if (0 == OC_USER::getGroupId($groupName) ) {
- $groupName = OC_DB::escape($groupName);
- $query = "INSERT INTO `{$CONFIG_DBTABLEPREFIX}groups` (`group_name`) VALUES ('$groupName')";
- $result = OC_DB::query($query);
- return $result ? true : false;
- } else {
- return false;
- }
- }
-
- /**
- * Get the ID of a user
- *
- * @param string $username Name of the user to find the ID
- * @param boolean $noCache If false the cache is used to find the ID
- */
- public static function getUserId($username, $noCache=false) {
- global $CONFIG_DBTABLEPREFIX;
-
- $usernameClean = strToLower($username);
- // Try to use cached value to avoid an SQL query
- if ( !$noCache AND isset($_SESSION['user_id_cache'][$usernameClean]) ) {
- return $_SESSION['user_id_cache'][$usernameClean];
- }
- $usernameClean = OC_DB::escape($usernameClean);
- $query = "SELECT user_id FROM {$CONFIG_DBTABLEPREFIX}users WHERE user_name_clean = '$usernameClean'";
- $result = OC_DB::select($query);
- if ( !is_array($result) ) {
- return 0;
- }
- if ( isset($result[0]) AND isset($result[0]['user_id']) ) {
- $_SESSION['user_id_cache'][$usernameClean] = $result[0]['user_id'];
- return $result[0]['user_id'];
- } else {
- return 0;
- }
- }
-
- /**
- * Get the ID of a group
- *
- * @param string $groupName Name of the group to find the ID
- * @param boolean $noCache If false the cache is used to find the ID
- */
- public static function getGroupId($groupName, $noCache=false) {
- global $CONFIG_DBTABLEPREFIX;
-
- // Try to use cached value to avoid an SQL query
- if ( !$noCache AND isset($_SESSION['group_id_cache'][$groupName]) ) {
- return $_SESSION['group_id_cache'][$groupName];
- }
- $groupName = OC_DB::escape($groupName);
- $query = "SELECT group_id FROM {$CONFIG_DBTABLEPREFIX}groups WHERE group_name = '$groupName'";
- $result = OC_DB::select($query);
- if ( !is_array($result) ) {
- return 0;
- }
- if ( isset($result[0]) AND isset($result[0]['group_id']) ){
- $_SESSION['group_id_cache'][$groupName] = $result[0]['group_id'];
- return $result[0]['group_id'];
- } else {
- return 0;
- }
- }
-
- /**
- * Get the name of a group
- *
- * @param string $groupId ID of the group
- * @param boolean $noCache If false the cache is used to find the name of the group
- */
- public static function getGroupName($groupId, $noCache=false) {
- global $CONFIG_DBTABLEPREFIX;
-
- // Try to use cached value to avoid an sql query
- if ( !$noCache AND ($name = array_search($groupId, $_SESSION['group_id_cache'])) ) {
- return $name;
- }
- $groupId = (integer)$groupId;
- $query = "SELECT group_name FROM {$CONFIG_DBTABLEPREFIX}groups WHERE group_id = '$groupId' LIMIT 1";
- $result = OC_DB::select($query);
- if ( isset($result[0]) AND isset($result[0]['group_name']) ) {
- return $result[0]['group_name'];
- } else {
- return 0;
- }
- }
-
- /**
- * Check if a user belongs to a group
- *
- * @param string $username Name of the user to check
- * @param string $groupName Name of the group
- */
- public static function inGroup($username,$groupName) {
- global $CONFIG_DBTABLEPREFIX;
- $userId = OC_USER::getUserId($username);
- $groupId = OC_USER::getGroupId($groupName);
- self::getUserGroups($username);
- $groups=self::$userGroupCache[$userId];
- return (array_search($groupId,$groups)!==false);
- }
-
- /**
- * Add a user to a group
- *
- * @param string $username Name of the user to add to group
- * @param string $groupName Name of the group in which add the user
- */
- public static function addToGroup($username, $groupName) {
- global $CONFIG_DBTABLEPREFIX;
- self::clearCache();
- if ( !OC_USER::inGroup($username, $groupName) ) {
- $userId = OC_USER::getUserId($username,true);
- $groupId = OC_USER::getGroupId($groupName,true);
- if ( (0 != $groupId) AND (0 != $userId) ) {
- $query = "INSERT INTO `{$CONFIG_DBTABLEPREFIX}user_group` (`user_id` ,`group_id`) VALUES ('$userId', '$groupId');";
- $result = OC_DB::query($query);
- if ( $result ) {
- self::clearCache();
- return true;
- } else {
- return false;
- }
- } else {
- return false;
- }
- } else {
- return true;
- }
- }
-
- /**
- * Remove a user from a group
- *
- * @param string $username Name of the user to remove from group
- * @param string $groupName Name of the group from which remove the user
- */
- public static function removeFromGroup($username,$groupName){
- global $CONFIG_DBTABLEPREFIX;
- self::clearCache();
- if (OC_USER::inGroup($username, $groupName) ) {
- $userId = OC_USER::getUserId($username,true);
- $groupId = OC_USER::getGroupId($groupName,true);
- if ( (0 != $groupId) AND (0 != $userId) ) {
- $query="DELETE FROM `{$CONFIG_DBTABLEPREFIX}user_group` WHERE `group_id` =$groupId AND `user_id`=$userId";
- $result = OC_DB::query($query);
- if ( $result ) {
- self::clearCache();
- return true;
- } else {
- return false;
- }
- }
- }
- return false;
- }
-
- /**
- * Generate a random password
- */
- public static function generatePassword(){
- return uniqId();
- }
-
- /**
- * Get all groups the user belongs to
- *
- * @param string $username Name of the user
- */
- public static function getUserGroups($username) {
- global $CONFIG_DBTABLEPREFIX;
-
- $userId = OC_USER::getUserId($username);
- if(!isset(self::$userGroupCache[$userId])){
- $query = "SELECT group_id FROM {$CONFIG_DBTABLEPREFIX}user_group WHERE user_id = '$userId'";
- $result = OC_DB::select($query);
- $groupsId = array();
- if ( is_array($result) ) {
- foreach ( $result as $group ) {
- $groupId = $group['group_id'];
- $groupsId[]=$groupId;
- }
- }
- self::$userGroupCache[$userId]=$groupsId;
- return $groupsId;
- }else{
- return self::$userGroupCache[$userId];
- }
- }
-
- /**
- * Set the password of a user
- *
- * @param string $username User who password will be changed
- * @param string $password The new password for the user
- */
- public static function setPassword($username, $password) {
- global $CONFIG_DBTABLEPREFIX;
-
- $password = sha1($password);
- $userId = OC_USER::getUserId($username);
- $query = "UPDATE {$CONFIG_DBTABLEPREFIX}users SET user_password = '$password' WHERE user_id ='$userId'";
- $result = OC_DB::query($query);
- if ( $result ) {
- return true;
- } else {
- return false;
- }
- }
-
- /**
- * Check if the password of the user is correct
- *
- * @param string $username Name of the user
- * @param string $password Password of the user
- */
- public static function checkPassword($username, $password) {
- global $CONFIG_DBTABLEPREFIX;
-
- $password = sha1($password);
- $usernameClean = strToLower($username);
- $usernameClean = OC_DB::escape($usernameClean);
- $username = OC_DB::escape($username);
- $query = "SELECT user_id FROM `{$CONFIG_DBTABLEPREFIX}users` "
- . "WHERE user_name_clean = '$usernameClean' AND user_password = '$password' LIMIT 1";
- $result = OC_DB::select($query);
- if ( isset($result[0]) AND isset($result[0]['user_id']) AND ($result[0]['user_id'] > 0) ) {
- return true;
- } else {
- return false;
- }
- }
-
- /**
- * get a list of all users
- *
- */
- public static function getUsers() {
- global $CONFIG_DBTABLEPREFIX;
-
- $query = "SELECT user_name FROM `{$CONFIG_DBTABLEPREFIX}users`";
- $result = OC_DB::select($query);
- $users=array();
- foreach($result as $user){
- $users[]=$user['user_name'];
- }
- return $users;
- }
-
- /**
- * get a list of all groups
- *
- */
- public static function getGroups() {
- global $CONFIG_DBTABLEPREFIX;
-
- $query = "SELECT group_name FROM `{$CONFIG_DBTABLEPREFIX}groups`";
- $result = OC_DB::select($query);
- $groups=array();
- foreach($result as $group){
- $groups[]=$group['group_name'];
- }
- return $groups;
- }
-
- private static function clearCache(){
- self::$userGroupCache=array();
- $_SESSION['user_id_cache']=array();
- $_SESSION['group_id_cache']=array();
- }
-}
diff --git a/inc/XML/Parser.php b/inc/XML/Parser.php
deleted file mode 100644
index 6f77b5c66da..00000000000
--- a/inc/XML/Parser.php
+++ /dev/null
@@ -1,683 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 4 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available at through the world-wide-web at |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Author: Stig Bakken <ssb@fast.no> |
-// | Tomas V.V.Cox <cox@idecnet.com> |
-// | Stephan Schmidt <schst@php-tools.net> |
-// +----------------------------------------------------------------------+
-//
-// $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 <ssb@fast.no>
- * @author Tomas V.V.Cox <cox@idecnet.com>
- * @author Stephan Schmidt <schst@php-tools.net>
- */
-
-/**
- * uses PEAR's error handling
- */
-oc_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 <name></name> tags of your xml file.
- *
- * @category XML
- * @package XML_Parser
- * @author Stig Bakken <ssb@fast.no>
- * @author Tomas V.V.Cox <cox@idecnet.com>
- * @author Stephan Schmidt <schst@php-tools.net>
- * @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 (eregi('^[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/inc/XML/RPC.php b/inc/XML/RPC.php
deleted file mode 100644
index 2cdb44f4aea..00000000000
--- a/inc/XML/RPC.php
+++ /dev/null
@@ -1,1951 +0,0 @@
-<?php
-
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * PHP implementation of the XML-RPC protocol
- *
- * This is a PEAR-ified version of Useful inc's XML-RPC for PHP.
- * It has support for HTTP transport, proxies and authentication.
- *
- * PHP versions 4 and 5
- *
- * LICENSE: License is granted to use or modify this software
- * ("XML-RPC for PHP") for commercial or non-commercial use provided the
- * copyright of the author is preserved in any distributed or derivative work.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESSED 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 AUTHOR 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 Web Services
- * @package XML_RPC
- * @author Edd Dumbill <edd@usefulinc.com>
- * @author Stig Bakken <stig@php.net>
- * @author Martin Jansen <mj@php.net>
- * @author Daniel Convissor <danielc@php.net>
- * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group
- * @version CVS: $Id: RPC.php,v 1.83 2005/08/14 20:25:35 danielc Exp $
- * @link http://pear.php.net/package/XML_RPC
- */
-
-
-if (!function_exists('xml_parser_create')) {
- PEAR::loadExtension('xml');
-}
-
-/**#@+
- * Error constants
- */
-/**
- * Parameter values don't match parameter types
- */
-define('XML_RPC_ERROR_INVALID_TYPE', 101);
-/**
- * Parameter declared to be numeric but the values are not
- */
-define('XML_RPC_ERROR_NON_NUMERIC_FOUND', 102);
-/**
- * Communication error
- */
-define('XML_RPC_ERROR_CONNECTION_FAILED', 103);
-/**
- * The array or struct has already been started
- */
-define('XML_RPC_ERROR_ALREADY_INITIALIZED', 104);
-/**
- * Incorrect parameters submitted
- */
-define('XML_RPC_ERROR_INCORRECT_PARAMS', 105);
-/**
- * Programming error by developer
- */
-define('XML_RPC_ERROR_PROGRAMMING', 106);
-/**#@-*/
-
-
-/**
- * Data types
- * @global string $GLOBALS['XML_RPC_I4']
- */
-$GLOBALS['XML_RPC_I4'] = 'i4';
-
-/**
- * Data types
- * @global string $GLOBALS['XML_RPC_Int']
- */
-$GLOBALS['XML_RPC_Int'] = 'int';
-
-/**
- * Data types
- * @global string $GLOBALS['XML_RPC_Boolean']
- */
-$GLOBALS['XML_RPC_Boolean'] = 'boolean';
-
-/**
- * Data types
- * @global string $GLOBALS['XML_RPC_Double']
- */
-$GLOBALS['XML_RPC_Double'] = 'double';
-
-/**
- * Data types
- * @global string $GLOBALS['XML_RPC_String']
- */
-$GLOBALS['XML_RPC_String'] = 'string';
-
-/**
- * Data types
- * @global string $GLOBALS['XML_RPC_DateTime']
- */
-$GLOBALS['XML_RPC_DateTime'] = 'dateTime.iso8601';
-
-/**
- * Data types
- * @global string $GLOBALS['XML_RPC_Base64']
- */
-$GLOBALS['XML_RPC_Base64'] = 'base64';
-
-/**
- * Data types
- * @global string $GLOBALS['XML_RPC_Array']
- */
-$GLOBALS['XML_RPC_Array'] = 'array';
-
-/**
- * Data types
- * @global string $GLOBALS['XML_RPC_Struct']
- */
-$GLOBALS['XML_RPC_Struct'] = 'struct';
-
-
-/**
- * Data type meta-types
- * @global array $GLOBALS['XML_RPC_Types']
- */
-$GLOBALS['XML_RPC_Types'] = array(
- $GLOBALS['XML_RPC_I4'] => 1,
- $GLOBALS['XML_RPC_Int'] => 1,
- $GLOBALS['XML_RPC_Boolean'] => 1,
- $GLOBALS['XML_RPC_String'] => 1,
- $GLOBALS['XML_RPC_Double'] => 1,
- $GLOBALS['XML_RPC_DateTime'] => 1,
- $GLOBALS['XML_RPC_Base64'] => 1,
- $GLOBALS['XML_RPC_Array'] => 2,
- $GLOBALS['XML_RPC_Struct'] => 3,
-);
-
-
-/**
- * Error message numbers
- * @global array $GLOBALS['XML_RPC_err']
- */
-$GLOBALS['XML_RPC_err'] = array(
- 'unknown_method' => 1,
- 'invalid_return' => 2,
- 'incorrect_params' => 3,
- 'introspect_unknown' => 4,
- 'http_error' => 5,
- 'not_response_object' => 6,
- 'invalid_request' => 7,
-);
-
-/**
- * Error message strings
- * @global array $GLOBALS['XML_RPC_str']
- */
-$GLOBALS['XML_RPC_str'] = array(
- 'unknown_method' => 'Unknown method',
- 'invalid_return' => 'Invalid return payload: enable debugging to examine incoming payload',
- 'incorrect_params' => 'Incorrect parameters passed to method',
- 'introspect_unknown' => 'Can\'t introspect: method unknown',
- 'http_error' => 'Didn\'t receive 200 OK from remote server.',
- 'not_response_object' => 'The requested method didn\'t return an XML_RPC_Response object.',
- 'invalid_request' => 'Invalid request payload',
-);
-
-
-/**
- * Default XML encoding (ISO-8859-1, UTF-8 or US-ASCII)
- * @global string $GLOBALS['XML_RPC_defencoding']
- */
-$GLOBALS['XML_RPC_defencoding'] = 'UTF-8';
-
-/**
- * User error codes start at 800
- * @global int $GLOBALS['XML_RPC_erruser']
- */
-$GLOBALS['XML_RPC_erruser'] = 800;
-
-/**
- * XML parse error codes start at 100
- * @global int $GLOBALS['XML_RPC_errxml']
- */
-$GLOBALS['XML_RPC_errxml'] = 100;
-
-
-/**
- * Compose backslashes for escaping regexp
- * @global string $GLOBALS['XML_RPC_backslash']
- */
-$GLOBALS['XML_RPC_backslash'] = chr(92) . chr(92);
-
-
-/**
- * Valid parents of XML elements
- * @global array $GLOBALS['XML_RPC_valid_parents']
- */
-$GLOBALS['XML_RPC_valid_parents'] = array(
- 'BOOLEAN' => array('VALUE'),
- 'I4' => array('VALUE'),
- 'INT' => array('VALUE'),
- 'STRING' => array('VALUE'),
- 'DOUBLE' => array('VALUE'),
- 'DATETIME.ISO8601' => array('VALUE'),
- 'BASE64' => array('VALUE'),
- 'ARRAY' => array('VALUE'),
- 'STRUCT' => array('VALUE'),
- 'PARAM' => array('PARAMS'),
- 'METHODNAME' => array('METHODCALL'),
- 'PARAMS' => array('METHODCALL', 'METHODRESPONSE'),
- 'MEMBER' => array('STRUCT'),
- 'NAME' => array('MEMBER'),
- 'DATA' => array('ARRAY'),
- 'FAULT' => array('METHODRESPONSE'),
- 'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'),
-);
-
-
-/**
- * Stores state during parsing
- *
- * quick explanation of components:
- * + ac = accumulates values
- * + qt = decides if quotes are needed for evaluation
- * + cm = denotes struct or array (comma needed)
- * + isf = indicates a fault
- * + lv = indicates "looking for a value": implements the logic
- * to allow values with no types to be strings
- * + params = stores parameters in method calls
- * + method = stores method name
- *
- * @global array $GLOBALS['XML_RPC_xh']
- */
-$GLOBALS['XML_RPC_xh'] = array();
-
-
-/**
- * Start element handler for the XML parser
- *
- * @return void
- */
-function XML_RPC_se($parser_resource, $name, $attrs)
-{
- global $XML_RPC_xh, $XML_RPC_DateTime, $XML_RPC_String, $XML_RPC_valid_parents;
- $parser = (int) $parser_resource;
-
- // if invalid xmlrpc already detected, skip all processing
- if ($XML_RPC_xh[$parser]['isf'] >= 2) {
- return;
- }
-
- // check for correct element nesting
- // top level element can only be of 2 types
- if (count($XML_RPC_xh[$parser]['stack']) == 0) {
- if ($name != 'METHODRESPONSE' && $name != 'METHODCALL') {
- $XML_RPC_xh[$parser]['isf'] = 2;
- $XML_RPC_xh[$parser]['isf_reason'] = 'missing top level xmlrpc element';
- return;
- }
- } else {
- // not top level element: see if parent is OK
- if (!in_array($XML_RPC_xh[$parser]['stack'][0], $XML_RPC_valid_parents[$name])) {
- $name = preg_replace('[^a-zA-Z0-9._-]', '', $name);
- $XML_RPC_xh[$parser]['isf'] = 2;
- $XML_RPC_xh[$parser]['isf_reason'] = "xmlrpc element $name cannot be child of {$XML_RPC_xh[$parser]['stack'][0]}";
- return;
- }
- }
-
- switch ($name) {
- case 'STRUCT':
- $XML_RPC_xh[$parser]['cm']++;
-
- // turn quoting off
- $XML_RPC_xh[$parser]['qt'] = 0;
-
- $cur_val = array();
- $cur_val['value'] = array();
- $cur_val['members'] = 1;
- array_unshift($XML_RPC_xh[$parser]['valuestack'], $cur_val);
- break;
-
- case 'ARRAY':
- $XML_RPC_xh[$parser]['cm']++;
-
- // turn quoting off
- $XML_RPC_xh[$parser]['qt'] = 0;
-
- $cur_val = array();
- $cur_val['value'] = array();
- $cur_val['members'] = 0;
- array_unshift($XML_RPC_xh[$parser]['valuestack'], $cur_val);
- break;
-
- case 'NAME':
- $XML_RPC_xh[$parser]['ac'] = '';
- break;
-
- case 'FAULT':
- $XML_RPC_xh[$parser]['isf'] = 1;
- break;
-
- case 'PARAM':
- $XML_RPC_xh[$parser]['valuestack'] = array();
- break;
-
- case 'VALUE':
- $XML_RPC_xh[$parser]['lv'] = 1;
- $XML_RPC_xh[$parser]['vt'] = $XML_RPC_String;
- $XML_RPC_xh[$parser]['ac'] = '';
- $XML_RPC_xh[$parser]['qt'] = 0;
- // look for a value: if this is still 1 by the
- // time we reach the first data segment then the type is string
- // by implication and we need to add in a quote
- break;
-
- case 'I4':
- case 'INT':
- case 'STRING':
- case 'BOOLEAN':
- case 'DOUBLE':
- case 'DATETIME.ISO8601':
- case 'BASE64':
- $XML_RPC_xh[$parser]['ac'] = ''; // reset the accumulator
-
- if ($name == 'DATETIME.ISO8601' || $name == 'STRING') {
- $XML_RPC_xh[$parser]['qt'] = 1;
-
- if ($name == 'DATETIME.ISO8601') {
- $XML_RPC_xh[$parser]['vt'] = $XML_RPC_DateTime;
- }
-
- } elseif ($name == 'BASE64') {
- $XML_RPC_xh[$parser]['qt'] = 2;
- } else {
- // No quoting is required here -- but
- // at the end of the element we must check
- // for data format errors.
- $XML_RPC_xh[$parser]['qt'] = 0;
- }
- break;
-
- case 'MEMBER':
- $XML_RPC_xh[$parser]['ac'] = '';
- break;
-
- case 'DATA':
- case 'METHODCALL':
- case 'METHODNAME':
- case 'METHODRESPONSE':
- case 'PARAMS':
- // valid elements that add little to processing
- break;
- }
-
-
- // Save current element to stack
- array_unshift($XML_RPC_xh[$parser]['stack'], $name);
-
- if ($name != 'VALUE') {
- $XML_RPC_xh[$parser]['lv'] = 0;
- }
-}
-
-/**
- * End element handler for the XML parser
- *
- * @return void
- */
-function XML_RPC_ee($parser_resource, $name)
-{
- global $XML_RPC_xh, $XML_RPC_Types, $XML_RPC_String;
- $parser = (int) $parser_resource;
-
- if ($XML_RPC_xh[$parser]['isf'] >= 2) {
- return;
- }
-
- // push this element from stack
- // NB: if XML validates, correct opening/closing is guaranteed and
- // we do not have to check for $name == $curr_elem.
- // we also checked for proper nesting at start of elements...
- $curr_elem = array_shift($XML_RPC_xh[$parser]['stack']);
-
- switch ($name) {
- case 'STRUCT':
- case 'ARRAY':
- $cur_val = array_shift($XML_RPC_xh[$parser]['valuestack']);
- $XML_RPC_xh[$parser]['value'] = $cur_val['value'];
- $XML_RPC_xh[$parser]['vt'] = strtolower($name);
- $XML_RPC_xh[$parser]['cm']--;
- break;
-
- case 'NAME':
- $XML_RPC_xh[$parser]['valuestack'][0]['name'] = $XML_RPC_xh[$parser]['ac'];
- break;
-
- case 'BOOLEAN':
- // special case here: we translate boolean 1 or 0 into PHP
- // constants true or false
- if ($XML_RPC_xh[$parser]['ac'] == '1') {
- $XML_RPC_xh[$parser]['ac'] = 'true';
- } else {
- $XML_RPC_xh[$parser]['ac'] = 'false';
- }
-
- $XML_RPC_xh[$parser]['vt'] = strtolower($name);
- // Drop through intentionally.
-
- case 'I4':
- case 'INT':
- case 'STRING':
- case 'DOUBLE':
- case 'DATETIME.ISO8601':
- case 'BASE64':
- if ($XML_RPC_xh[$parser]['qt'] == 1) {
- // we use double quotes rather than single so backslashification works OK
- $XML_RPC_xh[$parser]['value'] = $XML_RPC_xh[$parser]['ac'];
- } elseif ($XML_RPC_xh[$parser]['qt'] == 2) {
- $XML_RPC_xh[$parser]['value'] = base64_decode($XML_RPC_xh[$parser]['ac']);
- } elseif ($name == 'BOOLEAN') {
- $XML_RPC_xh[$parser]['value'] = $XML_RPC_xh[$parser]['ac'];
- } else {
- // we have an I4, INT or a DOUBLE
- // we must check that only 0123456789-.<space> are characters here
- if (!ereg("^[+-]?[0123456789 \t\.]+$", $XML_RPC_xh[$parser]['ac'])) {
- XML_RPC_Base::raiseError('Non-numeric value received in INT or DOUBLE',
- XML_RPC_ERROR_NON_NUMERIC_FOUND);
- $XML_RPC_xh[$parser]['value'] = XML_RPC_ERROR_NON_NUMERIC_FOUND;
- } else {
- // it's ok, add it on
- $XML_RPC_xh[$parser]['value'] = $XML_RPC_xh[$parser]['ac'];
- }
- }
-
- $XML_RPC_xh[$parser]['ac'] = '';
- $XML_RPC_xh[$parser]['qt'] = 0;
- $XML_RPC_xh[$parser]['lv'] = 3; // indicate we've found a value
- break;
-
- case 'VALUE':
- // deal with a string value
- if (strlen($XML_RPC_xh[$parser]['ac']) > 0 &&
- $XML_RPC_xh[$parser]['vt'] == $XML_RPC_String) {
- $XML_RPC_xh[$parser]['value'] = $XML_RPC_xh[$parser]['ac'];
- }
-
- $temp = new XML_RPC_Value($XML_RPC_xh[$parser]['value'], $XML_RPC_xh[$parser]['vt']);
-
- $cur_val = array_shift($XML_RPC_xh[$parser]['valuestack']);
- if (is_array($cur_val)) {
- if ($cur_val['members']==0) {
- $cur_val['value'][] = $temp;
- } else {
- $XML_RPC_xh[$parser]['value'] = $temp;
- }
- array_unshift($XML_RPC_xh[$parser]['valuestack'], $cur_val);
- } else {
- $XML_RPC_xh[$parser]['value'] = $temp;
- }
- break;
-
- case 'MEMBER':
- $XML_RPC_xh[$parser]['ac'] = '';
- $XML_RPC_xh[$parser]['qt'] = 0;
-
- $cur_val = array_shift($XML_RPC_xh[$parser]['valuestack']);
- if (is_array($cur_val)) {
- if ($cur_val['members']==1) {
- $cur_val['value'][$cur_val['name']] = $XML_RPC_xh[$parser]['value'];
- }
- array_unshift($XML_RPC_xh[$parser]['valuestack'], $cur_val);
- }
- break;
-
- case 'DATA':
- $XML_RPC_xh[$parser]['ac'] = '';
- $XML_RPC_xh[$parser]['qt'] = 0;
- break;
-
- case 'PARAM':
- $XML_RPC_xh[$parser]['params'][] = $XML_RPC_xh[$parser]['value'];
- break;
-
- case 'METHODNAME':
- case 'RPCMETHODNAME':
- $XML_RPC_xh[$parser]['method'] = ereg_replace("^[\n\r\t ]+", '',
- $XML_RPC_xh[$parser]['ac']);
- break;
- }
-
- // if it's a valid type name, set the type
- if (isset($XML_RPC_Types[strtolower($name)])) {
- $XML_RPC_xh[$parser]['vt'] = strtolower($name);
- }
-}
-
-/**
- * Character data handler for the XML parser
- *
- * @return void
- */
-function XML_RPC_cd($parser_resource, $data)
-{
- global $XML_RPC_xh, $XML_RPC_backslash;
- $parser = (int) $parser_resource;
-
- if ($XML_RPC_xh[$parser]['lv'] != 3) {
- // "lookforvalue==3" means that we've found an entire value
- // and should discard any further character data
-
- if ($XML_RPC_xh[$parser]['lv'] == 1) {
- // if we've found text and we're just in a <value> then
- // turn quoting on, as this will be a string
- $XML_RPC_xh[$parser]['qt'] = 1;
- // and say we've found a value
- $XML_RPC_xh[$parser]['lv'] = 2;
- }
-
- // replace characters that eval would
- // do special things with
- if (!isset($XML_RPC_xh[$parser]['ac'])) {
- $XML_RPC_xh[$parser]['ac'] = '';
- }
- $XML_RPC_xh[$parser]['ac'] .= $data;
- }
-}
-
-/**
- * The common methods and properties for all of the XML_RPC classes
- *
- * @category Web Services
- * @package XML_RPC
- * @author Edd Dumbill <edd@usefulinc.com>
- * @author Stig Bakken <stig@php.net>
- * @author Martin Jansen <mj@php.net>
- * @author Daniel Convissor <danielc@php.net>
- * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group
- * @version Release: 1.4.0
- * @link http://pear.php.net/package/XML_RPC
- */
-class XML_RPC_Base {
-
- /**
- * PEAR Error handling
- *
- * @return object PEAR_Error object
- */
- function raiseError($msg, $code)
- {
- include_once 'PEAR.php';
- if (is_object(@$this)) {
- return PEAR::raiseError(get_class($this) . ': ' . $msg, $code);
- } else {
- return PEAR::raiseError('XML_RPC: ' . $msg, $code);
- }
- }
-
- /**
- * Tell whether something is a PEAR_Error object
- *
- * @param mixed $value the item to check
- *
- * @return bool whether $value is a PEAR_Error object or not
- *
- * @access public
- */
- function isError($value)
- {
- return is_a($value, 'PEAR_Error');
- }
-}
-
-/**
- * The methods and properties for submitting XML RPC requests
- *
- * @category Web Services
- * @package XML_RPC
- * @author Edd Dumbill <edd@usefulinc.com>
- * @author Stig Bakken <stig@php.net>
- * @author Martin Jansen <mj@php.net>
- * @author Daniel Convissor <danielc@php.net>
- * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group
- * @version Release: 1.4.0
- * @link http://pear.php.net/package/XML_RPC
- */
-class XML_RPC_Client extends XML_RPC_Base {
-
- /**
- * The path and name of the RPC server script you want the request to go to
- * @var string
- */
- var $path = '';
-
- /**
- * The name of the remote server to connect to
- * @var string
- */
- var $server = '';
-
- /**
- * The protocol to use in contacting the remote server
- * @var string
- */
- var $protocol = 'http://';
-
- /**
- * The port for connecting to the remote server
- *
- * The default is 80 for http:// connections
- * and 443 for https:// and ssl:// connections.
- *
- * @var integer
- */
- var $port = 80;
-
- /**
- * A user name for accessing the RPC server
- * @var string
- * @see XML_RPC_Client::setCredentials()
- */
- var $username = '';
-
- /**
- * A password for accessing the RPC server
- * @var string
- * @see XML_RPC_Client::setCredentials()
- */
- var $password = '';
-
- /**
- * The name of the proxy server to use, if any
- * @var string
- */
- var $proxy = '';
-
- /**
- * The protocol to use in contacting the proxy server, if any
- * @var string
- */
- var $proxy_protocol = 'http://';
-
- /**
- * The port for connecting to the proxy server
- *
- * The default is 8080 for http:// connections
- * and 443 for https:// and ssl:// connections.
- *
- * @var integer
- */
- var $proxy_port = 8080;
-
- /**
- * A user name for accessing the proxy server
- * @var string
- */
- var $proxy_user = '';
-
- /**
- * A password for accessing the proxy server
- * @var string
- */
- var $proxy_pass = '';
-
- /**
- * The error number, if any
- * @var integer
- */
- var $errno = 0;
-
- /**
- * The error message, if any
- * @var string
- */
- var $errstr = '';
-
- /**
- * The current debug mode (1 = on, 0 = off)
- * @var integer
- */
- var $debug = 0;
-
- /**
- * The HTTP headers for the current request.
- * @var string
- */
- var $headers = '';
-
-
- /**
- * Sets the object's properties
- *
- * @param string $path the path and name of the RPC server script
- * you want the request to go to
- * @param string $server the URL of the remote server to connect to.
- * If this parameter doesn't specify a
- * protocol and $port is 443, ssl:// is
- * assumed.
- * @param integer $port a port for connecting to the remote server.
- * Defaults to 80 for http:// connections and
- * 443 for https:// and ssl:// connections.
- * @param string $proxy the URL of the proxy server to use, if any.
- * If this parameter doesn't specify a
- * protocol and $port is 443, ssl:// is
- * assumed.
- * @param integer $proxy_port a port for connecting to the remote server.
- * Defaults to 8080 for http:// connections and
- * 443 for https:// and ssl:// connections.
- * @param string $proxy_user a user name for accessing the proxy server
- * @param string $proxy_pass a password for accessing the proxy server
- *
- * @return void
- */
- function XML_RPC_Client($path, $server, $port = 0,
- $proxy = '', $proxy_port = 0,
- $proxy_user = '', $proxy_pass = '')
- {
- $this->path = $path;
- $this->proxy_user = $proxy_user;
- $this->proxy_pass = $proxy_pass;
-
- preg_match('@^(http://|https://|ssl://)?(.*)$@', $server, $match);
- if ($match[1] == '') {
- if ($port == 443) {
- $this->server = $match[2];
- $this->protocol = 'ssl://';
- $this->port = 443;
- } else {
- $this->server = $match[2];
- if ($port) {
- $this->port = $port;
- }
- }
- } elseif ($match[1] == 'http://') {
- $this->server = $match[2];
- if ($port) {
- $this->port = $port;
- }
- } else {
- $this->server = $match[2];
- $this->protocol = 'ssl://';
- if ($port) {
- $this->port = $port;
- } else {
- $this->port = 443;
- }
- }
-
- if ($proxy) {
- preg_match('@^(http://|https://|ssl://)?(.*)$@', $proxy, $match);
- if ($match[1] == '') {
- if ($proxy_port == 443) {
- $this->proxy = $match[2];
- $this->proxy_protocol = 'ssl://';
- $this->proxy_port = 443;
- } else {
- $this->proxy = $match[2];
- if ($proxy_port) {
- $this->proxy_port = $proxy_port;
- }
- }
- } elseif ($match[1] == 'http://') {
- $this->proxy = $match[2];
- if ($proxy_port) {
- $this->proxy_port = $proxy_port;
- }
- } else {
- $this->proxy = $match[2];
- $this->proxy_protocol = 'ssl://';
- if ($proxy_port) {
- $this->proxy_port = $proxy_port;
- } else {
- $this->proxy_port = 443;
- }
- }
- }
- }
-
- /**
- * Change the current debug mode
- *
- * @param int $in where 1 = on, 0 = off
- *
- * @return void
- */
- function setDebug($in)
- {
- if ($in) {
- $this->debug = 1;
- } else {
- $this->debug = 0;
- }
- }
-
- /**
- * Set username and password properties for connecting to the RPC server
- *
- * @param string $u the user name
- * @param string $p the password
- *
- * @return void
- *
- * @see XML_RPC_Client::$username, XML_RPC_Client::$password
- */
- function setCredentials($u, $p)
- {
- $this->username = $u;
- $this->password = $p;
- }
-
- /**
- * Transmit the RPC request via HTTP 1.0 protocol
- *
- * @param object $msg the XML_RPC_Message object
- * @param int $timeout how many seconds to wait for the request
- *
- * @return object an XML_RPC_Response object. 0 is returned if any
- * problems happen.
- *
- * @see XML_RPC_Message, XML_RPC_Client::XML_RPC_Client(),
- * XML_RPC_Client::setCredentials()
- */
- function send($msg, $timeout = 0)
- {
- if (strtolower(get_class($msg)) != 'xml_rpc_message') {
- $this->errstr = 'send()\'s $msg parameter must be an'
- . ' XML_RPC_Message object.';
- $this->raiseError($this->errstr, XML_RPC_ERROR_PROGRAMMING);
- return 0;
- }
- $msg->debug = $this->debug;
- return $this->sendPayloadHTTP10($msg, $this->server, $this->port,
- $timeout, $this->username,
- $this->password);
- }
-
- /**
- * Transmit the RPC request via HTTP 1.0 protocol
- *
- * Requests should be sent using XML_RPC_Client send() rather than
- * calling this method directly.
- *
- * @param object $msg the XML_RPC_Message object
- * @param string $server the server to send the request to
- * @param int $port the server port send the request to
- * @param int $timeout how many seconds to wait for the request
- * before giving up
- * @param string $username a user name for accessing the RPC server
- * @param string $password a password for accessing the RPC server
- *
- * @return object an XML_RPC_Response object. 0 is returned if any
- * problems happen.
- *
- * @access protected
- * @see XML_RPC_Client::send()
- */
- function sendPayloadHTTP10($msg, $server, $port, $timeout = 0,
- $username = '', $password = '')
- {
- /*
- * If we're using a proxy open a socket to the proxy server
- * instead to the xml-rpc server
- */
- if ($this->proxy) {
- if ($this->proxy_protocol == 'http://') {
- $protocol = '';
- } else {
- $protocol = $this->proxy_protocol;
- }
- if ($timeout > 0) {
- $fp = @fsockopen($protocol . $this->proxy, $this->proxy_port,
- $this->errno, $this->errstr, $timeout);
- } else {
- $fp = @fsockopen($protocol . $this->proxy, $this->proxy_port,
- $this->errno, $this->errstr);
- }
- } else {
- if ($this->protocol == 'http://') {
- $protocol = '';
- } else {
- $protocol = $this->protocol;
- }
- if ($timeout > 0) {
- $fp = @fsockopen($protocol . $server, $port,
- $this->errno, $this->errstr, $timeout);
- } else {
- $fp = @fsockopen($protocol . $server, $port,
- $this->errno, $this->errstr);
- }
- }
-
- /*
- * Just raising the error without returning it is strange,
- * but keep it here for backwards compatibility.
- */
- if (!$fp && $this->proxy) {
- $this->raiseError('Connection to proxy server '
- . $this->proxy . ':' . $this->proxy_port
- . ' failed. ' . $this->errstr,
- XML_RPC_ERROR_CONNECTION_FAILED);
- return 0;
- } elseif (!$fp) {
- $this->raiseError('Connection to RPC server '
- . $server . ':' . $port
- . ' failed. ' . $this->errstr,
- XML_RPC_ERROR_CONNECTION_FAILED);
- return 0;
- }
-
- if ($timeout) {
- /*
- * Using socket_set_timeout() because stream_set_timeout()
- * was introduced in 4.3.0, but we need to support 4.2.0.
- */
- socket_set_timeout($fp, $timeout);
- }
-
- // Pre-emptive BC hacks for fools calling sendPayloadHTTP10() directly
- if ($username != $this->username) {
- $this->setCredentials($username, $password);
- }
-
- // Only create the payload if it was not created previously
- if (empty($msg->payload)) {
- $msg->createPayload();
- }
- $this->createHeaders($msg);
-
- $op = $this->headers . "\r\n\r\n";
- $op .= $msg->payload;
-
- if (!fputs($fp, $op, strlen($op))) {
- $this->errstr = 'Write error';
- return 0;
- }
- $resp = $msg->parseResponseFile($fp);
-
- $meta = socket_get_status($fp);
- if ($meta['timed_out']) {
- fclose($fp);
- $this->errstr = 'RPC server did not send response before timeout.';
- $this->raiseError($this->errstr, XML_RPC_ERROR_CONNECTION_FAILED);
- return 0;
- }
-
- fclose($fp);
- return $resp;
- }
-
- /**
- * Determines the HTTP headers and puts it in the $headers property
- *
- * @param object $msg the XML_RPC_Message object
- *
- * @return boolean TRUE if okay, FALSE if the message payload isn't set.
- *
- * @access protected
- */
- function createHeaders($msg)
- {
- if (empty($msg->payload)) {
- return false;
- }
- if ($this->proxy) {
- $this->headers = 'POST ' . $this->protocol . $this->server;
- if ($this->proxy_port) {
- $this->headers .= ':' . $this->port;
- }
- } else {
- $this->headers = 'POST ';
- }
- $this->headers .= $this->path. " HTTP/1.0\r\n";
-
- $this->headers .= "User-Agent: PEAR XML_RPC\r\n";
- $this->headers .= 'Host: ' . $this->server . "\r\n";
-
- if ($this->proxy && $this->proxy_user) {
- $this->headers .= 'Proxy-Authorization: Basic '
- . base64_encode("$this->proxy_user:$this->proxy_pass")
- . "\r\n";
- }
-
- // thanks to Grant Rauscher <grant7@firstworld.net> for this
- if ($this->username) {
- $this->headers .= 'Authorization: Basic '
- . base64_encode("$this->username:$this->password")
- . "\r\n";
- }
-
- $this->headers .= "Content-Type: text/xml\r\n";
- $this->headers .= 'Content-Length: ' . strlen($msg->payload);
- return true;
- }
-}
-
-/**
- * The methods and properties for interpreting responses to XML RPC requests
- *
- * @category Web Services
- * @package XML_RPC
- * @author Edd Dumbill <edd@usefulinc.com>
- * @author Stig Bakken <stig@php.net>
- * @author Martin Jansen <mj@php.net>
- * @author Daniel Convissor <danielc@php.net>
- * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group
- * @version Release: 1.4.0
- * @link http://pear.php.net/package/XML_RPC
- */
-class XML_RPC_Response extends XML_RPC_Base
-{
- var $xv;
- var $fn;
- var $fs;
- var $hdrs;
-
- /**
- * @return void
- */
- function XML_RPC_Response($val, $fcode = 0, $fstr = '')
- {
- if ($fcode != 0) {
- $this->fn = $fcode;
- $this->fs = htmlspecialchars($fstr);
- } else {
- $this->xv = $val;
- }
- }
-
- /**
- * @return int the error code
- */
- function faultCode()
- {
- if (isset($this->fn)) {
- return $this->fn;
- } else {
- return 0;
- }
- }
-
- /**
- * @return string the error string
- */
- function faultString()
- {
- return $this->fs;
- }
-
- /**
- * @return mixed the value
- */
- function value()
- {
- return $this->xv;
- }
-
- /**
- * @return string the error message in XML format
- */
- function serialize()
- {
- $rs = "<methodResponse>\n";
- if ($this->fn) {
- $rs .= "<fault>
- <value>
- <struct>
- <member>
- <name>faultCode</name>
- <value><int>" . $this->fn . "</int></value>
- </member>
- <member>
- <name>faultString</name>
- <value><string>" . $this->fs . "</string></value>
- </member>
- </struct>
- </value>
-</fault>";
- } else {
- $rs .= "<params>\n<param>\n" . $this->xv->serialize() .
- "</param>\n</params>";
- }
- $rs .= "\n</methodResponse>";
- return $rs;
- }
-}
-
-/**
- * The methods and properties for composing XML RPC messages
- *
- * @category Web Services
- * @package XML_RPC
- * @author Edd Dumbill <edd@usefulinc.com>
- * @author Stig Bakken <stig@php.net>
- * @author Martin Jansen <mj@php.net>
- * @author Daniel Convissor <danielc@php.net>
- * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group
- * @version Release: 1.4.0
- * @link http://pear.php.net/package/XML_RPC
- */
-class XML_RPC_Message extends XML_RPC_Base
-{
- /**
- * The current debug mode (1 = on, 0 = off)
- * @var integer
- */
- var $debug = 0;
-
- /**
- * The encoding to be used for outgoing messages
- *
- * Defaults to the value of <var>$GLOBALS['XML_RPC_defencoding']</var>
- *
- * @var string
- * @see XML_RPC_Message::setSendEncoding(),
- * $GLOBALS['XML_RPC_defencoding'], XML_RPC_Message::xml_header()
- */
- var $send_encoding = '';
-
- /**
- * The method presently being evaluated
- * @var string
- */
- var $methodname = '';
-
- /**
- * @var array
- */
- var $params = array();
-
- /**
- * The XML message being generated
- * @var string
- */
- var $payload = '';
-
- /**
- * @return void
- */
- function XML_RPC_Message($meth, $pars = 0)
- {
- $this->methodname = $meth;
- if (is_array($pars) && sizeof($pars) > 0) {
- for ($i = 0; $i < sizeof($pars); $i++) {
- $this->addParam($pars[$i]);
- }
- }
- }
-
- /**
- * Produces the XML declaration including the encoding attribute
- *
- * The encoding is determined by this class' <var>$send_encoding</var>
- * property. If the <var>$send_encoding</var> property is not set, use
- * <var>$GLOBALS['XML_RPC_defencoding']</var>.
- *
- * @return string the XML declaration and <methodCall> element
- *
- * @see XML_RPC_Message::setSendEncoding(),
- * XML_RPC_Message::$send_encoding, $GLOBALS['XML_RPC_defencoding']
- */
- function xml_header()
- {
- global $XML_RPC_defencoding;
- if (!$this->send_encoding) {
- $this->send_encoding = $XML_RPC_defencoding;
- }
- return '<?xml version="1.0" encoding="' . $this->send_encoding . '"?>'
- . "\n<methodCall>\n";
- }
-
- /**
- * @return string the closing </methodCall> tag
- */
- function xml_footer()
- {
- return "</methodCall>\n";
- }
-
- /**
- * @return void
- *
- * @uses XML_RPC_Message::xml_header(), XML_RPC_Message::xml_footer()
- */
- function createPayload()
- {
- $this->payload = $this->xml_header();
- $this->payload .= '<methodName>' . $this->methodname . "</methodName>\n";
- $this->payload .= "<params>\n";
- for ($i = 0; $i < sizeof($this->params); $i++) {
- $p = $this->params[$i];
- $this->payload .= "<param>\n" . $p->serialize() . "</param>\n";
- }
- $this->payload .= "</params>\n";
- $this->payload .= $this->xml_footer();
- $this->payload = ereg_replace("[\r\n]+", "\r\n", $this->payload);
- }
-
- /**
- * @return string the name of the method
- */
- function method($meth = '')
- {
- if ($meth != '') {
- $this->methodname = $meth;
- }
- return $this->methodname;
- }
-
- /**
- * @return string the payload
- */
- function serialize()
- {
- $this->createPayload();
- return $this->payload;
- }
-
- /**
- * @return void
- */
- function addParam($par)
- {
- $this->params[] = $par;
- }
-
- /**
- * Obtains an XML_RPC_Value object for the given parameter
- *
- * @param int $i the index number of the parameter to obtain
- *
- * @return object the XML_RPC_Value object.
- * If the parameter doesn't exist, an XML_RPC_Response object.
- *
- * @since Returns XML_RPC_Response object on error since Release 1.3.0
- */
- function getParam($i)
- {
- global $XML_RPC_err, $XML_RPC_str;
-
- if (isset($this->params[$i])) {
- return $this->params[$i];
- } else {
- $this->raiseError('The submitted request did not contain this parameter',
- XML_RPC_ERROR_INCORRECT_PARAMS);
- return new XML_RPC_Response(0, $XML_RPC_err['incorrect_params'],
- $XML_RPC_str['incorrect_params']);
- }
- }
-
- /**
- * @return int the number of parameters
- */
- function getNumParams()
- {
- return sizeof($this->params);
- }
-
- /**
- * Sets the XML declaration's encoding attribute
- *
- * @param string $type the encoding type (ISO-8859-1, UTF-8 or US-ASCII)
- *
- * @return void
- *
- * @see XML_RPC_Message::$send_encoding, XML_RPC_Message::xml_header()
- * @since Method available since Release 1.2.0
- */
- function setSendEncoding($type)
- {
- $this->send_encoding = $type;
- }
-
- /**
- * Determine the XML's encoding via the encoding attribute
- * in the XML declaration
- *
- * If the encoding parameter is not set or is not ISO-8859-1, UTF-8
- * or US-ASCII, $XML_RPC_defencoding will be returned.
- *
- * @param string $data the XML that will be parsed
- *
- * @return string the encoding to be used
- *
- * @link http://php.net/xml_parser_create
- * @since Method available since Release 1.2.0
- */
- function getEncoding($data)
- {
- global $XML_RPC_defencoding;
-
- if (preg_match('/<\?xml[^>]*\s*encoding\s*=\s*[\'"]([^"\']*)[\'"]/i',
- $data, $match))
- {
- $match[1] = trim(strtoupper($match[1]));
- switch ($match[1]) {
- case 'ISO-8859-1':
- case 'UTF-8':
- case 'US-ASCII':
- return $match[1];
- break;
-
- default:
- return $XML_RPC_defencoding;
- }
- } else {
- return $XML_RPC_defencoding;
- }
- }
-
- /**
- * @return object a new XML_RPC_Response object
- */
- function parseResponseFile($fp)
- {
- $ipd = '';
- while ($data = @fread($fp, 8192)) {
- $ipd .= $data;
- }
- return $this->parseResponse($ipd);
- }
-
- /**
- * @return object a new XML_RPC_Response object
- */
- function parseResponse($data = '')
- {
- global $XML_RPC_xh, $XML_RPC_err, $XML_RPC_str, $XML_RPC_defencoding;
-
- $encoding = $this->getEncoding($data);
- $parser_resource = xml_parser_create($encoding);
- $parser = (int) $parser_resource;
-
- $XML_RPC_xh = array();
- $XML_RPC_xh[$parser] = array();
-
- $XML_RPC_xh[$parser]['cm'] = 0;
- $XML_RPC_xh[$parser]['isf'] = 0;
- $XML_RPC_xh[$parser]['ac'] = '';
- $XML_RPC_xh[$parser]['qt'] = '';
- $XML_RPC_xh[$parser]['stack'] = array();
- $XML_RPC_xh[$parser]['valuestack'] = array();
-
- xml_parser_set_option($parser_resource, XML_OPTION_CASE_FOLDING, true);
- xml_set_element_handler($parser_resource, 'XML_RPC_se', 'XML_RPC_ee');
- xml_set_character_data_handler($parser_resource, 'XML_RPC_cd');
-
- $hdrfnd = 0;
- if ($this->debug) {
- print "\n<pre>---GOT---\n";
- print isset($_SERVER['SERVER_PROTOCOL']) ? htmlspecialchars($data) : $data;
- print "\n---END---</pre>\n";
- }
-
- // See if response is a 200 or a 100 then a 200, else raise error.
- // But only do this if we're using the HTTP protocol.
- if (ereg('^HTTP', $data) &&
- !ereg('^HTTP/[0-9\.]+ 200 ', $data) &&
- !preg_match('@^HTTP/[0-9\.]+ 10[0-9]([A-Za-z ]+)?[\r\n]+HTTP/[0-9\.]+ 200@', $data))
- {
- $errstr = substr($data, 0, strpos($data, "\n") - 1);
- error_log('HTTP error, got response: ' . $errstr);
- $r = new XML_RPC_Response(0, $XML_RPC_err['http_error'],
- $XML_RPC_str['http_error'] . ' (' .
- $errstr . ')');
- xml_parser_free($parser_resource);
- return $r;
- }
-
- // gotta get rid of headers here
- if (!$hdrfnd && ($brpos = strpos($data,"\r\n\r\n"))) {
- $XML_RPC_xh[$parser]['ha'] = substr($data, 0, $brpos);
- $data = substr($data, $brpos + 4);
- $hdrfnd = 1;
- }
-
- /*
- * be tolerant of junk after methodResponse
- * (e.g. javascript automatically inserted by free hosts)
- * thanks to Luca Mariano <luca.mariano@email.it>
- */
- $data = substr($data, 0, strpos($data, "</methodResponse>") + 17);
-
- if (!xml_parse($parser_resource, $data, sizeof($data))) {
- // thanks to Peter Kocks <peter.kocks@baygate.com>
- if (xml_get_current_line_number($parser_resource) == 1) {
- $errstr = 'XML error at line 1, check URL';
- } else {
- $errstr = sprintf('XML error: %s at line %d',
- xml_error_string(xml_get_error_code($parser_resource)),
- xml_get_current_line_number($parser_resource));
- }
- error_log($errstr);
- $r = new XML_RPC_Response(0, $XML_RPC_err['invalid_return'],
- $XML_RPC_str['invalid_return']);
- xml_parser_free($parser_resource);
- return $r;
- }
-
- xml_parser_free($parser_resource);
-
- if ($this->debug) {
- print "\n<pre>---PARSED---\n";
- var_dump($XML_RPC_xh[$parser]['value']);
- print "---END---</pre>\n";
- }
-
- if ($XML_RPC_xh[$parser]['isf'] > 1) {
- $r = new XML_RPC_Response(0, $XML_RPC_err['invalid_return'],
- $XML_RPC_str['invalid_return'].' '.$XML_RPC_xh[$parser]['isf_reason']);
- } elseif (!is_object($XML_RPC_xh[$parser]['value'])) {
- // then something odd has happened
- // and it's time to generate a client side error
- // indicating something odd went on
- $r = new XML_RPC_Response(0, $XML_RPC_err['invalid_return'],
- $XML_RPC_str['invalid_return']);
- } else {
- $v = $XML_RPC_xh[$parser]['value'];
- $allOK=1;
- if ($XML_RPC_xh[$parser]['isf']) {
- $f = $v->structmem('faultCode');
- $fs = $v->structmem('faultString');
- $r = new XML_RPC_Response($v, $f->scalarval(),
- $fs->scalarval());
- } else {
- $r = new XML_RPC_Response($v);
- }
- }
- $r->hdrs = split("\r?\n", $XML_RPC_xh[$parser]['ha'][1]);
- return $r;
- }
-}
-
-/**
- * The methods and properties that represent data in XML RPC format
- *
- * @category Web Services
- * @package XML_RPC
- * @author Edd Dumbill <edd@usefulinc.com>
- * @author Stig Bakken <stig@php.net>
- * @author Martin Jansen <mj@php.net>
- * @author Daniel Convissor <danielc@php.net>
- * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group
- * @version Release: 1.4.0
- * @link http://pear.php.net/package/XML_RPC
- */
-class XML_RPC_Value extends XML_RPC_Base
-{
- var $me = array();
- var $mytype = 0;
-
- /**
- * @return void
- */
- function XML_RPC_Value($val = -1, $type = '')
- {
- global $XML_RPC_Types;
- $this->me = array();
- $this->mytype = 0;
- if ($val != -1 || $type != '') {
- if ($type == '') {
- $type = 'string';
- }
- if (!array_key_exists($type, $XML_RPC_Types)) {
- // XXX
- // need some way to report this error
- } elseif ($XML_RPC_Types[$type] == 1) {
- $this->addScalar($val, $type);
- } elseif ($XML_RPC_Types[$type] == 2) {
- $this->addArray($val);
- } elseif ($XML_RPC_Types[$type] == 3) {
- $this->addStruct($val);
- }
- }
- }
-
- /**
- * @return int returns 1 if successful or 0 if there are problems
- */
- function addScalar($val, $type = 'string')
- {
- global $XML_RPC_Types, $XML_RPC_Boolean;
-
- if ($this->mytype == 1) {
- $this->raiseError('Scalar can have only one value',
- XML_RPC_ERROR_INVALID_TYPE);
- return 0;
- }
- $typeof = $XML_RPC_Types[$type];
- if ($typeof != 1) {
- $this->raiseError("Not a scalar type (${typeof})",
- XML_RPC_ERROR_INVALID_TYPE);
- return 0;
- }
-
- if ($type == $XML_RPC_Boolean) {
- if (strcasecmp($val, 'true') == 0
- || $val == 1
- || ($val == true && strcasecmp($val, 'false')))
- {
- $val = 1;
- } else {
- $val = 0;
- }
- }
-
- if ($this->mytype == 2) {
- // we're adding to an array here
- $ar = $this->me['array'];
- $ar[] = new XML_RPC_Value($val, $type);
- $this->me['array'] = $ar;
- } else {
- // a scalar, so set the value and remember we're scalar
- $this->me[$type] = $val;
- $this->mytype = $typeof;
- }
- return 1;
- }
-
- /**
- * @return int returns 1 if successful or 0 if there are problems
- */
- function addArray($vals)
- {
- global $XML_RPC_Types;
- if ($this->mytype != 0) {
- $this->raiseError(
- 'Already initialized as a [' . $this->kindOf() . ']',
- XML_RPC_ERROR_ALREADY_INITIALIZED);
- return 0;
- }
- $this->mytype = $XML_RPC_Types['array'];
- $this->me['array'] = $vals;
- return 1;
- }
-
- /**
- * @return int returns 1 if successful or 0 if there are problems
- */
- function addStruct($vals)
- {
- global $XML_RPC_Types;
- if ($this->mytype != 0) {
- $this->raiseError(
- 'Already initialized as a [' . $this->kindOf() . ']',
- XML_RPC_ERROR_ALREADY_INITIALIZED);
- return 0;
- }
- $this->mytype = $XML_RPC_Types['struct'];
- $this->me['struct'] = $vals;
- return 1;
- }
-
- /**
- * @return void
- */
- function dump($ar)
- {
- reset($ar);
- foreach ($ar as $key => $val) {
- echo "$key => $val<br />";
- if ($key == 'array') {
- foreach ($val as $key2 => $val2) {
- echo "-- $key2 => $val2<br />";
- }
- }
- }
- }
-
- /**
- * @return string the data type of the current value
- */
- function kindOf()
- {
- switch ($this->mytype) {
- case 3:
- return 'struct';
-
- case 2:
- return 'array';
-
- case 1:
- return 'scalar';
-
- default:
- return 'undef';
- }
- }
-
- /**
- * @return string the data in XML format
- */
- function serializedata($typ, $val)
- {
- $rs = '';
- global $XML_RPC_Types, $XML_RPC_Base64, $XML_RPC_String, $XML_RPC_Boolean;
- if (!array_key_exists($typ, $XML_RPC_Types)) {
- // XXX
- // need some way to report this error
- return;
- }
- switch ($XML_RPC_Types[$typ]) {
- case 3:
- // struct
- $rs .= "<struct>\n";
- reset($val);
- foreach ($val as $key2 => $val2) {
- $rs .= "<member><name>${key2}</name>\n";
- $rs .= $this->serializeval($val2);
- $rs .= "</member>\n";
- }
- $rs .= '</struct>';
- break;
-
- case 2:
- // array
- $rs .= "<array>\n<data>\n";
- for ($i = 0; $i < sizeof($val); $i++) {
- $rs .= $this->serializeval($val[$i]);
- }
- $rs .= "</data>\n</array>";
- break;
-
- case 1:
- switch ($typ) {
- case $XML_RPC_Base64:
- $rs .= "<${typ}>" . base64_encode($val) . "</${typ}>";
- break;
- case $XML_RPC_Boolean:
- $rs .= "<${typ}>" . ($val ? '1' : '0') . "</${typ}>";
- break;
- case $XML_RPC_String:
- $rs .= "<${typ}>" . htmlspecialchars($val). "</${typ}>";
- break;
- default:
- $rs .= "<${typ}>${val}</${typ}>";
- }
- }
- return $rs;
- }
-
- /**
- * @return string the data in XML format
- */
- function serialize()
- {
- return $this->serializeval($this);
- }
-
- /**
- * @return string the data in XML format
- */
- function serializeval($o)
- {
- if (!is_object($o) || empty($o->me) || !is_array($o->me)) {
- return '';
- }
- $ar = $o->me;
- reset($ar);
- list($typ, $val) = each($ar);
- return '<value>' . $this->serializedata($typ, $val) . "</value>\n";
- }
-
- /**
- * @return mixed the contents of the element requested
- */
- function structmem($m)
- {
- return $this->me['struct'][$m];
- }
-
- /**
- * @return void
- */
- function structreset()
- {
- reset($this->me['struct']);
- }
-
- /**
- * @return the key/value pair of the struct's current element
- */
- function structeach()
- {
- return each($this->me['struct']);
- }
-
- /**
- * @return mixed the current value
- */
- function getval()
- {
- // UNSTABLE
- global $XML_RPC_BOOLEAN, $XML_RPC_Base64;
-
- reset($this->me);
- $b = current($this->me);
-
- // contributed by I Sofer, 2001-03-24
- // add support for nested arrays to scalarval
- // i've created a new method here, so as to
- // preserve back compatibility
-
- if (is_array($b)) {
- foreach ($b as $id => $cont) {
- $b[$id] = $cont->scalarval();
- }
- }
-
- // add support for structures directly encoding php objects
- if (is_object($b)) {
- $t = get_object_vars($b);
- foreach ($t as $id => $cont) {
- $t[$id] = $cont->scalarval();
- }
- foreach ($t as $id => $cont) {
- $b->$id = $cont;
- }
- }
-
- // end contrib
- return $b;
- }
-
- /**
- * @return mixed
- */
- function scalarval()
- {
- global $XML_RPC_Boolean, $XML_RPC_Base64;
- reset($this->me);
- return current($this->me);
- }
-
- /**
- * @return string
- */
- function scalartyp()
- {
- global $XML_RPC_I4, $XML_RPC_Int;
- reset($this->me);
- $a = key($this->me);
- if ($a == $XML_RPC_I4) {
- $a = $XML_RPC_Int;
- }
- return $a;
- }
-
- /**
- * @return mixed the struct's current element
- */
- function arraymem($m)
- {
- return $this->me['array'][$m];
- }
-
- /**
- * @return int the number of elements in the array
- */
- function arraysize()
- {
- reset($this->me);
- list($a, $b) = each($this->me);
- return sizeof($b);
- }
-
- /**
- * Determines if the item submitted is an XML_RPC_Value object
- *
- * @param mixed $val the variable to be evaluated
- *
- * @return bool TRUE if the item is an XML_RPC_Value object
- *
- * @static
- * @since Method available since Release 1.3.0
- */
- function isValue($val)
- {
- return (strtolower(get_class($val)) == 'xml_rpc_value');
- }
-}
-
-/**
- * Return an ISO8601 encoded string
- *
- * While timezones ought to be supported, the XML-RPC spec says:
- *
- * "Don't assume a timezone. It should be specified by the server in its
- * documentation what assumptions it makes about timezones."
- *
- * This routine always assumes localtime unless $utc is set to 1, in which
- * case UTC is assumed and an adjustment for locale is made when encoding.
- *
- * @return string the formatted date
- */
-function XML_RPC_iso8601_encode($timet, $utc = 0)
-{
- if (!$utc) {
- $t = strftime('%Y%m%dT%H:%M:%S', $timet);
- } else {
- if (function_exists('gmstrftime')) {
- // gmstrftime doesn't exist in some versions
- // of PHP
- $t = gmstrftime('%Y%m%dT%H:%M:%S', $timet);
- } else {
- $t = strftime('%Y%m%dT%H:%M:%S', $timet - date('Z'));
- }
- }
- return $t;
-}
-
-/**
- * Convert a datetime string into a Unix timestamp
- *
- * While timezones ought to be supported, the XML-RPC spec says:
- *
- * "Don't assume a timezone. It should be specified by the server in its
- * documentation what assumptions it makes about timezones."
- *
- * This routine always assumes localtime unless $utc is set to 1, in which
- * case UTC is assumed and an adjustment for locale is made when encoding.
- *
- * @return int the unix timestamp of the date submitted
- */
-function XML_RPC_iso8601_decode($idate, $utc = 0)
-{
- $t = 0;
- if (ereg('([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})', $idate, $regs)) {
- if ($utc) {
- $t = gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
- } else {
- $t = mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
- }
- }
- return $t;
-}
-
-/**
- * Converts an XML_RPC_Value object into native PHP types
- *
- * @param object $XML_RPC_val the XML_RPC_Value object to decode
- *
- * @return mixed the PHP values
- */
-function XML_RPC_decode($XML_RPC_val)
-{
- $kind = $XML_RPC_val->kindOf();
-
- if ($kind == 'scalar') {
- return $XML_RPC_val->scalarval();
-
- } elseif ($kind == 'array') {
- $size = $XML_RPC_val->arraysize();
- $arr = array();
- for ($i = 0; $i < $size; $i++) {
- $arr[] = XML_RPC_decode($XML_RPC_val->arraymem($i));
- }
- return $arr;
-
- } elseif ($kind == 'struct') {
- $XML_RPC_val->structreset();
- $arr = array();
- while (list($key, $value) = $XML_RPC_val->structeach()) {
- $arr[$key] = XML_RPC_decode($value);
- }
- return $arr;
- }
-}
-
-/**
- * Converts native PHP types into an XML_RPC_Value object
- *
- * @param mixed $php_val the PHP value or variable you want encoded
- *
- * @return object the XML_RPC_Value object
- */
-function XML_RPC_encode($php_val)
-{
- global $XML_RPC_Boolean, $XML_RPC_Int, $XML_RPC_Double, $XML_RPC_String,
- $XML_RPC_Array, $XML_RPC_Struct;
-
- $type = gettype($php_val);
- $XML_RPC_val = new XML_RPC_Value;
-
- switch ($type) {
- case 'array':
- if (empty($php_val)) {
- $XML_RPC_val->addArray($php_val);
- break;
- }
- $tmp = array_diff(array_keys($php_val), range(0, count($php_val)-1));
- if (empty($tmp)) {
- $arr = array();
- foreach ($php_val as $k => $v) {
- $arr[$k] = XML_RPC_encode($v);
- }
- $XML_RPC_val->addArray($arr);
- break;
- }
- // fall though if it's not an enumerated array
-
- case 'object':
- $arr = array();
- foreach ($php_val as $k => $v) {
- $arr[$k] = XML_RPC_encode($v);
- }
- $XML_RPC_val->addStruct($arr);
- break;
-
- case 'integer':
- $XML_RPC_val->addScalar($php_val, $XML_RPC_Int);
- break;
-
- case 'double':
- $XML_RPC_val->addScalar($php_val, $XML_RPC_Double);
- break;
-
- case 'string':
- case 'NULL':
- $XML_RPC_val->addScalar($php_val, $XML_RPC_String);
- break;
-
- case 'boolean':
- // Add support for encoding/decoding of booleans, since they
- // are supported in PHP
- // by <G_Giunta_2001-02-29>
- $XML_RPC_val->addScalar($php_val, $XML_RPC_Boolean);
- break;
-
- case 'unknown type':
- default:
- $XML_RPC_val = false;
- }
- return $XML_RPC_val;
-}
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * c-hanging-comment-ender-p: nil
- * End:
- */
-
-?>
diff --git a/inc/XML/RPC/Server.php b/inc/XML/RPC/Server.php
deleted file mode 100644
index 5c5c04b1f7a..00000000000
--- a/inc/XML/RPC/Server.php
+++ /dev/null
@@ -1,624 +0,0 @@
-<?php
-
-/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
-
-/**
- * Server commands for our PHP implementation of the XML-RPC protocol
- *
- * This is a PEAR-ified version of Useful inc's XML-RPC for PHP.
- * It has support for HTTP transport, proxies and authentication.
- *
- * PHP versions 4 and 5
- *
- * LICENSE: License is granted to use or modify this software
- * ("XML-RPC for PHP") for commercial or non-commercial use provided the
- * copyright of the author is preserved in any distributed or derivative work.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESSED 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 AUTHOR 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 Web Services
- * @package XML_RPC
- * @author Edd Dumbill <edd@usefulinc.com>
- * @author Stig Bakken <stig@php.net>
- * @author Martin Jansen <mj@php.net>
- * @author Daniel Convissor <danielc@php.net>
- * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group
- * @version CVS: $Id: Server.php,v 1.29 2005/08/14 20:25:35 danielc Exp $
- * @link http://pear.php.net/package/XML_RPC
- */
-
-
-/**
- * Pull in the XML_RPC class
- */
-require_once 'XML/RPC.php';
-
-
-/**
- * signature for system.listMethods: return = array,
- * parameters = a string or nothing
- * @global array $GLOBALS['XML_RPC_Server_listMethods_sig']
- */
-$GLOBALS['XML_RPC_Server_listMethods_sig'] = array(
- array($GLOBALS['XML_RPC_Array'],
- $GLOBALS['XML_RPC_String']
- ),
- array($GLOBALS['XML_RPC_Array'])
-);
-
-/**
- * docstring for system.listMethods
- * @global string $GLOBALS['XML_RPC_Server_listMethods_doc']
- */
-$GLOBALS['XML_RPC_Server_listMethods_doc'] = 'This method lists all the'
- . ' methods that the XML-RPC server knows how to dispatch';
-
-/**
- * signature for system.methodSignature: return = array,
- * parameters = string
- * @global array $GLOBALS['XML_RPC_Server_methodSignature_sig']
- */
-$GLOBALS['XML_RPC_Server_methodSignature_sig'] = array(
- array($GLOBALS['XML_RPC_Array'],
- $GLOBALS['XML_RPC_String']
- )
-);
-
-/**
- * docstring for system.methodSignature
- * @global string $GLOBALS['XML_RPC_Server_methodSignature_doc']
- */
-$GLOBALS['XML_RPC_Server_methodSignature_doc'] = 'Returns an array of known'
- . ' signatures (an array of arrays) for the method name passed. If'
- . ' no signatures are known, returns a none-array (test for type !='
- . ' array to detect missing signature)';
-
-/**
- * signature for system.methodHelp: return = string,
- * parameters = string
- * @global array $GLOBALS['XML_RPC_Server_methodHelp_sig']
- */
-$GLOBALS['XML_RPC_Server_methodHelp_sig'] = array(
- array($GLOBALS['XML_RPC_String'],
- $GLOBALS['XML_RPC_String']
- )
-);
-
-/**
- * docstring for methodHelp
- * @global string $GLOBALS['XML_RPC_Server_methodHelp_doc']
- */
-$GLOBALS['XML_RPC_Server_methodHelp_doc'] = 'Returns help text if defined'
- . ' for the method passed, otherwise returns an empty string';
-
-/**
- * dispatch map for the automatically declared XML-RPC methods.
- * @global array $GLOBALS['XML_RPC_Server_dmap']
- */
-$GLOBALS['XML_RPC_Server_dmap'] = array(
- 'system.listMethods' => array(
- 'function' => 'XML_RPC_Server_listMethods',
- 'signature' => $GLOBALS['XML_RPC_Server_listMethods_sig'],
- 'docstring' => $GLOBALS['XML_RPC_Server_listMethods_doc']
- ),
- 'system.methodHelp' => array(
- 'function' => 'XML_RPC_Server_methodHelp',
- 'signature' => $GLOBALS['XML_RPC_Server_methodHelp_sig'],
- 'docstring' => $GLOBALS['XML_RPC_Server_methodHelp_doc']
- ),
- 'system.methodSignature' => array(
- 'function' => 'XML_RPC_Server_methodSignature',
- 'signature' => $GLOBALS['XML_RPC_Server_methodSignature_sig'],
- 'docstring' => $GLOBALS['XML_RPC_Server_methodSignature_doc']
- )
-);
-
-/**
- * @global string $GLOBALS['XML_RPC_Server_debuginfo']
- */
-$GLOBALS['XML_RPC_Server_debuginfo'] = '';
-
-
-/**
- * Lists all the methods that the XML-RPC server knows how to dispatch
- *
- * @return object a new XML_RPC_Response object
- */
-function XML_RPC_Server_listMethods($server, $m)
-{
- global $XML_RPC_err, $XML_RPC_str, $XML_RPC_Server_dmap;
-
- $v = new XML_RPC_Value();
- $outAr = array();
- foreach ($server->dmap as $key => $val) {
- $outAr[] = new XML_RPC_Value($key, 'string');
- }
- foreach ($XML_RPC_Server_dmap as $key => $val) {
- $outAr[] = new XML_RPC_Value($key, 'string');
- }
- $v->addArray($outAr);
- return new XML_RPC_Response($v);
-}
-
-/**
- * Returns an array of known signatures (an array of arrays)
- * for the given method
- *
- * If no signatures are known, returns a none-array
- * (test for type != array to detect missing signature)
- *
- * @return object a new XML_RPC_Response object
- */
-function XML_RPC_Server_methodSignature($server, $m)
-{
- global $XML_RPC_err, $XML_RPC_str, $XML_RPC_Server_dmap;
-
- $methName = $m->getParam(0);
- $methName = $methName->scalarval();
- if (strpos($methName, 'system.') === 0) {
- $dmap = $XML_RPC_Server_dmap;
- $sysCall = 1;
- } else {
- $dmap = $server->dmap;
- $sysCall = 0;
- }
- // print "<!-- ${methName} -->\n";
- if (isset($dmap[$methName])) {
- if ($dmap[$methName]['signature']) {
- $sigs = array();
- $thesigs = $dmap[$methName]['signature'];
- for ($i = 0; $i < sizeof($thesigs); $i++) {
- $cursig = array();
- $inSig = $thesigs[$i];
- for ($j = 0; $j < sizeof($inSig); $j++) {
- $cursig[] = new XML_RPC_Value($inSig[$j], 'string');
- }
- $sigs[] = new XML_RPC_Value($cursig, 'array');
- }
- $r = new XML_RPC_Response(new XML_RPC_Value($sigs, 'array'));
- } else {
- $r = new XML_RPC_Response(new XML_RPC_Value('undef', 'string'));
- }
- } else {
- $r = new XML_RPC_Response(0, $XML_RPC_err['introspect_unknown'],
- $XML_RPC_str['introspect_unknown']);
- }
- return $r;
-}
-
-/**
- * Returns help text if defined for the method passed, otherwise returns
- * an empty string
- *
- * @return object a new XML_RPC_Response object
- */
-function XML_RPC_Server_methodHelp($server, $m)
-{
- global $XML_RPC_err, $XML_RPC_str, $XML_RPC_Server_dmap;
-
- $methName = $m->getParam(0);
- $methName = $methName->scalarval();
- if (strpos($methName, 'system.') === 0) {
- $dmap = $XML_RPC_Server_dmap;
- $sysCall = 1;
- } else {
- $dmap = $server->dmap;
- $sysCall = 0;
- }
-
- if (isset($dmap[$methName])) {
- if ($dmap[$methName]['docstring']) {
- $r = new XML_RPC_Response(new XML_RPC_Value($dmap[$methName]['docstring']),
- 'string');
- } else {
- $r = new XML_RPC_Response(new XML_RPC_Value('', 'string'));
- }
- } else {
- $r = new XML_RPC_Response(0, $XML_RPC_err['introspect_unknown'],
- $XML_RPC_str['introspect_unknown']);
- }
- return $r;
-}
-
-/**
- * @return void
- */
-function XML_RPC_Server_debugmsg($m)
-{
- global $XML_RPC_Server_debuginfo;
- $XML_RPC_Server_debuginfo = $XML_RPC_Server_debuginfo . $m . "\n";
-}
-
-
-/**
- * A server for receiving and replying to XML RPC requests
- *
- * <code>
- * $server = new XML_RPC_Server(
- * array(
- * 'isan8' =>
- * array(
- * 'function' => 'is_8',
- * 'signature' =>
- * array(
- * array('boolean', 'int'),
- * array('boolean', 'int', 'boolean'),
- * array('boolean', 'string'),
- * array('boolean', 'string', 'boolean'),
- * ),
- * 'docstring' => 'Is the value an 8?'
- * ),
- * ),
- * 1,
- * 0
- * );
- * </code>
- *
- * @category Web Services
- * @package XML_RPC
- * @author Edd Dumbill <edd@usefulinc.com>
- * @author Stig Bakken <stig@php.net>
- * @author Martin Jansen <mj@php.net>
- * @author Daniel Convissor <danielc@php.net>
- * @copyright 1999-2001 Edd Dumbill, 2001-2005 The PHP Group
- * @version Release: 1.4.0
- * @link http://pear.php.net/package/XML_RPC
- */
-class XML_RPC_Server
-{
- /**
- * The dispatch map, listing the methods this server provides.
- * @var array
- */
- var $dmap = array();
-
- /**
- * The present response's encoding
- * @var string
- * @see XML_RPC_Message::getEncoding()
- */
- var $encoding = '';
-
- /**
- * Debug mode (0 = off, 1 = on)
- * @var integer
- */
- var $debug = 0;
-
- /**
- * The response's HTTP headers
- * @var string
- */
- var $server_headers = '';
-
- /**
- * The response's XML payload
- * @var string
- */
- var $server_payload = '';
-
-
- /**
- * Constructor for the XML_RPC_Server class
- *
- * @param array $dispMap the dispatch map. An associative array
- * explaining each function. The keys of the main
- * array are the procedure names used by the
- * clients. The value is another associative array
- * that contains up to three elements:
- * + The 'function' element's value is the name
- * of the function or method that gets called.
- * To define a class' method: 'class::method'.
- * + The 'signature' element (optional) is an
- * array describing the return values and
- * parameters
- * + The 'docstring' element (optional) is a
- * string describing what the method does
- * @param int $serviceNow should the HTTP response be sent now?
- * (1 = yes, 0 = no)
- * @param int $debug should debug output be displayed?
- * (1 = yes, 0 = no)
- *
- * @return void
- */
- function XML_RPC_Server($dispMap, $serviceNow = 1, $debug = 0)
- {
- global $HTTP_RAW_POST_DATA;
-
- if ($debug) {
- $this->debug = 1;
- } else {
- $this->debug = 0;
- }
-
- $this->dmap = $dispMap;
-
- if ($serviceNow) {
- $this->service();
- } else {
- $this->createServerPayload();
- $this->createServerHeaders();
- }
- }
-
- /**
- * @return string the debug information if debug debug mode is on
- */
- function serializeDebug()
- {
- global $XML_RPC_Server_debuginfo, $HTTP_RAW_POST_DATA;
-
- if ($this->debug) {
- XML_RPC_Server_debugmsg('vvv POST DATA RECEIVED BY SERVER vvv' . "\n"
- . $HTTP_RAW_POST_DATA
- . "\n" . '^^^ END POST DATA ^^^');
- }
-
- if ($XML_RPC_Server_debuginfo != '') {
- return "<!-- PEAR XML_RPC SERVER DEBUG INFO:\n\n"
- . preg_replace('/-(?=-)/', '- ', $XML_RPC_Server_debuginfo)
- . "-->\n";
- } else {
- return '';
- }
- }
-
- /**
- * Sends the response
- *
- * The encoding and content-type are determined by
- * XML_RPC_Message::getEncoding()
- *
- * @return void
- *
- * @uses XML_RPC_Server::createServerPayload(),
- * XML_RPC_Server::createServerHeaders()
- */
- function service()
- {
- if (!$this->server_payload) {
- $this->createServerPayload();
- }
- if (!$this->server_headers) {
- $this->createServerHeaders();
- }
- header($this->server_headers);
- print $this->server_payload;
- }
-
- /**
- * Generates the payload and puts it in the $server_payload property
- *
- * @return void
- *
- * @uses XML_RPC_Server::parseRequest(), XML_RPC_Server::$encoding,
- * XML_RPC_Response::serialize(), XML_RPC_Server::serializeDebug()
- */
- function createServerPayload()
- {
- $r = $this->parseRequest();
- $this->server_payload = '<?xml version="1.0" encoding="'
- . $this->encoding . '"?>' . "\n"
- . $this->serializeDebug()
- . $r->serialize();
- }
-
- /**
- * Determines the HTTP headers and puts them in the $server_headers
- * property
- *
- * @return boolean TRUE if okay, FALSE if $server_payload isn't set.
- *
- * @uses XML_RPC_Server::createServerPayload(),
- * XML_RPC_Server::$server_headers
- */
- function createServerHeaders()
- {
- if (!$this->server_payload) {
- return false;
- }
- $this->server_headers = 'Content-Length: '
- . strlen($this->server_payload) . "\r\n"
- . 'Content-Type: text/xml;'
- . ' charset=' . $this->encoding;
- return true;
- }
-
- /**
- * @return array
- */
- function verifySignature($in, $sig)
- {
- for ($i = 0; $i < sizeof($sig); $i++) {
- // check each possible signature in turn
- $cursig = $sig[$i];
- if (sizeof($cursig) == $in->getNumParams() + 1) {
- $itsOK = 1;
- for ($n = 0; $n < $in->getNumParams(); $n++) {
- $p = $in->getParam($n);
- // print "<!-- $p -->\n";
- if ($p->kindOf() == 'scalar') {
- $pt = $p->scalartyp();
- } else {
- $pt = $p->kindOf();
- }
- // $n+1 as first type of sig is return type
- if ($pt != $cursig[$n+1]) {
- $itsOK = 0;
- $pno = $n+1;
- $wanted = $cursig[$n+1];
- $got = $pt;
- break;
- }
- }
- if ($itsOK) {
- return array(1);
- }
- }
- }
- if (isset($wanted)) {
- return array(0, "Wanted ${wanted}, got ${got} at param ${pno}");
- } else {
- $allowed = array();
- foreach ($sig as $val) {
- end($val);
- $allowed[] = key($val);
- }
- $allowed = array_unique($allowed);
- $last = count($allowed) - 1;
- if ($last > 0) {
- $allowed[$last] = 'or ' . $allowed[$last];
- }
- return array(0,
- 'Signature permits ' . implode(', ', $allowed)
- . ' parameters but the request had '
- . $in->getNumParams());
- }
- }
-
- /**
- * @return object a new XML_RPC_Response object
- *
- * @uses XML_RPC_Message::getEncoding(), XML_RPC_Server::$encoding
- */
- function parseRequest($data = '')
- {
- global $XML_RPC_xh, $HTTP_RAW_POST_DATA,
- $XML_RPC_err, $XML_RPC_str, $XML_RPC_errxml,
- $XML_RPC_defencoding, $XML_RPC_Server_dmap;
-
- if ($data == '') {
- $data = $HTTP_RAW_POST_DATA;
- }
-
- $this->encoding = XML_RPC_Message::getEncoding($data);
- $parser_resource = xml_parser_create($this->encoding);
- $parser = (int) $parser_resource;
-
- $XML_RPC_xh[$parser] = array();
- $XML_RPC_xh[$parser]['cm'] = 0;
- $XML_RPC_xh[$parser]['isf'] = 0;
- $XML_RPC_xh[$parser]['params'] = array();
- $XML_RPC_xh[$parser]['method'] = '';
- $XML_RPC_xh[$parser]['stack'] = array();
- $XML_RPC_xh[$parser]['valuestack'] = array();
-
- $plist = '';
-
- // decompose incoming XML into request structure
-
- xml_parser_set_option($parser_resource, XML_OPTION_CASE_FOLDING, true);
- xml_set_element_handler($parser_resource, 'XML_RPC_se', 'XML_RPC_ee');
- xml_set_character_data_handler($parser_resource, 'XML_RPC_cd');
- if (!xml_parse($parser_resource, $data, 1)) {
- // return XML error as a faultCode
- $r = new XML_RPC_Response(0,
- $XML_RPC_errxml+xml_get_error_code($parser_resource),
- sprintf('XML error: %s at line %d',
- xml_error_string(xml_get_error_code($parser_resource)),
- xml_get_current_line_number($parser_resource)));
- xml_parser_free($parser_resource);
- } elseif ($XML_RPC_xh[$parser]['isf']>1) {
- $r = new XML_RPC_Response(0,
- $XML_RPC_err['invalid_request'],
- $XML_RPC_str['invalid_request']
- . ': '
- . $XML_RPC_xh[$parser]['isf_reason']);
- xml_parser_free($parser_resource);
- } else {
- xml_parser_free($parser_resource);
- $m = new XML_RPC_Message($XML_RPC_xh[$parser]['method']);
- // now add parameters in
- for ($i = 0; $i < sizeof($XML_RPC_xh[$parser]['params']); $i++) {
- // print '<!-- ' . $XML_RPC_xh[$parser]['params'][$i]. "-->\n";
- $plist .= "$i - " . var_export($XML_RPC_xh[$parser]['params'][$i], true) . " \n";
- $m->addParam($XML_RPC_xh[$parser]['params'][$i]);
- }
- XML_RPC_Server_debugmsg($plist);
-
- // now to deal with the method
- $methName = $XML_RPC_xh[$parser]['method'];
- if (strpos($methName, 'system.') === 0) {
- $dmap = $XML_RPC_Server_dmap;
- $sysCall = 1;
- } else {
- $dmap = $this->dmap;
- $sysCall = 0;
- }
-
- if (isset($dmap[$methName]['function'])
- && is_string($dmap[$methName]['function'])
- && strpos($dmap[$methName]['function'], '::') !== false)
- {
- $dmap[$methName]['function'] =
- explode('::', $dmap[$methName]['function']);
- }
-
- if (isset($dmap[$methName]['function'])
- && is_callable($dmap[$methName]['function']))
- {
- // dispatch if exists
- if (isset($dmap[$methName]['signature'])) {
- $sr = $this->verifySignature($m,
- $dmap[$methName]['signature'] );
- }
- if (!isset($dmap[$methName]['signature']) || $sr[0]) {
- // if no signature or correct signature
- if ($sysCall) {
- $r = call_user_func($dmap[$methName]['function'], $this, $m);
- } else {
- $r = call_user_func($dmap[$methName]['function'], $m);
- }
- if (!is_a($r, 'XML_RPC_Response')) {
- $r = new XML_RPC_Response(0, $XML_RPC_err['not_response_object'],
- $XML_RPC_str['not_response_object']);
- }
- } else {
- $r = new XML_RPC_Response(0, $XML_RPC_err['incorrect_params'],
- $XML_RPC_str['incorrect_params']
- . ': ' . $sr[1]);
- }
- } else {
- // else prepare error response
- $r = new XML_RPC_Response(0, $XML_RPC_err['unknown_method'],
- $XML_RPC_str['unknown_method']);
- }
- }
- return $r;
- }
-
- /**
- * Echos back the input packet as a string value
- *
- * @return void
- *
- * Useful for debugging.
- */
- function echoInput()
- {
- global $HTTP_RAW_POST_DATA;
-
- $r = new XML_RPC_Response(0);
- $r->xv = new XML_RPC_Value("'Aha said I: '" . $HTTP_RAW_POST_DATA, 'string');
- print $r->serialize();
- }
-}
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * c-hanging-comment-ender-p: nil
- * End:
- */
-
-?>
diff --git a/inc/docs/HTTP_WebDAV_Server/README b/inc/docs/HTTP_WebDAV_Server/README
deleted file mode 100644
index 9847b261684..00000000000
--- a/inc/docs/HTTP_WebDAV_Server/README
+++ /dev/null
@@ -1,10 +0,0 @@
-This code depends on code introduced into the developement branch for
-PHP 4.3, so it will not run with PHP releases before 4.3.0
-
-preliminary documentation is available in the dav.txt file,
-although it is currently a little outdated ...
-
-Server/Filesystem.php contains a sample implementation for a simple
-file server (including property and lock info storage in a mySQL
-database, see db/Fileserver.sql). This sample should give you a good
-clue about how to use this class for your own purpose.
diff --git a/inc/docs/HTTP_WebDAV_Server/dav.txt b/inc/docs/HTTP_WebDAV_Server/dav.txt
deleted file mode 100644
index 9e0b8299229..00000000000
--- a/inc/docs/HTTP_WebDAV_Server/dav.txt
+++ /dev/null
@@ -1,229 +0,0 @@
-The HTTP_WebDAV_Server class provides a framwork for the
-implementation of customized WebDAV servers that can provide
-filesystem like access to almost any kind of hierachically stored
-data.
-
-The (abstract) server base class tries to encapsulate as much of
-the protocol details as possible. It takes care of the needed WebDAV
-header and XML payload parsing and generation (and knows about some
-of the problems with common clients and tries hard to work around
-them).
-
-WebDAV itself is an extension to the HTTP protocol. The HTTP
-specific parts of it are already taken care of by the web server. Any
-data needed by the server class is provided by the PHP SAPI interface
-of the server used.
-
-To create a working server from the base class you have to extend and
-add methods for the actual access, modification and access control of
-your own data.
-
-You may use the included HTTP_WebDAV_Server_Filesystem class as an
-example of how to create a working server. This sample implementation
-is used for testing the implementation of this package against the
-litmus WebDAV compliance test suite.
-(litmus is available on http://www.webdav.org/neon/litmus)
-
-The methods you can add in your extended class are mostly named after
-the WebDAV specific request methods (using upper case names). Methods
-you may implement are:
-
-* GET() get a resource from the server
-* HEAD() get resource headers only from the server
-* PUT() create or modify a resource on the server
-* COPY() copy a resource on the server
-* MOVE() move a resource on the server
-* DELETE() delete a resource on the server
-* MKCOL() create a new collection
-* PROPFIND() get property data for a resource
-* PROPPATCH() modify property data for a resource
-* LOCK() lock a resource
-* UNLOCK() unlock a locked resource
-* checklock() check whether a resource is locked
-* check_auth() check authentication
-
-You can think of WebDAV resources as files, collections as directories
-and properties as filesystem meta data (like size, creation date, ...).
-
-The base class is able identify which of the methods you have
-implemented and will create appropriate answers to OPTIONS requests
-that ask for the WebDAV standards compliance level and the allowed
-HTTP methods for you.
-
-For a minimal working test server you need to implement GET(), PUT()
-and PROPFIND() only.
-
-For a minimal (level 1) standards compliant server you also need to
-implement MKCOL(), DELETE(), and PROPPATCH(). The COPY(), MOVE() and
-HEAD() methods are emulated using GET(), PUT() and DELETE() if not
-implemented, but for performance reasons you should better implement
-them yourself.
-
-For a complete (level 2) RFC2518 compliand server you also have to
-provide locking support by implementing LOCK(), UNLOCK() and
-checklock().
-
-Authentication is not really part of the WebDAV specification and
-should be handled on the HTTP level. You can do so by means of, for
-example, .htaccess files or similar services provided by your web
-server. But you can also make use of the authentication features
-offered by PHP by implementing the check_auth() method.
-Using the check_auth() method you can create a dynamic interface
-to any authentication system protecting the data you want to serve.
-
-
-<WARNING>
- the following reference information may be outdated and/or
- incomplete ...
-</WARNING>
-
-bool PROPINFO($options, &$files)
-
- options[path] - Resource-Path
- options[depth] - Depth of search requested: "0", "1", or "infinity"
- options[props] - "all", "names", or an arry of requested properties
- each property array element is either a string
- (which implies the default "DAV:" namespace) or
- an array with the two elements "name" and "xmlns"
- for the properties name and XML namespace
-
- &$files - storage array for property results with the following elements:
-
- "files" -> array of found properties forresources. elements are:
-
- "path" -> path of the resource
- "props" -> properties array
- each property array element is either a string
- (which implies the default "DAV:" namespace) or
- an array with the two elements "name" and "xmlns"
- for the properties name and XML namespace
-
- you should at least support the following
- list of properties from the "DAV:" namespave:
-
- - resourcetype: "collection" oder ""
- - creationdate: unix-timestamp
- - getcontentlength: integer
- - getlastmodified: unix-timestamp
-
- You may want to add support for these "DAV:"
- properties, too:
-
- - getcontenttype: mime-type
- - displayname: string
-
- for a compliant server you also have to be
- able to return any property from other
- namespaces that has been stored using
- PROPPATCH
-
-
- return-value: true / false
-
-
-
-
-string MKCOL($option)
-
- options[path] - path of the new collection to be created
-
- return-value: string
- HTTP status and status message, possible values are
- * 201 Success
- * 403 Forbidden
- * 405 Method not allowed
- * 409 Conflict
- * 415 Unsupported media type
- * 507 Insufficient Storage
- (see also RFC2518 8.3.2)
-
-
-
-
-string GET(&$options)
-
- $options['path'] - path to the requested resource
- $options['ranges'] - optional array of range specifications for
- partial access. range specs are arrays that
- consist of either a 'start' and 'end' element
- (where 'end' can be empty to indicate a request
- up to the actual end of the resource) or a
- 'last' element to access the last n bytes of
- a resource without knowing its actual size in
- advance
-
- Return-value: true bei Erfolg, false wenn not found
-
- (TODO: andere stati berücksichtigen)
-
- Content-Type, Content-Length header müssen von der Methode selbst
- erzeugt werden (TODO: outdated)
-
-
-
-
-string PUT($options)
-
- options[path] - path to the requested resource
- options[content_length] - size of request data in bytes
- options[stream] - a PHP stream providing the input data
-
- return-value: string
- HTTP status, possible values are:
- * 201 Created -> the resource did not exist before
- and has been successfully created
- * 204 No Content -> a previously existing resource has
- successfully been modified
- * 409 Conflict
- ...
-
-
-
-
-string COPY($options)
-
- options[path] - path to the resource to be copied
- options[depth] - "0" or "infinity" (applies only to directories)
- options[overwrite] - true / false
- options[dest] - path to the destination resource if local
- options[dest_url] - non-local destination path
-
- return-value: string
- HTTP status, see RFC2518 8.8.5
-
-
-
-
-
-string MOVE($options)
-
- options[path] - path to the resource to be moved
- options[overwrite] - true / false
- options[dest] - path to the destination resource if local
- options[dest_url] - non-local destination path
-
- return-value: string
- HTTP status, see RFC2518 8.9.4
-
-
-
-
-string DELETE($options)
-
- options[path] - path to the resource to be removed
-
- return-value: string
- HTTP status, see RFC2518 8.6.2
-
-
-
-
-
-bool check_auth($type, $user, $passwd)
-
- $type: HTTP-Auth type, i.A. "Basic"
- $user: HTTP Username
- $passwd: HTTP Passwort
-
- return-value: true bei success, sonst false
- (ToDo: array mit Auth-Type und Realm String zulassen bei fehler) \ No newline at end of file
diff --git a/inc/docs/HTTP_WebDAV_Server/db/Fileserver.sql b/inc/docs/HTTP_WebDAV_Server/db/Fileserver.sql
deleted file mode 100644
index 8047d12f5e4..00000000000
--- a/inc/docs/HTTP_WebDAV_Server/db/Fileserver.sql
+++ /dev/null
@@ -1,49 +0,0 @@
--- MySQL dump 9.06
---
--- Host: localhost Database: webdav
----------------------------------------------------------
--- Server version 4.0.3-beta
-
---
--- Table structure for table 'locks'
---
-
-CREATE TABLE locks (
- token varchar(255) NOT NULL default '',
- path varchar(200) NOT NULL default '',
- expires int(11) NOT NULL default '0',
- owner varchar(200) default NULL,
- recursive int(11) default '0',
- writelock int(11) default '0',
- exclusivelock int(11) NOT NULL default 0,
- PRIMARY KEY (token),
- UNIQUE KEY token (token),
- KEY path (path),
- KEY path_2 (path),
- KEY path_3 (path,token),
- KEY expires (expires)
-) TYPE=MyISAM;
-
---
--- Dumping data for table 'locks'
---
-
-
---
--- Table structure for table 'properties'
---
-
-CREATE TABLE properties (
- path varchar(255) NOT NULL default '',
- name varchar(120) NOT NULL default '',
- ns varchar(120) NOT NULL default 'DAV:',
- value text,
- PRIMARY KEY (path,name,ns),
- KEY path (path)
-) TYPE=MyISAM;
-
---
--- Dumping data for table 'properties'
---
-
-
diff --git a/inc/lib_base.php b/inc/lib_base.php
deleted file mode 100644
index be0883dc52a..00000000000
--- a/inc/lib_base.php
+++ /dev/null
@@ -1,728 +0,0 @@
-<?php
-
-/**
-* ownCloud
-*
-* @author Frank Karlitschek
-* @copyright 2010 Frank Karlitschek karlitschek@kde.org
-*
-* This library is free software; you can redistribute it and/or
-* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
-* License as published by the Free Software Foundation; either
-* version 3 of the License, or 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 AFFERO 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, see <http://www.gnu.org/licenses/>.
-*
-*/
-
-
-// set some stuff
-ob_start();
-// error_reporting(E_ALL | E_STRICT);
-error_reporting(E_ALL); // MDB2 gives loads of strict error, disabling for now
-
-date_default_timezone_set('Europe/Berlin');
-ini_set('arg_separator.output','&amp;');
-ini_set('session.cookie_httponly','1;');
-session_start();
-// calculate the documentroot
-$SERVERROOT=substr(__FILE__,0,-17);
-$DOCUMENTROOT=realpath($_SERVER['DOCUMENT_ROOT']);
-$SERVERROOT=str_replace("\\",'/',$SERVERROOT);
-$SUBURI=substr(realpath($_SERVER["SCRIPT_FILENAME"]),strlen($SERVERROOT));
-$WEBROOT=substr($_SERVER["SCRIPT_NAME"],0,strlen($_SERVER["SCRIPT_NAME"])-strlen($SUBURI));
-
-
-
-if($WEBROOT!='' and $WEBROOT[0]!=='/'){
- $WEBROOT='/'.$WEBROOT;
-}
-
-// set the right include path
-// set_include_path(get_include_path().PATH_SEPARATOR.$SERVERROOT.PATH_SEPARATOR.$SERVERROOT.'/inc'.PATH_SEPARATOR.$SERVERROOT.'/config');
-
-// define default config values
-$CONFIG_INSTALLED=false;
-$CONFIG_DATADIRECTORY=$SERVERROOT.'/data';
-$CONFIG_BACKUPDIRECTORY=$SERVERROOT.'/backup';
-$CONFIG_HTTPFORCESSL=false;
-$CONFIG_ENABLEBACKUP=false;
-$CONFIG_DATEFORMAT='j M Y G:i';
-$CONFIG_DBNAME='owncloud';
-$CONFIG_DBTYPE='sqlite';
-$CONFIG_FILESYSTEM=array();
-
-// include the generated configfile
-@include_once($SERVERROOT.'/config/config.php');
-
-
-$CONFIG_DATADIRECTORY_ROOT=$CONFIG_DATADIRECTORY;// store this in a seperate variable so we can change the data directory to jail users.
-// redirect to https site if configured
-if(isset($CONFIG_HTTPFORCESSL) and $CONFIG_HTTPFORCESSL){
- if(!isset($_SERVER['HTTPS']) or $_SERVER['HTTPS'] != 'on') {
- $url = "https://". $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
- header("Location: $url");
- exit;
- }
-}
-
-// load core libs
-oc_require_once('lib_files.php');
-oc_require_once('lib_filesystem.php');
-oc_require_once('lib_filestorage.php');
-oc_require_once('lib_fileobserver.php');
-oc_require_once('lib_log.php');
-oc_require_once('lib_config.php');
-oc_require_once('lib_user.php');
-oc_require_once('lib_ocs.php');
-@oc_require_once('MDB2.php');
-@oc_require_once('MDB2/Schema.php');
-oc_require_once('lib_connect.php');
-oc_require_once('lib_remotestorage.php');
-oc_require_once('lib_plugin.php');
-
-OC_PLUGIN::loadPlugins();
-
-if(!isset($CONFIG_BACKEND)){
- $CONFIG_BACKEND='database';
-}
-OC_USER::setBackend($CONFIG_BACKEND);
-
-OC_UTIL::setupFS();
-
-
-
-// check if the server is correctly configured for ownCloud
-OC_UTIL::checkserver();
-
-// listen for login or logout actions
-OC_USER::logoutlistener();
-$loginresult=OC_USER::loginlistener();
-
-/**
- * Class for utility functions
- *
- */
-class OC_UTIL {
- public static $scripts=array();
- public static $styles=array();
- private static $fsSetup=false;
-
- public static function setupFS(){// configure the initial filesystem based on the configuration
- if(self::$fsSetup){//setting up the filesystem twice can only lead to trouble
- return false;
- }
- global $SERVERROOT;
- global $CONFIG_DATADIRECTORY_ROOT;
- global $CONFIG_DATADIRECTORY;
- global $CONFIG_BACKUPDIRECTORY;
- global $CONFIG_ENABLEBACKUP;
- global $CONFIG_FILESYSTEM;
- if(!is_dir($CONFIG_DATADIRECTORY_ROOT)){
- @mkdir($CONFIG_DATADIRECTORY_ROOT) or die("Can't create data directory ($CONFIG_DATADIRECTORY_ROOT), you can usually fix this by setting the owner of '$SERVERROOT' to the user that the web server uses (www-data for debian/ubuntu)");
- }
- if(OC_USER::isLoggedIn()){ //if we aren't logged in, there is no use to set up the filesystem
- //first set up the local "root" storage and the backupstorage if needed
- $rootStorage=OC_FILESYSTEM::createStorage('local',array('datadir'=>$CONFIG_DATADIRECTORY));
- if($CONFIG_ENABLEBACKUP){
- if(!is_dir($CONFIG_BACKUPDIRECTORY)){
- mkdir($CONFIG_BACKUPDIRECTORY);
- }
- if(!is_dir($CONFIG_BACKUPDIRECTORY.'/'.$_SESSION['username_clean'])){
- mkdir($CONFIG_BACKUPDIRECTORY.'/'.$_SESSION['username_clean']);
- }
- $backupStorage=OC_FILESYSTEM::createStorage('local',array('datadir'=>$CONFIG_BACKUPDIRECTORY));
- $backup=new OC_FILEOBSERVER_BACKUP(array('storage'=>$backupStorage));
- $rootStorage->addObserver($backup);
- }
- OC_FILESYSTEM::mount($rootStorage,'/');
-
- $CONFIG_DATADIRECTORY=$CONFIG_DATADIRECTORY_ROOT.'/'.$_SESSION['username_clean'];
- if(!is_dir($CONFIG_DATADIRECTORY)){
- mkdir($CONFIG_DATADIRECTORY);
- }
-
- //set up the other storages according to the system settings
- foreach($CONFIG_FILESYSTEM as $storageConfig){
- if(OC_FILESYSTEM::hasStorageType($storageConfig['type'])){
- $arguments=$storageConfig;
- unset($arguments['type']);
- unset($arguments['mountpoint']);
- $storage=OC_FILESYSTEM::createStorage($storageConfig['type'],$arguments);
- if($storage){
- OC_FILESYSTEM::mount($storage,$storageConfig['mountpoint']);
- }
- }
- }
-
- //jail the user into his "home" directory
- OC_FILESYSTEM::chroot('/'.$_SESSION['username_clean']);
- self::$fsSetup=true;
- }
- }
-
- /**
- * get the current installed version of ownCloud
- * @return array
- */
- public static function getVersion(){
- return array(1,1,0);
- }
-
- /**
- * add a javascript file
- *
- * @param url $url
- */
- public static function addScript($url){
- self::$scripts[]=$url;
- }
- /**
- * add a css file
- *
- * @param url $url
- */
- public static function addStyle($url){
- self::$styles[]=$url;
- }
-
- /**
- * array to store all the optional navigation buttons of the plugins
- *
- */
- static private $NAVIGATION = array();
-
-
- /**
- * check if the current server configuration is suitable for ownCloud
- *
- */
- public static function checkServer(){
- global $SERVERROOT;
- global $CONFIG_DATADIRECTORY_ROOT;
- global $CONFIG_BACKUPDIRECTORY;
- global $CONFIG_ENABLEBACKUP;
- global $CONFIG_INSTALLED;
- $error='';
- if(!is_callable('sqlite_open') and !is_callable('mysql_connect')){
- $error.='No database drivers (sqlite or mysql) installed.<br/>';
- }
- global $CONFIG_DBTYPE;
- global $CONFIG_DBNAME;
- if(!stristr(PHP_OS, 'WIN')){
- if($CONFIG_DBTYPE=='sqlite'){
- $file=$SERVERROOT.'/'.$CONFIG_DBNAME;
- if(file_exists($file)){
- $prems=substr(decoct(fileperms($file)),-3);
- if(substr($prems,2,1)!='0'){
- @chmod($file,0660);
- clearstatcache();
- $prems=substr(decoct(fileperms($file)),-3);
- if(substr($prems,2,1)!='0'){
- $error.='SQLite database file ('.$file.') is readable from the web<br/>';
- }
- }
- }
- }
- $prems=substr(decoct(fileperms($CONFIG_DATADIRECTORY_ROOT)),-3);
- if(substr($prems,-1)!='0'){
- chmodr($CONFIG_DATADIRECTORY_ROOT,0770);
- clearstatcache();
- $prems=substr(decoct(fileperms($CONFIG_DATADIRECTORY_ROOT)),-3);
- if(substr($prems,2,1)!='0'){
- $error.='Data directory ('.$CONFIG_DATADIRECTORY_ROOT.') is readable from the web<br/>';
- }
- }
- if($CONFIG_ENABLEBACKUP){
- $prems=substr(decoct(fileperms($CONFIG_BACKUPDIRECTORY)),-3);
- if(substr($prems,-1)!='0'){
- chmodr($CONFIG_BACKUPDIRECTORY,0770);
- clearstatcache();
- $prems=substr(decoct(fileperms($CONFIG_BACKUPDIRECTORY)),-3);
- if(substr($prems,2,1)!='0'){
- $error.='Data directory ('.$CONFIG_BACKUPDIRECTORY.') is readable from the web<br/>';
- }
- }
- }
- }else{
- //TODO: premisions checks for windows hosts
- }
- if($error){
- die($error);
- }
-}
-
- /**
- * show the header of the web GUI
- *
- */
- public static function showHeader(){
- global $CONFIG_ADMINLOGIN;
- global $WEBROOT;
- oc_require('templates/header.php');;
- }
-
- /**
- * check if we need to use the layout optimized for smaller screen, currently only checks for iPhone/Android
- * @return bool
- */
- public static function hasSmallScreen(){
- $userAgent=strtolower($_SERVER['HTTP_USER_AGENT']);
- if(strpos($userAgent,'android') or strpos($userAgent,'iphone') or strpos($userAgent,'ipod')){//todo, add support for more devices
- return true;
- }
- return false;
- }
-
- /**
- * show the footer of the web GUI
- *
- */
- public static function showFooter(){
- global $CONFIG_FOOTEROWNERNAME;
- global $CONFIG_FOOTEROWNEREMAIL;
- oc_require('templates/footer.php');;
- }
-
- /**
- * add an navigationentry to the main navigation
- *
- * @param name $name
- * @param url $url
- */
- public static function addNavigationEntry($name,$url) {
- $entry=array();
- $entry['name']=$name;
- $entry['url']=$url;
- OC_UTIL::$NAVIGATION[]=$entry;
- }
-
- /**
- * show the main navigation
- *
- */
- public static function showNavigation(){
- global $WEBROOT;
- global $SERVERROOT;
- echo('<table class="center" cellpadding="5" cellspacing="0" border="0"><tr>');
- echo('<td class="navigationitem1"><a href="'.$WEBROOT.'/">'.$_SESSION['username'].'</a></td>');
- if($_SERVER['SCRIPT_NAME']==$WEBROOT.'/index.php') echo('<td class="navigationitemselected"><a href="'.$WEBROOT.'/">Files</a></td>'); else echo('<td class="navigationitem"><a href="'.$WEBROOT.'/">Files</a></td>');
-
- foreach(OC_UTIL::$NAVIGATION as $NAVI) {
- if(dirname($_SERVER['SCRIPT_NAME'])==$WEBROOT.$NAVI['url']) echo('<td class="navigationitemselected"><a href="'.$WEBROOT.$NAVI['url'].'">'.$NAVI['name'].'</a></td>'); else echo('<td class="navigationitem"><a href="'.$WEBROOT.$NAVI['url'].'">'.$NAVI['name'].'</a></td>');
- }
-
- if($_SERVER['SCRIPT_NAME']==$WEBROOT.'/log/index.php') echo('<td class="navigationitemselected"><a href="'.$WEBROOT.'/log">Log</a></td>'); else echo('<td class="navigationitem"><a href="'.$WEBROOT.'/log">Log</a></td>');
- if($_SERVER['SCRIPT_NAME']==$WEBROOT.'/settings/index.php') echo('<td class="navigationitemselected"><a href="'.$WEBROOT.'/settings">Settings</a></td>'); else echo('<td class="navigationitem"><a href="'.$WEBROOT.'/settings">Settings</a></td>');
- echo('<td class="navigationitem"><a href="?logoutbutton=1">Logout</a></td>');
- echo('</tr></table>');
- }
-
-
- /**
- * show the loginform
- *
- */
- public static function showLoginForm(){
- global $loginresult;
- oc_require('templates/loginform.php');
- }
-
-
- /**
- * show an icon for a filetype
- *
- */
- public static function showIcon($filetype){
- global $WEBROOT;
- if($filetype=='dir'){ echo('<td><img src="'.$WEBROOT.'/img/icons/folder.png" width="16" height="16"></td>');
- }elseif($filetype=='foo'){ echo('<td>foo</td>');
- }else{ echo('<td><img src="'.$WEBROOT.'/img/icons/other.png" width="16" height="16"></td>');
- }
- }
-}
-
-
-/**
- * Class for database access
- *
- */
-class OC_DB {
- static private $DBConnection=false;
- static private $schema=false;
- static private $affected=0;
- static private $result=false;
- /**
- * connect to the datbase if not already connected
- */
- public static function connect(){
- global $CONFIG_DBNAME;
- global $CONFIG_DBHOST;
- global $CONFIG_DBUSER;
- global $CONFIG_DBPASSWORD;
- global $CONFIG_DBTYPE;
- global $DOCUMENTROOT;
- global $SERVERROOT;
- if(!self::$DBConnection){
- $options = array(
- 'portability' => MDB2_PORTABILITY_ALL,
- 'log_line_break' => '<br>',
- 'idxname_format' => '%s',
- 'debug' => true,
- 'quote_identifier' => true,
- );
- if($CONFIG_DBTYPE=='sqlite'){
- $dsn = array(
- 'phptype' => 'sqlite',
- 'database' => $SERVERROOT.'/'.$CONFIG_DBNAME,
- 'mode' => '0644',
- );
- }elseif($CONFIG_DBTYPE=='mysql'){
- $dsn = array(
- 'phptype' => 'mysql',
- 'username' => $CONFIG_DBUSER,
- 'password' => $CONFIG_DBPASSWORD,
- 'hostspec' => $CONFIG_DBHOST,
- 'database' => $CONFIG_DBNAME,
- );
- }elseif($CONFIG_DBTYPE=='pgsql'){
- $dsn = array(
- 'phptype' => 'pgsql',
- 'username' => $CONFIG_DBUSER,
- 'password' => $CONFIG_DBPASSWORD,
- 'hostspec' => $CONFIG_DBHOST,
- 'database' => $CONFIG_DBNAME,
- );
- }
- self::$DBConnection=&MDB2::factory($dsn,$options);
- if (PEAR::isError(self::$DBConnection)) {
- echo('<b>can not connect to database, using '.$CONFIG_DBTYPE.'. ('.self::$DBConnection->getUserInfo().')</center>');
- die(self::$DBConnection->getMessage());
- }
- self::$DBConnection->setFetchMode(MDB2_FETCHMODE_ASSOC);
- }
- }
-
- public static function connectScheme(){
- self::connect();
- if(!self::$schema){
- self::$schema=&MDB2_Schema::factory(self::$DBConnection);
- }
- }
-
- /**
- * executes a query on the database
- *
- * @param string $cmd
- * @return result-set
- */
- static function query($cmd){
- global $CONFIG_DBTYPE;
- if(!trim($cmd)){
- return false;
- }
- OC_DB::connect();
- if($CONFIG_DBTYPE=='sqlite'){//fix differences between sql versions
- $cmd=str_replace('`','',$cmd);
- }elseif($CONFIG_DBTYPE=='pgsql'){
- $cmd=str_replace('`','"',$cmd);
- }
- $result=self::$DBConnection->exec($cmd);
- if (PEAR::isError($result)) {
- $entry='DB Error: "'.$result->getMessage().'"<br />';
- $entry.='Offending command was: '.$cmd.'<br />';
- error_log($entry);
- die($entry);
- }else{
- self::$affected=$result;
- }
- self::$result=$result;
- return $result;
- }
-
- /**
- * executes a query on the database and returns the result in an array
- *
- * @param string $cmd
- * @return result-set
- */
- static function select($cmd){
- OC_DB::connect();
- global $CONFIG_DBTYPE;
- if($CONFIG_DBTYPE=='sqlite'){//fix differences between sql versions
- $cmd=str_replace('`','',$cmd);
- }elseif($CONFIG_DBTYPE=='pgsql'){
- $cmd=str_replace('`','"',$cmd);
- }
- $result=self::$DBConnection->queryAll($cmd);
- if (PEAR::isError($result)) {
- $entry='DB Error: "'.$result->getMessage().'"<br />';
- $entry.='Offending command was: '.$cmd.'<br />';
- die($entry);
- }
- return $result;
- }
-
- /**
- * executes multiply queries on the database
- *
- * @param string $cmd
- * @return result-set
- */
- static function multiquery($cmd) {
- $queries=explode(';',$cmd);
- foreach($queries as $query){
- OC_DB::query($query);
- }
- return true;
- }
-
-
- /**
- * closing a db connection
- *
- * @return bool
- */
- static function close() {
- self::$DBConnection->disconnect();
- self::$DBConnection=false;
- }
-
-
- /**
- * Returning primarykey if last statement was an insert.
- *
- * @return primarykey
- */
- static function insertid() {
- $id=self::$DBConnection->lastInsertID();
- return $id;
- }
-
- /**
- * Returning number of rows in a result
- *
- * @param resultset $result
- * @return int
- */
- static function numrows($result) {
- $result->numRows();
- }
- /**
- * Returning number of affected rows
- *
- * @return int
- */
- static function affected_rows() {
- return self::$affected;
- }
-
- /**
- * get a field from the resultset
- *
- * @param resultset $result
- * @param int $i
- * @param int $field
- * @return unknown
- */
- static function result($result, $i, $field) {
- $tmp=$result->fetchRow(MDB2_FETCHMODE_ASSOC,$i);
- $tmp=$tmp[$field];
- return($tmp);
- }
-
- /**
- * get data-array from resultset
- *
- * @param resultset $result
- * @return data
- */
- static function fetch_assoc($result){
- return $result->fetchRow(MDB2_FETCHMODE_ASSOC);
- }
-
- /**
- * Freeing resultset (performance)
- *
- * @param unknown_type $result
- * @return bool
- */
- static function free_result() {
- if(self::$result){
- self::$result->free();
- self::$result=false;
- }
- }
-
- static public function disconnect(){
- if(self::$DBConnection){
- self::$DBConnection->disconnect();
- self::$DBConnection=false;
- }
- }
-
- /**
- * escape strings so they can be used in queries
- *
- * @param string string
- * @return string
- */
- static function escape($string){
- OC_DB::connect();
- return self::$DBConnection->escape($string);
- }
-
- static function getDbStructure($file){
- OC_DB::connectScheme();
- $definition = self::$schema->getDefinitionFromDatabase();
- $dump_options = array(
- 'output_mode' => 'file',
- 'output' => $file,
- 'end_of_line' => "\n"
- );
- self::$schema->dumpDatabase($definition, $dump_options, MDB2_SCHEMA_DUMP_STRUCTURE);
- }
-
- static function createDbFromStructure($file){
- OC_DB::connectScheme();
- global $CONFIG_DBNAME;
- global $CONFIG_DBTABLEPREFIX;
- $content=file_get_contents($file);
- $file2=tempnam(sys_get_temp_dir(),'oc_db_scheme_');
- $content=str_replace('*dbname*',$CONFIG_DBNAME,$content);
- $content=str_replace('*dbprefix*',$CONFIG_DBTABLEPREFIX,$content);
- file_put_contents($file2,$content);
- $definition=@self::$schema->parseDatabaseDefinitionFile($file2);
- unlink($file2);
- if($definition instanceof MDB2_Schema_Error){
- die($definition->getMessage() . ': ' . $definition->getUserInfo());
- }
- $ret=@self::$schema->createDatabase($definition);
- if($ret instanceof MDB2_Error) {
- die ($ret->getMessage() . ': ' . $ret->getUserInfo());
- }else{
- return true;
- }
- }
-}
-
-
-//custom require/include functions because not all hosts allow us to set the include path
-function oc_require($file){
- global $SERVERROOT;
- global $DOCUMENTROOT;
- global $WEBROOT;
- global $CONFIG_DBNAME;
- global $CONFIG_DBHOST;
- global $CONFIG_DBUSER;
- global $CONFIG_DBPASSWORD;
- global $CONFIG_DBTYPE;
- global $CONFIG_DATADIRECTORY;
- global $CONFIG_HTTPFORCESSL;
- global $CONFIG_DATEFORMAT;
- global $CONFIG_INSTALLED;
- if(is_file($file)){
- return require($file);
- }elseif(is_file($SERVERROOT.'/'.$file)){
- return require($SERVERROOT.'/'.$file);
- }elseif(is_file($SERVERROOT.'/inc/'.$file)){
- return require($SERVERROOT.'/inc/'.$file);
- }
-}
-
-function oc_require_once($file){
- global $SERVERROOT;
- global $DOCUMENTROOT;
- global $WEBROOT;
- global $CONFIG_DBNAME;
- global $CONFIG_DBHOST;
- global $CONFIG_DBUSER;
- global $CONFIG_DBPASSWORD;
- global $CONFIG_DBTYPE;
- global $CONFIG_DATADIRECTORY;
- global $CONFIG_HTTPFORCESSL;
- global $CONFIG_DATEFORMAT;
- global $CONFIG_INSTALLED;
- if(is_file($file)){
- return require_once($file);
- }elseif(is_file($SERVERROOT.'/'.$file)){
- return require_once($SERVERROOT.'/'.$file);
- }elseif(is_file($SERVERROOT.'/inc/'.$file)){
- return require_once($SERVERROOT.'/inc/'.$file);
- }
-}
-
-function oc_include($file){
- global $SERVERROOT;
- global $DOCUMENTROOT;
- global $WEBROOT;
- global $CONFIG_DBNAME;
- global $CONFIG_DBHOST;
- global $CONFIG_DBUSER;
- global $CONFIG_DBPASSWORD;
- global $CONFIG_DBTYPE;
- global $CONFIG_DATADIRECTORY;
- global $CONFIG_HTTPFORCESSL;
- global $CONFIG_DATEFORMAT;
- global $CONFIG_INSTALLED;
- if(is_file($file)){
- return include($file);
- }elseif(is_file($SERVERROOT.'/'.$file)){
- return include($SERVERROOT.'/'.$file);
- }elseif(is_file($SERVERROOT.'/inc/'.$file)){
- return include($SERVERROOT.'/inc/'.$file);
- }
-}
-
-function oc_include_once($file){
- global $SERVERROOT;
- global $DOCUMENTROOT;
- global $WEBROOT;
- global $CONFIG_DBNAME;
- global $CONFIG_DBHOST;
- global $CONFIG_DBUSER;
- global $CONFIG_DBPASSWORD;
- global $CONFIG_DBTYPE;
- global $CONFIG_DATADIRECTORY;
- global $CONFIG_HTTPFORCESSL;
- global $CONFIG_DATEFORMAT;
- global $CONFIG_INSTALLED;
- if(is_file($SERVERROOT.'/'.$file)){
- return include_once($SERVERROOT.'/'.$file);
- }elseif(is_file($SERVERROOT.'/inc/'.$file)){
- return include_once($SERVERROOT.'/inc/'.$file);
- }elseif(is_file($file)){
- return include_once($file);
- }
-}
-
-function chmodr($path, $filemode) {
-// echo "$path<br/>";
- if (!is_dir($path))
- return chmod($path, $filemode);
- $dh = opendir($path);
- while (($file = readdir($dh)) !== false) {
- if($file != '.' && $file != '..') {
- $fullpath = $path.'/'.$file;
- if(is_link($fullpath))
- return FALSE;
- elseif(!is_dir($fullpath) && !chmod($fullpath, $filemode))
- return FALSE;
- elseif(!chmodr($fullpath, $filemode))
- return FALSE;
- }
- }
- closedir($dh);
- if(chmod($path, $filemode))
- return TRUE;
- else
- return FALSE;
-}
-
-?>
diff --git a/inc/lib_config.php b/inc/lib_config.php
deleted file mode 100644
index 6863146cde9..00000000000
--- a/inc/lib_config.php
+++ /dev/null
@@ -1,391 +0,0 @@
-<?php
-class OC_CONFIG{
- static public $forms=array();
-
- /**
- * add a form to the settings page
- * @param string name
- * @param string url
- */
- public static function addForm($name,$url){
- self::$forms[$name]=$url;
- }
-
- /**
- * settings page
- *
- */
- public static function showSettings(){
- oc_require('templates/settings.php');
- }
-
- /**
- * show the configform
- *
- */
- public static function showAdminForm(){
- global $CONFIG_ADMINLOGIN;
- global $CONFIG_ADMINPASSWORD;
- global $CONFIG_DATADIRECTORY;
- global $CONFIG_HTTPFORCESSL;
- global $CONFIG_DATEFORMAT;
- global $CONFIG_DBNAME;
- global $CONFIG_DBTABLEPREFIX;
- global $CONFIG_INSTALLED;
- $allow=false;
- if(!$CONFIG_INSTALLED){
- $allow=true;
- }elseif(OC_USER::isLoggedIn()){
- if(OC_USER::ingroup($_SESSION['username'],'admin')){
- $allow=true;
- }
- }
- if($allow){
- oc_require('templates/adminform.php');
- }
- }
-
- public static function createUserListener(){
- if(OC_USER::isLoggedIn()){
- if(OC_USER::ingroup($_SESSION['username'],'admin')){
- if(isset($_POST['new_username']) and isset($_POST['new_password'])){
- if(OC_USER::createuser($_POST['new_username'],$_POST['new_password'])){
- return 'user successfully created';
- }else{
- return 'error while trying to create user';
- }
- }else{
- return false;
- }
- }else{
- return false;
- }
- }
- }
-
- public static function createGroupListener(){
- if(OC_USER::isLoggedIn()){
- if(isset($_POST['creategroup']) and $_POST['creategroup']==1){
- if(OC_USER::creategroup($_POST['groupname'])){
- return 'group successfully created';
- }else{
- return 'error while trying to create group';
- }
- }else{
- return false;
- }
- }else{
- return false;
- }
- }
-
-
- /**
- * listen for configuration changes
- *
- */
- public static function configListener(){
- if(OC_USER::isLoggedIn()){
- if(isset($_POST['config']) and $_POST['config']==1){
- $error='';
- if(!OC_USER::checkpassword($_SESSION['username'],$_POST['currentpassword'])){
- $error.='wrong password<br />';
- }else{
- if(isset($_POST['changepass']) and $_POST['changepass']==1){
- if(!isset($_POST['password']) or empty($_POST['password'])) $error.='password not set<br />';
- if(!isset($_POST['password2']) or empty($_POST['password2'])) $error.='retype password not set<br />';
- if($_POST['password']<>$_POST['password2'] ) $error.='passwords are not the same<br />';
- if(empty($error)){
- if(!OC_USER::setpassword($_SESSION['username'],$_POST['password'])){
- $error.='error while trying to set password<br />';
- }
- }
- }
- }
- return $error;
- }else{
- return false;
- }
- }else{
- return false;
- }
- }
-
- /**
- * Write the configuration to the `config.php` file
- *
- * $configuration contains key/value pairs
- * - the key is the option name without the 'CONFIG_' prefix
- * - the value is a string, a boolean or a number
- *
- * @param array $configuration is an associative array
- */
- protected static function saveConfiguration($configuration) {
- global $SERVERROOT;
-
- $configContent = '<?php';
- foreach ( $configuration as $key => $value ) {
- if ( is_string($value) ) {
- $configContent .= "\n\$CONFIG_$key = '$value';"; // e.g. $CONFIG_DBTYPE = 'mysql';
- } else if ( is_bool($value) ) {
- $value = $value ? 'true' : 'false';
- $configContent .= "\n\$CONFIG_$key = $value;"; // e.g. $CONFIG_INSTALLED = true;
- } else if ( is_numeric($value) ) {
- $configContent .= "\n\$CONFIG_$key = $value;"; // e.g. $CONFIG_PI = 3.14;
- }
- }
- $filename = "$SERVERROOT/config/config.php";
- file_put_contents($filename, $configContent);
- }
-
- /**
- * listen for admin configuration changes and write it to the file
- *4bd0be1185e76
- */
- public static function writeAdminListener(){
- global $CONFIG_INSTALLED;
- $allow=false;
- if(!$CONFIG_INSTALLED){
- $allow=true;
- }elseif(OC_USER::isLoggedIn()){
- if(OC_USER::ingroup($_SESSION['username'],'admin')){
- $allow=true;
- }
- }
- if($allow){
- global $DOCUMENTROOT;
- global $SERVERROOT;
- global $WEBROOT;
- global $CONFIG_DBHOST;
- global $CONFIG_DBNAME;
- global $CONFIG_DBTABLEPREFIX;
- global $CONFIG_INSTALLED;
- global $CONFIG_DBUSER;
- global $CONFIG_DBPASSWORD;
- global $CONFIG_DBTYPE;
- global $CONFIG_ADMINLOGIN;
- global $CONFIG_ADMINPASSWORD;
- if(isset($_POST['set_config'])){
- //checkdata
- $error='';
- $FIRSTRUN=!$CONFIG_INSTALLED;
- if(!$FIRSTRUN){
- if(!OC_USER::login($_SESSION['username'],$_POST['currentpassword'])){
- $error.='wrong password<br />';
- }
- }
-
- if((!isset($_POST['adminlogin']) or empty($_POST['adminlogin'])) and $FIRSTRUN) $error.='admin login not set<br />';
- if((!isset($_POST['adminpassword']) or empty($_POST['adminpassword'])) and $FIRSTRUN) $error.='admin password not set<br />';
- if((!isset($_POST['adminpassword2']) or empty($_POST['adminpassword2'])) and $FIRSTRUN) $error.='retype admin password not set<br />';
- if((!isset($_POST['datadirectory']) or empty($_POST['datadirectory'])) and $FIRSTRUN) $error.='data directory not set<br />';
- if(!isset($_POST['dateformat']) or empty($_POST['dateformat'])) $error.='dateformat not set<br />';
- if((!isset($_POST['dbname']) or empty($_POST['dbname'])) and $FIRSTRUN) $error.='databasename not set<br />';
- if($FIRSTRUN and $_POST['adminpassword']<>$_POST['adminpassword2'] ) $error.='admin passwords are not the same<br />';
- $dbtype=(isset($_POST['dbtype']))?$_POST['dbtype']:$CONFIG_DBTYPE;
- if($dbtype=='mysql'){
- if(!isset($_POST['dbhost']) or empty($_POST['dbhost'])) $error.='database host not set<br />';
- if(!isset($_POST['dbuser']) or empty($_POST['dbuser'])) $error.='database user not set<br />';
- if($_POST['dbpassword']<>$_POST['dbpassword2'] ) $error.='database passwords are not the same<br />';
-
- }
- if(isset($_POST['enablebackup']) and $_POST['enablebackup']==1){
- if(!isset($_POST['backupdirectory']) or empty($_POST['backupdirectory'])) $error.='backup directory not set<br />';
- }
- if(!$FIRSTRUN){
- if(!isset($_POST['adminpassword']) or empty($_POST['adminpassword'])){
- $_POST['adminpassword']=$CONFIG_ADMINPASSWORD;
- }
- if(!isset($_POST['dbpassword']) or empty($_POST['dbpassword'])){
- $_POST['dbpassword']=$CONFIG_DBPASSWORD;
- }
- }else{
- if(!is_dir($_POST['datadirectory'])){
- try{
- mkdir($_POST['datadirectory']);
- }catch(Exception $e){
- $error.='error while trying to create data directory<br/>';
- }
- }
- }
- if(empty($error)) {
- if($CONFIG_DBTYPE!=$dbtype or $FIRSTRUN){
- //create/fill database
- $CONFIG_DBTYPE=$dbtype;
- $CONFIG_DBNAME=$_POST['dbname'];
- if($dbtype!='sqlite'){
- $CONFIG_DBTABLEPREFIX=$_POST['dbtableprefix'];
- $CONFIG_DBHOST=$_POST['dbhost'];
- $CONFIG_DBUSER=$_POST['dbuser'];
- $CONFIG_DBPASSWORD=$_POST['dbpassword'];
- }else{
- $_POST['dbtableprefix']='';
- $CONFIG_DBTABLEPREFIX='';
- }
- try{
- if(isset($_POST['createdatabase']) and $CONFIG_DBTYPE!='sqlite'){
- self::createdatabase($_POST['dbadminuser'],$_POST['dbadminpwd']);
- }
- }catch(Exception $e){
- $error.='error while trying to create the database<br/>';
- }
- if($CONFIG_DBTYPE=='sqlite'){
- $f=@fopen($SERVERROOT.'/'.$CONFIG_DBNAME,'a+');
- if(!$f){
- $error.='path of sqlite database not writable by server<br/>';
- }
- OC_DB::disconnect();
- unlink($SERVERROOT.'/'.$CONFIG_DBNAME);
- }
- try{
- if(isset($_POST['filldb'])){
- self::filldatabase();
- }
- }catch(Exception $e){
- $error.='error while trying to fill the database<br/>';
- }
- if($CONFIG_DBTYPE=='sqlite'){
- OC_DB::disconnect();
- }
- }
- if($FIRSTRUN){
- if(!OC_USER::createuser($_POST['adminlogin'],$_POST['adminpassword']) && !OC_USER::login($_POST['adminlogin'],$_POST['adminpassword'])){
- $error.='error while trying to create the admin user<br/>';
- }
- if(OC_USER::getgroupid('admin',true)==0){
- if(!OC_USER::creategroup('admin')){
- $error.='error while trying to create the admin group<br/>';
- }
- }
- if(!OC_USER::addtogroup($_POST['adminlogin'],'admin')){
- $error.='error while trying to add the admin user to the admin group<br/>';
- }
- }
- // Build the configuration array
- $config = array();
- $config['INSTALLED'] = true;
- $config['DATADIRECTORY'] = $_POST['datadirectory'];
- $config['HTTPFORCESSL'] = isset($_POST['forcessl']);
- // Backup configuration
- $config['ENABLEBACKUP'] = isset($_POST['enablebackup']);
- if ( $config['ENABLEBACKUP'] AND (1 == $_POST['enablebackup']) )
- $config['BACKUPDIRECTORY'] = $_POST['backupdirectory'];
- $config['DATEFORMAT'] = $_POST['dateformat'];
- // DB Configuration
- $config['DBTYPE'] = $dbtype;
- $config['DBNAME'] = $_POST['dbname'];
- $config['DBTABLEPREFIX'] = $_POST['dbtableprefix'];
- if ( 'sqlite' != $dbtype ) {
- $config['DBHOST'] = $_POST['dbhost'];
- $config['DBUSER'] = $_POST['dbuser'];
- $config['DBPASSWORD'] = $_POST['dbpassword'];
- }
-
- if( empty($error) ) {
- header("Location: $WEBROOT/");
- try {
- // Write the configuration array to `/config/config.php`
- self::saveConfiguration($config);
- } catch ( Exception $e ) {
- $error.='error while trying to save the configuration file<br/>';
- return $error;
- }
- } else {
- return $error;
- }
- }
- return($error);
- }
- }
- }
-
- /**
- * Fills the database with the initial tables
- * Note: while the AUTO_INCREMENT function is not supported by SQLite
- * the same effect can be achieved by accessing the SQLite pseudo-column
- * "rowid"
- */
- private static function fillDatabase(){
- global $SERVERROOT;
- OC_DB::createDBFromStructure($SERVERROOT.'/db_structure.xml');
- }
-
- /**
- * Create the database and user
- * @param string adminUser
- * @param string adminPwd
- *
- */
- private static function createDatabase($adminUser,$adminPwd){
- global $CONFIG_DBHOST;
- global $CONFIG_DBNAME;
- global $CONFIG_DBUSER;
- global $CONFIG_DBPWD;
- global $CONFIG_DBTYPE;
- //we cant user OC_BD functions here because we need to connect as the administrative user.
- if($CONFIG_DBTYPE=='mysql'){
- $connection=mysql_connect($CONFIG_DBHOST, $adminUser, $adminPwd);
- if(!$connection) {
- @ob_end_clean();
- echo('<html><head></head><body bgcolor="#F0F0F0"><br /><br /><center><b>can not connect to database as administrative user.</center></body></html>');
- exit();
- }
- $query="SELECT user FROM mysql.user WHERE user='{$_POST['dbuser']}'";
- $result = mysql_query($query,$connection);
- if (!$result) {
- $entry='DB Error: "'.mysql_error($connection).'"<br />';
- $entry.='Offending command was: '.$query.'<br />';
- echo($entry);
- }
- if(mysql_num_rows($result)==0){
- $pwd=$_POST['dbpassword'];
- //we need to create 2 accounts, one for global use and one for local user. if we don't speccify the local one,
- // the anonymous user would take precedence when there is one.
- $query="CREATE USER '{$_POST['dbuser']}'@'localhost' IDENTIFIED BY '$pwd'";
- $result = mysql_query($query,$connection);
- if (!$result) {
- $entry='DB Error: "'.mysql_error($connection).'"<br />';
- $entry.='Offending command was: '.$query.'<br />';
- echo($entry);
- }
- $query="CREATE USER '{$_POST['dbuser']}'@'%' IDENTIFIED BY '$pwd'";
- $result = mysql_query($query,$connection);
- if (!$result) {
- $entry='DB Error: "'.mysql_error($connection).'"<br />';
- $entry.='Offending command was: '.$query.'<br />';
- echo($entry);
- }
- }
- $query="CREATE DATABASE IF NOT EXISTS `{$_POST['dbname']}`";
- $result = mysql_query($query,$connection);
- if (!$result) {
- $entry='DB Error: "'.mysql_error($connection).'"<br />';
- $entry.='Offending command was: '.$query.'<br />';
- echo($entry);
- }
- $query="GRANT ALL PRIVILEGES ON `{$_POST['dbname']}` . * TO '{$_POST['dbuser']}'";
- $result = mysql_query($query,$connection);
- if (!$result) {
- $entry='DB Error: "'.mysql_error($connection).'"<br />';
- $entry.='Offending command was: '.$query.'<br />';
- echo($entry);
- }
- mysql_close($connection);
- }elseif($CONFIG_DBTYPE=='pgsql'){
- $connection = pg_connect("user='$adminUser' host='$CONFIG_DBHOST' password='$adminPwd'");
- $query="CREATE USER {$_POST['dbuser']} WITH PASSWORD '{$_POST['dbpassword']}' CREATEDB;";
- $result = pg_exec($connection, $query);
- $query="select count(*) from pg_catalog.pg_database where datname = '{$_POST['dbname']}';";
- $result = pg_exec($connection, $query);
- if(pg_result($result,0,0)==0){
- $query="CREATE DATABASE {$_POST['dbname']};";
- $result = pg_exec($connection, $query);
- $query="ALTER DATABASE {$_POST['dbname']} OWNER TO {$_POST['dbuser']};";
- $result = pg_exec($connection, $query);
- }
- }
- }
-}
-?>
-
-
diff --git a/inc/lib_connect.php b/inc/lib_connect.php
deleted file mode 100644
index 9db867715e4..00000000000
--- a/inc/lib_connect.php
+++ /dev/null
@@ -1,300 +0,0 @@
-<?php
-
-/**
-* ownCloud
-*
-* @author Frank Karlitschek
-* @copyright 2010 Frank Karlitschek karlitschek@kde.org
-*
-* This library is free software; you can redistribute it and/or
-* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
-* License as published by the Free Software Foundation; either
-* version 3 of the License, or 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 AFFERO 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, see <http://www.gnu.org/licenses/>.
-*
-*/
-
-/**
- * Class for connecting multiply ownCloud installations
- *
- */
-class OC_CONNECT{
- static private $clouds=array();
-
- static function connect($path,$user,$password){
- $cloud=new OC_REMOTE_CLOUD($path,$user,$password);
- if($cloud->connected){
- self::$clouds[$path]=$cloud;
- return $cloud;
- }else{
- return false;
- }
- }
-}
-
-
-/**
- * Class for connection to a remote owncloud installation
- *
- */
-class OC_REMOTE_CLOUD{
- private $path;
- private $connected=false;
- private $cookiefile=false;
-
- /**
- * make an api call to the remote cloud
- * @param string $action
- * @param array parameters
- * @param bool assoc when set to true, the result will be parsed as associative array
- *
- */
- private function apiCall($action,$parameters=false,$assoc=false){
- if(!$this->cookiefile){
- $this->cookiefile=sys_get_temp_dir().'/remoteCloudCookie'.uniqid();
- }
- $url=$this->path.='/files/api.php';
- $fields_string="action=$action&";
- if(is_array($parameters)){
- foreach($parameters as $key=>$value){
- $fields_string.=$key.'='.$value.'&';
- }
- rtrim($fields_string,'&');
- }
- $ch=curl_init();
- curl_setopt($ch,CURLOPT_URL,$url);
- curl_setopt($ch,CURLOPT_POST,count($parameters));
- curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
- curl_setopt($ch, CURLOPT_COOKIEFILE,$this->cookiefile);
- curl_setopt($ch, CURLOPT_COOKIEJAR,$this->cookiefile);
- curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
- $result=curl_exec($ch);
- $result=trim($result);
- $info=curl_getinfo($ch);
- $httpCode=$info['http_code'];
- curl_close($ch);
- if($httpCode==200 or $httpCode==0){
- return json_decode($result,$assoc);
- }else{
- return false;
- }
- }
-
- public function __construct($path,$user,$password){
- $this->path=$path;
- $this->connected=$this->apiCall('login',array('username'=>$user,'password'=>$password));
- }
-
- /**
- * check if we are stull logged in on the remote cloud
- *
- */
- public function isLoggedIn(){
- if(!$this->connected){
- return false;
- }
- return $this->apiCall('checklogin');
- }
-
- public function __get($name){
- switch($name){
- case 'connected':
- return $this->connected;
- }
- }
-
- /**
- * disconnect from the remote cloud
- *
- */
- public function disconnect(){
- $this->connected=false;
- if(is_file($this->cookiefile)){
- unlink($this->cookiefile);
- }
- $this->cookiefile=false;
- }
-
- /**
- * create a new file or directory
- * @param string $dir
- * @param string $name
- * @param string $type
- */
- public function newFile($dir,$name,$type){
- if(!$this->connected){
- return false;
- }
- return $this->apiCall('new',array('dir'=>$dir,'name'=>$name,'type'=>$type),true);
- }
-
- /**
- * deletes a file or directory
- * @param string $dir
- * @param string $file
- */
- public function delete($dir,$name){
- if(!$this->connected){
- return false;
- }
- return $this->apiCall('delete',array('dir'=>$dir,'file'=>$name),true);
- }
-
- /**
- * moves a file or directory
- * @param string $sorceDir
- * @param string $sorceFile
- * @param string $targetDir
- * @param string $targetFile
- */
- public function move($sourceDir,$sourceFile,$targetDir,$targetFile){
- if(!$this->connected){
- return false;
- }
- return $this->apiCall('move',array('sourcedir'=>$sourceDir,'source'=>$sourceFile,'targetdir'=>$targetDir,'target'=>$targetFile),true);
- }
-
- /**
- * copies a file or directory
- * @param string $sorceDir
- * @param string $sorceFile
- * @param string $targetDir
- * @param string $targetFile
- */
- public function copy($sourceDir,$sourceFile,$targetDir,$targetFile){
- if(!$this->connected){
- return false;
- }
- return $this->apiCall('copy',array('sourcedir'=>$sourceDir,'source'=>$sourceFile,'targetdir'=>$targetDir,'target'=>$targetFile),true);
- }
-
- /**
- * get a file tree
- * @param string $dir
- */
- public function getTree($dir){
- if(!$this->connected){
- return false;
- }
- return $this->apiCall('gettree',array('dir'=>$dir),true);
- }
-
- /**
- * get the files inside a directory of the remote cloud
- * @param string $dir
- */
- public function getFiles($dir){
- if(!$this->connected){
- return false;
- }
- return $this->apiCall('getfiles',array('dir'=>$dir),true);
- }
-
- /**
- * get a remove file and save it in a temporary file and return the path of the temporary file
- * @param string $dir
- * @param string $file
- * @return string
- */
- public function getFile($dir, $file){
- if(!$this->connected){
- return false;
- }
- $ch=curl_init();
- if(!$this->cookiefile){
- $this->cookiefile=sys_get_temp_dir().'/remoteCloudCookie'.uniqid();
- }
- $tmpfile=tempnam(sys_get_temp_dir(),'remoteCloudFile');
- $fp=fopen($tmpfile,'w+');
- $url=$this->path.="/files/api.php?action=get&dir=$dir&file=$file";
- curl_setopt($ch,CURLOPT_URL,$url);
- curl_setopt($ch, CURLOPT_COOKIEFILE,$this->cookiefile);
- curl_setopt($ch, CURLOPT_COOKIEJAR,$this->cookiefile);
- curl_setopt($ch, CURLOPT_FILE, $fp);
- curl_exec($ch);
- fclose($fp);
- curl_close($ch);
- return $tmpfile;
- }
-
- public function sendFile($sourceDir,$sourceFile,$targetDir,$targetFile){
- global $WEBROOT;
- $source=$sourceDir.'/'.$sourceFile;
- $tmp=OC_FILESYSTEM::toTmpFile($source);
- return $this->sendTmpFile($tmp,$targetDir,$targetFile);
- }
-
- public function sendTmpFile($tmp,$targetDir,$targetFile){
- $token=sha1(uniqid().$tmp);
- global $WEBROOT;
- $file=sys_get_temp_dir().'/'.'remoteCloudFile'.$token;
- rename($tmp,$file);
- if((isset($CONFIG_HTTPFORCESSL) and $CONFIG_HTTPFORCESSL) or isset($_SERVER['HTTPS']) and $_SERVER['HTTPS'] == 'on') {
- $url = "https://". $_SERVER['SERVER_NAME'] . $WEBROOT;
- }else{
- $url = "http://". $_SERVER['SERVER_NAME'] . $WEBROOT;
- }
- return $this->apiCall('pull',array('dir'=>$targetDir,'file'=>$targetFile,'token'=>$token,'source'=>$url),true);
- }
-}
-
-function OC_CONNECT_TEST($path,$user,$password){
- echo 'connecting...';
- $remote=OC_CONNECT::connect($path,$user,$password);
- if($remote->connected){
- echo 'done<br/>';
- if($remote->isLoggedIn()){
- echo 'logged in, session working<br/>';
- echo 'trying to get remote files...';
- $files=$remote->getFiles('');
- if($files){
- echo count($files).' files found:<br/>';
- foreach($files as $file){
- echo "{$file['type']} {$file['name']}: {$file['size']} bytes<br/>";
- }
- echo 'getting file "'.$file['name'].'"...';
- $size=$file['size'];
- $file=$remote->getFile('',$file['name']);
- if(file_exists($file)){
- $newSize=filesize($file);
- if($size!=$newSize){
- echo "fail<br/>Error: $newSize bytes received, $size expected.";
- echo '<br/><br/>Recieved file:<br/>';
- readfile($file);
- unlink($file);
- return;
- }
- OC_FILESYSTEM::fromTmpFile($file,'/remoteFile');
- echo 'done<br/>';
- echo 'sending file "burning_avatar.png"...';
- $res=$remote->sendFile('','burning_avatar.png','','burning_avatar.png');
- if($res){
- echo 'done<br/>';
- }else{
- echo 'fail<br/>';
- }
- }else{
- echo 'fail<br/>';
- }
- }else{
- echo 'fail<br/>';
- }
- }else{
- echo 'no longer logged in, session fail<br/>';
- }
- }else{
- echo 'fail<br/>';
- }
- $remote->disconnect();
- die();
-}
-
-
-?>
diff --git a/inc/lib_fileobserver.php b/inc/lib_fileobserver.php
deleted file mode 100644
index c9c73faa6d2..00000000000
--- a/inc/lib_fileobserver.php
+++ /dev/null
@@ -1,82 +0,0 @@
-<?php
-
-/**
-* ownCloud
-*
-* @author Frank Karlitschek
-* @copyright 2010 Frank Karlitschek karlitschek@kde.org
-*
-* This library is free software; you can redistribute it and/or
-* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
-* License as published by the Free Software Foundation; either
-* version 3 of the License, or 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 AFFERO 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, see <http://www.gnu.org/licenses/>.
-*/
-
-define('OC_FILEACTION_WRITE',2);
-define('OC_FILEACTION_READ',4);
-define('OC_FILEACTION_DELETE',8);
-define('OC_FILEACTION_CREATE',16);
-define('OC_FILEACTION_RENAME',32);
-
-/**
- * base class for file observers
- */
-class OC_FILEOBSERVER{
- private $mask;
-
- public function __construct($arguments){}
-
- public function __get($name){
- switch($name){
- case 'mask':
- return $this->mask;
- }
- }
-
- public function notify($path,$action){}
-}
-
-/**
- * observer that makes automatic backups
- */
-class OC_FILEOBSERVER_BACKUP extends OC_FILEOBSERVER{
- private $storage;
-
- public function __construct($arguments){
- $this->mask=OC_FILEACTION_WRITE+OC_FILEACTION_DELETE+OC_FILEACTION_CREATE+OC_FILEACTION_RENAME;
- $this->storage=$arguments['storage'];
- }
-
- public function notify($path,$action,$storage){
- switch($action){
- case OC_FILEACTION_DELETE:
- if($storage->is_dir($path)){
- $this->storage->delTree($path);
- }else{
- $this->storage->unlink($path);
- }
- break;
- case OC_FILEACTION_CREATE:
- if($storage->is_dir($path)){
- $this->storage->mkdir($path);
- break;
- }
- case OC_FILEACTION_WRITE:
- $tmpFile=$storage->toTmpFile($path);
- $this->storage->fromTmpFile($tmpFile,$path);
- break;
- case OC_FILEACTION_RENAME:
- list($source,$target)=explode('->',$path);
- $this->storage->rename($source,$target);
- }
- }
-}
-?> \ No newline at end of file
diff --git a/inc/lib_files.php b/inc/lib_files.php
deleted file mode 100755
index f7d646e322a..00000000000
--- a/inc/lib_files.php
+++ /dev/null
@@ -1,399 +0,0 @@
-<?php
-
-/**
-* ownCloud
-*
-* @author Frank Karlitschek
-* @copyright 2010 Frank Karlitschek karlitschek@kde.org
-*
-* This library is free software; you can redistribute it and/or
-* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
-* License as published by the Free Software Foundation; either
-* version 3 of the License, or 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 AFFERO 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, see <http://www.gnu.org/licenses/>.
-*
-*/
-
-oc_require_once("lib_log.php");
-
-
-/**
- * Class for fileserver access
- *
- */
-class OC_FILES {
- static $tmpFiles=array();
- /**
- * show a web GUI filebrowser
- *
- * @param basedir $basedir
- * @param dir $dir
- */
- public static function showBrowser($basedir,$dir){
- echo '<div id="content"></div>';
- }
-
- /**
- * get the content of a directory
- * @param dir $directory
- */
- public static function getDirectoryContent($directory){
- global $CONFIG_DATADIRECTORY;
- if(strpos($directory,$CONFIG_DATADIRECTORY)===0){
- $directory=substr($directory,strlen($CONFIG_DATADIRECTORY));
- }
- $filesfound=true;
- $content=array();
- $dirs=array();
- $file=array();
- $files=array();
- if(OC_FILESYSTEM::is_dir($directory)) {
- if ($dh = OC_FILESYSTEM::opendir($directory)) {
- while (($filename = readdir($dh)) !== false) {
- if($filename<>'.' and $filename<>'..' and substr($filename,0,1)!='.'){
- $file=array();
- $filesfound=true;
- $file['name']=$filename;
- $file['directory']=$directory;
- $stat=OC_FILESYSTEM::stat($directory.'/'.$filename);
- $file=array_merge($file,$stat);
- $file['mime']=OC_FILES::getMimeType($directory .'/'. $filename);
- $file['readable']=OC_FILESYSTEM::is_readable($directory .'/'. $filename);
- $file['writeable']=OC_FILESYSTEM::is_writeable($directory .'/'. $filename);
- $file['type']=OC_FILESYSTEM::filetype($directory .'/'. $filename);
- if($file['type']=='dir'){
- $dirs[$file['name']]=$file;
- }else{
- $files[$file['name']]=$file;
- }
- }
- }
- closedir($dh);
- }
- }
- ksort($dirs);
- ksort($files);
- $content=array_merge($dirs,$files);
- if($filesfound){
- return $content;
- }else{
- return false;
- }
- }
-
-
-
- /**
- * return the content of a file or return a zip file containning multiply files
- *
- * @param dir $dir
- * @param file $file
- */
- public static function get($dir,$files){
- if(strpos($files,';')){
- $files=explode(';',$files);
- }
- if(is_array($files)){
- $zip = new ZipArchive();
- $filename = sys_get_temp_dir()."/ownCloud.zip";
- if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {
- exit("cannot open <$filename>\n");
- }
- foreach($files as $file){
- $file=$dir.'/'.$file;
- if(OC_FILESYSTEM::is_file($file)){
- $tmpFile=OC_FILESYSTEM::toTmpFile($file);
- self::$tmpFiles[]=$tmpFile;
- $zip->addFile($tmpFile,basename($file));
- }elseif(OC_FILESYSTEM::is_dir($file)){
- zipAddDir($file,$zip);
- }
- }
- $zip->close();
- }elseif(OC_FILESYSTEM::is_dir($dir.'/'.$files)){
- $zip = new ZipArchive();
- $filename = sys_get_temp_dir()."/ownCloud.zip";
- if ($zip->open($filename, ZIPARCHIVE::CREATE)!==TRUE) {
- exit("cannot open <$filename>\n");
- }
- $file=$dir.'/'.$files;
- zipAddDir($file,$zip);
- $zip->close();
- }else{
- $zip=false;
- $filename=$dir.'/'.$files;
- }
- if($zip or OC_FILESYSTEM::is_readable($filename)){
- header('Content-Disposition: attachment; filename="'.basename($filename).'"');
- header('Content-Transfer-Encoding: binary');
- header('Expires: 0');
- header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
- header('Pragma: public');
- if($zip){
- header('Content-Type: application/zip');
- header('Content-Length: ' . filesize($filename));
- }else{
- header('Content-Type: ' . OC_FILESYSTEM::getMimeType($filename));
- header('Content-Length: ' . OC_FILESYSTEM::filesize($filename));
- }
- }elseif($zip or !OC_FILESYSTEM::file_exists($filename)){
- header("HTTP/1.0 404 Not Found");
- die('404 Not Found');
- }else{
- header("HTTP/1.0 403 Forbidden");
- die('403 Forbidden');
- }
- ob_end_clean();
- OC_LOG::event($_SESSION['username'],3,"$dir/$files");
- if($zip){
- readfile($filename);
- unlink($filename);
- }else{
- OC_FILESYSTEM::readfile($filename);
- }
- foreach(self::$tmpFiles as $tmpFile){
- if(file_exists($tmpFile) and is_file($tmpFile)){
- unlink($tmpFile);
- }
- }
- }
-
- /**
- * move a file or folder
- *
- * @param dir $sourceDir
- * @param file $source
- * @param dir $targetDir
- * @param file $target
- */
- public static function move($sourceDir,$source,$targetDir,$target){
- if(OC_USER::isLoggedIn()){
- $targetFile=$targetDir.'/'.$target;
- $sourceFile=$sourceDir.'/'.$source;
- return OC_FILESYSTEM::rename($sourceFile,$targetFile);
- }
- }
-
- /**
- * copy a file or folder
- *
- * @param dir $sourceDir
- * @param file $source
- * @param dir $targetDir
- * @param file $target
- */
- public static function copy($sourceDir,$source,$targetDir,$target){
- if(OC_USER::isLoggedIn()){
- $targetFile=$targetDir.'/'.$target;
- $sourceFile=$sourceDir.'/'.$source;
- return OC_FILESYSTEM::copy($sourceFile,$targetFile);
- }
- }
-
- /**
- * create a new file or folder
- *
- * @param dir $dir
- * @param file $name
- * @param type $type
- */
- public static function newFile($dir,$name,$type){
- if(OC_USER::isLoggedIn()){
- $file=$dir.'/'.$name;
- if($type=='dir'){
- return OC_FILESYSTEM::mkdir($file);
- }elseif($type=='file'){
- $fileHandle=OC_FILESYSTEM::fopen($file, 'w');
- if($fileHandle){
- fclose($fileHandle);
- OC_LOG::event($_SESSION['username'],4,"$dir/$name");
- return true;
- }else{
- return false;
- }
- }
- }
- }
-
- /**
- * deletes a file or folder
- *
- * @param dir $dir
- * @param file $name
- */
- public static function delete($dir,$file){
- if(OC_USER::isLoggedIn()){
- $file=$dir.'/'.$file;
- if(OC_FILESYSTEM::is_file($file)){
- return OC_FILESYSTEM::unlink($file);
- }elseif(OC_FILESYSTEM::is_dir($file)){
- return OC_FILESYSTEM::delTree($file);
- }
- }
- }
-
- /**
- * try to detect the mime type of a file
- *
- * @param string path
- * @return string guessed mime type
- */
- static function getMimeType($path){
- return OC_FILESYSTEM::getMimeType($path);
- }
-
- /**
- * get a file tree
- *
- * @param string path
- * @return array
- */
- static function getTree($path){
- return OC_FILESYSTEM::getTree($path);
- }
-
- /**
- * pull a file from a remote server
- * @param string source
- * @param string token
- * @param string dir
- * @param string file
- * @return string guessed mime type
- */
- static function pull($source,$token,$dir,$file){
- $tmpfile=tempnam(sys_get_temp_dir(),'remoteCloudFile');
- $fp=fopen($tmpfile,'w+');
- $url=$source.="/files/pull.php?token=$token";
- $ch=curl_init();
- curl_setopt($ch,CURLOPT_URL,$url);
- curl_setopt($ch, CURLOPT_FILE, $fp);
- curl_exec($ch);
- fclose($fp);
- $info=curl_getinfo($ch);
- $httpCode=$info['http_code'];
- curl_close($ch);
- if($httpCode==200 or $httpCode==0){
- OC_FILESYSTEM::fromTmpFile($tmpfile,$dir.'/'.$file);
- return true;
- }else{
- return false;
- }
- }
-}
-
-function zipAddDir($dir,$zip,$internalDir=''){
- $dirname=basename($dir);
- $zip->addEmptyDir($internalDir.$dirname);
- $internalDir.=$dirname.='/';
- $files=OC_FILES::getdirectorycontent($dir);
- foreach($files as $file){
- $filename=$file['name'];
- $file=$dir.'/'.$filename;
- if(OC_FILESYSTEM::is_file($file)){
- $tmpFile=OC_FILESYSTEM::toTmpFile($file);
- OC_FILES::$tmpFiles[]=$tmpFile;
- $zip->addFile($tmpFile,$internalDir.$filename);
- }elseif(OC_FILESYSTEM::is_dir($file)){
- zipAddDir($file,$zip,$internalDir);
- }
- }
-}
-
-//remove a dir and it's content
-function delTree($dir) {
- if (!file_exists($dir)) return true;
- if (!is_dir($dir) || is_link($dir)) return unlink($dir);
- foreach (scandir($dir) as $item) {
- if ($item == '.' || $item == '..') continue;
- if(is_file($dir.'/'.$item)){
- unlink($dir.'/'.$item);
- }elseif(is_dir($dir.'/'.$item)){
- if (!delTree($dir. "/" . $item)){
- return false;
- };
- }
- }
- $return=rmdir($dir);
- return $return;
-}
-
-if(!function_exists('sys_get_temp_dir')) {
- function sys_get_temp_dir() {
- if( $temp=getenv('TMP') ) return $temp;
- if( $temp=getenv('TEMP') ) return $temp;
- if( $temp=getenv('TMPDIR') ) return $temp;
- $temp=tempnam(__FILE__,'');
- if (file_exists($temp)) {
- unlink($temp);
- return dirname($temp);
- }
- return null;
- }
-}
-
-function recursive_copy($src,$dst) {
- $dir = opendir($src);
- @mkdir($dst);
- while(false !== ( $file = readdir($dir)) ) {
- if (( $file != '.' ) && ( $file != '..' )) {
- if ( is_dir($src . '/' . $file) ) {
- recursive_copy($src . '/' . $file,$dst . '/' . $file);
- }
- else {
- copy($src . '/' . $file,$dst . '/' . $file);
- }
- }
- }
- closedir($dir);
-}
-
-global $FAKEDIRS;
-$FAKEDIRS=array();
-
-class fakeDirStream{
- private $name;
- private $data;
- private $index;
-
- public function dir_opendir($path,$options){
- global $FAKEDIRS;
- $url=parse_url($path);
- $this->name=substr($path,strlen('fakedir://'));
- $this->index=0;
- if(isset($FAKEDIRS[$this->name])){
- $this->data=$FAKEDIRS[$this->name];
- }else{
- $this->data=array();
- }
- return true;
- }
-
- public function dir_readdir(){
- if($this->index>=count($this->data)){
- return false;
- }
- $filename=$this->data[$this->index];
- $this->index++;
- return $filename;
- }
-
- public function dir_closedir() {
- $this->data=false;
- $this->name='';
- return true;
- }
-
- public function dir_rewinddir() {
- $this->index=0;
- return true;
- }
-}
-stream_wrapper_register("fakedir", "fakeDirStream");
-?> \ No newline at end of file
diff --git a/inc/lib_filestorage.php b/inc/lib_filestorage.php
deleted file mode 100644
index 5e37a1996fc..00000000000
--- a/inc/lib_filestorage.php
+++ /dev/null
@@ -1,430 +0,0 @@
-<?php
-
-/**
-* ownCloud
-*
-* @author Frank Karlitschek
-* @copyright 2010 Frank Karlitschek karlitschek@kde.org
-*
-* This library is free software; you can redistribute it and/or
-* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
-* License as published by the Free Software Foundation; either
-* version 3 of the License, or 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 AFFERO 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, see <http://www.gnu.org/licenses/>.
-*/
-
-/**
- * Privde a common interface to all different storage options
- */
-class OC_FILESTORAGE{
- private $observers=array();
- /**
- * add an observer to the list
- * @param OC_FILEOBERSER observer
- */
- public function addObserver($observer){
- $this->observers[]=$observer;
- }
- /**
- * notify the observers about an action
- * @param int action a combination of OC_FILEACTION_WRITE and OC_FILEACTION_READ
- * @param string path relative path of the file
- */
- public function notifyObservers($path,$action){
- foreach($this->observers as $observer){
- if($observer->mask & $action){
- $observer->notify($path,$action,$this);
- }
- }
- }
-
- public function __construct($parameters){}
- public function mkdir($path){}
- public function rmdir($path){}
- public function opendir($path){}
- public function is_dir($path){}
- public function is_file($path){}
- public function stat($path){}
- public function filetype($path){}
- public function filesize($path){}
- public function is_readable($path){}
- public function is_writeable($path){}
- public function file_exists($path){}
- public function readfile($path){}
- public function filectime($path){}
- public function filemtime($path){}
- public function fileatime($path){}
- public function file_get_contents($path){}
- public function file_put_contents($path,$data){}
- public function unlink($path){}
- public function rename($path1,$path2){}
- public function copy($path1,$path2){}
- public function fopen($path,$mode){}
- public function toTmpFile($path){}//copy the file to a temporary file, used for cross-storage file actions
- public function fromTmpFile($tmpPath,$path){}//copy a file from a temporary file, used for cross-storage file actions
- public function getMimeType($path){}
- public function delTree($path){}
- public function find($path){}
- public function getTree($path){}
-}
-
-
-OC_FILESYSTEM::registerStorageType('local','OC_FILESTORAGE_LOCAL',array('datadir'=>'string'));
-/**
- * for local filestore, we only have to map the paths
- */
-class OC_FILESTORAGE_LOCAL extends OC_FILESTORAGE{
- private $datadir;
- public function __construct($arguments){
- $this->datadir=$arguments['datadir'];
- if(substr($this->datadir,-1)!=='/'){
- $this->datadir.='/';
- }
- }
- public function mkdir($path){
- if($return=mkdir($this->datadir.$path)){
- $this->notifyObservers($path,OC_FILEACTION_CREATE);
- }
- return $return;
- }
- public function rmdir($path){
- if($return=rmdir($this->datadir.$path)){
- $this->notifyObservers($path,OC_FILEACTION_DELETE);
- }
- return $return;
- }
- public function opendir($path){
- if($return=opendir($this->datadir.$path)){
- $this->notifyObservers($path,OC_FILEACTION_READ);
- }
- return $return;
- }
- public function is_dir($path){
- return (is_dir($this->datadir.$path) or substr($path,-1)=='/');
- }
- public function is_file($path){
- return is_file($this->datadir.$path);
- }
- public function stat($path){
- return stat($this->datadir.$path);
- }
- public function filetype($path){
- $filetype=filetype($this->datadir.$path);
- if($filetype=='link'){
- $filetype=filetype(readlink($this->datadir.$path));
- }
- return $filetype;
- }
- public function filesize($path){
- return filesize($this->datadir.$path);
- }
- public function is_readable($path){
- return is_readable($this->datadir.$path);
- }
- public function is_writeable($path){
- return is_writeable($this->datadir.$path);
- }
- public function file_exists($path){
- return file_exists($this->datadir.$path);
- }
- public function readfile($path){
- if($return=readfile($this->datadir.$path)){
- $this->notifyObservers($path,OC_FILEACTION_READ);
- }
- return $return;
- }
- public function filectime($path){
- return filectime($this->datadir.$path);
- }
- public function filemtime($path){
- return filemtime($this->datadir.$path);
- }
- public function fileatime($path){
- return fileatime($this->datadir.$path);
- }
- public function file_get_contents($path){
- if($return=file_get_contents($this->datadir.$path)){
- $this->notifyObservers($path,OC_FILEACTION_READ);
- }
- return $return;
- }
- public function file_put_contents($path,$data){
- if($return=file_put_contents($this->datadir.$path,$data)){
- $this->notifyObservers($path,OC_FILEACTION_WRITE);
- }
- }
- public function unlink($path){
- if($return=unlink($this->datadir.$path)){
- $this->notifyObservers($path,OC_FILEACTION_DELETE);
- }
- return $return;
- }
- public function rename($path1,$path2){
- if($return=rename($this->datadir.$path1,$this->datadir.$path2)){
- $this->notifyObservers($path1.'->'.$path2,OC_FILEACTION_RENAME);
- }
- return $return;
- }
- public function copy($path1,$path2){
- if($this->is_dir($path2)){
- if(!$this->file_exists($path2)){
- $this->mkdir($path2);
- }
- $source=substr($path1,strrpos($path1,'/')+1);
- $path2.=$source;
- }
- if($return=copy($this->datadir.$path1,$this->datadir.$path2)){
- $this->notifyObservers($path2,OC_FILEACTION_CREATE);
- }
- return $return;
- }
- public function fopen($path,$mode){
- if($return=fopen($this->datadir.$path,$mode)){
- switch($mode){
- case 'r':
- $this->notifyObservers($path,OC_FILEACTION_READ);
- break;
- case 'r+':
- case 'w+':
- case 'x+':
- case 'a+':
- $this->notifyObservers($path,OC_FILEACTION_READ | OC_FILEACTION_WRITE);
- break;
- case 'w':
- case 'x':
- case 'a':
- $this->notifyObservers($path,OC_FILEACTION_WRITE);
- break;
- }
- }
- return $return;
- }
-
- public function getMimeType($fspath){
- if (@is_dir($this->datadir.$fspath)) {
- // directories are easy
- return "httpd/unix-directory";
- }elseif (function_exists('finfo_open') and function_exists('finfo_file') and $finfo=finfo_open(FILEINFO_MIME)){
- $mimeType =strtolower(finfo_file($finfo,$this->datadir.$fspath));
- $mimeType=substr($mimeType,0,strpos($mimeType,';'));
- finfo_close($finfo);
- return $mimeType;
- } else if (function_exists("mime_content_type")) {
- // use mime magic extension if available
- $mime_type = mime_content_type($this->datadir.$fspath);
- } else if (self::canExecute("file")) {
- // it looks like we have a 'file' command,
- // lets see it it does have mime support
- $fp = popen("file -i -b '{$this->datadir}$fspath' 2>/dev/null", "r");
- $reply = fgets($fp);
- pclose($fp);
-
- //trim the character set from the end of the response
- $mime_type=substr($reply,0,strrpos($reply,' '));
- }
- if (empty($mime_type)) {
- // Fallback solution: try to guess the type by the file extension
- // TODO: add more ...
- switch (strtolower(strrchr(basename($fspath), "."))) {
- case '.css':
- $mime_type = 'text/css';
- break;
- case '.flac':
- $mime_type = 'audio/flac';
- break;
- case '.gif':
- $mime_type = 'image/gif';
- break;
- case '.gzip':
- case '.gz':
- $mime_type = 'application/x-gzip';
- break;
- case '.htm':
- case '.html':
- $mime_type = 'text/html';
- break;
- case '.jpeg':
- case '.jpg':
- $mime_type = 'image/jpeg';
- break;
- case '.js':
- $mime_type = 'application/x-javascript';
- break;
- case '.oga':
- case '.ogg':
- $mime_type = 'audio/ogg';
- break;
- case '.ogv':
- $mime_type = 'video/ogg';
- break;
- case '.pdf':
- $mime_type = 'application/pdf';
- break;
- case '.png':
- $mime_type = 'image/png';
- break;
- case '.svg':
- $mime_type = 'image/svg+xml';
- break;
- case '.tar':
- $mime_type = 'application/x-tar';
- break;
- case '.tgz':
- $mime_type = 'application/x-compressed';
- break;
- case '.tif':
- case '.tiff':
- $mime_type = 'image/tiff';
- break;
- case '.txt':
- $mime_type = 'text/plain';
- break;
- case '.zip':
- $mime_type = 'application/zip';
- break;
- default:
- $mime_type = 'application/octet-stream';
- break;
- }
- }
-
- return $mime_type;
- }
-
- /**
- * 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
- */
- private function canExecute($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";
- }
-
- // Default check will be done with $path directories :
- $dirs = explode(PATH_SEPARATOR, $path);
-
- // WARNING : We have to check if open_basedir is enabled :
- $obd = ini_get('open_basedir');
-
- if($obd != "none")
- $obd_values = explode(PATH_SEPARATOR, $obd);
-
- if(count($obd_values) > 0)
- {
- // open_basedir is in effect !
- // We need to check if the program is in one of these dirs :
- $dirs = $obd_values;
- }
-
- foreach($dirs as $dir)
- {
- foreach($exts as $ext)
- {
- if($check_fn("$dir/$name".$ext))
- return true;
- }
- }
-
- return false;
- }
-
- public function toTmpFile($path){
- $tmpFolder=sys_get_temp_dir();
- $filename=tempnam($tmpFolder,'OC_TEMP_FILE_'.substr($path,strrpos($path,'.')));
- if(copy($this->datadir.$path,$filename)){
- $this->notifyObservers($path,OC_FILEACTION_READ);
- return $filename;
- }else{
- return false;
- }
- }
-
- public function fromTmpFile($tmpFile,$path){
- if(rename($tmpFile,$this->datadir.$path)){
- $this->notifyObservers($path,OC_FILEACTION_CREATE);
- return true;
- }else{
- return false;
- }
- }
-
- public function delTree($dir) {
- $dirRelative=$dir;
- $dir=$this->datadir.$dir;
- if (!file_exists($dir)) return true;
- if (!is_dir($dir) || is_link($dir)) return unlink($dir);
- foreach (scandir($dir) as $item) {
- if ($item == '.' || $item == '..') continue;
- if(is_file($dir.'/'.$item)){
- if(unlink($dir.'/'.$item)){
- $this->notifyObservers($dir.'/'.$item,OC_FILEACTION_DELETE);
- }
- }elseif(is_dir($dir.'/'.$item)){
- if (!$this->delTree($dirRelative. "/" . $item)){
- return false;
- };
- }
- }
- if($return=rmdir($dir)){
- $this->notifyObservers($dir,OC_FILEACTION_DELETE);
- }
- return $return;
- }
-
- public function find($path){
- $return=System::find($this->datadir.$path);
- foreach($return as &$file){
- $file=str_replace($file,$this->datadir,'');
- }
- return $return;
- }
-
- public function getTree($dir) {
- if(substr($dir,-1,1)=='/'){
- $dir=substr($dir,0,-1);
- }
- $tree=array();
- $tree[]=$dir;
- $dirRelative=$dir;
- $dir=$this->datadir.$dir;
- if (!file_exists($dir)) return true;
- foreach (scandir($dir) as $item) {
- if ($item == '.' || $item == '..') continue;
- if(is_file($dir.'/'.$item)){
- $tree[]=$dirRelative.'/'.$item;
- }elseif(is_dir($dir.'/'.$item)){
- if ($subTree=$this->getTree($dirRelative. "/" . $item)){
- $tree=array_merge($tree,$subTree);
- }
- }
- }
- return $tree;
- }
-}
-?> \ No newline at end of file
diff --git a/inc/lib_filesystem.php b/inc/lib_filesystem.php
deleted file mode 100644
index 57e4d7a70c2..00000000000
--- a/inc/lib_filesystem.php
+++ /dev/null
@@ -1,380 +0,0 @@
-<?php
-
-/**
-* ownCloud
-*
-* @author Frank Karlitschek
-* @copyright 2010 Frank Karlitschek karlitschek@kde.org
-*
-* This library is free software; you can redistribute it and/or
-* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
-* License as published by the Free Software Foundation; either
-* version 3 of the License, or 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 AFFERO 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, see <http://www.gnu.org/licenses/>.
-*
-*/
-
-
-/**
- * Class for abstraction of filesystem functions
- * This class won't call any filesystem functions for itself but but will pass them to the correct OC_FILESTORAGE object
- * this class should also handle all the file premission related stuff
- */
-class OC_FILESYSTEM{
- static private $storages=array();
- static private $fakeRoot='';
- static private $storageTypes=array();
-
-
- /**
- * register a storage type
- * @param string type
- * @param string classname
- * @param array arguments an associative array in the form of name=>type (eg array('datadir'=>'string'))
- */
- static public function registerStorageType($type,$classname,$arguments){
- self::$storageTypes[$type]=array('type'=>$type,'classname'=>$classname,'arguments'=>$arguments);
- }
-
- /**
- * check if the filesystem supports a specific storagetype
- * @param string type
- * @return bool
- */
- static public function hasStorageType($type){
- return isset(self::$storageTypes[$type]);
- }
-
- /**
- * get the list of names of storagetypes that the filesystem supports
- * @return array
- */
- static public function getStorageTypeNames(){
- return array_keys(self::$storageTypes);
- }
-
- /**
- * create a new storage of a specific type
- * @param string type
- * @param array arguments
- * @return OC_FILESTORAGE
- */
- static public function createStorage($type,$arguments){
- if(!self::hasStorageType($type)){
- return false;
- }
- $className=self::$storageTypes[$type]['classname'];
- if(class_exists($className)){
- return new $className($arguments);
- }else{
- return false;
- }
- }
-
- /**
- * change the root to a fake toor
- * @param string fakeRoot
- * @return bool
- */
- static public function chroot($fakeRoot){
- if($fakeRoot[0]!=='/'){
- $fakeRoot='/'.$fakeRoot;
- }
- self::$fakeRoot=$fakeRoot;
- }
-
- /**
- * get the part of the path relative to the mountpoint of the storage it's stored in
- * @param string path
- * @return bool
- */
- static public function getInternalPath($path){
- $mountPoint=self::getMountPoint($path);
- $path=self::$fakeRoot.$path;
- $internalPath=substr($path,strlen($mountPoint));
- return $internalPath;
- }
-
- /**
- * check if the current users has the right premissions to read a file
- * @param string path
- * @return bool
- */
- static private function canRead($path){
- if(substr($path,0,1)!=='/'){
- $path='/'.$path;
- }
- if(strstr($path,'/../') || strrchr($path, '/') === '/..' ){
- return false;
- }
- return true;//dummy untill premissions are correctly implemented, also the correcty value because for now users are locked in their seperate data dir and can read/write everything in there
- }
- /**
- * check if the current users has the right premissions to write a file
- * @param string path
- * @return bool
- */
- static private function canWrite($path){
- if(substr($path,0,1)!=='/'){
- $path='/'.$path;
- }
- if(strstr($path,'/../') || strrchr($path, '/') === '/..' ){
- return false;
- }
- return true;//dummy untill premissions are correctly implemented, also the correcty value because for now users are locked in their seperate data dir and can read/write everything in there
- }
-
- /**
- * mount an OC_FILESTORAGE in our virtual filesystem
- * @param OC_FILESTORAGE storage
- * @param string mountpoint
- */
- static public function mount($storage,$mountpoint){
- if(substr($mountpoint,0,1)!=='/'){
- $mountpoint='/'.$mountpoint;
- }
- self::$storages[self::$fakeRoot.$mountpoint]=$storage;
- }
-
- /**
- * get the storage object for a path
- * @param string path
- * @return OC_FILESTORAGE
- */
- static private function getStorage($path){
- $mountpoint=self::getMountPoint($path);
- if($mountpoint){
- return self::$storages[$mountpoint];
- }
- }
-
- /**
- * get the mountpoint of the storage object for a path
- ( note: because a storage is not always mounted inside the fakeroot, the returned mountpoint is relative to the absolute root of the filesystem and doesn't take the chroot into account
- *
- * @param string path
- * @return string
- */
- static private function getMountPoint($path){
- if(!$path){
- $path='/';
- }
- if(substr($path,0,1)!=='/'){
- $path='/'.$path;
- }
- if(substr($path,-1)!=='/'){
- $path=$path.'/';
- }
- $path=self::$fakeRoot.$path;
- $foundMountPoint='';
- foreach(self::$storages as $mountpoint=>$storage){
- if(substr($mountpoint,-1)!=='/'){
- $mountpoint=$mountpoint.'/';
- }
- if($mountpoint==$path){
- return $mountpoint;
- }
- if(strpos($path,$mountpoint)===0 and strlen($mountpoint)>strlen($foundMountPoint)){
- $foundMountPoint=$mountpoint;
- }
- }
- return $foundMountPoint;
- }
-
- static public function mkdir($path){
- $parent=substr($path,0,strrpos($path,'/'));
- if(self::canWrite($parent) and $storage=self::getStorage($path)){
- return $storage->mkdir(self::getInternalPath($path));
- }
- }
- static public function rmdir($path){
- if(self::canWrite($path) and $storage=self::getStorage($path)){
- return $storage->rmdir(self::getInternalPath($path));
- }
- }
- static public function opendir($path){
- if(self::canRead($path) and $storage=self::getStorage($path)){
- return $storage->opendir(self::getInternalPath($path));
- }
- }
- static public function is_dir($path){
- if($path=='/'){
- return true;
- }
- if(self::canRead($path) and $storage=self::getStorage($path)){
- return $storage->is_dir(self::getInternalPath($path));
- }
- }
- static public function is_file($path){
- if($path=='/'){
- return false;
- }
- if(self::canRead($path) and $storage=self::getStorage($path)){
- return $storage->is_file(self::getInternalPath($path));
- }
- }
- static public function stat($path){
- if(self::canRead($path) and $storage=self::getStorage($path)){
- return $storage->stat(self::getInternalPath($path));
- }
- }
- static public function filetype($path){
- if(self::canRead($path) and $storage=self::getStorage($path)){
- return $storage->filetype(self::getInternalPath($path));
- }
- }
- static public function filesize($path){
- if(self::canRead($path) and $storage=self::getStorage($path)){
- return $storage->filesize(self::getInternalPath($path));
- }
- }
- static public function readfile($path){
- if(self::canRead($path) and $storage=self::getStorage($path)){
- return $storage->readfile(self::getInternalPath($path));
- }
- }
- static public function is_readable($path){
- if(self::canRead($path) and $storage=self::getStorage($path)){
- return $storage->is_readable(self::getInternalPath($path));
- }
- return false;
- }
- static public function is_writeable($path){
- if(self::canWrite($path) and $storage=self::getStorage($path)){
- return $storage->is_writeable(self::getInternalPath($path));
- }
- return false;
- }
- static public function file_exists($path){
- if($path=='/'){
- return true;
- }
- if(self::canWrite($path) and $storage=self::getStorage($path)){
- return $storage->file_exists(self::getInternalPath($path));
- }
- return false;
- }
- static public function filectime($path){
- if($storage=self::getStorage($path)){
- return $storage->filectime(self::getInternalPath($path));
- }
- }
- static public function filemtime($path){
- if($storage=self::getStorage($path)){
- return $storage->filemtime(self::getInternalPath($path));
- }
- }
- static public function fileatime($path){
- if($storage=self::getStorage($path)){
- return $storage->fileatime(self::getInternalPath($path));
- }
- }
- static public function file_get_contents($path){
- if(self::canRead($path) and $storage=self::getStorage($path)){
- return $storage->file_get_contents(self::getInternalPath($path));
- }
- }
- static public function file_put_contents($path,$data){
- if(self::canWrite($path) and $storage=self::getStorage($path)){
- return $storage->file_put_contents(self::getInternalPath($path),$data);
- }
- }
- static public function unlink($path){
- if(self::canWrite($path) and $storage=self::getStorage($path)){
- return $storage->unlink(self::getInternalPath($path));
- }
- }
- static public function rename($path1,$path2){
- if(self::canWrite($path1) and self::canWrite($path2)){
- $mp1=self::getMountPoint($path1);
- $mp2=self::getMountPoint($path2);
- if($mp1==$mp2){
- if($storage=self::getStorage($path1)){
- return $storage->rename(self::getInternalPath($path1),self::getInternalPath($path2));
- }
- }elseif($storage1=self::getStorage($path1) and $storage2=self::getStorage($path2)){
- $tmpFile=$storage1->toTmpFile(self::getInternalPath($path1));
- $result=$storage2->fromTmpFile(self::getInternalPath($path2));
- $storage1->unlink(self::getInternalPath($path1));
- return $result;
- }
- }
- }
- static public function copy($path1,$path2){
- if(self::canRead($path1) and self::canWrite($path2)){
- $mp1=self::getMountPoint($path1);
- $mp2=self::getMountPoint($path2);
- if($mp1==$mp2){
- if($storage=self::getStorage($path1)){
- return $storage->copy(self::getInternalPath($path1),self::getInternalPath($path2));
- }
- }elseif($storage1=self::getStorage($path1) and $storage2=self::getStorage($path2)){
- $tmpFile=$storage1->toTmpFile(self::getInternalPath($path1));
- return $storage2->fromTmpFile(self::getInternalPath($path2));
- }
- }
- }
- static public function fopen($path,$mode){
- $allowed=((strpos($path,'r')===false and strpos($path,'r+')!==false and self::canRead) or self::canWrite($path));
- if($allowed){
- if($storage=self::getStorage($path)){
- return $storage->fopen(self::getInternalPath($path),$mode);
- }
- }
- }
- static public function toTmpFile($path){
- if(self::canRead($path) and $storage=self::getStorage($path)){
- return $storage->toTmpFile(self::getInternalPath($path));
- }
- }
- static public function fromTmpFile($tmpFile,$path){
- if(self::canWrite($path) and $storage=self::getStorage($path)){
- return $storage->fromTmpFile($tmpFile,self::getInternalPath($path));
- }
- }
- static public function getMimeType($path){
- if(self::canRead($path) and $storage=self::getStorage($path)){
- return $storage->getMimeType(self::getInternalPath($path));
- }
- }
- static public function delTree($path){
- if(self::canWrite($path) and $storage=self::getStorage($path)){
- return $storage->delTree(self::getInternalPath($path));
- }
- }
- static public function find($path){
- if($storage=self::getStorage($path)){
- $mp=self::getMountPoint($path);
- $return=$storage->find(self::getInternalPath($path));
- foreach($return as &$file){
- $file=$mp.$file;
- }
- }
- return $return;
- }
- static public function getTree($path){
- if(self::canRead($path) and $storage=self::getStorage($path)){
- $mp=self::getMountPoint($path);
- $return=$storage->getTree(self::getInternalPath($path));
- foreach($return as &$file){
- if(substr($file,0,1)=='/'){
- $file=substr($file,1);
- }
- $file=$mp.$file;
- $file=substr($file,strlen(self::$fakeRoot));
- if($file === '' || $file === false){
- $file = '/';
- }
- }
- return $return;
- }
- }
-}
-?>
diff --git a/inc/lib_log.php b/inc/lib_log.php
deleted file mode 100644
index 989308c82fc..00000000000
--- a/inc/lib_log.php
+++ /dev/null
@@ -1,86 +0,0 @@
-<?php
-
-/**
-* ownCloud
-*
-* @author Frank Karlitschek
-* @copyright 2010 Frank Karlitschek karlitschek@kde.org
-*
-* This library is free software; you can redistribute it and/or
-* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
-* License as published by the Free Software Foundation; either
-* version 3 of the License, or 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 AFFERO 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, see <http://www.gnu.org/licenses/>.
-*
-*/
-
-
-/**
- * Class for logging features
- *
- */
-class OC_LOG {
-
- /**
- * array to define different log types
- *
- */
- public static $TYPE = array (
- 1=>'login',
- 2=>'logout',
- 3=>'read',
- 4=>'write',
- );
-
-
- /**
- * log an event
- *
- * @param username $user
- * @param type $type
- * @param message $message
- */
- public static function event($user,$type,$message){
- global $CONFIG_DBTABLEPREFIX;
- $result = OC_DB::query('INSERT INTO `' . $CONFIG_DBTABLEPREFIX . 'log` (`timestamp`,`user`,`type`,`message`) VALUES ('.time().',\''.addslashes($user).'\','.addslashes($type).',\''.addslashes($message).'\');');
- }
-
-
- /**
- * show the log entries in a web GUI
- *
- */
- public static function show(){
- global $CONFIG_DATEFORMAT;
- global $CONFIG_DBTABLEPREFIX;
- echo('<div class="center"><table cellpadding="6" cellspacing="0" border="0" class="log">');
-
- if(OC_USER::ingroup($_SESSION['username_clean'],'admin')){
- $result = OC_DB::select('select `timestamp`,`user`,`type`,`message` from '.$CONFIG_DBTABLEPREFIX.'log order by timestamp desc limit 20');
- }else{
- $user=$_SESSION['username_clean'];
- $result = OC_DB::select('select `timestamp`,`user`,`type`,`message` from '.$CONFIG_DBTABLEPREFIX.'log where user=\''.$user.'\' order by timestamp desc limit 20');
- }
- foreach($result as $entry){
- echo('<tr class="browserline">');
- echo('<td class="sizetext">'.date($CONFIG_DATEFORMAT,$entry['timestamp']).'</td>');
- echo('<td class="highlighttext">'.OC_LOG::$TYPE[$entry['type']].'</td>');
- echo('<td class="nametext">'.$entry['user'].'</td>');
- echo('<td class="nametext">'.$entry['message'].'</td>');
- echo('</tr>');
- }
- echo('</table></div>');
- }
-
-}
-
-
-
-?>
diff --git a/inc/lib_ocs.php b/inc/lib_ocs.php
deleted file mode 100644
index a4c51f7c62d..00000000000
--- a/inc/lib_ocs.php
+++ /dev/null
@@ -1,496 +0,0 @@
-<?php
-
-/**
-* ownCloud
-*
-* @author Frank Karlitschek
-* @copyright 2010 Frank Karlitschek karlitschek@kde.org
-*
-* This library is free software; you can redistribute it and/or
-* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
-* License as published by the Free Software Foundation; either
-* version 3 of the License, or 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 AFFERO 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, see <http://www.gnu.org/licenses/>.
-*
-*/
-
-
-
-/**
- * Class to handle open collaboration services API requests
- *
- */
-class OC_OCS {
-
- /**
- * reads input date from get/post/cookies and converts the date to a special data-type
- *
- * @param variable $key
- * @param variable-type $type
- * @param priority $getpriority
- * @param default $default
- * @return data
- */
- public static function readData($key,$type='raw',$getpriority=false,$default='') {
- if($getpriority) {
- if(isset($_GET[$key])) {
- $data=$_GET[$key];
- } elseif(isset($_POST[$key])) {
- $data=$_POST[$key];
- } else {
- if($default=='') {
- if(($type=='int') or ($type=='float')) $data=0; else $data='';
- } else {
- $data=$default;
- }
- }
- } else {
- if(isset($_POST[$key])) {
- $data=$_POST[$key];
- } elseif(isset($_GET[$key])) {
- $data=$_GET[$key];
- } elseif(isset($_COOKIE[$key])) {
- $data=$_COOKIE[$key];
- } else {
- if($default=='') {
- if(($type=='int') or ($type=='float')) $data=0; else $data='';
- } else {
- $data=$default;
- }
- }
- }
-
- if($type=='raw') return($data);
- elseif($type=='text') return(addslashes(strip_tags($data)));
- elseif($type=='int') { $data = (int) $data; return($data); }
- elseif($type=='float') { $data = (float) $data; return($data); }
- elseif($type=='array') { $data = $data; return($data); }
- }
-
-
- /**
- main function to handle the REST request
- **/
- public static function handle() {
-
- // overwrite the 404 error page returncode
- header("HTTP/1.0 200 OK");
-
-
- if($_SERVER['REQUEST_METHOD'] == 'GET') {
- $method='get';
- }elseif($_SERVER['REQUEST_METHOD'] == 'PUT') {
- $method='put';
- parse_str(file_get_contents("php://input"),$put_vars);
- }elseif($_SERVER['REQUEST_METHOD'] == 'POST') {
- $method='post';
- }else{
- echo('internal server error: method not supported');
- exit();
- }
-
- // preprocess url
- $url=$_SERVER['REQUEST_URI'];
- if(substr($url,(strlen($url)-1))<>'/') $url.='/';
- $ex=explode('/',$url);
- $paracount=count($ex);
-
- // eventhandler
-
- // CONFIG
- // apiconfig - GET - CONFIG
- if(($method=='get') and (strtolower($ex[$paracount-3])=='v1.php') and (strtolower($ex[$paracount-2])=='config')){
- $format=OC_OCS::readdata('format','text');
- OC_OCS::apiconfig($format);
-
- // PERSON
- // personcheck - POST - PERSON/CHECK
- }elseif(($method=='post') and (strtolower($ex[$paracount-4])=='v1.php') and (strtolower($ex[$paracount-3])=='person') and (strtolower($ex[$paracount-2])=='check')){
- $format=OC_OCS::readdata('format','text');
- $login=OC_OCS::readdata('login','text');
- $passwd=OC_OCS::readdata('password','text');
- OC_OCS::personcheck($format,$login,$passwd);
-
- // ACTIVITY
- // activityget - GET ACTIVITY page,pagesize als urlparameter
- }elseif(($method=='get') and (strtolower($ex[$paracount-3])=='v1.php')and (strtolower($ex[$paracount-2])=='activity')){
- $format=OC_OCS::readdata('format','text');
- $page=OC_OCS::readdata('page','int');
- $pagesize=OC_OCS::readdata('pagesize','int');
- if($pagesize<1 or $pagesize>100) $pagesize=10;
- OC_OCS::activityget($format,$page,$pagesize);
-
- // activityput - POST ACTIVITY
- }elseif(($method=='post') and (strtolower($ex[$paracount-3])=='v1.php')and (strtolower($ex[$paracount-2])=='activity')){
- $format=OC_OCS::readdata('format','text');
- $message=OC_OCS::readdata('message','text');
- OC_OCS::activityput($format,$message);
-
- // PRIVATEDATA
- // get - GET DATA
- }elseif(($method=='get') and (strtolower($ex[$paracount-4])=='v1.php')and (strtolower($ex[$paracount-2])=='getattribute')){
- $format=OC_OCS::readdata('format','text');
- OC_OCS::privateDataGet($format, "");
-
- }elseif(($method=='get') and (strtolower($ex[$paracount-5])=='v1.php')and (strtolower($ex[$paracount-3])=='getattribute')){
- $format=OC_OCS::readdata('format','text');
- $key=$ex[$paracount-2];
- OC_OCS::privateDataGet($format, $key);
-
- // set - POST DATA
- }elseif(($method=='post') and (strtolower($ex[$paracount-6])=='v1.php')and (strtolower($ex[$paracount-4])=='setattribute')){
- $format=OC_OCS::readdata('format','text');
- $key=$ex[$paracount-2];
- $app=$ex[$paracount-3];
- $value=OC_OCS::readdata('value','text');
- OC_OCS::privatedataset($format, $app, $key, $value);
-
- }else{
- $format=OC_OCS::readdata('format','text');
- $txt='Invalid query, please check the syntax. API specifications are here: http://www.freedesktop.org/wiki/Specifications/open-collaboration-services. DEBUG OUTPUT:'."\n";
- $txt.=OC_OCS::getdebugoutput();
- echo(OC_OCS::generatexml($format,'failed',999,$txt));
- }
- exit();
- }
-
- /**
- * generated some debug information to make it easier to find faild API calls
- * @return debug data string
- */
- private static function getDebugOutput() {
- $txt='';
- $txt.="debug output:\n";
- if(isset($_SERVER['REQUEST_METHOD'])) $txt.='http request method: '.$_SERVER['REQUEST_METHOD']."\n";
- if(isset($_SERVER['REQUEST_URI'])) $txt.='http request uri: '.$_SERVER['REQUEST_URI']."\n";
- if(isset($_GET)) foreach($_GET as $key=>$value) $txt.='get parameter: '.$key.'->'.$value."\n";
- if(isset($_POST)) foreach($_POST as $key=>$value) $txt.='post parameter: '.$key.'->'.$value."\n";
- return($txt);
- }
-
- /**
- * checks if the user is authenticated
- * checks the IP whitlist, apikeys and login/password combination
- * if $forceuser is true and the authentication failed it returns an 401 http response.
- * if $forceuser is false and authentification fails it returns an empty username string
- * @param bool $forceuser
- * @return username string
- */
- private static function checkPassword($forceuser=true) {
- //valid user account ?
- if(isset($_SERVER['PHP_AUTH_USER'])) $authuser=$_SERVER['PHP_AUTH_USER']; else $authuser='';
- if(isset($_SERVER['PHP_AUTH_PW'])) $authpw=$_SERVER['PHP_AUTH_PW']; else $authpw='';
-
- if(empty($authuser)) {
- if($forceuser){
- header('WWW-Authenticate: Basic realm="your valid user account or api key"');
- header('HTTP/1.0 401 Unauthorized');
- exit;
- }else{
- $identifieduser='';
- }
- }else{
- if(!OC_USER::login($authuser,$authpw)){
- if($forceuser){
- header('WWW-Authenticate: Basic realm="your valid user account or api key"');
- header('HTTP/1.0 401 Unauthorized');
- exit;
- }else{
- $identifieduser='';
- }
- }else{
- $identifieduser=$authuser;
- }
- }
-
- return($identifieduser);
- }
-
-
- /**
- * generates the xml or json response for the API call from an multidimenional data array.
- * @param string $format
- * @param string $status
- * @param string $statuscode
- * @param string $message
- * @param array $data
- * @param string $tag
- * @param string $tagattribute
- * @param int $dimension
- * @param int $itemscount
- * @param int $itemsperpage
- * @return string xml/json
- */
- private static function generateXml($format,$status,$statuscode,$message,$data=array(),$tag='',$tagattribute='',$dimension=-1,$itemscount='',$itemsperpage='') {
- if($format=='json') {
-
- $json=array();
- $json['status']=$status;
- $json['statuscode']=$statuscode;
- $json['message']=$message;
- $json['totalitems']=$itemscount;
- $json['itemsperpage']=$itemsperpage;
- $json['data']=$data;
- return(json_encode($json));
-
-
- }else{
- $txt='';
- $writer = xmlwriter_open_memory();
- xmlwriter_set_indent( $writer, 2 );
- xmlwriter_start_document($writer );
- xmlwriter_start_element($writer,'ocs');
- xmlwriter_start_element($writer,'meta');
- xmlwriter_write_element($writer,'status',$status);
- xmlwriter_write_element($writer,'statuscode',$statuscode);
- xmlwriter_write_element($writer,'message',$message);
- if($itemscount<>'') xmlwriter_write_element($writer,'totalitems',$itemscount);
- if(!empty($itemsperpage)) xmlwriter_write_element($writer,'itemsperpage',$itemsperpage);
- xmlwriter_end_element($writer);
- if($dimension=='0') {
- // 0 dimensions
- xmlwriter_write_element($writer,'data',$data);
-
- }elseif($dimension=='1') {
- xmlwriter_start_element($writer,'data');
- foreach($data as $key=>$entry) {
- xmlwriter_write_element($writer,$key,$entry);
- }
- xmlwriter_end_element($writer);
-
- }elseif($dimension=='2') {
- xmlwriter_start_element($writer,'data');
- foreach($data as $entry) {
- xmlwriter_start_element($writer,$tag);
- if(!empty($tagattribute)) {
- xmlwriter_write_attribute($writer,'details',$tagattribute);
- }
- foreach($entry as $key=>$value) {
- if(is_array($value)){
- foreach($value as $k=>$v) {
- xmlwriter_write_element($writer,$k,$v);
- }
- } else {
- xmlwriter_write_element($writer,$key,$value);
- }
- }
- xmlwriter_end_element($writer);
- }
- xmlwriter_end_element($writer);
-
- }elseif($dimension=='3') {
- xmlwriter_start_element($writer,'data');
- foreach($data as $entrykey=>$entry) {
- xmlwriter_start_element($writer,$tag);
- if(!empty($tagattribute)) {
- xmlwriter_write_attribute($writer,'details',$tagattribute);
- }
- foreach($entry as $key=>$value) {
- if(is_array($value)){
- xmlwriter_start_element($writer,$entrykey);
- foreach($value as $k=>$v) {
- xmlwriter_write_element($writer,$k,$v);
- }
- xmlwriter_end_element($writer);
- } else {
- xmlwriter_write_element($writer,$key,$value);
- }
- }
- xmlwriter_end_element($writer);
- }
- xmlwriter_end_element($writer);
- }elseif($dimension=='dynamic') {
- xmlwriter_start_element($writer,'data');
- OC_OCS::toxml($writer,$data,'comment');
- xmlwriter_end_element($writer);
- }
-
- xmlwriter_end_element($writer);
-
- xmlwriter_end_document( $writer );
- $txt.=xmlwriter_output_memory( $writer );
- unset($writer);
- return($txt);
- }
- }
-
- public static function toXml($writer,$data,$node) {
- foreach($data as $key => $value) {
- if (is_numeric($key)) {
- $key = $node;
- }
- if (is_array($value)){
- xmlwriter_start_element($writer,$key);
- OC_OCS::toxml($writer,$value,$node);
- xmlwriter_end_element($writer);
- }else{
- xmlwriter_write_element($writer,$key,$value);
- }
-
- }
- }
-
-
-
-
- /**
- * return the config data of this server
- * @param string $format
- * @return string xml/json
- */
- private static function apiConfig($format) {
- $user=OC_OCS::checkpassword(false);
- $url=substr($_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'],0,-11).'';
-
- $xml['version']='1.5';
- $xml['website']='ownCloud';
- $xml['host']=$_SERVER['HTTP_HOST'];
- $xml['contact']='';
- $xml['ssl']='false';
- echo(OC_OCS::generatexml($format,'ok',100,'',$xml,'config','',1));
- }
-
-
- /**
- * check if the provided login/apikey/password is valid
- * @param string $format
- * @param string $login
- * @param string $passwd
- * @return string xml/json
- */
- private static function personCheck($format,$login,$passwd) {
- if($login<>''){
- if(OC_USER::login($login,$passwd)){
- $xml['person']['personid']=$login;
- echo(OC_OCS::generatexml($format,'ok',100,'',$xml,'person','check',2));
- }else{
- echo(OC_OCS::generatexml($format,'failed',102,'login not valid'));
- }
- }else{
- echo(OC_OCS::generatexml($format,'failed',101,'please specify all mandatory fields'));
- }
- }
-
-
-
- // ACTIVITY API #############################################
-
- /**
- * get my activities
- * @param string $format
- * @param string $page
- * @param string $pagesize
- * @return string xml/json
- */
- private static function activityGet($format,$page,$pagesize) {
- global $CONFIG_DBTABLEPREFIX;
-
- $user=OC_OCS::checkpassword();
-
- $result = OC_DB::query("select count(*) as co from {$CONFIG_DBTABLEPREFIX}log");
- $entry=$result->fetchRow();
- $totalcount=$entry['co'];
- OC_DB::free_result($result);
-
- $result = OC_DB::select("select id,timestamp,user,type,message from {$CONFIG_DBTABLEPREFIX}log order by timestamp desc limit " . ($page*$pagesize) . ",$pagesize");
- $itemscount=count($result);
-
- $url='http://'.substr($_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'],0,-11).'';
- $xml=array();
- foreach($result as $i=>$log) {
- $xml[$i]['id']=$log['id'];
- $xml[$i]['personid']=$log['user'];
- $xml[$i]['firstname']=$log['user'];
- $xml[$i]['lastname']='';
- $xml[$i]['profilepage']=$url;
-
- $pic=$url.'/img/owncloud-icon.png';
- $xml[$i]['avatarpic']=$pic;
-
- $xml[$i]['timestamp']=date('c',$log['timestamp']);
- $xml[$i]['type']=1;
- $xml[$i]['message']=OC_LOG::$TYPE[$log['type']].' '.strip_tags($log['message']);
- $xml[$i]['link']=$url;
- }
-
- $txt=OC_OCS::generatexml($format,'ok',100,'',$xml,'activity','full',2,$totalcount,$pagesize);
- echo($txt);
- }
-
- /**
- * submit a activity
- * @param string $format
- * @param string $message
- * @return string xml/json
- */
- private static function activityPut($format,$message) {
- // not implemented in ownCloud
- $user=OC_OCS::checkpassword();
- echo(OC_OCS::generatexml($format,'ok',100,''));
- }
-
- // PRIVATEDATA API #############################################
-
- /**
- * get private data
- * @param string $key
- * @return string xml/json
- */
- private static function privateDataGet($format, $key) {
- global $CONFIG_DBTABLEPREFIX;
-
- $user=OC_OCS::checkpassword();
-
- if (!trim($key)) {
- $result = OC_DB::select("select key,value,timestamp from {$CONFIG_DBTABLEPREFIX}privatedata order by timestamp desc");
- } else {
- $result = OC_DB::select("select key,value,timestamp from {$CONFIG_DBTABLEPREFIX}privatedata where key ='".addslashes($key)."' order by timestamp desc");
- }
- $itemscount=count($result);
-
- $xml=array();
- foreach($result as $i=>$log) {
- $xml[$i]['key']=$log['key'];
- $xml[$i]['value']=$log['value'];
- $xml[$i]['timestamp']=$log['timestamp'];
- }
-
-
- $txt=OC_OCS::generatexml($format, 'ok', 100, '', $xml, 'privatedata', 'full', 2, count($xml), 0);
- echo($txt);
- }
-
- /**
- * set private data referenced by $key to $value
- * @param string $key
- * @param string $value
- * @return string xml/json
- */
- private static function privateDataSet($format, $app, $key, $value) {
- global $CONFIG_DBTABLEPREFIX;
-
- //TODO: prepared statements, locking tables, fancy stuff, error checking/handling
- $user=OC_OCS::checkpassword();
-
- $result=OC_DB::select("select count(*) as co from {$CONFIG_DBTABLEPREFIX}privatedata where key = '".addslashes($key)."' and app = '".addslashes($app)."'");
- $totalcount=$result[0]['co'];
-
- if ($totalcount != 0) {
- $result = OC_DB::query("update {$CONFIG_DBTABLEPREFIX}privatedata set value='".addslashes($value)."', timestamp = datetime('now') where key = '".addslashes($key)."' and app = '".addslashes($app)."'");
- } else {
- $result = OC_DB::query("insert into {$CONFIG_DBTABLEPREFIX}privatedata(app, key, value, timestamp) values('".addslashes($app)."', '".addslashes($key)."', '".addslashes($value)."', datetime('now'))");
- }
-
- echo(OC_OCS::generatexml($format,'ok',100,''));
- }
-}
-
-
-?>
diff --git a/inc/lib_plugin.php b/inc/lib_plugin.php
deleted file mode 100644
index eb7533c4479..00000000000
--- a/inc/lib_plugin.php
+++ /dev/null
@@ -1,381 +0,0 @@
-<?php
-
-/**
-* ownCloud
-*
-* @author Frank Karlitschek
-* @copyright 2010 Frank Karlitschek karlitschek@kde.org
-*
-* This library is free software; you can redistribute it and/or
-* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
-* License as published by the Free Software Foundation; either
-* version 3 of the License, or 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 AFFERO 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, see <http://www.gnu.org/licenses/>.
-*
-*/
-
-class OC_PLUGIN{
- static private $blacklist=array();
-
- /**
- * load the plugin with the given id
- * @param string id
- * @return bool
- */
- static public function load($id){
- global $SERVERROOT;
- $data=self::getPluginData($id);
- if($data){
- if(isset($data['info']['require'])){
- $minVersion=explode('.',$data['info']['require']);
- $version=OC_UTIL::getVersion();
- $roundTo=count($minVersion);
- while(count($version)>$roundTo){
- if($version[count($version)-1]>=50){
- $version[count($version)-2]++;
- }
- unset($version[count($version)-1]);
- }
- for($i=0;$i<count($minVersion);$i++){
- if($version[$i]<$minVersion[$i]){
- return false;
- }
- }
- }
- //check for uninstalled db's
- if(isset($data['install']) and isset($data['install']['database'])){
- foreach($data['install']['database'] as $db){
- if(!$data['install']['database_installed'][$db]){
- self::installDB($id);
- break;
- }
- }
- }
-
- if(isset($data['runtime'])){
- foreach($data['runtime'] as $include){
- include($SERVERROOT.'/plugins/'.$id.'/'.$include);
- }
- }
- }
- return false;
- }
-
- /**
- * Get a list of all installed plugins
- */
- public static function listPlugins() {
- global $SERVERROOT;
- $plugins = array();
- $fd = opendir($SERVERROOT . '/plugins');
- while ( false !== ($filename = readdir($fd)) ) {
- if ( $filename<>'.' AND $filename<>'..' AND ('.' != substr($filename, 0, 1))) {
- if(file_exists($SERVERROOT . '/plugins/'.$filename.'/plugin.xml')){
- $plugins[]=$filename;
- }
- }
- }
- closedir($fd);
- return $plugins;
- }
-
- /**
- * Load all plugins that aren't blacklisted
- */
- public static function loadPlugins() {
- global $CONFIG_INSTALLED;
- if($CONFIG_INSTALLED){
- global $SERVERROOT;
- $plugins = self::listPlugins();
- $blacklist=self::loadBlacklist();
- foreach($plugins as $plugin){
- if (array_search($plugin,$blacklist)===false) {
- self::load($plugin);
- }
- }
- }
- }
-
- /**
- * load the blacklist from blacklist.txt
- * @return array
- */
- public static function loadBlacklist(){
- global $SERVERROOT;
- if(count(self::$blacklist)>0){
- return self::$blacklist;
- }
- $blacklist=array();
- if(is_file($SERVERROOT.'/plugins/blacklist.txt')){
- $file=file_get_contents($SERVERROOT.'/plugins/blacklist.txt');
- $lines=explode("\n",$file);
- foreach($lines as $line){
- $id=trim($line);
- if($id!='' and is_dir($SERVERROOT.'/plugins/'.$id)){
- $blacklist[]=$id;
- }
- }
- }
- self::$blacklist=$blacklist;
- return $blacklist;
- }
-
- /**
- * save a blacklist to blacklist.txt
- * @param array blacklist
- */
- private static function saveBlacklist($blacklist){
- global $SERVERROOT;
- $file='';
- foreach($blacklist as $item){
- $file.="$item\n";
- }
- self::$blacklist=$blacklist;
- file_put_contents($SERVERROOT.'/plugins/blacklist.txt',$file);
- }
-
- /**
- * add a plugin to the blacklist
- * @param string id
- */
- public static function addToBlacklist($id){
- $blacklist=self::loadBlacklist();
- if(array_search($id,$blacklist)===false){
- $blacklist[]=$id;
- self::$blacklist=$blacklist;
- self::saveBlacklist($blacklist);
- }
- }
-
- /**
- * remove a plugin to the blacklist
- * @param string id
- */
- public static function removeFromBlacklist($id){
- $blacklist=self::loadBlacklist();
- $index=array_search($id,$blacklist);
- if($index!==false){
- unset($blacklist[$index]);
- self::$blacklist=$blacklist;
- self::saveBlacklist($blacklist);
- }
- }
-
- /**
- * Load data from the plugin.xml of a plugin, either identified by the plugin or the path of the plugin.xml file
- * @param string id
- * @return array
- */
- public static function getPluginData($id){
- global $SERVERROOT;
- if(is_file($id)){
- $file=$id;
- }else{
- if(!is_dir($SERVERROOT.'/plugins/'.$id) or !is_file($SERVERROOT.'/plugins/'.$id.'/plugin.xml')){
- return false;
- }else{
- $file=$SERVERROOT.'/plugins/'.$id.'/plugin.xml';
- }
- }
- $data=array();
- $plugin=new DOMDocument();
- $plugin->load($file);
- $data['version']=$plugin->documentElement->getAttribute('version');
- $info=$plugin->getElementsByTagName('info');
- if($info->length>0){
- $info=$info->item(0);
- $data['info']=array();
- foreach($info->childNodes as $child){
- if($child->nodeType==XML_ELEMENT_NODE){
- $data['info'][$child->tagName]=$child->textContent;
- }
- }
- }
- $runtime=$plugin->getElementsByTagName('runtime');
- if($runtime->length>0){
- $runtime=$runtime->item(0);
- $data['runtime']=array();
- foreach($runtime->childNodes as $child){
- if($child->nodeType==XML_ELEMENT_NODE and $child->tagName=='include'){
- $data['runtime'][]=$child->textContent;
- }
- }
- }
- $install=$plugin->getElementsByTagName('install');
- if($install->length>0){
- $install=$install->item(0);
- $data['install']=array();
- foreach($install->childNodes as $child){
- if($child->nodeType==XML_ELEMENT_NODE){
- $data['install']['include']=array();
- $data['install']['dialog']=array();
- $data['install']['database']=array();
- switch($child->tagName){
- case 'include':
- $data['install']['include'][]=$child->textContent;
- break;
- case 'dialog':
- $data['install']['dialog'][]=$child->textContent;
- break;
- case 'database':
- $data['install']['database'][]=$child->textContent;
- $data['install']['database_installed'][$child->textContent]=($child->hasAttribute('installed') and $child->getAttribute('installed')=='true')?true:false;
- break;
- }
- }
- }
- }
- $uninstall=$plugin->getElementsByTagName('uninstall');
- if($uninstall->length>0){
- $uninstall=$uninstall->item(0);
- $data['uninstall']=array();
- foreach($uninstall->childNodes as $child){
- if($child->nodeType==XML_ELEMENT_NODE){
- $data['uninstall']['include']=array();
- $data['uninstall']['dialog']=array();
- switch($child->tagName){
- case 'include':
- $data['uninstall']['include'][]=$child->textContent;
- break;
- case 'dialog':
- $data['uninstall']['dialog'][]=$child->textContent;
- break;
- }
- }
- }
- }
- return $data;
- }
-
-
- /**
- * Save data to the plugin.xml of a plugin, either identified by the plugin or the path of the plugin.xml file
- * @param string id
- * @param array data the plugin data in the same structure as returned by getPluginData
- * @return bool
- */
- public static function savePluginData($id,$data){
- global $SERVERROOT;
- if(is_file($id)){
- $file=$id;
- }
- if(!is_dir($SERVERROOT.'/plugins/'.$id) or !is_file($SERVERROOT.'/plugins/'.$id.'/plugin.xml')){
- return false;
- }else{
- $file=$SERVERROOT.'/plugins/'.$id.'/plugin.xml';
- }
- $plugin=new DOMDocument();
- $pluginNode=$plugin->createElement('plugin');
- $pluginNode->setAttribute('version',$data['version']);
- $plugin->appendChild($pluginNode);
- $info=$plugin->createElement('info');
- foreach($data['info'] as $name=>$value){
- $node=$plugin->createElement($name);
- $node->appendChild($plugin->createTextNode($value));
- $info->appendChild($node);
- }
- $pluginNode->appendChild($info);
- if(isset($data['runtime'])){
- $runtime=$plugin->createElement('runtime');
- foreach($data['runtime'] as $include){
- $node=$plugin->createElement('include');
- $node->appendChild($plugin->createTextNode($include));
- $runtime->appendChild($node);
- }
- $pluginNode->appendChild($runtime);
- }
- if(isset($data['install'])){
- $install=$plugin->createElement('install');
- foreach($data['install']['include'] as $include){
- $node=$plugin->createElement('include');
- $node->appendChild($plugin->createTextNode($include));
- $install->appendChild($node);
- }
- foreach($data['install']['dialog'] as $dialog){
- $node=$plugin->createElement('dialog');
- $node->appendChild($plugin->createTextNode($dialog));
- $install->appendChild($node);
- }
- foreach($data['install']['database'] as $database){
- $node=$plugin->createElement('database');
- $node->appendChild($plugin->createTextNode($database));
- if($data['install']['database_installed'][$database]){
- $node->setAttribute('installed','true');
- }
- $install->appendChild($node);
- }
- $pluginNode->appendChild($install);
- }
- if(isset($data['uninstall'])){
- $uninstall=$plugin->createElement('uninstall');
- foreach($data['uninstall']['include'] as $include){
- $node=$plugin->createElement('include');
- $node->appendChild($plugin->createTextNode($include));
- $uninstall->appendChild($node);
- }
- foreach($data['uninstall']['dialog'] as $dialog){
- $node=$plugin->createElement('dialog');
- $node->appendChild($plugin->createTextNode($dialog));
- $uninstall->appendChild($node);
- }
- $pluginNode->appendChild($uninstall);
- }
- $plugin->save($file);
- }
-
- /**
- * install the databases of a plugin
- * @param string id
- * @return bool
- */
- public static function installDB($id){
- global $SERVERROOT;
- $data=OC_PLUGIN::getPluginData($id);
- foreach($data['install']['database'] as $db){
- if (!$data['install']['database_installed'][$db]){
- $file=$SERVERROOT.'/plugins/'.$id.'/'.$db;
- OC_DB::createDbFromStructure($file);
- $data['install']['database_installed'][$db]=true;
- }
- }
- self::savePluginData($id,$data);
- return true;
- }
-
- public static function installPlugin($path){
- global $SERVERROOT;
- if(is_file($path)){
- $zip = new ZipArchive;
- if($zip->open($path)===TRUE){
- $folder=sys_get_temp_dir().'/OC_PLUGIN_INSTALL/';
- mkdir($folder);
- $zip->extractTo($folder);
- if(is_file($folder.'/plugin.xml')){
- $pluginData=self::getPluginData($folder.'/plugin.xml');
- if(array_search($pluginData['info']['id'],self::listPlugins())===false){
- if(isset($pluginData['install'])){
- foreach($pluginData['install']['database'] as $db){
- OC_DB::createDbFromStructure($folder.'/'.$db);
- $pluginData['install']['database_installed'][$db]=true;
- }
- foreach($pluginData['install']['include'] as $include){
- include($folder.'/'.$include);
- }
- }
- recursive_copy($folder,$SERVERROOT.'/plugins/'.$pluginData['info']['id']);
- self::savePluginData($SERVERROOT.'/plugins/'.$pluginData['info']['id'].'/plugin.xml',$pluginData);
- }
- }
- delTree($folder);
- }
- }
- }
-}
-?>
diff --git a/inc/lib_remotestorage.php b/inc/lib_remotestorage.php
deleted file mode 100644
index f8835c1641a..00000000000
--- a/inc/lib_remotestorage.php
+++ /dev/null
@@ -1,353 +0,0 @@
-<?php
-
-/**
-* ownCloud
-*
-* @author Frank Karlitschek
-* @copyright 2010 Frank Karlitschek karlitschek@kde.org
-*
-* This library is free software; you can redistribute it and/or
-* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
-* License as published by the Free Software Foundation; either
-* version 3 of the License, or 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 AFFERO 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, see <http://www.gnu.org/licenses/>.
-*
-*/
-
-
-class OC_FILESTORAGE_REMOTE extends OC_FILESTORAGE{
- private $url;
- private $username;
- private $password;
- private $remote=false;
- private $statCache;
- private $statCacheDir=false;
- private $changed=array();
-
- private function cacheDir($dir){
- if($this->statCacheDir!=$dir or $this->statCacheDir===false){
- $this->statCache=$this->remote->getFiles($dir);
- $keys=array_keys($this->statCache);
- $this->statCacheDir=$dir;
- }
- }
-
- public function __construct($arguments){
- $this->url=$arguments['url'];
- $this->username=$arguments['username'];
- $this->password=$arguments['password'];
- }
- private function connect(){
- if($this->remote===false){
- $this->remote=OC_CONNECT::connect($this->url,$this->username,$this->password);
- }
- }
- public function mkdir($path){
- $this->connect();
- $parent=dirname($path);
- $name=substr($path,strlen($parent)+1);
- $return=$this->remote->newFile($parent,$name,'dir');
- if($return){
- $this->notifyObservers($path,OC_FILEACTION_CREATE);
- }
- return $return;
- }
- public function rmdir($path){
- $this->connect();
- $parent=dirname($path);
- $name=substr($path,strlen($parent)+1);
- $return=$this->remote->delete($parent,$name);
- if($return){
- $this->notifyObservers($path,OC_FILEACTION_DELETE);
- }
- return $return;
- }
- public function opendir($path){
- $this->connect();
- $this->cacheDir($path);
- $dirs=array_keys($this->statCache);
- $id=uniqid();
- global $FAKEDIRS;
- $FAKEDIRS[$id]=$dirs;
- if($return=opendir("fakedir://$id")){
- $this->notifyObservers($path,OC_FILEACTION_READ);
- }
- return $return;
- }
- public function is_dir($path){
- $this->connect();
- $parent=dirname($path);
- $name=substr($path,strlen($parent)+1);
- $this->cacheDir($path);
- if($path=='' or $path=='/'){
- return true;
- }
- if(!isset($this->statCache[$name])){
- return false;
- }
- return ($this->statCache[$name]['type'=='dir']);
- }
- public function is_file($path){
- $this->connect();
- $parent=dirname($path);
- $name=substr($path,strlen($parent)+1);
- $this->cacheDir($parent);
- if(!isset($this->statCache[$name])){
- return false;
- }
- return ($this->statCache[$name]['type'!='dir']);
- }
- public function stat($path){
- $this->connect();
- $parent=dirname($path);
- $name=substr($path,strlen($parent)+1);
- $this->cacheDir($parent);
- if(!isset($this->statCache[$name])){
- return $false;
- }
- return $this->statCache[$name];
- }
- public function filetype($path){
- $this->connect();
- $parent=dirname($path);
- $name=substr($path,strlen($parent)+1);
- $this->cacheDir($parent);
- if(!isset($this->statCache[$name])){
- return false;
- }
- return $this->statCache[$name]['type'];
- }
- public function filesize($path){
- $this->connect();
- $parent=dirname($path);
- $name=substr($path,strlen($parent)+1);
- $this->cacheDir($parent);
- if(!isset($this->statCache[$name])){
- return $false;
- }
- return $this->statCache[$name]['size'];
- }
- public function is_readable($path){
- $this->connect();
- $parent=dirname($path);
- $name=substr($path,strlen($parent)+1);
- $this->cacheDir($parent);
- if(!isset($this->statCache[$name])){
- return false;
- }
- return $this->statCache[$name]['readable'];
- }
- public function is_writeable($path){
- $this->connect();
- $parent=dirname($path);
- $name=substr($path,strlen($parent)+1);
- $this->cacheDir($parent);
- if(!isset($this->statCache[$name])){
- return false;
- }
- return $this->statCache[$name]['writeable'];
- }
- public function file_exists($path){
- $this->connect();
- $parent=dirname($path);
- $name=substr($path,strlen($parent)+1);
- $this->cacheDir($parent);
- return isset($this->statCache[$name]);
- }
- public function readfile($path){
- $this->connect();
- $parent=dirname($path);
- $name=substr($path,strlen($parent)+1);
- $file=$this->remote->getFile($parent,$name);
- readfile($file);
- unlink($file);
- }
- public function filectime($path){
- $this->connect();
- $parent=dirname($path);
- $name=substr($path,strlen($parent)+1);
- $this->cacheDir($parent);
- if(!isset($this->statCache[$name])){
- return false;
- }
- return $this->statCache[$name]['ctime'];
- }
- public function filemtime($path){
- $this->connect();
- $parent=dirname($path);
- $name=substr($path,strlen($parent)+1);
- $this->cacheDir($parent);
- if(!isset($this->statCache[$name])){
- return false;
- }
- return $this->statCache[$name]['mtime'];
- }
- public function fileatime($path){
- $this->connect();
- $parent=dirname($path);
- $name=substr($path,strlen($parent)+1);
- $this->cacheDir($parent);
- if(!isset($this->statCache[$name])){
- return false;
- }
- return $this->statCache[$name]['atime'];
- }
- public function file_get_contents($path){
- $this->connect();
- $parent=dirname($path);
- $name=substr($path,strlen($parent)+1);
- $file=$this->remote->getFile($parent,$name);
- file_get_contents($file);
- unlink($file);
- }
- public function file_put_contents($path,$data){
- $this->connect();
- $parent=dirname($path);
- $name=substr($path,strlen($parent)+1);
- $file=$this->remote->getFile($parent,$name);
- $file=tempnam(sys_get_temp_dir(),'oc_');
- file_put_contents($file,$data);
- if($return=$this->remote->sendTmpFile($file,$parent,$name)){
- $this->notifyObservers($path,OC_FILEACTION_WRITE);
- }
- }
- public function unlink($path){
- $this->connect();
- $parent=dirname($path);
- $name=substr($path,strlen($parent)+1);
- if($return=$this->remote->delete($paren,$name)){
- $this->notifyObservers($path,OC_FILEACTION_DELETE);
- }
- return $return;
- }
- public function rename($path1,$path2){
- $this->connect();
- $parent1=dirname($path1);
- $name1=substr($path1,strlen($parent1)+1);
- $parent2=dirname($path2);
- $name2=substr($path2,strlen($parent2)+1);
- if($return=$this->remote->move($parent1,$name1,$parent2,$name2)){
- $this->notifyObservers($path1.'->'.$path2,OC_FILEACTION_RENAME);
- }
- return $return;
- }
- public function copy($path1,$path2){
- $this->connect();
- $parent1=dirname($path1);
- $name1=substr($path1,strlen($parent1)+1);
- $parent2=dirname($path2);
- $name2=substr($path2,strlen($parent2)+1);
- if($return=$this->copy->rename($parent1,$name1,$parent2,$name2)){
- $this->notifyObservers($path1.'->'.$path2,OC_FILEACTION_RENAME);
- }
- return $return;
- }
- public function fopen($path,$mode){
- $this->connect();
- $changed=false;
- $parent=dirname($path);
- $name=substr($path,strlen($parent)+1);
- $file=$this->remote->getFile($parent,$name);
- if($return=fopen($file,$mode)){
- switch($mode){
- case 'r':
- $this->notifyObservers($path,OC_FILEACTION_READ);
- break;
- case 'r+':
- case 'w+':
- case 'x+':
- case 'a+':
- $this->notifyObservers($path,OC_FILEACTION_READ | OC_FILEACTION_WRITE);
- $this->changed[]=array('dir'=>$parent,'file'=>$name,'tmp'=>$file);
- break;
- case 'w':
- case 'x':
- case 'a':
- $this->notifyObservers($path,OC_FILEACTION_WRITE);
- $this->changed[]=array('dir'=>$parent,'file'=>$name,'tmp'=>$file);
- break;
- }
- }
- return $return;
- }
-
- public function getMimeType($path){
- $this->connect();
- $parent=dirname($path);
- $name=substr($path,strlen($parent)+1);
- if(substr($name,0,1)=='/'){
- $name=substr($name,1);
- }
- $this->cacheDir($parent);
- if(!isset($this->statCache[$name])){
- return false;
- }
- return $this->statCache[$name]['mime'];
- }
-
- public function toTmpFile($path){
- $this->connect();
- $parent=dirname($path);
- $name=substr($path,strlen($parent)+1);
- if(substr($name,0,1)=='/'){
- $name=substr($name,1);
- }
- $filename=$this->remote->getFile($parent,$name);
- if($filename){
- $this->notifyObservers($path,OC_FILEACTION_READ);
- return $filename;
- }else{
- return false;
- }
- }
-
- public function fromTmpFile($tmpFile,$path){
- $this->connect();
- $parent=dirname($path);
- $name=substr($path,strlen($parent)+1);
- if($this->remote->sendTmpFile($tmpFile,$parent,$name)){
- $this->notifyObservers($path,OC_FILEACTION_CREATE);
- return true;
- }else{
- return false;
- }
- }
-
- public function delTree($dir) {
- $this->connect();
- $parent=dirname($dir);
- $name=substr($dir,strlen($parent)+1);
- $return=$this->remote->delete($parent,$name);
- if($return=rmdir($dir)){
- $this->notifyObservers($dir,OC_FILEACTION_DELETE);
- }
- return $return;
- }
-
- public function find($path){
- return $this->getTree($path);
- }
-
- public function getTree($dir) {
- $this->connect();
- if($return=$this->remote->getTree($dir)){
- $this->notifyObservers($dir,OC_FILEACTION_READ);
- }
- return $return;
- }
-
- public function __destruct(){
- foreach($this->changed as $changed){
- $this->remote->sendTmpFile($changed['tmp'],$changed['dir'],$changed['file']);
- }
- }
-}
-
-?>
diff --git a/inc/lib_user.php b/inc/lib_user.php
deleted file mode 100644
index 5b48e0abf2f..00000000000
--- a/inc/lib_user.php
+++ /dev/null
@@ -1,241 +0,0 @@
-<?php
-
-/**
-* ownCloud
-*
-* @author Frank Karlitschek
-* @copyright 2010 Frank Karlitschek karlitschek@kde.org
-*
-* This library is free software; you can redistribute it and/or
-* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
-* License as published by the Free Software Foundation; either
-* version 3 of the License, or 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 AFFERO 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, see <http://www.gnu.org/licenses/>.
-*
-*/
-
-
-
-
-if ( !$CONFIG_INSTALLED ) {
- $_SESSION['user_id'] = false;
- $_SESSION['username'] = '';
- $_SESSION['username_clean'] = '';
-}
-
-//cache the userid's an groupid's
-if ( !isset($_SESSION['user_id_cache']) ) {
- $_SESSION['user_id_cache'] = array();
-}
-if ( !isset($_SESSION['group_id_cache']) ) {
- $_SESSION['group_id_cache'] = array();
-}
-
-
-
-
-/**
- * Class for User Management
- *
- */
-class OC_USER {
-
- // The backend used for user management
- private static $_backend;
-
- /**
- * Set the User Authentication Module
- *
- * @param string $backend The backend to use for user managment
- */
- public static function setBackend($backend='database') {
- if ( (null === $backend) OR (!is_string($backend)) ) {
- $backend = 'database';
- }
-
- switch ( $backend ) {
- case 'database':
- case 'mysql':
- case 'sqlite':
- oc_require_once('inc/User/database.php');
- self::$_backend = new OC_USER_DATABASE();
- break;
- default:
- $className = 'OC_USER_' . strToUpper($backend);
- self::$_backend = new $className();
- break;
- }
- }
-
- /**
- * Check if the login button is pressed and log the user in
- *
- */
- public static function loginListener() {
- return self::$_backend->loginListener();
- }
-
- /**
- * Try to create a new user
- *
- * @param string $username The username of the user to create
- * @param string $password The password of the new user
- */
- public static function createUser($username, $password) {
- return self::$_backend->createUser($username, $password);
- }
-
- /**
- * Try to login a user
- *
- * @param string $username The username of the user to log in
- * @param string $password The password of the user
- */
- public static function login($username, $password) {
- return self::$_backend->login($username, $password);
- }
-
- /**
- * Check if the logout button is pressed and logout the user
- *
- */
- public static function logoutListener() {
- return self::$_backend->logoutListener();
- }
-
- /**
- * Check if the user is logged in
- *
- */
- public static function isLoggedIn() {
- return self::$_backend->isLoggedIn();
- }
-
- /**
- * Try to create a new group
- *
- * @param string $groupName The name of the group to create
- */
- public static function createGroup($groupName) {
- return self::$_backend->createGroup($groupName);
- }
-
- /**
- * Get the ID of a user
- *
- * @param string $username Name of the user to find the ID
- * @param boolean $noCache If false the cache is used to find the ID
- */
- public static function getUserId($username, $noCache=false) {
- return self::$_backend->getUserId($username, $noCache);
- }
-
- /**
- * Get the ID of a group
- *
- * @param string $groupName Name of the group to find the ID
- * @param boolean $noCache If false the cache is used to find the ID
- */
- public static function getGroupId($groupName, $noCache=false) {
- return self::$_backend->getGroupId($groupName, $noCache);
- }
-
- /**
- * Get the name of a group
- *
- * @param string $groupId ID of the group
- * @param boolean $noCache If false the cache is used to find the name of the group
- */
- public static function getGroupName($groupId, $noCache=false) {
- return self::$_backend->getGroupName($groupId, $noCache);
- }
-
- /**
- * Check if a user belongs to a group
- *
- * @param string $username Name of the user to check
- * @param string $groupName Name of the group
- */
- public static function inGroup($username, $groupName) {
- return self::$_backend->inGroup($username, $groupName);
- }
-
- /**
- * Add a user to a group
- *
- * @param string $username Name of the user to add to group
- * @param string $groupName Name of the group in which add the user
- */
- public static function addToGroup($username, $groupName) {
- return self::$_backend->addToGroup($username, $groupName);
- }
-
- /**
- * Remove a user from a group
- *
- * @param string $username Name of the user to remove from group
- * @param string $groupName Name of the group from which remove the user
- */
- public static function removeFromGroup($username,$groupName){
- return self::$_backend->removeFromGroup($username, $groupName);
- }
-
- /**
- * Generate a random password
- */
- public static function generatePassword() {
- return substr(md5(uniqId().time()),0,10);
- }
-
- /**
- * Get all groups the user belongs to
- *
- * @param string $username Name of the user
- */
- public static function getUserGroups($username) {
- return self::$_backend->getUserGroups($username);
- }
-
- /**
- * Set the password of a user
- *
- * @param string $username User who password will be changed
- * @param string $password The new password for the user
- */
- public static function setPassword($username, $password) {
- return self::$_backend->setPassword($username, $password);
- }
-
- /**
- * Check if the password of the user is correct
- *
- * @param string $username Name of the user
- * @param string $password Password of the user
- */
- public static function checkPassword($username, $password) {
- return self::$_backend->checkPassword($username, $password);
- }
-
- /**
- * get a list of all users
- *
- */
- public static function getUsers() {
- return self::$_backend->getUsers();
- }
-
- /**
- * get a list of all groups
- *
- */
- public static function getGroups() {
- return self::$_backend->getGroups();
- }
-}
diff --git a/inc/package.dtd b/inc/package.dtd
deleted file mode 100644
index 6092e8f4ce3..00000000000
--- a/inc/package.dtd
+++ /dev/null
@@ -1,110 +0,0 @@
-<!--
- $Id: package.dtd,v 1.35.4.1 2004/12/31 18:43:21 cellog Exp $
-
- This is the PEAR package description, version 1.0.
- It should be used with the informal public identifier:
-
- "-//PHP Group//DTD PEAR Package 1.0//EN//XML"
-
- Copyright (c) 1997-2004 The PHP Group
-
- This source file is subject to version 3.0 of the PHP license,
- that is bundled with this package in the file LICENSE, and is
- available at through the world-wide-web at
- http://www.php.net/license/3_0.txt.
- If you did not receive a copy of the PHP license and are unable to
- obtain it through the world-wide-web, please send a note to
- license@php.net so we can mail you a copy immediately.
-
- Authors:
- Stig S. Bakken <ssb@php.net>
-
- -->
-<!ENTITY % NUMBER "CDATA">
-<!ELEMENT package (name|summary|description|license|maintainers|release|changelog)+>
-<!ATTLIST package type (source|binary|empty) "empty"
- version CDATA #REQUIRED>
-
-<!ELEMENT name (#PCDATA)>
-
-<!ELEMENT summary (#PCDATA)>
-
-<!ELEMENT description (#PCDATA)>
-
-<!ELEMENT license (#PCDATA)>
-
-<!ELEMENT maintainers (maintainer)+>
-
-<!ELEMENT maintainer (user|role|name|email)+>
-
-<!ELEMENT user (#PCDATA)>
-
-<!ELEMENT role (#PCDATA)>
-
-<!ELEMENT email (#PCDATA)>
-
-<!ELEMENT changelog (release)+>
-
-<!ELEMENT release (version|license|state|date|notes|filelist|deps|provides|script|configureoptions)+>
-
-<!ELEMENT version (#PCDATA)>
-
-<!ELEMENT state (#PCDATA)>
-
-<!ELEMENT date (#PCDATA)>
-
-<!ELEMENT notes (#PCDATA)>
-
-<!ELEMENT filelist (dir|file)+>
-
-<!ELEMENT dir (dir|file)+>
-<!ATTLIST dir name CDATA #REQUIRED
- baseinstalldir CDATA #IMPLIED>
-
-<!ELEMENT file (replace*)>
-<!ATTLIST file role (php|ext|src|test|doc|data|script) 'php'
- debug (na|on|off) 'na'
- zts (na|on|off) 'na'
- phpapi %NUMBER; #IMPLIED
- zendapi %NUMBER; #IMPLIED
- format CDATA #IMPLIED
- baseinstalldir CDATA #IMPLIED
- platform CDATA #IMPLIED
- md5sum CDATA #IMPLIED
- name CDATA #REQUIRED
- install-as CDATA #IMPLIED>
-
-<!ELEMENT replace EMPTY>
-<!ATTLIST replace from CDATA #REQUIRED
- to CDATA #REQUIRED
- type CDATA #REQUIRED>
-
-<!ELEMENT deps (dep)+>
-
-<!ELEMENT dep (#PCDATA)>
-<!ATTLIST dep
- optional (yes|no) 'no'
- type (pkg|ext|php|prog|ldlib|rtlib|os|websrv|sapi|zend) #REQUIRED
- rel (has|eq|lt|le|gt|ge) 'has'
- version CDATA #IMPLIED>
-
-<!ELEMENT provides (#PCDATA)>
-<!ATTLIST provides
- type (ext|prog|class|function|feature|api) #REQUIRED
- name CDATA #REQUIRED
- extends CDATA #IMPLIED>
-
-<!ELEMENT script (#PCDATA)>
-<!ATTLIST script
- phase (pre-install |post-install |
- pre-uninstall|post-uninstall|
- pre-build |post-build |
- pre-setup |post-setup ) #REQUIRED>
-
-<!ELEMENT configureoptions (configureoption*)>
-
-<!ELEMENT configureoption EMPTY>
-<!ATTLIST configureoption
- name CDATA #REQUIRED
- default CDATA #IMPLIED
- prompt CDATA #REQUIRED>
diff --git a/inc/packages/Archive_Tar.xml b/inc/packages/Archive_Tar.xml
deleted file mode 100644
index ba748a18afd..00000000000
--- a/inc/packages/Archive_Tar.xml
+++ /dev/null
@@ -1,122 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1" ?>
-<!DOCTYPE package SYSTEM "http://pear.php.net/dtd/package-1.0">
-<package version="1.0">
- <name>Archive_Tar</name>
- <summary>Tar file management class</summary>
- <description>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.</description>
- <maintainers>
- <maintainer>
- <user>vblavet</user>
- <name>Vincent Blavet</name>
- <email>vincent@phpconcept.net</email>
- <role>lead</role>
- </maintainer>
- <maintainer>
- <user>ssb</user>
- <name>Stig Bakken</name>
- <email>stig@php.net</email>
- <role>helper</role>
- </maintainer>
- </maintainers>
- <release>
- <version>1.3.1</version>
- <date>2005-03-17</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>Correct Bug #3855</notes>
- <provides type="class" name="Archive_Tar" />
- <provides type="function" name="Archive_Tar::create" />
- <provides type="function" name="Archive_Tar::add" />
- <provides type="function" name="Archive_Tar::extract" />
- <provides type="function" name="Archive_Tar::listContent" />
- <provides type="function" name="Archive_Tar::createModify" />
- <provides type="function" name="Archive_Tar::addModify" />
- <provides type="function" name="Archive_Tar::addString" />
- <provides type="function" name="Archive_Tar::extractModify" />
- <provides type="function" name="Archive_Tar::extractInString" />
- <provides type="function" name="Archive_Tar::extractList" />
- <provides type="function" name="Archive_Tar::setAttribute" />
- <filelist>
- <file role="php" baseinstalldir="/" md5sum="5a9ef212cbfc1789c875870b3a4db6e5" name="Archive/Tar.php"/>
- <file role="doc" baseinstalldir="/" md5sum="ae640b797078a6542ea0d236f28efffb" name="docs/Archive_Tar.txt"/>
- </filelist>
- </release>
- <changelog>
- <release>
- <version>1.3.0</version>
- <date>2005-03-06</date>
- <state>stable</state>
- <notes>Bugs correction (2475, 2488, 2135, 2176)
-
-</notes>
- </release>
- <release>
- <version>1.2</version>
- <date>2004-05-08</date>
- <state>stable</state>
- <notes>Add support for other separator than the space char and bug
- correction
-
-</notes>
- </release>
- <release>
- <version>1.1</version>
- <date>2003-05-28</date>
- <state>stable</state>
- <notes>* Add support for BZ2 compression
-* Add support for add and extract without using temporary files : methods addString() and extractInString()
-</notes>
- </release>
- <release>
- <version>1.0</version>
- <date>2003-01-24</date>
- <state>stable</state>
- <notes>Change status to stable
-
-</notes>
- </release>
- <release>
- <version>0.10-b1</version>
- <date>2003-01-08</date>
- <state>beta</state>
- <notes>Add support for long filenames (greater than 99 characters)
-
-</notes>
- </release>
- <release>
- <version>0.9</version>
- <date>2002-05-27</date>
- <state>stable</state>
- <notes>Auto-detect gzip'ed files
-
-</notes>
- </release>
- <release>
- <version>0.4</version>
- <date>2002-05-20</date>
- <state>stable</state>
- <notes>Windows bugfix: use forward slashes inside archives
-
-</notes>
- </release>
- <release>
- <version>0.2</version>
- <date>2002-02-18</date>
- <state>stable</state>
- <notes>From initial commit to stable
-
-</notes>
- </release>
- <release>
- <version>0.3</version>
- <date>2002-04-13</date>
- <state>stable</state>
- <notes>Windows bugfix: used wrong directory separators
-
-</notes>
- </release>
- </changelog>
-</package>
diff --git a/inc/packages/Console_Getopt.xml b/inc/packages/Console_Getopt.xml
deleted file mode 100644
index 221919d9767..00000000000
--- a/inc/packages/Console_Getopt.xml
+++ /dev/null
@@ -1,69 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1" ?>
-<!DOCTYPE package SYSTEM "http://pear.php.net/dtd/package-1.0">
-<package version="1.0">
- <name>Console_Getopt</name>
- <summary>Command-line option parser</summary>
- <description>This is a PHP implementation of &quot;getopt&quot; supporting both
-short and long options.</description>
- <maintainers>
- <maintainer>
- <user>andrei</user>
- <name>Andrei Zmievski</name>
- <email>andrei@php.net</email>
- <role>lead</role>
- </maintainer>
- <maintainer>
- <user>ssb</user>
- <name>Stig Bakken</name>
- <email>stig@php.net</email>
- <role>developer</role>
- </maintainer>
- </maintainers>
- <release>
- <version>1.2</version>
- <date>2003-12-11</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>Fix to preserve BC with 1.0 and allow correct behaviour for new users</notes>
- <provides type="class" name="Console_Getopt" />
- <provides type="function" name="Console_Getopt::getopt2" />
- <provides type="function" name="Console_Getopt::getopt" />
- <provides type="function" name="Console_Getopt::doGetopt" />
- <provides type="function" name="Console_Getopt::readPHPArgv" />
- <filelist>
- <file role="php" md5sum="add0781a1cae0b3daf5e8521b8a954cc" name="Console/Getopt.php"/>
- </filelist>
- </release>
- <changelog>
- <release>
- <version>1.0</version>
- <date>2002-09-13</date>
- <state>stable</state>
- <notes>Stable release
-</notes>
- </release>
- <release>
- <version>0.11</version>
- <date>2002-05-26</date>
- <state>beta</state>
- <notes>POSIX getopt compatibility fix: treat first element of args
- array as command name
-
-</notes>
- </release>
- <release>
- <version>0.10</version>
- <date>2002-05-12</date>
- <state>beta</state>
- <notes>Packaging fix
-</notes>
- </release>
- <release>
- <version>0.9</version>
- <date>2002-05-12</date>
- <state>beta</state>
- <notes>Initial release
-</notes>
- </release>
- </changelog>
-</package>
diff --git a/inc/packages/DB.xml b/inc/packages/DB.xml
deleted file mode 100644
index d8aaec82c27..00000000000
--- a/inc/packages/DB.xml
+++ /dev/null
@@ -1,348 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1" ?>
-<!DOCTYPE package SYSTEM "http://pear.php.net/dtd/package-1.0">
-<package version="1.0" packagerversion="1.4.0a10">
- <name>DB</name>
- <summary>Database Abstraction Layer</summary>
- <description>DB is a database abstraction layer providing:
-* an OO-style query API
-* portability features that make programs written for one DBMS work with other DBMS's
-* a DSN (data source name) format for specifying database servers
-* prepare/execute (bind) emulation for databases that don't support it natively
-* a result object for each query response
-* portable error codes
-* sequence emulation
-* sequential and non-sequential row fetching as well as bulk fetching
-* formats fetched rows as associative arrays, ordered arrays or objects
-* row limit support
-* transactions support
-* table information interface
-* DocBook and phpDocumentor API documentation
-
-DB layers itself on top of PHP's existing
-database extensions.
-
-Drivers for the following extensions pass
-the complete test suite and provide
-interchangeability when all of DB's
-portability options are enabled:
-
- fbsql, ibase, informix, msql, mssql,
- mysql, mysqli, oci8, odbc, pgsql,
- sqlite and sybase.
-
-There is also a driver for the dbase
-extension, but it can't be used
-interchangeably because dbase doesn't
-support many standard DBMS features.
-
-DB is compatible with both PHP 4 and PHP 5.
- </description>
- <maintainers>
- <maintainer>
- <user>ssb</user>
- <name>Stig Bakken</name>
- <email>stig@php.net</email>
- <role>developer</role>
- </maintainer>
- <maintainer>
- <user>cox</user>
- <name>Tomas V.V.Cox</name>
- <email>cox@idecnet.com</email>
- <role>developer</role>
- </maintainer>
- <maintainer>
- <user>danielc</user>
- <name>Daniel Convissor</name>
- <email>danielc@php.net</email>
- <role>lead</role>
- </maintainer>
- <maintainer>
- <user>lsmith</user>
- <name>Lukas Kahwe Smith</name>
- <email>smith@backendmedia.com</email>
- <role>helper</role>
- </maintainer>
- </maintainers>
- <release>
- <version>1.7.6</version>
- <date>2005-04-11</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>common:
-* Fix the docblocks regarding DB_FETCHMODE_FLIPPED. Bug 4027.
-
-oic8:
-* Provide BC hack for those connecting to oci8 using 'hostspec' instead of 'database'. Bug 4104.
- </notes>
- <deps>
- <dep type="php" rel="ge" version="4.2.0"/>
- <dep type="pkg" rel="ge" version="1.0b1">PEAR</dep>
- </deps>
- <provides type="class" name="DB" />
- <provides type="function" name="DB::factory" />
- <provides type="class" name="DB_common" extends="PEAR" />
- <provides type="function" name="DB_common::toString" />
- <provides type="function" name="DB_common::quoteString" />
- <provides type="function" name="DB_common::quote" />
- <provides type="function" name="DB_common::quoteIdentifier" />
- <provides type="function" name="DB_common::quoteSmart" />
- <provides type="function" name="DB_common::escapeSimple" />
- <provides type="function" name="DB_common::provides" />
- <provides type="function" name="DB_common::setFetchMode" />
- <provides type="function" name="DB_common::setOption" />
- <provides type="class" name="DB_dbase" extends="DB_common" />
- <provides type="function" name="DB_dbase::connect" />
- <provides type="function" name="DB_dbase::disconnect" />
- <provides type="function" name="DB_dbase::query" />
- <provides type="function" name="DB_dbase::fetchInto" />
- <provides type="function" name="DB_dbase::numCols" />
- <provides type="function" name="DB_dbase::numRows" />
- <provides type="function" name="DB_dbase::quoteSmart" />
- <provides type="function" name="DB_dbase::tableInfo" />
- <provides type="class" name="DB_fbsql" extends="DB_common" />
- <provides type="function" name="DB_fbsql::connect" />
- <provides type="function" name="DB_fbsql::disconnect" />
- <provides type="function" name="DB_fbsql::simpleQuery" />
- <provides type="class" name="DB_ibase" extends="DB_common" />
- <provides type="function" name="DB_ibase::connect" />
- <provides type="function" name="DB_ibase::disconnect" />
- <provides type="function" name="DB_ibase::simpleQuery" />
- <provides type="function" name="DB_ibase::modifyLimitQuery" />
- <provides type="class" name="DB_ifx" extends="DB_common" />
- <provides type="function" name="DB_ifx::connect" />
- <provides type="function" name="DB_ifx::disconnect" />
- <provides type="function" name="DB_ifx::simpleQuery" />
- <provides type="function" name="DB_ifx::nextResult" />
- <provides type="function" name="DB_ifx::affectedRows" />
- <provides type="function" name="DB_ifx::fetchInto" />
- <provides type="function" name="DB_ifx::numCols" />
- <provides type="function" name="DB_ifx::freeResult" />
- <provides type="function" name="DB_ifx::autoCommit" />
- <provides type="function" name="DB_ifx::commit" />
- <provides type="function" name="DB_ifx::rollback" />
- <provides type="function" name="DB_ifx::ifxRaiseError" />
- <provides type="function" name="DB_ifx::errorNative" />
- <provides type="function" name="DB_ifx::errorCode" />
- <provides type="function" name="DB_ifx::tableInfo" />
- <provides type="class" name="DB_msql" extends="DB_common" />
- <provides type="function" name="DB_msql::connect" />
- <provides type="function" name="DB_msql::disconnect" />
- <provides type="function" name="DB_msql::simpleQuery" />
- <provides type="function" name="DB_msql::nextResult" />
- <provides type="function" name="DB_msql::fetchInto" />
- <provides type="function" name="DB_msql::freeResult" />
- <provides type="function" name="DB_msql::numCols" />
- <provides type="function" name="DB_msql::numRows" />
- <provides type="function" name="DB_msql::affectedRows" />
- <provides type="function" name="DB_msql::nextId" />
- <provides type="class" name="DB_mssql" extends="DB_common" />
- <provides type="function" name="DB_mssql::connect" />
- <provides type="function" name="DB_mssql::disconnect" />
- <provides type="function" name="DB_mssql::simpleQuery" />
- <provides type="function" name="DB_mssql::nextResult" />
- <provides type="function" name="DB_mssql::fetchInto" />
- <provides type="function" name="DB_mssql::freeResult" />
- <provides type="function" name="DB_mssql::numCols" />
- <provides type="function" name="DB_mssql::numRows" />
- <provides type="function" name="DB_mssql::autoCommit" />
- <provides type="function" name="DB_mssql::commit" />
- <provides type="function" name="DB_mssql::rollback" />
- <provides type="function" name="DB_mssql::affectedRows" />
- <provides type="function" name="DB_mssql::nextId" />
- <provides type="class" name="DB_mysql" extends="DB_common" />
- <provides type="function" name="DB_mysql::connect" />
- <provides type="function" name="DB_mysql::disconnect" />
- <provides type="function" name="DB_mysql::simpleQuery" />
- <provides type="function" name="DB_mysql::nextResult" />
- <provides type="function" name="DB_mysql::fetchInto" />
- <provides type="function" name="DB_mysql::freeResult" />
- <provides type="function" name="DB_mysql::numCols" />
- <provides type="function" name="DB_mysql::numRows" />
- <provides type="function" name="DB_mysql::autoCommit" />
- <provides type="function" name="DB_mysql::commit" />
- <provides type="function" name="DB_mysql::rollback" />
- <provides type="function" name="DB_mysql::affectedRows" />
- <provides type="function" name="DB_mysql::nextId" />
- <provides type="class" name="DB_mysqli" extends="DB_common" />
- <provides type="function" name="DB_mysqli::connect" />
- <provides type="function" name="DB_mysqli::disconnect" />
- <provides type="function" name="DB_mysqli::simpleQuery" />
- <provides type="function" name="DB_mysqli::nextResult" />
- <provides type="function" name="DB_mysqli::fetchInto" />
- <provides type="function" name="DB_mysqli::freeResult" />
- <provides type="function" name="DB_mysqli::numCols" />
- <provides type="function" name="DB_mysqli::numRows" />
- <provides type="function" name="DB_mysqli::autoCommit" />
- <provides type="function" name="DB_mysqli::commit" />
- <provides type="function" name="DB_mysqli::rollback" />
- <provides type="function" name="DB_mysqli::affectedRows" />
- <provides type="function" name="DB_mysqli::nextId" />
- <provides type="class" name="DB_oci8" extends="DB_common" />
- <provides type="function" name="DB_oci8::connect" />
- <provides type="function" name="DB_oci8::disconnect" />
- <provides type="function" name="DB_oci8::simpleQuery" />
- <provides type="function" name="DB_oci8::nextResult" />
- <provides type="function" name="DB_oci8::fetchInto" />
- <provides type="function" name="DB_oci8::freeResult" />
- <provides type="function" name="DB_oci8::freePrepared" />
- <provides type="function" name="DB_oci8::numRows" />
- <provides type="function" name="DB_oci8::numCols" />
- <provides type="function" name="DB_oci8::prepare" />
- <provides type="function" name="DB_oci8::execute" />
- <provides type="class" name="DB_odbc" extends="DB_common" />
- <provides type="function" name="DB_odbc::connect" />
- <provides type="function" name="DB_odbc::disconnect" />
- <provides type="function" name="DB_odbc::simpleQuery" />
- <provides type="function" name="DB_odbc::nextResult" />
- <provides type="function" name="DB_odbc::fetchInto" />
- <provides type="function" name="DB_odbc::freeResult" />
- <provides type="function" name="DB_odbc::numCols" />
- <provides type="function" name="DB_odbc::affectedRows" />
- <provides type="function" name="DB_odbc::numRows" />
- <provides type="function" name="DB_odbc::quoteIdentifier" />
- <provides type="function" name="DB_odbc::quote" />
- <provides type="function" name="DB_odbc::nextId" />
- <provides type="class" name="DB_pgsql" extends="DB_common" />
- <provides type="function" name="DB_pgsql::connect" />
- <provides type="function" name="DB_pgsql::disconnect" />
- <provides type="function" name="DB_pgsql::simpleQuery" />
- <provides type="function" name="DB_pgsql::nextResult" />
- <provides type="function" name="DB_pgsql::fetchInto" />
- <provides type="function" name="DB_pgsql::freeResult" />
- <provides type="function" name="DB_pgsql::quote" />
- <provides type="function" name="DB_pgsql::quoteSmart" />
- <provides type="function" name="DB_pgsql::escapeSimple" />
- <provides type="function" name="DB_pgsql::numCols" />
- <provides type="function" name="DB_pgsql::numRows" />
- <provides type="function" name="DB_pgsql::autoCommit" />
- <provides type="function" name="DB_pgsql::commit" />
- <provides type="function" name="DB_pgsql::rollback" />
- <provides type="function" name="DB_pgsql::affectedRows" />
- <provides type="function" name="DB_pgsql::nextId" />
- <provides type="class" name="DB_sybase" extends="DB_common" />
- <provides type="function" name="DB_sybase::connect" />
- <provides type="function" name="DB_sybase::disconnect" />
- <provides type="function" name="DB_sybase::simpleQuery" />
- <provides type="function" name="DB_sybase::nextResult" />
- <provides type="function" name="DB_sybase::fetchInto" />
- <provides type="function" name="DB_sybase::freeResult" />
- <provides type="function" name="DB_sybase::numCols" />
- <provides type="function" name="DB_sybase::numRows" />
- <provides type="function" name="DB_sybase::affectedRows" />
- <provides type="function" name="DB_sybase::nextId" />
- <provides type="class" name="DB_storage" extends="PEAR" />
- <provides type="function" name="DB_storage::setup" />
- <provides type="function" name="DB_storage::insert" />
- <provides type="class" name="DB_sqlite" extends="DB_common" />
- <provides type="function" name="DB_sqlite::connect" />
- <provides type="function" name="DB_sqlite::disconnect" />
- <provides type="function" name="DB_sqlite::simpleQuery" />
- <provides type="function" name="DB_sqlite::nextResult" />
- <provides type="function" name="DB_sqlite::fetchInto" />
- <provides type="function" name="DB_sqlite::freeResult" />
- <provides type="function" name="DB_sqlite::numCols" />
- <provides type="function" name="DB_sqlite::numRows" />
- <provides type="function" name="DB_sqlite::affectedRows" />
- <provides type="function" name="DB_sqlite::dropSequence" />
- <provides type="function" name="DB_sqlite::createSequence" />
- <filelist>
- <file role="php" baseinstalldir="/" md5sum="ea7037643a27c7d1eb0f818efcbf35ee" name="DB.php">
- <replace from="@package_version@" to="version" type="package-info"/>
- </file>
- <file role="php" md5sum="05dadd359cf7682e73fe7bc41cc4742c" name="DB/common.php">
- <replace from="@package_version@" to="version" type="package-info"/>
- </file>
- <file role="php" md5sum="921d3cde2d8295ca978caae22ab48761" name="DB/dbase.php">
- <replace from="@package_version@" to="version" type="package-info"/>
- </file>
- <file role="php" md5sum="830899b5b2ee3dbc93a0ccaab184c153" name="DB/fbsql.php">
- <replace from="@package_version@" to="version" type="package-info"/>
- </file>
- <file role="php" md5sum="64376b17c209ebc78745e7a532ccdd86" name="DB/ibase.php">
- <replace from="@package_version@" to="version" type="package-info"/>
- </file>
- <file role="php" md5sum="a27b90a13bfc9580d3954ca420d87c01" name="DB/ifx.php">
- <replace from="@package_version@" to="version" type="package-info"/>
- </file>
- <file role="php" md5sum="0fc78181842e1b47893a0be27f680bd9" name="DB/msql.php">
- <replace from="@package_version@" to="version" type="package-info"/>
- </file>
- <file role="php" md5sum="c7f21c8c526d7cf698095d594acc0c7c" name="DB/mssql.php">
- <replace from="@package_version@" to="version" type="package-info"/>
- </file>
- <file role="php" md5sum="3838d8d75ce62c730814bdb87799e79c" name="DB/mysql.php">
- <replace from="@package_version@" to="version" type="package-info"/>
- </file>
- <file role="php" md5sum="908762bfcf17b2195a61ec9219cbf10e" name="DB/mysqli.php">
- <replace from="@package_version@" to="version" type="package-info"/>
- </file>
- <file role="php" md5sum="dc42cd00866890e91f9235938a9acf87" name="DB/oci8.php">
- <replace from="@package_version@" to="version" type="package-info"/>
- </file>
- <file role="php" md5sum="8d6d0c54cfcec2cf46eace182886d8aa" name="DB/odbc.php">
- <replace from="@package_version@" to="version" type="package-info"/>
- </file>
- <file role="php" md5sum="7018bbfb1cd7f5e283688747d83fe18b" name="DB/pgsql.php">
- <replace from="@package_version@" to="version" type="package-info"/>
- </file>
- <file role="php" md5sum="fdc093d71420407c0034206c4068d332" name="DB/sybase.php">
- <replace from="@package_version@" to="version" type="package-info"/>
- </file>
- <file role="php" md5sum="0a920908d899cf8ce620449207de5e89" name="DB/storage.php">
- <replace from="@package_version@" to="version" type="package-info"/>
- </file>
- <file role="php" md5sum="7726118beb7c038e531783542b816a33" name="DB/sqlite.php">
- <replace from="@package_version@" to="version" type="package-info"/>
- </file>
- <file role="doc" md5sum="651a644b6f3495fc39279d75b8099372" name="doc/IDEAS"/>
- <file role="doc" md5sum="8c5779871e07720a032615177403b691" name="doc/MAINTAINERS"/>
- <file role="doc" md5sum="30bc4ceeccd51413ab81fa98c1fb9aa8" name="doc/STATUS"/>
- <file role="doc" md5sum="31f276d6ff710a1f048c50cd533ffe5c" name="doc/TESTERS"/>
- <file role="test" md5sum="2e7f987503b8b5e2a7fc4c3c30e79c13" name="tests/db_error.phpt"/>
- <file role="test" md5sum="ca733f1d806681c6522ab993c999b12f" name="tests/db_parsedsn.phpt"/>
- <file role="test" md5sum="79e88e6db0c25ca1ee5e2aac35a24d6c" name="tests/db_factory.phpt"/>
- <file role="test" md5sum="859cffe6ae0f54122485879805629261" name="tests/db_ismanip.phpt"/>
- <file role="test" md5sum="5f5068a8a1a3742ff0810be61b57288d" name="tests/db_error2.phpt"/>
- <file role="test" md5sum="0ebba9b5012622df59dc2066e884cce1" name="tests/errors.inc"/>
- <file role="test" md5sum="3732edbe1c159b16d82c0cefb23fb283" name="tests/fetchmode_object.inc"/>
- <file role="test" md5sum="2cdad3e62c059414ddab8a410781458c" name="tests/fetchmodes.inc"/>
- <file role="test" md5sum="f3d663fdf145e5bb3797c96b3d0dcf47" name="tests/include.inc">
- <replace from="@include_path@" to="php_dir" type="pear-config"/>
- </file>
- <file role="test" md5sum="600316395dc9ebe05f8249b4252088e6" name="tests/limit.inc"/>
- <file role="test" md5sum="3abeeb0a61cdd7f4108a647cccb55810" name="tests/numcols.inc"/>
- <file role="test" md5sum="26fb3581b281991838b2dfacf4e86f5d" name="tests/numrows.inc"/>
- <file role="test" md5sum="06f6cd517eb324113c8cedf1c64a1e3e" name="tests/prepexe.inc"/>
- <file role="test" md5sum="aac444f47ed3ad1642013539d99f5757" name="tests/run.cvs"/>
- <file role="test" md5sum="0a3b6c14fb3a8cb6e3cd8ece9736e9eb" name="tests/sequences.inc"/>
- <file role="test" md5sum="8f773eb10ee19145937296dca60d296e" name="tests/simplequery.inc"/>
- <file role="test" md5sum="8b42ffcce8bbe68507f0ed21dab3200c" name="tests/transactions.inc"/>
- <file role="test" md5sum="5f6f6b62f9779b97adf57bdbbcffe450" name="tests/skipif.inc"/>
- <file role="test" md5sum="2cbff4d99f59d9ad71adf0833794f9e5" name="tests/driver/01connect.phpt"/>
- <file role="test" md5sum="0261a7e827ff9581e4aca6dd6b13642e" name="tests/driver/02fetch.phpt"/>
- <file role="test" md5sum="b671efeac9fd34b83309de8413531317" name="tests/driver/03simplequery.phpt"/>
- <file role="test" md5sum="a5ecf473f648022af5dc9fbb2f33e371" name="tests/driver/04numcols.phpt"/>
- <file role="test" md5sum="1ab9a3b8a98c691a222a510eb8134355" name="tests/driver/05sequences.phpt"/>
- <file role="test" md5sum="8d651d2da580619ed5abeaaa9e1f71ad" name="tests/driver/06prepexec.phpt"/>
- <file role="test" md5sum="b2e5ebe28916e63d8502845d58f74d49" name="tests/driver/08affectedrows.phpt"/>
- <file role="test" md5sum="7efee695096e0cf6e243e5590915b6fc" name="tests/driver/09numrows.phpt"/>
- <file role="test" md5sum="b2e481fc6f310db41e249a1e53f353c2" name="tests/driver/10errormap.phpt"/>
- <file role="test" md5sum="f53ca06e8370629e5ab6717bf7bbe2a7" name="tests/driver/11transactions.phpt"/>
- <file role="test" md5sum="7f2d525fc8d2038157a736b64b774811" name="tests/driver/13limit.phpt"/>
- <file role="test" md5sum="13870a67a986287a1dd7b8616538cb90" name="tests/driver/14fetchmode_object.phpt"/>
- <file role="test" md5sum="2cf853766a1c1dc21f0b38988cd5a406" name="tests/driver/15quote.phpt"/>
- <file role="test" md5sum="a7db7211ac1faebce9248ffba535472e" name="tests/driver/16tableinfo.phpt"/>
- <file role="test" md5sum="f796eae81fce16bc2a03cbea5af80b49" name="tests/driver/17query.phpt"/>
- <file role="test" md5sum="8363274c9471e5b8038856ec4b111bea" name="tests/driver/18get.phpt"/>
- <file role="test" md5sum="871bdd4a90291602c206042742922a71" name="tests/driver/19getlistof.phpt"/>
- <file role="test" md5sum="4180a5d038d41a1262d1cc41951f0f3d" name="tests/driver/connect.inc"/>
- <file role="test" md5sum="6f4a4b1e45c94733717a21ef26f388ba" name="tests/driver/mktable.inc"/>
- <file role="test" md5sum="4af9cff841e14f1c94e358346747e7b6" name="tests/driver/multiconnect.php"/>
- <file role="test" md5sum="7023d979e8bcb94a93d48597d864feb3" name="tests/driver/run.cvs"/>
- <file role="test" md5sum="a7ee27ff0a2aacf0ef906eea8569718f" name="tests/driver/setup.inc.cvs">
- <replace from="@include_path@" to="php_dir" type="pear-config"/>
- </file>
- <file role="test" md5sum="5e3ad6fb4ab28735d788396ab80a63b5" name="tests/driver/skipif.inc"/>
- </filelist>
- </release>
-</package>
diff --git a/inc/packages/Log.xml b/inc/packages/Log.xml
deleted file mode 100644
index de16370c8bf..00000000000
--- a/inc/packages/Log.xml
+++ /dev/null
@@ -1,315 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1" ?>
-<!DOCTYPE package SYSTEM "http://pear.php.net/dtd/package-1.0">
-<package version="1.0">
- <name>Log</name>
- <summary>Logging utilities</summary>
- <description>The Log framework provides an abstracted logging system. It supports logging to console, file, syslog, SQL, Sqlite, mail and mcal targets. It also provides a subject - observer mechanism.</description>
- <maintainers>
- <maintainer>
- <user>jon</user>
- <name>Jon Parise</name>
- <email>jon@php.net</email>
- <role>lead</role>
- </maintainer>
- </maintainers>
- <release>
- <version>1.8.7</version>
- <date>2004-12-20</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>The Log package now supports logging arrays with a 'message' key.
-The 'display' handler now preserves line breaks in its output.
-An experimental new handler ('daemon') has been added.</notes>
- <deps>
- <dep type="pkg" rel="has" optional="yes">DB</dep>
- <dep type="ext" rel="has" optional="yes">sqlite</dep>
- <dep type="php" rel="ge" version="4.3.0" optional="no"/>
- </deps>
- <filelist>
- <file role="doc" baseinstalldir="/" name="docs/guide.txt"/>
- <file role="doc" baseinstalldir="/" name="docs/examples/composite.php"/>
- <file role="doc" baseinstalldir="/" name="docs/examples/console.php"/>
- <file role="doc" baseinstalldir="/" name="docs/examples/display.php"/>
- <file role="doc" baseinstalldir="/" name="docs/examples/error_log.php"/>
- <file role="doc" baseinstalldir="/" name="docs/examples/file.php"/>
- <file role="doc" baseinstalldir="/" name="docs/examples/mail.php"/>
- <file role="doc" baseinstalldir="/" name="docs/examples/null.php"/>
- <file role="doc" baseinstalldir="/" name="docs/examples/observer_mail.php"/>
- <file role="doc" baseinstalldir="/" name="docs/examples/pear_error_handler.php"/>
- <file role="doc" baseinstalldir="/" name="docs/examples/php_error_handler.php"/>
- <file role="doc" baseinstalldir="/" name="docs/examples/sql.php"/>
- <file role="doc" baseinstalldir="/" name="docs/examples/sqlite.php"/>
- <file role="doc" baseinstalldir="/" name="docs/examples/syslog.php"/>
- <file role="doc" baseinstalldir="/" name="docs/examples/win.php"/>
- <file role="php" baseinstalldir="/" name="Log/composite.php"/>
- <file role="php" baseinstalldir="/" name="Log/console.php"/>
- <file role="php" baseinstalldir="/" name="Log/daemon.php"/>
- <file role="php" baseinstalldir="/" name="Log/display.php"/>
- <file role="php" baseinstalldir="/" name="Log/error_log.php"/>
- <file role="php" baseinstalldir="/" name="Log/file.php"/>
- <file role="php" baseinstalldir="/" name="Log/mail.php"/>
- <file role="php" baseinstalldir="/" name="Log/mcal.php"/>
- <file role="php" baseinstalldir="/" name="Log/null.php"/>
- <file role="php" baseinstalldir="/" name="Log/observer.php"/>
- <file role="php" baseinstalldir="/" name="Log/sql.php"/>
- <file role="php" baseinstalldir="/" name="Log/sqlite.php"/>
- <file role="php" baseinstalldir="/" name="Log/syslog.php"/>
- <file role="php" baseinstalldir="/" name="Log/win.php"/>
- <file role="data" baseinstalldir="/" name="misc/log.sql"/>
- <file role="test" baseinstalldir="/" name="tests/composite.phpt"/>
- <file role="test" baseinstalldir="/" name="tests/console.phpt"/>
- <file role="test" baseinstalldir="/" name="tests/display.phpt"/>
- <file role="test" baseinstalldir="/" name="tests/error_log.phpt"/>
- <file role="test" baseinstalldir="/" name="tests/extract.phpt"/>
- <file role="test" baseinstalldir="/" name="tests/extract2.phpt"/>
- <file role="test" baseinstalldir="/" name="tests/factory.phpt"/>
- <file role="test" baseinstalldir="/" name="tests/null.phpt"/>
- <file role="test" baseinstalldir="/" name="tests/priority.phpt"/>
- <file role="test" baseinstalldir="/" name="tests/singleton.phpt"/>
- <file role="test" baseinstalldir="/" name="tests/sqlite.phpt"/>
- <file role="test" baseinstalldir="/" name="tests/sql_ident.phpt"/>
- <file role="php" baseinstalldir="/" name="Log.php"/>
- </filelist>
- </release>
- <changelog>
- <release>
- <version>1.8.7</version>
- <date>2004-12-20</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>The Log::_extractMessage() routine will now extract and use the value of an array's 'message' key if it exists. (Laurent Laville)
-The 'display' handler now preserves line breaks in its output. (Bug 2606)
-An experimental new syslog daemon log handler ('daemon') has been added to the Log distribution. (Bart van der Schans)
-</notes>
- </release>
- <release>
- <version>1.8.6</version>
- <date>2004-09-08</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>The maximum length of the 'sql' handler's 'ident' string is now configurable via the 'identLimit' configuration parameter. (Bug 2137)
-
-Different instances of the 'win' handler can now address their own output windows. (Bug 2212)
-</notes>
- </release>
- <release>
- <version>1.8.5</version>
- <date>2004-08-09</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>The 'sql' handler now enforces a maximum 'ident' length of 16 characters.
-
-The 'sql' handler can now use a user-defined sequence (via the 'sequence' configuration parameter). This allows each log table to use its own sequence. You will need to take appropriate steps to preserve your sequence numbering if that is important to your site; the ID sequence will be reinitialized to 0 the first time this updated handler is used. You may also need to explicitly drop the 'log_id_seq' sequence before using this new code.
-
-The 'composite' handler now properly closes all of its children when its close() method is called. It also guards against multiple calls to open(). (Bug 1947)
-</notes>
- </release>
- <release>
- <version>1.8.4</version>
- <date>2004-02-16</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>The Log package now requires PHP 4.3.0 or later.
-
-The _extractMessage() method no longer uses the serialize()'ed version of an event object if no string conversion method is available. Instead, the human-readable (via print_r()) representation of the object will be used.
-
-_extractMessage() can now handle arrays. Their human-readable representation will be used.
-
-Each Log instance now has a default priority level. This priority will be used by the log() method when no specific priority parameter is provided. It can be accessed using the new getPriority() and setPriority() methods.
-</notes>
- </release>
- <release>
- <version>1.8.3</version>
- <date>2004-01-11</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>The open() and close() methods now consistently return success or failure. Previously, some handlers' open() and close() methods did not return any result. Also, the log() methods will return failure when the handler cannot be opened.
-
-Bertrand Mansion contributed a new handler that logs using the Sqlite extension.
-</notes>
- </release>
- <release>
- <version>1.8.2</version>
- <date>2004-01-01</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>A new 'null' log handler that simply consumes log events has been added. The 'null' handler will still respect log masks and attached observers.
-
-The public Log API has grown a flush() method. This allows buffered log output to be explicitly flushed. At this time, the flush() method is only implemented by the console, file and mail handlers.
-
-New unit tests for the Factory and Singleton construction methods have been added.
-</notes>
- </release>
- <release>
- <version>1.8.1</version>
- <date>2003-12-14</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>The 'win' handler now handles newline sequences correctly (Bug 282).
-
-The Log_observer::factory() method has been updated to accept an optional associative array of configuration values, return the newly-created object by reference, and look for files named 'Log/observer_.php'. Backwards compatibility for the old-style conventions has been preserved.
-</notes>
- </release>
- <release>
- <version>1.8.0</version>
- <date>2003-11-18</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>The Log package now includes a users guide, example scripts and unit tests.
-
-A number of small improvements have been made to the 'win' log handler (based on suggestions from Paul Yanchenko).
-
-A new 'display' log handler has been added to the distribution. Contributed by Paul Yanchenko, this handler simply prints the error message back to the browser. It respects the 'error_prepend_string' and 'error_append_string' PHP INI values and is useful when using PEAR::setErrorHandling()'s PEAR_ERROR_CALLBACK mechanism.
-</notes>
- </release>
- <release>
- <version>1.7.1</version>
- <date>2003-09-21</date>
- <state>stable</state>
- <notes>The mail handler now uses &quot;\n&quot; to terminate lines instead of &quot;\r\n&quot;.
-
-The file handler's path creation routines now guard against potentially infinite recursion.
-
-It is now possible to pass an object to the logging methods. If the object offers a PEAR_Error-style getMessage() or PHP5 exception-style toString() method, it will be used to extract the message text.
-</notes>
- </release>
- <release>
- <version>1.7.0</version>
- <date>2003-08-02</date>
- <state>stable</state>
- <notes>It is now possible to specific a specific mask that dictates exactly which levels will be logged.
-
-A number of convenient &quot;shortcut&quot; functions have been added for logging messages at specific log messages.
-
-Two new log handers have been added: the 'error_log' handler wraps PHP's native error_log() function; and the 'win' handler outputs log messages to a separate browser window.
-
-The file log handler has been completely rewritten based on suggestions from Roman Neuhauser. It no longer buffers log output in memory before writing to the log file.
-
-Greg Beaver submitted a change that allows callers to provide their own Log classes (that existing outside of the PEAR file hierarchy) by including them before invoking a factory() method.
-</notes>
- </release>
- <release>
- <version>1.6.7</version>
- <date>2003-06-16</date>
- <state>stable</state>
- <notes>It is now possible to set the identification string for all of a composite's child instances.
-
-The preamble of the mail handler's message is now configurable.
-</notes>
- </release>
- <release>
- <version>1.6.5</version>
- <date>2003-04-26</date>
- <state>stable</state>
- <notes>The mail log handler needs to register its own destructer now that the Log class no longer inherits from the PEAR base class.
-</notes>
- </release>
- <release>
- <version>1.6.4</version>
- <date>2003-04-08</date>
- <state>stable</state>
- <notes>The Log classes no longer inherits from the PEAR base class. Not including the PEAR base class gives us smaller, faster Log objects.
-
-The Log_file class now registers its own destructor to ensure that the logfile is correctly closed upon shutdown.
-
-A ZendEngine 1 incompatibility was introduced in the previous release. This has been corrrected.
-</notes>
- </release>
- <release>
- <version>1.6.3</version>
- <date>2003-04-07</date>
- <state>stable</state>
- <notes>A unique identifier is now stored inside each Log instance. Both the composite and subject-observer mechanisms use this identifier to index their object lists.
-
-The internals of the Log_observer system have been rewritten for general cleanliness. The external interface remains unchanged.
-
-The Log class now offers public setIdent() and getIdent() members for setting and getting the Log instance's identification string during the object's lifetime.
-</notes>
- </release>
- <release>
- <version>1.6.2</version>
- <date>2003-04-06</date>
- <state>stable</state>
- <notes>In the Log_observer class, operate directly on the reference to the Log instance (instead of on a copy of the object).
-</notes>
- </release>
- <release>
- <version>1.6.1</version>
- <date>2003-04-02</date>
- <state>stable</state>
- <notes>- Fix a typo that broke the Log_Observer class.
-</notes>
- </release>
- <release>
- <version>1.6.0</version>
- <date>2003-02-17</date>
- <state>stable</state>
- <notes>- The SQL handler now uses sequences instead of timestamps as unique identifiers.
-- The time format used by the file handler is now configurable.
-</notes>
- </release>
- <release>
- <version>1.5.3</version>
- <date>2003-01-01</date>
- <state>stable</state>
- <notes>- Improved singleton()'s signature generation.
-- The SQL handler no longer closes existing database connections.
-- The log() method now returns a boolean result indicating success or failure.
-</notes>
- </release>
- <release>
- <version>1.5.2</version>
- <date>2002-11-28</date>
- <state>stable</state>
- <notes>- Altered the singleton's &quot;signature&quot; construction to be shorter and more array-friendly.
-</notes>
- </release>
- <release>
- <version>1.5.1</version>
- <date>2002-11-17</date>
- <state>stable</state>
- <notes>- The mail handler now implements a destructor to ensure close() is called.
-- The syslog handler now requires $name to be a valid syslog facility.
-</notes>
- </release>
- <release>
- <version>1.5</version>
- <date>2002-10-24</date>
- <state>stable</state>
- <notes>- Adding the ability to set the mode of the logfile in the Log_file.
-- mail() failures in Log_mail are logged via error_log().
-- Replaced all remaining LOG_* constants with the PEAR_LOG_* versions.
-</notes>
- </release>
- <release>
- <version>1.4</version>
- <date>2002-09-28</date>
- <state>stable</state>
- <notes>- Altered the format of the SQL logging table to use a TIMESTAMP field.
-- The Log class now extends the PEAR base class.
-- New file logger that keeps the log file open for the life of the request.
-</notes>
- </release>
- <release>
- <version>1.3</version>
- <date>2002-09-15</date>
- <state>stable</state>
- <notes>Adding a mail logging target.
-</notes>
- </release>
- <release>
- <version>1.2</version>
- <date>2002-07-24</date>
- <state>stable</state>
- <notes>Introduce the PEAR_LOG_* constants.
-</notes>
- </release>
- <release>
- <version>1.1</version>
- <date>2002-04-12</date>
- <state>stable</state>
- <notes>Adding a new console logging target.
-</notes>
- </release>
- </changelog>
-</package>
diff --git a/inc/packages/Mail.xml b/inc/packages/Mail.xml
deleted file mode 100644
index 0fbd10ac951..00000000000
--- a/inc/packages/Mail.xml
+++ /dev/null
@@ -1,122 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1" ?>
-<!DOCTYPE package SYSTEM "http://pear.php.net/dtd/package-1.0">
-<package version="1.0">
- <name>Mail</name>
- <summary>Class that provides multiple interfaces for sending emails</summary>
- <description>PEAR's Mail:: package defines the interface for implementing mailers under the PEAR hierarchy, and provides supporting functions useful in multiple mailer backends. Currently supported are native PHP mail() function, sendmail and SMTP. This package also provides a RFC 822 Email address list validation utility class.</description>
- <maintainers>
- <maintainer>
- <user>chagenbu</user>
- <name>Chuck Hagenbuch</name>
- <email>chuck@horde.org</email>
- <role>lead</role>
- </maintainer>
- <maintainer>
- <user>richard</user>
- <name>Richard Heyes</name>
- <email>richard@phpguru.org</email>
- <role>developer</role>
- </maintainer>
- <maintainer>
- <user>jon</user>
- <name>Jon Parise</name>
- <email>jon@php.net</email>
- <role>lead</role>
- </maintainer>
- </maintainers>
- <release>
- <version>1.1.6</version>
- <date>2005-07-12</date>
- <license>PHP/BSD</license>
- <state>stable</state>
- <notes>- Don't emit warnings with PHP 4.4/5.1.</notes>
- <deps>
- <dep type="pkg" rel="ge" version="1.1.0" optional="yes">Net_SMTP</dep>
- </deps>
- <filelist>
- <file role="php" md5sum="b0699c0f6b51275e74a2c97cb1de7980" name="Mail.php"/>
- <file role="php" md5sum="ff2c701d512ef88a6c9c3dfe3f0e88e5" name="Mail/mail.php"/>
- <file role="php" md5sum="4a1ed7ae8036862b24fa0ea84f8bbe0e" name="Mail/null.php"/>
- <file role="php" md5sum="34ee064a62dae8fe5d9d3a17f3c27d39" name="Mail/sendmail.php"/>
- <file role="php" md5sum="2afc664c71665f79c30814427bfe36ae" name="Mail/smtp.php"/>
- <file role="php" md5sum="1dd4f8ccc2527904d07149d4d9855c41" name="Mail/RFC822.php"/>
- <file role="test" md5sum="415a187e606d547c3e852ab83e2ab4e8" name="tests/rfc822.phpt"/>
- </filelist>
- </release>
- <changelog>
- <release>
- <version>1.1.5</version>
- <date>2005-06-26</date>
- <state>stable</state>
- <notes>- Unfold long lines before parsing addresses in Mail_RFC822.
-- The SMTP driver now supports a 'timeout' value. (Request #3776)
-- An array of Received: headers can now be provided. (Bug #4636)
-
-</notes>
- </release>
- <release>
- <version>1.1.4</version>
- <date>2004-09-08</date>
- <state>stable</state>
- <notes>- Header key comparisons are now case-insensitive. (Colin Viebrock)
-- Header fields (e.g., 'Cc', 'Bcc') may now be specified as arrays of addresses. (Colin Viebrock)
-- PHP5 compatibility fix (Bug #1563).
-- PHP4 / Win32 compatibility fix for the 'sendmail' driver (Bug 1881).
-- Stricter &quot;local part&quot; parsing for Mail_RFC822 (in accordance with Section 6.2.4 of RFC 822) (Bug 1869).
-- The various send() implementations now properly escalate the PEAR_Error object returned by Mail::prepareHeaders() in the event of an invalid header.
-
-</notes>
- </release>
- <release>
- <version>1.1.3</version>
- <date>2004-04-08</date>
- <state>stable</state>
- <notes>- The 'mail' driver now returns a PEAR_Error object on failure.
-- The individual drivers no longer include the 'Mail.php' file. If you want to instantiate a driver directly, you'll need to explicitly include the 'Mail.php' file yourself.
-
-</notes>
- </release>
- <release>
- <version>1.1.2</version>
- <date>2003-09-04</date>
- <state>stable</state>
- <notes>The 'localhost' value can now be set in the SMTP driver.
-</notes>
- </release>
- <release>
- <version>1.1.1</version>
- <date>2003-06-26</date>
- <state>stable</state>
- <notes>Minor fixes with newlines in headers.
-</notes>
- </release>
- <release>
- <version>1.1.0</version>
- <date>2003-06-21</date>
- <state>stable</state>
- <notes>The Mail package now depends on Net_SMTP 1.1.0 or greater for its SMTP authentication capabilities.
-</notes>
- </release>
- <release>
- <version>1.0.2</version>
- <date>2002-07-27</date>
- <state>stable</state>
- <notes>Minor additions and changes to RFC822.php. Fixed line terminator issue for smtp.php and set smtp.php to use Return-Path header in place of From header for MAIL FROM: (if supplied)
-</notes>
- </release>
- <release>
- <version>1.0.1</version>
- <date>2002-07-27</date>
- <state>stable</state>
- <notes>License change for RFC822.php
-</notes>
- </release>
- <release>
- <version>1.0</version>
- <date>2002-06-06</date>
- <state>stable</state>
- <notes>Initial release as PEAR package
-</notes>
- </release>
- </changelog>
-</package>
diff --git a/inc/packages/Mail_Mime.xml b/inc/packages/Mail_Mime.xml
deleted file mode 100644
index ddf734f0c28..00000000000
--- a/inc/packages/Mail_Mime.xml
+++ /dev/null
@@ -1,113 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1" ?>
-<!DOCTYPE package SYSTEM "http://pear.php.net/dtd/package-1.0">
-<package version="1.0">
- <name>Mail_Mime</name>
- <summary>Provides classes to create and decode mime messages.</summary>
- <description>Provides classes to deal with creation and manipulation of mime messages.</description>
- <maintainers>
- <maintainer>
- <user>cipri</user>
- <name>Cipriano Groenendal</name>
- <email>cipri@php.net</email>
- <role>lead</role>
- </maintainer>
- <maintainer>
- <user>gschlossnagle</user>
- <name>George Schlossnagle</name>
- <email>gschlossnagle@php.net</email>
- <role>lead</role>
- </maintainer>
- <maintainer>
- <user>sean</user>
- <name>Sean Coates</name>
- <email>sean@php.net</email>
- <role>lead</role>
- </maintainer>
- <maintainer>
- <user>richard</user>
- <name>Richard Heyes</name>
- <email>richard@php.net</email>
- <role>contributor</role>
- </maintainer>
- <maintainer>
- <user>cox</user>
- <name>Tomas V.V.Cox</name>
- <email>cox@idecnet.com</email>
- <role>contributor</role>
- </maintainer>
- </maintainers>
- <release>
- <version>1.3.1</version>
- <date>2005-07-13</date>
- <license>PHP</license>
- <state>stable</state>
- <notes>A bugfix release:</notes>
- <filelist>
- <file role="php" baseinstalldir="Mail" md5sum="8c87c7120ef61cd7c927f022fb270d2d" name="mime.php"/>
- <file role="php" baseinstalldir="Mail" md5sum="e266dce6abce7f0e0e2e8972a8fe2275" name="mimeDecode.php"/>
- <file role="php" baseinstalldir="Mail" md5sum="3663406015b4ae1cc9df19f68247a784" name="mimePart.php"/>
- <file role="data" baseinstalldir="Mail" md5sum="194810c478066eaeb28f51116b88e25a" name="xmail.dtd"/>
- <file role="data" baseinstalldir="Mail" md5sum="61cea06fb6b4bd3a4b5e2d37384e14a9" name="xmail.xsl"/>
- </filelist>
- </release>
- <changelog>
- <release>
- <version>1.3.0</version>
- <date>2005-04-01</date>
- <license>PHP</license>
- <state>stable</state>
- <notes>o First (stable) release in over 2.5 years (!)
-o MANY bugfixes (see the bugtracker)
-o added a few tests
-o one small fix after RC1 (bug #3940)
-
-</notes>
- </release>
- <release>
- <version>1.3.0RC1</version>
- <date>2005-03-20</date>
- <state>beta</state>
- <notes>o First release in over 2.5 years (!)
-o MANY bugfixes (see the bugtracker)
-o added a few tests
-
-</notes>
- </release>
- <release>
- <version>1.2.1</version>
- <date>2002-07-27</date>
- <license>PHP</license>
- <state>stable</state>
- <notes>o License change
-o Applied a few changes From Ilia Alshanetsky
-
-</notes>
- </release>
- <release>
- <version>1.2</version>
- <date>2002-07-14</date>
- <state>stable</state>
- <notes>o Added header encoding
-o Altered mimePart to put boundary parameter on newline
-o Changed addFrom() to setFrom()
-o Added setSubject()
-o Made mimePart inherit crlf setting from mime
-
-</notes>
- </release>
- <release>
- <version>1.1</version>
- <date>2002-04-03</date>
- <state>stable</state>
- <notes>This is a maintenance release with various bugfixes and minor enhancements.
-</notes>
- </release>
- <release>
- <version>1.0</version>
- <date>2001-12-28</date>
- <state>stable</state>
- <notes>This is the initial release of the Mime_Mail package.
-</notes>
- </release>
- </changelog>
-</package>
diff --git a/inc/packages/Net_SMTP.xml b/inc/packages/Net_SMTP.xml
deleted file mode 100644
index d1e8c56332e..00000000000
--- a/inc/packages/Net_SMTP.xml
+++ /dev/null
@@ -1,137 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1" ?>
-<!DOCTYPE package SYSTEM "http://pear.php.net/dtd/package-1.0">
-<package version="1.0">
- <name>Net_SMTP</name>
- <summary>Provides an implementation of the SMTP protocol</summary>
- <description>Provides an implementation of the SMTP protocol using PEAR's Net_Socket class.</description>
- <maintainers>
- <maintainer>
- <user>chagenbu</user>
- <name>Chuck Hagenbuch</name>
- <email>chuck@horde.org</email>
- <role>lead</role>
- </maintainer>
- <maintainer>
- <user>jon</user>
- <name>Jon Parise</name>
- <email>jon@php.net</email>
- <role>lead</role>
- </maintainer>
- </maintainers>
- <release>
- <version>1.2.6</version>
- <date>2004-04-12</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>Renaming some methods to be compatible with the PEAR coding standards. Backwards-compatible wrappers have been provided.</notes>
- <deps>
- <dep type="pkg" rel="has" optional="no">Net_Socket</dep>
- <dep type="pkg" rel="has" optional="yes">Auth_SASL</dep>
- </deps>
- <filelist>
- <file role="doc" baseinstalldir="Net" name="docs/guide.txt"/>
- <file role="doc" baseinstalldir="Net" name="docs/examples/basic.php"/>
- <file role="test" baseinstalldir="Net" name="tests/auth.phpt"/>
- <file role="test" baseinstalldir="Net" name="tests/basic.phpt"/>
- <file role="test" baseinstalldir="Net" name="tests/config.php.dist"/>
- <file role="php" baseinstalldir="Net" name="SMTP.php"/>
- </filelist>
- </release>
- <changelog>
- <release>
- <version>1.2.6</version>
- <date>2004-04-12</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>The following methods have been renamed for compliance with the PEAR coding standards: send_from() -&gt; sendFrom(), soml_from() -&gt; somlFrom(), saml_from() -&gt; samlFrom(). Backwards-compatible wrappers have been provided.
-</notes>
- </release>
- <release>
- <version>1.2.5</version>
- <date>2004-03-11</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>The connect() method has grown an optional 'persistent' parameter that will be passed to the Net_Socket::connect() method. Previously, persistent connections will always disabled. 'persistent' defaults to false.
-
-Release 1.2.4 was incorrectly packaged. Release 1.2.5 corrects that error. The code itself remains the same.
-</notes>
- </release>
- <release>
- <version>1.2.4</version>
- <date>2004-03-11</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>The connect() method has grown an optional 'persistent' parameter that will be passed to the Net_Socket::connect() method. Previously, persistent connections will always disabled. 'persistent' defaults to false.
-</notes>
- </release>
- <release>
- <version>1.2.3</version>
- <date>2003-05-11</date>
- <state>stable</state>
- <notes>Both 235 (Authentication successful) and 503 (Error: already authenticated) are now accepted as valid AUTH responses.
-
-503 (Error: already authenticated) is now considered a valid EHLO response.
-</notes>
- </release>
- <release>
- <version>1.2.2</version>
- <date>2003-05-02</date>
- <state>stable</state>
- <notes>Fix a call-time pass-by-reference problem that was raising a warning if call-time pass-by-reference was disabled.
-</notes>
- </release>
- <release>
- <version>1.2.1</version>
- <date>2003-04-26</date>
- <state>stable</state>
- <notes>The Auth_SASL package is no longer absolutely required, but it will be used if it is available. Otherwise, the authentication methods that depend upon it will be disabled.
-</notes>
- </release>
- <release>
- <version>1.2.0</version>
- <date>2003-04-06</date>
- <state>stable</state>
- <notes>- Perform data quoting in its own routine: quotedata()
-</notes>
- </release>
- <release>
- <version>1.1.2</version>
- <date>2003-02-17</date>
- <state>stable</state>
- <notes>- Correctly handle the case where the server's ESMTP response includes a SIZE keyword with no specific value.
-</notes>
- </release>
- <release>
- <version>1.1.1</version>
- <date>2003-01-30</date>
- <state>stable</state>
- <notes>- Don't enforce a maximum message size if the SIZE parameter is zero.
-</notes>
- </release>
- <release>
- <version>1.1.0</version>
- <date>2003-01-18</date>
- <state>stable</state>
- <notes>- The SMTP server's SIZE capability is now honored.
-- Improved support for SMTP authentication (LOGIN, PLAIN, CRAM-MD5, DIGEST-MD5).
-- Overhauled the server response parsing system.
-- Added optional debugging output (enabled via setDebug()).
-- A timeout value can now be specified for the socket connection.
-</notes>
- </release>
- <release>
- <version>1.0.1</version>
- <date>2003-01-02</date>
- <state>stable</state>
- <notes>Corrected an off-by-one bug that corrupted the list of ESMTP capabilities.
-</notes>
- </release>
- <release>
- <version>1.0</version>
- <date>2002-06-11</date>
- <state>stable</state>
- <notes>Initial release as PEAR package
-</notes>
- </release>
- </changelog>
-</package>
diff --git a/inc/packages/Net_Socket.xml b/inc/packages/Net_Socket.xml
deleted file mode 100644
index 9c7eae00940..00000000000
--- a/inc/packages/Net_Socket.xml
+++ /dev/null
@@ -1,84 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1" ?>
-<!DOCTYPE package SYSTEM "http://pear.php.net/dtd/package-1.0">
-<package version="1.0">
- <name>Net_Socket</name>
- <summary>Network Socket Interface</summary>
- <description>Net_Socket is a class interface to TCP sockets. It provides blocking
-and non-blocking operation, with different reading and writing modes
-(byte-wise, block-wise, line-wise and special formats like network
-byte-order ip addresses).</description>
- <maintainers>
- <maintainer>
- <user>ssb</user>
- <name>Stig Bakken</name>
- <email>stig@php.net</email>
- <role>lead</role>
- </maintainer>
- <maintainer>
- <user>chagenbu</user>
- <name>Chuck Hagenbuch</name>
- <email>chuck@horde.org</email>
- <role>lead</role>
- </maintainer>
- </maintainers>
- <release>
- <version>1.0.6</version>
- <date>2005-02-26</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>- Make package.xml safe for PEAR 1.4.0.
-- Chunk socket writes on Windows by default, or if explicitly specified (Bug #980)
-- Don't run any $addr with a '/' in it through gethostbyname() (Bug #3372)</notes>
- <filelist>
- <file role="php" baseinstalldir="Net" md5sum="1c7a9a28fc3fa78e682200d7540b66d5" name="Socket.php"/>
- </filelist>
- </release>
- <changelog>
- <release>
- <version>1.0.0</version>
- <date>2002-04-01</date>
- <state>stable</state>
- <notes>First independent release of Net_Socket.
-</notes>
- </release>
- <release>
- <version>1.0.1</version>
- <date>2002-04-04</date>
- <state>stable</state>
- <notes>Touch up error handling.
-</notes>
- </release>
- <release>
- <version>1.0.2</version>
- <date>2004-04-26</date>
- <state>stable</state>
- <notes>Fixes for several longstanding bugs. Allow setting of stream
-context. Correctly read lines that only end in \n. Suppress
-PHP warnings.
-</notes>
- </release>
- <release>
- <version>1.0.3</version>
- <date>2004-12-08</date>
- <state>stable</state>
- <notes>Optimize away some duplicate is_resource() calls.
-Better solution for eof() on blocking sockets [#1427].
-Add select() implementation [#1428].
-</notes>
- </release>
- <release>
- <version>1.0.4</version>
- <date>2004-12-13</date>
- <state>stable</state>
- <notes>Restore support for unix sockets (Bug #2961).
-</notes>
- </release>
- <release>
- <version>1.0.5</version>
- <date>2005-01-11</date>
- <state>stable</state>
- <notes>Don't rely on gethostbyname() for error checking (Bug #3100).
-</notes>
- </release>
- </changelog>
-</package>
diff --git a/inc/packages/PEAR.xml b/inc/packages/PEAR.xml
deleted file mode 100644
index 83800a16a0d..00000000000
--- a/inc/packages/PEAR.xml
+++ /dev/null
@@ -1,282 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1" ?>
-<!DOCTYPE package SYSTEM "http://pear.php.net/dtd/package-1.0">
-<package version="1.0" packagerversion="1.4.0a1">
- <name>PEAR</name>
- <summary>PEAR Base System</summary>
- <description>The PEAR package contains:
- * the PEAR installer, for creating, distributing
- and installing packages
- * the alpha-quality PEAR_Exception php5-only exception class
- * the beta-quality PEAR_ErrorStack advanced error handling mechanism
- * the PEAR_Error error handling mechanism
- * the OS_Guess class for retrieving info about the OS
- where PHP is running on
- * the System class for quick handling common operations
- with files and directories
- * the PEAR base class
- </description>
- <maintainers>
- <maintainer>
- <user>ssb</user>
- <name>Stig Bakken</name>
- <email>stig@php.net</email>
- <role>lead</role>
- </maintainer>
- <maintainer>
- <user>cox</user>
- <name>Tomas V.V.Cox</name>
- <email>cox@idecnet.com</email>
- <role>lead</role>
- </maintainer>
- <maintainer>
- <user>cellog</user>
- <name>Greg Beaver</name>
- <email>cellog@php.net</email>
- <role>lead</role>
- </maintainer>
- <maintainer>
- <user>pajoye</user>
- <name>Pierre-Alain Joye</name>
- <email>pajoye@pearfr.org</email>
- <role>lead</role>
- </maintainer>
- <maintainer>
- <user>mj</user>
- <name>Martin Jansen</name>
- <email>mj@php.net</email>
- <role>developer</role>
- </maintainer>
- </maintainers>
- <release>
- <version>1.3.5</version>
- <date>2005-02-18</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>* fix Bug #3505: pecl can't install PDO
-* enhance pear run-tests dramatically
-* fix Bug #3506: pear install should export the pear version into the environment
- </notes>
- <deps>
- <dep type="php" rel="ge" version="4.2"/>
- <dep type="pkg" rel="ge" version="1.1">Archive_Tar</dep>
- <dep type="pkg" rel="ge" version="1.2">Console_Getopt</dep>
- <dep type="pkg" rel="ge" version="1.0.4">XML_RPC</dep>
- <dep type="ext" rel="has">xml</dep>
- <dep type="ext" rel="has">pcre</dep>
- </deps>
- <provides type="class" name="OS_Guess" />
- <provides type="class" name="System" />
- <provides type="function" name="md5_file" />
- <provides type="function" name="OS_Guess::parseSignature" />
- <provides type="class" name="PEAR_Command_Auth" extends="PEAR_Command_Common" />
- <provides type="function" name="PEAR_Command_Auth::doLogin" />
- <provides type="class" name="PEAR_Command_Build" extends="PEAR_Command_Common" />
- <provides type="function" name="PEAR_Command_Build::doBuild" />
- <provides type="function" name="PEAR_Command_Build::buildCallback" />
- <provides type="class" name="PEAR_Command_Common" extends="PEAR" />
- <provides type="function" name="PEAR_Command_Common::getCommands" />
- <provides type="function" name="PEAR_Command_Common::getShortcuts" />
- <provides type="function" name="PEAR_Command_Common::getOptions" />
- <provides type="function" name="PEAR_Command_Common::getGetoptArgs" />
- <provides type="function" name="PEAR_Command_Common::getHelp" />
- <provides type="class" name="PEAR_Command_Config" extends="PEAR_Command_Common" />
- <provides type="function" name="PEAR_Command_Config::doConfigShow" />
- <provides type="function" name="PEAR_Command_Config::doConfigGet" />
- <provides type="function" name="PEAR_Command_Config::doConfigSet" />
- <provides type="function" name="PEAR_Command_Config::doConfigHelp" />
- <provides type="class" name="PEAR_Command_Install" extends="PEAR_Command_Common" />
- <provides type="function" name="PEAR_Command_Install::doInstall" />
- <provides type="class" name="PEAR_Command_Package" extends="PEAR_Command_Common" />
- <provides type="class" name="PEAR_Command_Registry" extends="PEAR_Command_Common" />
- <provides type="function" name="PEAR_Command_Registry::doList" />
- <provides type="class" name="PEAR_Command_Remote" extends="PEAR_Command_Common" />
- <provides type="function" name="PEAR_Command_Remote::doRemoteInfo" />
- <provides type="class" name="PEAR_Command_Mirror" extends="PEAR_Command_Common" />
- <provides type="function" name="PEAR_Command_Mirror::doDownloadAll" />
- <provides type="class" name="PEAR_Frontend_CLI" extends="PEAR" />
- <provides type="function" name="PEAR_Frontend_CLI::displayLine" />
- <provides type="class" name="PEAR_Autoloader" extends="PEAR" />
- <provides type="function" name="PEAR_Autoloader::addAutoload" />
- <provides type="function" name="PEAR_Autoloader::removeAutoload" />
- <provides type="function" name="PEAR_Autoloader::addAggregateObject" />
- <provides type="function" name="PEAR_Autoloader::removeAggregateObject" />
- <provides type="class" name="PEAR_Command" />
- <provides type="function" name="PEAR_Command::factory" />
- <provides type="class" name="PEAR_Common" extends="PEAR" />
- <provides type="function" name="PEAR_Common::addTempFile" />
- <provides type="function" name="PEAR_Common::mkDirHier" />
- <provides type="class" name="PEAR_Config" extends="PEAR" />
- <provides type="function" name="PEAR_Config::singleton" />
- <provides type="function" name="PEAR_Config::readConfigFile" />
- <provides type="class" name="PEAR_Dependency" />
- <provides type="function" name="PEAR_Dependency::callCheckMethod" />
- <provides type="class" name="PEAR_Downloader" extends="PEAR_Common" />
- <provides type="function" name="PEAR_Downloader::configSet" />
- <provides type="function" name="PEAR_Downloader::setOptions" />
- <provides type="class" name="PEAR_Exception" extends="Exception" />
- <provides type="function" name="PEAR_Exception::addObserver" />
- <provides type="function" name="PEAR_Exception::removeObserver" />
- <provides type="function" name="PEAR_Exception::getUniqueId" />
- <provides type="function" name="PEAR_Exception::signal" />
- <provides type="function" name="PEAR_Exception::getErrorData" />
- <provides type="function" name="PEAR_Exception::getCause" />
- <provides type="function" name="PEAR_Exception::getCauseMessage" />
- <provides type="function" name="PEAR_Exception::getTraceSafe" />
- <provides type="function" name="PEAR_Exception::getErrorClass" />
- <provides type="function" name="PEAR_Exception::getErrorMethod" />
- <provides type="function" name="PEAR_Exception::toHtml" />
- <provides type="function" name="PEAR_Exception::toText" />
- <provides type="class" name="PEAR_ErrorStack" />
- <provides type="function" name="PEAR_ErrorStack::singleton" />
- <provides type="function" name="PEAR_ErrorStack::setDefaultLogger" />
- <provides type="function" name="PEAR_ErrorStack::setLogger" />
- <provides type="function" name="PEAR_ErrorStack::setMessageCallback" />
- <provides type="function" name="PEAR_ErrorStack::getMessageCallback" />
- <provides type="function" name="PEAR_ErrorStack::setDefaultCallback" />
- <provides type="function" name="PEAR_ErrorStack::setContextCallback" />
- <provides type="function" name="PEAR_ErrorStack::pushCallback" />
- <provides type="function" name="PEAR_ErrorStack::popCallback" />
- <provides type="function" name="PEAR_ErrorStack::staticPushCallback" />
- <provides type="function" name="PEAR_ErrorStack::staticPopCallback" />
- <provides type="function" name="PEAR_ErrorStack::push" />
- <provides type="function" name="PEAR_ErrorStack::staticPush" />
- <provides type="function" name="PEAR_ErrorStack::pop" />
- <provides type="function" name="PEAR_ErrorStack::hasErrors" />
- <provides type="function" name="PEAR_ErrorStack::getErrors" />
- <provides type="function" name="PEAR_ErrorStack::staticHasErrors" />
- <provides type="function" name="PEAR_ErrorStack::staticGetErrors" />
- <provides type="function" name="PEAR_ErrorStack::getFileLine" />
- <provides type="function" name="PEAR_ErrorStack::getErrorMessage" />
- <provides type="function" name="PEAR_ErrorStack::getErrorMessageTemplate" />
- <provides type="function" name="PEAR_ErrorStack::setErrorMessageTemplate" />
- <provides type="function" name="PEAR_ErrorStack::raiseError" />
- <provides type="class" name="PEAR_Builder" extends="PEAR_Common" />
- <provides type="class" name="PEAR_Installer" extends="PEAR_Downloader" />
- <provides type="class" name="PEAR_Packager" extends="PEAR_Common" />
- <provides type="function" name="PEAR_Packager::package" />
- <provides type="class" name="PEAR_Registry" extends="PEAR" />
- <provides type="class" name="PEAR_Remote" extends="PEAR" />
- <provides type="function" name="PEAR_Remote::getCache" />
- <provides type="function" name="PEAR_Remote::saveCache" />
- <provides type="function" name="PEAR_Remote::call" />
- <provides type="function" name="PEAR_Remote::call_epi" />
- <provides type="class" name="PEAR_RunTest" />
- <provides type="function" name="PEAR_RunTest::run" />
- <provides type="class" name="PEAR" />
- <provides type="function" name="System::raiseError" />
- <filelist>
- <file role="php" md5sum="7f552f5a5476a5ef8d180290d7d2a90f" name="OS/Guess.php"/>
- <file role="php" md5sum="f257b9252172a6e174b36499296bb972" name="PEAR/Command/Auth.php"/>
- <file role="php" md5sum="b0c210a914fb6c25507bfb948ff71bac" name="PEAR/Command/Build.php"/>
- <file role="php" md5sum="d90bfb54cf2505747999d8ad1f6c470f" name="PEAR/Command/Common.php"/>
- <file role="php" md5sum="303bbf44d112d510dd3a87ea7e55becf" name="PEAR/Command/Config.php"/>
- <file role="php" md5sum="6fee5ff129e8846d32e54dd5952c214d" name="PEAR/Command/Install.php"/>
- <file role="php" md5sum="3f428a3b9f09eb6f2e5e36dcf8983d1e" name="PEAR/Command/Package.php"/>
- <file role="php" md5sum="87a9582c0ba5ec6c9fbaba2d518e33dd" name="PEAR/Command/Registry.php"/>
- <file role="php" md5sum="db11793e282f070ad9dcadf2a644aeec" name="PEAR/Command/Remote.php"/>
- <file role="php" md5sum="a0f44e37e237f81404c6f73819a58206" name="PEAR/Command/Mirror.php"/>
- <file role="php" md5sum="8e310f4f947bf7079778ef0a71fcc5b3" name="PEAR/Frontend/CLI.php"/>
- <file role="php" md5sum="3940b7d27d339d72f019b8ab7e8e81b0" name="PEAR/Autoloader.php"/>
- <file role="php" md5sum="7fe4074ba2914cea3d17913b96c0088c" name="PEAR/Command.php"/>
- <file role="php" md5sum="435431d9bec9802f440845fce49f7b4b" name="PEAR/Common.php"/>
- <file role="php" md5sum="cea7df54a1491f7acf6d5290d68cd4ae" name="PEAR/Config.php"/>
- <file role="php" md5sum="e807f3abd241e82703725709c6a405c5" name="PEAR/Dependency.php"/>
- <file role="php" md5sum="bd1e073d4d42516164fe9da30bad9e75" name="PEAR/Downloader.php"/>
- <file role="php" md5sum="3b598325201802e8bb6498ec8c72128e" name="PEAR/Exception.php"/>
- <file role="php" md5sum="119d0fc70323e7a01bbc45a74c7840e4" name="PEAR/ErrorStack.php"/>
- <file role="php" md5sum="e2588d6c525aa58c0e063678a463138e" name="PEAR/Builder.php">
- <replace from="@PEAR-VER@" to="version" type="package-info"/>
- </file>
- <file role="php" md5sum="f6e026da8c0c36db331bd4e07f52608f" name="PEAR/Installer.php"/>
- <file role="php" md5sum="cf9a5b9cbd6cf1d43bbb6151c77a5b4c" name="PEAR/Packager.php"/>
- <file role="php" md5sum="6840ca9ca43e611da23aee935657a67d" name="PEAR/Registry.php"/>
- <file role="php" md5sum="a2a46e11af74a5b73cd1095f54ad5e51" name="PEAR/Remote.php"/>
- <file role="php" md5sum="342353331db1aff0c29818ff1b51e91c" name="PEAR/RunTest.php"/>
- <file role="script" baseinstalldir="/" md5sum="a3bc543b3f7174ab74108449496cad8b" install-as="pear" name="scripts/pear.sh">
- <replace from="/usr/bin/php" to="php_bin" type="pear-config"/>
- <replace from="/usr/share/pear" to="php_dir" type="pear-config"/>
- <replace from="5.0.4" to="version" type="package-info"/>
- <replace from="@include_path@" to="php_dir" type="pear-config"/>
- </file>
- <file role="script" baseinstalldir="/" md5sum="9ba3c9c4bd09c5dbd18af6dab0dab7b4" platform="windows" install-as="pear.bat" name="scripts/pear.bat">
- <replace from="@bin_dir@" to="bin_dir" type="pear-config"/>
- <replace from="/usr/bin/php" to="php_bin" type="pear-config"/>
- <replace from="@include_path@" to="php_dir" type="pear-config"/>
- </file>
- <file role="php" baseinstalldir="/" md5sum="ea4d7860cf26ab30a3f9426f8a7df8c1" install-as="pearcmd.php" name="scripts/pearcmd.php">
- <replace from="/usr/bin/php" to="php_bin" type="pear-config"/>
- <replace from="/usr/share/pear" to="php_dir" type="pear-config"/>
- <replace from="5.0.4" to="version" type="package-info"/>
- <replace from="@include_path@" to="php_dir" type="pear-config"/>
- </file>
- <file role="data" baseinstalldir="/" md5sum="72ce49e8fe0ec14277d29e15d0f6166f" name="package.dtd"/>
- <file role="data" baseinstalldir="/" md5sum="f2abf8db08a36295645d19b51e319a32" name="template.spec"/>
- <file role="php" baseinstalldir="/" md5sum="58a98a6d63e1089d7e389bc0249eac36" name="PEAR.php"/>
- <file role="php" baseinstalldir="/" md5sum="57012786babadc058fab98c6e6468689" name="System.php"/>
- </filelist>
- </release>
- <changelog>
- <release>
- <version>1.3.1</version>
- <date>2004-04-06</date>
- <state>stable</state>
- <notes>PEAR Installer:
-
- * Bug #534 pear search doesn't list unstable releases
- * Bug #933 CMD Usability Patch
- * Bug #937 throwError() treats every call as static
- * Bug #964 PEAR_ERROR_EXCEPTION causes fatal error
- * Bug #1008 safe mode raises warning
-
-PEAR_ErrorStack:
-
- * Added experimental error handling, designed to eventually replace
- PEAR_Error. It should be considered experimental until explicitly marked
- stable. require_once 'PEAR/ErrorStack.php' to use.
- </notes>
- </release>
- <release>
- <version>1.3.3</version>
- <date>2004-10-28</date>
- <state>stable</state>
- <notes>Installer:
- * fix Bug #1186 raise a notice error on PEAR::Common $_packageName
- * fix Bug #1249 display the right state when using --force option
- * fix Bug #2189 upgrade-all stops if dependancy fails
- * fix Bug #1637 The use of interface causes warnings when packaging with PEAR
- * fix Bug #1420 Parser bug for T_DOUBLE_COLON
- * fix Request #2220 pear5 build fails on dual php4/php5 system
- * fix Bug #1163 pear makerpm fails with packages that supply role=&quot;doc&quot;
-
-Other:
- * add PEAR_Exception class for PHP5 users
- * fix critical problem in package.xml for linux in 1.3.2
- * fix staticPopCallback() in PEAR_ErrorStack
- * fix warning in PEAR_Registry for windows 98 users
- </notes>
- </release>
- <release>
- <version>1.3.3.1</version>
- <date>2004-11-08</date>
- <state>stable</state>
- <notes>add RunTest.php to package.xml, make run-tests display failed tests, and use ui
- </notes>
- </release>
- <release>
- <version>1.3.4</version>
- <date>2005-01-01</date>
- <state>stable</state>
- <notes>* fix a serious problem caused by a bug in all versions of PHP that caused multiple registration
- of the shutdown function of PEAR.php
-* fix Bug #2861: package.dtd does not define NUMBER
-* fix Bug #2946: ini_set warning errors
-* fix Bug #3026: Dependency type &quot;ne&quot; is needed, &quot;not&quot; is not handled
- properly
-* fix Bug #3061: potential warnings in PEAR_Exception
-* implement Request #2848: PEAR_ErrorStack logger extends, PEAR_ERRORSTACK_DIE
-* implement Request #2914: Dynamic Include Path for run-tests command
-* make pear help listing more useful (put how-to-use info at the bottom of the listing)
- </notes>
- </release>
- </changelog>
-</package>
diff --git a/inc/packages/PHPUnit.xml b/inc/packages/PHPUnit.xml
deleted file mode 100644
index 71e736764db..00000000000
--- a/inc/packages/PHPUnit.xml
+++ /dev/null
@@ -1,224 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1" ?>
-<!DOCTYPE package SYSTEM "http://pear.php.net/dtd/package-1.0">
-<package version="1.0">
- <name>PHPUnit</name>
- <summary>Regression testing framework for unit tests.</summary>
- <description>PHPUnit is a regression testing framework used by the developer who implements unit tests in PHP. This is the version to be used with PHP 4.</description>
- <maintainers>
- <maintainer>
- <user>sebastian</user>
- <name>Sebastian Bergmann</name>
- <email>sb@sebastian-bergmann.de</email>
- <role>lead</role>
- </maintainer>
- </maintainers>
- <release>
- <version>1.2.3</version>
- <date>2005-05-14</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>Fixed bug #4342.</notes>
- <filelist>
- <file role="php" baseinstalldir="/" md5sum="5488043b7a6387fddd81e17a21f830ef" name="PHPUnit.php"/>
- <file role="php" md5sum="5851a03772edcb21eb6fe5b45190da20" name="PHPUnit/GUI/Gtk.php"/>
- <file role="php" md5sum="fa838ef5db2b541c6491164c3ea47077" name="PHPUnit/GUI/HTML.php"/>
- <file role="php" md5sum="222a8fef6537f8fb1653f68f1b1d6a28" name="PHPUnit/GUI/HTML.tpl"/>
- <file role="php" md5sum="8f82a97cc65ff80dced33a75fca0bc3d" name="PHPUnit/GUI/SetupDecorator.php"/>
- <file role="php" md5sum="23c0b3e2ecb4195e149c7a7b0e575cdf" name="PHPUnit/Assert.php"/>
- <file role="php" md5sum="e21e528ba2fdbf0f1e8b04cd36c477f0" name="PHPUnit/RepeatedTest.php"/>
- <file role="php" md5sum="2a425b3f6e42680e0926627d17413d59" name="PHPUnit/Skeleton.php"/>
- <file role="php" md5sum="7cc66f04974a60461bfb1ef03b2d23c4" name="PHPUnit/TestCase.php"/>
- <file role="php" md5sum="061dcb2cfc8ef9b17ac09032906e8beb" name="PHPUnit/TestDecorator.php"/>
- <file role="php" md5sum="74e1f1d35ff640598182ff86bed75142" name="PHPUnit/TestFailure.php"/>
- <file role="php" md5sum="e334f9dbad5478edb6da17714b9fa3ab" name="PHPUnit/TestListener.php"/>
- <file role="php" md5sum="9ca95d9252f8395def72fc3a9c68e73e" name="PHPUnit/TestResult.php"/>
- <file role="php" md5sum="20fccede54695a140ebad7f7289cb465" name="PHPUnit/TestSuite.php"/>
- </filelist>
- </release>
- <changelog>
- <release>
- <version>1.2.2</version>
- <date>2005-01-31</date>
- <state>stable</state>
- <notes>* Fixed bug #3332.
-
-
-</notes>
- </release>
- <release>
- <version>1.2.1</version>
- <date>2005-01-28</date>
- <state>stable</state>
- <notes>* Relaxed PHPUnit_Assert::assertNotNull() and PHPUnit_Assert::assertNull() to work on non-objects.
-
-* Fixed an issue in PHPUnit_GUI_SetupDecorator related to Windows' directory separators. (Patch by Lorenzo Alberton &lt;l.alberton@quipo.it&gt;)
-
-
-</notes>
- </release>
- <release>
- <version>1.2.0</version>
- <date>2005-01-19</date>
- <state>stable</state>
- <notes>+ Added Gtk-based frontend. (Patch by Scott Mattocks &lt;scott@crisscott.com&gt;)
-
-+ Re-Added PHPUnit_Assert::assertSame() and PHPUnit_Assert::assertNotSame() to make the PEAR QA team happy. These methods only work with PHP &gt;= 5.0.0.
-
-* PHPUnit_Assert::assertSame(), PHPUnit_Assert::assertNotSame(), PHPUnit_Assert::assertNotNull(), and PHPUnit_Assert::assertNull() are now stricter than before and only work on objects. This was always the documented behaviour.
-
-* Fixed a bug in the PHPUnit_GUI_SetupDecorator::_getFiles() method. (Patch by Michael Schmidt &lt;michael.schmidt@object-it.de&gt;)
-
-* Fixed bug #3127: PHPUnit_GUI_HTML and $_REQUEST. (Patch by cricket@djcricket.com)
-
-
-</notes>
- </release>
- <release>
- <version>1.1.1</version>
- <date>2004-11-05</date>
- <state>stable</state>
- <notes>* Fixed bug #2701.
-
-
-</notes>
- </release>
- <release>
- <version>1.1.0</version>
- <date>2004-09-29</date>
- <state>stable</state>
- <notes>+ Added PHPUnit_Skeleton class for creating a PHPUnit_TestCase skeleton file. (Patch by Scott Mattocks &lt;scott@crisscott.com&gt;)
-
-+ Added PHPUnit_Assert::assertContains() and PHPUnit_Assert::assertNotContains() methods to assert that an array contains (or not contains) a given value or that a string contains (or not contains) a given substring.
-
-+ Added PHPUnit_Assert::assertNotRegexp() to assert that a string does not match a given regular expression.
-
-- Removed PHPUnit_Assert::assertSame() and PHPUnit_Assert::assertNotSame() since these assertion methods do not work with PHP 4.
-
-
-</notes>
- </release>
- <release>
- <version>1.0.2</version>
- <date>2004-09-21</date>
- <state>stable</state>
- <notes>* Added/fixed phpDocumentor code documentation.
-
-
-</notes>
- </release>
- <release>
- <version>1.0.1</version>
- <date>2004-04-17</date>
- <state>stable</state>
- <notes>* Fixed a bug that let the HTML GUI fail for expected and/or actual results with newline characters. (Patch by Thiemo Maettig &lt;thiemo.maettig@gmx.de&gt;)
-
-* Fixed bug #1169.
-
-
-</notes>
- </release>
- <release>
- <version>1.0.0</version>
- <date>2004-03-15</date>
- <state>stable</state>
- <notes>* No functional changes since PHPUnit-0.6.2.
-
-
-</notes>
- </release>
- <release>
- <version>0.6.2</version>
- <date>2003-06-21</date>
- <notes>* Fixed PHPUnit_Assert::assertType().
-
-
-</notes>
- </release>
- <release>
- <version>0.6.1</version>
- <date>2003-05-15</date>
- <notes>+ Added assertType() assertion method.
-
-* Fixed parse error in GUI/HTML.php that occured with PHP 5.
-
-* Fixed a layout issue in the HTML GUI.
-
-
-</notes>
- </release>
- <release>
- <version>0.6</version>
- <date>2003-04-25</date>
- <notes>* Fixed bug that caused the constructor detection in PHPUnit_TestSuite to fail with upper-case class names.
-
-* Fixed bug with multiple assertions per Test Case.
-
-* call_user_func() was called with a copy instead of a reference in PHPUnit_TestCase::runTest().
-
-* Assertion methods append the generated actual/expected message to a user-defined message, rather than overwriting it.
-
-* Constructors are now excluded from automatic TestCase creation in TestSuite::addTestSuite(). (Patch by Wolfram Kriesing &lt;wolfram@kriesing.de&gt;.)
-
-* serialize() was called twice in PHPUnit_Assert::assertEquals().
-
-
-</notes>
- </release>
- <release>
- <version>0.5</version>
- <date>2003-03-26</date>
- <notes>+ Added new HTML GUI. (Patch by Wolfram Kriesing &lt;wolfram@kriesing.de&gt;.)
-
-+ Added &quot;loosely typed&quot; mode to assertEquals() that can be turned on/off using setLooselyTyped(). When activated, array elements are cast to strings before comparison.
-
-* Allow multiple assertions per Test Case.
-
-* Use call_user_func() instead of $object-&gt;$method().
-
-
-</notes>
- </release>
- <release>
- <version>0.4</version>
- <date>2002-09-25</date>
- <notes>+ Added PHPUnit_Assert::assertFalse() and PHPUnit_Assert::assertNotSame(). JUnit introduced those two convenience methods in the JUnit 3.8 release.
-
-* Fixed directory structure.
-
-
-</notes>
- </release>
- <release>
- <version>0.3</version>
- <date>2002-07-12</date>
- <notes>* Added PHPUnit_TestDecorator and PHPUnit_RepeatedTest.
-
-* Implemented PHPUnit_TestResult::addListener() and PHPUnit_TestResult::removeListener().
-
-* Added object support to PHPUnit_Assert::assertEquals().
-
-* Implemented PHPUnit_Assert::assertSame() using Zend Engine 2 object handles.
-
-
-</notes>
- </release>
- <release>
- <version>0.2</version>
- <date>2002-07-11</date>
- <notes>* Added Array support to PHPUnit_Assert::equals(). (Patch by Wolfram Kriesing &lt;wolfram@kriesing.de&gt;)
-
-* Added PHPUnit_Assert::assertRegExp(). (Patch by M@rms &lt;marms@marms.com&gt;)
-
-
-</notes>
- </release>
- <release>
- <version>0.1</version>
- <date>2002-04-06</date>
- <notes>First release.
-
-
-</notes>
- </release>
- </changelog>
-</package>
diff --git a/inc/packages/XML_Parser.xml b/inc/packages/XML_Parser.xml
deleted file mode 100644
index 9b4b0269faf..00000000000
--- a/inc/packages/XML_Parser.xml
+++ /dev/null
@@ -1,254 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1" ?>
-<!DOCTYPE package SYSTEM "http://pear.php.net/dtd/package-1.0">
-<package version="1.0" packagerversion="1.4.0a9">
- <name>XML_Parser</name>
- <summary>XML parsing class based on PHP's bundled expat</summary>
- <description>This is an XML parser based on PHPs built-in xml extension.
-It supports two basic modes of operation: &quot;func&quot; and &quot;event&quot;. In &quot;func&quot; mode, it will look for a function named after each element (xmltag_ELEMENT for start tags and xmltag_ELEMENT_ for end tags), and in &quot;event&quot; mode it uses a set of generic callbacks.
-
-Since version 1.2.0 there's a new XML_Parser_Simple class that makes parsing of most XML documents easier, by automatically providing a stack for the elements.
-Furthermore its now possible to split the parser from the handler object, so you do not have to extend XML_Parser anymore in order to parse a document with it.
- </description>
- <maintainers>
- <maintainer>
- <user>schst</user>
- <name>Stephan Schmidt</name>
- <email>schst@php-tools.net</email>
- <role>lead</role>
- </maintainer>
- <maintainer>
- <user>ssb</user>
- <name>Stig S&amp;#230;ther Bakken</name>
- <email>stig@php.net</email>
- <role>developer</role>
- </maintainer>
- <maintainer>
- <user>cox</user>
- <name>Tomas V.V.Cox</name>
- <email>cox@php.net</email>
- <role>developer</role>
- </maintainer>
- </maintainers>
- <release>
- <version>1.2.6</version>
- <date>2005-03-25</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>- fixed Bug #3949: reset does not return true on success as the documentation states
-- implement Request #3905: replace &quot;.&quot; with &quot;_&quot; in tagnames when using func mode
-- added package2.xml file for PEAR 1.4.0
- </notes>
- <deps>
- <dep type="php" rel="ge" version="4.2.0" optional="no"/>
- <dep type="pkg" rel="has" optional="no">PEAR</dep>
- </deps>
- <filelist>
- <file role="doc" baseinstalldir="XML" name="examples/xml_parser_file.php"/>
- <file role="doc" baseinstalldir="XML" name="examples/xml_parser_file.xml"/>
- <file role="doc" baseinstalldir="XML" name="examples/xml_parser_handler.php"/>
- <file role="doc" baseinstalldir="XML" name="examples/xml_parser_simple1.php"/>
- <file role="doc" baseinstalldir="XML" name="examples/xml_parser_simple1.xml"/>
- <file role="doc" baseinstalldir="XML" name="examples/xml_parser_simple2.php"/>
- <file role="doc" baseinstalldir="XML" name="examples/xml_parser_simple2.xml"/>
- <file role="doc" baseinstalldir="XML" name="examples/xml_parser_simple_handler.php"/>
- <file role="php" baseinstalldir="XML" name="Parser/Simple.php"/>
- <file role="test" baseinstalldir="XML" name="tests/001.phpt"/>
- <file role="test" baseinstalldir="XML" name="tests/002.phpt"/>
- <file role="test" baseinstalldir="XML" name="tests/003.phpt"/>
- <file role="test" baseinstalldir="XML" name="tests/004.phpt"/>
- <file role="test" baseinstalldir="XML" name="tests/005.phpt"/>
- <file role="test" baseinstalldir="XML" name="tests/test2.xml"/>
- <file role="test" baseinstalldir="XML" name="tests/test3.xml"/>
- <file role="php" baseinstalldir="XML" name="Parser.php"/>
- </filelist>
- </release>
- <changelog>
- <release>
- <version>1.1.0beta1</version>
- <date>2004-04-16</date>
- <license>PHP License</license>
- <state>beta</state>
- <notes>- Fixed memory leaks parsing many documents or big files (mroch)
-- Fixed setInput() url detection regex (mroch)
-- Added setInputString() method, allowing strings to be passed as input (schst)
-- Error handling rewritten (cox)
-- Increased the overall parsing speed (cox)
-- Added free() method (schst
-- Added reset() method, that is called when parsing a document so it is possible to parse more than one document per instance (schst)
-- Added error codes (schst)
-- revamped documentation (cox, schst)
-- Fixed bug #516 (url fopen and safe mode) (schst)
-- Fixed bug #637 (dependency on PEAR) (schst)
-- improved parse() and parseString() to be able to parse more than one document (schst)
-- added PHP5 constructor (schst)
-- moved xml_parser_create() to _create() for PHP5 compatibility (schst)
-- added dependency on PHP 4.2
-
-Thanks to Marshall Roch for commments and contributions and Tomas V.V. Cox
-for applying a lot of fixes and improvements.
- </notes>
- </release>
- <release>
- <version>1.1.0beta2</version>
- <date>2004-04-18</date>
- <license>PHP License</license>
- <state>beta</state>
- <notes>beta2:
-- Fixed calling of __construct
-
-beta1:
-- Fixed memory leaks parsing many documents or big files (mroch)
-- Fixed setInput() url detection regex (mroch)
-- Added setInputString() method, allowing strings to be passed as input (schst)
-- Error handling rewritten (cox)
-- Increased the overall parsing speed (cox)
-- Added free() method (schst
-- Added reset() method, that is called when parsing a document so it is possible to parse more than one document per instance (schst)
-- Added error codes (schst)
-- revamped documentation (cox, schst)
-- Fixed bug #516 (url fopen and safe mode) (schst)
-- Fixed bug #637 (dependency on PEAR) (schst)
-- improved parse() and parseString() to be able to parse more than one document (schst)
-- added PHP5 constructor (schst)
-- moved xml_parser_create() to _create() for PHP5 compatibility (schst)
-- added dependency on PHP 4.2
-
-Thanks to Marshall Roch for commments and contributions and Tomas V.V. Cox
-for applying a lot of fixes and improvements.
- </notes>
- </release>
- <release>
- <version>1.1.0</version>
- <date>2004-04-23</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>- Fixed memory leaks parsing many documents or big files (mroch)
-- Fixed setInput() url detection regex (mroch)
-- Added setInputString() method, allowing strings to be passed as input (schst)
-- Error handling rewritten (cox)
-- Increased the overall parsing speed (cox)
-- Added free() method (schst
-- Added reset() method, that is called when parsing a document so it is possible to parse more than one document per instance (schst)
-- Added error codes (schst)
-- revamped documentation (cox, schst)
-- Fixed bug #516 (url fopen and safe mode) (schst)
-- Fixed bug #637 (dependency on PEAR) (schst)
-- improved parse() and parseString() to be able to parse more than one document (schst)
-- added PHP5 constructor (schst)
-- moved xml_parser_create() to _create() for PHP5 compatibility (schst)
-- added dependency on PHP 4.2
-
-Thanks to Marshall Roch for commments and contributions and Tomas V.V. Cox
-for applying a lot of fixes and improvements.
- </notes>
- </release>
- <release>
- <version>1.2.0beta1</version>
- <date>2004-05-17</date>
- <license>PHP License</license>
- <state>beta</state>
- <notes>added new class XML_Parser_Simple that provides a stack for the elements so the user only needs to implement one method to handle the tag and cdata.
- </notes>
- </release>
- <release>
- <version>1.2.0beta2</version>
- <date>2004-05-24</date>
- <license>PHP License</license>
- <state>beta</state>
- <notes>XML_Parser:
-- fixed bug with setMode()
-- moved the init routines for the handlers in _initHandlers()
-XML_Parser_Simple:
-- fixed bug with character data (did not get parsed)
-- fixed bug with setMode()
-- some refactoring
-- added getCurrentDepth() to retrieve the tag depth
-- added addToData()
-- added new example
- </notes>
- </release>
- <release>
- <version>1.2.0beta3</version>
- <date>2004-05-25</date>
- <license>PHP License</license>
- <state>beta</state>
- <notes>- added setHandlerObj() which allows you to have the parser separate from the handler methods
- </notes>
- </release>
- <release>
- <version>1.2.0</version>
- <date>2004-05-28</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>- added setHandlerObj() which allows you to have the parser separate from the handler methods
-- fixed bug with setMode()
-- moved the init routines for the handlers in _initHandlers()
-- added new examples
-- fixed test files so they do not fail because of different resource ids
-XML_Parser_Simple:
-- added new class XML_Parser_Simple that provides a stack for the elements so the user only needs to implement one method to handle the tag and cdata.
- </notes>
- </release>
- <release>
- <version>1.2.1</version>
- <date>2004-10-04</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>fixed bug #2442: Call to &quot;xmltag_ELEMENT_&quot; not correctly managed in function funcEndHandler
- </notes>
- </release>
- <release>
- <version>1.2.2beta1</version>
- <date>2004-12-22</date>
- <license>PHP License</license>
- <state>beta</state>
- <notes>- fixed small notice in XML_Parser::free(),
-- fixed Bug #2939: bug in error routine leads to segmentation fault (raiseError does not free the internal resources anymore)
- </notes>
- </release>
- <release>
- <version>1.2.2</version>
- <date>2004-12-22</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>- fixed small notice in XML_Parser::free(),
-- fixed Bug #2939: bug in error routine leads to segmentation fault (raiseError does not free the internal resources anymore)
- </notes>
- </release>
- <release>
- <version>1.2.3</version>
- <date>2005-01-17</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>- fixed a bug that occured when using 'func' mode and setHandlerObj() (schst)
-- added default handlers for 'func' mode (schst)
- </notes>
- </release>
- <release>
- <version>1.2.4</version>
- <date>2005-01-18</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>- fixed a bug in XML_Parser_Simple when trying to register more than the default handlers and a separate callback object (schst)
- </notes>
- </release>
- <release>
- <version>1.2.5</version>
- <date>2005-02-26</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>- fixed Bug #3557 (removed $attribs parameter, which caused a notice)
-- fixed Bug #3277 (remove obsolete ini_set('allow_url_fopen'))
- </notes>
- </release>
- <release>
- <version>1.2.6</version>
- <date>2005-03-25</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>- fixed Bug #3949: reset does not return true on success as the documentation states
-- implement Request #3905: replace &quot;.&quot; with &quot;_&quot; in tagnames when using func mode
- </notes>
- </release>
- </changelog>
-</package>
diff --git a/inc/packages/XML_RPC.xml b/inc/packages/XML_RPC.xml
deleted file mode 100644
index 44e94882647..00000000000
--- a/inc/packages/XML_RPC.xml
+++ /dev/null
@@ -1,266 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1" ?>
-<!DOCTYPE package SYSTEM "http://pear.php.net/dtd/package-1.0">
-<package version="1.0" packagerversion="1.4.0a12">
- <name>XML_RPC</name>
- <summary>PHP implementation of the XML-RPC protocol</summary>
- <description>A PEAR-ified version of Useful Inc's XML-RPC for PHP.
-
-It has support for HTTP/HTTPS transport, proxies and authentication.
- </description>
- <maintainers>
- <maintainer>
- <user>ssb</user>
- <name>Stig Bakken</name>
- <email>stig@php.net</email>
- <role>lead</role>
- </maintainer>
- <maintainer>
- <user>danielc</user>
- <name>Daniel Convissor</name>
- <email>danielc@php.net</email>
- <role>lead</role>
- </maintainer>
- </maintainers>
- <release>
- <version>1.4.0</version>
- <date>2005-08-14</date>
- <license>PHP License</license>
- <state>stable</state>
- <notes>* MAJOR SECURITY FIX: eliminate use of eval().
-* Using socket_get_status() because stream_get_meta_data() was introduced in 4.3.0, but we need to support 4.2.0. Bug 4805.
- </notes>
- <filelist>
- <file role="php" baseinstalldir="XML" name="RPC.php">
- <replace from="@package_version@" to="version" type="package-info"/>
- </file>
- <file role="php" baseinstalldir="XML/RPC" name="Server.php">
- <replace from="@package_version@" to="version" type="package-info"/>
- </file>
- <file role="php" baseinstalldir="XML/RPC" name="Dump.php">
- <replace from="@package_version@" to="version" type="package-info"/>
- </file>
- <file role="test" name="tests/protoport.php">
- <replace from="@package_version@" to="version" type="package-info"/>
- </file>
- <file role="test" name="tests/test_Dump.php">
- <replace from="@package_version@" to="version" type="package-info"/>
- </file>
- </filelist>
- </release>
- <changelog>
- <release>
- <version>1.3.3</version>
- <date>2005-07-15</date>
- <state>stable</state>
- <notes>* Eliminate memory leak by resetting $XML_RPC_xh each time parseResponse() is called. Bug 4780.
-* Using socket_set_timeout() because stream_set_timeout() was introduced in 4.3.0, but we need to support 4.2.0. Bug 4805.
- </notes>
- </release>
- <release>
- <version>1.3.2</version>
- <date>2005-07-07</date>
- <state>stable</state>
- <notes>* Eliminate path disclosure vulnerabilities by suppressing error messages when eval()'ing.
-* Eliminate path disclosure vulnerability by catching bogus parameters submitted to XML_RPC_Value::serializeval().
-* In XML_RPC_Server::service(), only call createServerPayload() and createServerHeaders() if necessary. Fixes compatibility issue introduced in Release 1.3.0RC1 for users who set the $serviceNow parameter of XML_RPC_Server() to 0. Bug 4757.
-* Change &quot;var $errstring&quot; to &quot;var $errstr&quot;. Bug 4582. Was put into CVS version 1.75 of RPC.php but didn't make it into RELEASE_1_3_1.
- </notes>
- </release>
- <release>
- <version>1.3.1</version>
- <date>2005-06-29</date>
- <state>stable</state>
- <notes>* Security fix. Update highly recommended!
- </notes>
- </release>
- <release>
- <version>1.3.0</version>
- <date>2005-06-13</date>
- <state>stable</state>
- <notes>* Stable release. See earlier releases for changes since 1.2.2.
- </notes>
- </release>
- <release>
- <version>1.3.0RC3</version>
- <date>2005-05-10</date>
- <state>beta</state>
- <notes>* When verifying requests against function signatures, if the number of parameters don't match, provide an appropriate message. NOTE: this resolves a path disclosure vulnerability. (Refines the changes made in the last commit.) Bug 4231.
-* XML_RPC_Message::getParam() now returns an XML_RPC_Response object upon error. Changed from Release 1.3.0RC2.
-* Add the XML_RPC_Value::isValue() method. For testing if an item is an XML_RPC_Value object.
-* If XML_RPC_Client::send() is given an incorrect $msg parameter, raise an error with the new XML_RPC_ERROR_PROGRAMMING code and return 0.
-* Improve cross-platform operation by using PEAR::loadExtension() instead of dl().
-* Use &lt;br /&gt; instead of &lt;br&gt; in XML_RPC_Value::dump().
- </notes>
- </release>
- <release>
- <version>1.3.0RC2</version>
- <date>2005-05-05</date>
- <state>beta</state>
- <notes>* If XML_RPC_Message::getParam() is given an incorrect parameter, raise an error with the new XML_RPC_ERROR_INCORRECT_PARAMS code and return FALSE.
-* Handle improper requests to XML_RPC_Server::verifySignature(). Bug 4231.
-* Try to allow HTTP 100 responses if followed by a 200 response. Bug 4116.
-* Help Delphi users by making RPCMETHODNAME an alias for METHODNAME. Request 4205.
- </notes>
- </release>
- <release>
- <version>1.3.0RC1</version>
- <date>2005-04-07</date>
- <state>beta</state>
- <notes>* Improve timeout handling for situations where connection to server is made but no response is not received in time. Accomplished via stream_set_timeout(). Request 3963.
-* Add Fault Code 6: &quot;The requested method didn't return an XML_RPC_Response object.&quot; Request 4032.
-* Add the createServerPayload() and createServerHeaders() methods and the $server_payload and $server_headers properties. Request 3121.
-* As in earlier versions, if the $serviceNow parameter to XML_RPC_Server() is 0, no data will be returned, but now the new $server_payload and $server_headers properties will be set.
-* Convert the parser handle to an integer before using it as an index for $XML_RPC_xh[$parser]. Reduces E_STRICT notices. Bug 3782.
-* Add createHeaders() method and $headers property to XML_RPC_Client to make testing easier.
- </notes>
- </release>
- <release>
- <version>1.2.2</version>
- <date>2005-03-07</date>
- <state>stable</state>
- <notes>* When using a proxy, add the protocol to the Request-URI, making it an &quot;absoluteURI&quot; as per the HTTP 1.0 spec. Bug 3679.
- </notes>
- </release>
- <release>
- <version>1.2.1</version>
- <date>2005-03-01</date>
- <state>stable</state>
- <notes>* Add isset() check before examining the dispatch map. Bug 3658.
- </notes>
- </release>
- <release>
- <version>1.2.0</version>
- <date>2005-02-27</date>
- <state>stable</state>
- <notes>* Provide the &quot;stable&quot; release.
-* Add package2.xml for compatibility with PEAR 1.4.0.
-* For changes since 1.1.0, see the changelogs for the various RC releases.
- </notes>
- </release>
- <release>
- <version>1.2.0RC7</version>
- <date>2005-02-22</date>
- <state>beta</state>
- <notes>* Add the setSendEncoding() method and $send_encoding
- property to XML_RPC_Message. Request 3537.
-* Allow class methods to be mapped using either syntax:
- 'function' =&gt; 'hello::sayHello',
- or
- 'function' =&gt; array('hello', 'sayhello'),
- Bug 3363.
-* Use 8192 instead of 32768 for bytes in fread()
- in parseResponseFile(). Bug 3340.
- </notes>
- </release>
- <release>
- <version>1.2.0RC6</version>
- <date>2005-01-25</date>
- <state>beta</state>
- <notes>* Don't put the protocol in the Host field of the POST data. (danielc)
- </notes>
- </release>
- <release>
- <version>1.2.0RC5</version>
- <date>2005-01-24</date>
- <state>beta</state>
- <notes>* If $port is 443 but a protocol isn't specified in $server, assume ssl:// is the protocol.
- </notes>
- </release>
- <release>
- <version>1.2.0RC4</version>
- <date>2005-01-24</date>
- <state>beta</state>
- <notes>* When a connection attempt fails, have the method return 0. (danielc)
-* Move the protocol/port checking/switching and the property settings from sendPayloadHTTP10() to the XML_RPC_Client constructor. (danielc)
-* Add tests for setting the client properties. (danielc)
-* Remove $GLOBALS['XML_RPC_twoslash'] since it's not used. (danielc)
-* Bundle the tests with the package. (danielc)
- </notes>
- </release>
- <release>
- <version>1.2.0RC3</version>
- <date>2005-01-19</date>
- <state>beta</state>
- <notes>* ssl uses port 443, not 445.
- </notes>
- </release>
- <release>
- <version>1.2.0RC2</version>
- <date>2005-01-11</date>
- <state>beta</state>
- <notes>* Handle ssl:// in the $server string. (danielc)
-* Also default to port 445 for ssl:// requests as well. (danielc)
-* Enhance debugging in the server. (danielc)
- </notes>
- </release>
- <release>
- <version>1.2.0RC1</version>
- <date>2004-12-30</date>
- <state>beta</state>
- <notes>* Make things work with SSL. Bug 2489. (nkukard lbsd net)
-* Allow array function callbacks (Matt Kane)
-* Some minor speed-ups (Matt Kane)
-* Add Dump.php to the package (Christian Weiske)
-* Replace all line endings with \r\n. Had only done replacements on \n. Bug 2521. (danielc)
-* Silence fsockopen() errors. Bug 1714. (danielc)
-* Encode empty arrays as an array. Bug 1493. (danielc)
-* Eliminate undefined index notice when submitting empty arrays to XML_RPC_Encode(). Bug 1819. (danielc)
-* Speed up check for enumerated arrays in XML_RPC_Encode(). (danielc)
-* Prepend &quot;XML_RPC_&quot; to ERROR_NON_NUMERIC_FOUND, eliminating problem when eval()'ing error messages. (danielc)
-* Use XML_RPC_Base::raiseError() instead of PEAR::raiseError() in XML_RPC_ee() because PEAR.php is lazy loaded. (danielc)
-* Allow raiseError() to be called statically. (danielc)
-* Stop double escaping of character entities. Bug 987. (danielc)
- NOTICE: the following have been removed:
- * XML_RPC_dh()
- * $GLOBALS['XML_RPC_entities']
- * XML_RPC_entity_decode()
- * XML_RPC_lookup_entity()
-* Determine the XML's encoding via the encoding attribute in the XML declaration. Bug 52. (danielc)
- </notes>
- </release>
- <release>
- <version>1.1.0</version>
- <date>2004-03-15</date>
- <state>stable</state>
- <notes>* Added support for sequential arrays to XML_RPC_encode() (mroch)
-* Cleaned up new XML_RPC_encode() changes a bit (mroch, pierre)
-* Remove &quot;require_once 'PEAR.php'&quot;, include only when needed to raise an error
-* Replace echo and error_log() with raiseError() (mroch)
-* Make all classes extend XML_RPC_Base, which will handle common functions (mroch)
-* be tolerant of junk after methodResponse (Luca Mariano, mroch)
-* Silent notice even in the error log (pierre)
-* fix include of shared xml extension on win32 (pierre)
- </notes>
- </release>
- <release>
- <version>1.0.4</version>
- <date>2002-10-02</date>
- <state>stable</state>
- <notes>* added HTTP proxy authorization support (thanks to Arnaud Limbourg)
- </notes>
- </release>
- <release>
- <version>1.0.3</version>
- <date>2002-05-19</date>
- <state>stable</state>
- <notes>* fix bug when parsing responses with boolean types
- </notes>
- </release>
- <release>
- <version>1.0.2</version>
- <date>2002-04-16</date>
- <state>stable</state>
- <notes>* E_ALL fixes
-* fix HTTP response header parsing
- </notes>
- </release>
- <release>
- <version>1.0.1</version>
- <date>2001-09-25</date>
- <state>stable</state>
- <notes>This is a PEAR-ified version of Useful Inc's 1.0.1 release.
-Includes an urgent security fix identified by Dan Libby &lt;dan@libby.com&gt;.
- </notes>
- </release>
- </changelog>
-</package>
diff --git a/inc/pearcmd.php b/inc/pearcmd.php
deleted file mode 100644
index 28a81dcf67f..00000000000
--- a/inc/pearcmd.php
+++ /dev/null
@@ -1,318 +0,0 @@
-<?php
-//
-// +----------------------------------------------------------------------+
-// | PHP Version 5 |
-// +----------------------------------------------------------------------+
-// | Copyright (c) 1997-2004 The PHP Group |
-// +----------------------------------------------------------------------+
-// | This source file is subject to version 3.0 of the PHP license, |
-// | that is bundled with this package in the file LICENSE, and is |
-// | available through the world-wide-web at the following url: |
-// | http://www.php.net/license/3_0.txt. |
-// | If you did not receive a copy of the PHP license and are unable to |
-// | obtain it through the world-wide-web, please send a note to |
-// | license@php.net so we can mail you a copy immediately. |
-// +----------------------------------------------------------------------+
-// | Authors: Stig Bakken <ssb@php.net> |
-// | Tomas V.V.Cox <cox@idecnet.com> |
-// | |
-// +----------------------------------------------------------------------+
-//
-// $Id: pearcmd.php,v 1.13.2.2 2004/12/30 05:43:18 cellog Exp $
-
-ob_end_clean();
-/**
- * @nodep Gtk
- */
-if ('@include_path@' != '@'.'include_path'.'@') {
- ini_set('include_path', '@include_path@');
-}
-ini_set('allow_url_fopen', true);
-if (!ini_get('safe_mode')) {
- @set_time_limit(0);
-}
-ob_implicit_flush(true);
-ini_set('track_errors', true);
-ini_set('html_errors', false);
-ini_set('magic_quotes_runtime', false);
-set_error_handler('error_handler');
-
-$pear_package_version = "5.0.4";
-
-require_once 'PEAR.php';
-require_once 'PEAR/Config.php';
-require_once 'PEAR/Command.php';
-require_once 'Console/Getopt.php';
-
-PEAR_Command::setFrontendType('CLI');
-$all_commands = PEAR_Command::getCommands();
-
-$argv = Console_Getopt::readPHPArgv();
-/* $progname = basename($argv[0]); */
-$progname = 'pear';
-if (in_array('getopt2', get_class_methods('Console_Getopt'))) {
- array_shift($argv);
- $options = Console_Getopt::getopt2($argv, "c:C:d:D:Gh?sSqu:vV");
-} else {
- $options = Console_Getopt::getopt($argv, "c:C:d:D:Gh?sSqu:vV");
-}
-if (PEAR::isError($options)) {
- usage($options);
-}
-
-$opts = $options[0];
-
-$fetype = 'CLI';
-if ($progname == 'gpear' || $progname == 'pear-gtk') {
- $fetype = 'Gtk';
-} else {
- foreach ($opts as $opt) {
- if ($opt[0] == 'G') {
- $fetype = 'Gtk';
- }
- }
-}
-PEAR_Command::setFrontendType($fetype);
-$ui = &PEAR_Command::getFrontendObject();
-PEAR::setErrorHandling(PEAR_ERROR_CALLBACK, array($ui, "displayFatalError"));
-if (ini_get('safe_mode')) {
- $ui->outputData('WARNING: running in safe mode requires that all files created ' .
- 'be the same uid as the current script. PHP reports this script is uid: ' .
- @getmyuid() . ', and current user is: ' . @get_current_user());
-}
-
-$pear_user_config = '';
-$pear_system_config = '';
-$store_user_config = false;
-$store_system_config = false;
-$verbose = 1;
-
-foreach ($opts as $opt) {
- switch ($opt[0]) {
- case 'c':
- $pear_user_config = $opt[1];
- break;
- case 'C':
- $pear_system_config = $opt[1];
- break;
- }
-}
-
-$config = &PEAR_Config::singleton($pear_user_config, $pear_system_config);
-$verbose = $config->get("verbose");
-$cmdopts = array();
-
-foreach ($opts as $opt) {
- $param = !empty($opt[1]) ? $opt[1] : true;
- switch ($opt[0]) {
- case 'd':
- list($key, $value) = explode('=', $param);
- $config->set($key, $value, 'user');
- break;
- case 'D':
- list($key, $value) = explode('=', $param);
- $config->set($key, $value, 'system');
- break;
- case 's':
- $store_user_config = true;
- break;
- case 'S':
- $store_system_config = true;
- break;
- case 'u':
- $config->remove($param, 'user');
- break;
- case 'v':
- $config->set('verbose', $config->get('verbose') + 1);
- break;
- case 'q':
- $config->set('verbose', $config->get('verbose') - 1);
- break;
- case 'V':
- usage(null, 'version');
- default:
- // all non pear params goes to the command
- $cmdopts[$opt[0]] = $param;
- break;
- }
-}
-
-if ($store_system_config) {
- $config->store('system');
-}
-
-if ($store_user_config) {
- $config->store('user');
-}
-
-$command = (isset($options[1][0])) ? $options[1][0] : null;
-
-if (empty($command) && ($store_user_config || $store_system_config)) {
- exit;
-}
-
-if ($fetype == 'Gtk') {
- Gtk::main();
-} else do {
- if ($command == 'help') {
- usage(null, @$options[1][1]);
- }
-
- PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
- $cmd = PEAR_Command::factory($command, $config);
- PEAR::popErrorHandling();
- if (PEAR::isError($cmd)) {
- usage(null, @$options[1][1]);
- }
-
- $short_args = $long_args = null;
- PEAR_Command::getGetoptArgs($command, $short_args, $long_args);
- if (in_array('getopt2', get_class_methods('Console_Getopt'))) {
- array_shift($options[1]);
- $tmp = Console_Getopt::getopt2($options[1], $short_args, $long_args);
- } else {
- $tmp = Console_Getopt::getopt($options[1], $short_args, $long_args);
- }
- if (PEAR::isError($tmp)) {
- break;
- }
- list($tmpopt, $params) = $tmp;
- $opts = array();
- foreach ($tmpopt as $foo => $tmp2) {
- list($opt, $value) = $tmp2;
- if ($value === null) {
- $value = true; // options without args
- }
- if (strlen($opt) == 1) {
- $cmdoptions = $cmd->getOptions($command);
- foreach ($cmdoptions as $o => $d) {
- if (@$d['shortopt'] == $opt) {
- $opts[$o] = $value;
- }
- }
- } else {
- if (substr($opt, 0, 2) == '--') {
- $opts[substr($opt, 2)] = $value;
- }
- }
- }
- $ok = $cmd->run($command, $opts, $params);
- if ($ok === false) {
- PEAR::raiseError("unknown command `$command'");
- }
-} while (false);
-
-// {{{ usage()
-
-function usage($error = null, $helpsubject = null)
-{
- global $progname, $all_commands;
- $stderr = fopen('php://stderr', 'w');
- if (PEAR::isError($error)) {
- fputs($stderr, $error->getMessage() . "\n");
- } elseif ($error !== null) {
- fputs($stderr, "$error\n");
- }
- if ($helpsubject != null) {
- $put = cmdHelp($helpsubject);
- } else {
- $put =
- "Commands:\n";
- $maxlen = max(array_map("strlen", $all_commands));
- $formatstr = "%-{$maxlen}s %s\n";
- ksort($all_commands);
- foreach ($all_commands as $cmd => $class) {
- $put .= sprintf($formatstr, $cmd, PEAR_Command::getDescription($cmd));
- }
- $put .=
- "Usage: $progname [options] command [command-options] <parameters>\n".
- "Type \"$progname help options\" to list all options.\n".
- "Type \"$progname help shortcuts\" to list all command shortcuts.\n".
- "Type \"$progname help <command>\" to get the help for the specified command.";
- }
- fputs($stderr, "$put\n");
- fclose($stderr);
- exit;
-}
-
-function cmdHelp($command)
-{
- global $progname, $all_commands, $config;
- if ($command == "options") {
- return
- "Options:\n".
- " -v increase verbosity level (default 1)\n".
- " -q be quiet, decrease verbosity level\n".
- " -c file find user configuration in `file'\n".
- " -C file find system configuration in `file'\n".
- " -d foo=bar set user config variable `foo' to `bar'\n".
- " -D foo=bar set system config variable `foo' to `bar'\n".
- " -G start in graphical (Gtk) mode\n".
- " -s store user configuration\n".
- " -S store system configuration\n".
- " -u foo unset `foo' in the user configuration\n".
- " -h, -? display help/usage (this message)\n".
- " -V version information\n";
- } elseif ($command == "shortcuts") {
- $sc = PEAR_Command::getShortcuts();
- $ret = "Shortcuts:\n";
- foreach ($sc as $s => $c) {
- $ret .= sprintf(" %-8s %s\n", $s, $c);
- }
- return $ret;
-
- } elseif ($command == "version") {
- return "PEAR Version: ".$GLOBALS['pear_package_version'].
- "\nPHP Version: ".phpversion().
- "\nZend Engine Version: ".zend_version().
- "\nRunning on: ".php_uname();
-
- } elseif ($help = PEAR_Command::getHelp($command)) {
- if (is_string($help)) {
- return "$progname $command [options] $help\n";
- }
- if ($help[1] === null) {
- return "$progname $command $help[0]";
- } else {
- return "$progname $command [options] $help[0]\n$help[1]";
- }
- }
- return "Command '$command' is not valid, try 'pear help'";
-}
-
-// }}}
-
-function error_handler($errno, $errmsg, $file, $line, $vars) {
- if ((defined('E_STRICT') && $errno & E_STRICT) || !error_reporting()) {
- return; // @silenced error
- }
- $errortype = array (
- E_ERROR => "Error",
- E_WARNING => "Warning",
- E_PARSE => "Parsing Error",
- E_NOTICE => "Notice",
- E_CORE_ERROR => "Core Error",
- E_CORE_WARNING => "Core Warning",
- E_COMPILE_ERROR => "Compile Error",
- E_COMPILE_WARNING => "Compile Warning",
- E_USER_ERROR => "User Error",
- E_USER_WARNING => "User Warning",
- E_USER_NOTICE => "User Notice"
- );
- $prefix = $errortype[$errno];
- $file = basename($file);
- print "\n$prefix: $errmsg in $file on line $line\n";
-}
-
-
-/*
- * Local variables:
- * tab-width: 4
- * c-basic-offset: 4
- * indent-tabs-mode: nil
- * mode: php
- * End:
- */
-// vim600:syn=php
-
-?>
diff --git a/inc/templates/adminform.php b/inc/templates/adminform.php
deleted file mode 100755
index 5a04c4902ac..00000000000
--- a/inc/templates/adminform.php
+++ /dev/null
@@ -1,193 +0,0 @@
-<?php
-global $WEBROOT;
-global $FIRSTRUN;
-global $CONFIG_ENABLEBACKUP;
-global $CONFIG_DATADIRECTORY_ROOT;
-global $CONFIG_BACKUPDIRECTORY;
-global $CONFIG_ERROR;
-$f=@fopen($SERVERROOT.'/config/config.php','a+');
-if(!$f) die('Error: Config file (config/config.php) is not writable for the webserver.<br/>');
-@fclose($f);
-if(!isset($fillDB)) $fillDB=true;
-if(!isset($CONFIG_DBHOST)) $CONFIG_DBHOST='localhost';
-if(!isset($CONFIG_DBUSER)) $CONFIG_DBUSER='owncloud';
-if(!isset($CONFIG_DBTABLEPREFIX)) $CONFIG_DBTABLEPREFIX='oc_';
-?>
-<script type="text/javascript">
-function showDBAdmin(){
- var show=document.getElementById('dbcreate').checked;
- document.getElementById('dbAdminUser').style.display=(show)?'table-row':'none';
- document.getElementById('dbAdminPwd').style.display=(show)?'table-row':'none';
-}
-
-function showBackupPath(){
- var show=document.getElementById('enablebackup').checked;
- document.getElementById('backupdir').style.display=(show)?'table-row':'none';
-}
-
-function dbtypechange(){
- var dropdown=action=document.getElementById('dbtype');
- if (dropdown){
- var type=dropdown.options[dropdown.selectedIndex].value;
- var inputs=Array('dbhost','dbuser','dbpass','dbpass_retype','dbcreaterow','dbAdminPwd','dbAdminUser','dbname','dbfill','dbtableprefix');
- var id,element;
- if(type=='sqlite'){
- for(i in inputs){
- id=inputs[i];
- element=document.getElementById(id);
- if(element){
- element.style.display='none';
- }
- }
- }else if(type=='mysql' || type=='pgsql'){
- for(i in inputs){
- id=inputs[i];
- element=document.getElementById(id);
- if(element){
- element.style.display='table-row';
- }
- }
- showDBAdmin();
- }
- }
-}
-
-function datetypechange(){
- var dropdown=action=document.getElementById('datetype');
- var type=dropdown.options[dropdown.selectedIndex].value;
-
- var id,element;
- if(type=='custom'){
- element=document.getElementById('trdateformat');
- if(element){
- element.style.display='table-row';
- }
- }else{
- element=document.getElementById('trdateformat');
- if(element){
- element.style.display='none';
- }
- element=document.getElementById('inputdateformat');
- if(element){
- element.value = type;
- }
- }
-}
-</script>
-<?php
-if(!$FIRSTRUN){
- $action=$WEBROOT.'/settings/#system_settings';
-}else{
- $action='#';
-}
-echo('<form method="post" action="'.$action.'">')
-?>
-<table cellpadding="5" cellspacing="5" border="0" class="loginform">
-<?php
- if(!empty($CONFIG_ERROR) and !$FIRSTRUN){
- echo "<tr><td colspan='3' class='error'>$CONFIG_ERROR</td></tr>";
- }
-if($FIRSTRUN){?>
-<tr><th colspan="2">Administrator User</th></tr>
-<tr title="Name used to log in."><td>user name:</td><td><input type="text" name="adminlogin" size="30" class="formstyle" value=""></input></td></tr>
-<tr title="Make a secure password, use at least 9 characters. Use letters and numbers."><td>password:</td><td><input type="password" name="adminpassword" size="30" class="formstyle"></input></td></tr>
-<tr title="Retype password to avoid typing errors."><td>retype password:</td><td><input type="password" name="adminpassword2" size="30" class="formstyle"></input></td></tr>
-<?php
-}
-?>
-<tr><th colspan="2">Advanced Configuration</th></tr>
-<?php if($FIRSTRUN){?>
-<tr title="This directory is used to store files."><td>data directory:</td><td><input type="text" name="datadirectory" size="30" class="formstyle" value="<?php echo($CONFIG_DATADIRECTORY_ROOT);?>"></input></td></tr>
-<?php } ?>
-<tr title="Using SSL is more secure but requires specific configurations. Click the link to test SSL on your server."><td>force ssl: (<a href="https://<?php echo($_SERVER["HTTP_HOST"].$WEBROOT);?>" target="_blank">test SLL</a>)</td><td><input type="checkbox" name="forcessl" size="30" class="formstyle" value='1' <?php if($CONFIG_HTTPFORCESSL) echo 'checked="checked"'?>></input></td></tr>
-<tr title="If something goes wrong, it is often possible to protect your data using a back-up."><td>automatic backup:</td><td><input type="checkbox" name="enablebackup" id="enablebackup" onchange='showBackupPath()' size="30" class="formstyle" value='1' <?php if($CONFIG_ENABLEBACKUP) echo 'checked'?>></input></td></tr>
-<tr title="This directory is used to store backups." id='backupdir'><td>&nbsp; - backup directory:</td><td><input type="text" name="backupdirectory" size="30" class="formstyle" value="<?php echo($CONFIG_BACKUPDIRECTORY);?>"></input></td></tr>
-<tr><td>date format:</td><td><select id='datetype' name="datetype" onchange='datetypechange()'>
- <option value='<?php echo($CONFIG_DATEFORMAT);?>'><?php echo(date($CONFIG_DATEFORMAT));?></option>
- <!-- dd-mm-yyyy yyyy-mm-dd mm-dd-yyyy -->
- <optgroup label="DD-MM-YYYY">
- <option value='j M Y G:i'><?php echo(date('j M Y G:i'));?></option>
- <option value='j M Y'><?php echo(date('j M Y'));?></option>
- <option value='D j M Y G:i:s'><?php echo(date('D j M Y G:i:s'));?></option>
- <option value='l j F'><?php echo(date('l j F'));?></option>
- <option value='d-m-Y G:i'><?php echo(date('d-m-Y H:i'));?></option>
- </optgroup>
- <optgroup label="MM-DD-YYYY">
- <option value='M j Y G:i'><?php echo(date('M j Y G:i'));?></option>
- <option value='M j Y'><?php echo(date('M j Y'));?></option>
- </optgroup>
- <optgroup label="YYYY-MM-DD">
- <option value='Y M j G:i'><?php echo(date('Y M j G:i'));?></option>
- <option value='Y M j'><?php echo(date('Y M j'));?></option>
- </optgroup>
- <option value='custom'>Custom Date</option>
-</select></td></tr>
-<tr id='trdateformat'><td>&nbsp; - custom date:</td><td><input type="text" id="inputdateformat" name="dateformat" size="30" class="formstyle" value='<?php echo($CONFIG_DATEFORMAT);?>'></input></td></tr>
-<?php if($FIRSTRUN){
- if(!is_callable('sqlite_open')){
- echo '<tr><td colspan="2">No SQLite support detected, make sure you have both sqlite and the sqlite php module installed (sqlite and php5-sqlite for Debian/Ubuntu)</td></tr>';
- }
-?>
-<tr title="SQLite is usually the easiest database to work with."><td>database type:</td><td>
-<select id='dbtype' name="dbtype" onchange='dbtypechange()'>
-<?php
-global $CONFIG_DBTYPE;
-if($CONFIG_DBTYPE=='sqlite'){
- if(is_callable('sqlite_open')){
- echo "<option value='sqlite'>SQLite</option>";
- }
- if(is_callable('mysql_connect')){
- echo "<option value='mysql'>MySQL</option>";
- }
- if(is_callable('pg_connect')){
- echo "<option value='pgsql'>PostgreSQL</option>";
- }
-}elseif($CONFIG_DBTYPE=='mysql'){
- if(is_callable('mysql_connect')){
- echo "<option value='mysql'>MySQL</option>";
- }
- if(is_callable('sqlite_open')){
- echo "<option value='sqlite'>SQLite</option>";
- }
- if(is_callable('pg_connect')){
- echo "<option value='pgsql'>PostgreSQL</option>";
- }
-}elseif($CONFIG_DBTYPE=='pgsql'){
- if(is_callable('pg_connect')){
- echo "<option value='pgsql'>PostgreSQL</option>";
- }
- if(is_callable('mysql_connect')){
- echo "<option value='mysql'>MySQL</option>";
- }
- if(is_callable('sqlite_open')){
- echo "<option value='sqlite'>SQLite</option>";
- }
-}
-?>
-</select>
-</td></tr>
-<tr title="The database server. In most cases, localhost works fine." id='dbhost'><td>&nbsp; - database host:</td><td><input type="text" name="dbhost" size="30" class="formstyle" value='<?php echo($CONFIG_DBHOST);?>'></input></td></tr>
-<tr title="The name of the database." id='dbname'><td>&nbsp; - database name:</td><td><input type="text" name="dbname" size="30" class="formstyle" value='<?php echo($CONFIG_DBNAME);?>'></input></td></tr>
-<tr title="Used to avoid conflict between web-applications. Don't use the same prefix for two web-applications." id='dbtableprefix'><td>&nbsp; - table prefix:</td><td><input type="text" name="dbtableprefix" size="30" class="formstyle" value='<?php echo($CONFIG_DBTABLEPREFIX);?>'></input></td></tr>
-<tr title="The user of the database. If possible avoid the root user." id='dbuser'><td>&nbsp; - database user:</td><td><input type="text" name="dbuser" size="30" class="formstyle" value='<?php echo($CONFIG_DBUSER);?>'></input></td></tr>
-<tr title="The password of the database." id='dbpass'><td>&nbsp; &nbsp; &nbsp; - password:</td><td><input type="password" name="dbpassword" size="30" class="formstyle" value=''></input></td></tr>
-<tr title="Retype password to avoid typing errors." id='dbpass_retype'><td>&nbsp; &nbsp; &nbsp; - retype password:</td><td><input type="password" name="dbpassword2" size="30" class="formstyle" value=''></input></td></tr>
-<tr title="Automatically create a database and user for ownCloud." id='dbcreaterow'><td>&nbsp; - create database and user:</td><td><input id='dbcreate' type="checkbox" name="createdatabase" size="30" class="formstyle" value='1' checked="checked" onchange='showDBAdmin()'></input></td></tr>
-<tr title="The administrative database user. This is often 'root'. If in doubt, contact your web-host" id='dbAdminUser'><td>&nbsp; &nbsp; &nbsp; - administrative user:</td><td><input type="text" name="dbadminuser" size="30" class="formstyle" value='root'></input></td></tr>
-<tr title="The password of the administrative database user. If in doubt, contact your web-host." id='dbAdminPwd'><td>&nbsp; &nbsp; &nbsp; - administrative password:</td><td><input type="password" name="dbadminpwd" size="30" class="formstyle" value=''></input></td></tr>
-<tr title="Fill database with default data so you can start right away." id='dbfill'><td>&nbsp; - fill initial database:</td><td><input type="checkbox" name="filldb" size="30" class="formstyle" value='1' checked="checked"></input></td></tr>
-<?php }?>
-<tr><th colspan="2">Confirmation</th></tr>
-<?php
- if(!$FIRSTRUN){?>
- <tr title="This is to avoid abuse while you are away and have not logged out decently."><td>your password:</td><td><input type="password" name="currentpassword" size="30" class="formstyle"></input></td></tr>
- <?php
- }
-?>
-<tr><td></td><td><input type="submit" name="set_config" alt="save" value="save" class="formstyle" /></td></tr>
-</table></form><br/>
-<script type="text/javascript">
- dbtypechange();
- datetypechange();
- showBackupPath();
-</script>
diff --git a/inc/templates/configform.php b/inc/templates/configform.php
deleted file mode 100644
index 76c73cb8887..00000000000
--- a/inc/templates/configform.php
+++ /dev/null
@@ -1,36 +0,0 @@
-<?php
-global $FIRSTRUN;
-global $WEBROOT;
-global $CONFIG_ERROR;
-if(!isset($fillDB)) $fillDB=true;
-if(!isset($CONFIG_DBHOST)) $CONFIG_DBHOST='localhost';
-if(!isset($CONFIG_DBUSER)) $CONFIG_DBUSER='owncloud';
-$newuserpassword=OC_USER::generatepassword();
-?>
-<script type="text/javascript">
-changepassset=function(){
- var change=document.getElementById('changepass').checked;
- if(!change){
- document.getElementById('new_password').style.display='none';
- document.getElementById('new_password_retype').style.display='none';
- }else{
- document.getElementById('new_password').style.display='table-row';
- document.getElementById('new_password_retype').style.display='table-row';
- }
-}
-</script>
-<form method="post" enctype="multipart/form-data" action="<?php echo($WEBROOT);?>/settings/#">
-<div><input type='hidden' name='config' value='1' /></div>
-<table cellpadding="5" cellspacing="5" border="0" class="loginform">
-<?php
- if(!empty($CONFIG_ERROR) and !$FIRSTRUN){
- echo "<tr><td colspan='3' class='error'>$CONFIG_ERROR</td></tr>";
- }
-?>
-<tr><td>enter password</td><td><input type="password" name="currentpassword" size="30" class="formstyle"></input></td></tr>
-<tr><td>change password:</td><td><input onchange='changepassset()' id='changepass' type="checkbox" name="changepass" size="30" class="formstyle" value='1'></input></td></tr>
-<tr style='display:none' id='new_password'><td>new password:</td><td><input type="password" name="password" size="30" class="formstyle"></input></td></tr>
-<tr style='display:none' id='new_password_retype'><td>retype admin password:</td><td><input type="password" name="password2" size="30" class="formstyle"></input></td></tr>
-<tr><td></td><td><input type='submit' value='save' class='formstyle'/></td></tr>
-</table>
-</form>
diff --git a/inc/templates/footer.php b/inc/templates/footer.php
deleted file mode 100644
index 56f4fce1952..00000000000
--- a/inc/templates/footer.php
+++ /dev/null
@@ -1,26 +0,0 @@
-<?php
-global $WEBROOT;
-?>
-</div>
-<div class='foot'>
-<?php
-if(!OC_UTIL::hasSmallScreen()){
- if (isset($_SERVER['HTTPS'])) {
- $PROTO="webdavs://";
- } else {
- $PROTO="webdav://";
- }
-?>
-<div class='bar'><p class="hint">
-Hint: Mount it via webdav like this: <a href="<?php echo($PROTO.$_SERVER["HTTP_HOST"].$WEBROOT.'/webdav/owncloud.php');?>"><?php echo($PROTO.$_SERVER["HTTP_HOST"].$WEBROOT);?>/webdav/owncloud.php</a>
-</p></div>
-<?php }?>
-<p class="footer">
-<?php
- $version=implode('.',OC_UTIL::getVersion());
- echo('<a href="http://ownCloud.org">ownCloud</a> - '.$version);
-?>
-</p>
-</div>
-</div>
-</body></html>
diff --git a/inc/templates/header.php b/inc/templates/header.php
deleted file mode 100644
index 4593af59518..00000000000
--- a/inc/templates/header.php
+++ /dev/null
@@ -1,90 +0,0 @@
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
- "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
-<html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
- <title>ownCloud</title>
- <base href="<?php echo($WEBROOT); ?>/"/>
- <link rel="stylesheet" type="text/css" href="<?php
- if(!OC_UTIL::hasSmallScreen()){
- echo($WEBROOT.'/css/default.php');
- }else{
- echo($WEBROOT.'/css/small.php');
- }
- ?>"/>
- <script type='text/ecmascript' src='<?php echo($WEBROOT)?>/js/lib_ajax.js'></script>
- <?php
- global $CONFIG_INSTALLED;
- if($CONFIG_INSTALLED){//the javascripts somehow breaks the first run wizzard in konqueror?>
- <script type='text/ecmascript' src='<?php echo($WEBROOT)?>/js/lib_timer.js'></script>
- <script type='text/ecmascript' src='<?php echo($WEBROOT)?>/js/lib_notification.js'></script>
- <script type='text/ecmascript' src='<?php echo($WEBROOT)?>/js/lib_xmlloader.js'></script>
- <script type='text/ecmascript' src='<?php echo($WEBROOT)?>/js/lib_files.js'></script>
- <script type='text/ecmascript' src='<?php echo($WEBROOT)?>/js/lib_event.js'></script>
- <script type='text/ecmascript' src='<?php echo($WEBROOT)?>/js/lib_drag.js'></script>
- <script type='text/ecmascript' src='<?php echo($WEBROOT)?>/js/lib_api.js'></script>
- <script type='text/ecmascript' src='<?php echo($WEBROOT)?>/js/filebrowser.js'></script>
- <?php
- }
- ?>
-<?php
-foreach(OC_UTIL::$scripts as $script){
- echo("<script type='text/ecmascript' src='$WEBROOT/$script'></script>\n");
-}
-foreach(OC_UTIL::$styles as $style){
- echo("<link rel='stylesheet' type='text/css' href='$WEBROOT/$style'/>\n");
-}
-?>
- <script type='text/ecmascript'>
- var WEBROOT='<?php echo($WEBROOT)?>';
- var SMALLSCREEN='<?php echo((OC_UTIL::hasSmallScreen())?'true':'false')?>';
- </script>
- </head>
- <body onload='OC_onload.run()'>
-<div id='mainlayout'>
-<div class='head'>
-<?php
-global $CONFIG_ERROR;
-if(!OC_UTIL::hasSmallScreen()){
- echo('<h1><a id="owncloud-logo" href="'.$WEBROOT.'"><span>ownCloud</span></a></h1>');
-}
-
-
- // check if already configured. otherwise start configuration wizard
- $error=OC_CONFIG::writeadminlistener();
- if($e=OC_CONFIG::configlistener()){
- $error.=$e;
- }
- if($e=OC_CONFIG::createuserlistener()){
- $error.=$e;
- }
- if($e=OC_CONFIG::creategrouplistener()){
- $error.=$e;
- }
- $CONFIG_ERROR=$error;
- global $CONFIG_INSTALLED;
- if(!$CONFIG_INSTALLED) {
- global $FIRSTRUN;
- $FIRSTRUN=true;
- echo('</div><div class="body">');
- echo('<div class="center">');
- echo('<p class="errortext">'.$error.'</p>');
- echo('<p class="highlighttext">First Run Wizard</p>');
- OC_CONFIG::showadminform();
- echo('</div>');
- OC_UTIL::showfooter();
- exit();
- }elseif(!isset($_SESSION['username']) or $_SESSION['username']=='') { // show the loginform if not loggedin
- echo('<div class="center">');
- OC_UTIL::showloginform();
- echo('</div>');
- OC_UTIL::showfooter();
- exit();
- }else{
- echo('<div id="nav" class="center">');
- OC_UTIL::shownavigation();
- echo('</div>');
- echo('</div><div class="body">');
- }
-
-?>
diff --git a/inc/templates/loginform.php b/inc/templates/loginform.php
deleted file mode 100644
index 41c86eef013..00000000000
--- a/inc/templates/loginform.php
+++ /dev/null
@@ -1,9 +0,0 @@
-<?php
-if(isset($loginresult) and $loginresult=='error') echo('<p class="errortext">login failed</p>');
-?>
-<form method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
-<table cellpadding="5" cellspacing="5" border="0" class="loginform">
-<tr><td>login:</td><td><input type="text" name="login" size="30" class="formstyle"></input></td></tr>
-<tr><td>password:</td><td><input type="password" name="password" size="30" class="formstyle"></input></td></tr>
-<tr><td></td><td><input type="submit" name="loginbutton" alt="login" value="login" class="formstyle" /></td></tr>
-</table></form>
diff --git a/inc/templates/pluginform.php b/inc/templates/pluginform.php
deleted file mode 100644
index 01410f9c829..00000000000
--- a/inc/templates/pluginform.php
+++ /dev/null
@@ -1,77 +0,0 @@
-<?php
-$action=$WEBROOT.'/settings/#plugin_management';
-if(isset($_POST['plugin_disable_id'])){
- $id=$_POST['plugin_disable_id'];
- $disable=$_POST['plugin_disable'];
- if($disable=='true'){
- OC_PLUGIN::addToBlacklist($id);
- }else{
- OC_PLUGIN::removeFromBlacklist($id);
- }
- header('location: '.$action);
- die();
-}
-
-if(isset($_POST['install_plugin']) and $_POST['install_plugin']=='true'){
- $file=$_FILES['plugin_file']['tmp_name'];
- OC_PLUGIN::installPlugin($file);
- header('location: '.$action);
- die();
-}
-$plugins=OC_PLUGIN::listPlugins();
-$blacklist=OC_PLUGIN::loadBlackList();
-?>
-<script type="text/javascript">
-<?php
- echo('var plugins='.json_encode($plugins).";\n");
- echo('var blacklist='.json_encode($blacklist).";\n");
-?>
-
-disablePlugin=function(id,disable){
- var form=document.getElementById('disableForm');
- var input=document.getElementById('plugin_disable_name');
- input.value=id;
- var input=document.getElementById('plugin_disable');
- input.value=disable;
- form.submit();
-}
-</script>
-<p class='description'>Plugin List</p>
-<form id='disableForm' action='<?php echo($action);?>' method="post" enctype="multipart/form-data">
-<input id='plugin_disable_name' type='hidden' name='plugin_disable_id' value=''/>
-<input id='plugin_disable' type='hidden' name='plugin_disable' value=''/>
-</form>
-<table class='pluginlist'>
- <thead>
- <tr>
- <td colspan='2'>Id</td>
- <td>Version</td>
- <td>Description</td>
- <td>Author</td>
- </tr>
- </thead>
- <tbody>
- <?php
- foreach($plugins as $plugin){
- $pluginData=OC_PLUGIN::getPluginData($plugin);
- $enabled=(array_search($plugin,$blacklist)===false);
- $enabledString=($enabled)?'enabled':'disabled';
- $enabledStringOther=(!$enabled)?'enable':'disable';
- $enabled=($enabled)?'true':'false';
- echo("<tr class='$enabledString'>\n");
- echo("<td class='name'>$plugin</td>");
- echo("<td class='disable'>(<a href='$action' onclick='disablePlugin(\"$plugin\",$enabled)'>$enabledStringOther</a>)</td>");
- echo("<td class='version'>{$pluginData['info']['version']}</td>");
- echo("<td>{$pluginData['info']['name']}</td>");
- echo("<td>{$pluginData['info']['author']}</td>");
- echo("</tr>\n");
- }
- ?>
- </tbody>
-</table>
-<p class='description'>Install Plugin</p>
-<form action='<?php echo($action);?>' method="post" enctype="multipart/form-data">
- <input class='formstyle' type='file' name='plugin_file'/>
- <input type='hidden' name='install_plugin' value='true'/>
- <input class='formstyle' type='submit'/>
-</form> \ No newline at end of file
diff --git a/inc/templates/settings.php b/inc/templates/settings.php
deleted file mode 100755
index 5df6b70f5af..00000000000
--- a/inc/templates/settings.php
+++ /dev/null
@@ -1,50 +0,0 @@
-<script type="text/javascript">
-function showForm(id){
- hideAllForms();
- form=document.getElementById('settingsContent_'+id);
- form.setAttribute('class','settingsContent');
-}
-
-function showFormInit(){
- var loc=document.location.toString();
- if(loc.indexOf('#')!=-1){
- var id=loc.substring(loc.indexOf('#')+1);
- showForm(id);
- }
-}
-
-function hideAllForms(){
- forms=document.getElementById('settingsHolder').childNodes;
- for(var i=0;i<forms.length;i++){
- form=forms.item(i);
- if(form.nodeType==1 && (form.tagName=='div' || form.tagName=='DIV')){
- form.setAttribute('class','settingsContent hidden');
- }
- }
-}
-</script>
-<div id='settingsNav'>
-<ul>
-<?php
-global $WEBROOT;
-foreach(OC_CONFIG::$forms as $name=>$url){
- $clean=strtolower(str_replace(' ','_',$name));
- echo("<li><a onclick='showForm(\"$clean\")' href='{$WEBROOT}/settings/#$clean'>$name</a></li>\n");
-}
-?>
-</ul>
-</div>
-<div id='settingsHolder'>
-<div class='settingsContent'>Settings</div>
-<?php
-foreach(OC_CONFIG::$forms as $name=>$url){
- $clean=strtolower(str_replace(' ','_',$name));
- echo("<div id='settingsContent_$clean' class='settingsContent hidden'>\n");
- oc_include($url);
- echo("</div>\n");
-}
-?>
-</div>
-<script type="text/javascript">
-OC_onload.add(showFormInit());
-</script> \ No newline at end of file
diff --git a/inc/templates/userform.php b/inc/templates/userform.php
deleted file mode 100644
index dea419159e3..00000000000
--- a/inc/templates/userform.php
+++ /dev/null
@@ -1,126 +0,0 @@
-<?php
-//handle addTo and removeFrom group
-if(isset($_POST['groupAddRemove'])){
- $groupName=$_POST['groupname'];
- $users=explode(';',$_POST['users']);
- if($_POST['groupAddRemove']=='add'){
- foreach($users as $user){
- OC_USER::addToGroup($user,$groupName);
- }
- }elseif($_POST['groupAddRemove']=='remove'){
- foreach($users as $user){
- OC_USER::removeFromGroup($user,$groupName);
- }
- }
-}
-$action=$WEBROOT.'/settings/#user_management';
-if(!empty($CONFIG_ERROR)){
- echo "<p class='error'>$CONFIG_ERROR</p>";
-}
-?>
-<script type="text/javascript">
-<?php
- $users=OC_USER::getUsers();
- $groups=OC_USER::getGroups();
- echo('var users='.json_encode($users).";\n");
- echo('var groups='.json_encode($groups).";\n");
-?>
-sellectAllUsers=function(){
- var check=document.getElementById('user_selectall');
- for(i in users){
- if(users[i]){
- document.getElementById('user_select_'+users[i]).checked=check.checked;
- }
- }
- getSellectedUsers();
-}
-
-getSellectedUsers=function(){
- sellectedUsers=new Array();
- for(i in users){
- if(users[i]){
- if(document.getElementById('user_select_'+users[i]).checked){
- sellectedUsers.push(users[i]);
- }
- }
- }
- document.getElementById('removeFromGroupUsers').value=sellectedUsers.join(';');
- document.getElementById('addToGroupUsers').value=sellectedUsers.join(';');
-}
-
-var sellectedUsers=new Array();
-
-setGroup=function(){
- var select=document.getElementById('groupselect');
- var group=select.options[select.selectedIndex].value;
- document.getElementById('addToGroupName').value=group;
- document.getElementById('removeFromGroupName').value=group;
-}
-
-</script>
-<p class='description'>All Users</p>
-<table class='userlist'>
- <thead>
- <tr>
- <td class='sellect'><input type='checkbox' id='user_selectall' onchange='sellectAllUsers()' class='formstyle'/></td>
- <td class='name'>Name</td>
- <td class='groups'>Groups</td>
- </tr>
- </thead>
- <tbody>
- <?php
- foreach($users as $user){
- if($user){
- echo("<tr>\n");
- echo("<td class='sellect'><input type='checkbox' onchange='getSellectedUsers()' id='user_select_$user' class='formstyle'/></td>\n");
- echo("<td class='name'>$user</td>\n");
- $userGroups=OC_USER::getUserGroups($user);
- foreach($userGroups as &$userGroup){
- $userGroup=OC_USER::getGroupName($userGroup);
- }
- $userGroups=join(', ',$userGroups);
- echo("<td class='groups'>$userGroups</td>\n");
- echo("</tr>\n");
- }
- }
- ?>
- </tbody>
-</table>
-<div id='sellectedUsersActions'>
-Groups <select id='groupselect' onchange='setGroup()'>
-<?php
-foreach($groups as $group){
- echo("<option value='$group'>$group</option>");
-}
-?>
-</select>
-<form id='addToGroupForm' method="post" enctype="multipart/form-data" action="<?php echo($action);?>">
-<input type='hidden' name='groupAddRemove' value='add'></input>
-<input id='addToGroupName' type='hidden' name='groupname' value='<?php echo($groups[0]);?>'></input>
-<input id='addToGroupUsers' type='hidden' name='users' value=''></input>
-<input type='submit' value='Add'></input>
-</form>
-<form id='removeFromGroupForm' method="post" enctype="multipart/form-data" action="<?php echo($action);?>">
-<input type='hidden' name='groupAddRemove' value='remove'></input>
-<input id='removeFromGroupName' type='hidden' name='groupname' value='<?php echo($groups[0]);?>'></input>
-<input id='removeFromGroupUsers' type='hidden' name='users' value=''></input>
-<input type='submit' value='Remove'></input>
-</form>
-</div>
-<p class='description'>Add User</p>
-<?php
-$newuserpassword=OC_USER::generatepassword();
-?>
-<form id='newUserForm' method="post" enctype="multipart/form-data" action="<?php echo($action);?>">
-user name: <input type='text' name='new_username' class="formstyle"></input>
-password <input type='text' name='new_password' class="formstyle" autocomplete="off" value='<?php echo($newuserpassword);?>'></input>
-&nbsp;&nbsp;<input type='submit' value='create' class="formstyle"></input>
-</form>
-<p class='description'>Add Group</p>
-<form id='newGroupForm' method="post" enctype="multipart/form-data" action="<?php echo($action);?>">
-<input type='hidden' name='creategroup' value='1' />
-<input type='text' name='groupname' class="formstyle"></input>
-<input type='submit' value='create' class="formstyle"></input>
-</form>
-
-