MDL-52286 core: update ADODB library to 5.21
authorMarina Glancy <marina@moodle.com>
Tue, 8 Dec 2015 03:52:40 +0000 (11:52 +0800)
committerMarina Glancy <marina@moodle.com>
Tue, 8 Dec 2015 03:52:40 +0000 (11:52 +0800)
106 files changed:
lib/adodb/adodb-active-record.inc.php
lib/adodb/adodb-active-recordx.inc.php
lib/adodb/adodb-csvlib.inc.php
lib/adodb/adodb-datadict.inc.php
lib/adodb/adodb-error.inc.php
lib/adodb/adodb-errorhandler.inc.php
lib/adodb/adodb-errorpear.inc.php
lib/adodb/adodb-exceptions.inc.php
lib/adodb/adodb-iterator.inc.php
lib/adodb/adodb-lib.inc.php
lib/adodb/adodb-memcache.lib.inc.php
lib/adodb/adodb-pager.inc.php
lib/adodb/adodb-pear.inc.php
lib/adodb/adodb-perf.inc.php
lib/adodb/adodb-php4.inc.php
lib/adodb/adodb-time.inc.php
lib/adodb/adodb-xmlschema.inc.php
lib/adodb/adodb-xmlschema03.inc.php
lib/adodb/adodb.inc.php
lib/adodb/datadict/datadict-access.inc.php
lib/adodb/datadict/datadict-db2.inc.php
lib/adodb/datadict/datadict-firebird.inc.php
lib/adodb/datadict/datadict-generic.inc.php
lib/adodb/datadict/datadict-ibase.inc.php
lib/adodb/datadict/datadict-informix.inc.php
lib/adodb/datadict/datadict-mssql.inc.php
lib/adodb/datadict/datadict-mssqlnative.inc.php
lib/adodb/datadict/datadict-mysql.inc.php
lib/adodb/datadict/datadict-oci8.inc.php
lib/adodb/datadict/datadict-postgres.inc.php
lib/adodb/datadict/datadict-sapdb.inc.php
lib/adodb/datadict/datadict-sqlite.inc.php
lib/adodb/datadict/datadict-sybase.inc.php
lib/adodb/drivers/adodb-access.inc.php
lib/adodb/drivers/adodb-ado.inc.php
lib/adodb/drivers/adodb-ado5.inc.php
lib/adodb/drivers/adodb-ado_access.inc.php
lib/adodb/drivers/adodb-ado_mssql.inc.php
lib/adodb/drivers/adodb-ads.inc.php
lib/adodb/drivers/adodb-borland_ibase.inc.php
lib/adodb/drivers/adodb-csv.inc.php
lib/adodb/drivers/adodb-db2.inc.php
lib/adodb/drivers/adodb-db2oci.inc.php
lib/adodb/drivers/adodb-db2ora.inc.php
lib/adodb/drivers/adodb-fbsql.inc.php
lib/adodb/drivers/adodb-firebird.inc.php
lib/adodb/drivers/adodb-ibase.inc.php
lib/adodb/drivers/adodb-informix.inc.php
lib/adodb/drivers/adodb-informix72.inc.php
lib/adodb/drivers/adodb-ldap.inc.php
lib/adodb/drivers/adodb-mssql.inc.php
lib/adodb/drivers/adodb-mssql_n.inc.php
lib/adodb/drivers/adodb-mssqlnative.inc.php
lib/adodb/drivers/adodb-mssqlpo.inc.php
lib/adodb/drivers/adodb-mysql.inc.php
lib/adodb/drivers/adodb-mysqli.inc.php
lib/adodb/drivers/adodb-mysqlpo.inc.php
lib/adodb/drivers/adodb-mysqlt.inc.php
lib/adodb/drivers/adodb-netezza.inc.php
lib/adodb/drivers/adodb-oci8.inc.php
lib/adodb/drivers/adodb-oci805.inc.php
lib/adodb/drivers/adodb-oci8po.inc.php
lib/adodb/drivers/adodb-oci8quercus.inc.php
lib/adodb/drivers/adodb-odbc.inc.php
lib/adodb/drivers/adodb-odbc_db2.inc.php
lib/adodb/drivers/adodb-odbc_mssql.inc.php
lib/adodb/drivers/adodb-odbc_oracle.inc.php
lib/adodb/drivers/adodb-odbtp.inc.php
lib/adodb/drivers/adodb-odbtp_unicode.inc.php
lib/adodb/drivers/adodb-oracle.inc.php
lib/adodb/drivers/adodb-pdo.inc.php
lib/adodb/drivers/adodb-pdo_mssql.inc.php
lib/adodb/drivers/adodb-pdo_mysql.inc.php
lib/adodb/drivers/adodb-pdo_oci.inc.php
lib/adodb/drivers/adodb-pdo_pgsql.inc.php
lib/adodb/drivers/adodb-pdo_sqlite.inc.php
lib/adodb/drivers/adodb-pdo_sqlsrv.inc.php [new file with mode: 0644]
lib/adodb/drivers/adodb-postgres.inc.php
lib/adodb/drivers/adodb-postgres64.inc.php
lib/adodb/drivers/adodb-postgres7.inc.php
lib/adodb/drivers/adodb-postgres8.inc.php
lib/adodb/drivers/adodb-postgres9.inc.php
lib/adodb/drivers/adodb-proxy.inc.php
lib/adodb/drivers/adodb-sapdb.inc.php
lib/adodb/drivers/adodb-sqlanywhere.inc.php
lib/adodb/drivers/adodb-sqlite.inc.php
lib/adodb/drivers/adodb-sqlite3.inc.php
lib/adodb/drivers/adodb-sqlitepo.inc.php
lib/adodb/drivers/adodb-sybase.inc.php
lib/adodb/drivers/adodb-sybase_ase.inc.php
lib/adodb/drivers/adodb-text.inc.php [new file with mode: 0644]
lib/adodb/drivers/adodb-vfp.inc.php
lib/adodb/license.txt
lib/adodb/perf/perf-db2.inc.php
lib/adodb/perf/perf-informix.inc.php
lib/adodb/perf/perf-mssql.inc.php
lib/adodb/perf/perf-mssqlnative.inc.php
lib/adodb/perf/perf-mysql.inc.php
lib/adodb/perf/perf-oci8.inc.php
lib/adodb/perf/perf-postgres.inc.php
lib/adodb/pivottable.inc.php
lib/adodb/readme_moodle.txt
lib/adodb/rsfilter.inc.php
lib/adodb/toexport.inc.php
lib/adodb/tohtml.inc.php
lib/thirdpartylibs.xml

index 607fa94..ad9533c 100644 (file)
@@ -1,7 +1,9 @@
 <?php
 /*
 
-@version V5.19  23-Apr-2014  (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved.
+@version   v5.20.1  06-Dec-2015
+@copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
+@copyright (c) 2014      Damien Regad, Mark Newnham and the ADOdb community
   Latest version is available at http://adodb.sourceforge.net
 
   Released under both BSD license and Lesser GPL library license.
@@ -52,10 +54,13 @@ function ADODB_SetDatabaseAdapter(&$db, $index=false)
 
                foreach($_ADODB_ACTIVE_DBS as $k => $d) {
                        if (PHP_VERSION >= 5) {
-                               if ($d->db === $db) return $k;
+                               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;
+                               }
                        }
                }
 
@@ -63,8 +68,9 @@ function ADODB_SetDatabaseAdapter(&$db, $index=false)
                $obj->db = $db;
                $obj->tables = array();
 
-               if ($index == false) $index = sizeof($_ADODB_ACTIVE_DBS);
-
+               if ($index == false) {
+                       $index = sizeof($_ADODB_ACTIVE_DBS);
+               }
 
                $_ADODB_ACTIVE_DBS[$index] = $obj;
 
@@ -92,7 +98,9 @@ class ADODB_Active_Record {
        static function UseDefaultValues($bool=null)
        {
        global $ADODB_ACTIVE_DEFVALS;
-               if (isset($bool)) $ADODB_ACTIVE_DEFVALS = $bool;
+               if (isset($bool)) {
+                       $ADODB_ACTIVE_DEFVALS = $bool;
+               }
                return $ADODB_ACTIVE_DEFVALS;
        }
 
@@ -120,14 +128,21 @@ class ADODB_Active_Record {
                }
 
                if (!$table) {
-                       if (!empty($this->_table)) $table = $this->_table;
+                       if (!empty($this->_table)) {
+                               $table = $this->_table;
+                       }
                        else $table = $this->_pluralize(get_class($this));
                }
                $this->foreignName = strtolower(get_class($this)); // CFR: default foreign name
                if ($db) {
                        $this->_dbat = ADODB_Active_Record::SetDatabaseAdapter($db);
                } else if (!isset($this->_dbat)) {
-                       if (sizeof($_ADODB_ACTIVE_DBS) == 0) $this->Error("No database connection set; use ADOdb_Active_Record::SetDatabaseAdapter(\$db)",'ADODB_Active_Record::__constructor');
+                       if (sizeof($_ADODB_ACTIVE_DBS) == 0) {
+                               $this->Error(
+                                       "No database connection set; use ADOdb_Active_Record::SetDatabaseAdapter(\$db)",
+                                       'ADODB_Active_Record::__constructor'
+                               );
+                       }
                        end($_ADODB_ACTIVE_DBS);
                        $this->_dbat = key($_ADODB_ACTIVE_DBS);
                }
@@ -146,7 +161,9 @@ class ADODB_Active_Record {
 
        function _pluralize($table)
        {
-               if (!ADODB_Active_Record::$_changeNames) return $table;
+               if (!ADODB_Active_Record::$_changeNames) {
+                       return $table;
+               }
 
                $ut = strtoupper($table);
                $len = strlen($table);
@@ -160,8 +177,9 @@ class ADODB_Active_Record {
                case 'X':
                        return $table.'es';
                case 'H':
-                       if ($lastc2 == 'CH' || $lastc2 == 'SH')
+                       if ($lastc2 == 'CH' || $lastc2 == 'SH') {
                                return $table.'es';
+                       }
                default:
                        return $table.'s';
                }
@@ -172,24 +190,28 @@ class ADODB_Active_Record {
        function _singularize($tables)
        {
 
-               if (!ADODB_Active_Record::$_changeNames) return $table;
+               if (!ADODB_Active_Record::$_changeNames) {
+                       return $table;
+               }
 
                $ut = strtoupper($tables);
                $len = strlen($tables);
-               if($ut[$len-1] != 'S')
+               if($ut[$len-1] != 'S') {
                        return $tables; // I know...forget oxen
-               if($ut[$len-2] != 'E')
+               }
+               if($ut[$len-2] != 'E') {
                        return substr($tables, 0, $len-1);
-               switch($ut[$len-3])
-               {
+               }
+               switch($ut[$len-3]) {
                        case 'S':
                        case 'X':
                                return substr($tables, 0, $len-2);
                        case 'I':
                                return substr($tables, 0, $len-3) . 'y';
                        case 'H';
-                               if($ut[$len-4] == 'C' || $ut[$len-4] == 'S')
+                               if($ut[$len-4] == 'C' || $ut[$len-4] == 'S') {
                                        return substr($tables, 0, $len-2);
+                               }
                        default:
                                return substr($tables, 0, $len-1); // ?
                }
@@ -216,7 +238,9 @@ class ADODB_Active_Record {
        // use when you don't want ADOdb to auto-pluralize tablename
        static function TableKeyHasMany($table, $tablePKey, $foreignRef, $foreignKey = false, $foreignClass = 'ADODB_Active_Record')
        {
-               if (!is_array($tablePKey)) $tablePKey = array($tablePKey);
+               if (!is_array($tablePKey)) {
+                       $tablePKey = array($tablePKey);
+               }
                $ar = new ADODB_Active_Record($table,$tablePKey);
                $ar->hasMany($foreignRef, $foreignKey, $foreignClass);
        }
@@ -260,7 +284,9 @@ class ADODB_Active_Record {
 
        static function TableKeyBelongsTo($table, $tablePKey, $foreignRef, $foreignKey=false, $parentKey='', $parentClass = 'ADODB_Active_Record')
        {
-               if (!is_array($tablePKey)) $tablePKey = array($tablePKey);
+               if (!is_array($tablePKey)) {
+                       $tablePKey = array($tablePKey);
+               }
                $ar = new ADOdb_Active_Record($table, $tablePKey);
                $ar->belongsTo($foreignRef, $foreignKey, $parentKey, $parentClass);
        }
@@ -289,24 +315,34 @@ class ADODB_Active_Record {
        {
                $extras = array();
                $table = $this->TableInfo();
-               if ($limit >= 0) $extras['limit'] = $limit;
-               if ($offset >= 0) $extras['offset'] = $offset;
+               if ($limit >= 0) {
+                       $extras['limit'] = $limit;
+               }
+               if ($offset >= 0) {
+                       $extras['offset'] = $offset;
+               }
 
-               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 (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]))
-               {
+               if(!empty($table->_belongsTo[$name])) {
                        $obj = $table->_belongsTo[$name];
                        $columnName = $obj->foreignKey;
-                       if(empty($this->$columnName))
+                       if(empty($this->$columnName)) {
                                $this->$name = null;
-                       else
-                       {
-                               if ($obj->parentKey) $key = $obj->parentKey;
-                               else $key = reset($table->keys);
+                       }
+                       else {
+                               if ($obj->parentKey) {
+                                       $key = $obj->parentKey;
+                               }
+                               else {
+                                       $key = reset($table->keys);
+                               }
 
                                $arrayOfOne = $obj->Find($key.'='.$this->$columnName.' '.$whereOrderBy,false,false,$extras);
                                if ($arrayOfOne) {
@@ -315,8 +351,7 @@ class ADODB_Active_Record {
                                }
                        }
                }
-               if(!empty($table->_hasMany[$name]))
-               {
+               if(!empty($table->_hasMany[$name])) {
                        $obj = $table->_hasMany[$name];
                        $key = reset($table->keys);
                        $id = @$this->$key;
@@ -325,7 +360,9 @@ class ADODB_Active_Record {
                                $id = $db->qstr($id);
                        }
                        $objs = $obj->Find($obj->foreignKey.'='.$id. ' '.$whereOrderBy,false,false,$extras);
-                       if (!$objs) $objs = array();
+                       if (!$objs) {
+                               $objs = array();
+                       }
                        $this->$name = $objs;
                        return $objs;
                }
@@ -349,10 +386,12 @@ class ADODB_Active_Record {
 
                        $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;
+                               if ($ADODB_ACTIVE_DEFVALS && isset($fld->default_value)) {
+                                       $this->$name = $fld->default_value;
+                               }
+                               else {
+                                       $this->$name = null;
+                               }
                        }
                        return;
                }
@@ -368,10 +407,12 @@ class ADODB_Active_Record {
                                // ideally, you should cache at least 32 secs
 
                                foreach($acttab->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
+                                       }
+                                       else {
                                                $this->$name = null;
+                                       }
                                }
 
                                $activedb->tables[$table] = $acttab;
@@ -387,11 +428,15 @@ class ADODB_Active_Record {
 
                $save = $ADODB_FETCH_MODE;
                $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
-               if ($db->fetchMode !== false) $savem = $db->SetFetchMode(false);
+               if ($db->fetchMode !== false) {
+                       $savem = $db->SetFetchMode(false);
+               }
 
                $cols = $db->MetaColumns($table);
 
-               if (isset($savem)) $db->SetFetchMode($savem);
+               if (isset($savem)) {
+                       $db->SetFetchMode($savem);
+               }
                $ADODB_FETCH_MODE = $save;
 
                if (!$cols) {
@@ -403,7 +448,9 @@ class ADODB_Active_Record {
                        if (isset($fld->primary_key)) {
                                $pkeys = array();
                                foreach($cols as $name => $fld) {
-                                       if (!empty($fld->primary_key)) $pkeys[] = $name;
+                                       if (!empty($fld->primary_key)) {
+                                               $pkeys[] = $name;
+                                       }
                                }
                        } else
                                $pkeys = $this->GetPrimaryKeys($db, $table);
@@ -420,10 +467,12 @@ class ADODB_Active_Record {
                case 0:
                        foreach($cols as $name => $fldobj) {
                                $name = strtolower($name);
-                if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
-                    $this->$name = $fldobj->default_value;
-                else
+                               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) {
@@ -435,10 +484,12 @@ class ADODB_Active_Record {
                        foreach($cols as $name => $fldobj) {
                                $name = strtoupper($name);
 
-                if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
-                    $this->$name = $fldobj->default_value;
-                else
+                               if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value)) {
+                                       $this->$name = $fldobj->default_value;
+                               }
+                               else {
                                        $this->$name = null;
+                               }
                                $attr[$name] = $fldobj;
                        }
 
@@ -450,10 +501,12 @@ class ADODB_Active_Record {
                        foreach($cols as $name => $fldobj) {
                                $name = ($fldobj->name);
 
-                if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
-                    $this->$name = $fldobj->default_value;
-                else
+                               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) {
@@ -468,14 +521,18 @@ class ADODB_Active_Record {
                if ($ADODB_ACTIVE_CACHESECS && $ADODB_CACHE_DIR) {
                        $activetab->_created = time();
                        $s = serialize($activetab);
-                       if (!function_exists('adodb_write_file')) include(ADODB_DIR.'/adodb-csvlib.inc.php');
+                       if (!function_exists('adodb_write_file')) {
+                               include(ADODB_DIR.'/adodb-csvlib.inc.php');
+                       }
                        adodb_write_file($fname,$s);
                }
                if (isset($activedb->tables[$table])) {
                        $oldtab = $activedb->tables[$table];
 
-                       if ($oldtab) $activetab->_belongsTo = $oldtab->_belongsTo;
-                       if ($oldtab) $activetab->_hasMany = $oldtab->_hasMany;
+                       if ($oldtab) {
+                               $activetab->_belongsTo = $oldtab->_belongsTo;
+                               $activetab->_hasMany = $oldtab->_hasMany;
+                       }
                }
                $activedb->tables[$table] = $activetab;
        }
@@ -493,17 +550,26 @@ class ADODB_Active_Record {
                $fn = get_class($this).'::'.$fn;
                $this->_lasterr = $fn.': '.$err;
 
-               if ($this->_dbat < 0) $db = false;
+               if ($this->_dbat < 0) {
+                       $db = false;
+               }
                else {
                        $activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
                        $db = $activedb->db;
                }
 
                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);
+                       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);
+                       }
+               }
 
        }
 
@@ -511,18 +577,26 @@ class ADODB_Active_Record {
        function ErrorMsg()
        {
                if (!function_exists('adodb_throw')) {
-                       if ($this->_dbat < 0) $db = false;
-                       else $db = $this->DB();
+                       if ($this->_dbat < 0) {
+                               $db = false;
+                       }
+                       else {
+                               $db = $this->DB();
+                       }
 
                        // last error could be database error too
-                       if ($db && $db->ErrorMsg()) return $db->ErrorMsg();
+                       if ($db && $db->ErrorMsg()) {
+                               return $db->ErrorMsg();
+                       }
                }
                return $this->_lasterr;
        }
 
        function ErrorNo()
        {
-               if ($this->_dbat < 0) return -9999; // no database connection...
+               if ($this->_dbat < 0) {
+                       return -9999; // no database connection...
+               }
                $db = $this->DB();
 
                return (int) $db->ErrorNo();
@@ -558,8 +632,11 @@ class ADODB_Active_Record {
        // So, I find that for myTable, I want to reload an active record after saving it. -- Malcolm Cook
        function Reload()
        {
-               $db =& $this->DB(); if (!$db) return false;
-               $table =& $this->TableInfo();
+               $db = $this->DB();
+               if (!$db) {
+                       return false;
+               }
+               $table = $this->TableInfo();
                $where = $this->GenWhere($db, $table);
                return($this->Load($where));
        }
@@ -581,44 +658,47 @@ class ADODB_Active_Record {
 
                $table = $this->TableInfo();
                if ($ACTIVE_RECORD_SAFETY && sizeof($table->flds) != sizeof($row)) {
-            # <AP>
-            $bad_size = TRUE;
-            if (sizeof($row) == 2 * sizeof($table->flds)) {
-                // Only keep string keys
-                $keys = array_filter(array_keys($row), 'is_string');
-                if (sizeof($keys) == sizeof($table->flds))
-                    $bad_size = FALSE;
-            }
-            if ($bad_size) {
+                       # <AP>
+                       $bad_size = TRUE;
+                       if (sizeof($row) == 2 * sizeof($table->flds)) {
+                               // Only keep string keys
+                               $keys = array_filter(array_keys($row), 'is_string');
+                               if (sizeof($keys) == sizeof($table->flds)) {
+                                       $bad_size = FALSE;
+                               }
+                       }
+                       if ($bad_size) {
                        $this->Error("Table structure of $this->_table has changed","Load");
                        return false;
                }
-            # </AP>
+                       # </AP>
                }
-        else
+               else
                        $keys = array_keys($row);
 
-        # <AP>
-        reset($keys);
-        $this->_original = array();
+               # <AP>
+               reset($keys);
+               $this->_original = array();
                foreach($table->flds as $name=>$fld) {
-            $value = $row[current($keys)];
+                       $value = $row[current($keys)];
                        $this->$name = $value;
-            $this->_original[] = $value;
-            next($keys);
+                       $this->_original[] = $value;
+                       next($keys);
                }
 
-        # </AP>
+               # </AP>
                return true;
        }
 
        // get last inserted id for INSERT
        function LastInsertID(&$db,$fieldname)
        {
-               if ($db->hasInsertID)
+               if ($db->hasInsertID) {
                        $val = $db->Insert_ID($this->_table,$fieldname);
-               else
+               }
+               else {
                        $val = false;
+               }
 
                if (is_null($val) || $val === false) {
                        // this might not work reliably in multi-user environment
@@ -632,19 +712,25 @@ class ADODB_Active_Record {
        {
                switch($t) {
                case 'L':
-                       if (strpos($db->databaseType,'postgres') !== false) return $db->qstr($val);
+                       if (strpos($db->databaseType,'postgres') !== false) {
+                               return $db->qstr($val);
+                       }
                case 'D':
                case 'T':
-                       if (empty($val)) return 'null';
-
+                       if (empty($val)) {
+                               return 'null';
+                       }
                case 'B':
                case 'N':
                case 'C':
                case 'X':
-                       if (is_null($val)) return 'null';
+                       if (is_null($val)) {
+                               return 'null';
+                       }
 
                        if (strlen($val)>0 &&
-                               (strncmp($val,"'",1) != 0 || substr($val,strlen($val)-1,1) != "'")) {
+                               (strncmp($val,"'",1) != 0 || substr($val,strlen($val)-1,1) != "'")
+                       ) {
                                return $db->qstr($val);
                                break;
                        }
@@ -672,8 +758,15 @@ class ADODB_Active_Record {
 
        function _QName($n,$db=false)
        {
-               if (!ADODB_Active_Record::$_quoteNames) return $n;
-               if (!$db) $db = $this->DB(); if (!$db) return false;
+               if (!ADODB_Active_Record::$_quoteNames) {
+                       return $n;
+               }
+               if (!$db) {
+                       $db = $this->DB();
+                       if (!$db) {
+                               return false;
+                       }
+               }
                return $db->nameQuote.$n.$db->nameQuote;
        }
 
@@ -683,23 +776,32 @@ class ADODB_Active_Record {
        {
        global $ADODB_FETCH_MODE;
 
-               $db = $this->DB(); if (!$db) return false;
+               $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);
+               if ($db->fetchMode !== false) {
+                       $savem = $db->SetFetchMode(false);
+               }
 
                $qry = "select * from ".$this->_table;
 
                if($where) {
                        $qry .= ' WHERE '.$where;
                }
-               if ($lock) $qry .= $this->lockMode;
+               if ($lock) {
+                       $qry .= $this->lockMode;
+               }
 
                $row = $db->GetRow($qry,$bindarr);
 
-               if (isset($savem)) $db->SetFetchMode($savem);
+               if (isset($savem)) {
+                       $db->SetFetchMode($savem);
+               }
                $ADODB_FETCH_MODE = $save;
 
                return $this->Set($row);
@@ -714,25 +816,29 @@ class ADODB_Active_Record {
        # see http://phplens.com/lens/lensforum/msgs.php?id=17795
        function Reset()
        {
-        $this->_where=null;
-        $this->_saved = false;
-        $this->_lasterr = false;
-        $this->_original = false;
-        $vars=get_object_vars($this);
-        foreach($vars as $k=>$v){
-               if(substr($k,0,1)!=='_'){
-                       $this->{$k}=null;
-               }
-        }
-        $this->foreignName=strtolower(get_class($this));
-        return true;
-    }
+               $this->_where=null;
+               $this->_saved = false;
+               $this->_lasterr = false;
+               $this->_original = false;
+               $vars=get_object_vars($this);
+               foreach($vars as $k=>$v){
+                       if(substr($k,0,1)!=='_'){
+                               $this->{$k}=null;
+                       }
+               }
+               $this->foreignName=strtolower(get_class($this));
+               return true;
+       }
 
        // false on error
        function Save()
        {
-               if ($this->_saved) $ok = $this->Update();
-               else $ok = $this->Insert();
+               if ($this->_saved) {
+                       $ok = $this->Update();
+               }
+               else {
+                       $ok = $this->Insert();
+               }
 
                return $ok;
        }
@@ -741,7 +847,10 @@ class ADODB_Active_Record {
        // false on error
        function Insert()
        {
-               $db = $this->DB(); if (!$db) return false;
+               $db = $this->DB();
+               if (!$db) {
+                       return false;
+               }
                $cnt = 0;
                $table = $this->TableInfo();
 
@@ -791,7 +900,10 @@ class ADODB_Active_Record {
 
        function Delete()
        {
-               $db = $this->DB(); if (!$db) return false;
+               $db = $this->DB();
+               if (!$db) {
+                       return false;
+               }
                $table = $this->TableInfo();
 
                $where = $this->GenWhere($db,$table);
@@ -804,7 +916,10 @@ class ADODB_Active_Record {
        // returns an array of active record objects
        function Find($whereOrderBy,$bindarr=false,$pkeysArr=false,$extra=array())
        {
-               $db = $this->DB(); if (!$db || empty($this->_table)) return false;
+               $db = $this->DB();
+               if (!$db || empty($this->_table)) {
+                       return false;
+               }
                $arr = $db->GetActiveRecordsClass(get_class($this),$this->_table, $whereOrderBy,$bindarr,$pkeysArr,$extra);
                return $arr;
        }
@@ -814,7 +929,10 @@ class ADODB_Active_Record {
        {
        global $ADODB_ASSOC_CASE;
 
-               $db = $this->DB(); if (!$db) return false;
+               $db = $this->DB();
+               if (!$db) {
+                       return false;
+               }
                $table = $this->TableInfo();
 
                $pkey = $table->keys;
@@ -824,7 +942,9 @@ class ADODB_Active_Record {
                        /*
                        if (is_null($val)) {
                                if (isset($fld->not_null) && $fld->not_null) {
-                                       if (isset($fld->default_value) && strlen($fld->default_value)) continue;
+                                       if (isset($fld->default_value) && strlen($fld->default_value)) {
+                                               continue;
+                                       }
                                        else {
                                                $this->Error("Cannot update null into $name","Replace");
                                                return false;
@@ -832,25 +952,31 @@ class ADODB_Active_Record {
                                }
                        }*/
                        if (is_null($val) && !empty($fld->auto_increment)) {
-               continue;
-            }
+                               continue;
+                       }
 
