Raised ADOdb to version 5.11.0
authorXavier Perseguers <typo3@perseguers.ch>
Mon, 23 Aug 2010 14:27:05 +0000 (14:27 +0000)
committerXavier Perseguers <typo3@perseguers.ch>
Mon, 23 Aug 2010 14:27:05 +0000 (14:27 +0000)
git-svn-id: https://svn.typo3.org/TYPO3v4/Core/trunk@8649 709f56b5-9817-0410-a4d7-c38de5d9e867

122 files changed:
ChangeLog
typo3/sysext/adodb/adodb/adodb-active-record.inc.php
typo3/sysext/adodb/adodb/adodb-active-recordx.inc.php
typo3/sysext/adodb/adodb/adodb-csvlib.inc.php
typo3/sysext/adodb/adodb/adodb-datadict.inc.php
typo3/sysext/adodb/adodb/adodb-error.inc.php
typo3/sysext/adodb/adodb/adodb-errorhandler.inc.php
typo3/sysext/adodb/adodb/adodb-errorhandler.inc.php.orig [new file with mode: 0644]
typo3/sysext/adodb/adodb/adodb-errorpear.inc.php
typo3/sysext/adodb/adodb/adodb-exceptions.inc.php
typo3/sysext/adodb/adodb/adodb-iterator.inc.php
typo3/sysext/adodb/adodb/adodb-lib.inc.php
typo3/sysext/adodb/adodb/adodb-memcache.lib.inc.php
typo3/sysext/adodb/adodb/adodb-pager.inc.php
typo3/sysext/adodb/adodb/adodb-pear.inc.php
typo3/sysext/adodb/adodb/adodb-perf.inc.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/adodb-php4.inc.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/adodb-time.inc.php
typo3/sysext/adodb/adodb/adodb-xmlschema.inc.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/adodb-xmlschema03.inc.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/adodb.inc.php
typo3/sysext/adodb/adodb/datadict/datadict-access.inc.php
typo3/sysext/adodb/adodb/datadict/datadict-db2.inc.php
typo3/sysext/adodb/adodb/datadict/datadict-firebird.inc.php
typo3/sysext/adodb/adodb/datadict/datadict-generic.inc.php
typo3/sysext/adodb/adodb/datadict/datadict-ibase.inc.php
typo3/sysext/adodb/adodb/datadict/datadict-informix.inc.php
typo3/sysext/adodb/adodb/datadict/datadict-mssql.inc.php
typo3/sysext/adodb/adodb/datadict/datadict-mssqlnative.inc.php
typo3/sysext/adodb/adodb/datadict/datadict-mysql.inc.php
typo3/sysext/adodb/adodb/datadict/datadict-oci8.inc.php
typo3/sysext/adodb/adodb/datadict/datadict-postgres.inc.php
typo3/sysext/adodb/adodb/datadict/datadict-sapdb.inc.php
typo3/sysext/adodb/adodb/datadict/datadict-sqlite.inc.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/datadict/datadict-sybase.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-access.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-ado.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-ado5.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-ado_access.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-ado_mssql.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-borland_ibase.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-csv.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-db2.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-db2oci.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-db2ora.inc.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/drivers/adodb-fbsql.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-firebird.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-ibase.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-informix.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-informix72.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-ldap.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-mssql.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-mssql_n.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-mssqlnative.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-mssqlpo.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-mysql.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-mysqli.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-mysqlpo.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-mysqlt.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-netezza.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-oci8.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-oci805.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-oci8po.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-odbc.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-odbc_db2.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-odbc_mssql.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-odbc_oracle.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-odbtp.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-odbtp_unicode.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-oracle.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-pdo.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-pdo_mssql.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-pdo_mysql.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-pdo_oci.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-pdo_pgsql.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-pdo_sqlite.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-postgres.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-postgres64.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-postgres7.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-postgres8.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-proxy.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-sapdb.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-sqlanywhere.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-sqlite.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-sqlitepo.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-sybase.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-sybase_ase.inc.php
typo3/sysext/adodb/adodb/drivers/adodb-vfp.inc.php
typo3/sysext/adodb/adodb/perf/perf-db2.inc.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/perf/perf-informix.inc.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/perf/perf-mssql.inc.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/perf/perf-mssqlnative.inc.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/perf/perf-mysql.inc.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/perf/perf-oci8.inc.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/perf/perf-postgres.inc.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/pivottable.inc.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/rsfilter.inc.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/server.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/session/adodb-compress-bzip2.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/session/adodb-compress-gzip.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/session/adodb-cryptsession.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/session/adodb-cryptsession2.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/session/adodb-encrypt-mcrypt.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/session/adodb-encrypt-md5.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/session/adodb-encrypt-secret.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/session/adodb-encrypt-sha1.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/session/adodb-sess.txt [new file with mode: 0644]
typo3/sysext/adodb/adodb/session/adodb-session-clob.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/session/adodb-session-clob2.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/session/adodb-session.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/session/adodb-session2.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/session/adodb-sessions.mysql.sql [new file with mode: 0644]
typo3/sysext/adodb/adodb/session/adodb-sessions.oracle.clob.sql [new file with mode: 0644]
typo3/sysext/adodb/adodb/session/adodb-sessions.oracle.sql [new file with mode: 0644]
typo3/sysext/adodb/adodb/session/crypt.inc.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/session/session_schema.xml [new file with mode: 0644]
typo3/sysext/adodb/adodb/session/session_schema2.xml [new file with mode: 0644]
typo3/sysext/adodb/adodb/toexport.inc.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/tohtml.inc.php [new file with mode: 0644]
typo3/sysext/adodb/adodb/xmlschema.dtd [new file with mode: 0644]
typo3/sysext/adodb/adodb/xmlschema03.dtd [new file with mode: 0644]
typo3/sysext/adodb/ext_emconf.php

index ca7c129..da9786b 100755 (executable)
--- a/ChangeLog
+++ b/ChangeLog
@@ -4,6 +4,7 @@
 
 2010-08-23  Xavier Perseguers  <typo3@perseguers.ch>
 
+       * Raised ADOdb to version 5.11.0
        * Raised DBAL to version 1.2.0alpha1
        * Fixed bug #15528: Add unit tests for t3lib_db_PreparedStatement (thanks to Helmut Hummel)
        * Fixed bug #15527: Enhance t3lib_db_PreparedStatement (thanks to Helmut Hummel)
index 5bfbd61..845c656 100644 (file)
@@ -1,18 +1,18 @@
 <?php
 /*
 
-@version V5.10 10 Nov 2009   (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
+@version V5.11 5 May 2010   (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
   Latest version is available at http://adodb.sourceforge.net
-
-  Released under both BSD license and Lesser GPL library license.
-  Whenever there is any discrepancy between the two licenses,
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
   the BSD license will take precedence.
-
+  
   Active Record implementation. Superset of Zend Framework's.
-
+  
   Version 0.92
-
-  See http://www-128.ibm.com/developerworks/java/library/j-cb03076/?ca=dgr-lnxw01ActiveRecord
+  
+  See http://www-128.ibm.com/developerworks/java/library/j-cb03076/?ca=dgr-lnxw01ActiveRecord 
        for info on Ruby on Rails Active Record implementation
 */
 
