diff --git a/.htaccess b/.htaccess index 69dddc9abb6f4010d8b83094199e2029c32030ea..095a0cc6375baff9be13b2a485a873fde15b2015 100644 --- a/.htaccess +++ b/.htaccess @@ -1,9 +1,5 @@ ErrorDocument 403 /core/templates/403.php ErrorDocument 404 /core/templates/404.php -Redirect 301 /apps/calendar/caldav.php /remote.php/caldav/ -Redirect 301 /apps/contacts/carddav.php /remote.php/carddav/ -Redirect 301 /apps/files/webdav.php /remote.php/webdav/ -Redirect 301 /files/webdav.php /remote.php/webdav/ php_value upload_max_filesize 512M php_value post_max_size 512M @@ -18,6 +14,8 @@ RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}] RewriteRule ^.well-known/host-meta /public.php?service=host-meta [QSA,L] RewriteRule ^.well-known/carddav /remote.php/carddav/ [R] RewriteRule ^.well-known/caldav /remote.php/caldav/ [R] +RewriteRule ^apps/calendar/caldav.php remote.php/caldav/ [QSA,L] +RewriteRule ^apps/contacts/carddav.php remote.php/carddav/ [QSA,L] RewriteRule ^apps/([^/]*)/(.*\.(css|php))$ index.php?app=$1&getfile=$2 [QSA,L] RewriteRule ^remote/(.*) remote.php [QSA,L] diff --git a/3rdparty/Archive/Tar.php b/3rdparty/Archive/Tar.php index d8eae851bdcde846279a7832bbfca0ac9181c7db..e9969501a077e663795602476398bdd6c754c8f8 100644 --- a/3rdparty/Archive/Tar.php +++ b/3rdparty/Archive/Tar.php @@ -577,7 +577,7 @@ class Archive_Tar extends PEAR } // ----- Get the arguments - $v_att_list = &func_get_args(); + $v_att_list = func_get_args(); // ----- Read the attributes $i=0; diff --git a/3rdparty/MDB2.php b/3rdparty/MDB2.php index 2814f88ac0cd24e0cfcaab34710e86d6058e5810..a0ead9b9bcf27784b020c2b4fef3b08b17c4ee21 100644 --- a/3rdparty/MDB2.php +++ b/3rdparty/MDB2.php @@ -1,4270 +1,4587 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: MDB2.php 295587 2010-02-28 17:16:38Z quipo $ -// - -/** - * @package MDB2 - * @category Database - * @author Lukas Smith - */ - -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 - */ -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 - */ - static 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 - */ - static function classExists($classname) - { - return class_exists($classname, false); - } - - // }}} - // {{{ 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 - */ - static function loadClass($class_name, $debug) - { - if (!MDB2::classExists($class_name)) { - $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php'; - if ($debug) { - $include = include_once($file_name); - } else { - $include = @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; - } - if (!MDB2::classExists($class_name)) { - $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 - * - * @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 - */ - static 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 - * - * @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 - */ - static 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. - * - * @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 - */ - static 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'])) { - return $GLOBALS['_MDB2_databases'][key($GLOBALS['_MDB2_databases'])]; - } - $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 - */ - static 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 $file name of the file in the MDB2 directory (without '.php') - * - * @return string name of the file that was included - * - * @access public - */ - static 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.0b3'; - } - - // }}} - // {{{ 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 - */ - static function isError($data, $code = null) - { - if ($data instanceof MDB2_Error) { - if (null === $code) { - return true; - } - if (is_string($code)) { - return $data->getMessage() === $code; - } - return in_array($data->getCode(), (array)$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 ($value instanceof MDB2_Driver_Common); - } - - // }}} - // {{{ function isResult($value) - - /** - * Tell whether a value is a MDB2 result - * - * @param mixed $value value to test - * - * @return bool whether $value is a MDB2 result - * - * @access public - */ - function isResult($value) - { - return ($value instanceof MDB2_Result); - } - - // }}} - // {{{ function isResultCommon($value) - - /** - * Tell whether a value is a MDB2 result implementing the common interface - * - * @param mixed $value value to test - * - * @return bool whether $value is a MDB2 result implementing the common interface - * - * @access public - */ - static function isResultCommon($value) - { - return ($value instanceof 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 ($value instanceof 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 (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: - * - * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true - * - * - * Most variations are allowed: - * - * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644 - * phptype://username:password@hostspec/database_name - * phptype://username:password@hostspec - * phptype://username@hostspec - * phptype://hostspec/database - * phptype://hostspec - * phptype(dbsyntax) - * phptype - * - * - * @param string 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 - */ - static 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; - $pos = strrpos($proto_opts, '/'); - $dsn = substr($proto_opts, $pos + 1); - $proto_opts = substr($proto_opts, 0, $pos); - } 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¶m2=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 (!array_key_exists($key, $parsed) || false === $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 - */ - static function fileExists($file) - { - // safe_mode does notwork with is_readable() - if (!@ini_get('safe_mode')) { - $dirs = explode(PATH_SEPARATOR, ini_get('include_path')); - 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 - */ -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 __construct($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN, - $level = E_USER_NOTICE, $debuginfo = null, $dummy = null) - { - if (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 - */ -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: - *
    - *
  • $options['ssl'] -> boolean: determines if ssl should be used for connections
  • - *
  • $options['field_case'] -> CASE_LOWER|CASE_UPPER: determines what case to force on field/table names
  • - *
  • $options['disable_query'] -> boolean: determines if queries should be executed
  • - *
  • $options['result_class'] -> string: class used for result sets
  • - *
  • $options['buffered_result_class'] -> string: class used for buffered result sets
  • - *
  • $options['result_wrap_class'] -> string: class used to wrap result sets into
  • - *
  • $options['result_buffering'] -> boolean should results be buffered or not?
  • - *
  • $options['fetch_class'] -> string: class to use when fetch mode object is used
  • - *
  • $options['persistent'] -> boolean: persistent connection?
  • - *
  • $options['debug'] -> integer: numeric debug level
  • - *
  • $options['debug_handler'] -> string: function/method that captures debug messages
  • - *
  • $options['debug_expanded_output'] -> bool: BC option to determine if more context information should be send to the debug handler
  • - *
  • $options['default_text_field_length'] -> integer: default text field length to use
  • - *
  • $options['lob_buffer_length'] -> integer: LOB buffer length
  • - *
  • $options['log_line_break'] -> string: line-break format
  • - *
  • $options['idxname_format'] -> string: pattern for index name
  • - *
  • $options['seqname_format'] -> string: pattern for sequence name
  • - *
  • $options['savepoint_format'] -> string: pattern for auto generated savepoint names
  • - *
  • $options['statement_format'] -> string: pattern for prepared statement names
  • - *
  • $options['seqcol_name'] -> string: sequence column name
  • - *
  • $options['quote_identifier'] -> boolean: if identifier quoting should be done when check_option is used
  • - *
  • $options['use_transactions'] -> boolean: if transaction use should be enabled
  • - *
  • $options['decimal_places'] -> integer: number of decimal places to handle
  • - *
  • $options['portability'] -> integer: portability constant
  • - *
  • $options['modules'] -> array: short to long module name mapping for __call()
  • - *
  • $options['emulate_prepared'] -> boolean: force prepared statements to be emulated
  • - *
  • $options['datatype_map'] -> array: map user defined datatypes to other primitive datatypes
  • - *
  • $options['datatype_map_callback'] -> array: callback function/method that should be called
  • - *
  • $options['bindname_format'] -> string: regular expression pattern for named parameters
  • - *
  • $options['multi_query'] -> boolean: determines if queries returning multiple result sets should be executed
  • - *
  • $options['max_identifiers_length'] -> integer: max identifier length
  • - *
  • $options['default_fk_action_onupdate'] -> string: default FOREIGN KEY ON UPDATE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']
  • - *
  • $options['default_fk_action_ondelete'] -> string: default FOREIGN KEY ON DELETE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']
  • - *
- * - * @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; - } - - // }}} - // {{{ 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 ((null === $mode) && !empty($this->_default_error_mode)) { - $mode = $this->_default_error_mode; - $options = $this->_default_error_options; - } - if (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 ((null !== $native_errno) && $native_errno !== '') { - $userinfo.= "[Native code: $native_errno]\n"; - } - if ((null !== $native_msg) && $native_msg !== '') { - $userinfo.= "[Native message: ". strip_tags($native_msg) ."]\n"; - } - if (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 (`) -- due to MySQL - * + double quote (") -- due to Oracle - * + brackets ([ or ]) -- due to Access - * - * Delimited identifiers are known to generally work correctly under - * the following drivers: - * + mssql - * + mysql - * + mysqli - * + oci8 - * + 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 (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 (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_resource, $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_resource, $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_resource); - 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_resource, $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_resource, $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 (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 (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 (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 = array(); - $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 - */ -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 - */ -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 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 (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 (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 - */ -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]; - } - } - - // }}} -} - -// }}} -// {{{ class MDB2_Statement_Common - -/** - * The common statement class for MDB2 statement objects - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -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 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 (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 (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 (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 (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 - */ -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 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 + | +// +----------------------------------------------------------------------+ +// +// $Id$ +// + +/** + * @package MDB2 + * @category Database + * @author Lukas Smith + */ + +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 + */ +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 + */ + static function setOptions($db, $options) + { + if (is_array($options)) { + foreach ($options as $option => $value) { + $test = $db->setOption($option, $value); + if (MDB2::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 + */ + static function classExists($classname) + { + return class_exists($classname, false); + } + + // }}} + // {{{ 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 + */ + static function loadClass($class_name, $debug) + { + if (!MDB2::classExists($class_name)) { + $file_name = str_replace('_', DIRECTORY_SEPARATOR, $class_name).'.php'; + if ($debug) { + $include = include_once($file_name); + } else { + $include = @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; + } + if (!MDB2::classExists($class_name)) { + $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 + * + * @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 + */ + static 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 (MDB2::isError($err)) { + return $err; + } + + $db = new $class_name(); + $db->setDSN($dsninfo); + $err = MDB2::setOptions($db, $options); + if (MDB2::isError($err)) { + return $err; + } + + return $db; + } + + // }}} + // {{{ function connect($dsn, $options = false) + + /** + * Create a new MDB2_Driver_* connection object and connect to the specified + * database + * + * @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 + */ + static function connect($dsn, $options = false) + { + $db = MDB2::factory($dsn, $options); + if (MDB2::isError($db)) { + return $db; + } + + $err = $db->connect(); + if (MDB2::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. + * + * @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 + */ + static 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'])) { + return $GLOBALS['_MDB2_databases'][key($GLOBALS['_MDB2_databases'])]; + } + $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 + */ + static 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 $file name of the file in the MDB2 directory (without '.php') + * + * @return string name of the file that was included + * + * @access public + */ + static 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 '@package_version@'; + } + + // }}} + // {{{ 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 + */ + public static function &raiseError($code = null, + $mode = null, + $options = null, + $userinfo = null, + $dummy1 = null, + $dummy2 = null, + $dummy3 = false) + { + $pear = new PEAR; + $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 + */ + static function isError($data, $code = null) + { + if ($data instanceof MDB2_Error) { + if (null === $code) { + return true; + } + if (is_string($code)) { + return $data->getMessage() === $code; + } + return in_array($data->getCode(), (array)$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 + */ + static function isConnection($value) + { + return ($value instanceof MDB2_Driver_Common); + } + + // }}} + // {{{ function isResult($value) + + /** + * Tell whether a value is a MDB2 result + * + * @param mixed $value value to test + * + * @return bool whether $value is a MDB2 result + * + * @access public + */ + function isResult($value) + { + return ($value instanceof MDB2_Result); + } + + // }}} + // {{{ function isResultCommon($value) + + /** + * Tell whether a value is a MDB2 result implementing the common interface + * + * @param mixed $value value to test + * + * @return bool whether $value is a MDB2 result implementing the common interface + * + * @access public + */ + static function isResultCommon($value) + { + return ($value instanceof 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 ($value instanceof 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 + */ + static 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 (null === $value) { + return $errorMessages; + } + + if (MDB2::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: + * + * phptype(dbsyntax)://username:password@protocol+hostspec/database?option=8&another=true + * + * + * Most variations are allowed: + * + * phptype://username:password@protocol+hostspec:110//usr/db_file.db?mode=0644 + * phptype://username:password@hostspec/database_name + * phptype://username:password@hostspec + * phptype://username@hostspec + * phptype://hostspec/database + * phptype://hostspec + * phptype(dbsyntax) + * phptype + * + * + * @param string 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 + */ + static 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; + $pos = strrpos($proto_opts, '/'); + $dsn = substr($proto_opts, $pos + 1); + $proto_opts = substr($proto_opts, 0, $pos); + } 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'] = rawurldecode($dsn); + // /database?param1=value1¶m2=value2 + } else { + $parsed['database'] = rawurldecode(substr($dsn, 0, $pos)); + $dsn = substr($dsn, $pos + 1); + if (strpos($dsn, '&') !== false) { + $opts = explode('&', $dsn); + } else { // database?param1=value1 + $opts = array($dsn); + } + foreach ($opts as $opt) { + list($key, $value) = explode('=', $opt); + if (!array_key_exists($key, $parsed) || false === $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 + */ + static function fileExists($file) + { + // safe_mode does notwork with is_readable() + if (!@ini_get('safe_mode')) { + $dirs = explode(PATH_SEPARATOR, ini_get('include_path')); + 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 + */ +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 __construct($code = MDB2_ERROR, $mode = PEAR_ERROR_RETURN, + $level = E_USER_NOTICE, $debuginfo = null, $dummy = null) + { + if (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 + */ +class MDB2_Driver_Common +{ + // {{{ Variables (Properties) + + /** + * @var MDB2_Driver_Datatype_Common + */ + public $datatype; + + /** + * @var MDB2_Extended + */ + public $extended; + + /** + * @var MDB2_Driver_Function_Common + */ + public $function; + + /** + * @var MDB2_Driver_Manager_Common + */ + public $manager; + + /** + * @var MDB2_Driver_Native_Commonn + */ + public $native; + + /** + * @var MDB2_Driver_Reverse_Common + */ + public $reverse; + + /** + * index of the MDB2 object within the $GLOBALS['_MDB2_databases'] array + * @var int + * @access public + */ + public $db_index = 0; + + /** + * DSN used for the next query + * @var array + * @access protected + */ + public $dsn = array(); + + /** + * DSN that was used to create the current connection + * @var array + * @access protected + */ + public $connected_dsn = array(); + + /** + * connection resource + * @var mixed + * @access protected + */ + public $connection = 0; + + /** + * if the current opened connection is a persistent connection + * @var bool + * @access protected + */ + public $opened_persistent; + + /** + * the name of the database for the next query + * @var string + * @access public + */ + public $database_name = ''; + + /** + * the name of the database currently selected + * @var string + * @access protected + */ + public $connected_database_name = ''; + + /** + * server version information + * @var string + * @access protected + */ + public $connected_server_info = ''; + + /** + * list of all supported features of the given driver + * @var array + * @access public + */ + public $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: + *
    + *
  • $options['ssl'] -> boolean: determines if ssl should be used for connections
  • + *
  • $options['field_case'] -> CASE_LOWER|CASE_UPPER: determines what case to force on field/table names
  • + *
  • $options['disable_query'] -> boolean: determines if queries should be executed
  • + *
  • $options['result_class'] -> string: class used for result sets
  • + *
  • $options['buffered_result_class'] -> string: class used for buffered result sets
  • + *
  • $options['result_wrap_class'] -> string: class used to wrap result sets into
  • + *
  • $options['result_buffering'] -> boolean should results be buffered or not?
  • + *
  • $options['fetch_class'] -> string: class to use when fetch mode object is used
  • + *
  • $options['persistent'] -> boolean: persistent connection?
  • + *
  • $options['debug'] -> integer: numeric debug level
  • + *
  • $options['debug_handler'] -> string: function/method that captures debug messages
  • + *
  • $options['debug_expanded_output'] -> bool: BC option to determine if more context information should be send to the debug handler
  • + *
  • $options['default_text_field_length'] -> integer: default text field length to use
  • + *
  • $options['lob_buffer_length'] -> integer: LOB buffer length
  • + *
  • $options['log_line_break'] -> string: line-break format
  • + *
  • $options['idxname_format'] -> string: pattern for index name
  • + *
  • $options['seqname_format'] -> string: pattern for sequence name
  • + *
  • $options['savepoint_format'] -> string: pattern for auto generated savepoint names
  • + *
  • $options['statement_format'] -> string: pattern for prepared statement names
  • + *
  • $options['seqcol_name'] -> string: sequence column name
  • + *
  • $options['quote_identifier'] -> boolean: if identifier quoting should be done when check_option is used
  • + *
  • $options['use_transactions'] -> boolean: if transaction use should be enabled
  • + *
  • $options['decimal_places'] -> integer: number of decimal places to handle
  • + *
  • $options['portability'] -> integer: portability constant
  • + *
  • $options['modules'] -> array: short to long module name mapping for __call()
  • + *
  • $options['emulate_prepared'] -> boolean: force prepared statements to be emulated
  • + *
  • $options['datatype_map'] -> array: map user defined datatypes to other primitive datatypes
  • + *
  • $options['datatype_map_callback'] -> array: callback function/method that should be called
  • + *
  • $options['bindname_format'] -> string: regular expression pattern for named parameters
  • + *
  • $options['multi_query'] -> boolean: determines if queries returning multiple result sets should be executed
  • + *
  • $options['max_identifiers_length'] -> integer: max identifier length
  • + *
  • $options['default_fk_action_onupdate'] -> string: default FOREIGN KEY ON UPDATE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']
  • + *
  • $options['default_fk_action_ondelete'] -> string: default FOREIGN KEY ON DELETE action ['RESTRICT'|'NO ACTION'|'SET DEFAULT'|'SET NULL'|'CASCADE']
  • + *
+ * + * @var array + * @access public + * @see MDB2::connect() + * @see MDB2::factory() + * @see MDB2::singleton() + * @see MDB2_Driver_Common::setOption() + */ + public $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 public + */ + public $string_quoting = array( + 'start' => "'", + 'end' => "'", + 'escape' => false, + 'escape_pattern' => false, + ); + + /** + * identifier quoting + * @var array + * @access public + */ + public $identifier_quoting = array( + 'start' => '"', + 'end' => '"', + 'escape' => '"', + ); + + /** + * sql comments + * @var array + * @access protected + */ + public $sql_comments = array( + array('start' => '--', 'end' => "\n", 'escape' => false), + array('start' => '/*', 'end' => '*/', 'escape' => false), + ); + + /** + * comparision wildcards + * @var array + * @access protected + */ + protected $wildcards = array('%', '_'); + + /** + * column alias keyword + * @var string + * @access protected + */ + public $as_keyword = ' AS '; + + /** + * warnings + * @var array + * @access protected + */ + public $warnings = array(); + + /** + * string with the debugging information + * @var string + * @access public + */ + public $debug_output = ''; + + /** + * determine if there is an open transaction + * @var bool + * @access protected + */ + public $in_transaction = false; + + /** + * the smart transaction nesting depth + * @var int + * @access protected + */ + public $nested_transaction_counter = null; + + /** + * the first error that occured inside a nested transaction + * @var MDB2_Error|bool + * @access protected + */ + protected $has_transaction_error = false; + + /** + * result offset used in the next query + * @var int + * @access public + */ + public $offset = 0; + + /** + * result limit used in the next query + * @var int + * @access public + */ + public $limit = 0; + + /** + * Database backend used in PHP (mysql, odbc etc.) + * @var string + * @access public + */ + public $phptype; + + /** + * Database used with regards to SQL syntax etc. + * @var string + * @access public + */ + public $dbsyntax; + + /** + * the last query sent to the driver + * @var string + * @access public + */ + public $last_query; + + /** + * the default fetchmode used + * @var int + * @access public + */ + public $fetchmode = MDB2_FETCHMODE_ORDERED; + + /** + * array of module instances + * @var array + * @access protected + */ + protected $modules = array(); + + /** + * determines of the PHP4 destructor emulation has been enabled yet + * @var array + * @access protected + */ + protected $destructor_registered = true; + + /** + * @var PEAR + */ + protected $pear; + + // }}} + // {{{ 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; + $this->pear = new PEAR; + } + + // }}} + // {{{ 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 (MDB2::isError($code)) { + // because we use the static PEAR::raiseError, our global + // handler should be used if it is set + if ((null === $mode) && !empty($this->_default_error_mode)) { + $mode = $this->_default_error_mode; + $options = $this->_default_error_options; + } + if (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 ((null !== $native_errno) && $native_errno !== '') { + $userinfo.= "[Native code: $native_errno]\n"; + } + if ((null !== $native_msg) && $native_msg !== '') { + $userinfo.= "[Native message: ". strip_tags($native_msg) ."]\n"; + } + if (null !== $method) { + $userinfo = $method.': '.$userinfo; + } + } + + $err = $this->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 (`) -- due to MySQL + * + double quote (") -- due to Oracle + * + brackets ([ or ]) -- due to Access + * + * Delimited identifiers are known to generally work correctly under + * the following drivers: + * + mssql + * + mysql + * + mysqli + * + oci8 + * + 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 (MDB2::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 (MDB2::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 (MDB2::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 (MDB2::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 (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 (!MDB2::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 (!MDB2::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 (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 (MDB2::isError($connection)) { + return $connection; + } + + $result = $this->_doQuery($query, $is_manip, $connection, false); + if (MDB2::isError($result)) { + return $result; + } + + if ($is_manip) { + $affected_rows = $this->_affectedRows($connection, $result); + return $affected_rows; + } + $result = $this->_wrapResult($result, $types, true, true, $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 (MDB2::isError($result)) { + return $result; + } + $query = $result; + } + $err = MDB2_Driver_Common::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 MDB2_Driver_Common::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 (MDB2::isError($connection)) { + return $connection; + } + + $result = $this->_doQuery($query, true, $connection, $this->database_name); + if (MDB2::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 = true) + { + $offset = $this->offset; + $limit = $this->limit; + $this->offset = $this->limit = 0; + $query = $this->_modifyQuery($query, false, $limit, $offset); + + $connection = $this->getConnection(); + if (MDB2::isError($connection)) { + return $connection; + } + + $result = $this->_doQuery($query, false, $connection, $this->database_name); + if (MDB2::isError($result)) { + return $result; + } + + $result = $this->_wrapResult($result, $types, $result_class, $result_wrap_class, $limit, $offset); + return $result; + } + + // }}} + // {{{ function _wrapResult($result_resource, $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_resource, $types = array(), $result_class = true, + $result_wrap_class = true, $limit = null, $offset = null) + { + if ($types === true) { + if ($this->supports('result_introspection')) { + $this->loadModule('Reverse', null, true); + $tableInfo = $this->reverse->tableInfo($result_resource); + if (MDB2::isError($tableInfo)) { + return $tableInfo; + } + $types = array(); + $types_assoc = array(); + foreach ($tableInfo as $field) { + $types[] = $field['mdb2type']; + $types_assoc[$field['name']] = $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 = MDB2_Driver_Common::raiseError(MDB2_ERROR_NOT_FOUND, null, null, + 'result class does not exist '.$class_name, __FUNCTION__); + return $err; + } + $result = new $class_name($this, $result_resource, $limit, $offset); + if (!MDB2::isResultCommon($result)) { + $err = MDB2_Driver_Common::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 (MDB2::isError($err)) { + $result->free(); + return $err; + } + } + if (!empty($types_assoc)) { + $err = $result->setResultTypes($types_assoc); + if (MDB2::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 = MDB2_Driver_Common::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; + } + + return $result_resource; + } + + // }}} + // {{{ 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 MDB2_Driver_Common::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 MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null, + 'limit is not supported by this driver', __FUNCTION__); + } + $limit = (int)$limit; + if ($limit < 0) { + return MDB2_Driver_Common::raiseError(MDB2_ERROR_SYNTAX, null, null, + 'it was not specified a valid selected range row limit', __FUNCTION__); + } + $this->limit = $limit; + if (null !== $offset) { + $offset = (int)$offset; + if ($offset < 0) { + return MDB2_Driver_Common::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 MDB2_Driver_Common::raiseError(MDB2_ERROR_UNSUPPORTED, null, null, + 'method not implemented', __FUNCTION__); + } + + $col = $this->queryCol($query, $type); + if (MDB2::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 MDB2_Driver_Common::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 MDB2_Driver_Common::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 MDB2_Driver_Common::raiseError(MDB2_ERROR_CANNOT_REPLACE, null, null, + 'not specified which fields are keys', __FUNCTION__); + } + + $result = null; + $in_transaction = $this->in_transaction; + if (!$in_transaction && MDB2::isError($result = $this->beginTransaction())) { + return $result; + } + + $connection = $this->getConnection(); + if (MDB2::isError($connection)) { + return $connection; + } + + $condition = ' WHERE '.implode(' AND ', $condition); + $query = 'DELETE FROM ' . $this->quoteIdentifier($table, true) . $condition; + $result = $this->_doQuery($query, true, $connection); + if (!MDB2::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 (!MDB2::isError($result)) { + $affected_rows += $this->_affectedRows($connection, $result);; + } + } + + if (!$in_transaction) { + if (MDB2::isError($result)) { + $this->rollback(); + } else { + $result = $this->commit(); + } + } + + if (MDB2::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 (MDB2::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 (null === $placeholder_type) { + $placeholder_type_guess = $query[$p_position]; + } + + $new_pos = $this->_skipDelimitedStrings($query, $position, $p_position); + if (MDB2::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 (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 = MDB2_Driver_Common::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 = array(); + $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 = MDB2_Driver_Common::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 (MDB2::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 (MDB2::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 (MDB2::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 MDB2_Driver_Common::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 MDB2_Driver_Common::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 MDB2_Driver_Common::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; + } + + // }}} + // {{{ function delExpect($error_code) + + /** + * 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 + * + * @uses PEAR::delExpect() + */ + public function delExpect($error_code) + { + return $this->pear->delExpect($error_code); + } + + // }}} + // {{{ function expectError($code) + + /** + * 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 + * + * @uses PEAR::expectError() + */ + public function expectError($code = '*') + { + return $this->pear->expectError($code); + } + + // }}} + // {{{ function getStaticProperty($class, $var) + + /** + * If you have a class that's mostly/entirely static, and you need static + * properties, you can use this method to simulate them. Eg. in your method(s) + * do this: $myVar = &PEAR::getStaticProperty('myclass', 'myVar'); + * You MUST use a reference, or they will not persist! + * + * @param string $class The calling classname, to prevent clashes + * @param string $var The variable to retrieve. + * @return mixed A reference to the variable. If not set it will be + * auto initialised to NULL. + * + * @uses PEAR::getStaticProperty() + */ + public function &getStaticProperty($class, $var) + { + $tmp = $this->pear->getStaticProperty($class, $var); + return $tmp; + } + + // }}} + // {{{ function loadExtension($ext) + + /** + * 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 + * + * @uses PEAR::loadExtension() + */ + public function loadExtension($ext) + { + return $this->pear->loadExtension($ext); + } + + // }}} + // {{{ function popErrorHandling() + + /** + * Pop the last error handler used + * + * @return bool Always true + * + * @see PEAR::pushErrorHandling + * @uses PEAR::popErrorHandling() + */ + public function popErrorHandling() + { + return $this->pear->popErrorHandling(); + } + + // }}} + // {{{ function popExpect() + + /** + * This method pops one element off the expected error codes + * stack. + * + * @return array the list of error codes that were popped + * + * @uses PEAR::popExpect() + */ + public function popExpect() + { + return $this->pear->popExpect(); + } + + // }}} + // {{{ function pushErrorHandling($mode, $options = null) + + /** + * 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 + * @uses PEAR::pushErrorHandling() + */ + public function pushErrorHandling($mode, $options = null) + { + return $this->pear->pushErrorHandling($mode, $options); + } + + // }}} + // {{{ function registerShutdownFunc($func, $args = array()) + + /** + * Use this function to register a shutdown method for static + * classes. + * + * @param mixed $func The function name (or array of class/method) to call + * @param mixed $args The arguments to pass to the function + * @return void + * + * @uses PEAR::registerShutdownFunc() + */ + public function registerShutdownFunc($func, $args = array()) + { + return $this->pear->registerShutdownFunc($func, $args); + } + + // }}} + // {{{ function setErrorHandling($mode = null, $options = null) + + /** + * 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 + * @uses PEAR::setErrorHandling($mode, $options) + */ + public function setErrorHandling($mode = null, $options = null) + { + return $this->pear->setErrorHandling($mode, $options); + } + + /** + * @uses PEAR::staticPopErrorHandling() + */ + public function staticPopErrorHandling() + { + return $this->pear->staticPopErrorHandling(); + } + + // }}} + // {{{ function staticPushErrorHandling($mode, $options = null) + + /** + * @uses PEAR::staticPushErrorHandling($mode, $options) + */ + public function staticPushErrorHandling($mode, $options = null) + { + return $this->pear->staticPushErrorHandling($mode, $options); + } + + // }}} + // {{{ function &throwError($message = null, $code = null, $userinfo = null) + + /** + * Simpler form of raiseError with fewer options. In most cases + * message, code and userinfo are enough. + * + * @param mixed $message a text error message or a PEAR error object + * + * @param int $code a numeric error code (it is up to your class + * to define these if you want to use codes) + * + * @param string $userinfo If you need to pass along for example debug + * information, this parameter is meant for that. + * + * @return object a PEAR error object + * @see PEAR::raiseError + * @uses PEAR::&throwError() + */ + public function &throwError($message = null, $code = null, $userinfo = null) + { + $tmp = $this->pear->throwError($message, $code, $userinfo); + return $tmp; + } + + // }}} +} + +// }}} +// {{{ class MDB2_Result + +/** + * The dummy class that all user space result classes should extend from + * + * @package MDB2 + * @category Database + * @author Lukas Smith + */ +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 + */ +class MDB2_Result_Common extends MDB2_Result +{ + // {{{ Variables (Properties) + + public $db; + public $result; + public $rownum = -1; + public $types = array(); + public $types_assoc = array(); + public $values = array(); + public $offset; + public $offset_count = 0; + public $limit; + public $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 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 (MDB2::isError($load)) { + return $load; + } + $types = $this->db->datatype->checkResultTypes($types); + if (MDB2::isError($types)) { + return $types; + } + foreach ($types as $key => $value) { + if (is_numeric($key)) { + $this->types[$key] = $value; + } else { + $this->types_assoc[$key] = $value; + } + } + 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 MDB2::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 = MDB2::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) || MDB2::isError($row)) { + return $row; + } + if (!array_key_exists($colnum, $row)) { + return MDB2::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 MDB2::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 (MDB2::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 (MDB2::isError($row)) { + return $row; + } elseif (!$row) { + return $all; + } + + $shift_array = $rekey ? false : null; + if (null !== $shift_array) { + if (is_object($row)) { + $colnum = count(get_object_vars($row)); + } else { + $colnum = count($row); + } + if ($colnum < 2) { + return MDB2::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 + || $fetchmode == MDB2_FETCHMODE_OBJECT + ) { + $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 MDB2::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 MDB2::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 (MDB2::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 MDB2::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 MDB2::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 (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 + */ +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]; + } + } + + // }}} +} + +// }}} +// {{{ class MDB2_Statement_Common + +/** + * The common statement class for MDB2 statement objects + * + * @package MDB2 + * @category Database + * @author Lukas Smith + */ +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 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)) { + if (strpos($parameter, ':') === 0) { + $parameter = substr($parameter, 1); + } + } + if (!in_array($parameter, $this->positions)) { + return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null, + 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__); + } + $this->values[$parameter] = $value; + if (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); + $this->db->pushErrorHandling(PEAR_ERROR_RETURN); + $this->db->expectError(MDB2_ERROR_NOT_FOUND); + foreach ($parameters as $key => $parameter) { + $err = $this->bindValue($parameter, $values[$parameter], $types[$key]); + if (MDB2::isError($err)) { + if ($err->getCode() == MDB2_ERROR_NOT_FOUND) { + //ignore (extra value for missing placeholder) + continue; + } + $this->db->popExpect(); + $this->db->popErrorHandling(); + return $err; + } + } + $this->db->popExpect(); + $this->db->popErrorHandling(); + 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)) { + if (strpos($parameter, ':') === 0) { + $parameter = substr($parameter, 1); + } + } + if (!in_array($parameter, $this->positions)) { + return MDB2::raiseError(MDB2_ERROR_NOT_FOUND, null, null, + 'Unable to bind to missing placeholder: '.$parameter, __FUNCTION__); + } + $this->values[$parameter] =& $value; + if (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 (MDB2::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 (null === $this->positions) { + return MDB2::raiseError(MDB2_ERROR, null, null, + 'Prepared statement has already been freed', __FUNCTION__); + } + + $values = (array)$values; + if (!empty($values)) { + $err = $this->bindValueArray($values); + if (MDB2::isError($err)) { + return MDB2::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 MDB2::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 (MDB2::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 (null === $this->positions) { + return MDB2::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 + */ +class MDB2_Module_Common +{ + // {{{ Variables (Properties) + + /** + * contains the key to the global MDB2 instance array of the associated + * MDB2 instance + * + * @var int + * @access protected + */ + protected $db_index; + + // }}} + // {{{ constructor: function __construct($db_index) + + /** + * Constructor + */ + function __construct($db_index) + { + $this->db_index = $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; +} + +// }}} +?> diff --git a/3rdparty/MDB2/Date.php b/3rdparty/MDB2/Date.php index d874531150f75a43c3763d380b74ae670a53ea48..ca88eaa347e6cc06a55f9d0fe56a76cc66d6373c 100644 --- a/3rdparty/MDB2/Date.php +++ b/3rdparty/MDB2/Date.php @@ -1,183 +1,183 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Date.php 208329 2006-03-01 12:15:38Z lsmith $ -// - -/** - * @package MDB2 - * @category Database - * @author Lukas Smith - */ - -/** - * 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 - */ -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; - } - // }}} -} - -?> + | +// +----------------------------------------------------------------------+ +// +// $Id$ +// + +/** + * @package MDB2 + * @category Database + * @author Lukas Smith + */ + +/** + * 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 + */ +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/3rdparty/MDB2/Driver/Datatype/Common.php b/3rdparty/MDB2/Driver/Datatype/Common.php index db0cb45dd892c023b452c2e4088faf4c394ce8d4..3b02c86acdaeb9e0aaacd352a20b76bbb7df6541 100644 --- a/3rdparty/MDB2/Driver/Datatype/Common.php +++ b/3rdparty/MDB2/Driver/Datatype/Common.php @@ -1,1841 +1,1842 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Common.php 300551 2010-06-17 21:54:16Z quipo $ - -require_once 'MDB2/LOB.php'; - -/** - * @package MDB2 - * @category Database - * @author Lukas Smith - */ - -/** - * 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 - */ -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 (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 (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 (null !== $field['default']) { - $default = ' DEFAULT ' . $this->quote($field['default'], $field['type']); - } - } - if (empty($default) && empty($notnull)) { - $default = ' DEFAULT NULL'; - } - - $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 ((null === $value) - || ($value === '' && $db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL) - ) { - if (!$quote) { - return null; - } - return 'NULL'; - } - - if (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 (strtolower($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) - { - $db = $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - if ($db->options['lob_allow_url_include']) { - $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 (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 (null !== $operator) { - $operator = strtoupper($operator); - switch ($operator) { - // case insensitive - case 'ILIKE': - if (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 'NOT ILIKE': - if (null === $field) { - return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'case insensitive NOT ILIKE matching requires passing the field name', __FUNCTION__); - } - $db->loadModule('Function', null, true); - $match = $db->function->lower($field).' NOT LIKE '; - break; - // case sensitive - case 'LIKE': - $match = (null === $field) ? 'LIKE ' : ($field.' LIKE '); - break; - case 'NOT LIKE': - $match = (null === $field) ? 'NOT LIKE ' : ($field.' NOT 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 { - $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; - } -} -?> + | +// +----------------------------------------------------------------------+ +// +// $Id$ + +require_once 'MDB2/LOB.php'; + +/** + * @package MDB2 + * @category Database + * @author Lukas Smith + */ + +/** + * 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 + */ +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 (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); + $keys = array_keys($row); + if (is_int($keys[0])) { + $types = $this->_sortResultFieldTypes($keys, $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 (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 (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 ((null === $value) + || ($value === '' && $db->options['portability'] & MDB2_PORTABILITY_EMPTY_TO_NULL) + ) { + if (!$quote) { + return null; + } + return 'NULL'; + } + + if (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 (strtolower($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) + { + $db = $this->getDBInstance(); + if (PEAR::isError($db)) { + return $db; + } + if ($db->options['lob_allow_url_include']) { + $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_object($this->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_object($this->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_object($this->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 (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 (null !== $operator) { + $operator = strtoupper($operator); + switch ($operator) { + // case insensitive + case 'ILIKE': + if (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 'NOT ILIKE': + if (null === $field) { + return $db->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, + 'case insensitive NOT ILIKE matching requires passing the field name', __FUNCTION__); + } + $db->loadModule('Function', null, true); + $match = $db->function->lower($field).' NOT LIKE '; + break; + // case sensitive + case 'LIKE': + $match = (null === $field) ? 'LIKE ' : ($field.' LIKE '); + break; + case 'NOT LIKE': + $match = (null === $field) ? 'NOT LIKE ' : ($field.' NOT 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 { + $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/3rdparty/MDB2/Driver/Datatype/mysql.php b/3rdparty/MDB2/Driver/Datatype/mysql.php index 299901ae6e713b043c121dfccdb650361a3f7700..d23eed23ff7c5f4aada016fbdd72b814c6df2d49 100644 --- a/3rdparty/MDB2/Driver/Datatype/mysql.php +++ b/3rdparty/MDB2/Driver/Datatype/mysql.php @@ -1,562 +1,602 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: mysql.php 295587 2010-02-28 17:16:38Z quipo $ -// - -require_once 'MDB2/Driver/Datatype/Common.php'; - -/** - * MDB2 MySQL driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -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'; - if (empty($default) && empty($notnull)) { - $default = ' DEFAULT NULL'; - } - $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 (null !== $operator) { - $field = (null === $field) ? '' : $field.' '; - $operator = strtoupper($operator); - switch ($operator) { - // case insensitive - case 'ILIKE': - $match = $field.'LIKE '; - break; - case 'NOT ILIKE': - $match = $field.'NOT LIKE '; - break; - // case sensitive - case 'LIKE': - $match = $field.'LIKE BINARY '; - break; - case 'NOT LIKE': - $match = $field.'NOT 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); - } - - // }}} -} - + | +// +----------------------------------------------------------------------+ +// +// $Id$ +// + +require_once 'MDB2/Driver/Datatype/Common.php'; + +/** + * MDB2 MySQL driver + * + * @package MDB2 + * @category Database + * @author Lukas Smith + */ +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; + } + + // }}} + // {{{ 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) + { + // MySQL DDL syntax forbids combining NOT NULL with DEFAULT NULL. + // To get a default of NULL for NOT NULL columns, omit it. + if ( isset($field['notnull']) + && !empty($field['notnull']) + && array_key_exists('default', $field) // do not use isset() here! + && null === $field['default'] + ) { + unset($field['default']); + } + return parent::getDeclaration($type, $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': + 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': + $l = ''; + if (!empty($field['length'])) { + $l = '(' . $field['length']; + if (!empty($field['scale'])) { + $l .= ',' . $field['scale']; + } + $l .= ')'; + } + return 'DOUBLE' . $l; + 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'; + if (empty($default) && empty($notnull)) { + $default = ' DEFAULT NULL'; + } + $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 (null !== $operator) { + $field = (null === $field) ? '' : $field.' '; + $operator = strtoupper($operator); + switch ($operator) { + // case insensitive + case 'ILIKE': + $match = $field.'LIKE '; + break; + case 'NOT ILIKE': + $match = $field.'NOT LIKE '; + break; + // case sensitive + case 'LIKE': + $match = $field.'LIKE BINARY '; + break; + case 'NOT LIKE': + $match = $field.'NOT 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']); + if ($decimal !== false) { + $length = $length.','.$decimal; + } + 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/3rdparty/MDB2/Driver/Datatype/pgsql.php b/3rdparty/MDB2/Driver/Datatype/pgsql.php index fec2c9799f507e13e4afef546d9c181028e0d785..db2fa279024bcae8be1700edb36cb7fea624164a 100644 --- a/3rdparty/MDB2/Driver/Datatype/pgsql.php +++ b/3rdparty/MDB2/Driver/Datatype/pgsql.php @@ -1,575 +1,579 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: pgsql.php 298763 2010-04-29 08:49:41Z afz $ - -require_once 'MDB2/Driver/Datatype/Common.php'; - -/** - * MDB2 PostGreSQL driver - * - * @package MDB2 - * @category Database - * @author Paul Cooper - */ -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 (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'; - if (empty($default) && empty($notnull)) { - $default = ' DEFAULT 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) - { - $db = $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - $value = $this->_readFile($value, $db->options['lob_allow_url_include']); - if (PEAR::isError($value)) { - return $value; - } - 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; - } - $db = $this->getDBInstance(); - if (PEAR::isError($db)) { - return $db; - } - $value = $this->_readFile($value, $db->options['lob_allow_url_include']); - if (PEAR::isError($value)) { - return $value; - } - if (version_compare(PHP_VERSION, '5.2.0RC6', '>=')) { - $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 (null !== $operator) { - $field = (null === $field) ? '' : $field.' '; - $operator = strtoupper($operator); - switch ($operator) { - // case insensitive - case 'ILIKE': - $match = $field.'ILIKE '; - break; - case 'NOT ILIKE': - $match = $field.'NOT ILIKE '; - break; - // case sensitive - case 'LIKE': - $match = $field.'LIKE '; - break; - case 'NOT LIKE': - $match = $field.'NOT 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; - } - // }}} -} + | +// +----------------------------------------------------------------------+ +// +// $Id$ + +require_once 'MDB2/Driver/Datatype/Common.php'; + +/** + * MDB2 PostGreSQL driver + * + * @package MDB2 + * @category Database + * @author Paul Cooper + */ +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 (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'; + if (empty($default) && empty($notnull)) { + $default = ' DEFAULT 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) + { + $db = $this->getDBInstance(); + if (PEAR::isError($db)) { + return $db; + } + if ($db->options['lob_allow_url_include']) { + $value = $this->_readFile($value); + if (PEAR::isError($value)) { + return $value; + } + } + 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; + } + $db = $this->getDBInstance(); + if (PEAR::isError($db)) { + return $db; + } + if ($db->options['lob_allow_url_include']) { + $value = $this->_readFile($value); + if (PEAR::isError($value)) { + return $value; + } + } + if (version_compare(PHP_VERSION, '5.2.0RC6', '>=')) { + $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 (null !== $operator) { + $field = (null === $field) ? '' : $field.' '; + $operator = strtoupper($operator); + switch ($operator) { + // case insensitive + case 'ILIKE': + $match = $field.'ILIKE '; + break; + case 'NOT ILIKE': + $match = $field.'NOT ILIKE '; + break; + // case sensitive + case 'LIKE': + $match = $field.'LIKE '; + break; + case 'NOT LIKE': + $match = $field.'NOT 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/3rdparty/MDB2/Driver/Datatype/sqlite.php b/3rdparty/MDB2/Driver/Datatype/sqlite.php index e4711e46b32d4214de0301de80bcc8e71519d3b9..50475a36282e97db22b3cb21f39ad18bde901fde 100644 --- a/3rdparty/MDB2/Driver/Datatype/sqlite.php +++ b/3rdparty/MDB2/Driver/Datatype/sqlite.php @@ -1,418 +1,418 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: sqlite.php 295587 2010-02-28 17:16:38Z quipo $ -// - -require_once 'MDB2/Driver/Datatype/Common.php'; - -/** - * MDB2 SQLite driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -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'; - if (empty($default) && empty($notnull)) { - $default = ' DEFAULT NULL'; - } - $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 (null !== $operator) { - $field = (null === $field) ? '' : $field.' '; - $operator = strtoupper($operator); - switch ($operator) { - // case insensitive - case 'ILIKE': - $match = $field.'LIKE '; - break; - case 'NOT ILIKE': - $match = $field.'NOT LIKE '; - break; - // case sensitive - case 'LIKE': - $match = $field.'LIKE '; - break; - case 'NOT LIKE': - $match = $field.'NOT 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); - } - - // }}} -} - + | +// +----------------------------------------------------------------------+ +// +// $Id$ +// + +require_once 'MDB2/Driver/Datatype/Common.php'; + +/** + * MDB2 SQLite driver + * + * @package MDB2 + * @category Database + * @author Lukas Smith + */ +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'; + if (empty($default) && empty($notnull)) { + $default = ' DEFAULT NULL'; + } + $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 (null !== $operator) { + $field = (null === $field) ? '' : $field.' '; + $operator = strtoupper($operator); + switch ($operator) { + // case insensitive + case 'ILIKE': + $match = $field.'LIKE '; + break; + case 'NOT ILIKE': + $match = $field.'NOT LIKE '; + break; + // case sensitive + case 'LIKE': + $match = $field.'LIKE '; + break; + case 'NOT LIKE': + $match = $field.'NOT 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/3rdparty/MDB2/Driver/Function/Common.php b/3rdparty/MDB2/Driver/Function/Common.php index 5d247bec3599ea09e9095c5c38e7b1e4f194f38f..5a780fd48e851d5027b55217a696661e0e33dce6 100644 --- a/3rdparty/MDB2/Driver/Function/Common.php +++ b/3rdparty/MDB2/Driver/Function/Common.php @@ -1,293 +1,293 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Common.php 295587 2010-02-28 17:16:38Z quipo $ -// - -/** - * @package MDB2 - * @category Database - * @author Lukas Smith - */ - -/** - * 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 - */ -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 (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; - } - - // }}} -} + | +// +----------------------------------------------------------------------+ +// +// $Id$ +// + +/** + * @package MDB2 + * @category Database + * @author Lukas Smith + */ + +/** + * 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 + */ +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 (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/3rdparty/MDB2/Driver/Function/mysql.php b/3rdparty/MDB2/Driver/Function/mysql.php index bf91536e1f39a1289b739d56c23bc26cbc4be4de..90fdafc973c1e869137d6c5f9a7d7e3175e4b501 100644 --- a/3rdparty/MDB2/Driver/Function/mysql.php +++ b/3rdparty/MDB2/Driver/Function/mysql.php @@ -1,136 +1,136 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: mysql.php 295587 2010-02-28 17:16:38Z quipo $ -// - -require_once 'MDB2/Driver/Function/Common.php'; - -/** - * MDB2 MySQL driver for the function modules - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -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()'; - } - - // }}} -} + | +// +----------------------------------------------------------------------+ +// +// $Id$ +// + +require_once 'MDB2/Driver/Function/Common.php'; + +/** + * MDB2 MySQL driver for the function modules + * + * @package MDB2 + * @category Database + * @author Lukas Smith + */ +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/3rdparty/MDB2/Driver/Function/pgsql.php b/3rdparty/MDB2/Driver/Function/pgsql.php index e232e4feec15108e9f45187f2299b77c2223573c..7cc34a2d7042d52c51bed166e799d53d647fdffe 100644 --- a/3rdparty/MDB2/Driver/Function/pgsql.php +++ b/3rdparty/MDB2/Driver/Function/pgsql.php @@ -1,132 +1,132 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: pgsql.php 296139 2010-03-13 04:15:22Z afz $ - -require_once 'MDB2/Driver/Function/Common.php'; - -/** - * MDB2 MySQL driver for the function modules - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -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)))'; - } - - // }}} - // {{{ 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 (null !== $length) { - return "SUBSTRING(CAST($value AS VARCHAR) FROM $position FOR $length)"; - } - return "SUBSTRING(CAST($value AS VARCHAR) FROM $position)"; - } - - // }}} - // {{{ 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()'; - } - - // }}} -} + | +// +----------------------------------------------------------------------+ +// +// $Id$ + +require_once 'MDB2/Driver/Function/Common.php'; + +/** + * MDB2 MySQL driver for the function modules + * + * @package MDB2 + * @category Database + * @author Lukas Smith + */ +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)))'; + } + + // }}} + // {{{ 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 (null !== $length) { + return "SUBSTRING(CAST($value AS VARCHAR) FROM $position FOR $length)"; + } + return "SUBSTRING(CAST($value AS VARCHAR) FROM $position)"; + } + + // }}} + // {{{ 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/3rdparty/MDB2/Driver/Function/sqlite.php b/3rdparty/MDB2/Driver/Function/sqlite.php index 0a46a4f06a5233228c8a9c3d7de957952c2c476f..65ade4fec07f999bcd69661719845a89041e0797 100644 --- a/3rdparty/MDB2/Driver/Function/sqlite.php +++ b/3rdparty/MDB2/Driver/Function/sqlite.php @@ -1,162 +1,162 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: sqlite.php 295587 2010-02-28 17:16:38Z quipo $ -// - -require_once 'MDB2/Driver/Function/Common.php'; - -/** - * MDB2 SQLite driver for the function modules - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -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 (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; - } - - // }}} -} -?> + | +// +----------------------------------------------------------------------+ +// +// $Id$ +// + +require_once 'MDB2/Driver/Function/Common.php'; + +/** + * MDB2 SQLite driver for the function modules + * + * @package MDB2 + * @category Database + * @author Lukas Smith + */ +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 (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/3rdparty/MDB2/Driver/Manager/Common.php b/3rdparty/MDB2/Driver/Manager/Common.php index fadd72934d626a170704645b0c50e4182614cedf..2e99c332a231432930f98b00bceea71c84ac6661 100644 --- a/3rdparty/MDB2/Driver/Manager/Common.php +++ b/3rdparty/MDB2/Driver/Manager/Common.php @@ -1,1014 +1,1038 @@ - | -// | Lorenzo Alberton | -// +----------------------------------------------------------------------+ -// -// $Id: Common.php 295587 2010-02-28 17:16:38Z quipo $ -// - -/** - * @package MDB2 - * @category Database - * @author Lukas Smith - * @author Lorenzo Alberton - */ - -/** - * 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 - */ -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: - *
-     *          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
-     *          );
-     *          
- * @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 + | +// | Lorenzo Alberton | +// +----------------------------------------------------------------------+ +// +// $Id$ +// + +/** + * @package MDB2 + * @category Database + * @author Lukas Smith + * @author Lorenzo Alberton + */ + +/** + * 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 + */ +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); + $result = $db->exec("DROP TABLE $name"); + if (MDB2::isError($result)) { + return $result; + } + return MDB2_OK; + } + + // }}} + // {{{ 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); + $result = $db->exec("DELETE FROM $name"); + if (MDB2::isError($result)) { + return $result; + } + return MDB2_OK; + } + + // }}} + // {{{ 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) . ')'; + $result = $db->exec($query); + if (MDB2::isError($result)) { + return $result; + } + return MDB2_OK; + } + + // }}} + // {{{ 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); + $result = $db->exec("DROP INDEX $name"); + if (MDB2::isError($result)) { + return $result; + } + return MDB2_OK; + } + + // }}} + // {{{ 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: + *
+     *          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
+     *          );
+     *          
+ * @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); + } + $result = $db->exec($query); + if (MDB2::isError($result)) { + return $result; + } + 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; + } + + $table = $db->quoteIdentifier($table, true); + $name = $db->quoteIdentifier($db->getIndexName($name), true); + $result = $db->exec("ALTER TABLE $table DROP CONSTRAINT $name"); + if (MDB2::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; + } + + 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__); + } + + // }}} +} +?> diff --git a/3rdparty/MDB2/Driver/Manager/mysql.php b/3rdparty/MDB2/Driver/Manager/mysql.php index 8bcb338360499cf9e2671b4ffc1e0a6a72411c7d..c663c0c5d2bf19601f06e752a5734d893a613106 100644 --- a/3rdparty/MDB2/Driver/Manager/mysql.php +++ b/3rdparty/MDB2/Driver/Manager/mysql.php @@ -1,1436 +1,1471 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: mysql.php 302865 2010-08-29 10:30:55Z quipo $ -// - -require_once 'MDB2/Driver/Manager/Common.php'; - -/** - * MDB2 MySQL driver for the management modules - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -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 ((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 (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 (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 (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 (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 OLD.'.$referenced_fields[$i]; - } - - $restrict_action .= implode(' AND ', $conditions).') IS NOT NULL'; - $restrict_action2 = empty($conditions2) ? '' : ' AND (' .implode(' OR ', $conditions2) .')'; - $restrict_action3 = ' THEN CALL %s_ON_TABLE_'.$table.'_VIOLATES_FOREIGN_KEY_CONSTRAINT();' - .' END IF;'; - - $restrict_action_update = $restrict_action . $restrict_action2 . $restrict_action3; - $restrict_action_delete = $restrict_action . $restrict_action3; // There is no NEW row in on DELETE trigger - - $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_update, $trigger_names['pk_update'], 'AFTER UPDATE', 'update'); - } elseif ('RESTRICT' == $fkdef['onupdate']) { - $sql_update = sprintf($query.$restrict_action_update, $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_delete, $trigger_names['pk_delete'], 'AFTER DELETE', 'delete'); - } elseif ('RESTRICT' == $fkdef['ondelete']) { - $sql_delete = sprintf($query.$restrict_action_delete, $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 (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 + | +// +----------------------------------------------------------------------+ +// +// $Id$ +// + +require_once 'MDB2/Driver/Manager/Common.php'; + +/** + * MDB2 MySQL driver for the management modules + * + * @package MDB2 + * @category Database + * @author Lukas Smith + */ +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 ((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 (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); + $result = $db->exec("TRUNCATE TABLE $name"); + if (MDB2::isError($result)) { + return $result; + } + return MDB2_OK; + } + + // }}} + // {{{ 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'])) { + $result = $db->exec('ANALYZE TABLE '.$table); + if (MDB2::isError($result)) { + return $result; + } + } + 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); + $result = $db->exec("ALTER TABLE $name $query"); + if (MDB2::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; + } + + $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 (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 (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 (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) . ')'; + $result = $db->exec($query); + if (MDB2::isError($result)) { + return $result; + } + return MDB2_OK; + } + + // }}} + // {{{ 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); + $result = $db->exec("DROP INDEX $name ON $table"); + if (MDB2::isError($result)) { + return $result; + } + return MDB2_OK; + } + + // }}} + // {{{ 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'; + $result = $db->exec($query); + if (MDB2::isError($result)) { + return $result; + } + return MDB2_OK; + } + + //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"; + $result = $db->exec($query); + if (MDB2::isError($result)) { + return $result; + } + return MDB2_OK; + } + + $table = $db->quoteIdentifier($table, true); + $name = $db->quoteIdentifier($db->getIndexName($name), true); + $query = "ALTER TABLE $table DROP INDEX $name"; + $result = $db->exec($query); + if (MDB2::isError($result)) { + return $result; + } + return MDB2_OK; + } + + // }}} + // {{{ _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 OLD.'.$referenced_fields[$i]; + } + + $restrict_action .= implode(' AND ', $conditions).') IS NOT NULL'; + $restrict_action2 = empty($conditions2) ? '' : ' AND (' .implode(' OR ', $conditions2) .')'; + $restrict_action3 = ' THEN CALL %s_ON_TABLE_'.$table.'_VIOLATES_FOREIGN_KEY_CONSTRAINT();' + .' END IF;'; + + $restrict_action_update = $restrict_action . $restrict_action2 . $restrict_action3; + $restrict_action_delete = $restrict_action . $restrict_action3; // There is no NEW row in on DELETE trigger + + $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_update, $trigger_names['pk_update'], 'AFTER UPDATE', 'update'); + } elseif ('RESTRICT' == $fkdef['onupdate']) { + $sql_update = sprintf($query.$restrict_action_update, $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_delete, $trigger_names['pk_delete'], 'AFTER DELETE', 'delete'); + } elseif ('RESTRICT' == $fkdef['ondelete']) { + $sql_delete = sprintf($query.$restrict_action_delete, $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); + $result = $db->exec("DROP TABLE $sequence_name"); + if (MDB2::isError($result)) { + return $result; + } + return MDB2_OK; + } + + // }}} + // {{{ 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 (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; + } + + // }}} +} +?> diff --git a/3rdparty/MDB2/Driver/Manager/pgsql.php b/3rdparty/MDB2/Driver/Manager/pgsql.php index ec1b08975f0e3d4b769048866fdd92875d60355f..a7b776cc1b70c755300fad2b7c802d0eb4d04677 100644 --- a/3rdparty/MDB2/Driver/Manager/pgsql.php +++ b/3rdparty/MDB2/Driver/Manager/pgsql.php @@ -1,954 +1,978 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: pgsql.php 299393 2010-05-14 17:49:49Z afz $ - -require_once 'MDB2/Driver/Manager/Common.php'; - -/** - * MDB2 MySQL driver for the management modules - * - * @package MDB2 - * @category Database - * @author Paul Cooper - */ -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 = ''; - if (!empty($options['name'])) { - $query .= ' RENAME TO ' . $options['name']; - } - if (!empty($options['owner'])) { - $query .= ' OWNER TO ' . $options['owner']; - } - - if (empty($query)) { - return MDB2_OK; - } - - $query = 'ALTER DATABASE '. $db->quoteIdentifier($name, true) . $query; - 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 (array_key_exists('notnull', $field['definition'])) { - $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 (null !== $table) { - $table = $db->quote(strtoupper($table), 'text'); - $query .= " AND UPPER(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 + | +// +----------------------------------------------------------------------+ +// +// $Id$ + +require_once 'MDB2/Driver/Manager/Common.php'; + +/** + * MDB2 MySQL driver for the management modules + * + * @package MDB2 + * @category Database + * @author Paul Cooper + */ +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 = ''; + if (!empty($options['name'])) { + $query .= ' RENAME TO ' . $options['name']; + } + if (!empty($options['owner'])) { + $query .= ' OWNER TO ' . $options['owner']; + } + + if (empty($query)) { + return MDB2_OK; + } + + $query = 'ALTER DATABASE '. $db->quoteIdentifier($name, true) . $query; + 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); + $result = $db->exec("TRUNCATE TABLE $name"); + if (MDB2::isError($result)) { + return $result; + } + return MDB2_OK; + } + + // }}} + // {{{ 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); + } + $result = $db->exec($query); + if (MDB2::isError($result)) { + return $result; + } + 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 '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 (array_key_exists('notnull', $field['definition'])) { + $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($database = null) + { + $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 (null !== $table) { + $table = $db->quote(strtoupper($table), 'text'); + $query .= " AND UPPER(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($database = null) + { + $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)) { + $result = $db->exec('DROP INDEX '.$db->quoteIdentifier($name, true)); + if (MDB2::isError($result)) { + return $result; + } + return MDB2_OK; + } + $idxname = $db->getIndexName($name); + if (in_array($idxname, $unique)) { + $result = $db->exec('DROP INDEX '.$db->quoteIdentifier($idxname, true)); + if (MDB2::isError($result)) { + return $result; + } + return MDB2_OK; + } + 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); + $result = $db->exec("CREATE SEQUENCE $sequence_name INCREMENT 1". + ($start < 1 ? " MINVALUE $start" : '')." START $start"); + if (MDB2::isError($result)) { + return $result; + } + return MDB2_OK; + } + + // }}} + // {{{ 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); + $result = $db->exec("DROP SEQUENCE $sequence_name"); + if (MDB2::isError($result)) { + return $result; + } + return MDB2_OK; + } + + // }}} + // {{{ 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($database = null) + { + $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; + } +} +?> diff --git a/3rdparty/MDB2/Driver/Manager/sqlite.php b/3rdparty/MDB2/Driver/Manager/sqlite.php index c4c30c9ddad3b4a0d5b07e4d1440825eaf435088..1e7efe3e743dc7cbced870312b04ebf35d9a91df 100644 --- a/3rdparty/MDB2/Driver/Manager/sqlite.php +++ b/3rdparty/MDB2/Driver/Manager/sqlite.php @@ -1,1362 +1,1390 @@ - | -// | Lorenzo Alberton | -// +----------------------------------------------------------------------+ -// -// $Id: sqlite.php 295587 2010-02-28 17:16:38Z quipo $ -// - -require_once 'MDB2/Driver/Manager/Common.php'; - -/** - * MDB2 SQLite driver for the management modules - * - * @package MDB2 - * @category Database - * @author Lukas Smith - * @author Lorenzo Alberton - */ -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; $iexec(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 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 (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 + | +// | Lorenzo Alberton | +// +----------------------------------------------------------------------+ +// +// $Id$ +// + +require_once 'MDB2/Driver/Manager/Common.php'; + +/** + * MDB2 SQLite driver for the management modules + * + * @package MDB2 + * @category Database + * @author Lukas Smith + * @author Lorenzo Alberton + */ +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; $iexec(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 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); + $result = $db->exec("DROP TABLE $name"); + if (MDB2::isError($result)) { + return $result; + } + return MDB2_OK; + } + + // }}} + // {{{ 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); + } + $result = $db->exec($query); + if (MDB2::isError($result)) { + return $result; + } + 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, $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 (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->quoteIdentifier($db->getIndexName($name), true); + $query = "CREATE INDEX $name ON $table"; + $fields = array(); + foreach ($definition['fields'] as $field_name => $field) { + $field_string = $db->quoteIdentifier($field_name, true); + 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) . ')'; + $result = $db->exec($query); + if (MDB2::isError($result)) { + return $result; + } + return MDB2_OK; + } + + // }}} + // {{{ 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); + $result = $db->exec("DROP INDEX $name"); + if (MDB2::isError($result)) { + return $result; + } + return MDB2_OK; + } + + // }}} + // {{{ 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) . ')'; + $result = $db->exec($query); + if (MDB2::isError($result)) { + return $result; + } + 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) + { + 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); + $result = $db->exec("DROP INDEX $name"); + if (MDB2::isError($result)) { + return $result; + } + 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; + } + + $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); + $result = $db->exec("DROP TABLE $sequence_name"); + if (MDB2::isError($result)) { + return $result; + } + return MDB2_OK; + } + + // }}} + // {{{ 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; + } + + // }}} +} +?> diff --git a/3rdparty/MDB2/Driver/Native/Common.php b/3rdparty/MDB2/Driver/Native/Common.php index 7cd536ee566d47353903487a0844cfcc941e298d..67dc1bddd031224821ce724a831211550a8ea349 100644 --- a/3rdparty/MDB2/Driver/Native/Common.php +++ b/3rdparty/MDB2/Driver/Native/Common.php @@ -1,61 +1,61 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Common.php 242348 2007-09-09 13:47:36Z quipo $ -// - -/** - * 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 - */ -class MDB2_Driver_Native_Common extends MDB2_Module_Common -{ -} + | +// +----------------------------------------------------------------------+ +// +// $Id$ +// + +/** + * 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 + */ +class MDB2_Driver_Native_Common extends MDB2_Module_Common +{ +} ?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Native/mysql.php b/3rdparty/MDB2/Driver/Native/mysql.php index f32e3ec3374f789879a4150e66338c782f6e3e93..48e65a05fd25f76539499d08807b0e246015edb5 100644 --- a/3rdparty/MDB2/Driver/Native/mysql.php +++ b/3rdparty/MDB2/Driver/Native/mysql.php @@ -1,60 +1,60 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: mysql.php 215004 2006-06-18 21:59:05Z lsmith $ -// - -require_once 'MDB2/Driver/Native/Common.php'; - -/** - * MDB2 MySQL driver for the native module - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Driver_Native_mysql extends MDB2_Driver_Native_Common -{ -} + | +// +----------------------------------------------------------------------+ +// +// $Id$ +// + +require_once 'MDB2/Driver/Native/Common.php'; + +/** + * MDB2 MySQL driver for the native module + * + * @package MDB2 + * @category Database + * @author Lukas Smith + */ +class MDB2_Driver_Native_mysql extends MDB2_Driver_Native_Common +{ +} ?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Native/pgsql.php b/3rdparty/MDB2/Driver/Native/pgsql.php index 7977b38d3b4d067ced68580a01dd05e9a74d3905..f4db5eae5298b540abbcdd6c8b6d688f9c26c15d 100644 --- a/3rdparty/MDB2/Driver/Native/pgsql.php +++ b/3rdparty/MDB2/Driver/Native/pgsql.php @@ -1,88 +1,88 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: pgsql.php 295587 2010-02-28 17:16:38Z quipo $ - -require_once 'MDB2/Driver/Native/Common.php'; - -/** - * MDB2 PostGreSQL driver for the native module - * - * @package MDB2 - * @category Database - * @author Paul Cooper - */ -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; - } - -} + | +// +----------------------------------------------------------------------+ +// +// $Id$ + +require_once 'MDB2/Driver/Native/Common.php'; + +/** + * MDB2 PostGreSQL driver for the native module + * + * @package MDB2 + * @category Database + * @author Paul Cooper + */ +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/3rdparty/MDB2/Driver/Native/sqlite.php b/3rdparty/MDB2/Driver/Native/sqlite.php index b4da1ce83a3f6d6fe38f131317fa86ca76fe4eb8..4eb796dce7aebdbffdaebeca36ab1873273dc586 100644 --- a/3rdparty/MDB2/Driver/Native/sqlite.php +++ b/3rdparty/MDB2/Driver/Native/sqlite.php @@ -1,60 +1,60 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: sqlite.php 215004 2006-06-18 21:59:05Z lsmith $ -// - -require_once 'MDB2/Driver/Native/Common.php'; - -/** - * MDB2 SQLite driver for the native module - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Driver_Native_sqlite extends MDB2_Driver_Native_Common -{ -} + | +// +----------------------------------------------------------------------+ +// +// $Id$ +// + +require_once 'MDB2/Driver/Native/Common.php'; + +/** + * MDB2 SQLite driver for the native module + * + * @package MDB2 + * @category Database + * @author Lukas Smith + */ +class MDB2_Driver_Native_sqlite extends MDB2_Driver_Native_Common +{ +} ?> \ No newline at end of file diff --git a/3rdparty/MDB2/Driver/Reverse/Common.php b/3rdparty/MDB2/Driver/Reverse/Common.php index 153516d80d8afe9cf7cc9e4fdfd0d509457f57d1..2260520835ed9c0e3e447bfce512e6de7ad59b20 100644 --- a/3rdparty/MDB2/Driver/Reverse/Common.php +++ b/3rdparty/MDB2/Driver/Reverse/Common.php @@ -1,517 +1,517 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Common.php 295587 2010-02-28 17:16:38Z quipo $ -// - -/** - * @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 - */ -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: - * - * array ( - * [fields] => array ( - * [field1name] => array() // one entry per each field covered - * [field2name] => array() // by the index - * [field3name] => array( - * [sorting] => ascending - * ) - * ) - * ); - * - * @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: - *
-     *          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
-     *          );
-     *          
- * @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: - *
-     *          array (
-     *              [start] => n
-     *          );
-     *          
- * @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: - *
-     *          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',
-     *          );
-     *          
- * 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 $mode - * you select. The sample output below is based on this query: - *
-     *    SELECT tblFoo.fldID, tblFoo.fldPhone, tblBar.fldId
-     *    FROM tblFoo
-     *    JOIN tblBar ON tblFoo.fldId = tblBar.fldId
-     * 
- * - *
    - *
  • - * - * null (default) - *
    -     *   [0] => Array (
    -     *       [table] => tblFoo
    -     *       [name] => fldId
    -     *       [type] => int
    -     *       [len] => 11
    -     *       [flags] => primary_key not_null
    -     *   )
    -     *   [1] => Array (
    -     *       [table] => tblFoo
    -     *       [name] => fldPhone
    -     *       [type] => string
    -     *       [len] => 20
    -     *       [flags] =>
    -     *   )
    -     *   [2] => Array (
    -     *       [table] => tblBar
    -     *       [name] => fldId
    -     *       [type] => int
    -     *       [len] => 11
    -     *       [flags] => primary_key not_null
    -     *   )
    -     *   
    - * - *
  • - * - * MDB2_TABLEINFO_ORDER - * - *

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

    - * - *

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

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

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

    - * - *
    -     *   [num_fields] => 3
    -     *   [ordertable] => Array (
    -     *       [tblFoo] => Array (
    -     *           [fldId] => 0
    -     *           [fldPhone] => 1
    -     *       )
    -     *       [tblBar] => Array (
    -     *           [fldId] => 2
    -     *       )
    -     *   )
    -     *   
    - * - *
  • - *
- * - * The flags element contains a space separated list - * of extra information about the field. This data is inconsistent - * between DBMS's due to the way each DBMS works. - * + primary_key - * + unique_key - * + multiple_key - * + not_null - * - * Most DBMS's only provide the table and flags - * elements if $result is a table name. The following DBMS's - * provide full information from queries: - * + fbsql - * + mysql - * - * If the 'portability' option has MDB2_PORTABILITY_FIX_CASE - * 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: - * MDB2_TABLEINFO_ORDERTABLE, - * MDB2_TABLEINFO_ORDER or - * MDB2_TABLEINFO_FULL (which does both). - * These are bitwise, so the first two can be - * combined using |. - * - * @return array an associative array with the information requested. - * 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; - } -} + | +// +----------------------------------------------------------------------+ +// +// $Id$ +// + +/** + * @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 + */ +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: + * + * array ( + * [fields] => array ( + * [field1name] => array() // one entry per each field covered + * [field2name] => array() // by the index + * [field3name] => array( + * [sorting] => ascending + * ) + * ) + * ); + * + * @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: + *
+     *          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
+     *          );
+     *          
+ * @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: + *
+     *          array (
+     *              [start] => n
+     *          );
+     *          
+ * @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: + *
+     *          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',
+     *          );
+     *          
+ * 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 $mode + * you select. The sample output below is based on this query: + *
+     *    SELECT tblFoo.fldID, tblFoo.fldPhone, tblBar.fldId
+     *    FROM tblFoo
+     *    JOIN tblBar ON tblFoo.fldId = tblBar.fldId
+     * 
+ * + *
    + *
  • + * + * null (default) + *
    +     *   [0] => Array (
    +     *       [table] => tblFoo
    +     *       [name] => fldId
    +     *       [type] => int
    +     *       [len] => 11
    +     *       [flags] => primary_key not_null
    +     *   )
    +     *   [1] => Array (
    +     *       [table] => tblFoo
    +     *       [name] => fldPhone
    +     *       [type] => string
    +     *       [len] => 20
    +     *       [flags] =>
    +     *   )
    +     *   [2] => Array (
    +     *       [table] => tblBar
    +     *       [name] => fldId
    +     *       [type] => int
    +     *       [len] => 11
    +     *       [flags] => primary_key not_null
    +     *   )
    +     *   
    + * + *
  • + * + * MDB2_TABLEINFO_ORDER + * + *

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

    + * + *

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

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

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

    + * + *
    +     *   [num_fields] => 3
    +     *   [ordertable] => Array (
    +     *       [tblFoo] => Array (
    +     *           [fldId] => 0
    +     *           [fldPhone] => 1
    +     *       )
    +     *       [tblBar] => Array (
    +     *           [fldId] => 2
    +     *       )
    +     *   )
    +     *   
    + * + *
  • + *
+ * + * The flags element contains a space separated list + * of extra information about the field. This data is inconsistent + * between DBMS's due to the way each DBMS works. + * + primary_key + * + unique_key + * + multiple_key + * + not_null + * + * Most DBMS's only provide the table and flags + * elements if $result is a table name. The following DBMS's + * provide full information from queries: + * + fbsql + * + mysql + * + * If the 'portability' option has MDB2_PORTABILITY_FIX_CASE + * 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: + * MDB2_TABLEINFO_ORDERTABLE, + * MDB2_TABLEINFO_ORDER or + * MDB2_TABLEINFO_FULL (which does both). + * These are bitwise, so the first two can be + * combined using |. + * + * @return array an associative array with the information requested. + * 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/3rdparty/MDB2/Driver/Reverse/mysql.php b/3rdparty/MDB2/Driver/Reverse/mysql.php index 7b9b4e0019cc44a34b6e2cd34e826186f10144ab..8ebdc9979bcf9efa824e451967741ff986cd8dc4 100644 --- a/3rdparty/MDB2/Driver/Reverse/mysql.php +++ b/3rdparty/MDB2/Driver/Reverse/mysql.php @@ -1,546 +1,546 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: mysql.php 295587 2010-02-28 17:16:38Z quipo $ -// - -require_once 'MDB2/Driver/Reverse/Common.php'; - -/** - * MDB2 MySQL driver for the schema reverse engineering module - * - * @package MDB2 - * @category Database - * @author Lukas Smith - * @author Lorenzo Alberton - */ -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 ((null === $default) && $notnull) { - $default = ''; - } - } - $definition[0] = array( - 'notnull' => $notnull, - 'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $column['type']) - ); - $autoincrement = false; - if (!empty($column['extra'])) { - if ($column['extra'] == 'auto_increment') { - $autoincrement = true; - } else { - $definition[0]['extra'] = $column['extra']; - } - } - $collate = null; - if (!empty($column['collation'])) { - $collate = $column['collation']; - $charset = preg_replace('/(.+?)(_.+)?/', '$1', $collate); - } - - if (null !== $length) { - $definition[0]['length'] = $length; - } - if (null !== $unsigned) { - $definition[0]['unsigned'] = $unsigned; - } - if (null !== $fixed) { - $definition[0]['fixed'] = $fixed; - } - if ($default !== false) { - $definition[0]['default'] = $default; - } - if ($autoincrement !== false) { - $definition[0]['autoincrement'] = $autoincrement; - } - if (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) && (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) && (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; - } - //Use INFORMATION_SCHEMA instead? - //SELECT * - // FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS - // WHERE CONSTRAINT_SCHEMA = '$dbname' - // AND TABLE_NAME = '$table' - // AND CONSTRAINT_NAME = '$constraint_name'; - $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 ([^\s]+) \(([^\)]+)\)(?: ON DELETE ([^\s]+))?(?: ON UPDATE ([^\s]+))?/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 ([^\s]+) \(([^\)]+)\)(?: ON DELETE ([^\s]+))?(?: ON UPDATE ([^\s]+))?/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['ondelete'] = empty($matches[4]) ? 'RESTRICT' : strtoupper($matches[4]); - $definition['onupdate'] = empty($matches[5]) ? 'RESTRICT' : strtoupper($matches[5]); - $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; - } -} + | +// +----------------------------------------------------------------------+ +// +// $Id$ +// + +require_once 'MDB2/Driver/Reverse/Common.php'; + +/** + * MDB2 MySQL driver for the schema reverse engineering module + * + * @package MDB2 + * @category Database + * @author Lukas Smith + * @author Lorenzo Alberton + */ +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 ((null === $default) && $notnull) { + $default = ''; + } + } + $definition[0] = array( + 'notnull' => $notnull, + 'nativetype' => preg_replace('/^([a-z]+)[^a-z].*/i', '\\1', $column['type']) + ); + $autoincrement = false; + if (!empty($column['extra'])) { + if ($column['extra'] == 'auto_increment') { + $autoincrement = true; + } else { + $definition[0]['extra'] = $column['extra']; + } + } + $collate = null; + if (!empty($column['collation'])) { + $collate = $column['collation']; + $charset = preg_replace('/(.+?)(_.+)?/', '$1', $collate); + } + + if (null !== $length) { + $definition[0]['length'] = $length; + } + if (null !== $unsigned) { + $definition[0]['unsigned'] = $unsigned; + } + if (null !== $fixed) { + $definition[0]['fixed'] = $fixed; + } + if ($default !== false) { + $definition[0]['default'] = $default; + } + if ($autoincrement !== false) { + $definition[0]['autoincrement'] = $autoincrement; + } + if (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) && (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) && (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; + } + //Use INFORMATION_SCHEMA instead? + //SELECT * + // FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS + // WHERE CONSTRAINT_SCHEMA = '$dbname' + // AND TABLE_NAME = '$table' + // AND CONSTRAINT_NAME = '$constraint_name'; + $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 ([^\s]+) \(([^\)]+)\)(?: ON DELETE ([^\s]+))?(?: ON UPDATE ([^\s]+))?/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 ([^\s]+) \(([^\)]+)\)(?: ON DELETE ([^\s]+))?(?: ON UPDATE ([^\s]+))?/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['ondelete'] = empty($matches[4]) ? 'RESTRICT' : strtoupper($matches[4]); + $definition['onupdate'] = empty($matches[5]) ? 'RESTRICT' : strtoupper($matches[5]); + $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/3rdparty/MDB2/Driver/Reverse/pgsql.php b/3rdparty/MDB2/Driver/Reverse/pgsql.php index 45aa5a1503bc99ce9f6c96f948bc08589679ef0a..eab02f9b9988dc8b9885d6d1fb5aab0ec94586f1 100644 --- a/3rdparty/MDB2/Driver/Reverse/pgsql.php +++ b/3rdparty/MDB2/Driver/Reverse/pgsql.php @@ -1,574 +1,574 @@ - | -// | Lorenzo Alberton | -// +----------------------------------------------------------------------+ -// -// $Id: pgsql.php 295587 2010-02-28 17:16:38Z quipo $ - -require_once 'MDB2/Driver/Reverse/Common.php'; - -/** - * MDB2 PostGreSQL driver for the schema reverse engineering module - * - * @package MDB2 - * @category Database - * @author Paul Cooper - * @author Lorenzo Alberton - */ -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' - && strpos($column['default'], 'NULL') !== 0 - && !preg_match("/nextval\('([^']+)'/", $column['default']) - ) { - $pattern = '/^\'(.*)\'::[\w ]+$/i'; - $default = $column['default'];#substr($column['adsrc'], 1, -1); - if ((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 (null !== $length) { - $definition[0]['length'] = $length; - } - if (null !== $unsigned) { - $definition[0]['unsigned'] = $unsigned; - } - if (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 $result - * 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; - } -} + | +// | Lorenzo Alberton | +// +----------------------------------------------------------------------+ +// +// $Id$ + +require_once 'MDB2/Driver/Reverse/Common.php'; + +/** + * MDB2 PostGreSQL driver for the schema reverse engineering module + * + * @package MDB2 + * @category Database + * @author Paul Cooper + * @author Lorenzo Alberton + */ +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' + && strpos($column['default'], 'NULL') !== 0 + && !preg_match("/nextval\('([^']+)'/", $column['default']) + ) { + $pattern = '/^\'(.*)\'::[\w ]+$/i'; + $default = $column['default'];#substr($column['adsrc'], 1, -1); + if ((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 (null !== $length) { + $definition[0]['length'] = $length; + } + if (null !== $unsigned) { + $definition[0]['unsigned'] = $unsigned; + } + if (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 $result + * 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/3rdparty/MDB2/Driver/Reverse/sqlite.php b/3rdparty/MDB2/Driver/Reverse/sqlite.php index b98ccdb62cd60cb083f10e11cf20e9becb472685..811400480fef23e3bd6dbee94b0599d478e2854c 100644 --- a/3rdparty/MDB2/Driver/Reverse/sqlite.php +++ b/3rdparty/MDB2/Driver/Reverse/sqlite.php @@ -1,609 +1,611 @@ - | -// | Lorenzo Alberton | -// +----------------------------------------------------------------------+ -// -// $Id: sqlite.php 295587 2010-02-28 17:16:38Z quipo $ -// - -require_once 'MDB2/Driver/Reverse/Common.php'; - -/** - * MDB2 SQlite driver for the schema reverse engineering module - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -class MDB2_Driver_Reverse_sqlite extends MDB2_Driver_Reverse_Common -{ - /** - * Remove SQL comments from the field definition - * - * @access private - */ - function _removeComments($sql) { - $lines = explode("\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 = explode(',', $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 ((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 (null !== $length) { - $definition[0]['length'] = $length; - } - if (null !== $unsigned) { - $definition[0]['unsigned'] = $unsigned; - } - if (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 = explode(',', $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 = explode(',', $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 = explode(',', $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 = explode(',', $tmp[1]); - $colpos = 1; - foreach ($column_names as $column_name) { - $definition['fields'][trim($column_name)] = array( - 'position' => $colpos++ - ); - } - $referenced_cols = explode(',', $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 = explode(',', $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__); - } -} - + | +// | Lorenzo Alberton | +// +----------------------------------------------------------------------+ +// +// $Id$ +// + +require_once 'MDB2/Driver/Reverse/Common.php'; + +/** + * MDB2 SQlite driver for the schema reverse engineering module + * + * @package MDB2 + * @category Database + * @author Lukas Smith + */ +class MDB2_Driver_Reverse_sqlite extends MDB2_Driver_Reverse_Common +{ + /** + * Remove SQL comments from the field definition + * + * @access private + */ + function _removeComments($sql) { + $lines = explode("\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 = explode(',', $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|TINYINT|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; + } else { + $columns[$j]['default'] = null; + } + 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 ((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 (null !== $length) { + $definition[0]['length'] = $length; + } + if (null !== $unsigned) { + $definition[0]['unsigned'] = $unsigned; + } + if (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 = explode(',', $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 = explode(',', $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 = explode(',', $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 = explode(',', $tmp[1]); + $colpos = 1; + foreach ($column_names as $column_name) { + $definition['fields'][trim($column_name)] = array( + 'position' => $colpos++ + ); + } + $referenced_cols = explode(',', $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 = explode(',', $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/3rdparty/MDB2/Driver/mysql.php b/3rdparty/MDB2/Driver/mysql.php index eda3310deeb0b0ce24db76ba61b7e29bdb7b3517..3008bd04f0939a049ac1076db4cbc7641160311a 100644 --- a/3rdparty/MDB2/Driver/mysql.php +++ b/3rdparty/MDB2/Driver/mysql.php @@ -1,1710 +1,1729 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: mysql.php 302867 2010-08-29 11:22:07Z quipo $ -// - -/** - * MDB2 MySQL driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -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) - * @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)); - 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(); - $unix = ($this->dsn['protocol'] && $this->dsn['protocol'] == 'unix'); - if (empty($this->dsn['hostspec'])) { - $this->dsn['hostspec'] = $unix ? '' : 'localhost'; - } - if ($this->dsn['hostspec']) { - $params[0] = $this->dsn['hostspec'] . ($this->dsn['port'] ? ':' . $this->dsn['port'] : ''); - } else { - $params[0] = ':' . $this->dsn['socket']; - } - $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 '".mysql_real_escape_string($collation, $connection)."'"; - } - 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 && 0 !== mysql_errno($connection)) { - $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()) - { - // connect to get server capabilities (http://pear.php.net/bugs/16147) - $connection = $this->getConnection(); - if (PEAR::isError($connection)) { - return $connection; - } - - if ($this->options['emulate_prepared'] - || $this->supported['prepared_statements'] !== true - ) { - return parent::prepare($query, $types, $result_types, $lobs); - } - $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; - } - } - - 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 - // not casting to integer to handle BIGINT http://pear.php.net/bugs/bug.php?id=17650 - return $this->queryOne('SELECT LAST_INSERT_ID()'); - } - - // }}} - // {{{ 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 - */ -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; - } - 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 { - $rowObj = new $object_class($row); - $row = $rowObj; - } - } - ++$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 - */ -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 - */ -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__); - } - $close = false; - $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; - } -} -?> + | +// +----------------------------------------------------------------------+ +// +// $Id$ +// + +/** + * MDB2 MySQL driver + * + * @package MDB2 + * @category Database + * @author Lukas Smith + */ +class MDB2_Driver_mysql extends MDB2_Driver_Common +{ + // {{{ properties + + public $string_quoting = array( + 'start' => "'", + 'end' => "'", + 'escape' => '\\', + 'escape_pattern' => '\\', + ); + + public $identifier_quoting = array( + 'start' => '`', + 'end' => '`', + 'escape' => '`', + ); + + public $sql_comments = array( + array('start' => '-- ', 'end' => "\n", 'escape' => false), + array('start' => '#', 'end' => "\n", 'escape' => false), + array('start' => '/*', 'end' => '*/', 'escape' => false), + ); + + protected $server_capabilities_checked = false; + + protected $start_transaction = false; + + protected $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) + * @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)); + 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(); + $unix = ($this->dsn['protocol'] && $this->dsn['protocol'] == 'unix'); + if (empty($this->dsn['hostspec'])) { + $this->dsn['hostspec'] = $unix ? '' : 'localhost'; + } + if ($this->dsn['hostspec']) { + $params[0] = $this->dsn['hostspec'] . ($this->dsn['port'] ? ':' . $this->dsn['port'] : ''); + } else { + $params[0] = ':' . $this->dsn['socket']; + } + $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 '".mysql_real_escape_string($collation, $connection)."'"; + } + 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 && 0 !== mysql_errno($connection)) { + $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()) + { + // connect to get server capabilities (http://pear.php.net/bugs/16147) + $connection = $this->getConnection(); + if (PEAR::isError($connection)) { + return $connection; + } + + if ($this->options['emulate_prepared'] + || $this->supported['prepared_statements'] !== true + ) { + return parent::prepare($query, $types, $result_types, $lobs); + } + $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; + } + } + + 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 + // not casting to integer to handle BIGINT http://pear.php.net/bugs/bug.php?id=17650 + return $this->queryOne('SELECT LAST_INSERT_ID()'); + } + + // }}} + // {{{ 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 + */ +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 + || $fetchmode == MDB2_FETCHMODE_OBJECT + ) { + $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; + } + 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 ( ( $fetchmode != MDB2_FETCHMODE_ASSOC + && $fetchmode != MDB2_FETCHMODE_OBJECT) + && !empty($this->types) + ) { + $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim); + } elseif (($fetchmode == MDB2_FETCHMODE_ASSOC + || $fetchmode == MDB2_FETCHMODE_OBJECT) + && !empty($this->types_assoc) + ) { + $row = $this->db->datatype->convertResultRow($this->types_assoc, $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 { + $rowObj = new $object_class($row); + $row = $rowObj; + } + } + ++$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 + */ +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 + */ +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 = true) + { + 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__); + } + $close = false; + $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; + } +} +?> diff --git a/3rdparty/MDB2/Driver/pgsql.php b/3rdparty/MDB2/Driver/pgsql.php index 15bd280f40bc7f8d22a3af4c7b6c94f020136e9d..8a8b3f7c91dea57eef3067cb424f8bed673e7c8c 100644 --- a/3rdparty/MDB2/Driver/pgsql.php +++ b/3rdparty/MDB2/Driver/pgsql.php @@ -1,1548 +1,1583 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: pgsql.php 295587 2010-02-28 17:16:38Z quipo $ - -/** - * MDB2 PostGreSQL driver - * - * @package MDB2 - * @category Database - * @author Paul Cooper - */ -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 (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); - } - if ($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 (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 (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) - * @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)); - 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; - } - } - - // Enable extra compatibility settings on 8.2 and later - if (function_exists('pg_parameter_status')) { - $version = pg_parameter_status($connection, 'server_version'); - if ($version == false) { - return $this->raiseError(null, null, null, - 'Unable to retrieve server version', __FUNCTION__); - } - $version = explode ('.', $version); - if ( $version['0'] > 8 - || ($version['0'] == 8 && $version['1'] >= 2) - ) { - if (!@pg_query($connection, "SET SESSION STANDARD_CONFORMING_STRINGS = OFF")) { - return $this->raiseError(null, null, null, - 'Unable to set standard_conforming_strings to off', __FUNCTION__); - } - - if (!@pg_query($connection, "SET SESSION ESCAPE_STRING_WARNING = OFF")) { - return $this->raiseError(null, null, null, - 'Unable to set escape_string_warning to off', __FUNCTION__); - } - } - } - - 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 (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 (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 (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']) { - return parent::prepare($query, $types, $result_types, $lobs); - } - $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 (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 (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 (false === $pgtypes) { - $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 - */ -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 (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 (false === $this->result) { - $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'resultset has already been freed', __FUNCTION__); - return $err; - } - 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 { - $rowObj = new $object_class($row); - $row = $rowObj; - } - } - ++$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 (null === $cols) { - if (false === $this->result) { - return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'resultset has already been freed', __FUNCTION__); - } - if (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 (false === $free) { - 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 - */ -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 (false === $this->result) { - return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'resultset has already been freed', __FUNCTION__); - } - if (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 (null === $rows) { - if (false === $this->result) { - return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'resultset has already been freed', __FUNCTION__); - } - if (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 - */ -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 (null === $this->statement) { - return parent::_execute($result_class, $result_wrap_class); - } - $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 (null === $this->positions) { - return $this->db->raiseError(MDB2_ERROR, null, null, - 'Prepared statement has already been freed', __FUNCTION__); - } - $result = MDB2_OK; - - if (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 + | +// +----------------------------------------------------------------------+ +// +// $Id$ + +/** + * MDB2 PostGreSQL driver + * + * @package MDB2 + * @category Database + * @author Paul Cooper + */ +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 (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); + } + if ($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 (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 (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) + * @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)); + 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; + } + } + + // Enable extra compatibility settings on 8.2 and later + if (function_exists('pg_parameter_status')) { + $version = pg_parameter_status($connection, 'server_version'); + if ($version == false) { + return $this->raiseError(null, null, null, + 'Unable to retrieve server version', __FUNCTION__); + } + $version = explode ('.', $version); + if ( $version['0'] > 8 + || ($version['0'] == 8 && $version['1'] >= 2) + ) { + if (!@pg_query($connection, "SET SESSION STANDARD_CONFORMING_STRINGS = OFF")) { + return $this->raiseError(null, null, null, + 'Unable to set standard_conforming_strings to off', __FUNCTION__); + } + + if (!@pg_query($connection, "SET SESSION ESCAPE_STRING_WARNING = OFF")) { + return $this->raiseError(null, null, null, + 'Unable to set escape_string_warning to off', __FUNCTION__); + } + } + } + + 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 (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, true, $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 (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 (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']) { + return parent::prepare($query, $types, $result_types, $lobs); + } + $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 (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 (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)) !== false) { + //$next_parameter = 1; + $parameter = $key_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 (false === $pgtypes) { + $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 + */ +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 (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 + || $fetchmode == MDB2_FETCHMODE_OBJECT + ) { + $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 (false === $this->result) { + $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, + 'resultset has already been freed', __FUNCTION__); + return $err; + } + 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 ( ( $fetchmode != MDB2_FETCHMODE_ASSOC + && $fetchmode != MDB2_FETCHMODE_OBJECT) + && !empty($this->types) + ) { + $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim); + } elseif (($fetchmode == MDB2_FETCHMODE_ASSOC + || $fetchmode == MDB2_FETCHMODE_OBJECT) + && !empty($this->types_assoc) + ) { + $row = $this->db->datatype->convertResultRow($this->types_assoc, $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 { + $rowObj = new $object_class($row); + $row = $rowObj; + } + } + ++$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 (null === $cols) { + if (false === $this->result) { + return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, + 'resultset has already been freed', __FUNCTION__); + } + if (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 (false === $free) { + 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 + */ +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 (false === $this->result) { + return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, + 'resultset has already been freed', __FUNCTION__); + } + if (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 (null === $rows) { + if (false === $this->result) { + return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, + 'resultset has already been freed', __FUNCTION__); + } + if (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 + */ +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 = true) + { + if (null === $this->statement) { + return parent::_execute($result_class, $result_wrap_class); + } + $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 (null === $this->positions) { + return $this->db->raiseError(MDB2_ERROR, null, null, + 'Prepared statement has already been freed', __FUNCTION__); + } + $result = MDB2_OK; + + if (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; + } + + /** + * 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); + $result = $db->exec("DROP TABLE $name"); + + if (PEAR::isError($result)) { + $result = $db->exec("DROP TABLE $name CASCADE"); + } + + return $result; + } +} +?> diff --git a/3rdparty/MDB2/Driver/sqlite.php b/3rdparty/MDB2/Driver/sqlite.php index e8f1bba583cdf9651b32a646844de0ed6eec0c99..42363bb8c58cbe0eed5813aea5bc047182c67db2 100644 --- a/3rdparty/MDB2/Driver/sqlite.php +++ b/3rdparty/MDB2/Driver/sqlite.php @@ -1,1093 +1,1104 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: sqlite.php 295587 2010-02-28 17:16:38Z quipo $ -// - -/** - * MDB2 SQLite driver - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -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 (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 (null !== $savepoint) { - return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, - 'savepoints are not supported', __FUNCTION__); - } - if ($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 (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 (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) - * @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)); - 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 (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) { - $code = null; - if (0 === strpos($this->_lasterror, 'no such table')) { - $code = MDB2_ERROR_NOSUCHTABLE; - } - $err = $this->raiseError($code, 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 (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 - */ -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 (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 (false === $this->result) { - $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'resultset has already been freed', __FUNCTION__); - return $err; - } - 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 { - $rowObj = new $object_class($row); - $row = $rowObj; - } - } - ++$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 (null === $cols) { - if (false === $this->result) { - return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'resultset has already been freed', __FUNCTION__); - } - if (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 - */ -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 (false === $this->result) { - return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'resultset has already been freed', __FUNCTION__); - } - if (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 (null === $rows) { - if (false === $this->result) { - return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, - 'resultset has already been freed', __FUNCTION__); - } - if (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 - */ -class MDB2_Statement_sqlite extends MDB2_Statement_Common -{ - -} -?> \ No newline at end of file + | +// +----------------------------------------------------------------------+ +// +// $Id$ +// + +/** + * MDB2 SQLite driver + * + * @package MDB2 + * @category Database + * @author Lukas Smith + */ +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 (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, + '/violates .*constraint/' => 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 (null !== $savepoint) { + return $this->raiseError(MDB2_ERROR_UNSUPPORTED, null, null, + 'savepoints are not supported', __FUNCTION__); + } + if ($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 (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 (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) + * @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)); + 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 (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) { + $code = null; + if (0 === strpos($this->_lasterror, 'no such table')) { + $code = MDB2_ERROR_NOSUCHTABLE; + } + $err = $this->raiseError($code, 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 (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 + */ +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 (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 + || $fetchmode == MDB2_FETCHMODE_OBJECT + ) { + $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 (false === $this->result) { + $err = $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, + 'resultset has already been freed', __FUNCTION__); + return $err; + } + 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 ( ( $fetchmode != MDB2_FETCHMODE_ASSOC + && $fetchmode != MDB2_FETCHMODE_OBJECT) + && !empty($this->types) + ) { + $row = $this->db->datatype->convertResultRow($this->types, $row, $rtrim); + } elseif (($fetchmode == MDB2_FETCHMODE_ASSOC + || $fetchmode == MDB2_FETCHMODE_OBJECT) + && !empty($this->types_assoc) + ) { + $row = $this->db->datatype->convertResultRow($this->types_assoc, $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 { + $rowObj = new $object_class($row); + $row = $rowObj; + } + } + ++$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 (null === $cols) { + if (false === $this->result) { + return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, + 'resultset has already been freed', __FUNCTION__); + } + if (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 + */ +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 (false === $this->result) { + return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, + 'resultset has already been freed', __FUNCTION__); + } + if (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 (null === $rows) { + if (false === $this->result) { + return $this->db->raiseError(MDB2_ERROR_NEED_MORE_DATA, null, null, + 'resultset has already been freed', __FUNCTION__); + } + if (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 + */ +class MDB2_Statement_sqlite extends MDB2_Statement_Common +{ + +} +?> diff --git a/3rdparty/MDB2/Extended.php b/3rdparty/MDB2/Extended.php index fed82f965981bbf86c05013a4c205d67c26e9acb..5b0a5be34a02e36c5131849701b0ce12e65becd2 100644 --- a/3rdparty/MDB2/Extended.php +++ b/3rdparty/MDB2/Extended.php @@ -1,720 +1,723 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Extended.php 302784 2010-08-25 23:29:16Z quipo $ - -/** - * @package MDB2 - * @category Database - * @author Lukas Smith - */ - -/** - * 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 - */ -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 ((false !== $where) && (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; - } - return $db->query($query, $types, $result_class, $result_wrap_class); - } - - // }}} - // {{{ 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: - *
-     *   ID      TEXT       DATE
-     * --------------------------------
-     *   1       'one'      944679408
-     *   2       'two'      944679408
-     *   3       'three'    944679408
-     * 
- * Then the call getAssoc('SELECT id,text FROM mytable') returns: - *
-     *    array(
-     *      '1' => 'one',
-     *      '2' => 'two',
-     *      '3' => 'three',
-     *    )
-     * 
- * ...while the call getAssoc('SELECT id,text,date FROM mytable') returns: - *
-     *    array(
-     *      '1' => array('one', '944679408'),
-     *      '2' => array('two', '944679408'),
-     *      '3' => array('three', '944679408')
-     *    )
-     * 
- * - * If the more than one row occurs with the same value in the - * first column, the last row overwrites all previous ones by - * default. Use the $group parameter if you don't want to - * overwrite like this. Example: - *
-     * getAssoc('SELECT category,id,name FROM mytable', 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')
-     *             )
-     *    )
-     * 
- * - * 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); - } - - // }}} -} + | +// +----------------------------------------------------------------------+ +// +// $Id$ + +/** + * @package MDB2 + * @category Database + * @author Lukas Smith + */ + +/** + * 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 + */ +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 ((false !== $where) && (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; + } + return $db->query($query, $types, $result_class, $result_wrap_class); + } + + // }}} + // {{{ 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: + *
+     *   ID      TEXT       DATE
+     * --------------------------------
+     *   1       'one'      944679408
+     *   2       'two'      944679408
+     *   3       'three'    944679408
+     * 
+ * Then the call getAssoc('SELECT id,text FROM mytable') returns: + *
+     *    array(
+     *      '1' => 'one',
+     *      '2' => 'two',
+     *      '3' => 'three',
+     *    )
+     * 
+ * ...while the call getAssoc('SELECT id,text,date FROM mytable') returns: + *
+     *    array(
+     *      '1' => array('one', '944679408'),
+     *      '2' => array('two', '944679408'),
+     *      '3' => array('three', '944679408')
+     *    )
+     * 
+ * + * If the more than one row occurs with the same value in the + * first column, the last row overwrites all previous ones by + * default. Use the $group parameter if you don't want to + * overwrite like this. Example: + *
+     * getAssoc('SELECT category,id,name FROM mytable', 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')
+     *             )
+     *    )
+     * 
+ * + * 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) + { + if (MDB2::isError($stmt)) { + return $stmt; + } + 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/3rdparty/MDB2/Iterator.php b/3rdparty/MDB2/Iterator.php index 8d31919b6deff679bd3c8233c874cd512488de74..46feade32183bc459abdb4691d7cbb602e887745 100644 --- a/3rdparty/MDB2/Iterator.php +++ b/3rdparty/MDB2/Iterator.php @@ -1,259 +1,262 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: Iterator.php 295586 2010-02-28 17:04:17Z quipo $ - -/** - * PHP5 Iterator - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -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 (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 - */ -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); - } - // }}} -} - + | +// +----------------------------------------------------------------------+ +// +// $Id$ + +/** + * PHP5 Iterator + * + * @package MDB2 + * @category Database + * @author Lukas Smith + */ +class MDB2_Iterator implements Iterator +{ + protected $fetchmode; + /** + * @var MDB2_Result_Common + */ + protected $result; + protected $row; + + // {{{ constructor + + /** + * Constructor + */ + public function __construct(MDB2_Result_Common $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 (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 + */ +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/3rdparty/MDB2/LOB.php b/3rdparty/MDB2/LOB.php index f7df13dc4782c31c8e92d0bfca15e7b1775efcd7..537a77e546bcddbf49b8aa1488f74ee62dcdcdeb 100644 --- a/3rdparty/MDB2/LOB.php +++ b/3rdparty/MDB2/LOB.php @@ -1,264 +1,264 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: LOB.php 222350 2006-10-25 11:52:21Z lsmith $ - -/** - * @package MDB2 - * @category Database - * @author Lukas Smith - */ - -require_once 'MDB2.php'; - -/** - * MDB2_LOB: user land stream wrapper implementation for LOB support - * - * @package MDB2 - * @category Database - * @author Lukas Smith - */ -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; -} - -?> + | +// +----------------------------------------------------------------------+ +// +// $Id$ + +/** + * @package MDB2 + * @category Database + * @author Lukas Smith + */ + +require_once 'MDB2.php'; + +/** + * MDB2_LOB: user land stream wrapper implementation for LOB support + * + * @package MDB2 + * @category Database + * @author Lukas Smith + */ +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/3rdparty/MDB2/Schema.php b/3rdparty/MDB2/Schema.php index 037397018135680fafb6888dc73984f9e0a78677..5eeb97b055bf1c74a101ad0601f0b58e94d60e30 100644 --- a/3rdparty/MDB2/Schema.php +++ b/3rdparty/MDB2/Schema.php @@ -1,8 +1,6 @@ - - * Author: Igor Feghali + * PHP version 5 * * @category Database * @package MDB2_Schema * @author Lukas Smith * @author Igor Feghali * @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 $ + * @version SVN: $Id$ * @link http://pear.php.net/packages/MDB2_Schema */ @@ -96,7 +93,7 @@ class MDB2_Schema extends PEAR 'parser' => 'MDB2_Schema_Parser', 'writer' => 'MDB2_Schema_Writer', 'validate' => 'MDB2_Schema_Validate', - 'drop_missing_tables' => false + 'drop_obsolete_objects' => false ); // }}} @@ -237,9 +234,9 @@ class MDB2_Schema extends PEAR * @access public * @see MDB2::parseDSN */ - function &factory(&$db, $options = array()) + static function &factory(&$db, $options = array()) { - $obj =& new MDB2_Schema(); + $obj = new MDB2_Schema(); $result = $obj->connect($db, $options); if (PEAR::isError($result)) { @@ -284,14 +281,14 @@ class MDB2_Schema extends PEAR $this->disconnect(); if (!MDB2::isConnection($db)) { - $db =& MDB2::factory($db, $db_options); + $db = MDB2::factory($db, $db_options); } if (PEAR::isError($db)) { return $db; } - $this->db =& $db; + $this->db = $db; $this->db->loadModule('Datatype'); $this->db->loadModule('Manager'); $this->db->loadModule('Reverse'); @@ -380,7 +377,7 @@ class MDB2_Schema extends PEAR $dtd_file = $this->options['dtd_file']; if ($dtd_file) { include_once 'XML/DTD/XmlValidator.php'; - $dtd =& new XML_DTD_XmlValidator; + $dtd = new XML_DTD_XmlValidator; if (!$dtd->isValid($dtd_file, $input_file)) { return $this->raiseError(MDB2_SCHEMA_ERROR_PARSE, null, null, $dtd->getMessage()); } @@ -393,7 +390,16 @@ class MDB2_Schema extends PEAR return $result; } - $parser =& new $class_name($variables, $fail_on_invalid_names, $structure, $this->options['valid_types'], $this->options['force_defaults']); + $max_identifiers_length = null; + if (isset($this->db->options['max_identifiers_length'])) { + $max_identifiers_length = $this->db->options['max_identifiers_length']; + } + + $parser = new $class_name($variables, $fail_on_invalid_names, $structure, + $this->options['valid_types'], $this->options['force_defaults'], + $max_identifiers_length + ); + $result = $parser->setInputFile($input_file); if (PEAR::isError($result)) { return $result; @@ -436,7 +442,17 @@ class MDB2_Schema extends PEAR return $result; } - $val =& new $class_name($this->options['fail_on_invalid_names'], $this->options['valid_types'], $this->options['force_defaults']); + $max_identifiers_length = null; + if (isset($this->db->options['max_identifiers_length'])) { + $max_identifiers_length = $this->db->options['max_identifiers_length']; + } + + $val = new $class_name( + $this->options['fail_on_invalid_names'], + $this->options['valid_types'], + $this->options['force_defaults'], + $max_identifiers_length + ); $database_definition = array( 'name' => $database, @@ -470,7 +486,7 @@ class MDB2_Schema extends PEAR 'initialization' => array() ); - $table_definition =& $database_definition['tables'][$table_name]; + $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)) { @@ -628,6 +644,7 @@ class MDB2_Schema extends PEAR if (PEAR::isError($result)) { return $result; } + $database_definition['tables'][$table_name]=$table_definition; } @@ -1455,16 +1472,17 @@ class MDB2_Schema extends PEAR $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($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) { @@ -1484,14 +1502,17 @@ class MDB2_Schema extends PEAR $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; - } + } + 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; } @@ -2022,9 +2043,10 @@ class MDB2_Schema extends PEAR } } - if ($this->options['drop_missing_tables'] + if ($this->options['drop_obsolete_objects'] && !empty($changes['remove']) - && is_array($changes['remove'])) { + && is_array($changes['remove']) + ) { foreach ($changes['remove'] as $table_name => $table) { $result = $this->db->manager->dropTable($table_name); if (PEAR::isError($result)) { @@ -2105,7 +2127,10 @@ class MDB2_Schema extends PEAR } } - if (!empty($changes['remove']) && is_array($changes['remove'])) { + if ($this->options['drop_obsolete_objects'] + && !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)) { @@ -2232,7 +2257,7 @@ class MDB2_Schema extends PEAR } if (!empty($changes['tables']['remove']) && is_array($changes['tables']['remove'])) { - if ($this->options['drop_missing_tables']) { + if ($this->options['drop_obsolete_objects']) { foreach ($changes['tables']['remove'] as $table_name => $table) { $this->db->debug("$table_name:", __FUNCTION__); $this->db->debug("\tRemoved table '$table_name'", __FUNCTION__); @@ -2338,9 +2363,15 @@ class MDB2_Schema extends PEAR } } 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 ($this->options['drop_obsolete_objects']) { + foreach ($changes['sequences']['remove'] as $sequence_name => $sequence) { + $this->db->debug("$sequence_name:", __FUNCTION__); + $this->db->debug("\tRemoved sequence '$sequence_name'", __FUNCTION__); + } + } else { + foreach ($changes['sequences']['remove'] as $sequence_name => $sequence) { + $this->db->debug("\tObsolete sequence '$sequence_name' left as is", __FUNCTION__); + } } } if (!empty($changes['sequences']['change']) && is_array($changes['sequences']['change'])) { @@ -2448,7 +2479,7 @@ class MDB2_Schema extends PEAR } } - $writer =& new $class_name($this->options['valid_types']); + $writer = new $class_name($this->options['valid_types']); return $writer->dumpDatabase($database_definition, $arguments, $dump); } @@ -2696,9 +2727,9 @@ class MDB2_Schema extends PEAR * @access public * @see PEAR_Error */ - function &raiseError($code = null, $mode = null, $options = null, $userinfo = null) + static function &raiseError($code = null, $mode = null, $options = null, $userinfo = null, $dummy1 = null, $dummy2 = null, $dummy3 = false) { - $err =& PEAR::raiseError(null, $code, $mode, $options, + $err = PEAR::raiseError(null, $code, $mode, $options, $userinfo, 'MDB2_Schema_Error', true); return $err; } @@ -2717,7 +2748,7 @@ class MDB2_Schema extends PEAR * @return bool true if parameter is an error * @access public */ - function isError($data, $code = null) + static function isError($data, $code = null) { if (is_a($data, 'MDB2_Schema_Error')) { if (is_null($code)) { @@ -2764,4 +2795,3 @@ class MDB2_Schema_Error extends PEAR_Error $mode, $level, $debuginfo); } } -?> diff --git a/3rdparty/MDB2/Schema/Parser.php b/3rdparty/MDB2/Schema/Parser.php index 9e8e74b6317bd6968f077a282a6e4f937f7fb674..cfd0c37d8a3a834234bb7d7b7b48c675c29f2ca7 100644 --- a/3rdparty/MDB2/Schema/Parser.php +++ b/3rdparty/MDB2/Schema/Parser.php @@ -1,8 +1,6 @@ - - * Author: Igor Feghali - * - * $Id: Parser.php,v 1.68 2008/11/30 03:34:00 clockwerx Exp $ + * PHP version 5 * * @category Database * @package MDB2_Schema * @author Christian Dickmann * @author Igor Feghali * @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 $ + * @version SVN: $Id$ * @link http://pear.php.net/packages/MDB2_Schema */ - require_once 'XML/Parser.php'; require_once 'MDB2/Schema/Validate.php'; @@ -114,27 +108,83 @@ class MDB2_Schema_Parser extends XML_Parser var $val; + /** + * PHP 5 constructor + * + * @param array $variables mixed array with user defined schema + * variables + * @param bool $fail_on_invalid_names array with reserved words per RDBMS + * @param array $structure multi dimensional array with + * database schema and data + * @param array $valid_types information of all valid fields + * types + * @param bool $force_defaults if true sets a default value to + * field when not explicit + * @param int $max_identifiers_length maximum allowed size for entities + * name + * + * @return void + * + * @access public + * @static + */ function __construct($variables, $fail_on_invalid_names = true, - $structure = false, $valid_types = array(), - $force_defaults = true) - { + $structure = false, $valid_types = array(), $force_defaults = true, + $max_identifiers_length = null + ) { // 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'); + parent::__construct('ISO-8859-1'); $this->variables = $variables; $this->structure = $structure; - $this->val =& new MDB2_Schema_Validate($fail_on_invalid_names, $valid_types, $force_defaults); + $this->val = new MDB2_Schema_Validate( + $fail_on_invalid_names, + $valid_types, + $force_defaults, + $max_identifiers_length + ); } + /** + * PHP 4 compatible constructor + * + * @param array $variables mixed array with user defined schema + * variables + * @param bool $fail_on_invalid_names array with reserved words per RDBMS + * @param array $structure multi dimensional array with + * database schema and data + * @param array $valid_types information of all valid fields + * types + * @param bool $force_defaults if true sets a default value to + * field when not explicit + * @param int $max_identifiers_length maximum allowed size for entities + * name + * + * @return void + * + * @access public + * @static + */ function MDB2_Schema_Parser($variables, $fail_on_invalid_names = true, - $structure = false, $valid_types = array(), - $force_defaults = true) - { + $structure = false, $valid_types = array(), $force_defaults = true, + $max_identifiers_length = null + ) { $this->__construct($variables, $fail_on_invalid_names, $structure, $valid_types, $force_defaults); } - function startHandler($xp, $element, $attribs) + /** + * Triggered when reading a XML open tag + * + * @param resource $xp xml parser resource + * @param string $element element name + * @param array $attribs attributes + * + * @return void + * @access private + * @static + */ + function startHandler($xp, $element, &$attribs) { if (strtolower($element) == 'variable') { $this->var_mode = true; @@ -335,12 +385,21 @@ class MDB2_Schema_Parser extends XML_Parser 'start' => '', 'description' => '', 'comments' => '', - 'on' => array('table' => '', 'field' => '') ); break; } } + /** + * Triggered when reading a XML close tag + * + * @param resource $xp xml parser resource + * @param string $element element name + * + * @return void + * @access private + * @static + */ function endHandler($xp, $element) { if (strtolower($element) == 'variable') { @@ -503,7 +562,21 @@ class MDB2_Schema_Parser extends XML_Parser $this->element = implode('-', $this->elements); } - function &raiseError($msg = null, $xmlecode = 0, $xp = null, $ecode = MDB2_SCHEMA_ERROR_PARSE) + /** + * Pushes a MDB2_Schema_Error into stack and returns it + * + * @param string $msg textual message + * @param int $xmlecode PHP's XML parser error code + * @param resource $xp xml parser resource + * @param int $ecode MDB2_Schema's error code + * + * @return object + * @access private + * @static + */ + static function &raiseError($msg = null, $xmlecode = 0, $xp = null, $ecode = MDB2_SCHEMA_ERROR_PARSE, $userinfo = null, + $error_class = null, + $skipmsg = false) { if (is_null($this->error)) { $error = ''; @@ -530,11 +603,21 @@ class MDB2_Schema_Parser extends XML_Parser $error .= "\n"; - $this->error =& MDB2_Schema::raiseError($ecode, null, null, $error); + $this->error = MDB2_Schema::raiseError($ecode, null, null, $error); } return $this->error; } + /** + * Triggered when reading data in a XML element (text between tags) + * + * @param resource $xp xml parser resource + * @param string $data text + * + * @return void + * @access private + * @static + */ function cdataHandler($xp, $data) { if ($this->var_mode == true) { @@ -806,6 +889,9 @@ class MDB2_Schema_Parser extends XML_Parser case 'database-sequence-comments': $this->sequence['comments'] .= $data; break; + case 'database-sequence-on': + $this->sequence['on'] = array('table' => '', 'field' => ''); + break; case 'database-sequence-on-table': $this->sequence['on']['table'] .= $data; break; @@ -815,5 +901,3 @@ class MDB2_Schema_Parser extends XML_Parser } } } - -?> diff --git a/3rdparty/MDB2/Schema/Parser2.php b/3rdparty/MDB2/Schema/Parser2.php index 01318473fddf0163f89626aa14d0002ce5ed53f3..b415b4a336e7447de736c45c2bb04aff9acedab4 100644 --- a/3rdparty/MDB2/Schema/Parser2.php +++ b/3rdparty/MDB2/Schema/Parser2.php @@ -1,8 +1,6 @@ - + * PHP version 5 * * @category Database * @package MDB2_Schema * @author Igor Feghali * @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 $ + * @version SVN: $Id$ * @link http://pear.php.net/packages/MDB2_Schema */ @@ -100,8 +98,30 @@ class MDB2_Schema_Parser2 extends XML_Unserializer var $init = array(); - function __construct($variables, $fail_on_invalid_names = true, $structure = false, $valid_types = array(), $force_defaults = true) - { + /** + * PHP 5 constructor + * + * @param array $variables mixed array with user defined schema + * variables + * @param bool $fail_on_invalid_names array with reserved words per RDBMS + * @param array $structure multi dimensional array with + * database schema and data + * @param array $valid_types information of all valid fields + * types + * @param bool $force_defaults if true sets a default value to + * field when not explicit + * @param int $max_identifiers_length maximum allowed size for entities + * name + * + * @return void + * + * @access public + * @static + */ + function __construct($variables, $fail_on_invalid_names = true, + $structure = false, $valid_types = array(), $force_defaults = true, + $max_identifiers_length = null + ) { // 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'; @@ -119,15 +139,44 @@ class MDB2_Schema_Parser2 extends XML_Unserializer $this->variables = $variables; $this->structure = $structure; - $this->val =& new MDB2_Schema_Validate($fail_on_invalid_names, $valid_types, $force_defaults); + $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) - { + /** + * PHP 4 compatible constructor + * + * @param array $variables mixed array with user defined schema + * variables + * @param bool $fail_on_invalid_names array with reserved words per RDBMS + * @param array $structure multi dimensional array with + * database schema and data + * @param array $valid_types information of all valid fields + * types + * @param bool $force_defaults if true sets a default value to + * field when not explicit + * @param int $max_identifiers_length maximum allowed size for entities + * name + * + * @return void + * + * @access public + * @static + */ + function MDB2_Schema_Parser2($variables, $fail_on_invalid_names = true, + $structure = false, $valid_types = array(), $force_defaults = true, + $max_identifiers_length = null + ) { $this->__construct($variables, $fail_on_invalid_names, $structure, $valid_types, $force_defaults); } + /** + * Main method. Parses XML Schema File. + * + * @return bool|error object + * + * @access public + */ function parse() { $result = $this->unserialize($this->filename, true); @@ -140,18 +189,33 @@ class MDB2_Schema_Parser2 extends XML_Unserializer } } + /** + * Do the necessary stuff to set the input XML schema file + * + * @param string $filename full path to schema file + * + * @return boolean MDB2_OK on success + * + * @access public + */ function setInputFile($filename) { $this->filename = $filename; return MDB2_OK; } - function renameKey(&$arr, $oKey, $nKey) - { - $arr[$nKey] = &$arr[$oKey]; - unset($arr[$oKey]); - } - + /** + * Enforce the default values for mandatory keys and ensure everything goes + * always in the same order (simulates the behaviour of the original + * parser). Works at database level. + * + * @param array $database multi dimensional array with database definition + * and data. + * + * @return bool|error MDB2_OK on success or error object + * + * @access private + */ function fixDatabaseKeys($database) { $this->database_definition = array( @@ -204,6 +268,18 @@ class MDB2_Schema_Parser2 extends XML_Unserializer return MDB2_OK; } + /** + * Enforce the default values for mandatory keys and ensure everything goes + * always in the same order (simulates the behaviour of the original + * parser). Works at table level. + * + * @param array $table multi dimensional array with table definition + * and data. + * + * @return bool|error MDB2_OK on success or error object + * + * @access private + */ function fixTableKeys($table) { $this->table = array( @@ -279,6 +355,17 @@ class MDB2_Schema_Parser2 extends XML_Unserializer return MDB2_OK; } + /** + * Enforce the default values for mandatory keys and ensure everything goes + * always in the same order (simulates the behaviour of the original + * parser). Works at table field level. + * + * @param array $field array with table field definition + * + * @return bool|error MDB2_OK on success or error object + * + * @access private + */ function fixTableFieldKeys($field) { $this->field = array(); @@ -328,6 +415,17 @@ class MDB2_Schema_Parser2 extends XML_Unserializer return MDB2_OK; } + /** + * Enforce the default values for mandatory keys and ensure everything goes + * always in the same order (simulates the behaviour of the original + * parser). Works at table index level. + * + * @param array $index array with table index definition + * + * @return bool|error MDB2_OK on success or error object + * + * @access private + */ function fixTableIndexKeys($index) { $this->index = array( @@ -389,6 +487,17 @@ class MDB2_Schema_Parser2 extends XML_Unserializer return MDB2_OK; } + /** + * Enforce the default values for mandatory keys and ensure everything goes + * always in the same order (simulates the behaviour of the original + * parser). Works at table constraint level. + * + * @param array $constraint array with table index definition + * + * @return bool|error MDB2_OK on success or error object + * + * @access private + */ function fixTableConstraintKeys($constraint) { $this->constraint = array( @@ -468,6 +577,18 @@ class MDB2_Schema_Parser2 extends XML_Unserializer return MDB2_OK; } + /** + * Enforce the default values for mandatory keys and ensure everything goes + * always in the same order (simulates the behaviour of the original + * parser). Works at table data level. + * + * @param array $element multi dimensional array with query definition + * @param string $type whether its a insert|update|delete query + * + * @return bool|error MDB2_OK on success or error object + * + * @access private + */ function fixTableInitializationKeys($element, $type = '') { if (!empty($element['select']) && is_array($element['select'])) { @@ -480,6 +601,43 @@ class MDB2_Schema_Parser2 extends XML_Unserializer $this->table['initialization'][] = array( 'type' => $type, 'data' => $this->init ); } + /** + * Enforce the default values for mandatory keys and ensure everything goes + * always in the same order (simulates the behaviour of the original + * parser). Works deeper at the table initialization level (data). At this + * point we are look at one of the below: + * + * + * {field}+ + * + * + * + * + * + * {field}+ + * + * {expression} + * ? + * + * + * + * + * {expression} + * + * + * + * @param array $element multi dimensional array with query definition + * + * @return bool|error MDB2_OK on success or error object + * + * @access private + */ function fixTableInitializationDataKeys($element) { $this->init = array(); @@ -505,6 +663,22 @@ class MDB2_Schema_Parser2 extends XML_Unserializer } } + /** + * Recursively diggs into an "expression" element. According to our + * documentation an "expression" element is of the kind: + * + * + * or or or {function} or {expression} + * + * or or or {function} or {expression} + * + * + * @param array &$arr reference to current element definition + * + * @return void + * + * @access private + */ function setExpression(&$arr) { $element = each($arr); @@ -555,6 +729,30 @@ class MDB2_Schema_Parser2 extends XML_Unserializer } } + /** + * Enforce the default values for mandatory keys and ensure everything goes + * always in the same order (simulates the behaviour of the original + * parser). Works at database sequences level. A "sequence" element looks + * like: + * + * + * + * ? + * ? + * ? + * ? + * + * + * + * ? + * + * + * @param array $sequence multi dimensional array with sequence definition + * + * @return bool|error MDB2_OK on success or error object + * + * @access private + */ function fixSequenceKeys($sequence) { $this->sequence = array( @@ -562,7 +760,6 @@ class MDB2_Schema_Parser2 extends XML_Unserializer 'start' => '', 'description' => '', 'comments' => '', - 'on' => array('table' => '', 'field' => '') ); if (!empty($sequence['name'])) { @@ -610,15 +807,23 @@ class MDB2_Schema_Parser2 extends XML_Unserializer return MDB2_OK; } + /** + * Pushes a MDB2_Schema_Error into stack and returns it + * + * @param string $msg textual message + * @param int $ecode MDB2_Schema's error code + * + * @return object + * @access private + * @static + */ 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); + $this->error = MDB2_Schema::raiseError($ecode, null, null, $error); } return $this->error; } } - -?> diff --git a/3rdparty/MDB2/Schema/Reserved/ibase.php b/3rdparty/MDB2/Schema/Reserved/ibase.php index b208abc83a383c6a4d792b7c25b9bbcedb10b6a8..d797822a4b96b3ea350701924e4539c7d4b67ce7 100644 --- a/3rdparty/MDB2/Schema/Reserved/ibase.php +++ b/3rdparty/MDB2/Schema/Reserved/ibase.php @@ -1,49 +1,51 @@ - | -// +----------------------------------------------------------------------+ -// -// }}} + + * @license BSD http://www.opensource.org/licenses/bsd-license.php + * @version SVN: $Id$ + * @link http://pear.php.net/packages/MDB2_Schema + */ // {{{ $GLOBALS['_MDB2_Schema_Reserved']['ibase'] /** * Has a list of reserved words of Interbase/Firebird @@ -433,4 +435,3 @@ $GLOBALS['_MDB2_Schema_Reserved']['ibase'] = array( 'ZONE', ); // }}} -?> \ No newline at end of file diff --git a/3rdparty/MDB2/Schema/Reserved/mssql.php b/3rdparty/MDB2/Schema/Reserved/mssql.php index 74ac688578015f7c552854918cbe97ee4977a96e..7aa65f426f9a2f78526e07b7548d154ca2ceac2d 100644 --- a/3rdparty/MDB2/Schema/Reserved/mssql.php +++ b/3rdparty/MDB2/Schema/Reserved/mssql.php @@ -1,48 +1,52 @@ - | -// +----------------------------------------------------------------------+ -// }}} + + * @license BSD http://www.opensource.org/licenses/bsd-license.php + * @version SVN: $Id$ + * @link http://pear.php.net/packages/MDB2_Schema + */ + // {{{ $GLOBALS['_MDB2_Schema_Reserved']['mssql'] /** * Has a list of all the reserved words for mssql. @@ -254,5 +258,3 @@ $GLOBALS['_MDB2_Schema_Reserved']['mssql'] = array( 'SELECT', ); //}}} - -?> diff --git a/3rdparty/MDB2/Schema/Reserved/mysql.php b/3rdparty/MDB2/Schema/Reserved/mysql.php index 4f0575e0bb1018d21ad7cdc1f50c124f8f5b98f6..6a4338b261d58e6a5f6337c6f070ed32a0167cfe 100644 --- a/3rdparty/MDB2/Schema/Reserved/mysql.php +++ b/3rdparty/MDB2/Schema/Reserved/mysql.php @@ -1,50 +1,52 @@ - | -// +----------------------------------------------------------------------+ -// -// $Id: mysql.php,v 1.3 2006/03/01 12:16:40 lsmith Exp $ -// }}} + + * @license BSD http://www.opensource.org/licenses/bsd-license.php + * @version SVN: $Id$ + * @link http://pear.php.net/packages/MDB2_Schema + */ + // {{{ $GLOBALS['_MDB2_Schema_Reserved']['mysql'] /** * Has a list of reserved words of mysql @@ -281,4 +283,3 @@ $GLOBALS['_MDB2_Schema_Reserved']['mysql'] = array( 'ZEROFILL', ); // }}} -?> diff --git a/3rdparty/MDB2/Schema/Reserved/oci8.php b/3rdparty/MDB2/Schema/Reserved/oci8.php index 57fe12ddcab96ac1835ce133c68291add516a2f3..3cc898e1d68715a049900c50280d9efc39433f0c 100644 --- a/3rdparty/MDB2/Schema/Reserved/oci8.php +++ b/3rdparty/MDB2/Schema/Reserved/oci8.php @@ -1,48 +1,52 @@ - | -// +----------------------------------------------------------------------+ -// }}} + + * @license BSD http://www.opensource.org/licenses/bsd-license.php + * @version SVN: $Id$ + * @link http://pear.php.net/packages/MDB2_Schema + */ + // {{{ $GLOBALS['_MDB2_Schema_Reserved']['oci8'] /** * Has a list of all the reserved words for oracle. @@ -167,5 +171,3 @@ $GLOBALS['_MDB2_Schema_Reserved']['oci8'] = array( 'WITH', ); // }}} - -?> diff --git a/3rdparty/MDB2/Schema/Reserved/pgsql.php b/3rdparty/MDB2/Schema/Reserved/pgsql.php index d358e9c12f033a42b806fb5645a4caa9d1a74ed5..84537685e0fb9113f347822fc433c9bfdad56381 100644 --- a/3rdparty/MDB2/Schema/Reserved/pgsql.php +++ b/3rdparty/MDB2/Schema/Reserved/pgsql.php @@ -1,49 +1,52 @@ - | -// +----------------------------------------------------------------------+ -// -// }}} + + * @license BSD http://www.opensource.org/licenses/bsd-license.php + * @version SVN: $Id$ + * @link http://pear.php.net/packages/MDB2_Schema + */ + // {{{ $GLOBALS['_MDB2_Schema_Reserved']['pgsql'] /** * Has a list of reserved words of pgsql @@ -143,5 +146,3 @@ $GLOBALS['_MDB2_Schema_Reserved']['pgsql'] = array( 'WHERE' ); // }}} -?> - diff --git a/3rdparty/MDB2/Schema/Tool.php b/3rdparty/MDB2/Schema/Tool.php index 9689a0f6d73ef6ee01d01246a1f4e1b449af6333..3210c9173ebd49acccf26597bd9fc8c80886432e 100644 --- a/3rdparty/MDB2/Schema/Tool.php +++ b/3rdparty/MDB2/Schema/Tool.php @@ -1,8 +1,6 @@ - - * $Id: Tool.php,v 1.6 2008/12/13 00:26:07 clockwerx Exp $ + * PHP version 5 * * @category Database * @package MDB2_Schema * @author Christian Weiske * @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 $ + * @version SVN: $Id$ * @link http://pear.php.net/packages/MDB2_Schema */ @@ -152,7 +149,9 @@ class MDB2_Schema_Tool case '--init': return 'init'; default: - throw new MDB2_Schema_Tool_ParameterException("Unknown mode \"$arg\""); + throw new MDB2_Schema_Tool_ParameterException( + "Unknown mode \"$arg\"" + ); } }//protected function getAction(&$args) @@ -179,7 +178,8 @@ class MDB2_Schema_Tool */ protected function doHelp() { - self::toStdErr(<<getFileOrDsn($args); if ($type == 'file') { throw new MDB2_Schema_Tool_ParameterException( - 'Dumping a schema file as a schema file does not make much sense' + 'Dumping a schema file as a schema file does not make much ' . + 'sense' ); } @@ -503,8 +512,14 @@ EOH $definition = $schemaDest->parseDatabaseDefinitionFile($dsnSource); $where = 'loading schema file'; } else { - $schemaSource = MDB2_Schema::factory($dsnSource, $this->getSchemaOptions()); - $this->throwExceptionOnError($schemaSource, 'connecting to source database'); + $schemaSource = MDB2_Schema::factory( + $dsnSource, + $this->getSchemaOptions() + ); + $this->throwExceptionOnError( + $schemaSource, + 'connecting to source database' + ); $definition = $schemaSource->getDefinitionFromDatabase(); $where = 'loading definition from database'; @@ -514,7 +529,11 @@ EOH //create destination database from definition $simulate = false; - $op = $schemaDest->createDatabase($definition, array(), $simulate); + $op = $schemaDest->createDatabase( + $definition, + array(), + $simulate + ); $this->throwExceptionOnError($op, 'creating the database'); }//protected function doLoad($args) @@ -545,10 +564,16 @@ EOH } $schemaDest = MDB2_Schema::factory($dsnDest, $this->getSchemaOptions()); - $this->throwExceptionOnError($schemaDest, 'connecting to destination database'); + $this->throwExceptionOnError( + $schemaDest, + 'connecting to destination database' + ); $definition = $schemaDest->getDefinitionFromDatabase(); - $this->throwExceptionOnError($definition, 'loading definition from database'); + $this->throwExceptionOnError( + $definition, + 'loading definition from database' + ); $op = $schemaDest->writeInitialization($dsnSource, $definition); $this->throwExceptionOnError($op, 'initializing database'); @@ -556,5 +581,3 @@ EOH }//class MDB2_Schema_Tool - -?> diff --git a/3rdparty/MDB2/Schema/Tool/ParameterException.php b/3rdparty/MDB2/Schema/Tool/ParameterException.php index fab1e03e250de7206d7ccf7f195354fb8edfc4a2..92bea69391722dda6fa09b1bbac162577b2a4744 100644 --- a/3rdparty/MDB2/Schema/Tool/ParameterException.php +++ b/3rdparty/MDB2/Schema/Tool/ParameterException.php @@ -1,6 +1,61 @@ - + * @license BSD http://www.opensource.org/licenses/bsd-license.php + * @version SVN: $Id$ + * @link http://pear.php.net/packages/MDB2_Schema + */ +/** + * To be implemented yet + * + * @category Database + * @package MDB2_Schema + * @author Christian Weiske + * @license BSD http://www.opensource.org/licenses/bsd-license.php + * @link http://pear.php.net/packages/MDB2_Schema + */ class MDB2_Schema_Tool_ParameterException extends Exception -{} - -?> \ No newline at end of file +{ +} diff --git a/3rdparty/MDB2/Schema/Validate.php b/3rdparty/MDB2/Schema/Validate.php index 21be024ce9fbbc883ea200aecbad1f7c038abcf7..4cff175576f1d7d702588b71bc20af066ab79ccf 100644 --- a/3rdparty/MDB2/Schema/Validate.php +++ b/3rdparty/MDB2/Schema/Validate.php @@ -1,8 +1,6 @@ - - * Author: Igor Feghali + * PHP version 5 * * @category Database * @package MDB2_Schema * @author Christian Dickmann * @author Igor Feghali * @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 $ + * @version SVN: $Id$ * @link http://pear.php.net/packages/MDB2_Schema */ @@ -70,11 +67,30 @@ class MDB2_Schema_Validate var $force_defaults = true; + var $max_identifiers_length = null; + // }}} // {{{ constructor - function __construct($fail_on_invalid_names = true, $valid_types = array(), $force_defaults = true) - { + /** + * PHP 5 constructor + * + * @param bool $fail_on_invalid_names array with reserved words per RDBMS + * @param array $valid_types information of all valid fields + * types + * @param bool $force_defaults if true sets a default value to + * field when not explicit + * @param int $max_identifiers_length maximum allowed size for entities + * name + * + * @return void + * + * @access public + * @static + */ + function __construct($fail_on_invalid_names = true, $valid_types = array(), + $force_defaults = true, $max_identifiers_length = null + ) { if (empty($GLOBALS['_MDB2_Schema_Reserved'])) { $GLOBALS['_MDB2_Schema_Reserved'] = array(); } @@ -87,21 +103,49 @@ class MDB2_Schema_Validate } else { $this->fail_on_invalid_names = array(); } - $this->valid_types = $valid_types; - $this->force_defaults = $force_defaults; + $this->valid_types = $valid_types; + $this->force_defaults = $force_defaults; + $this->max_identifiers_length = $max_identifiers_length; } - function MDB2_Schema_Validate($fail_on_invalid_names = true, $valid_types = array(), $force_defaults = true) - { + /** + * PHP 4 compatible constructor + * + * @param bool $fail_on_invalid_names array with reserved words per RDBMS + * @param array $valid_types information of all valid fields + * types + * @param bool $force_defaults if true sets a default value to + * field when not explicit + * @param int $max_identifiers_length maximum allowed size for entities + * name + * + * @return void + * + * @access public + * @static + */ + function MDB2_Schema_Validate($fail_on_invalid_names = true, $valid_types = array(), + $force_defaults = true, $max_identifiers_length = null + ) { $this->__construct($fail_on_invalid_names, $valid_types, $force_defaults); } // }}} // {{{ raiseError() + /** + * Pushes a MDB2_Schema_Error into stack and returns it + * + * @param int $ecode MDB2_Schema's error code + * @param string $msg textual message + * + * @return object + * @access private + * @static + */ function &raiseError($ecode, $msg = null) { - $error =& MDB2_Schema::raiseError($ecode, null, null, $msg); + $error = MDB2_Schema::raiseError($ecode, null, null, $msg); return $error; } @@ -176,27 +220,18 @@ class MDB2_Schema_Validate */ 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); - } - } + /** + * Valid name ? + */ + $result = $this->validateIdentifier($table_name, 'table'); + if (PEAR::isError($result)) { + return $result; } /* Was */ @@ -289,10 +324,12 @@ class MDB2_Schema_Validate */ function validateField($fields, &$field, $field_name) { - /* Have we got a name? */ - if (!$field_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field name missing'); + /** + * Valid name ? + */ + $result = $this->validateIdentifier($field_name, 'field'); + if (PEAR::isError($result)) { + return $result; } /* Field name duplicated? */ @@ -301,17 +338,6 @@ class MDB2_Schema_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, @@ -422,10 +448,14 @@ class MDB2_Schema_Validate */ function validateIndex($table_indexes, &$index, $index_name) { - if (!$index_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'an index has to have a name'); + /** + * Valid name ? + */ + $result = $this->validateIdentifier($index_name, 'index'); + if (PEAR::isError($result)) { + return $result; } + if (is_array($table_indexes) && isset($table_indexes[$index_name])) { return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, 'index "'.$index_name.'" already exists'); @@ -470,14 +500,18 @@ class MDB2_Schema_Validate */ function validateIndexField($index_fields, &$field, $field_name) { + /** + * Valid name ? + */ + $result = $this->validateIdentifier($field_name, 'index field'); + if (PEAR::isError($result)) { + return $result; + } + 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') { @@ -506,10 +540,14 @@ class MDB2_Schema_Validate */ 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'); + /** + * Valid name ? + */ + $result = $this->validateIdentifier($constraint_name, 'foreign key'); + if (PEAR::isError($result)) { + return $result; } + if (is_array($table_constraints) && isset($table_constraints[$constraint_name])) { return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, 'foreign key "'.$constraint_name.'" already exists'); @@ -555,10 +593,14 @@ class MDB2_Schema_Validate */ function validateConstraintField($constraint_fields, $field_name) { - if (!$field_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'empty value for foreign-field'); + /** + * Valid name ? + */ + $result = $this->validateIdentifier($field_name, 'foreign key field'); + if (PEAR::isError($result)) { + return $result; } + if (is_array($constraint_fields) && isset($constraint_fields[$field_name])) { return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, 'foreign field "'.$field_name.'" already exists'); @@ -582,10 +624,14 @@ class MDB2_Schema_Validate */ function validateConstraintReferencedField($referenced_fields, $field_name) { - if (!$field_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'empty value for referenced foreign-field'); + /** + * Valid name ? + */ + $result = $this->validateIdentifier($field_name, 'referenced foreign field'); + if (PEAR::isError($result)) { + return $result; } + if (is_array($referenced_fields) && isset($referenced_fields[$field_name])) { return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, 'foreign field "'.$field_name.'" already referenced'); @@ -612,9 +658,12 @@ class MDB2_Schema_Validate */ function validateSequence($sequences, &$sequence, $sequence_name) { - if (!$sequence_name) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'a sequence has to have a name'); + /** + * Valid name ? + */ + $result = $this->validateIdentifier($sequence_name, 'sequence'); + if (PEAR::isError($result)) { + return $result; } if (is_array($sequences) && isset($sequences[$sequence_name])) { @@ -661,21 +710,17 @@ class MDB2_Schema_Validate */ function validateDatabase(&$database) { - /* Have we got a name? */ - if (!is_array($database) || !isset($database['name']) || !$database['name']) { + if (!is_array($database)) { return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'a database has to have a name'); + 'something wrong went with database definition'); } - /* 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); - } - } + /** + * Valid name ? + */ + $result = $this->validateIdentifier($database['name'], 'database'); + if (PEAR::isError($result)) { + return $result; } /* Create */ @@ -798,9 +843,12 @@ class MDB2_Schema_Validate */ function validateDataField($table_fields, $instruction_fields, &$field) { - if (!$field['name']) { - return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, - 'field-name has to be specified'); + /** + * Valid name ? + */ + $result = $this->validateIdentifier($field['name'], 'field'); + if (PEAR::isError($result)) { + return $result; } if (is_array($instruction_fields) && isset($instruction_fields[$field['name']])) { @@ -917,6 +965,62 @@ class MDB2_Schema_Validate } return MDB2_OK; } -} -?> + // }}} + // {{{ validateIdentifier() + + /** + * Checks whether a given identifier is valid for current driver. + * + * @param string $id identifier to check + * @param string $type whether identifier represents a table name, index, etc. + * + * @return bool|error object + * + * @access public + */ + function validateIdentifier($id, $type) + { + $max_length = $this->max_identifiers_length; + $cur_length = strlen($id); + + /** + * Have we got a name? + */ + if (!$id) { + return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, + "a $type has to have a name"); + } + + /** + * Supported length ? + */ + if ($max_length !== null + && $cur_length > $max_length + ) { + return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, + "$type name '$id' is too long for current driver"); + } elseif ($cur_length > 30) { + // FIXME: find a way to issue a warning in MDB2_Schema object + /* $this->warnings[] = "$type name '$id' might not be + portable to other drivers"; */ + } + + /** + * Reserved ? + */ + if (is_array($this->fail_on_invalid_names)) { + $name = strtoupper($id); + foreach ($this->fail_on_invalid_names as $rdbms) { + if (in_array($name, $GLOBALS['_MDB2_Schema_Reserved'][$rdbms])) { + return $this->raiseError(MDB2_SCHEMA_ERROR_VALIDATE, + "$type name '$id' is a reserved word in: $rdbms"); + } + } + } + + return MDB2_OK; + } + + // }}} +} diff --git a/3rdparty/MDB2/Schema/Writer.php b/3rdparty/MDB2/Schema/Writer.php index 5ae4918dc1d086af46f6e297a72c7af9d4105b1f..70a03168de6e559136f44dda037f849cc89f3e9e 100644 --- a/3rdparty/MDB2/Schema/Writer.php +++ b/3rdparty/MDB2/Schema/Writer.php @@ -1,8 +1,6 @@ - - * Author: Igor Feghali + * PHP version 5 * * @category Database * @package MDB2_Schema * @author Lukas Smith * @author Igor Feghali * @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 $ + * @version SVN: $Id$ * @link http://pear.php.net/packages/MDB2_Schema */ @@ -69,11 +66,33 @@ class MDB2_Schema_Writer // }}} // {{{ constructor + /** + * PHP 5 constructor + * + * @param array $valid_types information of all valid fields + * types + * + * @return void + * + * @access public + * @static + */ function __construct($valid_types = array()) { $this->valid_types = $valid_types; } + /** + * PHP 4 compatible constructor + * + * @param array $valid_types information of all valid fields + * types + * + * @return void + * + * @access public + * @static + */ function MDB2_Schema_Writer($valid_types = array()) { $this->__construct($valid_types); @@ -87,15 +106,18 @@ class MDB2_Schema_Writer * 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. + * @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. + * @param string $userinfo User-friendly error message * * @return object a PEAR error object * @access public @@ -103,7 +125,7 @@ class MDB2_Schema_Writer */ function &raiseError($code = null, $mode = null, $options = null, $userinfo = null) { - $error =& MDB2_Schema::raiseError($code, $mode, $options, $userinfo); + $error = MDB2_Schema::raiseError($code, $mode, $options, $userinfo); return $error; } @@ -578,4 +600,3 @@ class MDB2_Schema_Writer // }}} } -?> diff --git a/3rdparty/PEAR.php b/3rdparty/PEAR.php index 2aa85259d62dc69c0cad3f38320bc82fdcf28af9..501f6a653d8a9e8741beca76ca4f2227790057f8 100644 --- a/3rdparty/PEAR.php +++ b/3rdparty/PEAR.php @@ -247,7 +247,7 @@ class PEAR * @access public * @return bool true if parameter is an error */ - function isError($data, $code = null) + static function isError($data, $code = null) { if (!is_a($data, 'PEAR_Error')) { return false; @@ -469,7 +469,7 @@ class PEAR * @see PEAR::setErrorHandling * @since PHP 4.0.5 */ - function &raiseError($message = null, + static function &raiseError($message = null, $code = null, $mode = null, $options = null, @@ -555,11 +555,11 @@ class PEAR function &throwError($message = null, $code = null, $userinfo = null) { if (isset($this) && is_a($this, 'PEAR')) { - $a = &$this->raiseError($message, $code, null, null, $userinfo); + $a = $this->raiseError($message, $code, null, null, $userinfo); return $a; } - $a = &PEAR::raiseError($message, $code, null, null, $userinfo); + $a = PEAR::raiseError($message, $code, null, null, $userinfo); return $a; } @@ -695,7 +695,7 @@ class PEAR * @param string $ext The extension name * @return bool Success or not on the dl() call */ - function loadExtension($ext) + static function loadExtension($ext) { if (extension_loaded($ext)) { return true; diff --git a/3rdparty/PEAR/Autoloader.php b/3rdparty/PEAR/Autoloader.php index 0ed707ec842f577ca1649d74e0b4e3446170fb24..51620c7085f7d6a54864b31bde09d042fdea741a 100644 --- a/3rdparty/PEAR/Autoloader.php +++ b/3rdparty/PEAR/Autoloader.php @@ -144,7 +144,7 @@ class PEAR_Autoloader extends PEAR $include_file = preg_replace('/[^a-z0-9]/i', '_', $classname); include_once $include_file; } - $obj =& new $classname; + $obj = new $classname; $methods = get_class_methods($classname); foreach ($methods as $method) { // don't import priviate methods and constructors diff --git a/3rdparty/PEAR/Command.php b/3rdparty/PEAR/Command.php index db39b8f36f357f17dc97a2d463d4c5908a207fb4..13518d4e4b253574978b389b2bae4f64a0a3143f 100644 --- a/3rdparty/PEAR/Command.php +++ b/3rdparty/PEAR/Command.php @@ -133,8 +133,8 @@ class PEAR_Command $a = PEAR::raiseError("unknown command `$command'"); return $a; } - $ui =& PEAR_Command::getFrontendObject(); - $obj = &new $class($ui, $config); + $ui = PEAR_Command::getFrontendObject(); + $obj = new $class($ui, $config); return $obj; } @@ -149,7 +149,7 @@ class PEAR_Command if (!class_exists($class)) { return PEAR::raiseError("unknown command `$command'"); } - $ui =& PEAR_Command::getFrontendObject(); + $ui = PEAR_Command::getFrontendObject(); $config = &PEAR_Config::singleton(); $obj = &new $class($ui, $config); return $obj; diff --git a/3rdparty/PEAR/Common.php b/3rdparty/PEAR/Common.php index 3a8c7e80d33f83aae44ff7a7ebed70a969312d5d..83f2de742ac0e68db714cb5cd056e2c76495c4a3 100644 --- a/3rdparty/PEAR/Common.php +++ b/3rdparty/PEAR/Common.php @@ -168,7 +168,7 @@ class PEAR_Common extends PEAR function PEAR_Common() { parent::PEAR(); - $this->config = &PEAR_Config::singleton(); + $this->config = PEAR_Config::singleton(); $this->debug = $this->config->get('verbose'); } diff --git a/3rdparty/PEAR/PackageFile/Generator/v1.php b/3rdparty/PEAR/PackageFile/Generator/v1.php index 2f42f178d595c8b57f7d7ac9838e2008af8c3109..69a4818799e2f99d6964e4859c61e4dad1f08665 100644 --- a/3rdparty/PEAR/PackageFile/Generator/v1.php +++ b/3rdparty/PEAR/PackageFile/Generator/v1.php @@ -109,7 +109,7 @@ class PEAR_PackageFile_Generator_v1 // }}} $packagexml = $this->toPackageFile($where, PEAR_VALIDATE_PACKAGING, 'package.xml', true); if ($packagexml) { - $tar =& new Archive_Tar($dest_package, $compress); + $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($packagexml), '', $where); diff --git a/3rdparty/PEAR/PackageFile/Generator/v2.php b/3rdparty/PEAR/PackageFile/Generator/v2.php index 4d202df27d30602c0f9acb46ad2d3c59fd61faca..8250e0ac4d027a85d3776ff6244b8a5958c30f57 100644 --- a/3rdparty/PEAR/PackageFile/Generator/v2.php +++ b/3rdparty/PEAR/PackageFile/Generator/v2.php @@ -269,7 +269,7 @@ http://pear.php.net/dtd/package-2.0.xsd', $name = $pf1 !== null ? 'package2.xml' : 'package.xml'; $packagexml = $this->toPackageFile($where, PEAR_VALIDATE_PACKAGING, $name); if ($packagexml) { - $tar =& new Archive_Tar($dest_package, $compress); + $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($packagexml), '', $where); diff --git a/3rdparty/XML/Parser.php b/3rdparty/XML/Parser.php index a38a161aef9dae100925b8cdcafde59883254aaa..04dd348753d2949f7c08a45492c69ce9c30b262a 100644 --- a/3rdparty/XML/Parser.php +++ b/3rdparty/XML/Parser.php @@ -191,26 +191,6 @@ class XML_Parser extends PEAR */ var $_validEncodings = array('ISO-8859-1', 'UTF-8', 'US-ASCII'); - // }}} - // {{{ php4 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 $tgtenc a valid target encoding - */ - function XML_Parser($srcenc = null, $mode = 'event', $tgtenc = null) - { - XML_Parser::__construct($srcenc, $mode, $tgtenc); - } // }}} // {{{ php5 constructor @@ -364,7 +344,7 @@ class XML_Parser extends PEAR } $this->parser = $xp; $result = $this->_initHandlers($this->mode); - if ($this->isError($result)) { + if (PEAR::isError($result)) { return $result; } xml_parser_set_option($xp, XML_OPTION_CASE_FOLDING, $this->folding); @@ -393,7 +373,7 @@ class XML_Parser extends PEAR function reset() { $result = $this->_create(); - if ($this->isError($result)) { + if (PEAR::isError($result)) { return $result; } return true; @@ -505,7 +485,7 @@ class XML_Parser extends PEAR * reset the parser */ $result = $this->reset(); - if ($this->isError($result)) { + if (PEAR::isError($result)) { return $result; } // if $this->fp was fopened previously @@ -610,10 +590,16 @@ class XML_Parser extends PEAR * * @return XML_Parser_Error reference to the error object **/ - function &raiseError($msg = null, $ecode = 0) + static function &raiseError($message = null, + $code = 0, + $mode = null, + $options = null, + $userinfo = null, + $error_class = null, + $skipmsg = false) { $msg = !is_null($msg) ? $msg : $this->parser; - $err = &new XML_Parser_Error($msg, $ecode); + $err = new XML_Parser_Error($msg, $ecode); return parent::raiseError($err); } diff --git a/3rdparty/simpletest/test/acceptance_test.php b/3rdparty/simpletest/test/acceptance_test.php deleted file mode 100644 index e96fe737e5fcdae82a72762bbbf5b9979ef4df4b..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/acceptance_test.php +++ /dev/null @@ -1,1729 +0,0 @@ -addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $this->assertTrue($browser->get($this->samples() . 'network_confirm.php')); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - $this->assertPattern('/Request method.*?
GET<\/dd>/', $browser->getContent()); - $this->assertEqual($browser->getTitle(), 'Simple test target file'); - $this->assertEqual($browser->getResponseCode(), 200); - $this->assertEqual($browser->getMimeType(), 'text/html'); - } - - function testPost() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $this->assertTrue($browser->post($this->samples() . 'network_confirm.php')); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - $this->assertPattern('/Request method.*?
POST<\/dd>/', $browser->getContent()); - } - - function testAbsoluteLinkFollowing() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($browser->clickLink('Absolute')); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - } - - function testRelativeEncodedLinkFollowing() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'link_confirm.php'); - // Warning: the below data is ISO 8859-1 encoded - $this->assertTrue($browser->clickLink("m\xE4rc\xEAl kiek'eboe")); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - } - - function testRelativeLinkFollowing() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($browser->clickLink('Relative')); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - } - - function testUnifiedClickLinkClicking() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($browser->click('Relative')); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - } - - function testIdLinkFollowing() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($browser->clickLinkById(1)); - $this->assertPattern('/target for the SimpleTest/', $browser->getContent()); - } - - function testCookieReading() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'set_cookies.php'); - $this->assertEqual($browser->getCurrentCookieValue('session_cookie'), 'A'); - $this->assertEqual($browser->getCurrentCookieValue('short_cookie'), 'B'); - $this->assertEqual($browser->getCurrentCookieValue('day_cookie'), 'C'); - } - - function testSimpleSubmit() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'form.html'); - $this->assertTrue($browser->clickSubmit('Go!')); - $this->assertPattern('/Request method.*?
POST<\/dd>/', $browser->getContent()); - $this->assertPattern('/go=\[Go!\]/', $browser->getContent()); - } - - function testUnifiedClickCanSubmit() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $browser->get($this->samples() . 'form.html'); - $this->assertTrue($browser->click('Go!')); - $this->assertPattern('/go=\[Go!\]/', $browser->getContent()); - } -} - -class TestOfLocalFileBrowser extends UnitTestCase { - function samples() { - return 'file://'.dirname(__FILE__).'/site/'; - } - - function testGet() { - $browser = new SimpleBrowser(); - $browser->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - $this->assertTrue($browser->get($this->samples() . 'file.html')); - $this->assertPattern('/Link to SimpleTest/', $browser->getContent()); - $this->assertEqual($browser->getTitle(), 'Link to SimpleTest'); - $this->assertFalse($browser->getResponseCode()); - $this->assertEqual($browser->getMimeType(), ''); - } -} - -class TestOfRequestMethods extends UnitTestCase { - function samples() { - return SimpleTestAcceptanceTest::samples(); - } - - function testHeadRequest() { - $browser = new SimpleBrowser(); - $this->assertTrue($browser->head($this->samples() . 'request_methods.php')); - $this->assertEqual($browser->getResponseCode(), 202); - } - - function testGetRequest() { - $browser = new SimpleBrowser(); - $this->assertTrue($browser->get($this->samples() . 'request_methods.php')); - $this->assertEqual($browser->getResponseCode(), 405); - } - - function testPostWithPlainEncoding() { - $browser = new SimpleBrowser(); - $this->assertTrue($browser->post($this->samples() . 'request_methods.php', 'A content message')); - $this->assertEqual($browser->getResponseCode(), 406); - $this->assertPattern('/Please ensure content type is an XML format/', $browser->getContent()); - } - - function testPostWithXmlEncoding() { - $browser = new SimpleBrowser(); - $this->assertTrue($browser->post($this->samples() . 'request_methods.php', 'c', 'text/xml')); - $this->assertEqual($browser->getResponseCode(), 201); - $this->assertPattern('/c/', $browser->getContent()); - } - - function testPutWithPlainEncoding() { - $browser = new SimpleBrowser(); - $this->assertTrue($browser->put($this->samples() . 'request_methods.php', 'A content message')); - $this->assertEqual($browser->getResponseCode(), 406); - $this->assertPattern('/Please ensure content type is an XML format/', $browser->getContent()); - } - - function testPutWithXmlEncoding() { - $browser = new SimpleBrowser(); - $this->assertTrue($browser->put($this->samples() . 'request_methods.php', 'c', 'application/xml')); - $this->assertEqual($browser->getResponseCode(), 201); - $this->assertPattern('/c/', $browser->getContent()); - } - - function testDeleteRequest() { - $browser = new SimpleBrowser(); - $browser->delete($this->samples() . 'request_methods.php'); - $this->assertEqual($browser->getResponseCode(), 202); - $this->assertPattern('/Your delete request was accepted/', $browser->getContent()); - } - -} - -class TestRadioFields extends SimpleTestAcceptanceTest { - function testSetFieldAsInteger() { - $this->get($this->samples() . 'form_with_radio_buttons.html'); - $this->assertTrue($this->setField('tested_field', 2)); - $this->clickSubmitByName('send'); - $this->assertEqual($this->getUrl(), $this->samples() . 'form_with_radio_buttons.html?tested_field=2&send=click+me'); - } - - function testSetFieldAsString() { - $this->get($this->samples() . 'form_with_radio_buttons.html'); - $this->assertTrue($this->setField('tested_field', '2')); - $this->clickSubmitByName('send'); - $this->assertEqual($this->getUrl(), $this->samples() . 'form_with_radio_buttons.html?tested_field=2&send=click+me'); - } -} - -class TestOfLiveFetching extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testFormWithArrayBasedInputs() { - $this->get($this->samples() . 'form_with_array_based_inputs.php'); - $this->setField('value[]', '3', '1'); - $this->setField('value[]', '4', '2'); - $this->clickSubmit('Go'); - $this->assertPattern('/QUERY_STRING : value%5B%5D=3&value%5B%5D=4&submit=Go/'); - } - - function testFormWithQuotedValues() { - $this->get($this->samples() . 'form_with_quoted_values.php'); - $this->assertField('a', 'default'); - $this->assertFieldById('text_field', 'default'); - $this->clickSubmit('Go'); - $this->assertPattern('/a=default&submit=Go/'); - } - - function testGet() { - $this->assertTrue($this->get($this->samples() . 'network_confirm.php')); - $this->assertEqual($this->getUrl(), $this->samples() . 'network_confirm.php'); - $this->assertText('target for the SimpleTest'); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertTitle('Simple test target file'); - $this->assertTitle(new PatternExpectation('/target file/')); - $this->assertResponse(200); - $this->assertMime('text/html'); - $this->assertHeader('connection', 'close'); - $this->assertHeader('connection', new PatternExpectation('/los/')); - } - - function testSlowGet() { - $this->assertTrue($this->get($this->samples() . 'slow_page.php')); - } - - function testTimedOutGet() { - $this->setConnectionTimeout(1); - $this->ignoreErrors(); - $this->assertFalse($this->get($this->samples() . 'slow_page.php')); - } - - function testPost() { - $this->assertTrue($this->post($this->samples() . 'network_confirm.php')); - $this->assertText('target for the SimpleTest'); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - } - - function testGetWithData() { - $this->get($this->samples() . 'network_confirm.php', array("a" => "aaa")); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertText('a=[aaa]'); - } - - function testPostWithData() { - $this->post($this->samples() . 'network_confirm.php', array("a" => "aaa")); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aaa]'); - } - - function testPostWithRecursiveData() { - $this->post($this->samples() . 'network_confirm.php', array("a" => "aaa")); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aaa]'); - - $this->post($this->samples() . 'network_confirm.php', array("a[aa]" => "aaa")); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aa=[aaa]]'); - - $this->post($this->samples() . 'network_confirm.php', array("a[aa][aaa]" => "aaaa")); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aa=[aaa=[aaaa]]]'); - - $this->post($this->samples() . 'network_confirm.php', array("a" => array("aa" => "aaa"))); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aa=[aaa]]'); - - $this->post($this->samples() . 'network_confirm.php', array("a" => array("aa" => array("aaa" => "aaaa")))); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aa=[aaa=[aaaa]]]'); - } - - function testRelativeGet() { - $this->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($this->get('network_confirm.php')); - $this->assertText('target for the SimpleTest'); - } - - function testRelativePost() { - $this->post($this->samples() . 'link_confirm.php', array('a' => '123')); - $this->assertTrue($this->post('network_confirm.php')); - $this->assertText('target for the SimpleTest'); - } -} - -class TestOfLinkFollowing extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testLinkAssertions() { - $this->get($this->samples() . 'link_confirm.php'); - $this->assertLink('Absolute', $this->samples() . 'network_confirm.php'); - $this->assertLink('Absolute', new PatternExpectation('/confirm/')); - $this->assertClickable('Absolute'); - } - - function testAbsoluteLinkFollowing() { - $this->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($this->clickLink('Absolute')); - $this->assertText('target for the SimpleTest'); - } - - function testRelativeLinkFollowing() { - $this->get($this->samples() . 'link_confirm.php'); - $this->assertTrue($this->clickLink('Relative')); - $this->assertText('target for the SimpleTest'); - } - - function testLinkIdFollowing() { - $this->get($this->samples() . 'link_confirm.php'); - $this->assertLinkById(1); - $this->assertTrue($this->clickLinkById(1)); - $this->assertText('target for the SimpleTest'); - } - - function testAbsoluteUrlBehavesAbsolutely() { - $this->get($this->samples() . 'link_confirm.php'); - $this->get('http://www.lastcraft.com'); - $this->assertText('No guarantee of quality is given or even intended'); - } - - function testRelativeUrlRespectsBaseTag() { - $this->get($this->samples() . 'base_tag/base_link.html'); - $this->click('Back to test pages'); - $this->assertTitle('Simple test target file'); - } -} - -class TestOfLivePageLinkingWithMinimalLinks extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testClickToExplicitelyNamedSelfReturns() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->assertEqual($this->getUrl(), $this->samples() . 'front_controller_style/a_page.php'); - $this->assertTitle('Simple test page with links'); - $this->assertLink('Self'); - $this->clickLink('Self'); - $this->assertTitle('Simple test page with links'); - } - - function testClickToMissingPageReturnsToSamePage() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->clickLink('No page'); - $this->assertTitle('Simple test page with links'); - $this->assertText('[action=no_page]'); - } - - function testClickToBareActionReturnsToSamePage() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->clickLink('Bare action'); - $this->assertTitle('Simple test page with links'); - $this->assertText('[action=]'); - } - - function testClickToSingleQuestionMarkReturnsToSamePage() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->clickLink('Empty query'); - $this->assertTitle('Simple test page with links'); - } - - function testClickToEmptyStringReturnsToSamePage() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->clickLink('Empty link'); - $this->assertTitle('Simple test page with links'); - } - - function testClickToSingleDotGoesToCurrentDirectory() { - $this->get($this->samples() . 'front_controller_style/a_page.php'); - $this->clickLink('Current directory'); - $this->assertTitle( - 'Simple test front controller', - '%s -> index.php needs to be set as a default web server home page'); - } - - function testClickBackADirectoryLevel() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('Down one'); - $this->assertPattern('|Index of .*?/test|i'); - } -} - -class TestOfLiveFrontControllerEmulation extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testJumpToNamedPage() { - $this->get($this->samples() . 'front_controller_style/'); - $this->assertText('Simple test front controller'); - $this->clickLink('Index'); - $this->assertResponse(200); - $this->assertText('[action=index]'); - } - - function testJumpToUnnamedPage() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('No page'); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - $this->assertText('[action=no_page]'); - } - - function testJumpToUnnamedPageWithBareParameter() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('Bare action'); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - $this->assertText('[action=]'); - } - - function testJumpToUnnamedPageWithEmptyQuery() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('Empty query'); - $this->assertResponse(200); - $this->assertPattern('/Simple test front controller/'); - $this->assertPattern('/raw get data.*?\[\].*?get data/si'); - } - - function testJumpToUnnamedPageWithEmptyLink() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('Empty link'); - $this->assertResponse(200); - $this->assertPattern('/Simple test front controller/'); - $this->assertPattern('/raw get data.*?\[\].*?get data/si'); - } - - function testJumpBackADirectoryLevel() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickLink('Down one'); - $this->assertPattern('|Index of .*?/test|'); - } - - function testSubmitToNamedPage() { - $this->get($this->samples() . 'front_controller_style/'); - $this->assertText('Simple test front controller'); - $this->clickSubmit('Index'); - $this->assertResponse(200); - $this->assertText('[action=Index]'); - } - - function testSubmitToSameDirectory() { - $this->get($this->samples() . 'front_controller_style/index.php'); - $this->clickSubmit('Same directory'); - $this->assertResponse(200); - $this->assertText('[action=Same+directory]'); - } - - function testSubmitToEmptyAction() { - $this->get($this->samples() . 'front_controller_style/index.php'); - $this->clickSubmit('Empty action'); - $this->assertResponse(200); - $this->assertText('[action=Empty+action]'); - } - - function testSubmitToNoAction() { - $this->get($this->samples() . 'front_controller_style/index.php'); - $this->clickSubmit('No action'); - $this->assertResponse(200); - $this->assertText('[action=No+action]'); - } - - function testSubmitBackADirectoryLevel() { - $this->get($this->samples() . 'front_controller_style/'); - $this->clickSubmit('Down one'); - $this->assertPattern('|Index of .*?/test|'); - } - - function testSubmitToNamedPageWithMixedPostAndGet() { - $this->get($this->samples() . 'front_controller_style/?a=A'); - $this->assertText('Simple test front controller'); - $this->clickSubmit('Index post'); - $this->assertText('action=[Index post]'); - $this->assertNoText('[a=A]'); - } - - function testSubmitToSameDirectoryMixedPostAndGet() { - $this->get($this->samples() . 'front_controller_style/index.php?a=A'); - $this->clickSubmit('Same directory post'); - $this->assertText('action=[Same directory post]'); - $this->assertNoText('[a=A]'); - } - - function testSubmitToEmptyActionMixedPostAndGet() { - $this->get($this->samples() . 'front_controller_style/index.php?a=A'); - $this->clickSubmit('Empty action post'); - $this->assertText('action=[Empty action post]'); - $this->assertText('[a=A]'); - } - - function testSubmitToNoActionMixedPostAndGet() { - $this->get($this->samples() . 'front_controller_style/index.php?a=A'); - $this->clickSubmit('No action post'); - $this->assertText('action=[No action post]'); - $this->assertText('[a=A]'); - } -} - -class TestOfLiveHeaders extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testConfirmingHeaderExistence() { - $this->get('http://www.lastcraft.com/'); - $this->assertHeader('content-type'); - $this->assertHeader('content-type', 'text/html'); - $this->assertHeader('content-type', new PatternExpectation('/HTML/i')); - $this->assertNoHeader('WWW-Authenticate'); - } -} - -class TestOfLiveRedirects extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testNoRedirects() { - $this->setMaximumRedirects(0); - $this->get($this->samples() . 'redirect.php'); - $this->assertTitle('Redirection test'); - } - - function testRedirects() { - $this->setMaximumRedirects(1); - $this->get($this->samples() . 'redirect.php'); - $this->assertTitle('Simple test target file'); - } - - function testRedirectLosesGetData() { - $this->get($this->samples() . 'redirect.php', array('a' => 'aaa')); - $this->assertNoText('a=[aaa]'); - } - - function testRedirectKeepsExtraRequestDataOfItsOwn() { - $this->get($this->samples() . 'redirect.php'); - $this->assertText('r=[rrr]'); - } - - function testRedirectLosesPostData() { - $this->post($this->samples() . 'redirect.php', array('a' => 'aaa')); - $this->assertTitle('Simple test target file'); - $this->assertNoText('a=[aaa]'); - } - - function testRedirectWithBaseUrlChange() { - $this->get($this->samples() . 'base_change_redirect.php'); - $this->assertTitle('Simple test target file in folder'); - $this->get($this->samples() . 'path/base_change_redirect.php'); - $this->assertTitle('Simple test target file'); - } - - function testRedirectWithDoubleBaseUrlChange() { - $this->get($this->samples() . 'double_base_change_redirect.php'); - $this->assertTitle('Simple test target file'); - } -} - -class TestOfLiveCookies extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function here() { - return new SimpleUrl($this->samples()); - } - - function thisHost() { - $here = $this->here(); - return $here->getHost(); - } - - function thisPath() { - $here = $this->here(); - return $here->getPath(); - } - - function testCookieSettingAndAssertions() { - $this->setCookie('a', 'Test cookie a'); - $this->setCookie('b', 'Test cookie b', $this->thisHost()); - $this->setCookie('c', 'Test cookie c', $this->thisHost(), $this->thisPath()); - $this->get($this->samples() . 'network_confirm.php'); - $this->assertText('Test cookie a'); - $this->assertText('Test cookie b'); - $this->assertText('Test cookie c'); - $this->assertCookie('a'); - $this->assertCookie('b', 'Test cookie b'); - $this->assertTrue($this->getCookie('c') == 'Test cookie c'); - } - - function testNoCookieSetWhenCookiesDisabled() { - $this->setCookie('a', 'Test cookie a'); - $this->ignoreCookies(); - $this->get($this->samples() . 'network_confirm.php'); - $this->assertNoText('Test cookie a'); - } - - function testCookieReading() { - $this->get($this->samples() . 'set_cookies.php'); - $this->assertCookie('session_cookie', 'A'); - $this->assertCookie('short_cookie', 'B'); - $this->assertCookie('day_cookie', 'C'); - } - - function testNoCookie() { - $this->assertNoCookie('aRandomCookie'); - } - - function testNoCookieReadingWhenCookiesDisabled() { - $this->ignoreCookies(); - $this->get($this->samples() . 'set_cookies.php'); - $this->assertNoCookie('session_cookie'); - $this->assertNoCookie('short_cookie'); - $this->assertNoCookie('day_cookie'); - } - - function testCookiePatternAssertions() { - $this->get($this->samples() . 'set_cookies.php'); - $this->assertCookie('session_cookie', new PatternExpectation('/a/i')); - } - - function testTemporaryCookieExpiry() { - $this->get($this->samples() . 'set_cookies.php'); - $this->restart(); - $this->assertNoCookie('session_cookie'); - $this->assertCookie('day_cookie', 'C'); - } - - function testTimedCookieExpiryWith100SecondMargin() { - $this->get($this->samples() . 'set_cookies.php'); - $this->ageCookies(3600); - $this->restart(time() + 100); - $this->assertNoCookie('session_cookie'); - $this->assertNoCookie('hour_cookie'); - $this->assertCookie('day_cookie', 'C'); - } - - function testNoClockOverDriftBy100Seconds() { - $this->get($this->samples() . 'set_cookies.php'); - $this->restart(time() + 200); - $this->assertNoCookie( - 'short_cookie', - '%s -> Please check your computer clock setting if you are not using NTP'); - } - - function testNoClockUnderDriftBy100Seconds() { - $this->get($this->samples() . 'set_cookies.php'); - $this->restart(time() + 0); - $this->assertCookie( - 'short_cookie', - 'B', - '%s -> Please check your computer clock setting if you are not using NTP'); - } - - function testCookiePath() { - $this->get($this->samples() . 'set_cookies.php'); - $this->assertNoCookie('path_cookie', 'D'); - $this->get('./path/show_cookies.php'); - $this->assertPattern('/path_cookie/'); - $this->assertCookie('path_cookie', 'D'); - } -} - -class LiveTestOfForms extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testSimpleSubmit() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('go=[Go!]'); - } - - function testDefaultFormValues() { - $this->get($this->samples() . 'form.html'); - $this->assertFieldByName('a', ''); - $this->assertFieldByName('b', 'Default text'); - $this->assertFieldByName('c', ''); - $this->assertFieldByName('d', 'd1'); - $this->assertFieldByName('e', false); - $this->assertFieldByName('f', 'on'); - $this->assertFieldByName('g', 'g3'); - $this->assertFieldByName('h', 2); - $this->assertFieldByName('go', 'Go!'); - $this->assertClickable('Go!'); - $this->assertSubmit('Go!'); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('go=[Go!]'); - $this->assertText('a=[]'); - $this->assertText('b=[Default text]'); - $this->assertText('c=[]'); - $this->assertText('d=[d1]'); - $this->assertNoText('e=['); - $this->assertText('f=[on]'); - $this->assertText('g=[g3]'); - } - - function testFormSubmissionByButtonLabel() { - $this->get($this->samples() . 'form.html'); - $this->setFieldByName('a', 'aaa'); - $this->setFieldByName('b', 'bbb'); - $this->setFieldByName('c', 'ccc'); - $this->setFieldByName('d', 'D2'); - $this->setFieldByName('e', 'on'); - $this->setFieldByName('f', false); - $this->setFieldByName('g', 'g2'); - $this->setFieldByName('h', 1); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[aaa]'); - $this->assertText('b=[bbb]'); - $this->assertText('c=[ccc]'); - $this->assertText('d=[d2]'); - $this->assertText('e=[on]'); - $this->assertNoText('f=['); - $this->assertText('g=[g2]'); - } - - function testAdditionalFormValues() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmit('Go!', array('add' => 'A'))); - $this->assertText('go=[Go!]'); - $this->assertText('add=[A]'); - } - - function testFormSubmissionByName() { - $this->get($this->samples() . 'form.html'); - $this->setFieldByName('a', 'A'); - $this->assertTrue($this->clickSubmitByName('go')); - $this->assertText('a=[A]'); - } - - function testFormSubmissionByNameAndAdditionalParameters() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmitByName('go', array('add' => 'A'))); - $this->assertText('go=[Go!]'); - $this->assertText('add=[A]'); - } - - function testFormSubmissionBySubmitButtonLabeledSubmit() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmitByName('test')); - $this->assertText('test=[Submit]'); - } - - function testFormSubmissionWithIds() { - $this->get($this->samples() . 'form.html'); - $this->assertFieldById(1, ''); - $this->assertFieldById(2, 'Default text'); - $this->assertFieldById(3, ''); - $this->assertFieldById(4, 'd1'); - $this->assertFieldById(5, false); - $this->assertFieldById(6, 'on'); - $this->assertFieldById(8, 'g3'); - $this->assertFieldById(11, 2); - $this->setFieldById(1, 'aaa'); - $this->setFieldById(2, 'bbb'); - $this->setFieldById(3, 'ccc'); - $this->setFieldById(4, 'D2'); - $this->setFieldById(5, 'on'); - $this->setFieldById(6, false); - $this->setFieldById(8, 'g2'); - $this->setFieldById(11, 'H1'); - $this->assertTrue($this->clickSubmitById(99)); - $this->assertText('a=[aaa]'); - $this->assertText('b=[bbb]'); - $this->assertText('c=[ccc]'); - $this->assertText('d=[d2]'); - $this->assertText('e=[on]'); - $this->assertNoText('f=['); - $this->assertText('g=[g2]'); - $this->assertText('h=[1]'); - $this->assertText('go=[Go!]'); - } - - function testFormSubmissionWithIdsAndAdditionnalData() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmitById(99, array('additionnal' => "data"))); - $this->assertText('additionnal=[data]'); - } - - function testFormSubmissionWithLabels() { - $this->get($this->samples() . 'form.html'); - $this->assertField('Text A', ''); - $this->assertField('Text B', 'Default text'); - $this->assertField('Text area C', ''); - $this->assertField('Selection D', 'd1'); - $this->assertField('Checkbox E', false); - $this->assertField('Checkbox F', 'on'); - $this->assertField('3', 'g3'); - $this->assertField('Selection H', 2); - $this->setField('Text A', 'aaa'); - $this->setField('Text B', 'bbb'); - $this->setField('Text area C', 'ccc'); - $this->setField('Selection D', 'D2'); - $this->setField('Checkbox E', 'on'); - $this->setField('Checkbox F', false); - $this->setField('2', 'g2'); - $this->setField('Selection H', 'H1'); - $this->clickSubmit('Go!'); - $this->assertText('a=[aaa]'); - $this->assertText('b=[bbb]'); - $this->assertText('c=[ccc]'); - $this->assertText('d=[d2]'); - $this->assertText('e=[on]'); - $this->assertNoText('f=['); - $this->assertText('g=[g2]'); - $this->assertText('h=[1]'); - $this->assertText('go=[Go!]'); - } - - function testSettingCheckboxWithBooleanTrueSetsUnderlyingValue() { - $this->get($this->samples() . 'form.html'); - $this->setField('Checkbox E', true); - $this->assertField('Checkbox E', 'on'); - $this->clickSubmit('Go!'); - $this->assertText('e=[on]'); - } - - function testFormSubmissionWithMixedPostAndGet() { - $this->get($this->samples() . 'form_with_mixed_post_and_get.html'); - $this->setField('Text A', 'Hello'); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[Hello]'); - $this->assertText('x=[X]'); - $this->assertText('y=[Y]'); - } - - function testFormSubmissionWithMixedPostAndEncodedGet() { - $this->get($this->samples() . 'form_with_mixed_post_and_get.html'); - $this->setField('Text B', 'Hello'); - $this->assertTrue($this->clickSubmit('Go encoded!')); - $this->assertText('b=[Hello]'); - $this->assertText('x=[X]'); - $this->assertText('y=[Y]'); - } - - function testFormSubmissionWithoutAction() { - $this->get($this->samples() . 'form_without_action.php?test=test'); - $this->assertText('_GET : [test]'); - $this->assertTrue($this->clickSubmit('Submit Post With Empty Action')); - $this->assertText('_GET : [test]'); - $this->assertText('_POST : [test]'); - } - - function testImageSubmissionByLabel() { - $this->get($this->samples() . 'form.html'); - $this->assertImage('Image go!'); - $this->assertTrue($this->clickImage('Image go!', 10, 12)); - $this->assertText('go_x=[10]'); - $this->assertText('go_y=[12]'); - } - - function testImageSubmissionByLabelWithAdditionalParameters() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickImage('Image go!', 10, 12, array('add' => 'A'))); - $this->assertText('add=[A]'); - } - - function testImageSubmissionByName() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickImageByName('go', 10, 12)); - $this->assertText('go_x=[10]'); - $this->assertText('go_y=[12]'); - } - - function testImageSubmissionById() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickImageById(97, 10, 12)); - $this->assertText('go_x=[10]'); - $this->assertText('go_y=[12]'); - } - - function testButtonSubmissionByLabel() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->clickSubmit('Button go!', 10, 12)); - $this->assertPattern('/go=\[ButtonGo\]/s'); - } - - function testNamelessSubmitSendsNoValue() { - $this->get($this->samples() . 'form_with_unnamed_submit.html'); - $this->click('Go!'); - $this->assertNoText('Go!'); - $this->assertNoText('submit'); - } - - function testNamelessImageSendsXAndYValues() { - $this->get($this->samples() . 'form_with_unnamed_submit.html'); - $this->clickImage('Image go!', 4, 5); - $this->assertNoText('ImageGo'); - $this->assertText('x=[4]'); - $this->assertText('y=[5]'); - } - - function testNamelessButtonSendsNoValue() { - $this->get($this->samples() . 'form_with_unnamed_submit.html'); - $this->click('Button Go!'); - $this->assertNoText('ButtonGo'); - } - - function testSelfSubmit() { - $this->get($this->samples() . 'self_form.php'); - $this->assertNoText('[Submitted]'); - $this->assertNoText('[Wrong form]'); - $this->assertTrue($this->clickSubmit()); - $this->assertText('[Submitted]'); - $this->assertNoText('[Wrong form]'); - $this->assertTitle('Test of form self submission'); - } - - function testSelfSubmitWithParameters() { - $this->get($this->samples() . 'self_form.php'); - $this->setFieldByName('visible', 'Resent'); - $this->assertTrue($this->clickSubmit()); - $this->assertText('[Resent]'); - } - - function testSettingOfBlankOption() { - $this->get($this->samples() . 'form.html'); - $this->assertTrue($this->setFieldByName('d', '')); - $this->clickSubmit('Go!'); - $this->assertText('d=[]'); - } - - function testAssertingFieldValueWithPattern() { - $this->get($this->samples() . 'form.html'); - $this->setField('c', 'A very long string'); - $this->assertField('c', new PatternExpectation('/very long/')); - } - - function testSendingMultipartFormDataEncodedForm() { - $this->get($this->samples() . 'form_data_encoded_form.html'); - $this->assertField('Text A', ''); - $this->assertField('Text B', 'Default text'); - $this->assertField('Text area C', ''); - $this->assertField('Selection D', 'd1'); - $this->assertField('Checkbox E', false); - $this->assertField('Checkbox F', 'on'); - $this->assertField('3', 'g3'); - $this->assertField('Selection H', 2); - $this->setField('Text A', 'aaa'); - $this->setField('Text B', 'bbb'); - $this->setField('Text area C', 'ccc'); - $this->setField('Selection D', 'D2'); - $this->setField('Checkbox E', 'on'); - $this->setField('Checkbox F', false); - $this->setField('2', 'g2'); - $this->setField('Selection H', 'H1'); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[aaa]'); - $this->assertText('b=[bbb]'); - $this->assertText('c=[ccc]'); - $this->assertText('d=[d2]'); - $this->assertText('e=[on]'); - $this->assertNoText('f=['); - $this->assertText('g=[g2]'); - $this->assertText('h=[1]'); - $this->assertText('go=[Go!]'); - } - - function testSettingVariousBlanksInFields() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->assertField('Text A', ''); - $this->setField('Text A', '0'); - $this->assertField('Text A', '0'); - $this->assertField('Text area B', ''); - $this->setField('Text area B', '0'); - $this->assertField('Text area B', '0'); - $this->assertField('Selection D', ''); - $this->setField('Selection D', 'D2'); - $this->assertField('Selection D', 'D2'); - $this->setField('Selection D', 'D3'); - $this->assertField('Selection D', '0'); - $this->setField('Selection D', 'D4'); - $this->assertField('Selection D', '?'); - $this->assertField('Checkbox E', ''); - $this->assertField('Checkbox F', 'on'); - $this->assertField('Checkbox G', '0'); - $this->assertField('Checkbox H', '?'); - $this->assertFieldByName('i', 'on'); - $this->setFieldByName('i', ''); - $this->assertFieldByName('i', ''); - $this->setFieldByName('i', '0'); - $this->assertFieldByName('i', '0'); - $this->setFieldByName('i', '?'); - $this->assertFieldByName('i', '?'); - } - - function testDefaultValueOfTextareaHasNewlinesAndWhitespacePreserved() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->assertField('Text area C', ' '); - } - - function chars($t) { - for ($i = 0; $i < strlen($t); $i++) { - print "[$t[$i]]"; - } - } - - function testSubmissionOfBlankFields() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->setField('Text A', ''); - $this->setField('Text area B', ''); - $this->setFieldByName('i', ''); - $this->click('Go!'); - $this->assertText('a=[]'); - $this->assertText('b=[]'); - $this->assertText('d=[]'); - $this->assertText('e=[]'); - $this->assertText('i=[]'); - } - - function testDefaultValueOfTextareaHasNewlinesAndWhitespacePreservedOnSubmission() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->click('Go!'); - $this->assertPattern('/c=\[ \]/'); - } - - function testSubmissionOfEmptyValues() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->setField('Selection D', 'D2'); - $this->click('Go!'); - $this->assertText('a=[]'); - $this->assertText('b=[]'); - $this->assertText('d=[D2]'); - $this->assertText('f=[on]'); - $this->assertText('i=[on]'); - } - - function testSubmissionOfZeroes() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->setField('Text A', '0'); - $this->setField('Text area B', '0'); - $this->setField('Selection D', 'D3'); - $this->setFieldByName('i', '0'); - $this->click('Go!'); - $this->assertText('a=[0]'); - $this->assertText('b=[0]'); - $this->assertText('d=[0]'); - $this->assertText('g=[0]'); - $this->assertText('i=[0]'); - } - - function testSubmissionOfQuestionMarks() { - $this->get($this->samples() . 'form_with_false_defaults.html'); - $this->setField('Text A', '?'); - $this->setField('Text area B', '?'); - $this->setField('Selection D', 'D4'); - $this->setFieldByName('i', '?'); - $this->click('Go!'); - $this->assertText('a=[?]'); - $this->assertText('b=[?]'); - $this->assertText('d=[?]'); - $this->assertText('h=[?]'); - $this->assertText('i=[?]'); - } - - function testSubmissionOfHtmlEncodedValues() { - $this->get($this->samples() . 'form_with_tricky_defaults.html'); - $this->assertField('Text A', '&\'"<>'); - $this->assertField('Text B', '"'); - $this->assertField('Text area C', '&\'"<>'); - $this->assertField('Selection D', "'"); - $this->assertField('Checkbox E', '&\'"<>'); - $this->assertField('Checkbox F', false); - $this->assertFieldByname('i', "'"); - $this->click('Go!'); - $this->assertText('a=[&\'"<>, "]'); - $this->assertText('c=[&\'"<>]'); - $this->assertText("d=[']"); - $this->assertText('e=[&\'"<>]'); - $this->assertText("i=[']"); - } - - function testFormActionRespectsBaseTag() { - $this->get($this->samples() . 'base_tag/form.html'); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('go=[Go!]'); - $this->assertText('a=[]'); - } -} - -class TestOfLiveMultiValueWidgets extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testDefaultFormValueSubmission() { - $this->get($this->samples() . 'multiple_widget_form.html'); - $this->assertFieldByName('a', array('a2', 'a3')); - $this->assertFieldByName('b', array('b2', 'b3')); - $this->assertFieldByName('c[]', array('c2', 'c3')); - $this->assertFieldByName('d', array('2', '3')); - $this->assertFieldByName('e', array('2', '3')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[a2, a3]'); - $this->assertText('b=[b2, b3]'); - $this->assertText('c=[c2, c3]'); - $this->assertText('d=[2, 3]'); - $this->assertText('e=[2, 3]'); - } - - function testSubmittingMultipleValues() { - $this->get($this->samples() . 'multiple_widget_form.html'); - $this->setFieldByName('a', array('a1', 'a4')); - $this->assertFieldByName('a', array('a1', 'a4')); - $this->assertFieldByName('a', array('a4', 'a1')); - $this->setFieldByName('b', array('b1', 'b4')); - $this->assertFieldByName('b', array('b1', 'b4')); - $this->setFieldByName('c[]', array('c1', 'c4')); - $this->assertField('c[]', array('c1', 'c4')); - $this->setFieldByName('d', array('1', '4')); - $this->assertField('d', array('1', '4')); - $this->setFieldByName('e', array('e1', 'e4')); - $this->assertField('e', array('1', '4')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[a1, a4]'); - $this->assertText('b=[b1, b4]'); - $this->assertText('c=[c1, c4]'); - $this->assertText('d=[1, 4]'); - $this->assertText('e=[1, 4]'); - } - - function testSettingByOptionValue() { - $this->get($this->samples() . 'multiple_widget_form.html'); - $this->setFieldByName('d', array('1', '4')); - $this->assertField('d', array('1', '4')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('d=[1, 4]'); - } - - function testSubmittingMultipleValuesByLabel() { - $this->get($this->samples() . 'multiple_widget_form.html'); - $this->setField('Multiple selection A', array('a1', 'a4')); - $this->assertField('Multiple selection A', array('a1', 'a4')); - $this->assertField('Multiple selection A', array('a4', 'a1')); - $this->setField('multiple selection C', array('c1', 'c4')); - $this->assertField('multiple selection C', array('c1', 'c4')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[a1, a4]'); - $this->assertText('c=[c1, c4]'); - } - - function testSavantStyleHiddenFieldDefaults() { - $this->get($this->samples() . 'savant_style_form.html'); - $this->assertFieldByName('a', array('a0')); - $this->assertFieldByName('b', array('b0')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[a0]'); - $this->assertText('b=[b0]'); - } - - function testSavantStyleHiddenDefaultsAreOverridden() { - $this->get($this->samples() . 'savant_style_form.html'); - $this->assertTrue($this->setFieldByName('a', array('a1'))); - $this->assertTrue($this->setFieldByName('b', 'b1')); - $this->assertTrue($this->clickSubmit('Go!')); - $this->assertText('a=[a1]'); - $this->assertText('b=[b1]'); - } - - function testSavantStyleFormSettingById() { - $this->get($this->samples() . 'savant_style_form.html'); - $this->assertFieldById(1, array('a0')); - $this->assertFieldById(4, array('b0')); - $this->assertTrue($this->setFieldById(2, 'a1')); - $this->assertTrue($this->setFieldById(5, 'b1')); - $this->assertTrue($this->clickSubmitById(99)); - $this->assertText('a=[a1]'); - $this->assertText('b=[b1]'); - } -} - -class TestOfFileUploads extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testSingleFileUpload() { - $this->get($this->samples() . 'upload_form.html'); - $this->assertTrue($this->setField('Content:', - dirname(__FILE__) . '/support/upload_sample.txt')); - $this->assertField('Content:', dirname(__FILE__) . '/support/upload_sample.txt'); - $this->click('Go!'); - $this->assertText('Sample for testing file upload'); - } - - function testMultipleFileUpload() { - $this->get($this->samples() . 'upload_form.html'); - $this->assertTrue($this->setField('Content:', - dirname(__FILE__) . '/support/upload_sample.txt')); - $this->assertTrue($this->setField('Supplemental:', - dirname(__FILE__) . '/support/supplementary_upload_sample.txt')); - $this->assertField('Supplemental:', - dirname(__FILE__) . '/support/supplementary_upload_sample.txt'); - $this->click('Go!'); - $this->assertText('Sample for testing file upload'); - $this->assertText('Some more text content'); - } - - function testBinaryFileUpload() { - $this->get($this->samples() . 'upload_form.html'); - $this->assertTrue($this->setField('Content:', - dirname(__FILE__) . '/support/latin1_sample')); - $this->click('Go!'); - $this->assertText( - implode('', file(dirname(__FILE__) . '/support/latin1_sample'))); - } -} - -class TestOfLiveHistoryNavigation extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testRetry() { - $this->get($this->samples() . 'cookie_based_counter.php'); - $this->assertPattern('/count: 1/i'); - $this->retry(); - $this->assertPattern('/count: 2/i'); - $this->retry(); - $this->assertPattern('/count: 3/i'); - } - - function testOfBackButton() { - $this->get($this->samples() . '1.html'); - $this->clickLink('2'); - $this->assertTitle('2'); - $this->assertTrue($this->back()); - $this->assertTitle('1'); - $this->assertTrue($this->forward()); - $this->assertTitle('2'); - $this->assertFalse($this->forward()); - } - - function testGetRetryResubmitsData() { - $this->assertTrue($this->get( - $this->samples() . 'network_confirm.php?a=aaa')); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertText('a=[aaa]'); - $this->retry(); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertText('a=[aaa]'); - } - - function testGetRetryResubmitsExtraData() { - $this->assertTrue($this->get( - $this->samples() . 'network_confirm.php', - array('a' => 'aaa'))); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertText('a=[aaa]'); - $this->retry(); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertText('a=[aaa]'); - } - - function testPostRetryResubmitsData() { - $this->assertTrue($this->post( - $this->samples() . 'network_confirm.php', - array('a' => 'aaa'))); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aaa]'); - $this->retry(); - $this->assertPattern('/Request method.*?
POST<\/dd>/'); - $this->assertText('a=[aaa]'); - } - - function testGetRetryResubmitsRepeatedData() { - $this->assertTrue($this->get( - $this->samples() . 'network_confirm.php?a=1&a=2')); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertText('a=[1, 2]'); - $this->retry(); - $this->assertPattern('/Request method.*?
GET<\/dd>/'); - $this->assertText('a=[1, 2]'); - } -} - -class TestOfLiveAuthentication extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testChallengeFromProtectedPage() { - $this->get($this->samples() . 'protected/'); - $this->assertResponse(401); - $this->assertAuthentication('Basic'); - $this->assertRealm('SimpleTest basic authentication'); - $this->assertRealm(new PatternExpectation('/simpletest/i')); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->retry(); - $this->assertResponse(200); - } - - function testTrailingSlashImpliedWithinRealm() { - $this->get($this->samples() . 'protected/'); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->get($this->samples() . 'protected'); - $this->assertResponse(200); - } - - function testTrailingSlashImpliedSettingRealm() { - $this->get($this->samples() . 'protected'); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->get($this->samples() . 'protected/'); - $this->assertResponse(200); - } - - function testEncodedAuthenticationFetchesPage() { - $this->get('http://test:secret@www.lastcraft.com/test/protected/'); - $this->assertResponse(200); - } - - function testEncodedAuthenticationFetchesPageAfterTrailingSlashRedirect() { - $this->get('http://test:secret@www.lastcraft.com/test/protected'); - $this->assertResponse(200); - } - - function testRealmExtendsToWholeDirectory() { - $this->get($this->samples() . 'protected/1.html'); - $this->authenticate('test', 'secret'); - $this->clickLink('2'); - $this->assertResponse(200); - $this->clickLink('3'); - $this->assertResponse(200); - } - - function testRedirectKeepsAuthentication() { - $this->get($this->samples() . 'protected/local_redirect.php'); - $this->authenticate('test', 'secret'); - $this->assertTitle('Simple test target file'); - } - - function testRedirectKeepsEncodedAuthentication() { - $this->get('http://test:secret@www.lastcraft.com/test/protected/local_redirect.php'); - $this->assertResponse(200); - $this->assertTitle('Simple test target file'); - } - - function testSessionRestartLosesAuthentication() { - $this->get($this->samples() . 'protected/'); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->restart(); - $this->get($this->samples() . 'protected/'); - $this->assertResponse(401); - } -} - -class TestOfLoadingFrames extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testNoFramesContentWhenFramesDisabled() { - $this->ignoreFrames(); - $this->get($this->samples() . 'one_page_frameset.html'); - $this->assertTitle('Frameset for testing of SimpleTest'); - $this->assertText('This content is for no frames only'); - } - - function testPatternMatchCanReadTheOnlyFrame() { - $this->get($this->samples() . 'one_page_frameset.html'); - $this->assertText('A target for the SimpleTest test suite'); - $this->assertNoText('This content is for no frames only'); - } - - function testMessyFramesetResponsesByName() { - $this->assertTrue($this->get( - $this->samples() . 'messy_frameset.html')); - $this->assertTitle('Frameset for testing of SimpleTest'); - - $this->assertTrue($this->setFrameFocus('Front controller')); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - - $this->assertTrue($this->setFrameFocus('One')); - $this->assertResponse(200); - $this->assertLink('2'); - - $this->assertTrue($this->setFrameFocus('Frame links')); - $this->assertResponse(200); - $this->assertLink('Set one to 2'); - - $this->assertTrue($this->setFrameFocus('Counter')); - $this->assertResponse(200); - $this->assertText('Count: 1'); - - $this->assertTrue($this->setFrameFocus('Redirected')); - $this->assertResponse(200); - $this->assertText('r=rrr'); - - $this->assertTrue($this->setFrameFocus('Protected')); - $this->assertResponse(401); - - $this->assertTrue($this->setFrameFocus('Protected redirect')); - $this->assertResponse(401); - - $this->assertTrue($this->setFrameFocusByIndex(1)); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - - $this->assertTrue($this->setFrameFocusByIndex(2)); - $this->assertResponse(200); - $this->assertLink('2'); - - $this->assertTrue($this->setFrameFocusByIndex(3)); - $this->assertResponse(200); - $this->assertLink('Set one to 2'); - - $this->assertTrue($this->setFrameFocusByIndex(4)); - $this->assertResponse(200); - $this->assertText('Count: 1'); - - $this->assertTrue($this->setFrameFocusByIndex(5)); - $this->assertResponse(200); - $this->assertText('r=rrr'); - - $this->assertTrue($this->setFrameFocusByIndex(6)); - $this->assertResponse(401); - - $this->assertTrue($this->setFrameFocusByIndex(7)); - } - - function testReloadingFramesetPage() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->assertText('Count: 1'); - $this->retry(); - $this->assertText('Count: 2'); - $this->retry(); - $this->assertText('Count: 3'); - } - - function testReloadingSingleFrameWithCookieCounter() { - $this->get($this->samples() . 'counting_frameset.html'); - $this->setFrameFocus('a'); - $this->assertText('Count: 1'); - $this->setFrameFocus('b'); - $this->assertText('Count: 2'); - - $this->setFrameFocus('a'); - $this->retry(); - $this->assertText('Count: 3'); - $this->retry(); - $this->assertText('Count: 4'); - $this->setFrameFocus('b'); - $this->assertText('Count: 2'); - } - - function testReloadingFrameWhenUnfocusedReloadsWholeFrameset() { - $this->get($this->samples() . 'counting_frameset.html'); - $this->setFrameFocus('a'); - $this->assertText('Count: 1'); - $this->setFrameFocus('b'); - $this->assertText('Count: 2'); - - $this->clearFrameFocus('a'); - $this->retry(); - - $this->assertTitle('Frameset for testing of SimpleTest'); - $this->setFrameFocus('a'); - $this->assertText('Count: 3'); - $this->setFrameFocus('b'); - $this->assertText('Count: 4'); - } - - function testClickingNormalLinkReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('2'); - $this->assertLink('3'); - $this->assertText('Simple test front controller'); - } - - function testJumpToNamedPageReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->assertPattern('/Simple test front controller/'); - $this->clickLink('Index'); - $this->assertResponse(200); - $this->assertText('[action=index]'); - $this->assertText('Count: 1'); - } - - function testJumpToUnnamedPageReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('No page'); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - $this->assertText('[action=no_page]'); - $this->assertText('Count: 1'); - } - - function testJumpToUnnamedPageWithBareParameterReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('Bare action'); - $this->assertResponse(200); - $this->assertText('Simple test front controller'); - $this->assertText('[action=]'); - $this->assertText('Count: 1'); - } - - function testJumpToUnnamedPageWithEmptyQueryReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('Empty query'); - $this->assertResponse(200); - $this->assertPattern('/Simple test front controller/'); - $this->assertPattern('/raw get data.*?\[\].*?get data/si'); - $this->assertPattern('/Count: 1/'); - } - - function testJumpToUnnamedPageWithEmptyLinkReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('Empty link'); - $this->assertResponse(200); - $this->assertPattern('/Simple test front controller/'); - $this->assertPattern('/raw get data.*?\[\].*?get data/si'); - $this->assertPattern('/Count: 1/'); - } - - function testJumpBackADirectoryLevelReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('Down one'); - $this->assertPattern('/index of .*\/test/i'); - $this->assertPattern('/Count: 1/'); - } - - function testSubmitToNamedPageReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->assertPattern('/Simple test front controller/'); - $this->clickSubmit('Index'); - $this->assertResponse(200); - $this->assertText('[action=Index]'); - $this->assertText('Count: 1'); - } - - function testSubmitToSameDirectoryReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickSubmit('Same directory'); - $this->assertResponse(200); - $this->assertText('[action=Same+directory]'); - $this->assertText('Count: 1'); - } - - function testSubmitToEmptyActionReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickSubmit('Empty action'); - $this->assertResponse(200); - $this->assertText('[action=Empty+action]'); - $this->assertText('Count: 1'); - } - - function testSubmitToNoActionReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickSubmit('No action'); - $this->assertResponse(200); - $this->assertText('[action=No+action]'); - $this->assertText('Count: 1'); - } - - function testSubmitBackADirectoryLevelReplacesJustThatFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickSubmit('Down one'); - $this->assertPattern('/index of .*\/test/i'); - $this->assertPattern('/Count: 1/'); - } - - function testTopLinkExitsFrameset() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->clickLink('Exit the frameset'); - $this->assertTitle('Simple test target file'); - } - - function testLinkInOnePageCanLoadAnother() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->assertNoLink('3'); - $this->clickLink('Set one to 2'); - $this->assertLink('3'); - $this->assertNoLink('2'); - $this->assertTitle('Frameset for testing of SimpleTest'); - } - - function testFrameWithRelativeLinksRespectsBaseTagForThatPage() { - $this->get($this->samples() . 'base_tag/frameset.html'); - $this->click('Back to test pages'); - $this->assertTitle('Frameset for testing of SimpleTest'); - $this->assertText('A target for the SimpleTest test suite'); - } - - function testRelativeLinkInFrameIsNotAffectedByFramesetBaseTag() { - $this->get($this->samples() . 'base_tag/frameset_with_base_tag.html'); - $this->assertText('This is page 1'); - $this->click('To page 2'); - $this->assertTitle('Frameset for testing of SimpleTest'); - $this->assertText('This is page 2'); - } -} - -class TestOfFrameAuthentication extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testUnauthenticatedFrameSendsChallenge() { - $this->get($this->samples() . 'protected/'); - $this->setFrameFocus('Protected'); - $this->assertAuthentication('Basic'); - $this->assertRealm('SimpleTest basic authentication'); - $this->assertResponse(401); - } - - function testCanReadFrameFromAlreadyAuthenticatedRealm() { - $this->get($this->samples() . 'protected/'); - $this->authenticate('test', 'secret'); - $this->get($this->samples() . 'messy_frameset.html'); - $this->setFrameFocus('Protected'); - $this->assertResponse(200); - $this->assertText('A target for the SimpleTest test suite'); - } - - function testCanAuthenticateFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->setFrameFocus('Protected'); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->assertText('A target for the SimpleTest test suite'); - $this->clearFrameFocus(); - $this->assertText('Count: 1'); - } - - function testCanAuthenticateRedirectedFrame() { - $this->get($this->samples() . 'messy_frameset.html'); - $this->setFrameFocus('Protected redirect'); - $this->assertResponse(401); - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->assertText('A target for the SimpleTest test suite'); - $this->clearFrameFocus(); - $this->assertText('Count: 1'); - } -} - -class TestOfNestedFrames extends SimpleTestAcceptanceTest { - function setUp() { - $this->addHeader('User-Agent: SimpleTest ' . SimpleTest::getVersion()); - } - - function testCanNavigateToSpecificContent() { - $this->get($this->samples() . 'nested_frameset.html'); - $this->assertTitle('Nested frameset for testing of SimpleTest'); - - $this->assertPattern('/This is frame A/'); - $this->assertPattern('/This is frame B/'); - $this->assertPattern('/Simple test front controller/'); - $this->assertLink('2'); - $this->assertLink('Set one to 2'); - $this->assertPattern('/Count: 1/'); - $this->assertPattern('/r=rrr/'); - - $this->setFrameFocus('pair'); - $this->assertPattern('/This is frame A/'); - $this->assertPattern('/This is frame B/'); - $this->assertNoPattern('/Simple test front controller/'); - $this->assertNoLink('2'); - - $this->setFrameFocus('aaa'); - $this->assertPattern('/This is frame A/'); - $this->assertNoPattern('/This is frame B/'); - - $this->clearFrameFocus(); - $this->assertResponse(200); - $this->setFrameFocus('messy'); - $this->assertResponse(200); - $this->setFrameFocus('Front controller'); - $this->assertResponse(200); - $this->assertPattern('/Simple test front controller/'); - $this->assertNoLink('2'); - } - - function testReloadingFramesetPage() { - $this->get($this->samples() . 'nested_frameset.html'); - $this->assertPattern('/Count: 1/'); - $this->retry(); - $this->assertPattern('/Count: 2/'); - $this->retry(); - $this->assertPattern('/Count: 3/'); - } - - function testRetryingNestedPageOnlyRetriesThatSet() { - $this->get($this->samples() . 'nested_frameset.html'); - $this->assertPattern('/Count: 1/'); - $this->setFrameFocus('messy'); - $this->retry(); - $this->assertPattern('/Count: 2/'); - $this->setFrameFocus('Counter'); - $this->retry(); - $this->assertPattern('/Count: 3/'); - - $this->clearFrameFocus(); - $this->setFrameFocus('messy'); - $this->setFrameFocus('Front controller'); - $this->retry(); - - $this->clearFrameFocus(); - $this->assertPattern('/Count: 3/'); - } - - function testAuthenticatingNestedPage() { - $this->get($this->samples() . 'nested_frameset.html'); - $this->setFrameFocus('messy'); - $this->setFrameFocus('Protected'); - $this->assertAuthentication('Basic'); - $this->assertRealm('SimpleTest basic authentication'); - $this->assertResponse(401); - - $this->authenticate('test', 'secret'); - $this->assertResponse(200); - $this->assertPattern('/A target for the SimpleTest test suite/'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/adapter_test.php b/3rdparty/simpletest/test/adapter_test.php deleted file mode 100644 index c1a06a2f6534b60f6f20e69864fa8fac6c738438..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/adapter_test.php +++ /dev/null @@ -1,50 +0,0 @@ -assertTrue(true, "PEAR true"); - $this->assertFalse(false, "PEAR false"); - } - - function testName() { - $this->assertTrue($this->getName() == get_class($this)); - } - - function testPass() { - $this->pass("PEAR pass"); - } - - function testNulls() { - $value = null; - $this->assertNull($value, "PEAR null"); - $value = 0; - $this->assertNotNull($value, "PEAR not null"); - } - - function testType() { - $this->assertType("Hello", "string", "PEAR type"); - } - - function testEquals() { - $this->assertEquals(12, 12, "PEAR identity"); - $this->setLooselyTyped(true); - $this->assertEquals("12", 12, "PEAR equality"); - } - - function testSame() { - $same = new SameTestClass(); - $this->assertSame($same, $same, "PEAR same"); - } - - function testRegExp() { - $this->assertRegExp('/hello/', "A big hello from me", "PEAR regex"); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/all_tests.php b/3rdparty/simpletest/test/all_tests.php deleted file mode 100644 index 99ce9451e32b8d62edc5e29efadab38ea43bbac8..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/all_tests.php +++ /dev/null @@ -1,13 +0,0 @@ -TestSuite('All tests for SimpleTest ' . SimpleTest::getVersion()); - $this->addFile(dirname(__FILE__) . '/unit_tests.php'); - $this->addFile(dirname(__FILE__) . '/shell_test.php'); - $this->addFile(dirname(__FILE__) . '/live_test.php'); - $this->addFile(dirname(__FILE__) . '/acceptance_test.php'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/arguments_test.php b/3rdparty/simpletest/test/arguments_test.php deleted file mode 100644 index 0cca4e99b244436869243a65b09cdfe8816cfcce..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/arguments_test.php +++ /dev/null @@ -1,82 +0,0 @@ -assertIdentical($arguments->a, false); - $this->assertIdentical($arguments->all(), array()); - } - - function testSingleArgumentNameRecordedAsTrue() { - $arguments = new SimpleArguments(array('me', '-a')); - $this->assertIdentical($arguments->a, true); - } - - function testSingleArgumentCanBeGivenAValue() { - $arguments = new SimpleArguments(array('me', '-a=AAA')); - $this->assertIdentical($arguments->a, 'AAA'); - } - - function testSingleArgumentCanBeGivenSpaceSeparatedValue() { - $arguments = new SimpleArguments(array('me', '-a', 'AAA')); - $this->assertIdentical($arguments->a, 'AAA'); - } - - function testWillBuildArrayFromRepeatedValue() { - $arguments = new SimpleArguments(array('me', '-a', 'A', '-a', 'AA')); - $this->assertIdentical($arguments->a, array('A', 'AA')); - } - - function testWillBuildArrayFromMultiplyRepeatedValues() { - $arguments = new SimpleArguments(array('me', '-a', 'A', '-a', 'AA', '-a', 'AAA')); - $this->assertIdentical($arguments->a, array('A', 'AA', 'AAA')); - } - - function testCanParseLongFormArguments() { - $arguments = new SimpleArguments(array('me', '--aa=AA', '--bb', 'BB')); - $this->assertIdentical($arguments->aa, 'AA'); - $this->assertIdentical($arguments->bb, 'BB'); - } - - function testGetsFullSetOfResultsAsHash() { - $arguments = new SimpleArguments(array('me', '-a', '-b=1', '-b', '2', '--aa=AA', '--bb', 'BB', '-c')); - $this->assertEqual($arguments->all(), - array('a' => true, 'b' => array('1', '2'), 'aa' => 'AA', 'bb' => 'BB', 'c' => true)); - } -} - -class TestOfHelpOutput extends UnitTestCase { - function testDisplaysGeneralHelpBanner() { - $help = new SimpleHelp('Cool program'); - $this->assertEqual($help->render(), "Cool program\n"); - } - - function testDisplaysOnlySingleLineEndings() { - $help = new SimpleHelp("Cool program\n"); - $this->assertEqual($help->render(), "Cool program\n"); - } - - function testDisplaysHelpOnShortFlag() { - $help = new SimpleHelp('Cool program'); - $help->explainFlag('a', 'Enables A'); - $this->assertEqual($help->render(), "Cool program\n-a Enables A\n"); - } - - function testHasAtleastFourSpacesAfterLongestFlag() { - $help = new SimpleHelp('Cool program'); - $help->explainFlag('a', 'Enables A'); - $help->explainFlag('long', 'Enables Long'); - $this->assertEqual($help->render(), - "Cool program\n-a Enables A\n--long Enables Long\n"); - } - - function testCanDisplaysMultipleFlagsForEachOption() { - $help = new SimpleHelp('Cool program'); - $help->explainFlag(array('a', 'aa'), 'Enables A'); - $this->assertEqual($help->render(), "Cool program\n-a Enables A\n --aa\n"); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/authentication_test.php b/3rdparty/simpletest/test/authentication_test.php deleted file mode 100644 index 081cccddfaedb74c38ce2fcc611cbbaa2f15a687..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/authentication_test.php +++ /dev/null @@ -1,145 +0,0 @@ -assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/hello.html'))); - } - - function testInsideWithLongerUrl() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/hello.html'))); - } - - function testBelowRootIsOutside() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/more/hello.html'))); - } - - function testOldNetscapeDefinitionIsOutside() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/')); - $this->assertFalse($realm->isWithin( - new SimpleUrl('http://www.here.com/pathmore/hello.html'))); - } - - function testInsideWithMissingTrailingSlash() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path'))); - } - - function testDifferentPageNameStillInside() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/hello.html')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/goodbye.html'))); - } - - function testNewUrlInSameDirectoryDoesNotChangeRealm() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/hello.html')); - $realm->stretch(new SimpleUrl('http://www.here.com/path/goodbye.html')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/index.html'))); - $this->assertFalse($realm->isWithin( - new SimpleUrl('http://www.here.com/index.html'))); - } - - function testNewUrlMakesRealmTheCommonPath() { - $realm = new SimpleRealm( - 'Basic', - new SimpleUrl('http://www.here.com/path/here/hello.html')); - $realm->stretch(new SimpleUrl('http://www.here.com/path/there/goodbye.html')); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/here/index.html'))); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/there/index.html'))); - $this->assertTrue($realm->isWithin( - new SimpleUrl('http://www.here.com/path/index.html'))); - $this->assertFalse($realm->isWithin( - new SimpleUrl('http://www.here.com/index.html'))); - $this->assertFalse($realm->isWithin( - new SimpleUrl('http://www.here.com/paths/index.html'))); - $this->assertFalse($realm->isWithin( - new SimpleUrl('http://www.here.com/pathindex.html'))); - } -} - -class TestOfAuthenticator extends UnitTestCase { - - function testNoRealms() { - $request = new MockSimpleHttpRequest(); - $request->expectNever('addHeaderLine'); - $authenticator = new SimpleAuthenticator(); - $authenticator->addHeaders($request, new SimpleUrl('http://here.com/')); - } - - function &createSingleRealm() { - $authenticator = new SimpleAuthenticator(); - $authenticator->addRealm( - new SimpleUrl('http://www.here.com/path/hello.html'), - 'Basic', - 'Sanctuary'); - $authenticator->setIdentityForRealm('www.here.com', 'Sanctuary', 'test', 'secret'); - return $authenticator; - } - - function testOutsideRealm() { - $request = new MockSimpleHttpRequest(); - $request->expectNever('addHeaderLine'); - $authenticator = &$this->createSingleRealm(); - $authenticator->addHeaders( - $request, - new SimpleUrl('http://www.here.com/hello.html')); - } - - function testWithinRealm() { - $request = new MockSimpleHttpRequest(); - $request->expectOnce('addHeaderLine'); - $authenticator = &$this->createSingleRealm(); - $authenticator->addHeaders( - $request, - new SimpleUrl('http://www.here.com/path/more/hello.html')); - } - - function testRestartingClearsRealm() { - $request = new MockSimpleHttpRequest(); - $request->expectNever('addHeaderLine'); - $authenticator = &$this->createSingleRealm(); - $authenticator->restartSession(); - $authenticator->addHeaders( - $request, - new SimpleUrl('http://www.here.com/hello.html')); - } - - function testDifferentHostIsOutsideRealm() { - $request = new MockSimpleHttpRequest(); - $request->expectNever('addHeaderLine'); - $authenticator = &$this->createSingleRealm(); - $authenticator->addHeaders( - $request, - new SimpleUrl('http://here.com/path/hello.html')); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/autorun_test.php b/3rdparty/simpletest/test/autorun_test.php deleted file mode 100644 index d85ea19897ce7150f690fb4a4d996e4f2c045491..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/autorun_test.php +++ /dev/null @@ -1,23 +0,0 @@ -addFile(dirname(__FILE__) . '/support/test1.php'); - $this->assertEqual($tests->getSize(), 1); - } - - function testExitStatusOneIfTestsFail() { - exec('php ' . dirname(__FILE__) . '/support/failing_test.php', $output, $exit_status); - $this->assertEqual($exit_status, 1); - } - - function testExitStatusZeroIfTestsPass() { - exec('php ' . dirname(__FILE__) . '/support/passing_test.php', $output, $exit_status); - $this->assertEqual($exit_status, 0); - } -} - -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/bad_test_suite.php b/3rdparty/simpletest/test/bad_test_suite.php deleted file mode 100644 index b426013be40f19a9d7634e1084394b45fbe182b9..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/bad_test_suite.php +++ /dev/null @@ -1,10 +0,0 @@ -TestSuite('Two bad test cases'); - $this->addFile(dirname(__FILE__) . '/support/empty_test_file.php'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/browser_test.php b/3rdparty/simpletest/test/browser_test.php deleted file mode 100644 index 3a52aaa8ff4a1c8b5ba9eae486fdbad0231eeaef..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/browser_test.php +++ /dev/null @@ -1,802 +0,0 @@ -assertIdentical($history->getUrl(), false); - $this->assertIdentical($history->getParameters(), false); - } - - function testCannotMoveInEmptyHistory() { - $history = new SimpleBrowserHistory(); - $this->assertFalse($history->back()); - $this->assertFalse($history->forward()); - } - - function testCurrentTargetAccessors() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.here.com/'), - new SimpleGetEncoding()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.here.com/')); - $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); - } - - function testSecondEntryAccessors() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.second.com/'), - new SimplePostEncoding(array('a' => 1))); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.second.com/')); - $this->assertIdentical( - $history->getParameters(), - new SimplePostEncoding(array('a' => 1))); - } - - function testGoingBackwards() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.second.com/'), - new SimplePostEncoding(array('a' => 1))); - $this->assertTrue($history->back()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); - $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); - } - - function testGoingBackwardsOffBeginning() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $this->assertFalse($history->back()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); - $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); - } - - function testGoingForwardsOffEnd() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $this->assertFalse($history->forward()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); - $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); - } - - function testGoingBackwardsAndForwards() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.second.com/'), - new SimplePostEncoding(array('a' => 1))); - $this->assertTrue($history->back()); - $this->assertTrue($history->forward()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.second.com/')); - $this->assertIdentical( - $history->getParameters(), - new SimplePostEncoding(array('a' => 1))); - } - - function testNewEntryReplacesNextOne() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.second.com/'), - new SimplePostEncoding(array('a' => 1))); - $history->back(); - $history->recordEntry( - new SimpleUrl('http://www.third.com/'), - new SimpleGetEncoding()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.third.com/')); - $this->assertIdentical($history->getParameters(), new SimpleGetEncoding()); - } - - function testNewEntryDropsFutureEntries() { - $history = new SimpleBrowserHistory(); - $history->recordEntry( - new SimpleUrl('http://www.first.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.second.com/'), - new SimpleGetEncoding()); - $history->recordEntry( - new SimpleUrl('http://www.third.com/'), - new SimpleGetEncoding()); - $history->back(); - $history->back(); - $history->recordEntry( - new SimpleUrl('http://www.fourth.com/'), - new SimpleGetEncoding()); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.fourth.com/')); - $this->assertFalse($history->forward()); - $history->back(); - $this->assertIdentical($history->getUrl(), new SimpleUrl('http://www.first.com/')); - $this->assertFalse($history->back()); - } -} - -class TestOfParsedPageAccess extends UnitTestCase { - - function loadPage(&$page) { - $response = new MockSimpleHttpResponse($this); - $agent = new MockSimpleUserAgent($this); - $agent->returns('fetchResponse', $response); - - $browser = new MockParseSimpleBrowser($this); - $browser->returns('createUserAgent', $agent); - $browser->returns('parse', $page); - $browser->__construct(); - - $browser->get('http://this.com/page.html'); - return $browser; - } - - function testAccessorsWhenNoPage() { - $agent = new MockSimpleUserAgent($this); - $browser = new MockParseSimpleBrowser($this); - $browser->returns('createUserAgent', $agent); - $browser->__construct(); - $this->assertEqual($browser->getContent(), ''); - } - - function testParse() { - $page = new MockSimplePage(); - $page->setReturnValue('getRequest', "GET here.html\r\n\r\n"); - $page->setReturnValue('getRaw', 'Raw HTML'); - $page->setReturnValue('getTitle', 'Here'); - $page->setReturnValue('getFrameFocus', 'Frame'); - $page->setReturnValue('getMimeType', 'text/html'); - $page->setReturnValue('getResponseCode', 200); - $page->setReturnValue('getAuthentication', 'Basic'); - $page->setReturnValue('getRealm', 'Somewhere'); - $page->setReturnValue('getTransportError', 'Ouch!'); - - $browser = $this->loadPage($page); - $this->assertEqual($browser->getRequest(), "GET here.html\r\n\r\n"); - $this->assertEqual($browser->getContent(), 'Raw HTML'); - $this->assertEqual($browser->getTitle(), 'Here'); - $this->assertEqual($browser->getFrameFocus(), 'Frame'); - $this->assertIdentical($browser->getResponseCode(), 200); - $this->assertEqual($browser->getMimeType(), 'text/html'); - $this->assertEqual($browser->getAuthentication(), 'Basic'); - $this->assertEqual($browser->getRealm(), 'Somewhere'); - $this->assertEqual($browser->getTransportError(), 'Ouch!'); - } - - function testLinkAffirmationWhenPresent() { - $page = new MockSimplePage(); - $page->setReturnValue('getUrlsByLabel', array('http://www.nowhere.com')); - $page->expectOnce('getUrlsByLabel', array('a link label')); - $browser = $this->loadPage($page); - $this->assertIdentical($browser->getLink('a link label'), 'http://www.nowhere.com'); - } - - function testLinkAffirmationByIdWhenPresent() { - $page = new MockSimplePage(); - $page->setReturnValue('getUrlById', 'a_page.com', array(99)); - $page->setReturnValue('getUrlById', false, array('*')); - $browser = $this->loadPage($page); - $this->assertIdentical($browser->getLinkById(99), 'a_page.com'); - $this->assertFalse($browser->getLinkById(98)); - } - - function testSettingFieldIsPassedToPage() { - $page = new MockSimplePage(); - $page->expectOnce('setField', array(new SimpleByLabelOrName('key'), 'Value', false)); - $page->setReturnValue('getField', 'Value'); - $browser = $this->loadPage($page); - $this->assertEqual($browser->getField('key'), 'Value'); - $browser->setField('key', 'Value'); - } -} - -class TestOfBrowserNavigation extends UnitTestCase { - function createBrowser($agent, $page) { - $browser = new MockParseSimpleBrowser(); - $browser->returns('createUserAgent', $agent); - $browser->returns('parse', $page); - $browser->__construct(); - return $browser; - } - - function testBrowserRequestMethods() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt( - 0, - 'fetchResponse', - array(new SimpleUrl('http://this.com/get.req'), new SimpleGetEncoding())); - $agent->expectAt( - 1, - 'fetchResponse', - array(new SimpleUrl('http://this.com/post.req'), new SimplePostEncoding())); - $agent->expectAt( - 2, - 'fetchResponse', - array(new SimpleUrl('http://this.com/put.req'), new SimplePutEncoding())); - $agent->expectAt( - 3, - 'fetchResponse', - array(new SimpleUrl('http://this.com/delete.req'), new SimpleDeleteEncoding())); - $agent->expectAt( - 4, - 'fetchResponse', - array(new SimpleUrl('http://this.com/head.req'), new SimpleHeadEncoding())); - $agent->expectCallCount('fetchResponse', 5); - - $page = new MockSimplePage(); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/get.req'); - $browser->post('http://this.com/post.req'); - $browser->put('http://this.com/put.req'); - $browser->delete('http://this.com/delete.req'); - $browser->head('http://this.com/head.req'); - } - - function testClickLinkRequestsPage() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt( - 0, - 'fetchResponse', - array(new SimpleUrl('http://this.com/page.html'), new SimpleGetEncoding())); - $agent->expectAt( - 1, - 'fetchResponse', - array(new SimpleUrl('http://this.com/new.html'), new SimpleGetEncoding())); - $agent->expectCallCount('fetchResponse', 2); - - $page = new MockSimplePage(); - $page->setReturnValue('getUrlsByLabel', array(new SimpleUrl('http://this.com/new.html'))); - $page->expectOnce('getUrlsByLabel', array('New')); - $page->setReturnValue('getRaw', 'A page'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickLink('New')); - } - - function testClickLinkWithUnknownFrameStillRequestsWholePage() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt( - 0, - 'fetchResponse', - array(new SimpleUrl('http://this.com/page.html'), new SimpleGetEncoding())); - $target = new SimpleUrl('http://this.com/new.html'); - $target->setTarget('missing'); - $agent->expectAt( - 1, - 'fetchResponse', - array($target, new SimpleGetEncoding())); - $agent->expectCallCount('fetchResponse', 2); - - $parsed_url = new SimpleUrl('http://this.com/new.html'); - $parsed_url->setTarget('missing'); - - $page = new MockSimplePage(); - $page->setReturnValue('getUrlsByLabel', array($parsed_url)); - $page->setReturnValue('hasFrames', false); - $page->expectOnce('getUrlsByLabel', array('New')); - $page->setReturnValue('getRaw', 'A page'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickLink('New')); - } - - function testClickingMissingLinkFails() { - $agent = new MockSimpleUserAgent($this); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - - $page = new MockSimplePage(); - $page->setReturnValue('getUrlsByLabel', array()); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $this->assertTrue($browser->get('http://this.com/page.html')); - $this->assertFalse($browser->clickLink('New')); - } - - function testClickIndexedLink() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt( - 1, - 'fetchResponse', - array(new SimpleUrl('1.html'), new SimpleGetEncoding())); - $agent->expectCallCount('fetchResponse', 2); - - $page = new MockSimplePage(); - $page->setReturnValue( - 'getUrlsByLabel', - array(new SimpleUrl('0.html'), new SimpleUrl('1.html'))); - $page->setReturnValue('getRaw', 'A page'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickLink('New', 1)); - } - - function testClinkLinkById() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt(1, 'fetchResponse', array( - new SimpleUrl('http://this.com/link.html'), - new SimpleGetEncoding())); - $agent->expectCallCount('fetchResponse', 2); - - $page = new MockSimplePage(); - $page->setReturnValue('getUrlById', new SimpleUrl('http://this.com/link.html')); - $page->expectOnce('getUrlById', array(2)); - $page->setReturnValue('getRaw', 'A page'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickLinkById(2)); - } - - function testClickingMissingLinkIdFails() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - - $page = new MockSimplePage(); - $page->setReturnValue('getUrlById', false); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertFalse($browser->clickLink(0)); - } - - function testSubmitFormByLabel() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt(1, 'fetchResponse', array( - new SimpleUrl('http://this.com/handler.html'), - new SimplePostEncoding(array('a' => 'A')))); - $agent->expectCallCount('fetchResponse', 2); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitButton', new SimplePostEncoding(array('a' => 'A'))); - $form->expectOnce('submitButton', array(new SimpleByLabel('Go'), false)); - - $page = new MockSimplePage(); - $page->returns('getFormBySubmit', $form); - $page->expectOnce('getFormBySubmit', array(new SimpleByLabel('Go'))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickSubmit('Go')); - } - - function testDefaultSubmitFormByLabel() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt(1, 'fetchResponse', array( - new SimpleUrl('http://this.com/page.html'), - new SimpleGetEncoding(array('a' => 'A')))); - $agent->expectCallCount('fetchResponse', 2); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/page.html')); - $form->setReturnValue('getMethod', 'get'); - $form->setReturnValue('submitButton', new SimpleGetEncoding(array('a' => 'A'))); - - $page = new MockSimplePage(); - $page->returns('getFormBySubmit', $form); - $page->expectOnce('getFormBySubmit', array(new SimpleByLabel('Submit'))); - $page->setReturnValue('getRaw', 'stuff'); - $page->setReturnValue('getUrl', new SimpleUrl('http://this.com/page.html')); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickSubmit()); - } - - function testSubmitFormByName() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitButton', new SimplePostEncoding(array('a' => 'A'))); - - $page = new MockSimplePage(); - $page->returns('getFormBySubmit', $form); - $page->expectOnce('getFormBySubmit', array(new SimpleByName('me'))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickSubmitByName('me')); - } - - function testSubmitFormById() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitButton', new SimplePostEncoding(array('a' => 'A'))); - $form->expectOnce('submitButton', array(new SimpleById(99), false)); - - $page = new MockSimplePage(); - $page->returns('getFormBySubmit', $form); - $page->expectOnce('getFormBySubmit', array(new SimpleById(99))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickSubmitById(99)); - } - - function testSubmitFormByImageLabel() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitImage', new SimplePostEncoding(array('a' => 'A'))); - $form->expectOnce('submitImage', array(new SimpleByLabel('Go!'), 10, 11, false)); - - $page = new MockSimplePage(); - $page->returns('getFormByImage', $form); - $page->expectOnce('getFormByImage', array(new SimpleByLabel('Go!'))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickImage('Go!', 10, 11)); - } - - function testSubmitFormByImageName() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitImage', new SimplePostEncoding(array('a' => 'A'))); - $form->expectOnce('submitImage', array(new SimpleByName('a'), 10, 11, false)); - - $page = new MockSimplePage(); - $page->returns('getFormByImage', $form); - $page->expectOnce('getFormByImage', array(new SimpleByName('a'))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickImageByName('a', 10, 11)); - } - - function testSubmitFormByImageId() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submitImage', new SimplePostEncoding(array('a' => 'A'))); - $form->expectOnce('submitImage', array(new SimpleById(99), 10, 11, false)); - - $page = new MockSimplePage(); - $page->returns('getFormByImage', $form); - $page->expectOnce('getFormByImage', array(new SimpleById(99))); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->clickImageById(99, 10, 11)); - } - - function testSubmitFormByFormId() { - $agent = new MockSimpleUserAgent(); - $agent->returns('fetchResponse', new MockSimpleHttpResponse()); - $agent->expectAt(1, 'fetchResponse', array( - new SimpleUrl('http://this.com/handler.html'), - new SimplePostEncoding(array('a' => 'A')))); - $agent->expectCallCount('fetchResponse', 2); - - $form = new MockSimpleForm(); - $form->setReturnValue('getAction', new SimpleUrl('http://this.com/handler.html')); - $form->setReturnValue('getMethod', 'post'); - $form->setReturnValue('submit', new SimplePostEncoding(array('a' => 'A'))); - - $page = new MockSimplePage(); - $page->returns('getFormById', $form); - $page->expectOnce('getFormById', array(33)); - $page->setReturnValue('getRaw', 'stuff'); - - $browser = $this->createBrowser($agent, $page); - $browser->get('http://this.com/page.html'); - $this->assertTrue($browser->submitFormById(33)); - } -} - -class TestOfBrowserFrames extends UnitTestCase { - - function createBrowser($agent) { - $browser = new MockUserAgentSimpleBrowser(); - $browser->returns('createUserAgent', $agent); - $browser->__construct(); - return $browser; - } - - function createUserAgent($pages) { - $agent = new MockSimpleUserAgent(); - foreach ($pages as $url => $raw) { - $url = new SimpleUrl($url); - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getUrl', $url); - $response->setReturnValue('getContent', $raw); - $agent->returns('fetchResponse', $response, array($url, '*')); - } - return $agent; - } - - function testSimplePageHasNoFrames() { - $browser = $this->createBrowser($this->createUserAgent( - array('http://site.with.no.frames/' => 'A non-framed page'))); - $this->assertEqual( - $browser->get('http://site.with.no.frames/'), - 'A non-framed page'); - $this->assertIdentical($browser->getFrames(), 'http://site.with.no.frames/'); - } - - function testFramesetWithSingleFrame() { - $frameset = ''; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.one.frame/' => $frameset, - 'http://site.with.one.frame/frame.html' => 'A frame'))); - $this->assertEqual($browser->get('http://site.with.one.frame/'), 'A frame'); - $this->assertIdentical( - $browser->getFrames(), - array('a' => 'http://site.with.one.frame/frame.html')); - } - - function testTitleTakenFromFramesetPage() { - $frameset = 'Frameset title' . - ''; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.one.frame/' => $frameset, - 'http://site.with.one.frame/frame.html' => 'Page title'))); - $browser->get('http://site.with.one.frame/'); - $this->assertEqual($browser->getTitle(), 'Frameset title'); - } - - function testFramesetWithSingleUnnamedFrame() { - $frameset = ''; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.one.frame/' => $frameset, - 'http://site.with.one.frame/frame.html' => 'One frame'))); - $this->assertEqual( - $browser->get('http://site.with.one.frame/'), - 'One frame'); - $this->assertIdentical( - $browser->getFrames(), - array(1 => 'http://site.with.one.frame/frame.html')); - } - - function testFramesetWithMultipleFrames() { - $frameset = '' . - '' . - '' . - '' . - ''; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.frames/' => $frameset, - 'http://site.with.frames/frame_a.html' => 'A frame', - 'http://site.with.frames/frame_b.html' => 'B frame', - 'http://site.with.frames/frame_c.html' => 'C frame'))); - $this->assertEqual( - $browser->get('http://site.with.frames/'), - 'A frameB frameC frame'); - $this->assertIdentical($browser->getFrames(), array( - 'a' => 'http://site.with.frames/frame_a.html', - 'b' => 'http://site.with.frames/frame_b.html', - 'c' => 'http://site.with.frames/frame_c.html')); - } - - function testFrameFocusByName() { - $frameset = '' . - '' . - '' . - '' . - ''; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.frames/' => $frameset, - 'http://site.with.frames/frame_a.html' => 'A frame', - 'http://site.with.frames/frame_b.html' => 'B frame', - 'http://site.with.frames/frame_c.html' => 'C frame'))); - $browser->get('http://site.with.frames/'); - $browser->setFrameFocus('a'); - $this->assertEqual($browser->getContent(), 'A frame'); - $browser->setFrameFocus('b'); - $this->assertEqual($browser->getContent(), 'B frame'); - $browser->setFrameFocus('c'); - $this->assertEqual($browser->getContent(), 'C frame'); - } - - function testFramesetWithSomeNamedFrames() { - $frameset = '' . - '' . - '' . - '' . - '' . - ''; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.frames/' => $frameset, - 'http://site.with.frames/frame_a.html' => 'A frame', - 'http://site.with.frames/frame_b.html' => 'B frame', - 'http://site.with.frames/frame_c.html' => 'C frame', - 'http://site.with.frames/frame_d.html' => 'D frame'))); - $this->assertEqual( - $browser->get('http://site.with.frames/'), - 'A frameB frameC frameD frame'); - $this->assertIdentical($browser->getFrames(), array( - 'a' => 'http://site.with.frames/frame_a.html', - 2 => 'http://site.with.frames/frame_b.html', - 'c' => 'http://site.with.frames/frame_c.html', - 4 => 'http://site.with.frames/frame_d.html')); - } - - function testFrameFocusWithMixedNamesAndIndexes() { - $frameset = '' . - '' . - '' . - '' . - '' . - ''; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.frames/' => $frameset, - 'http://site.with.frames/frame_a.html' => 'A frame', - 'http://site.with.frames/frame_b.html' => 'B frame', - 'http://site.with.frames/frame_c.html' => 'C frame', - 'http://site.with.frames/frame_d.html' => 'D frame'))); - $browser->get('http://site.with.frames/'); - $browser->setFrameFocus('a'); - $this->assertEqual($browser->getContent(), 'A frame'); - $browser->setFrameFocus(2); - $this->assertEqual($browser->getContent(), 'B frame'); - $browser->setFrameFocus('c'); - $this->assertEqual($browser->getContent(), 'C frame'); - $browser->setFrameFocus(4); - $this->assertEqual($browser->getContent(), 'D frame'); - $browser->clearFrameFocus(); - $this->assertEqual($browser->getContent(), 'A frameB frameC frameD frame'); - } - - function testNestedFrameset() { - $inner = '' . - '' . - ''; - $outer = '' . - '' . - ''; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.nested.frame/' => $outer, - 'http://site.with.nested.frame/inner.html' => $inner, - 'http://site.with.nested.frame/page.html' => 'The page'))); - $this->assertEqual( - $browser->get('http://site.with.nested.frame/'), - 'The page'); - $this->assertIdentical($browser->getFrames(), array( - 'inner' => array( - 'page' => 'http://site.with.nested.frame/page.html'))); - } - - function testCanNavigateToNestedFrame() { - $inner = '' . - '' . - '' . - ''; - $outer = '' . - '' . - '' . - ''; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.nested.frames/' => $outer, - 'http://site.with.nested.frames/inner.html' => $inner, - 'http://site.with.nested.frames/one.html' => 'Page one', - 'http://site.with.nested.frames/two.html' => 'Page two', - 'http://site.with.nested.frames/three.html' => 'Page three'))); - - $browser->get('http://site.with.nested.frames/'); - $this->assertEqual($browser->getContent(), 'Page onePage twoPage three'); - - $this->assertTrue($browser->setFrameFocus('inner')); - $this->assertEqual($browser->getFrameFocus(), array('inner')); - $this->assertTrue($browser->setFrameFocus('one')); - $this->assertEqual($browser->getFrameFocus(), array('inner', 'one')); - $this->assertEqual($browser->getContent(), 'Page one'); - - $this->assertTrue($browser->setFrameFocus('two')); - $this->assertEqual($browser->getFrameFocus(), array('inner', 'two')); - $this->assertEqual($browser->getContent(), 'Page two'); - - $browser->clearFrameFocus(); - $this->assertTrue($browser->setFrameFocus('three')); - $this->assertEqual($browser->getFrameFocus(), array('three')); - $this->assertEqual($browser->getContent(), 'Page three'); - - $this->assertTrue($browser->setFrameFocus('inner')); - $this->assertEqual($browser->getContent(), 'Page onePage two'); - } - - function testCanNavigateToNestedFrameByIndex() { - $inner = '' . - '' . - '' . - ''; - $outer = '' . - '' . - '' . - ''; - $browser = $this->createBrowser($this->createUserAgent(array( - 'http://site.with.nested.frames/' => $outer, - 'http://site.with.nested.frames/inner.html' => $inner, - 'http://site.with.nested.frames/one.html' => 'Page one', - 'http://site.with.nested.frames/two.html' => 'Page two', - 'http://site.with.nested.frames/three.html' => 'Page three'))); - - $browser->get('http://site.with.nested.frames/'); - $this->assertEqual($browser->getContent(), 'Page onePage twoPage three'); - - $this->assertTrue($browser->setFrameFocusByIndex(1)); - $this->assertEqual($browser->getFrameFocus(), array(1)); - $this->assertTrue($browser->setFrameFocusByIndex(1)); - $this->assertEqual($browser->getFrameFocus(), array(1, 1)); - $this->assertEqual($browser->getContent(), 'Page one'); - - $this->assertTrue($browser->setFrameFocusByIndex(2)); - $this->assertEqual($browser->getFrameFocus(), array(1, 2)); - $this->assertEqual($browser->getContent(), 'Page two'); - - $browser->clearFrameFocus(); - $this->assertTrue($browser->setFrameFocusByIndex(2)); - $this->assertEqual($browser->getFrameFocus(), array(2)); - $this->assertEqual($browser->getContent(), 'Page three'); - - $this->assertTrue($browser->setFrameFocusByIndex(1)); - $this->assertEqual($browser->getContent(), 'Page onePage two'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/collector_test.php b/3rdparty/simpletest/test/collector_test.php deleted file mode 100644 index efdbf377ece41ed96968d28f65ac82ac78d12543..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/collector_test.php +++ /dev/null @@ -1,50 +0,0 @@ -expectMinimumCallCount('addFile', 2); - $suite->expect( - 'addFile', - array(new PatternExpectation('/collectable\\.(1|2)$/'))); - $collector = new SimpleCollector(); - $collector->collect($suite, dirname(__FILE__) . '/support/collector/'); - } -} - -class TestOfPatternCollector extends UnitTestCase { - - function testAddingEverythingToGroup() { - $suite = new MockTestSuite(); - $suite->expectCallCount('addFile', 2); - $suite->expect( - 'addFile', - array(new PatternExpectation('/collectable\\.(1|2)$/'))); - $collector = new SimplePatternCollector('/.*/'); - $collector->collect($suite, dirname(__FILE__) . '/support/collector/'); - } - - function testOnlyMatchedFilesAreAddedToGroup() { - $suite = new MockTestSuite(); - $suite->expectOnce('addFile', array(new PathEqualExpectation( - dirname(__FILE__) . '/support/collector/collectable.1'))); - $collector = new SimplePatternCollector('/1$/'); - $collector->collect($suite, dirname(__FILE__) . '/support/collector/'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/command_line_test.php b/3rdparty/simpletest/test/command_line_test.php deleted file mode 100644 index 5baabff33c6794916815ed8ade8265677e1aa76b..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/command_line_test.php +++ /dev/null @@ -1,40 +0,0 @@ -assertIdentical($parser->getTest(), ''); - $this->assertIdentical($parser->getTestCase(), ''); - } - - function testNotXmlByDefault() { - $parser = new SimpleCommandLineParser(array()); - $this->assertFalse($parser->isXml()); - } - - function testCanDetectRequestForXml() { - $parser = new SimpleCommandLineParser(array('--xml')); - $this->assertTrue($parser->isXml()); - } - - function testCanReadAssignmentSyntax() { - $parser = new SimpleCommandLineParser(array('--test=myTest')); - $this->assertEqual($parser->getTest(), 'myTest'); - } - - function testCanReadFollowOnSyntax() { - $parser = new SimpleCommandLineParser(array('--test', 'myTest')); - $this->assertEqual($parser->getTest(), 'myTest'); - } - - function testCanReadShortForms() { - $parser = new SimpleCommandLineParser(array('-t', 'myTest', '-c', 'MyClass', '-x')); - $this->assertEqual($parser->getTest(), 'myTest'); - $this->assertEqual($parser->getTestCase(), 'MyClass'); - $this->assertTrue($parser->isXml()); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/compatibility_test.php b/3rdparty/simpletest/test/compatibility_test.php deleted file mode 100644 index b8635e5bb8370fa46c6d4ac2a97d23fa58188c3b..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/compatibility_test.php +++ /dev/null @@ -1,87 +0,0 @@ -assertTrue(SimpleTestCompatibility::isA( - new ComparisonClass(), - 'ComparisonClass')); - $this->assertFalse(SimpleTestCompatibility::isA( - new ComparisonClass(), - 'ComparisonSubclass')); - $this->assertTrue(SimpleTestCompatibility::isA( - new ComparisonSubclass(), - 'ComparisonClass')); - } - - function testIdentityOfNumericStrings() { - $numericString1 = "123"; - $numericString2 = "00123"; - $this->assertNotIdentical($numericString1, $numericString2); - } - - function testIdentityOfObjects() { - $object1 = new ComparisonClass(); - $object2 = new ComparisonClass(); - $this->assertIdentical($object1, $object2); - } - - function testReferences () { - $thing = "Hello"; - $thing_reference = &$thing; - $thing_copy = $thing; - $this->assertTrue(SimpleTestCompatibility::isReference( - $thing, - $thing)); - $this->assertTrue(SimpleTestCompatibility::isReference( - $thing, - $thing_reference)); - $this->assertFalse(SimpleTestCompatibility::isReference( - $thing, - $thing_copy)); - } - - function testObjectReferences () { - $object = new ComparisonClass(); - $object_reference = $object; - $object_copy = new ComparisonClass(); - $object_assignment = $object; - $this->assertTrue(SimpleTestCompatibility::isReference( - $object, - $object)); - $this->assertTrue(SimpleTestCompatibility::isReference( - $object, - $object_reference)); - $this->assertFalse(SimpleTestCompatibility::isReference( - $object, - $object_copy)); - if (version_compare(phpversion(), '5', '>=')) { - $this->assertTrue(SimpleTestCompatibility::isReference( - $object, - $object_assignment)); - } else { - $this->assertFalse(SimpleTestCompatibility::isReference( - $object, - $object_assignment)); - } - } - - function testInteraceComparison() { - $object = new ComparisonClassWithInterface(); - $this->assertFalse(SimpleTestCompatibility::isA( - new ComparisonClass(), - 'ComparisonInterface')); - $this->assertTrue(SimpleTestCompatibility::isA( - new ComparisonClassWithInterface(), - 'ComparisonInterface')); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/cookies_test.php b/3rdparty/simpletest/test/cookies_test.php deleted file mode 100644 index 0b49e43bf9f809805499d56d1c8ef2fc27e9662e..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/cookies_test.php +++ /dev/null @@ -1,227 +0,0 @@ -assertFalse($cookie->getValue()); - $this->assertEqual($cookie->getPath(), "/"); - $this->assertIdentical($cookie->getHost(), false); - $this->assertFalse($cookie->getExpiry()); - $this->assertFalse($cookie->isSecure()); - } - - function testCookieAccessors() { - $cookie = new SimpleCookie( - "name", - "value", - "/path", - "Mon, 18 Nov 2002 15:50:29 GMT", - true); - $this->assertEqual($cookie->getName(), "name"); - $this->assertEqual($cookie->getValue(), "value"); - $this->assertEqual($cookie->getPath(), "/path/"); - $this->assertEqual($cookie->getExpiry(), "Mon, 18 Nov 2002 15:50:29 GMT"); - $this->assertTrue($cookie->isSecure()); - } - - function testFullHostname() { - $cookie = new SimpleCookie("name"); - $this->assertTrue($cookie->setHost("host.name.here")); - $this->assertEqual($cookie->getHost(), "host.name.here"); - $this->assertTrue($cookie->setHost("host.com")); - $this->assertEqual($cookie->getHost(), "host.com"); - } - - function testHostTruncation() { - $cookie = new SimpleCookie("name"); - $cookie->setHost("this.host.name.here"); - $this->assertEqual($cookie->getHost(), "host.name.here"); - $cookie->setHost("this.host.com"); - $this->assertEqual($cookie->getHost(), "host.com"); - $this->assertTrue($cookie->setHost("dashes.in-host.com")); - $this->assertEqual($cookie->getHost(), "in-host.com"); - } - - function testBadHosts() { - $cookie = new SimpleCookie("name"); - $this->assertFalse($cookie->setHost("gibberish")); - $this->assertFalse($cookie->setHost("host.here")); - $this->assertFalse($cookie->setHost("host..com")); - $this->assertFalse($cookie->setHost("...")); - $this->assertFalse($cookie->setHost("host.com.")); - } - - function testHostValidity() { - $cookie = new SimpleCookie("name"); - $cookie->setHost("this.host.name.here"); - $this->assertTrue($cookie->isValidHost("host.name.here")); - $this->assertTrue($cookie->isValidHost("that.host.name.here")); - $this->assertFalse($cookie->isValidHost("bad.host")); - $this->assertFalse($cookie->isValidHost("nearly.name.here")); - } - - function testPathValidity() { - $cookie = new SimpleCookie("name", "value", "/path"); - $this->assertFalse($cookie->isValidPath("/")); - $this->assertTrue($cookie->isValidPath("/path/")); - $this->assertTrue($cookie->isValidPath("/path/more")); - } - - function testSessionExpiring() { - $cookie = new SimpleCookie("name", "value", "/path"); - $this->assertTrue($cookie->isExpired(0)); - } - - function testTimestampExpiry() { - $cookie = new SimpleCookie("name", "value", "/path", 456); - $this->assertFalse($cookie->isExpired(0)); - $this->assertTrue($cookie->isExpired(457)); - $this->assertFalse($cookie->isExpired(455)); - } - - function testDateExpiry() { - $cookie = new SimpleCookie( - "name", - "value", - "/path", - "Mon, 18 Nov 2002 15:50:29 GMT"); - $this->assertTrue($cookie->isExpired("Mon, 18 Nov 2002 15:50:30 GMT")); - $this->assertFalse($cookie->isExpired("Mon, 18 Nov 2002 15:50:28 GMT")); - } - - function testAging() { - $cookie = new SimpleCookie("name", "value", "/path", 200); - $cookie->agePrematurely(199); - $this->assertFalse($cookie->isExpired(0)); - $cookie->agePrematurely(2); - $this->assertTrue($cookie->isExpired(0)); - } -} - -class TestOfCookieJar extends UnitTestCase { - - function testAddCookie() { - $jar = new SimpleCookieJar(); - $jar->setCookie("a", "A"); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=A')); - } - - function testHostFilter() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', 'my-host.com'); - $jar->setCookie('b', 'B', 'another-host.com'); - $jar->setCookie('c', 'C'); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('my-host.com')), - array('a=A', 'c=C')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('another-host.com')), - array('b=B', 'c=C')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('www.another-host.com')), - array('b=B', 'c=C')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('new-host.org')), - array('c=C')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('/')), - array('a=A', 'b=B', 'c=C')); - } - - function testPathFilter() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', false, '/path/'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/elsewhere')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/')), array('a=A')); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path')), array('a=A')); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/pa')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/here')), array('a=A')); - } - - function testPathFilterDeeply() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', false, '/path/more_path/'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/pa')), array()); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/more_path/')), array('a=A')); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/more_path/and_more')), array('a=A')); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/path/not_here/')), array()); - } - - function testMultipleCookieWithDifferentPathsButSameName() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'abc', false, '/'); - $jar->setCookie('a', '123', false, '/path/here/'); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('/')), - array('a=abc')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('my-host.com/')), - array('a=abc')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('my-host.com/path/')), - array('a=abc')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('my-host.com/path/here')), - array('a=abc', 'a=123')); - $this->assertEqual( - $jar->selectAsPairs(new SimpleUrl('my-host.com/path/here/there')), - array('a=abc', 'a=123')); - } - - function testOverwrite() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'abc', false, '/'); - $jar->setCookie('a', 'cde', false, '/'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=cde')); - } - - function testClearSessionCookies() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', false, '/'); - $jar->restartSession(); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); - } - - function testExpiryFilterByDate() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', false, '/', 'Wed, 25-Dec-02 04:24:20 GMT'); - $jar->restartSession("Wed, 25-Dec-02 04:24:19 GMT"); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=A')); - $jar->restartSession("Wed, 25-Dec-02 04:24:21 GMT"); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); - } - - function testExpiryFilterByAgeing() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A', false, '/', 'Wed, 25-Dec-02 04:24:20 GMT'); - $jar->restartSession("Wed, 25-Dec-02 04:24:19 GMT"); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=A')); - $jar->agePrematurely(2); - $jar->restartSession("Wed, 25-Dec-02 04:24:19 GMT"); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); - } - - function testCookieClearing() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'abc', false, '/'); - $jar->setCookie('a', '', false, '/'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=')); - } - - function testCookieClearByLoweringDate() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'abc', false, '/', 'Wed, 25-Dec-02 04:24:21 GMT'); - $jar->setCookie('a', 'def', false, '/', 'Wed, 25-Dec-02 04:24:19 GMT'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array('a=def')); - $jar->restartSession('Wed, 25-Dec-02 04:24:20 GMT'); - $this->assertEqual($jar->selectAsPairs(new SimpleUrl('/')), array()); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/detached_test.php b/3rdparty/simpletest/test/detached_test.php deleted file mode 100644 index f651d97eb61404bf57c31f47760f4b434299976c..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/detached_test.php +++ /dev/null @@ -1,15 +0,0 @@ -add(new DetachedTestCase($command)); -if (SimpleReporter::inCli()) { - exit ($test->run(new TextReporter()) ? 0 : 1); -} -$test->run(new HtmlReporter()); -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/dumper_test.php b/3rdparty/simpletest/test/dumper_test.php deleted file mode 100644 index 789047de92467d02abc1a75bf8847335df24d615..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/dumper_test.php +++ /dev/null @@ -1,88 +0,0 @@ -assertEqual( - $dumper->clipString("Hello", 6), - "Hello", - "Hello, 6->%s"); - $this->assertEqual( - $dumper->clipString("Hello", 5), - "Hello", - "Hello, 5->%s"); - $this->assertEqual( - $dumper->clipString("Hello world", 3), - "Hel...", - "Hello world, 3->%s"); - $this->assertEqual( - $dumper->clipString("Hello world", 6, 3), - "Hello ...", - "Hello world, 6, 3->%s"); - $this->assertEqual( - $dumper->clipString("Hello world", 3, 6), - "...o w...", - "Hello world, 3, 6->%s"); - $this->assertEqual( - $dumper->clipString("Hello world", 4, 11), - "...orld", - "Hello world, 4, 11->%s"); - $this->assertEqual( - $dumper->clipString("Hello world", 4, 12), - "...orld", - "Hello world, 4, 12->%s"); - } - - function testDescribeNull() { - $dumper = new SimpleDumper(); - $this->assertPattern('/null/i', $dumper->describeValue(null)); - } - - function testDescribeBoolean() { - $dumper = new SimpleDumper(); - $this->assertPattern('/boolean/i', $dumper->describeValue(true)); - $this->assertPattern('/true/i', $dumper->describeValue(true)); - $this->assertPattern('/false/i', $dumper->describeValue(false)); - } - - function testDescribeString() { - $dumper = new SimpleDumper(); - $this->assertPattern('/string/i', $dumper->describeValue('Hello')); - $this->assertPattern('/Hello/', $dumper->describeValue('Hello')); - } - - function testDescribeInteger() { - $dumper = new SimpleDumper(); - $this->assertPattern('/integer/i', $dumper->describeValue(35)); - $this->assertPattern('/35/', $dumper->describeValue(35)); - } - - function testDescribeFloat() { - $dumper = new SimpleDumper(); - $this->assertPattern('/float/i', $dumper->describeValue(0.99)); - $this->assertPattern('/0\.99/', $dumper->describeValue(0.99)); - } - - function testDescribeArray() { - $dumper = new SimpleDumper(); - $this->assertPattern('/array/i', $dumper->describeValue(array(1, 4))); - $this->assertPattern('/2/i', $dumper->describeValue(array(1, 4))); - } - - function testDescribeObject() { - $dumper = new SimpleDumper(); - $this->assertPattern( - '/object/i', - $dumper->describeValue(new DumperDummy())); - $this->assertPattern( - '/DumperDummy/i', - $dumper->describeValue(new DumperDummy())); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/eclipse_test.php b/3rdparty/simpletest/test/eclipse_test.php deleted file mode 100644 index c90cbc918fd614e6d45f526f33665199deaed9ea..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/eclipse_test.php +++ /dev/null @@ -1,32 +0,0 @@ -expectOnce('write',array($expected)); - $listener->setReturnValue('write',-1); - - $pathparts = pathinfo($fullpath); - $filename = $pathparts['basename']; - $test= &new TestSuite($filename); - $test->addTestFile($fullpath); - $test->run(new EclipseReporter($listener)); - $this->assertEqual($expected,$listener->output); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/encoding_test.php b/3rdparty/simpletest/test/encoding_test.php deleted file mode 100644 index a09236e057cc4df97cb7b5603c36e2e328de8b5d..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/encoding_test.php +++ /dev/null @@ -1,240 +0,0 @@ -assertEqual($pair->asRequest(), 'a=A'); - } - - function testMimeEncodedAsHeadersAndContent() { - $pair = new SimpleEncodedPair('a', 'A'); - $this->assertEqual( - $pair->asMime(), - "Content-Disposition: form-data; name=\"a\"\r\n\r\nA"); - } - - function testAttachmentEncodedAsHeadersWithDispositionAndContent() { - $part = new SimpleAttachment('a', 'A', 'aaa.txt'); - $this->assertEqual( - $part->asMime(), - "Content-Disposition: form-data; name=\"a\"; filename=\"aaa.txt\"\r\n" . - "Content-Type: text/plain\r\n\r\nA"); - } -} - -class TestOfEncoding extends UnitTestCase { - private $content_so_far; - - function write($content) { - $this->content_so_far .= $content; - } - - function clear() { - $this->content_so_far = ''; - } - - function assertWritten($encoding, $content, $message = '%s') { - $this->clear(); - $encoding->writeTo($this); - $this->assertIdentical($this->content_so_far, $content, $message); - } - - function testGetEmpty() { - $encoding = new SimpleGetEncoding(); - $this->assertIdentical($encoding->getValue('a'), false); - $this->assertIdentical($encoding->asUrlRequest(), ''); - } - - function testPostEmpty() { - $encoding = new SimplePostEncoding(); - $this->assertIdentical($encoding->getValue('a'), false); - $this->assertWritten($encoding, ''); - } - - function testPrefilled() { - $encoding = new SimplePostEncoding(array('a' => 'aaa')); - $this->assertIdentical($encoding->getValue('a'), 'aaa'); - $this->assertWritten($encoding, 'a=aaa'); - } - - function testPrefilledWithTwoLevels() { - $query = array('a' => array('aa' => 'aaa')); - $encoding = new SimplePostEncoding($query); - $this->assertTrue($encoding->hasMoreThanOneLevel($query)); - $this->assertEqual($encoding->rewriteArrayWithMultipleLevels($query), array('a[aa]' => 'aaa')); - $this->assertIdentical($encoding->getValue('a[aa]'), 'aaa'); - $this->assertWritten($encoding, 'a%5Baa%5D=aaa'); - } - - function testPrefilledWithThreeLevels() { - $query = array('a' => array('aa' => array('aaa' => 'aaaa'))); - $encoding = new SimplePostEncoding($query); - $this->assertTrue($encoding->hasMoreThanOneLevel($query)); - $this->assertEqual($encoding->rewriteArrayWithMultipleLevels($query), array('a[aa][aaa]' => 'aaaa')); - $this->assertIdentical($encoding->getValue('a[aa][aaa]'), 'aaaa'); - $this->assertWritten($encoding, 'a%5Baa%5D%5Baaa%5D=aaaa'); - } - - function testPrefilledWithObject() { - $encoding = new SimplePostEncoding(new SimpleEncoding(array('a' => 'aaa'))); - $this->assertIdentical($encoding->getValue('a'), 'aaa'); - $this->assertWritten($encoding, 'a=aaa'); - } - - function testMultiplePrefilled() { - $query = array('a' => array('a1', 'a2')); - $encoding = new SimplePostEncoding($query); - $this->assertTrue($encoding->hasMoreThanOneLevel($query)); - $this->assertEqual($encoding->rewriteArrayWithMultipleLevels($query), array('a[0]' => 'a1', 'a[1]' => 'a2')); - $this->assertIdentical($encoding->getValue('a[0]'), 'a1'); - $this->assertIdentical($encoding->getValue('a[1]'), 'a2'); - $this->assertWritten($encoding, 'a%5B0%5D=a1&a%5B1%5D=a2'); - } - - function testSingleParameter() { - $encoding = new SimplePostEncoding(); - $encoding->add('a', 'Hello'); - $this->assertEqual($encoding->getValue('a'), 'Hello'); - $this->assertWritten($encoding, 'a=Hello'); - } - - function testFalseParameter() { - $encoding = new SimplePostEncoding(); - $encoding->add('a', false); - $this->assertEqual($encoding->getValue('a'), false); - $this->assertWritten($encoding, ''); - } - - function testUrlEncoding() { - $encoding = new SimplePostEncoding(); - $encoding->add('a', 'Hello there!'); - $this->assertWritten($encoding, 'a=Hello+there%21'); - } - - function testUrlEncodingOfKey() { - $encoding = new SimplePostEncoding(); - $encoding->add('a!', 'Hello'); - $this->assertWritten($encoding, 'a%21=Hello'); - } - - function testMultipleParameter() { - $encoding = new SimplePostEncoding(); - $encoding->add('a', 'Hello'); - $encoding->add('b', 'Goodbye'); - $this->assertWritten($encoding, 'a=Hello&b=Goodbye'); - } - - function testEmptyParameters() { - $encoding = new SimplePostEncoding(); - $encoding->add('a', ''); - $encoding->add('b', ''); - $this->assertWritten($encoding, 'a=&b='); - } - - function testRepeatedParameter() { - $encoding = new SimplePostEncoding(); - $encoding->add('a', 'Hello'); - $encoding->add('a', 'Goodbye'); - $this->assertIdentical($encoding->getValue('a'), array('Hello', 'Goodbye')); - $this->assertWritten($encoding, 'a=Hello&a=Goodbye'); - } - - function testAddingLists() { - $encoding = new SimplePostEncoding(); - $encoding->add('a', array('Hello', 'Goodbye')); - $this->assertIdentical($encoding->getValue('a'), array('Hello', 'Goodbye')); - $this->assertWritten($encoding, 'a=Hello&a=Goodbye'); - } - - function testMergeInHash() { - $encoding = new SimpleGetEncoding(array('a' => 'A1', 'b' => 'B')); - $encoding->merge(array('a' => 'A2')); - $this->assertIdentical($encoding->getValue('a'), array('A1', 'A2')); - $this->assertIdentical($encoding->getValue('b'), 'B'); - } - - function testMergeInObject() { - $encoding = new SimpleGetEncoding(array('a' => 'A1', 'b' => 'B')); - $encoding->merge(new SimpleEncoding(array('a' => 'A2'))); - $this->assertIdentical($encoding->getValue('a'), array('A1', 'A2')); - $this->assertIdentical($encoding->getValue('b'), 'B'); - } - - function testPrefilledMultipart() { - $encoding = new SimpleMultipartEncoding(array('a' => 'aaa'), 'boundary'); - $this->assertIdentical($encoding->getValue('a'), 'aaa'); - $this->assertwritten($encoding, - "--boundary\r\n" . - "Content-Disposition: form-data; name=\"a\"\r\n" . - "\r\n" . - "aaa\r\n" . - "--boundary--\r\n"); - } - - function testAttachment() { - $encoding = new SimpleMultipartEncoding(array(), 'boundary'); - $encoding->attach('a', 'aaa', 'aaa.txt'); - $this->assertIdentical($encoding->getValue('a'), 'aaa.txt'); - $this->assertwritten($encoding, - "--boundary\r\n" . - "Content-Disposition: form-data; name=\"a\"; filename=\"aaa.txt\"\r\n" . - "Content-Type: text/plain\r\n" . - "\r\n" . - "aaa\r\n" . - "--boundary--\r\n"); - } - - function testEntityEncodingDefaultContentType() { - $encoding = new SimpleEntityEncoding(); - $this->assertIdentical($encoding->getContentType(), 'application/x-www-form-urlencoded'); - $this->assertWritten($encoding, ''); - } - - function testEntityEncodingTextBody() { - $encoding = new SimpleEntityEncoding('plain text'); - $this->assertIdentical($encoding->getContentType(), 'text/plain'); - $this->assertWritten($encoding, 'plain text'); - } - - function testEntityEncodingXmlBody() { - $encoding = new SimpleEntityEncoding('

xmltext

', 'text/xml'); - $this->assertIdentical($encoding->getContentType(), 'text/xml'); - $this->assertWritten($encoding, '

xmltext

'); - } -} - -class TestOfEncodingHeaders extends UnitTestCase { - - function testEmptyEncodingWritesZeroContentLength() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Content-Length: 0\r\n")); - $socket->expectAt(1, 'write', array("Content-Type: application/x-www-form-urlencoded\r\n")); - $encoding = new SimpleEntityEncoding(); - $encoding->writeHeadersTo($socket); - } - - function testTextEncodingWritesDefaultContentType() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Content-Length: 18\r\n")); - $socket->expectAt(1, 'write', array("Content-Type: text/plain\r\n")); - $encoding = new SimpleEntityEncoding('one two three four'); - $encoding->writeHeadersTo($socket); - } - - function testEmptyMultipartEncodingWritesEndBoundaryContentLength() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Content-Length: 14\r\n")); - $socket->expectAt(1, 'write', array("Content-Type: multipart/form-data; boundary=boundary\r\n")); - $encoding = new SimpleMultipartEncoding(array(), 'boundary'); - $encoding->writeHeadersTo($socket); - } - -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/errors_test.php b/3rdparty/simpletest/test/errors_test.php deleted file mode 100644 index ebb9e05891f25d15279f986d58732edd096ae984..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/errors_test.php +++ /dev/null @@ -1,229 +0,0 @@ -get('SimpleErrorQueue'); - $queue->clear(); - } - - function tearDown() { - $context = SimpleTest::getContext(); - $queue = $context->get('SimpleErrorQueue'); - $queue->clear(); - } - - function testExpectationMatchCancelsIncomingError() { - $test = new MockSimpleTestCase(); - $test->expectOnce('assert', array( - new IdenticalExpectation(new AnythingExpectation()), - 'B', - 'a message')); - $test->setReturnValue('assert', true); - $test->expectNever('error'); - $queue = new SimpleErrorQueue(); - $queue->setTestCase($test); - $queue->expectError(new AnythingExpectation(), 'a message'); - $queue->add(1024, 'B', 'b.php', 100); - } -} - -class TestOfErrorTrap extends UnitTestCase { - private $old; - - function setUp() { - $this->old = error_reporting(E_ALL); - set_error_handler('SimpleTestErrorHandler'); - } - - function tearDown() { - restore_error_handler(); - error_reporting($this->old); - } - - function testQueueStartsEmpty() { - $context = SimpleTest::getContext(); - $queue = $context->get('SimpleErrorQueue'); - $this->assertFalse($queue->extract()); - } - - function testErrorsAreSwallowedByMatchingExpectation() { - $this->expectError('Ouch!'); - trigger_error('Ouch!'); - } - - function testErrorsAreSwallowedInOrder() { - $this->expectError('a'); - $this->expectError('b'); - trigger_error('a'); - trigger_error('b'); - } - - function testAnyErrorCanBeSwallowed() { - $this->expectError(); - trigger_error('Ouch!'); - } - - function testErrorCanBeSwallowedByPatternMatching() { - $this->expectError(new PatternExpectation('/ouch/i')); - trigger_error('Ouch!'); - } - - function testErrorWithPercentsPassesWithNoSprintfError() { - $this->expectError("%"); - trigger_error('%'); - } -} - -class TestOfErrors extends UnitTestCase { - private $old; - - function setUp() { - $this->old = error_reporting(E_ALL); - } - - function tearDown() { - error_reporting($this->old); - } - - function testDefaultWhenAllReported() { - error_reporting(E_ALL); - $this->expectError('Ouch!'); - trigger_error('Ouch!'); - } - - function testNoticeWhenReported() { - error_reporting(E_ALL); - $this->expectError('Ouch!'); - trigger_error('Ouch!', E_USER_NOTICE); - } - - function testWarningWhenReported() { - error_reporting(E_ALL); - $this->expectError('Ouch!'); - trigger_error('Ouch!', E_USER_WARNING); - } - - function testErrorWhenReported() { - error_reporting(E_ALL); - $this->expectError('Ouch!'); - trigger_error('Ouch!', E_USER_ERROR); - } - - function testNoNoticeWhenNotReported() { - error_reporting(0); - trigger_error('Ouch!', E_USER_NOTICE); - } - - function testNoWarningWhenNotReported() { - error_reporting(0); - trigger_error('Ouch!', E_USER_WARNING); - } - - function testNoticeSuppressedWhenReported() { - error_reporting(E_ALL); - @trigger_error('Ouch!', E_USER_NOTICE); - } - - function testWarningSuppressedWhenReported() { - error_reporting(E_ALL); - @trigger_error('Ouch!', E_USER_WARNING); - } - - function testErrorWithPercentsReportedWithNoSprintfError() { - $this->expectError('%'); - trigger_error('%'); - } -} - -class TestOfPHP52RecoverableErrors extends UnitTestCase { - function skip() { - $this->skipIf( - version_compare(phpversion(), '5.2', '<'), - 'E_RECOVERABLE_ERROR not tested for PHP below 5.2'); - } - - function testError() { - eval(' - class RecoverableErrorTestingStub { - function ouch(RecoverableErrorTestingStub $obj) { - } - } - '); - - $stub = new RecoverableErrorTestingStub(); - $this->expectError(new PatternExpectation('/must be an instance of RecoverableErrorTestingStub/i')); - $stub->ouch(new stdClass()); - } -} - -class TestOfErrorsExcludingPHP52AndAbove extends UnitTestCase { - function skip() { - $this->skipIf( - version_compare(phpversion(), '5.2', '>='), - 'E_USER_ERROR not tested for PHP 5.2 and above'); - } - - function testNoErrorWhenNotReported() { - error_reporting(0); - trigger_error('Ouch!', E_USER_ERROR); - } - - function testErrorSuppressedWhenReported() { - error_reporting(E_ALL); - @trigger_error('Ouch!', E_USER_ERROR); - } -} - -SimpleTest::ignore('TestOfNotEnoughErrors'); -/** - * This test is ignored as it is used by {@link TestRunnerForLeftOverAndNotEnoughErrors} - * to verify that it fails as expected. - * - * @ignore - */ -class TestOfNotEnoughErrors extends UnitTestCase { - function testExpectTwoErrorsThrowOne() { - $this->expectError('Error 1'); - trigger_error('Error 1'); - $this->expectError('Error 2'); - } -} - -SimpleTest::ignore('TestOfLeftOverErrors'); -/** - * This test is ignored as it is used by {@link TestRunnerForLeftOverAndNotEnoughErrors} - * to verify that it fails as expected. - * - * @ignore - */ -class TestOfLeftOverErrors extends UnitTestCase { - function testExpectOneErrorGetTwo() { - $this->expectError('Error 1'); - trigger_error('Error 1'); - trigger_error('Error 2'); - } -} - -class TestRunnerForLeftOverAndNotEnoughErrors extends UnitTestCase { - function testRunLeftOverErrorsTestCase() { - $test = new TestOfLeftOverErrors(); - $this->assertFalse($test->run(new SimpleReporter())); - } - - function testRunNotEnoughErrors() { - $test = new TestOfNotEnoughErrors(); - $this->assertFalse($test->run(new SimpleReporter())); - } -} - -// TODO: Add stacked error handler test -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/exceptions_test.php b/3rdparty/simpletest/test/exceptions_test.php deleted file mode 100644 index 1011543d4fa8c9443a76377272c7b20513d85379..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/exceptions_test.php +++ /dev/null @@ -1,183 +0,0 @@ -assertTrue($expectation->test(new MyTestException())); - $this->assertTrue($expectation->test(new HigherTestException())); - $this->assertFalse($expectation->test(new OtherTestException())); - } - - function testMatchesClassAndMessageWhenExceptionExpected() { - $expectation = new ExceptionExpectation(new MyTestException('Hello')); - $this->assertTrue($expectation->test(new MyTestException('Hello'))); - $this->assertFalse($expectation->test(new HigherTestException('Hello'))); - $this->assertFalse($expectation->test(new OtherTestException('Hello'))); - $this->assertFalse($expectation->test(new MyTestException('Goodbye'))); - $this->assertFalse($expectation->test(new MyTestException())); - } - - function testMessagelessExceptionMatchesOnlyOnClass() { - $expectation = new ExceptionExpectation(new MyTestException()); - $this->assertTrue($expectation->test(new MyTestException())); - $this->assertFalse($expectation->test(new HigherTestException())); - } -} - -class TestOfExceptionTrap extends UnitTestCase { - - function testNoExceptionsInQueueMeansNoTestMessages() { - $test = new MockSimpleTestCase(); - $test->expectNever('assert'); - $queue = new SimpleExceptionTrap(); - $this->assertFalse($queue->isExpected($test, new Exception())); - } - - function testMatchingExceptionGivesTrue() { - $expectation = new MockSimpleExpectation(); - $expectation->setReturnValue('test', true); - $test = new MockSimpleTestCase(); - $test->setReturnValue('assert', true); - $queue = new SimpleExceptionTrap(); - $queue->expectException($expectation, 'message'); - $this->assertTrue($queue->isExpected($test, new Exception())); - } - - function testMatchingExceptionTriggersAssertion() { - $test = new MockSimpleTestCase(); - $test->expectOnce('assert', array( - '*', - new ExceptionExpectation(new Exception()), - 'message')); - $queue = new SimpleExceptionTrap(); - $queue->expectException(new ExceptionExpectation(new Exception()), 'message'); - $queue->isExpected($test, new Exception()); - } -} - -class TestOfCatchingExceptions extends UnitTestCase { - - function testCanCatchAnyExpectedException() { - $this->expectException(); - throw new Exception(); - } - - function testCanMatchExceptionByClass() { - $this->expectException('MyTestException'); - throw new HigherTestException(); - } - - function testCanMatchExceptionExactly() { - $this->expectException(new Exception('Ouch')); - throw new Exception('Ouch'); - } - - function testLastListedExceptionIsTheOneThatCounts() { - $this->expectException('OtherTestException'); - $this->expectException('MyTestException'); - throw new HigherTestException(); - } -} - -class TestOfIgnoringExceptions extends UnitTestCase { - - function testCanIgnoreAnyException() { - $this->ignoreException(); - throw new Exception(); - } - - function testCanIgnoreSpecificException() { - $this->ignoreException('MyTestException'); - throw new MyTestException(); - } - - function testCanIgnoreExceptionExactly() { - $this->ignoreException(new Exception('Ouch')); - throw new Exception('Ouch'); - } - - function testIgnoredExceptionsDoNotMaskExpectedExceptions() { - $this->ignoreException('Exception'); - $this->expectException('MyTestException'); - throw new MyTestException(); - } - - function testCanIgnoreMultipleExceptions() { - $this->ignoreException('MyTestException'); - $this->ignoreException('OtherTestException'); - throw new OtherTestException(); - } -} - -class TestOfCallingTearDownAfterExceptions extends UnitTestCase { - private $debri = 0; - - function tearDown() { - $this->debri--; - } - - function testLeaveSomeDebri() { - $this->debri++; - $this->expectException(); - throw new Exception(__FUNCTION__); - } - - function testDebriWasRemovedOnce() { - $this->assertEqual($this->debri, 0); - } -} - -class TestOfExceptionThrownInSetUpDoesNotRunTestBody extends UnitTestCase { - - function setUp() { - $this->expectException(); - throw new Exception(); - } - - function testShouldNotBeRun() { - $this->fail('This test body should not be run'); - } - - function testShouldNotBeRunEither() { - $this->fail('This test body should not be run either'); - } -} - -class TestOfExpectExceptionWithSetUp extends UnitTestCase { - - function setUp() { - $this->expectException(); - } - - function testThisExceptionShouldBeCaught() { - throw new Exception(); - } - - function testJustThrowingMyTestException() { - throw new MyTestException(); - } -} - -class TestOfThrowingExceptionsInTearDown extends UnitTestCase { - - function tearDown() { - throw new Exception(); - } - - function testDoesntFatal() { - $this->expectException(); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/expectation_test.php b/3rdparty/simpletest/test/expectation_test.php deleted file mode 100644 index 31fbe65e683289b907c14b9bec36e7174cb378db..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/expectation_test.php +++ /dev/null @@ -1,317 +0,0 @@ -assertTrue($is_true->test(true)); - $this->assertFalse($is_true->test(false)); - } - - function testStringMatch() { - $hello = new EqualExpectation("Hello"); - $this->assertTrue($hello->test("Hello")); - $this->assertFalse($hello->test("Goodbye")); - } - - function testInteger() { - $fifteen = new EqualExpectation(15); - $this->assertTrue($fifteen->test(15)); - $this->assertFalse($fifteen->test(14)); - } - - function testFloat() { - $pi = new EqualExpectation(3.14); - $this->assertTrue($pi->test(3.14)); - $this->assertFalse($pi->test(3.15)); - } - - function testArray() { - $colours = new EqualExpectation(array("r", "g", "b")); - $this->assertTrue($colours->test(array("r", "g", "b"))); - $this->assertFalse($colours->test(array("g", "b", "r"))); - } - - function testHash() { - $is_blue = new EqualExpectation(array("r" => 0, "g" => 0, "b" => 255)); - $this->assertTrue($is_blue->test(array("r" => 0, "g" => 0, "b" => 255))); - $this->assertFalse($is_blue->test(array("r" => 0, "g" => 255, "b" => 0))); - } - - function testHashWithOutOfOrderKeysShouldStillMatch() { - $any_order = new EqualExpectation(array('a' => 1, 'b' => 2)); - $this->assertTrue($any_order->test(array('b' => 2, 'a' => 1))); - } -} - -class TestOfWithin extends UnitTestCase { - - function testWithinFloatingPointMargin() { - $within = new WithinMarginExpectation(1.0, 0.2); - $this->assertFalse($within->test(0.7)); - $this->assertTrue($within->test(0.8)); - $this->assertTrue($within->test(0.9)); - $this->assertTrue($within->test(1.1)); - $this->assertTrue($within->test(1.2)); - $this->assertFalse($within->test(1.3)); - } - - function testOutsideFloatingPointMargin() { - $within = new OutsideMarginExpectation(1.0, 0.2); - $this->assertTrue($within->test(0.7)); - $this->assertFalse($within->test(0.8)); - $this->assertFalse($within->test(1.2)); - $this->assertTrue($within->test(1.3)); - } -} - -class TestOfInequality extends UnitTestCase { - - function testStringMismatch() { - $not_hello = new NotEqualExpectation("Hello"); - $this->assertTrue($not_hello->test("Goodbye")); - $this->assertFalse($not_hello->test("Hello")); - } -} - -class RecursiveNasty { - private $me; - - function RecursiveNasty() { - $this->me = $this; - } -} - -class OpaqueContainer { - private $stuff; - private $value; - - public function __construct($value) { - $this->value = $value; - } -} - -class DerivedOpaqueContainer extends OpaqueContainer { - // Deliberately have a variable whose name with the same suffix as a later - // variable - private $new_value = 1; - - // Deliberately obscures the variable of the same name in the base - // class. - private $value; - - public function __construct($value, $base_value) { - parent::__construct($base_value); - $this->value = $value; - } -} - -class TestOfIdentity extends UnitTestCase { - - function testType() { - $string = new IdenticalExpectation("37"); - $this->assertTrue($string->test("37")); - $this->assertFalse($string->test(37)); - $this->assertFalse($string->test("38")); - } - - function _testNastyPhp5Bug() { - $this->assertFalse(new RecursiveNasty() != new RecursiveNasty()); - } - - function _testReallyHorribleRecursiveStructure() { - $hopeful = new IdenticalExpectation(new RecursiveNasty()); - $this->assertTrue($hopeful->test(new RecursiveNasty())); - } - - function testCanComparePrivateMembers() { - $expectFive = new IdenticalExpectation(new OpaqueContainer(5)); - $this->assertTrue($expectFive->test(new OpaqueContainer(5))); - $this->assertFalse($expectFive->test(new OpaqueContainer(6))); - } - - function testCanComparePrivateMembersOfObjectsInArrays() { - $expectFive = new IdenticalExpectation(array(new OpaqueContainer(5))); - $this->assertTrue($expectFive->test(array(new OpaqueContainer(5)))); - $this->assertFalse($expectFive->test(array(new OpaqueContainer(6)))); - } - - function testCanComparePrivateMembersOfObjectsWherePrivateMemberOfBaseClassIsObscured() { - $expectFive = new IdenticalExpectation(array(new DerivedOpaqueContainer(1,2))); - $this->assertTrue($expectFive->test(array(new DerivedOpaqueContainer(1,2)))); - $this->assertFalse($expectFive->test(array(new DerivedOpaqueContainer(0,2)))); - $this->assertFalse($expectFive->test(array(new DerivedOpaqueContainer(0,9)))); - $this->assertFalse($expectFive->test(array(new DerivedOpaqueContainer(1,0)))); - } -} - -class TransparentContainer { - public $value; - - public function __construct($value) { - $this->value = $value; - } -} - -class TestOfMemberComparison extends UnitTestCase { - - function testMemberExpectationCanMatchPublicMember() { - $expect_five = new MemberExpectation('value', 5); - $this->assertTrue($expect_five->test(new TransparentContainer(5))); - $this->assertFalse($expect_five->test(new TransparentContainer(8))); - } - - function testMemberExpectationCanMatchPrivateMember() { - $expect_five = new MemberExpectation('value', 5); - $this->assertTrue($expect_five->test(new OpaqueContainer(5))); - $this->assertFalse($expect_five->test(new OpaqueContainer(8))); - } - - function testMemberExpectationCanMatchPrivateMemberObscuredByDerivedClass() { - $expect_five = new MemberExpectation('value', 5); - $this->assertTrue($expect_five->test(new DerivedOpaqueContainer(5,8))); - $this->assertTrue($expect_five->test(new DerivedOpaqueContainer(5,5))); - $this->assertFalse($expect_five->test(new DerivedOpaqueContainer(8,8))); - $this->assertFalse($expect_five->test(new DerivedOpaqueContainer(8,5))); - } - -} - -class DummyReferencedObject{} - -class TestOfReference extends UnitTestCase { - - function testReference() { - $foo = "foo"; - $ref = &$foo; - $not_ref = $foo; - $bar = "bar"; - - $expect = new ReferenceExpectation($foo); - $this->assertTrue($expect->test($ref)); - $this->assertFalse($expect->test($not_ref)); - $this->assertFalse($expect->test($bar)); - } -} - -class TestOfNonIdentity extends UnitTestCase { - - function testType() { - $string = new NotIdenticalExpectation("37"); - $this->assertTrue($string->test("38")); - $this->assertTrue($string->test(37)); - $this->assertFalse($string->test("37")); - } -} - -class TestOfPatterns extends UnitTestCase { - - function testWanted() { - $pattern = new PatternExpectation('/hello/i'); - $this->assertTrue($pattern->test("Hello world")); - $this->assertFalse($pattern->test("Goodbye world")); - } - - function testUnwanted() { - $pattern = new NoPatternExpectation('/hello/i'); - $this->assertFalse($pattern->test("Hello world")); - $this->assertTrue($pattern->test("Goodbye world")); - } -} - -class ExpectedMethodTarget { - function hasThisMethod() {} -} - -class TestOfMethodExistence extends UnitTestCase { - - function testHasMethod() { - $instance = new ExpectedMethodTarget(); - $expectation = new MethodExistsExpectation('hasThisMethod'); - $this->assertTrue($expectation->test($instance)); - $expectation = new MethodExistsExpectation('doesNotHaveThisMethod'); - $this->assertFalse($expectation->test($instance)); - } -} - -class TestOfIsA extends UnitTestCase { - - function testString() { - $expectation = new IsAExpectation('string'); - $this->assertTrue($expectation->test('Hello')); - $this->assertFalse($expectation->test(5)); - } - - function testBoolean() { - $expectation = new IsAExpectation('boolean'); - $this->assertTrue($expectation->test(true)); - $this->assertFalse($expectation->test(1)); - } - - function testBool() { - $expectation = new IsAExpectation('bool'); - $this->assertTrue($expectation->test(true)); - $this->assertFalse($expectation->test(1)); - } - - function testDouble() { - $expectation = new IsAExpectation('double'); - $this->assertTrue($expectation->test(5.0)); - $this->assertFalse($expectation->test(5)); - } - - function testFloat() { - $expectation = new IsAExpectation('float'); - $this->assertTrue($expectation->test(5.0)); - $this->assertFalse($expectation->test(5)); - } - - function testReal() { - $expectation = new IsAExpectation('real'); - $this->assertTrue($expectation->test(5.0)); - $this->assertFalse($expectation->test(5)); - } - - function testInteger() { - $expectation = new IsAExpectation('integer'); - $this->assertTrue($expectation->test(5)); - $this->assertFalse($expectation->test(5.0)); - } - - function testInt() { - $expectation = new IsAExpectation('int'); - $this->assertTrue($expectation->test(5)); - $this->assertFalse($expectation->test(5.0)); - } - - function testScalar() { - $expectation = new IsAExpectation('scalar'); - $this->assertTrue($expectation->test(5)); - $this->assertFalse($expectation->test(array(5))); - } - - function testNumeric() { - $expectation = new IsAExpectation('numeric'); - $this->assertTrue($expectation->test(5)); - $this->assertFalse($expectation->test('string')); - } - - function testNull() { - $expectation = new IsAExpectation('null'); - $this->assertTrue($expectation->test(null)); - $this->assertFalse($expectation->test('string')); - } -} - -class TestOfNotA extends UnitTestCase { - - function testString() { - $expectation = new NotAExpectation('string'); - $this->assertFalse($expectation->test('Hello')); - $this->assertTrue($expectation->test(5)); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/form_test.php b/3rdparty/simpletest/test/form_test.php deleted file mode 100644 index 70a18f2b3a0a3abe7cfccb6c4475f0bc6fbb3b08..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/form_test.php +++ /dev/null @@ -1,344 +0,0 @@ -returns('getUrl', new SimpleUrl($url)); - $page->returns('expandUrl', new SimpleUrl($url)); - return $page; - } - - function testFormAttributes() { - $tag = new SimpleFormTag(array('method' => 'GET', 'action' => 'here.php', 'id' => '33')); - $form = new SimpleForm($tag, $this->page('http://host/a/index.html')); - $this->assertEqual($form->getMethod(), 'get'); - $this->assertIdentical($form->getId(), '33'); - $this->assertNull($form->getValue(new SimpleByName('a'))); - } - - function testAction() { - $page = new MockSimplePage(); - $page->expectOnce('expandUrl', array(new SimpleUrl('here.php'))); - $page->setReturnValue('expandUrl', new SimpleUrl('http://host/here.php')); - $tag = new SimpleFormTag(array('method' => 'GET', 'action' => 'here.php')); - $form = new SimpleForm($tag, $page); - $this->assertEqual($form->getAction(), new SimpleUrl('http://host/here.php')); - } - - function testEmptyAction() { - $tag = new SimpleFormTag(array('method' => 'GET', 'action' => '', 'id' => '33')); - $form = new SimpleForm($tag, $this->page('http://host/a/index.html')); - $this->assertEqual( - $form->getAction(), - new SimpleUrl('http://host/a/index.html')); - } - - function testMissingAction() { - $tag = new SimpleFormTag(array('method' => 'GET')); - $form = new SimpleForm($tag, $this->page('http://host/a/index.html')); - $this->assertEqual( - $form->getAction(), - new SimpleUrl('http://host/a/index.html')); - } - - function testRootAction() { - $page = new MockSimplePage(); - $page->expectOnce('expandUrl', array(new SimpleUrl('/'))); - $page->setReturnValue('expandUrl', new SimpleUrl('http://host/')); - $tag = new SimpleFormTag(array('method' => 'GET', 'action' => '/')); - $form = new SimpleForm($tag, $page); - $this->assertEqual( - $form->getAction(), - new SimpleUrl('http://host/')); - } - - function testDefaultFrameTargetOnForm() { - $page = new MockSimplePage(); - $page->expectOnce('expandUrl', array(new SimpleUrl('here.php'))); - $page->setReturnValue('expandUrl', new SimpleUrl('http://host/here.php')); - $tag = new SimpleFormTag(array('method' => 'GET', 'action' => 'here.php')); - $form = new SimpleForm($tag, $page); - $form->setDefaultTarget('frame'); - $expected = new SimpleUrl('http://host/here.php'); - $expected->setTarget('frame'); - $this->assertEqual($form->getAction(), $expected); - } - - function testTextWidget() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleTextTag( - array('name' => 'me', 'type' => 'text', 'value' => 'Myself'))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'Myself'); - $this->assertTrue($form->setField(new SimpleByName('me'), 'Not me')); - $this->assertFalse($form->setField(new SimpleByName('not_present'), 'Not me')); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'Not me'); - $this->assertNull($form->getValue(new SimpleByName('not_present'))); - } - - function testTextWidgetById() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleTextTag( - array('name' => 'me', 'type' => 'text', 'value' => 'Myself', 'id' => 50))); - $this->assertIdentical($form->getValue(new SimpleById(50)), 'Myself'); - $this->assertTrue($form->setField(new SimpleById(50), 'Not me')); - $this->assertIdentical($form->getValue(new SimpleById(50)), 'Not me'); - } - - function testTextWidgetByLabel() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $widget = new SimpleTextTag(array('name' => 'me', 'type' => 'text', 'value' => 'a')); - $form->addWidget($widget); - $widget->setLabel('thing'); - $this->assertIdentical($form->getValue(new SimpleByLabel('thing')), 'a'); - $this->assertTrue($form->setField(new SimpleByLabel('thing'), 'b')); - $this->assertIdentical($form->getValue(new SimpleByLabel('thing')), 'b'); - } - - function testSubmitEmpty() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $this->assertIdentical($form->submit(), new SimpleGetEncoding()); - } - - function testSubmitButton() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('http://host')); - $form->addWidget(new SimpleSubmitTag( - array('type' => 'submit', 'name' => 'go', 'value' => 'Go!', 'id' => '9'))); - $this->assertTrue($form->hasSubmit(new SimpleByName('go'))); - $this->assertEqual($form->getValue(new SimpleByName('go')), 'Go!'); - $this->assertEqual($form->getValue(new SimpleById(9)), 'Go!'); - $this->assertEqual( - $form->submitButton(new SimpleByName('go')), - new SimpleGetEncoding(array('go' => 'Go!'))); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Go!')), - new SimpleGetEncoding(array('go' => 'Go!'))); - $this->assertEqual( - $form->submitButton(new SimpleById(9)), - new SimpleGetEncoding(array('go' => 'Go!'))); - } - - function testSubmitWithAdditionalParameters() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('http://host')); - $form->addWidget(new SimpleSubmitTag( - array('type' => 'submit', 'name' => 'go', 'value' => 'Go!'))); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Go!'), array('a' => 'A')), - new SimpleGetEncoding(array('go' => 'Go!', 'a' => 'A'))); - } - - function testSubmitButtonWithLabelOfSubmit() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('http://host')); - $form->addWidget(new SimpleSubmitTag( - array('type' => 'submit', 'name' => 'test', 'value' => 'Submit'))); - $this->assertEqual( - $form->submitButton(new SimpleByName('test')), - new SimpleGetEncoding(array('test' => 'Submit'))); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Submit')), - new SimpleGetEncoding(array('test' => 'Submit'))); - } - - function testSubmitButtonWithWhitespacePaddedLabelOfSubmit() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('http://host')); - $form->addWidget(new SimpleSubmitTag( - array('type' => 'submit', 'name' => 'test', 'value' => ' Submit '))); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Submit')), - new SimpleGetEncoding(array('test' => ' Submit '))); - } - - function testImageSubmitButton() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleImageSubmitTag(array( - 'type' => 'image', - 'src' => 'source.jpg', - 'name' => 'go', - 'alt' => 'Go!', - 'id' => '9'))); - $this->assertTrue($form->hasImage(new SimpleByLabel('Go!'))); - $this->assertEqual( - $form->submitImage(new SimpleByLabel('Go!'), 100, 101), - new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101))); - $this->assertTrue($form->hasImage(new SimpleByName('go'))); - $this->assertEqual( - $form->submitImage(new SimpleByName('go'), 100, 101), - new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101))); - $this->assertTrue($form->hasImage(new SimpleById(9))); - $this->assertEqual( - $form->submitImage(new SimpleById(9), 100, 101), - new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101))); - } - - function testImageSubmitButtonWithAdditionalData() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleImageSubmitTag(array( - 'type' => 'image', - 'src' => 'source.jpg', - 'name' => 'go', - 'alt' => 'Go!'))); - $this->assertEqual( - $form->submitImage(new SimpleByLabel('Go!'), 100, 101, array('a' => 'A')), - new SimpleGetEncoding(array('go.x' => 100, 'go.y' => 101, 'a' => 'A'))); - } - - function testButtonTag() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('http://host')); - $widget = new SimpleButtonTag( - array('type' => 'submit', 'name' => 'go', 'value' => 'Go', 'id' => '9')); - $widget->addContent('Go!'); - $form->addWidget($widget); - $this->assertTrue($form->hasSubmit(new SimpleByName('go'))); - $this->assertTrue($form->hasSubmit(new SimpleByLabel('Go!'))); - $this->assertEqual( - $form->submitButton(new SimpleByName('go')), - new SimpleGetEncoding(array('go' => 'Go'))); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Go!')), - new SimpleGetEncoding(array('go' => 'Go'))); - $this->assertEqual( - $form->submitButton(new SimpleById(9)), - new SimpleGetEncoding(array('go' => 'Go'))); - } - - function testMultipleFieldsWithSameNameSubmitted() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $input = new SimpleTextTag(array('name' => 'elements[]', 'value' => '1')); - $form->addWidget($input); - $input = new SimpleTextTag(array('name' => 'elements[]', 'value' => '2')); - $form->addWidget($input); - $form->setField(new SimpleByLabelOrName('elements[]'), '3', 1); - $form->setField(new SimpleByLabelOrName('elements[]'), '4', 2); - $submit = $form->submit(); - $requests = $submit->getAll(); - $this->assertEqual(count($requests), 2); - $this->assertIdentical($requests[0], new SimpleEncodedPair('elements[]', '3')); - $this->assertIdentical($requests[1], new SimpleEncodedPair('elements[]', '4')); - } - - function testSingleSelectFieldSubmitted() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $select = new SimpleSelectionTag(array('name' => 'a')); - $select->addTag(new SimpleOptionTag( - array('value' => 'aaa', 'selected' => ''))); - $form->addWidget($select); - $this->assertIdentical( - $form->submit(), - new SimpleGetEncoding(array('a' => 'aaa'))); - } - - function testSingleSelectFieldSubmittedWithPost() { - $form = new SimpleForm(new SimpleFormTag(array('method' => 'post')), $this->page('htp://host')); - $select = new SimpleSelectionTag(array('name' => 'a')); - $select->addTag(new SimpleOptionTag( - array('value' => 'aaa', 'selected' => ''))); - $form->addWidget($select); - $this->assertIdentical( - $form->submit(), - new SimplePostEncoding(array('a' => 'aaa'))); - } - - function testUnchecked() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleCheckboxTag( - array('name' => 'me', 'type' => 'checkbox'))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), false); - $this->assertTrue($form->setField(new SimpleByName('me'), 'on')); - $this->assertEqual($form->getValue(new SimpleByName('me')), 'on'); - $this->assertFalse($form->setField(new SimpleByName('me'), 'other')); - $this->assertEqual($form->getValue(new SimpleByName('me')), 'on'); - } - - function testChecked() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleCheckboxTag( - array('name' => 'me', 'value' => 'a', 'type' => 'checkbox', 'checked' => ''))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a'); - $this->assertTrue($form->setField(new SimpleByName('me'), 'a')); - $this->assertEqual($form->getValue(new SimpleByName('me')), 'a'); - $this->assertTrue($form->setField(new SimpleByName('me'), false)); - $this->assertEqual($form->getValue(new SimpleByName('me')), false); - } - - function testSingleUncheckedRadioButton() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'a', 'type' => 'radio'))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), false); - $this->assertTrue($form->setField(new SimpleByName('me'), 'a')); - $this->assertEqual($form->getValue(new SimpleByName('me')), 'a'); - } - - function testSingleCheckedRadioButton() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'a', 'type' => 'radio', 'checked' => ''))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a'); - $this->assertFalse($form->setField(new SimpleByName('me'), 'other')); - } - - function testUncheckedRadioButtons() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'a', 'type' => 'radio'))); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'b', 'type' => 'radio'))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), false); - $this->assertTrue($form->setField(new SimpleByName('me'), 'a')); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a'); - $this->assertTrue($form->setField(new SimpleByName('me'), 'b')); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'b'); - $this->assertFalse($form->setField(new SimpleByName('me'), 'c')); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'b'); - } - - function testCheckedRadioButtons() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'a', 'type' => 'radio'))); - $form->addWidget(new SimpleRadioButtonTag( - array('name' => 'me', 'value' => 'b', 'type' => 'radio', 'checked' => ''))); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'b'); - $this->assertTrue($form->setField(new SimpleByName('me'), 'a')); - $this->assertIdentical($form->getValue(new SimpleByName('me')), 'a'); - } - - function testMultipleFieldsWithSameKey() { - $form = new SimpleForm(new SimpleFormTag(array()), $this->page('htp://host')); - $form->addWidget(new SimpleCheckboxTag( - array('name' => 'a', 'type' => 'checkbox', 'value' => 'me'))); - $form->addWidget(new SimpleCheckboxTag( - array('name' => 'a', 'type' => 'checkbox', 'value' => 'you'))); - $this->assertIdentical($form->getValue(new SimpleByName('a')), false); - $this->assertTrue($form->setField(new SimpleByName('a'), 'me')); - $this->assertIdentical($form->getValue(new SimpleByName('a')), 'me'); - } - - function testRemoveGetParamsFromAction() { - Mock::generatePartial('SimplePage', 'MockPartialSimplePage', array('getUrl')); - $page = new MockPartialSimplePage(); - $page->returns('getUrl', new SimpleUrl('htp://host/')); - - # Keep GET params in "action", if the form has no widgets - $form = new SimpleForm(new SimpleFormTag(array('action'=>'?test=1')), $page); - $this->assertEqual($form->getAction()->asString(), 'htp://host/'); - - $form = new SimpleForm(new SimpleFormTag(array('action'=>'?test=1')), $page); - $form->addWidget(new SimpleTextTag(array('name' => 'me', 'type' => 'text', 'value' => 'a'))); - $this->assertEqual($form->getAction()->asString(), 'htp://host/'); - - $form = new SimpleForm(new SimpleFormTag(array('action'=>'')), $page); - $this->assertEqual($form->getAction()->asString(), 'htp://host/'); - - $form = new SimpleForm(new SimpleFormTag(array('action'=>'?test=1', 'method'=>'post')), $page); - $this->assertEqual($form->getAction()->asString(), 'htp://host/?test=1'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/frames_test.php b/3rdparty/simpletest/test/frames_test.php deleted file mode 100644 index 29309700e3115ff1b30ac08ec9f522466f9c96ee..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/frames_test.php +++ /dev/null @@ -1,549 +0,0 @@ -setReturnValue('getTitle', 'This page'); - $frameset = new SimpleFrameset($page); - $this->assertEqual($frameset->getTitle(), 'This page'); - } - - function TestHeadersReadFromFramesetByDefault() { - $page = new MockSimplePage(); - $page->setReturnValue('getHeaders', 'Header: content'); - $page->setReturnValue('getMimeType', 'text/xml'); - $page->setReturnValue('getResponseCode', 401); - $page->setReturnValue('getTransportError', 'Could not parse headers'); - $page->setReturnValue('getAuthentication', 'Basic'); - $page->setReturnValue('getRealm', 'Safe place'); - - $frameset = new SimpleFrameset($page); - - $this->assertIdentical($frameset->getHeaders(), 'Header: content'); - $this->assertIdentical($frameset->getMimeType(), 'text/xml'); - $this->assertIdentical($frameset->getResponseCode(), 401); - $this->assertIdentical($frameset->getTransportError(), 'Could not parse headers'); - $this->assertIdentical($frameset->getAuthentication(), 'Basic'); - $this->assertIdentical($frameset->getRealm(), 'Safe place'); - } - - function testEmptyFramesetHasNoContent() { - $page = new MockSimplePage(); - $page->setReturnValue('getRaw', 'This content'); - $frameset = new SimpleFrameset($page); - $this->assertEqual($frameset->getRaw(), ''); - } - - function testRawContentIsFromOnlyFrame() { - $page = new MockSimplePage(); - $page->expectNever('getRaw'); - - $frame = new MockSimplePage(); - $frame->setReturnValue('getRaw', 'Stuff'); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame); - $this->assertEqual($frameset->getRaw(), 'Stuff'); - } - - function testRawContentIsFromAllFrames() { - $page = new MockSimplePage(); - $page->expectNever('getRaw'); - - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getRaw', 'Stuff1'); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getRaw', 'Stuff2'); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - $this->assertEqual($frameset->getRaw(), 'Stuff1Stuff2'); - } - - function testTextContentIsFromOnlyFrame() { - $page = new MockSimplePage(); - $page->expectNever('getText'); - - $frame = new MockSimplePage(); - $frame->setReturnValue('getText', 'Stuff'); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame); - $this->assertEqual($frameset->getText(), 'Stuff'); - } - - function testTextContentIsFromAllFrames() { - $page = new MockSimplePage(); - $page->expectNever('getText'); - - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getText', 'Stuff1'); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getText', 'Stuff2'); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - $this->assertEqual($frameset->getText(), 'Stuff1 Stuff2'); - } - - function testFieldFoundIsFirstInFramelist() { - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getField', null); - $frame1->expectOnce('getField', array(new SimpleByName('a'))); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getField', 'A'); - $frame2->expectOnce('getField', array(new SimpleByName('a'))); - - $frame3 = new MockSimplePage(); - $frame3->expectNever('getField'); - - $page = new MockSimplePage(); - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - $frameset->addFrame($frame3); - $this->assertIdentical($frameset->getField(new SimpleByName('a')), 'A'); - } - - function testFrameReplacementByIndex() { - $page = new MockSimplePage(); - $page->expectNever('getRaw'); - - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getRaw', 'Stuff1'); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getRaw', 'Stuff2'); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->setFrame(array(1), $frame2); - $this->assertEqual($frameset->getRaw(), 'Stuff2'); - } - - function testFrameReplacementByName() { - $page = new MockSimplePage(); - $page->expectNever('getRaw'); - - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getRaw', 'Stuff1'); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getRaw', 'Stuff2'); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1, 'a'); - $frameset->setFrame(array('a'), $frame2); - $this->assertEqual($frameset->getRaw(), 'Stuff2'); - } -} - -class TestOfFrameNavigation extends UnitTestCase { - - function testStartsWithoutFrameFocus() { - $page = new MockSimplePage(); - $frameset = new SimpleFrameset($page); - $frameset->addFrame(new MockSimplePage()); - $this->assertFalse($frameset->getFrameFocus()); - } - - function testCanFocusOnSingleFrame() { - $page = new MockSimplePage(); - $page->expectNever('getRaw'); - - $frame = new MockSimplePage(); - $frame->setReturnValue('getFrameFocus', array()); - $frame->setReturnValue('getRaw', 'Stuff'); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame); - - $this->assertFalse($frameset->setFrameFocusByIndex(0)); - $this->assertTrue($frameset->setFrameFocusByIndex(1)); - $this->assertEqual($frameset->getRaw(), 'Stuff'); - $this->assertFalse($frameset->setFrameFocusByIndex(2)); - $this->assertIdentical($frameset->getFrameFocus(), array(1)); - } - - function testContentComesFromFrameInFocus() { - $page = new MockSimplePage(); - - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getRaw', 'Stuff1'); - $frame1->setReturnValue('getFrameFocus', array()); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getRaw', 'Stuff2'); - $frame2->setReturnValue('getFrameFocus', array()); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - - $this->assertTrue($frameset->setFrameFocusByIndex(1)); - $this->assertEqual($frameset->getFrameFocus(), array(1)); - $this->assertEqual($frameset->getRaw(), 'Stuff1'); - - $this->assertTrue($frameset->setFrameFocusByIndex(2)); - $this->assertEqual($frameset->getFrameFocus(), array(2)); - $this->assertEqual($frameset->getRaw(), 'Stuff2'); - - $this->assertFalse($frameset->setFrameFocusByIndex(3)); - $this->assertEqual($frameset->getFrameFocus(), array(2)); - - $frameset->clearFrameFocus(); - $this->assertEqual($frameset->getRaw(), 'Stuff1Stuff2'); - } - - function testCanFocusByName() { - $page = new MockSimplePage(); - - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getRaw', 'Stuff1'); - $frame1->setReturnValue('getFrameFocus', array()); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getRaw', 'Stuff2'); - $frame2->setReturnValue('getFrameFocus', array()); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1, 'A'); - $frameset->addFrame($frame2, 'B'); - - $this->assertTrue($frameset->setFrameFocus('A')); - $this->assertEqual($frameset->getFrameFocus(), array('A')); - $this->assertEqual($frameset->getRaw(), 'Stuff1'); - - $this->assertTrue($frameset->setFrameFocusByIndex(2)); - $this->assertEqual($frameset->getFrameFocus(), array('B')); - $this->assertEqual($frameset->getRaw(), 'Stuff2'); - - $this->assertFalse($frameset->setFrameFocus('z')); - - $frameset->clearFrameFocus(); - $this->assertEqual($frameset->getRaw(), 'Stuff1Stuff2'); - } -} - -class TestOfFramesetPageInterface extends UnitTestCase { - private $page_interface; - private $frameset_interface; - - function __construct() { - parent::__construct(); - $this->page_interface = $this->getPageMethods(); - $this->frameset_interface = $this->getFramesetMethods(); - } - - function assertListInAnyOrder($list, $expected) { - sort($list); - sort($expected); - $this->assertEqual($list, $expected); - } - - private function getPageMethods() { - $methods = array(); - foreach (get_class_methods('SimplePage') as $method) { - if (strtolower($method) == strtolower('SimplePage')) { - continue; - } - if (strtolower($method) == strtolower('getFrameset')) { - continue; - } - if (strncmp($method, '_', 1) == 0) { - continue; - } - if (in_array($method, array('setTitle', 'setBase', 'setForms', 'normalise', 'setFrames', 'addLink'))) { - continue; - } - $methods[] = $method; - } - return $methods; - } - - private function getFramesetMethods() { - $methods = array(); - foreach (get_class_methods('SimpleFrameset') as $method) { - if (strtolower($method) == strtolower('SimpleFrameset')) { - continue; - } - if (strncmp($method, '_', 1) == 0) { - continue; - } - if (strncmp($method, 'add', 3) == 0) { - continue; - } - $methods[] = $method; - } - return $methods; - } - - function testFramsetHasPageInterface() { - $difference = array(); - foreach ($this->page_interface as $method) { - if (! in_array($method, $this->frameset_interface)) { - $this->fail("No [$method] in Frameset class"); - return; - } - } - $this->pass('Frameset covers Page interface'); - } - - function testHeadersReadFromFrameIfInFocus() { - $frame = new MockSimplePage(); - $frame->setReturnValue('getUrl', new SimpleUrl('http://localhost/stuff')); - - $frame->setReturnValue('getRequest', 'POST stuff'); - $frame->setReturnValue('getMethod', 'POST'); - $frame->setReturnValue('getRequestData', array('a' => 'A')); - $frame->setReturnValue('getHeaders', 'Header: content'); - $frame->setReturnValue('getMimeType', 'text/xml'); - $frame->setReturnValue('getResponseCode', 401); - $frame->setReturnValue('getTransportError', 'Could not parse headers'); - $frame->setReturnValue('getAuthentication', 'Basic'); - $frame->setReturnValue('getRealm', 'Safe place'); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame); - $frameset->setFrameFocusByIndex(1); - - $url = new SimpleUrl('http://localhost/stuff'); - $url->setTarget(1); - $this->assertIdentical($frameset->getUrl(), $url); - - $this->assertIdentical($frameset->getRequest(), 'POST stuff'); - $this->assertIdentical($frameset->getMethod(), 'POST'); - $this->assertIdentical($frameset->getRequestData(), array('a' => 'A')); - $this->assertIdentical($frameset->getHeaders(), 'Header: content'); - $this->assertIdentical($frameset->getMimeType(), 'text/xml'); - $this->assertIdentical($frameset->getResponseCode(), 401); - $this->assertIdentical($frameset->getTransportError(), 'Could not parse headers'); - $this->assertIdentical($frameset->getAuthentication(), 'Basic'); - $this->assertIdentical($frameset->getRealm(), 'Safe place'); - } - - function testUrlsComeFromBothFrames() { - $page = new MockSimplePage(); - $page->expectNever('getUrls'); - - $frame1 = new MockSimplePage(); - $frame1->setReturnValue( - 'getUrls', - array('http://www.lastcraft.com/', 'http://myserver/')); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue( - 'getUrls', - array('http://www.lastcraft.com/', 'http://test/')); - - $frameset = new SimpleFrameset($page); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - $this->assertListInAnyOrder( - $frameset->getUrls(), - array('http://www.lastcraft.com/', 'http://myserver/', 'http://test/')); - } - - function testLabelledUrlsComeFromBothFrames() { - $frame1 = new MockSimplePage(); - $frame1->setReturnValue( - 'getUrlsByLabel', - array(new SimpleUrl('goodbye.php')), - array('a')); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue( - 'getUrlsByLabel', - array(new SimpleUrl('hello.php')), - array('a')); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2, 'Two'); - - $expected1 = new SimpleUrl('goodbye.php'); - $expected1->setTarget(1); - $expected2 = new SimpleUrl('hello.php'); - $expected2->setTarget('Two'); - $this->assertEqual( - $frameset->getUrlsByLabel('a'), - array($expected1, $expected2)); - } - - function testUrlByIdComesFromFirstFrameToRespond() { - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getUrlById', new SimpleUrl('four.php'), array(4)); - $frame1->setReturnValue('getUrlById', false, array(5)); - - $frame2 = new MockSimplePage(); - $frame2->setReturnValue('getUrlById', false, array(4)); - $frame2->setReturnValue('getUrlById', new SimpleUrl('five.php'), array(5)); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1); - $frameset->addFrame($frame2); - - $four = new SimpleUrl('four.php'); - $four->setTarget(1); - $this->assertEqual($frameset->getUrlById(4), $four); - $five = new SimpleUrl('five.php'); - $five->setTarget(2); - $this->assertEqual($frameset->getUrlById(5), $five); - } - - function testReadUrlsFromFrameInFocus() { - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getUrls', array('a')); - $frame1->setReturnValue('getUrlsByLabel', array(new SimpleUrl('l'))); - $frame1->setReturnValue('getUrlById', new SimpleUrl('i')); - - $frame2 = new MockSimplePage(); - $frame2->expectNever('getUrls'); - $frame2->expectNever('getUrlsByLabel'); - $frame2->expectNever('getUrlById'); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1, 'A'); - $frameset->addFrame($frame2, 'B'); - $frameset->setFrameFocus('A'); - - $this->assertIdentical($frameset->getUrls(), array('a')); - $expected = new SimpleUrl('l'); - $expected->setTarget('A'); - $this->assertIdentical($frameset->getUrlsByLabel('label'), array($expected)); - $expected = new SimpleUrl('i'); - $expected->setTarget('A'); - $this->assertIdentical($frameset->getUrlById(99), $expected); - } - - function testReadFrameTaggedUrlsFromFrameInFocus() { - $frame = new MockSimplePage(); - - $by_label = new SimpleUrl('l'); - $by_label->setTarget('L'); - $frame->setReturnValue('getUrlsByLabel', array($by_label)); - - $by_id = new SimpleUrl('i'); - $by_id->setTarget('I'); - $frame->setReturnValue('getUrlById', $by_id); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame, 'A'); - $frameset->setFrameFocus('A'); - - $this->assertIdentical($frameset->getUrlsByLabel('label'), array($by_label)); - $this->assertIdentical($frameset->getUrlById(99), $by_id); - } - - function testFindingFormsById() { - $frame = new MockSimplePage(); - $form = new MockSimpleForm(); - $frame->returns('getFormById', $form, array('a')); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame(new MockSimplePage(), 'A'); - $frameset->addFrame($frame, 'B'); - $this->assertSame($frameset->getFormById('a'), $form); - - $frameset->setFrameFocus('A'); - $this->assertNull($frameset->getFormById('a')); - - $frameset->setFrameFocus('B'); - $this->assertSame($frameset->getFormById('a'), $form); - } - - function testFindingFormsBySubmit() { - $frame = new MockSimplePage(); - $form = new MockSimpleForm(); - $frame->returns( - 'getFormBySubmit', - $form, - array(new SimpleByLabel('a'))); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame(new MockSimplePage(), 'A'); - $frameset->addFrame($frame, 'B'); - $this->assertSame($frameset->getFormBySubmit(new SimpleByLabel('a')), $form); - - $frameset->setFrameFocus('A'); - $this->assertNull($frameset->getFormBySubmit(new SimpleByLabel('a'))); - - $frameset->setFrameFocus('B'); - $this->assertSame($frameset->getFormBySubmit(new SimpleByLabel('a')), $form); - } - - function testFindingFormsByImage() { - $frame = new MockSimplePage(); - $form = new MockSimpleForm(); - $frame->returns( - 'getFormByImage', - $form, - array(new SimpleByLabel('a'))); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame(new MockSimplePage(), 'A'); - $frameset->addFrame($frame, 'B'); - $this->assertSame($frameset->getFormByImage(new SimpleByLabel('a')), $form); - - $frameset->setFrameFocus('A'); - $this->assertNull($frameset->getFormByImage(new SimpleByLabel('a'))); - - $frameset->setFrameFocus('B'); - $this->assertSame($frameset->getFormByImage(new SimpleByLabel('a')), $form); - } - - function testSettingAllFrameFieldsWhenNoFrameFocus() { - $frame1 = new MockSimplePage(); - $frame1->expectOnce('setField', array(new SimpleById(22), 'A')); - - $frame2 = new MockSimplePage(); - $frame2->expectOnce('setField', array(new SimpleById(22), 'A')); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1, 'A'); - $frameset->addFrame($frame2, 'B'); - $frameset->setField(new SimpleById(22), 'A'); - } - - function testOnlySettingFieldFromFocusedFrame() { - $frame1 = new MockSimplePage(); - $frame1->expectOnce('setField', array(new SimpleByLabelOrName('a'), 'A')); - - $frame2 = new MockSimplePage(); - $frame2->expectNever('setField'); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1, 'A'); - $frameset->addFrame($frame2, 'B'); - $frameset->setFrameFocus('A'); - $frameset->setField(new SimpleByLabelOrName('a'), 'A'); - } - - function testOnlyGettingFieldFromFocusedFrame() { - $frame1 = new MockSimplePage(); - $frame1->setReturnValue('getField', 'f', array(new SimpleByName('a'))); - - $frame2 = new MockSimplePage(); - $frame2->expectNever('getField'); - - $frameset = new SimpleFrameset(new MockSimplePage()); - $frameset->addFrame($frame1, 'A'); - $frameset->addFrame($frame2, 'B'); - $frameset->setFrameFocus('A'); - $this->assertIdentical($frameset->getField(new SimpleByName('a')), 'f'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/http_test.php b/3rdparty/simpletest/test/http_test.php deleted file mode 100644 index bd3fdd0d02841897f06473957802e2212637ddc0..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/http_test.php +++ /dev/null @@ -1,492 +0,0 @@ -expectAt(0, 'write', array("GET /here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: a.valid.host\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - $route = new PartialSimpleRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct(new SimpleUrl('http://a.valid.host/here.html')); - $this->assertSame($route->createConnection('GET', 15), $socket); - } - - function testDefaultPostRequest() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("POST /here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: a.valid.host\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - $route = new PartialSimpleRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct(new SimpleUrl('http://a.valid.host/here.html')); - - $route->createConnection('POST', 15); - } - - function testDefaultDeleteRequest() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("DELETE /here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: a.valid.host\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - $route = new PartialSimpleRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct(new SimpleUrl('http://a.valid.host/here.html')); - $this->assertSame($route->createConnection('DELETE', 15), $socket); - } - - function testDefaultHeadRequest() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("HEAD /here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: a.valid.host\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - $route = new PartialSimpleRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct(new SimpleUrl('http://a.valid.host/here.html')); - $this->assertSame($route->createConnection('HEAD', 15), $socket); - } - - function testGetWithPort() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("GET /here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: a.valid.host:81\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = new PartialSimpleRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct(new SimpleUrl('http://a.valid.host:81/here.html')); - - $route->createConnection('GET', 15); - } - - function testGetWithParameters() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("GET /here.html?a=1&b=2 HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: a.valid.host\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = new PartialSimpleRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct(new SimpleUrl('http://a.valid.host/here.html?a=1&b=2')); - - $route->createConnection('GET', 15); - } -} - -class TestOfProxyRoute extends UnitTestCase { - - function testDefaultGet() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("GET http://a.valid.host/here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: my-proxy:8080\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = new PartialSimpleProxyRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct( - new SimpleUrl('http://a.valid.host/here.html'), - new SimpleUrl('http://my-proxy')); - $route->createConnection('GET', 15); - } - - function testDefaultPost() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("POST http://a.valid.host/here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: my-proxy:8080\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = new PartialSimpleProxyRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct( - new SimpleUrl('http://a.valid.host/here.html'), - new SimpleUrl('http://my-proxy')); - $route->createConnection('POST', 15); - } - - function testGetWithPort() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("GET http://a.valid.host:81/here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: my-proxy:8081\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = new PartialSimpleProxyRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct( - new SimpleUrl('http://a.valid.host:81/here.html'), - new SimpleUrl('http://my-proxy:8081')); - $route->createConnection('GET', 15); - } - - function testGetWithParameters() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("GET http://a.valid.host/here.html?a=1&b=2 HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: my-proxy:8080\r\n")); - $socket->expectAt(2, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 3); - - $route = new PartialSimpleProxyRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct( - new SimpleUrl('http://a.valid.host/here.html?a=1&b=2'), - new SimpleUrl('http://my-proxy')); - $route->createConnection('GET', 15); - } - - function testGetWithAuthentication() { - $encoded = base64_encode('Me:Secret'); - - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("GET http://a.valid.host/here.html HTTP/1.0\r\n")); - $socket->expectAt(1, 'write', array("Host: my-proxy:8080\r\n")); - $socket->expectAt(2, 'write', array("Proxy-Authorization: Basic $encoded\r\n")); - $socket->expectAt(3, 'write', array("Connection: close\r\n")); - $socket->expectCallCount('write', 4); - - $route = new PartialSimpleProxyRoute(); - $route->setReturnReference('createSocket', $socket); - $route->__construct( - new SimpleUrl('http://a.valid.host/here.html'), - new SimpleUrl('http://my-proxy'), - 'Me', - 'Secret'); - $route->createConnection('GET', 15); - } -} - -class TestOfHttpRequest extends UnitTestCase { - - function testReadingBadConnection() { - $socket = new MockSimpleSocket(); - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $request = new SimpleHttpRequest($route, new SimpleGetEncoding()); - $reponse = $request->fetch(15); - $this->assertTrue($reponse->isError()); - } - - function testReadingGoodConnection() { - $socket = new MockSimpleSocket(); - $socket->expectOnce('write', array("\r\n")); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $route->expect('createConnection', array('GET', 15)); - - $request = new SimpleHttpRequest($route, new SimpleGetEncoding()); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } - - function testWritingAdditionalHeaders() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("My: stuff\r\n")); - $socket->expectAt(1, 'write', array("\r\n")); - $socket->expectCallCount('write', 2); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - - $request = new SimpleHttpRequest($route, new SimpleGetEncoding()); - $request->addHeaderLine('My: stuff'); - $request->fetch(15); - } - - function testCookieWriting() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Cookie: a=A\r\n")); - $socket->expectAt(1, 'write', array("\r\n")); - $socket->expectCallCount('write', 2); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A'); - - $request = new SimpleHttpRequest($route, new SimpleGetEncoding()); - $request->readCookiesFromJar($jar, new SimpleUrl('/')); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } - - function testMultipleCookieWriting() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Cookie: a=A;b=B\r\n")); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A'); - $jar->setCookie('b', 'B'); - - $request = new SimpleHttpRequest($route, new SimpleGetEncoding()); - $request->readCookiesFromJar($jar, new SimpleUrl('/')); - $request->fetch(15); - } - - function testReadingDeleteConnection() { - $socket = new MockSimpleSocket(); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $route->expect('createConnection', array('DELETE', 15)); - - $request = new SimpleHttpRequest($route, new SimpleDeleteEncoding()); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } -} - -class TestOfHttpPostRequest extends UnitTestCase { - - function testReadingBadConnectionCausesErrorBecauseOfDeadSocket() { - $socket = new MockSimpleSocket(); - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $request = new SimpleHttpRequest($route, new SimplePostEncoding()); - $reponse = $request->fetch(15); - $this->assertTrue($reponse->isError()); - } - - function testReadingGoodConnection() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Content-Length: 0\r\n")); - $socket->expectAt(1, 'write', array("Content-Type: application/x-www-form-urlencoded\r\n")); - $socket->expectAt(2, 'write', array("\r\n")); - $socket->expectAt(3, 'write', array("")); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $route->expect('createConnection', array('POST', 15)); - - $request = new SimpleHttpRequest($route, new SimplePostEncoding()); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } - - function testContentHeadersCalculatedWithUrlEncodedParams() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Content-Length: 3\r\n")); - $socket->expectAt(1, 'write', array("Content-Type: application/x-www-form-urlencoded\r\n")); - $socket->expectAt(2, 'write', array("\r\n")); - $socket->expectAt(3, 'write', array("a=A")); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $route->expect('createConnection', array('POST', 15)); - - $request = new SimpleHttpRequest( - $route, - new SimplePostEncoding(array('a' => 'A'))); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } - - function testContentHeadersCalculatedWithRawEntityBody() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Content-Length: 8\r\n")); - $socket->expectAt(1, 'write', array("Content-Type: text/plain\r\n")); - $socket->expectAt(2, 'write', array("\r\n")); - $socket->expectAt(3, 'write', array("raw body")); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $route->expect('createConnection', array('POST', 15)); - - $request = new SimpleHttpRequest( - $route, - new SimplePostEncoding('raw body')); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } - - function testContentHeadersCalculatedWithXmlEntityBody() { - $socket = new MockSimpleSocket(); - $socket->expectAt(0, 'write', array("Content-Length: 27\r\n")); - $socket->expectAt(1, 'write', array("Content-Type: text/xml\r\n")); - $socket->expectAt(2, 'write', array("\r\n")); - $socket->expectAt(3, 'write', array("onetwo")); - - $route = new MockSimpleRoute(); - $route->setReturnReference('createConnection', $socket); - $route->expect('createConnection', array('POST', 15)); - - $request = new SimpleHttpRequest( - $route, - new SimplePostEncoding('onetwo', 'text/xml')); - $this->assertIsA($request->fetch(15), 'SimpleHttpResponse'); - } -} - -class TestOfHttpHeaders extends UnitTestCase { - - function testParseBasicHeaders() { - $headers = new SimpleHttpHeaders( - "HTTP/1.1 200 OK\r\n" . - "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n" . - "Content-Type: text/plain\r\n" . - "Server: Apache/1.3.24 (Win32) PHP/4.2.3\r\n" . - "Connection: close"); - $this->assertIdentical($headers->getHttpVersion(), "1.1"); - $this->assertIdentical($headers->getResponseCode(), 200); - $this->assertEqual($headers->getMimeType(), "text/plain"); - } - - function testNonStandardResponseHeader() { - $headers = new SimpleHttpHeaders( - "HTTP/1.1 302 (HTTP-Version SP Status-Code CRLF)\r\n" . - "Connection: close"); - $this->assertIdentical($headers->getResponseCode(), 302); - } - - function testCanParseMultipleCookies() { - $jar = new MockSimpleCookieJar(); - $jar->expectAt(0, 'setCookie', array('a', 'aaa', 'host', '/here/', 'Wed, 25 Dec 2002 04:24:20 GMT')); - $jar->expectAt(1, 'setCookie', array('b', 'bbb', 'host', '/', false)); - - $headers = new SimpleHttpHeaders( - "HTTP/1.1 200 OK\r\n" . - "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n" . - "Content-Type: text/plain\r\n" . - "Server: Apache/1.3.24 (Win32) PHP/4.2.3\r\n" . - "Set-Cookie: a=aaa; expires=Wed, 25-Dec-02 04:24:20 GMT; path=/here/\r\n" . - "Set-Cookie: b=bbb\r\n" . - "Connection: close"); - $headers->writeCookiesToJar($jar, new SimpleUrl('http://host')); - } - - function testCanRecogniseRedirect() { - $headers = new SimpleHttpHeaders("HTTP/1.1 301 OK\r\n" . - "Content-Type: text/plain\r\n" . - "Content-Length: 0\r\n" . - "Location: http://www.somewhere-else.com/\r\n" . - "Connection: close"); - $this->assertIdentical($headers->getResponseCode(), 301); - $this->assertEqual($headers->getLocation(), "http://www.somewhere-else.com/"); - $this->assertTrue($headers->isRedirect()); - } - - function testCanParseChallenge() { - $headers = new SimpleHttpHeaders("HTTP/1.1 401 Authorization required\r\n" . - "Content-Type: text/plain\r\n" . - "Connection: close\r\n" . - "WWW-Authenticate: Basic realm=\"Somewhere\""); - $this->assertEqual($headers->getAuthentication(), 'Basic'); - $this->assertEqual($headers->getRealm(), 'Somewhere'); - $this->assertTrue($headers->isChallenge()); - } -} - -class TestOfHttpResponse extends UnitTestCase { - - function testBadRequest() { - $socket = new MockSimpleSocket(); - $socket->setReturnValue('getSent', ''); - - $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $this->assertTrue($response->isError()); - $this->assertPattern('/Nothing fetched/', $response->getError()); - $this->assertIdentical($response->getContent(), false); - $this->assertIdentical($response->getSent(), ''); - } - - function testBadSocketDuringResponse() { - $socket = new MockSimpleSocket(); - $socket->setReturnValueAt(0, "read", "HTTP/1.1 200 OK\r\n"); - $socket->setReturnValueAt(1, "read", "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n"); - $socket->setReturnValue("read", ""); - $socket->setReturnValue('getSent', 'HTTP/1.1 ...'); - - $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $this->assertTrue($response->isError()); - $this->assertEqual($response->getContent(), ''); - $this->assertEqual($response->getSent(), 'HTTP/1.1 ...'); - } - - function testIncompleteHeader() { - $socket = new MockSimpleSocket(); - $socket->setReturnValueAt(0, "read", "HTTP/1.1 200 OK\r\n"); - $socket->setReturnValueAt(1, "read", "Date: Mon, 18 Nov 2002 15:50:29 GMT\r\n"); - $socket->setReturnValueAt(2, "read", "Content-Type: text/plain\r\n"); - $socket->setReturnValue("read", ""); - - $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $this->assertTrue($response->isError()); - $this->assertEqual($response->getContent(), ""); - } - - function testParseOfResponseHeadersWhenChunked() { - $socket = new MockSimpleSocket(); - $socket->setReturnValueAt(0, "read", "HTTP/1.1 200 OK\r\nDate: Mon, 18 Nov 2002 15:50:29 GMT\r\n"); - $socket->setReturnValueAt(1, "read", "Content-Type: text/plain\r\n"); - $socket->setReturnValueAt(2, "read", "Server: Apache/1.3.24 (Win32) PHP/4.2.3\r\nConne"); - $socket->setReturnValueAt(3, "read", "ction: close\r\n\r\nthis is a test file\n"); - $socket->setReturnValueAt(4, "read", "with two lines in it\n"); - $socket->setReturnValue("read", ""); - - $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $this->assertFalse($response->isError()); - $this->assertEqual( - $response->getContent(), - "this is a test file\nwith two lines in it\n"); - $headers = $response->getHeaders(); - $this->assertIdentical($headers->getHttpVersion(), "1.1"); - $this->assertIdentical($headers->getResponseCode(), 200); - $this->assertEqual($headers->getMimeType(), "text/plain"); - $this->assertFalse($headers->isRedirect()); - $this->assertFalse($headers->getLocation()); - } - - function testRedirect() { - $socket = new MockSimpleSocket(); - $socket->setReturnValueAt(0, "read", "HTTP/1.1 301 OK\r\n"); - $socket->setReturnValueAt(1, "read", "Content-Type: text/plain\r\n"); - $socket->setReturnValueAt(2, "read", "Location: http://www.somewhere-else.com/\r\n"); - $socket->setReturnValueAt(3, "read", "Connection: close\r\n"); - $socket->setReturnValueAt(4, "read", "\r\n"); - $socket->setReturnValue("read", ""); - - $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $headers = $response->getHeaders(); - $this->assertTrue($headers->isRedirect()); - $this->assertEqual($headers->getLocation(), "http://www.somewhere-else.com/"); - } - - function testRedirectWithPort() { - $socket = new MockSimpleSocket(); - $socket->setReturnValueAt(0, "read", "HTTP/1.1 301 OK\r\n"); - $socket->setReturnValueAt(1, "read", "Content-Type: text/plain\r\n"); - $socket->setReturnValueAt(2, "read", "Location: http://www.somewhere-else.com:80/\r\n"); - $socket->setReturnValueAt(3, "read", "Connection: close\r\n"); - $socket->setReturnValueAt(4, "read", "\r\n"); - $socket->setReturnValue("read", ""); - - $response = new SimpleHttpResponse($socket, new SimpleUrl('here'), new SimpleGetEncoding()); - $headers = $response->getHeaders(); - $this->assertTrue($headers->isRedirect()); - $this->assertEqual($headers->getLocation(), "http://www.somewhere-else.com:80/"); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/interfaces_test.php b/3rdparty/simpletest/test/interfaces_test.php deleted file mode 100644 index ab30fe47ff8ef8f674052686fd02e9f7a48fc644..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/interfaces_test.php +++ /dev/null @@ -1,137 +0,0 @@ -=')) { - include(dirname(__FILE__) . '/interfaces_test_php5_1.php'); -} - -interface DummyInterface { - function aMethod(); - function anotherMethod($a); - function &referenceMethod(&$a); -} - -Mock::generate('DummyInterface'); -Mock::generatePartial('DummyInterface', 'PartialDummyInterface', array()); - -class TestOfMockInterfaces extends UnitTestCase { - - function testCanMockAnInterface() { - $mock = new MockDummyInterface(); - $this->assertIsA($mock, 'SimpleMock'); - $this->assertIsA($mock, 'MockDummyInterface'); - $this->assertTrue(method_exists($mock, 'aMethod')); - $this->assertTrue(method_exists($mock, 'anotherMethod')); - $this->assertNull($mock->aMethod()); - } - - function testMockedInterfaceExpectsParameters() { - $mock = new MockDummyInterface(); - $this->expectError(); - $mock->anotherMethod(); - } - - function testCannotPartiallyMockAnInterface() { - $this->assertFalse(class_exists('PartialDummyInterface')); - } -} - -class TestOfSpl extends UnitTestCase { - - function skip() { - $this->skipUnless(function_exists('spl_classes'), 'No SPL module loaded'); - } - - function testCanMockAllSplClasses() { - if (! function_exists('spl_classes')) { - return; - } - foreach(spl_classes() as $class) { - if ($class == 'SplHeap' or $class = 'SplFileObject') { - continue; - } - if (version_compare(PHP_VERSION, '5.1', '<') && - $class == 'CachingIterator' || - $class == 'CachingRecursiveIterator' || - $class == 'FilterIterator' || - $class == 'LimitIterator' || - $class == 'ParentIterator') { - // These iterators require an iterator be passed to them during - // construction in PHP 5.0; there is no way for SimpleTest - // to supply such an iterator, however, so support for it is - // disabled. - continue; - } - $mock_class = "Mock$class"; - Mock::generate($class); - $this->assertIsA(new $mock_class(), $mock_class); - } - } - - function testExtensionOfCommonSplClasses() { - Mock::generate('IteratorImplementation'); - $this->assertIsA( - new IteratorImplementation(), - 'IteratorImplementation'); - Mock::generate('IteratorAggregateImplementation'); - $this->assertIsA( - new IteratorAggregateImplementation(), - 'IteratorAggregateImplementation'); - } -} - -class WithHint { - function hinted(DummyInterface $object) { } -} - -class ImplementsDummy implements DummyInterface { - function aMethod() { } - function anotherMethod($a) { } - function &referenceMethod(&$a) { } - function extraMethod($a = false) { } -} -Mock::generate('ImplementsDummy'); - -class TestOfImplementations extends UnitTestCase { - - function testMockedInterfaceCanPassThroughTypeHint() { - $mock = new MockDummyInterface(); - $hinter = new WithHint(); - $hinter->hinted($mock); - } - - function testImplementedInterfacesAreCarried() { - $mock = new MockImplementsDummy(); - $hinter = new WithHint(); - $hinter->hinted($mock); - } - - function testNoSpuriousWarningsWhenSkippingDefaultedParameter() { - $mock = new MockImplementsDummy(); - $mock->extraMethod(); - } -} - -interface SampleInterfaceWithConstruct { - function __construct($something); -} - -class TestOfInterfaceMocksWithConstruct extends UnitTestCase { - function TODO_testBasicConstructOfAnInterface() { // Fails in PHP 5.3dev - Mock::generate('SampleInterfaceWithConstruct'); - } -} - -interface SampleInterfaceWithClone { - function __clone(); -} - -class TestOfSampleInterfaceWithClone extends UnitTestCase { - function testCanMockWithoutErrors() { - Mock::generate('SampleInterfaceWithClone'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/interfaces_test_php5_1.php b/3rdparty/simpletest/test/interfaces_test_php5_1.php deleted file mode 100644 index 3d154f9953972d2fc1b10cd3b59efb322d8678a4..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/interfaces_test_php5_1.php +++ /dev/null @@ -1,14 +0,0 @@ -assertIsA($mock, 'SampleInterfaceWithHintInSignature'); - } -} - diff --git a/3rdparty/simpletest/test/live_test.php b/3rdparty/simpletest/test/live_test.php deleted file mode 100644 index 3fbb54499d3e5de230696580a82cb049bc3a9ee2..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/live_test.php +++ /dev/null @@ -1,47 +0,0 @@ -assertTrue($socket->isError()); - $this->assertPattern( - '/Cannot open \\[bad_url:111\\] with \\[/', - $socket->getError()); - $this->assertFalse($socket->isOpen()); - $this->assertFalse($socket->write('A message')); - } - - function testSocketClosure() { - $socket = new SimpleSocket('www.lastcraft.com', 80, 15, 8); - $this->assertTrue($socket->isOpen()); - $this->assertTrue($socket->write("GET /test/network_confirm.php HTTP/1.0\r\n")); - $socket->write("Host: www.lastcraft.com\r\n"); - $socket->write("Connection: close\r\n\r\n"); - $this->assertEqual($socket->read(), "HTTP/1.1"); - $socket->close(); - $this->assertIdentical($socket->read(), false); - } - - function testRecordOfSentCharacters() { - $socket = new SimpleSocket('www.lastcraft.com', 80, 15); - $this->assertTrue($socket->write("GET /test/network_confirm.php HTTP/1.0\r\n")); - $socket->write("Host: www.lastcraft.com\r\n"); - $socket->write("Connection: close\r\n\r\n"); - $socket->close(); - $this->assertEqual($socket->getSent(), - "GET /test/network_confirm.php HTTP/1.0\r\n" . - "Host: www.lastcraft.com\r\n" . - "Connection: close\r\n\r\n"); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/mock_objects_test.php b/3rdparty/simpletest/test/mock_objects_test.php deleted file mode 100644 index 7f3178995a743dc99340aba201cd27a8cfe148b1..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/mock_objects_test.php +++ /dev/null @@ -1,985 +0,0 @@ -assertTrue($expectation->test(33)); - $this->assertTrue($expectation->test(false)); - $this->assertTrue($expectation->test(null)); - } -} - -class TestOfParametersExpectation extends UnitTestCase { - - function testEmptyMatch() { - $expectation = new ParametersExpectation(array()); - $this->assertTrue($expectation->test(array())); - $this->assertFalse($expectation->test(array(33))); - } - - function testSingleMatch() { - $expectation = new ParametersExpectation(array(0)); - $this->assertFalse($expectation->test(array(1))); - $this->assertTrue($expectation->test(array(0))); - } - - function testAnyMatch() { - $expectation = new ParametersExpectation(false); - $this->assertTrue($expectation->test(array())); - $this->assertTrue($expectation->test(array(1, 2))); - } - - function testMissingParameter() { - $expectation = new ParametersExpectation(array(0)); - $this->assertFalse($expectation->test(array())); - } - - function testNullParameter() { - $expectation = new ParametersExpectation(array(null)); - $this->assertTrue($expectation->test(array(null))); - $this->assertFalse($expectation->test(array())); - } - - function testAnythingExpectations() { - $expectation = new ParametersExpectation(array(new AnythingExpectation())); - $this->assertFalse($expectation->test(array())); - $this->assertIdentical($expectation->test(array(null)), true); - $this->assertIdentical($expectation->test(array(13)), true); - } - - function testOtherExpectations() { - $expectation = new ParametersExpectation( - array(new PatternExpectation('/hello/i'))); - $this->assertFalse($expectation->test(array('Goodbye'))); - $this->assertTrue($expectation->test(array('hello'))); - $this->assertTrue($expectation->test(array('Hello'))); - } - - function testIdentityOnly() { - $expectation = new ParametersExpectation(array("0")); - $this->assertFalse($expectation->test(array(0))); - $this->assertTrue($expectation->test(array("0"))); - } - - function testLongList() { - $expectation = new ParametersExpectation( - array("0", 0, new AnythingExpectation(), false)); - $this->assertTrue($expectation->test(array("0", 0, 37, false))); - $this->assertFalse($expectation->test(array("0", 0, 37, true))); - $this->assertFalse($expectation->test(array("0", 0, 37))); - } -} - -class TestOfSimpleSignatureMap extends UnitTestCase { - - function testEmpty() { - $map = new SimpleSignatureMap(); - $this->assertFalse($map->isMatch("any", array())); - $this->assertNull($map->findFirstAction("any", array())); - } - - function testDifferentCallSignaturesCanHaveDifferentReferences() { - $map = new SimpleSignatureMap(); - $fred = 'Fred'; - $jim = 'jim'; - $map->add(array(0), $fred); - $map->add(array('0'), $jim); - $this->assertSame($fred, $map->findFirstAction(array(0))); - $this->assertSame($jim, $map->findFirstAction(array('0'))); - } - - function testWildcard() { - $fred = 'Fred'; - $map = new SimpleSignatureMap(); - $map->add(array(new AnythingExpectation(), 1, 3), $fred); - $this->assertTrue($map->isMatch(array(2, 1, 3))); - $this->assertSame($map->findFirstAction(array(2, 1, 3)), $fred); - } - - function testAllWildcard() { - $fred = 'Fred'; - $map = new SimpleSignatureMap(); - $this->assertFalse($map->isMatch(array(2, 1, 3))); - $map->add('', $fred); - $this->assertTrue($map->isMatch(array(2, 1, 3))); - $this->assertSame($map->findFirstAction(array(2, 1, 3)), $fred); - } - - function testOrdering() { - $map = new SimpleSignatureMap(); - $map->add(array(1, 2), new SimpleByValue("1, 2")); - $map->add(array(1, 3), new SimpleByValue("1, 3")); - $map->add(array(1), new SimpleByValue("1")); - $map->add(array(1, 4), new SimpleByValue("1, 4")); - $map->add(array(new AnythingExpectation()), new SimpleByValue("Any")); - $map->add(array(2), new SimpleByValue("2")); - $map->add("", new SimpleByValue("Default")); - $map->add(array(), new SimpleByValue("None")); - $this->assertEqual($map->findFirstAction(array(1, 2)), new SimpleByValue("1, 2")); - $this->assertEqual($map->findFirstAction(array(1, 3)), new SimpleByValue("1, 3")); - $this->assertEqual($map->findFirstAction(array(1, 4)), new SimpleByValue("1, 4")); - $this->assertEqual($map->findFirstAction(array(1)), new SimpleByValue("1")); - $this->assertEqual($map->findFirstAction(array(2)), new SimpleByValue("Any")); - $this->assertEqual($map->findFirstAction(array(3)), new SimpleByValue("Any")); - $this->assertEqual($map->findFirstAction(array()), new SimpleByValue("Default")); - } -} - -class TestOfCallSchedule extends UnitTestCase { - function testCanBeSetToAlwaysReturnTheSameReference() { - $a = 5; - $schedule = new SimpleCallSchedule(); - $schedule->register('aMethod', false, new SimpleByReference($a)); - $this->assertReference($schedule->respond(0, 'aMethod', array()), $a); - $this->assertReference($schedule->respond(1, 'aMethod', array()), $a); - } - - function testSpecificSignaturesOverrideTheAlwaysCase() { - $any = 'any'; - $one = 'two'; - $schedule = new SimpleCallSchedule(); - $schedule->register('aMethod', array(1), new SimpleByReference($one)); - $schedule->register('aMethod', false, new SimpleByReference($any)); - $this->assertReference($schedule->respond(0, 'aMethod', array(2)), $any); - $this->assertReference($schedule->respond(0, 'aMethod', array(1)), $one); - } - - function testReturnsCanBeSetOverTime() { - $one = 'one'; - $two = 'two'; - $schedule = new SimpleCallSchedule(); - $schedule->registerAt(0, 'aMethod', false, new SimpleByReference($one)); - $schedule->registerAt(1, 'aMethod', false, new SimpleByReference($two)); - $this->assertReference($schedule->respond(0, 'aMethod', array()), $one); - $this->assertReference($schedule->respond(1, 'aMethod', array()), $two); - } - - function testReturnsOverTimecanBeAlteredByTheArguments() { - $one = '1'; - $two = '2'; - $two_a = '2a'; - $schedule = new SimpleCallSchedule(); - $schedule->registerAt(0, 'aMethod', false, new SimpleByReference($one)); - $schedule->registerAt(1, 'aMethod', array('a'), new SimpleByReference($two_a)); - $schedule->registerAt(1, 'aMethod', false, new SimpleByReference($two)); - $this->assertReference($schedule->respond(0, 'aMethod', array()), $one); - $this->assertReference($schedule->respond(1, 'aMethod', array()), $two); - $this->assertReference($schedule->respond(1, 'aMethod', array('a')), $two_a); - } - - function testCanReturnByValue() { - $a = 5; - $schedule = new SimpleCallSchedule(); - $schedule->register('aMethod', false, new SimpleByValue($a)); - $this->assertCopy($schedule->respond(0, 'aMethod', array()), $a); - } - - function testCanThrowException() { - if (version_compare(phpversion(), '5', '>=')) { - $schedule = new SimpleCallSchedule(); - $schedule->register('aMethod', false, new SimpleThrower(new Exception('Ouch'))); - $this->expectException(new Exception('Ouch')); - $schedule->respond(0, 'aMethod', array()); - } - } - - function testCanEmitError() { - $schedule = new SimpleCallSchedule(); - $schedule->register('aMethod', false, new SimpleErrorThrower('Ouch', E_USER_WARNING)); - $this->expectError('Ouch'); - $schedule->respond(0, 'aMethod', array()); - } -} - -class Dummy { - function Dummy() { - } - - function aMethod() { - return true; - } - - function &aReferenceMethod() { - return true; - } - - function anotherMethod() { - return true; - } -} -Mock::generate('Dummy'); -Mock::generate('Dummy', 'AnotherMockDummy'); -Mock::generate('Dummy', 'MockDummyWithExtraMethods', array('extraMethod')); - -class TestOfMockGeneration extends UnitTestCase { - - function testCloning() { - $mock = new MockDummy(); - $this->assertTrue(method_exists($mock, "aMethod")); - $this->assertNull($mock->aMethod()); - } - - function testCloningWithExtraMethod() { - $mock = new MockDummyWithExtraMethods(); - $this->assertTrue(method_exists($mock, "extraMethod")); - } - - function testCloningWithChosenClassName() { - $mock = new AnotherMockDummy(); - $this->assertTrue(method_exists($mock, "aMethod")); - } -} - -class TestOfMockReturns extends UnitTestCase { - - function testDefaultReturn() { - $mock = new MockDummy(); - $mock->returnsByValue("aMethod", "aaa"); - $this->assertIdentical($mock->aMethod(), "aaa"); - $this->assertIdentical($mock->aMethod(), "aaa"); - } - - function testParameteredReturn() { - $mock = new MockDummy(); - $mock->returnsByValue('aMethod', 'aaa', array(1, 2, 3)); - $this->assertNull($mock->aMethod()); - $this->assertIdentical($mock->aMethod(1, 2, 3), 'aaa'); - } - - function testSetReturnGivesObjectReference() { - $mock = new MockDummy(); - $object = new Dummy(); - $mock->returns('aMethod', $object, array(1, 2, 3)); - $this->assertSame($mock->aMethod(1, 2, 3), $object); - } - - function testSetReturnReferenceGivesOriginalReference() { - $mock = new MockDummy(); - $object = 1; - $mock->returnsByReference('aReferenceMethod', $object, array(1, 2, 3)); - $this->assertReference($mock->aReferenceMethod(1, 2, 3), $object); - } - - function testReturnValueCanBeChosenJustByPatternMatchingArguments() { - $mock = new MockDummy(); - $mock->returnsByValue( - "aMethod", - "aaa", - array(new PatternExpectation('/hello/i'))); - $this->assertIdentical($mock->aMethod('Hello'), 'aaa'); - $this->assertNull($mock->aMethod('Goodbye')); - } - - function testMultipleMethods() { - $mock = new MockDummy(); - $mock->returnsByValue("aMethod", 100, array(1)); - $mock->returnsByValue("aMethod", 200, array(2)); - $mock->returnsByValue("anotherMethod", 10, array(1)); - $mock->returnsByValue("anotherMethod", 20, array(2)); - $this->assertIdentical($mock->aMethod(1), 100); - $this->assertIdentical($mock->anotherMethod(1), 10); - $this->assertIdentical($mock->aMethod(2), 200); - $this->assertIdentical($mock->anotherMethod(2), 20); - } - - function testReturnSequence() { - $mock = new MockDummy(); - $mock->returnsByValueAt(0, "aMethod", "aaa"); - $mock->returnsByValueAt(1, "aMethod", "bbb"); - $mock->returnsByValueAt(3, "aMethod", "ddd"); - $this->assertIdentical($mock->aMethod(), "aaa"); - $this->assertIdentical($mock->aMethod(), "bbb"); - $this->assertNull($mock->aMethod()); - $this->assertIdentical($mock->aMethod(), "ddd"); - } - - function testSetReturnReferenceAtGivesOriginal() { - $mock = new MockDummy(); - $object = 100; - $mock->returnsByReferenceAt(1, "aReferenceMethod", $object); - $this->assertNull($mock->aReferenceMethod()); - $this->assertReference($mock->aReferenceMethod(), $object); - $this->assertNull($mock->aReferenceMethod()); - } - - function testReturnsAtGivesOriginalObjectHandle() { - $mock = new MockDummy(); - $object = new Dummy(); - $mock->returnsAt(1, "aMethod", $object); - $this->assertNull($mock->aMethod()); - $this->assertSame($mock->aMethod(), $object); - $this->assertNull($mock->aMethod()); - } - - function testComplicatedReturnSequence() { - $mock = new MockDummy(); - $object = new Dummy(); - $mock->returnsAt(1, "aMethod", "aaa", array("a")); - $mock->returnsAt(1, "aMethod", "bbb"); - $mock->returnsAt(2, "aMethod", $object, array('*', 2)); - $mock->returnsAt(2, "aMethod", "value", array('*', 3)); - $mock->returns("aMethod", 3, array(3)); - $this->assertNull($mock->aMethod()); - $this->assertEqual($mock->aMethod("a"), "aaa"); - $this->assertSame($mock->aMethod(1, 2), $object); - $this->assertEqual($mock->aMethod(3), 3); - $this->assertNull($mock->aMethod()); - } - - function testMultipleMethodSequences() { - $mock = new MockDummy(); - $mock->returnsByValueAt(0, "aMethod", "aaa"); - $mock->returnsByValueAt(1, "aMethod", "bbb"); - $mock->returnsByValueAt(0, "anotherMethod", "ccc"); - $mock->returnsByValueAt(1, "anotherMethod", "ddd"); - $this->assertIdentical($mock->aMethod(), "aaa"); - $this->assertIdentical($mock->anotherMethod(), "ccc"); - $this->assertIdentical($mock->aMethod(), "bbb"); - $this->assertIdentical($mock->anotherMethod(), "ddd"); - } - - function testSequenceFallback() { - $mock = new MockDummy(); - $mock->returnsByValueAt(0, "aMethod", "aaa", array('a')); - $mock->returnsByValueAt(1, "aMethod", "bbb", array('a')); - $mock->returnsByValue("aMethod", "AAA"); - $this->assertIdentical($mock->aMethod('a'), "aaa"); - $this->assertIdentical($mock->aMethod('b'), "AAA"); - } - - function testMethodInterference() { - $mock = new MockDummy(); - $mock->returnsByValueAt(0, "anotherMethod", "aaa"); - $mock->returnsByValue("aMethod", "AAA"); - $this->assertIdentical($mock->aMethod(), "AAA"); - $this->assertIdentical($mock->anotherMethod(), "aaa"); - } -} - -class TestOfMockExpectationsThatPass extends UnitTestCase { - - function testAnyArgument() { - $mock = new MockDummy(); - $mock->expect('aMethod', array('*')); - $mock->aMethod(1); - $mock->aMethod('hello'); - } - - function testAnyTwoArguments() { - $mock = new MockDummy(); - $mock->expect('aMethod', array('*', '*')); - $mock->aMethod(1, 2); - } - - function testSpecificArgument() { - $mock = new MockDummy(); - $mock->expect('aMethod', array(1)); - $mock->aMethod(1); - } - - function testExpectation() { - $mock = new MockDummy(); - $mock->expect('aMethod', array(new IsAExpectation('Dummy'))); - $mock->aMethod(new Dummy()); - } - - function testArgumentsInSequence() { - $mock = new MockDummy(); - $mock->expectAt(0, 'aMethod', array(1, 2)); - $mock->expectAt(1, 'aMethod', array(3, 4)); - $mock->aMethod(1, 2); - $mock->aMethod(3, 4); - } - - function testAtLeastOnceSatisfiedByOneCall() { - $mock = new MockDummy(); - $mock->expectAtLeastOnce('aMethod'); - $mock->aMethod(); - } - - function testAtLeastOnceSatisfiedByTwoCalls() { - $mock = new MockDummy(); - $mock->expectAtLeastOnce('aMethod'); - $mock->aMethod(); - $mock->aMethod(); - } - - function testOnceSatisfiedByOneCall() { - $mock = new MockDummy(); - $mock->expectOnce('aMethod'); - $mock->aMethod(); - } - - function testMinimumCallsSatisfiedByEnoughCalls() { - $mock = new MockDummy(); - $mock->expectMinimumCallCount('aMethod', 1); - $mock->aMethod(); - } - - function testMinimumCallsSatisfiedByTooManyCalls() { - $mock = new MockDummy(); - $mock->expectMinimumCallCount('aMethod', 3); - $mock->aMethod(); - $mock->aMethod(); - $mock->aMethod(); - $mock->aMethod(); - } - - function testMaximumCallsSatisfiedByEnoughCalls() { - $mock = new MockDummy(); - $mock->expectMaximumCallCount('aMethod', 1); - $mock->aMethod(); - } - - function testMaximumCallsSatisfiedByNoCalls() { - $mock = new MockDummy(); - $mock->expectMaximumCallCount('aMethod', 1); - } -} - -class MockWithInjectedTestCase extends SimpleMock { - protected function getCurrentTestCase() { - return SimpleTest::getContext()->getTest()->getMockedTest(); - } -} -SimpleTest::setMockBaseClass('MockWithInjectedTestCase'); -Mock::generate('Dummy', 'MockDummyWithInjectedTestCase'); -SimpleTest::setMockBaseClass('SimpleMock'); -Mock::generate('SimpleTestCase'); - -class LikeExpectation extends IdenticalExpectation { - function __construct($expectation) { - $expectation->message = ''; - parent::__construct($expectation); - } - - function test($compare) { - $compare->message = ''; - return parent::test($compare); - } - - function testMessage($compare) { - $compare->message = ''; - return parent::testMessage($compare); - } -} - -class TestOfMockExpectations extends UnitTestCase { - private $test; - - function setUp() { - $this->test = new MockSimpleTestCase(); - } - - function getMockedTest() { - return $this->test; - } - - function testSettingExpectationOnNonMethodThrowsError() { - $mock = new MockDummyWithInjectedTestCase(); - $this->expectError(); - $mock->expectMaximumCallCount('aMissingMethod', 2); - } - - function testMaxCallsDetectsOverrun() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 2), 3)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectMaximumCallCount('aMethod', 2); - $mock->aMethod(); - $mock->aMethod(); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testTallyOnMaxCallsSendsPassOnUnderrun() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 2), 2)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectMaximumCallCount("aMethod", 2); - $mock->aMethod(); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testExpectNeverDetectsOverrun() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 0), 1)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectNever('aMethod'); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testTallyOnExpectNeverStillSendsPassOnUnderrun() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 0), 0)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectNever('aMethod'); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testMinCalls() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 2), 2)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectMinimumCallCount('aMethod', 2); - $mock->aMethod(); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testFailedNever() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 0), 1)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectNever('aMethod'); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testUnderOnce() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 1), 0)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectOnce('aMethod'); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testOverOnce() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 1), 2)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectOnce('aMethod'); - $mock->aMethod(); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testUnderAtLeastOnce() { - $this->test->expectOnce('assert', array(new MemberExpectation('count', 1), 0)); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectAtLeastOnce("aMethod"); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testZeroArguments() { - $this->test->expectOnce('assert', - array(new MemberExpectation('expected', array()), array(), '*')); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expect('aMethod', array()); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testExpectedArguments() { - $this->test->expectOnce('assert', - array(new MemberExpectation('expected', array(1, 2, 3)), array(1, 2, 3), '*')); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expect('aMethod', array(1, 2, 3)); - $mock->aMethod(1, 2, 3); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testFailedArguments() { - $this->test->expectOnce('assert', - array(new MemberExpectation('expected', array('this')), array('that'), '*')); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expect('aMethod', array('this')); - $mock->aMethod('that'); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testWildcardsAreTranslatedToAnythingExpectations() { - $this->test->expectOnce('assert', - array(new MemberExpectation('expected', - array(new AnythingExpectation(), - 123, - new AnythingExpectation())), - array(100, 123, 101), '*')); - $mock = new MockDummyWithInjectedTestCase($this); - $mock->expect("aMethod", array('*', 123, '*')); - $mock->aMethod(100, 123, 101); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testSpecificPassingSequence() { - $this->test->expectAt(0, 'assert', - array(new MemberExpectation('expected', array(1, 2, 3)), array(1, 2, 3), '*')); - $this->test->expectAt(1, 'assert', - array(new MemberExpectation('expected', array('Hello')), array('Hello'), '*')); - $mock = new MockDummyWithInjectedTestCase(); - $mock->expectAt(1, 'aMethod', array(1, 2, 3)); - $mock->expectAt(2, 'aMethod', array('Hello')); - $mock->aMethod(); - $mock->aMethod(1, 2, 3); - $mock->aMethod('Hello'); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } - - function testNonArrayForExpectedParametersGivesError() { - $mock = new MockDummyWithInjectedTestCase(); - $this->expectError(new PatternExpectation('/\$args.*not an array/i')); - $mock->expect("aMethod", "foo"); - $mock->aMethod(); - $mock->mock->atTestEnd('testSomething', $this->test); - } -} - -class TestOfMockComparisons extends UnitTestCase { - - function testEqualComparisonOfMocksDoesNotCrash() { - $expectation = new EqualExpectation(new MockDummy()); - $this->assertTrue($expectation->test(new MockDummy(), true)); - } - - function testIdenticalComparisonOfMocksDoesNotCrash() { - $expectation = new IdenticalExpectation(new MockDummy()); - $this->assertTrue($expectation->test(new MockDummy())); - } -} - -class ClassWithSpecialMethods { - function __get($name) { } - function __set($name, $value) { } - function __isset($name) { } - function __unset($name) { } - function __call($method, $arguments) { } - function __toString() { } -} -Mock::generate('ClassWithSpecialMethods'); - -class TestOfSpecialMethodsAfterPHP51 extends UnitTestCase { - - function skip() { - $this->skipIf(version_compare(phpversion(), '5.1', '<'), '__isset and __unset overloading not tested unless PHP 5.1+'); - } - - function testCanEmulateIsset() { - $mock = new MockClassWithSpecialMethods(); - $mock->returnsByValue('__isset', true); - $this->assertIdentical(isset($mock->a), true); - } - - function testCanExpectUnset() { - $mock = new MockClassWithSpecialMethods(); - $mock->expectOnce('__unset', array('a')); - unset($mock->a); - } - -} - -class TestOfSpecialMethods extends UnitTestCase { - function skip() { - $this->skipIf(version_compare(phpversion(), '5', '<'), 'Overloading not tested unless PHP 5+'); - } - - function testCanMockTheThingAtAll() { - $mock = new MockClassWithSpecialMethods(); - } - - function testReturnFromSpecialAccessor() { - $mock = new MockClassWithSpecialMethods(); - $mock->returnsByValue('__get', '1st Return', array('first')); - $mock->returnsByValue('__get', '2nd Return', array('second')); - $this->assertEqual($mock->first, '1st Return'); - $this->assertEqual($mock->second, '2nd Return'); - } - - function testcanExpectTheSettingOfValue() { - $mock = new MockClassWithSpecialMethods(); - $mock->expectOnce('__set', array('a', 'A')); - $mock->a = 'A'; - } - - function testCanSimulateAnOverloadmethod() { - $mock = new MockClassWithSpecialMethods(); - $mock->expectOnce('__call', array('amOverloaded', array('A'))); - $mock->returnsByValue('__call', 'aaa'); - $this->assertIdentical($mock->amOverloaded('A'), 'aaa'); - } - - function testToStringMagic() { - $mock = new MockClassWithSpecialMethods(); - $mock->expectOnce('__toString'); - $mock->returnsByValue('__toString', 'AAA'); - ob_start(); - print $mock; - $output = ob_get_contents(); - ob_end_clean(); - $this->assertEqual($output, 'AAA'); - } -} - -class WithStaticMethod { - static function aStaticMethod() { } -} -Mock::generate('WithStaticMethod'); - -class TestOfMockingClassesWithStaticMethods extends UnitTestCase { - - function testStaticMethodIsMockedAsStatic() { - $mock = new WithStaticMethod(); - $reflection = new ReflectionClass($mock); - $method = $reflection->getMethod('aStaticMethod'); - $this->assertTrue($method->isStatic()); - } -} - -class MockTestException extends Exception { } - -class TestOfThrowingExceptionsFromMocks extends UnitTestCase { - - function testCanThrowOnMethodCall() { - $mock = new MockDummy(); - $mock->throwOn('aMethod'); - $this->expectException(); - $mock->aMethod(); - } - - function testCanThrowSpecificExceptionOnMethodCall() { - $mock = new MockDummy(); - $mock->throwOn('aMethod', new MockTestException()); - $this->expectException(); - $mock->aMethod(); - } - - function testThrowsOnlyWhenCallSignatureMatches() { - $mock = new MockDummy(); - $mock->throwOn('aMethod', new MockTestException(), array(3)); - $mock->aMethod(1); - $mock->aMethod(2); - $this->expectException(); - $mock->aMethod(3); - } - - function testCanThrowOnParticularInvocation() { - $mock = new MockDummy(); - $mock->throwAt(2, 'aMethod', new MockTestException()); - $mock->aMethod(); - $mock->aMethod(); - $this->expectException(); - $mock->aMethod(); - } -} - -class TestOfThrowingErrorsFromMocks extends UnitTestCase { - - function testCanGenerateErrorFromMethodCall() { - $mock = new MockDummy(); - $mock->errorOn('aMethod', 'Ouch!'); - $this->expectError('Ouch!'); - $mock->aMethod(); - } - - function testGeneratesErrorOnlyWhenCallSignatureMatches() { - $mock = new MockDummy(); - $mock->errorOn('aMethod', 'Ouch!', array(3)); - $mock->aMethod(1); - $mock->aMethod(2); - $this->expectError(); - $mock->aMethod(3); - } - - function testCanGenerateErrorOnParticularInvocation() { - $mock = new MockDummy(); - $mock->errorAt(2, 'aMethod', 'Ouch!'); - $mock->aMethod(); - $mock->aMethod(); - $this->expectError(); - $mock->aMethod(); - } -} - -Mock::generatePartial('Dummy', 'TestDummy', array('anotherMethod', 'aReferenceMethod')); - -class TestOfPartialMocks extends UnitTestCase { - - function testMethodReplacementWithNoBehaviourReturnsNull() { - $mock = new TestDummy(); - $this->assertEqual($mock->aMethod(99), 99); - $this->assertNull($mock->anotherMethod()); - } - - function testSettingReturns() { - $mock = new TestDummy(); - $mock->returnsByValue('anotherMethod', 33, array(3)); - $mock->returnsByValue('anotherMethod', 22); - $mock->returnsByValueAt(2, 'anotherMethod', 44, array(3)); - $this->assertEqual($mock->anotherMethod(), 22); - $this->assertEqual($mock->anotherMethod(3), 33); - $this->assertEqual($mock->anotherMethod(3), 44); - } - - function testSetReturnReferenceGivesOriginal() { - $mock = new TestDummy(); - $object = 99; - $mock->returnsByReferenceAt(0, 'aReferenceMethod', $object, array(3)); - $this->assertReference($mock->aReferenceMethod(3), $object); - } - - function testReturnsAtGivesOriginalObjectHandle() { - $mock = new TestDummy(); - $object = new Dummy(); - $mock->returnsAt(0, 'anotherMethod', $object, array(3)); - $this->assertSame($mock->anotherMethod(3), $object); - } - - function testExpectations() { - $mock = new TestDummy(); - $mock->expectCallCount('anotherMethod', 2); - $mock->expect('anotherMethod', array(77)); - $mock->expectAt(1, 'anotherMethod', array(66)); - $mock->anotherMethod(77); - $mock->anotherMethod(66); - } - - function testSettingExpectationOnMissingMethodThrowsError() { - $mock = new TestDummy(); - $this->expectError(); - $mock->expectCallCount('aMissingMethod', 2); - } -} - -class ConstructorSuperClass { - function ConstructorSuperClass() { } -} - -class ConstructorSubClass extends ConstructorSuperClass { } - -class TestOfPHP4StyleSuperClassConstruct extends UnitTestCase { - function testBasicConstruct() { - Mock::generate('ConstructorSubClass'); - $mock = new MockConstructorSubClass(); - $this->assertIsA($mock, 'ConstructorSubClass'); - $this->assertTrue(method_exists($mock, 'ConstructorSuperClass')); - } -} - -class TestOfPHP5StaticMethodMocking extends UnitTestCase { - function testCanCreateAMockObjectWithStaticMethodsWithoutError() { - eval(' - class SimpleObjectContainingStaticMethod { - static function someStatic() { } - } - '); - Mock::generate('SimpleObjectContainingStaticMethod'); - } -} - -class TestOfPHP5AbstractMethodMocking extends UnitTestCase { - function testCanCreateAMockObjectFromAnAbstractWithProperFunctionDeclarations() { - eval(' - abstract class SimpleAbstractClassContainingAbstractMethods { - abstract function anAbstract(); - abstract function anAbstractWithParameter($foo); - abstract function anAbstractWithMultipleParameters($foo, $bar); - } - '); - Mock::generate('SimpleAbstractClassContainingAbstractMethods'); - $this->assertTrue( - method_exists( - // Testing with class name alone does not work in PHP 5.0 - new MockSimpleAbstractClassContainingAbstractMethods, - 'anAbstract' - ) - ); - $this->assertTrue( - method_exists( - new MockSimpleAbstractClassContainingAbstractMethods, - 'anAbstractWithParameter' - ) - ); - $this->assertTrue( - method_exists( - new MockSimpleAbstractClassContainingAbstractMethods, - 'anAbstractWithMultipleParameters' - ) - ); - } - - function testMethodsDefinedAsAbstractInParentShouldHaveFullSignature() { - eval(' - abstract class SimpleParentAbstractClassContainingAbstractMethods { - abstract function anAbstract(); - abstract function anAbstractWithParameter($foo); - abstract function anAbstractWithMultipleParameters($foo, $bar); - } - - class SimpleChildAbstractClassContainingAbstractMethods extends SimpleParentAbstractClassContainingAbstractMethods { - function anAbstract(){} - function anAbstractWithParameter($foo){} - function anAbstractWithMultipleParameters($foo, $bar){} - } - - class EvenDeeperEmptyChildClass extends SimpleChildAbstractClassContainingAbstractMethods {} - '); - Mock::generate('SimpleChildAbstractClassContainingAbstractMethods'); - $this->assertTrue( - method_exists( - new MockSimpleChildAbstractClassContainingAbstractMethods, - 'anAbstract' - ) - ); - $this->assertTrue( - method_exists( - new MockSimpleChildAbstractClassContainingAbstractMethods, - 'anAbstractWithParameter' - ) - ); - $this->assertTrue( - method_exists( - new MockSimpleChildAbstractClassContainingAbstractMethods, - 'anAbstractWithMultipleParameters' - ) - ); - Mock::generate('EvenDeeperEmptyChildClass'); - $this->assertTrue( - method_exists( - new MockEvenDeeperEmptyChildClass, - 'anAbstract' - ) - ); - $this->assertTrue( - method_exists( - new MockEvenDeeperEmptyChildClass, - 'anAbstractWithParameter' - ) - ); - $this->assertTrue( - method_exists( - new MockEvenDeeperEmptyChildClass, - 'anAbstractWithMultipleParameters' - ) - ); - } -} - -class DummyWithProtected -{ - public function aMethodCallsProtected() { return $this->aProtectedMethod(); } - protected function aProtectedMethod() { return true; } -} - -Mock::generatePartial('DummyWithProtected', 'TestDummyWithProtected', array('aProtectedMethod')); -class TestOfProtectedMethodPartialMocks extends UnitTestCase -{ - function testProtectedMethodExists() { - $this->assertTrue( - method_exists( - new TestDummyWithProtected, - 'aProtectedMethod' - ) - ); - } - - function testProtectedMethodIsCalled() { - $object = new DummyWithProtected(); - $this->assertTrue($object->aMethodCallsProtected(), 'ensure original was called'); - } - - function testMockedMethodIsCalled() { - $object = new TestDummyWithProtected(); - $object->returnsByValue('aProtectedMethod', false); - $this->assertFalse($object->aMethodCallsProtected()); - } -} - -?> diff --git a/3rdparty/simpletest/test/page_test.php b/3rdparty/simpletest/test/page_test.php deleted file mode 100644 index fdc15c5d008b8ddfafa939e2c28b1dd278783f7f..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/page_test.php +++ /dev/null @@ -1,166 +0,0 @@ -assertEqual($page->getTransportError(), 'No page fetched yet'); - $this->assertIdentical($page->getRaw(), false); - $this->assertIdentical($page->getHeaders(), false); - $this->assertIdentical($page->getMimeType(), false); - $this->assertIdentical($page->getResponseCode(), false); - $this->assertIdentical($page->getAuthentication(), false); - $this->assertIdentical($page->getRealm(), false); - $this->assertFalse($page->hasFrames()); - $this->assertIdentical($page->getUrls(), array()); - $this->assertIdentical($page->getTitle(), false); - } -} - -class TestOfPageHeaders extends UnitTestCase { - - function testUrlAccessor() { - $headers = new MockSimpleHttpHeaders(); - - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getHeaders', $headers); - $response->setReturnValue('getMethod', 'POST'); - $response->setReturnValue('getUrl', new SimpleUrl('here')); - $response->setReturnValue('getRequestData', array('a' => 'A')); - - $page = new SimplePage($response); - $this->assertEqual($page->getMethod(), 'POST'); - $this->assertEqual($page->getUrl(), new SimpleUrl('here')); - $this->assertEqual($page->getRequestData(), array('a' => 'A')); - } - - function testTransportError() { - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getError', 'Ouch'); - - $page = new SimplePage($response); - $this->assertEqual($page->getTransportError(), 'Ouch'); - } - - function testHeadersAccessor() { - $headers = new MockSimpleHttpHeaders(); - $headers->setReturnValue('getRaw', 'My: Headers'); - - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getHeaders', $headers); - - $page = new SimplePage($response); - $this->assertEqual($page->getHeaders(), 'My: Headers'); - } - - function testMimeAccessor() { - $headers = new MockSimpleHttpHeaders(); - $headers->setReturnValue('getMimeType', 'text/html'); - - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getHeaders', $headers); - - $page = new SimplePage($response); - $this->assertEqual($page->getMimeType(), 'text/html'); - } - - function testResponseAccessor() { - $headers = new MockSimpleHttpHeaders(); - $headers->setReturnValue('getResponseCode', 301); - - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getHeaders', $headers); - - $page = new SimplePage($response); - $this->assertIdentical($page->getResponseCode(), 301); - } - - function testAuthenticationAccessors() { - $headers = new MockSimpleHttpHeaders(); - $headers->setReturnValue('getAuthentication', 'Basic'); - $headers->setReturnValue('getRealm', 'Secret stuff'); - - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getHeaders', $headers); - - $page = new SimplePage($response); - $this->assertEqual($page->getAuthentication(), 'Basic'); - $this->assertEqual($page->getRealm(), 'Secret stuff'); - } -} - -class TestOfHtmlStrippingAndNormalisation extends UnitTestCase { - - function testImageSuppressionWhileKeepingParagraphsAndAltText() { - $this->assertEqual( - SimplePage::normalise('

some text

bar'), - 'some text bar'); - } - - function testSpaceNormalisation() { - $this->assertEqual( - SimplePage::normalise("\nOne\tTwo \nThree\t"), - 'One Two Three'); - } - - function testMultilinesCommentSuppression() { - $this->assertEqual( - SimplePage::normalise(''), - ''); - } - - function testCommentSuppression() { - $this->assertEqual( - SimplePage::normalise(''), - ''); - } - - function testJavascriptSuppression() { - $this->assertEqual( - SimplePage::normalise(''), - ''); - $this->assertEqual( - SimplePage::normalise(''), - ''); - $this->assertEqual( - SimplePage::normalise(''), - ''); - } - - function testTagSuppression() { - $this->assertEqual( - SimplePage::normalise('Hello'), - 'Hello'); - } - - function testAdjoiningTagSuppression() { - $this->assertEqual( - SimplePage::normalise('HelloGoodbye'), - 'HelloGoodbye'); - } - - function testExtractImageAltTextWithDifferentQuotes() { - $this->assertEqual( - SimplePage::normalise('One\'Two\'Three'), - 'One Two Three'); - } - - function testExtractImageAltTextMultipleTimes() { - $this->assertEqual( - SimplePage::normalise('OneTwoThree'), - 'One Two Three'); - } - - function testHtmlEntityTranslation() { - $this->assertEqual( - SimplePage::normalise('<>"&''), - '<>"&\''); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/parse_error_test.php b/3rdparty/simpletest/test/parse_error_test.php deleted file mode 100644 index c3ffb3d42057459a7590e5583d949e88e9afbca0..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/parse_error_test.php +++ /dev/null @@ -1,9 +0,0 @@ -addFile('test_with_parse_error.php'); -$test->run(new HtmlReporter()); -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/parsing_test.php b/3rdparty/simpletest/test/parsing_test.php deleted file mode 100644 index 2c5e6cafe1d7bdab93e55b9d422ceb7d0ad378e3..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/parsing_test.php +++ /dev/null @@ -1,642 +0,0 @@ -whenVisiting('http://host/', 'Raw HTML'); - $this->assertEqual($page->getRaw(), 'Raw HTML'); - } - - function testTextAccessor() { - $page = $this->whenVisiting('http://host/', 'Some "messy" HTML'); - $this->assertEqual($page->getText(), 'Some "messy" HTML'); - } - - function testFramesetAbsence() { - $page = $this->whenVisiting('http://here/', ''); - $this->assertFalse($page->hasFrames()); - $this->assertIdentical($page->getFrameset(), false); - } - - function testPageWithNoUrlsGivesEmptyArrayOfLinks() { - $page = $this->whenVisiting('http://here/', '

Stuff

'); - $this->assertIdentical($page->getUrls(), array()); - } - - function testAddAbsoluteLink() { - $page = $this->whenVisiting('http://host', - 'Label'); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://somewhere.com'))); - } - - function testUrlLabelsHaveHtmlTagsStripped() { - $page = $this->whenVisiting('http://host', - 'Label'); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://somewhere.com'))); - } - - function testAddStrictRelativeLink() { - $page = $this->whenVisiting('http://host', - 'Label'); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://host/somewhere.php'))); - } - - function testAddBareRelativeLink() { - $page = $this->whenVisiting('http://host', - 'Label'); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://host/somewhere.php'))); - } - - function testAddRelativeLinkWithBaseTag() { - $raw = '' . - 'Label' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://www.lastcraft.com/stuff/somewhere.php'))); - } - - function testAddAbsoluteLinkWithBaseTag() { - $raw = '' . - 'Label' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://here.com/somewhere.php'))); - } - - function testCanFindLinkInsideForm() { - $raw = '
Label'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://host/somewhere.php'))); - } - - function testCanGetLinksByIdOrLabel() { - $raw = 'Label'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual( - $page->getUrlsByLabel('Label'), - array(new SimpleUrl('http://host/somewhere.php'))); - $this->assertFalse($page->getUrlById(0)); - $this->assertEqual( - $page->getUrlById(33), - new SimpleUrl('http://host/somewhere.php')); - } - - function testCanFindLinkByNormalisedLabel() { - $raw = 'Long & thin'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual( - $page->getUrlsByLabel('Long & thin'), - array(new SimpleUrl('http://host/somewhere.php'))); - } - - function testCanFindLinkByImageAltText() { - $raw = '<A picture>'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual( - array_map(array($this, 'urlToString'), $page->getUrlsByLabel('')), - array('http://host/somewhere.php')); - } - - function testTitle() { - $page = $this->whenVisiting('http://host', - 'Me'); - $this->assertEqual($page->getTitle(), 'Me'); - } - - function testTitleWithEntityReference() { - $page = $this->whenVisiting('http://host', - 'Me&Me'); - $this->assertEqual($page->getTitle(), "Me&Me"); - } - - function testOnlyFramesInFramesetAreRecognised() { - $raw = - '' . - ' ' . - ' ' . - '' . - ''; - $page = $this->whenVisiting('http://here', $raw); - $this->assertTrue($page->hasFrames()); - $this->assertSameFrameset($page->getFrameset(), array( - 1 => new SimpleUrl('http://here/2.html'), - 2 => new SimpleUrl('http://here/3.html'))); - } - - function testReadsNamesInFrames() { - $raw = - '' . - ' ' . - ' ' . - ' ' . - ' ' . - ''; - $page = $this->whenVisiting('http://here', $raw); - $this->assertTrue($page->hasFrames()); - $this->assertSameFrameset($page->getFrameset(), array( - 1 => new SimpleUrl('http://here/1.html'), - 'A' => new SimpleUrl('http://here/2.html'), - 'B' => new SimpleUrl('http://here/3.html'), - 4 => new SimpleUrl('http://here/4.html'))); - } - - function testRelativeFramesRespectBaseTag() { - $raw = ''; - $page = $this->whenVisiting('http://here', $raw); - $this->assertSameFrameset( - $page->getFrameset(), - array(1 => new SimpleUrl('https://there.com/stuff/1.html'))); - } - - function testSingleFrameInNestedFrameset() { - $raw = '' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->hasFrames()); - $this->assertIdentical( - $page->getFrameset(), - array(1 => new SimpleUrl('http://host/a.html'))); - } - - function testFramesCollectedWithNestedFramesetTags() { - $raw = '' . - '' . - '' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->hasFrames()); - $this->assertIdentical($page->getFrameset(), array( - 1 => new SimpleUrl('http://host/a.html'), - 2 => new SimpleUrl('http://host/b.html'), - 3 => new SimpleUrl('http://host/c.html'))); - } - - function testNamedFrames() { - $raw = '' . - '' . - '' . - '' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->hasFrames()); - $this->assertIdentical($page->getFrameset(), array( - 1 => new SimpleUrl('http://host/a.html'), - '_one' => new SimpleUrl('http://host/b.html'), - 3 => new SimpleUrl('http://host/c.html'), - '_two' => new SimpleUrl('http://host/d.html'))); - } - - function testCanReadElementOfCompleteForm() { - $raw = '
' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('here')), "Hello"); - } - - function testCanReadElementOfUnclosedForm() { - $raw = '
' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('here')), "Hello"); - } - - function testCanReadElementByLabel() { - $raw = '' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('Where')), "Hello"); - } - - function testCanFindFormByLabel() { - $raw = ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertNull($page->getFormBySubmit(new SimpleByLabel('submit'))); - $this->assertNull($page->getFormBySubmit(new SimpleByName('submit'))); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByLabel('Submit')), - 'SimpleForm'); - } - - function testConfirmSubmitAttributesAreCaseSensitive() { - $raw = '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByName('S')), - 'SimpleForm'); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByLabel('S')), - 'SimpleForm'); - } - - function testCanFindFormByImage() { - $raw = '
' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertIsA( - $page->getFormByImage(new SimpleByLabel('Label')), - 'SimpleForm'); - $this->assertIsA( - $page->getFormByImage(new SimpleByName('me')), - 'SimpleForm'); - $this->assertIsA( - $page->getFormByImage(new SimpleById(100)), - 'SimpleForm'); - } - - function testCanFindFormByButtonTag() { - $raw = '
' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertNull($page->getFormBySubmit(new SimpleByLabel('b'))); - $this->assertNull($page->getFormBySubmit(new SimpleByLabel('B'))); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByName('b')), - 'SimpleForm'); - $this->assertIsA( - $page->getFormBySubmit(new SimpleByLabel('BBB')), - 'SimpleForm'); - } - - function testCanFindFormById() { - $raw = '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertNull($page->getFormById(54)); - $this->assertIsA($page->getFormById(55), 'SimpleForm'); - } - - function testFormCanBeSubmitted() { - $raw = '
' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $form = $page->getFormBySubmit(new SimpleByLabel('Submit')); - $this->assertEqual( - $form->submitButton(new SimpleByLabel('Submit')), - new SimpleGetEncoding(array('s' => 'Submit'))); - } - - function testUnparsedTagDoesNotCrash() { - $raw = '
'; - $this->whenVisiting('http://host', $raw); - } - - function testReadingTextField() { - $raw = '
' . - '' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertNull($page->getField(new SimpleByName('missing'))); - $this->assertIdentical($page->getField(new SimpleByName('a')), ''); - $this->assertIdentical($page->getField(new SimpleByName('b')), 'bbb'); - } - - function testEntitiesAreDecodedInDefaultTextFieldValue() { - $raw = '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), '&\'"<>'); - } - - function testReadingTextFieldIsCaseInsensitive() { - $raw = '
' . - '' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertNull($page->getField(new SimpleByName('missing'))); - $this->assertIdentical($page->getField(new SimpleByName('a')), ''); - $this->assertIdentical($page->getField(new SimpleByName('b')), 'bbb'); - } - - function testSettingTextField() { - $raw = '
' . - '' . - '' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByName('a'), 'aaa')); - $this->assertEqual($page->getField(new SimpleByName('a')), 'aaa'); - $this->assertTrue($page->setField(new SimpleById(3), 'bbb')); - $this->assertEqual($page->getField(new SimpleBYId(3)), 'bbb'); - $this->assertFalse($page->setField(new SimpleByName('z'), 'zzz')); - $this->assertNull($page->getField(new SimpleByName('z'))); - } - - function testSettingTextFieldByEnclosingLabel() { - $raw = '
' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), 'A'); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); - $this->assertTrue($page->setField(new SimpleByLabel('Stuff'), 'aaa')); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'aaa'); - } - - function testLabelsWithoutForDoNotAttachToInputsWithNoId() { - $raw = '
- - - '; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabelOrName('Text A')), 'one'); - $this->assertEqual($page->getField(new SimpleByLabelOrName('Text B')), 'two'); - $this->assertTrue($page->setField(new SimpleByLabelOrName('Text A'), '1')); - $this->assertTrue($page->setField(new SimpleByLabelOrName('Text B'), '2')); - $this->assertEqual($page->getField(new SimpleByLabelOrName('Text A')), '1'); - $this->assertEqual($page->getField(new SimpleByLabelOrName('Text B')), '2'); - } - - function testGettingTextFieldByEnclosingLabelWithConflictingOtherFields() { - $raw = '
' . - '' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), 'A'); - $this->assertEqual($page->getField(new SimpleByName('b')), 'B'); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); - } - - function testSettingTextFieldByExternalLabel() { - $raw = '
' . - '' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); - $this->assertTrue($page->setField(new SimpleByLabel('Stuff'), 'aaa')); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'aaa'); - } - - function testReadingTextArea() { - $raw = '
' . - '' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), 'aaa'); - } - - function testEntitiesAreDecodedInTextareaValue() { - $raw = '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), '&\'"<>'); - } - - function testNewlinesPreservedInTextArea() { - $raw = "
"; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), "hello\r\nworld"); - } - - function testWhitespacePreservedInTextArea() { - $raw = '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), ' '); - } - - function testComplexWhitespaceInTextArea() { - $raw = "\n" . - " \n" . - " \n" . - "
\n". - " \n" . - " \n" . - " \n" . - ""; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('c')), " "); - } - - function testSettingTextArea() { - $raw = '
' . - '' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByName('a'), 'AAA')); - $this->assertEqual($page->getField(new SimpleByName('a')), 'AAA'); - } - - function testDontIncludeTextAreaContentInLabel() { - $raw = '
'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('Text area C')), 'mouse'); - } - - function testSettingSelectionField() { - $raw = '
' . - '' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), 'bbb'); - $this->assertFalse($page->setField(new SimpleByName('a'), 'ccc')); - $this->assertTrue($page->setField(new SimpleByName('a'), 'aaa')); - $this->assertEqual($page->getField(new SimpleByName('a')), 'aaa'); - } - - function testSelectionOptionsAreNormalised() { - $raw = '
' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('a')), 'Big bold'); - $this->assertTrue($page->setField(new SimpleByName('a'), 'small italic')); - $this->assertEqual($page->getField(new SimpleByName('a')), 'small italic'); - } - - function testCanParseBlankOptions() { - $raw = '
- - '; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByName('d'), '')); - } - - function testTwoSelectionFieldsAreIndependent() { - $raw = '
- - - '; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByName('d'), 'd2')); - $this->assertTrue($page->setField(new SimpleByName('h'), 'h1')); - $this->assertEqual($page->getField(new SimpleByName('d')), 'd2'); - } - - function testEmptyOptionDoesNotScrewUpTwoSelectionFields() { - $raw = '
- - - '; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByName('d'), 'd2')); - $this->assertTrue($page->setField(new SimpleByName('h'), 'h1')); - $this->assertEqual($page->getField(new SimpleByName('d')), 'd2'); - } - - function testSettingSelectionFieldByEnclosingLabel() { - $raw = '
' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'A'); - $this->assertTrue($page->setField(new SimpleByLabel('Stuff'), 'B')); - $this->assertEqual($page->getField(new SimpleByLabel('Stuff')), 'B'); - } - - function testTwoSelectionFieldsWithLabelsAreIndependent() { - $raw = '
- - - '; - $page = $this->whenVisiting('http://host', $raw); - $this->assertTrue($page->setField(new SimpleByLabel('Labelled D'), 'd2')); - $this->assertTrue($page->setField(new SimpleByLabel('Labelled H'), 'h1')); - $this->assertEqual($page->getField(new SimpleByLabel('Labelled D')), 'd2'); - } - - function testSettingRadioButtonByEnclosingLabel() { - $raw = '
' . - '' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('A')), 'a'); - $this->assertTrue($page->setField(new SimpleBylabel('B'), 'b')); - $this->assertEqual($page->getField(new SimpleByLabel('B')), 'b'); - } - - function testCanParseInputsWithAllKindsOfAttributeQuoting() { - $raw = '
' . - '' . - '' . - '' . - ''; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByName('first')), 'one'); - $this->assertEqual($page->getField(new SimpleByName('second')), false); - $this->assertEqual($page->getField(new SimpleByName('third')), 'three'); - } - - function urlToString($url) { - return $url->asString(); - } - - function assertSameFrameset($actual, $expected) { - $this->assertIdentical(array_map(array($this, 'urlToString'), $actual), - array_map(array($this, 'urlToString'), $expected)); - } -} - -class TestOfParsingUsingPhpParser extends TestOfParsing { - - function whenVisiting($url, $content) { - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', $content); - $response->setReturnValue('getUrl', new SimpleUrl($url)); - $builder = new SimplePhpPageBuilder(); - return $builder->parse($response); - } - - function testNastyTitle() { - $page = $this->whenVisiting('http://host', - ' <b>Me&Me '); - $this->assertEqual($page->getTitle(), "Me&Me"); - } - - function testLabelShouldStopAtClosingLabelTag() { - $raw = '
stuff'; - $page = $this->whenVisiting('http://host', $raw); - $this->assertEqual($page->getField(new SimpleByLabel('startend')), 'stuff'); - } -} - -class TestOfParsingUsingTidyParser extends TestOfParsing { - - function skip() { - $this->skipUnless(extension_loaded('tidy'), 'Install \'tidy\' php extension to enable html tidy based parser'); - } - - function whenVisiting($url, $content) { - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', $content); - $response->setReturnValue('getUrl', new SimpleUrl($url)); - $builder = new SimpleTidyPageBuilder(); - return $builder->parse($response); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/php_parser_test.php b/3rdparty/simpletest/test/php_parser_test.php deleted file mode 100644 index d95c7d06a60efd0f56ce6e899e5d21fc814922aa..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/php_parser_test.php +++ /dev/null @@ -1,489 +0,0 @@ -assertFalse($regex->match("Hello", $match)); - $this->assertEqual($match, ""); - } - - function testNoSubject() { - $regex = new ParallelRegex(false); - $regex->addPattern(".*"); - $this->assertTrue($regex->match("", $match)); - $this->assertEqual($match, ""); - } - - function testMatchAll() { - $regex = new ParallelRegex(false); - $regex->addPattern(".*"); - $this->assertTrue($regex->match("Hello", $match)); - $this->assertEqual($match, "Hello"); - } - - function testCaseSensitive() { - $regex = new ParallelRegex(true); - $regex->addPattern("abc"); - $this->assertTrue($regex->match("abcdef", $match)); - $this->assertEqual($match, "abc"); - $this->assertTrue($regex->match("AAABCabcdef", $match)); - $this->assertEqual($match, "abc"); - } - - function testCaseInsensitive() { - $regex = new ParallelRegex(false); - $regex->addPattern("abc"); - $this->assertTrue($regex->match("abcdef", $match)); - $this->assertEqual($match, "abc"); - $this->assertTrue($regex->match("AAABCabcdef", $match)); - $this->assertEqual($match, "ABC"); - } - - function testMatchMultiple() { - $regex = new ParallelRegex(true); - $regex->addPattern("abc"); - $regex->addPattern("ABC"); - $this->assertTrue($regex->match("abcdef", $match)); - $this->assertEqual($match, "abc"); - $this->assertTrue($regex->match("AAABCabcdef", $match)); - $this->assertEqual($match, "ABC"); - $this->assertFalse($regex->match("Hello", $match)); - } - - function testPatternLabels() { - $regex = new ParallelRegex(false); - $regex->addPattern("abc", "letter"); - $regex->addPattern("123", "number"); - $this->assertIdentical($regex->match("abcdef", $match), "letter"); - $this->assertEqual($match, "abc"); - $this->assertIdentical($regex->match("0123456789", $match), "number"); - $this->assertEqual($match, "123"); - } -} - -class TestOfStateStack extends UnitTestCase { - - function testStartState() { - $stack = new SimpleStateStack("one"); - $this->assertEqual($stack->getCurrent(), "one"); - } - - function testExhaustion() { - $stack = new SimpleStateStack("one"); - $this->assertFalse($stack->leave()); - } - - function testStateMoves() { - $stack = new SimpleStateStack("one"); - $stack->enter("two"); - $this->assertEqual($stack->getCurrent(), "two"); - $stack->enter("three"); - $this->assertEqual($stack->getCurrent(), "three"); - $this->assertTrue($stack->leave()); - $this->assertEqual($stack->getCurrent(), "two"); - $stack->enter("third"); - $this->assertEqual($stack->getCurrent(), "third"); - $this->assertTrue($stack->leave()); - $this->assertTrue($stack->leave()); - $this->assertEqual($stack->getCurrent(), "one"); - } -} - -class TestParser { - - function accept() { - } - - function a() { - } - - function b() { - } -} -Mock::generate('TestParser'); - -class TestOfLexer extends UnitTestCase { - - function testEmptyPage() { - $handler = new MockTestParser(); - $handler->expectNever("accept"); - $handler->setReturnValue("accept", true); - $handler->expectNever("accept"); - $handler->setReturnValue("accept", true); - $lexer = new SimpleLexer($handler); - $lexer->addPattern("a+"); - $this->assertTrue($lexer->parse("")); - } - - function testSinglePattern() { - $handler = new MockTestParser(); - $handler->expectAt(0, "accept", array("aaa", LEXER_MATCHED)); - $handler->expectAt(1, "accept", array("x", LEXER_UNMATCHED)); - $handler->expectAt(2, "accept", array("a", LEXER_MATCHED)); - $handler->expectAt(3, "accept", array("yyy", LEXER_UNMATCHED)); - $handler->expectAt(4, "accept", array("a", LEXER_MATCHED)); - $handler->expectAt(5, "accept", array("x", LEXER_UNMATCHED)); - $handler->expectAt(6, "accept", array("aaa", LEXER_MATCHED)); - $handler->expectAt(7, "accept", array("z", LEXER_UNMATCHED)); - $handler->expectCallCount("accept", 8); - $handler->setReturnValue("accept", true); - $lexer = new SimpleLexer($handler); - $lexer->addPattern("a+"); - $this->assertTrue($lexer->parse("aaaxayyyaxaaaz")); - } - - function testMultiplePattern() { - $handler = new MockTestParser(); - $target = array("a", "b", "a", "bb", "x", "b", "a", "xxxxxx", "a", "x"); - for ($i = 0; $i < count($target); $i++) { - $handler->expectAt($i, "accept", array($target[$i], '*')); - } - $handler->expectCallCount("accept", count($target)); - $handler->setReturnValue("accept", true); - $lexer = new SimpleLexer($handler); - $lexer->addPattern("a+"); - $lexer->addPattern("b+"); - $this->assertTrue($lexer->parse("ababbxbaxxxxxxax")); - } -} - -class TestOfLexerModes extends UnitTestCase { - - function testIsolatedPattern() { - $handler = new MockTestParser(); - $handler->expectAt(0, "a", array("a", LEXER_MATCHED)); - $handler->expectAt(1, "a", array("b", LEXER_UNMATCHED)); - $handler->expectAt(2, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(3, "a", array("bxb", LEXER_UNMATCHED)); - $handler->expectAt(4, "a", array("aaa", LEXER_MATCHED)); - $handler->expectAt(5, "a", array("x", LEXER_UNMATCHED)); - $handler->expectAt(6, "a", array("aaaa", LEXER_MATCHED)); - $handler->expectAt(7, "a", array("x", LEXER_UNMATCHED)); - $handler->expectCallCount("a", 8); - $handler->setReturnValue("a", true); - $lexer = new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addPattern("b+", "b"); - $this->assertTrue($lexer->parse("abaabxbaaaxaaaax")); - } - - function testModeChange() { - $handler = new MockTestParser(); - $handler->expectAt(0, "a", array("a", LEXER_MATCHED)); - $handler->expectAt(1, "a", array("b", LEXER_UNMATCHED)); - $handler->expectAt(2, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(3, "a", array("b", LEXER_UNMATCHED)); - $handler->expectAt(4, "a", array("aaa", LEXER_MATCHED)); - $handler->expectAt(0, "b", array(":", LEXER_ENTER)); - $handler->expectAt(1, "b", array("a", LEXER_UNMATCHED)); - $handler->expectAt(2, "b", array("b", LEXER_MATCHED)); - $handler->expectAt(3, "b", array("a", LEXER_UNMATCHED)); - $handler->expectAt(4, "b", array("bb", LEXER_MATCHED)); - $handler->expectAt(5, "b", array("a", LEXER_UNMATCHED)); - $handler->expectAt(6, "b", array("bbb", LEXER_MATCHED)); - $handler->expectAt(7, "b", array("a", LEXER_UNMATCHED)); - $handler->expectCallCount("a", 5); - $handler->expectCallCount("b", 8); - $handler->setReturnValue("a", true); - $handler->setReturnValue("b", true); - $lexer = new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addEntryPattern(":", "a", "b"); - $lexer->addPattern("b+", "b"); - $this->assertTrue($lexer->parse("abaabaaa:ababbabbba")); - } - - function testNesting() { - $handler = new MockTestParser(); - $handler->setReturnValue("a", true); - $handler->setReturnValue("b", true); - $handler->expectAt(0, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(1, "a", array("b", LEXER_UNMATCHED)); - $handler->expectAt(2, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(3, "a", array("b", LEXER_UNMATCHED)); - $handler->expectAt(0, "b", array("(", LEXER_ENTER)); - $handler->expectAt(1, "b", array("bb", LEXER_MATCHED)); - $handler->expectAt(2, "b", array("a", LEXER_UNMATCHED)); - $handler->expectAt(3, "b", array("bb", LEXER_MATCHED)); - $handler->expectAt(4, "b", array(")", LEXER_EXIT)); - $handler->expectAt(4, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(5, "a", array("b", LEXER_UNMATCHED)); - $handler->expectCallCount("a", 6); - $handler->expectCallCount("b", 5); - $lexer = new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addEntryPattern("(", "a", "b"); - $lexer->addPattern("b+", "b"); - $lexer->addExitPattern(")", "b"); - $this->assertTrue($lexer->parse("aabaab(bbabb)aab")); - } - - function testSingular() { - $handler = new MockTestParser(); - $handler->setReturnValue("a", true); - $handler->setReturnValue("b", true); - $handler->expectAt(0, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(1, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(2, "a", array("xx", LEXER_UNMATCHED)); - $handler->expectAt(3, "a", array("xx", LEXER_UNMATCHED)); - $handler->expectAt(0, "b", array("b", LEXER_SPECIAL)); - $handler->expectAt(1, "b", array("bbb", LEXER_SPECIAL)); - $handler->expectCallCount("a", 4); - $handler->expectCallCount("b", 2); - $lexer = new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addSpecialPattern("b+", "a", "b"); - $this->assertTrue($lexer->parse("aabaaxxbbbxx")); - } - - function testUnwindTooFar() { - $handler = new MockTestParser(); - $handler->setReturnValue("a", true); - $handler->expectAt(0, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(1, "a", array(")", LEXER_EXIT)); - $handler->expectCallCount("a", 2); - $lexer = new SimpleLexer($handler, "a"); - $lexer->addPattern("a+", "a"); - $lexer->addExitPattern(")", "a"); - $this->assertFalse($lexer->parse("aa)aa")); - } -} - -class TestOfLexerHandlers extends UnitTestCase { - - function testModeMapping() { - $handler = new MockTestParser(); - $handler->setReturnValue("a", true); - $handler->expectAt(0, "a", array("aa", LEXER_MATCHED)); - $handler->expectAt(1, "a", array("(", LEXER_ENTER)); - $handler->expectAt(2, "a", array("bb", LEXER_MATCHED)); - $handler->expectAt(3, "a", array("a", LEXER_UNMATCHED)); - $handler->expectAt(4, "a", array("bb", LEXER_MATCHED)); - $handler->expectAt(5, "a", array(")", LEXER_EXIT)); - $handler->expectAt(6, "a", array("b", LEXER_UNMATCHED)); - $handler->expectCallCount("a", 7); - $lexer = new SimpleLexer($handler, "mode_a"); - $lexer->addPattern("a+", "mode_a"); - $lexer->addEntryPattern("(", "mode_a", "mode_b"); - $lexer->addPattern("b+", "mode_b"); - $lexer->addExitPattern(")", "mode_b"); - $lexer->mapHandler("mode_a", "a"); - $lexer->mapHandler("mode_b", "a"); - $this->assertTrue($lexer->parse("aa(bbabb)b")); - } -} - -class TestOfSimpleHtmlLexer extends UnitTestCase { - - function &createParser() { - $parser = new MockSimpleHtmlSaxParser(); - $parser->setReturnValue('acceptStartToken', true); - $parser->setReturnValue('acceptEndToken', true); - $parser->setReturnValue('acceptAttributeToken', true); - $parser->setReturnValue('acceptEntityToken', true); - $parser->setReturnValue('acceptTextToken', true); - $parser->setReturnValue('ignore', true); - return $parser; - } - - function testNoContent() { - $parser = $this->createParser(); - $parser->expectNever('acceptStartToken'); - $parser->expectNever('acceptEndToken'); - $parser->expectNever('acceptAttributeToken'); - $parser->expectNever('acceptEntityToken'); - $parser->expectNever('acceptTextToken'); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse('')); - } - - function testUninteresting() { - $parser = $this->createParser(); - $parser->expectOnce('acceptTextToken', array('', '*')); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse('')); - } - - function testSkipCss() { - $parser = $this->createParser(); - $parser->expectNever('acceptTextToken'); - $parser->expectAtLeastOnce('ignore'); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse("")); - } - - function testSkipJavaScript() { - $parser = $this->createParser(); - $parser->expectNever('acceptTextToken'); - $parser->expectAtLeastOnce('ignore'); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse("")); - } - - function testSkipHtmlComments() { - $parser = $this->createParser(); - $parser->expectNever('acceptTextToken'); - $parser->expectAtLeastOnce('ignore'); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse("")); - } - - function testTagWithNoAttributes() { - $parser = $this->createParser(); - $parser->expectAt(0, 'acceptStartToken', array('expectAt(1, 'acceptStartToken', array('>', '*')); - $parser->expectCallCount('acceptStartToken', 2); - $parser->expectOnce('acceptTextToken', array('Hello', '*')); - $parser->expectOnce('acceptEndToken', array('', '*')); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse('Hello')); - } - - function testTagWithAttributes() { - $parser = $this->createParser(); - $parser->expectOnce('acceptTextToken', array('label', '*')); - $parser->expectAt(0, 'acceptStartToken', array('expectAt(1, 'acceptStartToken', array('href', '*')); - $parser->expectAt(2, 'acceptStartToken', array('>', '*')); - $parser->expectCallCount('acceptStartToken', 3); - $parser->expectAt(0, 'acceptAttributeToken', array('= "', '*')); - $parser->expectAt(1, 'acceptAttributeToken', array('here.html', '*')); - $parser->expectAt(2, 'acceptAttributeToken', array('"', '*')); - $parser->expectCallCount('acceptAttributeToken', 3); - $parser->expectOnce('acceptEndToken', array('
', '*')); - $lexer = new SimpleHtmlLexer($parser); - $this->assertTrue($lexer->parse('label')); - } -} - -class TestOfHtmlSaxParser extends UnitTestCase { - - function createListener() { - $listener = new MockSimplePhpPageBuilder(); - $listener->setReturnValue('startElement', true); - $listener->setReturnValue('addContent', true); - $listener->setReturnValue('endElement', true); - return $listener; - } - - function testFramesetTag() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('frameset', array())); - $listener->expectOnce('addContent', array('Frames')); - $listener->expectOnce('endElement', array('frameset')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('Frames')); - } - - function testTagWithUnquotedAttributes() { - $listener = $this->createListener(); - $listener->expectOnce( - 'startElement', - array('input', array('name' => 'a.b.c', 'value' => 'd'))); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('')); - } - - function testTagInsideContent() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('a', array())); - $listener->expectAt(0, 'addContent', array('')); - $listener->expectAt(1, 'addContent', array('')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('')); - } - - function testTagWithInternalContent() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('a', array())); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('label')); - } - - function testLinkAddress() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('a', array('href' => 'here.html'))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse("label")); - } - - function testEncodedAttribute() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('a', array('href' => 'here&there.html'))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse("label")); - } - - function testTagWithId() { - $listener = $this->createListener(); - $listener->expectOnce('startElement', array('a', array('id' => '0'))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('label')); - } - - function testTagWithEmptyAttributes() { - $listener = $this->createListener(); - $listener->expectOnce( - 'startElement', - array('option', array('value' => '', 'selected' => ''))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('option')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('')); - } - - function testComplexTagWithLotsOfCaseVariations() { - $listener = $this->createListener(); - $listener->expectOnce( - 'startElement', - array('a', array('href' => 'here.html', 'style' => "'cool'"))); - $listener->expectOnce('addContent', array('label')); - $listener->expectOnce('endElement', array('a')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('label')); - } - - function testXhtmlSelfClosingTag() { - $listener = $this->createListener(); - $listener->expectOnce( - 'startElement', - array('input', array('type' => 'submit', 'name' => 'N', 'value' => 'V'))); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse('')); - } - - function testNestedFrameInFrameset() { - $listener = $this->createListener(); - $listener->expectAt(0, 'startElement', array('frameset', array())); - $listener->expectAt(1, 'startElement', array('frame', array('src' => 'frame.html'))); - $listener->expectCallCount('startElement', 2); - $listener->expectOnce('addContent', array('Hello')); - $listener->expectOnce('endElement', array('frameset')); - $parser = new SimpleHtmlSaxParser($listener); - $this->assertTrue($parser->parse( - 'Hello')); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/recorder_test.php b/3rdparty/simpletest/test/recorder_test.php deleted file mode 100644 index fdae4c1cccce69cfbca77e650180310fb58a446d..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/recorder_test.php +++ /dev/null @@ -1,23 +0,0 @@ -addFile(dirname(__FILE__) . '/support/recorder_sample.php'); - $recorder = new Recorder(new SimpleReporter()); - $test->run($recorder); - $this->assertEqual(count($recorder->results), 2); - $this->assertIsA($recorder->results[0], 'SimpleResultOfPass'); - $this->assertEqual('testTrueIsTrue', array_pop($recorder->results[0]->breadcrumb)); - $this->assertPattern('/ at \[.*\Wrecorder_sample\.php line 7\]/', $recorder->results[0]->message); - $this->assertIsA($recorder->results[1], 'SimpleResultOfFail'); - $this->assertEqual('testFalseIsTrue', array_pop($recorder->results[1]->breadcrumb)); - $this->assertPattern("/Expected false, got \[Boolean: true\] at \[.*\Wrecorder_sample\.php line 11\]/", - $recorder->results[1]->message); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/reflection_php5_test.php b/3rdparty/simpletest/test/reflection_php5_test.php deleted file mode 100644 index d9f46e6db78c886a543996b93543744b19ef6e1c..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/reflection_php5_test.php +++ /dev/null @@ -1,263 +0,0 @@ -assertTrue($reflection->classOrInterfaceExists()); - $this->assertTrue($reflection->classOrInterfaceExistsSansAutoload()); - $this->assertFalse($reflection->isAbstract()); - $this->assertFalse($reflection->isInterface()); - } - - function testClassNonExistence() { - $reflection = new SimpleReflection('UnknownThing'); - $this->assertFalse($reflection->classOrInterfaceExists()); - $this->assertFalse($reflection->classOrInterfaceExistsSansAutoload()); - } - - function testDetectionOfAbstractClass() { - $reflection = new SimpleReflection('AnyOldClass'); - $this->assertTrue($reflection->isAbstract()); - } - - function testDetectionOfFinalMethods() { - $reflection = new SimpleReflection('AnyOldClass'); - $this->assertFalse($reflection->hasFinal()); - $reflection = new SimpleReflection('AnyOldLeafClassWithAFinal'); - $this->assertTrue($reflection->hasFinal()); - } - - function testFindingParentClass() { - $reflection = new SimpleReflection('AnyOldSubclass'); - $this->assertEqual($reflection->getParent(), 'AnyOldImplementation'); - } - - function testInterfaceExistence() { - $reflection = new SimpleReflection('AnyOldInterface'); - $this->assertTrue($reflection->classOrInterfaceExists()); - $this->assertTrue($reflection->classOrInterfaceExistsSansAutoload()); - $this->assertTrue($reflection->isInterface()); - } - - function testMethodsListFromClass() { - $reflection = new SimpleReflection('AnyOldClass'); - $this->assertIdentical($reflection->getMethods(), array('aMethod')); - } - - function testMethodsListFromInterface() { - $reflection = new SimpleReflection('AnyOldInterface'); - $this->assertIdentical($reflection->getMethods(), array('aMethod')); - $this->assertIdentical($reflection->getInterfaceMethods(), array('aMethod')); - } - - function testMethodsComeFromDescendentInterfacesASWell() { - $reflection = new SimpleReflection('AnyDescendentInterface'); - $this->assertIdentical($reflection->getMethods(), array('aMethod')); - } - - function testCanSeparateInterfaceMethodsFromOthers() { - $reflection = new SimpleReflection('AnyOldImplementation'); - $this->assertIdentical($reflection->getMethods(), array('aMethod', 'extraMethod')); - $this->assertIdentical($reflection->getInterfaceMethods(), array('aMethod')); - } - - function testMethodsComeFromDescendentInterfacesInAbstractClass() { - $reflection = new SimpleReflection('AnyAbstractImplementation'); - $this->assertIdentical($reflection->getMethods(), array('aMethod')); - } - - function testInterfaceHasOnlyItselfToImplement() { - $reflection = new SimpleReflection('AnyOldInterface'); - $this->assertEqual( - $reflection->getInterfaces(), - array('AnyOldInterface')); - } - - function testInterfacesListedForClass() { - $reflection = new SimpleReflection('AnyOldImplementation'); - $this->assertEqual( - $reflection->getInterfaces(), - array('AnyOldInterface')); - } - - function testInterfacesListedForSubclass() { - $reflection = new SimpleReflection('AnyOldSubclass'); - $this->assertEqual( - $reflection->getInterfaces(), - array('AnyOldInterface')); - } - - function testNoParameterCreationWhenNoInterface() { - $reflection = new SimpleReflection('AnyOldArgumentClass'); - $function = $reflection->getSignature('aMethod'); - if (version_compare(phpversion(), '5.0.2', '<=')) { - $this->assertEqual('function amethod($argument)', strtolower($function)); - } else { - $this->assertEqual('function aMethod($argument)', $function); - } - } - - function testParameterCreationWithoutTypeHinting() { - $reflection = new SimpleReflection('AnyOldArgumentImplementation'); - $function = $reflection->getSignature('aMethod'); - if (version_compare(phpversion(), '5.0.2', '<=')) { - $this->assertEqual('function amethod(AnyOldInterface $argument)', $function); - } else { - $this->assertEqual('function aMethod(AnyOldInterface $argument)', $function); - } - } - - function testParameterCreationForTypeHinting() { - $reflection = new SimpleReflection('AnyOldTypeHintedClass'); - $function = $reflection->getSignature('aMethod'); - if (version_compare(phpversion(), '5.0.2', '<=')) { - $this->assertEqual('function amethod(AnyOldInterface $argument)', $function); - } else { - $this->assertEqual('function aMethod(AnyOldInterface $argument)', $function); - } - } - - function testIssetFunctionSignature() { - $reflection = new SimpleReflection('AnyOldOverloadedClass'); - $function = $reflection->getSignature('__isset'); - $this->assertEqual('function __isset($key)', $function); - } - - function testUnsetFunctionSignature() { - $reflection = new SimpleReflection('AnyOldOverloadedClass'); - $function = $reflection->getSignature('__unset'); - $this->assertEqual('function __unset($key)', $function); - } - - function testProperlyReflectsTheFinalInterfaceWhenObjectImplementsAnExtendedInterface() { - $reflection = new SimpleReflection('AnyDescendentImplementation'); - $interfaces = $reflection->getInterfaces(); - $this->assertEqual(1, count($interfaces)); - $this->assertEqual('AnyDescendentInterface', array_shift($interfaces)); - } - - function testCreatingSignatureForAbstractMethod() { - $reflection = new SimpleReflection('AnotherOldAbstractClass'); - $this->assertEqual($reflection->getSignature('aMethod'), 'function aMethod(AnyOldInterface $argument)'); - } - - function testCanProperlyGenerateStaticMethodSignatures() { - $reflection = new SimpleReflection('AnyOldClassWithStaticMethods'); - $this->assertEqual('static function aStatic()', $reflection->getSignature('aStatic')); - $this->assertEqual( - 'static function aStaticWithParameters($arg1, $arg2)', - $reflection->getSignature('aStaticWithParameters') - ); - } -} - -class TestOfReflectionWithTypeHints extends UnitTestCase { - function skip() { - $this->skipIf(version_compare(phpversion(), '5.1.0', '<'), 'Reflection with type hints only tested for PHP 5.1.0 and above'); - } - - function testParameterCreationForTypeHintingWithArray() { - eval('interface AnyOldArrayTypeHintedInterface { - function amethod(array $argument); - } - class AnyOldArrayTypeHintedClass implements AnyOldArrayTypeHintedInterface { - function amethod(array $argument) {} - }'); - $reflection = new SimpleReflection('AnyOldArrayTypeHintedClass'); - $function = $reflection->getSignature('amethod'); - $this->assertEqual('function amethod(array $argument)', $function); - } -} - -class TestOfAbstractsWithAbstractMethods extends UnitTestCase { - function testCanProperlyGenerateAbstractMethods() { - $reflection = new SimpleReflection('AnyOldAbstractClassWithAbstractMethods'); - $this->assertEqual( - 'function anAbstract()', - $reflection->getSignature('anAbstract') - ); - $this->assertEqual( - 'function anAbstractWithParameter($foo)', - $reflection->getSignature('anAbstractWithParameter') - ); - $this->assertEqual( - 'function anAbstractWithMultipleParameters($foo, $bar)', - $reflection->getSignature('anAbstractWithMultipleParameters') - ); - } -} - -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/remote_test.php b/3rdparty/simpletest/test/remote_test.php deleted file mode 100644 index 5f3f96a4de9e176056b238e0fba78fa10ce2a117..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/remote_test.php +++ /dev/null @@ -1,19 +0,0 @@ -add(new RemoteTestCase($test_url . '?xml=yes', $test_url . '?xml=yes&dry=yes')); -if (SimpleReporter::inCli()) { - exit ($test->run(new TextReporter()) ? 0 : 1); -} -$test->run(new HtmlReporter()); diff --git a/3rdparty/simpletest/test/shell_test.php b/3rdparty/simpletest/test/shell_test.php deleted file mode 100644 index d1d769a679598999afad5f9c9876b731bd785d83..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/shell_test.php +++ /dev/null @@ -1,38 +0,0 @@ -assertIdentical($shell->execute('echo Hello'), 0); - $this->assertPattern('/Hello/', $shell->getOutput()); - } - - function testBadCommand() { - $shell = new SimpleShell(); - $this->assertNotEqual($ret = $shell->execute('blurgh! 2>&1'), 0); - } -} - -class TestOfShellTesterAndShell extends ShellTestCase { - - function testEcho() { - $this->assertTrue($this->execute('echo Hello')); - $this->assertExitCode(0); - $this->assertoutput('Hello'); - } - - function testFileExistence() { - $this->assertFileExists(dirname(__FILE__) . '/all_tests.php'); - $this->assertFileNotExists('wibble'); - } - - function testFilePatterns() { - $this->assertFilePattern('/all[_ ]tests/i', dirname(__FILE__) . '/all_tests.php'); - $this->assertNoFilePattern('/sputnik/i', dirname(__FILE__) . '/all_tests.php'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/shell_tester_test.php b/3rdparty/simpletest/test/shell_tester_test.php deleted file mode 100644 index b12c602a39fd23edbd190f3e84c9dd7c42b48ac1..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/shell_tester_test.php +++ /dev/null @@ -1,42 +0,0 @@ -mock_shell; - } - - function testGenericEquality() { - $this->assertEqual('a', 'a'); - $this->assertNotEqual('a', 'A'); - } - - function testExitCode() { - $this->mock_shell = new MockSimpleShell(); - $this->mock_shell->setReturnValue('execute', 0); - $this->mock_shell->expectOnce('execute', array('ls')); - $this->assertTrue($this->execute('ls')); - $this->assertExitCode(0); - } - - function testOutput() { - $this->mock_shell = new MockSimpleShell(); - $this->mock_shell->setReturnValue('execute', 0); - $this->mock_shell->setReturnValue('getOutput', "Line 1\nLine 2\n"); - $this->assertOutput("Line 1\nLine 2\n"); - } - - function testOutputPatterns() { - $this->mock_shell = new MockSimpleShell(); - $this->mock_shell->setReturnValue('execute', 0); - $this->mock_shell->setReturnValue('getOutput', "Line 1\nLine 2\n"); - $this->assertOutputPattern('/line/i'); - $this->assertNoOutputPattern('/line 2/'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/simpletest_test.php b/3rdparty/simpletest/test/simpletest_test.php deleted file mode 100644 index daa65c6f4726f707e274642ba5016248f7668f1e..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/simpletest_test.php +++ /dev/null @@ -1,58 +0,0 @@ -fail('Should be ignored'); - } -} - -class ShouldNeverBeRunEither extends ShouldNeverBeRun { } - -class TestOfStackTrace extends UnitTestCase { - - function testCanFindAssertInTrace() { - $trace = new SimpleStackTrace(array('assert')); - $this->assertEqual( - $trace->traceMethod(array(array( - 'file' => '/my_test.php', - 'line' => 24, - 'function' => 'assertSomething'))), - ' at [/my_test.php line 24]'); - } -} - -class DummyResource { } - -class TestOfContext extends UnitTestCase { - - function testCurrentContextIsUnique() { - $this->assertSame( - SimpleTest::getContext(), - SimpleTest::getContext()); - } - - function testContextHoldsCurrentTestCase() { - $context = SimpleTest::getContext(); - $this->assertSame($this, $context->getTest()); - } - - function testResourceIsSingleInstanceWithContext() { - $context = new SimpleTestContext(); - $this->assertSame( - $context->get('DummyResource'), - $context->get('DummyResource')); - } - - function testClearingContextResetsResources() { - $context = new SimpleTestContext(); - $resource = $context->get('DummyResource'); - $context->clear(); - $this->assertClone($resource, $context->get('DummyResource')); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/site/file.html b/3rdparty/simpletest/test/site/file.html deleted file mode 100644 index cc41aee1b8b638347b7ef84533b3714c44b12005..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/site/file.html +++ /dev/null @@ -1,6 +0,0 @@ - - Link to SimpleTest - - Link to SimpleTest - - \ No newline at end of file diff --git a/3rdparty/simpletest/test/socket_test.php b/3rdparty/simpletest/test/socket_test.php deleted file mode 100644 index 729adda4960d8e3e236bcaab3617348aa7321986..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/socket_test.php +++ /dev/null @@ -1,25 +0,0 @@ -assertFalse($error->isError()); - $error->setError('Ouch'); - $this->assertTrue($error->isError()); - $this->assertEqual($error->getError(), 'Ouch'); - } - - function testClearingError() { - $error = new SimpleStickyError(); - $error->setError('Ouch'); - $this->assertTrue($error->isError()); - $error->clearError(); - $this->assertFalse($error->isError()); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/collector/collectable.1 b/3rdparty/simpletest/test/support/collector/collectable.1 deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/3rdparty/simpletest/test/support/collector/collectable.2 b/3rdparty/simpletest/test/support/collector/collectable.2 deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/3rdparty/simpletest/test/support/empty_test_file.php b/3rdparty/simpletest/test/support/empty_test_file.php deleted file mode 100644 index 31e3f7bed620a0064bdbdb28716698e04dcdfe4f..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/support/empty_test_file.php +++ /dev/null @@ -1,3 +0,0 @@ - \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/failing_test.php b/3rdparty/simpletest/test/support/failing_test.php deleted file mode 100644 index 30f0d7507d9877d7804ff67c55391dfb880093c8..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/support/failing_test.php +++ /dev/null @@ -1,9 +0,0 @@ -assertEqual(1,2); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/latin1_sample b/3rdparty/simpletest/test/support/latin1_sample deleted file mode 100644 index 190352577660774b2d23243f9a1169b16fb53ad9..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/support/latin1_sample +++ /dev/null @@ -1 +0,0 @@ -@櫻 \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/passing_test.php b/3rdparty/simpletest/test/support/passing_test.php deleted file mode 100644 index b786321635357733a8356e9dd1911cb0a6d55d04..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/support/passing_test.php +++ /dev/null @@ -1,9 +0,0 @@ -assertEqual(2,2); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/recorder_sample.php b/3rdparty/simpletest/test/support/recorder_sample.php deleted file mode 100644 index 4f157f6b601312e8a0afe2617e1c4ef75565e9b6..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/support/recorder_sample.php +++ /dev/null @@ -1,14 +0,0 @@ -assertTrue(true); - } - - function testFalseIsTrue() { - $this->assertFalse(true); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/spl_examples.php b/3rdparty/simpletest/test/support/spl_examples.php deleted file mode 100644 index 45add356c445f3df47692b746a1cdd409446ff6d..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/support/spl_examples.php +++ /dev/null @@ -1,15 +0,0 @@ - \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/supplementary_upload_sample.txt b/3rdparty/simpletest/test/support/supplementary_upload_sample.txt deleted file mode 100644 index d8aa9e8101328e4d96244187a9a11a8f6d460478..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/support/supplementary_upload_sample.txt +++ /dev/null @@ -1 +0,0 @@ -Some more text content \ No newline at end of file diff --git a/3rdparty/simpletest/test/support/test1.php b/3rdparty/simpletest/test/support/test1.php deleted file mode 100644 index b414586d64212af6913d30eeadfec0f0d4817ad0..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/support/test1.php +++ /dev/null @@ -1,7 +0,0 @@ -assertEqual(3,1+2, "pass1"); - } -} -?> diff --git a/3rdparty/simpletest/test/support/upload_sample.txt b/3rdparty/simpletest/test/support/upload_sample.txt deleted file mode 100644 index ec98d7c5e3fe88d9be026122fc63e089aa504f56..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/support/upload_sample.txt +++ /dev/null @@ -1 +0,0 @@ -Sample for testing file upload \ No newline at end of file diff --git a/3rdparty/simpletest/test/tag_test.php b/3rdparty/simpletest/test/tag_test.php deleted file mode 100644 index 5e8a377f089cf7d3a79c8fef811aa27cb560c0a5..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/tag_test.php +++ /dev/null @@ -1,554 +0,0 @@ - '1', 'b' => '')); - $this->assertEqual($tag->getTagName(), 'title'); - $this->assertIdentical($tag->getAttribute('a'), '1'); - $this->assertIdentical($tag->getAttribute('b'), ''); - $this->assertIdentical($tag->getAttribute('c'), false); - $this->assertIdentical($tag->getContent(), ''); - } - - function testTitleContent() { - $tag = new SimpleTitleTag(array()); - $this->assertTrue($tag->expectEndTag()); - $tag->addContent('Hello'); - $tag->addContent('World'); - $this->assertEqual($tag->getText(), 'HelloWorld'); - } - - function testMessyTitleContent() { - $tag = new SimpleTitleTag(array()); - $this->assertTrue($tag->expectEndTag()); - $tag->addContent('Hello'); - $tag->addContent('World'); - $this->assertEqual($tag->getText(), 'HelloWorld'); - } - - function testTagWithNoEnd() { - $tag = new SimpleTextTag(array()); - $this->assertFalse($tag->expectEndTag()); - } - - function testAnchorHref() { - $tag = new SimpleAnchorTag(array('href' => 'http://here/')); - $this->assertEqual($tag->getHref(), 'http://here/'); - - $tag = new SimpleAnchorTag(array('href' => '')); - $this->assertIdentical($tag->getAttribute('href'), ''); - $this->assertIdentical($tag->getHref(), ''); - - $tag = new SimpleAnchorTag(array()); - $this->assertIdentical($tag->getAttribute('href'), false); - $this->assertIdentical($tag->getHref(), ''); - } - - function testIsIdMatchesIdAttribute() { - $tag = new SimpleAnchorTag(array('href' => 'http://here/', 'id' => 7)); - $this->assertIdentical($tag->getAttribute('id'), '7'); - $this->assertTrue($tag->isId(7)); - } -} - -class TestOfWidget extends UnitTestCase { - - function testTextEmptyDefault() { - $tag = new SimpleTextTag(array('type' => 'text')); - $this->assertIdentical($tag->getDefault(), ''); - $this->assertIdentical($tag->getValue(), ''); - } - - function testSettingOfExternalLabel() { - $tag = new SimpleTextTag(array('type' => 'text')); - $tag->setLabel('it'); - $this->assertTrue($tag->isLabel('it')); - } - - function testTextDefault() { - $tag = new SimpleTextTag(array('value' => 'aaa')); - $this->assertEqual($tag->getDefault(), 'aaa'); - $this->assertEqual($tag->getValue(), 'aaa'); - } - - function testSettingTextValue() { - $tag = new SimpleTextTag(array('value' => 'aaa')); - $tag->setValue('bbb'); - $this->assertEqual($tag->getValue(), 'bbb'); - $tag->resetValue(); - $this->assertEqual($tag->getValue(), 'aaa'); - } - - function testFailToSetHiddenValue() { - $tag = new SimpleTextTag(array('value' => 'aaa', 'type' => 'hidden')); - $this->assertFalse($tag->setValue('bbb')); - $this->assertEqual($tag->getValue(), 'aaa'); - } - - function testSubmitDefaults() { - $tag = new SimpleSubmitTag(array('type' => 'submit')); - $this->assertIdentical($tag->getName(), false); - $this->assertEqual($tag->getValue(), 'Submit'); - $this->assertFalse($tag->setValue('Cannot set this')); - $this->assertEqual($tag->getValue(), 'Submit'); - $this->assertEqual($tag->getLabel(), 'Submit'); - - $encoding = new MockSimpleMultipartEncoding(); - $encoding->expectNever('add'); - $tag->write($encoding); - } - - function testPopulatedSubmit() { - $tag = new SimpleSubmitTag( - array('type' => 'submit', 'name' => 's', 'value' => 'Ok!')); - $this->assertEqual($tag->getName(), 's'); - $this->assertEqual($tag->getValue(), 'Ok!'); - $this->assertEqual($tag->getLabel(), 'Ok!'); - - $encoding = new MockSimpleMultipartEncoding(); - $encoding->expectOnce('add', array('s', 'Ok!')); - $tag->write($encoding); - } - - function testImageSubmit() { - $tag = new SimpleImageSubmitTag( - array('type' => 'image', 'name' => 's', 'alt' => 'Label')); - $this->assertEqual($tag->getName(), 's'); - $this->assertEqual($tag->getLabel(), 'Label'); - - $encoding = new MockSimpleMultipartEncoding(); - $encoding->expectAt(0, 'add', array('s.x', 20)); - $encoding->expectAt(1, 'add', array('s.y', 30)); - $tag->write($encoding, 20, 30); - } - - function testImageSubmitTitlePreferredOverAltForLabel() { - $tag = new SimpleImageSubmitTag( - array('type' => 'image', 'name' => 's', 'alt' => 'Label', 'title' => 'Title')); - $this->assertEqual($tag->getLabel(), 'Title'); - } - - function testButton() { - $tag = new SimpleButtonTag( - array('type' => 'submit', 'name' => 's', 'value' => 'do')); - $tag->addContent('I am a button'); - $this->assertEqual($tag->getName(), 's'); - $this->assertEqual($tag->getValue(), 'do'); - $this->assertEqual($tag->getLabel(), 'I am a button'); - - $encoding = new MockSimpleMultipartEncoding(); - $encoding->expectOnce('add', array('s', 'do')); - $tag->write($encoding); - } -} - -class TestOfTextArea extends UnitTestCase { - - function testDefault() { - $tag = new SimpleTextAreaTag(array('name' => 'a')); - $tag->addContent('Some text'); - $this->assertEqual($tag->getName(), 'a'); - $this->assertEqual($tag->getDefault(), 'Some text'); - } - - function testWrapping() { - $tag = new SimpleTextAreaTag(array('cols' => '10', 'wrap' => 'physical')); - $tag->addContent("Lot's of text that should be wrapped"); - $this->assertEqual( - $tag->getDefault(), - "Lot's of\r\ntext that\r\nshould be\r\nwrapped"); - $tag->setValue("New long text\r\nwith two lines"); - $this->assertEqual( - $tag->getValue(), - "New long\r\ntext\r\nwith two\r\nlines"); - } - - function testWrappingRemovesLeadingcariageReturn() { - $tag = new SimpleTextAreaTag(array('cols' => '20', 'wrap' => 'physical')); - $tag->addContent("\rStuff"); - $this->assertEqual($tag->getDefault(), 'Stuff'); - $tag->setValue("\nNew stuff\n"); - $this->assertEqual($tag->getValue(), "New stuff\r\n"); - } - - function testBreaksAreNewlineAndCarriageReturn() { - $tag = new SimpleTextAreaTag(array('cols' => '10')); - $tag->addContent("Some\nText\rwith\r\nbreaks"); - $this->assertEqual($tag->getValue(), "Some\r\nText\r\nwith\r\nbreaks"); - } -} - -class TestOfCheckbox extends UnitTestCase { - - function testCanSetCheckboxToNamedValueWithBooleanTrue() { - $tag = new SimpleCheckboxTag(array('name' => 'a', 'value' => 'A')); - $this->assertEqual($tag->getValue(), false); - $tag->setValue(true); - $this->assertIdentical($tag->getValue(), 'A'); - } -} - -class TestOfSelection extends UnitTestCase { - - function testEmpty() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $this->assertIdentical($tag->getValue(), ''); - } - - function testSingle() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $option = new SimpleOptionTag(array()); - $option->addContent('AAA'); - $tag->addTag($option); - $this->assertEqual($tag->getValue(), 'AAA'); - } - - function testSingleDefault() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $option = new SimpleOptionTag(array('selected' => '')); - $option->addContent('AAA'); - $tag->addTag($option); - $this->assertEqual($tag->getValue(), 'AAA'); - } - - function testSingleMappedDefault() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $option = new SimpleOptionTag(array('selected' => '', 'value' => 'aaa')); - $option->addContent('AAA'); - $tag->addTag($option); - $this->assertEqual($tag->getValue(), 'aaa'); - } - - function testStartsWithDefault() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array()); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $c = new SimpleOptionTag(array()); - $c->addContent('CCC'); - $tag->addTag($c); - $this->assertEqual($tag->getValue(), 'BBB'); - } - - function testSettingOption() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array()); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $c = new SimpleOptionTag(array()); - $c->addContent('CCC'); - $tag->setValue('AAA'); - $this->assertEqual($tag->getValue(), 'AAA'); - } - - function testSettingMappedOption() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array('value' => 'aaa')); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('value' => 'bbb', 'selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $c = new SimpleOptionTag(array('value' => 'ccc')); - $c->addContent('CCC'); - $tag->addTag($c); - $tag->setValue('AAA'); - $this->assertEqual($tag->getValue(), 'aaa'); - $tag->setValue('ccc'); - $this->assertEqual($tag->getValue(), 'ccc'); - } - - function testSelectionDespiteSpuriousWhitespace() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array()); - $a->addContent(' AAA '); - $tag->addTag($a); - $b = new SimpleOptionTag(array('selected' => '')); - $b->addContent(' BBB '); - $tag->addTag($b); - $c = new SimpleOptionTag(array()); - $c->addContent(' CCC '); - $tag->addTag($c); - $this->assertEqual($tag->getValue(), ' BBB '); - $tag->setValue('AAA'); - $this->assertEqual($tag->getValue(), ' AAA '); - } - - function testFailToSetIllegalOption() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array()); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $c = new SimpleOptionTag(array()); - $c->addContent('CCC'); - $tag->addTag($c); - $this->assertFalse($tag->setValue('Not present')); - $this->assertEqual($tag->getValue(), 'BBB'); - } - - function testNastyOptionValuesThatLookLikeFalse() { - $tag = new SimpleSelectionTag(array('name' => 'a')); - $a = new SimpleOptionTag(array('value' => '1')); - $a->addContent('One'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('value' => '0')); - $b->addContent('Zero'); - $tag->addTag($b); - $this->assertIdentical($tag->getValue(), '1'); - $tag->setValue('Zero'); - $this->assertIdentical($tag->getValue(), '0'); - } - - function testBlankOption() { - $tag = new SimpleSelectionTag(array('name' => 'A')); - $a = new SimpleOptionTag(array()); - $tag->addTag($a); - $b = new SimpleOptionTag(array()); - $b->addContent('b'); - $tag->addTag($b); - $this->assertIdentical($tag->getValue(), ''); - $tag->setValue('b'); - $this->assertIdentical($tag->getValue(), 'b'); - $tag->setValue(''); - $this->assertIdentical($tag->getValue(), ''); - } - - function testMultipleDefaultWithNoSelections() { - $tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); - $a = new SimpleOptionTag(array()); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array()); - $b->addContent('BBB'); - $tag->addTag($b); - $this->assertIdentical($tag->getDefault(), array()); - $this->assertIdentical($tag->getValue(), array()); - } - - function testMultipleDefaultWithSelections() { - $tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); - $a = new SimpleOptionTag(array('selected' => '')); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array('selected' => '')); - $b->addContent('BBB'); - $tag->addTag($b); - $this->assertIdentical($tag->getDefault(), array('AAA', 'BBB')); - $this->assertIdentical($tag->getValue(), array('AAA', 'BBB')); - } - - function testSettingMultiple() { - $tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); - $a = new SimpleOptionTag(array('selected' => '')); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array()); - $b->addContent('BBB'); - $tag->addTag($b); - $c = new SimpleOptionTag(array('selected' => '', 'value' => 'ccc')); - $c->addContent('CCC'); - $tag->addTag($c); - $this->assertIdentical($tag->getDefault(), array('AAA', 'ccc')); - $this->assertTrue($tag->setValue(array('BBB', 'ccc'))); - $this->assertIdentical($tag->getValue(), array('BBB', 'ccc')); - $this->assertTrue($tag->setValue(array())); - $this->assertIdentical($tag->getValue(), array()); - } - - function testFailToSetIllegalOptionsInMultiple() { - $tag = new MultipleSelectionTag(array('name' => 'a', 'multiple' => '')); - $a = new SimpleOptionTag(array('selected' => '')); - $a->addContent('AAA'); - $tag->addTag($a); - $b = new SimpleOptionTag(array()); - $b->addContent('BBB'); - $tag->addTag($b); - $this->assertFalse($tag->setValue(array('CCC'))); - $this->assertTrue($tag->setValue(array('AAA', 'BBB'))); - $this->assertFalse($tag->setValue(array('AAA', 'CCC'))); - } -} - -class TestOfRadioGroup extends UnitTestCase { - - function testEmptyGroup() { - $group = new SimpleRadioGroup(); - $this->assertIdentical($group->getDefault(), false); - $this->assertIdentical($group->getValue(), false); - $this->assertFalse($group->setValue('a')); - } - - function testReadingSingleButtonGroup() { - $group = new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'A', 'checked' => ''))); - $this->assertIdentical($group->getDefault(), 'A'); - $this->assertIdentical($group->getValue(), 'A'); - } - - function testReadingMultipleButtonGroup() { - $group = new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'A'))); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'B', 'checked' => ''))); - $this->assertIdentical($group->getDefault(), 'B'); - $this->assertIdentical($group->getValue(), 'B'); - } - - function testFailToSetUnlistedValue() { - $group = new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag(array('value' => 'z'))); - $this->assertFalse($group->setValue('a')); - $this->assertIdentical($group->getValue(), false); - } - - function testSettingNewValueClearsTheOldOne() { - $group = new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'A'))); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'B', 'checked' => ''))); - $this->assertTrue($group->setValue('A')); - $this->assertIdentical($group->getValue(), 'A'); - } - - function testIsIdMatchesAnyWidgetInSet() { - $group = new SimpleRadioGroup(); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'A', 'id' => 'i1'))); - $group->addWidget(new SimpleRadioButtonTag( - array('value' => 'B', 'id' => 'i2'))); - $this->assertFalse($group->isId('i0')); - $this->assertTrue($group->isId('i1')); - $this->assertTrue($group->isId('i2')); - } - - function testIsLabelMatchesAnyWidgetInSet() { - $group = new SimpleRadioGroup(); - $button1 = new SimpleRadioButtonTag(array('value' => 'A')); - $button1->setLabel('one'); - $group->addWidget($button1); - $button2 = new SimpleRadioButtonTag(array('value' => 'B')); - $button2->setLabel('two'); - $group->addWidget($button2); - $this->assertFalse($group->isLabel('three')); - $this->assertTrue($group->isLabel('one')); - $this->assertTrue($group->isLabel('two')); - } -} - -class TestOfTagGroup extends UnitTestCase { - - function testReadingMultipleCheckboxGroup() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag( - array('value' => 'B', 'checked' => ''))); - $this->assertIdentical($group->getDefault(), 'B'); - $this->assertIdentical($group->getValue(), 'B'); - } - - function testReadingMultipleUncheckedItems() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); - $this->assertIdentical($group->getDefault(), false); - $this->assertIdentical($group->getValue(), false); - } - - function testReadingMultipleCheckedItems() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag( - array('value' => 'A', 'checked' => ''))); - $group->addWidget(new SimpleCheckboxTag( - array('value' => 'B', 'checked' => ''))); - $this->assertIdentical($group->getDefault(), array('A', 'B')); - $this->assertIdentical($group->getValue(), array('A', 'B')); - } - - function testSettingSingleValue() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); - $this->assertTrue($group->setValue('A')); - $this->assertIdentical($group->getValue(), 'A'); - $this->assertTrue($group->setValue('B')); - $this->assertIdentical($group->getValue(), 'B'); - } - - function testSettingMultipleValues() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); - $this->assertTrue($group->setValue(array('A', 'B'))); - $this->assertIdentical($group->getValue(), array('A', 'B')); - } - - function testSettingNoValue() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('value' => 'B'))); - $this->assertTrue($group->setValue(false)); - $this->assertIdentical($group->getValue(), false); - } - - function testIsIdMatchesAnyIdInSet() { - $group = new SimpleCheckboxGroup(); - $group->addWidget(new SimpleCheckboxTag(array('id' => 1, 'value' => 'A'))); - $group->addWidget(new SimpleCheckboxTag(array('id' => 2, 'value' => 'B'))); - $this->assertFalse($group->isId(0)); - $this->assertTrue($group->isId(1)); - $this->assertTrue($group->isId(2)); - } -} - -class TestOfUploadWidget extends UnitTestCase { - - function testValueIsFilePath() { - $upload = new SimpleUploadTag(array('name' => 'a')); - $upload->setValue(dirname(__FILE__) . '/support/upload_sample.txt'); - $this->assertEqual($upload->getValue(), dirname(__FILE__) . '/support/upload_sample.txt'); - } - - function testSubmitsFileContents() { - $encoding = new MockSimpleMultipartEncoding(); - $encoding->expectOnce('attach', array( - 'a', - 'Sample for testing file upload', - 'upload_sample.txt')); - $upload = new SimpleUploadTag(array('name' => 'a')); - $upload->setValue(dirname(__FILE__) . '/support/upload_sample.txt'); - $upload->write($encoding); - } -} - -class TestOfLabelTag extends UnitTestCase { - - function testLabelShouldHaveAnEndTag() { - $label = new SimpleLabelTag(array()); - $this->assertTrue($label->expectEndTag()); - } - - function testContentIsTextOnly() { - $label = new SimpleLabelTag(array()); - $label->addContent('Here are words'); - $this->assertEqual($label->getText(), 'Here are words'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/test_with_parse_error.php b/3rdparty/simpletest/test/test_with_parse_error.php deleted file mode 100644 index 41a5832a5cb9fe5e8589115921527f73b4298a0d..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/test_with_parse_error.php +++ /dev/null @@ -1,8 +0,0 @@ - \ No newline at end of file diff --git a/3rdparty/simpletest/test/unit_tester_test.php b/3rdparty/simpletest/test/unit_tester_test.php deleted file mode 100644 index ce9850f09abd2ae28d0a8e95a67bbe0573e65942..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/unit_tester_test.php +++ /dev/null @@ -1,61 +0,0 @@ -assertTrue($this->assertTrue(true)); - } - - function testAssertFalseReturnsAssertionAsBoolean() { - $this->assertTrue($this->assertFalse(false)); - } - - function testAssertEqualReturnsAssertionAsBoolean() { - $this->assertTrue($this->assertEqual(5, 5)); - } - - function testAssertIdenticalReturnsAssertionAsBoolean() { - $this->assertTrue($this->assertIdentical(5, 5)); - } - - function testCoreAssertionsDoNotThrowErrors() { - $this->assertIsA($this, 'UnitTestCase'); - $this->assertNotA($this, 'WebTestCase'); - } - - function testReferenceAssertionOnObjects() { - $a = new ReferenceForTesting(); - $b = $a; - $this->assertSame($a, $b); - } - - function testReferenceAssertionOnScalars() { - $a = 25; - $b = &$a; - $this->assertReference($a, $b); - } - - function testCloneOnObjects() { - $a = new ReferenceForTesting(); - $b = new ReferenceForTesting(); - $this->assertClone($a, $b); - } - - function TODO_testCloneOnScalars() { - $a = 25; - $b = 25; - $this->assertClone($a, $b); - } - - function testCopyOnScalars() { - $a = 25; - $b = 25; - $this->assertCopy($a, $b); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/unit_tests.php b/3rdparty/simpletest/test/unit_tests.php deleted file mode 100644 index 9e621293f9e1640e0006c765c4ff0c2709aa7536..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/unit_tests.php +++ /dev/null @@ -1,49 +0,0 @@ -TestSuite('Unit tests'); - $path = dirname(__FILE__); - $this->addFile($path . '/errors_test.php'); - $this->addFile($path . '/exceptions_test.php'); - $this->addFile($path . '/arguments_test.php'); - $this->addFile($path . '/autorun_test.php'); - $this->addFile($path . '/compatibility_test.php'); - $this->addFile($path . '/simpletest_test.php'); - $this->addFile($path . '/dumper_test.php'); - $this->addFile($path . '/expectation_test.php'); - $this->addFile($path . '/unit_tester_test.php'); - $this->addFile($path . '/reflection_php5_test.php'); - $this->addFile($path . '/mock_objects_test.php'); - $this->addFile($path . '/interfaces_test.php'); - $this->addFile($path . '/collector_test.php'); - $this->addFile($path . '/recorder_test.php'); - $this->addFile($path . '/adapter_test.php'); - $this->addFile($path . '/socket_test.php'); - $this->addFile($path . '/encoding_test.php'); - $this->addFile($path . '/url_test.php'); - $this->addFile($path . '/cookies_test.php'); - $this->addFile($path . '/http_test.php'); - $this->addFile($path . '/authentication_test.php'); - $this->addFile($path . '/user_agent_test.php'); - $this->addFile($path . '/php_parser_test.php'); - $this->addFile($path . '/parsing_test.php'); - $this->addFile($path . '/tag_test.php'); - $this->addFile($path . '/form_test.php'); - $this->addFile($path . '/page_test.php'); - $this->addFile($path . '/frames_test.php'); - $this->addFile($path . '/browser_test.php'); - $this->addFile($path . '/web_tester_test.php'); - $this->addFile($path . '/shell_tester_test.php'); - $this->addFile($path . '/xml_test.php'); - $this->addFile($path . '/../extensions/testdox/test.php'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/url_test.php b/3rdparty/simpletest/test/url_test.php deleted file mode 100644 index 80119afbdde88d7aa78fa654f9c5dc0d7b0e7513..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/url_test.php +++ /dev/null @@ -1,515 +0,0 @@ -assertEqual($url->getScheme(), ''); - $this->assertEqual($url->getHost(), ''); - $this->assertEqual($url->getScheme('http'), 'http'); - $this->assertEqual($url->getHost('localhost'), 'localhost'); - $this->assertEqual($url->getPath(), ''); - } - - function testBasicParsing() { - $url = new SimpleUrl('https://www.lastcraft.com/test/'); - $this->assertEqual($url->getScheme(), 'https'); - $this->assertEqual($url->getHost(), 'www.lastcraft.com'); - $this->assertEqual($url->getPath(), '/test/'); - } - - function testRelativeUrls() { - $url = new SimpleUrl('../somewhere.php'); - $this->assertEqual($url->getScheme(), false); - $this->assertEqual($url->getHost(), false); - $this->assertEqual($url->getPath(), '../somewhere.php'); - } - - function testParseBareParameter() { - $url = new SimpleUrl('?a'); - $this->assertEqual($url->getPath(), ''); - $this->assertEqual($url->getEncodedRequest(), '?a'); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=&x=X'); - } - - function testParseEmptyParameter() { - $url = new SimpleUrl('?a='); - $this->assertEqual($url->getPath(), ''); - $this->assertEqual($url->getEncodedRequest(), '?a='); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=&x=X'); - } - - function testParseParameterPair() { - $url = new SimpleUrl('?a=A'); - $this->assertEqual($url->getPath(), ''); - $this->assertEqual($url->getEncodedRequest(), '?a=A'); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&x=X'); - } - - function testParseMultipleParameters() { - $url = new SimpleUrl('?a=A&b=B'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B'); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B&x=X'); - } - - function testParsingParameterMixture() { - $url = new SimpleUrl('?a=A&b=&c'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c'); - $url->addRequestParameter('x', 'X'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c=&x=X'); - } - - function testAddParametersFromScratch() { - $url = new SimpleUrl(''); - $url->addRequestParameter('a', 'A'); - $this->assertEqual($url->getEncodedRequest(), '?a=A'); - $url->addRequestParameter('b', 'B'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B'); - $url->addRequestParameter('a', 'aaa'); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=B&a=aaa'); - } - - function testClearingParameters() { - $url = new SimpleUrl(''); - $url->addRequestParameter('a', 'A'); - $url->clearRequest(); - $this->assertIdentical($url->getEncodedRequest(), ''); - } - - function testEncodingParameters() { - $url = new SimpleUrl(''); - $url->addRequestParameter('a', '?!"\'#~@[]{}:;<>,./|$%^&*()_+-='); - $this->assertIdentical( - $request = $url->getEncodedRequest(), - '?a=%3F%21%22%27%23%7E%40%5B%5D%7B%7D%3A%3B%3C%3E%2C.%2F%7C%24%25%5E%26%2A%28%29_%2B-%3D'); - } - - function testDecodingParameters() { - $url = new SimpleUrl('?a=%3F%21%22%27%23%7E%40%5B%5D%7B%7D%3A%3B%3C%3E%2C.%2F%7C%24%25%5E%26%2A%28%29_%2B-%3D'); - $this->assertEqual( - $url->getEncodedRequest(), - '?a=' . urlencode('?!"\'#~@[]{}:;<>,./|$%^&*()_+-=')); - } - - function testUrlInQueryDoesNotConfuseParsing() { - $url = new SimpleUrl('wibble/login.php?url=http://www.google.com/moo/'); - $this->assertFalse($url->getScheme()); - $this->assertFalse($url->getHost()); - $this->assertEqual($url->getPath(), 'wibble/login.php'); - $this->assertEqual($url->getEncodedRequest(), '?url=http://www.google.com/moo/'); - } - - function testSettingCordinates() { - $url = new SimpleUrl(''); - $url->setCoordinates('32', '45'); - $this->assertIdentical($url->getX(), 32); - $this->assertIdentical($url->getY(), 45); - $this->assertEqual($url->getEncodedRequest(), ''); - } - - function testParseCordinates() { - $url = new SimpleUrl('?32,45'); - $this->assertIdentical($url->getX(), 32); - $this->assertIdentical($url->getY(), 45); - } - - function testClearingCordinates() { - $url = new SimpleUrl('?32,45'); - $url->setCoordinates(); - $this->assertIdentical($url->getX(), false); - $this->assertIdentical($url->getY(), false); - } - - function testParsingParameterCordinateMixture() { - $url = new SimpleUrl('?a=A&b=&c?32,45'); - $this->assertIdentical($url->getX(), 32); - $this->assertIdentical($url->getY(), 45); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c'); - } - - function testParsingParameterWithBadCordinates() { - $url = new SimpleUrl('?a=A&b=&c?32'); - $this->assertIdentical($url->getX(), false); - $this->assertIdentical($url->getY(), false); - $this->assertEqual($url->getEncodedRequest(), '?a=A&b=&c?32'); - } - - function testPageSplitting() { - $url = new SimpleUrl('./here/../there/somewhere.php'); - $this->assertEqual($url->getPath(), './here/../there/somewhere.php'); - $this->assertEqual($url->getPage(), 'somewhere.php'); - $this->assertEqual($url->getBasePath(), './here/../there/'); - } - - function testAbsolutePathPageSplitting() { - $url = new SimpleUrl("http://host.com/here/there/somewhere.php"); - $this->assertEqual($url->getPath(), "/here/there/somewhere.php"); - $this->assertEqual($url->getPage(), "somewhere.php"); - $this->assertEqual($url->getBasePath(), "/here/there/"); - } - - function testSplittingUrlWithNoPageGivesEmptyPage() { - $url = new SimpleUrl('/here/there/'); - $this->assertEqual($url->getPath(), '/here/there/'); - $this->assertEqual($url->getPage(), ''); - $this->assertEqual($url->getBasePath(), '/here/there/'); - } - - function testPathNormalisation() { - $url = new SimpleUrl(); - $this->assertEqual( - $url->normalisePath('https://host.com/I/am/here/../there/somewhere.php'), - 'https://host.com/I/am/there/somewhere.php'); - } - - // regression test for #1535407 - function testPathNormalisationWithSinglePeriod() { - $url = new SimpleUrl(); - $this->assertEqual( - $url->normalisePath('https://host.com/I/am/here/./../there/somewhere.php'), - 'https://host.com/I/am/there/somewhere.php'); - } - - // regression test for #1852413 - function testHostnameExtractedFromUContainingAtSign() { - $url = new SimpleUrl("http://localhost/name@example.com"); - $this->assertEqual($url->getScheme(), "http"); - $this->assertEqual($url->getUsername(), ""); - $this->assertEqual($url->getPassword(), ""); - $this->assertEqual($url->getHost(), "localhost"); - $this->assertEqual($url->getPath(), "/name@example.com"); - } - - function testHostnameInLocalhost() { - $url = new SimpleUrl("http://localhost/name/example.com"); - $this->assertEqual($url->getScheme(), "http"); - $this->assertEqual($url->getUsername(), ""); - $this->assertEqual($url->getPassword(), ""); - $this->assertEqual($url->getHost(), "localhost"); - $this->assertEqual($url->getPath(), "/name/example.com"); - } - - function testUsernameAndPasswordAreUrlDecoded() { - $url = new SimpleUrl('http://' . urlencode('test@test') . - ':' . urlencode('$!�@*&%') . '@www.lastcraft.com'); - $this->assertEqual($url->getUsername(), 'test@test'); - $this->assertEqual($url->getPassword(), '$!�@*&%'); - } - - function testBlitz() { - $this->assertUrl( - "https://username:password@www.somewhere.com:243/this/that/here.php?a=1&b=2#anchor", - array("https", "username", "password", "www.somewhere.com", 243, "/this/that/here.php", "com", "?a=1&b=2", "anchor"), - array("a" => "1", "b" => "2")); - $this->assertUrl( - "username:password@www.somewhere.com/this/that/here.php?a=1", - array(false, "username", "password", "www.somewhere.com", false, "/this/that/here.php", "com", "?a=1", false), - array("a" => "1")); - $this->assertUrl( - "username:password@somewhere.com:243?1,2", - array(false, "username", "password", "somewhere.com", 243, "/", "com", "", false), - array(), - array(1, 2)); - $this->assertUrl( - "https://www.somewhere.com", - array("https", false, false, "www.somewhere.com", false, "/", "com", "", false)); - $this->assertUrl( - "username@www.somewhere.com:243#anchor", - array(false, "username", false, "www.somewhere.com", 243, "/", "com", "", "anchor")); - $this->assertUrl( - "/this/that/here.php?a=1&b=2?3,4", - array(false, false, false, false, false, "/this/that/here.php", false, "?a=1&b=2", false), - array("a" => "1", "b" => "2"), - array(3, 4)); - $this->assertUrl( - "username@/here.php?a=1&b=2", - array(false, "username", false, false, false, "/here.php", false, "?a=1&b=2", false), - array("a" => "1", "b" => "2")); - } - - function testAmbiguousHosts() { - $this->assertUrl( - "tigger", - array(false, false, false, false, false, "tigger", false, "", false)); - $this->assertUrl( - "/tigger", - array(false, false, false, false, false, "/tigger", false, "", false)); - $this->assertUrl( - "//tigger", - array(false, false, false, "tigger", false, "/", false, "", false)); - $this->assertUrl( - "//tigger/", - array(false, false, false, "tigger", false, "/", false, "", false)); - $this->assertUrl( - "tigger.com", - array(false, false, false, "tigger.com", false, "/", "com", "", false)); - $this->assertUrl( - "me.net/tigger", - array(false, false, false, "me.net", false, "/tigger", "net", "", false)); - } - - function testAsString() { - $this->assertPreserved('https://www.here.com'); - $this->assertPreserved('http://me:secret@www.here.com'); - $this->assertPreserved('http://here/there'); - $this->assertPreserved('http://here/there?a=A&b=B'); - $this->assertPreserved('http://here/there?a=1&a=2'); - $this->assertPreserved('http://here/there?a=1&a=2?9,8'); - $this->assertPreserved('http://host?a=1&a=2'); - $this->assertPreserved('http://host#stuff'); - $this->assertPreserved('http://me:secret@www.here.com/a/b/c/here.html?a=A?7,6'); - $this->assertPreserved('http://www.here.com/?a=A__b=B'); - $this->assertPreserved('http://www.example.com:8080/'); - } - - function testUrlWithTwoSlashesInPath() { - $url = new SimpleUrl('/article/categoryedit/insert//'); - $this->assertEqual($url->getPath(), '/article/categoryedit/insert//'); - } - - function testUrlWithRequestKeyEncoded() { - $url = new SimpleUrl('/?foo%5B1%5D=bar'); - $this->assertEqual($url->getEncodedRequest(), '?foo%5B1%5D=bar'); - $url->addRequestParameter('a[1]', 'b[]'); - $this->assertEqual($url->getEncodedRequest(), '?foo%5B1%5D=bar&a%5B1%5D=b%5B%5D'); - - $url = new SimpleUrl('/'); - $url->addRequestParameter('a[1]', 'b[]'); - $this->assertEqual($url->getEncodedRequest(), '?a%5B1%5D=b%5B%5D'); - } - - function testUrlWithRequestKeyEncodedAndParamNamLookingLikePair() { - $url = new SimpleUrl('/'); - $url->addRequestParameter('foo[]=bar', ''); - $this->assertEqual($url->getEncodedRequest(), '?foo%5B%5D%3Dbar='); - $url = new SimpleUrl('/?foo%5B%5D%3Dbar='); - $this->assertEqual($url->getEncodedRequest(), '?foo%5B%5D%3Dbar='); - } - - function assertUrl($raw, $parts, $params = false, $coords = false) { - if (! is_array($params)) { - $params = array(); - } - $url = new SimpleUrl($raw); - $this->assertIdentical($url->getScheme(), $parts[0], "[$raw] scheme -> %s"); - $this->assertIdentical($url->getUsername(), $parts[1], "[$raw] username -> %s"); - $this->assertIdentical($url->getPassword(), $parts[2], "[$raw] password -> %s"); - $this->assertIdentical($url->getHost(), $parts[3], "[$raw] host -> %s"); - $this->assertIdentical($url->getPort(), $parts[4], "[$raw] port -> %s"); - $this->assertIdentical($url->getPath(), $parts[5], "[$raw] path -> %s"); - $this->assertIdentical($url->getTld(), $parts[6], "[$raw] tld -> %s"); - $this->assertIdentical($url->getEncodedRequest(), $parts[7], "[$raw] encoded -> %s"); - $this->assertIdentical($url->getFragment(), $parts[8], "[$raw] fragment -> %s"); - if ($coords) { - $this->assertIdentical($url->getX(), $coords[0], "[$raw] x -> %s"); - $this->assertIdentical($url->getY(), $coords[1], "[$raw] y -> %s"); - } - } - - function assertPreserved($string) { - $url = new SimpleUrl($string); - $this->assertEqual($url->asString(), $string); - } -} - -class TestOfAbsoluteUrls extends UnitTestCase { - - function testDirectoriesAfterFilename() { - $string = '../../index.php/foo/bar'; - $url = new SimpleUrl($string); - $this->assertEqual($url->asString(), $string); - - $absolute = $url->makeAbsolute('http://www.domain.com/some/path/'); - $this->assertEqual($absolute->asString(), 'http://www.domain.com/index.php/foo/bar'); - } - - function testMakingAbsolute() { - $url = new SimpleUrl('../there/somewhere.php'); - $this->assertEqual($url->getPath(), '../there/somewhere.php'); - $absolute = $url->makeAbsolute('https://host.com:1234/I/am/here/'); - $this->assertEqual($absolute->getScheme(), 'https'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPort(), 1234); - $this->assertEqual($absolute->getPath(), '/I/am/there/somewhere.php'); - } - - function testMakingAnEmptyUrlAbsolute() { - $url = new SimpleUrl(''); - $this->assertEqual($url->getPath(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPath(), '/I/am/here/page.html'); - } - - function testMakingAnEmptyUrlAbsoluteWithMissingPageName() { - $url = new SimpleUrl(''); - $this->assertEqual($url->getPath(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPath(), '/I/am/here/'); - } - - function testMakingAShortQueryUrlAbsolute() { - $url = new SimpleUrl('?a#b'); - $this->assertEqual($url->getPath(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPath(), '/I/am/here/'); - $this->assertEqual($absolute->getEncodedRequest(), '?a'); - $this->assertEqual($absolute->getFragment(), 'b'); - } - - function testMakingADirectoryUrlAbsolute() { - $url = new SimpleUrl('hello/'); - $this->assertEqual($url->getPath(), 'hello/'); - $this->assertEqual($url->getBasePath(), 'hello/'); - $this->assertEqual($url->getPage(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); - $this->assertEqual($absolute->getPath(), '/I/am/here/hello/'); - } - - function testMakingARootUrlAbsolute() { - $url = new SimpleUrl('/'); - $this->assertEqual($url->getPath(), '/'); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); - $this->assertEqual($absolute->getPath(), '/'); - } - - function testMakingARootPageUrlAbsolute() { - $url = new SimpleUrl('/here.html'); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/page.html'); - $this->assertEqual($absolute->getPath(), '/here.html'); - } - - function testCarryAuthenticationFromRootPage() { - $url = new SimpleUrl('here.html'); - $absolute = $url->makeAbsolute('http://test:secret@host.com/'); - $this->assertEqual($absolute->getPath(), '/here.html'); - $this->assertEqual($absolute->getUsername(), 'test'); - $this->assertEqual($absolute->getPassword(), 'secret'); - } - - function testMakingCoordinateUrlAbsolute() { - $url = new SimpleUrl('?1,2'); - $this->assertEqual($url->getPath(), ''); - $absolute = $url->makeAbsolute('http://host.com/I/am/here/'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'host.com'); - $this->assertEqual($absolute->getPath(), '/I/am/here/'); - $this->assertEqual($absolute->getX(), 1); - $this->assertEqual($absolute->getY(), 2); - } - - function testMakingAbsoluteAppendedPath() { - $url = new SimpleUrl('./there/somewhere.php'); - $absolute = $url->makeAbsolute('https://host.com/here/'); - $this->assertEqual($absolute->getPath(), '/here/there/somewhere.php'); - } - - function testMakingAbsoluteBadlyFormedAppendedPath() { - $url = new SimpleUrl('there/somewhere.php'); - $absolute = $url->makeAbsolute('https://host.com/here/'); - $this->assertEqual($absolute->getPath(), '/here/there/somewhere.php'); - } - - function testMakingAbsoluteHasNoEffectWhenAlreadyAbsolute() { - $url = new SimpleUrl('https://test:secret@www.lastcraft.com:321/stuff/?a=1#f'); - $absolute = $url->makeAbsolute('http://host.com/here/'); - $this->assertEqual($absolute->getScheme(), 'https'); - $this->assertEqual($absolute->getUsername(), 'test'); - $this->assertEqual($absolute->getPassword(), 'secret'); - $this->assertEqual($absolute->getHost(), 'www.lastcraft.com'); - $this->assertEqual($absolute->getPort(), 321); - $this->assertEqual($absolute->getPath(), '/stuff/'); - $this->assertEqual($absolute->getEncodedRequest(), '?a=1'); - $this->assertEqual($absolute->getFragment(), 'f'); - } - - function testMakingAbsoluteCarriesAuthenticationWhenAlreadyAbsolute() { - $url = new SimpleUrl('https://www.lastcraft.com'); - $absolute = $url->makeAbsolute('http://test:secret@host.com/here/'); - $this->assertEqual($absolute->getHost(), 'www.lastcraft.com'); - $this->assertEqual($absolute->getUsername(), 'test'); - $this->assertEqual($absolute->getPassword(), 'secret'); - } - - function testMakingHostOnlyAbsoluteDoesNotCarryAnyOtherInformation() { - $url = new SimpleUrl('http://www.lastcraft.com'); - $absolute = $url->makeAbsolute('https://host.com:81/here/'); - $this->assertEqual($absolute->getScheme(), 'http'); - $this->assertEqual($absolute->getHost(), 'www.lastcraft.com'); - $this->assertIdentical($absolute->getPort(), false); - $this->assertEqual($absolute->getPath(), '/'); - } -} - -class TestOfFrameUrl extends UnitTestCase { - - function testTargetAttachment() { - $url = new SimpleUrl('http://www.site.com/home.html'); - $this->assertIdentical($url->getTarget(), false); - $url->setTarget('A frame'); - $this->assertIdentical($url->getTarget(), 'A frame'); - } -} - -/** - * @note Based off of http://www.mozilla.org/quality/networking/testing/filetests.html - */ -class TestOfFileUrl extends UnitTestCase { - - function testMinimalUrl() { - $url = new SimpleUrl('file:///'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/'); - } - - function testUnixUrl() { - $url = new SimpleUrl('file:///fileInRoot'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/fileInRoot'); - } - - function testDOSVolumeUrl() { - $url = new SimpleUrl('file:///C:/config.sys'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/C:/config.sys'); - } - - function testDOSVolumePromotion() { - $url = new SimpleUrl('file://C:/config.sys'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/C:/config.sys'); - } - - function testDOSBackslashes() { - $url = new SimpleUrl('file:///C:\config.sys'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/C:/config.sys'); - } - - function testDOSDirnameAfterFile() { - $url = new SimpleUrl('file://C:\config.sys'); - $this->assertEqual($url->getScheme(), 'file'); - $this->assertIdentical($url->getHost(), false); - $this->assertEqual($url->getPath(), '/C:/config.sys'); - } - -} - -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/user_agent_test.php b/3rdparty/simpletest/test/user_agent_test.php deleted file mode 100644 index 030abeb257d84bb30204a88f0a7c54809803622e..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/user_agent_test.php +++ /dev/null @@ -1,348 +0,0 @@ -headers = new MockSimpleHttpHeaders(); - $this->response = new MockSimpleHttpResponse(); - $this->response->setReturnValue('isError', false); - $this->response->returns('getHeaders', new MockSimpleHttpHeaders()); - $this->request = new MockSimpleHttpRequest(); - $this->request->returns('fetch', $this->response); - } - - function testGetRequestWithoutIncidentGivesNoErrors() { - $url = new SimpleUrl('http://test:secret@this.com/page.html'); - $url->addRequestParameters(array('a' => 'A', 'b' => 'B')); - - $agent = new MockRequestUserAgent(); - $agent->returns('createHttpRequest', $this->request); - $agent->__construct(); - - $response = $agent->fetchResponse( - new SimpleUrl('http://test:secret@this.com/page.html'), - new SimpleGetEncoding(array('a' => 'A', 'b' => 'B'))); - $this->assertFalse($response->isError()); - } -} - -class TestOfAdditionalHeaders extends UnitTestCase { - - function testAdditionalHeaderAddedToRequest() { - $response = new MockSimpleHttpResponse(); - $response->setReturnReference('getHeaders', new MockSimpleHttpHeaders()); - - $request = new MockSimpleHttpRequest(); - $request->setReturnReference('fetch', $response); - $request->expectOnce( - 'addHeaderLine', - array('User-Agent: SimpleTest')); - - $agent = new MockRequestUserAgent(); - $agent->setReturnReference('createHttpRequest', $request); - $agent->__construct(); - $agent->addHeader('User-Agent: SimpleTest'); - $response = $agent->fetchResponse(new SimpleUrl('http://this.host/'), new SimpleGetEncoding()); - } -} - -class TestOfBrowserCookies extends UnitTestCase { - - private function createStandardResponse() { - $response = new MockSimpleHttpResponse(); - $response->setReturnValue("isError", false); - $response->setReturnValue("getContent", "stuff"); - $response->setReturnReference("getHeaders", new MockSimpleHttpHeaders()); - return $response; - } - - private function createCookieSite($header_lines) { - $headers = new SimpleHttpHeaders($header_lines); - $response = new MockSimpleHttpResponse(); - $response->setReturnValue("isError", false); - $response->setReturnReference("getHeaders", $headers); - $response->setReturnValue("getContent", "stuff"); - $request = new MockSimpleHttpRequest(); - $request->setReturnReference("fetch", $response); - return $request; - } - - private function createMockedRequestUserAgent(&$request) { - $agent = new MockRequestUserAgent(); - $agent->setReturnReference('createHttpRequest', $request); - $agent->__construct(); - return $agent; - } - - function testCookieJarIsSentToRequest() { - $jar = new SimpleCookieJar(); - $jar->setCookie('a', 'A'); - - $request = new MockSimpleHttpRequest(); - $request->returns('fetch', $this->createStandardResponse()); - $request->expectOnce('readCookiesFromJar', array($jar, '*')); - - $agent = $this->createMockedRequestUserAgent($request); - $agent->setCookie('a', 'A'); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - } - - function testNoCookieJarIsSentToRequestWhenCookiesAreDisabled() { - $request = new MockSimpleHttpRequest(); - $request->returns('fetch', $this->createStandardResponse()); - $request->expectNever('readCookiesFromJar'); - - $agent = $this->createMockedRequestUserAgent($request); - $agent->setCookie('a', 'A'); - $agent->ignoreCookies(); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - } - - function testReadingNewCookie() { - $request = $this->createCookieSite('Set-cookie: a=AAAA'); - $agent = $this->createMockedRequestUserAgent($request); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertEqual($agent->getCookieValue("this.com", "this/path/", "a"), "AAAA"); - } - - function testIgnoringNewCookieWhenCookiesDisabled() { - $request = $this->createCookieSite('Set-cookie: a=AAAA'); - $agent = $this->createMockedRequestUserAgent($request); - $agent->ignoreCookies(); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertIdentical($agent->getCookieValue("this.com", "this/path/", "a"), false); - } - - function testOverwriteCookieThatAlreadyExists() { - $request = $this->createCookieSite('Set-cookie: a=AAAA'); - $agent = $this->createMockedRequestUserAgent($request); - $agent->setCookie('a', 'A'); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertEqual($agent->getCookieValue("this.com", "this/path/", "a"), "AAAA"); - } - - function testClearCookieBySettingExpiry() { - $request = $this->createCookieSite('Set-cookie: a=b'); - $agent = $this->createMockedRequestUserAgent($request); - - $agent->setCookie("a", "A", "this/path/", "Wed, 25-Dec-02 04:24:21 GMT"); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertIdentical( - $agent->getCookieValue("this.com", "this/path/", "a"), - "b"); - $agent->restart("Wed, 25-Dec-02 04:24:20 GMT"); - $this->assertIdentical( - $agent->getCookieValue("this.com", "this/path/", "a"), - false); - } - - function testAgeingAndClearing() { - $request = $this->createCookieSite('Set-cookie: a=A; expires=Wed, 25-Dec-02 04:24:21 GMT; path=/this/path'); - $agent = $this->createMockedRequestUserAgent($request); - - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $agent->restart("Wed, 25-Dec-02 04:24:20 GMT"); - $this->assertIdentical( - $agent->getCookieValue("this.com", "this/path/", "a"), - "A"); - $agent->ageCookies(2); - $agent->restart("Wed, 25-Dec-02 04:24:20 GMT"); - $this->assertIdentical( - $agent->getCookieValue("this.com", "this/path/", "a"), - false); - } - - function testReadingIncomingAndSettingNewCookies() { - $request = $this->createCookieSite('Set-cookie: a=AAA'); - $agent = $this->createMockedRequestUserAgent($request); - - $this->assertNull($agent->getBaseCookieValue("a", false)); - $agent->fetchResponse( - new SimpleUrl('http://this.com/this/path/page.html'), - new SimpleGetEncoding()); - $agent->setCookie("b", "BBB", "this.com", "this/path/"); - $this->assertEqual( - $agent->getBaseCookieValue("a", new SimpleUrl('http://this.com/this/path/page.html')), - "AAA"); - $this->assertEqual( - $agent->getBaseCookieValue("b", new SimpleUrl('http://this.com/this/path/page.html')), - "BBB"); - } -} - -class TestOfHttpRedirects extends UnitTestCase { - - function createRedirect($content, $redirect) { - $headers = new MockSimpleHttpHeaders(); - $headers->setReturnValue('isRedirect', (boolean)$redirect); - $headers->setReturnValue('getLocation', $redirect); - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('getContent', $content); - $response->setReturnReference('getHeaders', $headers); - $request = new MockSimpleHttpRequest(); - $request->setReturnReference('fetch', $response); - return $request; - } - - function testDisabledRedirects() { - $agent = new MockRequestUserAgent(); - $agent->returns( - 'createHttpRequest', - $this->createRedirect('stuff', 'there.html')); - $agent->expectOnce('createHttpRequest'); - $agent->__construct(); - $agent->setMaximumRedirects(0); - $response = $agent->fetchResponse(new SimpleUrl('here.html'), new SimpleGetEncoding()); - $this->assertEqual($response->getContent(), 'stuff'); - } - - function testSingleRedirect() { - $agent = new MockRequestUserAgent(); - $agent->returnsAt( - 0, - 'createHttpRequest', - $this->createRedirect('first', 'two.html')); - $agent->returnsAt( - 1, - 'createHttpRequest', - $this->createRedirect('second', 'three.html')); - $agent->expectCallCount('createHttpRequest', 2); - $agent->__construct(); - - $agent->setMaximumRedirects(1); - $response = $agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding()); - $this->assertEqual($response->getContent(), 'second'); - } - - function testDoubleRedirect() { - $agent = new MockRequestUserAgent(); - $agent->returnsAt( - 0, - 'createHttpRequest', - $this->createRedirect('first', 'two.html')); - $agent->returnsAt( - 1, - 'createHttpRequest', - $this->createRedirect('second', 'three.html')); - $agent->returnsAt( - 2, - 'createHttpRequest', - $this->createRedirect('third', 'four.html')); - $agent->expectCallCount('createHttpRequest', 3); - $agent->__construct(); - - $agent->setMaximumRedirects(2); - $response = $agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding()); - $this->assertEqual($response->getContent(), 'third'); - } - - function testSuccessAfterRedirect() { - $agent = new MockRequestUserAgent(); - $agent->returnsAt( - 0, - 'createHttpRequest', - $this->createRedirect('first', 'two.html')); - $agent->returnsAt( - 1, - 'createHttpRequest', - $this->createRedirect('second', false)); - $agent->returnsAt( - 2, - 'createHttpRequest', - $this->createRedirect('third', 'four.html')); - $agent->expectCallCount('createHttpRequest', 2); - $agent->__construct(); - - $agent->setMaximumRedirects(2); - $response = $agent->fetchResponse(new SimpleUrl('one.html'), new SimpleGetEncoding()); - $this->assertEqual($response->getContent(), 'second'); - } - - function testRedirectChangesPostToGet() { - $agent = new MockRequestUserAgent(); - $agent->returnsAt( - 0, - 'createHttpRequest', - $this->createRedirect('first', 'two.html')); - $agent->expectAt(0, 'createHttpRequest', array('*', new IsAExpectation('SimplePostEncoding'))); - $agent->returnsAt( - 1, - 'createHttpRequest', - $this->createRedirect('second', 'three.html')); - $agent->expectAt(1, 'createHttpRequest', array('*', new IsAExpectation('SimpleGetEncoding'))); - $agent->expectCallCount('createHttpRequest', 2); - $agent->__construct(); - $agent->setMaximumRedirects(1); - $response = $agent->fetchResponse(new SimpleUrl('one.html'), new SimplePostEncoding()); - } -} - -class TestOfBadHosts extends UnitTestCase { - - private function createSimulatedBadHost() { - $response = new MockSimpleHttpResponse(); - $response->setReturnValue('isError', true); - $response->setReturnValue('getError', 'Bad socket'); - $response->setReturnValue('getContent', false); - $request = new MockSimpleHttpRequest(); - $request->setReturnReference('fetch', $response); - return $request; - } - - function testUntestedHost() { - $request = $this->createSimulatedBadHost(); - $agent = new MockRequestUserAgent(); - $agent->setReturnReference('createHttpRequest', $request); - $agent->__construct(); - $response = $agent->fetchResponse( - new SimpleUrl('http://this.host/this/path/page.html'), - new SimpleGetEncoding()); - $this->assertTrue($response->isError()); - } -} - -class TestOfAuthorisation extends UnitTestCase { - - function testAuthenticateHeaderAdded() { - $response = new MockSimpleHttpResponse(); - $response->setReturnReference('getHeaders', new MockSimpleHttpHeaders()); - - $request = new MockSimpleHttpRequest(); - $request->returns('fetch', $response); - $request->expectOnce( - 'addHeaderLine', - array('Authorization: Basic ' . base64_encode('test:secret'))); - - $agent = new MockRequestUserAgent(); - $agent->returns('createHttpRequest', $request); - $agent->__construct(); - $response = $agent->fetchResponse( - new SimpleUrl('http://test:secret@this.host'), - new SimpleGetEncoding()); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/visual_test.php b/3rdparty/simpletest/test/visual_test.php deleted file mode 100644 index 6b9d085d67f9bd2939e56b98695034462a152998..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/visual_test.php +++ /dev/null @@ -1,495 +0,0 @@ -a = $a; - } -} - -class PassingUnitTestCaseOutput extends UnitTestCase { - - function testOfResults() { - $this->pass('Pass'); - } - - function testTrue() { - $this->assertTrue(true); - } - - function testFalse() { - $this->assertFalse(false); - } - - function testExpectation() { - $expectation = &new EqualExpectation(25, 'My expectation message: %s'); - $this->assert($expectation, 25, 'My assert message : %s'); - } - - function testNull() { - $this->assertNull(null, "%s -> Pass"); - $this->assertNotNull(false, "%s -> Pass"); - } - - function testType() { - $this->assertIsA("hello", "string", "%s -> Pass"); - $this->assertIsA($this, "PassingUnitTestCaseOutput", "%s -> Pass"); - $this->assertIsA($this, "UnitTestCase", "%s -> Pass"); - } - - function testTypeEquality() { - $this->assertEqual("0", 0, "%s -> Pass"); - } - - function testNullEquality() { - $this->assertNotEqual(null, 1, "%s -> Pass"); - $this->assertNotEqual(1, null, "%s -> Pass"); - } - - function testIntegerEquality() { - $this->assertNotEqual(1, 2, "%s -> Pass"); - } - - function testStringEquality() { - $this->assertEqual("a", "a", "%s -> Pass"); - $this->assertNotEqual("aa", "ab", "%s -> Pass"); - } - - function testHashEquality() { - $this->assertEqual(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "A"), "%s -> Pass"); - } - - function testWithin() { - $this->assertWithinMargin(5, 5.4, 0.5, "%s -> Pass"); - } - - function testOutside() { - $this->assertOutsideMargin(5, 5.6, 0.5, "%s -> Pass"); - } - - function testStringIdentity() { - $a = "fred"; - $b = $a; - $this->assertIdentical($a, $b, "%s -> Pass"); - } - - function testTypeIdentity() { - $a = "0"; - $b = 0; - $this->assertNotIdentical($a, $b, "%s -> Pass"); - } - - function testNullIdentity() { - $this->assertNotIdentical(null, 1, "%s -> Pass"); - $this->assertNotIdentical(1, null, "%s -> Pass"); - } - - function testHashIdentity() { - } - - function testObjectEquality() { - $this->assertEqual(new TestDisplayClass(4), new TestDisplayClass(4), "%s -> Pass"); - $this->assertNotEqual(new TestDisplayClass(4), new TestDisplayClass(5), "%s -> Pass"); - } - - function testObjectIndentity() { - $this->assertIdentical(new TestDisplayClass(false), new TestDisplayClass(false), "%s -> Pass"); - $this->assertNotIdentical(new TestDisplayClass(false), new TestDisplayClass(0), "%s -> Pass"); - } - - function testReference() { - $a = "fred"; - $b = &$a; - $this->assertReference($a, $b, "%s -> Pass"); - } - - function testCloneOnDifferentObjects() { - $a = "fred"; - $b = $a; - $c = "Hello"; - $this->assertClone($a, $b, "%s -> Pass"); - } - - function testPatterns() { - $this->assertPattern('/hello/i', "Hello there", "%s -> Pass"); - $this->assertNoPattern('/hello/', "Hello there", "%s -> Pass"); - } - - function testLongStrings() { - $text = ""; - for ($i = 0; $i < 10; $i++) { - $text .= "0123456789"; - } - $this->assertEqual($text, $text); - } -} - -class FailingUnitTestCaseOutput extends UnitTestCase { - - function testOfResults() { - $this->fail('Fail'); // Fail. - } - - function testTrue() { - $this->assertTrue(false); // Fail. - } - - function testFalse() { - $this->assertFalse(true); // Fail. - } - - function testExpectation() { - $expectation = &new EqualExpectation(25, 'My expectation message: %s'); - $this->assert($expectation, 24, 'My assert message : %s'); // Fail. - } - - function testNull() { - $this->assertNull(false, "%s -> Fail"); // Fail. - $this->assertNotNull(null, "%s -> Fail"); // Fail. - } - - function testType() { - $this->assertIsA(14, "string", "%s -> Fail"); // Fail. - $this->assertIsA(14, "TestOfUnitTestCaseOutput", "%s -> Fail"); // Fail. - $this->assertIsA($this, "TestReporter", "%s -> Fail"); // Fail. - } - - function testTypeEquality() { - $this->assertNotEqual("0", 0, "%s -> Fail"); // Fail. - } - - function testNullEquality() { - $this->assertEqual(null, 1, "%s -> Fail"); // Fail. - $this->assertEqual(1, null, "%s -> Fail"); // Fail. - } - - function testIntegerEquality() { - $this->assertEqual(1, 2, "%s -> Fail"); // Fail. - } - - function testStringEquality() { - $this->assertNotEqual("a", "a", "%s -> Fail"); // Fail. - $this->assertEqual("aa", "ab", "%s -> Fail"); // Fail. - } - - function testHashEquality() { - $this->assertEqual(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "Z"), "%s -> Fail"); - } - - function testWithin() { - $this->assertWithinMargin(5, 5.6, 0.5, "%s -> Fail"); // Fail. - } - - function testOutside() { - $this->assertOutsideMargin(5, 5.4, 0.5, "%s -> Fail"); // Fail. - } - - function testStringIdentity() { - $a = "fred"; - $b = $a; - $this->assertNotIdentical($a, $b, "%s -> Fail"); // Fail. - } - - function testTypeIdentity() { - $a = "0"; - $b = 0; - $this->assertIdentical($a, $b, "%s -> Fail"); // Fail. - } - - function testNullIdentity() { - $this->assertIdentical(null, 1, "%s -> Fail"); // Fail. - $this->assertIdentical(1, null, "%s -> Fail"); // Fail. - } - - function testHashIdentity() { - $this->assertIdentical(array("a" => "A", "b" => "B"), array("b" => "B", "a" => "A"), "%s -> fail"); // Fail. - } - - function testObjectEquality() { - $this->assertNotEqual(new TestDisplayClass(4), new TestDisplayClass(4), "%s -> Fail"); // Fail. - $this->assertEqual(new TestDisplayClass(4), new TestDisplayClass(5), "%s -> Fail"); // Fail. - } - - function testObjectIndentity() { - $this->assertNotIdentical(new TestDisplayClass(false), new TestDisplayClass(false), "%s -> Fail"); // Fail. - $this->assertIdentical(new TestDisplayClass(false), new TestDisplayClass(0), "%s -> Fail"); // Fail. - } - - function testReference() { - $a = "fred"; - $b = &$a; - $this->assertClone($a, $b, "%s -> Fail"); // Fail. - } - - function testCloneOnDifferentObjects() { - $a = "fred"; - $b = $a; - $c = "Hello"; - $this->assertClone($a, $c, "%s -> Fail"); // Fail. - } - - function testPatterns() { - $this->assertPattern('/hello/', "Hello there", "%s -> Fail"); // Fail. - $this->assertNoPattern('/hello/i', "Hello there", "%s -> Fail"); // Fail. - } - - function testLongStrings() { - $text = ""; - for ($i = 0; $i < 10; $i++) { - $text .= "0123456789"; - } - $this->assertEqual($text . $text, $text . "a" . $text); // Fail. - } -} - -class Dummy { - function Dummy() { - } - - function a() { - } -} -Mock::generate('Dummy'); - -class TestOfMockObjectsOutput extends UnitTestCase { - - function testCallCounts() { - $dummy = &new MockDummy(); - $dummy->expectCallCount('a', 1, 'My message: %s'); - $dummy->a(); - $dummy->a(); - } - - function testMinimumCallCounts() { - $dummy = &new MockDummy(); - $dummy->expectMinimumCallCount('a', 2, 'My message: %s'); - $dummy->a(); - $dummy->a(); - } - - function testEmptyMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array()); - $dummy->a(); - $dummy->a(null); // Fail. - } - - function testEmptyMatchingWithCustomMessage() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(), 'My expectation message: %s'); - $dummy->a(); - $dummy->a(null); // Fail. - } - - function testNullMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(null)); - $dummy->a(null); - $dummy->a(); // Fail. - } - - function testBooleanMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(true, false)); - $dummy->a(true, false); - $dummy->a(true, true); // Fail. - } - - function testIntegerMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(32, 33)); - $dummy->a(32, 33); - $dummy->a(32, 34); // Fail. - } - - function testFloatMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(3.2, 3.3)); - $dummy->a(3.2, 3.3); - $dummy->a(3.2, 3.4); // Fail. - } - - function testStringMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array('32', '33')); - $dummy->a('32', '33'); - $dummy->a('32', '34'); // Fail. - } - - function testEmptyMatchingWithCustomExpectationMessage() { - $dummy = &new MockDummy(); - $dummy->expect( - 'a', - array(new EqualExpectation('A', 'My part expectation message: %s')), - 'My expectation message: %s'); - $dummy->a('A'); - $dummy->a('B'); // Fail. - } - - function testArrayMatching() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(array(32), array(33))); - $dummy->a(array(32), array(33)); - $dummy->a(array(32), array('33')); // Fail. - } - - function testObjectMatching() { - $a = new Dummy(); - $a->a = 'a'; - $b = new Dummy(); - $b->b = 'b'; - $dummy = &new MockDummy(); - $dummy->expect('a', array($a, $b)); - $dummy->a($a, $b); - $dummy->a($a, $a); // Fail. - } - - function testBigList() { - $dummy = &new MockDummy(); - $dummy->expect('a', array(false, 0, 1, 1.0)); - $dummy->a(false, 0, 1, 1.0); - $dummy->a(true, false, 2, 2.0); // Fail. - } -} - -class TestOfPastBugs extends UnitTestCase { - - function testMixedTypes() { - $this->assertEqual(array(), null, "%s -> Pass"); - $this->assertIdentical(array(), null, "%s -> Fail"); // Fail. - } - - function testMockWildcards() { - $dummy = &new MockDummy(); - $dummy->expect('a', array('*', array(33))); - $dummy->a(array(32), array(33)); - $dummy->a(array(32), array('33')); // Fail. - } -} - -class TestOfVisualShell extends ShellTestCase { - - function testDump() { - $this->execute('ls'); - $this->dumpOutput(); - $this->execute('dir'); - $this->dumpOutput(); - } - - function testDumpOfList() { - $this->execute('ls'); - $this->dump($this->getOutputAsList()); - } -} - -class PassesAsWellReporter extends HtmlReporter { - - protected function getCss() { - return parent::getCss() . ' .pass { color: darkgreen; }'; - } - - function paintPass($message) { - parent::paintPass($message); - print "Pass: "; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print implode(" -> ", $breadcrumb); - print " -> " . htmlentities($message) . "
\n"; - } - - function paintSignal($type, &$payload) { - print "$type: "; - $breadcrumb = $this->getTestList(); - array_shift($breadcrumb); - print implode(" -> ", $breadcrumb); - print " -> " . htmlentities(serialize($payload)) . "
\n"; - } -} - -class TestOfSkippingNoMatterWhat extends UnitTestCase { - function skip() { - $this->skipIf(true, 'Always skipped -> %s'); - } - - function testFail() { - $this->fail('This really shouldn\'t have happened'); - } -} - -class TestOfSkippingOrElse extends UnitTestCase { - function skip() { - $this->skipUnless(false, 'Always skipped -> %s'); - } - - function testFail() { - $this->fail('This really shouldn\'t have happened'); - } -} - -class TestOfSkippingTwiceOver extends UnitTestCase { - function skip() { - $this->skipIf(true, 'First reason -> %s'); - $this->skipIf(true, 'Second reason -> %s'); - } - - function testFail() { - $this->fail('This really shouldn\'t have happened'); - } -} - -class TestThatShouldNotBeSkipped extends UnitTestCase { - function skip() { - $this->skipIf(false); - $this->skipUnless(true); - } - - function testFail() { - $this->fail('We should see this message'); - } - - function testPass() { - $this->pass('We should see this message'); - } -} - -$test = &new TestSuite('Visual test with 46 passes, 47 fails and 0 exceptions'); -$test->add(new PassingUnitTestCaseOutput()); -$test->add(new FailingUnitTestCaseOutput()); -$test->add(new TestOfMockObjectsOutput()); -$test->add(new TestOfPastBugs()); -$test->add(new TestOfVisualShell()); -$test->add(new TestOfSkippingNoMatterWhat()); -$test->add(new TestOfSkippingOrElse()); -$test->add(new TestOfSkippingTwiceOver()); -$test->add(new TestThatShouldNotBeSkipped()); - -if (isset($_GET['xml']) || in_array('xml', (isset($argv) ? $argv : array()))) { - $reporter = new XmlReporter(); -} elseif (TextReporter::inCli()) { - $reporter = new TextReporter(); -} else { - $reporter = new PassesAsWellReporter(); -} -if (isset($_GET['dry']) || in_array('dry', (isset($argv) ? $argv : array()))) { - $reporter->makeDry(); -} -exit ($test->run($reporter) ? 0 : 1); -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/web_tester_test.php b/3rdparty/simpletest/test/web_tester_test.php deleted file mode 100644 index 8c3bf1adf639e8587c048f314239cc86928629a1..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/web_tester_test.php +++ /dev/null @@ -1,155 +0,0 @@ -assertTrue($expectation->test('a')); - $this->assertTrue($expectation->test(array('a'))); - $this->assertFalse($expectation->test('A')); - } - - function testMatchesInteger() { - $expectation = new FieldExpectation('1'); - $this->assertTrue($expectation->test('1')); - $this->assertTrue($expectation->test(1)); - $this->assertTrue($expectation->test(array('1'))); - $this->assertTrue($expectation->test(array(1))); - } - - function testNonStringFailsExpectation() { - $expectation = new FieldExpectation('a'); - $this->assertFalse($expectation->test(null)); - } - - function testUnsetFieldCanBeTestedFor() { - $expectation = new FieldExpectation(false); - $this->assertTrue($expectation->test(false)); - } - - function testMultipleValuesCanBeInAnyOrder() { - $expectation = new FieldExpectation(array('a', 'b')); - $this->assertTrue($expectation->test(array('a', 'b'))); - $this->assertTrue($expectation->test(array('b', 'a'))); - $this->assertFalse($expectation->test(array('a', 'a'))); - $this->assertFalse($expectation->test('a')); - } - - function testSingleItemCanBeArrayOrString() { - $expectation = new FieldExpectation(array('a')); - $this->assertTrue($expectation->test(array('a'))); - $this->assertTrue($expectation->test('a')); - } -} - -class TestOfHeaderExpectations extends UnitTestCase { - - function testExpectingOnlyTheHeaderName() { - $expectation = new HttpHeaderExpectation('a'); - $this->assertIdentical($expectation->test(false), false); - $this->assertIdentical($expectation->test('a: A'), true); - $this->assertIdentical($expectation->test('A: A'), true); - $this->assertIdentical($expectation->test('a: B'), true); - $this->assertIdentical($expectation->test(' a : A '), true); - } - - function testHeaderValueAsWell() { - $expectation = new HttpHeaderExpectation('a', 'A'); - $this->assertIdentical($expectation->test(false), false); - $this->assertIdentical($expectation->test('a: A'), true); - $this->assertIdentical($expectation->test('A: A'), true); - $this->assertIdentical($expectation->test('A: a'), false); - $this->assertIdentical($expectation->test('a: B'), false); - $this->assertIdentical($expectation->test(' a : A '), true); - $this->assertIdentical($expectation->test(' a : AB '), false); - } - - function testHeaderValueWithColons() { - $expectation = new HttpHeaderExpectation('a', 'A:B:C'); - $this->assertIdentical($expectation->test('a: A'), false); - $this->assertIdentical($expectation->test('a: A:B'), false); - $this->assertIdentical($expectation->test('a: A:B:C'), true); - $this->assertIdentical($expectation->test('a: A:B:C:D'), false); - } - - function testMultilineSearch() { - $expectation = new HttpHeaderExpectation('a', 'A'); - $this->assertIdentical($expectation->test("aa: A\r\nb: B\r\nc: C"), false); - $this->assertIdentical($expectation->test("aa: A\r\na: A\r\nb: B"), true); - } - - function testMultilineSearchWithPadding() { - $expectation = new HttpHeaderExpectation('a', ' A '); - $this->assertIdentical($expectation->test("aa:A\r\nb:B\r\nc:C"), false); - $this->assertIdentical($expectation->test("aa:A\r\na:A\r\nb:B"), true); - } - - function testPatternMatching() { - $expectation = new HttpHeaderExpectation('a', new PatternExpectation('/A/')); - $this->assertIdentical($expectation->test('a: A'), true); - $this->assertIdentical($expectation->test('A: A'), true); - $this->assertIdentical($expectation->test('A: a'), false); - $this->assertIdentical($expectation->test('a: B'), false); - $this->assertIdentical($expectation->test(' a : A '), true); - $this->assertIdentical($expectation->test(' a : AB '), true); - } - - function testCaseInsensitivePatternMatching() { - $expectation = new HttpHeaderExpectation('a', new PatternExpectation('/A/i')); - $this->assertIdentical($expectation->test('a: a'), true); - $this->assertIdentical($expectation->test('a: B'), false); - $this->assertIdentical($expectation->test(' a : A '), true); - $this->assertIdentical($expectation->test(' a : BAB '), true); - $this->assertIdentical($expectation->test(' a : bab '), true); - } - - function testUnwantedHeader() { - $expectation = new NoHttpHeaderExpectation('a'); - $this->assertIdentical($expectation->test(''), true); - $this->assertIdentical($expectation->test('stuff'), true); - $this->assertIdentical($expectation->test('b: B'), true); - $this->assertIdentical($expectation->test('a: A'), false); - $this->assertIdentical($expectation->test('A: A'), false); - } - - function testMultilineUnwantedSearch() { - $expectation = new NoHttpHeaderExpectation('a'); - $this->assertIdentical($expectation->test("aa:A\r\nb:B\r\nc:C"), true); - $this->assertIdentical($expectation->test("aa:A\r\na:A\r\nb:B"), false); - } - - function testLocationHeaderSplitsCorrectly() { - $expectation = new HttpHeaderExpectation('Location', 'http://here/'); - $this->assertIdentical($expectation->test('Location: http://here/'), true); - } -} - -class TestOfTextExpectations extends UnitTestCase { - - function testMatchingSubString() { - $expectation = new TextExpectation('wanted'); - $this->assertIdentical($expectation->test(''), false); - $this->assertIdentical($expectation->test('Wanted'), false); - $this->assertIdentical($expectation->test('wanted'), true); - $this->assertIdentical($expectation->test('the wanted text is here'), true); - } - - function testNotMatchingSubString() { - $expectation = new NoTextExpectation('wanted'); - $this->assertIdentical($expectation->test(''), true); - $this->assertIdentical($expectation->test('Wanted'), true); - $this->assertIdentical($expectation->test('wanted'), false); - $this->assertIdentical($expectation->test('the wanted text is here'), false); - } -} - -class TestOfGenericAssertionsInWebTester extends WebTestCase { - function testEquality() { - $this->assertEqual('a', 'a'); - $this->assertNotEqual('a', 'A'); - } -} -?> \ No newline at end of file diff --git a/3rdparty/simpletest/test/xml_test.php b/3rdparty/simpletest/test/xml_test.php deleted file mode 100644 index f99e0dcd98b07dbe7489512ee6cf14f38e2e4253..0000000000000000000000000000000000000000 --- a/3rdparty/simpletest/test/xml_test.php +++ /dev/null @@ -1,187 +0,0 @@ - 2)); - $this->assertEqual($nesting->getSize(), 2); - } -} - -class TestOfXmlStructureParsing extends UnitTestCase { - function testValidXml() { - $listener = new MockSimpleScorer(); - $listener->expectNever('paintGroupStart'); - $listener->expectNever('paintGroupEnd'); - $listener->expectNever('paintCaseStart'); - $listener->expectNever('paintCaseEnd'); - $parser = new SimpleTestXmlParser($listener); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("\n")); - } - - function testEmptyGroup() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintGroupStart', array('a_group', 7)); - $listener->expectOnce('paintGroupEnd', array('a_group')); - $parser = new SimpleTestXmlParser($listener); - $parser->parse("\n"); - $parser->parse("\n"); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("a_group\n")); - $this->assertTrue($parser->parse("\n")); - $parser->parse("\n"); - } - - function testEmptyCase() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintCaseStart', array('a_case')); - $listener->expectOnce('paintCaseEnd', array('a_case')); - $parser = new SimpleTestXmlParser($listener); - $parser->parse("\n"); - $parser->parse("\n"); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("a_case\n")); - $this->assertTrue($parser->parse("\n")); - $parser->parse("\n"); - } - - function testEmptyMethod() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintCaseStart', array('a_case')); - $listener->expectOnce('paintCaseEnd', array('a_case')); - $listener->expectOnce('paintMethodStart', array('a_method')); - $listener->expectOnce('paintMethodEnd', array('a_method')); - $parser = new SimpleTestXmlParser($listener); - $parser->parse("\n"); - $parser->parse("\n"); - $parser->parse("\n"); - $parser->parse("a_case\n"); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("a_method\n")); - $this->assertTrue($parser->parse("\n")); - $parser->parse("\n"); - $parser->parse("\n"); - } - - function testNestedGroup() { - $listener = new MockSimpleScorer(); - $listener->expectAt(0, 'paintGroupStart', array('a_group', 7)); - $listener->expectAt(1, 'paintGroupStart', array('b_group', 3)); - $listener->expectCallCount('paintGroupStart', 2); - $listener->expectAt(0, 'paintGroupEnd', array('b_group')); - $listener->expectAt(1, 'paintGroupEnd', array('a_group')); - $listener->expectCallCount('paintGroupEnd', 2); - - $parser = new SimpleTestXmlParser($listener); - $parser->parse("\n"); - $parser->parse("\n"); - - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("a_group\n")); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("b_group\n")); - $this->assertTrue($parser->parse("\n")); - $this->assertTrue($parser->parse("\n")); - $parser->parse("\n"); - } -} - -class AnyOldSignal { - public $stuff = true; -} - -class TestOfXmlResultsParsing extends UnitTestCase { - - function sendValidStart(&$parser) { - $parser->parse("\n"); - $parser->parse("\n"); - $parser->parse("\n"); - $parser->parse("a_case\n"); - $parser->parse("\n"); - $parser->parse("a_method\n"); - } - - function sendValidEnd(&$parser) { - $parser->parse("\n"); - $parser->parse("\n"); - $parser->parse("\n"); - } - - function testPass() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintPass', array('a_message')); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("a_message\n")); - $this->sendValidEnd($parser); - } - - function testFail() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintFail', array('a_message')); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("a_message\n")); - $this->sendValidEnd($parser); - } - - function testException() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintError', array('a_message')); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("a_message\n")); - $this->sendValidEnd($parser); - } - - function testSkip() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintSkip', array('a_message')); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("a_message\n")); - $this->sendValidEnd($parser); - } - - function testSignal() { - $signal = new AnyOldSignal(); - $signal->stuff = "Hello"; - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintSignal', array('a_signal', $signal)); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse( - "\n")); - $this->sendValidEnd($parser); - } - - function testMessage() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintMessage', array('a_message')); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("a_message\n")); - $this->sendValidEnd($parser); - } - - function testFormattedMessage() { - $listener = new MockSimpleScorer(); - $listener->expectOnce('paintFormattedMessage', array("\na\tmessage\n")); - $parser = new SimpleTestXmlParser($listener); - $this->sendValidStart($parser); - $this->assertTrue($parser->parse("\n")); - $this->sendValidEnd($parser); - } -} -?> \ No newline at end of file diff --git a/apps/admin_dependencies_chk/appinfo/app.php b/apps/admin_dependencies_chk/appinfo/app.php old mode 100755 new mode 100644 diff --git a/apps/admin_dependencies_chk/settings.php b/apps/admin_dependencies_chk/settings.php old mode 100755 new mode 100644 diff --git a/apps/admin_migrate/appinfo/app.php b/apps/admin_migrate/appinfo/app.php old mode 100755 new mode 100644 diff --git a/apps/admin_migrate/settings.php b/apps/admin_migrate/settings.php old mode 100755 new mode 100644 diff --git a/apps/bookmarks/addBm.php b/apps/bookmarks/addBm.php old mode 100755 new mode 100644 diff --git a/apps/bookmarks/ajax/addBookmark.php b/apps/bookmarks/ajax/addBookmark.php old mode 100755 new mode 100644 diff --git a/apps/bookmarks/ajax/delBookmark.php b/apps/bookmarks/ajax/delBookmark.php old mode 100755 new mode 100644 diff --git a/apps/bookmarks/ajax/editBookmark.php b/apps/bookmarks/ajax/editBookmark.php old mode 100755 new mode 100644 diff --git a/apps/bookmarks/ajax/recordClick.php b/apps/bookmarks/ajax/recordClick.php old mode 100755 new mode 100644 diff --git a/apps/bookmarks/ajax/updateList.php b/apps/bookmarks/ajax/updateList.php old mode 100755 new mode 100644 diff --git a/apps/bookmarks/appinfo/app.php b/apps/bookmarks/appinfo/app.php old mode 100755 new mode 100644 diff --git a/apps/bookmarks/appinfo/migrate.php b/apps/bookmarks/appinfo/migrate.php old mode 100755 new mode 100644 diff --git a/apps/bookmarks/bookmarksHelper.php b/apps/bookmarks/bookmarksHelper.php old mode 100755 new mode 100644 diff --git a/apps/bookmarks/index.php b/apps/bookmarks/index.php old mode 100755 new mode 100644 diff --git a/apps/bookmarks/js/bookmarks.js b/apps/bookmarks/js/bookmarks.js index 73986e491860a28c17f4013c65acd50c1f51f686..a746cf437bf9d209cee4b5debee629b2984801b8 100644 --- a/apps/bookmarks/js/bookmarks.js +++ b/apps/bookmarks/js/bookmarks.js @@ -60,7 +60,14 @@ function addOrEditBookmark(event) { var title = encodeEntities($('#bookmark_add_title').val()); var tags = encodeEntities($('#bookmark_add_tags').val()); $("#firstrun").hide(); - + if($.trim(url) == '') { + OC.dialogs.alert('A valid bookmark url must be provided', 'Error creating bookmark'); + return false; + } + if($.trim(title) == '') { + OC.dialogs.alert('A valid bookmark title must be provided', 'Error creating bookmark'); + return false; + } if (id == 0) { $.ajax({ url: OC.filePath('bookmarks', 'ajax', 'addBookmark.php'), @@ -115,11 +122,8 @@ function showBookmark(event) { if ($('.bookmarks_add').css('display') == 'none') { $('.bookmarks_add').slideToggle(); } - $('html, body').animate({ - scrollTop: ($('.bookmarks_menu'))?$('.bookmarks_menu').offset().top:0 - }, 500); - } + function replaceQueryString(url,param,value) { var re = new RegExp("([?|&])" + param + "=.*?(&|$)","i"); if (url.match(re)) diff --git a/apps/bookmarks/lib/bookmarks.php b/apps/bookmarks/lib/bookmarks.php old mode 100755 new mode 100644 diff --git a/apps/bookmarks/lib/search.php b/apps/bookmarks/lib/search.php old mode 100755 new mode 100644 diff --git a/apps/bookmarks/settings.php b/apps/bookmarks/settings.php old mode 100755 new mode 100644 diff --git a/apps/bookmarks/templates/bookmarklet.php b/apps/bookmarks/templates/bookmarklet.php old mode 100755 new mode 100644 diff --git a/apps/bookmarks/templates/list.php b/apps/bookmarks/templates/list.php index ced6154c1986533749e215f02d9190cfcd45071c..fdd2b19f79ac0dcee2ce737cdb57c26a975c66e2 100644 --- a/apps/bookmarks/templates/list.php +++ b/apps/bookmarks/templates/list.php @@ -7,7 +7,7 @@ * See the COPYING-README file. */ ?> - +
diff --git a/apps/calendar/ajax/calendar/activation.php b/apps/calendar/ajax/calendar/activation.php old mode 100755 new mode 100644 index 3523590aa27df0180aaec803f183385eb3fb7f01..380db6a9437c46aae0ecc2546459d31c48f8bda5 --- a/apps/calendar/ajax/calendar/activation.php +++ b/apps/calendar/ajax/calendar/activation.php @@ -10,7 +10,11 @@ OCP\JSON::checkLoggedIn(); OCP\JSON::checkAppEnabled('calendar'); $calendarid = $_POST['calendarid']; -$calendar = OC_Calendar_App::getCalendar($calendarid);//access check +$calendar = OC_Calendar_App::getCalendar($calendarid, true); +if(!$calendar){ + OCP\JSON::error(array('message'=>'permission denied')); + exit; +} OC_Calendar_Calendar::setCalendarActive($calendarid, $_POST['active']); $calendar = OC_Calendar_App::getCalendar($calendarid); OCP\JSON::success(array( diff --git a/apps/calendar/ajax/calendar/delete.php b/apps/calendar/ajax/calendar/delete.php old mode 100755 new mode 100644 index a36a05346500c436b64892fb19e3257451c6548b..9e092f2df1d931d9c4cd9d32bb21db3460c8a412 --- a/apps/calendar/ajax/calendar/delete.php +++ b/apps/calendar/ajax/calendar/delete.php @@ -11,7 +11,11 @@ OCP\JSON::checkLoggedIn(); OCP\JSON::checkAppEnabled('calendar'); $cal = $_POST["calendarid"]; -$calendar = OC_Calendar_App::getCalendar($cal); +$calendar = OC_Calendar_App::getCalendar($cal, true); +if(!$calendar){ + OCP\JSON::error(array('message'=>'permission denied')); + exit; +} $del = OC_Calendar_Calendar::deleteCalendar($cal); if($del == true){ OCP\JSON::success(); diff --git a/apps/calendar/ajax/calendar/edit.form.php b/apps/calendar/ajax/calendar/edit.form.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/calendar/edit.php b/apps/calendar/ajax/calendar/edit.php old mode 100755 new mode 100644 index 77366809311ced6709508d3b0f0372eaccf2fc16..516c9f6c765c81237ad0265720708e70d346bea8 --- a/apps/calendar/ajax/calendar/edit.php +++ b/apps/calendar/ajax/calendar/edit.php @@ -11,7 +11,11 @@ OCP\JSON::checkLoggedIn(); OCP\JSON::checkAppEnabled('calendar'); $calendarcolor_options = OC_Calendar_Calendar::getCalendarColorOptions(); -$calendar = OC_Calendar_App::getCalendar($_GET['calendarid']); +$calendar = OC_Calendar_App::getCalendar($_GET['calendarid'], true); +if(!$calendar){ + OCP\JSON::error(array('message'=>'permission denied')); + exit; +} $tmpl = new OCP\Template("calendar", "part.editcalendar"); $tmpl->assign('new', false); $tmpl->assign('calendarcolor_options', $calendarcolor_options); diff --git a/apps/calendar/ajax/calendar/new.form.php b/apps/calendar/ajax/calendar/new.form.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/calendar/new.php b/apps/calendar/ajax/calendar/new.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/calendar/overview.php b/apps/calendar/ajax/calendar/overview.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/calendar/update.php b/apps/calendar/ajax/calendar/update.php old mode 100755 new mode 100644 index 3b1cc32b3165bfc7cf2d5c4e2c9e6d3f8e5459ef..dce0027304aba8086bb16b80c1162ac205dc3bcb --- a/apps/calendar/ajax/calendar/update.php +++ b/apps/calendar/ajax/calendar/update.php @@ -25,7 +25,11 @@ foreach($calendars as $cal){ } $calendarid = $_POST['id']; -$calendar = OC_Calendar_App::getCalendar($calendarid);//access check +$calendar = OC_Calendar_App::getCalendar($calendarid, true); +if(!$calendar){ + OCP\JSON::error(array('message'=>'permission denied')); + exit; +} OC_Calendar_Calendar::editCalendar($calendarid, strip_tags($_POST['name']), null, null, null, $_POST['color']); OC_Calendar_Calendar::setCalendarActive($calendarid, $_POST['active']); diff --git a/apps/calendar/ajax/categories/rescan.php b/apps/calendar/ajax/categories/rescan.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/changeview.php b/apps/calendar/ajax/changeview.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/event/delete.php b/apps/calendar/ajax/event/delete.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/event/edit.form.php b/apps/calendar/ajax/event/edit.form.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/event/edit.php b/apps/calendar/ajax/event/edit.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/event/move.php b/apps/calendar/ajax/event/move.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/event/new.form.php b/apps/calendar/ajax/event/new.form.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/event/new.php b/apps/calendar/ajax/event/new.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/event/resize.php b/apps/calendar/ajax/event/resize.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/events.php b/apps/calendar/ajax/events.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/import/dialog.php b/apps/calendar/ajax/import/dialog.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/import/import.php b/apps/calendar/ajax/import/import.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/settings/getfirstday.php b/apps/calendar/ajax/settings/getfirstday.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/settings/gettimezonedetection.php b/apps/calendar/ajax/settings/gettimezonedetection.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/settings/guesstimezone.php b/apps/calendar/ajax/settings/guesstimezone.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/settings/setfirstday.php b/apps/calendar/ajax/settings/setfirstday.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/settings/settimeformat.php b/apps/calendar/ajax/settings/settimeformat.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/settings/settimezone.php b/apps/calendar/ajax/settings/settimezone.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/settings/timeformat.php b/apps/calendar/ajax/settings/timeformat.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/settings/timezonedetection.php b/apps/calendar/ajax/settings/timezonedetection.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/share/activation.php b/apps/calendar/ajax/share/activation.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/share/changepermission.php b/apps/calendar/ajax/share/changepermission.php old mode 100755 new mode 100644 index e4a4f186ab06548457eecb15467e7fd6802b1959..2737420c94ede4c2717f8008cd163c040d401242 --- a/apps/calendar/ajax/share/changepermission.php +++ b/apps/calendar/ajax/share/changepermission.php @@ -17,6 +17,14 @@ switch($idtype){ OCP\JSON::error(array('message'=>'unexspected parameter')); exit; } +if($idtype == 'calendar' && !OC_Calendar_App::getCalendar($id)){ + OCP\JSON::error(array('message'=>'permission denied')); + exit; +} +if($idtype == 'event' && !OC_Calendar_App::getEventObject($id)){ + OCP\JSON::error(array('message'=>'permission denied')); + exit; +} $sharewith = $_GET['sharewith']; $sharetype = strip_tags($_GET['sharetype']); switch($sharetype){ diff --git a/apps/calendar/ajax/share/dropdown.php b/apps/calendar/ajax/share/dropdown.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/share/share.php b/apps/calendar/ajax/share/share.php old mode 100755 new mode 100644 diff --git a/apps/calendar/ajax/share/unshare.php b/apps/calendar/ajax/share/unshare.php old mode 100755 new mode 100644 index cbd5ed8e505bbe8c511e919578316be2c8a2c49d..fe7c98452d7e14528dd4d9532944d1ee51350756 --- a/apps/calendar/ajax/share/unshare.php +++ b/apps/calendar/ajax/share/unshare.php @@ -16,6 +16,14 @@ switch($idtype){ OCP\JSON::error(array('message'=>'unexspected parameter')); exit; } +if($idtype == 'calendar' && !OC_Calendar_App::getCalendar($id)){ + OCP\JSON::error(array('message'=>'permission denied')); + exit; +} +if($idtype == 'event' && !OC_Calendar_App::getEventObject($id)){ + OCP\JSON::error(array('message'=>'permission denied')); + exit; +} $sharewith = $_GET['sharewith']; $sharetype = strip_tags($_GET['sharetype']); switch($sharetype){ diff --git a/apps/calendar/appinfo/app.php b/apps/calendar/appinfo/app.php old mode 100755 new mode 100644 diff --git a/apps/calendar/appinfo/remote.php b/apps/calendar/appinfo/remote.php old mode 100755 new mode 100644 index 7ff6a2fbbe2b3cbc00111bac59adb9d7f8258dbe..3bd8737ee974831bc6577f83b1bad2640c973215 --- a/apps/calendar/appinfo/remote.php +++ b/apps/calendar/appinfo/remote.php @@ -7,6 +7,14 @@ */ OCP\App::checkAppEnabled('calendar'); +if(substr($_SERVER["REQUEST_URI"],0,strlen(OC::$APPSWEBROOT . '/apps/calendar/caldav.php')) == OC::$APPSWEBROOT . '/apps/calendar/caldav.php'){ + $baseuri = OC::$APPSWEBROOT . '/apps/calendar/caldav.php'; +} + +// only need authentication apps +$RUNTIME_APPTYPES=array('authentication'); +OC_App::loadApps($RUNTIME_APPTYPES); + // Backends $authBackend = new OC_Connector_Sabre_Auth(); $principalBackend = new OC_Connector_Sabre_Principal(); diff --git a/apps/calendar/appinfo/update.php b/apps/calendar/appinfo/update.php old mode 100755 new mode 100644 diff --git a/apps/calendar/caldav.php b/apps/calendar/caldav.php new file mode 100644 index 0000000000000000000000000000000000000000..7b811d3cdf1225da95b546c69564198cfc8bba9e --- /dev/null +++ b/apps/calendar/caldav.php @@ -0,0 +1,6 @@ +' + $('#share_user option:selected').text() + ''; + var newitem = '
  • ' + $('#share_user option:selected').text() + '
  • '; $('#sharewithuser_list').append(newitem); $('#sharewithuser_' + $('#share_user option:selected').text() + ' > img').click(function(){ $('#share_user option[value="' + $(this).parent().text() + '"]').removeAttr('disabled'); @@ -558,7 +559,7 @@ Calendar={ $('#share_group').live('change', function(){ if($('#sharewithgroup_' + $('#share_group option:selected').text()).length == 0){ Calendar.UI.Share.share(Calendar.UI.Share.currentid, Calendar.UI.Share.idtype, $('#share_group option:selected').text(), 'group'); - var newitem = '
  • ' + $('#share_group option:selected').text() + '
  • '; + var newitem = '
  • ' + $('#share_group option:selected').text() + '
  • '; $('#sharewithgroup_list').append(newitem); $('#sharewithgroup_' + $('#share_group option:selected').text() + ' > img').click(function(){ $('#share_group option[value="' + $(this).parent().text() + '"]').removeAttr('disabled'); diff --git a/apps/calendar/l10n/ca.php b/apps/calendar/l10n/ca.php index 50e9c1fc56e88e510a311cc5115f73ba3f662f6a..afb1c799d93d9e012b30ce39ccf1b0579578163f 100644 --- a/apps/calendar/l10n/ca.php +++ b/apps/calendar/l10n/ca.php @@ -1,9 +1,12 @@ "No s'han trobat calendaris.", +"No events found." => "No s'han trobat events.", "Wrong calendar" => "Calendari erroni", "New Timezone:" => "Nova zona horària:", "Timezone changed" => "La zona horària ha canviat", "Invalid request" => "Sol.licitud no vàlida", "Calendar" => "Calendari", +"MMM d[ yyyy]{ '—'[ MMM] d yyyy}" => "MMM d[ yyyy]{ '—'[ MMM] d yyyy}", "Birthday" => "Aniversari", "Business" => "Feina", "Call" => "Trucada", @@ -19,6 +22,7 @@ "Projects" => "Projectes", "Questions" => "Preguntes", "Work" => "Feina", +"unnamed" => "sense nom", "Does not repeat" => "No es repeteix", "Daily" => "Diari", "Weekly" => "Mensual", @@ -80,10 +84,15 @@ "Calendars" => "Calendaris", "There was a fail, while parsing the file." => "S'ha produït un error en analitzar el fitxer.", "Choose active calendars" => "Seleccioneu calendaris actius", +"Your calendars" => "Els vostres calendaris", "CalDav Link" => "Enllaç CalDav", +"Shared calendars" => "Calendaris compartits", +"No shared calendars" => "No hi ha calendaris compartits", +"Share Calendar" => "Comparteix el calendari", "Download" => "Baixa", "Edit" => "Edita", "Delete" => "Suprimeix", +"shared with you by" => "compartit amb vós", "New calendar" => "Calendari nou", "Edit calendar" => "Edita el calendari", "Displayname" => "Mostra el nom", @@ -94,8 +103,15 @@ "Cancel" => "Cancel·la", "Edit an event" => "Edició d'un esdeveniment", "Export" => "Exporta", +"Eventinfo" => "Eventinfo", +"Repeating" => "Repetició", +"Alarm" => "Alarma", +"Attendees" => "Assistents", +"Share" => "Comparteix", "Title of the Event" => "Títol de l'esdeveniment", "Category" => "Categoria", +"Separate categories with commas" => "Separeu les categories amb comes", +"Edit categories" => "Edita categories", "All Day Event" => "Esdeveniment de tot el dia", "From" => "Des de", "To" => "Fins a", @@ -125,11 +141,22 @@ "Calendar imported successfully" => "El calendari s'ha importat amb èxit", "Close Dialog" => "Tanca el diàleg", "Create a new event" => "Crea un nou esdeveniment", +"View an event" => "Mostra un event", +"No categories selected" => "No hi ha categories seleccionades", "Select category" => "Seleccioneu categoria", +"of" => "de", +"at" => "a", "Timezone" => "Zona horària", "Check always for changes of the timezone" => "Comprova sempre en els canvis de zona horària", "Timeformat" => "Format de temps", "24h" => "24h", "12h" => "12h", -"Calendar CalDAV syncing address:" => "Adreça de sincronització del calendari CalDAV:" +"First day of the week" => "Primer dia de la setmana", +"Calendar CalDAV syncing address:" => "Adreça de sincronització del calendari CalDAV:", +"Users" => "Usuaris", +"select users" => "seleccioneu usuaris", +"Editable" => "Editable", +"Groups" => "Grups", +"select groups" => "seleccioneu grups", +"make public" => "fes-ho public" ); diff --git a/apps/calendar/l10n/cs_CZ.php b/apps/calendar/l10n/cs_CZ.php index 5149aea8fe5b1bae6d786152cdf3acaf97640761..05d286d82c1a4af4ca35e8e03785b43ff6e98fca 100644 --- a/apps/calendar/l10n/cs_CZ.php +++ b/apps/calendar/l10n/cs_CZ.php @@ -1,9 +1,12 @@ "Žádné kalendáře nenalezeny.", +"No events found." => "Žádné události nenalezeny.", "Wrong calendar" => "Nesprávný kalendář", "New Timezone:" => "Nová časová zóna:", "Timezone changed" => "Časová zóna byla změněna", "Invalid request" => "Chybný požadavek", "Calendar" => "Kalendář", +"MMM d[ yyyy]{ '—'[ MMM] d yyyy}" => "d. MMM[ yyyy]{ '—' d.[ MMM] yyyy}", "Birthday" => "Narozeniny", "Business" => "Obchodní", "Call" => "Hovor", @@ -19,6 +22,7 @@ "Projects" => "Projekty", "Questions" => "Dotazy", "Work" => "Pracovní", +"unnamed" => "nepojmenováno", "Does not repeat" => "Neopakuje se", "Daily" => "Denně", "Weekly" => "Týdně", @@ -80,10 +84,15 @@ "Calendars" => "Kalendáře", "There was a fail, while parsing the file." => "Chyba při převodu souboru", "Choose active calendars" => "Vybrat aktivní kalendář", +"Your calendars" => "Vaše kalendáře", "CalDav Link" => "CalDav odkaz", +"Shared calendars" => "Sdílené kalendáře", +"No shared calendars" => "Žádné sdílené kalendáře", +"Share Calendar" => "Sdílet kalendář", "Download" => "Stáhnout", "Edit" => "Editovat", "Delete" => "Odstranit", +"shared with you by" => "sdíleno s vámi uživatelem", "New calendar" => "Nový kalendář", "Edit calendar" => "Editovat kalendář", "Displayname" => "Zobrazované jméno", @@ -94,8 +103,15 @@ "Cancel" => "Storno", "Edit an event" => "Editovat událost", "Export" => "Export", +"Eventinfo" => "Informace o události", +"Repeating" => "Opakující se", +"Alarm" => "Alarm", +"Attendees" => "Účastníci", +"Share" => "Sdílet", "Title of the Event" => "Název události", "Category" => "Kategorie", +"Separate categories with commas" => "Kategorie oddělené čárkami", +"Edit categories" => "Upravit kategorie", "All Day Event" => "Celodenní událost", "From" => "od", "To" => "do", @@ -125,11 +141,22 @@ "Calendar imported successfully" => "Kalendář byl úspěšně importován", "Close Dialog" => "Zavřít dialog", "Create a new event" => "Vytvořit novou událost", +"View an event" => "Zobrazit událost", +"No categories selected" => "Žádné kategorie nevybrány", "Select category" => "Vyberte kategorii", +"of" => "z", +"at" => "v", "Timezone" => "Časové pásmo", "Check always for changes of the timezone" => "Vždy kontrolavat, zda nedošlo ke změně časového pásma", "Timeformat" => "Formát času", "24h" => "24h", "12h" => "12h", -"Calendar CalDAV syncing address:" => "Adresa pro synchronizaci kalendáře pomocí CalDAV:" +"First day of the week" => "Týden začína v", +"Calendar CalDAV syncing address:" => "Adresa pro synchronizaci kalendáře pomocí CalDAV:", +"Users" => "Uživatelé", +"select users" => "vybrat uživatele", +"Editable" => "Upravovatelné", +"Groups" => "Skupiny", +"select groups" => "vybrat skupiny", +"make public" => "zveřejnit" ); diff --git a/apps/calendar/l10n/de.php b/apps/calendar/l10n/de.php index 47d8145e12dbdeda0bf8b976081c1b74cb1d6d0e..34e6f05f100473fd6b08c600dedbf96d8eb20913 100644 --- a/apps/calendar/l10n/de.php +++ b/apps/calendar/l10n/de.php @@ -1,4 +1,6 @@ "Keine Kalender gefunden", +"No events found." => "Keine Termine gefunden", "Wrong calendar" => "Falscher Kalender", "New Timezone:" => "Neue Zeitzone:", "Timezone changed" => "Zeitzone geändert", @@ -19,6 +21,7 @@ "Projects" => "Projekte", "Questions" => "Fragen", "Work" => "Arbeit", +"unnamed" => "unbenannt", "Does not repeat" => "einmalig", "Daily" => "täglich", "Weekly" => "wöchentlich", @@ -80,10 +83,15 @@ "Calendars" => "Kalender", "There was a fail, while parsing the file." => "Fehler beim Einlesen der Datei.", "Choose active calendars" => "Aktive Kalender wählen", +"Your calendars" => "Deine Kalender", "CalDav Link" => "CalDAV-Link", +"Shared calendars" => "geteilte Kalender", +"No shared calendars" => "Keine geteilten Kalender", +"Share Calendar" => "Kalender teilen", "Download" => "Herunterladen", "Edit" => "Bearbeiten", "Delete" => "Löschen", +"shared with you by" => "Von dir geteilt mit", "New calendar" => "Neuer Kalender", "Edit calendar" => "Kalender bearbeiten", "Displayname" => "Anzeigename", @@ -94,8 +102,15 @@ "Cancel" => "Abbrechen", "Edit an event" => "Ereignis bearbeiten", "Export" => "Exportieren", +"Eventinfo" => "Termininfo", +"Repeating" => "Wiederholen", +"Alarm" => "Alarm", +"Attendees" => "Teilnehmer", +"Share" => "Teilen", "Title of the Event" => "Name", "Category" => "Kategorie", +"Separate categories with commas" => "Kategorien trennen mittels Komma", +"Edit categories" => "Kategorien ändern", "All Day Event" => "Ganztägiges Ereignis", "From" => "von", "To" => "bis", @@ -125,11 +140,21 @@ "Calendar imported successfully" => "Kalender erfolgreich importiert", "Close Dialog" => "Dialog schließen", "Create a new event" => "Neues Ereignis", +"View an event" => "Termin öffnen", +"No categories selected" => "Keine Kategorie ausgewählt", "Select category" => "Kategorie auswählen", +"of" => "von", "Timezone" => "Zeitzone", "Check always for changes of the timezone" => "immer die Zeitzone überprüfen", "Timeformat" => "Zeitformat", "24h" => "24h", "12h" => "12h", -"Calendar CalDAV syncing address:" => "Kalender CalDAV Synchronisationsadresse:" +"First day of the week" => "erster Wochentag", +"Calendar CalDAV syncing address:" => "Kalender CalDAV Synchronisationsadresse:", +"Users" => "Nutzer", +"select users" => "gewählte Nutzer", +"Editable" => "editierbar", +"Groups" => "Gruppen", +"select groups" => "Wähle Gruppen", +"make public" => "Veröffentlichen" ); diff --git a/apps/calendar/l10n/el.php b/apps/calendar/l10n/el.php index 53eaf452a4d754f03a099e32bfb62df376fcd7b3..0b289fbcf6848f8d6f6d00745050fe684da0cc72 100644 --- a/apps/calendar/l10n/el.php +++ b/apps/calendar/l10n/el.php @@ -1,9 +1,12 @@ "Δε βρέθηκαν ημερολόγια.", +"No events found." => "Δε βρέθηκαν γεγονότα.", "Wrong calendar" => "Λάθος ημερολόγιο", "New Timezone:" => "Νέα ζώνη ώρας:", "Timezone changed" => "Η ζώνη ώρας άλλαξε", "Invalid request" => "Μη έγκυρο αίτημα", "Calendar" => "Ημερολόγιο", +"MMM d[ yyyy]{ '—'[ MMM] d yyyy}" => "MMM d[ yyyy]{ '—'[ MMM] d yyyy}", "Birthday" => "Γενέθλια", "Business" => "Επιχείρηση", "Call" => "Κλήση", @@ -19,6 +22,7 @@ "Projects" => "Έργα", "Questions" => "Ερωτήσεις", "Work" => "Εργασία", +"unnamed" => "ανώνυμο", "Does not repeat" => "Μη επαναλαμβανόμενο", "Daily" => "Καθημερινά", "Weekly" => "Εβδομαδιαία", @@ -78,12 +82,17 @@ "List" => "Λίστα", "Today" => "Σήμερα", "Calendars" => "Ημερολόγια", -"There was a fail, while parsing the file." => "Υπήρξε μια αποτυχία, κατά την αξιολόγηση του αρχείου.", +"There was a fail, while parsing the file." => "Υπήρξε μια αποτυχία, κατά την σάρωση του αρχείου.", "Choose active calendars" => "Επιλέξτε τα ενεργά ημερολόγια", +"Your calendars" => "Τα ημερολόγια σου", "CalDav Link" => "Σύνδεση CalDAV", +"Shared calendars" => "Κοινόχρηστα ημερολόγια", +"No shared calendars" => "Δεν υπάρχουν κοινόχρηστα ημερολόγια", +"Share Calendar" => "Διαμοίρασε ένα ημερολόγιο", "Download" => "Λήψη", "Edit" => "Επεξεργασία", "Delete" => "Διαγραφή", +"shared with you by" => "μοιράστηκε μαζί σας από ", "New calendar" => "Νέο ημερολόγιο", "Edit calendar" => "Επεξεργασία ημερολογίου", "Displayname" => "Προβολή ονόματος", @@ -94,8 +103,15 @@ "Cancel" => "Ακύρωση", "Edit an event" => "Επεξεργασία ενός γεγονότος", "Export" => "Εξαγωγή", +"Eventinfo" => "Πληροφορίες γεγονότος", +"Repeating" => "Επαναλαμβανόμενο", +"Alarm" => "Ειδοποίηση", +"Attendees" => "Συμμετέχοντες", +"Share" => "Διαμοίρασε", "Title of the Event" => "Τίτλος συμβάντος", "Category" => "Κατηγορία", +"Separate categories with commas" => "Διαχώρισε τις κατηγορίες με κόμμα", +"Edit categories" => "Επεξεργασία κατηγοριών", "All Day Event" => "Ολοήμερο συμβάν", "From" => "Από", "To" => "Έως", @@ -125,11 +141,22 @@ "Calendar imported successfully" => "Το ημερολόγιο εισήχθει επιτυχώς", "Close Dialog" => "Κλείσιμο Διαλόγου", "Create a new event" => "Δημιουργήστε ένα νέο συμβάν", +"View an event" => "Εμφάνισε ένα γεγονός", +"No categories selected" => "Δεν επελέγησαν κατηγορίες", "Select category" => "Επιλέξτε κατηγορία", +"of" => "του", +"at" => "στο", "Timezone" => "Ζώνη ώρας", "Check always for changes of the timezone" => "Έλεγχος πάντα για τις αλλαγές της ζώνης ώρας", "Timeformat" => "Μορφή ώρας", "24h" => "24ω", "12h" => "12ω", -"Calendar CalDAV syncing address:" => "Διεύθυνση για το συγχρονισμού του ημερολογίου CalDAV:" +"First day of the week" => "Πρώτη μέρα της εβδομάδας", +"Calendar CalDAV syncing address:" => "Διεύθυνση για το συγχρονισμού του ημερολογίου CalDAV:", +"Users" => "Χρήστες", +"select users" => "επέλεξε χρήστες", +"Editable" => "Επεξεργάσιμο", +"Groups" => "Ομάδες", +"select groups" => "Επέλεξε ομάδες", +"make public" => "κάνε το δημόσιο" ); diff --git a/apps/calendar/l10n/eo.php b/apps/calendar/l10n/eo.php index 3b65ef63dd061c7e3336f7b66d45645277776fea..b1127d59ca99ede55d0d64bce1bcba7d644e874f 100644 --- a/apps/calendar/l10n/eo.php +++ b/apps/calendar/l10n/eo.php @@ -1,9 +1,12 @@ "Neniu kalendaro troviĝis.", +"No events found." => "Neniu okazaĵo troviĝis.", "Wrong calendar" => "Malĝusta kalendaro", "New Timezone:" => "Nova horzono:", "Timezone changed" => "La horozono estas ŝanĝita", "Invalid request" => "Nevalida peto", "Calendar" => "Kalendaro", +"MMM d[ yyyy]{ '—'[ MMM] d yyyy}" => "d MMM[ yyyy]{ '—'d[ MMM] yyyy}", "Birthday" => "Naskiĝotago", "Business" => "Negoco", "Call" => "Voko", @@ -19,10 +22,11 @@ "Projects" => "Projektoj", "Questions" => "Demandoj", "Work" => "Laboro", +"unnamed" => "nenomita", "Does not repeat" => "Ĉi tio ne ripetiĝas", "Daily" => "Tage", "Weekly" => "Semajne", -"Every Weekday" => "Tage", +"Every Weekday" => "Labortage", "Bi-Weekly" => "Semajnduope", "Monthly" => "Monate", "Yearly" => "Jare", @@ -80,10 +84,15 @@ "Calendars" => "Kalendaroj", "There was a fail, while parsing the file." => "Malsukceso okazis dum analizo de la dosiero.", "Choose active calendars" => "Elektu aktivajn kalendarojn", +"Your calendars" => "Viaj kalendaroj", "CalDav Link" => "CalDav-a ligilo", +"Shared calendars" => "Kunhavigitaj kalendaroj", +"No shared calendars" => "Neniu kunhavigita kalendaro", +"Share Calendar" => "Kunhavigi kalendaron", "Download" => "Elŝuti", "Edit" => "Redakti", "Delete" => "Forigi", +"shared with you by" => "kunhavigita kun vi fare de", "New calendar" => "Nova kalendaro", "Edit calendar" => "Redakti la kalendaron", "Displayname" => "Montrota nomo", @@ -94,14 +103,21 @@ "Cancel" => "Nuligi", "Edit an event" => "Redakti okazaĵon", "Export" => "Elporti", +"Eventinfo" => "Informo de okazaĵo", +"Repeating" => "Ripetata", +"Alarm" => "Alarmo", +"Attendees" => "Ĉeestontoj", +"Share" => "Kunhavigi", "Title of the Event" => "Okazaĵotitolo", "Category" => "Kategorio", +"Separate categories with commas" => "Disigi kategoriojn per komoj", +"Edit categories" => "Redakti kategoriojn", "All Day Event" => "La tuta tago", "From" => "Ekde", "To" => "Ĝis", "Advanced options" => "Altnivela agordo", "Location" => "Loko", -"Location of the Event" => "Okazaĵoloko", +"Location of the Event" => "Loko de okazaĵo", "Description" => "Priskribo", "Description of the Event" => "Okazaĵopriskribo", "Repeat" => "Ripeti", @@ -125,11 +141,22 @@ "Calendar imported successfully" => "La kalendaro enportiĝis sukcese", "Close Dialog" => "Fermi la dialogon", "Create a new event" => "Krei okazaĵon", +"View an event" => "Vidi okazaĵon", +"No categories selected" => "Neniu kategorio elektita", "Select category" => "Elekti kategorion", +"of" => "de", +"at" => "ĉe", "Timezone" => "Horozono", "Check always for changes of the timezone" => "Ĉiam kontroli ĉu la horzono ŝanĝiĝis", "Timeformat" => "Tempoformo", "24h" => "24h", "12h" => "12h", -"Calendar CalDAV syncing address:" => "Adreso de kalendarosinkronigo per CalDAV:" +"First day of the week" => "Unua tago de la semajno", +"Calendar CalDAV syncing address:" => "Adreso de kalendarosinkronigo per CalDAV:", +"Users" => "Uzantoj", +"select users" => "elekti uzantojn", +"Editable" => "Redaktebla", +"Groups" => "Grupoj", +"select groups" => "elekti grupojn", +"make public" => "publikigi" ); diff --git a/apps/calendar/l10n/es.php b/apps/calendar/l10n/es.php index e667ee10b8196bb2ede1ad4c32a605ac562784b9..4cd9e3202bf36b6619cbb1ee18638ca85b9d8905 100644 --- a/apps/calendar/l10n/es.php +++ b/apps/calendar/l10n/es.php @@ -1,9 +1,12 @@ "No se encontraron calendarios.", +"No events found." => "No se encontraron eventos.", "Wrong calendar" => "Calendario incorrecto", "New Timezone:" => "Nueva zona horaria:", "Timezone changed" => "Zona horaria cambiada", "Invalid request" => "Petición no válida", "Calendar" => "Calendario", +"MMM d[ yyyy]{ '—'[ MMM] d yyyy}" => "MMM d[ yyyy]{ '—'[ MMM] d yyyy}", "Birthday" => "Cumpleaños", "Business" => "Negocios", "Call" => "Llamada", @@ -19,6 +22,7 @@ "Projects" => "Proyectos", "Questions" => "Preguntas", "Work" => "Trabajo", +"unnamed" => "Sin nombre", "Does not repeat" => "No se repite", "Daily" => "Diariamente", "Weekly" => "Semanalmente", @@ -80,10 +84,15 @@ "Calendars" => "Calendarios", "There was a fail, while parsing the file." => "Se ha producido un fallo al analizar el archivo.", "Choose active calendars" => "Elige los calendarios activos", +"Your calendars" => "Tus calendarios", "CalDav Link" => "Enlace a CalDav", +"Shared calendars" => "Calendarios compartidos", +"No shared calendars" => "Calendarios no compartidos", +"Share Calendar" => "Compartir calendario", "Download" => "Descargar", "Edit" => "Editar", "Delete" => "Eliminar", +"shared with you by" => "compartido contigo por", "New calendar" => "Nuevo calendario", "Edit calendar" => "Editar calendario", "Displayname" => "Nombre", @@ -94,8 +103,15 @@ "Cancel" => "Cancelar", "Edit an event" => "Editar un evento", "Export" => "Exportar", +"Eventinfo" => "Información del evento", +"Repeating" => "Repetición", +"Alarm" => "Alarma", +"Attendees" => "Asistentes", +"Share" => "Compartir", "Title of the Event" => "Título del evento", "Category" => "Categoría", +"Separate categories with commas" => "Separar categorías con comas", +"Edit categories" => "Editar categorías", "All Day Event" => "Todo el día", "From" => "Desde", "To" => "Hasta", @@ -117,7 +133,7 @@ "End" => "Fin", "occurrences" => "ocurrencias", "Import a calendar file" => "Importar un archivo de calendario", -"Please choose the calendar" => "Elija el calendario", +"Please choose the calendar" => "Por favor elige el calendario", "create a new calendar" => "Crear un nuevo calendario", "Name of new calendar" => "Nombre del nuevo calendario", "Import" => "Importar", @@ -125,11 +141,22 @@ "Calendar imported successfully" => "Calendario importado exitosamente", "Close Dialog" => "Cerrar diálogo", "Create a new event" => "Crear un nuevo evento", +"View an event" => "Ver un evento", +"No categories selected" => "Ninguna categoría seleccionada", "Select category" => "Seleccionar categoría", +"of" => "de", +"at" => "a las", "Timezone" => "Zona horaria", "Check always for changes of the timezone" => "Comprobar siempre por cambios en la zona horaria", "Timeformat" => "Formato de hora", "24h" => "24h", "12h" => "12h", -"Calendar CalDAV syncing address:" => "Dirección de sincronización de calendario CalDAV:" +"First day of the week" => "Primer día de la semana", +"Calendar CalDAV syncing address:" => "Dirección de sincronización de calendario CalDAV:", +"Users" => "Usuarios", +"select users" => "seleccionar usuarios", +"Editable" => "Editable", +"Groups" => "Grupos", +"select groups" => "seleccionar grupos", +"make public" => "hacerlo público" ); diff --git a/apps/calendar/l10n/et_EE.php b/apps/calendar/l10n/et_EE.php index d80bf9edef8d4b3bb3ab7ed336820c546ebd345f..931ca56f5fdbcad0b4ff39f6ef6b846865240d7f 100644 --- a/apps/calendar/l10n/et_EE.php +++ b/apps/calendar/l10n/et_EE.php @@ -1,9 +1,12 @@ "Kalendreid ei leitud.", +"No events found." => "Üritusi ei leitud.", "Wrong calendar" => "Vale kalender", "New Timezone:" => "Uus ajavöönd:", "Timezone changed" => "Ajavöönd on muudetud", "Invalid request" => "Vigane päring", "Calendar" => "Kalender", +"MMM d[ yyyy]{ '—'[ MMM] d yyyy}" => "MMM d[ yyyy]{ '—'[ MMM] d yyyy}", "Birthday" => "Sünnipäev", "Business" => "Äri", "Call" => "Helista", @@ -19,6 +22,7 @@ "Projects" => "Projektid", "Questions" => "Küsimused", "Work" => "Töö", +"unnamed" => "nimetu", "Does not repeat" => "Ei kordu", "Daily" => "Iga päev", "Weekly" => "Iga nädal", @@ -80,10 +84,15 @@ "Calendars" => "Kalendrid", "There was a fail, while parsing the file." => "Faili parsimisel tekkis viga.", "Choose active calendars" => "Vali aktiivsed kalendrid", +"Your calendars" => "Sinu kalendrid", "CalDav Link" => "CalDav Link", +"Shared calendars" => "Jagatud kalendrid", +"No shared calendars" => "Jagatud kalendreid pole", +"Share Calendar" => "Jaga kalendrit", "Download" => "Lae alla", "Edit" => "Muuda", "Delete" => "Kustuta", +"shared with you by" => "jagas sinuga", "New calendar" => "Uus kalender", "Edit calendar" => "Muuda kalendrit", "Displayname" => "Näidatav nimi", @@ -94,8 +103,15 @@ "Cancel" => "Loobu", "Edit an event" => "Muuda sündmust", "Export" => "Ekspordi", +"Eventinfo" => "Ürituse info", +"Repeating" => "Kordamine", +"Alarm" => "Alarm", +"Attendees" => "Osalejad", +"Share" => "Jaga", "Title of the Event" => "Sündmuse pealkiri", "Category" => "Kategooria", +"Separate categories with commas" => "Eralda kategooriad komadega", +"Edit categories" => "Muuda kategooriaid", "All Day Event" => "Kogu päeva sündmus", "From" => "Alates", "To" => "Kuni", @@ -125,11 +141,22 @@ "Calendar imported successfully" => "Kalender on imporditud", "Close Dialog" => "Sulge dialoogiaken", "Create a new event" => "Loo sündmus", +"View an event" => "Vaata üritust", +"No categories selected" => "Ühtegi kategooriat pole valitud", "Select category" => "Salvesta kategooria", +"of" => "/", +"at" => "kell", "Timezone" => "Ajavöönd", "Check always for changes of the timezone" => "Kontrolli alati muudatusi ajavööndis", "Timeformat" => "Aja vorming", "24h" => "24h", "12h" => "12h", -"Calendar CalDAV syncing address:" => "Kalendri CalDAV sünkroniseerimise aadress:" +"First day of the week" => "Nädala esimene päev", +"Calendar CalDAV syncing address:" => "Kalendri CalDAV sünkroniseerimise aadress:", +"Users" => "Kasutajad", +"select users" => "valitud kasutajad", +"Editable" => "Muudetav", +"Groups" => "Grupid", +"select groups" => "valitud grupid", +"make public" => "tee avalikuks" ); diff --git a/apps/calendar/l10n/eu.php b/apps/calendar/l10n/eu.php index 2cfcbcdb3473ce28adf94ea88a8493157ee49d20..9e1300032f8cf04a771a5f9a4c21da6f728b6ff0 100644 --- a/apps/calendar/l10n/eu.php +++ b/apps/calendar/l10n/eu.php @@ -1,4 +1,6 @@ "Ez da egutegirik aurkitu.", +"No events found." => "Ez da gertaerarik aurkitu.", "Wrong calendar" => "Egutegi okerra", "New Timezone:" => "Ordu-zonalde berria", "Timezone changed" => "Ordu-zonaldea aldatuta", @@ -19,6 +21,7 @@ "Projects" => "Proiektuak", "Questions" => "Galderak", "Work" => "Lana", +"unnamed" => "izengabea", "Does not repeat" => "Ez da errepikatzen", "Daily" => "Egunero", "Weekly" => "Astero", @@ -27,6 +30,7 @@ "Monthly" => "Hilabetero", "Yearly" => "Urtero", "never" => "inoiz", +"by occurrences" => "errepikapen kopuruagatik", "by date" => "dataren arabera", "by monthday" => "hileko egunaren arabera", "by weekday" => "asteko egunaren arabera", @@ -79,10 +83,15 @@ "Calendars" => "Egutegiak", "There was a fail, while parsing the file." => "Huts bat egon da, fitxategia aztertzen zen bitartea.", "Choose active calendars" => "Aukeratu egutegi aktiboak", +"Your calendars" => "Zure egutegiak", "CalDav Link" => "CalDav lotura", +"Shared calendars" => "Elkarbanatutako egutegiak", +"No shared calendars" => "Ez dago elkarbanatutako egutegirik", +"Share Calendar" => "Elkarbanatu egutegia", "Download" => "Deskargatu", "Edit" => "Editatu", "Delete" => "Ezabatu", +"shared with you by" => "honek zurekin elkarbanatu du", "New calendar" => "Egutegi berria", "Edit calendar" => "Editatu egutegia", "Displayname" => "Bistaratzeko izena", @@ -93,8 +102,15 @@ "Cancel" => "Ezeztatu", "Edit an event" => "Editatu gertaera", "Export" => "Exportatu", +"Eventinfo" => "Gertaeraren informazioa", +"Repeating" => "Errepikapena", +"Alarm" => "Alarma", +"Attendees" => "Partaideak", +"Share" => "Elkarbanatu", "Title of the Event" => "Gertaeraren izenburua", "Category" => "Kategoria", +"Separate categories with commas" => "Banatu kategoriak komekin", +"Edit categories" => "Editatu kategoriak", "All Day Event" => "Egun osoko gertaera", "From" => "Hasiera", "To" => "Bukaera", @@ -124,11 +140,20 @@ "Calendar imported successfully" => "Egutegia ongi inportatu da", "Close Dialog" => "Itxi lehioa", "Create a new event" => "Sortu gertaera berria", +"View an event" => "Ikusi gertaera bat", +"No categories selected" => "Ez da kategoriarik hautatu", "Select category" => "Aukeratu kategoria", "Timezone" => "Ordu-zonaldea", "Check always for changes of the timezone" => "Egiaztatu beti ordu-zonalde aldaketen bila", "Timeformat" => "Ordu formatua", "24h" => "24h", "12h" => "12h", -"Calendar CalDAV syncing address:" => "Egutegiaren CalDAV sinkronizazio helbidea" +"First day of the week" => "Asteko lehenego eguna", +"Calendar CalDAV syncing address:" => "Egutegiaren CalDAV sinkronizazio helbidea", +"Users" => "Erabiltzaileak", +"select users" => "hautatutako erabiltzaileak", +"Editable" => "Editagarria", +"Groups" => "Taldeak", +"select groups" => "hautatutako taldeak", +"make public" => "publikoa egin" ); diff --git a/apps/calendar/l10n/fa.php b/apps/calendar/l10n/fa.php new file mode 100644 index 0000000000000000000000000000000000000000..cd2bb9c2e5ad7069103c1516ae4b6e0b9d8e4448 --- /dev/null +++ b/apps/calendar/l10n/fa.php @@ -0,0 +1,162 @@ + "هیچ تقویمی پیدا نشد", +"No events found." => "هیچ رویدادی پیدا نشد", +"Wrong calendar" => "تقویم اشتباه", +"New Timezone:" => "زمان محلی جدید", +"Timezone changed" => "زمان محلی تغییر یافت", +"Invalid request" => "درخواست نامعتبر", +"Calendar" => "تقویم", +"MMM d[ yyyy]{ '—'[ MMM] d yyyy}" => "DDD m[ yyyy]{ '—'[ DDD] m yyyy}", +"Birthday" => "روزتولد", +"Business" => "تجارت", +"Call" => "تماس گرفتن", +"Clients" => "مشتریان", +"Deliverer" => "نجات", +"Holidays" => "روزهای تعطیل", +"Ideas" => "ایده ها", +"Journey" => "سفر", +"Jubilee" => "سالگرد", +"Meeting" => "ملاقات", +"Other" => "دیگر", +"Personal" => "شخصی", +"Projects" => "پروژه ها", +"Questions" => "سوالات", +"Work" => "کار", +"unnamed" => "نام گذاری نشده", +"Does not repeat" => "تکرار نکنید", +"Daily" => "روزانه", +"Weekly" => "هفتهگی", +"Every Weekday" => "هرروز هفته", +"Bi-Weekly" => "دوهفته", +"Monthly" => "ماهانه", +"Yearly" => "سالانه", +"never" => "هرگز", +"by occurrences" => "به وسیله ظهور", +"by date" => "به وسیله تاریخ", +"by monthday" => "به وسیله روزهای ماه", +"by weekday" => "به وسیله روز های هفته", +"Monday" => "دوشنبه", +"Tuesday" => "سه شنبه", +"Wednesday" => "چهارشنبه", +"Thursday" => "پنجشنبه", +"Friday" => "جمعه", +"Saturday" => "شنبه", +"Sunday" => "یکشنبه", +"events week of month" => "رویداد های هفته هایی از ماه", +"first" => "اولین", +"second" => "دومین", +"third" => "سومین", +"fourth" => "چهارمین", +"fifth" => "پنجمین", +"last" => "آخرین", +"January" => "ژانویه", +"February" => "فبریه", +"March" => "مارس", +"April" => "آوریل", +"May" => "می", +"June" => "ژوءن", +"July" => "جولای", +"August" => "آگوست", +"September" => "سپتامبر", +"October" => "اکتبر", +"November" => "نوامبر", +"December" => "دسامبر", +"by events date" => "به وسیله رویداد های روزانه", +"by yearday(s)" => "به وسیله روز های سال(ها)", +"by weeknumber(s)" => "به وسیله شماره هفته(ها)", +"by day and month" => "به وسیله روز و ماه", +"Date" => "تاریخ", +"Cal." => "تقویم.", +"All day" => "هرروز", +"New Calendar" => "تقویم جدید", +"Missing fields" => "فیلد های گم شده", +"Title" => "عنوان", +"From Date" => "از تاریخ", +"From Time" => "از ساعت", +"To Date" => "به تاریخ", +"To Time" => "به ساعت", +"The event ends before it starts" => "رویداد قبل از شروع شدن تمام شده!", +"There was a database fail" => "یک پایگاه داده فرو مانده است", +"Week" => "هفته", +"Month" => "ماه", +"List" => "فهرست", +"Today" => "امروز", +"Calendars" => "تقویم ها", +"There was a fail, while parsing the file." => "ناتوان در تجزیه پرونده", +"Choose active calendars" => "تقویم فعال را انتخاب کنید", +"Your calendars" => "تقویم های شما", +"CalDav Link" => "CalDav Link", +"Shared calendars" => "تقویمهای به اشترک گذاری شده", +"No shared calendars" => "هیچ تقویمی به اشتراک گذارده نشده", +"Share Calendar" => "تقویم را به اشتراک بگذارید", +"Download" => "بارگیری", +"Edit" => "ویرایش", +"Delete" => "پاک کردن", +"shared with you by" => "به اشتراک گذارده شده به وسیله", +"New calendar" => "تقویم جدید", +"Edit calendar" => "ویرایش تقویم", +"Displayname" => "نام برای نمایش", +"Active" => "فعال", +"Calendar color" => "رنگ تقویم", +"Save" => "ذخیره سازی", +"Submit" => "ارسال", +"Cancel" => "انصراف", +"Edit an event" => "ویرایش رویداد", +"Export" => "خروجی گرفتن", +"Eventinfo" => "اطلاعات رویداد", +"Repeating" => "در حال تکرار کردن", +"Alarm" => "هشدار", +"Attendees" => "شرکت کنندگان", +"Share" => "به اشتراک گذاردن", +"Title of the Event" => "عنوان رویداد", +"Category" => "نوع", +"Separate categories with commas" => "گروه ها را به وسیله درنگ نما از هم جدا کنید", +"Edit categories" => "ویرایش گروه", +"All Day Event" => "رویداد های روزانه", +"From" => "از", +"To" => "به", +"Advanced options" => "تنظیمات حرفه ای", +"Location" => "منطقه", +"Location of the Event" => "منطقه رویداد", +"Description" => "توضیحات", +"Description of the Event" => "توضیحات درباره رویداد", +"Repeat" => "تکرار", +"Advanced" => "پیشرفته", +"Select weekdays" => "انتخاب روز های هفته ", +"Select days" => "انتخاب روز ها", +"and the events day of year." => "و رویداد های روز از سال", +"and the events day of month." => "و رویداد های روز از ماه", +"Select months" => "انتخاب ماه ها", +"Select weeks" => "انتخاب هفته ها", +"and the events week of year." => "و رویداد هفته ها از سال", +"Interval" => "فاصله", +"End" => "پایان", +"occurrences" => "ظهور", +"Import a calendar file" => "یک پرونده حاوی تقویم وارد کنید", +"Please choose the calendar" => "لطفا تقویم را انتخاب کنید", +"create a new calendar" => "یک تقویم جدید ایجاد کنید", +"Name of new calendar" => "نام تقویم جدید", +"Import" => "ورودی دادن", +"Importing calendar" => "درحال افزودن تقویم", +"Calendar imported successfully" => "افزودن تقویم موفقیت آمیز بود", +"Close Dialog" => "بستن دیالوگ", +"Create a new event" => "یک رویداد ایجاد کنید", +"View an event" => "دیدن یک رویداد", +"No categories selected" => "هیچ گروهی انتخاب نشده", +"Select category" => "انتخاب گروه", +"of" => "از", +"at" => "در", +"Timezone" => "زمان محلی", +"Check always for changes of the timezone" => "همیشه بررسی کنید برای تغییر زمان محلی", +"Timeformat" => "نوع زمان", +"24h" => "24 ساعت", +"12h" => "12 ساعت", +"First day of the week" => "یکمین روز هفته", +"Calendar CalDAV syncing address:" => "Calendar CalDAV syncing address :", +"Users" => "کاربرها", +"select users" => "انتخاب شناسه ها", +"Editable" => "قابل ویرایش", +"Groups" => "گروه ها", +"select groups" => "انتخاب گروه ها", +"make public" => "عمومی سازی" +); diff --git a/apps/calendar/l10n/fr.php b/apps/calendar/l10n/fr.php index 29cd978068c1f33adf982710812ff7100084d736..506453af428001ad65d15417a9841b8310aae246 100644 --- a/apps/calendar/l10n/fr.php +++ b/apps/calendar/l10n/fr.php @@ -1,9 +1,12 @@ "Aucun calendrier n'a été trouvé.", +"No events found." => "Aucun événement n'a été trouvé.", "Wrong calendar" => "Mauvais calendrier", "New Timezone:" => "Nouveau fuseau horaire :", "Timezone changed" => "Fuseau horaire modifié", "Invalid request" => "Requête invalide", "Calendar" => "Calendrier", +"MMM d[ yyyy]{ '—'[ MMM] d yyyy}" => "MMM d[ yyyy]{ '—'[ MMM] d yyyy}", "Birthday" => "Anniversaire", "Business" => "Professionnel", "Call" => "Appel", @@ -19,6 +22,7 @@ "Projects" => "Projets", "Questions" => "Questions", "Work" => "Travail", +"unnamed" => "sans-nom", "Does not repeat" => "Pas de répétition", "Daily" => "Tous les jours", "Weekly" => "Hebdomadaire", @@ -80,10 +84,15 @@ "Calendars" => "Calendriers", "There was a fail, while parsing the file." => "Une erreur est survenue pendant la lecture du fichier.", "Choose active calendars" => "Choix des calendriers actifs", +"Your calendars" => "Vos calendriers", "CalDav Link" => "Lien CalDav", +"Shared calendars" => "Calendriers partagés", +"No shared calendars" => "Aucun calendrier partagé", +"Share Calendar" => "Partager le calendrier", "Download" => "Télécharger", "Edit" => "Éditer", "Delete" => "Supprimer", +"shared with you by" => "partagé avec vous par", "New calendar" => "Nouveau calendrier", "Edit calendar" => "Éditer le calendrier", "Displayname" => "Nom d'affichage", @@ -94,8 +103,15 @@ "Cancel" => "Annuler", "Edit an event" => "Éditer un événement", "Export" => "Exporter", +"Eventinfo" => "Événement", +"Repeating" => "Occurences", +"Alarm" => "Alarmes", +"Attendees" => "Participants", +"Share" => "Partage", "Title of the Event" => "Titre de l'événement", "Category" => "Catégorie", +"Separate categories with commas" => "Séparer les catégories par des virgules", +"Edit categories" => "Modifier les catégories", "All Day Event" => "Journée entière", "From" => "De", "To" => "À", @@ -125,11 +141,22 @@ "Calendar imported successfully" => "Calendrier importé avec succès", "Close Dialog" => "Fermer la fenêtre", "Create a new event" => "Créer un nouvel événement", +"View an event" => "Voir un événement", +"No categories selected" => "Aucune catégorie sélectionnée", "Select category" => "Sélectionner une catégorie", +"of" => "de", +"at" => "à", "Timezone" => "Fuseau horaire", "Check always for changes of the timezone" => "Toujours vérifier d'éventuels changements de fuseau horaire", "Timeformat" => "Format de l'heure", "24h" => "24h", "12h" => "12h", -"Calendar CalDAV syncing address:" => "Adresse de synchronisation du calendrier CalDAV :" +"First day of the week" => "Premier jour de la semaine", +"Calendar CalDAV syncing address:" => "Adresse de synchronisation du calendrier CalDAV :", +"Users" => "Utilisateurs", +"select users" => "sélectionner les utilisateurs", +"Editable" => "Modifiable", +"Groups" => "Groupes", +"select groups" => "sélectionner les groupes", +"make public" => "rendre public" ); diff --git a/apps/calendar/l10n/hu_HU.php b/apps/calendar/l10n/hu_HU.php index 5afc24305e7b327e3b0d9f53ac4e9577ba876ecc..d97887aac7a23098812e5a38f07b20500b2a5610 100644 --- a/apps/calendar/l10n/hu_HU.php +++ b/apps/calendar/l10n/hu_HU.php @@ -1,8 +1,12 @@ "Nem található naptár", +"No events found." => "Nem található esemény", "Wrong calendar" => "Hibás naptár", +"New Timezone:" => "Új időzóna", "Timezone changed" => "Időzóna megváltozott", "Invalid request" => "Érvénytelen kérés", "Calendar" => "Naptár", +"MMM d[ yyyy]{ '—'[ MMM] d yyyy}" => "MMM d[ yyyy]{ '—'[ MMM] d yyyy}", "Birthday" => "Születésap", "Business" => "Üzlet", "Call" => "Hívás", @@ -18,6 +22,7 @@ "Projects" => "Projektek", "Questions" => "Kérdések", "Work" => "Munka", +"unnamed" => "névtelen", "Does not repeat" => "Nem ismétlődik", "Daily" => "Napi", "Weekly" => "Heti", @@ -25,6 +30,43 @@ "Bi-Weekly" => "Kéthetente", "Monthly" => "Havi", "Yearly" => "Évi", +"never" => "soha", +"by occurrences" => "előfordulás szerint", +"by date" => "dátum szerint", +"by monthday" => "hónap napja szerint", +"by weekday" => "hét napja szerint", +"Monday" => "Hétfő", +"Tuesday" => "Kedd", +"Wednesday" => "Szerda", +"Thursday" => "Csütörtök", +"Friday" => "Péntek", +"Saturday" => "Szombat", +"Sunday" => "Vasárnap", +"events week of month" => "hónap heteinek sorszáma", +"first" => "első", +"second" => "második", +"third" => "harmadik", +"fourth" => "negyedik", +"fifth" => "ötödik", +"last" => "utolsó", +"January" => "Január", +"February" => "Február", +"March" => "Március", +"April" => "Április", +"May" => "Május", +"June" => "Június", +"July" => "Július", +"August" => "Augusztus", +"September" => "Szeptember", +"October" => "Október", +"November" => "November", +"December" => "December", +"by events date" => "az esemény napja szerint", +"by yearday(s)" => "az év napja(i) szerint", +"by weeknumber(s)" => "a hét sorszáma szerint", +"by day and month" => "nap és hónap szerint", +"Date" => "Dátum", +"Cal." => "Naptár", "All day" => "Egész nap", "New Calendar" => "Új naptár", "Missing fields" => "Hiányzó mezők", @@ -42,10 +84,15 @@ "Calendars" => "Naptárak", "There was a fail, while parsing the file." => "Probléma volt a fájl elemzése közben.", "Choose active calendars" => "Aktív naptár kiválasztása", +"Your calendars" => "Naptárjaid", "CalDav Link" => "CalDAV link", +"Shared calendars" => "Megosztott naptárak", +"No shared calendars" => "Nincs megosztott naptár", +"Share Calendar" => "Naptármegosztás", "Download" => "Letöltés", "Edit" => "Szerkesztés", "Delete" => "Törlés", +"shared with you by" => "megosztotta veled: ", "New calendar" => "Új naptár", "Edit calendar" => "Naptár szerkesztése", "Displayname" => "Megjelenítési név", @@ -56,22 +103,60 @@ "Cancel" => "Mégse", "Edit an event" => "Esemény szerkesztése", "Export" => "Export", +"Eventinfo" => "Eseményinfó", +"Repeating" => "Ismétlődő", +"Alarm" => "Riasztás", +"Attendees" => "Résztvevők", +"Share" => "Megosztás", "Title of the Event" => "Az esemény címe", "Category" => "Kategória", +"Separate categories with commas" => "Vesszővel válaszd el a kategóriákat", +"Edit categories" => "Kategóriák szerkesztése", "All Day Event" => "Egész napos esemény", +"From" => "Ettől", +"To" => "Eddig", "Advanced options" => "Haladó beállítások", "Location" => "Hely", "Location of the Event" => "Az esemény helyszíne", "Description" => "Leírás", "Description of the Event" => "Az esemény leírása", "Repeat" => "Ismétlés", +"Advanced" => "Haladó", +"Select weekdays" => "Hétköznapok kiválasztása", +"Select days" => "Napok kiválasztása", +"and the events day of year." => "és az éves esemény napja.", +"and the events day of month." => "és a havi esemény napja.", +"Select months" => "Hónapok kiválasztása", +"Select weeks" => "Hetek kiválasztása", +"and the events week of year." => "és az heti esemény napja.", +"Interval" => "Időköz", +"End" => "Vége", +"occurrences" => "előfordulások", +"Import a calendar file" => "Naptár-fájl importálása", "Please choose the calendar" => "Válassz naptárat", +"create a new calendar" => "új naptár létrehozása", +"Name of new calendar" => "Új naptár neve", "Import" => "Importálás", +"Importing calendar" => "Naptár importálása", +"Calendar imported successfully" => "Naptár sikeresen importálva", +"Close Dialog" => "Párbeszédablak bezárása", "Create a new event" => "Új esemény létrehozása", +"View an event" => "Esemény megtekintése", +"No categories selected" => "Nincs kiválasztott kategória", "Select category" => "Kategória kiválasztása", +"of" => ", tulaj ", +"at" => ", ", "Timezone" => "Időzóna", +"Check always for changes of the timezone" => "Mindig ellenőrizze az időzóna-változásokat", "Timeformat" => "Időformátum", "24h" => "24h", "12h" => "12h", -"Calendar CalDAV syncing address:" => "Naptár CalDAV szinkronizálási cím:" +"First day of the week" => "A hét első napja", +"Calendar CalDAV syncing address:" => "Naptár CalDAV szinkronizálási cím:", +"Users" => "Felhasználók", +"select users" => "válassz felhasználókat", +"Editable" => "Szerkeszthető", +"Groups" => "Csoportok", +"select groups" => "válassz csoportokat", +"make public" => "nyilvánossá tétel" ); diff --git a/apps/calendar/l10n/ia.php b/apps/calendar/l10n/ia.php index 89f8ad203420ca1237a0b0ca3058f39ca317fe4f..a346e4de5b7e7aabfe0aef0fbe67763ff163ca45 100644 --- a/apps/calendar/l10n/ia.php +++ b/apps/calendar/l10n/ia.php @@ -1,14 +1,27 @@ "Necun calendarios trovate.", +"No events found." => "Nulle eventos trovate.", "New Timezone:" => "Nove fuso horari", "Invalid request" => "Requesta invalide.", "Calendar" => "Calendario", +"Birthday" => "Anniversario de nativitate", +"Business" => "Affaires", "Call" => "Appello", +"Clients" => "Clientes", +"Holidays" => "Dies feriate", "Meeting" => "Incontro", "Other" => "Altere", "Personal" => "Personal", "Projects" => "Projectos", "Questions" => "Demandas", "Work" => "Travalio", +"unnamed" => "sin nomine", +"Does not repeat" => "Non repite", +"Daily" => "Quotidian", +"Weekly" => "Septimanal", +"Every Weekday" => "Cata die", +"Monthly" => "Mensual", +"Yearly" => "Cata anno", "never" => "nunquam", "by date" => "per data", "Monday" => "Lunedi", @@ -34,9 +47,12 @@ "October" => "Octobre", "November" => "Novembre", "December" => "Decembre", +"by events date" => "per data de eventos", +"by day and month" => "per dia e mense", "Date" => "Data", "All day" => "Omne die", "New Calendar" => "Nove calendario", +"Missing fields" => "Campos incomplete", "Title" => "Titulo", "From Date" => "Data de initio", "From Time" => "Hora de initio", @@ -48,6 +64,7 @@ "Today" => "Hodie", "Calendars" => "Calendarios", "Choose active calendars" => "Selectionar calendarios active", +"Your calendars" => "Tu calendarios", "Download" => "Discarga", "Edit" => "Modificar", "Delete" => "Deler", @@ -60,8 +77,10 @@ "Cancel" => "Cancellar", "Edit an event" => "Modificar evento", "Export" => "Exportar", +"Share" => "Compartir", "Title of the Event" => "Titulo del evento.", "Category" => "Categoria", +"Edit categories" => "Modificar categorias", "From" => "Ab", "To" => "A", "Advanced options" => "Optiones avantiate", @@ -71,16 +90,26 @@ "Description of the Event" => "Description del evento", "Repeat" => "Repeter", "Advanced" => "Avantiate", +"Select weekdays" => "Seliger dies del septimana", +"Select days" => "Seliger dies", "Select months" => "Seliger menses", "Select weeks" => "Seliger septimanas", "Interval" => "Intervallo", "End" => "Fin", "Import a calendar file" => "Importar un file de calendario", "Please choose the calendar" => "Selige el calendario", +"create a new calendar" => "crear un nove calendario", "Name of new calendar" => "Nomine del calendario", "Import" => "Importar", "Close Dialog" => "Clauder dialogo", "Create a new event" => "Crear un nove evento", +"View an event" => "Vide un evento", +"No categories selected" => "Nulle categorias seligite", "Select category" => "Selectionar categoria", -"Timezone" => "Fuso horari" +"of" => "de", +"at" => "in", +"Timezone" => "Fuso horari", +"First day of the week" => "Prime die del septimana", +"Users" => "Usatores", +"Groups" => "Gruppos" ); diff --git a/apps/calendar/l10n/it.php b/apps/calendar/l10n/it.php index fc43d5faed39acf0ce887fdf47c8c6eff8e0d72b..cdb2d99c82e96b4677b83a5a7904b24c139475f4 100644 --- a/apps/calendar/l10n/it.php +++ b/apps/calendar/l10n/it.php @@ -1,9 +1,12 @@ "Nessun calendario trovato.", +"No events found." => "Nessun evento trovato.", "Wrong calendar" => "Calendario sbagliato", "New Timezone:" => "Nuovo fuso orario:", "Timezone changed" => "Fuso orario cambiato", "Invalid request" => "Richiesta non valida", "Calendar" => "Calendario", +"MMM d[ yyyy]{ '—'[ MMM] d yyyy}" => "MMM d[ yyyy]{ '—'[ MMM] d yyyy}", "Birthday" => "Compleanno", "Business" => "Azienda", "Call" => "Chiama", @@ -19,6 +22,7 @@ "Projects" => "Progetti", "Questions" => "Domande", "Work" => "Lavoro", +"unnamed" => "senza nome", "Does not repeat" => "Non ripetere", "Daily" => "Giornaliero", "Weekly" => "Settimanale", @@ -80,10 +84,15 @@ "Calendars" => "Calendari", "There was a fail, while parsing the file." => "Si è verificato un errore durante l'analisi del file.", "Choose active calendars" => "Scegli i calendari attivi", +"Your calendars" => "I tuoi calendari", "CalDav Link" => "Collegamento CalDav", +"Shared calendars" => "Calendari condivisi", +"No shared calendars" => "Nessun calendario condiviso", +"Share Calendar" => "Condividi calendario", "Download" => "Scarica", "Edit" => "Modifica", "Delete" => "Elimina", +"shared with you by" => "condiviso con te da", "New calendar" => "Nuovo calendario", "Edit calendar" => "Modifica calendario", "Displayname" => "Nome visualizzato", @@ -94,8 +103,15 @@ "Cancel" => "Annulla", "Edit an event" => "Modifica un evento", "Export" => "Esporta", +"Eventinfo" => "Informazioni evento", +"Repeating" => "Ripetizione", +"Alarm" => "Avviso", +"Attendees" => "Partecipanti", +"Share" => "Condividi", "Title of the Event" => "Titolo dell'evento", "Category" => "Categoria", +"Separate categories with commas" => "Categorie separate con virgole", +"Edit categories" => "Modifica le categorie", "All Day Event" => "Evento che occupa tutta la giornata", "From" => "Da", "To" => "A", @@ -125,11 +141,22 @@ "Calendar imported successfully" => "Calendario importato correttamente", "Close Dialog" => "Chiudi la finestra di dialogo", "Create a new event" => "Crea un nuovo evento", +"View an event" => "Visualizza un evento", +"No categories selected" => "Nessuna categoria selezionata", "Select category" => "Seleziona una categoria", +"of" => "di", +"at" => "alle", "Timezone" => "Fuso orario", "Check always for changes of the timezone" => "Controlla sempre i cambiamenti di fuso orario", "Timeformat" => "Formato orario", "24h" => "24h", "12h" => "12h", -"Calendar CalDAV syncing address:" => "Indirizzo sincronizzazione calendario CalDAV:" +"First day of the week" => "Primo giorno della settimana", +"Calendar CalDAV syncing address:" => "Indirizzo sincronizzazione calendario CalDAV:", +"Users" => "Utenti", +"select users" => "seleziona utenti", +"Editable" => "Modificabile", +"Groups" => "Gruppi", +"select groups" => "seleziona gruppi", +"make public" => "rendi pubblico" ); diff --git a/apps/calendar/l10n/ko.php b/apps/calendar/l10n/ko.php index 5b22ef0156a5615b996e7f520dd21bc3b051ba86..181bfa4378fb82ec21eb36bd43f06e6eb0be47ec 100644 --- a/apps/calendar/l10n/ko.php +++ b/apps/calendar/l10n/ko.php @@ -1,4 +1,6 @@ "달력이 없습니다", +"No events found." => "일정이 없습니다", "Wrong calendar" => "잘못된 달력", "New Timezone:" => "새로운 시간대 설정", "Timezone changed" => "시간대 변경됨", @@ -19,6 +21,7 @@ "Projects" => "프로젝트", "Questions" => "질문", "Work" => "작업", +"unnamed" => "익명의", "Does not repeat" => "반복 없음", "Daily" => "매일", "Weekly" => "매주", @@ -80,10 +83,15 @@ "Calendars" => "달력", "There was a fail, while parsing the file." => "파일을 처리하는 중 오류가 발생하였습니다.", "Choose active calendars" => "활성 달력 선택", +"Your calendars" => "내 달력", "CalDav Link" => "CalDav 링크", +"Shared calendars" => "공유 달력", +"No shared calendars" => "달력 공유하지 않음", +"Share Calendar" => "달력 공유", "Download" => "다운로드", "Edit" => "편집", "Delete" => "삭제", +"shared with you by" => "로 인해 당신과 함께 공유", "New calendar" => "새로운 달력", "Edit calendar" => "달력 편집", "Displayname" => "표시 이름", @@ -94,8 +102,15 @@ "Cancel" => "취소", "Edit an event" => "이벤트 편집", "Export" => "출력", +"Eventinfo" => "일정 정보", +"Repeating" => "반복", +"Alarm" => "알람", +"Attendees" => "참석자", +"Share" => "공유", "Title of the Event" => "이벤트 제목", "Category" => "분류", +"Separate categories with commas" => "쉼표로 카테고리 구분", +"Edit categories" => "카테고리 수정", "All Day Event" => "종일 이벤트", "From" => "시작", "To" => "끝", @@ -125,11 +140,22 @@ "Calendar imported successfully" => "달력 입력을 성공적으로 마쳤습니다.", "Close Dialog" => "대화 마침", "Create a new event" => "새 이벤트 만들기", +"View an event" => "일정 보기", +"No categories selected" => "선택된 카테고리 없음", "Select category" => "선택 카테고리", +"of" => "의", +"at" => "에서", "Timezone" => "시간대", "Check always for changes of the timezone" => "항상 시간대 변경 확인하기", "Timeformat" => "시간 형식 설정", "24h" => "24시간", "12h" => "12시간", -"Calendar CalDAV syncing address:" => "달력 CalDav 동기화 주소" +"First day of the week" => "그 주의 첫째날", +"Calendar CalDAV syncing address:" => "달력 CalDav 동기화 주소", +"Users" => "사용자", +"select users" => "사용자 선택", +"Editable" => "편집 가능", +"Groups" => "그룹", +"select groups" => "선택 그룹", +"make public" => "공개" ); diff --git a/apps/calendar/l10n/mk.php b/apps/calendar/l10n/mk.php index 784adfc8f24ce73685d7a08c0a98d4f1950e171e..41df376dfa6da79a9c973c5750feb036b839132a 100644 --- a/apps/calendar/l10n/mk.php +++ b/apps/calendar/l10n/mk.php @@ -1,9 +1,12 @@ "Не се најдени календари.", +"No events found." => "Не се најдени настани.", "Wrong calendar" => "Погрешен календар", "New Timezone:" => "Нова временска зона:", "Timezone changed" => "Временската зона е променета", "Invalid request" => "Неправилно барање", "Calendar" => "Календар", +"MMM d[ yyyy]{ '—'[ MMM] d yyyy}" => "MMM d[ yyyy]{ '—'[ MMM] d yyyy}", "Birthday" => "Роденден", "Business" => "Деловно", "Call" => "Повикај", @@ -19,6 +22,7 @@ "Projects" => "Проекти", "Questions" => "Прашања", "Work" => "Работа", +"unnamed" => "неименувано", "Does not repeat" => "Не се повторува", "Daily" => "Дневно", "Weekly" => "Седмично", @@ -38,6 +42,7 @@ "Friday" => "Петок", "Saturday" => "Сабота", "Sunday" => "Недела", +"events week of month" => "седмични настани од месец", "first" => "прв", "second" => "втор", "third" => "трет", @@ -79,10 +84,15 @@ "Calendars" => "Календари", "There was a fail, while parsing the file." => "Имаше проблем при парсирање на датотеката.", "Choose active calendars" => "Избери активни календари", +"Your calendars" => "Ваши календари", "CalDav Link" => "Врска за CalDav", +"Shared calendars" => "Споделени календари", +"No shared calendars" => "Нема споделени календари", +"Share Calendar" => "Сподели календар", "Download" => "Преземи", "Edit" => "Уреди", "Delete" => "Избриши", +"shared with you by" => "Споделен со вас од", "New calendar" => "Нов календар", "Edit calendar" => "Уреди календар", "Displayname" => "Име за приказ", @@ -93,8 +103,15 @@ "Cancel" => "Откажи", "Edit an event" => "Уреди настан", "Export" => "Извези", +"Eventinfo" => "Инфо за настан", +"Repeating" => "Повторување", +"Alarm" => "Аларм", +"Attendees" => "Присутни", +"Share" => "Сподели", "Title of the Event" => "Наслов на настанот", "Category" => "Категорија", +"Separate categories with commas" => "Одвоете ги категориите со запирка", +"Edit categories" => "Уреди категории", "All Day Event" => "Целодневен настан", "From" => "Од", "To" => "До", @@ -107,8 +124,11 @@ "Advanced" => "Напредно", "Select weekdays" => "Избери работни денови", "Select days" => "Избери денови", +"and the events day of year." => "и настаните ден од година.", +"and the events day of month." => "и настаните ден од месец.", "Select months" => "Избери месеци", "Select weeks" => "Избери седмици", +"and the events week of year." => "и настаните седмица од година.", "Interval" => "интервал", "End" => "Крај", "occurrences" => "повторувања", @@ -121,11 +141,22 @@ "Calendar imported successfully" => "Календарот беше успешно увезен", "Close Dialog" => "Затвори дијалог", "Create a new event" => "Создади нов настан", +"View an event" => "Погледај настан", +"No categories selected" => "Нема избрано категории", "Select category" => "Избери категорија", +"of" => "од", +"at" => "на", "Timezone" => "Временска зона", "Check always for changes of the timezone" => "Секогаш провери за промени на временската зона", "Timeformat" => "Формат на времето", "24h" => "24ч", "12h" => "12ч", -"Calendar CalDAV syncing address:" => "CalDAV календар адресата за синхронизација:" +"First day of the week" => "Прв ден од седмицата", +"Calendar CalDAV syncing address:" => "CalDAV календар адресата за синхронизација:", +"Users" => "Корисници", +"select users" => "избери корисници", +"Editable" => "Изменливо", +"Groups" => "Групи", +"select groups" => "избери групи", +"make public" => "направи јавно" ); diff --git a/apps/calendar/l10n/nb_NO.php b/apps/calendar/l10n/nb_NO.php index 216794f43042e6c16842a9081bf7195a310bba8b..b9a7bf4cb17b334447396b1682382f80f26f7599 100644 --- a/apps/calendar/l10n/nb_NO.php +++ b/apps/calendar/l10n/nb_NO.php @@ -1,4 +1,6 @@ "Ingen kalendere funnet", +"No events found." => "Ingen hendelser funnet", "Wrong calendar" => "Feil kalender", "New Timezone:" => "Ny tidssone:", "Timezone changed" => "Tidssone endret", @@ -17,6 +19,7 @@ "Projects" => "Prosjekter", "Questions" => "Spørsmål", "Work" => "Arbeid", +"unnamed" => "uten navn", "Does not repeat" => "Gjentas ikke", "Daily" => "Daglig", "Weekly" => "Ukentlig", @@ -78,10 +81,15 @@ "Calendars" => "Kalendre", "There was a fail, while parsing the file." => "Det oppstod en feil under åpningen av filen.", "Choose active calendars" => "Velg en aktiv kalender", +"Your calendars" => "Dine kalendere", "CalDav Link" => "CalDav-lenke", +"Shared calendars" => "Delte kalendere", +"No shared calendars" => "Ingen delte kalendere", +"Share Calendar" => "Del Kalender", "Download" => "Last ned", "Edit" => "Endre", "Delete" => "Slett", +"shared with you by" => "delt med deg", "New calendar" => "Ny kalender", "Edit calendar" => "Rediger kalender", "Displayname" => "Visningsnavn", @@ -92,8 +100,15 @@ "Cancel" => "Avbryt", "Edit an event" => "Rediger en hendelse", "Export" => "Eksporter", +"Eventinfo" => "Hendelsesinformasjon", +"Repeating" => "Gjentas", +"Alarm" => "Alarm", +"Attendees" => "Deltakere", +"Share" => "Del", "Title of the Event" => "Hendelsestittel", "Category" => "Kategori", +"Separate categories with commas" => "Separer kategorier med komma", +"Edit categories" => "Rediger kategorier", "All Day Event" => "Hele dagen-hendelse", "From" => "Fra", "To" => "Til", @@ -123,11 +138,20 @@ "Calendar imported successfully" => "Kalenderen ble importert uten feil", "Close Dialog" => "Lukk dialog", "Create a new event" => "Opprett en ny hendelse", +"View an event" => "Se på hendelse", +"No categories selected" => "Ingen kategorier valgt", "Select category" => "Velg kategori", "Timezone" => "Tidssone", "Check always for changes of the timezone" => "Se alltid etter endringer i tidssone", "Timeformat" => "Tidsformat:", "24h" => "24 t", "12h" => "12 t", -"Calendar CalDAV syncing address:" => "Kalender CalDAV synkroniseringsadresse" +"First day of the week" => "Ukens første dag", +"Calendar CalDAV syncing address:" => "Kalender CalDAV synkroniseringsadresse", +"Users" => "Brukere", +"select users" => "valgte brukere", +"Editable" => "Redigerbar", +"Groups" => "Grupper", +"select groups" => "velg grupper", +"make public" => "gjør offentlig" ); diff --git a/apps/calendar/l10n/nl.php b/apps/calendar/l10n/nl.php index 948dcf13c60f9c86985a07c659a3f034b49c77b7..d141a1cc08c48c2f6c3d1d4f18a86151efd2d6d2 100644 --- a/apps/calendar/l10n/nl.php +++ b/apps/calendar/l10n/nl.php @@ -1,9 +1,12 @@ "Geen kalenders gevonden.", +"No events found." => "Geen gebeurtenissen gevonden.", "Wrong calendar" => "Verkeerde kalender", "New Timezone:" => "Nieuwe tijdszone:", "Timezone changed" => "Tijdzone is veranderd", "Invalid request" => "Ongeldige aanvraag", "Calendar" => "Kalender", +"MMM d[ yyyy]{ '—'[ MMM] d yyyy}" => "d MMM[ yyyy]{ '—' d[ MMM] yyyy}", "Birthday" => "Verjaardag", "Business" => "Zakelijk", "Call" => "Bellen", @@ -19,6 +22,7 @@ "Projects" => "Projecten", "Questions" => "Vragen", "Work" => "Werk", +"unnamed" => "onbekend", "Does not repeat" => "Wordt niet herhaald", "Daily" => "Dagelijks", "Weekly" => "Wekelijks", @@ -38,6 +42,7 @@ "Friday" => "Vrijdag", "Saturday" => "Zaterdag", "Sunday" => "Zondag", +"events week of month" => "gebeurtenissen week van maand", "first" => "eerste", "second" => "tweede", "third" => "derde", @@ -79,10 +84,15 @@ "Calendars" => "Kalenders", "There was a fail, while parsing the file." => "Er is een fout opgetreden bij het verwerken van het bestand.", "Choose active calendars" => "Kies actieve kalenders", +"Your calendars" => "Je kalenders", "CalDav Link" => "CalDav Link", +"Shared calendars" => "Gedeelde kalenders", +"No shared calendars" => "Geen gedeelde kalenders", +"Share Calendar" => "Deel kalender", "Download" => "Download", "Edit" => "Bewerken", "Delete" => "Verwijderen", +"shared with you by" => "gedeeld met jou door", "New calendar" => "Nieuwe kalender", "Edit calendar" => "Bewerk kalender", "Displayname" => "Weergavenaam", @@ -93,8 +103,15 @@ "Cancel" => "Annuleren", "Edit an event" => "Bewerken van een afspraak", "Export" => "Exporteren", +"Eventinfo" => "Geberurtenisinformatie", +"Repeating" => "Herhalend", +"Alarm" => "Alarm", +"Attendees" => "Deelnemers", +"Share" => "Delen", "Title of the Event" => "Titel van de afspraak", "Category" => "Categorie", +"Separate categories with commas" => "Gescheiden door komma's", +"Edit categories" => "Wijzig categorieën", "All Day Event" => "Hele dag", "From" => "Van", "To" => "Aan", @@ -107,8 +124,11 @@ "Advanced" => "Geavanceerd", "Select weekdays" => "Selecteer weekdagen", "Select days" => "Selecteer dagen", +"and the events day of year." => "en de gebeurtenissen dag van het jaar", +"and the events day of month." => "en de gebeurtenissen dag van de maand", "Select months" => "Selecteer maanden", "Select weeks" => "Selecteer weken", +"and the events week of year." => "en de gebeurtenissen week van het jaar", "Interval" => "Interval", "End" => "Einde", "occurrences" => "gebeurtenissen", @@ -121,11 +141,22 @@ "Calendar imported successfully" => "Agenda succesvol geïmporteerd", "Close Dialog" => "Sluit venster", "Create a new event" => "Maak een nieuwe afspraak", +"View an event" => "Bekijk een gebeurtenis", +"No categories selected" => "Geen categorieën geselecteerd", "Select category" => "Kies een categorie", +"of" => "van", +"at" => "op", "Timezone" => "Tijdzone", "Check always for changes of the timezone" => "Controleer altijd op aanpassingen van de tijdszone", "Timeformat" => "Tijdformaat", "24h" => "24uur", "12h" => "12uur", -"Calendar CalDAV syncing address:" => "CalDAV kalender synchronisatie adres:" +"First day of the week" => "Eerste dag van de week", +"Calendar CalDAV syncing address:" => "CalDAV kalender synchronisatie adres:", +"Users" => "Gebruikers", +"select users" => "kies gebruikers", +"Editable" => "Te wijzigen", +"Groups" => "Groepen", +"select groups" => "kies groep", +"make public" => "maak publiek" ); diff --git a/apps/calendar/l10n/pt_BR.php b/apps/calendar/l10n/pt_BR.php index c89c1a9ffe2e6f862b99c31ed51430cbc28a846e..95317eea0f73c6b512939ce920b4823816bd2809 100644 --- a/apps/calendar/l10n/pt_BR.php +++ b/apps/calendar/l10n/pt_BR.php @@ -1,9 +1,12 @@ "Nenhum calendário encontrado.", +"No events found." => "Nenhum evento encontrado.", "Wrong calendar" => "Calendário incorreto", "New Timezone:" => "Novo fuso horário", "Timezone changed" => "Fuso horário alterado", "Invalid request" => "Pedido inválido", "Calendar" => "Calendário", +"MMM d[ yyyy]{ '—'[ MMM] d yyyy}" => "MMM d[ yyyy]{ '—'[ MMM] d yyyy}", "Birthday" => "Aniversário", "Business" => "Negócio", "Call" => "Chamada", @@ -19,6 +22,7 @@ "Projects" => "Projetos", "Questions" => "Perguntas", "Work" => "Trabalho", +"unnamed" => "sem nome", "Does not repeat" => "Não repetir", "Daily" => "Diariamente", "Weekly" => "Semanal", @@ -80,10 +84,15 @@ "Calendars" => "Calendários", "There was a fail, while parsing the file." => "Houve uma falha, ao analisar o arquivo.", "Choose active calendars" => "Escolha calendários ativos", +"Your calendars" => "Meus Calendários", "CalDav Link" => "Link para CalDav", +"Shared calendars" => "Calendários Compartilhados", +"No shared calendars" => "Nenhum Calendário Compartilhado", +"Share Calendar" => "Compartilhar Calendário", "Download" => "Baixar", "Edit" => "Editar", "Delete" => "Excluir", +"shared with you by" => "compartilhado com você por", "New calendar" => "Novo calendário", "Edit calendar" => "Editar calendário", "Displayname" => "Mostrar Nome", @@ -94,8 +103,15 @@ "Cancel" => "Cancelar", "Edit an event" => "Editar um evento", "Export" => "Exportar", +"Eventinfo" => "Info de Evento", +"Repeating" => "Repetindo", +"Alarm" => "Alarme", +"Attendees" => "Participantes", +"Share" => "Compartilhar", "Title of the Event" => "Título do evento", "Category" => "Categoria", +"Separate categories with commas" => "Separe as categorias por vírgulas", +"Edit categories" => "Editar categorias", "All Day Event" => "Evento de dia inteiro", "From" => "De", "To" => "Para", @@ -125,11 +141,22 @@ "Calendar imported successfully" => "Calendário importado com sucesso", "Close Dialog" => "Fechar caixa de diálogo", "Create a new event" => "Criar um novo evento", +"View an event" => "Visualizar evento", +"No categories selected" => "Nenhuma categoria selecionada", "Select category" => "Selecionar categoria", +"of" => "de", +"at" => "para", "Timezone" => "Fuso horário", "Check always for changes of the timezone" => "Verificar sempre mudanças no fuso horário", "Timeformat" => "Formato da Hora", "24h" => "24h", "12h" => "12h", -"Calendar CalDAV syncing address:" => "Sincronização de endereço do calendário CalDAV :" +"First day of the week" => "Primeiro dia da semana", +"Calendar CalDAV syncing address:" => "Sincronização de endereço do calendário CalDAV :", +"Users" => "Usuários", +"select users" => "Selecione usuários", +"Editable" => "Editável", +"Groups" => "Grupos", +"select groups" => "Selecione grupos", +"make public" => "Tornar público" ); diff --git a/apps/calendar/l10n/sk_SK.php b/apps/calendar/l10n/sk_SK.php index 3455c2bc75f6173c52c6ef2ad1acb559f28a3d91..e182a9d3ea435d826821e30a875dad194049cca8 100644 --- a/apps/calendar/l10n/sk_SK.php +++ b/apps/calendar/l10n/sk_SK.php @@ -1,9 +1,12 @@ "Nenašiel sa žiadny kalendár.", +"No events found." => "Nenašla sa žiadna udalosť.", "Wrong calendar" => "Zlý kalendár", "New Timezone:" => "Nová časová zóna:", "Timezone changed" => "Časové pásmo zmenené", "Invalid request" => "Neplatná požiadavka", "Calendar" => "Kalendár", +"MMM d[ yyyy]{ '—'[ MMM] d yyyy}" => "d. MMM[ yyyy]{ '—' d.[ MMM] yyyy}", "Birthday" => "Narodeniny", "Business" => "Podnikanie", "Call" => "Hovor", @@ -19,6 +22,7 @@ "Projects" => "Projekty", "Questions" => "Otázky", "Work" => "Práca", +"unnamed" => "nepomenovaný", "Does not repeat" => "Neopakovať", "Daily" => "Denne", "Weekly" => "Týždenne", @@ -80,10 +84,15 @@ "Calendars" => "Kalendáre", "There was a fail, while parsing the file." => "Nastala chyba počas parsovania súboru.", "Choose active calendars" => "Zvoľte aktívne kalendáre", +"Your calendars" => "Vaše kalendáre", "CalDav Link" => "CalDav odkaz", +"Shared calendars" => "Zdielané kalendáre", +"No shared calendars" => "Žiadne zdielané kalendáre", +"Share Calendar" => "Zdielať kalendár", "Download" => "Stiahnuť", "Edit" => "Upraviť", "Delete" => "Odstrániť", +"shared with you by" => "zdielané s vami používateľom", "New calendar" => "Nový kalendár", "Edit calendar" => "Upraviť kalendár", "Displayname" => "Zobrazené meno", @@ -94,8 +103,15 @@ "Cancel" => "Zrušiť", "Edit an event" => "Upraviť udalosť", "Export" => "Exportovať", +"Eventinfo" => "Informácie o udalosti", +"Repeating" => "Opakovanie", +"Alarm" => "Alarm", +"Attendees" => "Účastníci", +"Share" => "Zdielať", "Title of the Event" => "Nadpis udalosti", "Category" => "Kategória", +"Separate categories with commas" => "Kategórie oddelené čiarkami", +"Edit categories" => "Úprava kategórií", "All Day Event" => "Celodenná udalosť", "From" => "Od", "To" => "Do", @@ -125,11 +141,22 @@ "Calendar imported successfully" => "Kalendár úspešne importovaný", "Close Dialog" => "Zatvoriť dialóg", "Create a new event" => "Vytvoriť udalosť", +"View an event" => "Zobraziť udalosť", +"No categories selected" => "Žiadne vybraté kategórie", "Select category" => "Vybrať kategóriu", +"of" => "z", +"at" => "v", "Timezone" => "Časová zóna", "Check always for changes of the timezone" => "Vždy kontroluj zmeny časového pásma", "Timeformat" => "Formát času", "24h" => "24h", "12h" => "12h", -"Calendar CalDAV syncing address:" => "Synchronizačná adresa kalendára CalDAV: " +"First day of the week" => "Prvý deň v týždni", +"Calendar CalDAV syncing address:" => "Synchronizačná adresa kalendára CalDAV: ", +"Users" => "Používatelia", +"select users" => "vybrať používateľov", +"Editable" => "Upravovateľné", +"Groups" => "Skupiny", +"select groups" => "vybrať skupiny", +"make public" => "zverejniť" ); diff --git a/apps/calendar/l10n/sl.php b/apps/calendar/l10n/sl.php index f20f5026dc549bd1210109ea95bfa3e3a2a6fa89..3bf03ede1271e9d5140dd665b4bb1a24c0d12f5e 100644 --- a/apps/calendar/l10n/sl.php +++ b/apps/calendar/l10n/sl.php @@ -1,9 +1,12 @@ "Ni bilo najdenih koledarjev.", +"No events found." => "Ni bilo najdenih dogodkov.", "Wrong calendar" => "Napačen koledar", "New Timezone:" => "Nov časovni pas:", "Timezone changed" => "Časovni pas je bil spremenjen", "Invalid request" => "Neveljaven zahtevek", "Calendar" => "Koledar", +"MMM d[ yyyy]{ '—'[ MMM] d yyyy}" => "MMM d[ yyyy]{ '—'[ MMM] d yyyy}", "Birthday" => "Rojstni dan", "Business" => "Poslovno", "Call" => "Pokliči", @@ -19,6 +22,7 @@ "Projects" => "Projekt", "Questions" => "Vprašanja", "Work" => "Delo", +"unnamed" => "neimenovan", "Does not repeat" => "Se ne ponavlja", "Daily" => "Dnevno", "Weekly" => "Tedensko", @@ -80,10 +84,15 @@ "Calendars" => "Koledarji", "There was a fail, while parsing the file." => "Pri razčlenjevanju datoteke je prišlo do napake.", "Choose active calendars" => "Izberite aktivne koledarje", +"Your calendars" => "Vaši koledarji", "CalDav Link" => "CalDav povezava", +"Shared calendars" => "Koledarji v souporabi", +"No shared calendars" => "Ni koledarjev v souporabi", +"Share Calendar" => "Daj koledar v souporabo", "Download" => "Prenesi", "Edit" => "Uredi", "Delete" => "Izbriši", +"shared with you by" => "z vami souporablja", "New calendar" => "Nov koledar", "Edit calendar" => "Uredi koledar", "Displayname" => "Ime za prikaz", @@ -94,8 +103,15 @@ "Cancel" => "Prekliči", "Edit an event" => "Uredi dogodek", "Export" => "Izvozi", +"Eventinfo" => "Informacije od dogodku", +"Repeating" => "Ponavljanja", +"Alarm" => "Alarm", +"Attendees" => "Udeleženci", +"Share" => "Souporaba", "Title of the Event" => "Naslov dogodka", "Category" => "Kategorija", +"Separate categories with commas" => "Kategorije ločite z vejico", +"Edit categories" => "Uredi kategorije", "All Day Event" => "Celodnevni dogodek", "From" => "Od", "To" => "Do", @@ -125,11 +141,22 @@ "Calendar imported successfully" => "Koledar je bil uspešno uvožen", "Close Dialog" => "Zapri dialog", "Create a new event" => "Ustvari nov dogodek", +"View an event" => "Poglej dogodek", +"No categories selected" => "Nobena kategorija ni izbrana", "Select category" => "Izberi kategorijo", +"of" => "od", +"at" => "pri", "Timezone" => "Časovni pas", "Check always for changes of the timezone" => "Vedno preveri za spremembe časovnega pasu", "Timeformat" => "Zapis časa", "24h" => "24ur", "12h" => "12ur", -"Calendar CalDAV syncing address:" => "CalDAV sinhronizacijski naslov koledarja:" +"First day of the week" => "Prvi dan v tednu", +"Calendar CalDAV syncing address:" => "CalDAV sinhronizacijski naslov koledarja:", +"Users" => "Uporabniki", +"select users" => "izberite uporabnike", +"Editable" => "Možno urejanje", +"Groups" => "Skupine", +"select groups" => "izberite skupine", +"make public" => "objavi" ); diff --git a/apps/calendar/l10n/th_TH.php b/apps/calendar/l10n/th_TH.php index 7dda3943b6f278a23df29fd99bbcea44e15545d1..8aaa7ae756aa91c80798ace6ed3af0d388ceee51 100644 --- a/apps/calendar/l10n/th_TH.php +++ b/apps/calendar/l10n/th_TH.php @@ -1,9 +1,12 @@ "ไม่พบปฏิทินที่ต้องการ", +"No events found." => "ไม่พบกิจกรรมที่ต้องการ", "Wrong calendar" => "ปฏิทินไม่ถูกต้อง", "New Timezone:" => "สร้างโซนเวลาใหม่:", "Timezone changed" => "โซนเวลาถูกเปลี่ยนแล้ว", "Invalid request" => "คำร้องขอไม่ถูกต้อง", "Calendar" => "ปฏิทิน", +"MMM d[ yyyy]{ '—'[ MMM] d yyyy}" => "MMM d[ yyyy]{ '—'[ MMM] d yyyy}", "Birthday" => "วันเกิด", "Business" => "ธุรกิจ", "Call" => "โทรติดต่อ", @@ -19,6 +22,7 @@ "Projects" => "โครงการ", "Questions" => "คำถาม", "Work" => "งาน", +"unnamed" => "ไม่มีชื่อ", "Does not repeat" => "ไม่ต้องทำซ้ำ", "Daily" => "รายวัน", "Weekly" => "รายสัปดาห์", @@ -80,10 +84,15 @@ "Calendars" => "ปฏิทิน", "There was a fail, while parsing the file." => "เกิดความล้มเหลวในการแยกไฟล์", "Choose active calendars" => "เลือกปฏิทินที่ต้องการใช้งาน", +"Your calendars" => "ปฏิทินของคุณ", "CalDav Link" => "ลิงค์ CalDav", +"Shared calendars" => "ปฏิทินที่เปิดแชร์", +"No shared calendars" => "ไม่มีปฏิทินที่เปิดแชร์ไว้", +"Share Calendar" => "เปิดแชร์ปฏิทิน", "Download" => "ดาวน์โหลด", "Edit" => "แก้ไข", "Delete" => "ลบ", +"shared with you by" => "แชร์ให้คุณโดย", "New calendar" => "สร้างปฏิทินใหม่", "Edit calendar" => "แก้ไขปฏิทิน", "Displayname" => "ชื่อที่ต้องการให้แสดง", @@ -94,8 +103,15 @@ "Cancel" => "ยกเลิก", "Edit an event" => "แก้ไขกิจกรรม", "Export" => "ส่งออกข้อมูล", +"Eventinfo" => "ข้อมูลเกี่ยวกับกิจกรรม", +"Repeating" => "ทำซ้ำ", +"Alarm" => "แจ้งเตือน", +"Attendees" => "ผู้เข้าร่วมกิจกรรม", +"Share" => "แชร์", "Title of the Event" => "ชื่อของกิจกรรม", "Category" => "หมวดหมู่", +"Separate categories with commas" => "คั่นระหว่างรายการหมวดหมู่ด้วยเครื่องหมายจุลภาคหรือคอมม่า", +"Edit categories" => "แก้ไขหมวดหมู่", "All Day Event" => "เป็นกิจกรรมตลอดทั้งวัน", "From" => "จาก", "To" => "ถึง", @@ -125,11 +141,22 @@ "Calendar imported successfully" => "ปฏิทินถูกนำเข้าข้อมูลเรียบร้อยแล้ว", "Close Dialog" => "ปิดกล่องข้อความโต้ตอบ", "Create a new event" => "สร้างกิจกรรมใหม่", +"View an event" => "ดูกิจกรรม", +"No categories selected" => "ยังไม่ได้เลือกหมวดหมู่", "Select category" => "เลือกหมวดหมู่", +"of" => "ของ", +"at" => "ที่", "Timezone" => "โซนเวลา", "Check always for changes of the timezone" => "ตรวจสอบการเปลี่ยนแปลงโซนเวลาอยู่เสมอ", "Timeformat" => "รูปแบบการแสดงเวลา", "24h" => "24 ช.ม.", "12h" => "12 ช.ม.", -"Calendar CalDAV syncing address:" => "ที่อยู่ในการเชื่อมข้อมูลกับปฏิทิน CalDav:" +"First day of the week" => "วันแรกของสัปดาห์", +"Calendar CalDAV syncing address:" => "ที่อยู่ในการเชื่อมข้อมูลกับปฏิทิน CalDav:", +"Users" => "ผู้ใช้งาน", +"select users" => "เลือกผู้ใช้งาน", +"Editable" => "สามารถแก้ไขได้", +"Groups" => "กลุ่ม", +"select groups" => "เลือกกลุ่ม", +"make public" => "กำหนดเป็นสาธารณะ" ); diff --git a/apps/calendar/l10n/tr.php b/apps/calendar/l10n/tr.php index aa72c76ebab4771bad5fd4b3f3dbd50eca0d3470..a72e4c39f6d114670d576b6fb5b1fdaa0dd977fc 100644 --- a/apps/calendar/l10n/tr.php +++ b/apps/calendar/l10n/tr.php @@ -1,9 +1,12 @@ "Takvim yok.", +"No events found." => "Etkinlik yok.", "Wrong calendar" => "Yanlış takvim", "New Timezone:" => "Yeni Zamandilimi:", "Timezone changed" => "Zaman dilimi değiştirildi", "Invalid request" => "Geçersiz istek", "Calendar" => "Takvim", +"MMM d[ yyyy]{ '—'[ MMM] d yyyy}" => "AAA g[ yyyy]{ '—'[ AAA] g yyyy}", "Birthday" => "Doğum günü", "Business" => "İş", "Call" => "Arama", @@ -19,6 +22,7 @@ "Projects" => "Projeler", "Questions" => "Sorular", "Work" => "İş", +"unnamed" => "isimsiz", "Does not repeat" => "Tekrar etmiyor", "Daily" => "Günlük", "Weekly" => "Haftalı", @@ -38,6 +42,7 @@ "Friday" => "Cuma", "Saturday" => "Cumartesi", "Sunday" => "Pazar", +"events week of month" => "ayın etkinlikler haftası", "first" => "birinci", "second" => "ikinci", "third" => "üçüncü", @@ -79,10 +84,15 @@ "Calendars" => "Takvimler", "There was a fail, while parsing the file." => "Dosya okunurken başarısızlık oldu.", "Choose active calendars" => "Aktif takvimleri seçin", +"Your calendars" => "Takvimleriniz", "CalDav Link" => "CalDav Bağlantısı", +"Shared calendars" => "Paylaşılan", +"No shared calendars" => "Paylaşılan takvim yok", +"Share Calendar" => "Takvimi paylaş", "Download" => "İndir", "Edit" => "Düzenle", "Delete" => "Sil", +"shared with you by" => "sizinle paylaşılmış", "New calendar" => "Yeni takvim", "Edit calendar" => "Takvimi düzenle", "Displayname" => "Görünüm adı", @@ -93,8 +103,15 @@ "Cancel" => "İptal", "Edit an event" => "Bir olay düzenle", "Export" => "Dışa aktar", +"Eventinfo" => "Etkinlik bilgisi", +"Repeating" => "Tekrarlama", +"Alarm" => "Alarm", +"Attendees" => "Katılanlar", +"Share" => "Paylaş", "Title of the Event" => "Olayın Başlığı", "Category" => "Kategori", +"Separate categories with commas" => "Kategorileri virgülle ayırın", +"Edit categories" => "Kategorileri düzenle", "All Day Event" => "Tüm Gün Olay", "From" => "Kimden", "To" => "Kime", @@ -107,18 +124,39 @@ "Advanced" => "Gelişmiş", "Select weekdays" => "Hafta günlerini seçin", "Select days" => "Günleri seçin", +"and the events day of year." => "ve yılın etkinlikler günü.", +"and the events day of month." => "ve ayın etkinlikler günü.", "Select months" => "Ayları seç", "Select weeks" => "Haftaları seç", +"and the events week of year." => "ve yılın etkinkinlikler haftası.", "Interval" => "Aralık", "End" => "Son", +"occurrences" => "olaylar", +"Import a calendar file" => "Takvim dosyasını içeri aktar", "Please choose the calendar" => "Lütfen takvimi seçin", +"create a new calendar" => "Yeni bir takvim oluştur", "Name of new calendar" => "Yeni takvimin adı", "Import" => "İçe Al", +"Importing calendar" => "Takvim içe aktarılıyor", +"Calendar imported successfully" => "Takvim başarıyla içe aktarıldı", +"Close Dialog" => "Diyalogu kapat", "Create a new event" => "Yeni olay oluştur", +"View an event" => "Bir olay görüntüle", +"No categories selected" => "Kategori seçilmedi", "Select category" => "Kategori seçin", +"of" => "nın", +"at" => "üzerinde", "Timezone" => "Zaman dilimi", +"Check always for changes of the timezone" => "Sürekli zaman dilimi değişikliklerini kontrol et", "Timeformat" => "Saat biçimi", "24h" => "24s", "12h" => "12s", -"Calendar CalDAV syncing address:" => "CalDAV Takvim senkron adresi:" +"First day of the week" => "Haftanın ilk günü", +"Calendar CalDAV syncing address:" => "CalDAV Takvim eşzamanlama adresi:", +"Users" => "Kullanıcılar", +"select users" => "kullanıcıları seç", +"Editable" => "Düzenlenebilir", +"Groups" => "Gruplar", +"select groups" => "grupları seç", +"make public" => "kamuyla paylaş" ); diff --git a/apps/calendar/l10n/zh_CN.php b/apps/calendar/l10n/zh_CN.php index 8cd909cc7f80fef459a2a713fc9b772b8d404518..129aa8d8e86e4cfb3fa2b34387c84e03898fefce 100644 --- a/apps/calendar/l10n/zh_CN.php +++ b/apps/calendar/l10n/zh_CN.php @@ -1,4 +1,6 @@ "无法找到日历。", +"No events found." => "无法找到事件。", "Wrong calendar" => "错误的日历", "New Timezone:" => "新时区:", "Timezone changed" => "时区已修改", @@ -19,6 +21,7 @@ "Projects" => "项目", "Questions" => "问题", "Work" => "工作", +"unnamed" => "未命名", "Does not repeat" => "不重复", "Daily" => "每天", "Weekly" => "每周", @@ -80,10 +83,15 @@ "Calendars" => "日历", "There was a fail, while parsing the file." => "解析文件失败", "Choose active calendars" => "选择活动日历", +"Your calendars" => "您的日历", "CalDav Link" => "CalDav 链接", +"Shared calendars" => "共享的日历", +"No shared calendars" => "无共享的日历", +"Share Calendar" => "共享日历", "Download" => "下载", "Edit" => "编辑", "Delete" => "删除", +"shared with you by" => " ", "New calendar" => "新日历", "Edit calendar" => "编辑日历", "Displayname" => "显示名称", @@ -94,8 +102,14 @@ "Cancel" => "取消", "Edit an event" => "编辑事件", "Export" => "导出", +"Eventinfo" => "事件信息", +"Repeating" => "重复", +"Attendees" => "参加者", +"Share" => "共享", "Title of the Event" => "事件标题", "Category" => "分类", +"Separate categories with commas" => "用逗号分隔分类", +"Edit categories" => "编辑分类", "All Day Event" => "全天事件", "From" => "自", "To" => "至", @@ -125,11 +139,20 @@ "Calendar imported successfully" => "导入日历成功", "Close Dialog" => "关闭对话框", "Create a new event" => "创建新事件", +"View an event" => "查看事件", +"No categories selected" => "无选中分类", "Select category" => "选择分类", "Timezone" => "时区", "Check always for changes of the timezone" => "选中则总是按照时区变化", "Timeformat" => "时间格式", "24h" => "24小时", "12h" => "12小时", -"Calendar CalDAV syncing address:" => "日历CalDAV 同步地址:" +"First day of the week" => "每周的第一天", +"Calendar CalDAV syncing address:" => "日历CalDAV 同步地址:", +"Users" => "用户", +"select users" => "选中用户", +"Editable" => "可编辑", +"Groups" => "分组", +"select groups" => "选中分组", +"make public" => "公开" ); diff --git a/apps/calendar/l10n/zh_TW.php b/apps/calendar/l10n/zh_TW.php index 2b8fc790cca878858c44c776603c02db0241de12..b4f1d4e9b87cce06f2fc2fe886cdd5f524a38fb7 100644 --- a/apps/calendar/l10n/zh_TW.php +++ b/apps/calendar/l10n/zh_TW.php @@ -90,6 +90,9 @@ "Cancel" => "取消", "Edit an event" => "編輯事件", "Export" => "匯出", +"Alarm" => "鬧鐘", +"Attendees" => "出席者", +"Share" => "分享", "Title of the Event" => "事件標題", "Category" => "分類", "All Day Event" => "全天事件", @@ -124,5 +127,10 @@ "Timeformat" => "日期格式", "24h" => "24小時制", "12h" => "12小時制", -"Calendar CalDAV syncing address:" => "CalDAV 的日曆同步地址:" +"Calendar CalDAV syncing address:" => "CalDAV 的日曆同步地址:", +"Users" => "使用者", +"select users" => "選擇使用者", +"Editable" => "可編輯", +"Groups" => "群組", +"select groups" => "選擇群組" ); diff --git a/apps/calendar/lib/app.php b/apps/calendar/lib/app.php old mode 100755 new mode 100644 diff --git a/apps/calendar/lib/calendar.php b/apps/calendar/lib/calendar.php old mode 100755 new mode 100644 diff --git a/apps/calendar/lib/hooks.php b/apps/calendar/lib/hooks.php index 22e8d8e20f28257bc1c6e7c31401546b2a9d693a..328d2951d231cde4669accd7da609c5b730a1449 100644 --- a/apps/calendar/lib/hooks.php +++ b/apps/calendar/lib/hooks.php @@ -22,6 +22,8 @@ class OC_Calendar_Hooks{ OC_Calendar_Calendar::deleteCalendar($calendar['id']); } + OC_Calendar_Share::post_userdelete($parameters['uid']); + return true; } } diff --git a/apps/calendar/lib/object.php b/apps/calendar/lib/object.php old mode 100755 new mode 100644 diff --git a/apps/calendar/lib/search.php b/apps/calendar/lib/search.php old mode 100755 new mode 100644 diff --git a/apps/calendar/lib/share.php b/apps/calendar/lib/share.php old mode 100755 new mode 100644 index 488495aefc424e02b6138d1eaa5ec7771585e547..54c531892f05b3c095b83022a6619fbab2fc91fb --- a/apps/calendar/lib/share.php +++ b/apps/calendar/lib/share.php @@ -256,4 +256,21 @@ class OC_Calendar_Share{ $stmt = OCP\DB::prepare("UPDATE *PREFIX*calendar_share_calendar SET active = ? WHERE share = ? AND sharetype = 'user' AND calendarid = ?"); $stmt->execute(array($active, $share, $id)); } + + /* + * @brief delete all shared calendars / events after a user was deleted + * @param (string) $userid + * @return (bool) + */ + public static function post_userdelete($userid){ + $stmt = OCP\DB::prepare('DELETE FROM *PREFIX*calendar_share_calendar WHERE owner = ?'); + $stmt->execute(array($userid)); + $stmt = OCP\DB::prepare('DELETE FROM *PREFIX*calendar_share_event WHERE owner = ?'); + $stmt->execute(array($userid)); + $stmt = OCP\DB::prepare("DELETE FROM *PREFIX*calendar_share_calendar WHERE share = ? AND sharetype = 'user'"); + $stmt->execute(array($userid)); + $stmt = OCP\DB::prepare("DELETE FROM *PREFIX*calendar_share_event WHERE share = ? AND sharetype = 'user'"); + $stmt->execute(array($userid)); + return true; + } } \ No newline at end of file diff --git a/apps/calendar/settings.php b/apps/calendar/settings.php old mode 100755 new mode 100644 diff --git a/apps/calendar/templates/calendar.php b/apps/calendar/templates/calendar.php old mode 100755 new mode 100644 diff --git a/apps/calendar/templates/part.choosecalendar.php b/apps/calendar/templates/part.choosecalendar.php old mode 100755 new mode 100644 index a140316ea07863ab96c7173ed0d22a998cdfaba1..8d621cc3630a5e1b6ca554f4ed85acd82cd2cf09 --- a/apps/calendar/templates/part.choosecalendar.php +++ b/apps/calendar/templates/part.choosecalendar.php @@ -24,7 +24,7 @@ for($i = 0; $i < count($option_calendars); $i++){
    -

    ">

    +

    ">


    diff --git a/apps/calendar/templates/part.choosecalendar.rowfields.php b/apps/calendar/templates/part.choosecalendar.rowfields.php old mode 100755 new mode 100644 diff --git a/apps/calendar/templates/part.eventform.php b/apps/calendar/templates/part.eventform.php old mode 100755 new mode 100644 diff --git a/apps/calendar/templates/part.import.php b/apps/calendar/templates/part.import.php old mode 100755 new mode 100644 diff --git a/apps/calendar/templates/part.showevent.php b/apps/calendar/templates/part.showevent.php old mode 100755 new mode 100644 diff --git a/apps/calendar/templates/settings.php b/apps/calendar/templates/settings.php old mode 100755 new mode 100644 diff --git a/apps/calendar/templates/share.dropdown.php b/apps/calendar/templates/share.dropdown.php old mode 100755 new mode 100644 index 20d4c19bc19ea1c4fa9d0a301186b7837ed9f657..07b4c4bced5811b04473a09df0239064d6418ea2 --- a/apps/calendar/templates/share.dropdown.php +++ b/apps/calendar/templates/share.dropdown.php @@ -63,7 +63,7 @@ echo OCP\html_select_options($allgroups, array());