-                       if (is_array($val)) 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 (!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)
-                       foreach($pkey as $k => $v)
+               }
+               elseif ($ADODB_ASSOC_CASE == 1) {
+                       foreach($pkey as $k => $v) {
                                $pkey[$k] = strtoupper($v);
+                       }
+               }
 
                $ok = $db->Replace($this->_table,$arr,$pkey);
                if ($ok) {
@@ -877,7 +1003,10 @@ class ADODB_Active_Record {
        // returns 0 on error, 1 on update, -1 if no change in data (no update)
        function Update()
        {
-               $db = $this->DB(); if (!$db) return false;
+               $db = $this->DB();
+               if (!$db) {
+                       return false;
+               }
                $table = $this->TableInfo();
 
                $where = $this->GenWhere($db, $table);
@@ -896,12 +1025,15 @@ class ADODB_Active_Record {
                        $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;
+                                       if (isset($fld->default_value) && strlen($fld->default_value)) {
+                                               continue;
+                                       }
                                        else {
                                                $this->Error("Cannot set field $name to NULL","Update");
                                                return false;
@@ -909,9 +1041,13 @@ class ADODB_Active_Record {
                                }
                        }
 
-                       if (isset($this->_original[$i]) && strcmp($val,$this->_original[$i]) == 0) continue;
+                       if (isset($this->_original[$i]) && strcmp($val,$this->_original[$i]) == 0) {
+                               continue;
+                       }
 
-                       if (is_null($this->_original[$i]) && is_null($val)) continue;
+                       if (is_null($this->_original[$i]) && is_null($val)) {
+                               continue;
+                       }
 
                        $valarr[] = $val;
                        $pairs[] = $this->_QName($name,$db).'='.$db->Param($cnt);
@@ -919,7 +1055,10 @@ class ADODB_Active_Record {
                }
 
 
-               if (!$cnt) return -1;
+               if (!$cnt) {
+                       return -1;
+               }
+
                $sql = 'UPDATE '.$this->_table." SET ".implode(",",$pairs)." WHERE ".$where;
                $ok = $db->Execute($sql,$valarr);
                if ($ok) {
@@ -932,7 +1071,9 @@ class ADODB_Active_Record {
        function GetAttributeNames()
        {
                $table = $this->TableInfo();
-               if (!$table) return false;
+               if (!$table) {
+                       return false;
+               }
                return array_keys($table->flds);
        }
 
@@ -947,10 +1088,10 @@ global $_ADODB_ACTIVE_DBS;
        $save = $db->SetFetchMode(ADODB_FETCH_NUM);
        $qry = "select * from ".$table;
 
-       if (!empty($whereOrderBy))
+       if (!empty($whereOrderBy)) {
                $qry .= ' WHERE '.$whereOrderBy;
-       if(isset($extra['limit']))
-       {
+       }
+       if(isset($extra['limit'])) {
                $rows = false;
                if(isset($extra['offset'])) {
                        $rs = $db->SelectLimit($qry, $extra['limit'], $extra['offset'],$bindarr);
index e820144..771a086 100644 (file)
@@ -1,7 +1,9 @@
 <?php
 /*
 
-@version V5.19  23-Apr-2014  (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved.
+@version   v5.20.1  06-Dec-2015
+@copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
+@copyright (c) 2014      Damien Regad, Mark Newnham and the ADOdb community
   Latest version is available at http://adodb.sourceforge.net
 
   Released under both BSD license and Lesser GPL library license.
@@ -66,10 +68,13 @@ function ADODB_SetDatabaseAdapter(&$db)
 
                foreach($_ADODB_ACTIVE_DBS as $k => $d) {
                        if (PHP_VERSION >= 5) {
-                               if ($d->db === $db) return $k;
+                               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;
+                               }
                        }
                }
 
@@ -101,7 +106,9 @@ class ADODB_Active_Record {
        static function UseDefaultValues($bool=null)
        {
        global $ADODB_ACTIVE_DEFVALS;
-               if (isset($bool)) $ADODB_ACTIVE_DEFVALS = $bool;
+               if (isset($bool)) {
+                       $ADODB_ACTIVE_DEFVALS = $bool;
+               }
                return $ADODB_ACTIVE_DEFVALS;
        }
 
@@ -137,15 +144,13 @@ class ADODB_Active_Record {
                        $pkeyarr = false;
                }
 
-               if($table)
-               {
+               if($table) {
                        // table argument exists. It is expected to be
                        // already plural form.
                        $this->_pTable = $table;
                        $this->_sTable = $this->_singularize($this->_pTable);
                }
-               else
-               {
+               else {
                        // We will use current classname as table name.
                        // We need to pluralize it for the real table name.
                        $this->_sTable = strtolower(get_class($this));
@@ -161,7 +166,12 @@ class ADODB_Active_Record {
                        $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');
+               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
 
@@ -169,8 +179,7 @@ class ADODB_Active_Record {
                // but there was no way to ask it to do that.
                $forceUpdate = (isset($options['refresh']) && true === $options['refresh']);
                $this->UpdateActiveTable($pkeyarr, $forceUpdate);
-               if(isset($options['new']) && true === $options['new'])
-               {
+               if(isset($options['new']) && true === $options['new']) {
                        $table =& $this->TableInfo();
                        unset($table->_hasMany);
                        unset($table->_belongsTo);
@@ -181,8 +190,8 @@ class ADODB_Active_Record {
 
        function __wakeup()
        {
-               $class = get_class($this);
-               new $class;
+               $class = get_class($this);
+               new $class;
        }
 
        // CFR: Constants found in Rails
@@ -215,32 +224,32 @@ class ADODB_Active_Record {
 
        function _pluralize($table)
        {
-               if (!ADODB_Active_Record::$_changeNames) return $table;
-
+               if (!ADODB_Active_Record::$_changeNames) {
+                       return $table;
+               }
                $ut = strtoupper($table);
-               if(isset(self::$WeIsI[$ut]))
-               {
+               if(isset(self::$WeIsI[$ut])) {
                        return $table;
                }
-               if(isset(self::$IrregularP[$ut]))
-               {
+               if(isset(self::$IrregularP[$ut])) {
                        return self::$IrregularP[$ut];
                }
                $len = strlen($table);
                $lastc = $ut[$len-1];
                $lastc2 = substr($ut,$len-2);
                switch ($lastc) {
-               case 'S':
-                       return $table.'es';
-               case 'Y':
-                       return substr($table,0,$len-1).'ies';
-               case 'X':
-                       return $table.'es';
-               case 'H':
-                       if ($lastc2 == 'CH' || $lastc2 == 'SH')
+                       case 'S':
                                return $table.'es';
-               default:
-                       return $table.'s';
+                       case 'Y':
+                               return substr($table,0,$len-1).'ies';
+                       case 'X':
+                               return $table.'es';
+                       case 'H':
+                               if ($lastc2 == 'CH' || $lastc2 == 'SH') {
+                                       return $table.'es';
+                               }
+                       default:
+                               return $table.'s';
                }
        }
 
@@ -249,32 +258,33 @@ class ADODB_Active_Record {
        function _singularize($table)
        {
 
-               if (!ADODB_Active_Record::$_changeNames) return $table;
-
+               if (!ADODB_Active_Record::$_changeNames) {
+               return $table;
+       }
                $ut = strtoupper($table);
-               if(isset(self::$WeIsI[$ut]))
-               {
+               if(isset(self::$WeIsI[$ut])) {
                        return $table;
                }
-               if(isset(self::$IrregularS[$ut]))
-               {
+               if(isset(self::$IrregularS[$ut])) {
                        return self::$IrregularS[$ut];
                }
                $len = strlen($table);
-               if($ut[$len-1] != 'S')
+               if($ut[$len-1] != 'S') {
                        return $table; // I know...forget oxen
-               if($ut[$len-2] != 'E')
+               }
+               if($ut[$len-2] != 'E') {
                        return substr($table, 0, $len-1);
-               switch($ut[$len-3])
-               {
+               }
+               switch($ut[$len-3]) {
                        case 'S':
                        case 'X':
                                return substr($table, 0, $len-2);
                        case 'I':
                                return substr($table, 0, $len-3) . 'y';
                        case 'H';
-                               if($ut[$len-4] == 'C' || $ut[$len-4] == 'S')
+                               if($ut[$len-4] == 'C' || $ut[$len-4] == 'S') {
                                        return substr($table, 0, $len-2);
+                               }
                        default:
                                return substr($table, 0, $len-1); // ?
                }
@@ -296,8 +306,7 @@ class ADODB_Active_Record {
                $ar->foreignKey = ($foreignKey) ? $foreignKey : strtolower(get_class($this)) . self::$_foreignSuffix;
 
                $table =& $this->TableInfo();
-               if(!isset($table->_hasMany[$foreignRef]))
-               {
+               if(!isset($table->_hasMany[$foreignRef])) {
                        $table->_hasMany[$foreignRef] = $ar;
                        $table->updateColsCount();
                }
@@ -322,8 +331,7 @@ class ADODB_Active_Record {
                $ar->foreignKey = ($foreignKey) ? $foreignKey : $ar->foreignName . self::$_foreignSuffix;
 
                $table =& $this->TableInfo();
-               if(!isset($table->_belongsTo[$foreignRef]))
-               {
+               if(!isset($table->_belongsTo[$foreignRef])) {
                        $table->_belongsTo[$foreignRef] = $ar;
                        $table->updateColsCount();
                }
@@ -345,27 +353,35 @@ class ADODB_Active_Record {
        function LoadRelations($name, $whereOrderBy, $offset=-1, $limit=-1)
        {
                $extras = array();
-               if($offset >= 0) $extras['offset'] = $offset;
-               if($limit >= 0) $extras['limit'] = $limit;
+               if($offset >= 0) {
+                       $extras['offset'] = $offset;
+               }
+               if($limit >= 0) {
+                       $extras['limit'] = $limit;
+               }
                $table =& $this->TableInfo();
 
-               if (strlen($whereOrderBy))
-                       if (!preg_match('/^[ \n\r]*AND/i',$whereOrderBy))
-                               if (!preg_match('/^[ \n\r]*ORDER[ \n\r]/i',$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]))
-               {
+               if(!empty($table->_belongsTo[$name])) {
                        $obj = $table->_belongsTo[$name];
                        $columnName = $obj->foreignKey;
-                       if(empty($this->$columnName))
+                       if(empty($this->$columnName)) {
                                $this->$name = null;
-                       else
-                       {
-                               if(($k = reset($obj->TableInfo()->keys)))
+                       }
+                       else {
+                               if(($k = reset($obj->TableInfo()->keys))) {
                                        $belongsToId = $k;
-                               else
+                               }
+                               else {
                                        $belongsToId = 'id';
+                               }
 
                                $arrayOfOne =
                                        $obj->Find(
@@ -374,13 +390,14 @@ class ADODB_Active_Record {
                        }
                        return $this->$name;
                }
-               if(!empty($table->_hasMany[$name]))
-               {
+               if(!empty($table->_hasMany[$name])) {
                        $obj = $table->_hasMany[$name];
-                       if(($k = reset($table->keys)))
+                       if(($k = reset($table->keys))) {
                                $hasManyId   = $k;
-                       else
+                       }
+                       else {
                                $hasManyId   = 'id';
+                       }
 
                        $this->$name =
                                $obj->Find(
@@ -405,10 +422,12 @@ class ADODB_Active_Record {
 
                        $tobj = $tables[$tableat];
                        foreach($tobj->flds as $name => $fld) {
-                       if ($ADODB_ACTIVE_DEFVALS && isset($fld->default_value))
-                               $this->$name = $fld->default_value;
-                       else
-                               $this->$name = null;
+                               if ($ADODB_ACTIVE_DEFVALS && isset($fld->default_value)) {
+                                       $this->$name = $fld->default_value;
+                               }
+                               else {
+                                       $this->$name = null;
+                               }
                        }
                        return;
                }
@@ -426,7 +445,7 @@ class ADODB_Active_Record {
                                $activedb->tables[$table] = $acttab;
 
                                //if ($db->debug) ADOConnection::outp("Reading cached active record file: $fname");
-                               return;
+                                       return;
                        } else if ($db->debug) {
                                ADOConnection::outp("Refreshing cached active record file: $fname");
                        }
@@ -436,11 +455,15 @@ class ADODB_Active_Record {
 
                $save = $ADODB_FETCH_MODE;
                $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
-               if ($db->fetchMode !== false) $savem = $db->SetFetchMode(false);
+               if ($db->fetchMode !== false) {
+                       $savem = $db->SetFetchMode(false);
+               }
 
                $cols = $db->MetaColumns($table);
 
-               if (isset($savem)) $db->SetFetchMode($savem);
+               if (isset($savem)) {
+                       $db->SetFetchMode($savem);
+               }
                $ADODB_FETCH_MODE = $save;
 
                if (!$cols) {
@@ -452,10 +475,13 @@ class ADODB_Active_Record {
                        if (isset($fld->primary_key)) {
                                $pkeys = array();
                                foreach($cols as $name => $fld) {
-                                       if (!empty($fld->primary_key)) $pkeys[] = $name;
+                                       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');
@@ -469,10 +495,12 @@ class ADODB_Active_Record {
                case 0:
                        foreach($cols as $name => $fldobj) {
                                $name = strtolower($name);
-                if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
-                    $this->$name = $fldobj->default_value;
-                else
+                               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) {
@@ -484,10 +512,12 @@ class ADODB_Active_Record {
                        foreach($cols as $name => $fldobj) {
                                $name = strtoupper($name);
 
-                if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
-                    $this->$name = $fldobj->default_value;
-                else
+                               if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value)) {
+                                       $this->$name = $fldobj->default_value;
+                               }
+                               else {
                                        $this->$name = null;
+                               }
                                $attr[$name] = $fldobj;
                        }
 
@@ -499,10 +529,12 @@ class ADODB_Active_Record {
                        foreach($cols as $name => $fldobj) {
                                $name = ($fldobj->name);
 
-                if ($ADODB_ACTIVE_DEFVALS && isset($fldobj->default_value))
-                    $this->$name = $fldobj->default_value;
-                else
+                               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) {
@@ -518,14 +550,18 @@ class ADODB_Active_Record {
                if ($ADODB_ACTIVE_CACHESECS && $ADODB_CACHE_DIR) {
                        $activetab->_created = time();
                        $s = serialize($activetab);
-                       if (!function_exists('adodb_write_file')) include(ADODB_DIR.'/adodb-csvlib.inc.php');
+                       if (!function_exists('adodb_write_file')) {
+                               include(ADODB_DIR.'/adodb-csvlib.inc.php');
+                       }
                        adodb_write_file($fname,$s);
                }
                if (isset($activedb->tables[$table])) {
                        $oldtab = $activedb->tables[$table];
 
-                       if ($oldtab) $activetab->_belongsTo = $oldtab->_belongsTo;
-                       if ($oldtab) $activetab->_hasMany = $oldtab->_hasMany;
+                       if ($oldtab) {
+                               $activetab->_belongsTo = $oldtab->_belongsTo;
+                               $activetab->_hasMany = $oldtab->_hasMany;
+                       }
                }
                $activedb->tables[$table] = $activetab;
        }
@@ -543,17 +579,26 @@ class ADODB_Active_Record {
                $fn = get_class($this).'::'.$fn;
                $this->_lasterr = $fn.': '.$err;
 
-               if ($this->_dbat < 0) $db = false;
+               if ($this->_dbat < 0) {
+                       $db = false;
+               }
                else {
                        $activedb = $_ADODB_ACTIVE_DBS[$this->_dbat];
                        $db = $activedb->db;
                }
 
                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);
+                       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);
+                       }
+               }
 
        }
 
@@ -561,18 +606,26 @@ class ADODB_Active_Record {
        function ErrorMsg()
        {
                if (!function_exists('adodb_throw')) {
-                       if ($this->_dbat < 0) $db = false;
-                       else $db = $this->DB();
+                       if ($this->_dbat < 0) {
+                               $db = false;
+                       }
+                       else {
+                               $db = $this->DB();
+                       }
 
                        // last error could be database error too
-                       if ($db && $db->ErrorMsg()) return $db->ErrorMsg();
+                       if ($db && $db->ErrorMsg()) {
+                               return $db->ErrorMsg();
+                       }
                }
                return $this->_lasterr;
        }
 
        function ErrorNo()
        {
-               if ($this->_dbat < 0) return -9999; // no database connection...
+               if ($this->_dbat < 0) {
+                       return -9999; // no database connection...
+               }
                $db = $this->DB();
 
                return (int) $db->ErrorNo();
@@ -609,7 +662,10 @@ class ADODB_Active_Record {
        // So, I find that for myTable, I want to reload an active record after saving it. -- Malcolm Cook
        function Reload()
        {
-               $db =& $this->DB(); if (!$db) return false;
+               $db =& $this->DB();
+               if (!$db) {
+                       return false;
+               }
                $table =& $this->TableInfo();
                $where = $this->GenWhere($db, $table);
                return($this->Load($where));
@@ -634,67 +690,74 @@ class ADODB_Active_Record {
                $sizeofFlds = sizeof($table->flds);
                $sizeofRow  = sizeof($row);
                if ($ACTIVE_RECORD_SAFETY && $table->_colsCount != $sizeofRow && $sizeofFlds != $sizeofRow) {
-            # <AP>
-            $bad_size = TRUE;
-       if($sizeofRow == 2 * $table->_colsCount || $sizeofRow == 2 * $sizeofFlds) {
-                // Only keep string keys
-                $keys = array_filter(array_keys($row), 'is_string');
-                if (sizeof($keys) == sizeof($table->flds))
-                    $bad_size = FALSE;
-            }
-            if ($bad_size) {
-                       $this->Error("Table structure of $this->_table has changed","Load");
-                       return false;
+                       # <AP>
+                       $bad_size = TRUE;
+                       if($sizeofRow == 2 * $table->_colsCount || $sizeofRow == 2 * $sizeofFlds) {
+                               // Only keep string keys
+                               $keys = array_filter(array_keys($row), 'is_string');
+                               if (sizeof($keys) == sizeof($table->flds)) {
+                                       $bad_size = FALSE;
+                               }
+                       }
+                       if ($bad_size) {
+                               $this->Error("Table structure of $this->_table has changed","Load");
+                               return false;
+                       }
+                       # </AP>
                }
-            # </AP>
+               else {
+                       $keys = array_keys($row);
                }
-        else
-               $keys = array_keys($row);
-        # <AP>
-        reset($keys);
-        $this->_original = array();
-               foreach($table->flds as $name=>$fld)
-               {
-            $value = $row[current($keys)];
+
+               # <AP>
+               reset($keys);
+               $this->_original = array();
+               foreach($table->flds as $name=>$fld) {
+                       $value = $row[current($keys)];
                        $this->$name = $value;
-            $this->_original[] = $value;
-            if(!next($keys)) break;
+                       $this->_original[] = $value;
+                       if(!next($keys)) {
+                               break;
+                       }
                }
                $table =& $this->TableInfo();
-               foreach($table->_belongsTo as $foreignTable)
-               {
+               foreach($table->_belongsTo as $foreignTable) {
                        $ft = $foreignTable->TableInfo();
                        $propertyName = $ft->name;
-                       foreach($ft->flds as $name=>$fld)
-                       {
+                       foreach($ft->flds as $name=>$fld) {
                                $value = $row[current($keys)];
                                $foreignTable->$name = $value;
                                $foreignTable->_original[] = $value;
-                               if(!next($keys)) break;
+                               if(!next($keys)) {
+                                       break;
+                               }
                        }
                }
-               foreach($table->_hasMany as $foreignTable)
-               {
+               foreach($table->_hasMany as $foreignTable) {
                        $ft = $foreignTable->TableInfo();
-                       foreach($ft->flds as $name=>$fld)
-                       {
+                       foreach($ft->flds as $name=>$fld) {
                                $value = $row[current($keys)];
                                $foreignTable->$name = $value;
                                $foreignTable->_original[] = $value;
-                               if(!next($keys)) break;
+                               if(!next($keys)) {
+                                       break;
+                               }
                        }
                }
-        # </AP>
+               # </AP>
+
                return true;
        }
 
        // get last inserted id for INSERT
        function LastInsertID(&$db,$fieldname)
        {
-               if ($db->hasInsertID)
+               if ($db->hasInsertID) {
                        $val = $db->Insert_ID($this->_table,$fieldname);
-               else
+               }
+               else {
                        $val = false;
+               }
 
                if (is_null($val) || $val === false) {
                        // this might not work reliably in multi-user environment
@@ -709,14 +772,17 @@ class ADODB_Active_Record {
                switch($t) {
                case 'D':
                case 'T':
-                       if (empty($val)) return 'null';
-
+                       if (empty($val)) {
+                               return 'null';
+                       }
                case 'C':
                case 'X':
-                       if (is_null($val)) return 'null';
-
+                       if (is_null($val)) {
+                               return 'null';
+                       }
                        if (strlen($val)>0 &&
-                               (strncmp($val,"'",1) != 0 || substr($val,strlen($val)-1,1) != "'")) {
+                               (strncmp($val,"'",1) != 0 || substr($val,strlen($val)-1,1) != "'")
+                       ) {
                                return $db->qstr($val);
                                break;
                        }
@@ -746,26 +812,28 @@ class ADODB_Active_Record {
 
        function Load($where=null,$bindarr=false)
        {
-               $db = $this->DB(); if (!$db) return 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();
 
-               if(($k = reset($table->keys)))
+               if(($k = reset($table->keys))) {
                        $hasManyId   = $k;
-               else
+               }
+               else {
                        $hasManyId   = 'id';
+               }
 
-               foreach($table->_belongsTo as $foreignTable)
-               {
-                       if(($k = reset($foreignTable->TableInfo()->keys)))
-                       {
+               foreach($table->_belongsTo as $foreignTable) {
+                       if(($k = reset($foreignTable->TableInfo()->keys))) {
                                $belongsToId = $k;
                        }
-                       else
-                       {
+                       else {
                                $belongsToId = 'id';
                        }
                        $qry .= ' LEFT JOIN '.$foreignTable->_table.' ON '.
@@ -778,96 +846,88 @@ class ADODB_Active_Record {
                                $this->_table.'.'.$hasManyId.'='.
                                $foreignTable->_table.'.'.$foreignTable->foreignKey;
                }
-               if($where)
+               if($where) {
                        $qry .= ' WHERE '.$where;
+               }
 
                // Simple case: no relations. Load row and return.
-               if((count($table->_hasMany) + count($table->_belongsTo)) < 1)
-               {
+               if((count($table->_hasMany) + count($table->_belongsTo)) < 1) {
                        $row = $db->GetRow($qry,$bindarr);
-                       if(!$row)
+                       if(!$row) {
                                return false;
+                       }
                        $db->SetFetchMode($save);
                        return $this->Set($row);
                }
 
                // More complex case when relations have to be collated
                $rows = $db->GetAll($qry,$bindarr);
-               if(!$rows)
+               if(!$rows) {
                        return false;
+               }
                $db->SetFetchMode($save);
-               if(count($rows) < 1)
+               if(count($rows) < 1) {
                        return false;
+               }
                $class = get_class($this);
                $isFirstRow = true;
 
-               if(($k = reset($this->TableInfo()->keys)))
+               if(($k = reset($this->TableInfo()->keys))) {
                        $myId   = $k;
-               else
+               }
+               else {
                        $myId   = 'id';
+               }
                $index = 0; $found = false;
                /** @todo Improve by storing once and for all in table metadata */
                /** @todo Also re-use info for hasManyId */
-               foreach($this->TableInfo()->flds as $fld)
-               {
-                       if($fld->name == $myId)
-                       {
+               foreach($this->TableInfo()->flds as $fld) {
+                       if($fld->name == $myId) {
                                $found = true;
                                break;
                        }
                        $index++;
                }
-               if(!$found)
+               if(!$found) {
                        $this->outp_throw("Unable to locate key $myId for $class in Load()",'Load');
+               }
 
-               foreach($rows as $row)
-               {
+               foreach($rows as $row) {
                        $rowId = intval($row[$index]);
-                       if($rowId > 0)
-                       {
-                               if($isFirstRow)
-                               {
+                       if($rowId > 0) {
+                               if($isFirstRow) {
                                        $isFirstRow = false;
-                                       if(!$this->Set($row))
+                                       if(!$this->Set($row)) {
                                                return false;
+                                       }
                                }
                                $obj = new $class($table,false,$db);
                                $obj->Set($row);
                                // TODO Copy/paste code below: bad!
-                               if(count($table->_hasMany) > 0)
-                               {
-                                       foreach($table->_hasMany as $foreignTable)
-                                       {
+                               if(count($table->_hasMany) > 0) {
+                                       foreach($table->_hasMany as $foreignTable) {
                                                $foreignName = $foreignTable->foreignName;
-                                               if(!empty($obj->$foreignName))
-                                               {
-                                                       if(!is_array($this->$foreignName))
-                                                       {
+                                               if(!empty($obj->$foreignName)) {
+                                                       if(!is_array($this->$foreignName)) {
                                                                $foreignObj = $this->$foreignName;
                                                                $this->$foreignName = array(clone($foreignObj));
                                                        }
-                                                       else
-                                                       {
+                                                       else {
                                                                $foreignObj = $obj->$foreignName;
                                                                array_push($this->$foreignName, clone($foreignObj));
                                                        }
                                                }
                                        }
                                }
-                               if(count($table->_belongsTo) > 0)
-                               {
-                                       foreach($table->_belongsTo as $foreignTable)
-                                       {
+                               if(count($table->_belongsTo) > 0) {
+                                       foreach($table->_belongsTo as $foreignTable) {
                                                $foreignName = $foreignTable->foreignName;
-                                               if(!empty($obj->$foreignName))
-                                               {
-                                                       if(!is_array($this->$foreignName))
-                                                       {
+                                               if(!empty($obj->$foreignName)) {
+                                                       if(!is_array($this->$foreignName)) {
                                                                $foreignObj = $this->$foreignName;
                                                                $this->$foreignName = array(clone($foreignObj));
                                                        }
-                                                       else
-                                                       {
+                                                       else {
                                                                $foreignObj = $obj->$foreignName;
                                                                array_push($this->$foreignName, clone($foreignObj));
                                                        }
@@ -882,8 +942,12 @@ class ADODB_Active_Record {
        // false on error
        function Save()
        {
-               if ($this->_saved) $ok = $this->Update();
-               else $ok = $this->Insert();
+               if ($this->_saved) {
+                       $ok = $this->Update();
+               }
+               else {
+                       $ok = $this->Insert();
+               }
 
                return $ok;
        }
@@ -898,7 +962,10 @@ class ADODB_Active_Record {
        // false on error
        function Insert()
        {
-               $db = $this->DB(); if (!$db) return false;
+               $db = $this->DB();
+               if (!$db) {
+                       return false;
+               }
                $cnt = 0;
                $table = $this->TableInfo();
 
@@ -948,7 +1015,10 @@ class ADODB_Active_Record {
 
        function Delete()
        {
-               $db = $this->DB(); if (!$db) return false;
+               $db = $this->DB();
+               if (!$db) {
+                       return false;
+               }
                $table = $this->TableInfo();
 
                $where = $this->GenWhere($db,$table);
@@ -961,7 +1031,10 @@ class ADODB_Active_Record {
        // returns an array of active record objects
        function Find($whereOrderBy,$bindarr=false,$pkeysArr=false,$extra=array())
        {
-               $db = $this->DB(); if (!$db || empty($this->_table)) return false;
+               $db = $this->DB();
+               if (!$db || empty($this->_table)) {
+                       return false;
+               }
                $table =& $this->TableInfo();
                $arr = $db->GetActiveRecordsClass(get_class($this),$this, $whereOrderBy,$bindarr,$pkeysArr,$extra,
                        array('foreignName'=>$this->foreignName, 'belongsTo'=>$table->_belongsTo, 'hasMany'=>$table->_hasMany));
@@ -974,7 +1047,10 @@ class ADODB_Active_Record {
        // Shockingly because I want to preserve PHP4 compatibility.
        function packageFind($whereOrderBy,$bindarr=false,$pkeysArr=false,$extra=array())
        {
-               $db = $this->DB(); if (!$db || empty($this->_table)) return false;
+               $db = $this->DB();
+               if (!$db || empty($this->_table)) {
+                       return false;
+               }
                $table =& $this->TableInfo();
                $arr = $db->GetActiveRecordsClass(get_class($this),$this, $whereOrderBy,$bindarr,$pkeysArr,$extra,
                        array('foreignName'=>$this->foreignName, 'belongsTo'=>$table->_belongsTo, 'hasMany'=>$table->_hasMany));
@@ -986,7 +1062,10 @@ class ADODB_Active_Record {
        {
        global $ADODB_ASSOC_CASE;
 
-               $db = $this->DB(); if (!$db) return false;
+               $db = $this->DB();
+               if (!$db) {
+                       return false;
+               }
                $table = $this->TableInfo();
 
                $pkey = $table->keys;
@@ -996,7 +1075,9 @@ class ADODB_Active_Record {
                        /*
                        if (is_null($val)) {
                                if (isset($fld->not_null) && $fld->not_null) {
-                                       if (isset($fld->default_value) && strlen($fld->default_value)) continue;
+                                       if (isset($fld->default_value) && strlen($fld->default_value)) {
+                                               continue;
+                                       }
                                        else {
                                                $this->Error("Cannot update null into $name","Replace");
                                                return false;
@@ -1004,22 +1085,30 @@ class ADODB_Active_Record {
                                }
                        }*/
                        if (is_null($val) && !empty($fld->auto_increment)) {
-               continue;
-            }
+                               continue;
+                       }
                        $t = $db->MetaType($fld->type);
                        $arr[$name] = $this->doquote($db,$val,$t);
                        $valarr[] = $val;
                }
 
-               if (!is_array($pkey)) $pkey = array($pkey);
+               if (!is_array($pkey)) {
+                       $pkey = array($pkey);
+               }
 
 
-               if ($ADODB_ASSOC_CASE == 0)
-                       foreach($pkey as $k => $v)
-                               $pkey[$k] = strtolower($v);
-               elseif ($ADODB_ASSOC_CASE == 1)
-                       foreach($pkey as $k => $v)
-                               $pkey[$k] = strtoupper($v);
+               switch ($ADODB_ASSOC_CASE == 0) {
+                       case ADODB_ASSOC_CASE_LOWER:
+                               foreach($pkey as $k => $v) {
+                                       $pkey[$k] = strtolower($v);
+                               }
+                               break;
+                       case ADODB_ASSOC_CASE_UPPER:
+                               foreach($pkey as $k => $v) {
+                                       $pkey[$k] = strtoupper($v);
+                               }
+                               break;
+               }
 
                $ok = $db->Replace($this->_table,$arr,$pkey);
                if ($ok) {
@@ -1046,7 +1135,10 @@ class ADODB_Active_Record {
        // returns 0 on error, 1 on update, -1 if no change in data (no update)
        function Update()
        {
-               $db = $this->DB(); if (!$db) return false;
+               $db = $this->DB();
+               if (!$db) {
+                       return false;
+               }
                $table = $this->TableInfo();
 
                $where = $this->GenWhere($db, $table);
@@ -1071,7 +1163,9 @@ class ADODB_Active_Record {
 
                        if (is_null($val)) {
                                if (isset($fld->not_null) && $fld->not_null) {
-                                       if (isset($fld->default_value) && strlen($fld->default_value)) continue;
+                                       if (isset($fld->default_value) && strlen($fld->default_value)) {
+                                               continue;
+                                       }
                                        else {
                                                $this->Error("Cannot set field $name to NULL","Update");
                                                return false;
@@ -1079,7 +1173,7 @@ class ADODB_Active_Record {
                                }
                        }
 
-                       if (isset($this->_original[$i]) && $val == $this->_original[$i]) {
+                       if (isset($this->_original[$i]) && $val === $this->_original[$i]) {
                                continue;
                        }
                        $valarr[] = $val;
@@ -1088,7 +1182,9 @@ class ADODB_Active_Record {
                }
 
 
-               if (!$cnt) return -1;
+               if (!$cnt) {
+                       return -1;
+               }
                $sql = 'UPDATE '.$this->_table." SET ".implode(",",$pairs)." WHERE ".$where;
                $ok = $db->Execute($sql,$valarr);
                if ($ok) {
@@ -1101,7 +1197,9 @@ class ADODB_Active_Record {
        function GetAttributeNames()
        {
                $table = $this->TableInfo();
-               if (!$table) return false;
+               if (!$table) {
+                       return false;
+               }
                return array_keys($table->flds);
        }
 
@@ -1112,43 +1210,41 @@ function adodb_GetActiveRecordsClass(&$db, $class, $tableObj,$whereOrderBy,$bind
 {
        global $_ADODB_ACTIVE_DBS;
 
-               if (empty($extra['loading'])) $extra['loading'] = ADODB_LAZY_AR;
-
+               if (empty($extra['loading'])) {
+                       $extra['loading'] = ADODB_LAZY_AR;
+               }
                $save = $db->SetFetchMode(ADODB_FETCH_NUM);
                $table = &$tableObj->_table;
                $tableInfo =& $tableObj->TableInfo();
-               if(($k = reset($tableInfo->keys)))
-                       $myId   = $k;
-               else
-                       $myId   = 'id';
+               if(($k = reset($tableInfo->keys))) {
+                       $myId = $k;
+               }
+               else {
+                       $myId = 'id';
+               }
                $index = 0; $found = false;
                /** @todo Improve by storing once and for all in table metadata */
                /** @todo Also re-use info for hasManyId */
                foreach($tableInfo->flds as $fld)
                {
-                       if($fld->name == $myId)
-                       {
+                       if($fld->name == $myId) {
                                $found = true;
                                break;
                        }
                        $index++;
                }
-               if(!$found)
+               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'])
-               {
-                       if(!empty($relations['belongsTo']))
-                       {
-                               foreach($relations['belongsTo'] as $foreignTable)
-                               {
-                                       if(($k = reset($foreignTable->TableInfo()->keys)))
-                                       {
+               if(ADODB_JOIN_AR == $extra['loading']) {
+                       if(!empty($relations['belongsTo'])) {
+                               foreach($relations['belongsTo'] as $foreignTable) {
+                                       if(($k = reset($foreignTable->TableInfo()->keys))) {
                                                $belongsToId = $k;
                                        }
-                                       else
-                                       {
+                                       else {
                                                $belongsToId = 'id';
                                        }
 
@@ -1157,27 +1253,28 @@ function adodb_GetActiveRecordsClass(&$db, $class, $tableObj,$whereOrderBy,$bind
                                                $foreignTable->_table.'.'.$belongsToId;
                                }
                        }
-                       if(!empty($relations['hasMany']))
-                       {
-                               if(empty($relations['foreignName']))
+                       if(!empty($relations['hasMany'])) {
+                               if(empty($relations['foreignName'])) {
                                        $db->outp_throw("Missing foreignName is relation specification in GetActiveRecordsClass()",'GetActiveRecordsClass');
-                               if(($k = reset($tableInfo->keys)))
+                               }
+                               if(($k = reset($tableInfo->keys))) {
                                        $hasManyId   = $k;
-                               else
+                               }
+                               else {
                                        $hasManyId   = 'id';
+                               }
 
-                               foreach($relations['hasMany'] as $foreignTable)
-                               {
+                               foreach($relations['hasMany'] as $foreignTable) {
                                        $qry .= ' LEFT JOIN '.$foreignTable->_table.' ON '.
                                                $table.'.'.$hasManyId.'='.
                                                $foreignTable->_table.'.'.$foreignTable->foreignKey;
                                }
                        }
                }
-               if (!empty($whereOrderBy))
+               if (!empty($whereOrderBy)) {
                        $qry .= ' WHERE '.$whereOrderBy;
-               if(isset($extra['limit']))
-               {
+               }
+               if(isset($extra['limit'])) {
                        $rows = false;
                        if(isset($extra['offset'])) {
                                $rs = $db->SelectLimit($qry, $extra['limit'], $extra['offset']);
@@ -1237,59 +1334,55 @@ function adodb_GetActiveRecordsClass(&$db, $class, $tableObj,$whereOrderBy,$bind
                        // Note: to-many relationships mess around with the 'limit' parameter
                        $rowId = intval($row[$index]);
 
-                       if(ADODB_WORK_AR == $extra['loading'])
-                       {
+                       if(ADODB_WORK_AR == $extra['loading']) {
                                $arrRef[$rowId] = $obj;
                                $arr[] = &$arrRef[$rowId];
-                               if(!isset($indices))
+                               if(!isset($indices)) {
                                        $indices = $rowId;
-                               else
+                               }
+                               else {
                                        $indices .= ','.$rowId;
-                               if(!empty($relations['belongsTo']))
-                               {
-                                       foreach($relations['belongsTo'] as $foreignTable)
-                                       {
+                               }
+                               if(!empty($relations['belongsTo'])) {
+                                       foreach($relations['belongsTo'] as $foreignTable) {
                                                $foreignTableRef = $foreignTable->foreignKey;
                                                // First array: list of foreign ids we are looking for
-                                               if(empty($bTos[$foreignTableRef]))
+                                               if(empty($bTos[$foreignTableRef])) {
                                                        $bTos[$foreignTableRef] = array();
+                                               }
                                                // Second array: list of ids found
-                                               if(empty($obj->$foreignTableRef))
+                                               if(empty($obj->$foreignTableRef)) {
                                                        continue;
-                                               if(empty($bTos[$foreignTableRef][$obj->$foreignTableRef]))
+                                               }
+                                               if(empty($bTos[$foreignTableRef][$obj->$foreignTableRef])) {
                                                        $bTos[$foreignTableRef][$obj->$foreignTableRef] = array();
+                                               }
                                                $bTos[$foreignTableRef][$obj->$foreignTableRef][] = $obj;
                                        }
                                }
                                continue;
                        }
 
-                       if($rowId>0)
-                       {
-                               if(ADODB_JOIN_AR == $extra['loading'])
-                               {
+                       if($rowId>0) {
+                               if(ADODB_JOIN_AR == $extra['loading']) {
                                        $isNewObj = !isset($uniqArr['_'.$row[0]]);
-                                       if($isNewObj)
+                                       if($isNewObj) {
                                                $uniqArr['_'.$row[0]] = $obj;
+                                       }
 
                                        // TODO Copy/paste code below: bad!
-                                       if(!empty($relations['hasMany']))
-                                       {
-                                               foreach($relations['hasMany'] as $foreignTable)
-                                               {
+                                       if(!empty($relations['hasMany'])) {
+                                               foreach($relations['hasMany'] as $foreignTable) {
                                                        $foreignName = $foreignTable->foreignName;
-                                                       if(!empty($obj->$foreignName))
-                                                       {
+                                                       if(!empty($obj->$foreignName)) {
                                                                $masterObj = &$uniqArr['_'.$row[0]];
                                                                // Assumption: this property exists in every object since they are instances of the same class
-                                                               if(!is_array($masterObj->$foreignName))
-                                                               {
+                                                               if(!is_array($masterObj->$foreignName)) {
                                                                        // Pluck!
                                                                        $foreignObj = $masterObj->$foreignName;
                                                                        $masterObj->$foreignName = array(clone($foreignObj));
                                                                }
-                                                               else
-                                                               {
+                                                               else {
                                                                        // Pluck pluck!
                                                                        $foreignObj = $obj->$foreignName;
                                                                        array_push($masterObj->$foreignName, clone($foreignObj));
@@ -1297,23 +1390,18 @@ function adodb_GetActiveRecordsClass(&$db, $class, $tableObj,$whereOrderBy,$bind
                                                        }
                                                }
                                        }
-                                       if(!empty($relations['belongsTo']))
-                                       {
-                                               foreach($relations['belongsTo'] as $foreignTable)
-                                               {
+                                       if(!empty($relations['belongsTo'])) {
+                                               foreach($relations['belongsTo'] as $foreignTable) {
                                                        $foreignName = $foreignTable->foreignName;
-                                                       if(!empty($obj->$foreignName))
-                                                       {
+                                                       if(!empty($obj->$foreignName)) {
                                                                $masterObj = &$uniqArr['_'.$row[0]];
                                                                // Assumption: this property exists in every object since they are instances of the same class
-                                                               if(!is_array($masterObj->$foreignName))
-                                                               {
+                                                               if(!is_array($masterObj->$foreignName)) {
                                                                        // Pluck!
                                                                        $foreignObj = $masterObj->$foreignName;
                                                                        $masterObj->$foreignName = array(clone($foreignObj));
                                                                }
-                                                               else
-                                                               {
+                                                               else {
                                                                        // Pluck pluck!
                                                                        $foreignObj = $obj->$foreignName;
                                                                        array_push($masterObj->$foreignName, clone($foreignObj));
@@ -1321,34 +1409,28 @@ function adodb_GetActiveRecordsClass(&$db, $class, $tableObj,$whereOrderBy,$bind
                                                        }
                                                }
                                        }
-                                       if(!$isNewObj)
+                                       if(!$isNewObj) {
                                                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'])
-                               {
+                               else if(ADODB_LAZY_AR == $extra['loading']) {
                                        // Lazy loading: we need to give AdoDb a hint that we have not really loaded
                                        // anything, all the while keeping enough information on what we wish to load.
                                        // Let's do this by keeping the relevant info in our relationship arrays
                                        // but get rid of the actual properties.
                                        // We will then use PHP's __get to load these properties on-demand.
-                                       if(!empty($relations['hasMany']))
-                                       {
-                                               foreach($relations['hasMany'] as $foreignTable)
-                                               {
+                                       if(!empty($relations['hasMany'])) {
+                                               foreach($relations['hasMany'] as $foreignTable) {
                                                        $foreignName = $foreignTable->foreignName;
-                                                       if(!empty($obj->$foreignName))
-                                                       {
+                                                       if(!empty($obj->$foreignName)) {
                                                                unset($obj->$foreignName);
                                                        }
                                                }
                                        }
-                                       if(!empty($relations['belongsTo']))
-                                       {
-                                               foreach($relations['belongsTo'] as $foreignTable)
-                                               {
+                                       if(!empty($relations['belongsTo'])) {
+                                               foreach($relations['belongsTo'] as $foreignTable) {
                                                        $foreignName = $foreignTable->foreignName;
-                                                       if(!empty($obj->$foreignName))
-                                                       {
+                                                       if(!empty($obj->$foreignName)) {
                                                                unset($obj->$foreignName);
                                                        }
                                                }
@@ -1356,47 +1438,42 @@ function adodb_GetActiveRecordsClass(&$db, $class, $tableObj,$whereOrderBy,$bind
                                }
                        }
 
-                       if(isset($obj))
+                       if(isset($obj)) {
                                $arr[] = $obj;
+                       }
                }
 
-               if(ADODB_WORK_AR == $extra['loading'])
-               {
+               if(ADODB_WORK_AR == $extra['loading']) {
                        // The best of both worlds?
                        // Here, the number of queries is constant: 1 + n*relationship.
                        // The second query will allow us to perform a good join
                        // while preserving LIMIT etc.
-                       if(!empty($relations['hasMany']))
-                       {
-                               foreach($relations['hasMany'] as $foreignTable)
-                               {
+                       if(!empty($relations['hasMany'])) {
+                               foreach($relations['hasMany'] as $foreignTable) {
                                        $foreignName = $foreignTable->foreignName;
                                        $className = ucfirst($foreignTable->_singularize($foreignName));
                                        $obj = new $className();
                                        $dbClassRef = $foreignTable->foreignKey;
                                        $objs = $obj->packageFind($dbClassRef.' IN ('.$indices.')');
-                                       foreach($objs as $obj)
-                                       {
-                                               if(!is_array($arrRef[$obj->$dbClassRef]->$foreignName))
+                                       foreach($objs as $obj) {
+                                               if(!is_array($arrRef[$obj->$dbClassRef]->$foreignName)) {
                                                        $arrRef[$obj->$dbClassRef]->$foreignName = array();
+                                               }
                                                array_push($arrRef[$obj->$dbClassRef]->$foreignName, $obj);
                                        }
                                }
 
                        }
-                       if(!empty($relations['belongsTo']))
-                       {
-                               foreach($relations['belongsTo'] as $foreignTable)
-                               {
+                       if(!empty($relations['belongsTo'])) {
+                               foreach($relations['belongsTo'] as $foreignTable) {
                                        $foreignTableRef = $foreignTable->foreignKey;
-                                       if(empty($bTos[$foreignTableRef]))
+                                       if(empty($bTos[$foreignTableRef])) {
                                                continue;
-                                       if(($k = reset($foreignTable->TableInfo()->keys)))
-                                       {
+                                       }
+                                       if(($k = reset($foreignTable->TableInfo()->keys))) {
                                                $belongsToId = $k;
                                        }
-                                       else
-                                       {
+                                       else {
                                                $belongsToId = 'id';
                                        }
                                        $origObjsArr = $bTos[$foreignTableRef];
index d70c16f..a379450 100644 (file)
@@ -8,7 +8,9 @@ $ADODB_INCLUDED_CSV = 1;
 
 /*
 
-  V5.19  23-Apr-2014  (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved.
+  @version   v5.20.1  06-Dec-2015
+  @copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
+  @copyright (c) 2014      Damien Regad, Mark Newnham and the ADOdb community
   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.
@@ -292,7 +294,7 @@ $ADODB_INCLUDED_CSV = 1;
                                // the tricky moment
                                @unlink($filename);
                                if (!@rename($tmpname,$filename)) {
-                                       unlink($tmpname);
+                                       @unlink($tmpname);
                                        $ok = 0;
                                }
                                if (!$ok) {
index b8b881e..7810bdb 100644 (file)
@@ -1,7 +1,9 @@
 <?php
 
 /**
-  V5.19  23-Apr-2014  (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved.
+  @version   v5.20.1  06-Dec-2015
+  @copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
+  @copyright (c) 2014      Damien Regad, Mark Newnham and the ADOdb community
   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 29c6a9c..b149092 100644 (file)
@@ -1,6 +1,8 @@
 <?php
 /**
- * @version V5.19  23-Apr-2014  (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved.
+ * @version   v5.20.1  06-Dec-2015
+ * @copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
+ * @copyright (c) 2014      Damien Regad, Mark Newnham and the ADOdb community
  * 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 680e76d..8bf0af4 100644 (file)
@@ -1,6 +1,8 @@
 <?php
 /**
- * @version V5.19  23-Apr-2014  (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved.
+ * @version   v5.20.1  06-Dec-2015
+ * @copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
+ * @copyright (c) 2014      Damien Regad, Mark Newnham and the ADOdb community
  * 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 10dbb97..dce7c73 100644 (file)
@@ -1,6 +1,8 @@
 <?php
 /**
- * @version V5.19  23-Apr-2014  (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved.
+ * @version   v5.20.1  06-Dec-2015
+ * @copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
+ * @copyright (c) 2014      Damien Regad, Mark Newnham and the ADOdb community
  * 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 2300f11..eb14b78 100644 (file)
@@ -1,7 +1,9 @@
 <?php
 
 /**
- * @version V5.19  23-Apr-2014  (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved.
+ * @version   v5.20.1  06-Dec-2015
+ * @copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
+ * @copyright (c) 2014      Damien Regad, Mark Newnham and the ADOdb community
  * 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.
@@ -29,9 +31,9 @@ var $database = '';
        {
                switch($fn) {
                case 'EXECUTE':
-                       $this->sql = $p1;
+                       $this->sql = is_array($p1) ? $p1[0] : $p1;
                        $this->params = $p2;
-                       $s = "$dbms error: [$errno: $errmsg] in $fn(\"$p1\")\n";
+                       $s = "$dbms error: [$errno: $errmsg] in $fn(\"$this->sql\")\n";
                        break;
 
                case 'PCONNECT':
index 2d26326..164dfb2 100644 (file)
@@ -1,7 +1,9 @@
 <?php
 
 /*
-  V5.19  23-Apr-2014  (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved.
+  @version   v5.20.1  06-Dec-2015
+  @copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
+  @copyright (c) 2014      Damien Regad, Mark Newnham and the ADOdb community
   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 de35bc9..dc404b5 100644 (file)
@@ -6,7 +6,9 @@ global $ADODB_INCLUDED_LIB;
 $ADODB_INCLUDED_LIB = 1;
 
 /*
-  @version V5.19  23-Apr-2014  (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved.
+  @version   v5.20.1  06-Dec-2015
+  @copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
+  @copyright (c) 2014      Damien Regad, Mark Newnham and the ADOdb community
   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.
@@ -17,7 +19,7 @@ $ADODB_INCLUDED_LIB = 1;
 
 function adodb_strip_order_by($sql)
 {
-       $rez = preg_match('/(\sORDER\s+BY\s(?:[^)](?!limit))*)(?:\sLIMIT\s+[0-9]+)?/is', $sql, $arr);
+       $rez = preg_match('/(\sORDER\s+BY\s(?:[^)](?!LIMIT))*)/is', $sql, $arr);
        if ($arr)
                if (strpos($arr[1], '(') !== false) {
                        $at = strpos($sql, $arr[1]);
@@ -38,7 +40,7 @@ function adodb_strip_order_by($sql)
                        $sql = str_replace($arr[1], '', $sql);
                }
        return $sql;
- }
+}
 
 if (false) {
        $sql = 'select * from (select a from b order by a(b),b(c) desc)';
@@ -421,8 +423,11 @@ function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0)
                }
        } else {
                // now replace SELECT ... FROM with SELECT COUNT(*) FROM
-               $rewritesql = preg_replace(
-                                       '/^\s*SELECT\s.*\s+FROM\s/Uis','SELECT COUNT(*) FROM ',$sql);
+               if ( strpos($sql, '_ADODB_COUNT') !== FALSE ) {
+                       $rewritesql = preg_replace('/^\s*?SELECT\s+_ADODB_COUNT(.*)_ADODB_COUNT\s/is','SELECT COUNT(*) ',$sql);
+               } else {
+                       $rewritesql = preg_replace('/^\s*?SELECT\s.*?\s+(.*?)\s+FROM\s/is','SELECT COUNT(*) FROM ',$sql);
+               }
                // 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
@@ -543,46 +548,86 @@ function _adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page,
        return $rsreturn;
 }
 
-// Iván Oliva version
+// Iván Oliva version
 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
+       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
-       // the last page number.
-       $pagecounter = $page + 1;
-       $pagecounteroffset = ($pagecounter * $nrows) - $nrows;
-       if ($secs2cache>0) $rstest = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
-       else $rstest = $zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
-       if ($rstest) {
-               while ($rstest && $rstest->EOF && $pagecounter>0) {
-                       $atlastpage = true;
-                       $pagecounter--;
-                       $pagecounteroffset = $nrows * ($pagecounter - 1);
-                       $rstest->Close();
-                       if ($secs2cache>0) $rstest = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
-                       else $rstest = $zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
-               }
-               if ($rstest) $rstest->Close();
+       if ($nrows <= 0) {
+               // If an invalid nrows is supplied, we assume a default value of 10 rows per page
+               $nrows = 10;
        }
-       if ($atlastpage) {      // If we are at the last page or beyond it, we are going to retrieve it
-               $page = $pagecounter;
-               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.
+
+       $pagecounteroffset = ($page * $nrows) - $nrows;
+
+       // To find out if there are more pages of rows, simply increase the limit or
+       // nrows by 1 and see if that number of records was returned. If it was,
+       // then we know there is at least one more page left, otherwise we are on
+       // the last page. Therefore allow non-Count() paging with single queries
+       // rather than three queries as was done before.
+       $test_nrows = $nrows + 1;
+       if ($secs2cache > 0) {
+               $rsreturn = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
+       } else {
+               $rsreturn = $zthis->SelectLimit($sql, $test_nrows, $pagecounteroffset, $inputarr, $secs2cache);
        }
 
-       // 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);
+       // Now check to see if the number of rows returned was the higher value we asked for or not.
+       if ( $rsreturn->_numOfRows == $test_nrows ) {
+               // Still at least 1 more row, so we are not on last page yet...
+               // Remove the last row from the RS.
+               $rsreturn->_numOfRows = ( $rsreturn->_numOfRows - 1 );
+       } elseif ( $rsreturn->_numOfRows == 0 && $page > 1 ) {
+               // Likely requested a page that doesn't exist, so need to find the last
+               // page and return it. Revert to original method and loop through pages
+               // until we find some data...
+               $pagecounter = $page + 1;
+               $pagecounteroffset = ($pagecounter * $nrows) - $nrows;
+
+               $rstest = $rsreturn;
+               if ($rstest) {
+                       while ($rstest && $rstest->EOF && $pagecounter > 0) {
+                               $atlastpage = true;
+                               $pagecounter--;
+                               $pagecounteroffset = $nrows * ($pagecounter - 1);
+                               $rstest->Close();
+                               if ($secs2cache>0) {
+                                       $rstest = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
+                               }
+                               else {
+                                       $rstest = $zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
+                               }
+                       }
+                       if ($rstest) $rstest->Close();
+               }
+               if ($atlastpage) {
+                       // If we are at the last page or beyond it, we are going to retrieve it
+                       $page = $pagecounter;
+                       if ($page == 1) {
+                               // 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.
+                               $atfirstpage = true;
+                       }
+               }
+               // 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);
+               }
+       } elseif ( $rsreturn->_numOfRows < $test_nrows ) {
+               // Rows is less than what we asked for, so must be at the last page.
+               $atlastpage = true;
+       }
 
        // Before returning the RecordSet, we set the pagination properties we need
        if ($rsreturn) {
index 6e0040d..25f0fe6 100644 (file)
@@ -7,11 +7,13 @@ global $ADODB_INCLUDED_MEMCACHE;
 $ADODB_INCLUDED_MEMCACHE = 1;
 
 global $ADODB_INCLUDED_CSV;
-if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
+if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
 
 /*
 
-  V5.19  23-Apr-2014  (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved.
+  @version   v5.20.1  06-Dec-2015
+  @copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
+  @copyright (c) 2014      Damien Regad, Mark Newnham and the ADOdb community
   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.
@@ -48,7 +50,7 @@ $db->CacheExecute($sql);
                var $_connected = false;
                var $_memcache = false;
 
-               function ADODB_Cache_MemCache(&$obj)
+               function __construct(&$obj)
                {
                        $this->hosts = $obj->memCacheHost;
                        $this->port = $obj->memCachePort;
index a08ced4..bdb2ca3 100644 (file)
@@ -1,7 +1,9 @@
 <?php
 
 /*
-       V5.19  23-Apr-2014  (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved.
+       @version   v5.20.1  06-Dec-2015
+       @copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
+       @copyright (c) 2014      Damien Regad, Mark Newnham and the ADOdb community
          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.
@@ -55,7 +57,7 @@ class ADODB_Pager {
        //              if you have multiple on 1 page.
        //              $id should be only be [a-z0-9]*
        //
-       function ADODB_Pager(&$db,$sql,$id = 'adodb', $showPageLinks = false)
+       function __construct(&$db,$sql,$id = 'adodb', $showPageLinks = false)
        {
        global $PHP_SELF;
 
index 49ba936..edf1548 100644 (file)
@@ -1,6 +1,8 @@
 <?php
 /**
- * @version V5.19  23-Apr-2014  (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved.
+ * @version   v5.20.1  06-Dec-2015
+ * @copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
+ * @copyright (c) 2014      Damien Regad, Mark Newnham and the ADOdb community
  * 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.
@@ -52,10 +54,6 @@ if (!defined('DB_OK')) {
 define("DB_OK",        1);
 define("DB_ERROR",-1);
 
-// autoExecute constants
-define('DB_AUTOQUERY_INSERT', 1);
-define('DB_AUTOQUERY_UPDATE', 2);
-
 /**
  * This is a special constant that tells DB the user hasn't specified
  * any particular get mode, so the default should be used.
index 8e6e6cc..6a98678 100644 (file)
@@ -1,6 +1,8 @@
 <?php
 /*
-V5.19  23-Apr-2014  (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved.
+@version   v5.20.1  06-Dec-2015
+@copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
+@copyright (c) 2014      Damien Regad, Mark Newnham and the ADOdb community
   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.
@@ -224,7 +226,7 @@ class adodb_perf {
        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 $helpurl = '<a href="http://adodb.sourceforge.net/docs-adodb.htm#logsql">LogSQL help</a>';
        var $createTableSQL = false;
        var $maxLength = 2000;
 
index e999983..ab47b2c 100644 (file)
@@ -1,7 +1,9 @@
 <?php
 
 /*
-  V5.19  23-Apr-2014  (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved.
+  @version   v5.20.1  06-Dec-2015
+  @copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
+  @copyright (c) 2014      Damien Regad, Mark Newnham and the ADOdb community
   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 c74778b..c8f4ae5 100644 (file)
@@ -1,7 +1,11 @@
 <?php
-/**
+/*
 ADOdb Date Library, part of the ADOdb abstraction library
-Download: http://phplens.com/phpeverywhere/
+Download: http://adodb.sourceforge.net/#download
+
+@version   v5.20.1  06-Dec-2015
+@copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
+@copyright (c) 2014      Damien Regad, Mark Newnham and the ADOdb community
 
 PHP native date functions use integer timestamps for computations.
 Because of this, dates are restricted to the years 1901-2038 on Unix
index 72a9f9b..0890155 100644 (file)
@@ -118,7 +118,7 @@ class dbObject {
        /**
        * NOP
        */
-       function dbObject( &$parent, $attributes = NULL ) {
+       function __construct( &$parent, $attributes = NULL ) {
                $this->parent = $parent;
        }
 
@@ -248,7 +248,7 @@ class dbTable extends dbObject {
        * @param string $prefix DB Object prefix
        * @param array $attributes Array of table attributes.
        */
-       function dbTable( &$parent, $attributes = NULL ) {
+       function __construct( &$parent, $attributes = NULL ) {
                $this->parent = $parent;
                $this->name = $this->prefix($attributes['NAME']);
        }
@@ -642,7 +642,7 @@ class dbIndex extends dbObject {
        *
        * @internal
        */
-       function dbIndex( &$parent, $attributes = NULL ) {
+       function __construct( &$parent, $attributes = NULL ) {
                $this->parent = $parent;
 
                $this->name = $this->prefix ($attributes['NAME']);
@@ -786,7 +786,7 @@ class dbData extends dbObject {
        *
        * @internal
        */
-       function dbData( &$parent, $attributes = NULL ) {
+       function __construct( &$parent, $attributes = NULL ) {
                $this->parent = $parent;
        }
 
@@ -985,7 +985,7 @@ class dbQuerySet extends dbObject {
        * @param object $parent Parent object
        * @param array $attributes Attributes
        */
-       function dbQuerySet( &$parent, $attributes = NULL ) {
+       function __construct( &$parent, $attributes = NULL ) {
                $this->parent = $parent;
 
                // Overrides the manual prefix key
@@ -1301,7 +1301,7 @@ class adoSchema {
        *
        * @param object $db ADOdb database connection object.
        */
-       function adoSchema( $db ) {
+       function __construct( $db ) {
                // Initialize the environment
                $this->mgq = get_magic_quotes_runtime();
                ini_set("magic_quotes_runtime", 0);
index 3ed5aec..45a59bb 100644 (file)
@@ -136,7 +136,7 @@ class dbObject {
        /**
        * NOP
        */
-       function dbObject( &$parent, $attributes = NULL ) {
+       function __construct( &$parent, $attributes = NULL ) {
                $this->parent = $parent;
        }
 
@@ -273,7 +273,7 @@ class dbTable extends dbObject {
        * @param string $prefix DB Object prefix
        * @param array $attributes Array of table attributes.
        */
-       function dbTable( &$parent, $attributes = NULL ) {
+       function __construct( &$parent, $attributes = NULL ) {
                $this->parent = $parent;
                $this->name = $this->prefix($attributes['NAME']);
        }
@@ -683,7 +683,7 @@ class dbIndex extends dbObject {
        *
        * @internal
        */
-       function dbIndex( &$parent, $attributes = NULL ) {
+       function __construct( &$parent, $attributes = NULL ) {
                $this->parent = $parent;
 
                $this->name = $this->prefix ($attributes['NAME']);
@@ -828,7 +828,7 @@ class dbData extends dbObject {
        *
        * @internal
        */
-       function dbData( &$parent, $attributes = NULL ) {
+       function __construct( &$parent, $attributes = NULL ) {
                $this->parent = $parent;
        }
 
@@ -1084,7 +1084,7 @@ class dbQuerySet extends dbObject {
        * @param object $parent Parent object
        * @param array $attributes Attributes
        */
-       function dbQuerySet( &$parent, $attributes = NULL ) {
+       function __construct( &$parent, $attributes = NULL ) {
                $this->parent = $parent;
 
                // Overrides the manual prefix key
@@ -1405,7 +1405,7 @@ class adoSchema {
        *
        * @param object $db ADOdb database connection object.
        */
-       function adoSchema( $db ) {
+       function __construct( $db ) {
                // Initialize the environment
                $this->mgq = get_magic_quotes_runtime();
                #set_magic_quotes_runtime(0);
@@ -2104,11 +2104,12 @@ class adoSchema {
 
                $schema = '<?xml version="1.0"?>' . "\n"
                                . '<schema version="' . $this->schemaVersion . '">' . "\n";
-
-               if( is_array( $tables = $this->db->MetaTables( 'TABLES' , ($prefix) ? $prefix.'%' : '') ) ) {
+               if( is_array( $tables = $this->db->MetaTables( 'TABLES' ,false ,($prefix) ? str_replace('_','\_',$prefix).'%' : '') ) ) {
                        foreach( $tables as $table ) {
-                               if ($stripprefix) $table = str_replace(str_replace('\\_', '_', $pfx ), '', $table);
-                               $schema .= $indent . '<table name="' . htmlentities( $table ) . '">' . "\n";
+                               $schema .= $indent
+                                       . '<table name="'
+                                       . htmlentities( $stripprefix ? str_replace($prefix, '', $table) : $table )
+                                       . '">' . "\n";
 
                                // grab details from database
                                $rs = $this->db->Execute( 'SELECT * FROM ' . $table . ' WHERE -1' );
index a561772..eec531b 100644 (file)
@@ -14,7 +14,9 @@
 /**
        \mainpage
 
-        @version V5.19  23-Apr-2014  (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved.
+       @version   v5.20.1  06-Dec-2015
+       @copyright (c) 2000-2013 John Lim (jlim#natsoft.com). All rights reserved.
+       @copyright (c) 2014      Damien Regad, Mark Newnham and the ADOdb community
 
        Released under both BSD license and Lesser GPL library license. You can choose which license
        you prefer.
@@ -44,21 +46,23 @@ if (!defined('_ADODB_LAYER')) {
         * Set ADODB_DIR to the directory where this file resides...
         * This constant was formerly called $ADODB_RootPath
         */
-       if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__));
+       if (!defined('ADODB_DIR')) {
+               define('ADODB_DIR',dirname(__FILE__));
+       }
 
        //==============================================================================================
        // GLOBAL VARIABLES
        //==============================================================================================
 
        GLOBAL
-               $ADODB_vers,            // database version
+               $ADODB_vers,            // database version
                $ADODB_COUNTRECS,       // count number of records returned - slows down query
                $ADODB_CACHE_DIR,       // directory to cache recordsets
                $ADODB_CACHE,
                $ADODB_CACHE_CLASS,
                $ADODB_EXTENSION,   // ADODB extension installed
                $ADODB_COMPAT_FETCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF
-               $ADODB_FETCH_MODE,      // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...
+               $ADODB_FETCH_MODE,      // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...
                $ADODB_GETONE_EOF,
                $ADODB_QUOTE_FIELDNAMES; // Allows you to force quotes (backticks) around field names in queries generated by getinsertsql and getupdatesql.
 
@@ -92,27 +96,59 @@ if (!defined('_ADODB_LAYER')) {
                define('ADODB_TABLE_REGEX','([]0-9a-z_\:\"\`\.\@\[-]*)');
 
        // prefetching used by oracle
-               if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10);
+               if (!defined('ADODB_PREFETCH_ROWS')) {
+                       define('ADODB_PREFETCH_ROWS',10);
+               }
 
 
-       /*
-       Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names.
-       This currently works only with mssql, odbc, oci8po and ibase derived drivers.
+       /**
+        * Fetch mode
+        *
+        * Set global variable $ADODB_FETCH_MODE to one of these constants or use
+        * the SetFetchMode() method to control how recordset fields are returned
+        * when fetching data.
+        *
+        *   - NUM:     array()
+        *   - ASSOC:   array('id' => 456, 'name' => 'john')
+        *   - BOTH:    array(0 => 456, 'id' => 456, 1 => 'john', 'name' => 'john')
+        *   - DEFAULT: driver-dependent
+        */
+               define('ADODB_FETCH_DEFAULT', 0);
+               define('ADODB_FETCH_NUM', 1);
+               define('ADODB_FETCH_ASSOC', 2);
+               define('ADODB_FETCH_BOTH', 3);
 
-               0 = assoc lowercase field names. $rs->fields['orderid']
-               1 = assoc uppercase field names. $rs->fields['ORDERID']
-               2 = use native-case field names. $rs->fields['OrderID']
-       */
+       /**
+        * Associative array case constants
+        *
+        * By defining the ADODB_ASSOC_CASE constant to one of these values, it is
+        * possible to control the case of field names (associative array's keys)
+        * when operating in ADODB_FETCH_ASSOC fetch mode.
+        *   - LOWER:  $rs->fields['orderid']
+        *   - UPPER:  $rs->fields['ORDERID']
+        *   - NATIVE: $rs->fields['OrderID'] (or whatever the RDBMS will return)
+        *
+        * The default is to use native case-names.
+        *
+        * NOTE: This functionality is not implemented everywhere, it currently
+        * works only with: mssql, odbc, oci8 and ibase derived drivers
+        */
                define('ADODB_ASSOC_CASE_LOWER', 0);
                define('ADODB_ASSOC_CASE_UPPER', 1);
                define('ADODB_ASSOC_CASE_NATIVE', 2);
 
-               define('ADODB_FETCH_DEFAULT',0);
-               define('ADODB_FETCH_NUM',1);
-               define('ADODB_FETCH_ASSOC',2);
-               define('ADODB_FETCH_BOTH',3);
 
-               if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
+               if (!defined('TIMESTAMP_FIRST_YEAR')) {
+                       define('TIMESTAMP_FIRST_YEAR',100);
+               }
+
+               /**
+                * AutoExecute constants
+                * (moved from adodb-pear.inc.php since they are only used in here)
+                */
+               define('DB_AUTOQUERY_INSERT', 1);
+               define('DB_AUTOQUERY_UPDATE', 2);
+
 
                // PHP's version scheme makes converting to numbers difficult - workaround
                $_adodb_ver = (float) PHP_VERSION;
@@ -120,20 +156,20 @@ if (!defined('_ADODB_LAYER')) {
                        define('ADODB_PHPVER',0x5200);
                } else if ($_adodb_ver >= 5.0) {
                        define('ADODB_PHPVER',0x5000);
-               } else
+               } else {
                        die("PHP5 or later required. You are running ".PHP_VERSION);
+               }
+               unset($_adodb_ver);
        }
 
 
-       //if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
-
-
        /**
-               Accepts $src and $dest arrays, replacing string $data
+               Accepts $src and $dest arrays, replacing string $data
        */
-       function ADODB_str_replace($src, $dest, $data)
-       {
-               if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data);
+       function ADODB_str_replace($src, $dest, $data) {
+               if (ADODB_PHPVER >= 0x4050) {
+                       return str_replace($src,$dest,$data);
+               }
 
                $s = reset($src);
                $d = reset($dest);
@@ -145,20 +181,21 @@ if (!defined('_ADODB_LAYER')) {
                return $data;
        }
 
-       function ADODB_Setup()
-       {
+       function ADODB_Setup() {
        GLOBAL
-               $ADODB_vers,            // database version
+               $ADODB_vers,            // database version
                $ADODB_COUNTRECS,       // count number of records returned - slows down query
                $ADODB_CACHE_DIR,       // directory to cache recordsets
-               $ADODB_FETCH_MODE,
+               $ADODB_FETCH_MODE,
                $ADODB_CACHE,
                $ADODB_CACHE_CLASS,
                $ADODB_FORCE_TYPE,
                $ADODB_GETONE_EOF,
                $ADODB_QUOTE_FIELDNAMES;
 
-               if (empty($ADODB_CACHE_CLASS)) $ADODB_CACHE_CLASS =  'ADODB_Cache_File' ;
+               if (empty($ADODB_CACHE_CLASS)) {
+                       $ADODB_CACHE_CLASS =  'ADODB_Cache_File' ;
+               }
                $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT;
                $ADODB_FORCE_TYPE = ADODB_FORCE_VALUE;
                $ADODB_GETONE_EOF = null;
@@ -167,8 +204,9 @@ if (!defined('_ADODB_LAYER')) {
                        $ADODB_CACHE_DIR = '/tmp'; //(isset($_ENV['TMP'])) ? $_ENV['TMP'] : '/tmp';
                } else {
                        // do not accept url based paths, eg. http:/ or ftp:/
-                       if (strpos($ADODB_CACHE_DIR,'://') !== false)
+                       if (strpos($ADODB_CACHE_DIR,'://') !== false) {
                                die("Illegal path http:// or ftp://");
+                       }
                }
 
 
@@ -180,14 +218,16 @@ if (!defined('_ADODB_LAYER')) {
                /**
                 * ADODB version as a string.
                 */
-               $ADODB_vers = 'V5.19  23-Apr-2014  (c) 2000-2014 John Lim (jlim#natsoft.com). All rights reserved. Released BSD & LGPL.';
+               $ADODB_vers = 'v5.20.1  06-Dec-2015';
 
                /**
                 * Determines whether recordset->RecordCount() is used.
                 * Set to false for highest performance -- RecordCount() will always return -1 then
                 * for databases that provide "virtual" recordcounts...
                 */
-               if (!isset($ADODB_COUNTRECS)) $ADODB_COUNTRECS = true;
+               if (!isset($ADODB_COUNTRECS)) {
+                       $ADODB_COUNTRECS = true;
+               }
        }
 
 
@@ -220,18 +260,19 @@ if (!defined('_ADODB_LAYER')) {
        }
 
 
-       function _adodb_safedate($s)
-       {
+       function _adodb_safedate($s) {
                return str_replace(array("'", '\\'), '', $s);
        }
 
        // parse date string to prevent injection attack
        // date string will have one quote at beginning e.g. '3434343'
-       function _adodb_safedateq($s)
-       {
+       function _adodb_safedateq($s) {
                $len = strlen($s);
-               if ($s[0] !== "'") $s2 = "'".$s[0];
-               else $s2 = "'";
+               if ($s[0] !== "'") {
+                       $s2 = "'".$s[0];
+               } else {
+                       $s2 = "'";
+               }
                for($i=1; $i<$len; $i++) {
                        $ch = $s[$i];
                        if ($ch === '\\') {
@@ -251,8 +292,7 @@ if (!defined('_ADODB_LAYER')) {
 
        // for transaction handling
 
-       function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
-       {
+       function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection) {
                //print "Errorno ($fn errno=$errno m=$errmsg) ";
                $thisConnection->_transOK = false;
                if ($thisConnection->_oldRaiseFn) {
@@ -267,63 +307,68 @@ if (!defined('_ADODB_LAYER')) {
 
                var $createdir = true; // requires creation of temp dirs
 
-               function ADODB_Cache_File()
-               {
-               global $ADODB_INCLUDED_CSV;
-                       if (empty($ADODB_INCLUDED_CSV)) include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
+               function __construct() {
+                       global $ADODB_INCLUDED_CSV;
+                       if (empty($ADODB_INCLUDED_CSV)) {
+                               include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
+                       }
                }
 
                // write serialised recordset to cache item/file
-               function writecache($filename, $contents,  $debug, $secs2cache)
-               {
+               function writecache($filename, $contents,  $debug, $secs2cache) {
                        return adodb_write_file($filename, $contents,$debug);
                }
 
                // load serialised recordset and unserialise it
-               function &readcache($filename, &$err, $secs2cache, $rsClass)
-               {
+               function &readcache($filename, &$err, $secs2cache, $rsClass) {
                        $rs = csv2rs($filename,$err,$secs2cache,$rsClass);
                        return $rs;
                }
 
                // flush all items in cache
-               function flushall($debug=false)
-               {
-               global $ADODB_CACHE_DIR;
+               function flushall($debug=false) {
+                       global $ADODB_CACHE_DIR;
 
-               $rez = false;
+                       $rez = false;
 
                        if (strlen($ADODB_CACHE_DIR) > 1) {
                                $rez = $this->_dirFlush($ADODB_CACHE_DIR);
-                       if ($debug) ADOConnection::outp( "flushall: $dir<br><pre>\n". $rez."</pre>");
-                       }
+                               if ($debug) {
+                                       ADOConnection::outp( "flushall: $ADODB_CACHE_DIR<br><pre>\n". $rez."</pre>");
+                               }
+                       }
                        return $rez;
                }
 
                // flush one file in cache
-               function flushcache($f, $debug=false)
-               {
+               function flushcache($f, $debug=false) {
                        if (!@unlink($f)) {
-                               if ($debug) ADOConnection::outp( "flushcache: failed for $f");
+                               if ($debug) {
+                                       ADOConnection::outp( "flushcache: failed for $f");
+                               }
                        }
                }
 
-               function getdirname($hash)
-               {
-               global $ADODB_CACHE_DIR;
-                       if (!isset($this->notSafeMode)) $this->notSafeMode = !ini_get('safe_mode');
+               function getdirname($hash) {
+                       global $ADODB_CACHE_DIR;
+                       if (!isset($this->notSafeMode)) {
+                               $this->notSafeMode = !ini_get('safe_mode');
+                       }
                        return ($this->notSafeMode) ? $ADODB_CACHE_DIR.'/'.substr($hash,0,2) : $ADODB_CACHE_DIR;
                }
 
                // create temp directories
-               function createdir($hash, $debug)
-               {
-               global $ADODB_CACHE_PERMS;
+               function createdir($hash, $debug) {
+                       global $ADODB_CACHE_PERMS;
 
                        $dir = $this->getdirname($hash);
                        if ($this->notSafeMode && !file_exists($dir)) {
                                $oldu = umask(0);
-                               if (!@mkdir($dir, empty($ADODB_CACHE_PERMS) ? 0771 : $ADODB_CACHE_PERMS)) if(!is_dir($dir) && $debug) ADOConnection::outp("Cannot create $dir");
+                               if (!@mkdir($dir, empty($ADODB_CACHE_PERMS) ? 0771 : $ADODB_CACHE_PERMS)) {
+                                       if(!is_dir($dir) && $debug) {
+                                               ADOConnection::outp("Cannot create $dir");
+                                       }
+                               }
                                umask($oldu);
                        }
 
@@ -336,19 +381,24 @@ if (!defined('_ADODB_LAYER')) {
                * Just specify the directory, and tell it if you want to delete the directory or just clear it out.
                * Note: $kill_top_level is used internally in the function to flush subdirectories.
                */
-               function _dirFlush($dir, $kill_top_level = false)
-               {
-                  if(!$dh = @opendir($dir)) return;
+               function _dirFlush($dir, $kill_top_level = false) {
+                       if(!$dh = @opendir($dir)) return;
 
-                  while (($obj = readdir($dh))) {
-                               if($obj=='.' || $obj=='..') continue;
+                       while (($obj = readdir($dh))) {
+                               if($obj=='.' || $obj=='..') continue;
                                $f = $dir.'/'.$obj;
 
-                               if (strpos($obj,'.cache')) @unlink($f);
-                               if (is_dir($f)) $this->_dirFlush($f, true);
-                  }
-                  if ($kill_top_level === true) @rmdir($dir);
-                  return true;
+                               if (strpos($obj,'.cache')) {
+                                       @unlink($f);
+                               }
+                               if (is_dir($f)) {
+                                       $this->_dirFlush($f, true);
+                               }
+                       }
+                       if ($kill_top_level === true) {
+                               @rmdir($dir);
+                       }
+                       return true;
                }
        }
 
@@ -366,11 +416,11 @@ if (!defined('_ADODB_LAYER')) {
        var $dataProvider = 'native';
        var $databaseType = '';         /// RDBMS currently in use, eg. odbc, mysql, mssql
        var $database = '';                     /// Name of database to be used.
-       var $host = '';                         /// The hostname of the database server
-       var $user = '';                         /// The username which is used to connect to the database server.
-       var $password = '';             /// Password for the username. For security, we no longer store it.
-       var $debug = false;             /// if set to true will output sql statements
-       var $maxblobsize = 262144;      /// maximum size of blobs or large text fields (262144 = 256K)-- some db's die otherwise like foxpro
+       var $host = '';                         /// The hostname of the database server
+       var $user = '';                         /// The username which is used to connect to the database server.
+       var $password = '';                     /// Password for the username. For security, we no longer store it.
+       var $debug = false;                     /// if set to true will output sql statements
+       var $maxblobsize = 262144;      /// maximum size of blobs or large text fields (262144 = 256K)-- some db's die otherwise like foxpro
        var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase
        var $substr = 'substr';         /// substring operator
        var $length = 'length';         /// string length ofperator
@@ -378,11 +428,11 @@ if (!defined('_ADODB_LAYER')) {
        var $upperCase = 'upper';               /// uppercase function
        var $fmtDate = "'Y-m-d'";       /// used by DBDate() as the default date format used by the database
        var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt.
-       var $true = '1';                        /// string that represents TRUE for a database
-       var $false = '0';                       /// string that represents FALSE for a database
-       var $replaceQuote = "\\'";      /// string to use to replace quotes
+       var $true = '1';                        /// string that represents TRUE for a database
+       var $false = '0';                       /// string that represents FALSE for a database
+       var $replaceQuote = "\\'";      /// string to use to replace quotes
        var $nameQuote = '"';           /// string to use to quote identifiers and names
-       var $charSet=false;             /// character set to use - only for interbase, postgres and oci8
+       var $charSet=false;                     /// character set to use - only for interbase, postgres and oci8
        var $metaDatabasesSQL = '';
        var $metaTablesSQL = '';
        var $uniqueOrderBy = false; /// All order by columns have to be unique
@@ -390,19 +440,19 @@ if (!defined('_ADODB_LAYER')) {
        var $emptyTimeStamp = '&nbsp;';
        var $lastInsID = false;
        //--
-       var $hasInsertID = false;               /// supports autoincrement ID?
-       var $hasAffectedRows = false;   /// supports affected rows for update/delete?
+       var $hasInsertID = false;               /// supports autoincrement ID?
+       var $hasAffectedRows = false;   /// supports affected rows for update/delete?
        var $hasTop = false;                    /// support mssql/access SELECT TOP 10 * FROM TABLE
        var $hasLimit = false;                  /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10
-       var $readOnly = false;                  /// this is a readonly database - used by phpLens
-       var $hasMoveFirst = false;  /// has ability to run MoveFirst(), scrolling backwards
-       var $hasGenID = false;          /// can generate sequences using GenID();
-       var $hasTransactions = true; /// has transactions
+       var $readOnly = false;                  /// this is a readonly database - used by phpLens
+       var $hasMoveFirst = false;              /// has ability to run MoveFirst(), scrolling backwards
+       var $hasGenID = false;                  /// can generate sequences using GenID();
+       var $hasTransactions = true;    /// has transactions
        //--
-       var $genID = 0;                         /// sequence id used by GenID();
-       var $raiseErrorFn = false;      /// error function to call
-       var $isoDates = false; /// accepts dates in ISO format
-       var $cacheSecs = 3600; /// cache for 1 hour
+       var $genID = 0;                                 /// sequence id used by GenID();
+       var $raiseErrorFn = false;              /// error function to call
+       var $isoDates = false;                  /// accepts dates in ISO format
+       var $cacheSecs = 3600;                  /// cache for 1 hour
 
        // memcache
        var $memCache = false; /// should we use memCache instead of caching in files
@@ -431,17 +481,17 @@ if (!defined('_ADODB_LAYER')) {
        var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char
        var $rsPrefix = "ADORecordSet_";
 
-       var $autoCommit = true;         /// do not modify this yourself - actually private
-       var $transOff = 0;                      /// temporarily disable transactions
-       var $transCnt = 0;                      /// count of nested transactions
+       var $autoCommit = true;         /// do not modify this yourself - actually private
+       var $transOff = 0;                      /// temporarily disable transactions
+       var $transCnt = 0;                      /// count of nested transactions
 
        var $fetchMode=false;
 
        var $null2null = 'null'; // in autoexecute/getinsertsql/getupdatesql, this value will be converted to a null
        var $bulkBind = false; // enable 2D Execute array
-        //
-        // PRIVATE VARS
-        //
+       //
+       // PRIVATE VARS
+       //
        var $_oldRaiseFn =  false;
        var $_transOK = null;
        var $_connectionID      = false;        /// The returned link identifier whenever a successful database connection is made.
@@ -457,14 +507,50 @@ if (!defined('_ADODB_LAYER')) {
        var $_logsql = false;
        var $_transmode = ''; // transaction mode
 
+       /*
+        * Additional parameters that may be passed to drivers in the connect string
+        * Driver must be coded to accept the parameters
+        */
+       protected $connectionParameters = array();
 
-       static function Version()
+       /**
+       * Adds a parameter to the connection string.
+       *
+       * These parameters are added to the connection string when connecting,
+       * if the driver is coded to use it.
+       *
+       * @param        string  $parameter      The name of the parameter to set
+       * @param        string  $value          The value of the parameter
+       *
+       * @return null
+       *
+       * @example, for mssqlnative driver ('CharacterSet','UTF-8')
+       */
+       final public function setConnectionParameter($parameter,$value)
        {
-       global $ADODB_vers;
 
-               $ok = preg_match( '/^[Vv]?([0-9]\.[0-9]+(dev|[a-z]))?/', $ADODB_vers, $matches );
-               if (!$ok) return (float) substr($ADODB_vers,1);
-               else return $matches[1];
+               $this->connectionParameters[$parameter] = $value;
+
+       }
+
+       static function Version() {
+               global $ADODB_vers;
+
+               // Semantic Version number matching regex
+               $regex = '^[vV]?(\d+\.\d+\.\d+'         // Version number (X.Y.Z) with optional 'V'
+                       . '(?:-(?:'                         // Optional preprod version: a '-'
+                       . 'dev|'                            // followed by 'dev'
+                       . '(?:(?:alpha|beta|rc)(?:\.\d+))'  // or a preprod suffix and version number
+                       . '))?)(?:\s|$)';                   // Whitespace or end of string
+
+               if (!preg_match("/$regex/", $ADODB_vers, $matches)) {
+                       // This should normally not happen... Return whatever is between the start
+                       // of the string and the first whitespace (or the end of the string).
+                       self::outp("Invalid version number: '$ADODB_vers'", 'Version');
+                       $regex = '^[vV]?(.*?)(?:\s|$)';
+                       preg_match("/$regex/", $ADODB_vers, $matches);
+               }
+               return $matches[1];
        }
 
        /**
@@ -473,29 +559,28 @@ if (!defined('_ADODB_LAYER')) {
                @returns An array with 2 elements: $arr['string'] is the description string,
                        and $arr[version] is the version (also a string).
        */
-       function ServerInfo()
-       {
+       function ServerInfo() {
                return array('description' => '', 'version' => '');
        }
 
-       function IsConnected()
-       {
+       function IsConnected() {
                return !empty($this->_connectionID);
        }
 
-       function _findvers($str)
-       {
-               if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1];
-               else return '';
+       function _findvers($str) {
+               if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) {
+                       return $arr[1];
+               } else {
+                       return '';
+               }
        }
 
        /**
        * All error messages go through this bottleneck function.
        * You can define your own handler by defining the function name in ADODB_OUTP.
        */
-       static function outp($msg,$newline=true)
-       {
-       global $ADODB_FLUSH,$ADODB_OUTP;
+       static function outp($msg,$newline=true) {
+               global $ADODB_FLUSH,$ADODB_OUTP;
 
                if (defined('ADODB_OUTP')) {
                        $fn = ADODB_OUTP;
@@ -507,20 +592,28 @@ if (!defined('_ADODB_LAYER')) {
                        return;
                }
 
-               if ($newline) $msg .= "<br>\n";
+               if ($newline) {
+                       $msg .= "<br>\n";
+               }
 
-               if (isset($_SERVER['HTTP_USER_AGENT']) || !$newline) echo $msg;
-               else echo strip_tags($msg);
+               if (isset($_SERVER['HTTP_USER_AGENT']) || !$newline) {
+                       echo $msg;
+               } else {
+                       echo strip_tags($msg);
+               }
 
 
-               if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); //  do not flush if output buffering enabled - useless - thx to Jesse Mullan
+               if (!empty($ADODB_FLUSH) && ob_get_length() !== false) {
+                       flush(); //  do not flush if output buffering enabled - useless - thx to Jesse Mullan
+               }
 
        }
 
-       function Time()
-       {
+       function Time() {
                $rs = $this->_Execute("select $this->sysTimeStamp");
-               if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields));
+               if ($rs && !$rs->EOF) {
+                       return $this->UnixTimeStamp(reset($rs->fields));
+               }
 
                return false;
        }
@@ -536,39 +629,56 @@ if (!defined('_ADODB_LAYER')) {
         *
         * @return true or false
         */
-       function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false)
-       {
-               if ($argHostname != "") $this->host = $argHostname;
-               if ($argUsername != "") $this->user = $argUsername;
-               if ($argPassword != "") $this->password = 'not stored'; // not stored for security reasons
-               if ($argDatabaseName != "") $this->database = $argDatabaseName;
+       function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false) {
+               if ($argHostname != "") {
+                       $this->host = $argHostname;
+               }
+               if ( strpos($this->host, ':') > 0 && isset($this->port) ) {
+                       list($this->host, $this->port) = explode(":", $this->host, 2);
+               }
+               if ($argUsername != "") {
+                       $this->user = $argUsername;
+               }
+               if ($argPassword != "") {
+                       $this->password = 'not stored'; // not stored for security reasons
+               }
+               if ($argDatabaseName != "") {
+                       $this->database = $argDatabaseName;
+               }
 
                $this->_isPersistentConnection = false;
 
                if ($forceNew) {
-                       if ($rez=$this->_nconnect($this->host, $this->user, $argPassword, $this->database)) return true;
+                       if ($rez=$this->_nconnect($this->host, $this->user, $argPassword, $this->database)) {
+                               return true;
+                       }
                } else {
-                        if ($rez=$this->_connect($this->host, $this->user, $argPassword, $this->database)) return true;
+                       if ($rez=$this->_connect($this->host, $this->user, $argPassword, $this->database)) {
+                               return true;
+                       }
                }
                if (isset($rez)) {
                        $err = $this->ErrorMsg();
-                       if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
+                       if (empty($err)) {
+                               $err = "Connection error to server '$argHostname' with user '$argUsername'";
+                       }
                        $ret = false;
                } else {
                        $err = "Missing extension for ".$this->dataProvider;
                        $ret = 0;
                }
-               if ($fn = $this->raiseErrorFn)
+               if ($fn = $this->raiseErrorFn) {
                        $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
-
+               }
 
                $this->_connectionID = false;
-               if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
+               if ($this->debug) {
+                       ADOConnection::outp( $this->host.': '.$err);
+               }
                return $ret;
        }
 
-       function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
-       {
+       function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName) {
                return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName);
        }
 
@@ -583,8 +693,7 @@ if (!defined('_ADODB_LAYER')) {
         *
         * @return true or false
         */
-       function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
-       {
+       function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") {
                return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true);
        }
 
@@ -598,23 +707,38 @@ if (!defined('_ADODB_LAYER')) {
         *
         * @return return true or false
         */
-       function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
-       {
+       function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") {
 
-               if (defined('ADODB_NEVER_PERSIST'))
+               if (defined('ADODB_NEVER_PERSIST')) {
                        return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);
+               }
 
-               if ($argHostname != "") $this->host = $argHostname;
-               if ($argUsername != "") $this->user = $argUsername;
-               if ($argPassword != "") $this->password = 'not stored';
-               if ($argDatabaseName != "") $this->database = $argDatabaseName;
+               if ($argHostname != "") {
+                       $this->host = $argHostname;
+               }
+               if ( strpos($this->host, ':') > 0 && isset($this->port) ) {
+                       list($this->host, $this->port) = explode(":", $this->host, 2);
+               }
+               if ($argUsername != "") {
+                       $this->user = $argUsername;
+               }
+               if ($argPassword != "") {
+                       $this->password = 'not stored';
+               }
+               if ($argDatabaseName != "") {
+                       $this->database = $argDatabaseName;
+               }
 
                $this->_isPersistentConnection = true;
 
-               if ($rez = $this->_pconnect($this->host, $this->user, $argPassword, $this->database)) return true;
+               if ($rez = $this->_pconnect($this->host, $this->user, $argPassword, $this->database)) {
+                       return true;
+               }
                if (isset($rez)) {
                        $err = $this->ErrorMsg();
-                       if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
+                       if (empty($err)) {
+                               $err = "Connection error to server '$argHostname' with user '$argUsername'";
+                       }
                        $ret = false;
                } else {
                        $err = "Missing extension for ".$this->dataProvider;
@@ -625,12 +749,13 @@ if (!defined('_ADODB_LAYER')) {
                }
 
                $this->_connectionID = false;
-               if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
+               if ($this->debug) {
+                       ADOConnection::outp( $this->host.': '.$err);
+               }
                return $ret;
        }
 
-       function outp_throw($msg,$src='WARN',$sql='')
-       {
+       function outp_throw($msg,$src='WARN',$sql='') {
                if (defined('ADODB_ERROR_HANDLER') &&  ADODB_ERROR_HANDLER == 'adodb_throw') {
                        adodb_throw($this->databaseType,$src,-9999,$msg,$sql,false,$this);
                        return;
@@ -639,24 +764,26 @@ if (!defined('_ADODB_LAYER')) {
        }
 
        // create cache class. Code is backward compat with old memcache implementation
-       function _CreateCache()
-       {
-       global $ADODB_CACHE, $ADODB_CACHE_CLASS;
+       function _CreateCache() {
+               global $ADODB_CACHE, $ADODB_CACHE_CLASS;
 
                if ($this->memCache) {
-               global $ADODB_INCLUDED_MEMCACHE;
-
-                       if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php');
-                               $ADODB_CACHE = new ADODB_Cache_MemCache($this);
-               } else
-                               $ADODB_CACHE = new $ADODB_CACHE_CLASS($this);
+                       global $ADODB_INCLUDED_MEMCACHE;
 
+                       if (empty($ADODB_INCLUDED_MEMCACHE)) {
+                               include_once(ADODB_DIR.'/adodb-memcache.lib.inc.php');
+                       }
+                       $ADODB_CACHE = new ADODB_Cache_MemCache($this);
+               } else {
+                       $ADODB_CACHE = new $ADODB_CACHE_CLASS($this);
+               }
        }
 
        // Format date column in sql string given an input format that understands Y M D
-       function SQLDate($fmt, $col=false)
-       {
-               if (!$col) $col = $this->sysDate;
+       function SQLDate($fmt, $col=false) {
+               if (!$col) {
+                       $col = $this->sysDate;
+               }
                return $col; // child class implement
        }
 
@@ -672,11 +799,10 @@ if (!defined('_ADODB_LAYER')) {
         * @param sql   SQL to send to database
         *
         * @return return FALSE, or the prepared statement, or the original sql if
-        *                      if the database does not support prepare.
+        *         if the database does not support prepare.
         *
         */
-       function Prepare($sql)
-       {
+       function Prepare($sql) {
                return $sql;
        }
 
@@ -691,41 +817,38 @@ if (!defined('_ADODB_LAYER')) {
         * @param sql   SQL to send to database
         *
         * @return return FALSE, or the prepared statement, or the original sql if
-        *                      if the database does not support prepare.
+        *         if the database does not support prepare.
         *
         */
-       function PrepareSP($sql,$param=true)
-       {
+       function PrepareSP($sql,$param=true) {
                return $this->Prepare($sql,$param);
        }
 
        /**
        * PEAR DB Compat
        */
-       function Quote($s)
-       {
+       function Quote($s) {
                return $this->qstr($s,false);
        }
 
        /**
-        Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de>
-       */
-       function QMagic($s)
-       {
+        * Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de>
+        */
+       function QMagic($s) {
                return $this->qstr($s,get_magic_quotes_gpc());
        }
 
-       function q(&$s)
-       {
-               #if (!empty($this->qNull)) if ($s == 'null') return $s;
+       function q(&$s) {
+               //if (!empty($this->qNull && $s == 'null') {
+               //      return $s;
+               //}
                $s = $this->qstr($s,false);
        }
 
        /**
        * PEAR DB Compat - do not use internally.
        */
-       function ErrorNative()
-       {
+       function ErrorNative() {
                return $this->ErrorNo();
        }
 
@@ -733,30 +856,26 @@ if (!defined('_ADODB_LAYER')) {
        /**
         * PEAR DB Compat - do not use internally.
         */
-       function nextId($seq_name)
-       {
+       function nextId($seq_name) {
                return $this->GenID($seq_name);
        }
 
        /**
-        *       Lock a row, will escalate and lock the table if row locking not supported
-        *      will normally free the lock at the end of the transaction
+        * Lock a row, will escalate and lock the table if row locking not supported
+        * will normally free the lock at the end of the transaction
         *
-        *  @param $table       name of table to lock
-        *  @param $where       where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock
+        * @param $table        name of table to lock
+        * @param $where        where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock
         */
-       function RowLock($table,$where,$col='1 as adodbignore')
-       {
+       function RowLock($table,$where,$col='1 as adodbignore') {
                return false;
        }
 
-       function CommitLock($table)
-       {
+       function CommitLock($table) {
                return $this->CommitTrans();
        }
 
-       function RollbackLock($table)
-       {
+       function RollbackLock($table) {
                return $this->RollbackTrans();
        }
 
@@ -764,18 +883,17 @@ if (!defined('_ADODB_LAYER')) {
        * PEAR DB Compat - do not use internally.
        *
        * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical
-       *       for easy porting :-)
+       * for easy porting :-)
        *
        * @param mode   The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM
        * @returns              The previous fetch mode
        */
-       function SetFetchMode($mode)
-       {
+       function SetFetchMode($mode) {
                $old = $this->fetchMode;
                $this->fetchMode = $mode;
 
                if ($old === false) {
-               global $ADODB_FETCH_MODE;
+                       global $ADODB_FETCH_MODE;
                        return $ADODB_FETCH_MODE;
                }
                return $old;
@@ -785,10 +903,11 @@ if (!defined('_ADODB_LAYER')) {
        /**
        * PEAR DB Compat - do not use internally.
        */
-       function Query($sql, $inputarr=false)
-       {
+       function Query($sql, $inputarr=false) {
                $rs = $this->Execute($sql, $inputarr);
-               if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
+               if (!$rs && defined('ADODB_PEAR')) {
+                       return ADODB_PEAR_Error();
+               }
                return $rs;
        }
 
@@ -796,10 +915,11 @@ if (!defined('_ADODB_LAYER')) {
        /**
        * PEAR DB Compat - do not use internally
        */
-       function LimitQuery($sql, $offset, $count, $params=false)
-       {
+       function LimitQuery($sql, $offset, $count, $params=false) {
                $rs = $this->SelectLimit($sql, $count, $offset, $params);
-               if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
+               if (!$rs && defined('ADODB_PEAR')) {
+                       return ADODB_PEAR_Error();
+               }
                return $rs;
        }
 
@@ -807,8 +927,7 @@ if (!defined('_ADODB_LAYER')) {
        /**
        * PEAR DB Compat - do not use internally
        */
-       function Disconnect()
-       {
+       function Disconnect() {
                return $this->Close();
        }
 
@@ -825,23 +944,20 @@ if (!defined('_ADODB_LAYER')) {
         * @param string $type (unused)
         * @return string query parameter placeholder
         */
-       function Param($name,$type='C')
-       {
+       function Param($name,$type='C') {
                return '?';
        }
 
        /*
                InParameter and OutParameter are self-documenting versions of Parameter().
        */
-       function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
-       {
+       function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false) {
                return $this->Parameter($stmt,$var,$name,false,$maxLen,$type);
        }
 
        /*
        */
-       function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
-       {
+       function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false) {
                return $this->Parameter($stmt,$var,$name,true,$maxLen,$type);
 
        }
@@ -862,14 +978,12 @@ if (!defined('_ADODB_LAYER')) {
                @param [$type] The data type of $var. Legal values depend on driver.
 
        */
-       function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
-       {
+       function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false) {
                return false;
        }
 
 
-       function IgnoreErrors($saveErrs=false)
-       {
+       function IgnoreErrors($saveErrs=false) {
                if (!$saveErrs) {
                        $saveErrs = array($this->raiseErrorFn,$this->_transOK);
                        $this->raiseErrorFn = false;
@@ -881,17 +995,16 @@ if (!defined('_ADODB_LAYER')) {
        }
 
        /**
-               Improved method of initiating a transaction. Used together with CompleteTrans().
-               Advantages include:
-
-               a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.
-                  Only the outermost block is treated as a transaction.<br>
-               b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>
-               c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block
-                  are disabled, making it backward compatible.
-       */
-       function StartTrans($errfn = 'ADODB_TransMonitor')
-       {
+        * Improved method of initiating a transaction. Used together with CompleteTrans().
+        * Advantages include:
+     *
+        * a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.
+        *    Only the outermost block is treated as a transaction.<br>
+        * b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>
+        * c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block
+        *    are disabled, making it backward compatible.
+        */
+       function StartTrans($errfn = 'ADODB_TransMonitor') {
                if ($this->transOff > 0) {
                        $this->transOff += 1;
                        return true;
@@ -901,7 +1014,9 @@ if (!defined('_ADODB_LAYER')) {
                $this->raiseErrorFn = $errfn;
                $this->_transOK = true;
 
-               if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
+               if ($this->debug && $this->transCnt > 0) {
+                       ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
+               }
                $ok = $this->BeginTrans();
                $this->transOff = 1;
                return $ok;
@@ -916,8 +1031,7 @@ if (!defined('_ADODB_LAYER')) {
                and if set to false force rollback even if no SQL error detected.
                @returns true on commit, false on rollback.
        */
-       function CompleteTrans($autoComplete = true)
-       {
+       function CompleteTrans($autoComplete = true) {
                if ($this->transOff > 1) {
                        $this->transOff -= 1;
                        return true;
@@ -928,13 +1042,20 @@ if (!defined('_ADODB_LAYER')) {
                if ($this->_transOK && $autoComplete) {
                        if (!$this->CommitTrans()) {
                                $this->_transOK = false;
-                               if ($this->debug) ADOConnection::outp("Smart Commit failed");
-                       } else
-                               if ($this->debug) ADOConnection::outp("Smart Commit occurred");
+                               if ($this->debug) {
+                                       ADOConnection::outp("Smart Commit failed");
+                               }
+                       } else {
+                               if ($this->debug) {
+                                       ADOConnection::outp("Smart Commit occurred");
+                               }
+                       }
                } else {
                        $this->_transOK = false;
                        $this->RollbackTrans();
-                       if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred");
+                       if ($this->debug) {
+                               ADOCOnnection::outp("Smart Rollback occurred");
+                       }
                }
 
                return $this->_transOK;
@@ -943,8 +1064,7 @@ if (!defined('_ADODB_LAYER')) {
        /*
                At the end of a StartTrans/CompleteTrans block, perform a rollback.
        */
-       function FailTrans()
-       {
+       function FailTrans() {
                if ($this->debug)
                        if ($this->transOff == 0) {
                                ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
@@ -958,9 +1078,10 @@ if (!defined('_ADODB_LAYER')) {
        /**
                Check if transaction has failed, only for Smart Transactions.
        */
-       function HasFailedTrans()
-       {
-               if ($this->transOff > 0) return $this->_transOK == false;
+       function HasFailedTrans() {
+               if ($this->transOff > 0) {
+                       return $this->_transOK == false;
+               }
                return false;
        }
 
@@ -969,17 +1090,20 @@ if (!defined('_ADODB_LAYER')) {
         *
         * @param sql           SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
         * @param [inputarr]    holds the input data to bind to. Null elements will be set to null.
-        * @return              RecordSet or false
+        * @return RecordSet or false
         */
-       function Execute($sql,$inputarr=false)
-       {
+       function Execute($sql,$inputarr=false) {
                if ($this->fnExecute) {
                        $fn = $this->fnExecute;
                        $ret = $fn($this,$sql,$inputarr);
-                       if (isset($ret)) return $ret;
+                       if (isset($ret)) {
+                               return $ret;
+                       }
                }
                if ($inputarr !== false) {
-                       if (!is_array($inputarr)) $inputarr = array($inputarr);
+                       if (!is_array($inputarr)) {
+                               $inputarr = array($inputarr);
+                       }
 
                        $element0 = reset($inputarr);
                        # is_object check because oci8 descriptors can be passed in
@@ -989,9 +1113,24 @@ if (!defined('_ADODB_LAYER')) {
                        unset($element0);
 
                        if (!is_array($sql) && !$this->_bindInputArray) {
+                               // @TODO this would consider a '?' within a string as a parameter...
                                $sqlarr = explode('?',$sql);
                                $nparams = sizeof($sqlarr)-1;
-                               if (!$array_2d) $inputarr = array($inputarr);
+
+                               // Make sure the number of parameters provided in the input
+                               // array matches what the query expects
+                               if ($nparams != count($inputarr)) {
+                                       $this->outp_throw(
+                                               "Input array has " . count($inputarr) .
+                                               " params, does not match query: '" . htmlspecialchars($sql) . "'",
+                                               'Execute'
+                                       );
+                                       return false;
+                               }
+
+                               if (!$array_2d) {
+                                       $inputarr = array($inputarr);
+                               }
 
                                foreach($inputarr as $arr) {
                                        $sql = ''; $i = 0;
@@ -1001,43 +1140,57 @@ if (!defined('_ADODB_LAYER')) {
                                                // from Ron Baldwin <ron.baldwin#sourceprose.com>
                                                // Only quote string types
                                                $typ = gettype($v);
-                                               if ($typ == 'string')
+                                               if ($typ == 'string') {
                                                        //New memory copy of input created here -mikefedyk
                                                        $sql .= $this->qstr($v);
-                                               else if ($typ == 'double')
+                                               } else if ($typ == 'double') {
                                                        $sql .= str_replace(',','.',$v); // locales fix so 1.1 does not get converted to 1,1
-                                               else if ($typ == 'boolean')
+                                               } else if ($typ == 'boolean') {
                                                        $sql .= $v ? $this->true : $this->false;
-                                               else if ($typ == 'object') {
-                                                       if (method_exists($v, '__toString')) $sql .= $this->qstr($v->__toString());
-                                                       else $sql .= $this->qstr((string) $v);
-                                               } else if ($v === null)
+                                               } else if ($typ == 'object') {
+                                                       if (method_exists($v, '__toString')) {
+                                                               $sql .= $this->qstr($v->__toString());
+                                                       } else {
+                                                               $sql .= $this->qstr((string) $v);
+                                                       }
+                                               } else if ($v === null) {
                                                        $sql .= 'NULL';
-                                               else
+                                               } else {
                                                        $sql .= $v;
+                                               }
                                                $i += 1;
 
-                                               if ($i == $nparams) break;
+                                               if ($i == $nparams) {
+                                                       break;
+                                               }
                                        } // while
                                        if (isset($sqlarr[$i])) {
                                                $sql .= $sqlarr[$i];
-                                               if ($i+1 != sizeof($sqlarr)) $this->outp_throw( "Input Array does not match ?: ".htmlspecialchars($sql),'Execute');
-                                       } else if ($i != sizeof($sqlarr))
+                                               if ($i+1 != sizeof($sqlarr)) {
+                                                       $this->outp_throw( "Input Array does not match ?: ".htmlspecialchars($sql),'Execute');
+                                               }
+                                       } else if ($i != sizeof($sqlarr)) {
                                                $this->outp_throw( "Input array does not match ?: ".htmlspecialchars($sql),'Execute');
+                                       }
 
                                        $ret = $this->_Execute($sql);
-                                       if (!$ret) return $ret;
+                                       if (!$ret) {
+                                               return $ret;
+                                       }
                                }
                        } else {
                                if ($array_2d) {
-                                       if (is_string($sql))
+                                       if (is_string($sql)) {
                                                $stmt = $this->Prepare($sql);
-                                       else
+                                       } else {
                                                $stmt = $sql;
+                                       }
 
                                        foreach($inputarr as $arr) {
                                                $ret = $this->_Execute($stmt,$arr);
-                                               if (!$ret) return $ret;
+                                               if (!$ret) {
+                                                       return $ret;
+                                               }
                                        }
                                } else {
                                        $ret = $this->_Execute($sql,$inputarr);
@@ -1050,12 +1203,20 @@ if (!defined('_ADODB_LAYER')) {
                return $ret;
        }
 
+       function _Execute($sql,$inputarr=false) {
+               // ExecuteCursor() may send non-string queries (such as arrays),
+               // so we need to ignore those.
+               if( is_string($sql) ) {
+                       // Strips keyword used to help generate SELECT COUNT(*) queries
+                       // from SQL if it exists.
+                       $sql = ADODB_str_replace( '_ADODB_COUNT', '', $sql );
+               }
 
-       function _Execute($sql,$inputarr=false)
-       {
                if ($this->debug) {
                        global $ADODB_INCLUDED_LIB;
-                       if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
+                       if (empty($ADODB_INCLUDED_LIB)) {
+                               include(ADODB_DIR.'/adodb-lib.inc.php');
+                       }
                        $this->_queryID = _adodb_debug_execute($this, $sql,$inputarr);
                } else {
                        $this->_queryID = @$this->_query($sql,$inputarr);
@@ -1065,17 +1226,20 @@ if (!defined('_ADODB_LAYER')) {
                // OK, query executed
                // ************************
 
-               if ($this->_queryID === false) { // error handling if query fails
-                       if ($this->debug == 99) adodb_backtrace(true,5);
+               // error handling if query fails
+               if ($this->_queryID === false) {
+                       if ($this->debug == 99) {
+                               adodb_backtrace(true,5);
+                       }
                        $fn = $this->raiseErrorFn;
                        if ($fn) {
                                $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this);
                        }
-                       $false = false;
-                       return $false;
+                       return false;
                }
 
-               if ($this->_queryID === true) { // return simplified recordset for inserts/updates/deletes with lower overhead
+               // return simplified recordset for inserts/updates/deletes with lower overhead
+               if ($this->_queryID === true) {
                        $rsclass = $this->rsPrefix.'empty';
                        $rs = (class_exists($rsclass)) ? new $rsclass():  new ADORecordSet_empty();
 
@@ -1087,10 +1251,13 @@ if (!defined('_ADODB_LAYER')) {
                $rs = new $rsclass($this->_queryID,$this->fetchMode);
                $rs->connection = $this; // Pablo suggestion
                $rs->Init();
-               if (is_array($sql)) $rs->sql = $sql[0];
-               else $rs->sql = $sql;
+               if (is_array($sql)) {
+                       $rs->sql = $sql[0];
+               } else {
+                       $rs->sql = $sql;
+               }
                if ($rs->_numOfRows <= 0) {
-               global $ADODB_COUNTRECS;
+                       global $ADODB_COUNTRECS;
                        if ($ADODB_COUNTRECS) {
                                if (!$rs->EOF) {
                                        $rs = $this->_rs2rs($rs,-1,-1,!is_array($sql));
@@ -1102,15 +1269,17 @@ if (!defined('_ADODB_LAYER')) {
                return $rs;
        }
 
-       function CreateSequence($seqname='adodbseq',$startID=1)
-       {
-               if (empty($this->_genSeqSQL)) return false;
+       function CreateSequence($seqname='adodbseq',$startID=1) {
+               if (empty($this->_genSeqSQL)) {
+                       return false;
+               }
                return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
        }
 
-       function DropSequence($seqname='adodbseq')
-       {
-               if (empty($this->_dropSeqSQL)) return false;
+       function DropSequence($seqname='adodbseq') {
+               if (empty($this->_dropSeqSQL)) {
+                       return false;
+               }
                return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
        }
 
@@ -1122,8 +1291,7 @@ if (!defined('_ADODB_LAYER')) {
         * @param startID               if sequence does not exist, start at this ID
         * @return              0 if not supported, otherwise a sequence id
         */
-       function GenID($seqname='adodbseq',$startID=1)
-       {
+       function GenID($seqname='adodbseq',$startID=1) {
                if (!$this->hasGenID) {
                        return 0; // formerly returns false pre 1.60
                }
@@ -1142,10 +1310,15 @@ if (!defined('_ADODB_LAYER')) {
                        $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
                        $rs = $this->Execute($getnext);
                }
-               if ($rs && !$rs->EOF) $this->genID = reset($rs->fields);
-               else $this->genID = 0; // false
+               if ($rs && !$rs->EOF) {
+                       $this->genID = reset($rs->fields);
+               } else {
+                       $this->genID = 0; // false
+               }
 
-               if ($rs) $rs->Close();
+               if ($rs) {
+                       $rs->Close();
+               }
 
                return $this->genID;
        }
@@ -1155,10 +1328,13 @@ if (!defined('_ADODB_LAYER')) {
         * @param $column string name of the column, not needed by all databases (eg. mysql), default ''
         * @return  the last inserted ID. Not all databases support this.
         */
-       function Insert_ID($table='',$column='')
-       {
-               if ($this->_logsql && $this->lastInsID) return $this->lastInsID;
-               if ($this->hasInsertID) return $this->_insertid($table,$column);
+       function Insert_ID($table='',$column='') {
+               if ($this->_logsql && $this->lastInsID) {
+                       return $this->lastInsID;
+               }
+               if ($this->hasInsertID) {
+                       return $this->_insertid($table,$column);
+               }
                if ($this->debug) {
                        ADOConnection::outp( '<p>Insert_ID error</p>');
                        adodb_backtrace();
@@ -1173,29 +1349,31 @@ if (!defined('_ADODB_LAYER')) {
         * @return  the last inserted ID. All databases support this. But aware possible
         * problems in multiuser environments. Heavy test this before deploying.
         */
-       function PO_Insert_ID($table="", $id="")
-       {
-          if ($this->hasInsertID){
-                  return $this->Insert_ID($table,$id);
-          } else {
-                  return $this->GetOne("SELECT MAX($id) FROM $table");
-          }
+       function PO_Insert_ID($table="", $id="") {
+               if ($this->hasInsertID){
+                       return $this->Insert_ID($table,$id);
+               } else {
+                       return $this->GetOne("SELECT MAX($id) FROM $table");
+               }
        }
 
        /**
        * @return # rows affected by UPDATE/DELETE
        */
-       function Affected_Rows()
-       {
+       function Affected_Rows() {
                if ($this->hasAffectedRows) {
                        if ($this->fnExecute === 'adodb_log_sql') {
-                               if ($this->_logsql && $this->_affected !== false) return $this->_affected;
+                               if ($this->_logsql && $this->_affected !== false) {
+                                       return $this->_affected;
+                               }
                        }
                        $val = $this->_affectedrows();
                        return ($val < 0) ? false : $val;
                }
 
-               if ($this->debug) ADOConnection::outp( '<p>Affected_Rows error</p>',false);
+               if ($this->debug) {
+                       ADOConnection::outp( '<p>Affected_Rows error</p>',false);
+               }
                return false;
        }
 
@@ -1203,30 +1381,31 @@ if (!defined('_ADODB_LAYER')) {
        /**
         * @return  the last error message
         */
-       function ErrorMsg()
-       {
-               if ($this->_errorMsg) return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;
-               else return '';
+       function ErrorMsg() {
+               if ($this->_errorMsg) {
+                       return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;
+               } else {
+                       return '';
+               }
        }
 
 
        /**
         * @return the last error number. Normally 0 means no error.
         */
-       function ErrorNo()
-       {
+       function ErrorNo() {
                return ($this->_errorMsg) ? -1 : 0;
        }
 
-       function MetaError($err=false)
-       {
+       function MetaError($err=false) {
                include_once(ADODB_DIR."/adodb-error.inc.php");
-               if ($err === false) $err = $this->ErrorNo();
+               if ($err === false) {
+                       $err = $this->ErrorNo();
+               }
                return adodb_error($this->dataProvider,$this->databaseType,$err);
        }
 
-       function MetaErrorMsg($errno)
-       {
+       function MetaErrorMsg($errno) {
                include_once(ADODB_DIR."/adodb-error.inc.php");
                return adodb_errormsg($errno);
        }
@@ -1234,38 +1413,39 @@ if (!defined('_ADODB_LAYER')) {
        /**
         * @returns an array with the primary key columns in it.
         */
-       function MetaPrimaryKeys($table, $owner=false)
-       {
+       function MetaPrimaryKeys($table, $owner=false) {
        // owner not used in base class - see oci8
                $p = array();
                $objs = $this->MetaColumns($table);
                if ($objs) {
                        foreach($objs as $v) {
-                               if (!empty($v->primary_key))
+                               if (!empty($v->primary_key)) {
                                        $p[] = $v->name;
+                               }
                        }
                }
-               if (sizeof($p)) return $p;
-               if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
+               if (sizeof($p)) {
+                       return $p;
+               }
+               if (function_exists('ADODB_VIEW_PRIMARYKEYS')) {
                        return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
+               }
                return false;
        }
 
        /**
         * @returns assoc array where keys are tables, and values are foreign keys
         */
-       function MetaForeignKeys($table, $owner=false, $upper=false)
-       {
+       function MetaForeignKeys($table, $owner=false, $upper=false) {
                return false;
        }
        /**
         * Choose a database to connect to. Many databases do not support this.
         *
-        * @param dbName        is the name of the database to select
-        * @return              true or false
+        * @param dbName is the name of the database to select
+        * @return true or false
         */
-       function SelectDB($dbName)
-       {return false;}
+       function SelectDB($dbName) {return false;}
 
 
        /**
@@ -1287,17 +1467,18 @@ if (!defined('_ADODB_LAYER')) {
         * @param [secs2cache]          is a private parameter only used by jlim
         * @return              the recordset ($rs->databaseType == 'array')
         */
-       function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
-       {
+       function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0) {
                if ($this->hasTop && $nrows > 0) {
-               // suggested by Reinhard Balling. Access requires top after distinct
-                // Informix requires first before distinct - F Riosa
+                       // suggested by Reinhard Balling. Access requires top after distinct
+                       // Informix requires first before distinct - F Riosa
                        $ismssql = (strpos($this->databaseType,'mssql') !== false);
-                       if ($ismssql) $isaccess = false;
-                       else $isaccess = (strpos($this->databaseType,'access') !== false);
-
-                       if ($offset <=  0) {
+                       if ($ismssql) {
+                               $isaccess = false;
+                       } else {
+                               $isaccess = (strpos($this->databaseType,'access') !== false);
+                       }
 
+                       if ($offset <= 0) {
                                        // access includes ties in result
                                        if ($isaccess) {
                                                $sql = preg_replace(
@@ -1336,8 +1517,11 @@ if (!defined('_ADODB_LAYER')) {
                $ADODB_COUNTRECS = false;
 
 
-               if ($secs2cache != 0) $rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
-               else $rs = $this->Execute($sql,$inputarr);
+               if ($secs2cache != 0) {
+                       $rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
+               } else {
+                       $rs = $this->Execute($sql,$inputarr);
+               }
 
                $ADODB_COUNTRECS = $savec;
                if ($rs && !$rs->EOF) {
@@ -1352,8 +1536,7 @@ if (!defined('_ADODB_LAYER')) {
        *
        * @param rs                     the recordset to serialize
        */
-       function SerializableRS(&$rs)
-       {
+       function SerializableRS(&$rs) {
                $rs2 = $this->_rs2rs($rs);
                $ignore = false;
                $rs2->connection = $ignore;
@@ -1367,15 +1550,13 @@ if (!defined('_ADODB_LAYER')) {
        * old $rs will be closed.
        *
        * @param rs                     the recordset to copy
-       * @param [nrows]        number of rows to retrieve (optional)
-       * @param [offset]       offset by number of rows (optional)
-       * @return                       the new recordset
+       * @param [nrows]        number of rows to retrieve (optional)
+       * @param [offset]       offset by number of rows (optional)
+       * @return                       the new recordset
        */
-       function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true)
-       {
+       function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true) {
                if (! $rs) {
-                       $false = false;
-                       return $false;
+                       return false;
                }
                $dbtype = $rs->databaseType;
                if (!$dbtype) {
@@ -1394,7 +1575,9 @@ if (!defined('_ADODB_LAYER')) {
 
                $arr = $rs->GetArrayLimit($nrows,$offset);
                //print_r($arr);
-               if ($close) $rs->Close();
+               if ($close) {
+                       $rs->Close();
+               }
 
                $arrayClass = $this->arrayClass;
 
@@ -1410,33 +1593,28 @@ if (!defined('_ADODB_LAYER')) {
        /*
        * Return all rows. Compat with PEAR DB
        */
-       function GetAll($sql, $inputarr=false)
-       {
+       function GetAll($sql, $inputarr=false) {
                $arr = $this->GetArray($sql,$inputarr);
                return $arr;
        }
 
-       function GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false)
-       {
+       function GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false) {
                $rs = $this->Execute($sql, $inputarr);
                if (!$rs) {
-                       $false = false;
-                       return $false;
+                       return false;
                }
                $arr = $rs->GetAssoc($force_array,$first2cols);
                return $arr;
        }
 
-       function CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false)
-       {
+       function CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false) {
                if (!is_numeric($secs2cache)) {
                        $first2cols = $force_array;
                        $force_array = $inputarr;
                }
                $rs = $this->CacheExecute($secs2cache, $sql, $inputarr);
                if (!$rs) {
-                       $false = false;
-                       return $false;
+                       return false;
                }
                $arr = $rs->GetAssoc($force_array,$first2cols);
                return $arr;
@@ -1449,17 +1627,20 @@ if (!defined('_ADODB_LAYER')) {
        * @param sql                    SQL statement
        * @param [inputarr]             input bind array
        */
-       function GetOne($sql,$inputarr=false)
-       {
-       global $ADODB_COUNTRECS,$ADODB_GETONE_EOF;
+       function GetOne($sql,$inputarr=false) {
+               global $ADODB_COUNTRECS,$ADODB_GETONE_EOF;
+
                $crecs = $ADODB_COUNTRECS;
                $ADODB_COUNTRECS = false;
 
                $ret = false;
                $rs = $this->Execute($sql,$inputarr);
                if ($rs) {
-                       if ($rs->EOF) $ret = $ADODB_GETONE_EOF;
-                       else $ret = reset($rs->fields);
+                       if ($rs->EOF) {
+                               $ret = $ADODB_GETONE_EOF;
+                       } else {
+                               $ret = reset($rs->fields);
+                       }
 
                        $rs->Close();
                }
@@ -1468,83 +1649,88 @@ if (!defined('_ADODB_LAYER')) {
        }
 
        // $where should include 'WHERE fld=value'
-       function GetMedian($table, $field,$where = '')
-       {
+       function GetMedian($table, $field,$where = '') {
                $total = $this->GetOne("select count(*) from $table $where");
-               if (!$total) return false;
+               if (!$total) {
+                       return false;
+               }
 
                $midrow = (integer) ($total/2);
                $rs = $this->SelectLimit("select $field from $table $where order by 1",1,$midrow);
-               if ($rs && !$rs->EOF) return reset($rs->fields);
+               if ($rs && !$rs->EOF) {
+                       return reset($rs->fields);
+               }
                return false;
        }
 
 
-       function CacheGetOne($secs2cache,$sql=false,$inputarr=false)
-       {
-       global $ADODB_GETONE_EOF;
+       function CacheGetOne($secs2cache,$sql=false,$inputarr=false) {
+               global $ADODB_GETONE_EOF;
+
                $ret = false;
                $rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
                if ($rs) {
-                       if ($rs->EOF) $ret = $ADODB_GETONE_EOF;
-                       else $ret = reset($rs->fields);
+                       if ($rs->EOF) {
+                               $ret = $ADODB_GETONE_EOF;
+                       } else {
+                               $ret = reset($rs->fields);
+                       }
                        $rs->Close();
                }
 
                return $ret;
        }
 
-       function GetCol($sql, $inputarr = false, $trim = false)
-       {
+       function GetCol($sql, $inputarr = false, $trim = false) {
 
-               $rs = $this->Execute($sql, $inputarr);
-               if ($rs) {
+               $rs = $this->Execute($sql, $inputarr);
+               if ($rs) {
                        $rv = array();
-                       if ($trim) {
+                       if ($trim) {
                                while (!$rs->EOF) {
                                        $rv[] = trim(reset($rs->fields));
                                        $rs->MoveNext();
-                               }
+                               }
                        } else {
                                while (!$rs->EOF) {
                                        $rv[] = reset($rs->fields);
                                        $rs->MoveNext();
-                               }
+                               }
                        }
-                       $rs->Close();
-               } else
+                       $rs->Close();
+               } else {
                        $rv = false;
-               return $rv;
+               }
+               return $rv;
        }
 
-       function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false)
-       {
-               $rs = $this->CacheExecute($secs, $sql, $inputarr);
-               if ($rs) {
+       function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false) {
+               $rs = $this->CacheExecute($secs, $sql, $inputarr);
+               if ($rs) {
                        $rv = array();
                        if ($trim) {
                                while (!$rs->EOF) {
                                        $rv[] = trim(reset($rs->fields));
                                        $rs->MoveNext();
-                               }
+                               }
                        } else {
                                while (!$rs->EOF) {
                                        $rv[] = reset($rs->fields);
                                        $rs->MoveNext();
-                               }
+                               }
                        }
-                       $rs->Close();
-               } else
+                       $rs->Close();
+               } else
                        $rv = false;
 
-               return $rv;
+               return $rv;
        }
 
-       function Transpose(&$rs,$addfieldnames=true)
-       {
+       function Transpose(&$rs,$addfieldnames=true) {
                $rs2 = $this->_rs2rs($rs);
-               $false = false;
-               if (!$rs2) return $false;
+               if (!$rs2) {
+                       return false;
+               }
 
                $rs2->_transpose($addfieldnames);
                return $rs2;
@@ -1557,9 +1743,10 @@ if (!defined('_ADODB_LAYER')) {
 
                If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour.
        */
-       function OffsetDate($dayFraction,$date=false)
-       {
-               if (!$date) $date = $this->sysDate;
+       function OffsetDate($dayFraction,$date=false) {
+               if (!$date) {
+                       $date = $this->sysDate;
+               }
                return  '('.$date.'+'.$dayFraction.')';
        }
 
@@ -1569,9 +1756,8 @@ if (!defined('_ADODB_LAYER')) {
        * @param sql                    SQL statement
        * @param [inputarr]             input bind array
        */
-       function GetArray($sql,$inputarr=false)
-       {
-       global $ADODB_COUNTRECS;
+       function GetArray($sql,$inputarr=false) {
+               global $ADODB_COUNTRECS;
 
                $savec = $ADODB_COUNTRECS;
                $ADODB_COUNTRECS = false;
@@ -1582,23 +1768,20 @@ if (!defined('_ADODB_LAYER')) {
                                $cls = ADODB_PEAR_Error();
                                return $cls;
                        } else {
-                               $false = false;
-                               return $false;
+                               return false;
                        }
                $arr = $rs->GetArray();
                $rs->Close();
                return $arr;
        }
 
-       function CacheGetAll($secs2cache,$sql=false,$inputarr=false)
-       {
+       function CacheGetAll($secs2cache,$sql=false,$inputarr=false) {
                $arr = $this->CacheGetArray($secs2cache,$sql,$inputarr);
                return $arr;
        }
 
-       function CacheGetArray($secs2cache,$sql=false,$inputarr=false)
-       {
-       global $ADODB_COUNTRECS;
+       function CacheGetArray($secs2cache,$sql=false,$inputarr=false) {
+               global $ADODB_COUNTRECS;
 
                $savec = $ADODB_COUNTRECS;
                $ADODB_COUNTRECS = false;
@@ -1610,16 +1793,14 @@ if (!defined('_ADODB_LAYER')) {
                                $cls = ADODB_PEAR_Error();
                                return $cls;
                        } else {
-                               $false = false;
-                               return $false;
+                               return false;
                        }
                $arr = $rs->GetArray();
                $rs->Close();
                return $arr;
        }
 
-       function GetRandRow($sql, $arr= false)
-       {
+       function GetRandRow($sql, $arr= false) {
                $rezarr = $this->GetAll($sql, $arr);
                $sz = sizeof($rezarr);
                return $rezarr[abs(rand()) % $sz];
@@ -1632,9 +1813,9 @@ if (!defined('_ADODB_LAYER')) {
        * @param sql                    SQL statement
        * @param [inputarr]             input bind array
        */
-       function GetRow($sql,$inputarr=false)
-       {
-       global $ADODB_COUNTRECS;
+       function GetRow($sql,$inputarr=false) {
+               global $ADODB_COUNTRECS;
+
                $crecs = $ADODB_COUNTRECS;
                $ADODB_COUNTRECS = false;
 
@@ -1642,28 +1823,31 @@ if (!defined('_ADODB_LAYER')) {
 
                $ADODB_COUNTRECS = $crecs;
                if ($rs) {
-                       if (!$rs->EOF) $arr = $rs->fields;
-                       else $arr = array();
+                       if (!$rs->EOF) {
+                               $arr = $rs->fields;
+                       } else {
+                               $arr = array();
+                       }
                        $rs->Close();
                        return $arr;
                }
 
-               $false = false;
-               return $false;
+               return false;
        }
 
-       function CacheGetRow($secs2cache,$sql=false,$inputarr=false)
-       {
+       function CacheGetRow($secs2cache,$sql=false,$inputarr=false) {
                $rs = $this->CacheExecute($secs2cache,$sql,$inputarr);
                if ($rs) {
-                       if (!$rs->EOF) $arr = $rs->fields;
-                       else $arr = array();
+                       if (!$rs->EOF) {
+                               $arr = $rs->fields;
+                       } else {
+                               $arr = array();
+                       }
 
                        $rs->Close();
                        return $arr;
                }
-               $false = false;
-               return $false;
+               return false;
        }
 
        /**
@@ -1686,10 +1870,11 @@ if (!defined('_ADODB_LAYER')) {
        * returns 0 = fail, 1 = update, 2 = insert
        */
 
-       function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false)
-       {
+       function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false) {
                global $ADODB_INCLUDED_LIB;
-               if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
+               if (empty($ADODB_INCLUDED_LIB)) {
+                       include(ADODB_DIR.'/adodb-lib.inc.php');
+               }
 
                return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc);
        }
@@ -1713,40 +1898,41 @@ if (!defined('_ADODB_LAYER')) {
         * @param [inputarr]    array of bind variables
         * @return              the recordset ($rs->databaseType == 'array')
         */
-       function CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false)
-       {
+       function CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false) {
                if (!is_numeric($secs2cache)) {
-                       if ($sql === false) $sql = -1;
-                       if ($offset == -1) $offset = false;
-                                                                         // sql,       nrows, offset,inputarr
+                       if ($sql === false) {
+                               $sql = -1;
+                       }
+                       if ($offset == -1) {
+                               $offset = false;
+                       }
+                                                                                               // sql, nrows, offset,inputarr
                        $rs = $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs);
                } else {
-                       if ($sql === false) $this->outp_throw("Warning: \$sql missing from CacheSelectLimit()",'CacheSelectLimit');
+                       if ($sql === false) {
+                               $this->outp_throw("Warning: \$sql missing from CacheSelectLimit()",'CacheSelectLimit');
+                       }
                        $rs = $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
                }
                return $rs;
        }
 
-
        /**
         * Flush cached recordsets that match a particular $sql statement.
         * If $sql == false, then we purge all files in the cache.
         */
+       function CacheFlush($sql=false,$inputarr=false) {
+               global $ADODB_CACHE_DIR, $ADODB_CACHE;
 
-       /**
-        * Flush cached recordsets that match a particular $sql statement.
-        * If $sql == false, then we purge all files in the cache.
-        */
-       function CacheFlush($sql=false,$inputarr=false)
-       {
-       global $ADODB_CACHE_DIR, $ADODB_CACHE;
-
-               if (empty($ADODB_CACHE)) return false;
+               # Create cache if it does not exist
+               if (empty($ADODB_CACHE)) {
+                       $this->_CreateCache();
+               }
 
                if (!$sql) {
-                        $ADODB_CACHE->flushall($this->debug);
-                return;
-           }
+                       $ADODB_CACHE->flushall($this->debug);
+                       return;
+               }
 
                $f = $this->_gencachename($sql.serialize($inputarr),false);
                return $ADODB_CACHE->flushcache($f, $this->debug);
@@ -1767,20 +1953,24 @@ if (!defined('_ADODB_LAYER')) {
         * Assuming that we can have 50,000 files per directory with good performance,
         * then we can scale to 12.8 million unique cached recordsets. Wow!
         */
-       function _gencachename($sql,$createdir)
-       {
-       global $ADODB_CACHE, $ADODB_CACHE_DIR;
+       function _gencachename($sql,$createdir) {
+               global $ADODB_CACHE, $ADODB_CACHE_DIR;
 
                if ($this->fetchMode === false) {
-               global $ADODB_FETCH_MODE;
+                       global $ADODB_FETCH_MODE;
                        $mode = $ADODB_FETCH_MODE;
                } else {
                        $mode = $this->fetchMode;
                }
                $m = md5($sql.$this->databaseType.$this->database.$this->user.$mode);
-               if (!$ADODB_CACHE->createdir) return $m;
-               if (!$createdir) $dir = $ADODB_CACHE->getdirname($m);
-               else $dir = $ADODB_CACHE->createdir($m, $this->debug);
+               if (!$ADODB_CACHE->createdir) {
+                       return $m;
+               }
+               if (!$createdir) {
+                       $dir = $ADODB_CACHE->getdirname($m);
+               } else {
+                       $dir = $ADODB_CACHE->createdir($m, $this->debug);
+               }
 
                return $dir.'/adodb_'.$m.'.cache';
        }
@@ -1793,13 +1983,14 @@ if (!defined('_ADODB_LAYER')) {
         *                                        This is an optional parameter.
         * @param sql           SQL statement to execute
         * @param [inputarr]    holds the input data  to bind to
-        * @return              RecordSet or false
+        * @return              RecordSet or false
         */
-       function CacheExecute($secs2cache,$sql=false,$inputarr=false)
-       {
-       global $ADODB_CACHE;
+       function CacheExecute($secs2cache,$sql=false,$inputarr=false) {
+               global $ADODB_CACHE;
 
-               if (empty($ADODB_CACHE)) $this->_CreateCache();
+               if (empty($ADODB_CACHE)) {
+                       $this->_CreateCache();
+               }
 
                if (!is_numeric($secs2cache)) {
                        $inputarr = $sql;
@@ -1832,13 +2023,14 @@ if (!defined('_ADODB_LAYER')) {
                                if (get_magic_quotes_runtime() && !$this->memCache) {
                                        ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :(");
                                }
-                               if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (this is a notice and not an error)");
+                               if ($this->debug !== -1) {
+                                       ADOConnection::outp( " $md5file cache failure: $err (this is a notice and not an error)");
+                               }
                        }
 
                        $rs = $this->Execute($sqlparam,$inputarr);
 
                        if ($rs) {
-
                                $eof = $rs->EOF;
                                $rs = $this->_rs2rs($rs); // read entire recordset into memory immediately
                                $rs->timeCreated = time(); // used by caching
@@ -1859,7 +2051,9 @@ if (!defined('_ADODB_LAYER')) {
                                                // do not call error handling for just a warning
                                        }
 
-                                       if ($this->debug) ADOConnection::outp( " ".$em);
+                                       if ($this->debug) {
+                                               ADOConnection::outp( " ".$em);
+                                       }
                                }
                                if ($rs->EOF && !$eof) {
                                        $rs->MoveFirst();
@@ -1867,8 +2061,9 @@ if (!defined('_ADODB_LAYER')) {
                                        $rs->connection = $this; // Pablo suggestion
                                }
 
-                       } else if (!$this->memCache)
+                       } else if (!$this->memCache) {
                                $ADODB_CACHE->flushcache($md5file);
+                       }
                } else {
                        $this->_errorMsg = '';
                        $this->_errorCode = 0;
@@ -1877,14 +2072,18 @@ if (!defined('_ADODB_LAYER')) {
                                $fn = $this->fnCacheExecute;
                                $fn($this, $secs2cache, $sql, $inputarr);
                        }
-               // ok, set cached object found
+                       // ok, set cached object found
                        $rs->connection = $this; // Pablo suggestion
                        if ($this->debug){
-                               if ($this->debug == 99) adodb_backtrace();
+                               if ($this->debug == 99) {
+                                       adodb_backtrace();
+                               }
                                $inBrowser = isset($_SERVER['HTTP_USER_AGENT']);
                                $ttl = $rs->timeCreated + $secs2cache - time();
                                $s = is_array($sql) ? $sql[0] : $sql;
-                               if ($inBrowser) $s = '<i>'.htmlspecialchars($s).'</i>';
+                               if ($inBrowser) {
+                                       $s = '<i>'.htmlspecialchars($s).'</i>';
+                               }
 
                                ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]");
                        }
@@ -1900,38 +2099,38 @@ if (!defined('_ADODB_LAYER')) {
 
                $forceUpdate means that even if the data has not changed, perform update.
         */
-       function AutoExecute($table, $fields_values, $mode = 'INSERT', $where = FALSE, $forceUpdate=true, $magicq=false)
-       {
-               $false = false;
-               $sql = 'SELECT * FROM '.$table;
-               if ($where!==FALSE) $sql .= ' WHERE '.$where;
-               else if ($mode == 'UPDATE' || $mode == 2 /* DB_AUTOQUERY_UPDATE */) {
-                       $this->outp_throw('AutoExecute: Illegal mode=UPDATE with empty WHERE clause','AutoExecute');
-                       return $false;
+       function AutoExecute($table, $fields_values, $mode = 'INSERT', $where = false, $forceUpdate = true, $magicq = false) {
+               if ($where === false && ($mode == 'UPDATE' || $mode == 2 /* DB_AUTOQUERY_UPDATE */) ) {
+                       $this->outp_throw('AutoExecute: Illegal mode=UPDATE with empty WHERE clause', 'AutoExecute');
+                       return false;
+               }
+
+               $sql = "SELECT * FROM $table";
+               $rs = $this->SelectLimit($sql, 1);
+               if (!$rs) {
+                       return false; // table does not exist
                }
 
-               $rs = $this->SelectLimit($sql,1);
-               if (!$rs) return $false; // table does not exist
                $rs->tableName = $table;
+               if ($where !== false) {
+                       $sql .= " WHERE $where";
+               }
                $rs->sql = $sql;
 
-               switch((string) $mode) {
-               case 'UPDATE':
-               case '2':
-                       $sql = $this->GetUpdateSQL($rs, $fields_values, $forceUpdate, $magicq);
-                       break;
-               case 'INSERT':
-               case '1':
-                       $sql = $this->GetInsertSQL($rs, $fields_values, $magicq);
-                       break;
-               default:
-                       $this->outp_throw("AutoExecute: Unknown mode=$mode",'AutoExecute');
-                       return $false;
+               switch($mode) {
+                       case 'UPDATE':
+                       case DB_AUTOQUERY_UPDATE:
+                               $sql = $this->GetUpdateSQL($rs, $fields_values, $forceUpdate, $magicq);
+                               break;
+                       case 'INSERT':
+                       case DB_AUTOQUERY_INSERT:
+                               $sql = $this->GetInsertSQL($rs, $fields_values, $magicq);
+                               break;
+                       default:
+                               $this->outp_throw("AutoExecute: Unknown mode=$mode", 'AutoExecute');
+                               return false;
                }
-               $ret = false;
-               if ($sql) $ret = $this->Execute($sql);
-               if ($ret) $ret = true;
-               return $ret;
+               return $sql && $this->Execute($sql);
        }
 
 
@@ -1946,20 +2145,21 @@ if (!defined('_ADODB_LAYER')) {
         *
         * "Jonathan Younger" <jyounger@unilab.com>
         */
-       function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=null)
-       {
+       function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=null) {
                global $ADODB_INCLUDED_LIB;
 
                // ********************************************************
                // This is here to maintain compatibility
                // with older adodb versions. Sets force type to force nulls if $forcenulls is set.
                if (!isset($force)) {
-                               global $ADODB_FORCE_TYPE;
-                           $force = $ADODB_FORCE_TYPE;
+                       global $ADODB_FORCE_TYPE;
+                       $force = $ADODB_FORCE_TYPE;
                }
                // ********************************************************
 
-               if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
+               if (empty($ADODB_INCLUDED_LIB)) {
+                       include(ADODB_DIR.'/adodb-lib.inc.php');
+               }
                return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq,$force);
        }
 
@@ -1971,15 +2171,15 @@ if (!defined('_ADODB_LAYER')) {
         * Note: This function should only be used on a recordset
         *       that is run against a single table.
         */
-       function GetInsertSQL(&$rs, $arrFields,$magicq=false,$force=null)
-       {
+       function GetInsertSQL(&$rs, $arrFields,$magicq=false,$force=null) {
                global $ADODB_INCLUDED_LIB;
                if (!isset($force)) {
                        global $ADODB_FORCE_TYPE;
                        $force = $ADODB_FORCE_TYPE;
-
                }
-               if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
+               if (empty($ADODB_INCLUDED_LIB)) {
+                       include(ADODB_DIR.'/adodb-lib.inc.php');
+               }
                return _adodb_getinsertsql($this,$rs,$arrFields,$magicq,$force);
        }
 
@@ -2002,9 +2202,7 @@ if (!defined('_ADODB_LAYER')) {
        *       $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
        *       $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
        */
-
-       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
-       {
+       function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB') {
                return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
        }
 
@@ -2017,53 +2215,54 @@ if (!defined('_ADODB_LAYER')) {
        *       $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
        *       $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1');
        */
-       function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
-       {
+       function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') {
                $fd = fopen($path,'rb');
-               if ($fd === false) return false;
+               if ($fd === false) {
+                       return false;
+               }
                $val = fread($fd,filesize($path));
                fclose($fd);
                return $this->UpdateBlob($table,$column,$val,$where,$blobtype);
        }
 
-       function BlobDecode($blob)
-       {
+       function BlobDecode($blob) {
                return $blob;
        }
 
-       function BlobEncode($blob)
-       {
+       function BlobEncode($blob) {
                return $blob;
        }
 
-       function SetCharSet($charset)
-       {
-               return false;
+       function GetCharSet() {
+               return $this->charSet;
        }
 
-       function IfNull( $field, $ifNull )
-       {
+       function SetCharSet($charset) {
+               $this->charSet = $charset;
+               return true;
+       }
+
+       function IfNull( $field, $ifNull ) {
                return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";
        }
 
-       function LogSQL($enable=true)
-       {
+       function LogSQL($enable=true) {
                include_once(ADODB_DIR.'/adodb-perf.inc.php');
 
-               if ($enable) $this->fnExecute = 'adodb_log_sql';
-               else $this->fnExecute = false;
+               if ($enable) {
+                       $this->fnExecute = 'adodb_log_sql';
+               } else {
+                       $this->fnExecute = false;
+               }
 
                $old = $this->_logsql;
                $this->_logsql = $enable;
-               if ($enable && !$old) $this->_affected = false;
+               if ($enable && !$old) {
+                       $this->_affected = false;
+               }
                return $old;
        }
 
-       function GetCharSet()
-       {
-               return false;
-       }
-
        /**
        * Usage:
        *       UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB');
@@ -2071,15 +2270,13 @@ if (!defined('_ADODB_LAYER')) {
        *       $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');
        *       $conn->UpdateClob('clobtable','clobcol',$clob,'id=1');
        */
-       function UpdateClob($table,$column,$val,$where)
-       {
+       function UpdateClob($table,$column,$val,$where) {
                return $this->UpdateBlob($table,$column,$val,$where,'CLOB');
        }
 
        // not the fastest implementation - quick and dirty - jlim
        // for best performance, use the actual $rs->MetaType().
-       function MetaType($t,$len=-1,$fieldobj=false)
-       {
+       function MetaType($t,$len=-1,$fieldobj=false) {
 
                if (empty($this->_metars)) {
                        $rsclass = $this->rsPrefix.$this->databaseType;
@@ -2094,8 +2291,7 @@ if (!defined('_ADODB_LAYER')) {
        *  Change the SQL connection locale to a specified locale.
        *  This is used to get the date formats written depending on the client locale.
        */
-       function SetDateLocale($locale = 'En')
-       {
+       function SetDateLocale($locale = 'En') {
                $this->locale = $locale;
                switch (strtoupper($locale))
                {
@@ -2148,15 +2344,16 @@ if (!defined('_ADODB_LAYER')) {
                        $extra=array(),
                        $relations=array())
        {
-       global $_ADODB_ACTIVE_DBS;
+               global $_ADODB_ACTIVE_DBS;
                ## reduce overhead of adodb.inc.php -- moved to adodb-active-record.inc.php
                ## if adodb-active-recordx is loaded -- should be no issue as they will probably use Find()
-               if (!isset($_ADODB_ACTIVE_DBS))include_once(ADODB_DIR.'/adodb-active-record.inc.php');
+               if (!isset($_ADODB_ACTIVE_DBS)) {
+                       include_once(ADODB_DIR.'/adodb-active-record.inc.php');
+               }
                return adodb_GetActiveRecordsClass($this, $class, $table, $whereOrderBy, $bindarr, $primkeyArr, $extra, $relations);
        }
 
-       function GetActiveRecords($table,$where=false,$bindarr=false,$primkeyArr=false)
-       {
+       function GetActiveRecords($table,$where=false,$bindarr=false,$primkeyArr=false) {
                $arr = $this->GetActiveRecordsClass('ADODB_Active_Record', $table, $where, $bindarr, $primkeyArr);
             &