@@ -44,30 +44,30 @@ class ADODB_Active_Table {
 
 // $db = database connection
 // $index = name of index - can be associative, for an example see
-//    http://phplens.com/lens/lensforum/msgs.php?id=17790
+//    http://phplens.com/lens/lensforum/msgs.php?id=17790 
 // returns index into $_ADODB_ACTIVE_DBS
 function ADODB_SetDatabaseAdapter(&$db, $index=false)
 {
        global $_ADODB_ACTIVE_DBS;
-
+       
                foreach($_ADODB_ACTIVE_DBS as $k => $d) {
                        if (PHP_VERSION >= 5) {
                                if ($d->db === $db) return $k;
                        } else {
-                               if ($d->db->_connectionID === $db->_connectionID && $db->database == $d->db->database)
+                               if ($d->db->_connectionID === $db->_connectionID && $db->database == $d->db->database) 
                                        return $k;
                        }
                }
-
+               
                $obj = new ADODB_Active_DB();
                $obj->db = $db;
                $obj->tables = array();
-
+               
                if ($index == false) $index = sizeof($_ADODB_ACTIVE_DBS);
 
-
+               
                $_ADODB_ACTIVE_DBS[$index] = $obj;
-
+               
                return sizeof($_ADODB_ACTIVE_DBS)-1;
 }
 
@@ -75,8 +75,8 @@ function ADODB_SetDatabaseAdapter(&$db, $index=false)
 class ADODB_Active_Record {
        static $_changeNames = true; // dynamically pluralize table names
        static $_quoteNames = false;
-
-       static $_foreignSuffix = '_id'; //
+       
+       static $_foreignSuffix = '_id'; // 
        var $_dbat; // associative index pointing to ADODB_Active_DB eg. $ADODB_Active_DBS[_dbat]
        var $_table; // tablename, if set in class definition then use it as table name
        var $_tableat; // associative index pointing to ADODB_Active_Table, eg $ADODB_Active_DBS[_dbat]->tables[$this->_tableat]
@@ -95,29 +95,29 @@ class ADODB_Active_Record {
        }
 
        // should be static
-       static function SetDatabaseAdapter(&$db, $index=false)
+       static function SetDatabaseAdapter(&$db, $index=false) 
        {
                return ADODB_SetDatabaseAdapter($db, $index);
        }
-
-
+       
+       
        public function __set($name, $value)
        {
                $name = str_replace(' ', '_', $name);
                $this->$name = $value;
        }
-
+       
        // php5 constructor
        function __construct($table = false, $pkeyarr=false, $db=false)
        {
        global $ADODB_ASSOC_CASE,$_ADODB_ACTIVE_DBS;
-
+       
                if ($db == false && is_object($pkeyarr)) {
                        $db = $pkeyarr;
                        $pkeyarr = false;
                }
-
-               if (!$table) {
+               
+               if (!$table) { 
                        if (!empty($this->_table)) $table = $this->_table;
                        else $table = $this->_pluralize(get_class($this));
                }
@@ -135,13 +135,13 @@ class ADODB_Active_Record {
 
                $this->UpdateActiveTable($pkeyarr);
        }
-
+       
        function __wakeup()
        {
                $class = get_class($this);
                new $class;
        }
-
+       
        function _pluralize($table)
        {
                if (!ADODB_Active_Record::$_changeNames) return $table;
@@ -152,26 +152,26 @@ class ADODB_Active_Record {
                $lastc2 = substr($ut,$len-2);
                switch ($lastc) {
                case 'S':
-                       return $table.'es';
+                       return $table.'es';     
                case 'Y':
                        return substr($table,0,$len-1).'ies';
-               case 'X':
+               case 'X':       
                        return $table.'es';
-               case 'H':
+               case 'H': 
                        if ($lastc2 == 'CH' || $lastc2 == 'SH')
                                return $table.'es';
                default:
                        return $table.'s';
                }
        }
-
+       
        // CFR Lamest singular inflector ever - @todo Make it real!
        // Note: There is an assumption here...and it is that the argument's length >= 4
        function _singularize($tables)
        {
-
+       
                if (!ADODB_Active_Record::$_changeNames) return $table;
-
+       
                $ut = strtoupper($tables);
                $len = strlen($tables);
                if($ut[$len-1] != 'S')
@@ -203,14 +203,14 @@ class ADODB_Active_Record {
                $table->_hasMany[$foreignRef] = $ar;
        #       $this->$foreignRef = $this->_hasMany[$foreignRef]; // WATCHME Removed assignment by ref. to please __get()
        }
-
+       
        // use when you don't want ADOdb to auto-pluralize tablename
        static function TableHasMany($table, $foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
        {
                $ar = new ADODB_Active_Record($table);
                $ar->hasMany($foreignRef, $foreignKey, $foreignClass);
        }
-
+       
        // use when you don't want ADOdb to auto-pluralize tablename
        static function TableKeyHasMany($table, $tablePKey, $foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
        {
@@ -218,8 +218,8 @@ class ADODB_Active_Record {
                $ar = new ADODB_Active_Record($table,$tablePKey);
                $ar->hasMany($foreignRef, $foreignKey, $foreignClass);
        }
-
-
+       
+       
        // use when you want ADOdb to auto-pluralize tablename for you. Note that the class must already be defined.
        // e.g. class Person will generate relationship for table Persons
        static function ClassHasMany($parentclass, $foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
@@ -227,7 +227,7 @@ class ADODB_Active_Record {
                $ar = new $parentclass();
                $ar->hasMany($foreignRef, $foreignKey, $foreignClass);
        }
-
+       
 
        function belongsTo($foreignRef,$foreignKey=false, $parentKey='', $parentClass = 'ADODB_Active_Record')
        {
@@ -238,24 +238,24 @@ class ADODB_Active_Record {
                $ar->parentKey = $parentKey;
                $ar->UpdateActiveTable();
                $ar->foreignKey = ($foreignKey) ? $foreignKey : $foreignRef.ADODB_Active_Record::$_foreignSuffix;
-
+               
                $table =& $this->TableInfo();
                $table->_belongsTo[$foreignRef] = $ar;
        #       $this->$foreignRef = $this->_belongsTo[$foreignRef];
        }
-
+       
        static function ClassBelongsTo($class, $foreignRef, $foreignKey=false, $parentKey='', $parentClass = 'ADODB_Active_Record')
        {
                $ar = new $class();
                $ar->belongsTo($foreignRef, $foreignKey, $parentKey, $parentClass);
        }
-
+       
        static function TableBelongsTo($table, $foreignRef, $foreignKey=false, $parentKey='', $parentClass = 'ADODB_Active_Record')
        {
                $ar = new ADOdb_Active_Record($table);
                $ar->belongsTo($foreignRef, $foreignKey, $parentKey, $parentClass);
        }
-
+       
        static function TableKeyBelongsTo($table, $tablePKey, $foreignRef, $foreignKey=false, $parentKey='', $parentClass = 'ADODB_Active_Record')
        {
                if (!is_array($tablePKey)) $tablePKey = array($tablePKey);
@@ -266,8 +266,8 @@ class ADODB_Active_Record {
 
        /**
         * __get Access properties - used for lazy loading
-        *
-        * @param mixed $name
+        * 
+        * @param mixed $name 
         * @access protected
         * @return mixed
         */
@@ -275,9 +275,9 @@ class ADODB_Active_Record {
        {
                return $this->LoadRelations($name, '', -1, -1);
        }
-
+       
        /**
-        * @param string $name
+        * @param string $name 
         * @param string $whereOrderBy : eg. ' AND field1 = value ORDER BY field2'
         * @param offset
         * @param limit
@@ -289,12 +289,12 @@ class ADODB_Active_Record {
                $table = $this->TableInfo();
                if ($limit >= 0) $extras['limit'] = $limit;
                if ($offset >= 0) $extras['offset'] = $offset;
-
-               if (strlen($whereOrderBy))
+               
+               if (strlen($whereOrderBy)) 
                        if (!preg_match('/^[ \n\r]*AND/i',$whereOrderBy))
                                if (!preg_match('/^[ \n\r]*ORDER[ \n\r]/i',$whereOrderBy))
                                        $whereOrderBy = 'AND '.$whereOrderBy;
-
+                               
                if(!empty($table->_belongsTo[$name]))
                {
                        $obj = $table->_belongsTo[$name];
@@ -305,7 +305,7 @@ class ADODB_Active_Record {
                        {
                                if ($obj->parentKey) $key = $obj->parentKey;
                                else $key = reset($table->keys);
-
+                               
                                $arrayOfOne = $obj->Find($key.'='.$this->$columnName.' '.$whereOrderBy,false,false,$extras);
                                if ($arrayOfOne) {
                                        $this->$name = $arrayOfOne[0];
@@ -314,7 +314,7 @@ class ADODB_Active_Record {
                        }
                }
                if(!empty($table->_hasMany[$name]))
-               {
+               {       
                        $obj = $table->_hasMany[$name];
                        $key = reset($table->keys);
                        $id = @$this->$key;
@@ -327,11 +327,11 @@ class ADODB_Active_Record {
                        $this->$name = $objs;
                        return $objs;
                }
-
+               
                return array();
        }
        //////////////////////////////////
-
+       
        // update metadata
        function UpdateActiveTable($pkeys=false,$forceUpdate=false)
        {
@@ -345,9 +345,9 @@ class ADODB_Active_Record {
                $tableat = $this->_tableat;
                if (!$forceUpdate && !empty($tables[$tableat])) {
 
-                       $tobj = $tables[$tableat];
-                       foreach($tobj->flds as $name => $fld) {
-                       if ($ADODB_ACTIVE_DEFVALS && isset($fld->default_value))
+                       $acttab = $tables[$tableat];
+                       foreach($acttab->flds as $name => $fld) {
+                       if ($ADODB_ACTIVE_DEFVALS && isset($fld->default_value)) 
                                $this->$name = $fld->default_value;
                        else
                                $this->$name = null;
@@ -361,11 +361,19 @@ class ADODB_Active_Record {
                        @flock($fp, LOCK_SH);
                        $acttab = unserialize(fread($fp,100000));
                        fclose($fp);
-                       if ($acttab->_created + $ADODB_ACTIVE_CACHESECS - (abs(rand()) % 16) > time()) {
+                       if ($acttab->_created + $ADODB_ACTIVE_CACHESECS - (abs(rand()) % 16) > time()) { 
                                // abs(rand()) randomizes deletion, reducing contention to delete/refresh file
                                // ideally, you should cache at least 32 secs
+                               
+                               foreach($acttab->flds as $name => $fld) {
+                                       if ($ADODB_ACTIVE_DEFVALS && isset($fld->default_value)) 
+                                               $this->$name = $fld->default_value;
+                                       else
+                                               $this->$name = null;
+                               }
+       
                                $activedb->tables[$table] = $acttab;
-
+                               
                                //if ($db->debug) ADOConnection::outp("Reading cached active record file: $fname");
                                return;
                        } else if ($db->debug) {
@@ -374,18 +382,18 @@ class ADODB_Active_Record {
                }
                $activetab = new ADODB_Active_Table();
                $activetab->name = $table;
-
+               
                $save = $ADODB_FETCH_MODE;
                $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
                if ($db->fetchMode !== false) $savem = $db->SetFetchMode(false);
-
+               
                $cols = $db->MetaColumns($table);
-
+               
                if (isset($savem)) $db->SetFetchMode($savem);
                $ADODB_FETCH_MODE = $save;
-
+               
                if (!$cols) {
-                       $this->Error("Invalid table name: $table",'UpdateActiveTable');
+                       $this->Error("Invalid table name: $table",'UpdateActiveTable'); 
                        return false;
                }
                $fld = reset($cols);
@@ -395,17 +403,17 @@ class ADODB_Active_Record {
                                foreach($cols as $name => $fld) {
                                        if (!empty($fld->primary_key)) $pkeys[] = $name;
                                }
-                       } else
+                       } else  
                                $pkeys = $this->GetPrimaryKeys($db, $table);
                }
                if (empty($pkeys)) {
                        $this->Error("No primary key found for table $table",'UpdateActiveTable');
                        return false;
                }
-
+               
                $attr = array();
                $keys = array();
-
+               
                switch($ADODB_ASSOC_CASE) {
                case 0:
                        foreach($cols as $name => $fldobj) {
@@ -420,18 +428,18 @@ class ADODB_Active_Record {
                                $keys[strtolower($name)] = strtolower($name);
                        }
                        break;
-
-               case 1:
+                       
+               case 1: 
                        foreach($cols as $name => $fldobj) {
                                $name = strtoupper($name);
-
+               
                 if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
                     $this->$name = $fldobj->default_value;
                 else
                                        $this->$name = null;
                                $attr[$name] = $fldobj;
                        }
-
+                       
                        foreach($pkeys as $k => $name) {
                                $keys[strtoupper($name)] = strtoupper($name);
                        }
@@ -439,7 +447,7 @@ class ADODB_Active_Record {
                default:
                        foreach($cols as $name => $fldobj) {
                                $name = ($fldobj->name);
-
+                
                 if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
                     $this->$name = $fldobj->default_value;
                 else
@@ -451,7 +459,7 @@ class ADODB_Active_Record {
                        }
                        break;
                }
-
+               
                $activetab->keys = $keys;
                $activetab->flds = $attr;
 
@@ -463,58 +471,58 @@ class ADODB_Active_Record {
                }
                if (isset($activedb->tables[$table])) {
                        $oldtab = $activedb->tables[$table];
-
+               
                        if ($oldtab) $activetab->_belongsTo = $oldtab->_belongsTo;
                        if ($oldtab) $activetab->_hasMany = $oldtab->_hasMany;
                }
                $activedb->tables[$table] = $activetab;
        }
-
+       
        function GetPrimaryKeys(&$db, $table)
        {
                return $db->MetaPrimaryKeys($table);
        }
-
-       // error handler for both PHP4+5.
+       
+       // error handler for both PHP4+5. 
        function Error($err,$fn)
        {
        global $_ADODB_ACTIVE_DBS;
-
+       
                $fn = get_class($this).'::'.$fn;
                $this->_lasterr = $fn.': '.$err;
-
+               
                if ($this->_dbat < 0) $db = false;
                else {
                        $activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
                        $db = $activedb->db;
                }
-
-               if (function_exists('adodb_throw')) {
+               
+               if (function_exists('adodb_throw')) {   
                        if (!$db) adodb_throw('ADOdb_Active_Record', $fn, -1, $err, 0, 0, false);
                        else adodb_throw($db->databaseType, $fn, -1, $err, 0, 0, $db);
                } else
                        if (!$db || $db->debug) ADOConnection::outp($this->_lasterr);
-
+               
        }
-
+       
        // return last error message
        function ErrorMsg()
        {
                if (!function_exists('adodb_throw')) {
                        if ($this->_dbat < 0) $db = false;
                        else $db = $this->DB();
-
+               
                        // last error could be database error too
                        if ($db && $db->ErrorMsg()) return $db->ErrorMsg();
                }
                return $this->_lasterr;
        }
-
-       function ErrorNo()
+       
+       function ErrorNo() 
        {
                if ($this->_dbat < 0) return -9999; // no database connection...
                $db = $this->DB();
-
+               
                return (int) $db->ErrorNo();
        }
 
@@ -523,7 +531,7 @@ class ADODB_Active_Record {
        function DB()
        {
        global $_ADODB_ACTIVE_DBS;
-
+       
                if ($this->_dbat < 0) {
                        $false = false;
                        $this->Error("No database connection set: use ADOdb_Active_Record::SetDatabaseAdaptor(\$db)", "DB");
@@ -533,7 +541,7 @@ class ADODB_Active_Record {
                $db = $activedb->db;
                return $db;
        }
-
+       
        // retrieve ADODB_Active_Table
        function &TableInfo()
        {
@@ -542,8 +550,8 @@ class ADODB_Active_Record {
                $table = $activedb->tables[$this->_tableat];
                return $table;
        }
-
-
+       
+       
        // I have an ON INSERT trigger on a table that sets other columns in the table.
        // So, I find that for myTable, I want to reload an active record after saving it. -- Malcolm Cook
        function Reload()
@@ -554,21 +562,21 @@ class ADODB_Active_Record {
                return($this->Load($where));
        }
 
-
+       
        // set a numeric array (using natural table field ordering) as object properties
        function Set(&$row)
        {
        global $ACTIVE_RECORD_SAFETY;
-
+       
                $db = $this->DB();
-
+               
                if (!$row) {
-                       $this->_saved = false;
+                       $this->_saved = false;          
                        return false;
                }
-
+               
                $this->_saved = true;
-
+               
                $table = $this->TableInfo();
                if ($ACTIVE_RECORD_SAFETY && sizeof($table->flds) != sizeof($row)) {
             # <AP>
@@ -587,7 +595,7 @@ class ADODB_Active_Record {
                }
         else
                        $keys = array_keys($row);
-
+                       
         # <AP>
         reset($keys);
         $this->_original = array();
@@ -601,7 +609,7 @@ class ADODB_Active_Record {
         # </AP>
                return true;
        }
-
+       
        // get last inserted id for INSERT
        function LastInsertID(&$db,$fieldname)
        {
@@ -609,30 +617,32 @@ class ADODB_Active_Record {
                        $val = $db->Insert_ID($this->_table,$fieldname);
                else
                        $val = false;
-
+                       
                if (is_null($val) || $val === false) {
                        // this might not work reliably in multi-user environment
                        return $db->GetOne("select max(".$fieldname.") from ".$this->_table);
                }
                return $val;
        }
-
+       
        // quote data in where clause
        function doquote(&$db, $val,$t)
        {
                switch($t) {
-               case 'D':
+               case 'L':
+                       if (strpos($db->databaseType,'postgres') !== false) return $db->qstr($val);
+               case 'D':       
                case 'T':
                        if (empty($val)) return 'null';
-
-               case 'B':
+               
+               case 'B':       
                case 'N':
                case 'C':
                case 'X':
                        if (is_null($val)) return 'null';
-
-                       if (strlen($val)>1 &&
-                               (strncmp($val,"'",1) != 0 || substr($val,strlen($val)-1,1) != "'")) {
+                       
+                       if (strlen($val)>1 && 
+                               (strncmp($val,"'",1) != 0 || substr($val,strlen($val)-1,1) != "'")) { 
                                return $db->qstr($val);
                                break;
                        }
@@ -641,13 +651,13 @@ class ADODB_Active_Record {
                        break;
                }
        }
-
+       
        // generate where clause for an UPDATE/SELECT
        function GenWhere(&$db, &$table)
        {
                $keys = $table->keys;
                $parr = array();
-
+               
                foreach($keys as $k) {
                        $f = $table->flds[$k];
                        if ($f) {
@@ -656,48 +666,48 @@ class ADODB_Active_Record {
                }
                return implode(' and ', $parr);
        }
-
-
+       
+       
        function _QName($n,$db=false)
        {
                if (!ADODB_Active_Record::$_quoteNames) return $n;
                if (!$db) $db = $this->DB(); if (!$db) return false;
                return $db->nameQuote.$n.$db->nameQuote;
        }
-
+       
        //------------------------------------------------------------ Public functions below
-
+       
        function Load($where=null,$bindarr=false)
        {
        global $ADODB_FETCH_MODE;
-
+       
                $db = $this->DB(); if (!$db) return false;
                $this->_where = $where;
-
+               
                $save = $ADODB_FETCH_MODE;
                $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
                if ($db->fetchMode !== false) $savem = $db->SetFetchMode(false);
-
+               
                $qry = "select * from ".$this->_table;
 
                if($where) {
                        $qry .= ' WHERE '.$where;
                }
                $row = $db->GetRow($qry,$bindarr);
-
+               
                if (isset($savem)) $db->SetFetchMode($savem);
                $ADODB_FETCH_MODE = $save;
-
+               
                return $this->Set($row);
        }
-
+       
        # useful for multiple record inserts
        # see http://phplens.com/lens/lensforum/msgs.php?id=17795
        function Reset()
        {
         $this->_where=null;
-        $this->_saved = false;
-        $this->_lasterr = false;
+        $this->_saved = false; 
+        $this->_lasterr = false; 
         $this->_original = false;
         $vars=get_object_vars($this);
         foreach($vars as $k=>$v){
@@ -708,24 +718,24 @@ class ADODB_Active_Record {
         $this->foreignName=strtolower(get_class($this));
         return true;
     }
-
+       
        // false on error
        function Save()
        {
                if ($this->_saved) $ok = $this->Update();
                else $ok = $this->Insert();
-
+               
                return $ok;
        }
-
-
+       
+       
        // false on error
        function Insert()
        {
                $db = $this->DB(); if (!$db) return false;
                $cnt = 0;
                $table = $this->TableInfo();
-
+               
                $valarr = array();
                $names = array();
                $valstr = array();
@@ -739,7 +749,7 @@ class ADODB_Active_Record {
                                $cnt += 1;
                        }
                }
-
+               
                if (empty($names)){
                        foreach($table->flds as $name=>$fld) {
                                $valarr[] = null;
@@ -750,7 +760,7 @@ class ADODB_Active_Record {
                }
                $sql = 'INSERT INTO '.$this->_table."(".implode(',',$names).') VALUES ('.implode(',',$valstr).')';
                $ok = $db->Execute($sql,$valarr);
-
+               
                if ($ok) {
                        $this->_saved = true;
                        $autoinc = false;
@@ -765,23 +775,23 @@ class ADODB_Active_Record {
                                $this->$k = $this->LastInsertID($db,$k);
                        }
                }
-
+               
                $this->_original = $valarr;
                return !empty($ok);
        }
-
+       
        function Delete()
        {
                $db = $this->DB(); if (!$db) return false;
                $table = $this->TableInfo();
-
+               
                $where = $this->GenWhere($db,$table);
                $sql = 'DELETE FROM '.$this->_table.' WHERE '.$where;
                $ok = $db->Execute($sql);
-
+               
                return $ok ? true : false;
        }
-
+       
        // returns an array of active record objects
        function Find($whereOrderBy,$bindarr=false,$pkeysArr=false,$extra=array())
        {
@@ -789,17 +799,17 @@ class ADODB_Active_Record {
                $arr = $db->GetActiveRecordsClass(get_class($this),$this->_table, $whereOrderBy,$bindarr,$pkeysArr,$extra);
                return $arr;
        }
-
+       
        // returns 0 on error, 1 on update, 2 on insert
        function Replace()
        {
        global $ADODB_ASSOC_CASE;
-
+               
                $db = $this->DB(); if (!$db) return false;
                $table = $this->TableInfo();
-
+               
                $pkey = $table->keys;
-
+               
                foreach($table->flds as $name=>$fld) {
                        $val = $this->$name;
                        /*
@@ -815,24 +825,24 @@ class ADODB_Active_Record {
                        if (is_null($val) && !empty($fld->auto_increment)) {
                continue;
             }
-
+                       
                        if (is_array($val)) continue;
-
+                       
                        $t = $db->MetaType($fld->type);
                        $arr[$name] = $this->doquote($db,$val,$t);
                        $valarr[] = $val;
                }
-
+               
                if (!is_array($pkey)) $pkey = array($pkey);
-
-
-               if ($ADODB_ASSOC_CASE == 0)
+               
+               
+               if ($ADODB_ASSOC_CASE == 0) 
                        foreach($pkey as $k => $v)
                                $pkey[$k] = strtolower($v);
-               elseif ($ADODB_ASSOC_CASE == 1)
+               elseif ($ADODB_ASSOC_CASE == 1) 
                        foreach($pkey as $k => $v)
                                $pkey[$k] = strtoupper($v);
-
+                               
                $ok = $db->Replace($this->_table,$arr,$pkey);
                if ($ok) {
                        $this->_saved = true; // 1= update 2=insert
@@ -849,9 +859,9 @@ class ADODB_Active_Record {
                                        $this->$k = $this->LastInsertID($db,$k);
                                }
                        }
-
+                       
                        $this->_original = $valarr;
-               }
+               } 
                return $ok;
        }
 
@@ -860,14 +870,14 @@ class ADODB_Active_Record {
        {
                $db = $this->DB(); if (!$db) return false;
                $table = $this->TableInfo();
-
+               
                $where = $this->GenWhere($db, $table);
-
+               
                if (!$where) {
                        $this->error("Where missing for table $table", "Update");
                        return false;
                }
-               $valarr = array();
+               $valarr = array(); 
                $neworig = array();
                $pairs = array();
                $i = -1;
@@ -876,10 +886,10 @@ class ADODB_Active_Record {
                        $i += 1;
                        $val = $this->$name;
                        $neworig[] = $val;
-
-                       if (isset($table->keys[$name]) || is_array($val))
+                       
+                       if (isset($table->keys[$name]) || is_array($val)) 
                                continue;
-
+                       
                        if (is_null($val)) {
                                if (isset($fld->not_null) && $fld->not_null) {
                                        if (isset($fld->default_value) && strlen($fld->default_value)) continue;
@@ -890,15 +900,15 @@ class ADODB_Active_Record {
                                }
                        }
 
-                       if (isset($this->_original[$i]) && $val == $this->_original[$i]) {
+                       if (isset($this->_original[$i]) && strcmp($val,$this->_original[$i]) == 0) {
                                continue;
                        }
                        $valarr[] = $val;
                        $pairs[] = $this->_QName($name,$db).'='.$db->Param($cnt);
                        $cnt += 1;
                }
-
-
+               
+               
                if (!$cnt) return -1;
                $sql = 'UPDATE '.$this->_table." SET ".implode(",",$pairs)." WHERE ".$where;
                $ok = $db->Execute($sql,$valarr);
@@ -908,14 +918,14 @@ class ADODB_Active_Record {
                }
                return 0;
        }
-
+       
        function GetAttributeNames()
        {
                $table = $this->TableInfo();
                if (!$table) return false;
                return array_keys($table->flds);
        }
-
+       
 };
 
 function adodb_GetActiveRecordsClass(&$db, $class, $table,$whereOrderBy,$bindarr, $primkeyArr,
@@ -923,10 +933,10 @@ function adodb_GetActiveRecordsClass(&$db, $class, $table,$whereOrderBy,$bindarr
 {
 global $_ADODB_ACTIVE_DBS;
 
-
+       
        $save = $db->SetFetchMode(ADODB_FETCH_NUM);
        $qry = "select * from ".$table;
-
+       
        if (!empty($whereOrderBy))
                $qry .= ' WHERE '.$whereOrderBy;
        if(isset($extra['limit']))
@@ -947,13 +957,13 @@ global $_ADODB_ACTIVE_DBS;
                $rows = $db->GetAll($qry,$bindarr);
 
        $db->SetFetchMode($save);
-
+       
        $false = false;
-
-       if ($rows === false) {
+       
+       if ($rows === false) {  
                return $false;
        }
-
+       
 
        if (!class_exists($class)) {
                $db->outp_throw("Unknown class $class in GetActiveRecordsClass()",'GetActiveRecordsClass');
@@ -967,7 +977,7 @@ global $_ADODB_ACTIVE_DBS;
        $arrRef = array();
        $bTos = array(); // Will store belongTo's indices if any
        foreach($rows as $row) {
-
+       
                $obj = new $class($table,$primkeyArr,$db);
                if ($obj->ErrorNo()){
                        $db->_errorMsg = $obj->ErrorMsg();
@@ -975,7 +985,7 @@ global $_ADODB_ACTIVE_DBS;
                }
                $obj->Set($row);
                $arr[] = $obj;
-       } // foreach($rows as $row)
+       } // foreach($rows as $row) 
 
        return $arr;
 }
index 4c5ebcb..974b611 100644 (file)
@@ -1,20 +1,20 @@
 <?php
 /*
 
-@version V5.06 29 Sept 2008   (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
+@version V5.06 29 Sept 2008   (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
   Latest version is available at http://adodb.sourceforge.net
-
-  Released under both BSD license and Lesser GPL library license.
-  Whenever there is any discrepancy between the two licenses,
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
   the BSD license will take precedence.
-
+  
   Active Record implementation. Superset of Zend Framework's.
-
-  This is "Active Record eXtended" to support JOIN, WORK and LAZY mode by Chris Ravenscroft  chris#voilaweb.com
-
+  
+  This is "Active Record eXtended" to support JOIN, WORK and LAZY mode by Chris Ravenscroft  chris#voilaweb.com 
+  
   Version 0.9
-
-  See http://www-128.ibm.com/developerworks/java/library/j-cb03076/?ca=dgr-lnxw01ActiveRecord
+  
+  See http://www-128.ibm.com/developerworks/java/library/j-cb03076/?ca=dgr-lnxw01ActiveRecord 
        for info on Ruby on Rails Active Record implementation
 */
 
@@ -63,29 +63,29 @@ class ADODB_Active_Table {
 function ADODB_SetDatabaseAdapter(&$db)
 {
        global $_ADODB_ACTIVE_DBS;
-
+       
                foreach($_ADODB_ACTIVE_DBS as $k => $d) {
                        if (PHP_VERSION >= 5) {
                                if ($d->db === $db) return $k;
                        } else {
-                               if ($d->db->_connectionID === $db->_connectionID && $db->database == $d->db->database)
+                               if ($d->db->_connectionID === $db->_connectionID && $db->database == $d->db->database) 
                                        return $k;
                        }
                }
-
+               
                $obj = new ADODB_Active_DB();
                $obj->db = $db;
                $obj->tables = array();
-
+               
                $_ADODB_ACTIVE_DBS[] = $obj;
-
+               
                return sizeof($_ADODB_ACTIVE_DBS)-1;
 }
 
 
 class ADODB_Active_Record {
        static $_changeNames = true; // dynamically pluralize table names
-       static $_foreignSuffix = '_id'; //
+       static $_foreignSuffix = '_id'; // 
        var $_dbat; // associative index pointing to ADODB_Active_DB eg. $ADODB_Active_DBS[_dbat]
        var $_table; // tablename, if set in class definition then use it as table name
        var $_sTable; // singularized table name
@@ -106,18 +106,18 @@ class ADODB_Active_Record {
        }
 
        // should be static
-       static function SetDatabaseAdapter(&$db)
+       static function SetDatabaseAdapter(&$db) 
        {
                return ADODB_SetDatabaseAdapter($db);
        }
-
-
+       
+       
        public function __set($name, $value)
        {
                $name = str_replace(' ', '_', $name);
                $this->$name = $value;
        }
-
+       
        // php5 constructor
        // Note: if $table is defined, then we will use it as our table name
        // Otherwise we will use our classname...
@@ -131,12 +131,12 @@ class ADODB_Active_Record {
        function __construct($table = false, $pkeyarr=false, $db=false, $options=array())
        {
        global $ADODB_ASSOC_CASE,$_ADODB_ACTIVE_DBS;
-
+       
                if ($db == false && is_object($pkeyarr)) {
                        $db = $pkeyarr;
                        $pkeyarr = false;
                }
-
+               
                if($table)
                {
                        // table argument exists. It is expected to be
@@ -159,10 +159,10 @@ class ADODB_Active_Record {
                        $this->_dbat = ADODB_Active_Record::SetDatabaseAdapter($db);
                } else
                        $this->_dbat = sizeof($_ADODB_ACTIVE_DBS)-1;
-
-
+               
+               
                if ($this->_dbat < 0) $this->Error("No database connection set; use ADOdb_Active_Record::SetDatabaseAdapter(\$db)",'ADODB_Active_Record::__constructor');
-
+               
                $this->_tableat = $this->_table; # reserved for setting the assoc value to a non-table name, eg. the sql string in future
 
                // CFR: Just added this option because UpdateActiveTable() can refresh its information
@@ -178,13 +178,13 @@ class ADODB_Active_Record {
                        $table->_belongsTo = array();
                }
        }
-
+       
        function __wakeup()
        {
                $class = get_class($this);
                new $class;
        }
-
+       
        // CFR: Constants found in Rails
        static $IrregularP = array(
                'PERSON'    => 'people',
@@ -231,26 +231,26 @@ class ADODB_Active_Record {
                $lastc2 = substr($ut,$len-2);
                switch ($lastc) {
                case 'S':
-                       return $table.'es';
+                       return $table.'es';     
                case 'Y':
                        return substr($table,0,$len-1).'ies';
-               case 'X':
+               case 'X':       
                        return $table.'es';
-               case 'H':
+               case 'H': 
                        if ($lastc2 == 'CH' || $lastc2 == 'SH')
                                return $table.'es';
                default:
                        return $table.'s';
                }
        }
-
+       
        // CFR Lamest singular inflector ever - @todo Make it real!
        // Note: There is an assumption here...and it is that the argument's length >= 4
        function _singularize($table)
        {
-
+       
                if (!ADODB_Active_Record::$_changeNames) return $table;
-
+       
                $ut = strtoupper($table);
                if(isset(self::$WeIsI[$ut]))
                {
@@ -320,7 +320,7 @@ class ADODB_Active_Record {
                $ar->foreignName = $foreignRef;
                $ar->UpdateActiveTable();
                $ar->foreignKey = ($foreignKey) ? $foreignKey : $ar->foreignName . self::$_foreignSuffix;
-
+               
                $table =& $this->TableInfo();
                if(!isset($table->_belongsTo[$foreignRef]))
                {
@@ -332,8 +332,8 @@ class ADODB_Active_Record {
 
        /**
         * __get Access properties - used for lazy loading
-        *
-        * @param mixed $name
+        * 
+        * @param mixed $name 
         * @access protected
         * @return void
         */
@@ -348,12 +348,12 @@ class ADODB_Active_Record {
                if($offset >= 0) $extras['offset'] = $offset;
                if($limit >= 0) $extras['limit'] = $limit;
                $table =& $this->TableInfo();
-
-               if (strlen($whereOrderBy))
+               
+               if (strlen($whereOrderBy)) 
                        if (!preg_match('/^[ \n\r]*AND/i',$whereOrderBy))
                                if (!preg_match('/^[ \n\r]*ORDER[ \n\r]/i',$whereOrderBy))
                                        $whereOrderBy = 'AND '.$whereOrderBy;
-
+                                       
                if(!empty($table->_belongsTo[$name]))
                {
                        $obj = $table->_belongsTo[$name];
@@ -366,7 +366,7 @@ class ADODB_Active_Record {
                                        $belongsToId = $k;
                                else
                                        $belongsToId = 'id';
-
+                               
                                $arrayOfOne =
                                        $obj->Find(
                                                $belongsToId.'='.$this->$columnName.' '.$whereOrderBy, false, false, $extras);
@@ -380,7 +380,7 @@ class ADODB_Active_Record {
                        if(($k = reset($table->keys)))
                                $hasManyId   = $k;
                        else
-                               $hasManyId   = 'id';
+                               $hasManyId   = 'id';                    
 
                        $this->$name =
                                $obj->Find(
@@ -389,7 +389,7 @@ class ADODB_Active_Record {
                }
        }
        //////////////////////////////////
-
+       
        // update metadata
        function UpdateActiveTable($pkeys=false,$forceUpdate=false)
        {
@@ -405,14 +405,14 @@ class ADODB_Active_Record {
 
                        $tobj = $tables[$tableat];
                        foreach($tobj->flds as $name => $fld) {
-                       if ($ADODB_ACTIVE_DEFVALS && isset($fld->default_value))
+                       if ($ADODB_ACTIVE_DEFVALS && isset($fld->default_value)) 
                                $this->$name = $fld->default_value;
                        else
                                $this->$name = null;
                        }
                        return;
                }
-
+               
                $db = $activedb->db;
                $fname = $ADODB_CACHE_DIR . '/adodb_' . $db->databaseType . '_active_'. $table . '.cache';
                if (!$forceUpdate && $ADODB_ACTIVE_CACHESECS && $ADODB_CACHE_DIR && file_exists($fname)) {
@@ -420,11 +420,11 @@ class ADODB_Active_Record {
                        @flock($fp, LOCK_SH);
                        $acttab = unserialize(fread($fp,100000));
                        fclose($fp);
-                       if ($acttab->_created + $ADODB_ACTIVE_CACHESECS - (abs(rand()) % 16) > time()) {
+                       if ($acttab->_created + $ADODB_ACTIVE_CACHESECS - (abs(rand()) % 16) > time()) { 
                                // abs(rand()) randomizes deletion, reducing contention to delete/refresh file
                                // ideally, you should cache at least 32 secs
                                $activedb->tables[$table] = $acttab;
-
+                               
                                //if ($db->debug) ADOConnection::outp("Reading cached active record file: $fname");
                                return;
                        } else if ($db->debug) {
@@ -433,18 +433,18 @@ class ADODB_Active_Record {
                }
                $activetab = new ADODB_Active_Table();
                $activetab->name = $table;
-
+               
                $save = $ADODB_FETCH_MODE;
                $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
                if ($db->fetchMode !== false) $savem = $db->SetFetchMode(false);
-
+               
                $cols = $db->MetaColumns($table);
-
+               
                if (isset($savem)) $db->SetFetchMode($savem);
                $ADODB_FETCH_MODE = $save;
-
+               
                if (!$cols) {
-                       $this->Error("Invalid table name: $table",'UpdateActiveTable');
+                       $this->Error("Invalid table name: $table",'UpdateActiveTable'); 
                        return false;
                }
                $fld = reset($cols);
@@ -454,17 +454,17 @@ class ADODB_Active_Record {
                                foreach($cols as $name => $fld) {
                                        if (!empty($fld->primary_key)) $pkeys[] = $name;
                                }
-                       } else
+                       } else  
                                $pkeys = $this->GetPrimaryKeys($db, $table);
                }
                if (empty($pkeys)) {
                        $this->Error("No primary key found for table $table",'UpdateActiveTable');
                        return false;
                }
-
+               
                $attr = array();
                $keys = array();
-
+               
                switch($ADODB_ASSOC_CASE) {
                case 0:
                        foreach($cols as $name => $fldobj) {
@@ -479,18 +479,18 @@ class ADODB_Active_Record {
                                $keys[strtolower($name)] = strtolower($name);
                        }
                        break;
-
-               case 1:
+                       
+               case 1: 
                        foreach($cols as $name => $fldobj) {
                                $name = strtoupper($name);
-
+               
                 if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
                     $this->$name = $fldobj->default_value;
                 else
                                        $this->$name = null;
                                $attr[$name] = $fldobj;
                        }
-
+                       
                        foreach($pkeys as $k => $name) {
                                $keys[strtoupper($name)] = strtoupper($name);
                        }
@@ -498,7 +498,7 @@ class ADODB_Active_Record {
                default:
                        foreach($cols as $name => $fldobj) {
                                $name = ($fldobj->name);
-
+                
                 if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
                     $this->$name = $fldobj->default_value;
                 else
@@ -510,7 +510,7 @@ class ADODB_Active_Record {
                        }
                        break;
                }
-
+               
                $activetab->keys = $keys;
                $activetab->flds = $attr;
                $activetab->updateColsCount();
@@ -523,58 +523,58 @@ class ADODB_Active_Record {
                }
                if (isset($activedb->tables[$table])) {
                        $oldtab = $activedb->tables[$table];
-
+               
                        if ($oldtab) $activetab->_belongsTo = $oldtab->_belongsTo;
                        if ($oldtab) $activetab->_hasMany = $oldtab->_hasMany;
                }
                $activedb->tables[$table] = $activetab;
        }
-
+       
        function GetPrimaryKeys(&$db, $table)
        {
                return $db->MetaPrimaryKeys($table);
        }
-
-       // error handler for both PHP4+5.
+       
+       // error handler for both PHP4+5. 
        function Error($err,$fn)
        {
        global $_ADODB_ACTIVE_DBS;
-
+       
                $fn = get_class($this).'::'.$fn;
                $this->_lasterr = $fn.': '.$err;
-
+               
                if ($this->_dbat < 0) $db = false;
                else {
                        $activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
                        $db = $activedb->db;
                }
-
-               if (function_exists('adodb_throw')) {
+               
+               if (function_exists('adodb_throw')) {   
                        if (!$db) adodb_throw('ADOdb_Active_Record', $fn, -1, $err, 0, 0, false);
                        else adodb_throw($db->databaseType, $fn, -1, $err, 0, 0, $db);
                } else
                        if (!$db || $db->debug) ADOConnection::outp($this->_lasterr);
-
+               
        }
-
+       
        // return last error message
        function ErrorMsg()
        {
                if (!function_exists('adodb_throw')) {
                        if ($this->_dbat < 0) $db = false;
                        else $db = $this->DB();
-
+               
                        // last error could be database error too
                        if ($db && $db->ErrorMsg()) return $db->ErrorMsg();
                }
                return $this->_lasterr;
        }
-
-       function ErrorNo()
+       
+       function ErrorNo() 
        {
                if ($this->_dbat < 0) return -9999; // no database connection...
                $db = $this->DB();
-
+               
                return (int) $db->ErrorNo();
        }
 
@@ -583,7 +583,7 @@ class ADODB_Active_Record {
        function DB()
        {
        global $_ADODB_ACTIVE_DBS;
-
+       
                if ($this->_dbat < 0) {
                        $false = false;
                        $this->Error("No database connection set: use ADOdb_Active_Record::SetDatabaseAdaptor(\$db)", "DB");
@@ -593,18 +593,18 @@ class ADODB_Active_Record {
                $db = $activedb->db;
                return $db;
        }
-
+       
        // retrieve ADODB_Active_Table
        function &TableInfo()
        {
        global $_ADODB_ACTIVE_DBS;
-
+       
                $activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
                $table = $activedb->tables[$this->_tableat];
                return $table;
        }
-
-
+       
+       
        // I have an ON INSERT trigger on a table that sets other columns in the table.
        // So, I find that for myTable, I want to reload an active record after saving it. -- Malcolm Cook
        function Reload()
@@ -615,21 +615,21 @@ class ADODB_Active_Record {
                return($this->Load($where));
        }
 
-
+       
        // set a numeric array (using natural table field ordering) as object properties
        function Set(&$row)
        {
        global $ACTIVE_RECORD_SAFETY;
-
+       
                $db = $this->DB();
-
+               
                if (!$row) {
-                       $this->_saved = false;
+                       $this->_saved = false;          
                        return false;
                }
-
+               
                $this->_saved = true;
-
+               
                $table = $this->TableInfo();
                $sizeofFlds = sizeof($table->flds);
                $sizeofRow  = sizeof($row);
@@ -687,7 +687,7 @@ class ADODB_Active_Record {
         # </AP>
                return true;
        }
-
+       
        // get last inserted id for INSERT
        function LastInsertID(&$db,$fieldname)
        {
@@ -695,14 +695,14 @@ class ADODB_Active_Record {
                        $val = $db->Insert_ID($this->_table,$fieldname);
                else
                        $val = false;
-
+                       
                if (is_null($val) || $val === false) {
                        // this might not work reliably in multi-user environment
                        return $db->GetOne("select max(".$fieldname.") from ".$this->_table);
                }
                return $val;
        }
-
+       
        // quote data in where clause
        function doquote(&$db, $val,$t)
        {
@@ -710,13 +710,13 @@ class ADODB_Active_Record {
                case 'D':
                case 'T':
                        if (empty($val)) return 'null';
-
+                       
                case 'C':
                case 'X':
                        if (is_null($val)) return 'null';
-
-                       if (strlen($val)>1 &&
-                               (strncmp($val,"'",1) != 0 || substr($val,strlen($val)-1,1) != "'")) {
+                       
+                       if (strlen($val)>1 && 
+                               (strncmp($val,"'",1) != 0 || substr($val,strlen($val)-1,1) != "'")) { 
                                return $db->qstr($val);
                                break;
                        }
@@ -725,13 +725,13 @@ class ADODB_Active_Record {
                        break;
                }
        }
-
+       
        // generate where clause for an UPDATE/SELECT
        function GenWhere(&$db, &$table)
        {
                $keys = $table->keys;
                $parr = array();
-
+               
                foreach($keys as $k) {
                        $f = $table->flds[$k];
                        if ($f) {
@@ -740,15 +740,15 @@ class ADODB_Active_Record {
                }
                return implode(' and ', $parr);
        }
-
-
+       
+       
        //------------------------------------------------------------ Public functions below
-
+       
        function Load($where=null,$bindarr=false)
        {
                $db = $this->DB(); if (!$db) return false;
                $this->_where = $where;
-
+               
                $save = $db->SetFetchMode(ADODB_FETCH_NUM);
                $qry = "select * from ".$this->_table;
                $table =& $this->TableInfo();
@@ -757,7 +757,7 @@ class ADODB_Active_Record {
                        $hasManyId   = $k;
                else
                        $hasManyId   = 'id';
-
+               
                foreach($table->_belongsTo as $foreignTable)
                {
                        if(($k = reset($foreignTable->TableInfo()->keys)))
@@ -780,7 +780,7 @@ class ADODB_Active_Record {
                }
                if($where)
                        $qry .= ' WHERE '.$where;
-
+               
                // Simple case: no relations. Load row and return.
                if((count($table->_hasMany) + count($table->_belongsTo)) < 1)
                {
@@ -790,7 +790,7 @@ class ADODB_Active_Record {
                        $db->SetFetchMode($save);
                        return $this->Set($row);
                }
-
+               
                // More complex case when relations have to be collated
                $rows = $db->GetAll($qry,$bindarr);
                if(!$rows)
@@ -800,7 +800,7 @@ class ADODB_Active_Record {
                        return false;
                $class = get_class($this);
                $isFirstRow = true;
-
+               
                if(($k = reset($this->TableInfo()->keys)))
                        $myId   = $k;
                else
@@ -819,7 +819,7 @@ class ADODB_Active_Record {
                }
                if(!$found)
                        $this->outp_throw("Unable to locate key $myId for $class in Load()",'Load');
-
+               
                foreach($rows as $row)
                {
                        $rowId = intval($row[$index]);
@@ -873,21 +873,21 @@ class ADODB_Active_Record {
                                                        }
                                                }
                                        }
-                               }
+                               }                               
                        }
                }
                return true;
        }
-
+       
        // false on error
        function Save()
        {
                if ($this->_saved) $ok = $this->Update();
                else $ok = $this->Insert();
-
+               
                return $ok;
        }
-
+       
        // CFR: Sometimes we may wish to consider that an object is not to be replaced but inserted.
        // Sample use case: an 'undo' command object (after a delete())
        function Dirty()
@@ -901,7 +901,7 @@ class ADODB_Active_Record {
                $db = $this->DB(); if (!$db) return false;
                $cnt = 0;
                $table = $this->TableInfo();
-
+               
                $valarr = array();
                $names = array();
                $valstr = array();
@@ -915,7 +915,7 @@ class ADODB_Active_Record {
                                $cnt += 1;
                        }
                }
-
+               
                if (empty($names)){
                        foreach($table->flds as $name=>$fld) {
                                $valarr[] = null;
@@ -926,7 +926,7 @@ class ADODB_Active_Record {
                }
                $sql = 'INSERT INTO '.$this->_table."(".implode(',',$names).') VALUES ('.implode(',',$valstr).')';
                $ok = $db->Execute($sql,$valarr);
-
+               
                if ($ok) {
                        $this->_saved = true;
                        $autoinc = false;
@@ -941,23 +941,23 @@ class ADODB_Active_Record {
                                $this->$k = $this->LastInsertID($db,$k);
                        }
                }
-
+               
                $this->_original = $valarr;
                return !empty($ok);
        }
-
+       
        function Delete()
        {
                $db = $this->DB(); if (!$db) return false;
                $table = $this->TableInfo();
-
+               
                $where = $this->GenWhere($db,$table);
                $sql = 'DELETE FROM '.$this->_table.' WHERE '.$where;
                $ok = $db->Execute($sql);
-
+               
                return $ok ? true : false;
        }
-
+       
        // returns an array of active record objects
        function Find($whereOrderBy,$bindarr=false,$pkeysArr=false,$extra=array())
        {
@@ -967,7 +967,7 @@ class ADODB_Active_Record {
                        array('foreignName'=>$this->foreignName, 'belongsTo'=>$table->_belongsTo, 'hasMany'=>$table->_hasMany));
                return $arr;
        }
-
+       
        // CFR: In introduced this method to ensure that inner workings are not disturbed by
        // subclasses...for instance when GetActiveRecordsClass invokes Find()
        // Why am I not invoking parent::Find?
@@ -985,12 +985,12 @@ class ADODB_Active_Record {
        function Replace()
        {
        global $ADODB_ASSOC_CASE;
-
+               
                $db = $this->DB(); if (!$db) return false;
                $table = $this->TableInfo();
-
+               
                $pkey = $table->keys;
-
+               
                foreach($table->flds as $name=>$fld) {
                        $val = $this->$name;
                        /*
@@ -1010,17 +1010,17 @@ class ADODB_Active_Record {
                        $arr[$name] = $this->doquote($db,$val,$t);
                        $valarr[] = $val;
                }
-
+               
                if (!is_array($pkey)) $pkey = array($pkey);
-
-
-               if ($ADODB_ASSOC_CASE == 0)
+               
+               
+               if ($ADODB_ASSOC_CASE == 0) 
                        foreach($pkey as $k => $v)
                                $pkey[$k] = strtolower($v);
-               elseif ($ADODB_ASSOC_CASE == 1)
+               elseif ($ADODB_ASSOC_CASE == 1) 
                        foreach($pkey as $k => $v)
                                $pkey[$k] = strtoupper($v);
-
+                               
                $ok = $db->Replace($this->_table,$arr,$pkey);
                if ($ok) {
                        $this->_saved = true; // 1= update 2=insert
@@ -1037,9 +1037,9 @@ class ADODB_Active_Record {
                                        $this->$k = $this->LastInsertID($db,$k);
                                }
                        }
-
+                       
                        $this->_original = $valarr;
-               }
+               } 
                return $ok;
        }
 
@@ -1048,14 +1048,14 @@ class ADODB_Active_Record {
        {
                $db = $this->DB(); if (!$db) return false;
                $table = $this->TableInfo();
-
+               
                $where = $this->GenWhere($db, $table);
-
+               
                if (!$where) {
                        $this->error("Where missing for table $table", "Update");
                        return false;
                }
-               $valarr = array();
+               $valarr = array(); 
                $neworig = array();
                $pairs = array();
                $i = -1;
@@ -1064,11 +1064,11 @@ class ADODB_Active_Record {
                        $i += 1;
                        $val = $this->$name;
                        $neworig[] = $val;
-
+                       
                        if (isset($table->keys[$name])) {
                                continue;
                        }
-
+                       
                        if (is_null($val)) {
                                if (isset($fld->not_null) && $fld->not_null) {
                                        if (isset($fld->default_value) && strlen($fld->default_value)) continue;
@@ -1078,16 +1078,16 @@ class ADODB_Active_Record {
                                        }
                                }
                        }
-
+                       
                        if (isset($this->_original[$i]) && $val == $this->_original[$i]) {
                                continue;
-                       }
+                       }                       
                        $valarr[] = $val;
                        $pairs[] = $name.'='.$db->Param($cnt);
                        $cnt += 1;
                }
-
-
+               
+               
                if (!$cnt) return -1;
                $sql = 'UPDATE '.$this->_table." SET ".implode(",",$pairs)." WHERE ".$where;
                $ok = $db->Execute($sql,$valarr);
@@ -1097,23 +1097,23 @@ class ADODB_Active_Record {
                }
                return 0;
        }
-
+       
        function GetAttributeNames()
        {
                $table = $this->TableInfo();
                if (!$table) return false;
                return array_keys($table->flds);
        }
-
+       
 };
 
 function adodb_GetActiveRecordsClass(&$db, $class, $tableObj,$whereOrderBy,$bindarr, $primkeyArr,
                        $extra, $relations)
 {
        global $_ADODB_ACTIVE_DBS;
-
+       
                if (empty($extra['loading'])) $extra['loading'] = ADODB_LAZY_AR;
-
+               
                $save = $db->SetFetchMode(ADODB_FETCH_NUM);
                $table = &$tableObj->_table;
                $tableInfo =& $tableObj->TableInfo();
@@ -1135,7 +1135,7 @@ function adodb_GetActiveRecordsClass(&$db, $class, $tableObj,$whereOrderBy,$bind
                }
                if(!$found)
                        $db->outp_throw("Unable to locate key $myId for $class in GetActiveRecordsClass()",'GetActiveRecordsClass');
-
+               
                $qry = "select * from ".$table;
                if(ADODB_JOIN_AR == $extra['loading'])
                {
@@ -1192,19 +1192,19 @@ function adodb_GetActiveRecordsClass(&$db, $class, $tableObj,$whereOrderBy,$bind
                        }
                } else
                        $rows = $db->GetAll($qry,$bindarr);
-
+                       
                $db->SetFetchMode($save);
-
+               
                $false = false;
-
-               if ($rows === false) {
+               
+               if ($rows === false) {  
                        return $false;
                }
-
-
+               
+               
                if (!isset($_ADODB_ACTIVE_DBS)) {
                        include(ADODB_DIR.'/adodb-active-record.inc.php');
-               }
+               }       
                if (!class_exists($class)) {
                        $db->outp_throw("Unknown class $class in GetActiveRecordsClass()",'GetActiveRecordsClass');
                        return $false;
@@ -1218,7 +1218,7 @@ function adodb_GetActiveRecordsClass(&$db, $class, $tableObj,$whereOrderBy,$bind
                $arrRef = array();
                $bTos = array(); // Will store belongTo's indices if any
                foreach($rows as $row) {
-
+               
                        $obj = new $class($table,$primkeyArr,$db);
                        if ($obj->ErrorNo()){
                                $db->_errorMsg = $obj->ErrorMsg();
@@ -1268,7 +1268,7 @@ function adodb_GetActiveRecordsClass(&$db, $class, $tableObj,$whereOrderBy,$bind
                        {
                                if(ADODB_JOIN_AR == $extra['loading'])
                                {
-                                       $isNewObj = !isset($uniqArr['_'.$row[0]]);
+                                       $isNewObj = !isset($uniqArr['_'.$row[0]]); 
                                        if($isNewObj)
                                                $uniqArr['_'.$row[0]] = $obj;
 
@@ -1322,7 +1322,7 @@ function adodb_GetActiveRecordsClass(&$db, $class, $tableObj,$whereOrderBy,$bind
                                                }
                                        }
                                        if(!$isNewObj)
-                                               unset($obj); // We do not need this object itself anymore and do not want it re-added to the main array
+                                               unset($obj); // We do not need this object itself anymore and do not want it re-added to the main array                                 
                                }
                                else if(ADODB_LAZY_AR == $extra['loading'])
                                {
@@ -1382,7 +1382,7 @@ function adodb_GetActiveRecordsClass(&$db, $class, $tableObj,$whereOrderBy,$bind
                                                array_push($arrRef[$obj->$dbClassRef]->$foreignName, $obj);
                                        }
                                }
-
+                               
                        }
                        if(!empty($relations['belongsTo']))
                        {
@@ -1398,7 +1398,7 @@ function adodb_GetActiveRecordsClass(&$db, $class, $tableObj,$whereOrderBy,$bind
                                        else
                                        {
                                                $belongsToId = 'id';
-                                       }
+                                       }                                               
                                        $origObjsArr = $bTos[$foreignTableRef];
                                        $bTosString = implode(',', array_keys($bTos[$foreignTableRef]));
                                        $foreignName = $foreignTable->foreignName;
index 874c478..1c0d081 100644 (file)
@@ -6,19 +6,19 @@ if (!defined('ADODB_DIR')) die();
 global $ADODB_INCLUDED_CSV;
 $ADODB_INCLUDED_CSV = 1;
 
-/*
+/* 
 
-  V5.10 10 Nov 2009   (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
-  Released under both BSD license and Lesser GPL library license.
-  Whenever there is any discrepancy between the two licenses,
-  the BSD license will take precedence. See License.txt.
+  V5.11 5 May 2010   (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
   Set tabs to 4 for best viewing.
-
+  
   Latest version is available at http://adodb.sourceforge.net
-
-  Library for CSV serialization. This is used by the csv/proxy driver and is the
-  CacheExecute() serialization format.
-
+  
+  Library for CSV serialization. This is used by the csv/proxy driver and is the 
+  CacheExecute() serialization format. 
+  
   ==== NOTE ====
   Format documented at http://php.weblogs.com/ADODB_CSV
   ==============
@@ -34,61 +34,61 @@ $ADODB_INCLUDED_CSV = 1;
        function _rs2serialize(&$rs,$conn=false,$sql='')
        {
                $max = ($rs) ? $rs->FieldCount() : 0;
-
+               
                if ($sql) $sql = urlencode($sql);
                // metadata setup
-
+               
                if ($max <= 0 || $rs->dataProvider == 'empty') { // is insert/update/delete
                        if (is_object($conn)) {
                                $sql .= ','.$conn->Affected_Rows();
                                $sql .= ','.$conn->Insert_ID();
                        } else
                                $sql .= ',,';
-
+                       
                        $text = "====-1,0,$sql\n";
                        return $text;
                }
                $tt = ($rs->timeCreated) ? $rs->timeCreated : time();
-
+               
                ## changed format from ====0 to ====1
                $line = "====1,$tt,$sql\n";
-
+               
                if ($rs->databaseType == 'array') {
                        $rows = $rs->_array;
                } else {
                        $rows = array();
-                       while (!$rs->EOF) {
+                       while (!$rs->EOF) {     
                                $rows[] = $rs->fields;
                                $rs->MoveNext();
-                       }
+                       } 
                }
-
+               
                for($i=0; $i < $max; $i++) {
                        $o = $rs->FetchField($i);
                        $flds[] = $o;
                }
-
+       
                $savefetch = isset($rs->adodbFetchMode) ? $rs->adodbFetchMode : $rs->fetchMode;
                $class = $rs->connection->arrayClass;
                $rs2 = new $class();
                $rs2->timeCreated = $rs->timeCreated; # memcache fix
                $rs2->sql = $rs->sql;
-               $rs2->oldProvider = $rs->dataProvider;
+               $rs2->oldProvider = $rs->dataProvider; 
                $rs2->InitArrayFields($rows,$flds);
                $rs2->fetchMode = $savefetch;
                return $line.serialize($rs2);
        }
 
-
+       
 /**
-* Open CSV file and convert it into Data.
+* Open CSV file and convert it into Data. 
 *
 * @param url           file/ftp/http url
 * @param err           returns the error message
 * @param timeout       dispose if recordset has been alive for $timeout secs
 *
 * @return              recordset, or false if error occured. If no
-*                      error occurred in sql INSERT/UPDATE/DELETE,
+*                      error occurred in sql INSERT/UPDATE/DELETE, 
 *                      empty recordset is returned
 */
        function csv2rs($url,&$err,$timeout=0, $rsclass='ADORecordSet_array')
@@ -103,7 +103,7 @@ $ADODB_INCLUDED_CSV = 1;
                @flock($fp, LOCK_SH);
                $arr = array();
                $ttl = 0;
-
+               
                if ($meta = fgetcsv($fp, 32000, ",")) {
                        // check if error message
                        if (strncmp($meta[0],'****',4) === 0) {
@@ -113,10 +113,10 @@ $ADODB_INCLUDED_CSV = 1;
                        }
                        // check for meta data
                        // $meta[0] is -1 means return an empty recordset
-                       // $meta[1] contains a time
-
+                       // $meta[1] contains a time 
+       
                        if (strncmp($meta[0], '====',4) === 0) {
-
+                       
                                if ($meta[0] == "====-1") {
                                        if (sizeof($meta) < 5) {
                                                $err = "Corrupt first line for format -1";
@@ -124,12 +124,12 @@ $ADODB_INCLUDED_CSV = 1;
                                                return $false;
                                        }
                                        fclose($fp);
-
+                                       
                                        if ($timeout > 0) {
                                                $err = " Illegal Timeout $timeout ";
                                                return $false;
                                        }
-
+                                       
                                        $rs = new $rsclass($val=true);
                                        $rs->fields = array();
                                        $rs->timeCreated = $meta[1];
@@ -137,9 +137,9 @@ $ADODB_INCLUDED_CSV = 1;
                                        $rs->_numOfFields = 0;
                                        $rs->sql = urldecode($meta[2]);
                                        $rs->affectedrows = (integer)$meta[3];
-                                       $rs->insertid = $meta[4];
+                                       $rs->insertid = $meta[4];       
                                        return $rs;
-                               }
+                               } 
                        # Under high volume loads, we want only 1 thread/process to _write_file
                        # so that we don't have 50 processes queueing to write the same data.
                        # We use probabilistic timeout, ahead of time.
@@ -149,7 +149,7 @@ $ADODB_INCLUDED_CSV = 1;
                        # -1 sec after timeout give processes 1/4 chance of timing out
                        # +0 sec after timeout, give processes 100% chance of timing out
                                if (sizeof($meta) > 1) {
-                                       if($timeout >0){
+                                       if($timeout >0){ 
                                                $tdiff = (integer)( $meta[1]+$timeout - time());
                                                if ($tdiff <= 2) {
                                                        switch($tdiff) {
@@ -161,7 +161,7 @@ $ADODB_INCLUDED_CSV = 1;
                                                                        return $false;
                                                                }
                                                                break;
-                                                       case 2:
+                                                       case 2: 
                                                                if ((rand() & 15) == 0) {
                                                                        fclose($fp);
                                                                        $err = "Timeout 2";
@@ -175,12 +175,12 @@ $ADODB_INCLUDED_CSV = 1;
                                                                        return $false;
                                                                }
                                                                break;
-                                                       default:
+                                                       default: 
                                                                fclose($fp);
                                                                $err = "Timeout 0";
                                                                return $false;
                                                        } // switch
-
+                                                       
                                                } // if check flush cache
                                        }// (timeout>0)
                                        $ttl = $meta[1];
@@ -190,7 +190,7 @@ $ADODB_INCLUDED_CSV = 1;
                                if ($meta[0] === '====1') {
                                        // slurp in the data
                                        $MAXSIZE = 128000;
-
+                                       
                                        $text = fread($fp,$MAXSIZE);
                                        if (strlen($text)) {
                                                while ($txt = fread($fp,$MAXSIZE)) {
@@ -206,7 +206,7 @@ $ADODB_INCLUDED_CSV = 1;
                                        }
                                        return $rs;
                                }
-
+                               
                                $meta = false;
                                $meta = fgetcsv($fp, 32000, ",");
                                if (!$meta) {
@@ -236,15 +236,15 @@ $ADODB_INCLUDED_CSV = 1;
                        $err = "Recordset had unexpected EOF 2";
                        return $false;
                }
-
+               
                // slurp in the data
                $MAXSIZE = 128000;
-
+               
                $text = '';
                while ($txt = fread($fp,$MAXSIZE)) {
                        $text .= $txt;
                }
-
+                       
                fclose($fp);
                @$arr = unserialize($text);
                //var_dump($arr);
@@ -258,18 +258,18 @@ $ADODB_INCLUDED_CSV = 1;
                $rs->InitArrayFields($arr,$flds);
                return $rs;
        }
-
+       
 
        /**
        * Save a file $filename and its $contents (normally for caching) with file locking
        * Returns true if ok, false if fopen/fwrite error, 0 if rename error (eg. file is locked)
        */
        function adodb_write_file($filename, $contents,$debug=false)
-       {
+       { 
        # http://www.php.net/bugs.php?id=9203 Bug that flock fails on Windows
        # So to simulate locking, we assume that rename is an atomic operation.
-       # First we delete $filename, then we create a $tempfile write to it and
-       # rename to the desired $filename. If the rename works, then we successfully
+       # First we delete $filename, then we create a $tempfile write to it and 
+       # rename to the desired $filename. If the rename works, then we successfully 
        # modified the file exclusively.
        # What a stupid need - having to simulate locking.
        # Risks:
@@ -279,14 +279,14 @@ $ADODB_INCLUDED_CSV = 1;
        # 4. another process creates $filename between unlink() and rename() -- ok, rename() fails and  cache updated
                if (strncmp(PHP_OS,'WIN',3) === 0) {
                        // skip the decimal place
-                       $mtime = substr(str_replace(' ','_',microtime()),2);
+                       $mtime = substr(str_replace(' ','_',microtime()),2); 
                        // getmypid() actually returns 0 on Win98 - never mind!
                        $tmpname = $filename.uniqid($mtime).getmypid();
                        if (!($fd = @fopen($tmpname,'w'))) return false;
                        if (fwrite($fd,$contents)) $ok = true;
                        else $ok = false;
                        fclose($fd);
-
+                       
                        if ($ok) {
                                @chmod($tmpname,0644);
                                // the tricky moment
@@ -312,7 +312,7 @@ $ADODB_INCLUDED_CSV = 1;
                        if ($debug)ADOConnection::outp( " Failed acquiring lock for $filename<br>\n");
                        $ok = false;
                }
-
+       
                return $ok;
        }
 ?>
\ No newline at end of file
index 607f6b8..69060c5 100644 (file)
@@ -1,15 +1,15 @@
 <?php
 
 /**
-  V5.10 10 Nov 2009   (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
-  Released under both BSD license and Lesser GPL library license.
-  Whenever there is any discrepancy between the two licenses,
+  V5.11 5 May 2010   (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
   the BSD license will take precedence.
-
+       
   Set tabs to 4 for best viewing.
-
        DOCUMENTATION:
-
+       
                See adodb/tests/test-datadict.php for docs and examples.
 */
 
@@ -42,13 +42,13 @@ if (!function_exists('ctype_alnum')) {
 /**
        Parse arguments, treat "text" (text) and 'text' as quotation marks.
        To escape, use "" or '' or ))
-
+       
        Will read in "abc def" sans quotes, as: abc def
        Same with 'abc def'.
        However if `abc def`, then will read in as `abc def`
-
+       
        @param endstmtchar    Character that indicates end of statement
-       @param tokenchars     Include the following characters in tokens apart from A-Z and 0-9
+       @param tokenchars     Include the following characters in tokens apart from A-Z and 0-9 
        @returns 2 dimensional array containing parsed tokens.
 */
 function Lens_ParseArgs($args,$endstmtchar=',',$tokenchars='_.-')
@@ -62,7 +62,7 @@ function Lens_ParseArgs($args,$endstmtchar=',',$tokenchars='_.-')
        $max = strlen($args);
        $quoted = false;
        $tokarr = array();
-
+       
        while ($pos < $max) {
                $ch = substr($args,$pos,1);
                switch($ch) {
@@ -77,17 +77,17 @@ function Lens_ParseArgs($args,$endstmtchar=',',$tokenchars='_.-')
                                }
                                break;
                        }
-
+                       
                        $tokarr[] = $ch;
                        break;
-
+               
                case '`':
                        if ($intoken) $tokarr[] = $ch;
                case '(':
-               case ')':
+               case ')':       
                case '"':
                case "'":
-
+                       
                        if ($intoken) {
                                if (empty($endquote)) {
                                        $tokens[$stmtno][] = implode('',$tokarr);
@@ -109,9 +109,9 @@ function Lens_ParseArgs($args,$endstmtchar=',',$tokenchars='_.-')
                                        }
                                } else
                                        $tokarr[] = $ch;
-
+                                       
                        }else {
-
+                       
                                if ($ch == '(') $endquote = ')';
                                else $endquote = $ch;
                                $quoted = true;
@@ -120,27 +120,27 @@ function Lens_ParseArgs($args,$endstmtchar=',',$tokenchars='_.-')
                                if ($ch == '`') $tokarr[] = '`';
                        }
                        break;
-
+                       
                default:
-
+                       
                        if (!$intoken) {
                                if ($ch == $endstmtchar) {
                                        $stmtno += 1;
                                        $tokens[$stmtno] = array();
                                        break;
                                }
-
+                       
                                $intoken = true;
                                $quoted = false;
                                $endquote = false;
                                $tokarr = array();
-
+       
                        }
-
+                       
                        if ($quoted) $tokarr[] = $ch;
                        else if (ctype_alnum($ch) || strpos($tokenchars,$ch) !== false) $tokarr[] = $ch;
                        else {
-                               if ($ch == $endstmtchar) {
+                               if ($ch == $endstmtchar) {                      
                                        $tokens[$stmtno][] = implode('',$tokarr);
                                        $stmtno += 1;
                                        $tokens[$stmtno] = array();
@@ -156,7 +156,7 @@ function Lens_ParseArgs($args,$endstmtchar=',',$tokenchars='_.-')
                $pos += 1;
        }
        if ($intoken) $tokens[$stmtno][] = implode('',$tokarr);
-
+       
        return $tokens;
 }
 
@@ -165,7 +165,7 @@ class ADODB_DataDict {
        var $connection;
        var $debug = false;
        var $dropTable = 'DROP TABLE %s';
-       var $renameTable = 'RENAME TABLE %s TO %s';
+       var $renameTable = 'RENAME TABLE %s TO %s'; 
        var $dropIndex = 'DROP INDEX %s';
        var $addCol = ' ADD';
        var $alterCol = ' ALTER COLUMN';
@@ -180,43 +180,43 @@ class ADODB_DataDict {
        var $invalidResizeTypes4 = array('CLOB','BLOB','TEXT','DATE','TIME'); // for changetablesql
        var $blobSize = 100;    /// any varchar/char field this size or greater is treated as a blob
                                                        /// in other words, we use a text area for editting.
-
+       
        function GetCommentSQL($table,$col)
        {
                return false;
        }
-
+       
        function SetCommentSQL($table,$col,$cmt)
        {
                return false;
        }
-
+       
        function MetaTables()
        {
                if (!$this->connection->IsConnected()) return array();
                return $this->connection->MetaTables();
        }
-
+       
        function MetaColumns($tab, $upper=true, $schema=false)
        {
                if (!$this->connection->IsConnected()) return array();
                return $this->connection->MetaColumns($this->TableName($tab), $upper, $schema);
        }
-
+       
        function MetaPrimaryKeys($tab,$owner=false,$intkey=false)
        {
                if (!$this->connection->IsConnected()) return array();
                return $this->connection->MetaPrimaryKeys($this->TableName($tab), $owner, $intkey);
        }
-
+       
        function MetaIndexes($table, $primary = false, $owner = false)
        {
                if (!$this->connection->IsConnected()) return array();
                return $this->connection->MetaIndexes($this->TableName($table), $primary, $owner);
        }
-
+       
        function MetaType($t,$len=-1,$fieldobj=false)
-       {
+       {               
                static $typeMap = array(
                'VARCHAR' => 'C',
                'VARCHAR2' => 'C',
@@ -263,7 +263,7 @@ class ADODB_DataDict {
                'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql
                ##
                'BOOL' => 'L',
-               'BOOLEAN' => 'L',
+               'BOOLEAN' => 'L', 
                'BIT' => 'L',
                'L' => 'L',
                ##
@@ -296,21 +296,21 @@ class ADODB_DataDict {
                'NUM' => 'N',
                'NUMERIC' => 'N',
                'MONEY' => 'N',
-
+               
                ## informix 9.2
-               'SQLINT' => 'I',
-               'SQLSERIAL' => 'I',
-               'SQLSMINT' => 'I',
-               'SQLSMFLOAT' => 'N',
-               'SQLFLOAT' => 'N',
-               'SQLMONEY' => 'N',
-               'SQLDECIMAL' => 'N',
-               'SQLDATE' => 'D',
-               'SQLVCHAR' => 'C',
-               'SQLCHAR' => 'C',
-               'SQLDTIME' => 'T',
-               'SQLINTERVAL' => 'N',
-               'SQLBYTES' => 'B',
+               'SQLINT' => 'I', 
+               'SQLSERIAL' => 'I', 
+               'SQLSMINT' => 'I', 
+               'SQLSMFLOAT' => 'N', 
+               'SQLFLOAT' => 'N', 
+               'SQLMONEY' => 'N', 
+               'SQLDECIMAL' => 'N', 
+               'SQLDATE' => 'D', 
+               'SQLVCHAR' => 'C', 
+               'SQLCHAR' => 'C', 
+               'SQLDTIME' => 'T', 
+               'SQLINTERVAL' => 'N', 
+               'SQLBYTES' => 'B', 
                'SQLTEXT' => 'X',
                 ## informix 10
                "SQLINT8" => 'I8',
@@ -320,7 +320,7 @@ class ADODB_DataDict {
                "SQLLVARCHAR" => 'X',
                "SQLBOOL" => 'L'
                );
-
+               
                if (!$this->connection->IsConnected()) {
                        $t = strtoupper($t);
                        if (isset($typeMap[$t])) return $typeMap[$t];
@@ -328,36 +328,36 @@ class ADODB_DataDict {
                }
                return $this->connection->MetaType($t,$len,$fieldobj);
        }
-
+       
        function NameQuote($name = NULL,$allowBrackets=false)
        {
                if (!is_string($name)) {
                        return FALSE;
                }
-
+               
                $name = trim($name);
-
+               
                if ( !is_object($this->connection) ) {
                        return $name;
                }
-
+               
                $quote = $this->connection->nameQuote;
-
+               
                // if name is of the form `name`, quote it
                if ( preg_match('/^`(.+)`$/', $name, $matches) ) {
                        return $quote . $matches[1] . $quote;
                }
-
+               
                // if name contains special characters, quote it
                $regex = ($allowBrackets) ? $this->nameRegexBrackets : $this->nameRegex;
-
+               
                if ( !preg_match('/^[' . $regex . ']+$/', $name) ) {
                        return $quote . $name . $quote;
                }
-
+               
                return $name;
        }
-
+       
        function TableName($name)
        {
                if ( $this->schema ) {
@@ -365,7 +365,7 @@ class ADODB_DataDict {
                }
                return $this->NameQuote($name);
        }
-
+       
        // Executes the sql array returned by GetTableSQL and GetIndexSQL
        function ExecuteSQLArray($sql, $continueOnError = true)
        {
@@ -373,7 +373,7 @@ class ADODB_DataDict {
                $conn = $this->connection;
                $saved = $conn->debug;
                foreach($sql as $line) {
-
+                       
                        if ($this->debug) $conn->debug = true;
                        $ok = $conn->Execute($line);
                        $conn->debug = $saved;
@@ -385,43 +385,43 @@ class ADODB_DataDict {
                }
                return $rez;
        }
-
+       
        /**
                Returns the actual type given a character code.
-
+               
                C:  varchar
                X:  CLOB (character large object) or largest varchar size if CLOB is not supported
                C2: Multibyte varchar
                X2: Multibyte CLOB
-
+               
                B:  BLOB (binary large object)
-
+               
                D:  Date
-               T:  Date-time
+               T:  Date-time 
                L:  Integer field suitable for storing booleans (0 or 1)
                I:  Integer
                F:  Floating point number
                N:  Numeric or decimal number
        */
-
+       
        function ActualType($meta)
        {
                return $meta;
        }
-
+       
        function CreateDatabase($dbname,$options=false)
        {
                $options = $this->_Options($options);
                $sql = array();
-
+               
                $s = 'CREATE DATABASE ' . $this->NameQuote($dbname);
                if (isset($options[$this->upperName]))
                        $s .= ' '.$options[$this->upperName];
-
+               
                $sql[] = $s;
                return $sql;
        }
-
+       
        /*
         Generates the SQL to create index. Returns an array of sql strings.
        */
@@ -430,25 +430,25 @@ class ADODB_DataDict {
                if (!is_array($flds)) {
                        $flds = explode(',',$flds);
                }
-
+               
                foreach($flds as $key => $fld) {
                        # some indexes can use partial fields, eg. index first 32 chars of "name" with NAME(32)
                        $flds[$key] = $this->NameQuote($fld,$allowBrackets=true);
                }
-
+               
                return $this->_IndexSQL($this->NameQuote($idxname), $this->TableName($tabname), $flds, $this->_Options($idxoptions));
        }
-
+       
        function DropIndexSQL ($idxname, $tabname = NULL)
        {
                return array(sprintf($this->dropIndex, $this->NameQuote($idxname), $this->TableName($tabname)));
        }
-
+       
        function SetSchema($schema)
        {
                $this->schema = $schema;
        }
-
+       
        function AddColumnSQL($tabname, $flds)
        {
                $tabname = $this->TableName ($tabname);
@@ -468,7 +468,7 @@ class ADODB_DataDict {
                }
                return $sql;
        }
-
+       
        /**
         * Change the definition of one column
         *
@@ -500,7 +500,7 @@ class ADODB_DataDict {
                }
                return $sql;
        }
-
+       
        /**
         * Rename one column
         *
@@ -523,7 +523,7 @@ class ADODB_DataDict {
                }
                return array(sprintf($this->renameColumn,$tabname,$this->NameQuote($oldcolumn),$this->NameQuote($newcolumn),$column_def));
        }
-
+               
        /**
         * Drop one column
         *
@@ -546,17 +546,17 @@ class ADODB_DataDict {
                }
                return $sql;
        }
-
+       
        function DropTableSQL($tabname)
        {
                return array (sprintf($this->dropTable, $this->TableName($tabname)));
        }
-
+       
        function RenameTableSQL($tabname,$newname)
        {
                return array (sprintf($this->renameTable, $this->TableName($tabname),$this->TableName($newname)));
-       }
-
+       }       
+       
        /**
         Generate the SQL to create table. Returns an array of sql strings.
        */
@@ -565,11 +565,11 @@ class ADODB_DataDict {
                list($lines,$pkey,$idxs) = $this->_GenFields($flds, true);
                // genfields can return FALSE at times
                if ($lines == null) $lines = array();
-
+               
                $taboptions = $this->_Options($tableoptions);
                $tabname = $this->TableName ($tabname);
                $sql = $this->_TableSQL($tabname,$lines,$pkey,$taboptions);
-
+               
                // ggiunta - 2006/10/12 - KLUDGE:
         // if we are on autoincrement, and table options includes REPLACE, the
         // autoincrement sequence has already been dropped on table creation sql, so
@@ -579,7 +579,7 @@ class ADODB_DataDict {
                unset($taboptions['REPLACE']);
                $tsql = $this->_Triggers($tabname,$taboptions);
                foreach($tsql as $s) $sql[] = $s;
-
+               
                if (is_array($idxs)) {
                        foreach($idxs as $idx => $idxdef) {
                                $sql_idxs = $this->CreateIndexSql($idx, $tabname,  $idxdef['cols'], $idxdef['opts']);
@@ -589,7 +589,9 @@ class ADODB_DataDict {
 
                return $sql;
        }
-
+               
+       
+       
        function _GenFields($flds,$widespacing=false)
        {
                if (is_string($flds)) {
@@ -606,7 +608,7 @@ class ADODB_DataDict {
                                                $f1['INDEX'] = '';
                                                // fall through intentionally
                                        case 'CONSTRAINT':
-                                       case 'DEFAULT':
+                                       case 'DEFAULT': 
                                                $hasparam = $token;
                                                break;
                                        default:
@@ -631,7 +633,7 @@ class ADODB_DataDict {
                                $hasparam = false;
 
                                $flds[] = $f1;
-
+                               
                        }
                }
                $this->autoIncrement = false;
@@ -640,7 +642,7 @@ class ADODB_DataDict {
                $idxs = array();
                foreach($flds as $fld) {
                        $fld = _array_change_key_case($fld);
-
+                       
                        $fname = false;
                        $fdefault = false;
                        $fautoinc = false;
@@ -656,20 +658,20 @@ class ADODB_DataDict {
                        $funsigned = false;
                        $findex = '';
                        $funiqueindex = false;
-
+                       
                        //-----------------
                        // Parse attributes
                        foreach($fld as $attr => $v) {
                                if ($attr == 2 && is_numeric($v)) $attr = 'SIZE';
                                else if (is_numeric($attr) && $attr > 1 && !is_numeric($v)) $attr = strtoupper($v);
-
+                               
                                switch($attr) {
                                case '0':
                                case 'NAME':    $fname = $v; break;
                                case '1':
                                case 'TYPE':    $ty = $v; $ftype = $this->ActualType(strtoupper($v)); break;
-
-                               case 'SIZE':
+                               
+                               case 'SIZE':    
                                                                $dotat = strpos($v,'.'); if ($dotat === false) $dotat = strpos($v,',');
                                                                if ($dotat === false) $fsize = $v;
                                                                else {
@@ -695,33 +697,33 @@ class ADODB_DataDict {
                                case 'UNIQUE': $funiqueindex = true; break;
                                } //switch
                        } // foreach $fld
-
+                       
                        //--------------------
                        // VALIDATE FIELD INFO
                        if (!strlen($fname)) {
                                if ($this->debug) ADOConnection::outp("Undefined NAME");
                                return false;
                        }
-
+                       
                        $fid = strtoupper(preg_replace('/^`(.+)`$/', '$1', $fname));
                        $fname = $this->NameQuote($fname);
-
+                       
                        if (!strlen($ftype)) {
                                if ($this->debug) ADOConnection::outp("Undefined TYPE for field '$fname'");
                                return false;
                        } else {
                                $ftype = strtoupper($ftype);
                        }
-
+                       
                        $ftype = $this->_GetSize($ftype, $ty, $fsize, $fprec);
-
+                       
                        if ($ty == 'X' || $ty == 'X2' || $ty == 'B') $fnotnull = false; // some blob types do not accept nulls
-
+                       
                        if ($fprimary) $pkey[] = $fname;
-
+                       
                        // some databases do not allow blobs to have defaults
                        if ($ty == 'X') $fdefault = false;
-
+                       
                        // build list of indexes
                        if ($findex != '') {
                                if (array_key_exists($findex, $idxs)) {
@@ -758,7 +760,7 @@ class ADODB_DataDict {
                                        $fdefault = $this->connection->sysDate;
                                }
                        } else if ($fdefault !== false && !$fnoquote) {
-                               if ($ty == 'C' or $ty == 'X' or
+                               if ($ty == 'C' or $ty == 'X' or 
                                        ( substr($fdefault,0,1) != "'" && !is_numeric($fdefault))) {
 
                                        if (($ty == 'D' || $ty == 'T') && strtolower($fdefault) != 'null') {
@@ -773,27 +775,27 @@ class ADODB_DataDict {
                                                }
                                        }
                                        else
-                                       if (strlen($fdefault) != 1 && substr($fdefault,0,1) == ' ' && substr($fdefault,strlen($fdefault)-1) == ' ')
+                                       if (strlen($fdefault) != 1 && substr($fdefault,0,1) == ' ' && substr($fdefault,strlen($fdefault)-1) == ' ') 
                                                $fdefault = trim($fdefault);
                                        else if (strtolower($fdefault) != 'null')
                                                $fdefault = $this->connection->qstr($fdefault);
                                }
                        }
                        $suffix = $this->_CreateSuffix($fname,$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned);
-
+                       
                        // add index creation
                        if ($widespacing) $fname = str_pad($fname,24);
-
+                       
                         // check for field names appearing twice
             if (array_key_exists($fid, $lines)) {
                 ADOConnection::outp("Field '$fname' defined twice");
             }
-
+                       
                        $lines[$fid] = $fname.' '.$ftype.$suffix;
-
+                       
                        if ($fautoinc) $this->autoIncrement = true;
                } // foreach $flds
-
+               
                return array($lines,$pkey,$idxs);
        }
 
@@ -811,56 +813,56 @@ class ADODB_DataDict {
                }
                return $ftype;
        }
-
-
+       
+       
        // return string must begin with space
        function _CreateSuffix($fname,&$ftype,$fnotnull,$fdefault,$fautoinc,$fconstraint,$funsigned)
-       {
+       {       
                $suffix = '';
                if (strlen($fdefault)) $suffix .= " DEFAULT $fdefault";
                if ($fnotnull) $suffix .= ' NOT NULL';
                if ($fconstraint) $suffix .= ' '.$fconstraint;
                return $suffix;
        }
-
+       
        function _IndexSQL($idxname, $tabname, $flds, $idxoptions)
        {
                $sql = array();
-
+               
                if ( isset($idxoptions['REPLACE']) || isset($idxoptions['DROP']) ) {
                        $sql[] = sprintf ($this->dropIndex, $idxname);
                        if ( isset($idxoptions['DROP']) )
                                return $sql;
                }
-
+               
                if ( empty ($flds) ) {
                        return $sql;
                }
-
+               
                $unique = isset($idxoptions['UNIQUE']) ? ' UNIQUE' : '';
-
+       
                $s = 'CREATE' . $unique . ' INDEX ' . $idxname . ' ON ' . $tabname . ' ';
-
+               
                if ( isset($idxoptions[$this->upperName]) )
                        $s .= $idxoptions[$this->upperName];
-
+               
                if ( is_array($flds) )
                        $flds = implode(', ',$flds);
                $s .= '(' . $flds . ')';
                $sql[] = $s;
-
+               
                return $sql;
        }
-
+       
        function _DropAutoIncrement($tabname)
        {
                return false;
        }
-
+       
        function _TableSQL($tabname,$lines,$pkey,$tableoptions)
        {
                $sql = array();
-
+               
                if (isset($tableoptions['REPLACE']) || isset ($tableoptions['DROP'])) {
                        $sql[] = sprintf($this->dropTable,$tabname);
                        if ($this->autoIncrement) {
@@ -877,19 +879,19 @@ class ADODB_DataDict {
                        $s .= ",\n                 PRIMARY KEY (";
                        $s .= implode(", ",$pkey).")";
                }
-               if (isset($tableoptions['CONSTRAINTS']))
+               if (isset($tableoptions['CONSTRAINTS'])) 
                        $s .= "\n".$tableoptions['CONSTRAINTS'];
-
-               if (isset($tableoptions[$this->upperName.'_CONSTRAINTS']))
+               
+               if (isset($tableoptions[$this->upperName.'_CONSTRAINTS'])) 
                        $s .= "\n".$tableoptions[$this->upperName.'_CONSTRAINTS'];
-
+               
                $s .= "\n)";
                if (isset($tableoptions[$this->upperName])) $s .= $tableoptions[$this->upperName];
                $sql[] = $s;
-
+               
                return $sql;
        }
-
+       
        /**
                GENERATE TRIGGERS IF NEEDED
                used when table has auto-incrementing field that is emulated using triggers
@@ -898,7 +900,7 @@ class ADODB_DataDict {
        {
                return array();
        }
-
+       
        /**
                Sanitize options, so that array elements with no keys are promoted to keys
        */
@@ -912,34 +914,49 @@ class ADODB_DataDict {
                }
                return $newopts;
        }
-
+       
+       
+       function _getSizePrec($size)
+       {
+               $fsize = false;
+               $fprec = false;
+               $dotat = strpos($size,'.');
+               if ($dotat === false) $dotat = strpos($size,',');
+               if ($dotat === false) $fsize = $size;
+               else {
+                       $fsize = substr($size,0,$dotat);
+                       $fprec = substr($size,$dotat+1);
+               }
+               return array($fsize, $fprec);
+       }
+       
        /**
        "Florian Buzin [ easywe ]" <florian.buzin#easywe.de>
-
+       
        This function changes/adds new fields to your table. You don't
        have to know if the col is new or not. It will check on its own.
        */
        function ChangeTableSQL($tablename, $flds, $tableoptions = false, $dropOldFlds=false)
        {
        global $ADODB_FETCH_MODE;
-
+       
                $save = $ADODB_FETCH_MODE;
                $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
                if ($this->connection->fetchMode !== false) $savem = $this->connection->SetFetchMode(false);
-
+               
                // check table exists
                $save_handler = $this->connection->raiseErrorFn;
                $this->connection->raiseErrorFn = '';
                $cols = $this->MetaColumns($tablename);
                $this->connection->raiseErrorFn = $save_handler;
-
+               
                if (isset($savem)) $this->connection->SetFetchMode($savem);
                $ADODB_FETCH_MODE = $save;
-
-               if ( empty($cols)) {
+               
+               if ( empty($cols)) { 
                        return $this->CreateTableSQL($tablename, $flds, $tableoptions);
                }
-
+               
                if (is_array($flds)) {
                // Cycle through the update fields, comparing
                // existing fields to fields to update.
@@ -952,24 +969,31 @@ class ADODB_DataDict {
                                        $obj = $cols[$k];
                                        if (isset($obj->not_null) && $obj->not_null)
                                                $v = str_replace('NOT NULL','',$v);
-                                       if (isset($obj->auto_increment) && $obj->auto_increment && empty($v['AUTOINCREMENT']))
+                                       if (isset($obj->auto_increment) && $obj->auto_increment && empty($v['AUTOINCREMENT'])) 
                                            $v = str_replace('AUTOINCREMENT','',$v);
-
+                                       
                                        $c = $cols[$k];
                                        $ml = $c->max_length;
                                        $mt = $this->MetaType($c->type,$ml);
+                                       
+                                       if (isset($c->scale)) $sc = $c->scale;
+                                       else $sc = 99; // always force change if scale not known.
+                                       
+                                       if ($sc == -1) $sc = false;
+                                       list($fsize, $fprec) = $this->_getSizePrec($v['SIZE']);
+
                                        if ($ml == -1) $ml = '';
                                        if ($mt == 'X') $ml = $v['SIZE'];
-                                       if (($mt != $v['TYPE']) ||  $ml != $v['SIZE'] || (isset($v['AUTOINCREMENT']) && $v['AUTOINCREMENT'] != $obj->auto_increment)) {
+                                       if (($mt != $v['TYPE']) || ($ml != $fsize || $sc != $fprec) || (isset($v['AUTOINCREMENT']) && $v['AUTOINCREMENT'] != $obj->auto_increment)) {
                                                $holdflds[$k] = $v;
                                        }
                                } else {
                                        $holdflds[$k] = $v;
-                               }
+                               }               
                        }
                        $flds = $holdflds;
                }
-
+       
 
                // already exists, alter table instead
                list($lines,$pkey,$idxs) = $this->_GenFields($flds);
@@ -980,26 +1004,26 @@ class ADODB_DataDict {
 
                foreach ( $lines as $id => $v ) {
                        if ( isset($cols[$id]) && is_object($cols[$id]) ) {
-
+                       
                                $flds = Lens_ParseArgs($v,',');
-
+                               
                                //  We are trying to change the size of the field, if not allowed, simply ignore the request.
                                // $flds[1] holds the type, $flds[2] holds the size -postnuke addition
                                if ($flds && in_array(strtoupper(substr($flds[0][1],0,4)),$this->invalidResizeTypes4)
                                 && (isset($flds[0][2]) && is_numeric($flds[0][2]))) {
                                        if ($this->debug) ADOConnection::outp(sprintf("<h3>%s cannot be changed to %s currently</h3>", $flds[0][0], $flds[0][1]));
                                        #echo "<h3>$this->alterCol cannot be changed to $flds currently</h3>";
-                                       continue;
+                                       continue;        
                                }
                                $sql[] = $alter . $this->alterCol . ' ' . $v;
                        } else {
                                $sql[] = $alter . $this->addCol . ' ' . $v;
                        }
                }
-
+               
                if ($dropOldFlds) {
                        foreach ( $cols as $id => $v )
-                           if ( !isset($lines[$id]) )
+                           if ( !isset($lines[$id]) ) 
                                        $sql[] = $alter . $this->dropCol . ' ' . $v->name;
                }
                return $sql;
index a749b2a..6ec614d 100644 (file)
@@ -1,12 +1,12 @@
 <?php
-/**
- * @version V5.06 16 Oct 2008  (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
- * Released under both BSD license and Lesser GPL library license.
- * Whenever there is any discrepancy between the two licenses,
- * the BSD license will take precedence.
+/** 
+ * @version V5.06 16 Oct 2008  (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+ * Whenever there is any discrepancy between the two licenses, 
+ * the BSD license will take precedence. 
  *
  * Set tabs to 4 for best viewing.
- *
+ * 
  * The following code is adapted from the PEAR DB error handling code.
  * Portions (c)1997-2002 The PHP Group.
  */
@@ -59,27 +59,27 @@ function adodb_error($provider,$dbType,$errno)
 {
        //var_dump($errno);
        if (is_numeric($errno) && $errno == 0) return 0;
-       switch($provider) {
+       switch($provider) { 
        case 'mysql': $map = adodb_error_mysql(); break;
-
+       
        case 'oracle':
        case 'oci8': $map = adodb_error_oci8(); break;
-
+       
        case 'ibase': $map = adodb_error_ibase(); break;
-
+       
        case 'odbc': $map = adodb_error_odbc(); break;
-
+       
        case 'mssql':
        case 'sybase': $map = adodb_error_mssql(); break;
-
+       
        case 'informix': $map = adodb_error_ifx(); break;
-
+       
        case 'postgres': return adodb_error_pg($errno); break;
-
+       
        case 'sqlite': return $map = adodb_error_sqlite(); break;
        default:
                return DB_ERROR;
-       }
+       }       
        //print_r($map);
        //var_dump($errno);
        if (isset($map[$errno])) return $map[$errno];
@@ -99,7 +99,7 @@ function adodb_error_pg($errormsg)
             '/ttribute [\"\'].*[\"\'] not found|Relation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/i' => DB_ERROR_NOSUCHFIELD,
             '/parser: parse error at or near \"/i'   => DB_ERROR_SYNTAX,
             '/referential integrity violation/i'     => DB_ERROR_CONSTRAINT,
-                       '/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*|duplicate key violates unique constraint/i'
+                       '/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*|duplicate key.*violates unique constraint/i'     
                                 => DB_ERROR_ALREADY_EXISTS
         );
        reset($error_regexps);
@@ -111,7 +111,7 @@ function adodb_error_pg($errormsg)
     // Fall back to DB_ERROR if there was no mapping.
     return DB_ERROR;
 }
-
+       
 function adodb_error_odbc()
 {
 static $MAP = array(
@@ -169,7 +169,7 @@ static $MAP = array(
             -923 => DB_ERROR_CONNECT_FAILED,
             -924 => DB_ERROR_CONNECT_FAILED
         );
-
+               
                return $MAP;
 }
 
@@ -187,7 +187,7 @@ static $MAP = array(
             '-1210'   => DB_ERROR_INVALID_DATE,
             '-1212'   => DB_ERROR_INVALID_DATE
        );
-
+          
           return $MAP;
 }
 
@@ -206,7 +206,7 @@ static $MAP = array(
             2291 => DB_ERROR_CONSTRAINT,
             2449 => DB_ERROR_CONSTRAINT
         );
-
+          
        return $MAP;
 }
 
@@ -216,7 +216,7 @@ static $MAP = array(
                  208 => DB_ERROR_NOSUCHTABLE,
           2601 => DB_ERROR_ALREADY_EXISTS
        );
-
+          
        return $MAP;
 }
 
@@ -225,7 +225,7 @@ function adodb_error_sqlite()
 static $MAP = array(
                  1 => DB_ERROR_SYNTAX
        );
-
+          
        return $MAP;
 }
 
@@ -252,7 +252,7 @@ static $MAP = array(
                    2002 => DB_ERROR_CONNECT_FAILED,
                        2005 => DB_ERROR_CONNECT_FAILED
        );
-
+          
        return $MAP;
 }
 ?>
\ No newline at end of file
index 10079a8..b760089 100644 (file)
@@ -1,6 +1,6 @@
 <?php
 /**
- * @version V5.10 10 Nov 2009   (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
+ * @version V5.11 5 May 2010   (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
  * Released under both BSD license and Lesser GPL library license.
  * Whenever there is any discrepancy between the two licenses,
  * the BSD license will take precedence.
@@ -13,7 +13,7 @@
 
 
 // added Claudio Bustos  clbustos#entelchile.net
-if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR);
+if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR); 
 
 if (!defined('ADODB_ERROR_HANDLER')) define('ADODB_ERROR_HANDLER','ADODB_Error_Handler');
 
@@ -74,6 +74,6 @@ function ADODB_Error_Handler($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnec
 
 
        //print "<p>$s</p>";
-       trigger_error($s,ADODB_ERROR_HANDLER_TYPE);
+       trigger_error($s,ADODB_ERROR_HANDLER_TYPE); 
 }
 ?>
diff --git a/typo3/sysext/adodb/adodb/adodb-errorhandler.inc.php.orig b/typo3/sysext/adodb/adodb/adodb-errorhandler.inc.php.orig
new file mode 100644 (file)
index 0000000..10079a8
--- /dev/null
@@ -0,0 +1,79 @@
+<?php
+/**
+ * @version V5.10 10 Nov 2009   (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license.
+ * Whenever there is any discrepancy between the two licenses,
+ * the BSD license will take precedence.
+ *
+ * Set tabs to 4 for best viewing.
+ *
+ * Latest version is available at http://php.weblogs.com
+ *
+*/
+
+
+// added Claudio Bustos  clbustos#entelchile.net
+if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR);
+
+if (!defined('ADODB_ERROR_HANDLER')) define('ADODB_ERROR_HANDLER','ADODB_Error_Handler');
+
+/**
+* Default Error Handler. This will be called with the following params
+*
+* @param $dbms         the RDBMS you are connecting to
+* @param $fn           the name of the calling function (in uppercase)
+* @param $errno                the native error number from the database
+* @param $errmsg       the native error msg from the database
+* @param $p1           $fn specific parameter - see below
+* @param $p2           $fn specific parameter - see below
+* @param $thisConn     $current connection object - can be false if no connection object created
+*/
+function ADODB_Error_Handler($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
+{
+       if (error_reporting() == 0) return; // obey @ protocol
+       switch($fn) {
+       case 'EXECUTE':
+               $sql = $p1;
+               $inputparams = $p2;
+
+               $s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")\n";
+               break;
+
+       case 'PCONNECT':
+       case 'CONNECT':
+               $host = $p1;
+               $database = $p2;
+
+               $s = "$dbms error: [$errno: $errmsg] in $fn($host, '****', '****', $database)\n";
+               break;
+       default:
+               $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)\n";
+               break;
+       }
+       /*
+       * Log connection error somewhere
+       *       0 message is sent to PHP's system logger, using the Operating System's system
+       *               logging mechanism or a file, depending on what the error_log configuration
+       *               directive is set to.
+       *       1 message is sent by email to the address in the destination parameter.
+       *               This is the only message type where the fourth parameter, extra_headers is used.
+       *               This message type uses the same internal function as mail() does.
+       *       2 message is sent through the PHP debugging connection.
+       *               This option is only available if remote debugging has been enabled.
+       *               In this case, the destination parameter specifies the host name or IP address
+       *               and optionally, port number, of the socket receiving the debug information.
+       *       3 message is appended to the file destination
+       */
+       if (defined('ADODB_ERROR_LOG_TYPE')) {
+               $t = date('Y-m-d H:i:s');
+               if (defined('ADODB_ERROR_LOG_DEST'))
+                       error_log("($t) $s", ADODB_ERROR_LOG_TYPE, ADODB_ERROR_LOG_DEST);
+               else
+                       error_log("($t) $s", ADODB_ERROR_LOG_TYPE);
+       }
+
+
+       //print "<p>$s</p>";
+       trigger_error($s,ADODB_ERROR_HANDLER_TYPE);
+}
+?>
index 0904a4b..6882e0a 100644 (file)
@@ -1,14 +1,14 @@
 <?php
-/**
- * @version V5.06 16 Oct 2008  (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
- * Released under both BSD license and Lesser GPL library license.
-  Whenever there is any discrepancy between the two licenses,
-  the BSD license will take precedence.
+/** 
+ * @version V5.06 16 Oct 2008  (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. 
  *
  * Set tabs to 4 for best viewing.
- *
+ * 
  * Latest version is available at http://php.weblogs.com
- *
+ * 
 */
 include_once('PEAR.php');
 
@@ -34,7 +34,7 @@ global $ADODB_Last_PEAR_Error; $ADODB_Last_PEAR_Error = false;
 *
 * @param $dbms         the RDBMS you are connecting to
 * @param $fn           the name of the calling function (in uppercase)
-* @param $errno                the native error number from the database
+* @param $errno                the native error number from the database 
 * @param $errmsg       the native error msg from the database
 * @param $p1           $fn specific parameter - see below
 * @param $P2           $fn specific parameter - see below
@@ -42,35 +42,35 @@ global $ADODB_Last_PEAR_Error; $ADODB_Last_PEAR_Error = false;
 function ADODB_Error_PEAR($dbms, $fn, $errno, $errmsg, $p1=false, $p2=false)
 {
 global $ADODB_Last_PEAR_Error;
-
+       
        if (error_reporting() == 0) return; // obey @ protocol
        switch($fn) {
        case 'EXECUTE':
                $sql = $p1;
                $inputparams = $p2;
-
+               
                $s = "$dbms error: [$errno: $errmsg] in $fn(\"$sql\")";
                break;
-
+               
        case 'PCONNECT':
        case 'CONNECT':
                $host = $p1;
                $database = $p2;
-
+               
                $s = "$dbms error: [$errno: $errmsg] in $fn('$host', ?, ?, '$database')";
                break;
-
+               
        default:
                $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)";
                break;
        }
-
+       
        $class = ADODB_PEAR_ERROR_CLASS;
        $ADODB_Last_PEAR_Error = new $class($s, $errno,
                $GLOBALS['_PEAR_default_error_mode'],
-               $GLOBALS['_PEAR_default_error_options'],
+               $GLOBALS['_PEAR_default_error_options'], 
                $errmsg);
-
+               
        //print "<p>!$s</p>";
 }
 
@@ -84,5 +84,5 @@ global $ADODB_Last_PEAR_Error;
 
        return $ADODB_Last_PEAR_Error;
 }
-
+               
 ?>
\ No newline at end of file
index 999f060..65f8943 100644 (file)
@@ -1,7 +1,7 @@
 <?php
 
 /**
- * @version V5.10 10 Nov 2009   (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
+ * @version V5.11 5 May 2010   (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
  * Released under both BSD license and Lesser GPL library license.
  * Whenever there is any discrepancy between the two licenses,
  * the BSD license will take precedence.
@@ -14,7 +14,7 @@
  */
 
 
-if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR);
+if (!defined('ADODB_ERROR_HANDLER_TYPE')) define('ADODB_ERROR_HANDLER_TYPE',E_USER_ERROR); 
 define('ADODB_ERROR_HANDLER','adodb_throw');
 
 class ADODB_Exception extends Exception {
@@ -24,7 +24,7 @@ var $sql = '';
 var $params = '';
 var $host = '';
 var $database = '';
-
+       
        function __construct($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection)
        {
                switch($fn) {
@@ -33,7 +33,7 @@ var $database = '';
                        $this->params = $p2;
                        $s = "$dbms error: [$errno: $errmsg] in $fn(\"$p1\")\n";
                        break;
-
+       
                case 'PCONNECT':
                case 'CONNECT':
                        $user = $thisConnection->user;
@@ -43,7 +43,7 @@ var $database = '';
                        $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)\n";
                        break;
                }
-
+       
                $this->dbms = $dbms;
                if ($thisConnection) {
                        $this->host = $thisConnection->host;
@@ -51,7 +51,7 @@ var $database = '';
                }
                $this->fn = $fn;
                $this->msg = $errmsg;
-
+                               
                if (!is_numeric($errno)) $errno = -1;
                parent::__construct($s,$errno);
        }
@@ -71,7 +71,7 @@ var $database = '';
 function adodb_throw($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection)
 {
 global $ADODB_EXCEPTION;
-
+       
        if (error_reporting() == 0) return; // obey @ protocol
        if (is_string($ADODB_EXCEPTION)) $errfn = $ADODB_EXCEPTION;
        else $errfn = 'ADODB_EXCEPTION';
index 7ccef13..e8b5e57 100644 (file)
@@ -1,28 +1,28 @@
 <?php
 
 /*
-  V5.10 10 Nov 2009   (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
-  Released under both BSD license and Lesser GPL library license.
-  Whenever there is any discrepancy between the two licenses,
+  V5.11 5 May 2010   (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
   the BSD license will take precedence.
-
+  
   Set tabs to 4.
-
-  Declares the ADODB Base Class for PHP5 "ADODB_BASE_RS", and supports iteration with
+  
+  Declares the ADODB Base Class for PHP5 "ADODB_BASE_RS", and supports iteration with 
   the ADODB_Iterator class.
-
+  
                $rs = $db->Execute("select * from adoxyz");
                foreach($rs as $k => $v) {
                        echo $k; print_r($v); echo "<br>";
                }
-
-
+               
+               
        Iterator code based on http://cvs.php.net/cvs.php/php-src/ext/spl/examples/cachingiterator.inc?login=2
-
-
+       
+       
        Moved to adodb.inc.php to improve performance.
  */
-
 
 
 
index 8bc362f..6b2e891 100644 (file)
@@ -9,15 +9,15 @@ if (!defined('ADODB_DIR')) die();
 global $ADODB_INCLUDED_LIB;
 $ADODB_INCLUDED_LIB = 1;
 
-/*
- @version V5.06 16 Oct 2008  (c) 2000-2009 John Lim (jlim\@natsoft.com.my). All rights reserved.
-  Released under both BSD license and Lesser GPL library license.
-  Whenever there is any discrepancy between the two licenses,
-  the BSD license will take precedence. See License.txt.
+/* 
+ @version V5.06 16 Oct 2008  (c) 2000-2010 John Lim (jlim\@natsoft.com.my). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
   Set tabs to 4 for best viewing.
-
-  Less commonly used functions are placed here to reduce size of adodb.inc.php.
-*/
+  
+  Less commonly used functions are placed here to reduce size of adodb.inc.php. 
+*/ 
 
 function adodb_strip_order_by($sql)
 {
@@ -39,7 +39,7 @@ function adodb_strip_order_by($sql)
                        }
                        $sql = substr($sql,0,$at).substr($sql,$i);
                } else
-                       $sql = str_replace($arr[0], '', $sql);
+                       $sql = str_replace($arr[0], '', $sql); 
        return $sql;
  }
 
@@ -55,8 +55,8 @@ function adodb_probetypes(&$array,&$types,$probe=8)
        $types = array();
        if ($probe > sizeof($array)) $max = sizeof($array);
        else $max = $probe;
-
-
+       
+       
        for ($j=0;$j < $max; $j++) {
                $row = $array[$j];
                if (!$row) break;
@@ -65,16 +65,16 @@ function adodb_probetypes(&$array,&$types,$probe=8)
                        $i += 1;
 
                        if (isset($types[$i]) && $types[$i]=='C') continue;
-
+                       
                        //print " ($i ".$types[$i]. "$v) ";
                        $v = trim($v);
-
+                       
                        if (!preg_match('/^[+-]{0,1}[0-9\.]+$/',$v)) {
                                $types[$i] = 'C'; // once C, always C
-
+                               
                                continue;
                        }
-                       if ($j == 0) {
+                       if ($j == 0) { 
                        // If empty string, we presume is character
                        // test for integer for 1st row only
                        // after that it is up to testing other rows to prove
@@ -84,19 +84,19 @@ function adodb_probetypes(&$array,&$types,$probe=8)
                                else  $types[$i] = 'I';
                                continue;
                        }
-
+                       
                        if (strpos($v,'.') !== false) $types[$i] = 'N';
-
+                       
                }
        }
-
+       
 }
 
 function  adodb_transpose(&$arr, &$newarr, &$hdr, &$fobjs)
 {
        $oldX = sizeof(reset($arr));
-       $oldY = sizeof($arr);
-
+       $oldY = sizeof($arr);   
+       
        if ($hdr) {
                $startx = 1;
                $hdr = array('Fields');
@@ -112,14 +112,14 @@ function  adodb_transpose(&$arr, &$newarr, &$hdr, &$fobjs)
                        $newarr[] = array($o->name);
                } else
                        $newarr[] = array();
-
+                       
                for ($y = 0; $y < $oldY; $y++) {
                        $newarr[$x-$startx][] = $arr[$y][$x];
                }
        }
 }
 
-// Force key to upper.
+// Force key to upper. 
 // See also http://www.php.net/manual/en/function.array-change-key-case.php
 function _array_change_key_case($an_array)
 {
@@ -139,7 +139,7 @@ function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_
                if (count($fieldArray) == 0) return 0;
                $first = true;
                $uSet = '';
-
+               
                if (!is_array($keyCol)) {
                        $keyCol = array($keyCol);
                }
@@ -152,14 +152,14 @@ function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_
                                $fieldArray[$k] = $v;
                        }
                        if (in_array($k,$keyCol)) continue; // skip UPDATE if is key
-
+                       
                        if ($first) {
-                               $first = false;
+                               $first = false;                 
                                $uSet = "$k=$v";
                        } else
                                $uSet .= ",$k=$v";
                }
-
+               
                $where = false;
                foreach ($keyCol as $v) {
                        if (isset($fieldArray[$v])) {
@@ -167,24 +167,24 @@ function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_
                                else $where = $v.'='.$fieldArray[$v];
                        }
                }
-
+               
                if ($uSet && $where) {
                        $update = "UPDATE $table SET $uSet WHERE $where";
 
                        $rs = $zthis->Execute($update);
-
-
+                       
+                       
                        if ($rs) {
                                if ($zthis->poorAffectedRows) {
                                /*
-                                The Select count(*) wipes out any errors that the update would have returned.
+                                The Select count(*) wipes out any errors that the update would have returned. 
                                http://phplens.com/lens/lensforum/msgs.php?id=5696
                                */
                                        if ($zthis->ErrorNo()<>0) return 0;
-
+                                       
                                # affected_rows == 0 if update field values identical to old values
-                               # for mysql - which is silly.
-
+                               # for mysql - which is silly. 
+                       
                                        $cnt = $zthis->GetOne("select count(*) from $table where $where");
                                        if ($cnt > 0) return 1; // record already exists
                                } else {
@@ -193,22 +193,22 @@ function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_
                        } else
                                return 0;
                }
-
+               
        //      print "<p>Error=".$this->ErrorNo().'<p>';
                $first = true;
                foreach($fieldArray as $k => $v) {
                        if ($has_autoinc && in_array($k,$keyCol)) continue; // skip autoinc col
-
+                       
                        if ($first) {
-                               $first = false;
+                               $first = false;                 
                                $iCols = "$k";
                                $iVals = "$v";
                        } else {
                                $iCols .= ",$k";
                                $iVals .= ",$v";
-                       }
+                       }                               
                }
-               $insert = "INSERT INTO $table ($iCols) VALUES ($iVals)";
+               $insert = "INSERT INTO $table ($iCols) VALUES ($iVals)"; 
                $rs = $zthis->Execute($insert);
                return ($rs) ? 2 : 0;
 }
@@ -225,9 +225,9 @@ function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=f
                if (!strpos($name,'[]')) $name .= '[]';
        } else if ($size) $attr = ' size="'.$size.'"';
        else $attr ='';
-
+       
        $s = '<select name="'.$name.'"'.$attr.' '.$selectAttr.'>';
-       if ($blank1stItem)
+       if ($blank1stItem) 
                if (is_string($blank1stItem))  {
                        $barr = explode(':',$blank1stItem);
                        if (sizeof($barr) == 1) $barr[] = '';
@@ -236,7 +236,7 @@ function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=f
 
        if ($zthis->FieldCount() > 1) $hasvalue=true;
        else $compareFields0 = true;
-
+       
        $value = '';
     $optgroup = null;
     $firstgroup = true;
@@ -256,12 +256,12 @@ function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=f
                                $zval2 = rtrim(next($zthis->fields));
                }
                $selected = ($compareFields0) ? $zval : $zval2;
-
+               
         $group = '';
                if ($fieldsize > 2) {
             $group = rtrim($zthis->fields[2]);
         }
-/*
+/* 
         if ($optgroup != $group) {
             $optgroup = $group;
             if ($firstgroup) {
@@ -273,25 +273,25 @@ function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=f
             }
                }
 */
-               if ($hasvalue)
+               if ($hasvalue) 
                        $value = " value='".htmlspecialchars($zval2)."'";
-
+               
                if (is_array($defstr))  {
-
-                       if (in_array($selected,$defstr))
+                       
+                       if (in_array($selected,$defstr)) 
                                $s .= "\n<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
-                       else
+                       else 
                                $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
                }
                else {
-                       if (strcasecmp($selected,$defstr)==0)
+                       if (strcasecmp($selected,$defstr)==0) 
                                $s .= "\n<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
                        else
                                $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
                }
                $zthis->MoveNext();
        } // while
-
+       
     // closing last optgroup
     if($optgroup != null) {
         $s .= "\n</optgroup>";
@@ -311,9 +311,9 @@ function _adodb_getmenu_gp(&$zthis, $name,$defstr='',$blank1stItem=true,$multipl
                if (!strpos($name,'[]')) $name .= '[]';
        } else if ($size) $attr = ' size="'.$size.'"';
        else $attr ='';
-
+       
        $s = '<select name="'.$name.'"'.$attr.' '.$selectAttr.'>';
-       if ($blank1stItem)
+       if ($blank1stItem) 
                if (is_string($blank1stItem))  {
                        $barr = explode(':',$blank1stItem);
                        if (sizeof($barr) == 1) $barr[] = '';
@@ -322,7 +322,7 @@ function _adodb_getmenu_gp(&$zthis, $name,$defstr='',$blank1stItem=true,$multipl
 
        if ($zthis->FieldCount() > 1) $hasvalue=true;
        else $compareFields0 = true;
-
+       
        $value = '';
     $optgroup = null;
     $firstgroup = true;
@@ -342,12 +342,12 @@ function _adodb_getmenu_gp(&$zthis, $name,$defstr='',$blank1stItem=true,$multipl
                                $zval2 = rtrim(next($zthis->fields));
                }
                $selected = ($compareFields0) ? $zval : $zval2;
-
+               
         $group = '';
                if (isset($zthis->fields[2])) {
             $group = rtrim($zthis->fields[2]);
         }
-
         if ($optgroup != $group) {
             $optgroup = $group;
             if ($firstgroup) {
@@ -358,26 +358,26 @@ function _adodb_getmenu_gp(&$zthis, $name,$defstr='',$blank1stItem=true,$multipl
                 $s .="\n<optgroup label='". htmlspecialchars($group) ."'>";
             }
                }
-
-               if ($hasvalue)
+       
+               if ($hasvalue) 
                        $value = " value='".htmlspecialchars($zval2)."'";
-
+               
                if (is_array($defstr))  {
-
-                       if (in_array($selected,$defstr))
+                       
+                       if (in_array($selected,$defstr)) 
                                $s .= "\n<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
-                       else
+                       else 
                                $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
                }
                else {
-                       if (strcasecmp($selected,$defstr)==0)
+                       if (strcasecmp($selected,$defstr)==0) 
                                $s .= "\n<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
                        else
                                $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
                }
                $zthis->MoveNext();
        } // while
-
+       
     // closing last optgroup
     if($optgroup != null) {
         $s .= "\n</optgroup>";
@@ -389,34 +389,34 @@ function _adodb_getmenu_gp(&$zthis, $name,$defstr='',$blank1stItem=true,$multipl
 /*
        Count the number of records this sql statement will return by using
        query rewriting heuristics...
-
+       
        Does not work with UNIONs, except with postgresql and oracle.
-
+       
        Usage:
-
+       
        $conn->Connect(...);
        $cnt = _adodb_getcount($conn, $sql);
-
+       
 */
-function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0)
+function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0) 
 {
        $qryRecs = 0;
-
-        if (!empty($zthis->_nestedSQL) || preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) ||
-               preg_match('/\s+GROUP\s+BY\s+/is',$sql) ||
+       
+        if (!empty($zthis->_nestedSQL) || preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) || 
+               preg_match('/\s+GROUP\s+BY\s+/is',$sql) || 
                preg_match('/\s+UNION\s+/is',$sql)) {
-
+               
                $rewritesql = adodb_strip_order_by($sql);
-
+               
                // ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias
                // but this is only supported by oracle and postgresql...
                if ($zthis->dataProvider == 'oci8') {
                        // Allow Oracle hints to be used for query optimization, Chris Wrye
                        if (preg_match('#/\\*+.*?\\*\\/#', $sql, $hint)) {
-                               $rewritesql = "SELECT ".$hint[0]." COUNT(*) FROM (".$rewritesql.")";
+                               $rewritesql = "SELECT ".$hint[0]." COUNT(*) FROM (".$rewritesql.")"; 
                        } else
-                               $rewritesql = "SELECT COUNT(*) FROM (".$rewritesql.")";
-
+                               $rewritesql = "SELECT COUNT(*) FROM (".$rewritesql.")"; 
+                       
                } else if (strncmp($zthis->databaseType,'postgres',8) == 0 || strncmp($zthis->databaseType,'mysql',5) == 0)  {
                        $rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _ADODB_ALIAS_";
                } else {
@@ -426,20 +426,20 @@ function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0)
                // now replace SELECT ... FROM with SELECT COUNT(*) FROM
                $rewritesql = preg_replace(
                                        '/^\s*SELECT\s.*\s+FROM\s/Uis','SELECT COUNT(*) FROM ',$sql);
-               // fix by alexander zhukov, alex#unipack.ru, because count(*) and 'order by' fails
+               // fix by alexander zhukov, alex#unipack.ru, because count(*) and 'order by' fails 
                // with mssql, access and postgresql. Also a good speedup optimization - skips sorting!
                // also see http://phplens.com/lens/lensforum/msgs.php?id=12752
                $rewritesql = adodb_strip_order_by($rewritesql);
        }
-
+       
        if (isset($rewritesql) && $rewritesql != $sql) {
                if (preg_match('/\sLIMIT\s+[0-9]+/i',$sql,$limitarr)) $rewritesql .= $limitarr[0];
-
+                
                if ($secs2cache) {
                        // we only use half the time of secs2cache because the count can quickly
                        // become inaccurate if new records are added
                        $qryRecs = $zthis->CacheGetOne($secs2cache/2,$rewritesql,$inputarr);
-
+                       
                } else {
                        $qryRecs = $zthis->GetOne($rewritesql,$inputarr);
                }
@@ -447,20 +447,24 @@ function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0)
        }
        //--------------------------------------------
        // query rewrite failed - so try slower way...
-
-
+       
+       
        // strip off unneeded ORDER BY if no UNION
        if (preg_match('/\s*UNION\s*/is', $sql)) $rewritesql = $sql;
-       else $rewritesql = $rewritesql = adodb_strip_order_by($sql);
-
+       else $rewritesql = $rewritesql = adodb_strip_order_by($sql); 
+       
        if (preg_match('/\sLIMIT\s+[0-9]+/i',$sql,$limitarr)) $rewritesql .= $limitarr[0];
-
-       $rstest = $zthis->Execute($rewritesql,$inputarr);
-       if (!$rstest) $rstest = $zthis->Execute($sql,$inputarr);
-
+               
+       if ($secs2cache) {
+               $rstest = $zthis->CacheExecute($secs2cache,$rewritesql,$inputarr);
+               if (!$rstest) $rstest = $zthis->CacheExecute($secs2cache,$sql,$inputarr);
+       } else {
+               $rstest = $zthis->Execute($rewritesql,$inputarr);
+               if (!$rstest) $rstest = $zthis->Execute($sql,$inputarr);
+       }
        if ($rstest) {
                        $qryRecs = $rstest->RecordCount();
-               if ($qryRecs == -1) {
+               if ($qryRecs == -1) { 
                global $ADODB_EXTENSION;
                // some databases will return -1 on MoveLast() - change to MoveNext()
                        if ($ADODB_EXTENSION) {
@@ -483,53 +487,53 @@ function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0)
 /*
        Code originally from "Cornel G" <conyg@fx.ro>
 
-       This code might not work with SQL that has UNION in it
-
+       This code might not work with SQL that has UNION in it  
+       
        Also if you are using CachePageExecute(), there is a strong possibility that
        data will get out of synch. use CachePageExecute() only with tables that
        rarely change.
 */
-function _adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page,
-                                               $inputarr=false, $secs2cache=0)
+function _adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page, 
+                                               $inputarr=false, $secs2cache=0) 
 {
        $atfirstpage = false;
        $atlastpage = false;
        $lastpageno=1;
 
-       // If an invalid nrows is supplied,
+       // If an invalid nrows is supplied, 
        // we assume a default value of 10 rows per page
        if (!isset($nrows) || $nrows <= 0) $nrows = 10;
 
        $qryRecs = false; //count records for no offset
-
+       
        $qryRecs = _adodb_getcount($zthis,$sql,$inputarr,$secs2cache);
        $lastpageno = (int) ceil($qryRecs / $nrows);
        $zthis->_maxRecordCount = $qryRecs;
+       
 
 
-
-       // ***** Here we check whether $page is the last page or
-       // whether we are trying to retrieve
+       // ***** Here we check whether $page is the last page or 
+       // whether we are trying to retrieve 
        // a page number greater than the last page number.
        if ($page >= $lastpageno) {
                $page = $lastpageno;
                $atlastpage = true;
        }
-
+       
        // If page number <= 1, then we are at the first page
-       if (empty($page) || $page <= 1) {
+       if (empty($page) || $page <= 1) {       
                $page = 1;
                $atfirstpage = true;
        }
-
+       
        // We get the data we want
        $offset = $nrows * ($page-1);
-       if ($secs2cache > 0)
+       if ($secs2cache > 0) 
                $rsreturn = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
-       else
+       else 
                $rsreturn = $zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
 
-
+       
        // Before returning the RecordSet, we set the pagination properties we need
        if ($rsreturn) {
                $rsreturn->_maxRecordCount = $qryRecs;
@@ -543,19 +547,19 @@ function _adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page,
 }
 
 // Iv├ín Oliva version
-function _adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr=false, $secs2cache=0)
+function _adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr=false, $secs2cache=0) 
 {
 
        $atfirstpage = false;
        $atlastpage = false;
-
+       
        if (!isset($page) || $page <= 1) {      // If page number <= 1, then we are at the first page
                $page = 1;
                $atfirstpage = true;
        }
        if ($nrows <= 0) $nrows = 10;   // If an invalid nrows is supplied, we assume a default value of 10 rows per page
-
-       // ***** Here we check whether $page is the last page or whether we are trying to retrieve a page number greater than
+       
+       // ***** Here we check whether $page is the last page or whether we are trying to retrieve a page number greater than 
        // the last page number.
        $pagecounter = $page + 1;
        $pagecounteroffset = ($pagecounter * $nrows) - $nrows;
@@ -577,12 +581,12 @@ function _adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr
                if ($page == 1) $atfirstpage = true;    // We have to do this again in case the last page is the same as the first
                        //... page, that is, the recordset has only 1 page.
        }
-
+       
        // We get the data we want
        $offset = $nrows * ($page-1);
        if ($secs2cache > 0) $rsreturn = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
        else $rsreturn = $zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
-
+       
        // Before returning the RecordSet, we set the pagination properties we need
        if ($rsreturn) {
                $rsreturn->rowsPerPage = $nrows;
@@ -601,13 +605,13 @@ function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq
                        printf(ADODB_BAD_RS,'GetUpdateSQL');
                        return false;
                }
-
+       
                $fieldUpdatedCount = 0;
                $arrFields = _array_change_key_case($arrFields);
 
                $hasnumeric = isset($rs->fields[0]);
                $setFields = '';
-
+               
                // Loop through all of the fields in the recordset
                for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
                        // Get the field from the recordset
@@ -617,19 +621,19 @@ function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq
                        // of the fields passed in then process.
                        $upperfname = strtoupper($field->name);
                        if (adodb_key_exists($upperfname,$arrFields,$force)) {
-
+                               
                                // If the existing field value in the recordset
                                // is different from the value passed in then
                                // go ahead and append the field name and new value to
                                // the update query.
-
+                               
                                if ($hasnumeric) $val = $rs->fields[$i];
                                else if (isset($rs->fields[$upperfname])) $val = $rs->fields[$upperfname];
                                else if (isset($rs->fields[$field->name])) $val =  $rs->fields[$field->name];
                                else if (isset($rs->fields[strtolower($upperfname)])) $val =  $rs->fields[strtolower($upperfname)];
                                else $val = '';
-
-
+                               
+                       
                                if ($forceUpdate || strcmp($val, $arrFields[$upperfname])) {
                                        // Set the counter for the number of fields that will be updated.
                                        $fieldUpdatedCount++;
@@ -637,18 +641,18 @@ function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq
                                        // Based on the datatype of the field
                                        // Format the value properly for the database
                                        $type = $rs->MetaType($field->type);
-
+                                               
 
                                        if ($type == 'null') {
                                                $type = 'C';
                                        }
-
+                                       
                                        if ((strpos($upperfname,' ') !== false) || ($ADODB_QUOTE_FIELDNAMES))
                                                $fnameq = $zthis->nameQuote.$upperfname.$zthis->nameQuote;
                                        else
                                                $fnameq = $upperfname;
-
-
+                                       
+                                       
                 // is_null requires php 4.0.4
                 //********************************************************//
                 if (is_null($arrFields[$upperfname])
@@ -666,7 +670,7 @@ function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq
                             //Set null
                             $setFields .= $field->name . " = null, ";
                         break;
-
+                                                       
                         case 2:
                             //Set empty
                             $arrFields[$upperfname] = "";
@@ -685,7 +689,7 @@ function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq
                 //********************************************************//
                 } else {
                                                //we do this so each driver can customize the sql for
-                                               //DB specific column types.
+                                               //DB specific column types. 
                                                //Oracle needs BLOB types to be handled with a returning clause
                                                //postgres has special needs as well
                                                $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,
@@ -706,7 +710,7 @@ function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq
                        // Get the full where clause excluding the word "WHERE" from
                        // the existing query.
                        preg_match('/\sWHERE\s(.*)/is', $rs->sql, $whereClause);
-
+                       
                        $discard = false;
                        // not a good hack, improvements?
                        if ($whereClause) {
@@ -717,12 +721,12 @@ function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq
                                else preg_match('/\s.*(\) WHERE .*)/is', $whereClause[1], $discard); # see http://sourceforge.net/tracker/index.php?func=detail&aid=1379638&group_id=42718&atid=433976
                        } else
                                $whereClause = array(false,false);
-
+                               
                        if ($discard)
                                $whereClause[1] = substr($whereClause[1], 0, strlen($whereClause[1]) - strlen($discard[1]));
-
+                       
                        $sql = 'UPDATE '.$tableName.' SET '.substr($setFields, 0, -2);
-                       if (strlen($whereClause[1]) > 0)
+                       if (strlen($whereClause[1]) > 0) 
                                $sql .= ' WHERE '.$whereClause[1];
 
                        return $sql;
@@ -749,8 +753,8 @@ function adodb_key_exists($key, &$arr,$force=2)
  * There is a special case of this function for the oci8 driver.
  * The proper way to handle an insert w/ a blob in oracle requires
  * a returning clause with bind variables and a descriptor blob.
- *
- *
+ * 
+ * 
  */
 function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false,$force=2)
 {
@@ -765,19 +769,19 @@ static $cacheCols;
        $recordSet = null;
        $arrFields = _array_change_key_case($arrFields);
        $fieldInsertedCount = 0;
-
+       
        if (is_string($rs)) {
                //ok we have a table name
                //try and get the column info ourself.
-               $tableName = $rs;
-
+               $tableName = $rs;                       
+       
                //we need an object for the recordSet
                //because we have to call MetaType.
                //php can't do a $rsclass::MetaType()
                $rsclass = $zthis->rsPrefix.$zthis->databaseType;
                $recordSet = new $rsclass(-1,$zthis->fetchMode);
                $recordSet->connection = $zthis;
-
+               
                if (is_string($cacheRS) && $cacheRS == $rs) {
                        $columns = $cacheCols;
                } else {
@@ -789,21 +793,21 @@ static $cacheCols;
                if (isset($rs->insertSig) && is_integer($cacheRS) && $cacheRS == $rs->insertSig) {
                        $columns = $cacheCols;
                } else {
-                       for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++)
+                       for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) 
                                $columns[] = $rs->FetchField($i);
                        $cacheRS = $cacheSig;
                        $cacheCols = $columns;
                        $rs->insertSig = $cacheSig++;
                }
                $recordSet = $rs;
-
+       
        } else {
                printf(ADODB_BAD_RS,'GetInsertSQL');
                return false;
        }
 
        // Loop through all of the fields in the recordset
-       foreach( $columns as $field ) {
+       foreach( $columns as $field ) { 
                $upperfname = strtoupper($field->name);
                if (adodb_key_exists($upperfname,$arrFields,$force)) {
                        $bad = false;
@@ -811,9 +815,9 @@ static $cacheCols;
                                $fnameq = $zthis->nameQuote.$upperfname.$zthis->nameQuote;
                        else
                                $fnameq = $upperfname;
-
+                       
                        $type = $recordSet->MetaType($field->type);
-
+                       
             /********************************************************/
             if (is_null($arrFields[$upperfname])
                 || (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0)
@@ -825,11 +829,11 @@ static $cacheCols;
                         case 0: // we must always set null if missing
                                                        $bad = true;
                                                        break;
-
+                                                       
                         case 1:
                             $values  .= "null, ";
                         break;
-
+               
                         case 2:
                             //Set empty
                             $arrFields[$upperfname] = "";
@@ -839,7 +843,7 @@ static $cacheCols;
                                                default:
                         case 3:
                             //Set the value that was given in array, so you can give both null and empty values
-                                                       if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === $zthis->null2null) {
+                                                       if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === $zthis->null2null) { 
                                                                $values  .= "null, ";
                                                        } else {
                                        $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq, $arrFields, $magicq);
@@ -850,18 +854,18 @@ static $cacheCols;
             /*********************************************************/
                        } else {
                                //we do this so each driver can customize the sql for
-                               //DB specific column types.
+                               //DB specific column types. 
                                //Oracle needs BLOB types to be handled with a returning clause
                                //postgres has special needs as well
                                $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq,
                                                                                           $arrFields, $magicq);
                        }
-
+                       
                        if ($bad) continue;
                        // Set the counter for the number of fields that will be inserted.
                        $fieldInsertedCount++;
-
-
+                       
+                       
                        // Get the name of the fields to insert
                        $fields .= $fnameq . ", ";
                }
@@ -870,15 +874,15 @@ static $cacheCols;
 
        // If there were any inserted fields then build the rest of the insert query.
        if ($fieldInsertedCount <= 0)  return false;
-
+       
        // Get the table name from the existing query.
        if (!$tableName) {
                if (!empty($rs->tableName)) $tableName = $rs->tableName;
                else if (preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName))
                        $tableName = $tableName[1];
-               else
+               else 
                        return false;
-       }
+       }               
 
        // Strip off the comma and space on the end of both the fields
        // and their values.
@@ -886,7 +890,7 @@ static $cacheCols;
        $values = substr($values, 0, -2);
 
        // Append the fields and their values to the insert query.
-       return 'INSERT INTO '.$zthis->nameQuote.$tableName.$zthis->nameQuote.' ( '.$fields.' ) VALUES ( '.$values.' )';
+       return 'INSERT INTO '.$tableName.' ( '.$fields.' ) VALUES ( '.$values.' )';
 }
 
 
@@ -895,20 +899,20 @@ static $cacheCols;
  * the update/sql which is generated by GetInsertSQL and GetUpdateSQL.
  * It handles the string construction of 1 column -> sql string based on
  * the column type.  We want to do 'safe' handling of BLOBs
- *
+ * 
  * @param string the type of sql we are trying to create
- *                'I' or 'U'.
- * @param string column data type from the db::MetaType() method
+ *                'I' or 'U'. 
+ * @param string column data type from the db::MetaType() method  
  * @param string the column name
  * @param array the column value
- *
+ * 
  * @return string
- *
+ * 
  */
-function _adodb_column_sql_oci8(&$zthis,$action, $type, $fname, $fnameq, $arrFields, $magicq)
+function _adodb_column_sql_oci8(&$zthis,$action, $type, $fname, $fnameq, $arrFields, $magicq) 
 {
     $sql = '';
-
+    
     // Based on the datatype of the field
     // Format the value properly for the database
     switch($type) {
@@ -916,7 +920,7 @@ function _adodb_column_sql_oci8(&$zthis,$action, $type, $fname, $fnameq, $arrFie
         //in order to handle Blobs correctly, we need
         //to do some magic for Oracle
 
-        //we need to create a new descriptor to handle
+        //we need to create a new descriptor to handle 
         //this properly
         if (!empty($zthis->hasReturningInto)) {
             if ($action == 'I') {
@@ -933,7 +937,7 @@ function _adodb_column_sql_oci8(&$zthis,$action, $type, $fname, $fnameq, $arrFie
                 $sql = 'empty_blob(), ';
             } else {
                 $sql = $fnameq. '=empty_blob(), ';
-            }
+            }            
         } else {
             //this is to maintain compatibility
             //with older adodb versions.
@@ -949,7 +953,7 @@ function _adodb_column_sql_oci8(&$zthis,$action, $type, $fname, $fnameq, $arrFie
         //to avoid conflicts w/ dupes.
        if (!empty($zthis->hasReturningInto)) {
             if ($action == 'I') {
-                $sql = ':xx'.$fname.'xx, ';
+                $sql = ':xx'.$fname.'xx, ';                
             } else {
                 $sql = $fnameq.'=:xx'.$fname.'xx, ';
             }
@@ -961,18 +965,18 @@ function _adodb_column_sql_oci8(&$zthis,$action, $type, $fname, $fnameq, $arrFie
             //this is to maintain compatibility
             //with older adodb versions.
             $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false);
-        }
+        }            
         break;
-
+        
     default:
         $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq,  $arrFields, $magicq,false);
         break;
     }
-
+    
     return $sql;
-}
-
-function _adodb_column_sql(&$zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq, $recurse=true)
+}    
+       
+function _adodb_column_sql(&$zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq, $recurse=true) 
 {
 
        if ($recurse) {
@@ -982,10 +986,10 @@ function _adodb_column_sql(&$zthis, $action, $type, $fname, $fnameq, $arrFields,
                        break;
                case 'oci8':
                        return _adodb_column_sql_oci8($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq);
-
+                       
                }
        }
-
+               
        switch($type) {
                case "C":
                case "X":
@@ -1000,7 +1004,7 @@ function _adodb_column_sql(&$zthis, $action, $type, $fname, $fnameq, $arrFields,
                case "T":
                        $val = $zthis->DBTimeStamp($arrFields[$fname]);
                        break;
-
+                       
                case "N":
                    $val = $arrFields[$fname];
                        if (!is_numeric($val)) $val = str_replace(',', '.', (float)$val);
@@ -1019,10 +1023,10 @@ function _adodb_column_sql(&$zthis, $action, $type, $fname, $fnameq, $arrFields,
        }
 
        if ($action == 'I') return $val . ", ";
-
-
+       
+       
        return $fnameq . "=" . $val  . ", ";
-
+       
 }
 
 
@@ -1045,7 +1049,7 @@ function _adodb_debug_execute(&$zthis, $sql, $inputarr)
        */
        // check if running from browser or command-line
        $inBrowser = isset($_SERVER['HTTP_USER_AGENT']);
-
+       
        $dbt = $zthis->databaseType;
        if (isset($zthis->dsnType)) $dbt .= '-'.$zthis->dsnType;
        if ($inBrowser) {
@@ -1063,31 +1067,31 @@ function _adodb_debug_execute(&$zthis, $sql, $inputarr)
        }
 
        $qID = $zthis->_query($sql,$inputarr);
-
-       /*
+       
+       /* 
                Alexios Fakios notes that ErrorMsg() must be called before ErrorNo() for mssql
                because ErrorNo() calls Execute('SELECT @ERROR'), causing recursion
        */
-       if ($zthis->databaseType == 'mssql') {
+       if ($zthis->databaseType == 'mssql') { 
        // ErrorNo is a slow function call in mssql, and not reliable in PHP 4.0.6
-
+       
                if($emsg = $zthis->ErrorMsg()) {
                        if ($err = $zthis->ErrorNo()) {
-                               if ($zthis->debug === -99)
+                               if ($zthis->debug === -99) 
                                        ADOConnection::outp( "<hr>\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; $ss\n<hr>\n",false);
-
+               
                                ADOConnection::outp($err.': '.$emsg);
                        }
                }
        } else if (!$qID) {
-
-               if ($zthis->debug === -99)
+       
+               if ($zthis->debug === -99) 
                                if ($inBrowser) ADOConnection::outp( "<hr>\n($dbt): ".htmlspecialchars($sqlTxt)." &nbsp; $ss\n<hr>\n",false);
                                else ADOConnection::outp("-----<hr>\n($dbt): ".$sqlTxt."$ss\n-----<hr>\n",false);
-
+                               
                ADOConnection::outp($zthis->ErrorNo() .': '. $zthis->ErrorMsg());
        }
-
+       
        if ($zthis->debug === 99) _adodb_backtrace(true,9999,2);
        return $qID;
 }
@@ -1096,27 +1100,27 @@ function _adodb_debug_execute(&$zthis, $sql, $inputarr)
 function _adodb_backtrace($printOrArr=true,$levels=9999,$skippy=0,$ishtml=null)
 {
        if (!function_exists('debug_backtrace')) return '';
-
+        
        if ($ishtml === null) $html =  (isset($_SERVER['HTTP_USER_AGENT']));
        else $html = $ishtml;
-
+       
        $fmt =  ($html) ? "</font><font color=#808080 size=-1> %% line %4d, file: <a href=\"file:/%s\">%s</a></font>" : "%% line %4d, file: %s";
 
        $MAXSTRLEN = 128;
 
        $s = ($html) ? '<pre align=left>' : '';
-
+       
        if (is_array($printOrArr)) $traceArr = $printOrArr;
        else $traceArr = debug_backtrace();
        array_shift($traceArr);
        array_shift($traceArr);
        $tabs = sizeof($traceArr)-2;
-
+       
        foreach ($traceArr as $arr) {
                if ($skippy) {$skippy -= 1; continue;}
                $levels -= 1;
                if ($levels < 0) break;
-
+               
                $args = array();
                for ($i=0; $i < $tabs; $i++) $s .=  ($html) ? ' &nbsp; ' : "\t";
                $tabs -= 1;
@@ -1136,30 +1140,30 @@ function _adodb_backtrace($printOrArr=true,$levels=9999,$skippy=0,$ishtml=null)
                        }
                }
                $s .= $arr['function'].'('.implode(', ',$args).')';
-
-
+               
+               
                $s .= @sprintf($fmt, $arr['line'],$arr['file'],basename($arr['file']));
-
+                       
                $s .= "\n";
-       }
+       }       
        if ($html) $s .= '</pre>';
        if ($printOrArr) print $s;
-
+       
        return $s;
 }
 /*
-function _adodb_find_from($sql)
+function _adodb_find_from($sql) 
 {
 
        $sql = str_replace(array("\n","\r"), ' ', $sql);
        $charCount = strlen($sql);
-
+       
        $inString = false;
        $quote = '';
        $parentheseCount = 0;
        $prevChars = '';
        $nextChars = '';
-
+       
 
        for($i = 0; $i < $charCount; $i++) {
 
index b7844f0..e666d56 100644 (file)
@@ -9,18 +9,18 @@ $ADODB_INCLUDED_MEMCACHE = 1;
 global $ADODB_INCLUDED_CSV;
 if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
 
-/*
+/* 
 
-  V5.06 16 Oct 2008  (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
-  Released under both BSD license and Lesser GPL library license.
-  Whenever there is any discrepancy between the two licenses,
-  the BSD license will take precedence. See License.txt.
+  V5.06 16 Oct 2008  (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
+  Released under both BSD license and Lesser GPL library license. 
+  Whenever there is any discrepancy between the two licenses, 
+  the BSD license will take precedence. See License.txt. 
   Set tabs to 4 for best viewing.
-
+  
   Latest version is available at http://adodb.sourceforge.net
 
 Usage:
-
+  
 $db = NewADOConnection($driver);
 $db->memCache = true; /// should we use memCache instead of caching in files
 $db->memCacheHost = array($ip1, $ip2, $ip3);
@@ -29,32 +29,32 @@ $db->memCacheCompress = false; /// Use 'true' to store the item compressed (uses
 
 $db->Connect(...);
 $db->CacheExecute($sql);
-
+  
   Note the memcache class is shared by all connections, is created during the first call to Connect/PConnect.
-
+  
   Class instance is stored in $ADODB_CACHE
 */
 
        class ADODB_Cache_MemCache {
                var $createdir = false; // create caching directory structure?
-
+               
                //-----------------------------
                // memcache specific variables
-
+               
                var $hosts;     // array of hosts
                var $port = 11211;
                var $compress = false; // memcache compression with zlib
-
+               
                var $_connected = false;
                var $_memcache = false;
-
+               
                function ADODB_Cache_MemCache(&$obj)
                {
                        $this->hosts = $obj->memCacheHost;
                        $this->port = $obj->memCachePort;
                        $this->compress = $obj->memCacheCompress;
                }
-
+               
                // implement as lazy connection. The connection only occurs on CacheExecute call
                function connect(&$err)
                {
@@ -64,9 +64,9 @@ $db->CacheExecute($sql);
                        }
 
                        $memcache = new MemCache;
-
+                       
                        if (!is_array($this->hosts)) $this->hosts = array($this->hosts);
-
+               
                        $failcnt = 0;
                        foreach($this->hosts as $host) {
                                if (!@$memcache->addServer($host,$this->port,true)) {
@@ -81,7 +81,7 @@ $db->CacheExecute($sql);
                        $this->_memcache = $memcache;
                        return true;
                }
-
+               
                // returns true or false. true if successful save
                function writecache($filename, $contents, $debug, $secs2cache)
                {
@@ -90,43 +90,43 @@ $db->CacheExecute($sql);
                                if (!$this->connect($err) && $debug) ADOConnection::outp($err);
                        }
                        if (!$this->_memcache) return false;
-
+                       
                        if (!$this->_memcache->set($filename, $contents, $this->compress, $secs2cache)) {
                                if ($debug) ADOConnection::outp(" Failed to save data at the memcached server!<br>\n");
                                return false;
                        }
-
+                       
                        return true;
                }
-
+               
                // returns a recordset
                function readcache($filename, &$err, $secs2cache, $rsClass)
                {
                        $false = false;
                        if (!$this->_connected) $this->connect($err);
                        if (!$this->_memcache) return $false;
-
+                       
                        $rs = $this->_memcache->get($filename);
                        if (!$rs) {
                                $err = 'Item with such key doesn\'t exists on the memcached server.';
                                return $false;
                        }
-
+                       
                        // hack, should actually use _csv2rs
                        $rs = explode("\n", $rs);
             unset($rs[0]);
             $rs = join("\n", $rs);
                        $rs = unserialize($rs);
                        if (! is_object($rs)) {
-                               $err = 'Unable to unserialize $rs';
+                               $err = 'Unable to unserialize $rs';             
                                return $false;
                        }
                        if ($rs->timeCreated == 0) return $rs; // apparently have been reports that timeCreated was set to 0 somewhere
-
+                       
                        $tdiff = intval($rs->timeCreated+$secs2cache - time());
                        if ($tdiff <= 2) {
                                switch($tdiff) {
-                                       case 2:
+                                       case 2: 
                                                if ((rand() & 15) == 0) {
                                                        $err = "Timeout 2";
                                                        return $false;
@@ -138,14 +138,14 @@ $db->CacheExecute($sql);
                                                        return $false;
                                                }
                                                break;
-                                       default:
+                                       default: 
                                                $err = "Timeout 0";
                                                return $false;
                                }
                        }
                        return $rs;
                }
-
+               
                function flushall($debug=false)
                {
                        if (!$this->_connected) {
@@ -153,35 +153,35 @@ $db->CacheExecute($sql);
                                if (!$this->connect($err) && $debug) ADOConnection::outp($err);
                        }
                        if (!$this->_memcache) return false;
-
+                       
                        $del = $this->_memcache->flush();
-
-                       if ($debug)
+                       
+                       if ($debug) 
                                if (!$del) ADOConnection::outp("flushall: failed!<br>\n");
                                else ADOConnection::outp("flushall: succeeded!<br>\n");
-
+                               
                        return $del;
                }
-
+               
                function flushcache($filename, $debug=false)
                {
                        if (!$this->_connected) {
                                $err = '';
-                               if (!$this->connect($err) && $debug) ADOConnection::outp($err);
-                       }
+                               if (!$this->connect($err) && $debug) ADOConnection::outp($err); 
+                       } 
                        if (!$this->_memcache) return false;
-
+  
                        $del = $this->_memcache->delete($filename);
-
-                       if ($debug)
+                       
+                       if ($debug) 
                                if (!$del) ADOConnection::outp("flushcache: $key entry doesn't exist on memcached server!<br>\n");
                                else ADOConnection::outp("flushcache: $key entry flushed from memcached server!<br>\n");
-
+                               
                        return $del;
                }
-
+               
                // not used for memcache
-               function createdir($dir, $hash)
+               function createdir($dir, $hash) 
                {
                        return true;
                }
index 51099e7..2d1d787 100644 (file)
@@ -1,7 +1,7 @@
 <?php
 
 /*
-       V5.10 10 Nov 2009   (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
+       V5.11 5 May 2010   (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
          Released under both BSD license and Lesser GPL library license.
          Whenever there is any discrepancy between the two licenses,
          the BSD license will take precedence.
index 7e196e2..04441a7 100644 (file)
@@ -1,12 +1,12 @@
 <?php
-/**
- * @version V5.06 16 Oct 2008  (c) 2000-2009 John Lim (jlim#natsoft.com). All rights reserved.
- * Released under both BSD license and Lesser GPL library license.
- * Whenever there is any discrepancy between the two licenses,
- * the BSD license will take precedence.
+/** 
+ * @version V5.06 16 Oct 2008  (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
+ * Released under both BSD license and Lesser GPL library license. 
+ * Whenever there is any discrepancy between the two licenses, 
+ * the BSD license will take precedence. 
  *
  * Set tabs to 4 for best viewing.
- *
+ * 
  * PEAR DB Emulation Layer for ADODB.
  *
  * The following code is modelled on PEAR DB code by Stig Bakken <ssb@fast.no>                                                            |
@@ -15,7 +15,7 @@
 
  /*
  We support:
-
  DB_Common
  ---------
        query - returns PEAR_Error on error
        quote
        nextID
        disconnect
-
+       
        getOne
        getAssoc
        getRow
        getCol
        getAll
-
+       
  DB_Result
  ---------
        numRows - returns -1 if not supported
@@ -42,7 +42,7 @@
        fetchRows - does not support passing of fetchmode
        free
  */
-
 define('ADODB_PEAR',dirname(__FILE__));
 include_once "PEAR.php";
 include_once ADODB_PEAR."/adodb-errorpear.inc.php";
@@ -183,10 +183,10 @@ class DB
 
                if (isset($dsninfo['socket'])) $dsninfo['hostspec'] .= ':'.$dsninfo['socket'];
                else if (isset($dsninfo['port'])) $dsninfo['hostspec'] .= ':'.$dsninfo['port'];
-
+               
                if($persist) $ok = $obj->PConnect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']);
                else  $ok = $obj->Connect($dsninfo['hostspec'], $dsninfo['username'],$dsninfo['password'],$dsninfo['database']);
-
+               
                if (!$ok) $obj = ADODB_PEAR_Error();
                return $obj;
        }
@@ -212,7 +212,7 @@ class DB
        {
                if (!is_object($value)) return false;
                $class = strtolower(get_class($value));
-               return $class == 'pear_error' || is_subclass_of($value, 'pear_error') ||
+               return $class == 'pear_error' || is_subclass_of($value, 'pear_error') || 
                                $class == 'db_error' || is_subclass_of($value, 'db_error');
        }
 
diff --git a/typo3/sysext/adodb/adodb/adodb-perf.inc.php b/typo3/sysext/adodb/adodb/adodb-perf.inc.php
new file mode 100644 (file)
index 0000000..4b2ea9e
--- /dev/null
@@ -0,0 +1,1099 @@
+<?php
+/*
+V5.11 5 May 2010   (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved.
+  Released under both BSD license and Lesser GPL library license.
+  Whenever there is any discrepancy between the two licenses,
+  the BSD license will take precedence. See License.txt.
+  Set tabs to 4 for best viewing.
+
+  Latest version is available at http://adodb.sourceforge.net
+
+  Library for basic performance monitoring and tuning.
+
+  My apologies if you see code mixed with presentation. The presentation suits
+  my needs. If you want to separate code from presentation, be my guest. Patches
+  are welcome.
+
+*/
+
+if (!defined('ADODB_DIR')) include_once(dirname(__FILE__).'/adodb.inc.php');
+include_once(ADODB_DIR.'/tohtml.inc.php');
+
+define( 'ADODB_OPT_HIGH', 2);
+define( 'ADODB_OPT_LOW', 1);
+
+global $ADODB_PERF_MIN;
+$ADODB_PERF_MIN = 0.05; // log only if >= minimum number of secs to run
+
+
+// returns in K the memory of current process, or 0 if not known
+function adodb_getmem()
+{
+       if (function_exists('memory_get_usage'))
+               return (integer) ((memory_get_usage()+512)/1024);
+
+       $pid = getmypid();
+
+       if ( strncmp(strtoupper(PHP_OS),'WIN',3)==0) {
+               $output = array();
+
+               exec('tasklist /FI "PID eq ' . $pid. '" /FO LIST', $output);
+               return substr($output[5], strpos($output[5], ':') + 1);
+       }
+
+       /* Hopefully UNIX */
+       exec("ps --pid $pid --no-headers -o%mem,size", $output);
+       if (sizeof($output) == 0) return 0;
+
+       $memarr = explode(' ',$output[0]);
+       if (sizeof($memarr)>=2) return (integer) $memarr[1];
+
+       return 0;
+}
+
+// avoids localization problems where , is used instead of .
+function adodb_round($n,$prec)
+{
+       return number_format($n, $prec, '.', '');
+}
+
+/* obsolete: return microtime value as a float. Retained for backward compat */
+function adodb_microtime()
+{
+       return microtime(true);
+}
+
+/* sql code timing */
+function adodb_log_sql(&$connx,$sql,$inputarr)
+{
+    $perf_table = adodb_perf::table();
+       $connx->fnExecute = false;
+       $a0 = microtime(true);
+       $rs = $connx->Execute($sql,$inputarr);
+       $a1 = microtime(true);
+
+       if (!empty($connx->_logsql) && (empty($connx->_logsqlErrors) || !$rs)) {
+       global $ADODB_LOG_CONN;
+
+               if (!empty($ADODB_LOG_CONN)) {
+                       $conn = $ADODB_LOG_CONN;
+                       if ($conn->databaseType != $connx->databaseType)
+                               $prefix = '/*dbx='.$connx->databaseType .'*/ ';
+                       else
+                               $prefix = '';
+               } else {
+                       $conn = $connx;
+                       $prefix = '';
+               }
+
+               $conn->_logsql = false; // disable logsql error simulation
+               $dbT = $conn->databaseType;
+
+               $time = $a1 - $a0;
+
+               if (!$rs) {
+                       $errM = $connx->ErrorMsg();
+                       $errN = $connx->ErrorNo();
+                       $conn->lastInsID = 0;
+                       $tracer = substr('ERROR: '.htmlspecialchars($errM),0,250);
+               } else {
+                       $tracer = '';
+                       $errM = '';
+                       $errN = 0;
+                       $dbg = $conn->debug;
+                       $conn->debug = false;
+                       if (!is_object($rs) || $rs->dataProvider == 'empty')
+                               $conn->_affected = $conn->affected_rows(true);
+                       $conn->lastInsID = @$conn->Insert_ID();
+                       $conn->debug = $dbg;
+               }
+               if (isset($_SERVER['HTTP_HOST'])) {
+                       $tracer .= '<br>'.$_SERVER['HTTP_HOST'];
+                       if (isset($_SERVER['PHP_SELF'])) $tracer .= htmlspecialchars($_SERVER['PHP_SELF']);
+               } else
+                       if (isset($_SERVER['PHP_SELF'])) $tracer .= '<br>'.htmlspecialchars($_SERVER['PHP_SELF']);
+               //$tracer .= (string) adodb_backtrace(false);
+
+               $tracer = (string) substr($tracer,0,500);
+
+               if (is_array($inputarr)) {
+                       if (is_array(reset($inputarr))) $params = 'Array sizeof='.sizeof($inputarr);
+                       else {
+                               // Quote string parameters so we can see them in the
+                               // performance stats. This helps spot disabled indexes.
+                               $xar_params = $inputarr;
+                               foreach ($xar_params as $xar_param_key => $xar_param) {
+                                       if (gettype($xar_param) == 'string')
+                                       $xar_params[$xar_param_key] = '"' . $xar_param . '"';
+                               }
+                               $params = implode(', ', $xar_params);
+                               if (strlen($params) >= 3000) $params = substr($params, 0, 3000);
+                       }
+               } else {
+                       $params = '';
+               }
+
+               if (is_array($sql)) $sql = $sql[0];
+               if ($prefix) $sql = $prefix.$sql;
+               $arr = array('b'=>strlen($sql).'.'.crc32($sql),
+                                       'c'=>substr($sql,0,3900), 'd'=>$params,'e'=>$tracer,'f'=>adodb_round($time,6));
+               //var_dump($arr);
+               $saved = $conn->debug;
+               $conn->debug = 0;
+
+               $d = $conn->sysTimeStamp;
+               if (empty($d)) $d = date("'Y-m-d H:i:s'");
+               if ($conn->dataProvider == 'oci8' && $dbT != 'oci8po') {
+                       $isql = "insert into $perf_table values($d,:b,:c,:d,:e,:f)";
+               } else if ($dbT == 'odbc_mssql' || $dbT == 'informix' || strncmp($dbT,'odbtp',4)==0) {
+                       $timer = $arr['f'];
+                       if ($dbT == 'informix') $sql2 = substr($sql2,0,230);
+
+                       $sql1 = $conn->qstr($arr['b']);
+                       $sql2 = $conn->qstr($arr['c']);
+                       $params = $conn->qstr($arr['d']);
+                       $tracer = $conn->qstr($arr['e']);
+
+                       $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values($d,$sql1,$sql2,$params,$tracer,$timer)";
+                       if ($dbT == 'informix') $isql = str_replace(chr(10),' ',$isql);
+                       $arr = false;
+               } else {
+                       if ($dbT == 'db2') $arr['f'] = (float) $arr['f'];
+                       $isql = "insert into $perf_table (created,sql0,sql1,params,tracer,timer) values( $d,?,?,?,?,?)";
+               }
+
+               global $ADODB_PERF_MIN;
+               if ($errN != 0 || $time >= $ADODB_PERF_MIN) {
+                       $ok = $conn->Execute($isql,$arr);
+               } else
+                       $ok = true;
+
+               $conn->debug = $saved;
+
+               if ($ok) {
+                       $conn->_logsql = true;
+               } else {
+                       $err2 = $conn->ErrorMsg();
+                       $conn->_logsql = true; // enable logsql error simulation
+                       $perf = NewPerfMonitor($conn);
+                       if ($perf) {
+                               if ($perf->CreateLogTable()) $ok = $conn->Execute($isql,$arr);
+                       } else {
+                               $ok = $conn->Execute("create table $perf_table (
+                               created varchar(50),
+                               sql0 varchar(250),
+                               sql1 varchar(4000),
+                               params varchar(3000),
+                               tracer varchar(500),
+                               timer decimal(16,6))");
+                       }
+                       if (!$ok) {
+                               ADOConnection::outp( "<p><strong>LOGSQL Insert Failed</strong>: $isql<br />$err2</p>");
+                               $conn->_logsql = false;
+                       }
+               }
+               $connx->_errorMsg = $errM;
+               $connx->_errorCode = $errN;
+       }
+       $connx->fnExecute = 'adodb_log_sql';
+       return $rs;
+}
+
+
+/*
+The settings data structure is an associative array that database parameter per element.
+
+Each database parameter element in the array is itself an array consisting of:
+
+0: category code, used to group related db parameters
+1: either
+       a. sql string to retrieve value, eg. "select value from v\$parameter where name='db_block_size'",
+       b. array holding sql string and field to look for, e.g. array('show variables','table_cache'),
+       c. a string prefixed by =, then a PHP method of the class is invoked,
+               e.g. to invoke $this->GetIndexValue(), set this array element to '=GetIndexValue',
+2: description of the database parameter
+*/
+
+class adodb_perf {
+       var $conn;
+       var $color = '#F0F0F0';
+       var $table = '<table border="1" bgcolor="white">';
+       var $titles = '<tr><td><strong>Parameter</strong></td><td><strong>Value</strong></td><td><strong>Description</strong></td></tr>';
+       var $warnRatio = 90;
+       var $tablesSQL = false;
+       var $cliFormat = "%32s => %s \r\n";
+       var $sql1 = 'sql1';  // used for casting sql1 to text for mssql
+       var $explain = true;
+       var $helpurl = "<a href=http://phplens.com/adodb/reference.functions.fnexecute.and.fncacheexecute.properties.html#logsql>LogSQL help</a>";
+       var $createTableSQL = false;
+       var $maxLength = 2000;
+
+    // Sets the tablename to be used
+    static function table($newtable = false)
+    {
+        static $_table;
+
+        if (!empty($newtable))  $_table = $newtable;
+               if (empty($_table)) $_table = 'adodb_logsql';
+        return $_table;
+    }
+
+       // returns array with info to calculate CPU Load
+       function _CPULoad()
+       {
+/*
+
+cpu  524152 2662 2515228 336057010
+cpu0 264339 1408 1257951 168025827
+cpu1 259813 1254 1257277 168031181
+page 622307 25475680
+swap 24 1891
+intr 890153570 868093576 6 0 4 4 0 6 1 2 0 0 0 124 0 8098760 2 13961053 0 0 0 0 0 0 0 0 0 0 0 0 0 16 16 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
+disk_io: (3,0):(3144904,54369,610378,3090535,50936192) (3,1):(3630212,54097,633016,3576115,50951320)
+ctxt 66155838
+btime 1062315585
+processes 69293
+
+*/
+               // Algorithm is taken from
+               // http://social.technet.microsoft.com/Forums/en-US/winservergen/thread/414b0e1b-499c-411e-8a02-6a12e339c0f1/
+               if (strncmp(PHP_OS,'WIN',3)==0) {
+                       if (PHP_VERSION == '5.0.0') return false;
+                       if (PHP_VERSION == '5.0.1') return false;
+                       if (PHP_VERSION == '5.0.2') return false;
+                       if (PHP_VERSION == '5.0.3') return false;
+                       if (PHP_VERSION == '4.3.10') return false; # see http://bugs.php.net/bug.php?id=31737
+
+                       static $FAIL = false;
+                       if ($FAIL) return false;
+
+                       $objName = "winmgmts:{impersonationLevel=impersonate}!\\\\.\\root\\CIMV2";
+                       $myQuery = "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name = '_Total'";
+
+                       try {
+                               @$objWMIService = new COM($objName);
+                               if (!$objWMIService) {
+                                       $FAIL = true;
+                                       return false;
+                               }
+
+                               $info[0] = -1;
+                               $info[1] = 0;
+                               $info[2] = 0;
+                               $info[3] = 0;
+                               foreach($objWMIService->ExecQuery($myQuery) as $objItem)  {
+                                               $info[0] = $objItem->PercentProcessorTime();
+                               }
+
+                       } catch(Exception $e) {
+                               $FAIL = true;
+                               echo $e->getMessage();
+                               return false;
+                       }
+
+                       return $info;
+               }
+
+               // Algorithm - Steve Blinch (BlitzAffe Online, http://www.blitzaffe.com)
+               $statfile = '/proc/stat';
+               if (!file_exists($statfile)) return false;
+
+               $fd = fopen($statfile,"r");
+               if (!$fd) return false;
+
+               $statinfo = explode("\n",fgets($fd, 1024));
+               fclose($fd);
+               foreach($statinfo as $line) {
+                       $info = explode(" ",$line);
+                       if($info[0]=="cpu") {
+                               array_shift($info);  // pop off "cpu"
+                               if(!$info[0]) array_shift($info); // pop off blank space (if any)
+                               return $info;
+                       }
+               }
+
+               return false;
+
+       }
+
+       /* NOT IMPLEMENTED */
+       function MemInfo()
+       {
+               /*
+
+        total:    used:    free:  shared: buffers:  cached:
+Mem:  1055289344 917299200 137990144        0 165437440 599773184
+Swap: 2146775040 11055104 2135719936
+MemTotal:      1030556 kB
+MemFree:        134756 kB
+MemShared:           0 kB
+Buffers:        161560 kB
+Cached:         581384 kB
+SwapCached:       4332 kB
+Active:         494468 kB
+Inact_dirty:    322856 kB
+Inact_clean:     24256 kB
+Inact_target:   168316 kB
+HighTotal:      131064 kB
+HighFree:         1024 kB
+LowTotal:       899492 kB
+LowFree:        133732 kB
+SwapTotal:     2096460 kB
+SwapFree:      2085664 kB
+Committed_AS:   348732 kB
+               */
+       }
+
+
+       /*
+               Remember that this is client load, not db server load!
+       */
+       var $_lastLoad;
+       function CPULoad()
+       {
+               $info = $this->_CPULoad();
+               if (!$info) return false;
+
+               if (strncmp(PHP_OS,'WIN',3)==0) {
+                       return (integer) $info[0];
+               }else {
+                       if (empty($this->_lastLoad)) {
+                               sleep(1);
+                               $this->_lastLoad = $info;
+                               $info = $this->_CPULoad();
+                       }
+
+                       $last = $this->_lastLoad;
+                       $this->_lastLoad = $info;
+
+                       $d_user = $info[0] - $last[0];
+                       $d_nice = $info[1] - $last[1];
+                       $d_system = $info[2] - $last[2];
+                       $d_idle = $info[3] - $last[3];
+
+                       //printf("Delta - User: %f  Nice: %f  System: %f  Idle: %f<br>",$d_user,$d_nice,$d_system,$d_idle);
+
+                       $total=$d_user+$d_nice+$d_system+$d_idle;
+                       if ($total<1) $total=1;
+                       return 100*($d_user+$d_nice+$d_system)/$total;
+               }
+       }
+
+       function Tracer($sql)
+       {
+        $perf_table = adodb_perf::table();
+               $saveE = $this->conn->fnExecute;
+               $this->conn->fnExecute = false;
+
+               global $ADODB_FETCH_MODE;
+               $save = $ADODB_FETCH_MODE;
+               $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+               if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
+
+               $sqlq = $this->conn->qstr($sql);
+               $arr = $this->conn->GetArray(
+"select count(*),tracer
+       from $perf_table where sql1=$sqlq
+       group by tracer
+       order by 1 desc");
+               $s = '';
+               if ($arr) {
+                       $s .= '<h3>Scripts Affected</h3>';
+                       foreach($arr as $k) {
+                               $s .= sprintf("%4d",$k[0]).' &nbsp; '.strip_tags($k[1]).'<br>';
+                       }
+               }
+
+               if (isset($savem)) $this->conn->SetFetchMode($savem);
+               $ADODB_CACHE_MODE = $save;
+               $this->conn->fnExecute = $saveE;
+               return $s;
+       }
+
+       /*
+               Explain Plan for $sql.
+               If only a snippet of the $sql is passed in, then $partial will hold the crc32 of the
+                       actual sql.
+       */
+       function Explain($sql,$partial=false)
+       {
+               return false;
+       }
+
+       function InvalidSQL($numsql = 10)
+       {
+
+               if (isset($_GET['sql'])) return;
+               $s = '<h3>Invalid SQL</h3>';
+               $saveE = $this->conn->fnExecute;
+               $this->conn->fnExecute = false;
+        $perf_table = adodb_perf::table();
+               $rs = $this->conn->SelectLimit("select distinct count(*),sql1,tracer as error_msg from $perf_table where tracer like 'ERROR:%' group by sql1,tracer order by 1 desc",$numsql);//,$numsql);
+               $this->conn->fnExecute = $saveE;
+               if ($rs) {
+                       $s .= rs2html($rs,false,false,false,false);
+               } else
+                       return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
+
+               return $s;
+       }
+
+
+       /*
+               This script identifies the longest running SQL
+       */
+       function _SuspiciousSQL($numsql = 10)
+       {
+               global $ADODB_FETCH_MODE;
+
+            $perf_table = adodb_perf::table();
+                       $saveE = $this->conn->fnExecute;
+                       $this->conn->fnExecute = false;
+
+                       if (isset($_GET['exps']) && isset($_GET['sql'])) {
+                               $partial = !empty($_GET['part']);
+                               echo "<a name=explain></a>".$this->Explain($_GET['sql'],$partial)."\n";
+                       }
+
+                       if (isset($_GET['sql'])) return;
+                       $sql1 = $this->sql1;
+
+                       $save = $ADODB_FETCH_MODE;
+                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+                       if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
+                       //$this->conn->debug=1;
+                       $rs = $this->conn->SelectLimit(
+                       "select avg(timer) as avg_timer,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer
+                               from $perf_table
+                               where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5)) not in ('DROP ','INSER','COMMI','CREAT')
+                               and (tracer is null or tracer not like 'ERROR:%')
+                               group by sql1
+                               order by 1 desc",$numsql);
+                       if (isset($savem)) $this->conn->SetFetchMode($savem);
+                       $ADODB_FETCH_MODE = $save;
+                       $this->conn->fnExecute = $saveE;
+
+                       if (!$rs) return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
+                       $s = "<h3>Suspicious SQL</h3>
+<font size=1>The following SQL have high average execution times</font><br>
+<table border=1 bgcolor=white><tr><td><strong>Avg Time</strong><td><strong>Count</strong><td><strong>SQL</strong><td><strong>Max</strong><td><strong>Min</strong></tr>\n";
+                       $max = $this->maxLength;
+                       while (!$rs->EOF) {
+                               $sql = $rs->fields[1];
+                               $raw = urlencode($sql);
+                               if (strlen($raw)>$max-100) {
+                                       $sql2 = substr($sql,0,$max-500);
+                                       $raw = urlencode($sql2).'&part='.crc32($sql);
+                               }
+                               $prefix = "<a target=sql".rand()." href=\"?hidem=1&exps=1&sql=".$raw."&x#explain\">";
+                               $suffix = "</a>";
+                               if ($this->explain == false || strlen($prefix)>$max) {
+                                       $suffix = ' ... <i>String too long for GET parameter: '.strlen($prefix).'</i>';
+                                       $prefix = '';
+                               }
+                               $s .= "<tr><td>".adodb_round($rs->fields[0],6)."<td align=right>".$rs->fields[2]."<td><font size=-1>".$prefix.htmlspecialchars($sql).$suffix."</font>".
+                                       "<td>".$rs->fields[3]."<td>".$rs->fields[4]."</tr>";
+                               $rs->MoveNext();
+                       }
+                       return $s."</table>";
+
+       }
+
+       function CheckMemory()
+       {
+               return '';
+       }
+
+
+       function SuspiciousSQL($numsql=10)
+       {
+               return adodb_perf::_SuspiciousSQL($numsql);
+       }
+
+       function ExpensiveSQL($numsql=10)
+       {
+               return adodb_perf::_ExpensiveSQL($numsql);
+       }
+
+
+       /*
+               This reports the percentage of load on the instance due to the most
+               expensive few SQL statements. Tuning these statements can often
+               make huge improvements in overall system performance.
+       */
+       function _ExpensiveSQL($numsql = 10)
+       {
+               global $ADODB_FETCH_MODE;
+
+            $perf_table = adodb_perf::table();
+                       $saveE = $this->conn->fnExecute;
+                       $this->conn->fnExecute = false;
+
+                       if (isset($_GET['expe']) && isset($_GET['sql'])) {
+                               $partial = !empty($_GET['part']);
+                               echo "<a name=explain></a>".$this->Explain($_GET['sql'],$partial)."\n";
+                       }
+
+                       if (isset($_GET['sql'])) return;
+
+                       $sql1 = $this->sql1;
+                       $save = $ADODB_FETCH_MODE;
+                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+                       if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
+
+                       $rs = $this->conn->SelectLimit(
+                       "select sum(timer) as total,$sql1,count(*),max(timer) as max_timer,min(timer) as min_timer
+                               from $perf_table
+                               where {$this->conn->upperCase}({$this->conn->substr}(sql0,1,5))  not in ('DROP ','INSER','COMMI','CREAT')
+                               and (tracer is null or tracer not like 'ERROR:%')
+                               group by sql1
+                               having count(*)>1
+                               order by 1 desc",$numsql);
+                       if (isset($savem)) $this->conn->SetFetchMode($savem);
+                       $this->conn->fnExecute = $saveE;
+                       $ADODB_FETCH_MODE = $save;
+                       if (!$rs) return "<p>$this->helpurl. ".$this->conn->ErrorMsg()."</p>";
+                       $s = "<h3>Expensive SQL</h3>
+<font size=\"1\">Tuning the following SQL could reduce the server load substantially</font><br>
+<table border=\"1\" bgcolor=\"white\"><tr><td><strong>Load</strong><td><strong>Count</strong><td><strong>SQL</strong><td><strong>Max</strong><td><strong>Min</strong></tr>\n";
+                       $max = $this->maxLength;
+                       while (!$rs->EOF) {
+                               $sql = $rs->fields[1];
+                               $raw = urlencode($sql);
+                               if (strlen($raw)>$max-100) {
+                                       $sql2 = substr($sql,0,$max-500);
+                                       $raw = urlencode($sql2).'&part='.crc32($sql);
+                               }
+                               $prefix = "<a target=sqle".rand()." href=\"?hidem=1&expe=1&sql=".$raw."&x#explain\">";
+                               $suffix = "</a>";
+                               if($this->explain == false || strlen($prefix>$max)) {
+                                       $prefix = '';
+                                       $suffix = '';
+                               }
+                               $s .= "<tr><td>".adodb_round($rs->fields[0],6)."<td align=right>".$rs->fields[2]."<td><font size=-1>".$prefix.htmlspecialchars($sql).$suffix."</font>".
+                                       "<td>".$rs->fields[3]."<td>".$rs->fields[4]."</tr>";
+                               $rs->MoveNext();
+                       }
+                       return $s."</table>";
+       }
+
+       /*
+               Raw function to return parameter value from $settings.
+       */
+       function DBParameter($param)
+       {
+               if (empty($this->settings[$param])) return false;
+               $sql = $this->settings[$param][1];
+               return $this->_DBParameter($sql);
+       }
+
+       /*
+               Raw function returning array of poll paramters
+       */
+       function PollParameters()
+       {
+               $arr[0] = (float)$this->DBParameter('data cache hit ratio');
+               $arr[1] = (float)$this->DBParameter('data reads');
+               $arr[2] = (float)$this->DBParameter('data writes');
+               $arr[3] = (integer) $this->DBParameter('current connections');
+               return $arr;
+       }
+
+       /*
+               Low-level Get Database Parameter
+       */
+       function _DBParameter($sql)
+       {
+               $savelog = $this->conn->LogSQL(false);
+               if (is_array($sql)) {
+               global $ADODB_FETCH_MODE;
+
+                       $sql1 = $sql[0];
+                       $key = $sql[1];
+                       if (sizeof($sql)>2) $pos = $sql[2];
+                       else $pos = 1;
+                       if (sizeof($sql)>3) $coef = $sql[3];
+                       else $coef = false;
+                       $ret = false;
+                       $save = $ADODB_FETCH_MODE;
+                       $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+                       if ($this->conn->fetchMode !== false) $savem = $this->conn->SetFetchMode(false);
+
+                       $rs = $this->conn->Execute($sql1);
+
+                       if (isset($savem)) $this->conn->SetFetchMode($savem);
+                       $ADODB_FETCH_MODE = $save;
+                       if ($rs) {
+                               while (!$rs->EOF) {
+                                       $keyf = reset($rs->fields);
+                                       if (trim($keyf) == $key) {
+                                               $ret = $rs->fields[$pos];
+                                               if ($coef) $ret *= $coef;
+                                               break;
+                                       }
+                                       $rs->MoveNext();
+                               }
+                               $rs->Close();
+                       }
+                       $this->conn->LogSQL($savelog);
+                       return $ret;
+               } else {
+                       if (strncmp($sql,'=',1) == 0) {
+                               $fn = substr($sql,1);
+                               return $this->$fn();
+                       }
+                       $sql = str_replace('$DATABASE',$this->conn->database,$sql);
+                       $ret = $this->conn->GetOne($sql);
+                       $this->conn->LogSQL($savelog);
+
+                       return $ret;
+               }
+       }
+
+       /*
+               Warn if cache ratio falls below threshold. Displayed in "Description" column.
+       */
+       function WarnCacheRatio($val)
+       {
+               if ($val < $this->warnRatio)
+                        return '<font color="red"><strong>Cache ratio should be at least '.$this->warnRatio.'%</strong></font>';
+               else return '';
+       }
+
+       function clearsql()
+       {
+               $perf_table = adodb_perf::table();
+               $this->conn->Execute("delete from $perf_table where created<".$this->conn->sysTimeStamp);
+       }
+       /***********************************************************************************************/
+       //                                    HIGH LEVEL UI FUNCTIONS
+       /***********************************************************************************************/
+
+
+       function UI($pollsecs=5)
+       {
+       global $ADODB_LOG_CONN;
+
+    $perf_table = adodb_perf::table();
+       $conn = $this->conn;
+
+       $app = $conn->host;
+       if ($conn->host && $conn->database) $app .= ', db=';
+       $app .= $conn->database;
+
+       if ($app) $app .= ', ';
+       $savelog = $this->conn->LogSQL(false);
+       $info = $conn->ServerInfo();
+       if (isset($_GET['clearsql'])) {
+               $this->clearsql();
+       }
+       $this->conn->LogSQL($savelog);
+
+       // magic quotes
+
+       if (isset($_GET['sql']) && get_magic_quotes_gpc()) {
+               $_GET['sql'] = $_GET['sql'] = str_replace(array("\\'",'\"'),array("'",'"'),$_GET['sql']);
+       }
+
+       if (!isset($_SESSION['ADODB_PERF_SQL'])) $nsql = $_SESSION['ADODB_PERF_SQL'] = 10;
+       else  $nsql = $_SESSION['ADODB_PERF_SQL'];
+
+       $app .= $info['description'];
+
+
+       if (isset($_GET['do'])) $do = $_GET['do'];
+       else if (isset($_POST['do'])) $do = $_POST['do'];
+        else if (isset($_GET['sql'])) $do = 'viewsql';
+        else $do = 'stats';
+
+       if (isset($_GET['nsql'])) {
+               if ($_GET['nsql'] > 0) $nsql = $_SESSION['ADODB_PERF_SQL'] = (integer) $_GET['nsql'];
+       }
+       echo "<title>ADOdb Performance Monitor on $app</title><body bgcolor=white>";
+       if ($do == 'viewsql') $form = "<td><form># SQL:<input type=hidden value=viewsql name=do> <input type=text size=4 name=nsql value=$nsql><input type=submit value=Go></td></form>";
+       else $form = "<td>&nbsp;</td>";
+
+       $allowsql = !defined('ADODB_PERF_NO_RUN_SQL');
+       global $ADODB_PERF_MIN;
+       $app .= " (Min sql timing \$ADODB_PERF_MIN=$ADODB_PERF_MIN secs)";
+
+       if  (empty($_GET['hidem']))
+       echo "<table border=1 width=100% bgcolor=lightyellow><tr><td colspan=2>
+       <strong><a href=http://adodb.sourceforge.net/?perf=1>ADOdb</a> Performance Monitor</strong> <font size=1>for $app</font></tr><tr><td>
+       <a href=?do=stats><strong>Performance Stats</strong></a> &nbsp; <a href=?do=viewsql><strong>View SQL</strong></a>
+        &nbsp; <a href=?do=tables><strong>View Tables</strong></a> &nbsp; <a href=?do=poll><strong>Poll Stats</strong></a>",
+        $allowsql ? ' &nbsp; <a href=?do=dosql><strong>Run SQL</strong></a>' : '',
+        "$form",
+        "</tr></table>";
+
+
+               switch ($do) {
+               default:
+               case 'stats':
+                       if (empty($ADODB_LOG_CONN))
+                               echo "<p>&nbsp; <a href=\"?do=viewsql&clearsql=1\">Clear SQL Log</a><br>";
+                       echo $this->HealthCheck();
+                       //$this->conn->debug=1;
+                       echo $this->CheckMemory();
+                       break;
+               case 'poll':
+                       $self = htmlspecialchars($_SERVER['PHP_SELF']);
+                       echo "<iframe width=720 height=80%
+                               src=\"{$self}?do=poll2&hidem=1\"></iframe>";
+                       break;
+               case 'poll2':
+                       echo "<pre>";
+                       $this->Poll($pollsecs);
+                       break;
+
+               case 'dosql':
+                       if (!$allowsql) break;
+
+                       $this->DoSQLForm();
+                       break;
+               case 'viewsql':
+                       if (empty($_GET['hidem']))
+                               echo "&nbsp; <a href=\"?do=viewsql&clearsql=1\">Clear SQL Log</a><br>";
+                       echo($this->SuspiciousSQL($nsql));
+                       echo($this->ExpensiveSQL($nsql));
+                       echo($this->InvalidSQL($nsql));
+                       break;
+               case 'tables':
+                       echo $this->Tables(); break;
+               }
+               global $ADODB_vers;
+               echo "<p><div align=center><font size=1>$ADODB_vers Sponsored by <a href=http://phplens.com/>phpLens</a></font></div>";
+       }
+
+       /*
+               Runs in infinite loop, returning real-time statistics
+       */
+       function Poll($secs=5)
+       {
+               $this->conn->fnExecute = false;
+               //$this->conn->debug=1;
+               if ($secs <= 1) $secs = 1;
+               echo "Accumulating statistics, every $secs seconds...\n";flush();
+               $arro = $this->PollParameters();
+               $cnt = 0;
+               set_time_limit(0);
+               sleep($secs);
+               while (1) {
+
+                       $arr = $this->PollParameters();
+
+                       $hits   = sprintf('%2.2f',$arr[0]);
+                       $reads  = sprintf('%12.4f',($arr[1]-$arro[1])/$secs);
+                       $writes = sprintf('%12.4f',($arr[2]-$arro[2])/$secs);
+                       $sess = sprintf('%5d',$arr[3]);
+
+                       $load = $this->CPULoad();
+                       if ($load !== false) {
+                               $oslabel = 'WS-CPU%';
+                               $osval = sprintf(" %2.1f  ",(float) $load);
+                       }else {
+                               $oslabel = '';
+                               $osval = '';
+                       }
+                       if ($cnt % 10 == 0) echo " Time   ".$oslabel."   Hit%   Sess           Reads/s          Writes/s\n";
+                       $cnt += 1;
+                       echo date('H:i:s').'  '.$osval."$hits  $sess $reads $writes\n";
+                       flush();
+
+                       if (connection_aborted()) return;
+
+                       sleep($secs);
+                       $arro = $arr;
+               }
+       }
+
+       /*
+               Returns basic health check in a command line interface
+       */
+       function HealthCheckCLI()
+       {
+               return $this->HealthCheck(true);
+       }
+
+
+       /*
+               Returns basic health check as HTML
+       */
+       function HealthCheck($cli=false)
+       {
+               $saveE = $this->conn->fnExecute;
+               $this->conn->fnExecute = false;
+               if ($cli) $html = '';
+               else $html = $this->table.'<tr><td colspan=3><h3>'.$this->conn->databaseType.'</h3></td></tr>'.$this->titles;
+
+               $oldc = false;
+               $bgc = '';
+               foreach($this->settings as $name => $arr) {
+                       if ($arr === false) break;
+
+                       if (!is_string($name)) {
+                               if ($cli) $html .= " -- $arr -- \n";
+                               else $html .= "<tr bgcolor=$this->color><td colspan=3><i>$arr</i> &nbsp;</td></tr>";
+                               continue;
+                       }
+
+                       if (!is_array($arr)) break;
+                       $category = $arr[0];
+                       $how = $arr[1];
+                       if (sizeof($arr)>2) $desc = $arr[2];
+                       else $desc = ' &nbsp; ';
+
+
+                       if ($category == 'HIDE') continue;
+
+                       $val = $this->_DBParameter($how);
+
+                       if ($desc && strncmp($desc,"=",1) === 0) {
+                               $fn = substr($desc,1);
+                               $desc = $this->$fn($val);
+                       }
+
+                       if ($val === false) {
+                               $m = $this->conn->ErrorMsg();
+                               $val = "Error: $m";
+                       } else {
+                               if (is_numeric($val) && $val >= 256*1024) {
+                                       if ($val % (1024*1024) == 0) {
+                                               $val /= (1024*1024);
+                                               $val .= 'M';
+                                       } else if ($val % 1024 == 0) {
+                                               $val /= 1024;
+                                               $val .= 'K';
+                                       }
+                                       //$val = htmlspecialchars($val);
+                               }
+                       }
+                       if ($category != $oldc) {
+                               $oldc = $category;
+                               //$bgc = ($bgc == ' bgcolor='.$this->color) ? ' bgcolor=white' : ' bgcolor='.$this->color;
+                       }
+                       if (strlen($desc)==0) $desc = '&nbsp;';
+                       if (strlen($val)==0) $val = '&nbsp;';
+                       if ($cli) {
+                               $html  .= str_replace('&nbsp;','',sprintf($this->cliFormat,strip_tags($name),strip_tags($val),strip_tags($desc)));
+
+                       }else {
+                               $html .= "<tr$bgc><td>".$name.'</td><td>'.$val.'</td><td>'.$desc."</td></tr>\n";
+                       }
+               }
+
+               if (!$cli) $html .= "</table>\n";
+               $this->conn->fnExecute = $saveE;
+
+               return $html;
+       }
+
+       function Tables($orderby='1')
+       {
+               if (!$this->tablesSQL) return false;
+
+               $savelog = $this->conn->LogSQL(false);
+               $rs = $this->conn->Execute($this->tablesSQL.' order by '.$orderby);
+               $this->conn->LogSQL($savelog);
+               $html = rs2html($rs,false,false,false,false);
+               return $html;
+       }
+
+
+       function CreateLogTable()
+       {
+               if (!$this->createTableSQL) return false;
+
+               $table = $this->table();
+               $sql = str_replace('adodb_logsql',$table,$this->createTableSQL);
+               $savelog = $this->conn->LogSQL(false);
+               $ok = $this->conn->Execute($sql);
+               $this->conn->LogSQL($savelog);
+               return ($ok) ? true : false;
+       }
+
+       function DoSQLForm()
+       {
+
+
+               $PHP_SELF = htmlspecialchars($_SERVER['PHP_SELF']);
+               $sql = isset($_REQUEST['sql']) ? $_REQUEST['sql'] : '';
+
+               if (isset($_SESSION['phplens_sqlrows'])) $rows = $_SESSION['phplens_sqlrows'];
+               else $rows = 3;
+
+               if (isset($_REQUEST['SMALLER'])) {
+                       $rows /= 2;
+                       if ($rows < 3) $rows = 3;
+                       $_SESSION['phplens_sqlrows'] = $rows;
+               }
+               if (isset($_REQUEST['BIGGER'])) {
+                       $rows *= 2;
+                       $_SESSION['phplens_sqlrows'] = $rows;
+               }
+
+?>
+
+<form method="POST" action="<?php echo $PHP_SELF ?>">
+<table><tr>
+<td> Form size: <input type="submit" value=" &lt; " name="SMALLER"><input type="submit" value=" &gt; &gt; " name="BIGGER">
+</td>
+<td align=right>
+<input type="submit" value=" Run SQL Below " name="RUN"><input type=hidden name=do value=dosql>
+</td></tr>
+  <tr>
+  <td colspan=2><textarea rows=<?php print $rows; ?> name="sql" cols="80"><?php print htmlspecialchars($sql) ?></textarea>
+  </td>
+  </tr>
+ </table>
+</form>
+
+<?php
+               if (!isset($_REQUEST['sql'])) return;
+
+               $sql = $this->undomq(trim($sql));
+               if (substr($sql,strlen($sql)-1) === ';') {
+                       $print = true;
+                       $sqla = $this->SplitSQL($sql);
+               } else  {
+                       $print = false;
+                       $sqla = array($sql);
+               }
+               foreach($sqla as $sqls) {
+
+                       if (!$sqls) continue;
+
+                       if ($print) {
+                               print "<p>".htmlspecialchars($sqls)."</p>";
+                               flush();
+                       }
+                       $savelog = $this->conn->LogSQL(false);
+                       $rs = $this->conn->Execute($sqls);
+                       $this->conn->LogSQL($savelog);
+                       if ($rs && is_object($rs) && !$rs->EOF) {
+                               rs2html($rs);
+                               while ($rs->NextRecordSet()) {
+                                       print "<table width=98% bgcolor=#C0C0FF><tr><td>&nbsp;</td></tr></table>";
+                                       rs2html($rs);
+                               }
+                       } else {
+                               $e1 = (integer) $this->conn->ErrorNo();
+                               $e2 = $this->conn->ErrorMsg();
+                               if (($e1) || ($e2)) {
+                                       if (empty($e1)) $e1 = '-1'; // postgresql fix
+                                       print ' &nbsp; '.$e1.': '.$e2;
+                               } else {
+                                       print "<p>No Recordset returned<br></p>";
+                               }
+                       }
+               } // foreach
+       }
+
+       function SplitSQL($sql)
+       {
+               $arr = explode(';',$sql);
+               return $arr;
+       }
+
+       function undomq($m)
+       {
+       if (get_magic_quotes_gpc()) {
+               // undo the damage
+               $m = str_replace('\\\\','\\',$m);
+               $m = str_replace('\"','"',$m);
+               $m = str_replace('\\\'','\'',$m);
+       }
+       return $m;
+}
+
+
+   /************************************************************************/
+
+    /**
+     * Reorganise multiple table-indices/statistics/..
+     * OptimizeMode could be given by last Parameter
+     *
+     * @example
+     *      <pre>
+     *          optimizeTables( 'tableA');
+     *      </pre>
+     *      <pre>
+     *          optimizeTables( 'tableA', 'tableB', 'tableC');
+     *      </pre>
+     *      <pre>
+     *          optimizeTables( 'tableA', 'tableB', ADODB_OPT_LOW);
+     *      </pre>
+     *
+     * @param string table name of the table to optimize
+     * @param int mode optimization-mode
+     *      <code>ADODB_OPT_HIGH</code> for full optimization
+     *      <code>ADODB_OPT_LOW</code> for CPU-less optimization
+     *      Default is LOW <code>ADODB_OPT_LOW</code>
+     * @author Markus Staab
+     * @return Returns <code>true</code> on success and <code>false</code> on error
+     */
+    function OptimizeTables()
+    {
+        $args = func_get_args();
+        $numArgs = func_num_args();
+
+        if ( $numArgs == 0) return false;
+
+        $mode = ADODB_OPT_LOW;
+        $lastArg = $args[ $numArgs - 1];
+        if ( !is_string($lastArg)) {
+            $mode = $lastArg;
+            unset( $args[ $numArgs - 1]);
+        }
+
+        foreach( $args as $table) {
+            $this->optimizeTable( $table, $mode);
+        }
+       }
+
+    /**
+     * Reorganise the table-indices/statistics/.. depending on the given mode.
+     * Default Implementation throws an error.
+     *
+     * @param string table name of the table to optimize
+     * @param int mode optimization-mode
+     *   &n