From f41205a84c5275a9436dbde450d754a90c43ab5d Mon Sep 17 00:00:00 2001 From: Marina Glancy Date: Tue, 8 Dec 2015 11:52:40 +0800 Subject: [PATCH] MDL-52286 core: update ADODB library to 5.21 --- lib/adodb/adodb-active-record.inc.php | 411 ++- lib/adodb/adodb-active-recordx.inc.php | 679 ++--- lib/adodb/adodb-csvlib.inc.php | 6 +- lib/adodb/adodb-datadict.inc.php | 4 +- lib/adodb/adodb-error.inc.php | 4 +- lib/adodb/adodb-errorhandler.inc.php | 4 +- lib/adodb/adodb-errorpear.inc.php | 4 +- lib/adodb/adodb-exceptions.inc.php | 8 +- lib/adodb/adodb-iterator.inc.php | 4 +- lib/adodb/adodb-lib.inc.php | 111 +- lib/adodb/adodb-memcache.lib.inc.php | 8 +- lib/adodb/adodb-pager.inc.php | 6 +- lib/adodb/adodb-pear.inc.php | 8 +- lib/adodb/adodb-perf.inc.php | 6 +- lib/adodb/adodb-php4.inc.php | 4 +- lib/adodb/adodb-time.inc.php | 8 +- lib/adodb/adodb-xmlschema.inc.php | 12 +- lib/adodb/adodb-xmlschema03.inc.php | 21 +- lib/adodb/adodb.inc.php | 2764 ++++++++++++-------- lib/adodb/datadict/datadict-access.inc.php | 8 +- lib/adodb/datadict/datadict-db2.inc.php | 8 +- lib/adodb/datadict/datadict-firebird.inc.php | 4 +- lib/adodb/datadict/datadict-generic.inc.php | 8 +- lib/adodb/datadict/datadict-ibase.inc.php | 8 +- lib/adodb/datadict/datadict-informix.inc.php | 8 +- lib/adodb/datadict/datadict-mssql.inc.php | 8 +- lib/adodb/datadict/datadict-mssqlnative.inc.php | 6 +- lib/adodb/datadict/datadict-mysql.inc.php | 4 +- lib/adodb/datadict/datadict-oci8.inc.php | 12 +- lib/adodb/datadict/datadict-postgres.inc.php | 6 +- lib/adodb/datadict/datadict-sapdb.inc.php | 8 +- lib/adodb/datadict/datadict-sqlite.inc.php | 8 +- lib/adodb/datadict/datadict-sybase.inc.php | 8 +- lib/adodb/drivers/adodb-access.inc.php | 12 +- lib/adodb/drivers/adodb-ado.inc.php | 14 +- lib/adodb/drivers/adodb-ado5.inc.php | 14 +- lib/adodb/drivers/adodb-ado_access.inc.php | 13 +- lib/adodb/drivers/adodb-ado_mssql.inc.php | 13 +- lib/adodb/drivers/adodb-ads.inc.php | 24 +- lib/adodb/drivers/adodb-borland_ibase.inc.php | 14 +- lib/adodb/drivers/adodb-csv.inc.php | 12 +- lib/adodb/drivers/adodb-db2.inc.php | 26 +- lib/adodb/drivers/adodb-db2oci.inc.php | 15 +- lib/adodb/drivers/adodb-db2ora.inc.php | 16 +- lib/adodb/drivers/adodb-fbsql.inc.php | 10 +- lib/adodb/drivers/adodb-firebird.inc.php | 13 +- lib/adodb/drivers/adodb-ibase.inc.php | 340 +-- lib/adodb/drivers/adodb-informix.inc.php | 8 +- lib/adodb/drivers/adodb-informix72.inc.php | 10 +- lib/adodb/drivers/adodb-ldap.inc.php | 850 +++--- lib/adodb/drivers/adodb-mssql.inc.php | 14 +- lib/adodb/drivers/adodb-mssql_n.inc.php | 238 +- lib/adodb/drivers/adodb-mssqlnative.inc.php | 107 +- lib/adodb/drivers/adodb-mssqlpo.inc.php | 15 +- lib/adodb/drivers/adodb-mysql.inc.php | 334 ++- lib/adodb/drivers/adodb-mysqli.inc.php | 721 ++--- lib/adodb/drivers/adodb-mysqlpo.inc.php | 34 +- lib/adodb/drivers/adodb-mysqlt.inc.php | 33 +- lib/adodb/drivers/adodb-netezza.inc.php | 28 +- lib/adodb/drivers/adodb-oci8.inc.php | 613 +++-- lib/adodb/drivers/adodb-oci805.inc.php | 13 +- lib/adodb/drivers/adodb-oci8po.inc.php | 96 +- lib/adodb/drivers/adodb-oci8quercus.inc.php | 10 +- lib/adodb/drivers/adodb-odbc.inc.php | 16 +- lib/adodb/drivers/adodb-odbc_db2.inc.php | 14 +- lib/adodb/drivers/adodb-odbc_mssql.inc.php | 14 +- lib/adodb/drivers/adodb-odbc_oracle.inc.php | 15 +- lib/adodb/drivers/adodb-odbtp.inc.php | 34 +- lib/adodb/drivers/adodb-odbtp_unicode.inc.php | 9 +- lib/adodb/drivers/adodb-oracle.inc.php | 14 +- lib/adodb/drivers/adodb-pdo.inc.php | 337 ++- lib/adodb/drivers/adodb-pdo_mssql.inc.php | 4 +- lib/adodb/drivers/adodb-pdo_mysql.inc.php | 203 +- lib/adodb/drivers/adodb-pdo_oci.inc.php | 4 +- lib/adodb/drivers/adodb-pdo_pgsql.inc.php | 4 +- lib/adodb/drivers/adodb-pdo_sqlite.inc.php | 4 +- lib/adodb/drivers/adodb-pdo_sqlsrv.inc.php | 49 + lib/adodb/drivers/adodb-postgres.inc.php | 4 +- lib/adodb/drivers/adodb-postgres64.inc.php | 113 +- lib/adodb/drivers/adodb-postgres7.inc.php | 291 ++- lib/adodb/drivers/adodb-postgres8.inc.php | 4 +- lib/adodb/drivers/adodb-postgres9.inc.php | 4 +- lib/adodb/drivers/adodb-proxy.inc.php | 8 +- lib/adodb/drivers/adodb-sapdb.inc.php | 18 +- lib/adodb/drivers/adodb-sqlanywhere.inc.php | 13 +- lib/adodb/drivers/adodb-sqlite.inc.php | 273 +- ...{adodb-sqlite.inc.php => adodb-sqlite3.inc.php} | 312 ++- lib/adodb/drivers/adodb-sqlitepo.inc.php | 13 +- lib/adodb/drivers/adodb-sybase.inc.php | 18 +- lib/adodb/drivers/adodb-sybase_ase.inc.php | 10 +- lib/adodb/drivers/adodb-text.inc.php | 389 +++ lib/adodb/drivers/adodb-vfp.inc.php | 15 +- lib/adodb/license.txt | 678 +++-- lib/adodb/perf/perf-db2.inc.php | 6 +- lib/adodb/perf/perf-informix.inc.php | 6 +- lib/adodb/perf/perf-mssql.inc.php | 6 +- lib/adodb/perf/perf-mssqlnative.inc.php | 6 +- lib/adodb/perf/perf-mysql.inc.php | 6 +- lib/adodb/perf/perf-oci8.inc.php | 6 +- lib/adodb/perf/perf-postgres.inc.php | 6 +- lib/adodb/pivottable.inc.php | 4 +- lib/adodb/readme_moodle.txt | 10 +- lib/adodb/rsfilter.inc.php | 4 +- lib/adodb/toexport.inc.php | 5 +- lib/adodb/tohtml.inc.php | 4 +- lib/thirdpartylibs.xml | 2 +- 106 files changed, 6473 insertions(+), 4318 deletions(-) rewrite lib/adodb/drivers/adodb-ldap.inc.php (60%) create mode 100644 lib/adodb/drivers/adodb-pdo_sqlsrv.inc.php copy lib/adodb/drivers/{adodb-sqlite.inc.php => adodb-sqlite3.inc.php} (51%) create mode 100644 lib/adodb/drivers/adodb-text.inc.php rewrite lib/adodb/license.txt (91%) diff --git a/lib/adodb/adodb-active-record.inc.php b/lib/adodb/adodb-active-record.inc.php index 607fa945096..ad9533ce41a 100644 --- a/lib/adodb/adodb-active-record.inc.php +++ b/lib/adodb/adodb-active-record.inc.php @@ -1,7 +1,9 @@ $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)) { - # - $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) { + # + $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; } - # + # } - else + else $keys = array_keys($row); - # - reset($keys); - $this->_original = array(); + # + 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); } - # + # 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); diff --git a/lib/adodb/adodb-active-recordx.inc.php b/lib/adodb/adodb-active-recordx.inc.php index e820144a1ea..771a086e161 100644 --- a/lib/adodb/adodb-active-recordx.inc.php +++ b/lib/adodb/adodb-active-recordx.inc.php @@ -1,7 +1,9 @@ $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) { - # - $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; + # + $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; + } + # } - # + else { + $keys = array_keys($row); } - else - $keys = array_keys($row); - # - reset($keys); - $this->_original = array(); - foreach($table->flds as $name=>$fld) - { - $value = $row[current($keys)]; + + # + 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; + } } } - # + # + 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]; diff --git a/lib/adodb/adodb-csvlib.inc.php b/lib/adodb/adodb-csvlib.inc.php index d70c16f7431..a37945002f4 100644 --- a/lib/adodb/adodb-csvlib.inc.php +++ b/lib/adodb/adodb-csvlib.inc.php @@ -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) { diff --git a/lib/adodb/adodb-datadict.inc.php b/lib/adodb/adodb-datadict.inc.php index b8b881e9de6..7810bdbc284 100644 --- a/lib/adodb/adodb-datadict.inc.php +++ b/lib/adodb/adodb-datadict.inc.php @@ -1,7 +1,9 @@ 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': diff --git a/lib/adodb/adodb-iterator.inc.php b/lib/adodb/adodb-iterator.inc.php index 2d26326b64e..164dfb2ae8e 100644 --- a/lib/adodb/adodb-iterator.inc.php +++ b/lib/adodb/adodb-iterator.inc.php @@ -1,7 +1,9 @@ 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) { diff --git a/lib/adodb/adodb-memcache.lib.inc.php b/lib/adodb/adodb-memcache.lib.inc.php index 6e0040d3a35..25f0fe6abc6 100644 --- a/lib/adodb/adodb-memcache.lib.inc.php +++ b/lib/adodb/adodb-memcache.lib.inc.php @@ -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; diff --git a/lib/adodb/adodb-pager.inc.php b/lib/adodb/adodb-pager.inc.php index a08ced46e09..bdb2ca3b937 100644 --- a/lib/adodb/adodb-pager.inc.php +++ b/lib/adodb/adodb-pager.inc.php @@ -1,7 +1,9 @@ %s \r\n"; var $sql1 = 'sql1'; // used for casting sql1 to text for mssql var $explain = true; - var $helpurl = "LogSQL help"; + var $helpurl = 'LogSQL help'; var $createTableSQL = false; var $maxLength = 2000; diff --git a/lib/adodb/adodb-php4.inc.php b/lib/adodb/adodb-php4.inc.php index e9999835fa4..ab47b2c54b8 100644 --- a/lib/adodb/adodb-php4.inc.php +++ b/lib/adodb/adodb-php4.inc.php @@ -1,7 +1,9 @@ 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); diff --git a/lib/adodb/adodb-xmlschema03.inc.php b/lib/adodb/adodb-xmlschema03.inc.php index 3ed5aecbe07..45a59bbf6e9 100644 --- a/lib/adodb/adodb-xmlschema03.inc.php +++ b/lib/adodb/adodb-xmlschema03.inc.php @@ -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 = '' . "\n" . '' . "\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 . '' . "\n"; + $schema .= $indent + . '
' . "\n"; // grab details from database $rs = $this->db->Execute( 'SELECT * FROM ' . $table . ' WHERE -1' ); diff --git a/lib/adodb/adodb.inc.php b/lib/adodb/adodb.inc.php index a561772fe75..eec531bd29d 100644 --- a/lib/adodb/adodb.inc.php +++ b/lib/adodb/adodb.inc.php @@ -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
\n". $rez."
"); - } + if ($debug) { + ADOConnection::outp( "flushall: $ADODB_CACHE_DIR
\n". $rez."
"); + } + } 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 = ' '; 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 .= "
\n"; + if ($newline) { + $msg .= "
\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" - */ - function QMagic($s) - { + * Requested by "Karsten Dambekalns" + */ + 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.
- b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.
- 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.
+ * b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.
+ * 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 // 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( '

Insert_ID error

'); 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( '

Affected_Rows error

',false); + if ($this->debug) { + ADOConnection::outp( '

Affected_Rows error

',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 = ''.htmlspecialchars($s).''; + if ($inBrowser) { + $s = ''.htmlspecialchars($s).''; + } 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" */ - 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); return $arr; } @@ -2164,8 +2361,7 @@ if (!defined('_ADODB_LAYER')) { /** * Close Connection */ - function Close() - { + function Close() { $rez = $this->_close(); $this->_connectionID = false; return $rez; @@ -2176,15 +2372,15 @@ if (!defined('_ADODB_LAYER')) { * * @return true if succeeded or false if database does not support transactions */ - function BeginTrans() - { - if ($this->debug) ADOConnection::outp("BeginTrans: Transactions not supported for this driver"); + function BeginTrans() { + if ($this->debug) { + ADOConnection::outp("BeginTrans: Transactions not supported for this driver"); + } return false; } /* set transaction mode */ - function SetTransactionMode( $transaction_mode ) - { + function SetTransactionMode( $transaction_mode ) { $transaction_mode = $this->MetaTransaction($transaction_mode, $this->dataProvider); $this->_transmode = $transaction_mode; } @@ -2194,8 +2390,7 @@ http://dev.mysql.com/doc/refman/5.0/en/innodb-transaction-isolation.html http://www.postgresql.org/docs/8.1/interactive/sql-set-transaction.html http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_10005.htm */ - function MetaTransaction($mode,$db) - { + function MetaTransaction($mode,$db) { $mode = strtoupper($mode); $mode = str_replace('ISOLATION LEVEL ','',$mode); @@ -2241,8 +2436,9 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return true/false. */ - function CommitTrans($ok=true) - { return true;} + function CommitTrans($ok=true) { + return true; + } /** @@ -2250,8 +2446,9 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return true/false. */ - function RollbackTrans() - { return false;} + function RollbackTrans() { + return false; + } /** @@ -2260,26 +2457,29 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return an array of database names. */ - function MetaDatabases() - { + function MetaDatabases() { global $ADODB_FETCH_MODE; - if ($this->metaDatabasesSQL) { - $save = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - - if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + if ($this->metaDatabasesSQL) { + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - $arr = $this->GetCol($this->metaDatabasesSQL); - if (isset($savem)) $this->SetFetchMode($savem); - $ADODB_FETCH_MODE = $save; + if ($this->fetchMode !== false) { + $savem = $this->SetFetchMode(false); + } - return $arr; + $arr = $this->GetCol($this->metaDatabasesSQL); + if (isset($savem)) { + $this->SetFetchMode($savem); } + $ADODB_FETCH_MODE = $save; - return false; + return $arr; } + return false; + } + /** * List procedures or functions in an array. * @param procedureNamePattern a procedure name pattern; must match the procedure name as it is stored in the database @@ -2297,15 +2497,14 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * ) * ) */ - function MetaProcedures($procedureNamePattern = null, $catalog = null, $schemaPattern = null) - { + function MetaProcedures($procedureNamePattern = null, $catalog = null, $schemaPattern = null) { return false; } /** * @param ttype can either be 'VIEW' or 'TABLE' or false. - * If false, both views and tables are returned. + * If false, both views and tables are returned. * "VIEW" returns only views * "TABLE" returns only tables * @param showSchema returns the schema/user with the table name, eg. USER.TABLE @@ -2313,26 +2512,29 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return array of tables for current database. */ - function MetaTables($ttype=false,$showSchema=false,$mask=false) - { - global $ADODB_FETCH_MODE; - + function MetaTables($ttype=false,$showSchema=false,$mask=false) { + global $ADODB_FETCH_MODE; - $false = false; if ($mask) { - return $false; + return false; } if ($this->metaTablesSQL) { $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + if ($this->fetchMode !== false) { + $savem = $this->SetFetchMode(false); + } $rs = $this->Execute($this->metaTablesSQL); - if (isset($savem)) $this->SetFetchMode($savem); + if (isset($savem)) { + $this->SetFetchMode($savem); + } $ADODB_FETCH_MODE = $save; - if ($rs === false) return $false; + if ($rs === false) { + return false; + } $arr = $rs->GetArray(); $arr2 = array(); @@ -2343,9 +2545,13 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 for ($i=0; $i < sizeof($arr); $i++) { if ($hast) { if ($showt == 0) { - if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]); + if (strncmp($arr[$i][1],'T',1) == 0) { + $arr2[] = trim($arr[$i][0]); + } } else { - if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]); + if (strncmp($arr[$i][1],'V',1) == 0) { + $arr2[] = trim($arr[$i][0]); + } } } else $arr2[] = trim($arr[$i][0]); @@ -2353,12 +2559,11 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 $rs->Close(); return $arr2; } - return $false; + return false; } - function _findschema(&$table,&$schema) - { + function _findschema(&$table,&$schema) { if (!$schema && ($at = strpos($table,'.')) !== false) { $schema = substr($table,0,$at); $table = substr($table,$at+1); @@ -2375,24 +2580,26 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return array of ADOFieldObjects for current table. */ - function MetaColumns($table,$normalize=true) - { - global $ADODB_FETCH_MODE; - - $false = false; + function MetaColumns($table,$normalize=true) { + global $ADODB_FETCH_MODE; if (!empty($this->metaColumnsSQL)) { - $schema = false; $this->_findschema($table,$schema); $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + if ($this->fetchMode !== false) { + $savem = $this->SetFetchMode(false); + } $rs = $this->Execute(sprintf($this->metaColumnsSQL,($normalize)?strtoupper($table):$table)); - if (isset($savem)) $this->SetFetchMode($savem); + if (isset($savem)) { + $this->SetFetchMode($savem); + } $ADODB_FETCH_MODE = $save; - if ($rs === false || $rs->EOF) return $false; + if ($rs === false || $rs->EOF) { + return false; + } $retarr = array(); while (!$rs->EOF) { //print_r($rs->fields); @@ -2400,20 +2607,28 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 $fld->name = $rs->fields[0]; $fld->type = $rs->fields[1]; if (isset($rs->fields[3]) && $rs->fields[3]) { - if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3]; + if ($rs->fields[3]>0) { + $fld->max_length = $rs->fields[3]; + } $fld->scale = $rs->fields[4]; - if ($fld->scale>0) $fld->max_length += 1; - } else + if ($fld->scale>0) { + $fld->max_length += 1; + } + } else { $fld->max_length = $rs->fields[2]; + } - if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld; - else $retarr[strtoupper($fld->name)] = $fld; + if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) { + $retarr[] = $fld; + } else { + $retarr[strtoupper($fld->name)] = $fld; + } $rs->MoveNext(); } $rs->Close(); return $retarr; } - return $false; + return false; } /** @@ -2433,10 +2648,8 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * ) * ) */ - function MetaIndexes($table, $primary = false, $owner = false) - { - $false = false; - return $false; + function MetaIndexes($table, $primary = false, $owner = false) { + return false; } /** @@ -2445,12 +2658,10 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return array of column names for current table. */ - function MetaColumnNames($table, $numIndexes=false,$useattnum=false /* only for postgres */) - { + function MetaColumnNames($table, $numIndexes=false,$useattnum=false /* only for postgres */) { $objarr = $this->MetaColumns($table); if (!is_array($objarr)) { - $false = false; - return $false; + return false; } $arr = array(); if ($numIndexes) { @@ -2477,8 +2688,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return concatenated string */ - function Concat() - { + function Concat() { $arr = func_get_args(); return implode($this->concat_operator, $arr); } @@ -2491,39 +2701,48 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return date string in database date format */ - function DBDate($d, $isfld=false) - { - if (empty($d) && $d !== 0) return 'null'; - if ($isfld) return $d; - - if (is_object($d)) return $d->format($this->fmtDate); - + function DBDate($d, $isfld=false) { + if (empty($d) && $d !== 0) { + return 'null'; + } + if ($isfld) { + return $d; + } + if (is_object($d)) { + return $d->format($this->fmtDate); + } if (is_string($d) && !is_numeric($d)) { - if ($d === 'null') return $d; + if ($d === 'null') { + return $d; + } if (strncmp($d,"'",1) === 0) { $d = _adodb_safedateq($d); return $d; } - if ($this->isoDates) return "'$d'"; + if ($this->isoDates) { + return "'$d'"; + } $d = ADOConnection::UnixDate($d); } return adodb_date($this->fmtDate,$d); } - function BindDate($d) - { + function BindDate($d) { $d = $this->DBDate($d); - if (strncmp($d,"'",1)) return $d; + if (strncmp($d,"'",1)) { + return $d; + } return substr($d,1,strlen($d)-2); } - function BindTimeStamp($d) - { + function BindTimeStamp($d) { $d = $this->DBTimeStamp($d); - if (strncmp($d,"'",1)) return $d; + if (strncmp($d,"'",1)) { + return $d; + } return substr($d,1,strlen($d)-2); } @@ -2536,17 +2755,25 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return timestamp string in database timestamp format */ - function DBTimeStamp($ts,$isfld=false) - { - if (empty($ts) && $ts !== 0) return 'null'; - if ($isfld) return $ts; - if (is_object($ts)) return $ts->format($this->fmtTimeStamp); + function DBTimeStamp($ts,$isfld=false) { + if (empty($ts) && $ts !== 0) { + return 'null'; + } + if ($isfld) { + return $ts; + } + if (is_object($ts)) { + return $ts->format($this->fmtTimeStamp); + } # strlen(14) allows YYYYMMDDHHMMSS format - if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14)) + if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14)) { return adodb_date($this->fmtTimeStamp,$ts); + } - if ($ts === 'null') return $ts; + if ($ts === 'null') { + return $ts; + } if ($this->isoDates && strlen($ts) !== 14) { $ts = _adodb_safedate($ts); return "'$ts'"; @@ -2561,19 +2788,24 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format */ - static function UnixDate($v) - { + static function UnixDate($v) { if (is_object($v)) { // odbtp support //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 ) return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year); } - if (is_numeric($v) && strlen($v) !== 8) return $v; - if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", - ($v), $rr)) return false; + if (is_numeric($v) && strlen($v) !== 8) { + return $v; + } + if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", $v, $rr)) { + return false; + } + + if ($rr[1] <= TIMESTAMP_FIRST_YEAR) { + return 0; + } - if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0; // h-m-s-MM-DD-YY return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); } @@ -2585,8 +2817,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format */ - static function UnixTimeStamp($v) - { + static function UnixTimeStamp($v) { if (is_object($v)) { // odbtp support //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 ) @@ -2597,11 +2828,15 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", ($v), $rr)) return false; - if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0; + if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) { + return 0; + } // h-m-s-MM-DD-YY - if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); - return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]); + if (!isset($rr[5])) { + return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]); + } + return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]); } /** @@ -2609,58 +2844,63 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * Format database date based on user defined format. * - * @param v is the character date in YYYY-MM-DD format, returned by database - * @param fmt is the format to apply to it, using date() + * @param v is the character date in YYYY-MM-DD format, returned by database + * @param fmt is the format to apply to it, using date() * * @return a date formated as user desires */ - - function UserDate($v,$fmt='Y-m-d',$gmt=false) - { + function UserDate($v,$fmt='Y-m-d',$gmt=false) { $tt = $this->UnixDate($v); // $tt == -1 if pre TIMESTAMP_FIRST_YEAR - if (($tt === false || $tt == -1) && $v != false) return $v; - else if ($tt == 0) return $this->emptyDate; - else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR + if (($tt === false || $tt == -1) && $v != false) { + return $v; + } else if ($tt == 0) { + return $this->emptyDate; + } else if ($tt == -1) { + // pre-TIMESTAMP_FIRST_YEAR } return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt); } - /** + /** * - * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format - * @param fmt is the format to apply to it, using date() + * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format + * @param fmt is the format to apply to it, using date() * * @return a timestamp formated as user desires */ - function UserTimeStamp($v,$fmt='Y-m-d H:i:s',$gmt=false) - { - if (!isset($v)) return $this->emptyTimeStamp; + function UserTimeStamp($v,$fmt='Y-m-d H:i:s',$gmt=false) { + if (!isset($v)) { + return $this->emptyTimeStamp; + } # strlen(14) allows YYYYMMDDHHMMSS format - if (is_numeric($v) && strlen($v)<14) return ($gmt) ? adodb_gmdate($fmt,$v) : adodb_date($fmt,$v); + if (is_numeric($v) && strlen($v)<14) { + return ($gmt) ? adodb_gmdate($fmt,$v) : adodb_date($fmt,$v); + } $tt = $this->UnixTimeStamp($v); // $tt == -1 if pre TIMESTAMP_FIRST_YEAR - if (($tt === false || $tt == -1) && $v != false) return $v; - if ($tt == 0) return $this->emptyTimeStamp; + if (($tt === false || $tt == -1) && $v != false) { + return $v; + } + if ($tt == 0) { + return $this->emptyTimeStamp; + } return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt); } - function escape($s,$magic_quotes=false) - { + function escape($s,$magic_quotes=false) { return $this->addq($s,$magic_quotes); } /** * Quotes a string, without prefixing nor appending quotes. */ - function addq($s,$magic_quotes=false) - { + function addq($s,$magic_quotes=false) { if (!$magic_quotes) { - - if ($this->replaceQuote[0] == '\\'){ + if ($this->replaceQuote[0] == '\\') { // only since php 4.0.5 $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s); //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s)); @@ -2671,9 +2911,11 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 // undo magic quotes for " $s = str_replace('\\"','"',$s); - if ($this->replaceQuote == "\\'" || ini_get('magic_quotes_sybase')) // ' already quoted, no need to change anything + if ($this->replaceQuote == "\\'" || ini_get('magic_quotes_sybase')) { + // ' already quoted, no need to change anything return $s; - else {// change \' to '' for sybase/mssql + } else { + // change \' to '' for sybase/mssql $s = str_replace('\\\\','\\',$s); return str_replace("\\'",$this->replaceQuote,$s); } @@ -2690,10 +2932,8 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return quoted string to be sent back to database */ - function qstr($s,$magic_quotes=false) - { + function qstr($s,$magic_quotes=false) { if (!$magic_quotes) { - if ($this->replaceQuote[0] == '\\'){ // only since php 4.0.5 $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s); @@ -2705,9 +2945,11 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 // undo magic quotes for " $s = str_replace('\\"','"',$s); - if ($this->replaceQuote == "\\'" || ini_get('magic_quotes_sybase')) // ' already quoted, no need to change anything + if ($this->replaceQuote == "\\'" || ini_get('magic_quotes_sybase')) { + // ' already quoted, no need to change anything return "'$s'"; - else {// change \' to '' for sybase/mssql + } else { + // change \' to '' for sybase/mssql $s = str_replace('\\\\','\\',$s); return "'".str_replace("\\'",$this->replaceQuote,$s)."'"; } @@ -2717,7 +2959,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 /** * Will select the supplied $page number from a recordset, given that it is paginated in pages of * $nrows rows per page. It also saves two boolean values saying if the given page is the first - * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination. + * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination. * * See docs-adodb.htm#ex8 for an example of usage. * @@ -2731,12 +2973,16 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * NOTE: phpLens uses a different algorithm and does not use PageExecute(). * */ - function PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0) - { + function PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0) { global $ADODB_INCLUDED_LIB; - if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php'); - if ($this->pageExecuteCountRows) $rs = _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache); - else $rs = _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache); + if (empty($ADODB_INCLUDED_LIB)) { + include(ADODB_DIR.'/adodb-lib.inc.php'); + } + if ($this->pageExecuteCountRows) { + $rs = _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache); + } else { + $rs = _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache); + } return $rs; } @@ -2744,7 +2990,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 /** * Will select the supplied $page number from a recordset, given that it is paginated in pages of * $nrows rows per page. It also saves two boolean values saying if the given page is the first - * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination. + * and/or last one of the recordset. Added by Iván Oliva to provide recordset pagination. * * @param secs2cache seconds to cache data, set to 0 to force query * @param sql @@ -2753,8 +2999,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * @param [inputarr] array of bind variables * @return the recordset ($rs->databaseType == 'array') */ - function CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false) - { + function CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false) { /*switch($this->dataProvider) { case 'postgres': case 'mysql': @@ -2785,42 +3030,33 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 class ADODB_Iterator_empty implements Iterator { - private $rs; + private $rs; - function __construct($rs) - { - $this->rs = $rs; - } - function rewind() - { - } + function __construct($rs) { + $this->rs = $rs; + } - function valid() - { - return !$this->rs->EOF; - } + function rewind() {} - function key() - { - return false; - } + function valid() { + return !$this->rs->EOF; + } - function current() - { - return false; - } + function key() { + return false; + } - function next() - { - } + function current() { + return false; + } - function __call($func, $params) - { + function next() {} + + function __call($func, $params) { return call_user_func_array(array($this->rs, $func), $params); } - function hasMore() - { + function hasMore() { return false; } @@ -2838,21 +3074,80 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 var $_numOfRows = 0; var $fields = false; var $connection = false; - function RowCount() {return 0;} - function RecordCount() {return 0;} - function PO_RecordCount(){return 0;} - function Close(){return true;} - function FetchRow() {return false;} - function FieldCount(){ return 0;} + + function RowCount() { + return 0; + } + + function RecordCount() { + return 0; + } + + function PO_RecordCount() { + return 0; + } + + function Close() { + return true; + } + + function FetchRow() { + return false; + } + + function FieldCount() { + return 0; + } + function Init() {} - function getIterator() {return new ADODB_Iterator_empty($this);} - function GetAssoc() {return array();} + + function getIterator() { + return new ADODB_Iterator_empty($this); + } + + function GetAssoc() { + return array(); + } + + function GetArray() { + return array(); + } + + function GetAll() { + return array(); + } + + function GetArrayLimit() { + return array(); + } + + function GetRows() { + return array(); + } + + function GetRowAssoc() { + return array(); + } + + function MaxRecordCount() { + return 0; + } + + function NumRows() { + return 0; + } + + function NumCols() { + return 0; + } } //============================================================================================== // DATE AND TIME FUNCTIONS //============================================================================================== - if (!defined('ADODB_DATE_VERSION')) include(ADODB_DIR.'/adodb-time.inc.php'); + if (!defined('ADODB_DATE_VERSION')) { + include(ADODB_DIR.'/adodb-time.inc.php'); + } //============================================================================================== // CLASS ADORecordSet @@ -2860,52 +3155,43 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 class ADODB_Iterator implements Iterator { - private $rs; + private $rs; - function __construct($rs) - { - $this->rs = $rs; - } - function rewind() - { - $this->rs->MoveFirst(); - } + function __construct($rs) { + $this->rs = $rs; + } - function valid() - { - return !$this->rs->EOF; - } + function rewind() { + $this->rs->MoveFirst(); + } - function key() - { - return $this->rs->_currentRow; - } + function valid() { + return !$this->rs->EOF; + } - function current() - { - return $this->rs->fields; - } + function key() { + return $this->rs->_currentRow; + } - function next() - { - $this->rs->MoveNext(); - } + function current() { + return $this->rs->fields; + } - function __call($func, $params) - { + function next() { + $this->rs->MoveNext(); + } + + function __call($func, $params) { return call_user_func_array(array($this->rs, $func), $params); } - - function hasMore() - { + function hasMore() { return !$this->rs->EOF; } } - /** * RecordSet class that represents the dataset returned by the database. * To keep memory overhead low, this class holds only the current row in memory. @@ -2913,40 +3199,42 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * means recordcount not known). */ class ADORecordSet implements IteratorAggregate { - /* + + /** * public variables */ var $dataProvider = "native"; - var $fields = false; /// holds the current row data - var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob + var $fields = false; /// holds the current row data + var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob /// in other words, we use a text area for editing. - var $canSeek = false; /// indicates that seek is supported - var $sql; /// sql text + var $canSeek = false; /// indicates that seek is supported + var $sql; /// sql text var $EOF = false; /// Indicates that the current record position is after the last record in a Recordset object. var $emptyTimeStamp = ' '; /// what to display when $time==0 var $emptyDate = ' '; /// what to display when $time==0 var $debug = false; - var $timeCreated=0; /// datetime in Unix format rs created -- for cached recordsets + var $timeCreated=0; /// datetime in Unix format rs created -- for cached recordsets - var $bind = false; /// used by Fields() to hold array - should be private? + var $bind = false; /// used by Fields() to hold array - should be private? var $fetchMode; /// default fetch mode var $connection = false; /// the parent connection - /* + + /** * private variables */ var $_numOfRows = -1; /** number of rows, or -1 */ var $_numOfFields = -1; /** number of fields in recordset */ var $_queryID = -1; /** This variable keeps the result link identifier. */ var $_currentRow = -1; /** This variable keeps the current row in the Recordset. */ - var $_closed = false; /** has recordset been closed */ - var $_inited = false; /** Init() should only be called once */ - var $_obj; /** Used by FetchObj */ + var $_closed = false; /** has recordset been closed */ + var $_inited = false; /** Init() should only be called once */ + var $_obj; /** Used by FetchObj */ var $_names; /** Used by FetchObj */ - var $_currentPage = -1; /** Added by Iván Oliva to implement recordset pagination */ - var $_atFirstPage = false; /** Added by Iván Oliva to implement recordset pagination */ - var $_atLastPage = false; /** Added by Iván Oliva to implement recordset pagination */ + var $_currentPage = -1; /** Added by Iván Oliva to implement recordset pagination */ + var $_atFirstPage = false; /** Added by Iván Oliva to implement recordset pagination */ + var $_atLastPage = false; /** Added by Iván Oliva to implement recordset pagination */ var $_lastPageNo = -1; var $_maxRecordCount = 0; var $datetime = false; @@ -2954,38 +3242,39 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 /** * Constructor * - * @param queryID this is the queryID returned by ADOConnection->_query() + * @param queryID this is the queryID returned by ADOConnection->_query() * */ - function ADORecordSet($queryID) - { + function __construct($queryID) { $this->_queryID = $queryID; } - function getIterator() - { + function __destruct() { + $this->Close(); + } + + function getIterator() { return new ADODB_Iterator($this); } /* this is experimental - i don't really know what to return... */ - function __toString() - { + function __toString() { include_once(ADODB_DIR.'/toexport.inc.php'); return _adodb_export($this,',',',',false,true); } - - function Init() - { - if ($this->_inited) return; + function Init() { + if ($this->_inited) { + return; + } $this->_inited = true; - if ($this->_queryID) @$this->_initrs(); - else { + if ($this->_queryID) { + @$this->_initrs(); + } else { $this->_numOfRows = 0; $this->_numOfFields = 0; } if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) { - $this->_currentRow = 0; if ($this->EOF = ($this->_fetch() === false)) { $this->_numOfRows = 0; // _numOfRows could be -1 @@ -3002,7 +3291,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * the text to display to the user, and 2nd col as the return value. Default * strings are compared with the FIRST column. * - * @param name name of SELECT tag + * @param name name of SELECT tag * @param [defstr] the value to hilite. Use an array for multiple hilites for listbox. * @param [blank1stItem] true to leave the 1st item in list empty * @param [multiple] true for listbox, false for popup @@ -3020,7 +3309,9 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 $size=0, $selectAttr='',$compareFields0=true) { 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_getmenu($this, $name,$defstr,$blank1stItem,$multiple, $size, $selectAttr,$compareFields0); } @@ -3034,8 +3325,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * strings are compared with the SECOND column. * */ - function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='') - { + function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='') { return $this->GetMenu($name,$defstr,$blank1stItem,$multiple, $size, $selectAttr,false); } @@ -3047,7 +3337,9 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 $size=0, $selectAttr='') { 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_getmenu_gp($this, $name,$defstr,$blank1stItem,$multiple, $size, $selectAttr,false); } @@ -3059,9 +3351,8 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return an array indexed by the rows (0-based) from the recordset */ - function GetArray($nRows = -1) - { - global $ADODB_EXTENSION; if ($ADODB_EXTENSION) { + function GetArray($nRows = -1) { + global $ADODB_EXTENSION; if ($ADODB_EXTENSION) { $results = adodb_getall($this,$nRows); return $results; } @@ -3075,8 +3366,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 return $results; } - function GetAll($nRows = -1) - { + function GetAll($nRows = -1) { $arr = $this->GetArray($nRows); return $arr; } @@ -3085,8 +3375,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * Some databases allow multiple recordsets to be returned. This function * will return true if there is a next recordset, or false if no more. */ - function NextRecordSet() - { + function NextRecordSet() { return false; } @@ -3099,8 +3388,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return an array indexed by the rows (0-based) from the recordset */ - function GetArrayLimit($nrows,$offset=-1) - { + function GetArrayLimit($nrows,$offset=-1) { if ($offset <= 0) { $arr = $this->GetArray($nrows); return $arr; @@ -3126,8 +3414,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return an array indexed by the rows (0-based) from the recordset */ - function GetRows($nRows = -1) - { + function GetRows($nRows = -1) { $arr = $this->GetArray($nRows); return $arr; } @@ -3139,25 +3426,31 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * $force_array == true. * * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional - * array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing, - * read the source. + * array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing, + * read the source. * * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and * instead of returning array[col0] => array(remaining cols), return array[col0] => col1 * * @return an associative array indexed by the first column of the array, - * or false if the data has less than 2 cols. + * or false if the data has less than 2 cols. */ - function GetAssoc($force_array = false, $first2cols = false) - { - global $ADODB_EXTENSION; + function GetAssoc($force_array = false, $first2cols = false) { + global $ADODB_EXTENSION; $cols = $this->_numOfFields; if ($cols < 2) { - $false = false; - return $false; + return false; + } + + // Empty recordset + if (!$this->fields) { + return array(); } - $numIndex = is_array($this->fields) && array_key_exists(0, $this->fields); + + // Determine whether the array is associative or 0-based numeric + $numIndex = array_keys($this->fields) == range(0, count($this->fields) - 1); + $results = array(); if (!$first2cols && ($cols > 2 || $force_array)) { @@ -3246,35 +3539,42 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 /** * - * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format - * @param fmt is the format to apply to it, using date() + * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format + * @param fmt is the format to apply to it, using date() * * @return a timestamp formated as user desires */ - function UserTimeStamp($v,$fmt='Y-m-d H:i:s') - { - if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v); + function UserTimeStamp($v,$fmt='Y-m-d H:i:s') { + if (is_numeric($v) && strlen($v)<14) { + return adodb_date($fmt,$v); + } $tt = $this->UnixTimeStamp($v); // $tt == -1 if pre TIMESTAMP_FIRST_YEAR - if (($tt === false || $tt == -1) && $v != false) return $v; - if ($tt === 0) return $this->emptyTimeStamp; + if (($tt === false || $tt == -1) && $v != false) { + return $v; + } + if ($tt === 0) { + return $this->emptyTimeStamp; + } return adodb_date($fmt,$tt); } /** - * @param v is the character date in YYYY-MM-DD format, returned by database - * @param fmt is the format to apply to it, using date() + * @param v is the character date in YYYY-MM-DD format, returned by database + * @param fmt is the format to apply to it, using date() * * @return a date formated as user desires */ - function UserDate($v,$fmt='Y-m-d') - { + function UserDate($v,$fmt='Y-m-d') { $tt = $this->UnixDate($v); // $tt == -1 if pre TIMESTAMP_FIRST_YEAR - if (($tt === false || $tt == -1) && $v != false) return $v; - else if ($tt == 0) return $this->emptyDate; - else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR + if (($tt === false || $tt == -1) && $v != false) { + return $v; + } else if ($tt == 0) { + return $this->emptyDate; + } else if ($tt == -1) { + // pre-TIMESTAMP_FIRST_YEAR } return adodb_date($fmt,$tt); } @@ -3285,8 +3585,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format */ - static function UnixDate($v) - { + static function UnixDate($v) { return ADOConnection::UnixDate($v); } @@ -3296,8 +3595,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format */ - static function UnixTimeStamp($v) - { + static function UnixTimeStamp($v) { return ADOConnection::UnixTimeStamp($v); } @@ -3305,8 +3603,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 /** * PEAR DB Compat - do not use internally */ - function Free() - { + function Free() { return $this->Close(); } @@ -3314,8 +3611,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 /** * PEAR DB compat, number of rows */ - function NumRows() - { + function NumRows() { return $this->_numOfRows; } @@ -3323,8 +3619,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 /** * PEAR DB compat, number of cols */ - function NumCols() - { + function NumCols() { return $this->_numOfFields; } @@ -3334,15 +3629,15 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return false or array containing the current record */ - function FetchRow() - { + function FetchRow() { if ($this->EOF) { - $false = false; - return $false; + return false; } $arr = $this->fields; $this->_currentRow++; - if (!$this->_fetch()) $this->EOF = true; + if (!$this->_fetch()) { + $this->EOF = true; + } return $arr; } @@ -3353,9 +3648,10 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return DB_OK or error object */ - function FetchInto(&$arr) - { - if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false; + function FetchInto(&$arr) { + if ($this->EOF) { + return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false; + } $arr = $this->fields; $this->MoveNext(); return 1; // DB_OK @@ -3367,9 +3663,10 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return true or false */ - function MoveFirst() - { - if ($this->_currentRow == 0) return true; + function MoveFirst() { + if ($this->_currentRow == 0) { + return true; + } return $this->Move(0); } @@ -3379,10 +3676,13 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return true or false */ - function MoveLast() - { - if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1); - if ($this->EOF) return false; + function MoveLast() { + if ($this->_numOfRows >= 0) { + return $this->Move($this->_numOfRows-1); + } + if ($this->EOF) { + return false; + } while (!$this->EOF) { $f = $this->fields; $this->MoveNext(); @@ -3398,11 +3698,12 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return true if there still rows available, or false if there are no more rows (EOF). */ - function MoveNext() - { + function MoveNext() { if (!$this->EOF) { $this->_currentRow++; - if ($this->_fetch()) return true; + if ($this->_fetch()) { + return true; + } } $this->EOF = true; /* -- tested error handling when scrolling cursor -- seems useless. @@ -3424,15 +3725,23 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return true if there still rows available, or false if there are no more rows (EOF). */ - function Move($rowNumber = 0) - { + function Move($rowNumber = 0) { $this->EOF = false; - if ($rowNumber == $this->_currentRow) return true; - if ($rowNumber >= $this->_numOfRows) - if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2; + if ($rowNumber == $this->_currentRow) { + return true; + } + if ($rowNumber >= $this->_numOfRows) { + if ($this->_numOfRows != -1) { + $rowNumber = $this->_numOfRows-2; + } + } - if ($this->canSeek) { + if ($rowNumber < 0) { + $this->EOF = true; + return false; + } + if ($this->canSeek) { if ($this->_seek($rowNumber)) { $this->_currentRow = $rowNumber; if ($this->_fetch()) { @@ -3443,18 +3752,21 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 return false; } } else { - if ($rowNumber < $this->_currentRow) return false; + if ($rowNumber < $this->_currentRow) { + return false; + } global $ADODB_EXTENSION; if ($ADODB_EXTENSION) { while (!$this->EOF && $this->_currentRow < $rowNumber) { adodb_movenext($this); } } else { - while (! $this->EOF && $this->_currentRow < $rowNumber) { $this->_currentRow++; - if (!$this->_fetch()) $this->EOF = true; + if (!$this->_fetch()) { + $this->EOF = true; + } } } return !($this->EOF); @@ -3474,34 +3786,59 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return the value of $colname column */ - function Fields($colname) - { + function Fields($colname) { return $this->fields[$colname]; } /** + * Defines the function to use for table fields case conversion + * depending on ADODB_ASSOC_CASE + * @return string strtolower/strtoupper or false if no conversion needed + */ + protected function AssocCaseConvertFunction($case = ADODB_ASSOC_CASE) { + switch($case) { + case ADODB_ASSOC_CASE_UPPER: + return 'strtoupper'; + case ADODB_ASSOC_CASE_LOWER: + return 'strtolower'; + case ADODB_ASSOC_CASE_NATIVE: + default: + return false; + } + } + + /** * Builds the bind array associating keys to recordset fields * * @param int $upper Case for the array keys, defaults to uppercase * (see ADODB_ASSOC_CASE_xxx constants) */ - function GetAssocKeys($upper=ADODB_ASSOC_CASE_UPPER) - { + function GetAssocKeys($upper = ADODB_ASSOC_CASE) { + if ($this->bind) { + return; + } $this->bind = array(); + + // Define case conversion function for ASSOC fetch mode + $fn_change_case = $this->AssocCaseConvertFunction($upper); + + // Build the bind array for ($i=0; $i < $this->_numOfFields; $i++) { $o = $this->FetchField($i); - switch($upper) { - case ADODB_ASSOC_CASE_LOWER: - $key = strtolower($o->name); - break; - case ADODB_ASSOC_CASE_UPPER: - $key = strtoupper($o->name); - break; - case ADODB_ASSOC_CASE_NATIVE: - default: - $key = $o->name; - break; + + // Set the array's key + if(is_numeric($o->name)) { + // Just use the field ID + $key = $i; + } + elseif( $fn_change_case ) { + // Convert the key's case + $key = $fn_change_case($o->name); + } + else { + $key = $o->name; } + $this->bind[$key] = $i; } } @@ -3513,12 +3850,10 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * @param int $upper Case for the array keys, defaults to uppercase * (see ADODB_ASSOC_CASE_xxx constants) */ - function GetRowAssoc($upper=ADODB_ASSOC_CASE_UPPER) - { + function GetRowAssoc($upper = ADODB_ASSOC_CASE) { $record = array(); - if (!$this->bind) { - $this->GetAssocKeys($upper); - } + $this->GetAssocKeys($upper); + foreach($this->bind as $k => $v) { if( array_key_exists( $v, $this->fields ) ) { $record[$k] = $this->fields[$v]; @@ -3537,8 +3872,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return true or false */ - function Close() - { + function Close() { // free connection object - this seems to globally free the object // and not merely the reference, so don't do this... // $this->connection = false; @@ -3554,15 +3888,16 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return the number of rows or -1 if this is not supported */ - function RecordCount() {return $this->_numOfRows;} + function RecordCount() { + return $this->_numOfRows; + } /* * If we are using PageExecute(), this will return the maximum possible rows * that can be returned when paging a recordset. */ - function MaxRecordCount() - { + function MaxRecordCount() { return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount(); } @@ -3571,7 +3906,9 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return the number of rows or -1 if this is not supported */ - function RowCount() {return $this->_numOfRows;} + function RowCount() { + return $this->_numOfRows; + } /** @@ -3588,9 +3925,13 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 // the database doesn't support native recordcount, so we do a workaround if ($lnumrows == -1 && $this->connection) { IF ($table) { - if ($condition) $condition = " WHERE " . $condition; + if ($condition) { + $condition = " WHERE " . $condition; + } $resultrows = $this->connection->Execute("SELECT COUNT(*) FROM $table $condition"); - if ($resultrows) $lnumrows = reset($resultrows->fields); + if ($resultrows) { + $lnumrows = reset($resultrows->fields); + } } } return $lnumrows; @@ -3600,20 +3941,26 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 /** * @return the current row in the recordset. If at EOF, will return the last row. 0-based. */ - function CurrentRow() {return $this->_currentRow;} + function CurrentRow() { + return $this->_currentRow; + } /** * synonym for CurrentRow -- for ADO compat * * @return the current row in the recordset. If at EOF, will return the last row. 0-based. */ - function AbsolutePosition() {return $this->_currentRow;} + function AbsolutePosition() { + return $this->_currentRow; + } /** * @return the number of columns in the recordset. Some databases will set this to 0 * if no records are returned, others will return the number of columns in the query. */ - function FieldCount() {return $this->_numOfFields;} + function FieldCount() { + return $this->_numOfFields; + } /** @@ -3623,20 +3970,17 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return the ADOFieldObject for that column, or false. */ - function FetchField($fieldoffset = -1) - { + function FetchField($fieldoffset = -1) { // must be defined by child class - $false = false; - return $false; + return false; } /** * Get the ADOFieldObjects of all columns in an array. * */ - function FieldTypesArray() - { + function FieldTypesArray() { $arr = array(); for ($i=0, $max=$this->_numOfFields; $i < $max; $i++) $arr[] = $this->FetchField($i); @@ -3649,8 +3993,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return the object with the properties set to the fields of the current row */ - function FetchObj() - { + function FetchObj() { $o = $this->FetchObject(false); return $o; } @@ -3663,8 +4006,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @return the object with the properties set to the fields of the current row */ - function FetchObject($isupper=true) - { + function FetchObject($isupper=true) { if (empty($this->_obj)) { $this->_obj = new ADOFetchObj(); $this->_names = array(); @@ -3674,13 +4016,19 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 } } $i = 0; - if (PHP_VERSION >= 5) $o = clone($this->_obj); - else $o = $this->_obj; + if (PHP_VERSION >= 5) { + $o = clone($this->_obj); + } else { + $o = $this->_obj; + } for ($i=0; $i <$this->_numOfFields; $i++) { $name = $this->_names[$i]; - if ($isupper) $n = strtoupper($name); - else $n = $name; + if ($isupper) { + $n = strtoupper($name); + } else { + $n = $name; + } $o->$n = $this->Fields($name); } @@ -3692,12 +4040,11 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * The default is lower-case field names. * * @return the object with the properties set to the fields of the current row, - * or false if EOF + * or false if EOF * * Fixed bug reported by tim@orotech.net */ - function FetchNextObj() - { + function FetchNextObj() { $o = $this->FetchNextObject(false); return $o; } @@ -3710,17 +4057,18 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * @param $isupper to set the object property names to uppercase * * @return the object with the properties set to the fields of the current row, - * or false if EOF + * or false if EOF * * Fixed bug reported by tim@orotech.net */ - function FetchNextObject($isupper=true) - { + function FetchNextObject($isupper=true) { $o = false; if ($this->_numOfRows != 0 && !$this->EOF) { $o = $this->FetchObject($isupper); $this->_currentRow++; - if ($this->_fetch()) return $o; + if ($this->_fetch()) { + return $o; + } } $this->EOF = true; return $o; @@ -3733,7 +4081,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @param t is the type passed in. Normally is ADOFieldObject->type. * @param len is the maximum length of that field. This is because we treat character - * fields bigger than a certain size as a 'B' (blob). + * fields bigger than a certain size as a 'B' (blob). * @param fieldobj is the field object returned by the database driver. Can hold * additional info (eg. primary_key for mysql). * @@ -3741,196 +4089,237 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * C for character < 250 chars * X for teXt (>= 250 chars) * B for Binary - * N for numeric or floating point + * N for numeric or floating point * D for date * T for timestamp - * L for logical/Boolean + * L for logical/Boolean * I for integer * R for autoincrement counter/integer * * */ - function MetaType($t,$len=-1,$fieldobj=false) - { + function MetaType($t,$len=-1,$fieldobj=false) { if (is_object($t)) { $fieldobj = $t; $t = $fieldobj->type; $len = $fieldobj->max_length; } - // changed in 2.32 to hashing instead of switch stmt for speed... - static $typeMap = array( - 'VARCHAR' => 'C', - 'VARCHAR2' => 'C', - 'CHAR' => 'C', - 'C' => 'C', - 'STRING' => 'C', - 'NCHAR' => 'C', - 'NVARCHAR' => 'C', - 'VARYING' => 'C', - 'BPCHAR' => 'C', - 'CHARACTER' => 'C', - 'INTERVAL' => 'C', # Postgres - 'MACADDR' => 'C', # postgres - 'VAR_STRING' => 'C', # mysql - ## - 'LONGCHAR' => 'X', - 'TEXT' => 'X', - 'NTEXT' => 'X', - 'M' => 'X', - 'X' => 'X', - 'CLOB' => 'X', - 'NCLOB' => 'X', - 'LVARCHAR' => 'X', - ## - 'BLOB' => 'B', - 'IMAGE' => 'B', - 'BINARY' => 'B', - 'VARBINARY' => 'B', - 'LONGBINARY' => 'B', - 'B' => 'B', - ## - 'YEAR' => 'D', // mysql - 'DATE' => 'D', - 'D' => 'D', - ## - 'UNIQUEIDENTIFIER' => 'C', # MS SQL Server - ## - 'SMALLDATETIME' => 'T', - 'TIME' => 'T', - 'TIMESTAMP' => 'T', - 'DATETIME' => 'T', - 'TIMESTAMPTZ' => 'T', - 'T' => 'T', - 'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql - ## - 'BOOL' => 'L', - 'BOOLEAN' => 'L', - 'BIT' => 'L', - 'L' => 'L', - ## - 'COUNTER' => 'R', - 'R' => 'R', - 'SERIAL' => 'R', // ifx - 'INT IDENTITY' => 'R', - ## - 'INT' => 'I', - 'INT2' => 'I', - 'INT4' => 'I', - 'INT8' => 'I', - 'INTEGER' => 'I', - 'INTEGER UNSIGNED' => 'I', - 'SHORT' => 'I', - 'TINYINT' => 'I', - 'SMALLINT' => 'I', - 'I' => 'I', - ## - 'LONG' => 'N', // interbase is numeric, oci8 is blob - 'BIGINT' => 'N', // this is bigger than PHP 32-bit integers - 'DECIMAL' => 'N', - 'DEC' => 'N', - 'REAL' => 'N', - 'DOUBLE' => 'N', - 'DOUBLE PRECISION' => 'N', - 'SMALLFLOAT' => 'N', - 'FLOAT' => 'N', - 'NUMBER' => 'N', - 'NUM' => 'N', - 'NUMERIC' => 'N', - 'MONEY' => 'N', - - ## informix 9.2 - 'SQLINT' => 'I', - 'SQLSERIAL' => 'I', - 'SQLSMINT' => 'I', - 'SQLSMFLOAT' => 'N', - 'SQLFLOAT' => 'N', - 'SQLMONEY' => 'N', - 'SQLDECIMAL' => 'N', - 'SQLDATE' => 'D', - 'SQLVCHAR' => 'C', - 'SQLCHAR' => 'C', - 'SQLDTIME' => 'T', - 'SQLINTERVAL' => 'N', - 'SQLBYTES' => 'B', - 'SQLTEXT' => 'X', - ## informix 10 - "SQLINT8" => 'I8', - "SQLSERIAL8" => 'I8', - "SQLNCHAR" => 'C', - "SQLNVCHAR" => 'C', - "SQLLVARCHAR" => 'X', - "SQLBOOL" => 'L' + + // changed in 2.32 to hashing instead of switch stmt for speed... + static $typeMap = array( + 'VARCHAR' => 'C', + 'VARCHAR2' => 'C', + 'CHAR' => 'C', + 'C' => 'C', + 'STRING' => 'C', + 'NCHAR' => 'C', + 'NVARCHAR' => 'C', + 'VARYING' => 'C', + 'BPCHAR' => 'C', + 'CHARACTER' => 'C', + 'INTERVAL' => 'C', # Postgres + 'MACADDR' => 'C', # postgres + 'VAR_STRING' => 'C', # mysql + ## + 'LONGCHAR' => 'X', + 'TEXT' => 'X', + 'NTEXT' => 'X', + 'M' => 'X', + 'X' => 'X', + 'CLOB' => 'X', + 'NCLOB' => 'X', + 'LVARCHAR' => 'X', + ## + 'BLOB' => 'B', + 'IMAGE' => 'B', + 'BINARY' => 'B', + 'VARBINARY' => 'B', + 'LONGBINARY' => 'B', + 'B' => 'B', + ## + 'YEAR' => 'D', // mysql + 'DATE' => 'D', + 'D' => 'D', + ## + 'UNIQUEIDENTIFIER' => 'C', # MS SQL Server + ## + 'SMALLDATETIME' => 'T', + 'TIME' => 'T', + 'TIMESTAMP' => 'T', + 'DATETIME' => 'T', + 'DATETIME2' => 'T', + 'TIMESTAMPTZ' => 'T', + 'T' => 'T', + 'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql + ## + 'BOOL' => 'L', + 'BOOLEAN' => 'L', + 'BIT' => 'L', + 'L' => 'L', + ## + 'COUNTER' => 'R', + 'R' => 'R', + 'SERIAL' => 'R', // ifx + 'INT IDENTITY' => 'R', + ## + 'INT' => 'I', + 'INT2' => 'I', + 'INT4' => 'I', + 'INT8' => 'I', + 'INTEGER' => 'I', + 'INTEGER UNSIGNED' => 'I', + 'SHORT' => 'I', + 'TINYINT' => 'I', + 'SMALLINT' => 'I', + 'I' => 'I', + ## + 'LONG' => 'N', // interbase is numeric, oci8 is blob + 'BIGINT' => 'N', // this is bigger than PHP 32-bit integers + 'DECIMAL' => 'N', + 'DEC' => 'N', + 'REAL' => 'N', + 'DOUBLE' => 'N', + 'DOUBLE PRECISION' => 'N', + 'SMALLFLOAT' => 'N', + 'FLOAT' => 'N', + 'NUMBER' => 'N', + 'NUM' => 'N', + 'NUMERIC' => 'N', + 'MONEY' => 'N', + + ## informix 9.2 + 'SQLINT' => 'I', + 'SQLSERIAL' => 'I', + 'SQLSMINT' => 'I', + 'SQLSMFLOAT' => 'N', + 'SQLFLOAT' => 'N', + 'SQLMONEY' => 'N', + 'SQLDECIMAL' => 'N', + 'SQLDATE' => 'D', + 'SQLVCHAR' => 'C', + 'SQLCHAR' => 'C', + 'SQLDTIME' => 'T', + 'SQLINTERVAL' => 'N', + 'SQLBYTES' => 'B', + 'SQLTEXT' => 'X', + ## informix 10 + "SQLINT8" => 'I8', + "SQLSERIAL8" => 'I8', + "SQLNCHAR" => 'C', + "SQLNVCHAR" => 'C', + "SQLLVARCHAR" => 'X', + "SQLBOOL" => 'L' ); $tmap = false; $t = strtoupper($t); $tmap = (isset($typeMap[$t])) ? $typeMap[$t] : 'N'; switch ($tmap) { - case 'C': - - // is the char field is too long, return as text field... - if ($this->blobSize >= 0) { - if ($len > $this->blobSize) return 'X'; - } else if ($len > 250) { - return 'X'; - } - return 'C'; + case 'C': + // is the char field is too long, return as text field... + if ($this->blobSize >= 0) { + if ($len > $this->blobSize) { + return 'X'; + } + } else if ($len > 250) { + return 'X'; + } + return 'C'; - case 'I': - if (!empty($fieldobj->primary_key)) return 'R'; - return 'I'; + case 'I': + if (!empty($fieldobj->primary_key)) { + return 'R'; + } + return 'I'; - case false: - return 'N'; + case false: + return 'N'; - case 'B': - if (isset($fieldobj->binary)) - return ($fieldobj->binary) ? 'B' : 'X'; - return 'B'; + case 'B': + if (isset($fieldobj->binary)) { + return ($fieldobj->binary) ? 'B' : 'X'; + } + return 'B'; - case 'D': - if (!empty($this->connection) && !empty($this->connection->datetime)) return 'T'; - return 'D'; + case 'D': + if (!empty($this->connection) && !empty($this->connection->datetime)) { + return 'T'; + } + return 'D'; - default: - if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B'; - return $tmap; + default: + if ($t == 'LONG' && $this->dataProvider == 'oci8') { + return 'B'; + } + return $tmap; } } + /** + * Convert case of field names associative array, if needed + * @return void + */ + protected function _updatefields() + { + if( empty($this->fields)) { + return; + } + + // Determine case conversion function + $fn_change_case = $this->AssocCaseConvertFunction(); + if(!$fn_change_case) { + // No conversion needed + return; + } + + $arr = array(); + + // Change the case + foreach($this->fields as $k => $v) { + if (!is_integer($k)) { + $k = $fn_change_case($k); + } + $arr[$k] = $v; + } + $this->fields = $arr; + } function _close() {} /** * set/returns the current recordset page when paginating */ - function AbsolutePage($page=-1) - { - if ($page != -1) $this->_currentPage = $page; + function AbsolutePage($page=-1) { + if ($page != -1) { + $this->_currentPage = $page; + } return $this->_currentPage; } /** * set/returns the status of the atFirstPage flag when paginating */ - function AtFirstPage($status=false) - { - if ($status != false) $this->_atFirstPage = $status; + function AtFirstPage($status=false) { + if ($status != false) { + $this->_atFirstPage = $status; + } return $this->_atFirstPage; } - function LastPageNo($page = false) - { - if ($page != false) $this->_lastPageNo = $page; + function LastPageNo($page = false) { + if ($page != false) { + $this->_lastPageNo = $page; + } return $this->_lastPageNo; } /** * set/returns the status of the atLastPage flag when paginating */ - function AtLastPage($status=false) - { - if ($status != false) $this->_atLastPage = $status; + function AtLastPage($status=false) { + if ($status != false) { + $this->_atLastPage = $status; + } return $this->_atLastPage; } @@ -3946,12 +4335,11 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * Note that the constructor is different from the standard ADORecordSet */ - class ADORecordSet_array extends ADORecordSet { var $databaseType = 'array'; - var $_array; // holds the 2-dimensional data array + var $_array; // holds the 2-dimensional data array var $_types; // the array of types of each column (C B I L M) var $_colnames; // names of each column in array var $_skiprow1; // skip 1st row because it holds column names @@ -3961,25 +4349,25 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 var $insertid = false; var $sql = ''; var $compat = false; + /** * Constructor - * */ - function ADORecordSet_array($fakeid=1) - { - global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH; + function __construct($fakeid=1) { + global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH; // fetch() on EOF does not delete $this->fields $this->compat = !empty($ADODB_COMPAT_FETCH); - $this->ADORecordSet($fakeid); // fake queryID + parent::__construct($fakeid); // fake queryID $this->fetchMode = $ADODB_FETCH_MODE; } - function _transpose($addfieldnames=true) - { - global $ADODB_INCLUDED_LIB; + function _transpose($addfieldnames=true) { + 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'); + } $hdr = true; $fobjs = $addfieldnames ? $this->_fieldobjects : false; @@ -4018,14 +4406,13 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * @param [colnames] array of column names. If set, then the first row of * $array should not hold the column names. */ - function InitArray($array,$typearr,$colnames=false) - { + function InitArray($array,$typearr,$colnames=false) { $this->_array = $array; $this->_types = $typearr; if ($colnames) { $this->_skiprow1 = false; $this->_colnames = $colnames; - } else { + } else { $this->_skiprow1 = true; $this->_colnames = $array[0]; } @@ -4039,8 +4426,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * unless paramter $colnames is used. * @param fieldarr holds an array of ADOFieldObject's. */ - function InitArrayFields(&$array,&$fieldarr) - { + function InitArrayFields(&$array,&$fieldarr) { $this->_array = $array; $this->_skiprow1= false; if ($fieldarr) { @@ -4049,8 +4435,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 $this->Init(); } - function GetArray($nRows=-1) - { + function GetArray($nRows=-1) { if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) { return $this->_array; } else { @@ -4059,22 +4444,25 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 } } - function _initrs() - { + function _initrs() { $this->_numOfRows = sizeof($this->_array); - if ($this->_skiprow1) $this->_numOfRows -= 1; + if ($this->_skiprow1) { + $this->_numOfRows -= 1; + } - $this->_numOfFields =(isset($this->_fieldobjects)) ? - sizeof($this->_fieldobjects):sizeof($this->_types); + $this->_numOfFields = (isset($this->_fieldobjects)) + ? sizeof($this->_fieldobjects) + : sizeof($this->_types); } /* Use associative array to get fields array */ - function Fields($colname) - { + function Fields($colname) { $mode = isset($this->adodbFetchMode) ? $this->adodbFetchMode : $this->fetchMode; if ($mode & ADODB_FETCH_ASSOC) { - if (!isset($this->fields[$colname]) && !is_null($this->fields[$colname])) $colname = strtolower($colname); + if (!isset($this->fields[$colname]) && !is_null($this->fields[$colname])) { + $colname = strtolower($colname); + } return $this->fields[$colname]; } if (!$this->bind) { @@ -4087,8 +4475,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 return $this->fields[$this->bind[strtoupper($colname)]]; } - function FetchField($fieldOffset = -1) - { + function FetchField($fieldOffset = -1) { if (isset($this->_fieldobjects)) { return $this->_fieldobjects[$fieldOffset]; } @@ -4100,28 +4487,32 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 return $o; } - function _seek($row) - { + function _seek($row) { if (sizeof($this->_array) && 0 <= $row && $row < $this->_numOfRows) { $this->_currentRow = $row; - if ($this->_skiprow1) $row += 1; + if ($this->_skiprow1) { + $row += 1; + } $this->fields = $this->_array[$row]; return true; } return false; } - function MoveNext() - { + function MoveNext() { if (!$this->EOF) { $this->_currentRow++; $pos = $this->_currentRow; if ($this->_numOfRows <= $pos) { - if (!$this->compat) $this->fields = false; + if (!$this->compat) { + $this->fields = false; + } } else { - if ($this->_skiprow1) $pos += 1; + if ($this->_skiprow1) { + $pos += 1; + } $this->fields = $this->_array[$pos]; return true; } @@ -4131,21 +4522,23 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 return false; } - function _fetch() - { + function _fetch() { $pos = $this->_currentRow; if ($this->_numOfRows <= $pos) { - if (!$this->compat) $this->fields = false; + if (!$this->compat) { + $this->fields = false; + } return false; } - if ($this->_skiprow1) $pos += 1; + if ($this->_skiprow1) { + $pos += 1; + } $this->fields = $this->_array[$pos]; return true; } - function _close() - { + function _close() { return true; } @@ -4160,23 +4553,25 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * * @deprecated */ - function ADOLoadDB($dbType) - { + function ADOLoadDB($dbType) { return ADOLoadCode($dbType); } /** * Load the code for a specific database driver. Private function. Do not use. */ - function ADOLoadCode($dbType) - { - global $ADODB_LASTDB; + function ADOLoadCode($dbType) { + global $ADODB_LASTDB; - if (!$dbType) return false; + if (!$dbType) { + return false; + } $db = strtolower($dbType); switch ($db) { case 'ado': - if (PHP_VERSION >= 5) $db = 'ado5'; + if (PHP_VERSION >= 5) { + $db = 'ado5'; + } $class = 'ado'; break; @@ -4197,19 +4592,23 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 $file = ADODB_DIR."/drivers/adodb-".$db.".inc.php"; @include_once($file); $ADODB_LASTDB = $class; - if (class_exists("ADODB_" . $class)) return $class; + if (class_exists("ADODB_" . $class)) { + return $class; + } //ADOConnection::outp(adodb_pr(get_declared_classes(),true)); - if (!file_exists($file)) ADOConnection::outp("Missing file: $file"); - else ADOConnection::outp("Syntax error in file: $file"); + if (!file_exists($file)) { + ADOConnection::outp("Missing file: $file"); + } else { + ADOConnection::outp("Syntax error in file: $file"); + } return false; } /** * synonym for ADONewConnection for people like me who cannot remember the correct name */ - function NewADOConnection($db='') - { + function NewADOConnection($db='') { $tmp = ADONewConnection($db); return $tmp; } @@ -4218,17 +4617,17 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 * Instantiate a new Connection class for a specific database driver. * * @param [db] is the database Connection object to create. If undefined, - * use the last database driver that was loaded by ADOLoadCode(). + * use the last database driver that was loaded by ADOLoadCode(). * * @return the freshly created instance of the Connection class. */ - function ADONewConnection($db='') - { - GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB; + function ADONewConnection($db='') { + global $ADODB_NEWCONNECTION, $ADODB_LASTDB; - if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2); + if (!defined('ADODB_ASSOC_CASE')) { + define('ADODB_ASSOC_CASE', ADODB_ASSOC_CASE_NATIVE); + } $errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false; - $false = false; if (($at = strpos($db,'://')) !== FALSE) { $origdsn = $db; $fakedsn = 'fake'.substr($origdsn,$at); @@ -4253,7 +4652,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 $dsna = @parse_url($fakedsn); if (!$dsna) { - return $false; + return false; } $dsna['scheme'] = substr($origdsn,0,$at); if ($at2 !== FALSE) { @@ -4263,18 +4662,20 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 if (strncmp($origdsn,'pdo',3) == 0) { $sch = explode('_',$dsna['scheme']); if (sizeof($sch)>1) { - $dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : ''; - if ($sch[1] == 'sqlite') + if ($sch[1] == 'sqlite') { $dsna['host'] = rawurlencode($sch[1].':'.rawurldecode($dsna['host'])); - else + } else { $dsna['host'] = rawurlencode($sch[1].':host='.rawurldecode($dsna['host'])); + } $dsna['scheme'] = 'pdo'; } } $db = @$dsna['scheme']; - if (!$db) return $false; + if (!$db) { + return false; + } $dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : ''; $dsna['user'] = isset($dsna['user']) ? rawurldecode($dsna['user']) : ''; $dsna['pass'] = isset($dsna['pass']) ? rawurldecode($dsna['pass']) : ''; @@ -4286,7 +4687,9 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 $arr = explode('=',$v); $opt[$arr[0]] = isset($arr[1]) ? rawurldecode($arr[1]) : 1; } - } else $opt = array(); + } else { + $opt = array(); + } } /* * phptype: Database backend used in PHP (mysql, odbc etc.) @@ -4304,29 +4707,36 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 if(empty($obj)) { - if (!isset($ADODB_LASTDB)) $ADODB_LASTDB = ''; - if (empty($db)) $db = $ADODB_LASTDB; - - if ($db != $ADODB_LASTDB) $db = ADOLoadCode($db); + if (!isset($ADODB_LASTDB)) { + $ADODB_LASTDB = ''; + } + if (empty($db)) { + $db = $ADODB_LASTDB; + } + if ($db != $ADODB_LASTDB) { + $db = ADOLoadCode($db); + } if (!$db) { - if (isset($origdsn)) $db = $origdsn; + if (isset($origdsn)) { + $db = $origdsn; + } if ($errorfn) { // raise an error $ignore = false; $errorfn('ADONewConnection', 'ADONewConnection', -998, - "could not load the database driver for '$db'", - $db,false,$ignore); - } else - ADOConnection::outp( "

ADONewConnection: Unable to load database driver '$db'

",false); - - return $false; + "could not load the database driver for '$db'", + $db,false,$ignore); + } else { + ADOConnection::outp( "

ADONewConnection: Unable to load database driver '$db'

",false); + } + return false; } $cls = 'ADODB_'.$db; if (!class_exists($cls)) { adodb_backtrace(); - return $false; + return false; } $obj = new $cls(); @@ -4334,19 +4744,23 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 # constructor should not fail if ($obj) { - if ($errorfn) $obj->raiseErrorFn = $errorfn; + if ($errorfn) { + $obj->raiseErrorFn = $errorfn; + } if (isset($dsna)) { - if (isset($dsna['port'])) $obj->port = $dsna['port']; + if (isset($dsna['port'])) { + $obj->port = $dsna['port']; + } foreach($opt as $k => $v) { switch(strtolower($k)) { case 'new': $nconnect = true; $persist = true; break; case 'persist': - case 'persistent': $persist = $v; break; + case 'persistent': $persist = $v; break; case 'debug': $obj->debug = (integer) $v; break; #ibase case 'role': $obj->role = $v; break; - case 'dialect': $obj->dialect = (integer) $v; break; + case 'dialect': $obj->dialect = (integer) $v; break; case 'charset': $obj->charset = $v; $obj->charSet=$v; break; case 'buffers': $obj->buffers = $v; break; case 'fetchmode': $obj->SetFetchMode($v); break; @@ -4364,24 +4778,33 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 case 'memcache': $varr = explode(':',$v); $vlen = sizeof($varr); - if ($vlen == 0) break; + if ($vlen == 0) { + break; + } $obj->memCache = true; $obj->memCacheHost = explode(',',$varr[0]); - if ($vlen == 1) break; + if ($vlen == 1) { + break; + } $obj->memCachePort = $varr[1]; - if ($vlen == 2) break; + if ($vlen == 2) { + break; + } $obj->memCacheCompress = $varr[2] ? true : false; break; } } - if (empty($persist)) + if (empty($persist)) { $ok = $obj->Connect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']); - else if (empty($nconnect)) + } else if (empty($nconnect)) { $ok = $obj->PConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']); - else + } else { $ok = $obj->NConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']); + } - if (!$ok) return $false; + if (!$ok) { + return false; + } } } return $obj; @@ -4390,56 +4813,76 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 // $perf == true means called by NewPerfMonitor(), otherwise for data dictionary - function _adodb_getdriver($provider,$drivername,$perf=false) - { + function _adodb_getdriver($provider,$drivername,$perf=false) { switch ($provider) { - case 'odbtp': if (strncmp('odbtp_',$drivername,6)==0) return substr($drivername,6); - case 'odbc' : if (strncmp('odbc_',$drivername,5)==0) return substr($drivername,5); - case 'ado' : if (strncmp('ado_',$drivername,4)==0) return substr($drivername,4); - case 'native': break; - default: - return $provider; + case 'odbtp': + if (strncmp('odbtp_',$drivername,6)==0) { + return substr($drivername,6); + } + case 'odbc' : + if (strncmp('odbc_',$drivername,5)==0) { + return substr($drivername,5); + } + case 'ado' : + if (strncmp('ado_',$drivername,4)==0) { + return substr($drivername,4); + } + case 'native': + break; + default: + return $provider; } switch($drivername) { - case 'mysqlt': - case 'mysqli': + case 'mysqlt': + case 'mysqli': $drivername='mysql'; break; - case 'postgres7': - case 'postgres8': + case 'postgres7': + case 'postgres8': $drivername = 'postgres'; break; - case 'firebird15': $drivername = 'firebird'; break; - case 'oracle': $drivername = 'oci8'; break; - case 'access': if ($perf) $drivername = ''; break; - case 'db2' : break; - case 'sapdb' : break; - default: - $drivername = 'generic'; - break; + case 'firebird15': + $drivername = 'firebird'; + break; + case 'oracle': + $drivername = 'oci8'; + break; + case 'access': + if ($perf) { + $drivername = ''; + } + break; + case 'db2' : + case 'sapdb' : + break; + default: + $drivername = 'generic'; + break; } return $drivername; } - function NewPerfMonitor(&$conn) - { - $false = false; + function NewPerfMonitor(&$conn) { $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true); - if (!$drivername || $drivername == 'generic') return $false; + if (!$drivername || $drivername == 'generic') { + return false; + } include_once(ADODB_DIR.'/adodb-perf.inc.php'); @include_once(ADODB_DIR."/perf/perf-$drivername.inc.php"); $class = "Perf_$drivername"; - if (!class_exists($class)) return $false; + if (!class_exists($class)) { + return false; + } $perf = new $class($conn); return $perf; } - function NewDataDictionary(&$conn,$drivername=false) - { - $false = false; - if (!$drivername) $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType); + function NewDataDictionary(&$conn,$drivername=false) { + if (!$drivername) { + $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType); + } include_once(ADODB_DIR.'/adodb-lib.inc.php'); include_once(ADODB_DIR.'/adodb-datadict.inc.php'); @@ -4447,7 +4890,7 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 if (!file_exists($path)) { ADOConnection::outp("Dictionary driver '$path' not available"); - return $false; + return false; } include_once($path); $class = "ADODB2_$drivername"; @@ -4456,8 +4899,9 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 $dict->connection = $conn; $dict->upperName = strtoupper($drivername); $dict->quote = $conn->nameQuote; - if (!empty($conn->_connectionID)) + if (!empty($conn->_connectionID)) { $dict->serverInfo = $conn->ServerInfo(); + } return $dict; } @@ -4467,14 +4911,16 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 /* Perform a print_r, with pre tags for better formatting. */ - function adodb_pr($var,$as_string=false) - { - if ($as_string) ob_start(); + function adodb_pr($var,$as_string=false) { + if ($as_string) { + ob_start(); + } if (isset($_SERVER['HTTP_USER_AGENT'])) { echo "
\n";print_r($var);echo "
\n"; - } else + } else { print_r($var); + } if ($as_string) { $s = ob_get_contents(); @@ -4489,12 +4935,12 @@ http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_1 @param printOrArr Pass in a boolean to indicate print, or an $exception->trace array (assumes that print is true then). @param levels Number of levels to display */ - function adodb_backtrace($printOrArr=true,$levels=9999,$ishtml=null) - { + function adodb_backtrace($printOrArr=true,$levels=9999,$ishtml=null) { 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_backtrace($printOrArr,$levels,0,$ishtml); } - } diff --git a/lib/adodb/datadict/datadict-access.inc.php b/lib/adodb/datadict/datadict-access.inc.php index 6a0a2cdc4a7..5032498641e 100644 --- a/lib/adodb/datadict/datadict-access.inc.php +++ b/lib/adodb/datadict/datadict-access.inc.php @@ -1,7 +1,9 @@ debug) ADOConnection::outp("AlterColumnSQL not supported"); return array(); } - function DropColumnSQL($tabname, $flds) + function DropColumnSQL($tabname, $flds, $tableflds='',$tableoptions='') { if ($this->debug) ADOConnection::outp("DropColumnSQL not supported"); return array(); diff --git a/lib/adodb/datadict/datadict-db2.inc.php b/lib/adodb/datadict/datadict-db2.inc.php index 5bbca1d0c99..00e738f93cc 100644 --- a/lib/adodb/datadict/datadict-db2.inc.php +++ b/lib/adodb/datadict/datadict-db2.inc.php @@ -1,7 +1,9 @@ debug) ADOConnection::outp("AlterColumnSQL not supported"); return array(); } - function DropColumnSQL($tabname, $flds) + function DropColumnSQL($tabname, $flds, $tableflds='',$tableoptions='') { if ($this->debug) ADOConnection::outp("DropColumnSQL not supported"); return array(); diff --git a/lib/adodb/datadict/datadict-firebird.inc.php b/lib/adodb/datadict/datadict-firebird.inc.php index d4471df73a3..45c8dc66854 100644 --- a/lib/adodb/datadict/datadict-firebird.inc.php +++ b/lib/adodb/datadict/datadict-firebird.inc.php @@ -1,7 +1,9 @@ debug) ADOConnection::outp("AlterColumnSQL not supported"); return array(); } - function DropColumnSQL($tabname, $flds) + function DropColumnSQL($tabname, $flds, $tableflds='',$tableoptions='') { if ($this->debug) ADOConnection::outp("DropColumnSQL not supported"); return array(); diff --git a/lib/adodb/datadict/datadict-ibase.inc.php b/lib/adodb/datadict/datadict-ibase.inc.php index 13f028e3102..999198d36cc 100644 --- a/lib/adodb/datadict/datadict-ibase.inc.php +++ b/lib/adodb/datadict/datadict-ibase.inc.php @@ -1,7 +1,9 @@ debug) ADOConnection::outp("AlterColumnSQL not supported"); return array(); } - function DropColumnSQL($tabname, $flds) + function DropColumnSQL($tabname, $flds, $tableflds='', $tableoptions='') { if ($this->debug) ADOConnection::outp("DropColumnSQL not supported"); return array(); diff --git a/lib/adodb/datadict/datadict-informix.inc.php b/lib/adodb/datadict/datadict-informix.inc.php index 1bc68807246..d0c6e187d6a 100644 --- a/lib/adodb/datadict/datadict-informix.inc.php +++ b/lib/adodb/datadict/datadict-informix.inc.php @@ -1,7 +1,9 @@ debug) ADOConnection::outp("AlterColumnSQL not supported"); return array(); } - function DropColumnSQL($tabname, $flds) + function DropColumnSQL($tabname, $flds, $tableflds='', $tableoptions='') { if ($this->debug) ADOConnection::outp("DropColumnSQL not supported"); return array(); diff --git a/lib/adodb/datadict/datadict-mssql.inc.php b/lib/adodb/datadict/datadict-mssql.inc.php index 6610fc44efa..47f70474e6f 100644 --- a/lib/adodb/datadict/datadict-mssql.inc.php +++ b/lib/adodb/datadict/datadict-mssql.inc.php @@ -1,7 +1,9 @@ TableName ($tabname); $sql = array(); @@ -137,7 +139,7 @@ class ADODB2_mssql extends ADODB_DataDict { } */ - function DropColumnSQL($tabname, $flds) + function DropColumnSQL($tabname, $flds, $tableflds='',$tableoptions='') { $tabname = $this->TableName ($tabname); if (!is_array($flds)) diff --git a/lib/adodb/datadict/datadict-mssqlnative.inc.php b/lib/adodb/datadict/datadict-mssqlnative.inc.php index 0741c79f7cd..f62e64bf16b 100644 --- a/lib/adodb/datadict/datadict-mssqlnative.inc.php +++ b/lib/adodb/datadict/datadict-mssqlnative.inc.php @@ -1,7 +1,9 @@ TableName ($tabname); $sql = array(); diff --git a/lib/adodb/datadict/datadict-mysql.inc.php b/lib/adodb/datadict/datadict-mysql.inc.php index 773aa0c79e1..27bdf2a7a02 100644 --- a/lib/adodb/datadict/datadict-mysql.inc.php +++ b/lib/adodb/datadict/datadict-mysql.inc.php @@ -1,7 +1,9 @@ TableName($tabname); $f = array(); list($lines,$pkey) = $this->_GenFields($flds); $s = "ALTER TABLE $tabname ADD ("; @@ -128,8 +131,9 @@ class ADODB2_oci8 extends ADODB_DataDict { return $sql; } - function AlterColumnSQL($tabname, $flds) + function AlterColumnSQL($tabname, $flds, $tableflds='', $tableoptions='') { + $tabname = $this->TableName($tabname); $f = array(); list($lines,$pkey) = $this->_GenFields($flds); $s = "ALTER TABLE $tabname MODIFY("; @@ -141,7 +145,7 @@ class ADODB2_oci8 extends ADODB_DataDict { return $sql; } - function DropColumnSQL($tabname, $flds) + function DropColumnSQL($tabname, $flds, $tableflds='', $tableoptions='') { if (!is_array($flds)) $flds = explode(',',$flds); foreach ($flds as $k => $v) $flds[$k] = $this->NameQuote($v); diff --git a/lib/adodb/datadict/datadict-postgres.inc.php b/lib/adodb/datadict/datadict-postgres.inc.php index 965314dbc44..00c2e672e4b 100644 --- a/lib/adodb/datadict/datadict-postgres.inc.php +++ b/lib/adodb/datadict/datadict-postgres.inc.php @@ -1,7 +1,9 @@ _GenFields($flds); $set_null = false; - $alter = 'ALTER TABLE ' . $tabname . $this->alterCol . ' '; foreach($lines as $v) { + $alter = 'ALTER TABLE ' . $tabname . $this->alterCol . ' '; if ($not_null = preg_match('/NOT NULL/i',$v)) { $v = preg_replace('/NOT NULL/i','',$v); } diff --git a/lib/adodb/datadict/datadict-sapdb.inc.php b/lib/adodb/datadict/datadict-sapdb.inc.php index aaa4820d1da..0f5e1915eb1 100644 --- a/lib/adodb/datadict/datadict-sapdb.inc.php +++ b/lib/adodb/datadict/datadict-sapdb.inc.php @@ -1,7 +1,9 @@ TableName ($tabname); $sql = array(); @@ -108,7 +110,7 @@ class ADODB2_sapdb extends ADODB_DataDict { return array( 'ALTER TABLE ' . $tabname . ' MODIFY (' . implode(', ',$lines) . ')' ); } - function DropColumnSQL($tabname, $flds) + function DropColumnSQL($tabname, $flds, $tableflds='',$tableoptions='') { $tabname = $this->TableName ($tabname); if (!is_array($flds)) $flds = explode(',',$flds); diff --git a/lib/adodb/datadict/datadict-sqlite.inc.php b/lib/adodb/datadict/datadict-sqlite.inc.php index 81fb0165340..dc3d038fcf7 100644 --- a/lib/adodb/datadict/datadict-sqlite.inc.php +++ b/lib/adodb/datadict/datadict-sqlite.inc.php @@ -1,7 +1,9 @@ debug) ADOConnection::outp("AlterColumnSQL not supported natively by SQLite"); return array(); } - function DropColumnSQL($tabname, $flds) + function DropColumnSQL($tabname, $flds, $tableflds='', $tableoptions='') { if ($this->debug) ADOConnection::outp("DropColumnSQL not supported natively by SQLite"); return array(); diff --git a/lib/adodb/datadict/datadict-sybase.inc.php b/lib/adodb/datadict/datadict-sybase.inc.php index 3426e078da2..ffbce3a37fd 100644 --- a/lib/adodb/datadict/datadict-sybase.inc.php +++ b/lib/adodb/datadict/datadict-sybase.inc.php @@ -1,7 +1,9 @@ TableName ($tabname); $sql = array(); @@ -99,7 +101,7 @@ class ADODB2_sybase extends ADODB_DataDict { return $sql; } - function DropColumnSQL($tabname, $flds) + function DropColumnSQL($tabname, $flds, $tableflds='', $tableoptions='') { $tabname = $this->TableName($tabname); if (!is_array($flds)) $flds = explode(',',$flds); diff --git a/lib/adodb/drivers/adodb-access.inc.php b/lib/adodb/drivers/adodb-access.inc.php index a0932a05a90..63121f8e56a 100644 --- a/lib/adodb/drivers/adodb-access.inc.php +++ b/lib/adodb/drivers/adodb-access.inc.php @@ -1,6 +1,8 @@ ADODB_odbc(); + parent::__construct(); } function Time() @@ -78,9 +80,9 @@ class ADORecordSet_access extends ADORecordSet_odbc { var $databaseType = "access"; - function ADORecordSet_access($id,$mode=false) + function __construct($id,$mode=false) { - return $this->ADORecordSet_odbc($id,$mode); + return parent::__construct($id,$mode); } }// class } diff --git a/lib/adodb/drivers/adodb-ado.inc.php b/lib/adodb/drivers/adodb-ado.inc.php index 2c312f7d8d6..815bef6adf4 100644 --- a/lib/adodb/drivers/adodb-ado.inc.php +++ b/lib/adodb/drivers/adodb-ado.inc.php @@ -1,6 +1,8 @@ _affectedRows = new VARIANT; } @@ -147,7 +149,7 @@ class ADODB_ado extends ADOConnection { */ - function MetaTables() + function MetaTables($ttype = false, $showSchema = false, $mask = false) { $arr= array(); $dbc = $this->_connectionID; @@ -341,14 +343,14 @@ class ADORecordSet_ado extends ADORecordSet { var $canSeek = true; var $hideErrors = true; - function ADORecordSet_ado($id,$mode=false) + function __construct($id,$mode=false) { if ($mode === false) { global $ADODB_FETCH_MODE; $mode = $ADODB_FETCH_MODE; } $this->fetchMode = $mode; - return $this->ADORecordSet($id,$mode); + return parent::__construct($id,$mode); } @@ -625,7 +627,7 @@ class ADORecordSet_ado extends ADORecordSet { @$rs->MoveNext(); // @ needed for some versions of PHP! if ($this->fetchMode & ADODB_FETCH_ASSOC) { - $this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE); + $this->fields = $this->GetRowAssoc(); } return true; } diff --git a/lib/adodb/drivers/adodb-ado5.inc.php b/lib/adodb/drivers/adodb-ado5.inc.php index 9f5cea25fcf..a94f88bf211 100644 --- a/lib/adodb/drivers/adodb-ado5.inc.php +++ b/lib/adodb/drivers/adodb-ado5.inc.php @@ -1,6 +1,8 @@ _affectedRows = new VARIANT; } @@ -172,7 +174,7 @@ class ADODB_ado extends ADOConnection { */ - function MetaTables() + function MetaTables($ttype = false, $showSchema = false, $mask = false) { $arr= array(); $dbc = $this->_connectionID; @@ -375,14 +377,14 @@ class ADORecordSet_ado extends ADORecordSet { var $canSeek = true; var $hideErrors = true; - function ADORecordSet_ado($id,$mode=false) + function __construct($id,$mode=false) { if ($mode === false) { global $ADODB_FETCH_MODE; $mode = $ADODB_FETCH_MODE; } $this->fetchMode = $mode; - return $this->ADORecordSet($id,$mode); + return parent::__construct($id,$mode); } @@ -670,7 +672,7 @@ class ADORecordSet_ado extends ADORecordSet { @$rs->MoveNext(); // @ needed for some versions of PHP! if ($this->fetchMode & ADODB_FETCH_ASSOC) { - $this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE); + $this->fields = $this->GetRowAssoc(); } return true; } diff --git a/lib/adodb/drivers/adodb-ado_access.inc.php b/lib/adodb/drivers/adodb-ado_access.inc.php index ad8a9826684..45210e26a5d 100644 --- a/lib/adodb/drivers/adodb-ado_access.inc.php +++ b/lib/adodb/drivers/adodb-ado_access.inc.php @@ -1,6 +1,8 @@ ADODB_ado(); - } - /*function BeginTrans() { return false;} function CommitTrans() { return false;} @@ -46,8 +43,8 @@ class ADORecordSet_ado_access extends ADORecordSet_ado { var $databaseType = "ado_access"; - function ADORecordSet_ado_access($id,$mode=false) + function __construct($id,$mode=false) { - return $this->ADORecordSet_ado($id,$mode); + return parent::__construct($id,$mode); } } diff --git a/lib/adodb/drivers/adodb-ado_mssql.inc.php b/lib/adodb/drivers/adodb-ado_mssql.inc.php index c03c0fae001..23a2faad21a 100644 --- a/lib/adodb/drivers/adodb-ado_mssql.inc.php +++ b/lib/adodb/drivers/adodb-ado_mssql.inc.php @@ -1,6 +1,8 @@ ADODB_ado(); - } - function _insertid() { return $this->GetOne('select SCOPE_IDENTITY()'); @@ -146,8 +143,8 @@ class ADODB_ado_mssql extends ADODB_ado { var $databaseType = 'ado_mssql'; - function ADORecordSet_ado_mssql($id,$mode=false) + function __construct($id,$mode=false) { - return $this->ADORecordSet_ado($id,$mode); + return parent::__construct($id,$mode); } } diff --git a/lib/adodb/drivers/adodb-ads.inc.php b/lib/adodb/drivers/adodb-ads.inc.php index 4481d2b83b7..d59df663a5f 100644 --- a/lib/adodb/drivers/adodb-ads.inc.php +++ b/lib/adodb/drivers/adodb-ads.inc.php @@ -66,7 +66,7 @@ class ADODB_ads extends ADOConnection { var $uCaseTables = true; // for meta* functions, uppercase table names - function ADODB_ads() + function __construct() { $this->_haserrorfunctions = ADODB_PHPVER >= 0x4050; $this->_has_stupid_odbc_fetch_api_change = ADODB_PHPVER >= 0x4200; @@ -136,7 +136,7 @@ class ADODB_ads extends ADOConnection { // returns true or false - function CreateSequence( $seqname,$start=1) + function CreateSequence($seqname = 'adodbseq', $start = 1) { $res = $this->Execute("CREATE TABLE $seqname ( ID autoinc( 1 ) ) IN DATABASE"); if(!$res){ @@ -149,7 +149,7 @@ class ADODB_ads extends ADOConnection { } // returns true or false - function DropSequence($seqname) + function DropSequence($seqname = 'adodbseq') { $res = $this->Execute("DROP TABLE $seqname"); if(!$res){ @@ -164,7 +164,7 @@ class ADODB_ads extends ADOConnection { // returns the generated ID or false // checks if the table already exists, else creates the table and inserts a record into the table // and gets the ID number of the last inserted record. - function GenID($seqname,$start=1) + function GenID($seqname = 'adodbseq', $start = 1) { $go = $this->Execute("select * from $seqname"); if (!$go){ @@ -254,7 +254,7 @@ class ADODB_ads extends ADOConnection { // Returns tables,Views or both on succesfull execution. Returns // tables by default on succesfull execustion. - function &MetaTables($ttype) + function &MetaTables($ttype = false, $showSchema = false, $mask = false) { $recordSet1 = $this->Execute("select * from system.tables"); if(!$recordSet1){ @@ -294,7 +294,7 @@ class ADODB_ads extends ADOConnection { } - function &MetaPrimaryKeys($table) + function &MetaPrimaryKeys($table, $owner = false) { $recordSet = $this->Execute("select table_primary_key from system.tables where name='$table'"); if(!$recordSet){ @@ -378,7 +378,7 @@ See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbc/htm/od } } - function &MetaColumns($table) + function &MetaColumns($table, $normalize = true) { global $ADODB_FETCH_MODE; @@ -486,7 +486,7 @@ See http://msdn.microsoft.com/library/default.asp?url=/library/en-us/odbc/htm/od } // Returns an array of columns names for a given table - function &MetaColumnNames($table) + function &MetaColumnNames($table, $numIndexes = false, $useattnum = false) { $recordSet = $this->Execute("select name from system.columns where parent='$table'"); if(!$recordSet){ @@ -654,7 +654,7 @@ class ADORecordSet_ads extends ADORecordSet { var $useFetchArray; var $_has_stupid_odbc_fetch_api_change; - function ADORecordSet_ads($id,$mode=false) + function __construct($id,$mode=false) { if ($mode === false) { global $ADODB_FETCH_MODE; @@ -667,7 +667,7 @@ class ADORecordSet_ads extends ADORecordSet { // the following is required for mysql odbc driver in 4.3.1 -- why? $this->EOF = false; $this->_currentRow = -1; - //$this->ADORecordSet($id); + //parent::__construct($id); } @@ -731,7 +731,7 @@ class ADORecordSet_ads extends ADORecordSet { $this->fetchMode = $savem; if ($this->fetchMode & ADODB_FETCH_ASSOC) { - $this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE); + $this->fields =& $this->GetRowAssoc(); } $results = array(); @@ -769,7 +769,7 @@ class ADORecordSet_ads extends ADORecordSet { } if ($rez) { if ($this->fetchMode & ADODB_FETCH_ASSOC) { - $this->fields =& $this->GetRowAssoc(ADODB_ASSOC_CASE); + $this->fields =& $this->GetRowAssoc(); } return true; } diff --git a/lib/adodb/drivers/adodb-borland_ibase.inc.php b/lib/adodb/drivers/adodb-borland_ibase.inc.php index 3338db790f1..283183fdef2 100644 --- a/lib/adodb/drivers/adodb-borland_ibase.inc.php +++ b/lib/adodb/drivers/adodb-borland_ibase.inc.php @@ -1,6 +1,8 @@ ADODB_ibase(); - } - function BeginTrans() { if ($this->transOff) return true; @@ -84,8 +80,8 @@ class ADORecordSet_borland_ibase extends ADORecordSet_ibase { var $databaseType = "borland_ibase"; - function ADORecordSet_borland_ibase($id,$mode=false) + function __construct($id,$mode=false) { - $this->ADORecordSet_ibase($id,$mode); + parent::__construct($id,$mode); } } diff --git a/lib/adodb/drivers/adodb-csv.inc.php b/lib/adodb/drivers/adodb-csv.inc.php index 4fb2dcc6e40..2b10499c740 100644 --- a/lib/adodb/drivers/adodb-csv.inc.php +++ b/lib/adodb/drivers/adodb-csv.inc.php @@ -1,6 +1,8 @@ ADORecordset($id,$mode); + parent::__construct($id,$mode); } function _close() diff --git a/lib/adodb/drivers/adodb-db2.inc.php b/lib/adodb/drivers/adodb-db2.inc.php index d7ff91af50f..b3487d2dfc2 100644 --- a/lib/adodb/drivers/adodb-db2.inc.php +++ b/lib/adodb/drivers/adodb-db2.inc.php @@ -1,6 +1,8 @@ _haserrorfunctions = ADODB_PHPVER >= 0x4050; } @@ -134,7 +136,7 @@ class ADODB_db2 extends ADOConnection { } // format and return date string in database timestamp format - function DBTimeStamp($ts) + function DBTimeStamp($ts, $isfld = false) { if (empty($ts) && $ts !== 0) return 'null'; if (is_string($ts)) $ts = ADORecordSet::UnixTimeStamp($ts); @@ -233,13 +235,13 @@ class ADODB_db2 extends ADOConnection { return true; } - function DropSequence($seqname) + function DropSequence($seqname = 'adodbseq') { if (empty($this->_dropSeqSQL)) return false; return $this->Execute(sprintf($this->_dropSeqSQL,$seqname)); } - function SelectLimit($sql,$nrows=-1,$offset=-1,$inputArr=false) + function SelectLimit($sql, $nrows = -1, $offset = -1, $inputArr = false, $secs2cache = 0) { $nrows = (integer) $nrows; if ($offset <= 0) { @@ -333,7 +335,7 @@ class ADODB_db2 extends ADOConnection { return $ret; } - function MetaPrimaryKeys($table) + function MetaPrimaryKeys($table, $owner = false) { global $ADODB_FETCH_MODE; @@ -409,7 +411,7 @@ class ADODB_db2 extends ADOConnection { } - function MetaTables($ttype=false,$schema=false) + function MetaTables($ttype = false, $schema = false, $mask = false) { global $ADODB_FETCH_MODE; @@ -726,7 +728,7 @@ class ADORecordSet_db2 extends ADORecordSet { var $dataProvider = "db2"; var $useFetchArray; - function ADORecordSet_db2($id,$mode=false) + function __construct($id,$mode=false) { if ($mode === false) { global $ADODB_FETCH_MODE; @@ -793,7 +795,7 @@ class ADORecordSet_db2 extends ADORecordSet { $this->fetchMode = $savem; if ($this->fetchMode & ADODB_FETCH_ASSOC) { - $this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE); + $this->fields = $this->GetRowAssoc(); } $results = array(); @@ -815,7 +817,7 @@ class ADORecordSet_db2 extends ADORecordSet { $this->fields = @db2_fetch_array($this->_queryID); if ($this->fields) { if ($this->fetchMode & ADODB_FETCH_ASSOC) { - $this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE); + $this->fields = $this->GetRowAssoc(); } return true; } @@ -831,7 +833,7 @@ class ADORecordSet_db2 extends ADORecordSet { $this->fields = db2_fetch_array($this->_queryID); if ($this->fields) { if ($this->fetchMode & ADODB_FETCH_ASSOC) { - $this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE); + $this->fields = $this->GetRowAssoc(); } return true; } diff --git a/lib/adodb/drivers/adodb-db2oci.inc.php b/lib/adodb/drivers/adodb-db2oci.inc.php index b58ec1a7f86..3779fff47b0 100644 --- a/lib/adodb/drivers/adodb-db2oci.inc.php +++ b/lib/adodb/drivers/adodb-db2oci.inc.php @@ -1,6 +1,8 @@ ADORecordSet_db2($id,$mode); + return parent::__construct($id,$mode); } } diff --git a/lib/adodb/drivers/adodb-db2ora.inc.php b/lib/adodb/drivers/adodb-db2ora.inc.php index ebcdab63776..286c0f5bd3e 100644 --- a/lib/adodb/drivers/adodb-db2ora.inc.php +++ b/lib/adodb/drivers/adodb-db2ora.inc.php @@ -1,6 +1,8 @@ ADODB_db2(); - } - - - function _Execute($sql, $inputarr) + function _Execute($sql, $inputarr = false) { if ($inputarr) list($sql,$inputarr) = _colonscope($sql, $inputarr); return parent::_Execute($sql, $inputarr); @@ -70,9 +66,9 @@ class ADORecordSet_db2oci extends ADORecordSet_odbc { var $databaseType = "db2oci"; - function ADORecordSet_db2oci($id,$mode=false) + function __construct($id,$mode=false) { - return $this->ADORecordSet_db2($id,$mode); + return parent::__construct($id,$mode); } } diff --git a/lib/adodb/drivers/adodb-fbsql.inc.php b/lib/adodb/drivers/adodb-fbsql.inc.php index 56957075529..646eb5289e3 100644 --- a/lib/adodb/drivers/adodb-fbsql.inc.php +++ b/lib/adodb/drivers/adodb-fbsql.inc.php @@ -1,6 +1,8 @@ fetchMode = FBSQL_BOTH; break; } - return $this->ADORecordSet($queryID); + return parent::__construct($queryID); } function _initrs() diff --git a/lib/adodb/drivers/adodb-firebird.inc.php b/lib/adodb/drivers/adodb-firebird.inc.php index 2e0917dd282..66f7bde2f7d 100644 --- a/lib/adodb/drivers/adodb-firebird.inc.php +++ b/lib/adodb/drivers/adodb-firebird.inc.php @@ -1,6 +1,8 @@ ADODB_ibase(); - } - function ServerInfo() { $arr['dialect'] = $this->dialect; @@ -69,8 +66,8 @@ class ADORecordSet_firebird extends ADORecordSet_ibase { var $databaseType = "firebird"; - function ADORecordSet_firebird($id,$mode=false) + function __construct($id,$mode=false) { - $this->ADORecordSet_ibase($id,$mode); + parent::__construct($id,$mode); } } diff --git a/lib/adodb/drivers/adodb-ibase.inc.php b/lib/adodb/drivers/adodb-ibase.inc.php index a638f58ed4d..cc8755b8c9f 100644 --- a/lib/adodb/drivers/adodb-ibase.inc.php +++ b/lib/adodb/drivers/adodb-ibase.inc.php @@ -1,6 +1,8 @@ ibasetrans = IBASE_DEFAULT; - } + if (defined('IBASE_DEFAULT')) $this->ibasetrans = IBASE_DEFAULT; + } - // returns true or false + // returns true or false function _connect($argHostname, $argUsername, $argPassword, $argDatabasename,$persist=false) { if (!function_exists('ibase_pconnect')) return null; @@ -84,8 +86,12 @@ class ADODB_ibase extends ADOConnection { // PHP5 change. if (function_exists('ibase_timefmt')) { ibase_timefmt($this->ibase_datefmt,IBASE_DATE ); - if ($this->dialect == 1) ibase_timefmt($this->ibase_datefmt,IBASE_TIMESTAMP ); - else ibase_timefmt($this->ibase_timestampfmt,IBASE_TIMESTAMP ); + if ($this->dialect == 1) { + ibase_timefmt($this->ibase_datefmt,IBASE_TIMESTAMP ); + } + else { + ibase_timefmt($this->ibase_timestampfmt,IBASE_TIMESTAMP ); + } ibase_timefmt($this->ibase_timefmt,IBASE_TIME ); } else { @@ -95,7 +101,8 @@ class ADODB_ibase extends ADOConnection { } return true; } - // returns true or false + + // returns true or false function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) { return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename,true); @@ -104,7 +111,9 @@ class ADODB_ibase extends ADOConnection { function MetaPrimaryKeys($table,$owner_notused=false,$internalKey=false) { - if ($internalKey) return array('RDB$DB_KEY'); + if ($internalKey) { + return array('RDB$DB_KEY'); + } $table = strtoupper($table); @@ -138,19 +147,25 @@ class ADODB_ibase extends ADOConnection { if ($this->transOff) return true; $this->transCnt += 1; $this->autoCommit = false; - $this->_transactionID = $this->_connectionID;//ibase_trans($this->ibasetrans, $this->_connectionID); + $this->_transactionID = $this->_connectionID;//ibase_trans($this->ibasetrans, $this->_connectionID); return $this->_transactionID; } function CommitTrans($ok=true) { - if (!$ok) return $this->RollbackTrans(); - if ($this->transOff) return true; - if ($this->transCnt) $this->transCnt -= 1; + if (!$ok) { + return $this->RollbackTrans(); + } + if ($this->transOff) { + return true; + } + if ($this->transCnt) { + $this->transCnt -= 1; + } $ret = false; $this->autoCommit = true; if ($this->_transactionID) { - //print ' commit '; + //print ' commit '; $ret = ibase_commit($this->_transactionID); } $this->_transactionID = false; @@ -180,8 +195,9 @@ class ADODB_ibase extends ADOConnection { if ($this->transCnt) $this->transCnt -= 1; $ret = false; $this->autoCommit = true; - if ($this->_transactionID) - $ret = ibase_rollback($this->_transactionID); + if ($this->_transactionID) { + $ret = ibase_rollback($this->_transactionID); + } $this->_transactionID = false; return $ret; @@ -189,75 +205,79 @@ class ADODB_ibase extends ADOConnection { function MetaIndexes ($table, $primary = FALSE, $owner=false) { - // save old fetch mode - global $ADODB_FETCH_MODE; - $false = false; - $save = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - if ($this->fetchMode !== FALSE) { - $savem = $this->SetFetchMode(FALSE); - } - $table = strtoupper($table); - $sql = "SELECT * FROM RDB\$INDICES WHERE RDB\$RELATION_NAME = '".$table."'"; - if (!$primary) { - $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$%'"; - } else { - $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$FOREIGN%'"; - } - // get index details - $rs = $this->Execute($sql); - if (!is_object($rs)) { - // restore fetchmode - if (isset($savem)) { - $this->SetFetchMode($savem); - } - $ADODB_FETCH_MODE = $save; - return $false; - } - - $indexes = array(); + // save old fetch mode + global $ADODB_FETCH_MODE; + $false = false; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== FALSE) { + $savem = $this->SetFetchMode(FALSE); + } + $table = strtoupper($table); + $sql = "SELECT * FROM RDB\$INDICES WHERE RDB\$RELATION_NAME = '".$table."'"; + if (!$primary) { + $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$%'"; + } else { + $sql .= " AND RDB\$INDEX_NAME NOT LIKE 'RDB\$FOREIGN%'"; + } + // get index details + $rs = $this->Execute($sql); + if (!is_object($rs)) { + // restore fetchmode + if (isset($savem)) { + $this->SetFetchMode($savem); + } + $ADODB_FETCH_MODE = $save; + return $false; + } + + $indexes = array(); while ($row = $rs->FetchRow()) { $index = $row[0]; - if (!isset($indexes[$index])) { - if (is_null($row[3])) {$row[3] = 0;} - $indexes[$index] = array( - 'unique' => ($row[3] == 1), - 'columns' => array() - ); - } + if (!isset($indexes[$index])) { + if (is_null($row[3])) { + $row[3] = 0; + } + $indexes[$index] = array( + 'unique' => ($row[3] == 1), + 'columns' => array() + ); + } $sql = "SELECT * FROM RDB\$INDEX_SEGMENTS WHERE RDB\$INDEX_NAME = '".$index."' ORDER BY RDB\$FIELD_POSITION ASC"; $rs1 = $this->Execute($sql); - while ($row1 = $rs1->FetchRow()) { - $indexes[$index]['columns'][$row1[2]] = $row1[1]; - } + while ($row1 = $rs1->FetchRow()) { + $indexes[$index]['columns'][$row1[2]] = $row1[1]; + } + } + // restore fetchmode + if (isset($savem)) { + $this->SetFetchMode($savem); } - // restore fetchmode - if (isset($savem)) { - $this->SetFetchMode($savem); - } - $ADODB_FETCH_MODE = $save; + $ADODB_FETCH_MODE = $save; - return $indexes; + return $indexes; } // See http://community.borland.com/article/0,1410,25844,00.html function RowLock($tables,$where,$col=false) { - if ($this->autoCommit) $this->BeginTrans(); + if ($this->autoCommit) { + $this->BeginTrans(); + } $this->Execute("UPDATE $table SET $col=$col WHERE $where "); // is this correct - jlim? return 1; } - function CreateSequence($seqname,$startID=1) + function CreateSequence($seqname = 'adodbseq', $startID = 1) { $ok = $this->Execute(("INSERT INTO RDB\$GENERATORS (RDB\$GENERATOR_NAME) VALUES (UPPER('$seqname'))" )); if (!$ok) return false; return $this->Execute("SET GENERATOR $seqname TO ".($startID-1).';'); } - function DropSequence($seqname) + function DropSequence($seqname = 'adodbseq') { $seqname = strtoupper($seqname); $this->Execute("delete from RDB\$GENERATORS where RDB\$GENERATOR_NAME='$seqname'"); @@ -272,17 +292,23 @@ class ADODB_ibase extends ADOConnection { $this->Execute("SET GENERATOR $seqname TO ".($startID-1).';'); $rs = $this->Execute($getnext); } - if ($rs && !$rs->EOF) $this->genID = (integer) reset($rs->fields); - else $this->genID = 0; // false + if ($rs && !$rs->EOF) { + $this->genID = (integer) reset($rs->fields); + } + else { + $this->genID = 0; // false + } - if ($rs) $rs->Close(); + if ($rs) { + $rs->Close(); + } return $this->genID; } function SelectDB($dbName) { - return false; + return false; } function _handleerror() @@ -308,8 +334,8 @@ class ADODB_ibase extends ADOConnection { return array($sql,$stmt); } - // returns query ID if successful, otherwise false - // there have been reports of problems with nested queries - the code is probably not re-entrant? + // returns query ID if successful, otherwise false + // there have been reports of problems with nested queries - the code is probably not re-entrant? function _query($sql,$iarr=false) { @@ -365,18 +391,22 @@ class ADODB_ibase extends ADOConnection { } } else $ret = $fn($conn,$sql); } - if ($docommit && $ret === true) ibase_commit($this->_connectionID); + if ($docommit && $ret === true) { + ibase_commit($this->_connectionID); + } $this->_handleerror(); return $ret; } - // returns true or false - function _close() - { - if (!$this->autoCommit) @ibase_rollback($this->_connectionID); + // returns true or false + function _close() + { + if (!$this->autoCommit) { + @ibase_rollback($this->_connectionID); + } return @ibase_close($this->_connectionID); - } + } //OPN STUFF start function _ConvertFieldType(&$fld, $ftype, $flen, $fscale, $fsubtype, $fprecision, $dialect3) @@ -388,24 +418,24 @@ class ADODB_ibase extends ADOConnection { case 7: case 8: if ($dialect3) { - switch($fsubtype){ - case 0: - $fld->type = ($ftype == 7 ? 'smallint' : 'integer'); - break; - case 1: - $fld->type = 'numeric'; + switch($fsubtype){ + case 0: + $fld->type = ($ftype == 7 ? 'smallint' : 'integer'); + break; + case 1: + $fld->type = 'numeric'; $fld->max_length = $fprecision; $fld->scale = $fscale; - break; - case 2: - $fld->type = 'decimal'; + break; + case 2: + $fld->type = 'decimal'; $fld->max_length = $fprecision; $fld->scale = $fscale; - break; - } // switch + break; + } // switch } else { if ($fscale !=0) { - $fld->type = 'decimal'; + $fld->type = 'decimal'; $fld->scale = $fscale; $fld->max_length = ($ftype == 7 ? 4 : 9); } else { @@ -415,23 +445,23 @@ class ADODB_ibase extends ADOConnection { break; case 16: if ($dialect3) { - switch($fsubtype){ - case 0: - $fld->type = 'decimal'; + switch($fsubtype){ + case 0: + $fld->type = 'decimal'; $fld->max_length = 18; $fld->scale = 0; - break; - case 1: - $fld->type = 'numeric'; + break; + case 1: + $fld->type = 'numeric'; $fld->max_length = $fprecision; $fld->scale = $fscale; - break; - case 2: - $fld->type = 'decimal'; + break; + case 2: + $fld->type = 'decimal'; $fld->max_length = $fprecision; $fld->scale = $fscale; - break; - } // switch + break; + } // switch } break; case 10: @@ -442,7 +472,7 @@ class ADODB_ibase extends ADOConnection { break; case 27: if ($fscale !=0) { - $fld->type = 'decimal'; + $fld->type = 'decimal'; $fld->max_length = 15; $fld->scale = 5; } else { @@ -451,7 +481,7 @@ class ADODB_ibase extends ADOConnection { break; case 35: if ($dialect3) { - $fld->type = 'timestamp'; + $fld->type = 'timestamp'; } else { $fld->type = 'date'; } @@ -475,7 +505,8 @@ class ADODB_ibase extends ADOConnection { } // switch } //OPN STUFF end - // returns array of ADOFieldObjects for current table + + // returns array of ADOFieldObjects for current table function MetaColumns($table, $normalize=true) { global $ADODB_FETCH_MODE; @@ -569,29 +600,29 @@ class ADODB_ibase extends ADOConnection { } function _BlobDecode( $blob ) - { - if (ADODB_PHPVER >= 0x5000) { - $blob_data = ibase_blob_info($this->_connectionID, $blob ); - $blobid = ibase_blob_open($this->_connectionID, $blob ); - } else { + { + if (ADODB_PHPVER >= 0x5000) { + $blob_data = ibase_blob_info($this->_connectionID, $blob ); + $blobid = ibase_blob_open($this->_connectionID, $blob ); + } else { - $blob_data = ibase_blob_info( $blob ); - $blobid = ibase_blob_open( $blob ); - } + $blob_data = ibase_blob_info( $blob ); + $blobid = ibase_blob_open( $blob ); + } - if( $blob_data[0] > $this->maxblobsize ) { + if( $blob_data[0] > $this->maxblobsize ) { - $realblob = ibase_blob_get($blobid, $this->maxblobsize); + $realblob = ibase_blob_get($blobid, $this->maxblobsize); - while($string = ibase_blob_get($blobid, 8192)){ - $realblob .= $string; - } - } else { - $realblob = ibase_blob_get($blobid, $blob_data[0]); - } + while($string = ibase_blob_get($blobid, 8192)){ + $realblob .= $string; + } + } else { + $realblob = ibase_blob_get($blobid, $blob_data[0]); + } - ibase_blob_close( $blobid ); - return( $realblob ); + ibase_blob_close( $blobid ); + return( $realblob ); } function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') @@ -695,16 +726,16 @@ class ADODB_ibase extends ADOConnection { break; case 'H': case 'h': - $s .= "(extract(hour from $col))"; - break; + $s .= "(extract(hour from $col))"; + break; case 'I': case 'i': - $s .= "(extract(minute from $col))"; - break; + $s .= "(extract(minute from $col))"; + break; case 'S': case 's': - $s .= "CAST((extract(second from $col)) AS INTEGER)"; - break; + $s .= "CAST((extract(second from $col)) AS INTEGER)"; + break; default: if ($ch == '\\') { @@ -720,7 +751,7 @@ class ADODB_ibase extends ADOConnection { } /*-------------------------------------------------------------------------------------- - Class Name: Recordset + Class Name: Recordset --------------------------------------------------------------------------------------*/ class ADORecordset_ibase extends ADORecordSet @@ -730,12 +761,12 @@ class ADORecordset_ibase extends ADORecordSet var $bind=false; var $_cacheType; - function ADORecordset_ibase($id,$mode=false) + function __construct($id,$mode=false) { global $ADODB_FETCH_MODE; $this->fetchMode = ($mode === false) ? $ADODB_FETCH_MODE : $mode; - $this->ADORecordSet($id); + parent::__construct($id); } /* Returns: an object containing field information. @@ -745,31 +776,32 @@ class ADORecordset_ibase extends ADORecordSet function FetchField($fieldOffset = -1) { - $fld = new ADOFieldObject; - $ibf = ibase_field_info($this->_queryID,$fieldOffset); - switch (ADODB_ASSOC_CASE) { - case 2: // the default - $fld->name = ($ibf['alias']); - if (empty($fld->name)) $fld->name = ($ibf['name']); - break; - case 0: - $fld->name = strtoupper($ibf['alias']); - if (empty($fld->name)) $fld->name = strtoupper($ibf['name']); - break; - case 1: - $fld->name = strtolower($ibf['alias']); - if (empty($fld->name)) $fld->name = strtolower($ibf['name']); - break; - } - - $fld->type = $ibf['type']; - $fld->max_length = $ibf['length']; - - /* This needs to be populated from the metadata */ - $fld->not_null = false; - $fld->has_default = false; - $fld->default_value = 'null'; - return $fld; + $fld = new ADOFieldObject; + $ibf = ibase_field_info($this->_queryID,$fieldOffset); + + $name = empty($ibf['alias']) ? $ibf['name'] : $ibf['alias']; + + switch (ADODB_ASSOC_CASE) { + case ADODB_ASSOC_CASE_UPPER: + $fld->name = strtoupper($name); + break; + case ADODB_ASSOC_CASE_LOWER: + $fld->name = strtolower($name); + break; + case ADODB_ASSOC_CASE_NATIVE: + default: + $fld->name = $name; + break; + } + + $fld->type = $ibf['type']; + $fld->max_length = $ibf['length']; + + /* This needs to be populated from the metadata */ + $fld->not_null = false; + $fld->has_default = false; + $fld->default_value = 'null'; + return $fld; } function _initrs() @@ -822,9 +854,9 @@ class ADORecordset_ibase extends ADORecordSet $this->fields = $f; if ($this->fetchMode == ADODB_FETCH_ASSOC) { - $this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE); + $this->fields = $this->GetRowAssoc(); } else if ($this->fetchMode == ADODB_FETCH_BOTH) { - $this->fields = array_merge($this->fields,$this->GetRowAssoc(ADODB_ASSOC_CASE)); + $this->fields = array_merge($this->fields,$this->GetRowAssoc()); } return true; } diff --git a/lib/adodb/drivers/adodb-informix.inc.php b/lib/adodb/drivers/adodb-informix.inc.php index 93205a802e7..79e865600ac 100644 --- a/lib/adodb/drivers/adodb-informix.inc.php +++ b/lib/adodb/drivers/adodb-informix.inc.php @@ -1,6 +1,8 @@ ADORecordset_informix72($id,$mode); + parent::__construct($id,$mode); } } diff --git a/lib/adodb/drivers/adodb-informix72.inc.php b/lib/adodb/drivers/adodb-informix72.inc.php index 267407b072d..b57f991a5ba 100644 --- a/lib/adodb/drivers/adodb-informix72.inc.php +++ b/lib/adodb/drivers/adodb-informix72.inc.php @@ -1,6 +1,8 @@ fetchMode = $mode; - return $this->ADORecordSet($id); + return parent::__construct($id); } diff --git a/lib/adodb/drivers/adodb-ldap.inc.php b/lib/adodb/drivers/adodb-ldap.inc.php dissimilarity index 60% index 720f469b8c5..86c705d7e9f 100644 --- a/lib/adodb/drivers/adodb-ldap.inc.php +++ b/lib/adodb/drivers/adodb-ldap.inc.php @@ -1,422 +1,428 @@ -_connectionID = @ldap_connect($host); - } else { - $conn_info = array( $host,$this->port); - - if ( strstr( $host, ':' ) ) { - $conn_info = explode( ':', $host ); - } - - $this->_connectionID = @ldap_connect( $conn_info[0], $conn_info[1] ); - } - if (!$this->_connectionID) { - $e = 'Could not connect to ' . $conn_info[0]; - $this->_errorMsg = $e; - if ($this->debug) ADOConnection::outp($e); - return false; - } - if( count( $LDAP_CONNECT_OPTIONS ) > 0 ) { - $this->_inject_bind_options( $LDAP_CONNECT_OPTIONS ); - } - - if ($username) { - $bind = @ldap_bind( $this->_connectionID, $username, $password ); - } else { - $username = 'anonymous'; - $bind = @ldap_bind( $this->_connectionID ); - } - - if (!$bind) { - $e = sprintf($this->_bind_errmsg,ldap_error($this->_connectionID)); - $this->_errorMsg = $e; - if ($this->debug) ADOConnection::outp($e); - return false; - } - $this->_errorMsg = ''; - $this->database = $ldapbase; - return $this->_connectionID; - } - -/* - Valid Domain Values for LDAP Options: - - LDAP_OPT_DEREF (integer) - LDAP_OPT_SIZELIMIT (integer) - LDAP_OPT_TIMELIMIT (integer) - LDAP_OPT_PROTOCOL_VERSION (integer) - LDAP_OPT_ERROR_NUMBER (integer) - LDAP_OPT_REFERRALS (boolean) - LDAP_OPT_RESTART (boolean) - LDAP_OPT_HOST_NAME (string) - LDAP_OPT_ERROR_STRING (string) - LDAP_OPT_MATCHED_DN (string) - LDAP_OPT_SERVER_CONTROLS (array) - LDAP_OPT_CLIENT_CONTROLS (array) - - Make sure to set this BEFORE calling Connect() - - Example: - - $LDAP_CONNECT_OPTIONS = Array( - Array ( - "OPTION_NAME"=>LDAP_OPT_DEREF, - "OPTION_VALUE"=>2 - ), - Array ( - "OPTION_NAME"=>LDAP_OPT_SIZELIMIT, - "OPTION_VALUE"=>100 - ), - Array ( - "OPTION_NAME"=>LDAP_OPT_TIMELIMIT, - "OPTION_VALUE"=>30 - ), - Array ( - "OPTION_NAME"=>LDAP_OPT_PROTOCOL_VERSION, - "OPTION_VALUE"=>3 - ), - Array ( - "OPTION_NAME"=>LDAP_OPT_ERROR_NUMBER, - "OPTION_VALUE"=>13 - ), - Array ( - "OPTION_NAME"=>LDAP_OPT_REFERRALS, - "OPTION_VALUE"=>FALSE - ), - Array ( - "OPTION_NAME"=>LDAP_OPT_RESTART, - "OPTION_VALUE"=>FALSE - ) - ); -*/ - - function _inject_bind_options( $options ) { - foreach( $options as $option ) { - ldap_set_option( $this->_connectionID, $option["OPTION_NAME"], $option["OPTION_VALUE"] ) - or die( "Unable to set server option: " . $option["OPTION_NAME"] ); - } - } - - /* returns _queryID or false */ - function _query($sql,$inputarr=false) - { - $rs = @ldap_search( $this->_connectionID, $this->database, $sql ); - $this->_errorMsg = ($rs) ? '' : 'Search error on '.$sql.': '.ldap_error($this->_connectionID); - return $rs; - } - - function ErrorMsg() - { - return $this->_errorMsg; - } - - function ErrorNo() - { - return @ldap_errno($this->_connectionID); - } - - /* closes the LDAP connection */ - function _close() - { - @ldap_close( $this->_connectionID ); - $this->_connectionID = false; - } - - function SelectDB($db) { - $this->database = $db; - return true; - } // SelectDB - - function ServerInfo() - { - if( !empty( $this->version ) ) return $this->version; - $version = array(); - /* - Determines how aliases are handled during search. - LDAP_DEREF_NEVER (0x00) - LDAP_DEREF_SEARCHING (0x01) - LDAP_DEREF_FINDING (0x02) - LDAP_DEREF_ALWAYS (0x03) - The LDAP_DEREF_SEARCHING value means aliases are dereferenced during the search but - not when locating the base object of the search. The LDAP_DEREF_FINDING value means - aliases are dereferenced when locating the base object but not during the search. - Default: LDAP_DEREF_NEVER - */ - ldap_get_option( $this->_connectionID, LDAP_OPT_DEREF, $version['LDAP_OPT_DEREF'] ) ; - switch ( $version['LDAP_OPT_DEREF'] ) { - case 0: - $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_NEVER'; - case 1: - $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_SEARCHING'; - case 2: - $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_FINDING'; - case 3: - $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_ALWAYS'; - } - - /* - A limit on the number of entries to return from a search. - LDAP_NO_LIMIT (0) means no limit. - Default: LDAP_NO_LIMIT - */ - ldap_get_option( $this->_connectionID, LDAP_OPT_SIZELIMIT, $version['LDAP_OPT_SIZELIMIT'] ); - if ( $version['LDAP_OPT_SIZELIMIT'] == 0 ) { - $version['LDAP_OPT_SIZELIMIT'] = 'LDAP_NO_LIMIT'; - } - - /* - A limit on the number of seconds to spend on a search. - LDAP_NO_LIMIT (0) means no limit. - Default: LDAP_NO_LIMIT - */ - ldap_get_option( $this->_connectionID, LDAP_OPT_TIMELIMIT, $version['LDAP_OPT_TIMELIMIT'] ); - if ( $version['LDAP_OPT_TIMELIMIT'] == 0 ) { - $version['LDAP_OPT_TIMELIMIT'] = 'LDAP_NO_LIMIT'; - } - - /* - Determines whether the LDAP library automatically follows referrals returned by LDAP servers or not. - LDAP_OPT_ON - LDAP_OPT_OFF - Default: ON - */ - ldap_get_option( $this->_connectionID, LDAP_OPT_REFERRALS, $version['LDAP_OPT_REFERRALS'] ); - if ( $version['LDAP_OPT_REFERRALS'] == 0 ) { - $version['LDAP_OPT_REFERRALS'] = 'LDAP_OPT_OFF'; - } else { - $version['LDAP_OPT_REFERRALS'] = 'LDAP_OPT_ON'; - - } - /* - Determines whether LDAP I/O operations are automatically restarted if they abort prematurely. - LDAP_OPT_ON - LDAP_OPT_OFF - Default: OFF - */ - ldap_get_option( $this->_connectionID, LDAP_OPT_RESTART, $version['LDAP_OPT_RESTART'] ); - if ( $version['LDAP_OPT_RESTART'] == 0 ) { - $version['LDAP_OPT_RESTART'] = 'LDAP_OPT_OFF'; - } else { - $version['LDAP_OPT_RESTART'] = 'LDAP_OPT_ON'; - - } - /* - This option indicates the version of the LDAP protocol used when communicating with the primary LDAP server. - LDAP_VERSION2 (2) - LDAP_VERSION3 (3) - Default: LDAP_VERSION2 (2) - */ - ldap_get_option( $this->_connectionID, LDAP_OPT_PROTOCOL_VERSION, $version['LDAP_OPT_PROTOCOL_VERSION'] ); - if ( $version['LDAP_OPT_PROTOCOL_VERSION'] == 2 ) { - $version['LDAP_OPT_PROTOCOL_VERSION'] = 'LDAP_VERSION2'; - } else { - $version['LDAP_OPT_PROTOCOL_VERSION'] = 'LDAP_VERSION3'; - - } - /* The host name (or list of hosts) for the primary LDAP server. */ - ldap_get_option( $this->_connectionID, LDAP_OPT_HOST_NAME, $version['LDAP_OPT_HOST_NAME'] ); - ldap_get_option( $this->_connectionID, LDAP_OPT_ERROR_NUMBER, $version['LDAP_OPT_ERROR_NUMBER'] ); - ldap_get_option( $this->_connectionID, LDAP_OPT_ERROR_STRING, $version['LDAP_OPT_ERROR_STRING'] ); - ldap_get_option( $this->_connectionID, LDAP_OPT_MATCHED_DN, $version['LDAP_OPT_MATCHED_DN'] ); - - return $this->version = $version; - - } -} - -/*-------------------------------------------------------------------------------------- - Class Name: Recordset ---------------------------------------------------------------------------------------*/ - -class ADORecordSet_ldap extends ADORecordSet{ - - var $databaseType = "ldap"; - var $canSeek = false; - var $_entryID; /* keeps track of the entry resource identifier */ - - function ADORecordSet_ldap($queryID,$mode=false) - { - if ($mode === false) { - global $ADODB_FETCH_MODE; - $mode = $ADODB_FETCH_MODE; - } - switch ($mode) - { - case ADODB_FETCH_NUM: - $this->fetchMode = LDAP_NUM; - break; - case ADODB_FETCH_ASSOC: - $this->fetchMode = LDAP_ASSOC; - break; - case ADODB_FETCH_DEFAULT: - case ADODB_FETCH_BOTH: - default: - $this->fetchMode = LDAP_BOTH; - break; - } - - $this->ADORecordSet($queryID); - } - - function _initrs() - { - /* - This could be teaked to respect the $COUNTRECS directive from ADODB - It's currently being used in the _fetch() function and the - GetAssoc() function - */ - $this->_numOfRows = ldap_count_entries( $this->connection->_connectionID, $this->_queryID ); - - } - - /* - Return whole recordset as a multi-dimensional associative array - */ - function GetAssoc($force_array = false, $first2cols = false) - { - $records = $this->_numOfRows; - $results = array(); - for ( $i=0; $i < $records; $i++ ) { - foreach ( $this->fields as $k=>$v ) { - if ( is_array( $v ) ) { - if ( $v['count'] == 1 ) { - $results[$i][$k] = $v[0]; - } else { - array_shift( $v ); - $results[$i][$k] = $v; - } - } - } - } - - return $results; - } - - function GetRowAssoc() - { - $results = array(); - foreach ( $this->fields as $k=>$v ) { - if ( is_array( $v ) ) { - if ( $v['count'] == 1 ) { - $results[$k] = $v[0]; - } else { - array_shift( $v ); - $results[$k] = $v; - } - } - } - - return $results; - } - - function GetRowNums() - { - $results = array(); - foreach ( $this->fields as $k=>$v ) { - static $i = 0; - if (is_array( $v )) { - if ( $v['count'] == 1 ) { - $results[$i] = $v[0]; - } else { - array_shift( $v ); - $results[$i] = $v; - } - $i++; - } - } - return $results; - } - - function _fetch() - { - if ( $this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0 ) - return false; - - if ( $this->_currentRow == 0 ) { - $this->_entryID = ldap_first_entry( $this->connection->_connectionID, $this->_queryID ); - } else { - $this->_entryID = ldap_next_entry( $this->connection->_connectionID, $this->_entryID ); - } - - $this->fields = ldap_get_attributes( $this->connection->_connectionID, $this->_entryID ); - $this->_numOfFields = $this->fields['count']; - switch ( $this->fetchMode ) { - - case LDAP_ASSOC: - $this->fields = $this->GetRowAssoc(); - break; - - case LDAP_NUM: - $this->fields = array_merge($this->GetRowNums(),$this->GetRowAssoc()); - break; - - case LDAP_BOTH: - default: - $this->fields = $this->GetRowNums(); - break; - } - return ( is_array( $this->fields ) ); - } - - function _close() { - @ldap_free_result( $this->_queryID ); - $this->_queryID = false; - } - -} +_connectionID = @ldap_connect($host); + } else { + $conn_info = array( $host,$this->port); + + if ( strstr( $host, ':' ) ) { + $conn_info = explode( ':', $host ); + } + + $this->_connectionID = @ldap_connect( $conn_info[0], $conn_info[1] ); + } + if (!$this->_connectionID) { + $e = 'Could not connect to ' . $conn_info[0]; + $this->_errorMsg = $e; + if ($this->debug) ADOConnection::outp($e); + return false; + } + if( count( $LDAP_CONNECT_OPTIONS ) > 0 ) { + $this->_inject_bind_options( $LDAP_CONNECT_OPTIONS ); + } + + if ($username) { + $bind = @ldap_bind( $this->_connectionID, $username, $password ); + } else { + $username = 'anonymous'; + $bind = @ldap_bind( $this->_connectionID ); + } + + if (!$bind) { + $e = sprintf($this->_bind_errmsg,ldap_error($this->_connectionID)); + $this->_errorMsg = $e; + if ($this->debug) ADOConnection::outp($e); + return false; + } + $this->_errorMsg = ''; + $this->database = $ldapbase; + return $this->_connectionID; + } + +/* + Valid Domain Values for LDAP Options: + + LDAP_OPT_DEREF (integer) + LDAP_OPT_SIZELIMIT (integer) + LDAP_OPT_TIMELIMIT (integer) + LDAP_OPT_PROTOCOL_VERSION (integer) + LDAP_OPT_ERROR_NUMBER (integer) + LDAP_OPT_REFERRALS (boolean) + LDAP_OPT_RESTART (boolean) + LDAP_OPT_HOST_NAME (string) + LDAP_OPT_ERROR_STRING (string) + LDAP_OPT_MATCHED_DN (string) + LDAP_OPT_SERVER_CONTROLS (array) + LDAP_OPT_CLIENT_CONTROLS (array) + + Make sure to set this BEFORE calling Connect() + + Example: + + $LDAP_CONNECT_OPTIONS = Array( + Array ( + "OPTION_NAME"=>LDAP_OPT_DEREF, + "OPTION_VALUE"=>2 + ), + Array ( + "OPTION_NAME"=>LDAP_OPT_SIZELIMIT, + "OPTION_VALUE"=>100 + ), + Array ( + "OPTION_NAME"=>LDAP_OPT_TIMELIMIT, + "OPTION_VALUE"=>30 + ), + Array ( + "OPTION_NAME"=>LDAP_OPT_PROTOCOL_VERSION, + "OPTION_VALUE"=>3 + ), + Array ( + "OPTION_NAME"=>LDAP_OPT_ERROR_NUMBER, + "OPTION_VALUE"=>13 + ), + Array ( + "OPTION_NAME"=>LDAP_OPT_REFERRALS, + "OPTION_VALUE"=>FALSE + ), + Array ( + "OPTION_NAME"=>LDAP_OPT_RESTART, + "OPTION_VALUE"=>FALSE + ) + ); +*/ + + function _inject_bind_options( $options ) { + foreach( $options as $option ) { + ldap_set_option( $this->_connectionID, $option["OPTION_NAME"], $option["OPTION_VALUE"] ) + or die( "Unable to set server option: " . $option["OPTION_NAME"] ); + } + } + + /* returns _queryID or false */ + function _query($sql,$inputarr=false) + { + $rs = @ldap_search( $this->_connectionID, $this->database, $sql ); + $this->_errorMsg = ($rs) ? '' : 'Search error on '.$sql.': '.ldap_error($this->_connectionID); + return $rs; + } + + function ErrorMsg() + { + return $this->_errorMsg; + } + + function ErrorNo() + { + return @ldap_errno($this->_connectionID); + } + + /* closes the LDAP connection */ + function _close() + { + @ldap_close( $this->_connectionID ); + $this->_connectionID = false; + } + + function SelectDB($db) { + $this->database = $db; + return true; + } // SelectDB + + function ServerInfo() + { + if( !empty( $this->version ) ) { + return $this->version; + } + + $version = array(); + /* + Determines how aliases are handled during search. + LDAP_DEREF_NEVER (0x00) + LDAP_DEREF_SEARCHING (0x01) + LDAP_DEREF_FINDING (0x02) + LDAP_DEREF_ALWAYS (0x03) + The LDAP_DEREF_SEARCHING value means aliases are dereferenced during the search but + not when locating the base object of the search. The LDAP_DEREF_FINDING value means + aliases are dereferenced when locating the base object but not during the search. + Default: LDAP_DEREF_NEVER + */ + ldap_get_option( $this->_connectionID, LDAP_OPT_DEREF, $version['LDAP_OPT_DEREF'] ) ; + switch ( $version['LDAP_OPT_DEREF'] ) { + case 0: + $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_NEVER'; + case 1: + $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_SEARCHING'; + case 2: + $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_FINDING'; + case 3: + $version['LDAP_OPT_DEREF'] = 'LDAP_DEREF_ALWAYS'; + } + + /* + A limit on the number of entries to return from a search. + LDAP_NO_LIMIT (0) means no limit. + Default: LDAP_NO_LIMIT + */ + ldap_get_option( $this->_connectionID, LDAP_OPT_SIZELIMIT, $version['LDAP_OPT_SIZELIMIT'] ); + if ( $version['LDAP_OPT_SIZELIMIT'] == 0 ) { + $version['LDAP_OPT_SIZELIMIT'] = 'LDAP_NO_LIMIT'; + } + + /* + A limit on the number of seconds to spend on a search. + LDAP_NO_LIMIT (0) means no limit. + Default: LDAP_NO_LIMIT + */ + ldap_get_option( $this->_connectionID, LDAP_OPT_TIMELIMIT, $version['LDAP_OPT_TIMELIMIT'] ); + if ( $version['LDAP_OPT_TIMELIMIT'] == 0 ) { + $version['LDAP_OPT_TIMELIMIT'] = 'LDAP_NO_LIMIT'; + } + + /* + Determines whether the LDAP library automatically follows referrals returned by LDAP servers or not. + LDAP_OPT_ON + LDAP_OPT_OFF + Default: ON + */ + ldap_get_option( $this->_connectionID, LDAP_OPT_REFERRALS, $version['LDAP_OPT_REFERRALS'] ); + if ( $version['LDAP_OPT_REFERRALS'] == 0 ) { + $version['LDAP_OPT_REFERRALS'] = 'LDAP_OPT_OFF'; + } else { + $version['LDAP_OPT_REFERRALS'] = 'LDAP_OPT_ON'; + } + + /* + Determines whether LDAP I/O operations are automatically restarted if they abort prematurely. + LDAP_OPT_ON + LDAP_OPT_OFF + Default: OFF + */ + ldap_get_option( $this->_connectionID, LDAP_OPT_RESTART, $version['LDAP_OPT_RESTART'] ); + if ( $version['LDAP_OPT_RESTART'] == 0 ) { + $version['LDAP_OPT_RESTART'] = 'LDAP_OPT_OFF'; + } else { + $version['LDAP_OPT_RESTART'] = 'LDAP_OPT_ON'; + } + + /* + This option indicates the version of the LDAP protocol used when communicating with the primary LDAP server. + LDAP_VERSION2 (2) + LDAP_VERSION3 (3) + Default: LDAP_VERSION2 (2) + */ + ldap_get_option( $this->_connectionID, LDAP_OPT_PROTOCOL_VERSION, $version['LDAP_OPT_PROTOCOL_VERSION'] ); + if ( $version['LDAP_OPT_PROTOCOL_VERSION'] == 2 ) { + $version['LDAP_OPT_PROTOCOL_VERSION'] = 'LDAP_VERSION2'; + } else { + $version['LDAP_OPT_PROTOCOL_VERSION'] = 'LDAP_VERSION3'; + } + + /* The host name (or list of hosts) for the primary LDAP server. */ + ldap_get_option( $this->_connectionID, LDAP_OPT_HOST_NAME, $version['LDAP_OPT_HOST_NAME'] ); + ldap_get_option( $this->_connectionID, LDAP_OPT_ERROR_NUMBER, $version['LDAP_OPT_ERROR_NUMBER'] ); + ldap_get_option( $this->_connectionID, LDAP_OPT_ERROR_STRING, $version['LDAP_OPT_ERROR_STRING'] ); + ldap_get_option( $this->_connectionID, LDAP_OPT_MATCHED_DN, $version['LDAP_OPT_MATCHED_DN'] ); + + return $this->version = $version; + } +} + +/*-------------------------------------------------------------------------------------- + Class Name: Recordset +--------------------------------------------------------------------------------------*/ + +class ADORecordSet_ldap extends ADORecordSet{ + + var $databaseType = "ldap"; + var $canSeek = false; + var $_entryID; /* keeps track of the entry resource identifier */ + + function __construct($queryID,$mode=false) + { + if ($mode === false) { + global $ADODB_FETCH_MODE; + $mode = $ADODB_FETCH_MODE; + } + switch ($mode) + { + case ADODB_FETCH_NUM: + $this->fetchMode = LDAP_NUM; + break; + case ADODB_FETCH_ASSOC: + $this->fetchMode = LDAP_ASSOC; + break; + case ADODB_FETCH_DEFAULT: + case ADODB_FETCH_BOTH: + default: + $this->fetchMode = LDAP_BOTH; + break; + } + + parent::__construct($queryID); + } + + function _initrs() + { + /* + This could be teaked to respect the $COUNTRECS directive from ADODB + It's currently being used in the _fetch() function and the + GetAssoc() function + */ + $this->_numOfRows = ldap_count_entries( $this->connection->_connectionID, $this->_queryID ); + } + + /* + Return whole recordset as a multi-dimensional associative array + */ + function GetAssoc($force_array = false, $first2cols = false) + { + $records = $this->_numOfRows; + $results = array(); + for ( $i=0; $i < $records; $i++ ) { + foreach ( $this->fields as $k=>$v ) { + if ( is_array( $v ) ) { + if ( $v['count'] == 1 ) { + $results[$i][$k] = $v[0]; + } else { + array_shift( $v ); + $results[$i][$k] = $v; + } + } + } + } + + return $results; + } + + function GetRowAssoc($upper = ADODB_ASSOC_CASE) + { + $results = array(); + foreach ( $this->fields as $k=>$v ) { + if ( is_array( $v ) ) { + if ( $v['count'] == 1 ) { + $results[$k] = $v[0]; + } else { + array_shift( $v ); + $results[$k] = $v; + } + } + } + + return $results; + } + + function GetRowNums() + { + $results = array(); + foreach ( $this->fields as $k=>$v ) { + static $i = 0; + if (is_array( $v )) { + if ( $v['count'] == 1 ) { + $results[$i] = $v[0]; + } else { + array_shift( $v ); + $results[$i] = $v; + } + $i++; + } + } + return $results; + } + + function _fetch() + { + if ( $this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0 ) { + return false; + } + + if ( $this->_currentRow == 0 ) { + $this->_entryID = ldap_first_entry( $this->connection->_connectionID, $this->_queryID ); + } else { + $this->_entryID = ldap_next_entry( $this->connection->_connectionID, $this->_entryID ); + } + + $this->fields = ldap_get_attributes( $this->connection->_connectionID, $this->_entryID ); + $this->_numOfFields = $this->fields['count']; + + switch ( $this->fetchMode ) { + + case LDAP_ASSOC: + $this->fields = $this->GetRowAssoc(); + break; + + case LDAP_NUM: + $this->fields = array_merge($this->GetRowNums(),$this->GetRowAssoc()); + break; + + case LDAP_BOTH: + default: + $this->fields = $this->GetRowNums(); + break; + } + + return is_array( $this->fields ); + } + + function _close() { + @ldap_free_result( $this->_queryID ); + $this->_queryID = false; + } + +} diff --git a/lib/adodb/drivers/adodb-mssql.inc.php b/lib/adodb/drivers/adodb-mssql.inc.php index 58a0259a674..a5ea6b908bc 100644 --- a/lib/adodb/drivers/adodb-mssql.inc.php +++ b/lib/adodb/drivers/adodb-mssql.inc.php @@ -1,6 +1,8 @@ _has_mssql_init = (strnatcmp(PHP_VERSION,'4.1.0')>=0); } @@ -865,7 +867,7 @@ class ADORecordset_mssql extends ADORecordSet { var $hasFetchAssoc; // see http://phplens.com/lens/lensforum/msgs.php?id=6083 // _mths works only in non-localised system - function ADORecordset_mssql($id,$mode=false) + function __construct($id,$mode=false) { // freedts check... $this->hasFetchAssoc = function_exists('mssql_fetch_assoc'); @@ -876,7 +878,7 @@ class ADORecordset_mssql extends ADORecordSet { } $this->fetchMode = $mode; - return $this->ADORecordSet($id,$mode); + return parent::__construct($id,$mode); } @@ -1068,9 +1070,9 @@ class ADORecordset_mssql extends ADORecordSet { class ADORecordSet_array_mssql extends ADORecordSet_array { - function ADORecordSet_array_mssql($id=-1,$mode=false) + function __construct($id=-1,$mode=false) { - $this->ADORecordSet_array($id,$mode); + parent::__construct($id,$mode); } // mssql uses a default date like Dec 30 2000 12:00AM diff --git a/lib/adodb/drivers/adodb-mssql_n.inc.php b/lib/adodb/drivers/adodb-mssql_n.inc.php index 69338b4a0ac..c9163b5fbd5 100644 --- a/lib/adodb/drivers/adodb-mssql_n.inc.php +++ b/lib/adodb/drivers/adodb-mssql_n.inc.php @@ -64,107 +64,191 @@ class ADODB_mssql_n extends ADODB_mssql { return ADODB_mssql::_query($sql,$inputarr); } - /** + /** * This function will intercept all the literals used in the SQL, prepending the "N" char to them * in order to allow mssql to store properly data sent in the correct UCS-2 encoding (by freeTDS * and ODBTP) keeping SQL compatibility at ADOdb level (instead of hacking every project to add * the "N" notation when working against MSSQL. * - * Note that this hack only must be used if ALL the char-based columns in your DB are of type nchar, - * nvarchar and ntext + * The orginal note indicated that this hack should only be used if ALL the char-based columns + * in your DB are of type nchar, nvarchar and ntext, but testing seems to indicate that SQL server + * doesn't seem to care if the statement is used against char etc fields. + * + * @todo This function should raise an ADOdb error if one of the transformations fail + * + * @param mixed $inboundData Either a string containing an SQL statement + * or an array with resources from prepared statements + * + * @return mixed */ - function _appendN($sql) { - - $result = $sql; - - /// Check we have some single quote in the query. Exit ok. - if (strpos($sql, SINGLEQUOTE) === false) { - return $sql; - } - - /// Check we haven't an odd number of single quotes (this can cause problems below - /// and should be considered one wrong SQL). Exit with debug info. - if ((substr_count($sql, SINGLEQUOTE) & 1)) { - if ($this->debug) { - ADOConnection::outp("{$this->databaseType} internal transformation: not converted. Wrong number of quotes (odd)"); + function _appendN($inboundData) { + + $inboundIsArray = false; + + if (is_array($inboundData)) + { + $inboundIsArray = true; + $inboundArray = $inboundData; + } else + $inboundArray = (array)$inboundData; + + /* + * All changes will be placed here + */ + $outboundArray = $inboundArray; + + foreach($inboundArray as $inboundKey=>$inboundValue) + { + + if (is_resource($inboundValue)) + { + /* + * Prepared statement resource + */ + if ($this->debug) + ADOConnection::outp("{$this->databaseType} index $inboundKey value is resource, continue"); + + continue; } - return $sql; - } - - /// Check we haven't any backslash + single quote combination. It should mean wrong - /// backslashes use (bad magic_quotes_sybase?). Exit with debug info. - $regexp = '/(\\\\' . SINGLEQUOTE . '[^' . SINGLEQUOTE . '])/'; - if (preg_match($regexp, $sql)) { - if ($this->debug) { - ADOConnection::outp("{$this->databaseType} internal transformation: not converted. Found bad use of backslash + single quote"); + + if (strpos($inboundValue, SINGLEQUOTE) === false) + { + /* + * Check we have something to manipulate + */ + if ($this->debug) + ADOConnection::outp("{$this->databaseType} index $inboundKey value $inboundValue has no single quotes, continue"); + continue; } - return $sql; - } - /// Remove pairs of single-quotes - $pairs = array(); - $regexp = '/(' . SINGLEQUOTE . SINGLEQUOTE . ')/'; - preg_match_all($regexp, $result, $list_of_pairs); - if ($list_of_pairs) { - foreach (array_unique($list_of_pairs[0]) as $key=>$value) { - $pairs['<@#@#@PAIR-'.$key.'@#@#@>'] = $value; + /* + * Check we haven't an odd number of single quotes (this can cause problems below + * and should be considered one wrong SQL). Exit with debug info. + */ + if ((substr_count($inboundValue, SINGLEQUOTE) & 1)) + { + if ($this->debug) + ADOConnection::outp("{$this->databaseType} internal transformation: not converted. Wrong number of quotes (odd)"); + + break; } - if (!empty($pairs)) { - $result = str_replace($pairs, array_keys($pairs), $result); - } - } - /// Remove the rest of literals present in the query - $literals = array(); - $regexp = '/(N?' . SINGLEQUOTE . '.*?' . SINGLEQUOTE . ')/is'; - preg_match_all($regexp, $result, $list_of_literals); - if ($list_of_literals) { - foreach (array_unique($list_of_literals[0]) as $key=>$value) { - $literals['<#@#@#LITERAL-'.$key.'#@#@#>'] = $value; + /* + * Check we haven't any backslash + single quote combination. It should mean wrong + * backslashes use (bad magic_quotes_sybase?). Exit with debug info. + */ + $regexp = '/(\\\\' . SINGLEQUOTE . '[^' . SINGLEQUOTE . '])/'; + if (preg_match($regexp, $inboundValue)) + { + if ($this->debug) + ADOConnection::outp("{$this->databaseType} internal transformation: not converted. Found bad use of backslash + single quote"); + + break; } - if (!empty($literals)) { - $result = str_replace($literals, array_keys($literals), $result); + + /* + * Remove pairs of single-quotes + */ + $pairs = array(); + $regexp = '/(' . SINGLEQUOTE . SINGLEQUOTE . ')/'; + preg_match_all($regexp, $inboundValue, $list_of_pairs); + + if ($list_of_pairs) + { + foreach (array_unique($list_of_pairs[0]) as $key=>$value) + $pairs['<@#@#@PAIR-'.$key.'@#@#@>'] = $value; + + + if (!empty($pairs)) + $inboundValue = str_replace($pairs, array_keys($pairs), $inboundValue); + } - } + /* + * Remove the rest of literals present in the query + */ + $literals = array(); + $regexp = '/(N?' . SINGLEQUOTE . '.*?' . SINGLEQUOTE . ')/is'; + preg_match_all($regexp, $inboundValue, $list_of_literals); + + if ($list_of_literals) + { + foreach (array_unique($list_of_literals[0]) as $key=>$value) + $literals['<#@#@#LITERAL-'.$key.'#@#@#>'] = $value; + + + if (!empty($literals)) + $inboundValue = str_replace($literals, array_keys($literals), $inboundValue); + } - /// Analyse literals to prepend the N char to them if their contents aren't numeric - if (!empty($literals)) { - foreach ($literals as $key=>$value) { - if (!is_numeric(trim($value, SINGLEQUOTE))) { - /// Non numeric string, prepend our dear N - $literals[$key] = 'N' . trim($value, 'N'); //Trimming potentially existing previous "N" + /* + * Analyse literals to prepend the N char to them if their contents aren't numeric + */ + if (!empty($literals)) + { + foreach ($literals as $key=>$value) { + if (!is_numeric(trim($value, SINGLEQUOTE))) + /* + * Non numeric string, prepend our dear N, whilst + * Trimming potentially existing previous "N" + */ + $literals[$key] = 'N' . trim($value, 'N'); + } } - } - /// Re-apply literals to the text - if (!empty($literals)) { - $result = str_replace(array_keys($literals), $literals, $result); + /* + * Re-apply literals to the text + */ + if (!empty($literals)) + $inboundValue = str_replace(array_keys($literals), $literals, $inboundValue); + + + /* + * Any pairs followed by N' must be switched to N' followed by those pairs + * (or strings beginning with single quotes will fail) + */ + $inboundValue = preg_replace("/((<@#@#@PAIR-(\d+)@#@#@>)+)N'/", "N'$1", $inboundValue); + + /* + * Re-apply pairs of single-quotes to the text + */ + if (!empty($pairs)) + $inboundValue = str_replace(array_keys($pairs), $pairs, $inboundValue); + + + /* + * Print transformation if debug = on + */ + if (strcmp($inboundValue,$inboundArray[$inboundKey]) <> 0 && $this->debug) + ADOConnection::outp("{$this->databaseType} internal transformation: {$inboundArray[$inboundKey]} to {$inboundValue}"); + + if (strcmp($inboundValue,$inboundArray[$inboundKey]) <> 0) + /* + * Place the transformed value into the outbound array + */ + $outboundArray[$inboundKey] = $inboundValue; } - - /// Any pairs followed by N' must be switched to N' followed by those pairs - /// (or strings beginning with single quotes will fail) - $result = preg_replace("/((<@#@#@PAIR-(\d+)@#@#@>)+)N'/", "N'$1", $result); - - /// Re-apply pairs of single-quotes to the text - if (!empty($pairs)) { - $result = str_replace(array_keys($pairs), $pairs, $result); - } - - /// Print transformation if debug = on - if ($result != $sql && $this->debug) { - ADOConnection::outp("{$this->databaseType} internal transformation:
{$sql}
to
{$result}"); - } - - return $result; + + /* + * Any transformations are in the $outboundArray + */ + if ($inboundIsArray) + return $outboundArray; + + /* + * We passed a string in originally + */ + return $outboundArray[0]; + } + } class ADORecordset_mssql_n extends ADORecordset_mssql { var $databaseType = "mssql_n"; - function ADORecordset_mssql_n($id,$mode=false) + function __construct($id,$mode=false) { - $this->ADORecordset_mssql($id,$mode); + parent::__construct($id,$mode); } } diff --git a/lib/adodb/drivers/adodb-mssqlnative.inc.php b/lib/adodb/drivers/adodb-mssqlnative.inc.php index b10d55546bc..ae5a11217b2 100644 --- a/lib/adodb/drivers/adodb-mssqlnative.inc.php +++ b/lib/adodb/drivers/adodb-mssqlnative.inc.php @@ -1,6 +1,8 @@ debug) { - error_log("
");
-            sqlsrv_set_error_handling( SQLSRV_ERRORS_LOG_ALL );
-            sqlsrv_log_set_severity( SQLSRV_LOG_SEVERITY_ALL );
-            sqlsrv_log_set_subsystems(SQLSRV_LOG_SYSTEM_ALL);
-            sqlsrv_configure('warnings_return_as_errors', 0);
-        } else {
-            sqlsrv_set_error_handling(0);
-            sqlsrv_log_set_severity(0);
-            sqlsrv_log_set_subsystems(SQLSRV_LOG_SYSTEM_ALL);
-            sqlsrv_configure('warnings_return_as_errors', 0);
-        }
+		if ($this->debug) {
+			ADOConnection::outp("
");
+			sqlsrv_set_error_handling( SQLSRV_ERRORS_LOG_ALL );
+			sqlsrv_log_set_severity( SQLSRV_LOG_SEVERITY_ALL );
+			sqlsrv_log_set_subsystems(SQLSRV_LOG_SYSTEM_ALL);
+			sqlsrv_configure('WarningsReturnAsErrors', 0);
+		} else {
+			sqlsrv_set_error_handling(0);
+			sqlsrv_log_set_severity(0);
+			sqlsrv_log_set_subsystems(SQLSRV_LOG_SYSTEM_ALL);
+			sqlsrv_configure('WarningsReturnAsErrors', 0);
+		}
 	}
 	function ServerVersion() {
 		$data = $this->ServerInfo();
@@ -239,13 +241,13 @@ class ADODB_mssqlnative extends ADOConnection {
 	 */
 	function CreateSequence2008($seq='adodbseq',$start=1)
 	{
-		if($this->debug) error_log("
CreateSequence($seq,$start)"); + if($this->debug) ADOConnection::outp("
CreateSequence($seq,$start)"); sqlsrv_begin_transaction($this->_connectionID); $start -= 1; $this->Execute("create table $seq (id int)");//was float(53) $ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)"); if (!$ok) { - if($this->debug) error_log("
Error: ROLLBACK"); + if($this->debug) ADOConnection::outp("
Error: ROLLBACK"); sqlsrv_rollback($this->_connectionID); return false; } @@ -272,7 +274,7 @@ class ADODB_mssqlnative extends ADOConnection { */ function GenID2008($seq='adodbseq',$start=1) { - if($this->debug) error_log("
CreateSequence($seq,$start)"); + if($this->debug) ADOConnection::outp("
CreateSequence($seq,$start)"); sqlsrv_begin_transaction($this->_connectionID); $ok = $this->Execute("update $seq with (tablock,holdlock) set id = id + 1"); if (!$ok) { @@ -280,7 +282,7 @@ class ADODB_mssqlnative extends ADOConnection { $this->Execute("create table $seq (id int)");//was float(53) $ok = $this->Execute("insert into $seq with (tablock,holdlock) values($start)"); if (!$ok) { - if($this->debug) error_log("
Error: ROLLBACK"); + if($this->debug) ADOConnection::outp("
Error: ROLLBACK"); sqlsrv_rollback($this->_connectionID); return false; } @@ -383,7 +385,7 @@ class ADODB_mssqlnative extends ADOConnection { { if ($this->transOff) return true; $this->transCnt += 1; - if ($this->debug) error_log('
begin transaction'); + if ($this->debug) ADOConnection::outp('
begin transaction'); sqlsrv_begin_transaction($this->_connectionID); return true; } @@ -391,7 +393,7 @@ class ADODB_mssqlnative extends ADOConnection { function CommitTrans($ok=true) { if ($this->transOff) return true; - if ($this->debug) error_log('
commit transaction'); + if ($this->debug) ADOConnection::outp('
commit transaction'); if (!$ok) return $this->RollbackTrans(); if ($this->transCnt) $this->transCnt -= 1; sqlsrv_commit($this->_connectionID); @@ -400,7 +402,7 @@ class ADODB_mssqlnative extends ADOConnection { function RollbackTrans() { if ($this->transOff) return true; - if ($this->debug) error_log('
rollback transaction'); + if ($this->debug) ADOConnection::outp('
rollback transaction'); if ($this->transCnt) $this->transCnt -= 1; sqlsrv_rollback($this->_connectionID); return true; @@ -480,14 +482,18 @@ class ADODB_mssqlnative extends ADOConnection { $connectionInfo["Database"]=$argDatabasename; $connectionInfo["UID"]=$argUsername; $connectionInfo["PWD"]=$argPassword; - if ($this->debug) error_log("
connecting... hostname: $argHostname params: ".var_export($connectionInfo,true)); - //if ($this->debug) error_log("
_connectionID before: ".serialize($this->_connectionID)); + + foreach ($this->connectionParameters as $parameter=>$value) + $connectionInfo[$parameter] = $value; + + if ($this->debug) ADOConnection::outp("
connecting... hostname: $argHostname params: ".var_export($connectionInfo,true)); + //if ($this->debug) ADOConnection::outp("
_connectionID before: ".serialize($this->_connectionID)); if(!($this->_connectionID = sqlsrv_connect($argHostname,$connectionInfo))) { - if ($this->debug) error_log( "
errors: ".print_r( sqlsrv_errors(), true)); + if ($this->debug) ADOConnection::outp( "
errors: ".print_r( sqlsrv_errors(), true)); return false; } - //if ($this->debug) error_log(" _connectionID after: ".serialize($this->_connectionID)); - //if ($this->debug) error_log("
defined functions:
".var_export(get_defined_functions(),true)."
"); + //if ($this->debug) ADOConnection::outp(" _connectionID after: ".serialize($this->_connectionID)); + //if ($this->debug) ADOConnection::outp("
defined functions:
".var_export(get_defined_functions(),true)."
"); return true; } @@ -558,12 +564,12 @@ class ADODB_mssqlnative extends ADOConnection { function _query($sql,$inputarr=false) { $this->_errorMsg = false; - + if (is_array($sql)) $sql = $sql[1]; - + $insert = false; // handle native driver flaw for retrieving the last insert ID - if(preg_match('/^\W*(insert [^;]+);?$/i', $sql)) { + if(preg_match('/^\W*insert\s(?:(?:(?:\'\')*\'[^\']+\'(?:\'\')*)|[^;\'])*;?$/i', $sql)) { $insert = true; $sql .= '; '.$this->identitySQL; // select scope_identity() } @@ -573,15 +579,16 @@ class ADODB_mssqlnative extends ADOConnection { $rez = sqlsrv_query($this->_connectionID,$sql); } - if ($this->debug) error_log("
running query: ".var_export($sql,true)."
input array: ".var_export($inputarr,true)."
result: ".var_export($rez,true)); + if ($this->debug) ADOConnection::outp("
running query: ".var_export($sql,true)."
input array: ".var_export($inputarr,true)."
result: ".var_export($rez,true)); if(!$rez) { $rez = false; } else if ($insert) { // retrieve the last insert ID (where applicable) - sqlsrv_next_result($rez); - sqlsrv_fetch($rez); - $this->lastInsertID = sqlsrv_get_field($rez, 0); + while ( sqlsrv_next_result($rez) ) { + sqlsrv_fetch($rez); + $this->lastInsertID = sqlsrv_get_field($rez, 0); + } } return $rez; } @@ -837,7 +844,7 @@ class ADORecordset_mssqlnative extends ADORecordSet { var $fieldOffset = 0; // _mths works only in non-localised system - function ADORecordset_mssqlnative($id,$mode=false) + function __construct($id,$mode=false) { if ($mode === false) { global $ADODB_FETCH_MODE; @@ -845,21 +852,21 @@ class ADORecordset_mssqlnative extends ADORecordSet { } $this->fetchMode = $mode; - return $this->ADORecordSet($id,$mode); + return parent::__construct($id,$mode); } function _initrs() { global $ADODB_COUNTRECS; - # KMN # if ($this->connection->debug) error_log("(before) ADODB_COUNTRECS: {$ADODB_COUNTRECS} _numOfRows: {$this->_numOfRows} _numOfFields: {$this->_numOfFields}"); + # KMN # if ($this->connection->debug) ADOConnection::outp("(before) ADODB_COUNTRECS: {$ADODB_COUNTRECS} _numOfRows: {$this->_numOfRows} _numOfFields: {$this->_numOfFields}"); /*$retRowsAff = sqlsrv_rows_affected($this->_queryID);//"If you need to determine the number of rows a query will return before retrieving the actual results, appending a SELECT COUNT ... query would let you get that information, and then a call to next_result would move you to the "real" results." - error_log("rowsaff: ".serialize($retRowsAff)); + ADOConnection::outp("rowsaff: ".serialize($retRowsAff)); $this->_numOfRows = ($ADODB_COUNTRECS)? $retRowsAff:-1;*/ $this->_numOfRows = -1;//not supported $fieldmeta = sqlsrv_field_metadata($this->_queryID); $this->_numOfFields = ($fieldmeta)? count($fieldmeta):-1; - # KMN # if ($this->connection->debug) error_log("(after) _numOfRows: {$this->_numOfRows} _numOfFields: {$this->_numOfFields}"); + # KMN # if ($this->connection->debug) ADOConnection::outp("(after) _numOfRows: {$this->_numOfRows} _numOfFields: {$this->_numOfFields}"); /* * Copy the oracle method and cache the metadata at init time */ @@ -995,16 +1002,16 @@ class ADORecordset_mssqlnative extends ADORecordSet { // speedup function MoveNext() { - //# KMN # if ($this->connection->debug) error_log("movenext()"); - //# KMN # if ($this->connection->debug) error_log("eof (beginning): ".$this->EOF); + //# KMN # if ($this->connection->debug) ADOConnection::outp("movenext()"); + //# KMN # if ($this->connection->debug) ADOConnection::outp("eof (beginning): ".$this->EOF); if ($this->EOF) return false; $this->_currentRow++; - // # KMN # if ($this->connection->debug) error_log("_currentRow: ".$this->_currentRow); + // # KMN # if ($this->connection->debug) ADOConnection::outp("_currentRow: ".$this->_currentRow); if ($this->_fetch()) return true; $this->EOF = true; - //# KMN # if ($this->connection->debug) error_log("eof (end): ".$this->EOF); + //# KMN # if ($this->connection->debug) ADOConnection::outp("eof (end): ".$this->EOF); return false; } @@ -1014,13 +1021,13 @@ class ADORecordset_mssqlnative extends ADORecordSet { // also the date format has been changed from YYYY-mm-dd to dd MMM YYYY in 4.0.4. Idiot! function _fetch($ignore_fields=false) { - # KMN # if ($this->connection->debug) error_log("_fetch()"); + # KMN # if ($this->connection->debug) ADOConnection::outp("_fetch()"); if ($this->fetchMode & ADODB_FETCH_ASSOC) { if ($this->fetchMode & ADODB_FETCH_NUM) { - //# KMN # if ($this->connection->debug) error_log("fetch mode: both"); + //# KMN # if ($this->connection->debug) ADOConnection::outp("fetch mode: both"); $this->fields = @sqlsrv_fetch_array($this->_queryID,SQLSRV_FETCH_BOTH); } else { - //# KMN # if ($this->connection->debug) error_log("fetch mode: assoc"); + //# KMN # if ($this->connection->debug) ADOConnection::outp("fetch mode: assoc"); $this->fields = @sqlsrv_fetch_array($this->_queryID,SQLSRV_FETCH_ASSOC); } @@ -1036,7 +1043,7 @@ class ADORecordset_mssqlnative extends ADORecordSet { } } } else { - //# KMN # if ($this->connection->debug) error_log("fetch mode: num"); + //# KMN # if ($this->connection->debug) ADOConnection::outp("fetch mode: num"); $this->fields = @sqlsrv_fetch_array($this->_queryID,SQLSRV_FETCH_NUMERIC); } if(is_array($this->fields) && array_key_exists(1,$this->fields) && !array_key_exists(0,$this->fields)) {//fix fetch numeric keys since they're not 0 based @@ -1048,7 +1055,7 @@ class ADORecordset_mssqlnative extends ADORecordSet { $arrFixed[$key] = $value; } } - //if($this->connection->debug) error_log("
fixing non 0 based return array, old: ".print_r($this->fields,true)." new: ".print_r($arrFixed,true)); + //if($this->connection->debug) ADOConnection::outp("
fixing non 0 based return array, old: ".print_r($this->fields,true)." new: ".print_r($arrFixed,true)); $this->fields = $arrFixed; } if(is_array($this->fields)) { @@ -1059,7 +1066,7 @@ class ADORecordset_mssqlnative extends ADORecordSet { } } if($this->fields === null) $this->fields = false; - # KMN # if ($this->connection->debug) error_log("
after _fetch, fields:
".print_r($this->fields,true)." backtrace: ".adodb_backtrace(false));
+		# KMN # if ($this->connection->debug) ADOConnection::outp("
after _fetch, fields:
".print_r($this->fields,true)." backtrace: ".adodb_backtrace(false));
 		return $this->fields;
 	}
 
@@ -1086,9 +1093,9 @@ class ADORecordset_mssqlnative extends ADORecordSet {
 
 
 class ADORecordSet_array_mssqlnative extends ADORecordSet_array {
-	function ADORecordSet_array_mssqlnative($id=-1,$mode=false)
+	function __construct($id=-1,$mode=false)
 	{
-		$this->ADORecordSet_array($id,$mode);
+		parent::__construct($id,$mode);
 	}
 
 		// mssql uses a default date like Dec 30 2000 12:00AM
diff --git a/lib/adodb/drivers/adodb-mssqlpo.inc.php b/lib/adodb/drivers/adodb-mssqlpo.inc.php
index ab226a69f64..faf25fc910e 100644
--- a/lib/adodb/drivers/adodb-mssqlpo.inc.php
+++ b/lib/adodb/drivers/adodb-mssqlpo.inc.php
@@ -1,6 +1,8 @@
 _has_mssql_init) {
 			ADOConnection::outp( "PrepareSP: mssql_init only available since PHP 4.1.0");
@@ -54,8 +51,8 @@ class ADODB_mssqlpo extends ADODB_mssql {
 
 class ADORecordset_mssqlpo extends ADORecordset_mssql {
 	var $databaseType = "mssqlpo";
-	function ADORecordset_mssqlpo($id,$mode=false)
+	function __construct($id,$mode=false)
 	{
-		$this->ADORecordset_mssql($id,$mode);
+		parent::__construct($id,$mode);
 	}
 }
diff --git a/lib/adodb/drivers/adodb-mysql.inc.php b/lib/adodb/drivers/adodb-mysql.inc.php
index d82f169059a..4e61b9330b9 100644
--- a/lib/adodb/drivers/adodb-mysql.inc.php
+++ b/lib/adodb/drivers/adodb-mysql.inc.php
@@ -1,12 +1,18 @@
 rsPrefix .= 'ext_';
 	}
 
 
-  // SetCharSet - switch the client encoding
-  function SetCharSet($charset_name)
-  {
-    if (!function_exists('mysql_set_charset'))
-    	return false;
+	// SetCharSet - switch the client encoding
+	function SetCharSet($charset_name)
+	{
+		if (!function_exists('mysql_set_charset')) {
+			return false;
+		}
 
-	if ($this->charSet !== $charset_name) {
-      $ok = @mysql_set_charset($charset_name,$this->_connectionID);
-      if ($ok) {
-		$this->charSet = $charset_name;
-        return true;
-      }
-	  return false;
-    }
-	return true;
-  }
+		if ($this->charSet !== $charset_name) {
+			$ok = @mysql_set_charset($charset_name,$this->_connectionID);
+			if ($ok) {
+				$this->charSet = $charset_name;
+				return true;
+			}
+			return false;
+		}
+		return true;
+	}
 
 	function ServerInfo()
 	{
@@ -80,65 +87,62 @@ class ADODB_mysql extends ADOConnection {
 		return " IFNULL($field, $ifNull) "; // if MySQL
 	}
 
-    function MetaProcedures($NamePattern = false, $catalog  = null, $schemaPattern  = null)
-    {
-        // save old fetch mode
-        global $ADODB_FETCH_MODE;
-
-        $false = false;
-        $save = $ADODB_FETCH_MODE;
-        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-
-        if ($this->fetchMode !== FALSE) {
-               $savem = $this->SetFetchMode(FALSE);
-        }
-
-        $procedures = array ();
-
-        // get index details
+	function MetaProcedures($NamePattern = false, $catalog = null, $schemaPattern = null)
+	{
+		// save old fetch mode
+		global $ADODB_FETCH_MODE;
 
-        $likepattern = '';
-        if ($NamePattern) {
-           $likepattern = " LIKE '".$NamePattern."'";
-        }
-        $rs = $this->Execute('SHOW PROCEDURE STATUS'.$likepattern);
-        if (is_object($rs)) {
+		$false = false;
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
 
-	    // parse index data into array
-	    while ($row = $rs->FetchRow()) {
-		    $procedures[$row[1]] = array(
-				    'type' => 'PROCEDURE',
-				    'catalog' => '',
+		if ($this->fetchMode !== FALSE) {
+			$savem = $this->SetFetchMode(FALSE);
+		}
 
-				    'schema' => '',
-				    'remarks' => $row[7],
-			    );
-	    }
-	}
+		$procedures = array ();
 
-        $rs = $this->Execute('SHOW FUNCTION STATUS'.$likepattern);
-        if (is_object($rs)) {
-            // parse index data into array
-            while ($row = $rs->FetchRow()) {
-                $procedures[$row[1]] = array(
-                        'type' => 'FUNCTION',
-                        'catalog' => '',
-                        'schema' => '',
-                        'remarks' => $row[7]
-                    );
-            }
-	    }
+		// get index details
 
-        // restore fetchmode
-        if (isset($savem)) {
-                $this->SetFetchMode($savem);
+		$likepattern = '';
+		if ($NamePattern) {
+			$likepattern = " LIKE '".$NamePattern."'";
+		}
+		$rs = $this->Execute('SHOW PROCEDURE STATUS'.$likepattern);
+		if (is_object($rs)) {
+
+			// parse index data into array
+			while ($row = $rs->FetchRow()) {
+				$procedures[$row[1]] = array(
+					'type' => 'PROCEDURE',
+					'catalog' => '',
+					'schema' => '',
+					'remarks' => $row[7],
+				);
+			}
+		}
 
-        }
-        $ADODB_FETCH_MODE = $save;
+		$rs = $this->Execute('SHOW FUNCTION STATUS'.$likepattern);
+		if (is_object($rs)) {
+			// parse index data into array
+			while ($row = $rs->FetchRow()) {
+				$procedures[$row[1]] = array(
+					'type' => 'FUNCTION',
+					'catalog' => '',
+					'schema' => '',
+					'remarks' => $row[7]
+				);
+			}
+		}
 
+		// restore fetchmode
+		if (isset($savem)) {
+			$this->SetFetchMode($savem);
+		}
+		$ADODB_FETCH_MODE = $save;
 
-        return $procedures;
-    }
+		return $procedures;
+	}
 
 	/**
 	 * Retrieves a list of tables based on given criteria
@@ -171,54 +175,54 @@ class ADODB_mysql extends ADOConnection {
 
 	function MetaIndexes ($table, $primary = FALSE, $owner=false)
 	{
-        // save old fetch mode
-        global $ADODB_FETCH_MODE;
+		// save old fetch mode
+		global $ADODB_FETCH_MODE;
 
 		$false = false;
-        $save = $ADODB_FETCH_MODE;
-        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-        if ($this->fetchMode !== FALSE) {
-               $savem = $this->SetFetchMode(FALSE);
-        }
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
+		if ($this->fetchMode !== FALSE) {
+			$savem = $this->SetFetchMode(FALSE);
+		}
 
-        // get index details
-        $rs = $this->Execute(sprintf('SHOW INDEX FROM %s',$table));
+		// get index details
+		$rs = $this->Execute(sprintf('SHOW INDEX FROM %s',$table));
 
-        // restore fetchmode
-        if (isset($savem)) {
-                $this->SetFetchMode($savem);
-        }
-        $ADODB_FETCH_MODE = $save;
+		// restore fetchmode
+		if (isset($savem)) {
+			$this->SetFetchMode($savem);
+		}
+		$ADODB_FETCH_MODE = $save;
 
-        if (!is_object($rs)) {
-                return $false;
-        }
+		if (!is_object($rs)) {
+			return $false;
+		}
 
-        $indexes = array ();
+		$indexes = array ();
 
-        // parse index data into array
-        while ($row = $rs->FetchRow()) {
-                if ($primary == FALSE AND $row[2] == 'PRIMARY') {
-                        continue;
-                }
+		// parse index data into array
+		while ($row = $rs->FetchRow()) {
+			if ($primary == FALSE AND $row[2] == 'PRIMARY') {
+				continue;
+			}
 
-                if (!isset($indexes[$row[2]])) {
-                        $indexes[$row[2]] = array(
-                                'unique' => ($row[1] == 0),
-                                'columns' => array()
-                        );
-                }
+			if (!isset($indexes[$row[2]])) {
+				$indexes[$row[2]] = array(
+					'unique' => ($row[1] == 0),
+					'columns' => array()
+				);
+			}
 
-                $indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];
-        }
+			$indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];
+		}
 
-        // sort columns by order in the index
-        foreach ( array_keys ($indexes) as $index )
-        {
-                ksort ($indexes[$index]['columns']);
-        }
+		// sort columns by order in the index
+		foreach ( array_keys ($indexes) as $index )
+		{
+			ksort ($indexes[$index]['columns']);
+		}
 
-        return $indexes;
+		return $indexes;
 	}
 
 
@@ -235,7 +239,7 @@ class ADODB_mysql extends ADOConnection {
 			if ($this->replaceQuote[0] == '\\'){
 				$s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
 			}
-			return  "'".str_replace("'",$this->replaceQuote,$s)."'";
+			return "'".str_replace("'",$this->replaceQuote,$s)."'";
 		}
 
 		// undo magic quotes for "
@@ -275,13 +279,13 @@ class ADODB_mysql extends ADOConnection {
 			return mysql_affected_rows($this->_connectionID);
 	}
 
- 	 // See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html
+	 // See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html
 	// Reference on Last_Insert_ID on the recommended way to simulate sequences
- 	var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
-	var $_genSeqSQL = "create table %s (id int not null)";
+	var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
+	var $_genSeqSQL = "create table if not exists %s (id int not null)";
 	var $_genSeqCountSQL = "select count(*) from %s";
 	var $_genSeq2SQL = "insert into %s values (%s)";
-	var $_dropSeqSQL = "drop table %s";
+	var $_dropSeqSQL = "drop table if exists %s";
 
 	function CreateSequence($seqname='adodbseq',$startID=1)
 	{
@@ -323,7 +327,7 @@ class ADODB_mysql extends ADOConnection {
 		return $this->genID;
 	}
 
-  	function MetaDatabases()
+	function MetaDatabases()
 	{
 		$qid = mysql_list_dbs($this->_connectionID);
 		$arr = array();
@@ -488,7 +492,7 @@ class ADODB_mysql extends ADOConnection {
 		return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
 	}
 
- 	function MetaColumns($table, $normalize=true)
+	function MetaColumns($table, $normalize=true)
 	{
 		$this->_findschema($table,$schema);
 		if ($schema) {
@@ -620,7 +624,7 @@ class ADODB_mysql extends ADOConnection {
 	function ErrorNo()
 	{
 		if ($this->_logsql) return $this->_errorCode;
-		if (empty($this->_connectionID))  return @mysql_errno();
+		if (empty($this->_connectionID)) return @mysql_errno();
 		else return @mysql_errno($this->_connectionID);
 	}
 
@@ -652,48 +656,50 @@ class ADODB_mysql extends ADOConnection {
 
 	// "Innox - Juan Carlos Gonzalez" 
 	function MetaForeignKeys( $table, $owner = FALSE, $upper = FALSE, $associative = FALSE )
-     {
+	{
 	 global $ADODB_FETCH_MODE;
 		if ($ADODB_FETCH_MODE == ADODB_FETCH_ASSOC || $this->fetchMode == ADODB_FETCH_ASSOC) $associative = true;
 
-         if ( !empty($owner) ) {
-            $table = "$owner.$table";
-         }
-         $a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table));
-		 if ($associative) {
-		 	$create_sql = isset($a_create_table["Create Table"]) ? $a_create_table["Create Table"] : $a_create_table["Create View"];
-         } else $create_sql  = $a_create_table[1];
+		if ( !empty($owner) ) {
+			$table = "$owner.$table";
+		}
+		$a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table));
+		if ($associative) {
+			$create_sql = isset($a_create_table["Create Table"]) ? $a_create_table["Create Table"] : $a_create_table["Create View"];
+		} else {
+			$create_sql = $a_create_table[1];
+		}
 
-         $matches = array();
+		$matches = array();
 
-         if (!preg_match_all("/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/", $create_sql, $matches)) return false;
-	     $foreign_keys = array();
-         $num_keys = count($matches[0]);
-         for ( $i = 0;  $i < $num_keys;  $i ++ ) {
-             $my_field  = explode('`, `', $matches[1][$i]);
-             $ref_table = $matches[2][$i];
-             $ref_field = explode('`, `', $matches[3][$i]);
+		if (!preg_match_all("/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/", $create_sql, $matches)) return false;
+		$foreign_keys = array();
+		$num_keys = count($matches[0]);
+		for ( $i = 0; $i < $num_keys; $i ++ ) {
+			$my_field  = explode('`, `', $matches[1][$i]);
+			$ref_table = $matches[2][$i];
+			$ref_field = explode('`, `', $matches[3][$i]);
 
-             if ( $upper ) {
-                 $ref_table = strtoupper($ref_table);
-             }
+			if ( $upper ) {
+				$ref_table = strtoupper($ref_table);
+			}
 
 			// see https://sourceforge.net/tracker/index.php?func=detail&aid=2287278&group_id=42718&atid=433976
 			if (!isset($foreign_keys[$ref_table])) {
 				$foreign_keys[$ref_table] = array();
 			}
-            $num_fields = count($my_field);
-            for ( $j = 0;  $j < $num_fields;  $j ++ ) {
-                 if ( $associative ) {
-                     $foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j];
-                 } else {
-                     $foreign_keys[$ref_table][] = "{$my_field[$j]}={$ref_field[$j]}";
-                 }
-             }
-         }
+			$num_fields = count($my_field);
+			for ( $j = 0; $j < $num_fields; $j ++ ) {
+				if ( $associative ) {
+					$foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j];
+				} else {
+					$foreign_keys[$ref_table][] = "{$my_field[$j]}={$ref_field[$j]}";
+				}
+			}
+		}
 
-         return  $foreign_keys;
-     }
+		return $foreign_keys;
+	}
 
 
 }
@@ -708,7 +714,7 @@ class ADORecordSet_mysql extends ADORecordSet{
 	var $databaseType = "mysql";
 	var $canSeek = true;
 
-	function ADORecordSet_mysql($queryID,$mode=false)
+	function __construct($queryID,$mode=false)
 	{
 		if ($mode === false) {
 			global $ADODB_FETCH_MODE;
@@ -724,7 +730,7 @@ class ADORecordSet_mysql extends ADORecordSet{
 			$this->fetchMode = MYSQL_BOTH; break;
 		}
 		$this->adodbFetchMode = $mode;
-		$this->ADORecordSet($queryID);
+		parent::__construct($queryID);
 	}
 
 	function _initrs()
@@ -744,7 +750,7 @@ class ADORecordSet_mysql extends ADORecordSet{
 			//$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
 			if ($o) $o->binary = (strpos($f,'binary')!== false);
 		}
-		else  {	/*	The $fieldOffset argument is not provided thus its -1 	*/
+		else {	/*	The $fieldOffset argument is not provided thus its -1 	*/
 			$o = @mysql_fetch_field($this->_queryID);
 			//if ($o) $o->max_length = @mysql_field_len($this->_queryID); // suggested by: Jim Nicholson (jnich#att.com)
 			$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable
@@ -753,10 +759,14 @@ class ADORecordSet_mysql extends ADORecordSet{
 		return $o;
 	}
 
-	function GetRowAssoc($upper=true)
+	function GetRowAssoc($upper = ADODB_ASSOC_CASE)
 	{
-		if ($this->fetchMode == MYSQL_ASSOC && !$upper) $row = $this->fields;
-		else $row = ADORecordSet::GetRowAssoc($upper);
+		if ($this->fetchMode == MYSQL_ASSOC && $upper == ADODB_ASSOC_CASE_LOWER) {
+			$row = $this->fields;
+		}
+		else {
+			$row = ADORecordSet::GetRowAssoc($upper);
+		}
 		return $row;
 	}
 
@@ -799,7 +809,8 @@ class ADORecordSet_mysql extends ADORecordSet{
 
 	function _fetch()
 	{
-		$this->fields =  @mysql_fetch_array($this->_queryID,$this->fetchMode);
+		$this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode);
+		$this->_updatefields();
 		return is_array($this->fields);
 	}
 
@@ -865,23 +876,9 @@ class ADORecordSet_mysql extends ADORecordSet{
 }
 
 class ADORecordSet_ext_mysql extends ADORecordSet_mysql {
-	function ADORecordSet_ext_mysql($queryID,$mode=false)
+	function __construct($queryID,$mode=false)
 	{
-		if ($mode === false) {
-			global $ADODB_FETCH_MODE;
-			$mode = $ADODB_FETCH_MODE;
-		}
-		switch ($mode)
-		{
-		case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break;
-		case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break;
-		case ADODB_FETCH_DEFAULT:
-		case ADODB_FETCH_BOTH:
-		default:
-		$this->fetchMode = MYSQL_BOTH; break;
-		}
-		$this->adodbFetchMode = $mode;
-		$this->ADORecordSet($queryID);
+		parent::__construct($queryID,$mode);
 	}
 
 	function MoveNext()
@@ -890,5 +887,4 @@ class ADORecordSet_ext_mysql extends ADORecordSet_mysql {
 	}
 }
 
-
 }
diff --git a/lib/adodb/drivers/adodb-mysqli.inc.php b/lib/adodb/drivers/adodb-mysqli.inc.php
index 6de3e7f80db..f14e2575b4d 100644
--- a/lib/adodb/drivers/adodb-mysqli.inc.php
+++ b/lib/adodb/drivers/adodb-mysqli.inc.php
@@ -1,12 +1,18 @@
 _transmode  = $transaction_mode;
+		$this->_transmode = $transaction_mode;
 		if (empty($transaction_mode)) {
 			$this->Execute('SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ');
 			return;
@@ -79,21 +84,22 @@ class ADODB_mysqli extends ADOConnection {
 	// To add: parameter int $port,
 	//         parameter string $socket
 	function _connect($argHostname = NULL,
-			  $argUsername = NULL,
-			  $argPassword = NULL,
-			  $argDatabasename = NULL, $persist=false)
-	  {
-	  	 if(!extension_loaded("mysqli")) {
+				$argUsername = NULL,
+				$argPassword = NULL,
+				$argDatabasename = NULL, $persist=false)
+	{
+		if(!extension_loaded("mysqli")) {
 			return null;
-		 }
-	    $this->_connectionID = @mysqli_init();
+		}
+		$this->_connectionID = @mysqli_init();
 
-	    if (is_null($this->_connectionID)) {
-	      // mysqli_init only fails if insufficient memory
-	      if ($this->debug)
+		if (is_null($this->_connectionID)) {
+			// mysqli_init only fails if insufficient memory
+			if ($this->debug) {
 				ADOConnection::outp("mysqli_init() failed : "  . $this->ErrorMsg());
-	      return false;
-	    }
+			}
+			return false;
+		}
 		/*
 		I suggest a simple fix which would enable adodb and mysqli driver to
 		read connection options from the standard mysql configuration file
@@ -108,23 +114,24 @@ class ADODB_mysqli extends ADOConnection {
 
 		#if (!empty($this->port)) $argHostname .= ":".$this->port;
 		$ok = mysqli_real_connect($this->_connectionID,
- 				    $argHostname,
- 				    $argUsername,
- 				    $argPassword,
- 				    $argDatabasename,
+					$argHostname,
+					$argUsername,
+					$argPassword,
+					$argDatabasename,
 					$this->port,
 					$this->socket,
 					$this->clientFlags);
 
 		if ($ok) {
-	 		if ($argDatabasename)  return $this->SelectDB($argDatabasename);
- 			return true;
- 	   } else {
-			if ($this->debug)
-		  		ADOConnection::outp("Could't connect : "  . $this->ErrorMsg());
+			if ($argDatabasename)  return $this->SelectDB($argDatabasename);
+			return true;
+		} else {
+			if ($this->debug) {
+				ADOConnection::outp("Could't connect : "  . $this->ErrorMsg());
+			}
 			$this->_connectionID = null;
 			return false;
-	   }
+		}
 	}
 
 	// returns true or false
@@ -132,16 +139,15 @@ class ADODB_mysqli extends ADOConnection {
 	function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
 	{
 		return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename, true);
-
 	}
 
 	// When is this used? Close old connection first?
 	// In _connect(), check $this->forceNewConnect?
 	function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename)
-	  {
-	    $this->forceNewConnect = true;
-	    return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
-	  }
+	{
+		$this->forceNewConnect = true;
+		return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename);
+	}
 
 	function IfNull( $field, $ifNull )
 	{
@@ -151,7 +157,7 @@ class ADODB_mysqli extends ADOConnection {
 	// do not use $ADODB_COUNTRECS
 	function GetOne($sql,$inputarr=false)
 	{
-	global $ADODB_GETONE_EOF;
+		global $ADODB_GETONE_EOF;
 
 		$ret = false;
 		$rs = $this->Execute($sql,$inputarr);
@@ -213,58 +219,64 @@ class ADODB_mysqli extends ADOConnection {
 		return !empty($rs);
 	}
 
-	// if magic quotes disabled, use mysql_real_escape_string()
-	// From docs-adodb.htm:
-	// Quotes a string to be sent to the database. The $magic_quotes_enabled
-	// parameter may look funny, but the idea is if you are quoting a
-	// string extracted from a POST/GET variable, then
-	// pass get_magic_quotes_gpc() as the second parameter. This will
-	// ensure that the variable is not quoted twice, once by qstr and once
-	// by the magic_quotes_gpc.
-	//
-	//Eg. $s = $db->qstr(_GET['name'],get_magic_quotes_gpc());
+	/**
+	 * Quotes a string to be sent to the database
+	 * When there is no active connection,
+	 * @param string $s The string to quote
+	 * @param boolean $magic_quotes If false, use mysqli_real_escape_string()
+	 *     if you are quoting a string extracted from a POST/GET variable,
+	 *     then pass get_magic_quotes_gpc() as the second parameter. This will
+	 *     ensure that the variable is not quoted twice, once by qstr() and
+	 *     once by the magic_quotes_gpc.
+	 *     Eg. $s = $db->qstr(_GET['name'],get_magic_quotes_gpc());
+	 * @return string Quoted string
+	 */
 	function qstr($s, $magic_quotes = false)
 	{
 		if (is_null($s)) return 'NULL';
 		if (!$magic_quotes) {
-	    	if (PHP_VERSION >= 5)
-	      		return "'" . mysqli_real_escape_string($this->_connectionID, $s) . "'";
-
-		if ($this->replaceQuote[0] == '\\')
-			$s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
-	    return  "'".str_replace("'",$this->replaceQuote,$s)."'";
-	  }
-	  // undo magic quotes for "
-	  $s = str_replace('\\"','"',$s);
-	  return "'$s'";
+			// mysqli_real_escape_string() throws a warning when the given
+			// connection is invalid
+			if (PHP_VERSION >= 5 && $this->_connectionID) {
+				return "'" . mysqli_real_escape_string($this->_connectionID, $s) . "'";
+			}
+
+			if ($this->replaceQuote[0] == '\\') {
+				$s = adodb_str_replace(array('\\',"\0"), array('\\\\',"\\\0") ,$s);
+			}
+			return "'" . str_replace("'", $this->replaceQuote, $s) . "'";
+		}
+		// undo magic quotes for "
+		$s = str_replace('\\"','"',$s);
+		return "'$s'";
 	}
 
 	function _insertid()
 	{
-	  $result = @mysqli_insert_id($this->_connectionID);
-	  if ($result == -1){
-	      if ($this->debug) ADOConnection::outp("mysqli_insert_id() failed : "  . $this->ErrorMsg());
-	  }
-	  return $result;
+		$result = @mysqli_insert_id($this->_connectionID);
+		if ($result == -1) {
+			if ($this->debug) ADOConnection::outp("mysqli_insert_id() failed : "  . $this->ErrorMsg());
+		}
+		return $result;
 	}
 
 	// Only works for INSERT, UPDATE and DELETE query's
 	function _affectedrows()
 	{
-	  $result =  @mysqli_affected_rows($this->_connectionID);
-	  if ($result == -1) {
-	      if ($this->debug) ADOConnection::outp("mysqli_affected_rows() failed : "  . $this->ErrorMsg());
-	  }
-	  return $result;
+		$result =  @mysqli_affected_rows($this->_connectionID);
+		if ($result == -1) {
+			if ($this->debug) ADOConnection::outp("mysqli_affected_rows() failed : "  . $this->ErrorMsg());
+		}
+		return $result;
 	}
 
- 	// See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html
+	// See http://www.mysql.com/doc/M/i/Miscellaneous_functions.html
 	// Reference on Last_Insert_ID on the recommended way to simulate sequences
- 	var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
-	var $_genSeqSQL = "create table %s (id int not null)";
+	var $_genIDSQL = "update %s set id=LAST_INSERT_ID(id+1);";
+	var $_genSeqSQL = "create table if not exists %s (id int not null)";
 	var $_genSeqCountSQL = "select count(*) from %s";
 	var $_genSeq2SQL = "insert into %s values (%s)";
-	var $_dropSeqSQL = "drop table %s";
+	var $_dropSeqSQL = "drop table if exists %s";
 
 	function CreateSequence($seqname='adodbseq',$startID=1)
 	{
@@ -302,20 +314,20 @@ class ADODB_mysqli extends ADOConnection {
 		return $this->genID;
 	}
 
-  	function MetaDatabases()
+	function MetaDatabases()
 	{
 		$query = "SHOW DATABASES";
 		$ret = $this->Execute($query);
 		if ($ret && is_object($ret)){
-		   $arr = array();
+			$arr = array();
 			while (!$ret->EOF){
 				$db = $ret->Fields('Database');
 				if ($db != 'mysql') $arr[] = $db;
 				$ret->MoveNext();
 			}
-   		   return $arr;
+			return $arr;
 		}
-        return $ret;
+		return $ret;
 	}
 
 
@@ -328,7 +340,7 @@ class ADODB_mysqli extends ADOConnection {
 		$save = $ADODB_FETCH_MODE;
 		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
 		if ($this->fetchMode !== FALSE) {
-		       $savem = $this->SetFetchMode(FALSE);
+			$savem = $this->SetFetchMode(FALSE);
 		}
 
 		// get index details
@@ -336,36 +348,36 @@ class ADODB_mysqli extends ADOConnection {
 
 		// restore fetchmode
 		if (isset($savem)) {
-		        $this->SetFetchMode($savem);
+			$this->SetFetchMode($savem);
 		}
 		$ADODB_FETCH_MODE = $save;
 
 		if (!is_object($rs)) {
-		        return $false;
+			return $false;
 		}
 
 		$indexes = array ();
 
 		// parse index data into array
 		while ($row = $rs->FetchRow()) {
-		        if ($primary == FALSE AND $row[2] == 'PRIMARY') {
-		                continue;
-		        }
-
-		        if (!isset($indexes[$row[2]])) {
-		                $indexes[$row[2]] = array(
-		                        'unique' => ($row[1] == 0),
-		                        'columns' => array()
-		                );
-		        }
-
-		        $indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];
+			if ($primary == FALSE AND $row[2] == 'PRIMARY') {
+				continue;
+			}
+
+			if (!isset($indexes[$row[2]])) {
+				$indexes[$row[2]] = array(
+					'unique' => ($row[1] == 0),
+					'columns' => array()
+				);
+			}
+
+			$indexes[$row[2]]['columns'][$row[3] - 1] = $row[4];
 		}
 
 		// sort columns by order in the index
 		foreach ( array_keys ($indexes) as $index )
 		{
-		        ksort ($indexes[$index]['columns']);
+			ksort ($indexes[$index]['columns']);
 		}
 
 		return $indexes;
@@ -474,65 +486,62 @@ class ADODB_mysqli extends ADOConnection {
 //		return "from_unixtime(unix_timestamp($date)+$fraction)";
 	}
 
-    function MetaProcedures($NamePattern = false, $catalog  = null, $schemaPattern  = null)
-    {
-        // save old fetch mode
-        global $ADODB_FETCH_MODE;
-
-        $false = false;
-        $save = $ADODB_FETCH_MODE;
-        $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
-
-        if ($this->fetchMode !== FALSE) {
-               $savem = $this->SetFetchMode(FALSE);
-        }
-
-        $procedures = array ();
-
-        // get index details
+	function MetaProcedures($NamePattern = false, $catalog  = null, $schemaPattern  = null)
+	{
+		// save old fetch mode
+		global $ADODB_FETCH_MODE;
 
-        $likepattern = '';
-        if ($NamePattern) {
-           $likepattern = " LIKE '".$NamePattern."'";
-        }
-        $rs = $this->Execute('SHOW PROCEDURE STATUS'.$likepattern);
-        if (is_object($rs)) {
+		$false = false;
+		$save = $ADODB_FETCH_MODE;
+		$ADODB_FETCH_MODE = ADODB_FETCH_NUM;
 
-	    // parse index data into array
-	    while ($row = $rs->FetchRow()) {
-		    $procedures[$row[1]] = array(
-				    'type' => 'PROCEDURE',
-				    'catalog' => '',
+		if ($this->fetchMode !== FALSE) {
+			$savem = $this->SetFetchMode(FALSE);
+		}
 
-				    'schema' => '',
-				    'remarks' => $row[7],
-			    );
-	    }
-	}
+		$procedures = array ();
 
-        $rs = $this->Execute('SHOW FUNCTION STATUS'.$likepattern);
-        if (is_object($rs)) {
-            // parse index data into array
-            while ($row = $rs->FetchRow()) {
-                $procedures[$row[1]] = array(
-                        'type' => 'FUNCTION',
-                        'catalog' => '',
-                        'schema' => '',
-                        'remarks' => $row[7]
-                    );
-            }
-	    }
+		// get index details
 
-        // restore fetchmode
-        if (isset($savem)) {
-                $this->SetFetchMode($savem);
+		$likepattern = '';
+		if ($NamePattern) {
+			$likepattern = " LIKE '".$NamePattern."'";
+		}
+		$rs = $this->Execute('SHOW PROCEDURE STATUS'.$likepattern);
+		if (is_object($rs)) {
+
+			// parse index data into array
+			while ($row = $rs->FetchRow()) {
+				$procedures[$row[1]] = array(
+					'type' => 'PROCEDURE',
+					'catalog' => '',
+					'schema' => '',
+					'remarks' => $row[7],
+				);
+			}
+		}
 
-        }
-        $ADODB_FETCH_MODE = $save;
+		$rs = $this->Execute('SHOW FUNCTION STATUS'.$likepattern);
+		if (is_object($rs)) {
+			// parse index data into array
+			while ($row = $rs->FetchRow()) {
+				$procedures[$row[1]] = array(
+					'type' => 'FUNCTION',
+					'catalog' => '',
+					'schema' => '',
+					'remarks' => $row[7]
+				);
+			}
+		}
 
+		// restore fetchmode
+		if (isset($savem)) {
+				$this->SetFetchMode($savem);
+		}
+		$ADODB_FETCH_MODE = $save;
 
-        return $procedures;
-    }
+		return $procedures;
+	}
 
 	/**
 	 * Retrieves a list of tables based on given criteria
@@ -569,46 +578,46 @@ class ADODB_mysqli extends ADOConnection {
 
 		if ($ADODB_FETCH_MODE == ADODB_FETCH_ASSOC || $this->fetchMode == ADODB_FETCH_ASSOC) $associative = true;
 
-	    if ( !empty($owner) ) {
-	       $table = "$owner.$table";
-	    }
-	    $a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table));
+		if ( !empty($owner) ) {
+			$table = "$owner.$table";
+		}
+		$a_create_table = $this->getRow(sprintf('SHOW CREATE TABLE %s', $table));
 		if ($associative) {
 			$create_sql = isset($a_create_table["Create Table"]) ? $a_create_table["Create Table"] : $a_create_table["Create View"];
-	    } else $create_sql  = $a_create_table[1];
+		} else $create_sql = $a_create_table[1];
 
-	    $matches = array();
+		$matches = array();
 
-	    if (!preg_match_all("/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/", $create_sql, $matches)) return false;
-	 	$foreign_keys = array();
-	    $num_keys = count($matches[0]);
-	    for ( $i = 0;  $i < $num_keys;  $i ++ ) {
-	        $my_field  = explode('`, `', $matches[1][$i]);
-	        $ref_table = $matches[2][$i];
-	        $ref_field = explode('`, `', $matches[3][$i]);
+		if (!preg_match_all("/FOREIGN KEY \(`(.*?)`\) REFERENCES `(.*?)` \(`(.*?)`\)/", $create_sql, $matches)) return false;
+		$foreign_keys = array();
+		$num_keys = count($matches[0]);
+		for ( $i = 0; $i < $num_keys; $i ++ ) {
+			$my_field  = explode('`, `', $matches[1][$i]);
+			$ref_table = $matches[2][$i];
+			$ref_field = explode('`, `', $matches[3][$i]);
 
-	        if ( $upper ) {
-	            $ref_table = strtoupper($ref_table);
-	        }
+			if ( $upper ) {
+				$ref_table = strtoupper($ref_table);
+			}
 
-	        // see https://sourceforge.net/tracker/index.php?func=detail&aid=2287278&group_id=42718&atid=433976
+			// see https://sourceforge.net/tracker/index.php?func=detail&aid=2287278&group_id=42718&atid=433976
 			if (!isset($foreign_keys[$ref_table])) {
 				$foreign_keys[$ref_table] = array();
 			}
-	        $num_fields = count($my_field);
-	        for ( $j = 0;  $j < $num_fields;  $j ++ ) {
-	            if ( $associative ) {
-	                $foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j];
-	            } else {
-	                $foreign_keys[$ref_table][] = "{$my_field[$j]}={$ref_field[$j]}";
-	            }
-	        }
-	    }
-
-	    return  $foreign_keys;
+			$num_fields = count($my_field);
+			for ( $j = 0; $j < $num_fields; $j ++ ) {
+				if ( $associative ) {
+					$foreign_keys[$ref_table][$ref_field[$j]] = $my_field[$j];
+				} else {
+					$foreign_keys[$ref_table][] = "{$my_field[$j]}={$ref_field[$j]}";
+				}
+			}
+		}
+
+		return $foreign_keys;
 	}
 
- 	function MetaColumns($table, $normalize=true)
+	function MetaColumns($table, $normalize=true)
 	{
 		$false = false;
 		if (!$this->metaColumnsSQL)
@@ -682,26 +691,26 @@ class ADODB_mysqli extends ADOConnection {
 	// returns true or false
 	function SelectDB($dbName)
 	{
-//	    $this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);
-	    $this->database = $dbName;
+//		$this->_connectionID = $this->mysqli_resolve_link($this->_connectionID);
+		$this->database = $dbName;
 		$this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions
 
-	    if ($this->_connectionID) {
-        	$result = @mysqli_select_db($this->_connectionID, $dbName);
+		if ($this->_connectionID) {
+			$result = @mysqli_select_db($this->_connectionID, $dbName);
 			if (!$result) {
-		    	ADOConnection::outp("Select of database " . $dbName . " failed. " . $this->ErrorMsg());
+				ADOConnection::outp("Select of database " . $dbName . " failed. " . $this->ErrorMsg());
 			}
 			return $result;
 		}
-	    return false;
+		return false;
 	}
 
 	// parameters use PostgreSQL convention, not MySQL
 	function SelectLimit($sql,
-			      $nrows = -1,
-			      $offset = -1,
-			      $inputarr = false,
-			      $secs = 0)
+				$nrows = -1,
+				$offset = -1,
+				$inputarr = false,
+				$secs = 0)
 	{
 		$offsetStr = ($offset >= 0) ? "$offset," : '';
 		if ($nrows < 0) $nrows = '18446744073709551615';
@@ -759,8 +768,8 @@ class ADODB_mysqli extends ADOConnection {
 
 		/*
 		if (!$mysql_res =  mysqli_query($this->_connectionID, $sql, ($ADODB_COUNTRECS) ? MYSQLI_STORE_RESULT : MYSQLI_USE_RESULT)) {
-		    if ($this->debug) ADOConnection::outp("Query: " . $sql . " failed. " . $this->ErrorMsg());
-		    return false;
+			if ($this->debug) ADOConnection::outp("Query: " . $sql . " failed. " . $this->ErrorMsg());
+			return false;
 		}
 
 		return $mysql_res;
@@ -787,29 +796,29 @@ class ADODB_mysqli extends ADOConnection {
 
 	/*	Returns: the last error message from previous database operation	*/
 	function ErrorMsg()
-	  {
-	    if (empty($this->_connectionID))
-	      $this->_errorMsg = @mysqli_connect_error();
-	    else
-	      $this->_errorMsg = @mysqli_error($this->_connectionID);
-	    return $this->_errorMsg;
-	  }
+	{
+		if (empty($this->_connectionID))
+			$this->_errorMsg = @mysqli_connect_error();
+		else
+			$this->_errorMsg = @mysqli_error($this->_connectionID);
+		return $this->_errorMsg;
+	}
 
 	/*	Returns: the last error number from previous database operation	*/
 	function ErrorNo()
-	  {
-	    if (empty($this->_connectionID))
-	      return @mysqli_connect_errno();
-	    else
-	      return @mysqli_errno($this->_connectionID);
-	  }
+	{
+		if (empty($this->_connectionID))
+			return @mysqli_connect_errno();
+		else
+			return @mysqli_errno($this->_connectionID);
+	}
 
 	// returns true or false
 	function _close()
-	  {
-	    @mysqli_close($this->_connectionID);
-	    $this->_connectionID = false;
-	  }
+	{
+		@mysqli_close($this->_connectionID);
+		$this->_connectionID = false;
+	}
 
 	/*
 	* Maximum size of C field
@@ -824,11 +833,10 @@ class ADODB_mysqli extends ADOConnection {
 	*/
 	function TextMax()
 	{
-	  return 4294967295;
+		return 4294967295;
 	}
 
 
-
 	// this is a set of functions for managing client encoding - very important if the encodings
 	// of your database and your output target (i.e. HTML) don't match
 	// for instance, you may have UTF8 database and server it on-site as latin1 etc.
@@ -836,36 +844,34 @@ class ADODB_mysqli extends ADOConnection {
 	// Under Windows, the functions should work with MySQL 4.1.11 and above, the set of charsets supported
 	// depends on compile flags of mysql distribution
 
-  function GetCharSet()
-  {
-    //we will use ADO's builtin property charSet
-    if (!method_exists($this->_connectionID,'character_set_name'))
-    	return false;
-
-    $this->charSet = @$this->_connectionID->character_set_name();
-    if (!$this->charSet) {
-      return false;
-    } else {
-      return $this->charSet;
-    }
-  }
-
-  // SetCharSet - switch the client encoding
-  function SetCharSet($charset_name)
-  {
-    if (!method_exists($this->_connectionID,'set_charset'))
-    	return false;
-
-    if ($this->charSet !== $charset_name) {
-      $if = @$this->_connectionID->set_charset($charset_name);
-      if ($if === true & $this->GetCharSet() == $charset_name) {
-        return true;
-      } else return false;
-    } else return true;
-  }
+	function GetCharSet()
+	{
+		//we will use ADO's builtin property charSet
+		if (!method_exists($this->_connectionID,'character_set_name'))
+			return false;
 
+		$this->charSet = @$this->_connectionID->character_set_name();
+		if (!$this->charSet) {
+			return false;
+		} else {
+			return $this->charSet;
+		}
+	}
 
+	// SetCharSet - switch the client encoding
+	function SetCharSet($charset_name)
+	{
+		if (!method_exists($this->_connectionID,'set_charset')) {
+			return false;
+		}
 
+		if ($this->charSet !== $charset_name) {
+			$if = @$this->_connectionID->set_charset($charset_name);
+			return ($if === true & $this->GetCharSet() == $charset_name);
+		} else {
+			return true;
+		}
+	}
 
 }
 
@@ -878,30 +884,28 @@ class ADORecordSet_mysqli extends ADORecordSet{
 	var $databaseType = "mysqli";
 	var $canSeek = true;
 
-	function ADORecordSet_mysqli($queryID, $mode = false)
+	function __construct($queryID, $mode = false)
 	{
-	  if ($mode === false)
-	   {
-	      global $ADODB_FETCH_MODE;
-	      $mode = $ADODB_FETCH_MODE;
-	   }
-
-	  switch ($mode)
-	    {
-	    case ADODB_FETCH_NUM:
-	      $this->fetchMode = MYSQLI_NUM;
-	      break;
-	    case ADODB_FETCH_ASSOC:
-	      $this->fetchMode = MYSQLI_ASSOC;
-	      break;
-	    case ADODB_FETCH_DEFAULT:
-	    case ADODB_FETCH_BOTH:
-	    default:
-	      $this->fetchMode = MYSQLI_BOTH;
-	      break;
-	    }
-	  $this->adodbFetchMode = $mode;
-	  $this->ADORecordSet($queryID);
+		if ($mode === false) {
+			global $ADODB_FETCH_MODE;
+			$mode = $ADODB_FETCH_MODE;
+		}
+
+		switch ($mode) {
+			case ADODB_FETCH_NUM:
+				$this->fetchMode = MYSQLI_NUM;
+				break;
+			case ADODB_FETCH_ASSOC:
+				$this->fetchMode = MYSQLI_ASSOC;
+				break;
+			case ADODB_FETCH_DEFAULT:
+			case ADODB_FETCH_BOTH:
+			default:
+				$this->fetchMode = MYSQLI_BOTH;
+				break;
+		}
+		$this->adodbFetchMode = $mode;
+		parent::__construct($queryID);
 	}
 
 	function _initrs()
@@ -936,10 +940,15 @@ class ADORecordSet_mysqli extends ADORecordSet{
 	{
 		$fieldnr = $fieldOffset;
 		if ($fieldOffset != -1) {
-		  $fieldOffset = @mysqli_field_seek($this->_queryID, $fieldnr);
+			$fieldOffset = @mysqli_field_seek($this->_queryID, $fieldnr);
 		}
 		$o = @mysqli_fetch_field($this->_queryID);
 		if (!$o) return false;
+
+		//Fix for HHVM
+		if ( !isset($o->flags) ) {
+			$o->flags = 0;
+		}
 		/* Properties of an ADOFieldObject as set by MetaColumns */
 		$o->primary_key = $o->flags & MYSQLI_PRI_KEY_FLAG;
 		$o->not_null = $o->flags & MYSQLI_NOT_NULL_FLAG;
@@ -951,10 +960,11 @@ class ADORecordSet_mysqli extends ADORecordSet{
 		return $o;
 	}
 
-	function GetRowAssoc($upper = true)
+	function GetRowAssoc($upper = ADODB_ASSOC_CASE)
 	{
-		if ($this->fetchMode == MYSQLI_ASSOC && !$upper)
-		  return $this->fields;
+		if ($this->fetchMode == MYSQLI_ASSOC && $upper == ADODB_ASSOC_CASE_LOWER) {
+			return $this->fields;
+		}
 		$row = ADORecordSet::GetRowAssoc($upper);
 		return $row;
 	}
@@ -962,30 +972,29 @@ class ADORecordSet_mysqli extends ADORecordSet{
 	/* Use associative array to get fields array */
 	function Fields($colname)
 	{
-	  if ($this->fetchMode != MYSQLI_NUM)
-	    return @$this->fields[$colname];
-
-	  if (!$this->bind) {
-	    $this->bind = array();
-	    for ($i = 0; $i < $this->_numOfFields; $i++) {
-	      $o = $this->FetchField($i);
-	      $this->bind[strtoupper($o->name)] = $i;
-	    }
-	  }
-	  return $this->fields[$this->bind[strtoupper($colname)]];
+		if ($this->fetchMode != MYSQLI_NUM) {
+			return @$this->fields[$colname];
+		}
+
+		if (!$this->bind) {
+			$this->bind = array();
+			for ($i = 0; $i < $this->_numOfFields; $i++) {
+				$o = $this->FetchField($i);
+				$this->bind[strtoupper($o->name)] = $i;
+			}
+		}
+		return $this->fields[$this->bind[strtoupper($colname)]];
 	}
 
 	function _seek($row)
 	{
-	  if ($this->_numOfRows == 0)
-	    return false;
-
-	  if ($row < 0)
-	    return false;
+		if ($this->_numOfRows == 0 || $row < 0) {
+			return false;
+		}
 
-	  mysqli_data_seek($this->_queryID, $row);
-	  $this->EOF = false;
-	  return true;
+		mysqli_data_seek($this->_queryID, $row);
+		$this->EOF = false;
+		return true;
 	}
 
 
@@ -1032,20 +1041,21 @@ class ADORecordSet_mysqli extends ADORecordSet{
 	function _fetch()
 	{
 		$this->fields = mysqli_fetch_array($this->_queryID,$this->fetchMode);
-	  	return is_array($this->fields);
+		$this->_updatefields();
+		return is_array($this->fields);
 	}
 
 	function _close()
 	{
-	    //if results are attached to this pointer from Stored Proceedure calls, the next standard query will die 2014
-        //only a problem with persistant connections
+		//if results are attached to this pointer from Stored Proceedure calls, the next standard query will die 2014
+		//only a problem with persistant connections
 
-        while(mysqli_more_results($this->connection->_connectionID)){
-           @mysqli_next_result($this->connection->_connectionID);
-        }
+		while(mysqli_more_results($this->connection->_connectionID)){
+			@mysqli_next_result($this->connection->_connectionID);
+		}
 
-		mysqli_free_result($this->_queryID);
-	  	$this->_queryID = false;
+		@mysqli_free_result($this->_queryID);
+		$this->_queryID = false;
 	}
 
 /*
@@ -1080,21 +1090,21 @@ class ADORecordSet_mysqli extends ADORecordSet{
 	function MetaType($t, $len = -1, $fieldobj = false)
 	{
 		if (is_object($t)) {
-		    $fieldobj = $t;
-		    $t = $fieldobj->type;
-		    $len = $fieldobj->max_length;
+			$fieldobj = $t;
+			$t = $fieldobj->type;
+			$len = $fieldobj->max_length;
 		}
 
 
-		 $len = -1; // mysql max_length is not accurate
-		 switch (strtoupper($t)) {
-		 case 'STRING':
-		 case 'CHAR':
-		 case 'VARCHAR':
-		 case 'TINYBLOB':
-		 case 'TINYTEXT':
-		 case 'ENUM':
-		 case 'SET':
+		$len = -1; // mysql max_length is not accurate
+		switch (strtoupper($t)) {
+		case 'STRING':
+		case 'CHAR':
+		case 'VARCHAR':
+		case 'TINYBLOB':
+		case 'TINYTEXT':
+		case 'ENUM':
+		case 'SET':
 
 		case MYSQLI_TYPE_TINY_BLOB :
 		#case MYSQLI_TYPE_CHAR :
@@ -1102,16 +1112,15 @@ class ADORecordSet_mysqli extends ADORecordSet{
 		case MYSQLI_TYPE_ENUM :
 		case MYSQLI_TYPE_SET :
 		case 253 :
-		   if ($len <= $this->blobSize) return 'C';
+			if ($len <= $this->blobSize) return 'C';
 
 		case 'TEXT':
 		case 'LONGTEXT':
 		case 'MEDIUMTEXT':
-		   return 'X';
+			return 'X';
 
-
-		   // php_mysql extension always returns 'blob' even if 'text'
-		   // so we have to check whether binary...
+		// php_mysql extension always returns 'blob' even if 'text'
+		// so we have to check whether binary...
 		case 'IMAGE':
 		case 'LONGBLOB':
 		case 'BLOB':
@@ -1120,14 +1129,13 @@ class ADORecordSet_mysqli extends ADORecordSet{
 		case MYSQLI_TYPE_BLOB :
 		case MYSQLI_TYPE_LONG_BLOB :
 		case MYSQLI_TYPE_MEDIUM_BLOB :
+			return !empty($fieldobj->binary) ? 'B' : 'X';
 
-		   return !empty($fieldobj->binary) ? 'B' : 'X';
 		case 'YEAR':
 		case 'DATE':
 		case MYSQLI_TYPE_DATE :
 		case MYSQLI_TYPE_YEAR :
-
-		   return 'D';
+			return 'D';
 
 		case 'TIME':
 		case 'DATETIME':
@@ -1137,7 +1145,6 @@ class ADORecordSet_mysqli extends ADORecordSet{
 		case MYSQLI_TYPE_NEWDATE :
 		case MYSQLI_TYPE_TIME :
 		case MYSQLI_TYPE_TIMESTAMP :
-
 			return 'T';
 
 		case 'INT':
@@ -1152,23 +1159,20 @@ class ADORecordSet_mysqli extends ADORecordSet{
 		case MYSQLI_TYPE_LONGLONG :
 		case MYSQLI_TYPE_SHORT :
 		case MYSQLI_TYPE_TINY :
-
-		   if (!empty($fieldobj->primary_key)) return 'R';
-
-		   return 'I';
-
-
-		   // Added floating-point types
-		   // Maybe not necessery.
-		 case 'FLOAT':
-		 case 'DOUBLE':
-		   //		case 'DOUBLE PRECISION':
-		 case 'DECIMAL':
-		 case 'DEC':
-		 case 'FIXED':
-		 default:
-		 	//if (!is_numeric($t)) echo "

--- Error in type matching $t -----

"; - return 'N'; + if (!empty($fieldobj->primary_key)) return 'R'; + return 'I'; + + // Added floating-point types + // Maybe not necessery. + case 'FLOAT': + case 'DOUBLE': +// case 'DOUBLE PRECISION': + case 'DECIMAL': + case 'DEC': + case 'FIXED': + default: + //if (!is_numeric($t)) echo "

--- Error in type matching $t -----

"; + return 'N'; } } // function @@ -1179,29 +1183,29 @@ class ADORecordSet_mysqli extends ADORecordSet{ class ADORecordSet_array_mysqli extends ADORecordSet_array { - function ADORecordSet_array_mysqli($id=-1,$mode=false) - { - $this->ADORecordSet_array($id,$mode); - } + function __construct($id=-1,$mode=false) + { + parent::__construct($id,$mode); + } function MetaType($t, $len = -1, $fieldobj = false) { if (is_object($t)) { - $fieldobj = $t; - $t = $fieldobj->type; - $len = $fieldobj->max_length; + $fieldobj = $t; + $t = $fieldobj->type; + $len = $fieldobj->max_length; } - $len = -1; // mysql max_length is not accurate - switch (strtoupper($t)) { - case 'STRING': - case 'CHAR': - case 'VARCHAR': - case 'TINYBLOB': - case 'TINYTEXT': - case 'ENUM': - case 'SET': + $len = -1; // mysql max_length is not accurate + switch (strtoupper($t)) { + case 'STRING': + case 'CHAR': + case 'VARCHAR': + case 'TINYBLOB': + case 'TINYTEXT': + case 'ENUM': + case 'SET': case MYSQLI_TYPE_TINY_BLOB : #case MYSQLI_TYPE_CHAR : @@ -1209,16 +1213,15 @@ class ADORecordSet_array_mysqli extends ADORecordSet_array { case MYSQLI_TYPE_ENUM : case MYSQLI_TYPE_SET : case 253 : - if ($len <= $this->blobSize) return 'C'; + if ($len <= $this->blobSize) return 'C'; case 'TEXT': case 'LONGTEXT': case 'MEDIUMTEXT': - return 'X'; - + return 'X'; - // php_mysql extension always returns 'blob' even if 'text' - // so we have to check whether binary... + // php_mysql extension always returns 'blob' even if 'text' + // so we have to check whether binary... case 'IMAGE': case 'LONGBLOB': case 'BLOB': @@ -1228,13 +1231,13 @@ class ADORecordSet_array_mysqli extends ADORecordSet_array { case MYSQLI_TYPE_LONG_BLOB : case MYSQLI_TYPE_MEDIUM_BLOB : - return !empty($fieldobj->binary) ? 'B' : 'X'; + return !empty($fieldobj->binary) ? 'B' : 'X'; case 'YEAR': case 'DATE': case MYSQLI_TYPE_DATE : case MYSQLI_TYPE_YEAR : - return 'D'; + return 'D'; case 'TIME': case 'DATETIME': @@ -1260,22 +1263,22 @@ class ADORecordSet_array_mysqli extends ADORecordSet_array { case MYSQLI_TYPE_SHORT : case MYSQLI_TYPE_TINY : - if (!empty($fieldobj->primary_key)) return 'R'; + if (!empty($fieldobj->primary_key)) return 'R'; - return 'I'; + return 'I'; - // Added floating-point types - // Maybe not necessery. - case 'FLOAT': - case 'DOUBLE': - // case 'DOUBLE PRECISION': - case 'DECIMAL': - case 'DEC': - case 'FIXED': - default: - //if (!is_numeric($t)) echo "

--- Error in type matching $t -----

"; - return 'N'; + // Added floating-point types + // Maybe not necessery. + case 'FLOAT': + case 'DOUBLE': +// case 'DOUBLE PRECISION': + case 'DECIMAL': + case 'DEC': + case 'FIXED': + default: + //if (!is_numeric($t)) echo "

--- Error in type matching $t -----

"; + return 'N'; } } // function diff --git a/lib/adodb/drivers/adodb-mysqlpo.inc.php b/lib/adodb/drivers/adodb-mysqlpo.inc.php index 90773010de3..8078a521a5e 100644 --- a/lib/adodb/drivers/adodb-mysqlpo.inc.php +++ b/lib/adodb/drivers/adodb-mysqlpo.inc.php @@ -1,7 +1,9 @@ + + This driver extends the deprecated mysql driver, and was originally designed to be a + portable driver in the same manner as oci8po and mssqlpo. Its functionality + is exactly duplicated in the mysqlt driver, which is itself deprecated. + This driver will be removed in ADOdb version 6.0.0. Requires mysql client. Works on Windows and Unix. */ @@ -25,7 +32,7 @@ class ADODB_mysqlt extends ADODB_mysql { var $hasTransactions = true; var $autoRollback = true; // apparently mysql does not autorollback properly - function ADODB_mysqlt() + function __construct() { global $ADODB_EXTENSION; if ($ADODB_EXTENSION) $this->rsPrefix .= 'ext_'; } @@ -72,7 +79,7 @@ class ADODB_mysqlt extends ADODB_mysql { class ADORecordSet_mysqlt extends ADORecordSet_mysql{ var $databaseType = "mysqlt"; - function ADORecordSet_mysqlt($queryID,$mode=false) + function __construct($queryID,$mode=false) { if ($mode === false) { global $ADODB_FETCH_MODE; @@ -90,7 +97,7 @@ class ADORecordSet_mysqlt extends ADORecordSet_mysql{ } $this->adodbFetchMode = $mode; - $this->ADORecordSet($queryID); + parent::__construct($queryID); } function MoveNext() @@ -109,24 +116,9 @@ class ADORecordSet_mysqlt extends ADORecordSet_mysql{ class ADORecordSet_ext_mysqlt extends ADORecordSet_mysqlt { - function ADORecordSet_ext_mysqlt($queryID,$mode=false) + function __construct($queryID,$mode=false) { - if ($mode === false) { - global $ADODB_FETCH_MODE; - $mode = $ADODB_FETCH_MODE; - } - switch ($mode) - { - case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break; - case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break; - - case ADODB_FETCH_DEFAULT: - case ADODB_FETCH_BOTH: - default: - $this->fetchMode = MYSQL_BOTH; break; - } - $this->adodbFetchMode = $mode; - $this->ADORecordSet($queryID); + parent::__construct($queryID,$mode); } function MoveNext() diff --git a/lib/adodb/drivers/adodb-mysqlt.inc.php b/lib/adodb/drivers/adodb-mysqlt.inc.php index 74ee4b406c4..55b5364015a 100644 --- a/lib/adodb/drivers/adodb-mysqlt.inc.php +++ b/lib/adodb/drivers/adodb-mysqlt.inc.php @@ -1,14 +1,18 @@ + This driver only supports the original MySQL driver in transactional mode. It + is deprected in PHP version 5.5 and removed in PHP version 7. It is deprecated + as of ADOdb version 5.20.0. Use the mysqli driver instead, which supports both + transactional and non-transactional updates Requires mysql client. Works on Windows and Unix. */ @@ -25,7 +29,7 @@ class ADODB_mysqlt extends ADODB_mysql { var $hasTransactions = true; var $autoRollback = true; // apparently mysql does not autorollback properly - function ADODB_mysqlt() + function __construct() { global $ADODB_EXTENSION; if ($ADODB_EXTENSION) $this->rsPrefix .= 'ext_'; } @@ -89,7 +93,7 @@ class ADODB_mysqlt extends ADODB_mysql { class ADORecordSet_mysqlt extends ADORecordSet_mysql{ var $databaseType = "mysqlt"; - function ADORecordSet_mysqlt($queryID,$mode=false) + function __construct($queryID,$mode=false) { if ($mode === false) { global $ADODB_FETCH_MODE; @@ -107,7 +111,7 @@ class ADORecordSet_mysqlt extends ADORecordSet_mysql{ } $this->adodbFetchMode = $mode; - $this->ADORecordSet($queryID); + parent::__construct($queryID); } function MoveNext() @@ -128,22 +132,7 @@ class ADORecordSet_ext_mysqlt extends ADORecordSet_mysqlt { function ADORecordSet_ext_mysqlt($queryID,$mode=false) { - if ($mode === false) { - global $ADODB_FETCH_MODE; - $mode = $ADODB_FETCH_MODE; - } - switch ($mode) - { - case ADODB_FETCH_NUM: $this->fetchMode = MYSQL_NUM; break; - case ADODB_FETCH_ASSOC:$this->fetchMode = MYSQL_ASSOC; break; - - case ADODB_FETCH_DEFAULT: - case ADODB_FETCH_BOTH: - default: - $this->fetchMode = MYSQL_BOTH; break; - } - $this->adodbFetchMode = $mode; - $this->ADORecordSet($queryID); + parent::__construct($queryID,$mode); } function MoveNext() diff --git a/lib/adodb/drivers/adodb-netezza.inc.php b/lib/adodb/drivers/adodb-netezza.inc.php index 7c1631bf8d5..5710bd6335c 100644 --- a/lib/adodb/drivers/adodb-netezza.inc.php +++ b/lib/adodb/drivers/adodb-netezza.inc.php @@ -1,6 +1,8 @@ fetchMode = PGSQL_NUM; break; - case ADODB_FETCH_ASSOC:$this->fetchMode = PGSQL_ASSOC; break; - - case ADODB_FETCH_DEFAULT: - case ADODB_FETCH_BOTH: - default: $this->fetchMode = PGSQL_BOTH; break; - } - $this->adodbFetchMode = $mode; - $this->ADORecordSet($queryID); + parent::__construct($queryID,$mode); } // _initrs modified to disable blob handling function _initrs() { global $ADODB_COUNTRECS; - $this->_numOfRows = ($ADODB_COUNTRECS)? @pg_numrows($this->_queryID):-1; - $this->_numOfFields = @pg_numfields($this->_queryID); + $this->_numOfRows = ($ADODB_COUNTRECS)? @pg_num_rows($this->_queryID):-1; + $this->_numOfFields = @pg_num_fields($this->_queryID); } } diff --git a/lib/adodb/drivers/adodb-oci8.inc.php b/lib/adodb/drivers/adodb-oci8.inc.php index 6eac31acb38..cf0cb5e0925 100644 --- a/lib/adodb/drivers/adodb-oci8.inc.php +++ b/lib/adodb/drivers/adodb-oci8.inc.php @@ -1,7 +1,9 @@ _hasOciFetchStatement = ADODB_PHPVER >= 0x4200; - if (defined('ADODB_EXTENSION')) $this->rsPrefix .= 'ext_'; + if (defined('ADODB_EXTENSION')) { + $this->rsPrefix .= 'ext_'; + } } /* function MetaColumns($table, $normalize=true) added by smondino@users.sourceforge.net*/ @@ -116,20 +119,25 @@ END; $schema = ''; $this->_findschema($table, $schema); - $false = false; $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); + if ($this->fetchMode !== false) { + $savem = $this->SetFetchMode(false); + } - if ($schema) + if ($schema){ $rs = $this->Execute(sprintf($this->metaColumnsSQL2, strtoupper($schema), strtoupper($table))); - else + } + else { $rs = $this->Execute(sprintf($this->metaColumnsSQL,strtoupper($table))); + } - if (isset($savem)) $this->SetFetchMode($savem); + if (isset($savem)) { + $this->SetFetchMode($savem); + } $ADODB_FETCH_MODE = $save; if (!$rs) { - return $false; + return false; } $retarr = array(); while (!$rs->EOF) { @@ -139,28 +147,36 @@ END; $fld->max_length = $rs->fields[2]; $fld->scale = $rs->fields[3]; if ($rs->fields[1] == 'NUMBER') { - if ($rs->fields[3] == 0) $fld->type = 'INT'; + if ($rs->fields[3] == 0) { + $fld->type = 'INT'; + } $fld->max_length = $rs->fields[4]; } $fld->not_null = (strncmp($rs->fields[5], 'NOT',3) === 0); $fld->binary = (strpos($fld->type,'BLOB') !== false); $fld->default_value = $rs->fields[6]; - if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld; - else $retarr[strtoupper($fld->name)] = $fld; + if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) { + $retarr[] = $fld; + } + else { + $retarr[strtoupper($fld->name)] = $fld; + } $rs->MoveNext(); } $rs->Close(); - if (empty($retarr)) - return $false; - else - return $retarr; + if (empty($retarr)) { + return false; + } + return $retarr; } function Time() { $rs = $this->Execute("select TO_CHAR($this->sysTimeStamp,'YYYY-MM-DD HH24:MI:SS') from dual"); - if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields)); + if ($rs && !$rs->EOF) { + return $this->UnixTimeStamp(reset($rs->fields)); + } return false; } @@ -193,14 +209,18 @@ END; */ function _connect($argHostname, $argUsername, $argPassword, $argDatabasename=null, $mode=0) { - if (!function_exists('oci_pconnect')) return null; + if (!function_exists('oci_pconnect')) { + return null; + } #adodb_backtrace(); $this->_errorMsg = false; $this->_errorCode = false; if($argHostname) { // added by Jorma Tuomainen - if (empty($argDatabasename)) $argDatabasename = $argHostname; + if (empty($argDatabasename)) { + $argDatabasename = $argHostname; + } else { if(strpos($argHostname,":")) { $argHostinfo=explode(":",$argHostname); @@ -229,7 +249,9 @@ END; $this->_connectionID = ($this->charSet) ? oci_pconnect($argUsername,$argPassword, $argDatabasename,$this->charSet) : oci_pconnect($argUsername,$argPassword, $argDatabasename); - if ($this->_connectionID && $this->autoRollback) oci_rollback($this->_connectionID); + if ($this->_connectionID && $this->autoRollback) { + oci_rollback($this->_connectionID); + } } else if ($mode==2) { $this->_connectionID = ($this->charSet) ? oci_new_connect($argUsername,$argPassword, $argDatabasename,$this->charSet) @@ -275,7 +297,9 @@ END; function _affectedrows() { - if (is_resource($this->_stmt)) return @oci_num_rows($this->_stmt); + if (is_resource($this->_stmt)) { + return @oci_num_rows($this->_stmt); + } return 0; } @@ -287,17 +311,25 @@ END; // format and return date string in database date format function DBDate($d,$isfld=false) { - if (empty($d) && $d !== 0) return 'null'; + if (empty($d) && $d !== 0) { + return 'null'; + } if ($isfld) { $d = _adodb_safedate($d); return 'TO_DATE('.$d.",'".$this->dateformat."')"; } - if (is_string($d)) $d = ADORecordSet::UnixDate($d); + if (is_string($d)) { + $d = ADORecordSet::UnixDate($d); + } - if (is_object($d)) $ds = $d->format($this->fmtDate); - else $ds = adodb_date($this->fmtDate,$d); + if (is_object($d)) { + $ds = $d->format($this->fmtDate); + } + else { + $ds = adodb_date($this->fmtDate,$d); + } return "TO_DATE(".$ds.",'".$this->dateformat."')"; } @@ -305,18 +337,28 @@ END; function BindDate($d) { $d = ADOConnection::DBDate($d); - if (strncmp($d,"'",1)) return $d; + if (strncmp($d, "'", 1)) { + return $d; + } - return substr($d,1,strlen($d)-2); + return substr($d, 1, strlen($d)-2); } function BindTimeStamp($ts) { - if (empty($ts) && $ts !== 0) return 'null'; - if (is_string($ts)) $ts = ADORecordSet::UnixTimeStamp($ts); + if (empty($ts) && $ts !== 0) { + return 'null'; + } + if (is_string($ts)) { + $ts = ADORecordSet::UnixTimeStamp($ts); + } - if (is_object($ts)) $tss = $ts->format("'Y-m-d H:i:s'"); - else $tss = adodb_date("'Y-m-d H:i:s'",$ts); + if (is_object($ts)) { + $tss = $ts->format("'Y-m-d H:i:s'"); + } + else { + $tss = adodb_date("'Y-m-d H:i:s'",$ts); + } return $tss; } @@ -324,19 +366,31 @@ END; // format and return date string in database timestamp format function DBTimeStamp($ts,$isfld=false) { - if (empty($ts) && $ts !== 0) return 'null'; - if ($isfld) return 'TO_DATE(substr('.$ts.",1,19),'RRRR-MM-DD, HH24:MI:SS')"; - if (is_string($ts)) $ts = ADORecordSet::UnixTimeStamp($ts); + if (empty($ts) && $ts !== 0) { + return 'null'; + } + if ($isfld) { + return 'TO_DATE(substr('.$ts.",1,19),'RRRR-MM-DD, HH24:MI:SS')"; + } + if (is_string($ts)) { + $ts = ADORecordSet::UnixTimeStamp($ts); + } - if (is_object($ts)) $tss = $ts->format("'Y-m-d H:i:s'"); - else $tss = date("'Y-m-d H:i:s'",$ts); + if (is_object($ts)) { + $tss = $ts->format("'Y-m-d H:i:s'"); + } + else { + $tss = date("'Y-m-d H:i:s'",$ts); + } return 'TO_DATE('.$tss.",'RRRR-MM-DD, HH24:MI:SS')"; } function RowLock($tables,$where,$col='1 as adodbignore') { - if ($this->autoCommit) $this->BeginTrans(); + if ($this->autoCommit) { + $this->BeginTrans(); + } return $this->GetOne("select $col from $tables where $where for update"); } @@ -374,40 +428,45 @@ END; // get Primary index $primary_key = ''; - $false = false; $rs = $this->Execute(sprintf("SELECT * FROM ALL_CONSTRAINTS WHERE UPPER(TABLE_NAME)='%s' AND CONSTRAINT_TYPE='P'",$table)); if (!is_object($rs)) { - if (isset($savem)) + if (isset($savem)) { $this->SetFetchMode($savem); + } $ADODB_FETCH_MODE = $save; - return $false; + return false; } - if ($row = $rs->FetchRow()) + if ($row = $rs->FetchRow()) { $primary_key = $row[1]; //constraint_name + } if ($primary==TRUE && $primary_key=='') { - if (isset($savem)) + if (isset($savem)) { $this->SetFetchMode($savem); + } $ADODB_FETCH_MODE = $save; - return $false; //There is no primary key + return false; //There is no primary key } $rs = $this->Execute(sprintf("SELECT ALL_INDEXES.INDEX_NAME, ALL_INDEXES.UNIQUENESS, ALL_IND_COLUMNS.COLUMN_POSITION, ALL_IND_COLUMNS.COLUMN_NAME FROM ALL_INDEXES,ALL_IND_COLUMNS WHERE UPPER(ALL_INDEXES.TABLE_NAME)='%s' AND ALL_IND_COLUMNS.INDEX_NAME=ALL_INDEXES.INDEX_NAME",$table)); if (!is_object($rs)) { - if (isset($savem)) + if (isset($savem)) { $this->SetFetchMode($savem); + } $ADODB_FETCH_MODE = $save; - return $false; + return false; } $indexes = array (); // parse index data into array while ($row = $rs->FetchRow()) { - if ($primary && $row[0] != $primary_key) continue; + if ($primary && $row[0] != $primary_key) { + continue; + } if (!isset($indexes[$row[0]])) { $indexes[$row[0]] = array( 'unique' => ($row[1] == 'UNIQUE'), @@ -431,23 +490,35 @@ END; function BeginTrans() { - if ($this->transOff) return true; + if ($this->transOff) { + return true; + } $this->transCnt += 1; $this->autoCommit = false; $this->_commit = OCI_DEFAULT; - if ($this->_transmode) $ok = $this->Execute("SET TRANSACTION ".$this->_transmode); - else $ok = true; + if ($this->_transmode) { + $ok = $this->Execute("SET TRANSACTION ".$this->_transmode); + } + else { + $ok = true; + } return $ok ? true : false; } function CommitTrans($ok=true) { - if ($this->transOff) return true; - if (!$ok) return $this->RollbackTrans(); + if ($this->transOff) { + return true; + } + if (!$ok) { + return $this->RollbackTrans(); + } - if ($this->transCnt) $this->transCnt -= 1; + if ($this->transCnt) { + $this->transCnt -= 1; + } $ret = oci_commit($this->_connectionID); $this->_commit = OCI_COMMIT_ON_SUCCESS; $this->autoCommit = true; @@ -456,8 +527,12 @@ END; function RollbackTrans() { - if ($this->transOff) return true; - if ($this->transCnt) $this->transCnt -= 1; + if ($this->transOff) { + return true; + } + if ($this->transCnt) { + $this->transCnt -= 1; + } $ret = oci_rollback($this->_connectionID); $this->_commit = OCI_COMMIT_ON_SUCCESS; $this->autoCommit = true; @@ -472,13 +547,23 @@ END; function ErrorMsg() { - if ($this->_errorMsg !== false) return $this->_errorMsg; + if ($this->_errorMsg !== false) { + return $this->_errorMsg; + } - if (is_resource($this->_stmt)) $arr = @oci_error($this->_stmt); + if (is_resource($this->_stmt)) { + $arr = @oci_error($this->_stmt); + } if (empty($arr)) { - if (is_resource($this->_connectionID)) $arr = @oci_error($this->_connectionID); - else $arr = @oci_error(); - if ($arr === false) return ''; + if (is_resource($this->_connectionID)) { + $arr = @oci_error($this->_connectionID); + } + else { + $arr = @oci_error(); + } + if ($arr === false) { + return ''; + } } $this->_errorMsg = $arr['message']; $this->_errorCode = $arr['code']; @@ -487,13 +572,21 @@ END; function ErrorNo() { - if ($this->_errorCode !== false) return $this->_errorCode; + if ($this->_errorCode !== false) { + return $this->_errorCode; + } - if (is_resource($this->_stmt)) $arr = @oci_error($this->_stmt); + if (is_resource($this->_stmt)) { + $arr = @oci_error($this->_stmt); + } if (empty($arr)) { $arr = @oci_error($this->_connectionID); - if ($arr == false) $arr = @oci_error(); - if ($arr == false) return ''; + if ($arr == false) { + $arr = @oci_error(); + } + if ($arr == false) { + return ''; + } } $this->_errorMsg = $arr['message']; @@ -507,7 +600,9 @@ END; */ function SQLDate($fmt, $col=false) { - if (!$col) $col = $this->sysTimeStamp; + if (!$col) { + $col = $this->sysTimeStamp; + } $s = 'TO_CHAR('.$col.",'"; $len = strlen($fmt); @@ -569,13 +664,17 @@ END; break; default: - // handle escape characters... + // handle escape characters... if ($ch == '\\') { $i++; $ch = substr($fmt,$i,1); } - if (strpos('-/.:;, ',$ch) !== false) $s .= $ch; - else $s .= '"'.$ch.'"'; + if (strpos('-/.:;, ',$ch) !== false) { + $s .= $ch; + } + else { + $s .= '"'.$ch.'"'; + } } } @@ -609,20 +708,29 @@ END; { // seems that oracle only supports 1 hint comment in 8i if ($this->firstrows) { - if ($nrows > 500 && $nrows < 1000) $hint = "FIRST_ROWS($nrows)"; - else $hint = 'FIRST_ROWS'; + if ($nrows > 500 && $nrows < 1000) { + $hint = "FIRST_ROWS($nrows)"; + } + else { + $hint = 'FIRST_ROWS'; + } - if (strpos($sql,'/*+') !== false) + if (strpos($sql,'/*+') !== false) { $sql = str_replace('/*+ ',"/*+$hint ",$sql); - else + } + else { $sql = preg_replace('/^[ \t\n]*select/i',"SELECT /*+$hint*/",$sql); + } $hint = "/*+ $hint */"; - } else + } else { $hint = ''; + } if ($offset == -1 || ($offset < $this->selectOffsetAlg1 && 0 < $nrows && $nrows < 1000)) { if ($nrows > 0) { - if ($offset > 0) $nrows += $offset; + if ($offset > 0) { + $nrows += $offset; + } //$inputarr['adodb_rownum'] = $nrows; if ($this->databaseType == 'oci8po') { $sql = "select * from (".$sql.") where rownum <= ?"; @@ -643,22 +751,26 @@ END; // Let Oracle return the name of the columns $q_fields = "SELECT * FROM (".$sql.") WHERE NULL = NULL"; - $false = false; if (! $stmt_arr = $this->Prepare($q_fields)) { - return $false; + return false; } $stmt = $stmt_arr[1]; if (is_array($inputarr)) { foreach($inputarr as $k => $v) { if (is_array($v)) { - if (sizeof($v) == 2) // suggested by g.giunta@libero. + // suggested by g.giunta@libero. + if (sizeof($v) == 2) { oci_bind_by_name($stmt,":$k",$inputarr[$k][0],$v[1]); - else + } + else { oci_bind_by_name($stmt,":$k",$inputarr[$k][0],$v[1],$v[2]); + } } else { $len = -1; - if ($v === ' ') $len = 1; + if ($v === ' ') { + $len = 1; + } if (isset($bindarr)) { // is prepared sql, so no need to oci_bind_by_name again $bindarr[$k] = $v; } else { // dynamic sql, so rebind every time @@ -670,7 +782,7 @@ END; if (!oci_execute($stmt, OCI_DEFAULT)) { oci_free_statement($stmt); - return $false; + return false; } $ncols = oci_num_fields($stmt); @@ -681,8 +793,12 @@ END; oci_free_statement($stmt); $fields = implode(',', $cols); - if ($nrows <= 0) $nrows = 999999999999; - else $nrows += $offset; + if ($nrows <= 0) { + $nrows = 999999999999; + } + else { + $nrows += $offset; + } $offset += 1; // in Oracle rownum starts at 1 if ($this->databaseType == 'oci8po') { @@ -699,7 +815,9 @@ END; $inputarr['adodb_nrows'] = $nrows; $inputarr['adodb_offset'] = $offset; - if ($secs2cache>0) $rs = $this->CacheExecute($secs2cache, $sql,$inputarr); + if ($secs2cache > 0) { + $rs = $this->CacheExecute($secs2cache, $sql,$inputarr); + } else $rs = $this->Execute($sql,$inputarr); return $rs; } @@ -741,16 +859,28 @@ END; $desc = oci_new_descriptor($this->_connectionID, OCI_D_LOB); $arr['blob'] = array($desc,-1,$type); - if ($this->session_sharing_force_blob) $this->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT'); + if ($this->session_sharing_force_blob) { + $this->Execute('ALTER SESSION SET CURSOR_SHARING=EXACT'); + } $commit = $this->autoCommit; - if ($commit) $this->BeginTrans(); + if ($commit) { + $this->BeginTrans(); + } $rs = $this->_Execute($sql,$arr); - if ($rez = !empty($rs)) $desc->save($val); + if ($rez = !empty($rs)) { + $desc->save($val); + } $desc->free(); - if ($commit) $this->CommitTrans(); - if ($this->session_sharing_force_blob) $this->Execute('ALTER SESSION SET CURSOR_SHARING=FORCE'); + if ($commit) { + $this->CommitTrans(); + } + if ($this->session_sharing_force_blob) { + $this->Execute('ALTER SESSION SET CURSOR_SHARING=FORCE'); + } - if ($rez) $rs->Close(); + if ($rez) { + $rs->Close(); + } return $rez; } @@ -775,11 +905,15 @@ END; $this->BeginTrans(); $rs = ADODB_oci8::Execute($sql,$arr); - if ($rez = !empty($rs)) $desc->savefile($val); + if ($rez = !empty($rs)) { + $desc->savefile($val); + } $desc->free(); $this->CommitTrans(); - if ($rez) $rs->Close(); + if ($rez) { + $rs->Close(); + } return $rez; } @@ -795,10 +929,14 @@ END; 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); $array2d = $this->bulkBind && is_array($element0) && !is_object(reset($element0)); @@ -806,31 +944,38 @@ END; # see http://phplens.com/lens/lensforum/msgs.php?id=18786 if ($array2d || !$this->_bindInputArray) { - # is_object check because oci8 descriptors can be passed in - if ($array2d && $this->_bindInputArray) { - if (is_string($sql)) - $stmt = $this->Prepare($sql); - else - $stmt = $sql; + # is_object check because oci8 descriptors can be passed in + if ($array2d && $this->_bindInputArray) { + if (is_string($sql)) { + $stmt = $this->Prepare($sql); + } else { + $stmt = $sql; + } - foreach($inputarr as $arr) { - $ret = $this->_Execute($stmt,$arr); - if (!$ret) return $ret; - } - return $ret; - } else { - $sqlarr = explode(':',$sql); - $sql = ''; - $lastnomatch = -2; - #var_dump($sqlarr);echo "
";var_dump($inputarr);echo"
"; - foreach($sqlarr as $k => $str) { - if ($k == 0) { $sql = $str; continue; } + foreach($inputarr as $arr) { + $ret = $this->_Execute($stmt,$arr); + if (!$ret) { + return $ret; + } + } + return $ret; + } else { + $sqlarr = explode(':', $sql); + $sql = ''; + $lastnomatch = -2; + #var_dump($sqlarr);echo "
";var_dump($inputarr);echo"
"; + foreach($sqlarr as $k => $str) { + if ($k == 0) { + $sql = $str; + continue; + } // we need $lastnomatch because of the following datetime, // eg. '10:10:01', which causes code to think that there is bind param :10 and :1 $ok = preg_match('/^([0-9]*)/', $str, $arr); - if (!$ok) $sql .= $str; - else { + if (!$ok) { + $sql .= $str; + } else { $at = $arr[1]; if (isset($inputarr[$at]) || is_null($inputarr[$at])) { if ((strlen($at) == strlen($str) && $k < sizeof($arr)-1)) { @@ -839,14 +984,17 @@ END; } else if ($lastnomatch == $k-1) { $sql .= ':'.$str; } else { - if (is_null($inputarr[$at])) $sql .= 'null'; - else $sql .= $this->qstr($inputarr[$at]); + if (is_null($inputarr[$at])) { + $sql .= 'null'; + } + else { + $sql .= $this->qstr($inputarr[$at]); + } $sql .= substr($str, strlen($at)); } } else { $sql .= ':'.$str; } - } } $inputarr = false; @@ -854,7 +1002,6 @@ END; } $ret = $this->_Execute($sql,$inputarr); - } else { $ret = $this->_Execute($sql,false); } @@ -876,7 +1023,9 @@ END; $this->_errorMsg = false; $this->_errorCode = false; $arr = @oci_error($this->_connectionID); - if ($arr === false) return false; + if ($arr === false) { + return false; + } $this->_errorMsg = $arr['message']; $this->_errorCode = $arr['code']; @@ -908,7 +1057,9 @@ END; */ function ExecuteCursor($sql,$cursorName='rs',$params=false) { - if (is_array($sql)) $stmt = $sql; + if (is_array($sql)) { + $stmt = $sql; + } else $stmt = ADODB_oci8::Prepare($sql,true); # true to allocate oci_new_cursor if (is_array($stmt) && sizeof($stmt) >= 5) { @@ -925,8 +1076,12 @@ END; $rs = $this->Execute($stmt); if ($rs) { - if ($rs->databaseType == 'array') oci_free_cursor($stmt[4]); - else if ($hasref) $rs->_refcursor = $stmt[4]; + if ($rs->databaseType == 'array') { + oci_free_cursor($stmt[4]); + } + elseif ($hasref) { + $rs->_refcursor = $stmt[4]; + } } return $rs; } @@ -963,15 +1118,21 @@ END; function Bind(&$stmt,&$var,$size=4000,$type=false,$name=false,$isOutput=false) { - if (!is_array($stmt)) return false; + if (!is_array($stmt)) { + return false; + } if (($type == OCI_B_CURSOR) && sizeof($stmt) >= 5) { return oci_bind_by_name($stmt[1],":".$name,$stmt[4],$size,$type); } if ($name == false) { - if ($type !== false) $rez = oci_bind_by_name($stmt[1],":".$stmt[2],$var,$size,$type); - else $rez = oci_bind_by_name($stmt[1],":".$stmt[2],$var,$size); // +1 byte for null terminator + if ($type !== false) { + $rez = oci_bind_by_name($stmt[1],":".$stmt[2],$var,$size,$type); + } + else { + $rez = oci_bind_by_name($stmt[1],":".$stmt[2],$var,$size); // +1 byte for null terminator + } $stmt[2] += 1; } else if (oci_lob_desc($type)) { if ($this->debug) { @@ -1004,8 +1165,12 @@ END; if ($this->debug) ADOConnection::outp("Bind: name = $name"); - if ($type !== false) $rez = oci_bind_by_name($stmt[1],":".$name,$var,$size,$type); - else $rez = oci_bind_by_name($stmt[1],":".$name,$var,$size); // +1 byte for null terminator + if ($type !== false) { + $rez = oci_bind_by_name($stmt[1],":".$name,$var,$size,$type); + } + else { + $rez = oci_bind_by_name($stmt[1],":".$name,$var,$size); // +1 byte for null terminator + } } return $rez; @@ -1084,28 +1249,39 @@ END; } $this->_stmt = $stmt; - if (!$stmt) return false; + if (!$stmt) { + return false; + } - if (defined('ADODB_PREFETCH_ROWS')) @oci_set_prefetch($stmt,ADODB_PREFETCH_ROWS); + if (defined('ADODB_PREFETCH_ROWS')) { + @oci_set_prefetch($stmt,ADODB_PREFETCH_ROWS); + } if (is_array($inputarr)) { foreach($inputarr as $k => $v) { if (is_array($v)) { - if (sizeof($v) == 2) // suggested by g.giunta@libero. + // suggested by g.giunta@libero. + if (sizeof($v) == 2) { oci_bind_by_name($stmt,":$k",$inputarr[$k][0],$v[1]); - else + } + else { oci_bind_by_name($stmt,":$k",$inputarr[$k][0],$v[1],$v[2]); + } if ($this->debug==99) { - if (is_object($v[0])) + if (is_object($v[0])) { echo "name=:$k",' len='.$v[1],' type='.$v[2],'
'; - else + } + else { echo "name=:$k",' var='.$inputarr[$k][0],' len='.$v[1],' type='.$v[2],'
'; + } } } else { $len = -1; - if ($v === ' ') $len = 1; + if ($v === ' ') { + $len = 1; + } if (isset($bindarr)) { // is prepared sql, so no need to oci_bind_by_name again $bindarr[$k] = $v; } else { // dynamic sql, so rebind every time @@ -1198,9 +1374,14 @@ END; // returns true or false function _close() { - if (!$this->_connectionID) return; + if (!$this->_connectionID) { + return; + } - if (!$this->autoCommit) oci_rollback($this->_connectionID); + + if (!$this->autoCommit) { + oci_rollback($this->_connectionID); + } if (count($this->_refLOBs) > 0) { foreach ($this ->_refLOBs as $key => $value) { $this->_refLOBs[$key]['LOB']->free(); @@ -1215,7 +1396,9 @@ END; function MetaPrimaryKeys($table, $owner=false,$internalKey=false) { - if ($internalKey) return array('ROWID'); + if ($internalKey) { + return array('ROWID'); + } // tested with oracle 8.1.7 $table = strtoupper($table); @@ -1321,7 +1504,9 @@ SELECT /*+ RULE */ distinct b.column_name { //$nofixquotes=false; - if ($this->noNullStrings && strlen($s)==0)$s = ' '; + if ($this->noNullStrings && strlen($s)==0) { + $s = ' '; + } if (!$magic_quotes) { if ($this->replaceQuote[0] == '\\'){ $s = str_replace('\\','\\\\',$s); @@ -1351,24 +1536,26 @@ class ADORecordset_oci8 extends ADORecordSet { var $bind=false; var $_fieldobjs; - //var $_arr = false; - - function ADORecordset_oci8($queryID,$mode=false) + function __construct($queryID,$mode=false) { if ($mode === false) { global $ADODB_FETCH_MODE; $mode = $ADODB_FETCH_MODE; } - switch ($mode) - { - case ADODB_FETCH_ASSOC:$this->fetchMode = OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break; - case ADODB_FETCH_DEFAULT: - case ADODB_FETCH_BOTH:$this->fetchMode = OCI_NUM+OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break; - case ADODB_FETCH_NUM: - default: - $this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break; + switch ($mode) { + case ADODB_FETCH_ASSOC: + $this->fetchMode = OCI_ASSOC; + break; + case ADODB_FETCH_DEFAULT: + case ADODB_FETCH_BOTH: + $this->fetchMode = OCI_NUM + OCI_ASSOC; + break; + case ADODB_FETCH_NUM: + default: + $this->fetchMode = OCI_NUM; + break; } - + $this->fetchMode += OCI_RETURN_NULLS + OCI_RETURN_LOBS; $this->adodbFetchMode = $mode; $this->_queryID = $queryID; } @@ -1376,21 +1563,27 @@ class ADORecordset_oci8 extends ADORecordSet { function Init() { - if ($this->_inited) return; + if ($this->_inited) { + return; + } $this->_inited = true; if ($this->_queryID) { $this->_currentRow = 0; @$this->_initrs(); - if ($this->_numOfFields) $this->EOF = !$this->_fetch(); + if ($this->_numOfFields) { + $this->EOF = !$this->_fetch(); + } else $this->EOF = true; /* // based on idea by Gaetano Giunta to detect unusual oracle errors // see http://phplens.com/lens/lensforum/msgs.php?id=6771 $err = oci_error($this->_queryID); - if ($err && $this->connection->debug) ADOConnection::outp($err); + if ($err && $this->connection->debug) { + ADOConnection::outp($err); + } */ if (!is_array($this->fields)) { @@ -1429,6 +1622,9 @@ class ADORecordset_oci8 extends ADORecordSet { $fld = new ADOFieldObject; $fieldOffset += 1; $fld->name =oci_field_name($this->_queryID, $fieldOffset); + if (ADODB_ASSOC_CASE == ADODB_ASSOC_CASE_LOWER) { + $fld->name = strtolower($fld->name); + } $fld->type = oci_field_type($this->_queryID, $fieldOffset); $fld->max_length = oci_field_size($this->_queryID, $fieldOffset); @@ -1436,7 +1632,9 @@ class ADORecordset_oci8 extends ADORecordSet { case 'NUMBER': $p = oci_field_precision($this->_queryID, $fieldOffset); $sc = oci_field_scale($this->_queryID, $fieldOffset); - if ($p != 0 && $sc == 0) $fld->type = 'INT'; + if ($p != 0 && $sc == 0) { + $fld->type = 'INT'; + } $fld->scale = $p; break; @@ -1456,28 +1654,11 @@ class ADORecordset_oci8 extends ADORecordSet { } -/* - // 10% speedup to move MoveNext to child class - function _MoveNext() - { - //global $ADODB_EXTENSION;if ($ADODB_EXTENSION) return @adodb_movenext($this); - - if ($this->EOF) return false; - - $this->_currentRow++; - if($this->fields = @oci_fetch_array($this->_queryID,$this->fetchMode)) - return true; - $this->EOF = true; - - return false; - } -*/ - - function MoveNext() { if ($this->fields = @oci_fetch_array($this->_queryID,$this->fetchMode)) { $this->_currentRow += 1; + $this->_updatefields(); return true; } if (!$this->EOF) { @@ -1487,41 +1668,6 @@ class ADORecordset_oci8 extends ADORecordSet { return false; } -/* - # does not work as first record is retrieved in _initrs(), so is not included in GetArray() - function GetArray($nRows = -1) - { - global $ADODB_OCI8_GETARRAY; - - if (true || !empty($ADODB_OCI8_GETARRAY)) { - # does not support $ADODB_ANSI_PADDING_OFF - - //OCI_RETURN_NULLS and OCI_RETURN_LOBS is set by oci_fetch_all - switch($this->adodbFetchMode) { - case ADODB_FETCH_NUM: - - $ncols = @oci_fetch_all($this->_queryID, $results, 0, $nRows, oci_fetch_all_BY_ROW+OCI_NUM); - $results = array_merge(array($this->fields),$results); - return $results; - - case ADODB_FETCH_ASSOC: - if (ADODB_ASSOC_CASE != 2 || $this->databaseType != 'oci8') break; - - $ncols = @oci_fetch_all($this->_queryID, $assoc, 0, $nRows, oci_fetch_all_BY_ROW); - $results = array_merge(array($this->fields),$assoc); - return $results; - - default: - break; - } - } - - $results = ADORecordSet::GetArray($nRows); - return $results; - - } -*/ - // Optimize SelectLimit() by using oci_fetch() function GetArrayLimit($nrows,$offset=-1) { @@ -1530,10 +1676,16 @@ class ADORecordset_oci8 extends ADORecordSet { return $arr; } $arr = array(); - for ($i=1; $i < $offset; $i++) - if (!@oci_fetch($this->_queryID)) return $arr; + for ($i=1; $i < $offset; $i++) { + if (!@oci_fetch($this->_queryID)) { + return $arr; + } + } - if (!$this->fields = @oci_fetch_array($this->_queryID,$this->fetchMode)) return $arr;; + if (!$this->fields = @oci_fetch_array($this->_queryID,$this->fetchMode)) { + return $arr; + } + $this->_updatefields(); $results = array(); $cnt = 0; while (!$this->EOF && $nrows != $cnt) { @@ -1560,7 +1712,6 @@ class ADORecordset_oci8 extends ADORecordSet { } - function _seek($row) { return false; @@ -1568,7 +1719,10 @@ class ADORecordset_oci8 extends ADORecordSet { function _fetch() { - return $this->fields = @oci_fetch_array($this->_queryID,$this->fetchMode); + $this->fields = @oci_fetch_array($this->_queryID,$this->fetchMode); + $this->_updatefields(); + + return $this->fields; } /** @@ -1578,7 +1732,9 @@ class ADORecordset_oci8 extends ADORecordSet { */ function _close() { - if ($this->connection->_stmt === $this->_queryID) $this->connection->_stmt = false; + if ($this->connection->_stmt === $this->_queryID) { + $this->connection->_stmt = false; + } if (!empty($this->_refcursor)) { oci_free_cursor($this->_refcursor); $this->_refcursor = false; @@ -1613,7 +1769,9 @@ class ADORecordset_oci8 extends ADORecordSet { case 'NCHAR': case 'NVARCHAR': case 'NVARCHAR2': - if ($len <= $this->blobSize) return 'C'; + if ($len <= $this->blobSize) { + return 'C'; + } case 'NCLOB': case 'LONG': @@ -1644,22 +1802,9 @@ class ADORecordset_oci8 extends ADORecordSet { } class ADORecordSet_ext_oci8 extends ADORecordSet_oci8 { - function ADORecordSet_ext_oci8($queryID,$mode=false) + function __construct($queryID,$mode=false) { - if ($mode === false) { - global $ADODB_FETCH_MODE; - $mode = $ADODB_FETCH_MODE; - } - switch ($mode) - { - case ADODB_FETCH_ASSOC:$this->fetchMode = OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break; - case ADODB_FETCH_DEFAULT: - case ADODB_FETCH_BOTH:$this->fetchMode = OCI_NUM+OCI_ASSOC+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break; - case ADODB_FETCH_NUM: - default: $this->fetchMode = OCI_NUM+OCI_RETURN_NULLS+OCI_RETURN_LOBS; break; - } - $this->adodbFetchMode = $mode; - $this->_queryID = $queryID; + parent::__construct($queryID, $mode); } function MoveNext() diff --git a/lib/adodb/drivers/adodb-oci805.inc.php b/lib/adodb/drivers/adodb-oci805.inc.php index 7dd5fa6177b..c75e10ba036 100644 --- a/lib/adodb/drivers/adodb-oci805.inc.php +++ b/lib/adodb/drivers/adodb-oci805.inc.php @@ -1,6 +1,8 @@ ADODB_oci8(); - } - function SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0) { // seems that oracle only supports 1 hint comment in 8i @@ -51,8 +48,8 @@ class ADODB_oci805 extends ADODB_oci8 { class ADORecordset_oci805 extends ADORecordset_oci8 { var $databaseType = "oci805"; - function ADORecordset_oci805($id,$mode=false) + function __construct($id,$mode=false) { - $this->ADORecordset_oci8($id,$mode); + parent::__construct($id,$mode); } } diff --git a/lib/adodb/drivers/adodb-oci8po.inc.php b/lib/adodb/drivers/adodb-oci8po.inc.php index fc3aba57065..cf76aa6aed5 100644 --- a/lib/adodb/drivers/adodb-oci8po.inc.php +++ b/lib/adodb/drivers/adodb-oci8po.inc.php @@ -1,6 +1,8 @@ _hasOCIFetchStatement = ADODB_PHPVER >= 0x4200; # oci8po does not support adodb extension: adodb_movenext() @@ -64,11 +66,22 @@ class ADODB_oci8po extends ADODB_oci8 { $arr['bind'.$i++] = $v; } } else { + // Need to identify if the ? is inside a quoted string, and if + // so not use it as a bind variable + preg_match_all('/".*\??"|\'.*\?.*?\'/', $sql, $matches); + foreach($matches[0] as $qmMatch){ + $qmReplace = str_replace('?', '-QUESTIONMARK-', $qmMatch); + $sql = str_replace($qmMatch, $qmReplace, $sql); + } + $sqlarr = explode('?',$sql); $sql = $sqlarr[0]; + foreach($inputarr as $k => $v) { $sql .= ":$k" . $sqlarr[++$i]; } + + $sql = str_replace('-QUESTIONMARK-', '?', $sql); } } return ADODB_oci8::_query($sql,$inputarr); @@ -83,9 +96,9 @@ class ADORecordset_oci8po extends ADORecordset_oci8 { var $databaseType = 'oci8po'; - function ADORecordset_oci8po($queryID,$mode=false) + function __construct($queryID,$mode=false) { - $this->ADORecordset_oci8($queryID,$mode); + parent::__construct($queryID,$mode); } function Fields($colname) @@ -105,32 +118,22 @@ class ADORecordset_oci8po extends ADORecordset_oci8 { // lowercase field names... function _FetchField($fieldOffset = -1) { - $fld = new ADOFieldObject; - $fieldOffset += 1; - $fld->name = OCIcolumnname($this->_queryID, $fieldOffset); - if (ADODB_ASSOC_CASE == 0) $fld->name = strtolower($fld->name); - $fld->type = OCIcolumntype($this->_queryID, $fieldOffset); - $fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset); - if ($fld->type == 'NUMBER') { - //$p = OCIColumnPrecision($this->_queryID, $fieldOffset); - $sc = OCIColumnScale($this->_queryID, $fieldOffset); - if ($sc == 0) $fld->type = 'INT'; - } - return $fld; - } - /* - function MoveNext() - { - if (@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) { - $this->_currentRow += 1; - return true; + $fld = new ADOFieldObject; + $fieldOffset += 1; + $fld->name = OCIcolumnname($this->_queryID, $fieldOffset); + if (ADODB_ASSOC_CASE == ADODB_ASSOC_CASE_LOWER) { + $fld->name = strtolower($fld->name); } - if (!$this->EOF) { - $this->_currentRow += 1; - $this->EOF = true; + $fld->type = OCIcolumntype($this->_queryID, $fieldOffset); + $fld->max_length = OCIcolumnsize($this->_queryID, $fieldOffset); + if ($fld->type == 'NUMBER') { + $sc = OCIColumnScale($this->_queryID, $fieldOffset); + if ($sc == 0) { + $fld->type = 'INT'; + } } - return false; - }*/ + return $fld; + } // 10% speedup to move MoveNext to child class function MoveNext() @@ -138,8 +141,8 @@ class ADORecordset_oci8po extends ADORecordset_oci8 { if(@OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode)) { global $ADODB_ANSI_PADDING_OFF; $this->_currentRow++; + $this->_updatefields(); - if ($this->fetchMode & OCI_ASSOC) $this->_updatefields(); if (!empty($ADODB_ANSI_PADDING_OFF)) { foreach($this->fields as $k => $v) { if (is_string($v)) $this->fields[$k] = rtrim($v); @@ -170,7 +173,7 @@ class ADORecordset_oci8po extends ADORecordset_oci8 { $arr = array(); return $arr; } - if ($this->fetchMode & OCI_ASSOC) $this->_updatefields(); + $this->_updatefields(); $results = array(); $cnt = 0; while (!$this->EOF && $nrows != $cnt) { @@ -181,38 +184,19 @@ class ADORecordset_oci8po extends ADORecordset_oci8 { return $results; } - // Create associative array - function _updatefields() - { - if (ADODB_ASSOC_CASE == 2) return; // native - - $arr = array(); - $lowercase = (ADODB_ASSOC_CASE == 0); - - foreach($this->fields as $k => $v) { - if (is_integer($k)) $arr[$k] = $v; - else { - if ($lowercase) - $arr[strtolower($k)] = $v; - else - $arr[strtoupper($k)] = $v; - } - } - $this->fields = $arr; - } - function _fetch() { + global $ADODB_ANSI_PADDING_OFF; + $ret = @OCIfetchinto($this->_queryID,$this->fields,$this->fetchMode); if ($ret) { - global $ADODB_ANSI_PADDING_OFF; + $this->_updatefields(); - if ($this->fetchMode & OCI_ASSOC) $this->_updatefields(); - if (!empty($ADODB_ANSI_PADDING_OFF)) { - foreach($this->fields as $k => $v) { - if (is_string($v)) $this->fields[$k] = rtrim($v); - } + if (!empty($ADODB_ANSI_PADDING_OFF)) { + foreach($this->fields as $k => $v) { + if (is_string($v)) $this->fields[$k] = rtrim($v); } + } } return $ret; } diff --git a/lib/adodb/drivers/adodb-oci8quercus.inc.php b/lib/adodb/drivers/adodb-oci8quercus.inc.php index 3029bc71074..0556fc57c9c 100644 --- a/lib/adodb/drivers/adodb-oci8quercus.inc.php +++ b/lib/adodb/drivers/adodb-oci8quercus.inc.php @@ -1,6 +1,8 @@ ADORecordset_oci8($queryID,$mode); + parent::__construct($queryID,$mode); } function _FetchField($fieldOffset = -1) diff --git a/lib/adodb/drivers/adodb-odbc.inc.php b/lib/adodb/drivers/adodb-odbc.inc.php index 0b271a4179e..c042ab57d5b 100644 --- a/lib/adodb/drivers/adodb-odbc.inc.php +++ b/lib/adodb/drivers/adodb-odbc.inc.php @@ -1,6 +1,8 @@ _haserrorfunctions = ADODB_PHPVER >= 0x4050; $this->_has_stupid_odbc_fetch_api_change = ADODB_PHPVER >= 0x4200; @@ -132,7 +134,7 @@ class ADODB_odbc extends ADOConnection { } var $_dropSeqSQL = 'drop table %s'; - function DropSequence($seqname) + function DropSequence($seqname = 'adodbseq') { if (empty($this->_dropSeqSQL)) return false; return $this->Execute(sprintf($this->_dropSeqSQL,$seqname)); @@ -606,7 +608,7 @@ class ADORecordSet_odbc extends ADORecordSet { var $useFetchArray; var $_has_stupid_odbc_fetch_api_change; - function ADORecordSet_odbc($id,$mode=false) + function __construct($id,$mode=false) { if ($mode === false) { global $ADODB_FETCH_MODE; @@ -619,7 +621,7 @@ class ADORecordSet_odbc extends ADORecordSet { // the following is required for mysql odbc driver in 4.3.1 -- why? $this->EOF = false; $this->_currentRow = -1; - //$this->ADORecordSet($id); + //parent::__construct($id); } @@ -683,7 +685,7 @@ class ADORecordSet_odbc extends ADORecordSet { $this->fetchMode = $savem; if ($this->fetchMode & ADODB_FETCH_ASSOC) { - $this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE); + $this->fields = $this->GetRowAssoc(); } $results = array(); @@ -721,7 +723,7 @@ class ADORecordSet_odbc extends ADORecordSet { } if ($rez) { if ($this->fetchMode & ADODB_FETCH_ASSOC) { - $this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE); + $this->fields = $this->GetRowAssoc(); } return true; } diff --git a/lib/adodb/drivers/adodb-odbc_db2.inc.php b/lib/adodb/drivers/adodb-odbc_db2.inc.php index 217ecb3b85c..dca54c6a1d3 100644 --- a/lib/adodb/drivers/adodb-odbc_db2.inc.php +++ b/lib/adodb/drivers/adodb-odbc_db2.inc.php @@ -1,6 +1,8 @@ curmode = SQL_CUR_USE_ODBC; - $this->ADODB_odbc(); + parent::__construct(); } function IfNull( $field, $ifNull ) @@ -278,7 +280,7 @@ class ADODB_ODBC_DB2 extends ADODB_odbc { } - function SelectLimit($sql,$nrows=-1,$offset=-1,$inputArr=false) + function SelectLimit($sql, $nrows = -1, $offset = -1, $inputArr = false, $secs2cache = 0) { $nrows = (integer) $nrows; if ($offset <= 0) { @@ -304,9 +306,9 @@ class ADORecordSet_odbc_db2 extends ADORecordSet_odbc { var $databaseType = "db2"; - function ADORecordSet_db2($id,$mode=false) + function __construct($id,$mode=false) { - $this->ADORecordSet_odbc($id,$mode); + parent::__construct($id,$mode); } function MetaType($t,$len=-1,$fieldobj=false) diff --git a/lib/adodb/drivers/adodb-odbc_mssql.inc.php b/lib/adodb/drivers/adodb-odbc_mssql.inc.php index d6894cdb581..8e1d57c473f 100644 --- a/lib/adodb/drivers/adodb-odbc_mssql.inc.php +++ b/lib/adodb/drivers/adodb-odbc_mssql.inc.php @@ -1,6 +1,8 @@ ADODB_odbc(); + parent::__construct(); //$this->curmode = SQL_CUR_USE_ODBC; } @@ -252,7 +254,7 @@ order by constraint_name, referenced_table_name, keyno"; // "Stein-Aksel Basma" // tested with MSSQL 2000 - function MetaPrimaryKeys($table) + function MetaPrimaryKeys($table, $owner = false) { global $ADODB_FETCH_MODE; @@ -354,8 +356,8 @@ class ADORecordSet_odbc_mssql extends ADORecordSet_odbc { var $databaseType = 'odbc_mssql'; - function ADORecordSet_odbc_mssql($id,$mode=false) + function __construct($id,$mode=false) { - return $this->ADORecordSet_odbc($id,$mode); + return parent::__construct($id,$mode); } } diff --git a/lib/adodb/drivers/adodb-odbc_oracle.inc.php b/lib/adodb/drivers/adodb-odbc_oracle.inc.php index 222e7726d00..5d566068441 100644 --- a/lib/adodb/drivers/adodb-odbc_oracle.inc.php +++ b/lib/adodb/drivers/adodb-odbc_oracle.inc.php @@ -1,6 +1,8 @@ ADODB_odbc(); - } - - function MetaTables() + function MetaTables($ttype = false, $showSchema = false, $mask = false) { $false = false; $rs = $this->Execute($this->metaTablesSQL); @@ -107,8 +104,8 @@ class ADORecordSet_odbc_oracle extends ADORecordSet_odbc { var $databaseType = 'odbc_oracle'; - function ADORecordSet_odbc_oracle($id,$mode=false) + function __construct($id,$mode=false) { - return $this->ADORecordSet_odbc($id,$mode); + return parent::__construct($id,$mode); } } diff --git a/lib/adodb/drivers/adodb-odbtp.inc.php b/lib/adodb/drivers/adodb-odbtp.inc.php index 2209b6c1deb..a5823a4e6be 100644 --- a/lib/adodb/drivers/adodb-odbtp.inc.php +++ b/lib/adodb/drivers/adodb-odbtp.inc.php @@ -1,6 +1,8 @@ Execute("insert into adodb_seq values('$seqname',$start)"); } - function DropSequence($seqname) + function DropSequence($seqname = 'adodbseq') { if (empty($this->_dropSeqSQL)) return false; return $this->Execute(sprintf($this->_dropSeqSQL,$seqname)); @@ -475,7 +477,7 @@ class ADODB_odbtp extends ADOConnection{ return array($sql,$stmt,false); } - function PrepareSP($sql) + function PrepareSP($sql, $param = true) { if (!$this->_canPrepareSP) return $sql; // Can't prepare procedures @@ -668,14 +670,14 @@ class ADORecordSet_odbtp extends ADORecordSet { var $databaseType = 'odbtp'; var $canSeek = true; - function ADORecordSet_odbtp($queryID,$mode=false) + function __construct($queryID,$mode=false) { if ($mode === false) { global $ADODB_FETCH_MODE; $mode = $ADODB_FETCH_MODE; } $this->fetchMode = $mode; - $this->ADORecordSet($queryID); + parent::__construct($queryID); } function _initrs() @@ -791,9 +793,9 @@ class ADORecordSet_odbtp_mssql extends ADORecordSet_odbtp { var $databaseType = 'odbtp_mssql'; - function ADORecordSet_odbtp_mssql($id,$mode=false) + function __construct($id,$mode=false) { - return $this->ADORecordSet_odbtp($id,$mode); + return parent::__construct($id,$mode); } } @@ -801,9 +803,9 @@ class ADORecordSet_odbtp_access extends ADORecordSet_odbtp { var $databaseType = 'odbtp_access'; - function ADORecordSet_odbtp_access($id,$mode=false) + function __construct($id,$mode=false) { - return $this->ADORecordSet_odbtp($id,$mode); + return parent::__construct($id,$mode); } } @@ -811,9 +813,9 @@ class ADORecordSet_odbtp_vfp extends ADORecordSet_odbtp { var $databaseType = 'odbtp_vfp'; - function ADORecordSet_odbtp_vfp($id,$mode=false) + function __construct($id,$mode=false) { - return $this->ADORecordSet_odbtp($id,$mode); + return parent::__construct($id,$mode); } } @@ -821,9 +823,9 @@ class ADORecordSet_odbtp_oci8 extends ADORecordSet_odbtp { var $databaseType = 'odbtp_oci8'; - function ADORecordSet_odbtp_oci8($id,$mode=false) + function __construct($id,$mode=false) { - return $this->ADORecordSet_odbtp($id,$mode); + return parent::__construct($id,$mode); } } @@ -831,8 +833,8 @@ class ADORecordSet_odbtp_sybase extends ADORecordSet_odbtp { var $databaseType = 'odbtp_sybase'; - function ADORecordSet_odbtp_sybase($id,$mode=false) + function __construct($id,$mode=false) { - return $this->ADORecordSet_odbtp($id,$mode); + return parent::__construct($id,$mode); } } diff --git a/lib/adodb/drivers/adodb-odbtp_unicode.inc.php b/lib/adodb/drivers/adodb-odbtp_unicode.inc.php index 0db44086ed1..350f091fe2d 100644 --- a/lib/adodb/drivers/adodb-odbtp_unicode.inc.php +++ b/lib/adodb/drivers/adodb-odbtp_unicode.inc.php @@ -1,6 +1,8 @@ ADODB_odbtp(); - } } diff --git a/lib/adodb/drivers/adodb-oracle.inc.php b/lib/adodb/drivers/adodb-oracle.inc.php index a92d84ea17e..48aa91ca5ce 100644 --- a/lib/adodb/drivers/adodb-oracle.inc.php +++ b/lib/adodb/drivers/adodb-oracle.inc.php @@ -1,6 +1,8 @@ format($this->fmtDate); @@ -41,7 +43,7 @@ class ADODB_oracle extends ADOConnection { } // format and return date string in database timestamp format - function DBTimeStamp($ts) + function DBTimeStamp($ts, $isfld = false) { if (is_string($ts)) $ts = ADORecordSet::UnixTimeStamp($ts); @@ -219,7 +221,7 @@ class ADORecordset_oracle extends ADORecordSet { var $databaseType = "oracle"; var $bind = false; - function ADORecordset_oracle($queryID,$mode=false) + function __construct($queryID,$mode=false) { if ($mode === false) { @@ -303,7 +305,7 @@ class ADORecordset_oracle extends ADORecordSet { return @ora_close($this->_queryID); } - function MetaType($t,$len=-1) + function MetaType($t, $len = -1, $fieldobj = false) { if (is_object($t)) { $fieldobj = $t; diff --git a/lib/adodb/drivers/adodb-pdo.inc.php b/lib/adodb/drivers/adodb-pdo.inc.php index 4ac616440ae..759d40d7647 100644 --- a/lib/adodb/drivers/adodb-pdo.inc.php +++ b/lib/adodb/drivers/adodb-pdo.inc.php @@ -1,19 +1,24 @@ _driver->_hasdual)) $sql = "select $this->sysTimeStamp from dual"; - else $sql = "select $this->sysTimeStamp"; + if (!empty($this->_driver->_hasdual)) { + $sql = "select $this->sysTimeStamp from dual"; + } + else { + $sql = "select $this->sysTimeStamp"; + } $rs = $this->_Execute($sql); - if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields)); + if ($rs && !$rs->EOF) { + return $this->UnixTimeStamp(reset($rs->fields)); + } return false; } @@ -128,7 +135,18 @@ class ADODB_pdo extends ADOConnection { $this->dsnType = substr($argDSN,0,$at); if ($argDatabasename) { - $argDSN .= ';dbname='.$argDatabasename; + switch($this->dsnType){ + case 'sqlsrv': + $argDSN .= ';database='.$argDatabasename; + break; + case 'mssql': + case 'mysql': + case 'oci': + case 'pgsql': + case 'sqlite': + default: + $argDSN .= ';dbname='.$argDatabasename; + } } try { $this->_connectionID = new PDO($argDSN, $argUsername, $argPassword); @@ -142,10 +160,16 @@ class ADODB_pdo extends ADOConnection { if ($this->_connectionID) { switch(ADODB_ASSOC_CASE){ - case 0: $m = PDO::CASE_LOWER; break; - case 1: $m = PDO::CASE_UPPER; break; - default: - case 2: $m = PDO::CASE_NATURAL; break; + case ADODB_ASSOC_CASE_LOWER: + $m = PDO::CASE_LOWER; + break; + case ADODB_ASSOC_CASE_UPPER: + $m = PDO::CASE_UPPER; + break; + default: + case ADODB_ASSOC_CASE_NATIVE: + $m = PDO::CASE_NATURAL; + break; } //$this->_connectionID->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_SILENT ); @@ -154,18 +178,21 @@ class ADODB_pdo extends ADOConnection { $class = 'ADODB_pdo_'.$this->dsnType; //$this->_connectionID->setAttribute(PDO::ATTR_AUTOCOMMIT,true); switch($this->dsnType) { - case 'oci': - case 'mysql': - case 'pgsql': - case 'mssql': - case 'sqlite': - include_once(ADODB_DIR.'/drivers/adodb-pdo_'.$this->dsnType.'.inc.php'); - break; + case 'mssql': + case 'mysql': + case 'oci': + case 'pgsql': + case 'sqlite': + case 'sqlsrv': + include_once(ADODB_DIR.'/drivers/adodb-pdo_'.$this->dsnType.'.inc.php'); + break; } - if (class_exists($class)) + if (class_exists($class)) { $this->_driver = new $class(); - else + } + else { $this->_driver = new ADODB_pdo_base(); + } $this->_driver->_connectionID = $this->_connectionID; $this->_UpdatePDO(); @@ -178,10 +205,13 @@ class ADODB_pdo extends ADOConnection { function Concat() { $args = func_get_args(); - if(method_exists($this->_driver, 'Concat')) + if(method_exists($this->_driver, 'Concat')) { return call_user_func_array(array($this->_driver, 'Concat'), $args); + } - if (PHP_VERSION >= 5.3) return call_user_func_array('parent::Concat', $args); + if (PHP_VERSION >= 5.3) { + return call_user_func_array('parent::Concat', $args); + } return call_user_func_array(array($this,'parent::Concat'), $args); } @@ -198,7 +228,7 @@ class ADODB_pdo extends ADOConnection { { $save = $this->_driver->fetchMode; $this->_driver->fetchMode = $this->fetchMode; - $this->_driver->debug = $this->debug; + $this->_driver->debug = $this->debug; $ret = $this->_driver->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache); $this->_driver->fetchMode = $save; return $ret; @@ -223,76 +253,123 @@ class ADODB_pdo extends ADOConnection { function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false) { $obj = $stmt[1]; - if ($type) $obj->bindParam($name,$var,$type,$maxLen); - else $obj->bindParam($name, $var); + if ($type) { + $obj->bindParam($name, $var, $type, $maxLen); + } + else { + $obj->bindParam($name, $var); + } } function OffsetDate($dayFraction,$date=false) - { - return $this->_driver->OffsetDate($dayFraction,$date); - } + { + return $this->_driver->OffsetDate($dayFraction,$date); + } function ErrorMsg() { - if ($this->_errormsg !== false) return $this->_errormsg; - if (!empty($this->_stmt)) $arr = $this->_stmt->errorInfo(); - else if (!empty($this->_connectionID)) $arr = $this->_connectionID->errorInfo(); - else return 'No Connection Established'; - + if ($this->_errormsg !== false) { + return $this->_errormsg; + } + if (!empty($this->_stmt)) { + $arr = $this->_stmt->errorInfo(); + } + else if (!empty($this->_connectionID)) { + $arr = $this->_connectionID->errorInfo(); + } + else { + return 'No Connection Established'; + } if ($arr) { - if (sizeof($arr)<2) return ''; - if ((integer)$arr[0]) return $arr[2]; - else return ''; - } else return '-1'; + if (sizeof($arr)<2) { + return ''; + } + if ((integer)$arr[0]) { + return $arr[2]; + } + else { + return ''; + } + } + else { + return '-1'; + } } function ErrorNo() { - if ($this->_errorno !== false) return $this->_errorno; - if (!empty($this->_stmt)) $err = $this->_stmt->errorCode(); + if ($this->_errorno !== false) { + return $this->_errorno; + } + if (!empty($this->_stmt)) { + $err = $this->_stmt->errorCode(); + } else if (!empty($this->_connectionID)) { $arr = $this->_connectionID->errorInfo(); - if (isset($arr[0])) $err = $arr[0]; - else $err = -1; - } else + if (isset($arr[0])) { + $err = $arr[0]; + } + else { + $err = -1; + } + } else { return 0; + } - if ($err == '00000') return 0; // allows empty check + if ($err == '00000') { + return 0; // allows empty check + } return $err; } function SetTransactionMode($transaction_mode) { - if(method_exists($this->_driver, 'SetTransactionMode')) + if(method_exists($this->_driver, 'SetTransactionMode')) { return $this->_driver->SetTransactionMode($transaction_mode); + } return parent::SetTransactionMode($seqname); } function BeginTrans() { - if(method_exists($this->_driver, 'BeginTrans')) + if(method_exists($this->_driver, 'BeginTrans')) { return $this->_driver->BeginTrans(); + } - if (!$this->hasTransactions) return false; - if ($this->transOff) return true; + if (!$this->hasTransactions) { + return false; + } + if ($this->transOff) { + return true; + } $this->transCnt += 1; $this->_autocommit = false; $this->_connectionID->setAttribute(PDO::ATTR_AUTOCOMMIT,false); + return $this->_connectionID->beginTransaction(); } function CommitTrans($ok=true) { - if(method_exists($this->_driver, 'CommitTrans')) + if(method_exists($this->_driver, 'CommitTrans')) { return $this->_driver->CommitTrans($ok); + } - if (!$this->hasTransactions) return false; - if ($this->transOff) return true; - if (!$ok) return $this->RollbackTrans(); - if ($this->transCnt) $this->transCnt -= 1; + if (!$this->hasTransactions) { + return false; + } + if ($this->transOff) { + return true; + } + if (!$ok) { + return $this->RollbackTrans(); + } + if ($this->transCnt) { + $this->transCnt -= 1; + } $this->_autocommit = true; $ret = $this->_connectionID->commit(); @@ -302,12 +379,19 @@ class ADODB_pdo extends ADOConnection { function RollbackTrans() { - if(method_exists($this->_driver, 'RollbackTrans')) + if(method_exists($this->_driver, 'RollbackTrans')) { return $this->_driver->RollbackTrans(); + } - if (!$this->hasTransactions) return false; - if ($this->transOff) return true; - if ($this->transCnt) $this->transCnt -= 1; + if (!$this->hasTransactions) { + return false; + } + if ($this->transOff) { + return true; + } + if ($this->transCnt) { + $this->transCnt -= 1; + } $this->_autocommit = true; $ret = $this->_connectionID->rollback(); @@ -318,7 +402,9 @@ class ADODB_pdo extends ADOConnection { function Prepare($sql) { $this->_stmt = $this->_connectionID->prepare($sql); - if ($this->_stmt) return array($sql,$this->_stmt); + if ($this->_stmt) { + return array($sql,$this->_stmt); + } return false; } @@ -326,31 +412,36 @@ class ADODB_pdo extends ADOConnection { function PrepareStmt($sql) { $stmt = $this->_connectionID->prepare($sql); - if (!$stmt) return false; + if (!$stmt) { + return false; + } $obj = new ADOPDOStatement($stmt,$this); return $obj; } function CreateSequence($seqname='adodbseq',$startID=1) { - if(method_exists($this->_driver, 'CreateSequence')) + if(method_exists($this->_driver, 'CreateSequence')) { return $this->_driver->CreateSequence($seqname, $startID); + } return parent::CreateSequence($seqname, $startID); } function DropSequence($seqname='adodbseq') { - if(method_exists($this->_driver, 'DropSequence')) + if(method_exists($this->_driver, 'DropSequence')) { return $this->_driver->DropSequence($seqname); + } return parent::DropSequence($seqname); } function GenID($seqname='adodbseq',$startID=1) { - if(method_exists($this->_driver, 'GenID')) + if(method_exists($this->_driver, 'GenID')) { return $this->_driver->GenID($seqname, $startID); + } return parent::GenID($seqname, $startID); } @@ -368,8 +459,12 @@ class ADODB_pdo extends ADOConnection { #var_dump($this->_bindInputArray); if ($stmt) { $this->_driver->debug = $this->debug; - if ($inputarr) $ok = $stmt->execute($inputarr); - else $ok = $stmt->execute(); + if ($inputarr) { + $ok = $stmt->execute($inputarr); + } + else { + $ok = $stmt->execute(); + } } @@ -437,12 +532,12 @@ class ADODB_pdo_base extends ADODB_pdo { return $ret; } - function MetaTables() + function MetaTables($ttype=false,$showSchema=false,$mask=false) { return false; } - function MetaColumns() + function MetaColumns($table,$normalize=true) { return false; } @@ -455,7 +550,7 @@ class ADOPDOStatement { var $_stmt; var $_connectionID; - function ADOPDOStatement($stmt,$connection) + function __construct($stmt,$connection) { $this->_stmt = $stmt; $this->_connectionID = $connection; @@ -472,8 +567,12 @@ class ADOPDOStatement { function InParameter(&$var,$name,$maxLen=4000,$type=false) { - if ($type) $this->_stmt->bindParam($name,$var,$type,$maxLen); - else $this->_stmt->bindParam($name, $var); + if ($type) { + $this->_stmt->bindParam($name,$var,$type,$maxLen); + } + else { + $this->_stmt->bindParam($name, $var); + } } function Affected_Rows() @@ -483,13 +582,23 @@ class ADOPDOStatement { function ErrorMsg() { - if ($this->_stmt) $arr = $this->_stmt->errorInfo(); - else $arr = $this->_connectionID->errorInfo(); + if ($this->_stmt) { + $arr = $this->_stmt->errorInfo(); + } + else { + $arr = $this->_connectionID->errorInfo(); + } if (is_array($arr)) { - if ((integer) $arr[0] && isset($arr[2])) return $arr[2]; - else return ''; - } else return '-1'; + if ((integer) $arr[0] && isset($arr[2])) { + return $arr[2]; + } + else { + return ''; + } + } else { + return '-1'; + } } function NumCols() @@ -499,13 +608,17 @@ class ADOPDOStatement { function ErrorNo() { - if ($this->_stmt) return $this->_stmt->errorCode(); - else return $this->_connectionID->errorInfo(); + if ($this->_stmt) { + return $this->_stmt->errorCode(); + } + else { + return $this->_connectionID->errorInfo(); + } } } /*-------------------------------------------------------------------------------------- - Class Name: Recordset + Class Name: Recordset --------------------------------------------------------------------------------------*/ class ADORecordSet_pdo extends ADORecordSet { @@ -514,7 +627,7 @@ class ADORecordSet_pdo extends ADORecordSet { var $databaseType = "pdo"; var $dataProvider = "pdo"; - function ADORecordSet_pdo($id,$mode=false) + function __construct($id,$mode=false) { if ($mode === false) { global $ADODB_FETCH_MODE; @@ -531,15 +644,19 @@ class ADORecordSet_pdo extends ADORecordSet { $this->fetchMode = $mode; $this->_queryID = $id; - $this->ADORecordSet($id); + parent::__construct($id); } function Init() { - if ($this->_inited) return; + if ($this->_inited) { + return; + } $this->_inited = true; - if ($this->_queryID) @$this->_initrs(); + if ($this->_queryID) { + @$this->_initrs(); + } else { $this->_numOfRows = 0; $this->_numOfFields = 0; @@ -559,7 +676,9 @@ class ADORecordSet_pdo extends ADORecordSet { global $ADODB_COUNTRECS; $this->_numOfRows = ($ADODB_COUNTRECS) ? @$this->_queryID->rowCount() : -1; - if (!$this->_numOfRows) $this->_numOfRows = -1; + if (!$this->_numOfRows) { + $this->_numOfRows = -1; + } $this->_numOfFields = $this->_queryID->columnCount(); } @@ -580,13 +699,23 @@ class ADORecordSet_pdo extends ADORecordSet { } //adodb_pr($arr); $o->name = $arr['name']; - if (isset($arr['native_type']) && $arr['native_type'] <> "null") $o->type = $arr['native_type']; - else $o->type = adodb_pdo_type($arr['pdo_type']); + if (isset($arr['native_type']) && $arr['native_type'] <> "null") { + $o->type = $arr['native_type']; + } + else { + $o->type = adodb_pdo_type($arr['pdo_type']); + } $o->max_length = $arr['len']; $o->precision = $arr['precision']; - if (ADODB_ASSOC_CASE == 0) $o->name = strtolower($o->name); - else if (ADODB_ASSOC_CASE == 1) $o->name = strtoupper($o->name); + switch(ADODB_ASSOC_CASE) { + case ADODB_ASSOC_CASE_LOWER: + $o->name = strtolower($o->name); + break; + case ADODB_ASSOC_CASE_UPPER: + $o->name = strtoupper($o->name); + break; + } return $o; } @@ -597,7 +726,9 @@ class ADORecordSet_pdo extends ADORecordSet { function _fetch() { - if (!$this->_queryID) return false; + if (!$this->_queryID) { + return false; + } $this->fields = $this->_queryID->fetch($this->fetchMode); return !empty($this->fields); @@ -610,7 +741,9 @@ class ADORecordSet_pdo extends ADORecordSet { function Fields($colname) { - if ($this->adodbFetchMode != ADODB_FETCH_NUM) return @$this->fields[$colname]; + if ($this->adodbFetchMode != ADODB_FETCH_NUM) { + return @$this->fields[$colname]; + } if (!$this->bind) { $this->bind = array(); @@ -619,7 +752,7 @@ class ADORecordSet_pdo extends ADORecordSet { $this->bind[strtoupper($o->name)] = $i; } } - return $this->fields[$this->bind[strtoupper($colname)]]; + return $this->fields[$this->bind[strtoupper($colname)]]; } } diff --git a/lib/adodb/drivers/adodb-pdo_mssql.inc.php b/lib/adodb/drivers/adodb-pdo_mssql.inc.php index 0b1ba8b2c21..111d465ef70 100644 --- a/lib/adodb/drivers/adodb-pdo_mssql.inc.php +++ b/lib/adodb/drivers/adodb-pdo_mssql.inc.php @@ -2,7 +2,9 @@ /* -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. diff --git a/lib/adodb/drivers/adodb-pdo_mysql.inc.php b/lib/adodb/drivers/adodb-pdo_mysql.inc.php index 524d1492e8e..d7ddba5cddd 100644 --- a/lib/adodb/drivers/adodb-pdo_mysql.inc.php +++ b/lib/adodb/drivers/adodb-pdo_mysql.inc.php @@ -1,8 +1,8 @@ hasTransactions = false; #$parentDriver->_bindInputArray = false; $parentDriver->hasInsertID = true; - $parentDriver->_connectionID->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,true); + $parentDriver->_connectionID->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true); } - // dayFraction is a day in floating point - function OffsetDate($dayFraction,$date=false) + // dayFraction is a day in floating point + function OffsetDate($dayFraction, $date=false) { - if (!$date) $date = $this->sysDate; + if (!$date) { + $date = $this->sysDate; + } $fraction = $dayFraction * 24 * 3600; - return $date . ' + INTERVAL ' . $fraction.' SECOND'; - + return $date . ' + INTERVAL ' . $fraction . ' SECOND'; // return "from_unixtime(unix_timestamp($date)+$fraction)"; } function Concat() { - $s = ""; + $s = ''; $arr = func_get_args(); // suggestion by andrew005#mnogo.ru - $s = implode(',',$arr); - if (strlen($s) > 0) return "CONCAT($s)"; return ''; + $s = implode(',', $arr); + if (strlen($s) > 0) { + return "CONCAT($s)"; + } + return ''; } function ServerInfo() { - $arr['description'] = ADOConnection::GetOne("select version()"); + $arr['description'] = ADOConnection::GetOne('select version()'); $arr['version'] = ADOConnection::_findvers($arr['description']); return $arr; } - function MetaTables($ttype=false,$showSchema=false,$mask=false) + function MetaTables($ttype=false, $showSchema=false, $mask=false) { $save = $this->metaTablesSQL; if ($showSchema && is_string($showSchema)) { @@ -69,26 +77,28 @@ class ADODB_pdo_mysql extends ADODB_pdo { $mask = $this->qstr($mask); $this->metaTablesSQL .= " like $mask"; } - $ret = ADOConnection::MetaTables($ttype,$showSchema); + $ret = ADOConnection::MetaTables($ttype, $showSchema); $this->metaTablesSQL = $save; return $ret; } - function SetTransactionMode( $transaction_mode ) + function SetTransactionMode($transaction_mode) { $this->_transmode = $transaction_mode; if (empty($transaction_mode)) { $this->Execute('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ'); return; } - if (!stristr($transaction_mode,'isolation')) $transaction_mode = 'ISOLATION LEVEL '.$transaction_mode; - $this->Execute("SET SESSION TRANSACTION ".$transaction_mode); + if (!stristr($transaction_mode, 'isolation')) { + $transaction_mode = 'ISOLATION LEVEL ' . $transaction_mode; + } + $this->Execute('SET SESSION TRANSACTION ' . $transaction_mode); } - function MetaColumns($table,$normalize=true) + function MetaColumns($table, $normalize=true) { - $this->_findschema($table,$schema); + $this->_findschema($table, $schema); if ($schema) { $dbName = $this->database; $this->SelectDB($schema); @@ -97,14 +107,18 @@ class ADODB_pdo_mysql extends ADODB_pdo { $save = $ADODB_FETCH_MODE; $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); - $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table)); + if ($this->fetchMode !== false) { + $savem = $this->SetFetchMode(false); + } + $rs = $this->Execute(sprintf($this->metaColumnsSQL, $table)); if ($schema) { $this->SelectDB($dbName); } - if (isset($savem)) $this->SetFetchMode($savem); + if (isset($savem)) { + $this->SetFetchMode($savem); + } $ADODB_FETCH_MODE = $save; if (!is_object($rs)) { $false = false; @@ -119,18 +133,18 @@ class ADODB_pdo_mysql extends ADODB_pdo { // split type into type(length): $fld->scale = null; - if (preg_match("/^(.+)\((\d+),(\d+)/", $type, $query_array)) { + if (preg_match('/^(.+)\((\d+),(\d+)/', $type, $query_array)) { $fld->type = $query_array[1]; $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1; $fld->scale = is_numeric($query_array[3]) ? $query_array[3] : -1; - } elseif (preg_match("/^(.+)\((\d+)/", $type, $query_array)) { + } elseif (preg_match('/^(.+)\((\d+)/', $type, $query_array)) { $fld->type = $query_array[1]; $fld->max_length = is_numeric($query_array[2]) ? $query_array[2] : -1; - } elseif (preg_match("/^(enum)\((.*)\)$/i", $type, $query_array)) { + } elseif (preg_match('/^(enum)\((.*)\)$/i', $type, $query_array)) { $fld->type = $query_array[1]; - $arr = explode(",",$query_array[2]); + $arr = explode(',', $query_array[2]); $fld->enums = $arr; - $zlen = max(array_map("strlen",$arr)) - 2; // PHP >= 4.0.6 + $zlen = max(array_map('strlen', $arr)) - 2; // PHP >= 4.0.6 $fld->max_length = ($zlen > 0) ? $zlen : 1; } else { $fld->type = $type; @@ -139,8 +153,8 @@ class ADODB_pdo_mysql extends ADODB_pdo { $fld->not_null = ($rs->fields[2] != 'YES'); $fld->primary_key = ($rs->fields[3] == 'PRI'); $fld->auto_increment = (strpos($rs->fields[5], 'auto_increment') !== false); - $fld->binary = (strpos($type,'blob') !== false); - $fld->unsigned = (strpos($type,'unsigned') !== false); + $fld->binary = (strpos($type, 'blob') !== false); + $fld->unsigned = (strpos($type, 'unsigned') !== false); if (!$fld->binary) { $d = $rs->fields[4]; @@ -157,25 +171,130 @@ class ADODB_pdo_mysql extends ADODB_pdo { } else { $retarr[strtoupper($fld->name)] = $fld; } - $rs->MoveNext(); - } + $rs->MoveNext(); + } - $rs->Close(); - return $retarr; + $rs->Close(); + return $retarr; } + // returns true or false + function SelectDB($dbName) + { + $this->database = $dbName; + $this->databaseName = $dbName; # obsolete, retained for compat with older adodb versions + $try = $this->Execute('use ' . $dbName); + return ($try !== false); + } // parameters use PostgreSQL convention, not MySQL - function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs=0) + function SelectLimit($sql, $nrows=-1, $offset=-1, $inputarr=false, $secs=0) { $offsetStr =($offset>=0) ? "$offset," : ''; // jason judge, see http://phplens.com/lens/lensforum/msgs.php?id=9220 - if ($nrows < 0) $nrows = '18446744073709551615'; + if ($nrows < 0) { + $nrows = '18446744073709551615'; + } - if ($secs) - $rs = $this->CacheExecute($secs,$sql." LIMIT $offsetStr$nrows",$inputarr); - else - $rs = $this->Execute($sql." LIMIT $offsetStr$nrows",$inputarr); + if ($secs) { + $rs = $this->CacheExecute($secs, $sql . " LIMIT $offsetStr$nrows", $inputarr); + } else { + $rs = $this->Execute($sql . " LIMIT $offsetStr$nrows", $inputarr); + } return $rs; } + + function SQLDate($fmt, $col=false) + { + if (!$col) { + $col = $this->sysTimeStamp; + } + $s = 'DATE_FORMAT(' . $col . ",'"; + $concat = false; + $len = strlen($fmt); + for ($i=0; $i < $len; $i++) { + $ch = $fmt[$i]; + switch($ch) { + + default: + if ($ch == '\\') { + $i++; + $ch = substr($fmt, $i, 1); + } + // FALL THROUGH + case '-': + case '/': + $s .= $ch; + break; + + case 'Y': + case 'y': + $s .= '%Y'; + break; + + case 'M': + $s .= '%b'; + break; + + case 'm': + $s .= '%m'; + break; + + case 'D': + case 'd': + $s .= '%d'; + break; + + case 'Q': + case 'q': + $s .= "'),Quarter($col)"; + + if ($len > $i+1) { + $s .= ",DATE_FORMAT($col,'"; + } else { + $s .= ",('"; + } + $concat = true; + break; + + case 'H': + $s .= '%H'; + break; + + case 'h': + $s .= '%I'; + break; + + case 'i': + $s .= '%i'; + break; + + case 's': + $s .= '%s'; + break; + + case 'a': + case 'A': + $s .= '%p'; + break; + + case 'w': + $s .= '%w'; + break; + + case 'W': + $s .= '%U'; + break; + + case 'l': + $s .= '%W'; + break; + } + } + $s .= "')"; + if ($concat) { + $s = "CONCAT($s)"; + } + return $s; + } } diff --git a/lib/adodb/drivers/adodb-pdo_oci.inc.php b/lib/adodb/drivers/adodb-pdo_oci.inc.php index 2ff56f52a34..40beed32a7d 100644 --- a/lib/adodb/drivers/adodb-pdo_oci.inc.php +++ b/lib/adodb/drivers/adodb-pdo_oci.inc.php @@ -2,7 +2,9 @@ /* -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. diff --git a/lib/adodb/drivers/adodb-pdo_pgsql.inc.php b/lib/adodb/drivers/adodb-pdo_pgsql.inc.php index 671ceabbbed..8b647c40eb3 100644 --- a/lib/adodb/drivers/adodb-pdo_pgsql.inc.php +++ b/lib/adodb/drivers/adodb-pdo_pgsql.inc.php @@ -1,7 +1,9 @@ hasTransactions = true; + $parentDriver->_bindInputArray = true; + $parentDriver->hasInsertID = true; + $parentDriver->fmtTimeStamp = "'Y-m-d H:i:s'"; + $parentDriver->fmtDate = "'Y-m-d'"; + } + + function BeginTrans() + { + $returnval = parent::BeginTrans(); + return $returnval; + } + + function MetaColumns($table, $normalize = true) + { + return false; + } + + function MetaTables($ttype = false, $showSchema = false, $mask = false) + { + return false; + } + + function SelectLimit($sql, $nrows = -1, $offset = -1, $inputarr = false, $secs2cache = 0) + { + $ret = ADOConnection::SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache); + return $ret; + } + + function ServerInfo() + { + return ADOConnection::ServerInfo(); + } + +} diff --git a/lib/adodb/drivers/adodb-postgres.inc.php b/lib/adodb/drivers/adodb-postgres.inc.php index d3831cd4d7e..3ebbbaa5f68 100644 --- a/lib/adodb/drivers/adodb-postgres.inc.php +++ b/lib/adodb/drivers/adodb-postgres.inc.php @@ -1,6 +1,8 @@ _connectionID, "SELECT last_value FROM ${tablename}_${fieldname}_seq"); + $result=pg_query($this->_connectionID, 'SELECT last_value FROM '. $tablename .'_'. $fieldname .'_seq'); if ($result) { $arr = @pg_fetch_row($result,0); - pg_freeresult($result); + pg_free_result($result); if (isset($arr[0])) return $arr[0]; } return false; } -/* Warning from http://www.php.net/manual/function.pg-getlastoid.php: -Using a OID as a unique identifier is not generally wise. -Unless you are very careful, you might end up with a tuple having -a different OID if a database must be reloaded. */ + /** + * Warning from http://www.php.net/manual/function.pg-getlastoid.php: + * Using a OID as a unique identifier is not generally wise. + * Unless you are very careful, you might end up with a tuple having + * a different OID if a database must be reloaded. + */ function _insertid($table,$column) { if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false; @@ -166,21 +170,21 @@ a different OID if a database must be reloaded. */ return empty($table) || empty($column) ? $oid : $this->GetOne("SELECT $column FROM $table WHERE oid=".(int)$oid); } -// I get this error with PHP before 4.0.6 - jlim -// Warning: This compilation does not support pg_cmdtuples() in adodb-postgres.inc.php on line 44 function _affectedrows() { if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false; - return pg_cmdtuples($this->_resultid); + return pg_affected_rows($this->_resultid); } - // returns true/false + /** + * @return true/false + */ function BeginTrans() { if ($this->transOff) return true; $this->transCnt += 1; - return @pg_Exec($this->_connectionID, "begin ".$this->_transmode); + return pg_query($this->_connectionID, 'begin '.$this->_transmode); } function RowLock($tables,$where,$col='1 as adodbignore') @@ -196,7 +200,7 @@ a different OID if a database must be reloaded. */ if (!$ok) return $this->RollbackTrans(); $this->transCnt -= 1; - return @pg_Exec($this->_connectionID, "commit"); + return pg_query($this->_connectionID, 'commit'); } // returns true/false @@ -204,7 +208,7 @@ a different OID if a database must be reloaded. */ { if ($this->transOff) return true; $this->transCnt -= 1; - return @pg_Exec($this->_connectionID, "rollback"); + return pg_query($this->_connectionID, 'rollback'); } function MetaTables($ttype=false,$showSchema=false,$mask=false) @@ -354,7 +358,7 @@ a different OID if a database must be reloaded. */ */ function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') { - pg_exec ($this->_connectionID, "begin"); + pg_query($this->_connectionID, 'begin'); $fd = fopen($path,'r'); $contents = fread($fd,filesize($path)); @@ -366,7 +370,7 @@ a different OID if a database must be reloaded. */ pg_lo_close($handle); // $oid = pg_lo_import ($path); - pg_exec($this->_connectionID, "commit"); + pg_query($this->_connectionID, 'commit'); $rs = ADOConnection::UpdateBlob($table,$column,$oid,$where,$blobtype); $rez = !empty($rs); return $rez; @@ -382,9 +386,9 @@ a different OID if a database must be reloaded. */ */ function BlobDelete( $blob ) { - pg_exec ($this->_connectionID, "begin"); + pg_query($this->_connectionID, 'begin'); $result = @pg_lo_unlink($blob); - pg_exec ($this->_connectionID, "commit"); + pg_query($this->_connectionID, 'commit'); return( $result ); } @@ -413,16 +417,16 @@ a different OID if a database must be reloaded. */ { if (!$this->GuessOID($blob)) return $blob; - if ($hastrans) @pg_exec($this->_connectionID,"begin"); - $fd = @pg_lo_open($this->_connectionID,$blob,"r"); + if ($hastrans) pg_query($this->_connectionID,'begin'); + $fd = @pg_lo_open($this->_connectionID,$blob,'r'); if ($fd === false) { - if ($hastrans) @pg_exec($this->_connectionID,"commit"); + if ($hastrans) pg_query($this->_connectionID,'commit'); return $blob; } if (!$maxsize) $maxsize = $this->maxblobsize; - $realblob = @pg_loread($fd,$maxsize); + $realblob = @pg_lo_read($fd,$maxsize); @pg_loclose($fd); - if ($hastrans) @pg_exec($this->_connectionID,"commit"); + if ($hastrans) pg_query($this->_connectionID,'commit'); return $realblob; } @@ -470,13 +474,28 @@ a different OID if a database must be reloaded. */ #return "($date+interval'$dayFraction days')"; } + /** + * Generate the SQL to retrieve MetaColumns data + * @param string $table Table name + * @param string $schema Schema name (can be blank) + * @return string SQL statement to execute + */ + protected function _generateMetaColumnsSQL($table, $schema) + { + if ($schema) { + return sprintf($this->metaColumnsSQL1, $table, $table, $schema); + } + else { + return sprintf($this->metaColumnsSQL, $table, $table, $schema); + } + } // for schema support, pass in the $table param "$schema.$tabname". // converts field names to lowercase, $upper is ignored // see http://phplens.com/lens/lensforum/msgs.php?id=14018 for more info function MetaColumns($table,$normalize=true) { - global $ADODB_FETCH_MODE; + global $ADODB_FETCH_MODE; $schema = false; $false = false; @@ -488,8 +507,7 @@ a different OID if a database must be reloaded. */ $ADODB_FETCH_MODE = ADODB_FETCH_NUM; if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); - if ($schema) $rs = $this->Execute(sprintf($this->metaColumnsSQL1,$table,$table,$schema)); - else $rs = $this->Execute(sprintf($this->metaColumnsSQL,$table,$table,$table)); + $rs = $this->Execute($this->_generateMetaColumnsSQL($table, $schema)); if (isset($savem)) $this->SetFetchMode($savem); $ADODB_FETCH_MODE = $save; @@ -721,7 +739,7 @@ a different OID if a database must be reloaded. */ # PHP does not handle 'hex' properly ('x74657374' is returned as 't657374') # https://bugs.php.net/bug.php?id=59831 states this is in fact not a bug, # so we manually set bytea_output - if (version_compare($info['version'], '9.0', '>=')) { + if ( !empty($this->connection->noBlobs) && version_compare($info['version'], '9.0', '>=')) { $this->Execute('set bytea_output=escape'); } @@ -759,9 +777,6 @@ a different OID if a database must be reloaded. */ with plan = 1.51861286163 secs no plan = 1.26903700829 secs - - - */ $plan = 'P'.md5($sql); @@ -779,7 +794,7 @@ a different OID if a database must be reloaded. */ else $exsql = "EXECUTE $plan"; - $rez = @pg_exec($this->_connectionID,$exsql); + $rez = @pg_execute($this->_connectionID,$exsql); if (!$rez) { # Perhaps plan does not exist? Prepare/compile plan. $params = ''; @@ -803,19 +818,19 @@ a different OID if a database must be reloaded. */ } $s = "PREPARE $plan ($params) AS ".substr($sql,0,strlen($sql)-2); //adodb_pr($s); - $rez = pg_exec($this->_connectionID,$s); + $rez = pg_execute($this->_connectionID,$s); //echo $this->ErrorMsg(); } if ($rez) - $rez = pg_exec($this->_connectionID,$exsql); + $rez = pg_execute($this->_connectionID,$exsql); } else { //adodb_backtrace(); - $rez = pg_exec($this->_connectionID,$sql); + $rez = pg_query($this->_connectionID,$sql); } // check if no data returned, then no need to create real recordset - if ($rez && pg_numfields($rez) <= 0) { + if ($rez && pg_num_fields($rez) <= 0) { if (is_resource($this->_resultid) && get_resource_type($this->_resultid) === 'pgsql result') { - pg_freeresult($this->_resultid); + pg_free_result($this->_resultid); } $this->_resultid = $rez; return true; @@ -864,7 +879,7 @@ a different OID if a database must be reloaded. */ { if ($this->transCnt) $this->RollbackTrans(); if ($this->_resultid) { - @pg_freeresult($this->_resultid); + @pg_free_result($this->_resultid); $this->_resultid = false; } @pg_close($this->_connectionID); @@ -919,12 +934,14 @@ class ADORecordSet_postgres64 extends ADORecordSet{ $this->adodbFetchMode = $mode; // Parent's constructor - $this->ADORecordSet($queryID); + parent::__construct($queryID); } - function GetRowAssoc($upper=true) + function GetRowAssoc($upper = ADODB_ASSOC_CASE) { - if ($this->fetchMode == PGSQL_ASSOC && !$upper) return $this->fields; + if ($this->fetchMode == PGSQL_ASSOC && $upper == ADODB_ASSOC_CASE_LOWER) { + return $this->fields; + } $row = ADORecordSet::GetRowAssoc($upper); return $row; } @@ -934,15 +951,15 @@ class ADORecordSet_postgres64 extends ADORecordSet{ { global $ADODB_COUNTRECS; $qid = $this->_queryID; - $this->_numOfRows = ($ADODB_COUNTRECS)? @pg_numrows($qid):-1; - $this->_numOfFields = @pg_numfields($qid); + $this->_numOfRows = ($ADODB_COUNTRECS)? @pg_num_rows($qid):-1; + $this->_numOfFields = @pg_num_fields($qid); // cache types for blob decode check - // apparently pg_fieldtype actually performs an sql query on the database to get the type. + // apparently pg_field_type actually performs an sql query on the database to get the type. if (empty($this->connection->noBlobs)) for ($i=0, $max = $this->_numOfFields; $i < $max; $i++) { - if (pg_fieldtype($qid,$i) == 'bytea') { - $this->_blobArr[$i] = pg_fieldname($qid,$i); + if (pg_field_type($qid,$i) == 'bytea') { + $this->_blobArr[$i] = pg_field_name($qid,$i); } } } @@ -967,8 +984,8 @@ class ADORecordSet_postgres64 extends ADORecordSet{ // offsets begin at 0 $o= new ADOFieldObject(); - $o->name = @pg_fieldname($this->_queryID,$off); - $o->type = @pg_fieldtype($this->_queryID,$off); + $o->name = @pg_field_name($this->_queryID,$off); + $o->type = @pg_field_type($this->_queryID,$off); $o->max_length = @pg_fieldsize($this->_queryID,$off); return $o; } @@ -1032,7 +1049,7 @@ class ADORecordSet_postgres64 extends ADORecordSet{ function _close() { - return @pg_freeresult($this->_queryID); + return @pg_free_result($this->_queryID); } function MetaType($t,$len=-1,$fieldobj=false) diff --git a/lib/adodb/drivers/adodb-postgres7.inc.php b/lib/adodb/drivers/adodb-postgres7.inc.php index 740650282a9..1b218393da5 100644 --- a/lib/adodb/drivers/adodb-postgres7.inc.php +++ b/lib/adodb/drivers/adodb-postgres7.inc.php @@ -1,6 +1,8 @@ 0 AND - a.attrelid = c.oid - ORDER BY a.attnum"; - - // used when schema defined + + // Richard 3/18/2012 - Modified SQL to return SERIAL type correctly AS old driver no longer return SERIAL as data type. + var $metaColumnsSQL = " + SELECT + a.attname, + CASE + WHEN x.sequence_name != '' + THEN 'SERIAL' + ELSE t.typname + END AS typname, + a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum + FROM + pg_class c, + pg_attribute a + JOIN pg_type t ON a.atttypid = t.oid + LEFT JOIN ( + SELECT + c.relname as sequence_name, + c1.relname as related_table, + a.attname as related_column + FROM pg_class c + JOIN pg_depend d ON d.objid = c.oid + LEFT JOIN pg_class c1 ON d.refobjid = c1.oid + LEFT JOIN pg_attribute a ON (d.refobjid, d.refobjsubid) = (a.attrelid, a.attnum) + WHERE c.relkind = 'S' AND c1.relname = '%s' + ) x ON x.related_column= a.attname + WHERE + c.relkind in ('r','v') + AND (c.relname='%s' or c.relname = lower('%s')) + AND a.attname not like '....%%' + AND a.attnum > 0 + AND a.attrelid = c.oid + ORDER BY + a.attnum"; + + // used when schema defined var $metaColumnsSQL1 = " - SELECT a.attname, - CASE - WHEN x.sequence_name != '' THEN 'SERIAL' - ELSE t.typname - END AS typname, - a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum - FROM pg_class c, pg_namespace n, pg_attribute a - JOIN pg_type t ON a.atttypid = t.oid - LEFT JOIN - (SELECT c.relname as sequence_name, - c1.relname as related_table, - a.attname as related_column - FROM pg_class c - JOIN pg_depend d ON d.objid = c.oid - LEFT JOIN pg_class c1 ON d.refobjid = c1.oid - LEFT JOIN pg_attribute a ON (d.refobjid, d.refobjsubid) = (a.attrelid, a.attnum) - WHERE c.relkind = 'S' AND c1.relname = '%s') x - ON x.related_column= a.attname - WHERE c.relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s')) - AND c.relnamespace=n.oid and n.nspname='%s' - AND a.attname not like '....%%' AND a.attnum > 0 - AND a.atttypid = t.oid AND a.attrelid = c.oid - ORDER BY a.attnum"; + SELECT + a.attname, + CASE + WHEN x.sequence_name != '' + THEN 'SERIAL' + ELSE t.typname + END AS typname, + a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum + FROM + pg_class c, + pg_namespace n, + pg_attribute a + JOIN pg_type t ON a.atttypid = t.oid + LEFT JOIN ( + SELECT + c.relname as sequence_name, + c1.relname as related_table, + a.attname as related_column + FROM pg_class c + JOIN pg_depend d ON d.objid = c.oid + LEFT JOIN pg_class c1 ON d.refobjid = c1.oid + LEFT JOIN pg_attribute a ON (d.refobjid, d.refobjsubid) = (a.attrelid, a.attnum) + WHERE c.relkind = 'S' AND c1.relname = '%s' + ) x ON x.related_column= a.attname + WHERE + c.relkind in ('r','v') + AND (c.relname='%s' or c.relname = lower('%s')) + AND c.relnamespace=n.oid and n.nspname='%s' + AND a.attname not like '....%%' + AND a.attnum > 0 + AND a.atttypid = t.oid + AND a.attrelid = c.oid + ORDER BY a.attnum"; function __construct() { parent::__construct(); - if (ADODB_ASSOC_CASE !== 2) { + if (ADODB_ASSOC_CASE !== ADODB_ASSOC_CASE_NATIVE) { $this->rsPrefix .= 'assoc_'; } $this->_bindInputArray = PHP_VERSION >= 5.1; @@ -87,19 +107,20 @@ class ADODB_postgres7 extends ADODB_postgres64 { // the following should be compat with postgresql 7.2, // which makes obsolete the LIMIT limit,offset syntax - function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) - { - $offsetStr = ($offset >= 0) ? " OFFSET ".((integer)$offset) : ''; - $limitStr = ($nrows >= 0) ? " LIMIT ".((integer)$nrows) : ''; - if ($secs2cache) - $rs = $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr); - else - $rs = $this->Execute($sql."$limitStr$offsetStr",$inputarr); + function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) + { + $offsetStr = ($offset >= 0) ? " OFFSET ".((integer)$offset) : ''; + $limitStr = ($nrows >= 0) ? " LIMIT ".((integer)$nrows) : ''; + if ($secs2cache) + $rs = $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr); + else + $rs = $this->Execute($sql."$limitStr$offsetStr",$inputarr); return $rs; - } - /* - function Prepare($sql) + } + + /* + function Prepare($sql) { $info = $this->ServerInfo(); if ($info['version']>=7.3) { @@ -107,55 +128,72 @@ class ADODB_postgres7 extends ADODB_postgres64 { } return $sql; } - */ - - /* - I discovered that the MetaForeignKeys method no longer worked for Postgres 8.3. - I went ahead and modified it to work for both 8.2 and 8.3. - Please feel free to include this change in your next release of adodb. - William Kolodny [William.Kolodny#gt-t.net] */ + + /** + * Generate the SQL to retrieve MetaColumns data + * @param string $table Table name + * @param string $schema Schema name (can be blank) + * @return string SQL statement to execute + */ + protected function _generateMetaColumnsSQL($table, $schema) + { + if ($schema) { + return sprintf($this->metaColumnsSQL1, $table, $table, $table, $schema); + } + else { + return sprintf($this->metaColumnsSQL, $table, $table, $schema); + } + } + + /** + * @returns assoc array where keys are tables, and values are foreign keys + */ function MetaForeignKeys($table, $owner=false, $upper=false) { - $sql=" - SELECT fum.ftblname AS lookup_table, split_part(fum.rf, ')'::text, 1) AS lookup_field, - fum.ltable AS dep_table, split_part(fum.lf, ')'::text, 1) AS dep_field - FROM ( - SELECT fee.ltable, fee.ftblname, fee.consrc, split_part(fee.consrc,'('::text, 2) AS lf, - split_part(fee.consrc, '('::text, 3) AS rf - FROM ( - SELECT foo.relname AS ltable, foo.ftblname, - pg_get_constraintdef(foo.oid) AS consrc - FROM ( - SELECT c.oid, c.conname AS name, t.relname, ft.relname AS ftblname - FROM pg_constraint c - JOIN pg_class t ON (t.oid = c.conrelid) - JOIN pg_class ft ON (ft.oid = c.confrelid) - JOIN pg_namespace nft ON (nft.oid = ft.relnamespace) - LEFT JOIN pg_description ds ON (ds.objoid = c.oid) - JOIN pg_namespace n ON (n.oid = t.relnamespace) - WHERE c.contype = 'f'::\"char\" - ORDER BY t.relname, n.nspname, c.conname, c.oid - ) foo - ) fee) fum - WHERE fum.ltable='".strtolower($table)."' - ORDER BY fum.ftblname, fum.ltable, split_part(fum.lf, ')'::text, 1) - "; - $rs = $this->Execute($sql); - - if (!$rs || $rs->EOF) return false; - - $a = array(); - while (!$rs->EOF) { - if ($upper) { - $a[strtoupper($rs->Fields('lookup_table'))][] = strtoupper(str_replace('"','',$rs->Fields('dep_field').'='.$rs->Fields('lookup_field'))); - } else { - $a[$rs->Fields('lookup_table')][] = str_replace('"','',$rs->Fields('dep_field').'='.$rs->Fields('lookup_field')); - } - $rs->MoveNext(); - } - - return $a; + # Regex isolates the 2 terms between parenthesis using subexpressions + $regex = '^.*\((.*)\).*\((.*)\).*$'; + $sql=" + SELECT + lookup_table, + regexp_replace(consrc, '$regex', '\\2') AS lookup_field, + dep_table, + regexp_replace(consrc, '$regex', '\\1') AS dep_field + FROM ( + SELECT + pg_get_constraintdef(c.oid) AS consrc, + t.relname AS dep_table, + ft.relname AS lookup_table + FROM pg_constraint c + JOIN pg_class t ON (t.oid = c.conrelid) + JOIN pg_class ft ON (ft.oid = c.confrelid) + JOIN pg_namespace nft ON (nft.oid = ft.relnamespace) + LEFT JOIN pg_description ds ON (ds.objoid = c.oid) + JOIN pg_namespace n ON (n.oid = t.relnamespace) + WHERE c.contype = 'f'::\"char\" + ORDER BY t.relname, n.nspname, c.conname, c.oid + ) constraints + WHERE + dep_table='".strtolower($table)."' + ORDER BY + lookup_table, + dep_table, + dep_field"; + $rs = $this->Execute($sql); + + if (!$rs || $rs->EOF) return false; + + $a = array(); + while (!$rs->EOF) { + if ($upper) { + $a[strtoupper($rs->Fields('lookup_table'))][] = strtoupper(str_replace('"','',$rs->Fields('dep_field').'='.$rs->Fields('lookup_field'))); + } else { + $a[$rs->Fields('lookup_table')][] = str_replace('"','',$rs->Fields('dep_field').'='.$rs->Fields('lookup_field')); + } + $rs->MoveNext(); + } + + return $a; } @@ -219,9 +257,9 @@ class ADODB_postgres7 extends ADODB_postgres64 { $rez = pg_query($this->_connectionID,$sql); } // check if no data returned, then no need to create real recordset - if ($rez && pg_numfields($rez) <= 0) { + if ($rez && pg_num_fields($rez) <= 0) { if (is_resource($this->_resultid) && get_resource_type($this->_resultid) === 'pgsql result') { - pg_freeresult($this->_resultid); + pg_free_result($this->_resultid); } $this->_resultid = $rez; return true; @@ -229,7 +267,7 @@ class ADODB_postgres7 extends ADODB_postgres64 { return $rez; } - // this is a set of functions for managing client encoding - very important if the encodings + // this is a set of functions for managing client encoding - very important if the encodings // of your database and your output target (i.e. HTML) don't match //for instance, you may have UNICODE database and server it on-site as WIN1251 etc. // GetCharSet - get the name of the character set the client is using now @@ -262,7 +300,7 @@ class ADODB_postgres7 extends ADODB_postgres64 { } /*-------------------------------------------------------------------------------------- - Class Name: Recordset + Class Name: Recordset --------------------------------------------------------------------------------------*/ class ADORecordSet_postgres7 extends ADORecordSet_postgres64{ @@ -308,8 +346,9 @@ class ADORecordSet_assoc_postgres7 extends ADORecordSet_postgres64{ function _fetch() { - if ($this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0) - return false; + if ($this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0) { + return false; + } $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode); @@ -321,26 +360,6 @@ class ADORecordSet_assoc_postgres7 extends ADORecordSet_postgres64{ return (is_array($this->fields)); } - // Create associative array - function _updatefields() - { - if (ADODB_ASSOC_CASE == 2) return; // native - - $arr = array(); - $lowercase = (ADODB_ASSOC_CASE == 0); - - foreach($this->fields as $k => $v) { - if (is_integer($k)) $arr[$k] = $v; - else { - if ($lowercase) - $arr[strtolower($k)] = $v; - else - $arr[strtoupper($k)] = $v; - } - } - $this->fields = $arr; - } - function MoveNext() { if (!$this->EOF) { diff --git a/lib/adodb/drivers/adodb-postgres8.inc.php b/lib/adodb/drivers/adodb-postgres8.inc.php index 2bd236a510c..1ef71180776 100644 --- a/lib/adodb/drivers/adodb-postgres8.inc.php +++ b/lib/adodb/drivers/adodb-postgres8.inc.php @@ -1,6 +1,8 @@ ADORecordset($id,$mode); + parent::__construct($id,$mode); } }; } // define diff --git a/lib/adodb/drivers/adodb-sapdb.inc.php b/lib/adodb/drivers/adodb-sapdb.inc.php index 5a51fa2a343..a056311091d 100644 --- a/lib/adodb/drivers/adodb-sapdb.inc.php +++ b/lib/adodb/drivers/adodb-sapdb.inc.php @@ -1,6 +1,8 @@ curmode = SQL_CUR_USE_ODBC; - $this->ADODB_odbc(); + parent::__construct(); } function ServerInfo() @@ -46,7 +48,7 @@ class ADODB_SAPDB extends ADODB_odbc { return $info; } - function MetaPrimaryKeys($table) + function MetaPrimaryKeys($table, $owner = false) { $table = $this->Quote(strtoupper($table)); @@ -92,7 +94,7 @@ class ADODB_SAPDB extends ADODB_odbc { return $indexes; } - function MetaColumns ($table) + function MetaColumns ($table, $normalize = true) { global $ADODB_FETCH_MODE; $save = $ADODB_FETCH_MODE; @@ -140,7 +142,7 @@ class ADODB_SAPDB extends ADODB_odbc { return $retarr; } - function MetaColumnNames($table) + function MetaColumnNames($table, $numIndexes = false, $useattnum = false) { $table = $this->Quote(strtoupper($table)); @@ -174,9 +176,9 @@ class ADORecordSet_sapdb extends ADORecordSet_odbc { var $databaseType = "sapdb"; - function ADORecordSet_sapdb($id,$mode=false) + function __construct($id,$mode=false) { - $this->ADORecordSet_odbc($id,$mode); + parent::__construct($id,$mode); } } diff --git a/lib/adodb/drivers/adodb-sqlanywhere.inc.php b/lib/adodb/drivers/adodb-sqlanywhere.inc.php index a0a7b86bb33..e6ee391b0ea 100644 --- a/lib/adodb/drivers/adodb-sqlanywhere.inc.php +++ b/lib/adodb/drivers/adodb-sqlanywhere.inc.php @@ -1,6 +1,8 @@ ADODB_odbc(); - } - function _insertid() { return $this->GetOne('select @@identity'); } @@ -156,9 +153,9 @@ if (!defined('ADODB_SYBASE_SQLANYWHERE')){ var $databaseType = "sqlanywhere"; - function ADORecordSet_sqlanywhere($id,$mode=false) + function __construct($id,$mode=false) { - $this->ADORecordSet_odbc($id,$mode); + parent::__construct($id,$mode); } diff --git a/lib/adodb/drivers/adodb-sqlite.inc.php b/lib/adodb/drivers/adodb-sqlite.inc.php index e7cf3534383..e1b12d43923 100644 --- a/lib/adodb/drivers/adodb-sqlite.inc.php +++ b/lib/adodb/drivers/adodb-sqlite.inc.php @@ -1,6 +1,8 @@ fmtDate)."'"; - case 'sysTimeStamp' : return "'".date($this->sysTimeStamp)."'"; - } - }*/ - function ServerInfo() { $arr['version'] = sqlite_libversion(); @@ -54,69 +47,90 @@ class ADODB_sqlite extends ADOConnection { function BeginTrans() { - if ($this->transOff) return true; - $ret = $this->Execute("BEGIN TRANSACTION"); - $this->transCnt += 1; - return true; + if ($this->transOff) { + return true; + } + $ret = $this->Execute("BEGIN TRANSACTION"); + $this->transCnt += 1; + return true; } function CommitTrans($ok=true) { - if ($this->transOff) return true; - if (!$ok) return $this->RollbackTrans(); + if ($this->transOff) { + return true; + } + if (!$ok) { + return $this->RollbackTrans(); + } $ret = $this->Execute("COMMIT"); - if ($this->transCnt>0)$this->transCnt -= 1; + if ($this->transCnt > 0) { + $this->transCnt -= 1; + } return !empty($ret); } function RollbackTrans() { - if ($this->transOff) return true; + if ($this->transOff) { + return true; + } $ret = $this->Execute("ROLLBACK"); - if ($this->transCnt>0)$this->transCnt -= 1; + if ($this->transCnt > 0) { + $this->transCnt -= 1; + } return !empty($ret); } // mark newnham function MetaColumns($table, $normalize=true) { - global $ADODB_FETCH_MODE; - $false = false; - $save = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; - if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); - $rs = $this->Execute("PRAGMA table_info('$table')"); - if (isset($savem)) $this->SetFetchMode($savem); - if (!$rs) { - $ADODB_FETCH_MODE = $save; - return $false; - } - $arr = array(); - while ($r = $rs->FetchRow()) { - $type = explode('(',$r['type']); - $size = ''; - if (sizeof($type)==2) - $size = trim($type[1],')'); - $fn = strtoupper($r['name']); - $fld = new ADOFieldObject; - $fld->name = $r['name']; - $fld->type = $type[0]; - $fld->max_length = $size; - $fld->not_null = $r['notnull']; - $fld->default_value = $r['dflt_value']; - $fld->scale = 0; - if (isset($r['pk']) && $r['pk']) $fld->primary_key=1; - if ($save == ADODB_FETCH_NUM) $arr[] = $fld; - else $arr[strtoupper($fld->name)] = $fld; - } - $rs->Close(); - $ADODB_FETCH_MODE = $save; - return $arr; + global $ADODB_FETCH_MODE; + $false = false; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + if ($this->fetchMode !== false) { + $savem = $this->SetFetchMode(false); + } + $rs = $this->Execute("PRAGMA table_info('$table')"); + if (isset($savem)) { + $this->SetFetchMode($savem); + } + if (!$rs) { + $ADODB_FETCH_MODE = $save; + return $false; + } + $arr = array(); + while ($r = $rs->FetchRow()) { + $type = explode('(',$r['type']); + $size = ''; + if (sizeof($type)==2) { + $size = trim($type[1],')'); + } + $fn = strtoupper($r['name']); + $fld = new ADOFieldObject; + $fld->name = $r['name']; + $fld->type = $type[0]; + $fld->max_length = $size; + $fld->not_null = $r['notnull']; + $fld->default_value = $r['dflt_value']; + $fld->scale = 0; + if (isset($r['pk']) && $r['pk']) { + $fld->primary_key=1; + } + if ($save == ADODB_FETCH_NUM) { + $arr[] = $fld; + } else { + $arr[strtoupper($fld->name)] = $fld; + } + } + $rs->Close(); + $ADODB_FETCH_MODE = $save; + return $arr; } function _init($parentDriver) { - $parentDriver->hasTransactions = false; $parentDriver->hasInsertID = true; } @@ -128,12 +142,14 @@ class ADODB_sqlite extends ADOConnection { function _affectedrows() { - return sqlite_changes($this->_connectionID); - } + return sqlite_changes($this->_connectionID); + } function ErrorMsg() { - if ($this->_logsql) return $this->_errorMsg; + if ($this->_logsql) { + return $this->_errorMsg; + } return ($this->_errorNo) ? sqlite_error_string($this->_errorNo) : ''; } @@ -159,11 +175,17 @@ class ADODB_sqlite extends ADOConnection { // returns true or false function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) { - if (!function_exists('sqlite_open')) return null; - if (empty($argHostname) && $argDatabasename) $argHostname = $argDatabasename; + if (!function_exists('sqlite_open')) { + return null; + } + if (empty($argHostname) && $argDatabasename) { + $argHostname = $argDatabasename; + } $this->_connectionID = sqlite_open($argHostname); - if ($this->_connectionID === false) return false; + if ($this->_connectionID === false) { + return false; + } $this->_createFunctions(); return true; } @@ -171,11 +193,17 @@ class ADODB_sqlite extends ADOConnection { // returns true or false function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) { - if (!function_exists('sqlite_open')) return null; - if (empty($argHostname) && $argDatabasename) $argHostname = $argDatabasename; + if (!function_exists('sqlite_open')) { + return null; + } + if (empty($argHostname) && $argDatabasename) { + $argHostname = $argDatabasename; + } $this->_connectionID = sqlite_popen($argHostname); - if ($this->_connectionID === false) return false; + if ($this->_connectionID === false) { + return false; + } $this->_createFunctions(); return true; } @@ -187,6 +215,11 @@ class ADODB_sqlite extends ADOConnection { if (!$rez) { $this->_errorNo = sqlite_last_error($this->_connectionID); } + // If no data was returned, we don't need to create a real recordset + // Note: this code is untested, as I don't have a sqlite2 setup available + elseif (sqlite_num_fields($rez) == 0) { + $rez = true; + } return $rez; } @@ -195,10 +228,11 @@ class ADODB_sqlite extends ADOConnection { { $offsetStr = ($offset >= 0) ? " OFFSET $offset" : ''; $limitStr = ($nrows >= 0) ? " LIMIT $nrows" : ($offset >= 0 ? ' LIMIT 999999999' : ''); - if ($secs2cache) - $rs = $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr); - else - $rs = $this->Execute($sql."$limitStr$offsetStr",$inputarr); + if ($secs2cache) { + $rs = $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr); + } else { + $rs = $this->Execute($sql."$limitStr$offsetStr",$inputarr); + } return $rs; } @@ -224,7 +258,9 @@ class ADODB_sqlite extends ADOConnection { $start -= 1; $num = '0'; $ok = $this->Execute("insert into $seq values($start)"); - if (!$ok) return false; + if (!$ok) { + return false; + } } $this->Execute("update $seq set id=id+1 where id=$num"); @@ -242,17 +278,23 @@ class ADODB_sqlite extends ADOConnection { function CreateSequence($seqname='adodbseq',$start=1) { - if (empty($this->_genSeqSQL)) return false; + if (empty($this->_genSeqSQL)) { + return false; + } $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname)); - if (!$ok) return false; + if (!$ok) { + return false; + } $start -= 1; return $this->Execute("insert into $seqname values($start)"); } var $_dropSeqSQL = 'drop table %s'; - function DropSequence($seqname) + function DropSequence($seqname = 'adodbseq') { - if (empty($this->_dropSeqSQL)) return false; + if (empty($this->_dropSeqSQL)) { + return false; + } return $this->Execute(sprintf($this->_dropSeqSQL,$seqname)); } @@ -262,56 +304,59 @@ class ADODB_sqlite extends ADOConnection { return @sqlite_close($this->_connectionID); } - function MetaIndexes($table, $primary = FALSE, $owner=false, $owner = false) + function MetaIndexes($table, $primary = FALSE, $owner = false) { $false = false; // save old fetch mode - global $ADODB_FETCH_MODE; - $save = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - if ($this->fetchMode !== FALSE) { - $savem = $this->SetFetchMode(FALSE); - } + global $ADODB_FETCH_MODE; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== FALSE) { + $savem = $this->SetFetchMode(FALSE); + } $SQL=sprintf("SELECT name,sql FROM sqlite_master WHERE type='index' AND tbl_name='%s'", strtolower($table)); - $rs = $this->Execute($SQL); - if (!is_object($rs)) { - if (isset($savem)) + $rs = $this->Execute($SQL); + if (!is_object($rs)) { + if (isset($savem)) { $this->SetFetchMode($savem); + } $ADODB_FETCH_MODE = $save; - return $false; - } + return $false; + } $indexes = array (); while ($row = $rs->FetchRow()) { - if ($primary && preg_match("/primary/i",$row[1]) == 0) continue; - if (!isset($indexes[$row[0]])) { - - $indexes[$row[0]] = array( - 'unique' => preg_match("/unique/i",$row[1]), - 'columns' => array()); + if ($primary && preg_match("/primary/i",$row[1]) == 0) { + continue; + } + if (!isset($indexes[$row[0]])) { + $indexes[$row[0]] = array( + 'unique' => preg_match("/unique/i",$row[1]), + 'columns' => array() + ); } /** - * There must be a more elegant way of doing this, - * the index elements appear in the SQL statement - * in cols[1] between parentheses - * e.g CREATE UNIQUE INDEX ware_0 ON warehouse (org,warehouse) - */ + * There must be a more elegant way of doing this, + * the index elements appear in the SQL statement + * in cols[1] between parentheses + * e.g CREATE UNIQUE INDEX ware_0 ON warehouse (org,warehouse) + */ $cols = explode("(",$row[1]); $cols = explode(")",$cols[1]); array_pop($cols); $indexes[$row[0]]['columns'] = $cols; } if (isset($savem)) { - $this->SetFetchMode($savem); + $this->SetFetchMode($savem); $ADODB_FETCH_MODE = $save; } - return $indexes; + return $indexes; } } /*-------------------------------------------------------------------------------------- - Class Name: Recordset + Class Name: Recordset --------------------------------------------------------------------------------------*/ class ADORecordset_sqlite extends ADORecordSet { @@ -319,7 +364,7 @@ class ADORecordset_sqlite extends ADORecordSet { var $databaseType = "sqlite"; var $bind = false; - function ADORecordset_sqlite($queryID,$mode=false) + function __construct($queryID,$mode=false) { if ($mode === false) { @@ -327,9 +372,15 @@ class ADORecordset_sqlite extends ADORecordSet { $mode = $ADODB_FETCH_MODE; } switch($mode) { - case ADODB_FETCH_NUM: $this->fetchMode = SQLITE_NUM; break; - case ADODB_FETCH_ASSOC: $this->fetchMode = SQLITE_ASSOC; break; - default: $this->fetchMode = SQLITE_BOTH; break; + case ADODB_FETCH_NUM: + $this->fetchMode = SQLITE_NUM; + break; + case ADODB_FETCH_ASSOC: + $this->fetchMode = SQLITE_ASSOC; + break; + default: + $this->fetchMode = SQLITE_BOTH; + break; } $this->adodbFetchMode = $mode; @@ -360,15 +411,17 @@ class ADORecordset_sqlite extends ADORecordSet { return $fld; } - function _initrs() - { + function _initrs() + { $this->_numOfRows = @sqlite_num_rows($this->_queryID); $this->_numOfFields = @sqlite_num_fields($this->_queryID); - } + } function Fields($colname) { - if ($this->fetchMode != SQLITE_NUM) return $this->fields[$colname]; + if ($this->fetchMode != SQLITE_NUM) { + return $this->fields[$colname]; + } if (!$this->bind) { $this->bind = array(); for ($i=0; $i < $this->_numOfFields; $i++) { @@ -377,13 +430,13 @@ class ADORecordset_sqlite extends ADORecordSet { } } - return $this->fields[$this->bind[strtoupper($colname)]]; + return $this->fields[$this->bind[strtoupper($colname)]]; } - function _seek($row) - { - return sqlite_seek($this->_queryID, $row); - } + function _seek($row) + { + return sqlite_seek($this->_queryID, $row); + } function _fetch($ignore_fields=false) { diff --git a/lib/adodb/drivers/adodb-sqlite.inc.php b/lib/adodb/drivers/adodb-sqlite3.inc.php similarity index 51% copy from lib/adodb/drivers/adodb-sqlite.inc.php copy to lib/adodb/drivers/adodb-sqlite3.inc.php index e7cf3534383..152ec694a0a 100644 --- a/lib/adodb/drivers/adodb-sqlite.inc.php +++ b/lib/adodb/drivers/adodb-sqlite3.inc.php @@ -1,6 +1,8 @@ fmtDate)."'"; - case 'sysTimeStamp' : return "'".date($this->sysTimeStamp)."'"; - } - }*/ - function ServerInfo() { - $arr['version'] = sqlite_libversion(); - $arr['description'] = 'SQLite '; - $arr['encoding'] = sqlite_libencoding(); + $version = SQLite3::version(); + $arr['version'] = $version['versionString']; + $arr['description'] = 'SQLite 3'; return $arr; } function BeginTrans() { - if ($this->transOff) return true; - $ret = $this->Execute("BEGIN TRANSACTION"); - $this->transCnt += 1; - return true; + if ($this->transOff) { + return true; + } + $ret = $this->Execute("BEGIN TRANSACTION"); + $this->transCnt += 1; + return true; } function CommitTrans($ok=true) { - if ($this->transOff) return true; - if (!$ok) return $this->RollbackTrans(); + if ($this->transOff) { + return true; + } + if (!$ok) { + return $this->RollbackTrans(); + } $ret = $this->Execute("COMMIT"); - if ($this->transCnt>0)$this->transCnt -= 1; + if ($this->transCnt > 0) { + $this->transCnt -= 1; + } return !empty($ret); } function RollbackTrans() { - if ($this->transOff) return true; + if ($this->transOff) { + return true; + } $ret = $this->Execute("ROLLBACK"); - if ($this->transCnt>0)$this->transCnt -= 1; + if ($this->transCnt > 0) { + $this->transCnt -= 1; + } return !empty($ret); } // mark newnham function MetaColumns($table, $normalize=true) { - global $ADODB_FETCH_MODE; - $false = false; - $save = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; - if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); - $rs = $this->Execute("PRAGMA table_info('$table')"); - if (isset($savem)) $this->SetFetchMode($savem); - if (!$rs) { - $ADODB_FETCH_MODE = $save; - return $false; - } - $arr = array(); - while ($r = $rs->FetchRow()) { - $type = explode('(',$r['type']); - $size = ''; - if (sizeof($type)==2) - $size = trim($type[1],')'); - $fn = strtoupper($r['name']); - $fld = new ADOFieldObject; - $fld->name = $r['name']; - $fld->type = $type[0]; - $fld->max_length = $size; - $fld->not_null = $r['notnull']; - $fld->default_value = $r['dflt_value']; - $fld->scale = 0; - if (isset($r['pk']) && $r['pk']) $fld->primary_key=1; - if ($save == ADODB_FETCH_NUM) $arr[] = $fld; - else $arr[strtoupper($fld->name)] = $fld; - } - $rs->Close(); - $ADODB_FETCH_MODE = $save; - return $arr; + global $ADODB_FETCH_MODE; + $false = false; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; + if ($this->fetchMode !== false) { + $savem = $this->SetFetchMode(false); + } + $rs = $this->Execute("PRAGMA table_info('$table')"); + if (isset($savem)) { + $this->SetFetchMode($savem); + } + if (!$rs) { + $ADODB_FETCH_MODE = $save; + return $false; + } + $arr = array(); + while ($r = $rs->FetchRow()) { + $type = explode('(',$r['type']); + $size = ''; + if (sizeof($type)==2) { + $size = trim($type[1],')'); + } + $fn = strtoupper($r['name']); + $fld = new ADOFieldObject; + $fld->name = $r['name']; + $fld->type = $type[0]; + $fld->max_length = $size; + $fld->not_null = $r['notnull']; + $fld->default_value = $r['dflt_value']; + $fld->scale = 0; + if (isset($r['pk']) && $r['pk']) { + $fld->primary_key=1; + } + if ($save == ADODB_FETCH_NUM) { + $arr[] = $fld; + } else { + $arr[strtoupper($fld->name)] = $fld; + } + } + $rs->Close(); + $ADODB_FETCH_MODE = $save; + return $arr; } function _init($parentDriver) { - $parentDriver->hasTransactions = false; $parentDriver->hasInsertID = true; } function _insertid() { - return sqlite_last_insert_rowid($this->_connectionID); + return $this->_connectionID->lastInsertRowID(); } function _affectedrows() { - return sqlite_changes($this->_connectionID); - } + return $this->_connectionID->changes(); + } function ErrorMsg() { - if ($this->_logsql) return $this->_errorMsg; - return ($this->_errorNo) ? sqlite_error_string($this->_errorNo) : ''; + if ($this->_logsql) { + return $this->_errorMsg; + } + return ($this->_errorNo) ? $this->ErrorNo() : ''; //**tochange? } function ErrorNo() { - return $this->_errorNo; + return $this->_connectionID->lastErrorCode(); //**tochange?? } function SQLDate($fmt, $col=false) @@ -151,41 +167,41 @@ class ADODB_sqlite extends ADOConnection { function _createFunctions() { - @sqlite_create_function($this->_connectionID, 'adodb_date', 'adodb_date', 1); - @sqlite_create_function($this->_connectionID, 'adodb_date2', 'adodb_date2', 2); + $this->_connectionID->createFunction('adodb_date', 'adodb_date', 1); + $this->_connectionID->createFunction('adodb_date2', 'adodb_date2', 2); } // returns true or false function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) { - if (!function_exists('sqlite_open')) return null; - if (empty($argHostname) && $argDatabasename) $argHostname = $argDatabasename; - - $this->_connectionID = sqlite_open($argHostname); - if ($this->_connectionID === false) return false; + if (empty($argHostname) && $argDatabasename) { + $argHostname = $argDatabasename; + } + $this->_connectionID = new SQLite3($argHostname); $this->_createFunctions(); + return true; } // returns true or false function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) { - if (!function_exists('sqlite_open')) return null; - if (empty($argHostname) && $argDatabasename) $argHostname = $argDatabasename; - - $this->_connectionID = sqlite_popen($argHostname); - if ($this->_connectionID === false) return false; - $this->_createFunctions(); - return true; + // There's no permanent connect in SQLite3 + return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename); } // returns query ID if successful, otherwise false function _query($sql,$inputarr=false) { - $rez = sqlite_query($sql,$this->_connectionID); - if (!$rez) { - $this->_errorNo = sqlite_last_error($this->_connectionID); + $rez = $this->_connectionID->query($sql); + if ($rez === false) { + $this->_errorNo = $this->_connectionID->lastErrorCode(); + } + // If no data was returned, we don't need to create a real recordset + elseif ($rez->numColumns() == 0) { + $rez->finalize(); + $rez = true; } return $rez; @@ -195,10 +211,11 @@ class ADODB_sqlite extends ADOConnection { { $offsetStr = ($offset >= 0) ? " OFFSET $offset" : ''; $limitStr = ($nrows >= 0) ? " LIMIT $nrows" : ($offset >= 0 ? ' LIMIT 999999999' : ''); - if ($secs2cache) - $rs = $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr); - else - $rs = $this->Execute($sql."$limitStr$offsetStr",$inputarr); + if ($secs2cache) { + $rs = $this->CacheExecute($secs2cache,$sql."$limitStr$offsetStr",$inputarr); + } else { + $rs = $this->Execute($sql."$limitStr$offsetStr",$inputarr); + } return $rs; } @@ -224,7 +241,9 @@ class ADODB_sqlite extends ADOConnection { $start -= 1; $num = '0'; $ok = $this->Execute("insert into $seq values($start)"); - if (!$ok) return false; + if (!$ok) { + return false; + } } $this->Execute("update $seq set id=id+1 where id=$num"); @@ -242,84 +261,93 @@ class ADODB_sqlite extends ADOConnection { function CreateSequence($seqname='adodbseq',$start=1) { - if (empty($this->_genSeqSQL)) return false; + if (empty($this->_genSeqSQL)) { + return false; + } $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname)); - if (!$ok) return false; + if (!$ok) { + return false; + } $start -= 1; return $this->Execute("insert into $seqname values($start)"); } var $_dropSeqSQL = 'drop table %s'; - function DropSequence($seqname) + function DropSequence($seqname = 'adodbseq') { - if (empty($this->_dropSeqSQL)) return false; + if (empty($this->_dropSeqSQL)) { + return false; + } return $this->Execute(sprintf($this->_dropSeqSQL,$seqname)); } // returns true or false function _close() { - return @sqlite_close($this->_connectionID); + return $this->_connectionID->close(); } - function MetaIndexes($table, $primary = FALSE, $owner=false, $owner = false) + function MetaIndexes($table, $primary = FALSE, $owner = false) { $false = false; // save old fetch mode - global $ADODB_FETCH_MODE; - $save = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - if ($this->fetchMode !== FALSE) { - $savem = $this->SetFetchMode(FALSE); - } + global $ADODB_FETCH_MODE; + $save = $ADODB_FETCH_MODE; + $ADODB_FETCH_MODE = ADODB_FETCH_NUM; + if ($this->fetchMode !== FALSE) { + $savem = $this->SetFetchMode(FALSE); + } $SQL=sprintf("SELECT name,sql FROM sqlite_master WHERE type='index' AND tbl_name='%s'", strtolower($table)); - $rs = $this->Execute($SQL); - if (!is_object($rs)) { - if (isset($savem)) + $rs = $this->Execute($SQL); + if (!is_object($rs)) { + if (isset($savem)) { $this->SetFetchMode($savem); + } $ADODB_FETCH_MODE = $save; - return $false; - } + return $false; + } $indexes = array (); while ($row = $rs->FetchRow()) { - if ($primary && preg_match("/primary/i",$row[1]) == 0) continue; - if (!isset($indexes[$row[0]])) { - - $indexes[$row[0]] = array( - 'unique' => preg_match("/unique/i",$row[1]), - 'columns' => array()); + if ($primary && preg_match("/primary/i",$row[1]) == 0) { + continue; + } + if (!isset($indexes[$row[0]])) { + $indexes[$row[0]] = array( + 'unique' => preg_match("/unique/i",$row[1]), + 'columns' => array() + ); } /** - * There must be a more elegant way of doing this, - * the index elements appear in the SQL statement - * in cols[1] between parentheses - * e.g CREATE UNIQUE INDEX ware_0 ON warehouse (org,warehouse) - */ + * There must be a more elegant way of doing this, + * the index elements appear in the SQL statement + * in cols[1] between parentheses + * e.g CREATE UNIQUE INDEX ware_0 ON warehouse (org,warehouse) + */ $cols = explode("(",$row[1]); $cols = explode(")",$cols[1]); array_pop($cols); $indexes[$row[0]]['columns'] = $cols; } if (isset($savem)) { - $this->SetFetchMode($savem); + $this->SetFetchMode($savem); $ADODB_FETCH_MODE = $save; } - return $indexes; + return $indexes; } } /*-------------------------------------------------------------------------------------- - Class Name: Recordset + Class Name: Recordset --------------------------------------------------------------------------------------*/ -class ADORecordset_sqlite extends ADORecordSet { +class ADORecordset_sqlite3 extends ADORecordSet { - var $databaseType = "sqlite"; + var $databaseType = "sqlite3"; var $bind = false; - function ADORecordset_sqlite($queryID,$mode=false) + function __construct($queryID,$mode=false) { if ($mode === false) { @@ -327,9 +355,15 @@ class ADORecordset_sqlite extends ADORecordSet { $mode = $ADODB_FETCH_MODE; } switch($mode) { - case ADODB_FETCH_NUM: $this->fetchMode = SQLITE_NUM; break; - case ADODB_FETCH_ASSOC: $this->fetchMode = SQLITE_ASSOC; break; - default: $this->fetchMode = SQLITE_BOTH; break; + case ADODB_FETCH_NUM: + $this->fetchMode = SQLITE3_NUM; + break; + case ADODB_FETCH_ASSOC: + $this->fetchMode = SQLITE3_ASSOC; + break; + default: + $this->fetchMode = SQLITE3_BOTH; + break; } $this->adodbFetchMode = $mode; @@ -354,21 +388,23 @@ class ADORecordset_sqlite extends ADORecordSet { function FetchField($fieldOffset = -1) { $fld = new ADOFieldObject; - $fld->name = sqlite_field_name($this->_queryID, $fieldOffset); + $fld->name = $this->_queryID->columnName($fieldOffset); $fld->type = 'VARCHAR'; $fld->max_length = -1; return $fld; } - function _initrs() - { - $this->_numOfRows = @sqlite_num_rows($this->_queryID); - $this->_numOfFields = @sqlite_num_fields($this->_queryID); - } + function _initrs() + { + $this->_numOfFields = $this->_queryID->numColumns(); + + } function Fields($colname) { - if ($this->fetchMode != SQLITE_NUM) return $this->fields[$colname]; + if ($this->fetchMode != SQLITE3_NUM) { + return $this->fields[$colname]; + } if (!$this->bind) { $this->bind = array(); for ($i=0; $i < $this->_numOfFields; $i++) { @@ -377,17 +413,21 @@ class ADORecordset_sqlite extends ADORecordSet { } } - return $this->fields[$this->bind[strtoupper($colname)]]; + return $this->fields[$this->bind[strtoupper($colname)]]; } - function _seek($row) - { - return sqlite_seek($this->_queryID, $row); - } + function _seek($row) + { + // sqlite3 does not implement seek + if ($this->debug) { + ADOConnection::outp("SQLite3 does not implement seek"); + } + return false; + } function _fetch($ignore_fields=false) { - $this->fields = @sqlite_fetch_array($this->_queryID,$this->fetchMode); + $this->fields = $this->_queryID->fetchArray($this->fetchMode); return !empty($this->fields); } diff --git a/lib/adodb/drivers/adodb-sqlitepo.inc.php b/lib/adodb/drivers/adodb-sqlitepo.inc.php index f1b8b99e0b1..d715e9ffbe3 100644 --- a/lib/adodb/drivers/adodb-sqlitepo.inc.php +++ b/lib/adodb/drivers/adodb-sqlitepo.inc.php @@ -1,6 +1,8 @@ ADODB_sqlite(); - } } /*-------------------------------------------------------------------------------------- @@ -38,9 +35,9 @@ class ADORecordset_sqlitepo extends ADORecordset_sqlite { var $databaseType = 'sqlitepo'; - function ADORecordset_sqlitepo($queryID,$mode=false) + function __construct($queryID,$mode=false) { - $this->ADORecordset_sqlite($queryID,$mode); + parent::__construct($queryID,$mode); } // Modified to strip table names from returned fields diff --git a/lib/adodb/drivers/adodb-sybase.inc.php b/lib/adodb/drivers/adodb-sybase.inc.php index d4ad1eb07cb..29016d0aa0e 100644 --- a/lib/adodb/drivers/adodb-sybase.inc.php +++ b/lib/adodb/drivers/adodb-sybase.inc.php @@ -1,6 +1,8 @@ 1,'FEB'=>2,'MAR'=>3,'APR'=>4,'MAY'=>5,'JUN'=>6,'JUL'=>7,'AUG'=>8,'SEP'=>9,'OCT'=>10,'NOV'=>11,'DEC'=>12); - function ADORecordset_sybase($id,$mode=false) + function __construct($id,$mode=false) { if ($mode === false) { global $ADODB_FETCH_MODE; @@ -316,7 +318,7 @@ class ADORecordset_sybase extends ADORecordSet { } if (!$mode) $this->fetchMode = ADODB_FETCH_ASSOC; else $this->fetchMode = $mode; - $this->ADORecordSet($id,$mode); + parent::__construct($id,$mode); } /* Returns: an object containing field information. @@ -356,7 +358,7 @@ class ADORecordset_sybase extends ADORecordSet { $this->fields = @sybase_fetch_assoc($this->_queryID); if (is_array($this->fields)) { - $this->fields = $this->GetRowAssoc(ADODB_ASSOC_CASE); + $this->fields = $this->GetRowAssoc(); return true; } return false; @@ -389,9 +391,9 @@ class ADORecordset_sybase extends ADORecordSet { } class ADORecordSet_array_sybase extends ADORecordSet_array { - function ADORecordSet_array_sybase($id=-1) + function __construct($id=-1) { - $this->ADORecordSet_array($id); + parent::__construct($id); } // sybase/mssql uses a default date like Dec 30 2000 12:00AM diff --git a/lib/adodb/drivers/adodb-sybase_ase.inc.php b/lib/adodb/drivers/adodb-sybase_ase.inc.php index 28de2dd4335..982eb5b3505 100644 --- a/lib/adodb/drivers/adodb-sybase_ase.inc.php +++ b/lib/adodb/drivers/adodb-sybase_ase.inc.php @@ -1,6 +1,8 @@ ADORecordSet_sybase($id,$mode); + parent::__construct($id,$mode); } } diff --git a/lib/adodb/drivers/adodb-text.inc.php b/lib/adodb/drivers/adodb-text.inc.php new file mode 100644 index 00000000000..a0d52323152 --- /dev/null +++ b/lib/adodb/drivers/adodb-text.inc.php @@ -0,0 +1,389 @@ +Connect($array,[$types],[$colnames]); + + Parameter $array is the 2 dimensional array of data. The first row can contain the + column names. If column names is not defined in first row, you MUST define $colnames, + the 3rd parameter. + + Parameter $types is optional. If defined, it should contain an array matching + the number of columns in $array, with each element matching the correct type defined + by MetaType: (B,C,I,L,N). If undefined, we will probe for $this->_proberows rows + to guess the type. Only C,I and N are recognised. + + Parameter $colnames is optional. If defined, it is an array that contains the + column names of $array. If undefined, we assume the first row of $array holds the + column names. + + The Execute() function will return a recordset. The recordset works like a normal recordset. + We have partial support for SQL parsing. We process the SQL using the following rules: + + 1. SQL order by's always work for the first column ordered. Subsequent cols are ignored + + 2. All operations take place on the same table. No joins possible. In fact the FROM clause + is ignored! You can use any name for the table. + + 3. To simplify code, all columns are returned, except when selecting 1 column + + $rs = $db->Execute('select col1,col2 from table'); // sql ignored, will generate all cols + + We special case handling of 1 column because it is used in filter popups + + $rs = $db->Execute('select col1 from table'); + // sql accepted and processed -- any table name is accepted + + $rs = $db->Execute('select distinct col1 from table'); + // sql accepted and processed + +4. Where clauses are ignored, but searching with the 3rd parameter of Execute is permitted. + This has to use PHP syntax and we will eval() it. You can even use PHP functions. + + $rs = $db->Execute('select * from table',false,"\$COL1='abc' and $\COL2=3") + // the 3rd param is searched -- make sure that $COL1 is a legal column name + // and all column names must be in upper case. + +4. Group by, having, other clauses are ignored + +5. Expression columns, min(), max() are ignored + +6. All data is readonly. Only SELECTs permitted. +*/ + +// security - hide paths +if (!defined('ADODB_DIR')) die(); + +if (! defined("_ADODB_TEXT_LAYER")) { + define("_ADODB_TEXT_LAYER", 1 ); + +// for sorting in _query() +function adodb_cmp($a, $b) { + if ($a[0] == $b[0]) return 0; + return ($a[0] < $b[0]) ? -1 : 1; +} +// for sorting in _query() +function adodb_cmpr($a, $b) { + if ($a[0] == $b[0]) return 0; + return ($a[0] > $b[0]) ? -1 : 1; +} +class ADODB_text extends ADOConnection { + var $databaseType = 'text'; + + var $_origarray; // original data + var $_types; + var $_proberows = 8; + var $_colnames; + var $_skiprow1=false; + var $readOnly = true; + var $hasTransactions = false; + + var $_rezarray; + var $_reznames; + var $_reztypes; + + function __construct() + { + } + + function RSRecordCount() + { + if (!empty($this->_rezarray)) return sizeof($this->_rezarray); + + return sizeof($this->_origarray); + } + + function _insertid() + { + return false; + } + + function _affectedrows() + { + return false; + } + + // returns true or false + function PConnect(&$array, $types = false, $colnames = false) + { + return $this->Connect($array, $types, $colnames); + } + // returns true or false + function Connect(&$array, $types = false, $colnames = false) + { + if (is_string($array) and $array === 'iluvphplens') return 'me2'; + + if (!$array) { + $this->_origarray = false; + return true; + } + $row = $array[0]; + $cols = sizeof($row); + + + if ($colnames) $this->_colnames = $colnames; + else { + $this->_colnames = $array[0]; + $this->_skiprow1 = true; + } + if (!$types) { + // probe and guess the type + $types = array(); + $firstrow = true; + if ($this->_proberows > sizeof($array)) $max = sizeof($array); + else $max = $this->_proberows; + for ($j=($this->_skiprow1)?1:0;$j < $max; $j++) { + $row = $array[$j]; + if (!$row) break; + $i = -1; + foreach($row as $v) { + $i += 1; + //print " ($i ".$types[$i]. "$v) "; + $v = trim($v); + if (!preg_match('/^[+-]{0,1}[0-9\.]+$/',$v)) { + $types[$i] = 'C'; // once C, always C + continue; + } + if (isset($types[$i]) && $types[$i]=='C') continue; + if ($firstrow) { + // If empty string, we presume is character + // test for integer for 1st row only + // after that it is up to testing other rows to prove + // that it is not an integer + if (strlen($v) == 0) $types[0] = 'C'; + if (strpos($v,'.') !== false) $types[0] = 'N'; + else $types[$i] = 'I'; + continue; + } + + if (strpos($v,'.') !== false) $types[$i] = 'N'; + + } + $firstrow = false; + } + } + //print_r($types); + $this->_origarray = $array; + $this->_types = $types; + return true; + } + + + + // returns queryID or false + // We presume that the select statement is on the same table (what else?), + // with the only difference being the order by. + //You can filter by using $eval and each clause is stored in $arr .eg. $arr[1] == 'name' + // also supports SELECT [DISTINCT] COL FROM ... -- only 1 col supported + function _query($sql,$input_arr,$eval=false) + { + if ($this->_origarray === false) return false; + + $eval = $this->evalAll; + $usql = strtoupper(trim($sql)); + $usql = preg_replace("/[\t\n\r]/",' ',$usql); + $usql = preg_replace('/ *BY/i',' BY',strtoupper($usql)); + + $eregword ='([A-Z_0-9]*)'; + //print "
$sql $eval "; + if ($eval) { + $i = 0; + foreach($this->_colnames as $n) { + $n = strtoupper(trim($n)); + $eval = str_replace("\$$n","\$arr[$i]",$eval); + + $i += 1; + } + + $i = 0; + $eval = "\$rez=($eval);"; + //print "

Eval string = $eval

"; + $where_arr = array(); + + reset($this->_origarray); + while (list($k_arr,$arr) = each($this->_origarray)) { + + if ($i == 0 && $this->_skiprow1) + $where_arr[] = $arr; + else { + eval($eval); + //print " $i: result=$rez arr[0]={$arr[0]} arr[1]={$arr[1]}
\n "; + if ($rez) $where_arr[] = $arr; + } + $i += 1; + } + $this->_rezarray = $where_arr; + }else + $where_arr = $this->_origarray; + + // THIS PROJECTION CODE ONLY WORKS FOR 1 COLUMN, + // OTHERWISE IT RETURNS ALL COLUMNS + if (substr($usql,0,7) == 'SELECT ') { + $at = strpos($usql,' FROM '); + $sel = trim(substr($usql,7,$at-7)); + + $distinct = false; + if (substr($sel,0,8) == 'DISTINCT') { + $distinct = true; + $sel = trim(substr($sel,8,$at)); + } + + // $sel holds the selection clause, comma delimited + // currently we only project if one column is involved + // this is to support popups in PHPLens + if (strpos(',',$sel)===false) { + $colarr = array(); + + preg_match("/$eregword/",$sel,$colarr); + $col = $colarr[1]; + $i = 0; + $n = ''; + reset($this->_colnames); + while (list($k_n,$n) = each($this->_colnames)) { + + if ($col == strtoupper(trim($n))) break; + $i += 1; + } + + if ($n && $col) { + $distarr = array(); + $projarray = array(); + $projtypes = array($this->_types[$i]); + $projnames = array($n); + + reset($where_arr); + while (list($k_a,$a) = each($where_arr)) { + if ($i == 0 && $this->_skiprow1) { + $projarray[] = array($n); + continue; + } + + if ($distinct) { + $v = strtoupper($a[$i]); + if (! $distarr[$v]) { + $projarray[] = array($a[$i]); + $distarr[$v] = 1; + } + } else + $projarray[] = array($a[$i]); + + } //foreach + //print_r($projarray); + } + } // check 1 column in projection + } // is SELECT + + if (empty($projarray)) { + $projtypes = $this->_types; + $projarray = $where_arr; + $projnames = $this->_colnames; + } + $this->_rezarray = $projarray; + $this->_reztypes = $projtypes; + $this->_reznames = $projnames; + + + $pos = strpos($usql,' ORDER BY '); + if ($pos === false) return $this; + $orderby = trim(substr($usql,$pos+10)); + + preg_match("/$eregword/",$orderby,$arr); + if (sizeof($arr) < 2) return $this; // actually invalid sql + $col = $arr[1]; + $at = (integer) $col; + if ($at == 0) { + $i = 0; + reset($projnames); + while (list($k_n,$n) = each($projnames)) { + if (strtoupper(trim($n)) == $col) { + $at = $i+1; + break; + } + $i += 1; + } + } + + if ($at <= 0 || $at > sizeof($projarray[0])) return $this; // cannot find sort column + $at -= 1; + + // generate sort array consisting of (sortval1, row index1) (sortval2, row index2)... + $sorta = array(); + $t = $projtypes[$at]; + $num = ($t == 'I' || $t == 'N'); + for ($i=($this->_skiprow1)?1:0, $max = sizeof($projarray); $i < $max; $i++) { + $row = $projarray[$i]; + $val = ($num)?(float)$row[$at]:$row[$at]; + $sorta[]=array($val,$i); + } + + // check for desc sort + $orderby = substr($orderby,strlen($col)+1); + $arr == array(); + preg_match('/([A-Z_0-9]*)/i',$orderby,$arr); + + if (trim($arr[1]) == 'DESC') $sortf = 'adodb_cmpr'; + else $sortf = 'adodb_cmp'; + + // hasta la sorta babe + usort($sorta, $sortf); + + // rearrange original array + $arr2 = array(); + if ($this->_skiprow1) $arr2[] = $projarray[0]; + foreach($sorta as $v) { + $arr2[] = $projarray[$v[1]]; + } + + $this->_rezarray = $arr2; + return $this; + } + + /* Returns: the last error message from previous database operation */ + function ErrorMsg() + { + return ''; + } + + /* Returns: the last error number from previous database operation */ + function ErrorNo() + { + return 0; + } + + // returns true or false + function _close() + { + } + + +} + +/*-------------------------------------------------------------------------------------- + Class Name: Recordset +--------------------------------------------------------------------------------------*/ + + +class ADORecordSet_text extends ADORecordSet_array +{ + + var $databaseType = "text"; + + function __construct(&$conn,$mode=false) + { + parent::__construct(); + $this->InitArray($conn->_rezarray,$conn->_reztypes,$conn->_reznames); + $conn->_rezarray = false; + } + +} // class ADORecordSet_text + + +} // defined diff --git a/lib/adodb/drivers/adodb-vfp.inc.php b/lib/adodb/drivers/adodb-vfp.inc.php index 9b7798b054e..9e4718dc710 100644 --- a/lib/adodb/drivers/adodb-vfp.inc.php +++ b/lib/adodb/drivers/adodb-vfp.inc.php @@ -1,6 +1,8 @@ ADODB_odbc(); - } - function Time() { return time(); @@ -72,12 +69,12 @@ class ADORecordSet_vfp extends ADORecordSet_odbc { var $databaseType = "vfp"; - function ADORecordSet_vfp($id,$mode=false) + function __construct($id,$mode=false) { - return $this->ADORecordSet_odbc($id,$mode); + return parent::__construct($id,$mode); } - function MetaType($t,$len=-1) + function MetaType($t, $len = -1, $fieldobj = false) { if (is_object($t)) { $fieldobj = $t; diff --git a/lib/adodb/license.txt b/lib/adodb/license.txt dissimilarity index 91% index d90f4e5ff6d..b8191587b91 100644 --- a/lib/adodb/license.txt +++ b/lib/adodb/license.txt @@ -1,182 +1,496 @@ -ADOdb is dual licensed using BSD and LGPL. - -In plain English, you do not need to distribute your application in source code form, nor do you need to distribute ADOdb source code, provided you follow the rest of terms of the BSD license. - -For more info about ADOdb, visit http://adodb.sourceforge.net/ - -BSD Style-License -================= - -Copyright (c) 2000, 2001, 2002, 2003, 2004 John Lim -All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, -are permitted provided that the following conditions are met: - -Redistributions of source code must retain the above copyright notice, this list -of conditions and the following disclaimer. - -Redistributions in binary form must reproduce the above copyright notice, this list -of conditions and the following disclaimer in the documentation and/or other materials -provided with the distribution. - -Neither the name of the John Lim nor the names of its contributors may be used to -endorse or promote products derived from this software without specific prior written -permission. - -DISCLAIMER: -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY -EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL -JOHN LIM OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) -HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, -OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -========================================================== -GNU LESSER GENERAL PUBLIC LICENSE -Version 2.1, February 1999 - -Copyright (C) 1991, 1999 Free Software Foundation, Inc. -59 Temple Place, Suite 330, Boston, MA 02111-1307 USA -Everyone is permitted to copy and distribute verbatim copies -of this license document, but changing it is not allowed. - -[This is the first released version of the Lesser GPL. It also counts - as the successor of the GNU Library Public License, version 2, hence - the version number 2.1.] - - -Preamble -The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. - -This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. - -When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. - -To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. - -For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. - -We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. - -To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. - -Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. - -Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. - -When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. - -We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. - -For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. - -In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. - -Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. - -The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. - - -TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION -0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". - -A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. - -The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) - -"Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. - -Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. - -1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. - -You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. - -2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: - - -a) The modified work must itself be a software library. -b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. -c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. -d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. -(For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) - -These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. - -In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. - -3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. - -Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. - -This option is useful when you wish to copy part of the code of the Library into a program that is not a library. - -4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. - -If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. - -5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. - -However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. - -When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. - -If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) - -Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. - -6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. - -You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: - - -a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) -b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. -c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. -d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. -e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. -For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. - -It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. - -7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: - - -a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. -b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. -8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. - -9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. - -10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. - -11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. - -If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. - -It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. - -This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. - -12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. - -13. The Free Software Foundation may publish revised and/or new versions of the Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. - -14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. - -NO WARRANTY - -15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - - -END OF TERMS AND CONDITIONS \ No newline at end of file +ADOdb License +============= + +ADOdb is dual licensed under BSD and LGPL. + +In plain English, you do not need to distribute your application in source code form, +nor do you need to distribute ADOdb source code, provided you follow the rest of +terms of the BSD license. + +For more info about ADOdb, visit http://adodb.sourceforge.net/ + +BSD 3-Clause License +-------------------- + +(c) 2000-2013 John Lim (jlim@natsoft.com) +(c) 2014 Damien Regad, Mark Newnham and the ADOdb community +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its contributors + may be used to endorse or promote products derived from this software without + specific prior written permission. + +### DISCLAIMER + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR +ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + +GNU LESSER GENERAL PUBLIC LICENSE +--------------------------------- + +_Version 2.1, February 1999_ +_Copyright © 1991, 1999 Free Software Foundation, Inc._ +_51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA_ + +Everyone is permitted to copy and distribute verbatim copies +of this license document, but changing it is not allowed. + +_This is the first released version of the Lesser GPL. It also counts +as the successor of the GNU Library Public License, version 2, hence +the version number 2.1._ + +### Preamble + +The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + +This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + +When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + +To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + +For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + +We protect your rights with a two-step method: **(1)** we copyright the +library, and **(2)** we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + +To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + +Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + +Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + +When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + +We call this license the “Lesser” General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + +For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + +In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + +Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + +The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +“work based on the library” and a “work that uses the library”. The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + +### TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + +**0.** This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called “this License”). +Each licensee is addressed as “you”. + +A “library” means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + +The “Library”, below, refers to any such software library or work +which has been distributed under these terms. A “work based on the +Library” means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term “modification”.) + +“Source code” for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + +**1.** You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + +You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + +**2.** You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + +* **a)** The modified work must itself be a software library. +* **b)** You must cause the files modified to carry prominent notices +stating that you changed the files and the date of any change. +* **c)** You must cause the whole of the work to be licensed at no +charge to all third parties under the terms of this License. +* **d)** If a facility in the modified Library refers to a function or a +table of data to be supplied by an application program that uses +the facility, other than as an argument passed when the facility +is invoked, then you must make a good faith effort to ensure that, +in the event an application does not supply such function or +table, the facility still operates, and performs whatever part of +its purpose remains meaningful. +(For example, a function in a library to compute square roots has +a purpose that is entirely well-defined independent of the +application. Therefore, Subsection 2d requires that any +application-supplied function or table used by this function must +be optional: if the application does not supply it, the square +root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + +**3.** You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + +Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + +This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + +**4.** You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + +If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + +**5.** A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a “work that uses the Library”. Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + +However, linking a “work that uses the Library” with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a “work that uses the +library”. The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + +When a “work that uses the Library” uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + +If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + +Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + +**6.** As an exception to the Sections above, you may also combine or +link a “work that uses the Library” with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + +You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + +* **a)** Accompany the work with the complete corresponding +machine-readable source code for the Library including whatever +changes were used in the work (which must be distributed under +Sections 1 and 2 above); and, if the work is an executable linked +with the Library, with the complete machine-readable “work that +uses the Library”, as object code and/or source code, so that the +user can modify the Library and then relink to produce a modified +executable containing the modified Library. (It is understood +that the user who changes the contents of definitions files in the +Library will not necessarily be able to recompile the application +to use the modified definitions.) +* **b)** Use a suitable shared library mechanism for linking with the +Library. A suitable mechanism is one that (1) uses at run time a +copy of the library already present on the user's computer system, +rather than copying library functions into the executable, and (2) +will operate properly with a modified version of the library, if +the user installs one, as long as the modified version is +interface-compatible with the version that the work was made with. +* **c)** Accompany the work with a written offer, valid for at +least three years, to give the same user the materials +specified in Subsection 6a, above, for a charge no more +than the cost of performing this distribution. +* **d)** If distribution of the work is made by offering access to copy +from a designated place, offer equivalent access to copy the above +specified materials from the same place. +* **e)** Verify that the user has already received a copy of these +materials or that you have already sent this user a copy. + +For an executable, the required form of the “work that uses the +Library” must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + +It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + +**7.** You may place library facilities that are a work based on the +Library side-by-side in a single library together with other library +facilities not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + +* **a)** Accompany the combined library with a copy of the same work +based on the Library, uncombined with any other library +facilities. This must be distributed under the terms of the +Sections above. +* **b)** Give prominent notice with the combined library of the fact +that part of it is a work based on the Library, and explaining +where to find the accompanying uncombined form of the same work. + +**8.** You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + +**9.** You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + +**10.** Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + +**11.** If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + +**12.** If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + +**13.** The Free Software Foundation may publish revised and/or new +versions of the Lesser General Public License from time to time. +Such new versions will be similar in spirit to the present version, +but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Library +specifies a version number of this License which applies to it and +“any later version”, you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + +**14.** If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + +### NO WARRANTY + +**15.** BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY “AS IS” WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +**16.** IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + +_END OF TERMS AND CONDITIONS_ diff --git a/lib/adodb/perf/perf-db2.inc.php b/lib/adodb/perf/perf-db2.inc.php index 9eb0c3299f2..2f0edee00a7 100644 --- a/lib/adodb/perf/perf-db2.inc.php +++ b/lib/adodb/perf/perf-db2.inc.php @@ -1,6 +1,8 @@ conn = $conn; } diff --git a/lib/adodb/perf/perf-informix.inc.php b/lib/adodb/perf/perf-informix.inc.php index 6de76c71953..8d1d01cc1ec 100644 --- a/lib/adodb/perf/perf-informix.inc.php +++ b/lib/adodb/perf/perf-informix.inc.php @@ -1,6 +1,8 @@ conn = $conn; } diff --git a/lib/adodb/perf/perf-mssql.inc.php b/lib/adodb/perf/perf-mssql.inc.php index 2ff4fea09dd..5a4339358f0 100644 --- a/lib/adodb/perf/perf-mssql.inc.php +++ b/lib/adodb/perf/perf-mssql.inc.php @@ -1,7 +1,9 @@ dataProvider == 'odbc') { $this->sql1 = 'sql1'; diff --git a/lib/adodb/perf/perf-mssqlnative.inc.php b/lib/adodb/perf/perf-mssqlnative.inc.php index b67d370581d..12a072d5ab8 100644 --- a/lib/adodb/perf/perf-mssqlnative.inc.php +++ b/lib/adodb/perf/perf-mssqlnative.inc.php @@ -1,7 +1,9 @@ dataProvider == 'odbc') { $this->sql1 = 'sql1'; diff --git a/lib/adodb/perf/perf-mysql.inc.php b/lib/adodb/perf/perf-mysql.inc.php index 338654d5944..fbaee31dc60 100644 --- a/lib/adodb/perf/perf-mysql.inc.php +++ b/lib/adodb/perf/perf-mysql.inc.php @@ -1,6 +1,8 @@ conn = $conn; } diff --git a/lib/adodb/perf/perf-oci8.inc.php b/lib/adodb/perf/perf-oci8.inc.php index 5dbd7c81cda..c4e58a83277 100644 --- a/lib/adodb/perf/perf-oci8.inc.php +++ b/lib/adodb/perf/perf-oci8.inc.php @@ -1,6 +1,8 @@ conn = $conn; } diff --git a/lib/adodb/pivottable.inc.php b/lib/adodb/pivottable.inc.php index d4695d2ff75..5aeb392d72f 100644 --- a/lib/adodb/pivottable.inc.php +++ b/lib/adodb/pivottable.inc.php @@ -1,6 +1,8 @@ FieldTypesArray(); reset($fieldTypes); $i = 0; + $elements = array(); while(list(,$o) = each($fieldTypes)) { $v = ($o) ? $o->name : 'Field'.($i++); diff --git a/lib/adodb/tohtml.inc.php b/lib/adodb/tohtml.inc.php index 808edf4a100..c628aa7025d 100644 --- a/lib/adodb/tohtml.inc.php +++ b/lib/adodb/tohtml.inc.php @@ -1,6 +1,8 @@ adodb AdoDB BSD/GPL - 5.19 + 5.21 2.1+ -- 2.11.4.GIT