From 5fc6cd44649f570ea43b1329204ec31d4c19a65f Mon Sep 17 00:00:00 2001 From: Shish Date: Fri, 31 Dec 2010 19:05:35 +0000 Subject: [PATCH 01/16] remove adodb --- lib/adodb/adodb-csvlib.inc.php | 318 -- lib/adodb/adodb-error.inc.php | 258 -- lib/adodb/adodb-exceptions.inc.php | 82 - lib/adodb/adodb-iterator.inc.php | 30 - lib/adodb/adodb-lib.inc.php | 1197 ------ lib/adodb/adodb-php4.inc.php | 16 - lib/adodb/adodb-time.inc.php | 1429 ------- lib/adodb/adodb.inc.php | 4416 -------------------- lib/adodb/drivers/adodb-mysql.inc.php | 795 ---- lib/adodb/drivers/adodb-postgres.inc.php | 14 - lib/adodb/drivers/adodb-postgres64.inc.php | 1071 ----- lib/adodb/drivers/adodb-postgres7.inc.php | 313 -- lib/adodb/drivers/adodb-postgres8.inc.php | 12 - lib/adodb/drivers/adodb-sqlite.inc.php | 398 -- lib/adodb/drivers/adodb-sqlitepo.inc.php | 62 - lib/adodb/license.txt | 182 - 16 files changed, 10593 deletions(-) delete mode 100644 lib/adodb/adodb-csvlib.inc.php delete mode 100644 lib/adodb/adodb-error.inc.php delete mode 100644 lib/adodb/adodb-exceptions.inc.php delete mode 100644 lib/adodb/adodb-iterator.inc.php delete mode 100644 lib/adodb/adodb-lib.inc.php delete mode 100644 lib/adodb/adodb-php4.inc.php delete mode 100644 lib/adodb/adodb-time.inc.php delete mode 100644 lib/adodb/adodb.inc.php delete mode 100644 lib/adodb/drivers/adodb-mysql.inc.php delete mode 100644 lib/adodb/drivers/adodb-postgres.inc.php delete mode 100644 lib/adodb/drivers/adodb-postgres64.inc.php delete mode 100644 lib/adodb/drivers/adodb-postgres7.inc.php delete mode 100644 lib/adodb/drivers/adodb-postgres8.inc.php delete mode 100644 lib/adodb/drivers/adodb-sqlite.inc.php delete mode 100644 lib/adodb/drivers/adodb-sqlitepo.inc.php delete mode 100644 lib/adodb/license.txt diff --git a/lib/adodb/adodb-csvlib.inc.php b/lib/adodb/adodb-csvlib.inc.php deleted file mode 100644 index 1c0d0818..00000000 --- a/lib/adodb/adodb-csvlib.inc.php +++ /dev/null @@ -1,318 +0,0 @@ -FieldCount() : 0; - - if ($sql) $sql = urlencode($sql); - // metadata setup - - if ($max <= 0 || $rs->dataProvider == 'empty') { // is insert/update/delete - if (is_object($conn)) { - $sql .= ','.$conn->Affected_Rows(); - $sql .= ','.$conn->Insert_ID(); - } else - $sql .= ',,'; - - $text = "====-1,0,$sql\n"; - return $text; - } - $tt = ($rs->timeCreated) ? $rs->timeCreated : time(); - - ## changed format from ====0 to ====1 - $line = "====1,$tt,$sql\n"; - - if ($rs->databaseType == 'array') { - $rows = $rs->_array; - } else { - $rows = array(); - while (!$rs->EOF) { - $rows[] = $rs->fields; - $rs->MoveNext(); - } - } - - for($i=0; $i < $max; $i++) { - $o = $rs->FetchField($i); - $flds[] = $o; - } - - $savefetch = isset($rs->adodbFetchMode) ? $rs->adodbFetchMode : $rs->fetchMode; - $class = $rs->connection->arrayClass; - $rs2 = new $class(); - $rs2->timeCreated = $rs->timeCreated; # memcache fix - $rs2->sql = $rs->sql; - $rs2->oldProvider = $rs->dataProvider; - $rs2->InitArrayFields($rows,$flds); - $rs2->fetchMode = $savefetch; - return $line.serialize($rs2); - } - - -/** -* Open CSV file and convert it into Data. -* -* @param url file/ftp/http url -* @param err returns the error message -* @param timeout dispose if recordset has been alive for $timeout secs -* -* @return recordset, or false if error occured. If no -* error occurred in sql INSERT/UPDATE/DELETE, -* empty recordset is returned -*/ - function csv2rs($url,&$err,$timeout=0, $rsclass='ADORecordSet_array') - { - $false = false; - $err = false; - $fp = @fopen($url,'rb'); - if (!$fp) { - $err = $url.' file/URL not found'; - return $false; - } - @flock($fp, LOCK_SH); - $arr = array(); - $ttl = 0; - - if ($meta = fgetcsv($fp, 32000, ",")) { - // check if error message - if (strncmp($meta[0],'****',4) === 0) { - $err = trim(substr($meta[0],4,1024)); - fclose($fp); - return $false; - } - // check for meta data - // $meta[0] is -1 means return an empty recordset - // $meta[1] contains a time - - if (strncmp($meta[0], '====',4) === 0) { - - if ($meta[0] == "====-1") { - if (sizeof($meta) < 5) { - $err = "Corrupt first line for format -1"; - fclose($fp); - return $false; - } - fclose($fp); - - if ($timeout > 0) { - $err = " Illegal Timeout $timeout "; - return $false; - } - - $rs = new $rsclass($val=true); - $rs->fields = array(); - $rs->timeCreated = $meta[1]; - $rs->EOF = true; - $rs->_numOfFields = 0; - $rs->sql = urldecode($meta[2]); - $rs->affectedrows = (integer)$meta[3]; - $rs->insertid = $meta[4]; - return $rs; - } - # Under high volume loads, we want only 1 thread/process to _write_file - # so that we don't have 50 processes queueing to write the same data. - # We use probabilistic timeout, ahead of time. - # - # -4 sec before timeout, give processes 1/32 chance of timing out - # -2 sec before timeout, give processes 1/16 chance of timing out - # -1 sec after timeout give processes 1/4 chance of timing out - # +0 sec after timeout, give processes 100% chance of timing out - if (sizeof($meta) > 1) { - if($timeout >0){ - $tdiff = (integer)( $meta[1]+$timeout - time()); - if ($tdiff <= 2) { - switch($tdiff) { - case 4: - case 3: - if ((rand() & 31) == 0) { - fclose($fp); - $err = "Timeout 3"; - return $false; - } - break; - case 2: - if ((rand() & 15) == 0) { - fclose($fp); - $err = "Timeout 2"; - return $false; - } - break; - case 1: - if ((rand() & 3) == 0) { - fclose($fp); - $err = "Timeout 1"; - return $false; - } - break; - default: - fclose($fp); - $err = "Timeout 0"; - return $false; - } // switch - - } // if check flush cache - }// (timeout>0) - $ttl = $meta[1]; - } - //================================================ - // new cache format - use serialize extensively... - if ($meta[0] === '====1') { - // slurp in the data - $MAXSIZE = 128000; - - $text = fread($fp,$MAXSIZE); - if (strlen($text)) { - while ($txt = fread($fp,$MAXSIZE)) { - $text .= $txt; - } - } - fclose($fp); - $rs = unserialize($text); - if (is_object($rs)) $rs->timeCreated = $ttl; - else { - $err = "Unable to unserialize recordset"; - //echo htmlspecialchars($text),' !--END--!

'; - } - return $rs; - } - - $meta = false; - $meta = fgetcsv($fp, 32000, ","); - if (!$meta) { - fclose($fp); - $err = "Unexpected EOF 1"; - return $false; - } - } - - // Get Column definitions - $flds = array(); - foreach($meta as $o) { - $o2 = explode(':',$o); - if (sizeof($o2)!=3) { - $arr[] = $meta; - $flds = false; - break; - } - $fld = new ADOFieldObject(); - $fld->name = urldecode($o2[0]); - $fld->type = $o2[1]; - $fld->max_length = $o2[2]; - $flds[] = $fld; - } - } else { - fclose($fp); - $err = "Recordset had unexpected EOF 2"; - return $false; - } - - // slurp in the data - $MAXSIZE = 128000; - - $text = ''; - while ($txt = fread($fp,$MAXSIZE)) { - $text .= $txt; - } - - fclose($fp); - @$arr = unserialize($text); - //var_dump($arr); - if (!is_array($arr)) { - $err = "Recordset had unexpected EOF (in serialized recordset)"; - if (get_magic_quotes_runtime()) $err .= ". Magic Quotes Runtime should be disabled!"; - return $false; - } - $rs = new $rsclass(); - $rs->timeCreated = $ttl; - $rs->InitArrayFields($arr,$flds); - return $rs; - } - - - /** - * Save a file $filename and its $contents (normally for caching) with file locking - * Returns true if ok, false if fopen/fwrite error, 0 if rename error (eg. file is locked) - */ - function adodb_write_file($filename, $contents,$debug=false) - { - # http://www.php.net/bugs.php?id=9203 Bug that flock fails on Windows - # So to simulate locking, we assume that rename is an atomic operation. - # First we delete $filename, then we create a $tempfile write to it and - # rename to the desired $filename. If the rename works, then we successfully - # modified the file exclusively. - # What a stupid need - having to simulate locking. - # Risks: - # 1. $tempfile name is not unique -- very very low - # 2. unlink($filename) fails -- ok, rename will fail - # 3. adodb reads stale file because unlink fails -- ok, $rs timeout occurs - # 4. another process creates $filename between unlink() and rename() -- ok, rename() fails and cache updated - if (strncmp(PHP_OS,'WIN',3) === 0) { - // skip the decimal place - $mtime = substr(str_replace(' ','_',microtime()),2); - // getmypid() actually returns 0 on Win98 - never mind! - $tmpname = $filename.uniqid($mtime).getmypid(); - if (!($fd = @fopen($tmpname,'w'))) return false; - if (fwrite($fd,$contents)) $ok = true; - else $ok = false; - fclose($fd); - - if ($ok) { - @chmod($tmpname,0644); - // the tricky moment - @unlink($filename); - if (!@rename($tmpname,$filename)) { - unlink($tmpname); - $ok = 0; - } - if (!$ok) { - if ($debug) ADOConnection::outp( " Rename $tmpname ".($ok? 'ok' : 'failed')); - } - } - return $ok; - } - if (!($fd = @fopen($filename, 'a'))) return false; - if (flock($fd, LOCK_EX) && ftruncate($fd, 0)) { - if (fwrite( $fd, $contents )) $ok = true; - else $ok = false; - fclose($fd); - @chmod($filename,0644); - }else { - fclose($fd); - if ($debug)ADOConnection::outp( " Failed acquiring lock for $filename
\n"); - $ok = false; - } - - return $ok; - } -?> \ No newline at end of file diff --git a/lib/adodb/adodb-error.inc.php b/lib/adodb/adodb-error.inc.php deleted file mode 100644 index 6ec614d2..00000000 --- a/lib/adodb/adodb-error.inc.php +++ /dev/null @@ -1,258 +0,0 @@ - DB_ERROR_NOSUCHTABLE, - '/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*/i' => DB_ERROR_ALREADY_EXISTS, - '/divide by zero$/i' => DB_ERROR_DIVZERO, - '/pg_atoi: error in .*: can\'t parse /i' => DB_ERROR_INVALID_NUMBER, - '/ttribute [\"\'].*[\"\'] not found|Relation [\"\'].*[\"\'] does not have attribute [\"\'].*[\"\']/i' => DB_ERROR_NOSUCHFIELD, - '/parser: parse error at or near \"/i' => DB_ERROR_SYNTAX, - '/referential integrity violation/i' => DB_ERROR_CONSTRAINT, - '/Relation [\"\'].*[\"\'] already exists|Cannot insert a duplicate key into (a )?unique index.*|duplicate key.*violates unique constraint/i' - => DB_ERROR_ALREADY_EXISTS - ); - reset($error_regexps); - while (list($regexp,$code) = each($error_regexps)) { - if (preg_match($regexp, $errormsg)) { - return $code; - } - } - // Fall back to DB_ERROR if there was no mapping. - return DB_ERROR; -} - -function adodb_error_odbc() -{ -static $MAP = array( - '01004' => DB_ERROR_TRUNCATED, - '07001' => DB_ERROR_MISMATCH, - '21S01' => DB_ERROR_MISMATCH, - '21S02' => DB_ERROR_MISMATCH, - '22003' => DB_ERROR_INVALID_NUMBER, - '22008' => DB_ERROR_INVALID_DATE, - '22012' => DB_ERROR_DIVZERO, - '23000' => DB_ERROR_CONSTRAINT, - '24000' => DB_ERROR_INVALID, - '34000' => DB_ERROR_INVALID, - '37000' => DB_ERROR_SYNTAX, - '42000' => DB_ERROR_SYNTAX, - 'IM001' => DB_ERROR_UNSUPPORTED, - 'S0000' => DB_ERROR_NOSUCHTABLE, - 'S0001' => DB_ERROR_NOT_FOUND, - 'S0002' => DB_ERROR_NOSUCHTABLE, - 'S0011' => DB_ERROR_ALREADY_EXISTS, - 'S0012' => DB_ERROR_NOT_FOUND, - 'S0021' => DB_ERROR_ALREADY_EXISTS, - 'S0022' => DB_ERROR_NOT_FOUND, - 'S1000' => DB_ERROR_NOSUCHTABLE, - 'S1009' => DB_ERROR_INVALID, - 'S1090' => DB_ERROR_INVALID, - 'S1C00' => DB_ERROR_NOT_CAPABLE - ); - return $MAP; -} - -function adodb_error_ibase() -{ -static $MAP = array( - -104 => DB_ERROR_SYNTAX, - -150 => DB_ERROR_ACCESS_VIOLATION, - -151 => DB_ERROR_ACCESS_VIOLATION, - -155 => DB_ERROR_NOSUCHTABLE, - -157 => DB_ERROR_NOSUCHFIELD, - -158 => DB_ERROR_VALUE_COUNT_ON_ROW, - -170 => DB_ERROR_MISMATCH, - -171 => DB_ERROR_MISMATCH, - -172 => DB_ERROR_INVALID, - -204 => DB_ERROR_INVALID, - -205 => DB_ERROR_NOSUCHFIELD, - -206 => DB_ERROR_NOSUCHFIELD, - -208 => DB_ERROR_INVALID, - -219 => DB_ERROR_NOSUCHTABLE, - -297 => DB_ERROR_CONSTRAINT, - -530 => DB_ERROR_CONSTRAINT, - -803 => DB_ERROR_CONSTRAINT, - -551 => DB_ERROR_ACCESS_VIOLATION, - -552 => DB_ERROR_ACCESS_VIOLATION, - -922 => DB_ERROR_NOSUCHDB, - -923 => DB_ERROR_CONNECT_FAILED, - -924 => DB_ERROR_CONNECT_FAILED - ); - - return $MAP; -} - -function adodb_error_ifx() -{ -static $MAP = array( - '-201' => DB_ERROR_SYNTAX, - '-206' => DB_ERROR_NOSUCHTABLE, - '-217' => DB_ERROR_NOSUCHFIELD, - '-329' => DB_ERROR_NODBSELECTED, - '-1204' => DB_ERROR_INVALID_DATE, - '-1205' => DB_ERROR_INVALID_DATE, - '-1206' => DB_ERROR_INVALID_DATE, - '-1209' => DB_ERROR_INVALID_DATE, - '-1210' => DB_ERROR_INVALID_DATE, - '-1212' => DB_ERROR_INVALID_DATE - ); - - return $MAP; -} - -function adodb_error_oci8() -{ -static $MAP = array( - 1 => DB_ERROR_ALREADY_EXISTS, - 900 => DB_ERROR_SYNTAX, - 904 => DB_ERROR_NOSUCHFIELD, - 923 => DB_ERROR_SYNTAX, - 942 => DB_ERROR_NOSUCHTABLE, - 955 => DB_ERROR_ALREADY_EXISTS, - 1476 => DB_ERROR_DIVZERO, - 1722 => DB_ERROR_INVALID_NUMBER, - 2289 => DB_ERROR_NOSUCHTABLE, - 2291 => DB_ERROR_CONSTRAINT, - 2449 => DB_ERROR_CONSTRAINT - ); - - return $MAP; -} - -function adodb_error_mssql() -{ -static $MAP = array( - 208 => DB_ERROR_NOSUCHTABLE, - 2601 => DB_ERROR_ALREADY_EXISTS - ); - - return $MAP; -} - -function adodb_error_sqlite() -{ -static $MAP = array( - 1 => DB_ERROR_SYNTAX - ); - - return $MAP; -} - -function adodb_error_mysql() -{ -static $MAP = array( - 1004 => DB_ERROR_CANNOT_CREATE, - 1005 => DB_ERROR_CANNOT_CREATE, - 1006 => DB_ERROR_CANNOT_CREATE, - 1007 => DB_ERROR_ALREADY_EXISTS, - 1008 => DB_ERROR_CANNOT_DROP, - 1045 => DB_ERROR_ACCESS_VIOLATION, - 1046 => DB_ERROR_NODBSELECTED, - 1049 => DB_ERROR_NOSUCHDB, - 1050 => DB_ERROR_ALREADY_EXISTS, - 1051 => DB_ERROR_NOSUCHTABLE, - 1054 => DB_ERROR_NOSUCHFIELD, - 1062 => DB_ERROR_ALREADY_EXISTS, - 1064 => DB_ERROR_SYNTAX, - 1100 => DB_ERROR_NOT_LOCKED, - 1136 => DB_ERROR_VALUE_COUNT_ON_ROW, - 1146 => DB_ERROR_NOSUCHTABLE, - 1048 => DB_ERROR_CONSTRAINT, - 2002 => DB_ERROR_CONNECT_FAILED, - 2005 => DB_ERROR_CONNECT_FAILED - ); - - return $MAP; -} -?> \ No newline at end of file diff --git a/lib/adodb/adodb-exceptions.inc.php b/lib/adodb/adodb-exceptions.inc.php deleted file mode 100644 index 65f89432..00000000 --- a/lib/adodb/adodb-exceptions.inc.php +++ /dev/null @@ -1,82 +0,0 @@ -sql = $p1; - $this->params = $p2; - $s = "$dbms error: [$errno: $errmsg] in $fn(\"$p1\")\n"; - break; - - case 'PCONNECT': - case 'CONNECT': - $user = $thisConnection->user; - $s = "$dbms error: [$errno: $errmsg] in $fn($p1, '$user', '****', $p2)\n"; - break; - default: - $s = "$dbms error: [$errno: $errmsg] in $fn($p1, $p2)\n"; - break; - } - - $this->dbms = $dbms; - if ($thisConnection) { - $this->host = $thisConnection->host; - $this->database = $thisConnection->database; - } - $this->fn = $fn; - $this->msg = $errmsg; - - if (!is_numeric($errno)) $errno = -1; - parent::__construct($s,$errno); - } -} - -/** -* Default Error Handler. This will be called with the following params -* -* @param $dbms the RDBMS you are connecting to -* @param $fn the name of the calling function (in uppercase) -* @param $errno the native error number from the database -* @param $errmsg the native error msg from the database -* @param $p1 $fn specific parameter - see below -* @param $P2 $fn specific parameter - see below -*/ - -function adodb_throw($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection) -{ -global $ADODB_EXCEPTION; - - if (error_reporting() == 0) return; // obey @ protocol - if (is_string($ADODB_EXCEPTION)) $errfn = $ADODB_EXCEPTION; - else $errfn = 'ADODB_EXCEPTION'; - throw new $errfn($dbms, $fn, $errno, $errmsg, $p1, $p2, $thisConnection); -} - - -?> \ No newline at end of file diff --git a/lib/adodb/adodb-iterator.inc.php b/lib/adodb/adodb-iterator.inc.php deleted file mode 100644 index e8b5e57b..00000000 --- a/lib/adodb/adodb-iterator.inc.php +++ /dev/null @@ -1,30 +0,0 @@ -Execute("select * from adoxyz"); - foreach($rs as $k => $v) { - echo $k; print_r($v); echo "
"; - } - - - Iterator code based on http://cvs.php.net/cvs.php/php-src/ext/spl/examples/cachingiterator.inc?login=2 - - - Moved to adodb.inc.php to improve performance. - */ - - - - - -?> \ No newline at end of file diff --git a/lib/adodb/adodb-lib.inc.php b/lib/adodb/adodb-lib.inc.php deleted file mode 100644 index 6b2e8910..00000000 --- a/lib/adodb/adodb-lib.inc.php +++ /dev/null @@ -1,1197 +0,0 @@ - sizeof($array)) $max = sizeof($array); - else $max = $probe; - - - for ($j=0;$j < $max; $j++) { - $row = $array[$j]; - if (!$row) break; - $i = -1; - foreach($row as $v) { - $i += 1; - - if (isset($types[$i]) && $types[$i]=='C') continue; - - //print " ($i ".$types[$i]. "$v) "; - $v = trim($v); - - if (!preg_match('/^[+-]{0,1}[0-9\.]+$/',$v)) { - $types[$i] = 'C'; // once C, always C - - continue; - } - if ($j == 0) { - // If 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[$i] = 'C'; - if (strpos($v,'.') !== false) $types[$i] = 'N'; - else $types[$i] = 'I'; - continue; - } - - if (strpos($v,'.') !== false) $types[$i] = 'N'; - - } - } - -} - -function adodb_transpose(&$arr, &$newarr, &$hdr, &$fobjs) -{ - $oldX = sizeof(reset($arr)); - $oldY = sizeof($arr); - - if ($hdr) { - $startx = 1; - $hdr = array('Fields'); - for ($y = 0; $y < $oldY; $y++) { - $hdr[] = $arr[$y][0]; - } - } else - $startx = 0; - - for ($x = $startx; $x < $oldX; $x++) { - if ($fobjs) { - $o = $fobjs[$x]; - $newarr[] = array($o->name); - } else - $newarr[] = array(); - - for ($y = 0; $y < $oldY; $y++) { - $newarr[$x-$startx][] = $arr[$y][$x]; - } - } -} - -// Force key to upper. -// See also http://www.php.net/manual/en/function.array-change-key-case.php -function _array_change_key_case($an_array) -{ - if (is_array($an_array)) { - $new_array = array(); - foreach($an_array as $key=>$value) - $new_array[strtoupper($key)] = $value; - - return $new_array; - } - - return $an_array; -} - -function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc) -{ - if (count($fieldArray) == 0) return 0; - $first = true; - $uSet = ''; - - if (!is_array($keyCol)) { - $keyCol = array($keyCol); - } - foreach($fieldArray as $k => $v) { - if ($v === null) { - $v = 'NULL'; - $fieldArray[$k] = $v; - } else if ($autoQuote && /*!is_numeric($v) /*and strncmp($v,"'",1) !== 0 -- sql injection risk*/ strcasecmp($v,$zthis->null2null)!=0) { - $v = $zthis->qstr($v); - $fieldArray[$k] = $v; - } - if (in_array($k,$keyCol)) continue; // skip UPDATE if is key - - if ($first) { - $first = false; - $uSet = "$k=$v"; - } else - $uSet .= ",$k=$v"; - } - - $where = false; - foreach ($keyCol as $v) { - if (isset($fieldArray[$v])) { - if ($where) $where .= ' and '.$v.'='.$fieldArray[$v]; - else $where = $v.'='.$fieldArray[$v]; - } - } - - if ($uSet && $where) { - $update = "UPDATE $table SET $uSet WHERE $where"; - - $rs = $zthis->Execute($update); - - - if ($rs) { - if ($zthis->poorAffectedRows) { - /* - The Select count(*) wipes out any errors that the update would have returned. - http://phplens.com/lens/lensforum/msgs.php?id=5696 - */ - if ($zthis->ErrorNo()<>0) return 0; - - # affected_rows == 0 if update field values identical to old values - # for mysql - which is silly. - - $cnt = $zthis->GetOne("select count(*) from $table where $where"); - if ($cnt > 0) return 1; // record already exists - } else { - if (($zthis->Affected_Rows()>0)) return 1; - } - } else - return 0; - } - - // print "

Error=".$this->ErrorNo().'

'; - $first = true; - foreach($fieldArray as $k => $v) { - if ($has_autoinc && in_array($k,$keyCol)) continue; // skip autoinc col - - if ($first) { - $first = false; - $iCols = "$k"; - $iVals = "$v"; - } else { - $iCols .= ",$k"; - $iVals .= ",$v"; - } - } - $insert = "INSERT INTO $table ($iCols) VALUES ($iVals)"; - $rs = $zthis->Execute($insert); - return ($rs) ? 2 : 0; -} - -// Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM -function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false, - $size=0, $selectAttr='',$compareFields0=true) -{ - $hasvalue = false; - - if ($multiple or is_array($defstr)) { - if ($size==0) $size=5; - $attr = ' multiple size="'.$size.'"'; - if (!strpos($name,'[]')) $name .= '[]'; - } else if ($size) $attr = ' size="'.$size.'"'; - else $attr =''; - - $s = '\n"; -} - -// Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM -function _adodb_getmenu_gp(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false, - $size=0, $selectAttr='',$compareFields0=true) -{ - $hasvalue = false; - - if ($multiple or is_array($defstr)) { - if ($size==0) $size=5; - $attr = ' multiple size="'.$size.'"'; - if (!strpos($name,'[]')) $name .= '[]'; - } else if ($size) $attr = ' size="'.$size.'"'; - else $attr =''; - - $s = '\n"; -} - - -/* - Count the number of records this sql statement will return by using - query rewriting heuristics... - - Does not work with UNIONs, except with postgresql and oracle. - - Usage: - - $conn->Connect(...); - $cnt = _adodb_getcount($conn, $sql); - -*/ -function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0) -{ - $qryRecs = 0; - - if (!empty($zthis->_nestedSQL) || preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) || - preg_match('/\s+GROUP\s+BY\s+/is',$sql) || - preg_match('/\s+UNION\s+/is',$sql)) { - - $rewritesql = adodb_strip_order_by($sql); - - // ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias - // but this is only supported by oracle and postgresql... - if ($zthis->dataProvider == 'oci8') { - // Allow Oracle hints to be used for query optimization, Chris Wrye - if (preg_match('#/\\*+.*?\\*\\/#', $sql, $hint)) { - $rewritesql = "SELECT ".$hint[0]." COUNT(*) FROM (".$rewritesql.")"; - } else - $rewritesql = "SELECT COUNT(*) FROM (".$rewritesql.")"; - - } else if (strncmp($zthis->databaseType,'postgres',8) == 0 || strncmp($zthis->databaseType,'mysql',5) == 0) { - $rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _ADODB_ALIAS_"; - } else { - $rewritesql = "SELECT COUNT(*) FROM ($rewritesql)"; - } - } else { - // now replace SELECT ... FROM with SELECT COUNT(*) FROM - $rewritesql = preg_replace( - '/^\s*SELECT\s.*\s+FROM\s/Uis','SELECT COUNT(*) FROM ',$sql); - // fix by alexander zhukov, alex#unipack.ru, because count(*) and 'order by' fails - // with mssql, access and postgresql. Also a good speedup optimization - skips sorting! - // also see http://phplens.com/lens/lensforum/msgs.php?id=12752 - $rewritesql = adodb_strip_order_by($rewritesql); - } - - if (isset($rewritesql) && $rewritesql != $sql) { - if (preg_match('/\sLIMIT\s+[0-9]+/i',$sql,$limitarr)) $rewritesql .= $limitarr[0]; - - if ($secs2cache) { - // we only use half the time of secs2cache because the count can quickly - // become inaccurate if new records are added - $qryRecs = $zthis->CacheGetOne($secs2cache/2,$rewritesql,$inputarr); - - } else { - $qryRecs = $zthis->GetOne($rewritesql,$inputarr); - } - if ($qryRecs !== false) return $qryRecs; - } - //-------------------------------------------- - // query rewrite failed - so try slower way... - - - // strip off unneeded ORDER BY if no UNION - if (preg_match('/\s*UNION\s*/is', $sql)) $rewritesql = $sql; - else $rewritesql = $rewritesql = adodb_strip_order_by($sql); - - if (preg_match('/\sLIMIT\s+[0-9]+/i',$sql,$limitarr)) $rewritesql .= $limitarr[0]; - - if ($secs2cache) { - $rstest = $zthis->CacheExecute($secs2cache,$rewritesql,$inputarr); - if (!$rstest) $rstest = $zthis->CacheExecute($secs2cache,$sql,$inputarr); - } else { - $rstest = $zthis->Execute($rewritesql,$inputarr); - if (!$rstest) $rstest = $zthis->Execute($sql,$inputarr); - } - if ($rstest) { - $qryRecs = $rstest->RecordCount(); - if ($qryRecs == -1) { - global $ADODB_EXTENSION; - // some databases will return -1 on MoveLast() - change to MoveNext() - if ($ADODB_EXTENSION) { - while(!$rstest->EOF) { - adodb_movenext($rstest); - } - } else { - while(!$rstest->EOF) { - $rstest->MoveNext(); - } - } - $qryRecs = $rstest->_currentRow; - } - $rstest->Close(); - if ($qryRecs == -1) return 0; - } - return $qryRecs; -} - -/* - Code originally from "Cornel G" - - This code might not work with SQL that has UNION in it - - Also if you are using CachePageExecute(), there is a strong possibility that - data will get out of synch. use CachePageExecute() only with tables that - rarely change. -*/ -function _adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page, - $inputarr=false, $secs2cache=0) -{ - $atfirstpage = false; - $atlastpage = false; - $lastpageno=1; - - // If an invalid nrows is supplied, - // we assume a default value of 10 rows per page - if (!isset($nrows) || $nrows <= 0) $nrows = 10; - - $qryRecs = false; //count records for no offset - - $qryRecs = _adodb_getcount($zthis,$sql,$inputarr,$secs2cache); - $lastpageno = (int) ceil($qryRecs / $nrows); - $zthis->_maxRecordCount = $qryRecs; - - - - // ***** Here we check whether $page is the last page or - // whether we are trying to retrieve - // a page number greater than the last page number. - if ($page >= $lastpageno) { - $page = $lastpageno; - $atlastpage = true; - } - - // If page number <= 1, then we are at the first page - if (empty($page) || $page <= 1) { - $page = 1; - $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); - - - // Before returning the RecordSet, we set the pagination properties we need - if ($rsreturn) { - $rsreturn->_maxRecordCount = $qryRecs; - $rsreturn->rowsPerPage = $nrows; - $rsreturn->AbsolutePage($page); - $rsreturn->AtFirstPage($atfirstpage); - $rsreturn->AtLastPage($atlastpage); - $rsreturn->LastPageNo($lastpageno); - } - return $rsreturn; -} - -// Iván Oliva version -function _adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr=false, $secs2cache=0) -{ - - $atfirstpage = false; - $atlastpage = false; - - if (!isset($page) || $page <= 1) { // If page number <= 1, then we are at the first page - $page = 1; - $atfirstpage = true; - } - if ($nrows <= 0) $nrows = 10; // If an invalid nrows is supplied, we assume a default value of 10 rows per page - - // ***** Here we check whether $page is the last page or whether we are trying to retrieve a page number greater than - // the last page number. - $pagecounter = $page + 1; - $pagecounteroffset = ($pagecounter * $nrows) - $nrows; - if ($secs2cache>0) $rstest = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr); - else $rstest = $zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache); - if ($rstest) { - while ($rstest && $rstest->EOF && $pagecounter>0) { - $atlastpage = true; - $pagecounter--; - $pagecounteroffset = $nrows * ($pagecounter - 1); - $rstest->Close(); - if ($secs2cache>0) $rstest = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr); - else $rstest = $zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache); - } - if ($rstest) $rstest->Close(); - } - if ($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. - } - - // We get the data we want - $offset = $nrows * ($page-1); - if ($secs2cache > 0) $rsreturn = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr); - else $rsreturn = $zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache); - - // Before returning the RecordSet, we set the pagination properties we need - if ($rsreturn) { - $rsreturn->rowsPerPage = $nrows; - $rsreturn->AbsolutePage($page); - $rsreturn->AtFirstPage($atfirstpage); - $rsreturn->AtLastPage($atlastpage); - } - return $rsreturn; -} - -function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=2) -{ - global $ADODB_QUOTE_FIELDNAMES; - - if (!$rs) { - printf(ADODB_BAD_RS,'GetUpdateSQL'); - return false; - } - - $fieldUpdatedCount = 0; - $arrFields = _array_change_key_case($arrFields); - - $hasnumeric = isset($rs->fields[0]); - $setFields = ''; - - // Loop through all of the fields in the recordset - for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) { - // Get the field from the recordset - $field = $rs->FetchField($i); - - // If the recordset field is one - // of the fields passed in then process. - $upperfname = strtoupper($field->name); - if (adodb_key_exists($upperfname,$arrFields,$force)) { - - // If the existing field value in the recordset - // is different from the value passed in then - // go ahead and append the field name and new value to - // the update query. - - if ($hasnumeric) $val = $rs->fields[$i]; - else if (isset($rs->fields[$upperfname])) $val = $rs->fields[$upperfname]; - else if (isset($rs->fields[$field->name])) $val = $rs->fields[$field->name]; - else if (isset($rs->fields[strtolower($upperfname)])) $val = $rs->fields[strtolower($upperfname)]; - else $val = ''; - - - if ($forceUpdate || strcmp($val, $arrFields[$upperfname])) { - // Set the counter for the number of fields that will be updated. - $fieldUpdatedCount++; - - // Based on the datatype of the field - // Format the value properly for the database - $type = $rs->MetaType($field->type); - - - if ($type == 'null') { - $type = 'C'; - } - - if ((strpos($upperfname,' ') !== false) || ($ADODB_QUOTE_FIELDNAMES)) - $fnameq = $zthis->nameQuote.$upperfname.$zthis->nameQuote; - else - $fnameq = $upperfname; - - - // is_null requires php 4.0.4 - //********************************************************// - if (is_null($arrFields[$upperfname]) - || (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0) - || $arrFields[$upperfname] === $zthis->null2null - ) - { - switch ($force) { - - //case 0: - // //Ignore empty values. This is allready handled in "adodb_key_exists" function. - //break; - - case 1: - //Set null - $setFields .= $field->name . " = null, "; - break; - - case 2: - //Set empty - $arrFields[$upperfname] = ""; - $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,$arrFields, $magicq); - break; - default: - case 3: - //Set the value that was given in array, so you can give both null and empty values - if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === $zthis->null2null) { - $setFields .= $field->name . " = null, "; - } else { - $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,$arrFields, $magicq); - } - break; - } - //********************************************************// - } else { - //we do this so each driver can customize the sql for - //DB specific column types. - //Oracle needs BLOB types to be handled with a returning clause - //postgres has special needs as well - $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq, - $arrFields, $magicq); - } - } - } - } - - // If there were any modified fields then build the rest of the update query. - if ($fieldUpdatedCount > 0 || $forceUpdate) { - // Get the table name from the existing query. - if (!empty($rs->tableName)) $tableName = $rs->tableName; - else { - preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName); - $tableName = $tableName[1]; - } - // Get the full where clause excluding the word "WHERE" from - // the existing query. - preg_match('/\sWHERE\s(.*)/is', $rs->sql, $whereClause); - - $discard = false; - // not a good hack, improvements? - if ($whereClause) { - #var_dump($whereClause); - if (preg_match('/\s(ORDER\s.*)/is', $whereClause[1], $discard)); - else if (preg_match('/\s(LIMIT\s.*)/is', $whereClause[1], $discard)); - else if (preg_match('/\s(FOR UPDATE.*)/is', $whereClause[1], $discard)); - else preg_match('/\s.*(\) WHERE .*)/is', $whereClause[1], $discard); # see http://sourceforge.net/tracker/index.php?func=detail&aid=1379638&group_id=42718&atid=433976 - } else - $whereClause = array(false,false); - - if ($discard) - $whereClause[1] = substr($whereClause[1], 0, strlen($whereClause[1]) - strlen($discard[1])); - - $sql = 'UPDATE '.$tableName.' SET '.substr($setFields, 0, -2); - if (strlen($whereClause[1]) > 0) - $sql .= ' WHERE '.$whereClause[1]; - - return $sql; - - } else { - return false; - } -} - -function adodb_key_exists($key, &$arr,$force=2) -{ - if ($force<=0) { - // the following is the old behaviour where null or empty fields are ignored - return (!empty($arr[$key])) || (isset($arr[$key]) && strlen($arr[$key])>0); - } - - if (isset($arr[$key])) return true; - ## null check below - if (ADODB_PHPVER >= 0x4010) return array_key_exists($key,$arr); - return false; -} - -/** - * There is a special case of this function for the oci8 driver. - * The proper way to handle an insert w/ a blob in oracle requires - * a returning clause with bind variables and a descriptor blob. - * - * - */ -function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false,$force=2) -{ -static $cacheRS = false; -static $cacheSig = 0; -static $cacheCols; - global $ADODB_QUOTE_FIELDNAMES; - - $tableName = ''; - $values = ''; - $fields = ''; - $recordSet = null; - $arrFields = _array_change_key_case($arrFields); - $fieldInsertedCount = 0; - - if (is_string($rs)) { - //ok we have a table name - //try and get the column info ourself. - $tableName = $rs; - - //we need an object for the recordSet - //because we have to call MetaType. - //php can't do a $rsclass::MetaType() - $rsclass = $zthis->rsPrefix.$zthis->databaseType; - $recordSet = new $rsclass(-1,$zthis->fetchMode); - $recordSet->connection = $zthis; - - if (is_string($cacheRS) && $cacheRS == $rs) { - $columns = $cacheCols; - } else { - $columns = $zthis->MetaColumns( $tableName ); - $cacheRS = $tableName; - $cacheCols = $columns; - } - } else if (is_subclass_of($rs, 'adorecordset')) { - if (isset($rs->insertSig) && is_integer($cacheRS) && $cacheRS == $rs->insertSig) { - $columns = $cacheCols; - } else { - for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) - $columns[] = $rs->FetchField($i); - $cacheRS = $cacheSig; - $cacheCols = $columns; - $rs->insertSig = $cacheSig++; - } - $recordSet = $rs; - - } else { - printf(ADODB_BAD_RS,'GetInsertSQL'); - return false; - } - - // Loop through all of the fields in the recordset - foreach( $columns as $field ) { - $upperfname = strtoupper($field->name); - if (adodb_key_exists($upperfname,$arrFields,$force)) { - $bad = false; - if ((strpos($upperfname,' ') !== false) || ($ADODB_QUOTE_FIELDNAMES)) - $fnameq = $zthis->nameQuote.$upperfname.$zthis->nameQuote; - else - $fnameq = $upperfname; - - $type = $recordSet->MetaType($field->type); - - /********************************************************/ - if (is_null($arrFields[$upperfname]) - || (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0) - || $arrFields[$upperfname] === $zthis->null2null - ) - { - switch ($force) { - - case 0: // we must always set null if missing - $bad = true; - break; - - case 1: - $values .= "null, "; - break; - - case 2: - //Set empty - $arrFields[$upperfname] = ""; - $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq,$arrFields, $magicq); - break; - - default: - case 3: - //Set the value that was given in array, so you can give both null and empty values - if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === $zthis->null2null) { - $values .= "null, "; - } else { - $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq, $arrFields, $magicq); - } - break; - } // switch - - /*********************************************************/ - } else { - //we do this so each driver can customize the sql for - //DB specific column types. - //Oracle needs BLOB types to be handled with a returning clause - //postgres has special needs as well - $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq, - $arrFields, $magicq); - } - - if ($bad) continue; - // Set the counter for the number of fields that will be inserted. - $fieldInsertedCount++; - - - // Get the name of the fields to insert - $fields .= $fnameq . ", "; - } - } - - - // If there were any inserted fields then build the rest of the insert query. - if ($fieldInsertedCount <= 0) return false; - - // Get the table name from the existing query. - if (!$tableName) { - if (!empty($rs->tableName)) $tableName = $rs->tableName; - else if (preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName)) - $tableName = $tableName[1]; - else - return false; - } - - // Strip off the comma and space on the end of both the fields - // and their values. - $fields = substr($fields, 0, -2); - $values = substr($values, 0, -2); - - // Append the fields and their values to the insert query. - return 'INSERT INTO '.$tableName.' ( '.$fields.' ) VALUES ( '.$values.' )'; -} - - -/** - * This private method is used to help construct - * the update/sql which is generated by GetInsertSQL and GetUpdateSQL. - * It handles the string construction of 1 column -> sql string based on - * the column type. We want to do 'safe' handling of BLOBs - * - * @param string the type of sql we are trying to create - * 'I' or 'U'. - * @param string column data type from the db::MetaType() method - * @param string the column name - * @param array the column value - * - * @return string - * - */ -function _adodb_column_sql_oci8(&$zthis,$action, $type, $fname, $fnameq, $arrFields, $magicq) -{ - $sql = ''; - - // Based on the datatype of the field - // Format the value properly for the database - switch($type) { - case 'B': - //in order to handle Blobs correctly, we need - //to do some magic for Oracle - - //we need to create a new descriptor to handle - //this properly - if (!empty($zthis->hasReturningInto)) { - if ($action == 'I') { - $sql = 'empty_blob(), '; - } else { - $sql = $fnameq. '=empty_blob(), '; - } - //add the variable to the returning clause array - //so the user can build this later in - //case they want to add more to it - $zthis->_returningArray[$fname] = ':xx'.$fname.'xx'; - } else if (empty($arrFields[$fname])){ - if ($action == 'I') { - $sql = 'empty_blob(), '; - } else { - $sql = $fnameq. '=empty_blob(), '; - } - } else { - //this is to maintain compatibility - //with older adodb versions. - $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false); - } - break; - - case "X": - //we need to do some more magic here for long variables - //to handle these correctly in oracle. - - //create a safe bind var name - //to avoid conflicts w/ dupes. - if (!empty($zthis->hasReturningInto)) { - if ($action == 'I') { - $sql = ':xx'.$fname.'xx, '; - } else { - $sql = $fnameq.'=:xx'.$fname.'xx, '; - } - //add the variable to the returning clause array - //so the user can build this later in - //case they want to add more to it - $zthis->_returningArray[$fname] = ':xx'.$fname.'xx'; - } else { - //this is to maintain compatibility - //with older adodb versions. - $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false); - } - break; - - default: - $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false); - break; - } - - return $sql; -} - -function _adodb_column_sql(&$zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq, $recurse=true) -{ - - if ($recurse) { - switch($zthis->dataProvider) { - case 'postgres': - if ($type == 'L') $type = 'C'; - break; - case 'oci8': - return _adodb_column_sql_oci8($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq); - - } - } - - switch($type) { - case "C": - case "X": - case 'B': - $val = $zthis->qstr($arrFields[$fname],$magicq); - break; - - case "D": - $val = $zthis->DBDate($arrFields[$fname]); - break; - - case "T": - $val = $zthis->DBTimeStamp($arrFields[$fname]); - break; - - case "N": - $val = $arrFields[$fname]; - if (!is_numeric($val)) $val = str_replace(',', '.', (float)$val); - break; - - case "I": - case "R": - $val = $arrFields[$fname]; - if (!is_numeric($val)) $val = (integer) $val; - break; - - default: - $val = str_replace(array("'"," ","("),"",$arrFields[$fname]); // basic sql injection defence - if (empty($val)) $val = '0'; - break; - } - - if ($action == 'I') return $val . ", "; - - - return $fnameq . "=" . $val . ", "; - -} - - - -function _adodb_debug_execute(&$zthis, $sql, $inputarr) -{ - $ss = ''; - if ($inputarr) { - foreach($inputarr as $kk=>$vv) { - if (is_string($vv) && strlen($vv)>64) $vv = substr($vv,0,64).'...'; - if (is_null($vv)) $ss .= "($kk=>null) "; - else $ss .= "($kk=>'$vv') "; - } - $ss = "[ $ss ]"; - } - $sqlTxt = is_array($sql) ? $sql[0] : $sql; - /*str_replace(', ','##1#__^LF',is_array($sql) ? $sql[0] : $sql); - $sqlTxt = str_replace(',',', ',$sqlTxt); - $sqlTxt = str_replace('##1#__^LF', ', ' ,$sqlTxt); - */ - // check if running from browser or command-line - $inBrowser = isset($_SERVER['HTTP_USER_AGENT']); - - $dbt = $zthis->databaseType; - if (isset($zthis->dsnType)) $dbt .= '-'.$zthis->dsnType; - if ($inBrowser) { - if ($ss) { - $ss = ''.htmlspecialchars($ss).''; - } - if ($zthis->debug === -1) - ADOConnection::outp( "
\n($dbt): ".htmlspecialchars($sqlTxt)."   $ss\n
\n",false); - else if ($zthis->debug !== -99) - ADOConnection::outp( "


\n($dbt): ".htmlspecialchars($sqlTxt)."   $ss\n
\n",false); - } else { - $ss = "\n ".$ss; - if ($zthis->debug !== -99) - ADOConnection::outp("-----
\n($dbt): ".$sqlTxt." $ss\n-----
\n",false); - } - - $qID = $zthis->_query($sql,$inputarr); - - /* - Alexios Fakios notes that ErrorMsg() must be called before ErrorNo() for mssql - because ErrorNo() calls Execute('SELECT @ERROR'), causing recursion - */ - if ($zthis->databaseType == 'mssql') { - // ErrorNo is a slow function call in mssql, and not reliable in PHP 4.0.6 - - if($emsg = $zthis->ErrorMsg()) { - if ($err = $zthis->ErrorNo()) { - if ($zthis->debug === -99) - ADOConnection::outp( "
\n($dbt): ".htmlspecialchars($sqlTxt)."   $ss\n
\n",false); - - ADOConnection::outp($err.': '.$emsg); - } - } - } else if (!$qID) { - - if ($zthis->debug === -99) - if ($inBrowser) ADOConnection::outp( "
\n($dbt): ".htmlspecialchars($sqlTxt)."   $ss\n
\n",false); - else ADOConnection::outp("-----
\n($dbt): ".$sqlTxt."$ss\n-----
\n",false); - - ADOConnection::outp($zthis->ErrorNo() .': '. $zthis->ErrorMsg()); - } - - if ($zthis->debug === 99) _adodb_backtrace(true,9999,2); - return $qID; -} - -# pretty print the debug_backtrace function -function _adodb_backtrace($printOrArr=true,$levels=9999,$skippy=0,$ishtml=null) -{ - if (!function_exists('debug_backtrace')) return ''; - - if ($ishtml === null) $html = (isset($_SERVER['HTTP_USER_AGENT'])); - else $html = $ishtml; - - $fmt = ($html) ? " %% line %4d, file: %s" : "%% line %4d, file: %s"; - - $MAXSTRLEN = 128; - - $s = ($html) ? '
' : '';
-	
-	if (is_array($printOrArr)) $traceArr = $printOrArr;
-	else $traceArr = debug_backtrace();
-	array_shift($traceArr);
-	array_shift($traceArr);
-	$tabs = sizeof($traceArr)-2;
-	
-	foreach ($traceArr as $arr) {
-		if ($skippy) {$skippy -= 1; continue;}
-		$levels -= 1;
-		if ($levels < 0) break;
-		
-		$args = array();
-		for ($i=0; $i < $tabs; $i++) $s .=  ($html) ? '   ' : "\t";
-		$tabs -= 1;
-		if ($html) $s .= '';
-		if (isset($arr['class'])) $s .= $arr['class'].'.';
-		if (isset($arr['args']))
-		 foreach($arr['args'] as $v) {
-			if (is_null($v)) $args[] = 'null';
-			else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';
-			else if (is_object($v)) $args[] = 'Object:'.get_class($v);
-			else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
-			else {
-				$v = (string) @$v;
-				$str = htmlspecialchars(str_replace(array("\r","\n"),' ',substr($v,0,$MAXSTRLEN)));
-				if (strlen($v) > $MAXSTRLEN) $str .= '...';
-				$args[] = $str;
-			}
-		}
-		$s .= $arr['function'].'('.implode(', ',$args).')';
-		
-		
-		$s .= @sprintf($fmt, $arr['line'],$arr['file'],basename($arr['file']));
-			
-		$s .= "\n";
-	}	
-	if ($html) $s .= '
'; - if ($printOrArr) print $s; - - return $s; -} -/* -function _adodb_find_from($sql) -{ - - $sql = str_replace(array("\n","\r"), ' ', $sql); - $charCount = strlen($sql); - - $inString = false; - $quote = ''; - $parentheseCount = 0; - $prevChars = ''; - $nextChars = ''; - - - for($i = 0; $i < $charCount; $i++) { - - $char = substr($sql,$i,1); - $prevChars = substr($sql,0,$i); - $nextChars = substr($sql,$i+1); - - if((($char == "'" || $char == '"' || $char == '`') && substr($prevChars,-1,1) != '\\') && $inString === false) { - $quote = $char; - $inString = true; - } - - elseif((($char == "'" || $char == '"' || $char == '`') && substr($prevChars,-1,1) != '\\') && $inString === true && $quote == $char) { - $quote = ""; - $inString = false; - } - - elseif($char == "(" && $inString === false) - $parentheseCount++; - - elseif($char == ")" && $inString === false && $parentheseCount > 0) - $parentheseCount--; - - elseif($parentheseCount <= 0 && $inString === false && $char == " " && strtoupper(substr($prevChars,-5,5)) == " FROM") - return $i; - - } -} -*/ - -?> \ No newline at end of file diff --git a/lib/adodb/adodb-php4.inc.php b/lib/adodb/adodb-php4.inc.php deleted file mode 100644 index e46a74d8..00000000 --- a/lib/adodb/adodb-php4.inc.php +++ /dev/null @@ -1,16 +0,0 @@ - \ No newline at end of file diff --git a/lib/adodb/adodb-time.inc.php b/lib/adodb/adodb-time.inc.php deleted file mode 100644 index d62f6784..00000000 --- a/lib/adodb/adodb-time.inc.php +++ /dev/null @@ -1,1429 +0,0 @@ - 4 digit year conversion. The maximum is billions of years in the -future, but this is a theoretical limit as the computation of that year -would take too long with the current implementation of adodb_mktime(). - -This library replaces native functions as follows: - -
	
-	getdate()  with  adodb_getdate()
-	date()     with  adodb_date() 
-	gmdate()   with  adodb_gmdate()
-	mktime()   with  adodb_mktime()
-	gmmktime() with  adodb_gmmktime()
-	strftime() with  adodb_strftime()
-	strftime() with  adodb_gmstrftime()
-
- -The parameters are identical, except that adodb_date() accepts a subset -of date()'s field formats. Mktime() will convert from local time to GMT, -and date() will convert from GMT to local time, but daylight savings is -not handled currently. - -This library is independant of the rest of ADOdb, and can be used -as standalone code. - -PERFORMANCE - -For high speed, this library uses the native date functions where -possible, and only switches to PHP code when the dates fall outside -the 32-bit signed integer range. - -GREGORIAN CORRECTION - -Pope Gregory shortened October of A.D. 1582 by ten days. Thursday, -October 4, 1582 (Julian) was followed immediately by Friday, October 15, -1582 (Gregorian). - -Since 0.06, we handle this correctly, so: - -adodb_mktime(0,0,0,10,15,1582) - adodb_mktime(0,0,0,10,4,1582) - == 24 * 3600 (1 day) - -============================================================================= - -COPYRIGHT - -(c) 2003-2005 John Lim and released under BSD-style license except for code by -jackbbs, which includes adodb_mktime, adodb_get_gmt_diff, adodb_is_leap_year -and originally found at http://www.php.net/manual/en/function.mktime.php - -============================================================================= - -BUG REPORTS - -These should be posted to the ADOdb forums at - - http://phplens.com/lens/lensforum/topics.php?id=4 - -============================================================================= - -FUNCTION DESCRIPTIONS - - -** FUNCTION adodb_getdate($date=false) - -Returns an array containing date information, as getdate(), but supports -dates greater than 1901 to 2038. The local date/time format is derived from a -heuristic the first time adodb_getdate is called. - - -** FUNCTION adodb_date($fmt, $timestamp = false) - -Convert a timestamp to a formatted local date. If $timestamp is not defined, the -current timestamp is used. Unlike the function date(), it supports dates -outside the 1901 to 2038 range. - -The format fields that adodb_date supports: - -
-	a - "am" or "pm" 
-	A - "AM" or "PM" 
-	d - day of the month, 2 digits with leading zeros; i.e. "01" to "31" 
-	D - day of the week, textual, 3 letters; e.g. "Fri" 
-	F - month, textual, long; e.g. "January" 
-	g - hour, 12-hour format without leading zeros; i.e. "1" to "12" 
-	G - hour, 24-hour format without leading zeros; i.e. "0" to "23" 
-	h - hour, 12-hour format; i.e. "01" to "12" 
-	H - hour, 24-hour format; i.e. "00" to "23" 
-	i - minutes; i.e. "00" to "59" 
-	j - day of the month without leading zeros; i.e. "1" to "31" 
-	l (lowercase 'L') - day of the week, textual, long; e.g. "Friday"  
-	L - boolean for whether it is a leap year; i.e. "0" or "1" 
-	m - month; i.e. "01" to "12" 
-	M - month, textual, 3 letters; e.g. "Jan" 
-	n - month without leading zeros; i.e. "1" to "12" 
-	O - Difference to Greenwich time in hours; e.g. "+0200" 
-	Q - Quarter, as in 1, 2, 3, 4 
-	r - RFC 2822 formatted date; e.g. "Thu, 21 Dec 2000 16:01:07 +0200" 
-	s - seconds; i.e. "00" to "59" 
-	S - English ordinal suffix for the day of the month, 2 characters; 
-	   			i.e. "st", "nd", "rd" or "th" 
-	t - number of days in the given month; i.e. "28" to "31"
-	T - Timezone setting of this machine; e.g. "EST" or "MDT" 
-	U - seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)  
-	w - day of the week, numeric, i.e. "0" (Sunday) to "6" (Saturday) 
-	Y - year, 4 digits; e.g. "1999" 
-	y - year, 2 digits; e.g. "99" 
-	z - day of the year; i.e. "0" to "365" 
-	Z - timezone offset in seconds (i.e. "-43200" to "43200"). 
-	   			The offset for timezones west of UTC is always negative, 
-				and for those east of UTC is always positive. 
-
- -Unsupported: -
-	B - Swatch Internet time 
-	I (capital i) - "1" if Daylight Savings Time, "0" otherwise.
-	W - ISO-8601 week number of year, weeks starting on Monday 
-
-
- - -** FUNCTION adodb_date2($fmt, $isoDateString = false) -Same as adodb_date, but 2nd parameter accepts iso date, eg. - - adodb_date2('d-M-Y H:i','2003-12-25 13:01:34'); - - -** FUNCTION adodb_gmdate($fmt, $timestamp = false) - -Convert a timestamp to a formatted GMT date. If $timestamp is not defined, the -current timestamp is used. Unlike the function date(), it supports dates -outside the 1901 to 2038 range. - - -** FUNCTION adodb_mktime($hr, $min, $sec[, $month, $day, $year]) - -Converts a local date to a unix timestamp. Unlike the function mktime(), it supports -dates outside the 1901 to 2038 range. All parameters are optional. - - -** FUNCTION adodb_gmmktime($hr, $min, $sec [, $month, $day, $year]) - -Converts a gmt date to a unix timestamp. Unlike the function gmmktime(), it supports -dates outside the 1901 to 2038 range. Differs from gmmktime() in that all parameters -are currently compulsory. - -** FUNCTION adodb_gmstrftime($fmt, $timestamp = false) -Convert a timestamp to a formatted GMT date. - -** FUNCTION adodb_strftime($fmt, $timestamp = false) - -Convert a timestamp to a formatted local date. Internally converts $fmt into -adodb_date format, then echo result. - -For best results, you can define the local date format yourself. Define a global -variable $ADODB_DATE_LOCALE which is an array, 1st element is date format using -adodb_date syntax, and 2nd element is the time format, also in adodb_date syntax. - - eg. $ADODB_DATE_LOCALE = array('d/m/Y','H:i:s'); - - Supported format codes: - -
-	%a - abbreviated weekday name according to the current locale 
-	%A - full weekday name according to the current locale 
-	%b - abbreviated month name according to the current locale 
-	%B - full month name according to the current locale 
-	%c - preferred date and time representation for the current locale 
-	%d - day of the month as a decimal number (range 01 to 31) 
-	%D - same as %m/%d/%y 
-	%e - day of the month as a decimal number, a single digit is preceded by a space (range ' 1' to '31') 
-	%h - same as %b
-	%H - hour as a decimal number using a 24-hour clock (range 00 to 23) 
-	%I - hour as a decimal number using a 12-hour clock (range 01 to 12) 
-	%m - month as a decimal number (range 01 to 12) 
-	%M - minute as a decimal number 
-	%n - newline character 
-	%p - either `am' or `pm' according to the given time value, or the corresponding strings for the current locale 
-	%r - time in a.m. and p.m. notation 
-	%R - time in 24 hour notation 
-	%S - second as a decimal number 
-	%t - tab character 
-	%T - current time, equal to %H:%M:%S 
-	%x - preferred date representation for the current locale without the time 
-	%X - preferred time representation for the current locale without the date 
-	%y - year as a decimal number without a century (range 00 to 99) 
-	%Y - year as a decimal number including the century 
-	%Z - time zone or name or abbreviation 
-	%% - a literal `%' character 
-
- - Unsupported codes: -
-	%C - century number (the year divided by 100 and truncated to an integer, range 00 to 99) 
-	%g - like %G, but without the century. 
-	%G - The 4-digit year corresponding to the ISO week number (see %V). 
-	     This has the same format and value as %Y, except that if the ISO week number belongs 
-		 to the previous or next year, that year is used instead. 
-	%j - day of the year as a decimal number (range 001 to 366) 
-	%u - weekday as a decimal number [1,7], with 1 representing Monday 
-	%U - week number of the current year as a decimal number, starting 
-	    with the first Sunday as the first day of the first week 
-	%V - The ISO 8601:1988 week number of the current year as a decimal number, 
-	     range 01 to 53, where week 1 is the first week that has at least 4 days in the 
-		 current year, and with Monday as the first day of the week. (Use %G or %g for 
-		 the year component that corresponds to the week number for the specified timestamp.) 
-	%w - day of the week as a decimal, Sunday being 0 
-	%W - week number of the current year as a decimal number, starting with the 
-	     first Monday as the first day of the first week 
-
- -============================================================================= - -NOTES - -Useful url for generating test timestamps: - http://www.4webhelp.net/us/timestamp.php - -Possible future optimizations include - -a. Using an algorithm similar to Plauger's in "The Standard C Library" -(page 428, xttotm.c _Ttotm() function). Plauger's algorithm will not -work outside 32-bit signed range, so i decided not to implement it. - -b. Implement daylight savings, which looks awfully complicated, see - http://webexhibits.org/daylightsaving/ - - -CHANGELOG - -- 11 Feb 2008 0.33 -* Bug in 0.32 fix for hour handling. Fixed. - -- 1 Feb 2008 0.32 -* Now adodb_mktime(0,0,0,12+$m,20,2040) works properly. - -- 10 Jan 2008 0.31 -* Now adodb_mktime(0,0,0,24,1,2037) works correctly. - -- 15 July 2007 0.30 -Added PHP 5.2.0 compatability fixes. - * gmtime behaviour for 1970 has changed. We use the actual date if it is between 1970 to 2038 to get the - * timezone, otherwise we use the current year as the baseline to retrieve the timezone. - * Also the timezone's in php 5.2.* support historical data better, eg. if timezone today was +8, but - in 1970 it was +7:30, then php 5.2 return +7:30, while this library will use +8. - * - -- 19 March 2006 0.24 -Changed strftime() locale detection, because some locales prepend the day of week to the date when %c is used. - -- 10 Feb 2006 0.23 -PHP5 compat: when we detect PHP5, the RFC2822 format for gmt 0000hrs is changed from -0000 to +0000. - In PHP4, we will still use -0000 for 100% compat with PHP4. - -- 08 Sept 2005 0.22 -In adodb_date2(), $is_gmt not supported properly. Fixed. - -- 18 July 2005 0.21 -In PHP 4.3.11, the 'r' format has changed. Leading 0 in day is added. Changed for compat. -Added support for negative months in adodb_mktime(). - -- 24 Feb 2005 0.20 -Added limited strftime/gmstrftime support. x10 improvement in performance of adodb_date(). - -- 21 Dec 2004 0.17 -In adodb_getdate(), the timestamp was accidentally converted to gmt when $is_gmt is false. -Also adodb_mktime(0,0,0) did not work properly. Both fixed thx Mauro. - -- 17 Nov 2004 0.16 -Removed intval typecast in adodb_mktime() for secs, allowing: - adodb_mktime(0,0,0 + 2236672153,1,1,1934); -Suggested by Ryan. - -- 18 July 2004 0.15 -All params in adodb_mktime were formerly compulsory. Now only the hour, min, secs is compulsory. -This brings it more in line with mktime (still not identical). - -- 23 June 2004 0.14 - -Allow you to define your own daylights savings function, adodb_daylight_sv. -If the function is defined (somewhere in an include), then you can correct for daylights savings. - -In this example, we apply daylights savings in June or July, adding one hour. This is extremely -unrealistic as it does not take into account time-zone, geographic location, current year. - -function adodb_daylight_sv(&$arr, $is_gmt) -{ - if ($is_gmt) return; - $m = $arr['mon']; - if ($m == 6 || $m == 7) $arr['hours'] += 1; -} - -This is only called by adodb_date() and not by adodb_mktime(). - -The format of $arr is -Array ( - [seconds] => 0 - [minutes] => 0 - [hours] => 0 - [mday] => 1 # day of month, eg 1st day of the month - [mon] => 2 # month (eg. Feb) - [year] => 2102 - [yday] => 31 # days in current year - [leap] => # true if leap year - [ndays] => 28 # no of days in current month - ) - - -- 28 Apr 2004 0.13 -Fixed adodb_date to properly support $is_gmt. Thx to Dimitar Angelov. - -- 20 Mar 2004 0.12 -Fixed month calculation error in adodb_date. 2102-June-01 appeared as 2102-May-32. - -- 26 Oct 2003 0.11 -Because of daylight savings problems (some systems apply daylight savings to -January!!!), changed adodb_get_gmt_diff() to ignore daylight savings. - -- 9 Aug 2003 0.10 -Fixed bug with dates after 2038. -See http://phplens.com/lens/lensforum/msgs.php?id=6980 - -- 1 July 2003 0.09 -Added support for Q (Quarter). -Added adodb_date2(), which accepts ISO date in 2nd param - -- 3 March 2003 0.08 -Added support for 'S' adodb_date() format char. Added constant ADODB_ALLOW_NEGATIVE_TS -if you want PHP to handle negative timestamps between 1901 to 1969. - -- 27 Feb 2003 0.07 -All negative numbers handled by adodb now because of RH 7.3+ problems. -See http://bugs.php.net/bug.php?id=20048&edit=2 - -- 4 Feb 2003 0.06 -Fixed a typo, 1852 changed to 1582! This means that pre-1852 dates -are now correctly handled. - -- 29 Jan 2003 0.05 - -Leap year checking differs under Julian calendar (pre 1582). Also -leap year code optimized by checking for most common case first. - -We also handle month overflow correctly in mktime (eg month set to 13). - -Day overflow for less than one month's days is supported. - -- 28 Jan 2003 0.04 - -Gregorian correction handled. In PHP5, we might throw an error if -mktime uses invalid dates around 5-14 Oct 1582. Released with ADOdb 3.10. -Added limbo 5-14 Oct 1582 check, when we set to 15 Oct 1582. - -- 27 Jan 2003 0.03 - -Fixed some more month problems due to gmt issues. Added constant ADODB_DATE_VERSION. -Fixed calculation of days since start of year for <1970. - -- 27 Jan 2003 0.02 - -Changed _adodb_getdate() to inline leap year checking for better performance. -Fixed problem with time-zones west of GMT +0000. - -- 24 Jan 2003 0.01 - -First implementation. -*/ - - -/* Initialization */ - -/* - Version Number -*/ -define('ADODB_DATE_VERSION',0.33); - -$ADODB_DATETIME_CLASS = (PHP_VERSION >= 5.2); - -/* - This code was originally for windows. But apparently this problem happens - also with Linux, RH 7.3 and later! - - glibc-2.2.5-34 and greater has been changed to return -1 for dates < - 1970. This used to work. The problem exists with RedHat 7.3 and 8.0 - echo (mktime(0, 0, 0, 1, 1, 1960)); // prints -1 - - References: - http://bugs.php.net/bug.php?id=20048&edit=2 - http://lists.debian.org/debian-glibc/2002/debian-glibc-200205/msg00010.html -*/ - -if (!defined('ADODB_ALLOW_NEGATIVE_TS')) define('ADODB_NO_NEGATIVE_TS',1); - -function adodb_date_test_date($y1,$m,$d=13) -{ - $h = round(rand()% 24); - $t = adodb_mktime($h,0,0,$m,$d,$y1); - $rez = adodb_date('Y-n-j H:i:s',$t); - if ($h == 0) $h = '00'; - else if ($h < 10) $h = '0'.$h; - if ("$y1-$m-$d $h:00:00" != $rez) { - print "$y1 error, expected=$y1-$m-$d $h:00:00, adodb=$rez
"; - return false; - } - return true; -} - -function adodb_date_test_strftime($fmt) -{ - $s1 = strftime($fmt); - $s2 = adodb_strftime($fmt); - - if ($s1 == $s2) return true; - - echo "error for $fmt, strftime=$s1, adodb=$s2
"; - return false; -} - -/** - Test Suite -*/ -function adodb_date_test() -{ - - for ($m=-24; $m<=24; $m++) - echo "$m :",adodb_date('d-m-Y',adodb_mktime(0,0,0,1+$m,20,2040)),"
"; - - error_reporting(E_ALL); - print "

Testing adodb_date and adodb_mktime. version=".ADODB_DATE_VERSION.' PHP='.PHP_VERSION."

"; - @set_time_limit(0); - $fail = false; - - // This flag disables calling of PHP native functions, so we can properly test the code - if (!defined('ADODB_TEST_DATES')) define('ADODB_TEST_DATES',1); - - $t = time(); - - - $fmt = 'Y-m-d H:i:s'; - echo '
';
-	echo 'adodb: ',adodb_date($fmt,$t),'
'; - echo 'php : ',date($fmt,$t),'
'; - echo '
'; - - adodb_date_test_strftime('%Y %m %x %X'); - adodb_date_test_strftime("%A %d %B %Y"); - adodb_date_test_strftime("%H %M S"); - - $t = adodb_mktime(0,0,0); - if (!(adodb_date('Y-m-d') == date('Y-m-d'))) print 'Error in '.adodb_mktime(0,0,0).'
'; - - $t = adodb_mktime(0,0,0,6,1,2102); - if (!(adodb_date('Y-m-d',$t) == '2102-06-01')) print 'Error in '.adodb_date('Y-m-d',$t).'
'; - - $t = adodb_mktime(0,0,0,2,1,2102); - if (!(adodb_date('Y-m-d',$t) == '2102-02-01')) print 'Error in '.adodb_date('Y-m-d',$t).'
'; - - - print "

Testing gregorian <=> julian conversion

"; - $t = adodb_mktime(0,0,0,10,11,1492); - //http://www.holidayorigins.com/html/columbus_day.html - Friday check - if (!(adodb_date('D Y-m-d',$t) == 'Fri 1492-10-11')) print 'Error in Columbus landing
'; - - $t = adodb_mktime(0,0,0,2,29,1500); - if (!(adodb_date('Y-m-d',$t) == '1500-02-29')) print 'Error in julian leap years
'; - - $t = adodb_mktime(0,0,0,2,29,1700); - if (!(adodb_date('Y-m-d',$t) == '1700-03-01')) print 'Error in gregorian leap years
'; - - print adodb_mktime(0,0,0,10,4,1582).' '; - print adodb_mktime(0,0,0,10,15,1582); - $diff = (adodb_mktime(0,0,0,10,15,1582) - adodb_mktime(0,0,0,10,4,1582)); - if ($diff != 3600*24) print " Error in gregorian correction = ".($diff/3600/24)." days
"; - - print " 15 Oct 1582, Fri=".(adodb_dow(1582,10,15) == 5 ? 'Fri' : 'Error')."
"; - print " 4 Oct 1582, Thu=".(adodb_dow(1582,10,4) == 4 ? 'Thu' : 'Error')."
"; - - print "

Testing overflow

"; - - $t = adodb_mktime(0,0,0,3,33,1965); - if (!(adodb_date('Y-m-d',$t) == '1965-04-02')) print 'Error in day overflow 1
'; - $t = adodb_mktime(0,0,0,4,33,1971); - if (!(adodb_date('Y-m-d',$t) == '1971-05-03')) print 'Error in day overflow 2
'; - $t = adodb_mktime(0,0,0,1,60,1965); - if (!(adodb_date('Y-m-d',$t) == '1965-03-01')) print 'Error in day overflow 3 '.adodb_date('Y-m-d',$t).'
'; - $t = adodb_mktime(0,0,0,12,32,1965); - if (!(adodb_date('Y-m-d',$t) == '1966-01-01')) print 'Error in day overflow 4 '.adodb_date('Y-m-d',$t).'
'; - $t = adodb_mktime(0,0,0,12,63,1965); - if (!(adodb_date('Y-m-d',$t) == '1966-02-01')) print 'Error in day overflow 5 '.adodb_date('Y-m-d',$t).'
'; - $t = adodb_mktime(0,0,0,13,3,1965); - if (!(adodb_date('Y-m-d',$t) == '1966-01-03')) print 'Error in mth overflow 1
'; - - print "Testing 2-digit => 4-digit year conversion

"; - if (adodb_year_digit_check(00) != 2000) print "Err 2-digit 2000
"; - if (adodb_year_digit_check(10) != 2010) print "Err 2-digit 2010
"; - if (adodb_year_digit_check(20) != 2020) print "Err 2-digit 2020
"; - if (adodb_year_digit_check(30) != 2030) print "Err 2-digit 2030
"; - if (adodb_year_digit_check(40) != 1940) print "Err 2-digit 1940
"; - if (adodb_year_digit_check(50) != 1950) print "Err 2-digit 1950
"; - if (adodb_year_digit_check(90) != 1990) print "Err 2-digit 1990
"; - - // Test string formating - print "

Testing date formating

"; - - $fmt = '\d\a\t\e T Y-m-d H:i:s a A d D F g G h H i j l L m M n O \R\F\C2822 r s t U w y Y z Z 2003'; - $s1 = date($fmt,0); - $s2 = adodb_date($fmt,0); - if ($s1 != $s2) { - print " date() 0 failed
$s1
$s2
"; - } - flush(); - for ($i=100; --$i > 0; ) { - - $ts = 3600.0*((rand()%60000)+(rand()%60000))+(rand()%60000); - $s1 = date($fmt,$ts); - $s2 = adodb_date($fmt,$ts); - //print "$s1
$s2

"; - $pos = strcmp($s1,$s2); - - if (($s1) != ($s2)) { - for ($j=0,$k=strlen($s1); $j < $k; $j++) { - if ($s1[$j] != $s2[$j]) { - print substr($s1,$j).' '; - break; - } - } - print "Error date(): $ts

 
-  \"$s1\" (date len=".strlen($s1).")
-  \"$s2\" (adodb_date len=".strlen($s2).")

"; - $fail = true; - } - - $a1 = getdate($ts); - $a2 = adodb_getdate($ts); - $rez = array_diff($a1,$a2); - if (sizeof($rez)>0) { - print "Error getdate() $ts
"; - print_r($a1); - print "
"; - print_r($a2); - print "

"; - $fail = true; - } - } - - // Test generation of dates outside 1901-2038 - print "

Testing random dates between 100 and 4000

"; - adodb_date_test_date(100,1); - for ($i=100; --$i >= 0;) { - $y1 = 100+rand(0,1970-100); - $m = rand(1,12); - adodb_date_test_date($y1,$m); - - $y1 = 3000-rand(0,3000-1970); - adodb_date_test_date($y1,$m); - } - print '

'; - $start = 1960+rand(0,10); - $yrs = 12; - $i = 365.25*86400*($start-1970); - $offset = 36000+rand(10000,60000); - $max = 365*$yrs*86400; - $lastyear = 0; - - // we generate a timestamp, convert it to a date, and convert it back to a timestamp - // and check if the roundtrip broke the original timestamp value. - print "Testing $start to ".($start+$yrs).", or $max seconds, offset=$offset: "; - $cnt = 0; - for ($max += $i; $i < $max; $i += $offset) { - $ret = adodb_date('m,d,Y,H,i,s',$i); - $arr = explode(',',$ret); - if ($lastyear != $arr[2]) { - $lastyear = $arr[2]; - print " $lastyear "; - flush(); - } - $newi = adodb_mktime($arr[3],$arr[4],$arr[5],$arr[0],$arr[1],$arr[2]); - if ($i != $newi) { - print "Error at $i, adodb_mktime returned $newi ($ret)"; - $fail = true; - break; - } - $cnt += 1; - } - echo "Tested $cnt dates
"; - if (!$fail) print "

Passed !

"; - else print "

Failed :-(

"; -} - -/** - Returns day of week, 0 = Sunday,... 6=Saturday. - Algorithm from PEAR::Date_Calc -*/ -function adodb_dow($year, $month, $day) -{ -/* -Pope Gregory removed 10 days - October 5 to October 14 - from the year 1582 and -proclaimed that from that time onwards 3 days would be dropped from the calendar -every 400 years. - -Thursday, October 4, 1582 (Julian) was followed immediately by Friday, October 15, 1582 (Gregorian). -*/ - if ($year <= 1582) { - if ($year < 1582 || - ($year == 1582 && ($month < 10 || ($month == 10 && $day < 15)))) $greg_correction = 3; - else - $greg_correction = 0; - } else - $greg_correction = 0; - - if($month > 2) - $month -= 2; - else { - $month += 10; - $year--; - } - - $day = floor((13 * $month - 1) / 5) + - $day + ($year % 100) + - floor(($year % 100) / 4) + - floor(($year / 100) / 4) - 2 * - floor($year / 100) + 77 + $greg_correction; - - return $day - 7 * floor($day / 7); -} - - -/** - Checks for leap year, returns true if it is. No 2-digit year check. Also - handles julian calendar correctly. -*/ -function _adodb_is_leap_year($year) -{ - if ($year % 4 != 0) return false; - - if ($year % 400 == 0) { - return true; - // if gregorian calendar (>1582), century not-divisible by 400 is not leap - } else if ($year > 1582 && $year % 100 == 0 ) { - return false; - } - - return true; -} - - -/** - checks for leap year, returns true if it is. Has 2-digit year check -*/ -function adodb_is_leap_year($year) -{ - return _adodb_is_leap_year(adodb_year_digit_check($year)); -} - -/** - Fix 2-digit years. Works for any century. - Assumes that if 2-digit is more than 30 years in future, then previous century. -*/ -function adodb_year_digit_check($y) -{ - if ($y < 100) { - - $yr = (integer) date("Y"); - $century = (integer) ($yr /100); - - if ($yr%100 > 50) { - $c1 = $century + 1; - $c0 = $century; - } else { - $c1 = $century; - $c0 = $century - 1; - } - $c1 *= 100; - // if 2-digit year is less than 30 years in future, set it to this century - // otherwise if more than 30 years in future, then we set 2-digit year to the prev century. - if (($y + $c1) < $yr+30) $y = $y + $c1; - else $y = $y + $c0*100; - } - return $y; -} - -function adodb_get_gmt_diff_ts($ts) -{ - if (0 <= $ts && $ts <= 0x7FFFFFFF) { // check if number in 32-bit signed range) { - $arr = getdate($ts); - $y = $arr['year']; - $m = $arr['mon']; - $d = $arr['mday']; - return adodb_get_gmt_diff($y,$m,$d); - } else { - return adodb_get_gmt_diff(false,false,false); - } - -} - -/** - get local time zone offset from GMT. Does not handle historical timezones before 1970. -*/ -function adodb_get_gmt_diff($y,$m,$d) -{ -static $TZ,$tzo; -global $ADODB_DATETIME_CLASS; - - if (!defined('ADODB_TEST_DATES')) $y = false; - else if ($y < 1970 || $y >= 2038) $y = false; - - if ($ADODB_DATETIME_CLASS && $y !== false) { - $dt = new DateTime(); - $dt->setISODate($y,$m,$d); - if (empty($tzo)) { - $tzo = new DateTimeZone(date_default_timezone_get()); - # $tzt = timezone_transitions_get( $tzo ); - } - return -$tzo->getOffset($dt); - } else { - if (isset($TZ)) return $TZ; - $y = date('Y'); - $TZ = mktime(0,0,0,12,2,$y,0) - gmmktime(0,0,0,12,2,$y,0); - } - - return $TZ; -} - -/** - Returns an array with date info. -*/ -function adodb_getdate($d=false,$fast=false) -{ - if ($d === false) return getdate(); - if (!defined('ADODB_TEST_DATES')) { - if ((abs($d) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range - if (!defined('ADODB_NO_NEGATIVE_TS') || $d >= 0) // if windows, must be +ve integer - return @getdate($d); - } - } - return _adodb_getdate($d); -} - -/* -// generate $YRS table for _adodb_getdate() -function adodb_date_gentable($out=true) -{ - - for ($i=1970; $i >= 1600; $i-=10) { - $s = adodb_gmmktime(0,0,0,1,1,$i); - echo "$i => $s,
"; - } -} -adodb_date_gentable(); - -for ($i=1970; $i > 1500; $i--) { - -echo "
$i "; - adodb_date_test_date($i,1,1); -} - -*/ - - -$_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31); -$_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31); - -function adodb_validdate($y,$m,$d) -{ -global $_month_table_normal,$_month_table_leaf; - - if (_adodb_is_leap_year($y)) $marr = $_month_table_leaf; - else $marr = $_month_table_normal; - - if ($m > 12 || $m < 1) return false; - - if ($d > 31 || $d < 1) return false; - - if ($marr[$m] < $d) return false; - - if ($y < 1000 && $y > 3000) return false; - - return true; -} - -/** - Low-level function that returns the getdate() array. We have a special - $fast flag, which if set to true, will return fewer array values, - and is much faster as it does not calculate dow, etc. -*/ -function _adodb_getdate($origd=false,$fast=false,$is_gmt=false) -{ -static $YRS; -global $_month_table_normal,$_month_table_leaf; - - $d = $origd - ($is_gmt ? 0 : adodb_get_gmt_diff_ts($origd)); - $_day_power = 86400; - $_hour_power = 3600; - $_min_power = 60; - - if ($d < -12219321600) $d -= 86400*10; // if 15 Oct 1582 or earlier, gregorian correction - - $_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31); - $_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31); - - $d366 = $_day_power * 366; - $d365 = $_day_power * 365; - - if ($d < 0) { - - if (empty($YRS)) $YRS = array( - 1970 => 0, - 1960 => -315619200, - 1950 => -631152000, - 1940 => -946771200, - 1930 => -1262304000, - 1920 => -1577923200, - 1910 => -1893456000, - 1900 => -2208988800, - 1890 => -2524521600, - 1880 => -2840140800, - 1870 => -3155673600, - 1860 => -3471292800, - 1850 => -3786825600, - 1840 => -4102444800, - 1830 => -4417977600, - 1820 => -4733596800, - 1810 => -5049129600, - 1800 => -5364662400, - 1790 => -5680195200, - 1780 => -5995814400, - 1770 => -6311347200, - 1760 => -6626966400, - 1750 => -6942499200, - 1740 => -7258118400, - 1730 => -7573651200, - 1720 => -7889270400, - 1710 => -8204803200, - 1700 => -8520336000, - 1690 => -8835868800, - 1680 => -9151488000, - 1670 => -9467020800, - 1660 => -9782640000, - 1650 => -10098172800, - 1640 => -10413792000, - 1630 => -10729324800, - 1620 => -11044944000, - 1610 => -11360476800, - 1600 => -11676096000); - - if ($is_gmt) $origd = $d; - // The valid range of a 32bit signed timestamp is typically from - // Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT - // - - # old algorithm iterates through all years. new algorithm does it in - # 10 year blocks - - /* - # old algo - for ($a = 1970 ; --$a >= 0;) { - $lastd = $d; - - if ($leaf = _adodb_is_leap_year($a)) $d += $d366; - else $d += $d365; - - if ($d >= 0) { - $year = $a; - break; - } - } - */ - - $lastsecs = 0; - $lastyear = 1970; - foreach($YRS as $year => $secs) { - if ($d >= $secs) { - $a = $lastyear; - break; - } - $lastsecs = $secs; - $lastyear = $year; - } - - $d -= $lastsecs; - if (!isset($a)) $a = $lastyear; - - //echo ' yr=',$a,' ', $d,'.'; - - for (; --$a >= 0;) { - $lastd = $d; - - if ($leaf = _adodb_is_leap_year($a)) $d += $d366; - else $d += $d365; - - if ($d >= 0) { - $year = $a; - break; - } - } - /**/ - - $secsInYear = 86400 * ($leaf ? 366 : 365) + $lastd; - - $d = $lastd; - $mtab = ($leaf) ? $_month_table_leaf : $_month_table_normal; - for ($a = 13 ; --$a > 0;) { - $lastd = $d; - $d += $mtab[$a] * $_day_power; - if ($d >= 0) { - $month = $a; - $ndays = $mtab[$a]; - break; - } - } - - $d = $lastd; - $day = $ndays + ceil(($d+1) / ($_day_power)); - - $d += ($ndays - $day+1)* $_day_power; - $hour = floor($d/$_hour_power); - - } else { - for ($a = 1970 ;; $a++) { - $lastd = $d; - - if ($leaf = _adodb_is_leap_year($a)) $d -= $d366; - else $d -= $d365; - if ($d < 0) { - $year = $a; - break; - } - } - $secsInYear = $lastd; - $d = $lastd; - $mtab = ($leaf) ? $_month_table_leaf : $_month_table_normal; - for ($a = 1 ; $a <= 12; $a++) { - $lastd = $d; - $d -= $mtab[$a] * $_day_power; - if ($d < 0) { - $month = $a; - $ndays = $mtab[$a]; - break; - } - } - $d = $lastd; - $day = ceil(($d+1) / $_day_power); - $d = $d - ($day-1) * $_day_power; - $hour = floor($d /$_hour_power); - } - - $d -= $hour * $_hour_power; - $min = floor($d/$_min_power); - $secs = $d - $min * $_min_power; - if ($fast) { - return array( - 'seconds' => $secs, - 'minutes' => $min, - 'hours' => $hour, - 'mday' => $day, - 'mon' => $month, - 'year' => $year, - 'yday' => floor($secsInYear/$_day_power), - 'leap' => $leaf, - 'ndays' => $ndays - ); - } - - - $dow = adodb_dow($year,$month,$day); - - return array( - 'seconds' => $secs, - 'minutes' => $min, - 'hours' => $hour, - 'mday' => $day, - 'wday' => $dow, - 'mon' => $month, - 'year' => $year, - 'yday' => floor($secsInYear/$_day_power), - 'weekday' => gmdate('l',$_day_power*(3+$dow)), - 'month' => gmdate('F',mktime(0,0,0,$month,2,1971)), - 0 => $origd - ); -} -/* - if ($isphp5) - $dates .= sprintf('%s%04d',($gmt<=0)?'+':'-',abs($gmt)/36); - else - $dates .= sprintf('%s%04d',($gmt<0)?'+':'-',abs($gmt)/36); - break;*/ -function adodb_tz_offset($gmt,$isphp5) -{ - $zhrs = abs($gmt)/3600; - $hrs = floor($zhrs); - if ($isphp5) - return sprintf('%s%02d%02d',($gmt<=0)?'+':'-',floor($zhrs),($zhrs-$hrs)*60); - else - return sprintf('%s%02d%02d',($gmt<0)?'+':'-',floor($zhrs),($zhrs-$hrs)*60); -} - - -function adodb_gmdate($fmt,$d=false) -{ - return adodb_date($fmt,$d,true); -} - -// accepts unix timestamp and iso date format in $d -function adodb_date2($fmt, $d=false, $is_gmt=false) -{ - if ($d !== false) { - if (!preg_match( - "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ -]?(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", - ($d), $rr)) return adodb_date($fmt,false,$is_gmt); - - if ($rr[1] <= 100 && $rr[2]<= 1) return adodb_date($fmt,false,$is_gmt); - - // h-m-s-MM-DD-YY - if (!isset($rr[5])) $d = adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1],false,$is_gmt); - else $d = @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1],false,$is_gmt); - } - - return adodb_date($fmt,$d,$is_gmt); -} - - -/** - Return formatted date based on timestamp $d -*/ -function adodb_date($fmt,$d=false,$is_gmt=false) -{ -static $daylight; -global $ADODB_DATETIME_CLASS; - - if ($d === false) return ($is_gmt)? @gmdate($fmt): @date($fmt); - if (!defined('ADODB_TEST_DATES')) { - if ((abs($d) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range - if (!defined('ADODB_NO_NEGATIVE_TS') || $d >= 0) // if windows, must be +ve integer - return ($is_gmt)? @gmdate($fmt,$d): @date($fmt,$d); - - } - } - $_day_power = 86400; - - $arr = _adodb_getdate($d,true,$is_gmt); - - if (!isset($daylight)) $daylight = function_exists('adodb_daylight_sv'); - if ($daylight) adodb_daylight_sv($arr, $is_gmt); - - $year = $arr['year']; - $month = $arr['mon']; - $day = $arr['mday']; - $hour = $arr['hours']; - $min = $arr['minutes']; - $secs = $arr['seconds']; - - $max = strlen($fmt); - $dates = ''; - - $isphp5 = PHP_VERSION >= 5; - - /* - at this point, we have the following integer vars to manipulate: - $year, $month, $day, $hour, $min, $secs - */ - for ($i=0; $i < $max; $i++) { - switch($fmt[$i]) { - case 'e': - $dates .= date('e'); - break; - case 'T': - if ($ADODB_DATETIME_CLASS) { - $dt = new DateTime(); - $dt->SetDate($year,$month,$day); - $dates .= $dt->Format('T'); - } else - $dates .= date('T'); - break; - // YEAR - case 'L': $dates .= $arr['leap'] ? '1' : '0'; break; - case 'r': // Thu, 21 Dec 2000 16:01:07 +0200 - - // 4.3.11 uses '04 Jun 2004' - // 4.3.8 uses ' 4 Jun 2004' - $dates .= gmdate('D',$_day_power*(3+adodb_dow($year,$month,$day))).', ' - . ($day<10?'0'.$day:$day) . ' '.date('M',mktime(0,0,0,$month,2,1971)).' '.$year.' '; - - if ($hour < 10) $dates .= '0'.$hour; else $dates .= $hour; - - if ($min < 10) $dates .= ':0'.$min; else $dates .= ':'.$min; - - if ($secs < 10) $dates .= ':0'.$secs; else $dates .= ':'.$secs; - - $gmt = adodb_get_gmt_diff($year,$month,$day); - - $dates .= ' '.adodb_tz_offset($gmt,$isphp5); - break; - - case 'Y': $dates .= $year; break; - case 'y': $dates .= substr($year,strlen($year)-2,2); break; - // MONTH - case 'm': if ($month<10) $dates .= '0'.$month; else $dates .= $month; break; - case 'Q': $dates .= ($month+3)>>2; break; - case 'n': $dates .= $month; break; - case 'M': $dates .= date('M',mktime(0,0,0,$month,2,1971)); break; - case 'F': $dates .= date('F',mktime(0,0,0,$month,2,1971)); break; - // DAY - case 't': $dates .= $arr['ndays']; break; - case 'z': $dates .= $arr['yday']; break; - case 'w': $dates .= adodb_dow($year,$month,$day); break; - case 'l': $dates .= gmdate('l',$_day_power*(3+adodb_dow($year,$month,$day))); break; - case 'D': $dates .= gmdate('D',$_day_power*(3+adodb_dow($year,$month,$day))); break; - case 'j': $dates .= $day; break; - case 'd': if ($day<10) $dates .= '0'.$day; else $dates .= $day; break; - case 'S': - $d10 = $day % 10; - if ($d10 == 1) $dates .= 'st'; - else if ($d10 == 2 && $day != 12) $dates .= 'nd'; - else if ($d10 == 3) $dates .= 'rd'; - else $dates .= 'th'; - break; - - // HOUR - case 'Z': - $dates .= ($is_gmt) ? 0 : -adodb_get_gmt_diff($year,$month,$day); break; - case 'O': - $gmt = ($is_gmt) ? 0 : adodb_get_gmt_diff($year,$month,$day); - - $dates .= adodb_tz_offset($gmt,$isphp5); - break; - - case 'H': - if ($hour < 10) $dates .= '0'.$hour; - else $dates .= $hour; - break; - case 'h': - if ($hour > 12) $hh = $hour - 12; - else { - if ($hour == 0) $hh = '12'; - else $hh = $hour; - } - - if ($hh < 10) $dates .= '0'.$hh; - else $dates .= $hh; - break; - - case 'G': - $dates .= $hour; - break; - - case 'g': - if ($hour > 12) $hh = $hour - 12; - else { - if ($hour == 0) $hh = '12'; - else $hh = $hour; - } - $dates .= $hh; - break; - // MINUTES - case 'i': if ($min < 10) $dates .= '0'.$min; else $dates .= $min; break; - // SECONDS - case 'U': $dates .= $d; break; - case 's': if ($secs < 10) $dates .= '0'.$secs; else $dates .= $secs; break; - // AM/PM - // Note 00:00 to 11:59 is AM, while 12:00 to 23:59 is PM - case 'a': - if ($hour>=12) $dates .= 'pm'; - else $dates .= 'am'; - break; - case 'A': - if ($hour>=12) $dates .= 'PM'; - else $dates .= 'AM'; - break; - default: - $dates .= $fmt[$i]; break; - // ESCAPE - case "\\": - $i++; - if ($i < $max) $dates .= $fmt[$i]; - break; - } - } - return $dates; -} - -/** - Returns a timestamp given a GMT/UTC time. - Note that $is_dst is not implemented and is ignored. -*/ -function adodb_gmmktime($hr,$min,$sec,$mon=false,$day=false,$year=false,$is_dst=false) -{ - return adodb_mktime($hr,$min,$sec,$mon,$day,$year,$is_dst,true); -} - -/** - Return a timestamp given a local time. Originally by jackbbs. - Note that $is_dst is not implemented and is ignored. - - Not a very fast algorithm - O(n) operation. Could be optimized to O(1). -*/ -function adodb_mktime($hr,$min,$sec,$mon=false,$day=false,$year=false,$is_dst=false,$is_gmt=false) -{ - if (!defined('ADODB_TEST_DATES')) { - - if ($mon === false) { - return $is_gmt? @gmmktime($hr,$min,$sec): @mktime($hr,$min,$sec); - } - - // for windows, we don't check 1970 because with timezone differences, - // 1 Jan 1970 could generate negative timestamp, which is illegal - $usephpfns = (1970 < $year && $year < 2038 - || !defined('ADODB_NO_NEGATIVE_TS') && (1901 < $year && $year < 2038) - ); - - - if ($usephpfns && ($year + $mon/12+$day/365.25+$hr/(24*365.25) >= 2038)) $usephpfns = false; - - if ($usephpfns) { - return $is_gmt ? - @gmmktime($hr,$min,$sec,$mon,$day,$year): - @mktime($hr,$min,$sec,$mon,$day,$year); - } - } - - $gmt_different = ($is_gmt) ? 0 : adodb_get_gmt_diff($year,$mon,$day); - - /* - # disabled because some people place large values in $sec. - # however we need it for $mon because we use an array... - $hr = intval($hr); - $min = intval($min); - $sec = intval($sec); - */ - $mon = intval($mon); - $day = intval($day); - $year = intval($year); - - - $year = adodb_year_digit_check($year); - - if ($mon > 12) { - $y = floor(($mon-1)/ 12); - $year += $y; - $mon -= $y*12; - } else if ($mon < 1) { - $y = ceil((1-$mon) / 12); - $year -= $y; - $mon += $y*12; - } - - $_day_power = 86400; - $_hour_power = 3600; - $_min_power = 60; - - $_month_table_normal = array("",31,28,31,30,31,30,31,31,30,31,30,31); - $_month_table_leaf = array("",31,29,31,30,31,30,31,31,30,31,30,31); - - $_total_date = 0; - if ($year >= 1970) { - for ($a = 1970 ; $a <= $year; $a++) { - $leaf = _adodb_is_leap_year($a); - if ($leaf == true) { - $loop_table = $_month_table_leaf; - $_add_date = 366; - } else { - $loop_table = $_month_table_normal; - $_add_date = 365; - } - if ($a < $year) { - $_total_date += $_add_date; - } else { - for($b=1;$b<$mon;$b++) { - $_total_date += $loop_table[$b]; - } - } - } - $_total_date +=$day-1; - $ret = $_total_date * $_day_power + $hr * $_hour_power + $min * $_min_power + $sec + $gmt_different; - - } else { - for ($a = 1969 ; $a >= $year; $a--) { - $leaf = _adodb_is_leap_year($a); - if ($leaf == true) { - $loop_table = $_month_table_leaf; - $_add_date = 366; - } else { - $loop_table = $_month_table_normal; - $_add_date = 365; - } - if ($a > $year) { $_total_date += $_add_date; - } else { - for($b=12;$b>$mon;$b--) { - $_total_date += $loop_table[$b]; - } - } - } - $_total_date += $loop_table[$mon] - $day; - - $_day_time = $hr * $_hour_power + $min * $_min_power + $sec; - $_day_time = $_day_power - $_day_time; - $ret = -( $_total_date * $_day_power + $_day_time - $gmt_different); - if ($ret < -12220185600) $ret += 10*86400; // if earlier than 5 Oct 1582 - gregorian correction - else if ($ret < -12219321600) $ret = -12219321600; // if in limbo, reset to 15 Oct 1582. - } - //print " dmy=$day/$mon/$year $hr:$min:$sec => " .$ret; - return $ret; -} - -function adodb_gmstrftime($fmt, $ts=false) -{ - return adodb_strftime($fmt,$ts,true); -} - -// hack - convert to adodb_date -function adodb_strftime($fmt, $ts=false,$is_gmt=false) -{ -global $ADODB_DATE_LOCALE; - - if (!defined('ADODB_TEST_DATES')) { - if ((abs($ts) <= 0x7FFFFFFF)) { // check if number in 32-bit signed range - if (!defined('ADODB_NO_NEGATIVE_TS') || $ts >= 0) // if windows, must be +ve integer - return ($is_gmt)? @gmstrftime($fmt,$ts): @strftime($fmt,$ts); - - } - } - - if (empty($ADODB_DATE_LOCALE)) { - /* - $tstr = strtoupper(gmstrftime('%c',31366800)); // 30 Dec 1970, 1 am - $sep = substr($tstr,2,1); - $hasAM = strrpos($tstr,'M') !== false; - */ - # see http://phplens.com/lens/lensforum/msgs.php?id=14865 for reasoning, and changelog for version 0.24 - $dstr = gmstrftime('%x',31366800); // 30 Dec 1970, 1 am - $sep = substr($dstr,2,1); - $tstr = strtoupper(gmstrftime('%X',31366800)); // 30 Dec 1970, 1 am - $hasAM = strrpos($tstr,'M') !== false; - - $ADODB_DATE_LOCALE = array(); - $ADODB_DATE_LOCALE[] = strncmp($tstr,'30',2) == 0 ? 'd'.$sep.'m'.$sep.'y' : 'm'.$sep.'d'.$sep.'y'; - $ADODB_DATE_LOCALE[] = ($hasAM) ? 'h:i:s a' : 'H:i:s'; - - } - $inpct = false; - $fmtdate = ''; - for ($i=0,$max = strlen($fmt); $i < $max; $i++) { - $ch = $fmt[$i]; - if ($ch == '%') { - if ($inpct) { - $fmtdate .= '%'; - $inpct = false; - } else - $inpct = true; - } else if ($inpct) { - - $inpct = false; - switch($ch) { - case '0': - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - case '8': - case '9': - case 'E': - case 'O': - /* ignore format modifiers */ - $inpct = true; - break; - - case 'a': $fmtdate .= 'D'; break; - case 'A': $fmtdate .= 'l'; break; - case 'h': - case 'b': $fmtdate .= 'M'; break; - case 'B': $fmtdate .= 'F'; break; - case 'c': $fmtdate .= $ADODB_DATE_LOCALE[0].$ADODB_DATE_LOCALE[1]; break; - case 'C': $fmtdate .= '\C?'; break; // century - case 'd': $fmtdate .= 'd'; break; - case 'D': $fmtdate .= 'm/d/y'; break; - case 'e': $fmtdate .= 'j'; break; - case 'g': $fmtdate .= '\g?'; break; //? - case 'G': $fmtdate .= '\G?'; break; //? - case 'H': $fmtdate .= 'H'; break; - case 'I': $fmtdate .= 'h'; break; - case 'j': $fmtdate .= '?z'; $parsej = true; break; // wrong as j=1-based, z=0-basd - case 'm': $fmtdate .= 'm'; break; - case 'M': $fmtdate .= 'i'; break; - case 'n': $fmtdate .= "\n"; break; - case 'p': $fmtdate .= 'a'; break; - case 'r': $fmtdate .= 'h:i:s a'; break; - case 'R': $fmtdate .= 'H:i:s'; break; - case 'S': $fmtdate .= 's'; break; - case 't': $fmtdate .= "\t"; break; - case 'T': $fmtdate .= 'H:i:s'; break; - case 'u': $fmtdate .= '?u'; $parseu = true; break; // wrong strftime=1-based, date=0-based - case 'U': $fmtdate .= '?U'; $parseU = true; break;// wrong strftime=1-based, date=0-based - case 'x': $fmtdate .= $ADODB_DATE_LOCALE[0]; break; - case 'X': $fmtdate .= $ADODB_DATE_LOCALE[1]; break; - case 'w': $fmtdate .= '?w'; $parseu = true; break; // wrong strftime=1-based, date=0-based - case 'W': $fmtdate .= '?W'; $parseU = true; break;// wrong strftime=1-based, date=0-based - case 'y': $fmtdate .= 'y'; break; - case 'Y': $fmtdate .= 'Y'; break; - case 'Z': $fmtdate .= 'T'; break; - } - } else if (('A' <= ($ch) && ($ch) <= 'Z' ) || ('a' <= ($ch) && ($ch) <= 'z' )) - $fmtdate .= "\\".$ch; - else - $fmtdate .= $ch; - } - //echo "fmt=",$fmtdate,"
"; - if ($ts === false) $ts = time(); - $ret = adodb_date($fmtdate, $ts, $is_gmt); - return $ret; -} - - -?> \ No newline at end of file diff --git a/lib/adodb/adodb.inc.php b/lib/adodb/adodb.inc.php deleted file mode 100644 index 2da3777d..00000000 --- a/lib/adodb/adodb.inc.php +++ /dev/null @@ -1,4416 +0,0 @@ -fields is available on EOF - $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. - - //============================================================================================== - // GLOBAL SETUP - //============================================================================================== - - $ADODB_EXTENSION = defined('ADODB_EXTENSION'); - - //********************************************************// - /* - Controls $ADODB_FORCE_TYPE mode. Default is ADODB_FORCE_VALUE (3). - Used in GetUpdateSql and GetInsertSql functions. Thx to Niko, nuko#mbnet.fi - - 0 = ignore empty fields. All empty fields in array are ignored. - 1 = force null. All empty, php null and string 'null' fields are changed to sql NULL values. - 2 = force empty. All empty, php null and string 'null' fields are changed to sql empty '' or 0 values. - 3 = force value. Value is left as it is. Php null and string 'null' are set to sql NULL values and empty fields '' are set to empty '' sql values. - */ - define('ADODB_FORCE_IGNORE',0); - define('ADODB_FORCE_NULL',1); - define('ADODB_FORCE_EMPTY',2); - define('ADODB_FORCE_VALUE',3); - //********************************************************// - - - if (!$ADODB_EXTENSION || ADODB_EXTENSION < 4.0) { - - define('ADODB_BAD_RS','

Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;

'); - - // allow [ ] @ ` " and . in table names - define('ADODB_TABLE_REGEX','([]0-9a-z_\:\"\`\.\@\[-]*)'); - - // prefetching used by oracle - 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. - - 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'] - */ - - 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); - - // PHP's version scheme makes converting to numbers difficult - workaround - $_adodb_ver = (float) PHP_VERSION; - if ($_adodb_ver >= 5.2) { - define('ADODB_PHPVER',0x5200); - } else if ($_adodb_ver >= 5.0) { - define('ADODB_PHPVER',0x5000); - } else - die("PHP5 or later required. You are running ".PHP_VERSION); - } - - - //if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2); - - - /** - 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); - - $s = reset($src); - $d = reset($dest); - while ($s !== false) { - $data = str_replace($s,$d,$data); - $s = next($src); - $d = next($dest); - } - return $data; - } - - function ADODB_Setup() - { - GLOBAL - $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_CACHE, - $ADODB_CACHE_CLASS, - $ADODB_FORCE_TYPE, - $ADODB_GETONE_EOF, - $ADODB_QUOTE_FIELDNAMES; - - 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; - - if (!isset($ADODB_CACHE_DIR)) { - $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) - die("Illegal path http:// or ftp://"); - } - - - // Initialize random number generator for randomizing cache flushes - // -- note Since PHP 4.2.0, the seed becomes optional and defaults to a random value if omitted. - srand(((double)microtime())*1000000); - - /** - * ADODB version as a string. - */ - $ADODB_vers = 'V5.11 5 May 2010 (c) 2000-2010 John Lim (jlim#natsoft.com). All rights reserved. Released BSD & LGPL.'; - - /** - * 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; - } - - - //============================================================================================== - // CHANGE NOTHING BELOW UNLESS YOU ARE DESIGNING ADODB - //============================================================================================== - - ADODB_Setup(); - - //============================================================================================== - // CLASS ADOFieldObject - //============================================================================================== - /** - * Helper class for FetchFields -- holds info on a column - */ - class ADOFieldObject { - var $name = ''; - var $max_length=0; - var $type=""; -/* - // additional fields by dannym... (danny_milo@yahoo.com) - var $not_null = false; - // actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^ - // so we can as well make not_null standard (leaving it at "false" does not harm anyways) - - var $has_default = false; // this one I have done only in mysql and postgres for now ... - // others to come (dannym) - var $default_value; // default, if any, and supported. Check has_default first. -*/ - } - - // for transaction handling - - function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection) - { - //print "Errorno ($fn errno=$errno m=$errmsg) "; - $thisConnection->_transOK = false; - if ($thisConnection->_oldRaiseFn) { - $fn = $thisConnection->_oldRaiseFn; - $fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection); - } - } - - //------------------ - // class for caching - class ADODB_Cache_File { - - 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'); - } - - // write serialised recordset to cache item/file - 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) - { - $rs = csv2rs($filename,$err,$secs2cache,$rsClass); - return $rs; - } - - // flush all items in cache - function flushall($debug=false) - { - global $ADODB_CACHE_DIR; - - $rez = false; - - if (strlen($ADODB_CACHE_DIR) > 1) { - $rez = $this->_dirFlush($ADODB_CACHE_DIR); - if ($debug) ADOConnection::outp( "flushall: $dir
\n". $rez."
"); - } - return $rez; - } - - // flush one file in cache - function flushcache($f, $debug=false) - { - if (!@unlink($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'); - return ($this->notSafeMode) ? $ADODB_CACHE_DIR.'/'.substr($hash,0,2) : $ADODB_CACHE_DIR; - } - - // create temp directories - function createdir($hash, $debug) - { - $dir = $this->getdirname($hash); - if ($this->notSafeMode && !file_exists($dir)) { - $oldu = umask(0); - if (!@mkdir($dir,0771)) if(!is_dir($dir) && $debug) ADOConnection::outp("Cannot create $dir"); - umask($oldu); - } - - return $dir; - } - - /** - * Private function to erase all of the files and subdirectories in a directory. - * - * 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; - - 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; - } - } - - //============================================================================================== - // CLASS ADOConnection - //============================================================================================== - - /** - * Connection object. For connecting to databases, and executing queries. - */ - class ADOConnection { - // - // PUBLIC VARS - // - 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 $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase - var $substr = 'substr'; /// substring operator - var $length = 'length'; /// string length ofperator - var $random = 'rand()'; /// random function - 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 $nameQuote = '"'; /// string to use to quote identifiers and names - 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 - var $emptyDate = ' '; - var $emptyTimeStamp = ' '; - var $lastInsID = false; - //-- - 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 $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 - var $memCacheHost; /// memCache host - var $memCachePort = 11211; /// memCache port - var $memCacheCompress = false; /// Use 'true' to store the item compressed (uses zlib) - - var $sysDate = false; /// name of function that returns the current date - var $sysTimeStamp = false; /// name of function that returns the current timestamp - var $sysUTimeStamp = false; // name of function that returns the current timestamp accurate to the microsecond or nearest fraction - var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets - - var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' ' - var $numCacheHits = 0; - var $numCacheMisses = 0; - var $pageExecuteCountRows = true; - var $uniqueSort = false; /// indicates that all fields in order by must be unique - var $leftOuter = false; /// operator to use for left outer join in WHERE clause - var $rightOuter = false; /// operator to use for right outer join in WHERE clause - var $ansiOuter = false; /// whether ansi outer join syntax supported - var $autoRollback = false; // autoRollback on PConnect(). - var $poorAffectedRows = false; // affectedRows not working or unreliable - - var $fnExecute = false; - var $fnCacheExecute = false; - 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 $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 - // - var $_oldRaiseFn = false; - var $_transOK = null; - var $_connectionID = false; /// The returned link identifier whenever a successful database connection is made. - var $_errorMsg = false; /// A variable which was used to keep the returned last error message. The value will - /// then returned by the errorMsg() function - var $_errorCode = false; /// Last error code, not guaranteed to be used - only by oci8 - var $_queryID = false; /// This variable keeps the last created result link identifier - - var $_isPersistentConnection = false; /// A boolean variable to state whether its a persistent connection or normal connection. */ - var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters. - var $_evalAll = false; - var $_affected = false; - var $_logsql = false; - var $_transmode = ''; // transaction mode - - - - /** - * Constructor - */ - function ADOConnection() - { - die('Virtual Class -- cannot instantiate'); - } - - static function Version() - { - global $ADODB_vers; - - $ok = preg_match( '/^[Vv]([0-9\.]+)/', $ADODB_vers, $matches ); - if (!$ok) return (float) substr($ADODB_vers,1); - else return $matches[1]; - } - - /** - Get server version info... - - @returns An array with 2 elements: $arr['string'] is the description string, - and $arr[version] is the version (also a string). - */ - function ServerInfo() - { - return array('description' => '', 'version' => ''); - } - - function IsConnected() - { - return !empty($this->_connectionID); - } - - 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; - - if (defined('ADODB_OUTP')) { - $fn = ADODB_OUTP; - $fn($msg,$newline); - return; - } else if (isset($ADODB_OUTP)) { - $fn = $ADODB_OUTP; - $fn($msg,$newline); - return; - } - - if ($newline) $msg .= "
\n"; - - 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 - - } - - function Time() - { - $rs = $this->_Execute("select $this->sysTimeStamp"); - if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields)); - - return false; - } - - /** - * Connect to database - * - * @param [argHostname] Host to connect to - * @param [argUsername] Userid to login - * @param [argPassword] Associated password - * @param [argDatabaseName] database - * @param [forceNew] force new connection - * - * @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; - - $this->_isPersistentConnection = false; - - if ($forceNew) { - 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 (isset($rez)) { - $err = $this->ErrorMsg(); - 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) - $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this); - - - $this->_connectionID = false; - if ($this->debug) ADOConnection::outp( $this->host.': '.$err); - return $ret; - } - - function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName) - { - return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName); - } - - - /** - * Always force a new connection to database - currently only works with oracle - * - * @param [argHostname] Host to connect to - * @param [argUsername] Userid to login - * @param [argPassword] Associated password - * @param [argDatabaseName] database - * - * @return true or false - */ - function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") - { - return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true); - } - - /** - * Establish persistent connect to database - * - * @param [argHostname] Host to connect to - * @param [argUsername] Userid to login - * @param [argPassword] Associated password - * @param [argDatabaseName] database - * - * @return return true or false - */ - function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") - { - - 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; - - $this->_isPersistentConnection = 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'"; - $ret = false; - } else { - $err = "Missing extension for ".$this->dataProvider; - $ret = 0; - } - if ($fn = $this->raiseErrorFn) { - $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this); - } - - $this->_connectionID = false; - if ($this->debug) ADOConnection::outp( $this->host.': '.$err); - return $ret; - } - - 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; - } - ADOConnection::outp($msg); - } - - // create cache class. Code is backward compat with old memcache implementation - 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); - - } - - // 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; - return $col; // child class implement - } - - /** - * Should prepare the sql statement and return the stmt resource. - * For databases that do not support this, we return the $sql. To ensure - * compatibility with databases that do not support prepare: - * - * $stmt = $db->Prepare("insert into table (id, name) values (?,?)"); - * $db->Execute($stmt,array(1,'Jill')) or die('insert failed'); - * $db->Execute($stmt,array(2,'Joe')) or die('insert failed'); - * - * @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. - * - */ - function Prepare($sql) - { - return $sql; - } - - /** - * Some databases, eg. mssql require a different function for preparing - * stored procedures. So we cannot use Prepare(). - * - * Should prepare the stored procedure and return the stmt resource. - * For databases that do not support this, we return the $sql. To ensure - * compatibility with databases that do not support prepare: - * - * @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. - * - */ - function PrepareSP($sql,$param=true) - { - return $this->Prepare($sql,$param); - } - - /** - * PEAR DB Compat - */ - function Quote($s) - { - return $this->qstr($s,false); - } - - /** - 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; - $s = $this->qstr($s,false); - } - - /** - * PEAR DB Compat - do not use internally. - */ - function ErrorNative() - { - return $this->ErrorNo(); - } - - - /** - * PEAR DB Compat - do not use internally. - */ - 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 - * - * @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') - { - return false; - } - - function CommitLock($table) - { - return $this->CommitTrans(); - } - - function RollbackLock($table) - { - return $this->RollbackTrans(); - } - - /** - * PEAR DB Compat - do not use internally. - * - * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical - * for easy porting :-) - * - * @param mode The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM - * @returns The previous fetch mode - */ - function SetFetchMode($mode) - { - $old = $this->fetchMode; - $this->fetchMode = $mode; - - if ($old === false) { - global $ADODB_FETCH_MODE; - return $ADODB_FETCH_MODE; - } - return $old; - } - - - /** - * PEAR DB Compat - do not use internally. - */ - function Query($sql, $inputarr=false) - { - $rs = $this->Execute($sql, $inputarr); - if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error(); - return $rs; - } - - - /** - * PEAR DB Compat - do not use internally - */ - function LimitQuery($sql, $offset, $count, $params=false) - { - $rs = $this->SelectLimit($sql, $count, $offset, $params); - if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error(); - return $rs; - } - - - /** - * PEAR DB Compat - do not use internally - */ - function Disconnect() - { - return $this->Close(); - } - - /* - Returns placeholder for parameter, eg. - $DB->Param('a') - - will return ':a' for Oracle, and '?' for most other databases... - - For databases that require positioned params, eg $1, $2, $3 for postgresql, - pass in Param(false) before setting the first parameter. - */ - function Param($name,$type='C') - { - return '?'; - } - - /* - InParameter and OutParameter are self-documenting versions of Parameter(). - */ - 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) - { - return $this->Parameter($stmt,$var,$name,true,$maxLen,$type); - - } - - - /* - Usage in oracle - $stmt = $db->Prepare('select * from table where id =:myid and group=:group'); - $db->Parameter($stmt,$id,'myid'); - $db->Parameter($stmt,$group,'group',64); - $db->Execute(); - - @param $stmt Statement returned by Prepare() or PrepareSP(). - @param $var PHP variable to bind to - @param $name Name of stored procedure variable name to bind to. - @param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in oci8. - @param [$maxLen] Holds an maximum length of the variable. - @param [$type] The data type of $var. Legal values depend on driver. - - */ - function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false) - { - return false; - } - - - function IgnoreErrors($saveErrs=false) - { - if (!$saveErrs) { - $saveErrs = array($this->raiseErrorFn,$this->_transOK); - $this->raiseErrorFn = false; - return $saveErrs; - } else { - $this->raiseErrorFn = $saveErrs[0]; - $this->_transOK = $saveErrs[1]; - } - } - - /** - 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; - } - - $this->_oldRaiseFn = $this->raiseErrorFn; - $this->raiseErrorFn = $errfn; - $this->_transOK = true; - - if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans"); - $ok = $this->BeginTrans(); - $this->transOff = 1; - return $ok; - } - - - /** - Used together with StartTrans() to end a transaction. Monitors connection - for sql errors, and will commit or rollback as appropriate. - - @autoComplete if true, monitor sql errors and commit and rollback as appropriate, - and if set to false force rollback even if no SQL error detected. - @returns true on commit, false on rollback. - */ - function CompleteTrans($autoComplete = true) - { - if ($this->transOff > 1) { - $this->transOff -= 1; - return true; - } - $this->raiseErrorFn = $this->_oldRaiseFn; - - $this->transOff = 0; - 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"); - } else { - $this->_transOK = false; - $this->RollbackTrans(); - if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred"); - } - - return $this->_transOK; - } - - /* - At the end of a StartTrans/CompleteTrans block, perform a rollback. - */ - function FailTrans() - { - if ($this->debug) - if ($this->transOff == 0) { - ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans"); - } else { - ADOConnection::outp("FailTrans was called"); - adodb_backtrace(); - } - $this->_transOK = false; - } - - /** - Check if transaction has failed, only for Smart Transactions. - */ - function HasFailedTrans() - { - if ($this->transOff > 0) return $this->_transOK == false; - return false; - } - - /** - * Execute SQL - * - * @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 - */ - function Execute($sql,$inputarr=false) - { - if ($this->fnExecute) { - $fn = $this->fnExecute; - $ret = $fn($this,$sql,$inputarr); - if (isset($ret)) return $ret; - } - if ($inputarr) { - if (!is_array($inputarr)) $inputarr = array($inputarr); - - $element0 = reset($inputarr); - # is_object check because oci8 descriptors can be passed in - $array_2d = $this->bulkBind && is_array($element0) && !is_object(reset($element0)); - //remove extra memory copy of input -mikefedyk - unset($element0); - - if (!is_array($sql) && !$this->_bindInputArray) { - $sqlarr = explode('?',$sql); - $nparams = sizeof($sqlarr)-1; - if (!$array_2d) $inputarr = array($inputarr); - foreach($inputarr as $arr) { - $sql = ''; $i = 0; - //Use each() instead of foreach to reduce memory usage -mikefedyk - while(list(, $v) = each($arr)) { - $sql .= $sqlarr[$i]; - // from Ron Baldwin - // Only quote string types - $typ = gettype($v); - if ($typ == 'string') - //New memory copy of input created here -mikefedyk - $sql .= $this->qstr($v); - else if ($typ == 'double') - $sql .= str_replace(',','.',$v); // locales fix so 1.1 does not get converted to 1,1 - 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) - $sql .= 'NULL'; - else - $sql .= $v; - $i += 1; - - 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)) - $this->outp_throw( "Input array does not match ?: ".htmlspecialchars($sql),'Execute'); - - $ret = $this->_Execute($sql); - if (!$ret) return $ret; - } - } else { - if ($array_2d) { - if (is_string($sql)) - $stmt = $this->Prepare($sql); - else - $stmt = $sql; - - foreach($inputarr as $arr) { - $ret = $this->_Execute($stmt,$arr); - if (!$ret) return $ret; - } - } else { - $ret = $this->_Execute($sql,$inputarr); - } - } - } else { - $ret = $this->_Execute($sql,false); - } - - return $ret; - } - - - function _Execute($sql,$inputarr=false) - { - if ($this->debug) { - global $ADODB_INCLUDED_LIB; - 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); - } - - /************************ - // OK, query executed - *************************/ - - if ($this->_queryID === false) { // error handling if query fails - 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; - } - - if ($this->_queryID === true) { // return simplified recordset for inserts/updates/deletes with lower overhead - $rsclass = $this->rsPrefix.'empty'; - $rs = (class_exists($rsclass)) ? new $rsclass(): new ADORecordSet_empty(); - - return $rs; - } - - // return real recordset from select statement - $rsclass = $this->rsPrefix.$this->databaseType; - $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 ($rs->_numOfRows <= 0) { - global $ADODB_COUNTRECS; - if ($ADODB_COUNTRECS) { - if (!$rs->EOF) { - $rs = $this->_rs2rs($rs,-1,-1,!is_array($sql)); - $rs->_queryID = $this->_queryID; - } else - $rs->_numOfRows = 0; - } - } - return $rs; - } - - 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; - return $this->Execute(sprintf($this->_dropSeqSQL,$seqname)); - } - - /** - * Generates a sequence id and stores it in $this->genID; - * GenID is only available if $this->hasGenID = true; - * - * @param seqname name of sequence to use - * @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) - { - if (!$this->hasGenID) { - return 0; // formerly returns false pre 1.60 - } - - $getnext = sprintf($this->_genIDSQL,$seqname); - - $holdtransOK = $this->_transOK; - - $save_handler = $this->raiseErrorFn; - $this->raiseErrorFn = ''; - @($rs = $this->Execute($getnext)); - $this->raiseErrorFn = $save_handler; - - if (!$rs) { - $this->_transOK = $holdtransOK; //if the status was ok before reset - $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->Close(); - - return $this->genID; - } - - /** - * @param $table string name of the table, not needed by all databases (eg. mysql), default '' - * @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); - if ($this->debug) { - ADOConnection::outp( '

Insert_ID error

'); - adodb_backtrace(); - } - return false; - } - - - /** - * Portable Insert ID. Pablo Roca - * - * @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"); - } - } - - /** - * @return # rows affected by UPDATE/DELETE - */ - function Affected_Rows() - { - if ($this->hasAffectedRows) { - if ($this->fnExecute === 'adodb_log_sql') { - 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); - return false; - } - - - /** - * @return the last error message - */ - 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() - { - return ($this->_errorMsg) ? -1 : 0; - } - - function MetaError($err=false) - { - include_once(ADODB_DIR."/adodb-error.inc.php"); - if ($err === false) $err = $this->ErrorNo(); - return adodb_error($this->dataProvider,$this->databaseType,$err); - } - - function MetaErrorMsg($errno) - { - include_once(ADODB_DIR."/adodb-error.inc.php"); - return adodb_errormsg($errno); - } - - /** - * @returns an array with the primary key columns in it. - */ - 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)) - $p[] = $v->name; - } - } - 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) - { - 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 - */ - function SelectDB($dbName) - {return false;} - - - /** - * Will select, getting rows from $offset (1-based), for $nrows. - * This simulates the MySQL "select * from table limit $offset,$nrows" , and - * the PostgreSQL "select * from table limit $nrows offset $offset". Note that - * MySQL and PostgreSQL parameter ordering is the opposite of the other. - * eg. - * SelectLimit('select * from table',3); will return rows 1 to 3 (1-based) - * SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based) - * - * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set) - * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set - * - * @param sql - * @param [offset] is the row to start calculations from (1-based) - * @param [nrows] is the number of rows to get - * @param [inputarr] array of bind variables - * @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) - { - if ($this->hasTop && $nrows > 0) { - // 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) { - - // access includes ties in result - if ($isaccess) { - $sql = preg_replace( - '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql); - - if ($secs2cache != 0) { - $ret = $this->CacheExecute($secs2cache, $sql,$inputarr); - } else { - $ret = $this->Execute($sql,$inputarr); - } - return $ret; // PHP5 fix - } else if ($ismssql){ - $sql = preg_replace( - '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql); - } else { - $sql = preg_replace( - '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql); - } - } else { - $nn = $nrows + $offset; - if ($isaccess || $ismssql) { - $sql = preg_replace( - '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql); - } else { - $sql = preg_replace( - '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql); - } - } - } - - // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer rows - // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS. - global $ADODB_COUNTRECS; - - $savec = $ADODB_COUNTRECS; - $ADODB_COUNTRECS = false; - - - if ($secs2cache != 0) $rs = $this->CacheExecute($secs2cache,$sql,$inputarr); - else $rs = $this->Execute($sql,$inputarr); - - $ADODB_COUNTRECS = $savec; - if ($rs && !$rs->EOF) { - $rs = $this->_rs2rs($rs,$nrows,$offset); - } - //print_r($rs); - return $rs; - } - - /** - * Create serializable recordset. Breaks rs link to connection. - * - * @param rs the recordset to serialize - */ - function SerializableRS(&$rs) - { - $rs2 = $this->_rs2rs($rs); - $ignore = false; - $rs2->connection = $ignore; - - return $rs2; - } - - /** - * Convert database recordset to an array recordset - * input recordset's cursor should be at beginning, and - * 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 - */ - function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true) - { - if (! $rs) { - $false = false; - return $false; - } - $dbtype = $rs->databaseType; - if (!$dbtype) { - $rs = $rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ? - return $rs; - } - if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) { - $rs->MoveFirst(); - $rs = $rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ? - return $rs; - } - $flds = array(); - for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) { - $flds[] = $rs->FetchField($i); - } - - $arr = $rs->GetArrayLimit($nrows,$offset); - //print_r($arr); - if ($close) $rs->Close(); - - $arrayClass = $this->arrayClass; - - $rs2 = new $arrayClass(); - $rs2->connection = $this; - $rs2->sql = $rs->sql; - $rs2->dataProvider = $this->dataProvider; - $rs2->InitArrayFields($arr,$flds); - $rs2->fetchMode = isset($rs->adodbFetchMode) ? $rs->adodbFetchMode : $rs->fetchMode; - return $rs2; - } - - /* - * Return all rows. Compat with PEAR DB - */ - function GetAll($sql, $inputarr=false) - { - $arr = $this->GetArray($sql,$inputarr); - return $arr; - } - - function GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false) - { - $rs = $this->Execute($sql, $inputarr); - if (!$rs) { - $false = false; - return $false; - } - $arr = $rs->GetAssoc($force_array,$first2cols); - return $arr; - } - - 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; - } - $arr = $rs->GetAssoc($force_array,$first2cols); - return $arr; - } - - /** - * Return first element of first row of sql statement. Recordset is disposed - * for you. - * - * @param sql SQL statement - * @param [inputarr] input bind array - */ - 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); - - $rs->Close(); - } - $ADODB_COUNTRECS = $crecs; - return $ret; - } - - // $where should include 'WHERE fld=value' - function GetMedian($table, $field,$where = '') - { - $total = $this->GetOne("select count(*) from $table $where"); - 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); - return false; - } - - - 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); - $rs->Close(); - } - - return $ret; - } - - function GetCol($sql, $inputarr = false, $trim = false) - { - - $rs = $this->Execute($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 - $rv = false; - return $rv; - } - - 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 - $rv = false; - - return $rv; - } - - function Transpose(&$rs,$addfieldnames=true) - { - $rs2 = $this->_rs2rs($rs); - $false = false; - if (!$rs2) return $false; - - $rs2->_transpose($addfieldnames); - return $rs2; - } - - /* - Calculate the offset of a date for a particular database and generate - appropriate SQL. Useful for calculating future/past dates and storing - in a database. - - 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; - return '('.$date.'+'.$dayFraction.')'; - } - - - /** - * - * @param sql SQL statement - * @param [inputarr] input bind array - */ - function GetArray($sql,$inputarr=false) - { - global $ADODB_COUNTRECS; - - $savec = $ADODB_COUNTRECS; - $ADODB_COUNTRECS = false; - $rs = $this->Execute($sql,$inputarr); - $ADODB_COUNTRECS = $savec; - if (!$rs) - if (defined('ADODB_PEAR')) { - $cls = ADODB_PEAR_Error(); - return $cls; - } else { - $false = false; - return $false; - } - $arr = $rs->GetArray(); - $rs->Close(); - return $arr; - } - - 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; - - $savec = $ADODB_COUNTRECS; - $ADODB_COUNTRECS = false; - $rs = $this->CacheExecute($secs2cache,$sql,$inputarr); - $ADODB_COUNTRECS = $savec; - - if (!$rs) - if (defined('ADODB_PEAR')) { - $cls = ADODB_PEAR_Error(); - return $cls; - } else { - $false = false; - return $false; - } - $arr = $rs->GetArray(); - $rs->Close(); - return $arr; - } - - function GetRandRow($sql, $arr= false) - { - $rezarr = $this->GetAll($sql, $arr); - $sz = sizeof($rezarr); - return $rezarr[abs(rand()) % $sz]; - } - - /** - * Return one row of sql statement. Recordset is disposed for you. - * - * @param sql SQL statement - * @param [inputarr] input bind array - */ - function GetRow($sql,$inputarr=false) - { - global $ADODB_COUNTRECS; - $crecs = $ADODB_COUNTRECS; - $ADODB_COUNTRECS = false; - - $rs = $this->Execute($sql,$inputarr); - - $ADODB_COUNTRECS = $crecs; - if ($rs) { - if (!$rs->EOF) $arr = $rs->fields; - else $arr = array(); - $rs->Close(); - return $arr; - } - - $false = false; - return $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(); - - $rs->Close(); - return $arr; - } - $false = false; - return $false; - } - - /** - * Insert or replace a single record. Note: this is not the same as MySQL's replace. - * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL. - * Also note that no table locking is done currently, so it is possible that the - * record be inserted twice by two programs... - * - * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname'); - * - * $table table name - * $fieldArray associative array of data (you must quote strings yourself). - * $keyCol the primary key field name or if compound key, array of field names - * autoQuote set to true to use a hueristic to quote strings. Works with nulls and numbers - * but does not work with dates nor SQL functions. - * has_autoinc the primary key is an auto-inc field, so skip in insert. - * - * Currently blob replace not supported - * - * returns 0 = fail, 1 = update, 2 = insert - */ - - 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'); - - return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc); - } - - - /** - * Will select, getting rows from $offset (1-based), for $nrows. - * This simulates the MySQL "select * from table limit $offset,$nrows" , and - * the PostgreSQL "select * from table limit $nrows offset $offset". Note that - * MySQL and PostgreSQL parameter ordering is the opposite of the other. - * eg. - * CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based) - * CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based) - * - * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set - * - * @param [secs2cache] seconds to cache data, set to 0 to force query. This is optional - * @param sql - * @param [offset] is the row to start calculations from (1-based) - * @param [nrows] is the number of rows to get - * @param [inputarr] array of bind variables - * @return the recordset ($rs->databaseType == 'array') - */ - 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 - $rs = $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs); - } else { - 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. - */ - - /** - * 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; - - if (!$sql) { - $ADODB_CACHE->flushall($this->debug); - return; - } - - $f = $this->_gencachename($sql.serialize($inputarr),false); - return $ADODB_CACHE->flushcache($f, $this->debug); - } - - - /** - * Private function to generate filename for caching. - * Filename is generated based on: - * - * - sql statement - * - database type (oci8, ibase, ifx, etc) - * - database name - * - userid - * - setFetchMode (adodb 4.23) - * - * When not in safe mode, we create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR). - * 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; - - if ($this->fetchMode === false) { - 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); - - return $dir.'/adodb_'.$m.'.cache'; - } - - - /** - * Execute SQL, caching recordsets. - * - * @param [secs2cache] seconds to cache data, set to 0 to force query. - * This is an optional parameter. - * @param sql SQL statement to execute - * @param [inputarr] holds the input data to bind to - * @return RecordSet or false - */ - function CacheExecute($secs2cache,$sql=false,$inputarr=false) - { - global $ADODB_CACHE; - - if (empty($ADODB_CACHE)) $this->_CreateCache(); - - if (!is_numeric($secs2cache)) { - $inputarr = $sql; - $sql = $secs2cache; - $secs2cache = $this->cacheSecs; - } - - if (is_array($sql)) { - $sqlparam = $sql; - $sql = $sql[0]; - } else - $sqlparam = $sql; - - - $md5file = $this->_gencachename($sql.serialize($inputarr),true); - $err = ''; - - if ($secs2cache > 0){ - $rs = $ADODB_CACHE->readcache($md5file,$err,$secs2cache,$this->arrayClass); - $this->numCacheHits += 1; - } else { - $err='Timeout 1'; - $rs = false; - $this->numCacheMisses += 1; - } - - if (!$rs) { - // no cached rs found - if ($this->debug) { - 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 (see sql below)"); - } - - $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 - $txt = _rs2serialize($rs,false,$sql); // serialize - - $ok = $ADODB_CACHE->writecache($md5file,$txt,$this->debug, $secs2cache); - if (!$ok) { - if ($ok === false) { - $em = 'Cache write error'; - $en = -32000; - - if ($fn = $this->raiseErrorFn) { - $fn($this->databaseType,'CacheExecute', $en, $em, $md5file,$sql,$this); - } - } else { - $em = 'Cache file locked warning'; - $en = -32001; - // do not call error handling for just a warning - } - - if ($this->debug) ADOConnection::outp( " ".$em); - } - if ($rs->EOF && !$eof) { - $rs->MoveFirst(); - //$rs = csv2rs($md5file,$err); - $rs->connection = $this; // Pablo suggestion - } - - } else if (!$this->memCache) - $ADODB_CACHE->flushcache($md5file); - } else { - $this->_errorMsg = ''; - $this->_errorCode = 0; - - if ($this->fnCacheExecute) { - $fn = $this->fnCacheExecute; - $fn($this, $secs2cache, $sql, $inputarr); - } - // ok, set cached object found - $rs->connection = $this; // Pablo suggestion - if ($this->debug){ - 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).''; - - ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]"); - } - } - return $rs; - } - - - /* - Similar to PEAR DB's autoExecute(), except that - $mode can be 'INSERT' or 'UPDATE' or DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE - If $mode == 'UPDATE', then $where is compulsory as a safety measure. - - $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; - } - - $rs = $this->SelectLimit($sql,1); - if (!$rs) return $false; // table does not exist - $rs->tableName = $table; - $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; - } - $ret = false; - if ($sql) $ret = $this->Execute($sql); - if ($ret) $ret = true; - return $ret; - } - - - /** - * Generates an Update Query based on an existing recordset. - * $arrFields is an associative array of fields with the value - * that should be assigned. - * - * Note: This function should only be used on a recordset - * that is run against a single table and sql should only - * be a simple select stmt with no groupby/orderby/limit - * - * "Jonathan Younger" - */ - 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; - } - //********************************************************// - - if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php'); - return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq,$force); - } - - /** - * Generates an Insert Query based on an existing recordset. - * $arrFields is an associative array of fields with the value - * that should be assigned. - * - * 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) - { - 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'); - return _adodb_getinsertsql($this,$rs,$arrFields,$magicq,$force); - } - - - /** - * Update a blob column, given a where clause. There are more sophisticated - * blob handling functions that we could have implemented, but all require - * a very complex API. Instead we have chosen something that is extremely - * simple to understand and use. - * - * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course. - * - * Usage to update a $blobvalue which has a primary key blob_id=1 into a - * field blobtable.blobcolumn: - * - * UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1'); - * - * Insert example: - * - * $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') - { - return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false; - } - - /** - * Usage: - * UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1'); - * - * $blobtype supports 'BLOB' and 'CLOB' - * - * $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') - { - $fd = fopen($path,'rb'); - if ($fd === false) return false; - $val = fread($fd,filesize($path)); - fclose($fd); - return $this->UpdateBlob($table,$column,$val,$where,$blobtype); - } - - function BlobDecode($blob) - { - return $blob; - } - - function BlobEncode($blob) - { - return $blob; - } - - function SetCharSet($charset) - { - return false; - } - - function IfNull( $field, $ifNull ) - { - return " CASE WHEN $field is null THEN $ifNull ELSE $field END "; - } - - function LogSQL($enable=true) - { - include_once(ADODB_DIR.'/adodb-perf.inc.php'); - - if ($enable) $this->fnExecute = 'adodb_log_sql'; - else $this->fnExecute = false; - - $old = $this->_logsql; - $this->_logsql = $enable; - if ($enable && !$old) $this->_affected = false; - return $old; - } - - function GetCharSet() - { - return false; - } - - /** - * Usage: - * UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB'); - * - * $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)'); - * $conn->UpdateClob('clobtable','clobcol',$clob,'id=1'); - */ - 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) - { - - if (empty($this->_metars)) { - $rsclass = $this->rsPrefix.$this->databaseType; - $this->_metars = new $rsclass(false,$this->fetchMode); - $this->_metars->connection = $this; - } - return $this->_metars->MetaType($t,$len,$fieldobj); - } - - - /** - * 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') - { - $this->locale = $locale; - switch (strtoupper($locale)) - { - case 'EN': - $this->fmtDate="'Y-m-d'"; - $this->fmtTimeStamp = "'Y-m-d H:i:s'"; - break; - - case 'US': - $this->fmtDate = "'m-d-Y'"; - $this->fmtTimeStamp = "'m-d-Y H:i:s'"; - break; - - case 'PT_BR': - case 'NL': - case 'FR': - case 'RO': - case 'IT': - $this->fmtDate="'d-m-Y'"; - $this->fmtTimeStamp = "'d-m-Y H:i:s'"; - break; - - case 'GE': - $this->fmtDate="'d.m.Y'"; - $this->fmtTimeStamp = "'d.m.Y H:i:s'"; - break; - - default: - $this->fmtDate="'Y-m-d'"; - $this->fmtTimeStamp = "'Y-m-d H:i:s'"; - break; - } - } - - /** - * GetActiveRecordsClass Performs an 'ALL' query - * - * @param mixed $class This string represents the class of the current active record - * @param mixed $table Table used by the active record object - * @param mixed $whereOrderBy Where, order, by clauses - * @param mixed $bindarr - * @param mixed $primkeyArr - * @param array $extra Query extras: limit, offset... - * @param mixed $relations Associative array: table's foreign name, "hasMany", "belongsTo" - * @access public - * @return void - */ - function GetActiveRecordsClass( - $class, $table,$whereOrderBy=false,$bindarr=false, $primkeyArr=false, - $extra=array(), - $relations=array()) - { - 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'); - return adodb_GetActiveRecordsClass($this, $class, $table, $whereOrderBy, $bindarr, $primkeyArr, $extra, $relations); - } - - function GetActiveRecords($table,$where=false,$bindarr=false,$primkeyArr=false) - { - $arr = $this->GetActiveRecordsClass('ADODB_Active_Record', $table, $where, $bindarr, $primkeyArr); - return $arr; - } - - /** - * Close Connection - */ - function Close() - { - $rez = $this->_close(); - $this->_connectionID = false; - return $rez; - } - - /** - * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans(). - * - * @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"); - return false; - } - - /* set transaction mode */ - function SetTransactionMode( $transaction_mode ) - { - $transaction_mode = $this->MetaTransaction($transaction_mode, $this->dataProvider); - $this->_transmode = $transaction_mode; - } -/* -http://msdn2.microsoft.com/en-US/ms173763.aspx -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) - { - $mode = strtoupper($mode); - $mode = str_replace('ISOLATION LEVEL ','',$mode); - - switch($mode) { - - case 'READ UNCOMMITTED': - switch($db) { - case 'oci8': - case 'oracle': - return 'ISOLATION LEVEL READ COMMITTED'; - default: - return 'ISOLATION LEVEL READ UNCOMMITTED'; - } - break; - - case 'READ COMMITTED': - return 'ISOLATION LEVEL READ COMMITTED'; - break; - - case 'REPEATABLE READ': - switch($db) { - case 'oci8': - case 'oracle': - return 'ISOLATION LEVEL SERIALIZABLE'; - default: - return 'ISOLATION LEVEL REPEATABLE READ'; - } - break; - - case 'SERIALIZABLE': - return 'ISOLATION LEVEL SERIALIZABLE'; - break; - - default: - return $mode; - } - } - - /** - * If database does not support transactions, always return true as data always commited - * - * @param $ok set to false to rollback transaction, true to commit - * - * @return true/false. - */ - function CommitTrans($ok=true) - { return true;} - - - /** - * If database does not support transactions, rollbacks always fail, so return false - * - * @return true/false. - */ - function RollbackTrans() - { return false;} - - - /** - * return the databases that the driver can connect to. - * Some databases will return an empty array. - * - * @return an array of database names. - */ - 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); - - $arr = $this->GetCol($this->metaDatabasesSQL); - if (isset($savem)) $this->SetFetchMode($savem); - $ADODB_FETCH_MODE = $save; - - return $arr; - } - - return false; - } - - - /** - * @param ttype can either be 'VIEW' or 'TABLE' or false. - * 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 - * @param mask is the input mask - only supported by oci8 and postgresql - * - * @return array of tables for current database. - */ - function MetaTables($ttype=false,$showSchema=false,$mask=false) - { - global $ADODB_FETCH_MODE; - - - $false = false; - if ($mask) { - return $false; - } - if ($this->metaTablesSQL) { - $save = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - - if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false); - - $rs = $this->Execute($this->metaTablesSQL); - if (isset($savem)) $this->SetFetchMode($savem); - $ADODB_FETCH_MODE = $save; - - if ($rs === false) return $false; - $arr = $rs->GetArray(); - $arr2 = array(); - - if ($hast = ($ttype && isset($arr[0][1]))) { - $showt = strncmp($ttype,'T',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]); - } else { - if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]); - } - } else - $arr2[] = trim($arr[$i][0]); - } - $rs->Close(); - return $arr2; - } - return $false; - } - - - function _findschema(&$table,&$schema) - { - if (!$schema && ($at = strpos($table,'.')) !== false) { - $schema = substr($table,0,$at); - $table = substr($table,$at+1); - } - } - - /** - * List columns in a database as an array of ADOFieldObjects. - * See top of file for definition of object. - * - * @param $table table name to query - * @param $normalize makes table name case-insensitive (required by some databases) - * @schema is optional database schema to use - not supported by all databases. - * - * @return array of ADOFieldObjects for current table. - */ - function MetaColumns($table,$normalize=true) - { - global $ADODB_FETCH_MODE; - - $false = false; - - 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); - $rs = $this->Execute(sprintf($this->metaColumnsSQL,($normalize)?strtoupper($table):$table)); - if (isset($savem)) $this->SetFetchMode($savem); - $ADODB_FETCH_MODE = $save; - if ($rs === false || $rs->EOF) return $false; - - $retarr = array(); - while (!$rs->EOF) { //print_r($rs->fields); - $fld = new ADOFieldObject(); - $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]; - $fld->scale = $rs->fields[4]; - 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; - $rs->MoveNext(); - } - $rs->Close(); - return $retarr; - } - return $false; - } - - /** - * List indexes on a table as an array. - * @param table table name to query - * @param primary true to only show primary keys. Not actually used for most databases - * - * @return array of indexes on current table. Each element represents an index, and is itself an associative array. - - Array ( - [name_of_index] => Array - ( - [unique] => true or false - [columns] => Array - ( - [0] => firstname - [1] => lastname - ) - ) - */ - function MetaIndexes($table, $primary = false, $owner = false) - { - $false = false; - return $false; - } - - /** - * List columns names in a table as an array. - * @param table table name to query - * - * @return array of column names for current table. - */ - function MetaColumnNames($table, $numIndexes=false,$useattnum=false /* only for postgres */) - { - $objarr = $this->MetaColumns($table); - if (!is_array($objarr)) { - $false = false; - return $false; - } - $arr = array(); - if ($numIndexes) { - $i = 0; - if ($useattnum) { - foreach($objarr as $v) - $arr[$v->attnum] = $v->name; - - } else - foreach($objarr as $v) $arr[$i++] = $v->name; - } else - foreach($objarr as $v) $arr[strtoupper($v->name)] = $v->name; - - return $arr; - } - - /** - * Different SQL databases used different methods to combine strings together. - * This function provides a wrapper. - * - * param s variable number of string parameters - * - * Usage: $db->Concat($str1,$str2); - * - * @return concatenated string - */ - function Concat() - { - $arr = func_get_args(); - return implode($this->concat_operator, $arr); - } - - - /** - * Converts a date "d" to a string that the database can understand. - * - * @param d a date in Unix date time format. - * - * @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); - - - if (is_string($d) && !is_numeric($d)) { - if ($d === 'null' || strncmp($d,"'",1) === 0) return $d; - if ($this->isoDates) return "'$d'"; - $d = ADOConnection::UnixDate($d); - } - - return adodb_date($this->fmtDate,$d); - } - - function BindDate($d) - { - $d = $this->DBDate($d); - if (strncmp($d,"'",1)) return $d; - - return substr($d,1,strlen($d)-2); - } - - function BindTimeStamp($d) - { - $d = $this->DBTimeStamp($d); - if (strncmp($d,"'",1)) return $d; - - return substr($d,1,strlen($d)-2); - } - - - /** - * Converts a timestamp "ts" to a string that the database can understand. - * - * @param ts a timestamp in Unix date time format. - * - * @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); - - # strlen(14) allows YYYYMMDDHHMMSS format - if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14)) - return adodb_date($this->fmtTimeStamp,$ts); - - if ($ts === 'null') return $ts; - if ($this->isoDates && strlen($ts) !== 14) return "'$ts'"; - - $ts = ADOConnection::UnixTimeStamp($ts); - return adodb_date($this->fmtTimeStamp,$ts); - } - - /** - * Also in ADORecordSet. - * @param $v is a date string in YYYY-MM-DD format - * - * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format - */ - 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 ($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]); - } - - - /** - * Also in ADORecordSet. - * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format - * - * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format - */ - static function UnixTimeStamp($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 (!preg_match( - "|^([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; - - // 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]); - } - - /** - * Also in ADORecordSet. - * - * 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() - * - * @return a date formated as user desires - */ - - 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 - } - - 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() - * - * @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; - # strlen(14) allows YYYYMMDDHHMMSS format - 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; - return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt); - } - - 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) - { - if (!$magic_quotes) { - - 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)); - } - return str_replace("'",$this->replaceQuote,$s); - } - - // undo magic quotes for " - $s = str_replace('\\"','"',$s); - - if ($this->replaceQuote == "\\'" || ini_get('magic_quotes_sybase')) // ' already quoted, no need to change anything - return $s; - else {// change \' to '' for sybase/mssql - $s = str_replace('\\\\','\\',$s); - return str_replace("\\'",$this->replaceQuote,$s); - } - } - - /** - * Correctly quotes a string so that all strings are escaped. We prefix and append - * to the string single-quotes. - * An example is $db->qstr("Don't bother",magic_quotes_runtime()); - * - * @param s the string to quote - * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc(). - * This undoes the stupidity of magic quotes for GPC. - * - * @return quoted string to be sent back to database - */ - 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); - //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s)); - } - return "'".str_replace("'",$this->replaceQuote,$s)."'"; - } - - // undo magic quotes for " - $s = str_replace('\\"','"',$s); - - if ($this->replaceQuote == "\\'" || ini_get('magic_quotes_sybase')) // ' already quoted, no need to change anything - return "'$s'"; - else {// change \' to '' for sybase/mssql - $s = str_replace('\\\\','\\',$s); - return "'".str_replace("\\'",$this->replaceQuote,$s)."'"; - } - } - - - /** - * 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. - * - * See readme.htm#ex8 for an example of usage. - * - * @param sql - * @param nrows is the number of rows per page to get - * @param page is the page number to get (1-based) - * @param [inputarr] array of bind variables - * @param [secs2cache] is a private parameter only used by jlim - * @return the recordset ($rs->databaseType == 'array') - * - * NOTE: phpLens uses a different algorithm and does not use PageExecute(). - * - */ - 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); - return $rs; - } - - - /** - * 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. - * - * @param secs2cache seconds to cache data, set to 0 to force query - * @param sql - * @param nrows is the number of rows per page to get - * @param page is the page number to get (1-based) - * @param [inputarr] array of bind variables - * @return the recordset ($rs->databaseType == 'array') - */ - function CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false) - { - /*switch($this->dataProvider) { - case 'postgres': - case 'mysql': - break; - default: $secs2cache = 0; break; - }*/ - $rs = $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache); - return $rs; - } - -} // end class ADOConnection - - - - //============================================================================================== - // CLASS ADOFetchObj - //============================================================================================== - - /** - * Internal placeholder for record objects. Used by ADORecordSet->FetchObj(). - */ - class ADOFetchObj { - }; - - //============================================================================================== - // CLASS ADORecordSet_empty - //============================================================================================== - - class ADODB_Iterator_empty implements Iterator { - - private $rs; - - function __construct($rs) - { - $this->rs = $rs; - } - function rewind() - { - } - - function valid() - { - return !$this->rs->EOF; - } - - function key() - { - return false; - } - - function current() - { - return false; - } - - function next() - { - } - - function __call($func, $params) - { - return call_user_func_array(array($this->rs, $func), $params); - } - - function hasMore() - { - return false; - } - - } - - - /** - * Lightweight recordset when there are no records to be returned - */ - class ADORecordSet_empty implements IteratorAggregate - { - var $dataProvider = 'empty'; - var $databaseType = false; - var $EOF = true; - 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 Init() {} - function getIterator() {return new ADODB_Iterator_empty($this);} - } - - //============================================================================================== - // DATE AND TIME FUNCTIONS - //============================================================================================== - if (!defined('ADODB_DATE_VERSION')) include(ADODB_DIR.'/adodb-time.inc.php'); - - //============================================================================================== - // CLASS ADORecordSet - //============================================================================================== - - class ADODB_Iterator implements Iterator { - - private $rs; - - function __construct($rs) - { - $this->rs = $rs; - } - function rewind() - { - $this->rs->MoveFirst(); - } - - function valid() - { - return !$this->rs->EOF; - } - - function key() - { - return $this->rs->_currentRow; - } - - function current() - { - return $this->rs->fields; - } - - function next() - { - $this->rs->MoveNext(); - } - - function __call($func, $params) - { - return call_user_func_array(array($this->rs, $func), $params); - } - - - 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. - * No prefetching of data is done, so the RecordCount() can return -1 ( which - * 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 - /// in other words, we use a text area for editing. - 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 $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 $_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 $_lastPageNo = -1; - var $_maxRecordCount = 0; - var $datetime = false; - - /** - * Constructor - * - * @param queryID this is the queryID returned by ADOConnection->_query() - * - */ - function ADORecordSet($queryID) - { - $this->_queryID = $queryID; - } - - function getIterator() - { - return new ADODB_Iterator($this); - } - - /* this is experimental - i don't really know what to return... */ - function __toString() - { - include_once(ADODB_DIR.'/toexport.inc.php'); - return _adodb_export($this,',',',',false,true); - } - - - function Init() - { - if ($this->_inited) return; - $this->_inited = true; - 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 - } - } else { - $this->EOF = true; - } - } - - - /** - * Generate a SELECT tag string from a recordset, and return the string. - * If the recordset has 2 cols, we treat the 1st col as the containing - * 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 [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 - * @param [size] #rows to show for listbox. not used by popup - * @param [selectAttr] additional attributes to defined for SELECT tag. - * useful for holding javascript onChange='...' handlers. - & @param [compareFields0] when we have 2 cols in recordset, we compare the defstr with - * column 0 (1st col) if this is true. This is not documented. - * - * @return HTML - * - * changes by glen.davies@cce.ac.nz to support multiple hilited items - */ - function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false, - $size=0, $selectAttr='',$compareFields0=true) - { - global $ADODB_INCLUDED_LIB; - if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php'); - return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple, - $size, $selectAttr,$compareFields0); - } - - - - /** - * Generate a SELECT tag string from a recordset, and return the string. - * If the recordset has 2 cols, we treat the 1st col as the containing - * the text to display to the user, and 2nd col as the return value. Default - * strings are compared with the SECOND column. - * - */ - function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='') - { - return $this->GetMenu($name,$defstr,$blank1stItem,$multiple, - $size, $selectAttr,false); - } - - /* - Grouped Menu - */ - function GetMenu3($name,$defstr='',$blank1stItem=true,$multiple=false, - $size=0, $selectAttr='') - { - global $ADODB_INCLUDED_LIB; - if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php'); - return _adodb_getmenu_gp($this, $name,$defstr,$blank1stItem,$multiple, - $size, $selectAttr,false); - } - - /** - * return recordset as a 2-dimensional array. - * - * @param [nRows] is the number of rows to return. -1 means every row. - * - * @return an array indexed by the rows (0-based) from the recordset - */ - function GetArray($nRows = -1) - { - global $ADODB_EXTENSION; if ($ADODB_EXTENSION) { - $results = adodb_getall($this,$nRows); - return $results; - } - $results = array(); - $cnt = 0; - while (!$this->EOF && $nRows != $cnt) { - $results[] = $this->fields; - $this->MoveNext(); - $cnt++; - } - return $results; - } - - function GetAll($nRows = -1) - { - $arr = $this->GetArray($nRows); - return $arr; - } - - /* - * 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() - { - return false; - } - - /** - * return recordset as a 2-dimensional array. - * Helper function for ADOConnection->SelectLimit() - * - * @param offset is the row to start calculations from (1-based) - * @param [nrows] is the number of rows to return - * - * @return an array indexed by the rows (0-based) from the recordset - */ - function GetArrayLimit($nrows,$offset=-1) - { - if ($offset <= 0) { - $arr = $this->GetArray($nrows); - return $arr; - } - - $this->Move($offset); - - $results = array(); - $cnt = 0; - while (!$this->EOF && $nrows != $cnt) { - $results[$cnt++] = $this->fields; - $this->MoveNext(); - } - - return $results; - } - - - /** - * Synonym for GetArray() for compatibility with ADO. - * - * @param [nRows] is the number of rows to return. -1 means every row. - * - * @return an array indexed by the rows (0-based) from the recordset - */ - function GetRows($nRows = -1) - { - $arr = $this->GetArray($nRows); - return $arr; - } - - /** - * return whole recordset as a 2-dimensional associative array if there are more than 2 columns. - * The first column is treated as the key and is not included in the array. - * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless - * $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. - * - * @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. - */ - function GetAssoc($force_array = false, $first2cols = false) - { - global $ADODB_EXTENSION; - - $cols = $this->_numOfFields; - if ($cols < 2) { - $false = false; - return $false; - } - $numIndex = isset($this->fields[0]); - $results = array(); - - if (!$first2cols && ($cols > 2 || $force_array)) { - if ($ADODB_EXTENSION) { - if ($numIndex) { - while (!$this->EOF) { - $results[trim($this->fields[0])] = array_slice($this->fields, 1); - adodb_movenext($this); - } - } else { - while (!$this->EOF) { - // Fix for array_slice re-numbering numeric associative keys - $keys = array_slice(array_keys($this->fields), 1); - $sliced_array = array(); - - foreach($keys as $key) { - $sliced_array[$key] = $this->fields[$key]; - } - - $results[trim(reset($this->fields))] = $sliced_array; - adodb_movenext($this); - } - } - } else { - if ($numIndex) { - while (!$this->EOF) { - $results[trim($this->fields[0])] = array_slice($this->fields, 1); - $this->MoveNext(); - } - } else { - while (!$this->EOF) { - // Fix for array_slice re-numbering numeric associative keys - $keys = array_slice(array_keys($this->fields), 1); - $sliced_array = array(); - - foreach($keys as $key) { - $sliced_array[$key] = $this->fields[$key]; - } - - $results[trim(reset($this->fields))] = $sliced_array; - $this->MoveNext(); - } - } - } - } else { - if ($ADODB_EXTENSION) { - // return scalar values - if ($numIndex) { - while (!$this->EOF) { - // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string - $results[trim(($this->fields[0]))] = $this->fields[1]; - adodb_movenext($this); - } - } else { - while (!$this->EOF) { - // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string - $v1 = trim(reset($this->fields)); - $v2 = ''.next($this->fields); - $results[$v1] = $v2; - adodb_movenext($this); - } - } - } else { - if ($numIndex) { - while (!$this->EOF) { - // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string - $results[trim(($this->fields[0]))] = $this->fields[1]; - $this->MoveNext(); - } - } else { - while (!$this->EOF) { - // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string - $v1 = trim(reset($this->fields)); - $v2 = ''.next($this->fields); - $results[$v1] = $v2; - $this->MoveNext(); - } - } - } - } - - $ref = $results; # workaround accelerator incompat with PHP 4.4 :( - return $ref; - } - - - /** - * - * @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); - $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; - 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() - * - * @return a date formated as user desires - */ - 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 - } - return adodb_date($fmt,$tt); - } - - - /** - * @param $v is a date string in YYYY-MM-DD format - * - * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format - */ - static function UnixDate($v) - { - return ADOConnection::UnixDate($v); - } - - - /** - * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format - * - * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format - */ - static function UnixTimeStamp($v) - { - return ADOConnection::UnixTimeStamp($v); - } - - - /** - * PEAR DB Compat - do not use internally - */ - function Free() - { - return $this->Close(); - } - - - /** - * PEAR DB compat, number of rows - */ - function NumRows() - { - return $this->_numOfRows; - } - - - /** - * PEAR DB compat, number of cols - */ - function NumCols() - { - return $this->_numOfFields; - } - - /** - * Fetch a row, returning false if no more rows. - * This is PEAR DB compat mode. - * - * @return false or array containing the current record - */ - function FetchRow() - { - if ($this->EOF) { - $false = false; - return $false; - } - $arr = $this->fields; - $this->_currentRow++; - if (!$this->_fetch()) $this->EOF = true; - return $arr; - } - - - /** - * Fetch a row, returning PEAR_Error if no more rows. - * This is PEAR DB compat mode. - * - * @return DB_OK or error object - */ - 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 - } - - - /** - * Move to the first row in the recordset. Many databases do NOT support this. - * - * @return true or false - */ - function MoveFirst() - { - if ($this->_currentRow == 0) return true; - return $this->Move(0); - } - - - /** - * Move to the last row in the recordset. - * - * @return true or 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(); - } - $this->fields = $f; - $this->EOF = false; - return true; - } - - - /** - * Move to next record in the recordset. - * - * @return true if there still rows available, or false if there are no more rows (EOF). - */ - function MoveNext() - { - if (!$this->EOF) { - $this->_currentRow++; - if ($this->_fetch()) return true; - } - $this->EOF = true; - /* -- tested error handling when scrolling cursor -- seems useless. - $conn = $this->connection; - if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) { - $fn = $conn->raiseErrorFn; - $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database); - } - */ - return false; - } - - - /** - * Random access to a specific row in the recordset. Some databases do not support - * access to previous rows in the databases (no scrolling backwards). - * - * @param rowNumber is the row to move to (0-based) - * - * @return true if there still rows available, or false if there are no more rows (EOF). - */ - 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 ($this->canSeek) { - - if ($this->_seek($rowNumber)) { - $this->_currentRow = $rowNumber; - if ($this->_fetch()) { - return true; - } - } else { - $this->EOF = true; - return false; - } - } else { - 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; - } - } - return !($this->EOF); - } - - $this->fields = false; - $this->EOF = true; - return false; - } - - - /** - * Get the value of a field in the current row by column name. - * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM. - * - * @param colname is the field to access - * - * @return the value of $colname column - */ - function Fields($colname) - { - return $this->fields[$colname]; - } - - function GetAssocKeys($upper=true) - { - $this->bind = array(); - for ($i=0; $i < $this->_numOfFields; $i++) { - $o = $this->FetchField($i); - if ($upper === 2) $this->bind[$o->name] = $i; - else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i; - } - } - - /** - * Use associative array to get fields array for databases that do not support - * associative arrays. Submitted by Paolo S. Asioli paolo.asioli#libero.it - * - * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC - * before you execute your SQL statement, and access $rs->fields['col'] directly. - * - * $upper 0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField - */ - function GetRowAssoc($upper=1) - { - $record = array(); - // if (!$this->fields) return $record; - - if (!$this->bind) { - $this->GetAssocKeys($upper); - } - - foreach($this->bind as $k => $v) { - $record[$k] = $this->fields[$v]; - } - - return $record; - } - - - /** - * Clean up recordset - * - * @return true or false - */ - 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; - if (!$this->_closed) { - $this->_closed = true; - return $this->_close(); - } else - return true; - } - - /** - * synonyms RecordCount and RowCount - * - * @return the number of rows or -1 if this is not supported - */ - 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() - { - return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount(); - } - - /** - * synonyms RecordCount and RowCount - * - * @return the number of rows or -1 if this is not supported - */ - function RowCount() {return $this->_numOfRows;} - - - /** - * Portable RecordCount. Pablo Roca - * - * @return the number of records from a previous SELECT. All databases support this. - * - * But aware possible problems in multiuser environments. For better speed the table - * must be indexed by the condition. Heavy test this before deploying. - */ - function PO_RecordCount($table="", $condition="") { - - $lnumrows = $this->_numOfRows; - // the database doesn't support native recordcount, so we do a workaround - if ($lnumrows == -1 && $this->connection) { - IF ($table) { - if ($condition) $condition = " WHERE " . $condition; - $resultrows = $this->connection->Execute("SELECT COUNT(*) FROM $table $condition"); - if ($resultrows) $lnumrows = reset($resultrows->fields); - } - } - return $lnumrows; - } - - - /** - * @return the current row in the recordset. If at EOF, will return the last row. 0-based. - */ - 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;} - - /** - * @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;} - - - /** - * Get the ADOFieldObject of a specific column. - * - * @param fieldoffset is the column position to access(0-based). - * - * @return the ADOFieldObject for that column, or false. - */ - function FetchField($fieldoffset = -1) - { - // must be defined by child class - - $false = false; - return $false; - } - - /** - * Get the ADOFieldObjects of all columns in an array. - * - */ - function FieldTypesArray() - { - $arr = array(); - for ($i=0, $max=$this->_numOfFields; $i < $max; $i++) - $arr[] = $this->FetchField($i); - return $arr; - } - - /** - * Return the fields array of the current row as an object for convenience. - * The default case is lowercase field names. - * - * @return the object with the properties set to the fields of the current row - */ - function FetchObj() - { - $o = $this->FetchObject(false); - return $o; - } - - /** - * Return the fields array of the current row as an object for convenience. - * The default case is uppercase. - * - * @param $isupper to set the object property names to uppercase - * - * @return the object with the properties set to the fields of the current row - */ - function FetchObject($isupper=true) - { - if (empty($this->_obj)) { - $this->_obj = new ADOFetchObj(); - $this->_names = array(); - for ($i=0; $i <$this->_numOfFields; $i++) { - $f = $this->FetchField($i); - $this->_names[] = $f->name; - } - } - $i = 0; - 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; - - $o->$n = $this->Fields($name); - } - return $o; - } - - /** - * Return the fields array of the current row as an object for convenience. - * 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 - * - * Fixed bug reported by tim@orotech.net - */ - function FetchNextObj() - { - $o = $this->FetchNextObject(false); - return $o; - } - - - /** - * Return the fields array of the current row as an object for convenience. - * The default is upper case field names. - * - * @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 - * - * Fixed bug reported by tim@orotech.net - */ - function FetchNextObject($isupper=true) - { - $o = false; - if ($this->_numOfRows != 0 && !$this->EOF) { - $o = $this->FetchObject($isupper); - $this->_currentRow++; - if ($this->_fetch()) return $o; - } - $this->EOF = true; - return $o; - } - - /** - * Get the metatype of the column. This is used for formatting. This is because - * many databases use different names for the same type, so we transform the original - * type to our standardised version which uses 1 character codes: - * - * @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). - * @param fieldobj is the field object returned by the database driver. Can hold - * additional info (eg. primary_key for mysql). - * - * @return the general type of the data: - * C for character < 250 chars - * X for teXt (>= 250 chars) - * B for Binary - * N for numeric or floating point - * D for date - * T for timestamp - * L for logical/Boolean - * I for integer - * R for autoincrement counter/integer - * - * - */ - 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' - ); - - $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 'I': - if (!empty($fieldobj->primary_key)) return 'R'; - return 'I'; - - case false: - return 'N'; - - 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'; - - default: - if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B'; - return $tmap; - } - } - - - function _close() {} - - /** - * set/returns the current recordset page when paginating - */ - 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; - return $this->_atFirstPage; - } - - 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; - return $this->_atLastPage; - } - -} // end class ADORecordSet - - //============================================================================================== - // CLASS ADORecordSet_array - //============================================================================================== - - /** - * This class encapsulates the concept of a recordset created in memory - * as an array. This is useful for the creation of cached recordsets. - * - * 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 $_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 - var $_fieldobjects; // holds array of field objects - var $canSeek = true; - var $affectedrows = false; - var $insertid = false; - var $sql = ''; - var $compat = false; - /** - * Constructor - * - */ - function ADORecordSet_array($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 - $this->fetchMode = $ADODB_FETCH_MODE; - } - - function _transpose($addfieldnames=true) - { - global $ADODB_INCLUDED_LIB; - - if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php'); - $hdr = true; - - $fobjs = $addfieldnames ? $this->_fieldobjects : false; - adodb_transpose($this->_array, $newarr, $hdr, $fobjs); - //adodb_pr($newarr); - - $this->_skiprow1 = false; - $this->_array = $newarr; - $this->_colnames = $hdr; - - adodb_probetypes($newarr,$this->_types); - - $this->_fieldobjects = array(); - - foreach($hdr as $k => $name) { - $f = new ADOFieldObject(); - $f->name = $name; - $f->type = $this->_types[$k]; - $f->max_length = -1; - $this->_fieldobjects[] = $f; - } - $this->fields = reset($this->_array); - - $this->_initrs(); - - } - - /** - * Setup the array. - * - * @param array is a 2-dimensional array holding the data. - * The first row should hold the column names - * unless paramter $colnames is used. - * @param typearr holds an array of types. These are the same types - * used in MetaTypes (C,B,L,I,N). - * @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) - { - $this->_array = $array; - $this->_types = $typearr; - if ($colnames) { - $this->_skiprow1 = false; - $this->_colnames = $colnames; - } else { - $this->_skiprow1 = true; - $this->_colnames = $array[0]; - } - $this->Init(); - } - /** - * Setup the Array and datatype file objects - * - * @param array is a 2-dimensional array holding the data. - * The first row should hold the column names - * unless paramter $colnames is used. - * @param fieldarr holds an array of ADOFieldObject's. - */ - function InitArrayFields(&$array,&$fieldarr) - { - $this->_array = $array; - $this->_skiprow1= false; - if ($fieldarr) { - $this->_fieldobjects = $fieldarr; - } - $this->Init(); - } - - function GetArray($nRows=-1) - { - if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) { - return $this->_array; - } else { - $arr = ADORecordSet::GetArray($nRows); - return $arr; - } - } - - function _initrs() - { - $this->_numOfRows = sizeof($this->_array); - if ($this->_skiprow1) $this->_numOfRows -= 1; - - $this->_numOfFields =(isset($this->_fieldobjects)) ? - sizeof($this->_fieldobjects):sizeof($this->_types); - } - - /* Use associative array to get fields array */ - 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); - 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 FetchField($fieldOffset = -1) - { - if (isset($this->_fieldobjects)) { - return $this->_fieldobjects[$fieldOffset]; - } - $o = new ADOFieldObject(); - $o->name = $this->_colnames[$fieldOffset]; - $o->type = $this->_types[$fieldOffset]; - $o->max_length = -1; // length not known - - return $o; - } - - function _seek($row) - { - if (sizeof($this->_array) && 0 <= $row && $row < $this->_numOfRows) { - $this->_currentRow = $row; - if ($this->_skiprow1) $row += 1; - $this->fields = $this->_array[$row]; - return true; - } - return false; - } - - function MoveNext() - { - if (!$this->EOF) { - $this->_currentRow++; - - $pos = $this->_currentRow; - - if ($this->_numOfRows <= $pos) { - if (!$this->compat) $this->fields = false; - } else { - if ($this->_skiprow1) $pos += 1; - $this->fields = $this->_array[$pos]; - return true; - } - $this->EOF = true; - } - - return false; - } - - function _fetch() - { - $pos = $this->_currentRow; - - if ($this->_numOfRows <= $pos) { - if (!$this->compat) $this->fields = false; - return false; - } - if ($this->_skiprow1) $pos += 1; - $this->fields = $this->_array[$pos]; - return true; - } - - function _close() - { - return true; - } - - } // ADORecordSet_array - - //============================================================================================== - // HELPER FUNCTIONS - //============================================================================================== - - /** - * Synonym for ADOLoadCode. Private function. Do not use. - * - * @deprecated - */ - 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; - - if (!$dbType) return false; - $db = strtolower($dbType); - switch ($db) { - case 'ado': - if (PHP_VERSION >= 5) $db = 'ado5'; - $class = 'ado'; - break; - case 'ifx': - case 'maxsql': $class = $db = 'mysqlt'; break; - case 'postgres': - case 'postgres8': - case 'pgsql': $class = $db = 'postgres7'; break; - default: - $class = $db; break; - } - - $file = ADODB_DIR."/drivers/adodb-".$db.".inc.php"; - @include_once($file); - $ADODB_LASTDB = $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"); - return false; - } - - /** - * synonym for ADONewConnection for people like me who cannot remember the correct name - */ - function NewADOConnection($db='') - { - $tmp = ADONewConnection($db); - return $tmp; - } - - /** - * 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(). - * - * @return the freshly created instance of the Connection class. - */ - function ADONewConnection($db='') - { - GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB; - - if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2); - $errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false; - $false = false; - if (($at = strpos($db,'://')) !== FALSE) { - $origdsn = $db; - $fakedsn = 'fake'.substr($origdsn,$at); - if (($at2 = strpos($origdsn,'@/')) !== FALSE) { - // special handling of oracle, which might not have host - $fakedsn = str_replace('@/','@adodb-fakehost/',$fakedsn); - } - - if ((strpos($origdsn, 'sqlite')) !== FALSE) { - // special handling for SQLite, it only might have the path to the database file. - // If you try to connect to a SQLite database using a dsn like 'sqlite:///path/to/database', the 'parse_url' php function - // will throw you an exception with a message such as "unable to parse url" - list($scheme, $path) = explode('://', $origdsn); - $dsna['scheme'] = $scheme; - if ($qmark = strpos($path,'?')) { - $dsn['query'] = substr($path,$qmark+1); - $path = substr($path,0,$qmark); - } - $dsna['path'] = '/' . urlencode($path); - } else - $dsna = @parse_url($fakedsn); - - if (!$dsna) { - return $false; - } - $dsna['scheme'] = substr($origdsn,0,$at); - if ($at2 !== FALSE) { - $dsna['host'] = ''; - } - - 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') - $dsna['host'] = rawurlencode($sch[1].':'.rawurldecode($dsna['host'])); - else - $dsna['host'] = rawurlencode($sch[1].':host='.rawurldecode($dsna['host'])); - $dsna['scheme'] = 'pdo'; - } - } - - $db = @$dsna['scheme']; - 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']) : ''; - $dsna['path'] = isset($dsna['path']) ? rawurldecode(substr($dsna['path'],1)) : ''; # strip off initial / - - if (isset($dsna['query'])) { - $opt1 = explode('&',$dsna['query']); - foreach($opt1 as $k => $v) { - $arr = explode('=',$v); - $opt[$arr[0]] = isset($arr[1]) ? rawurldecode($arr[1]) : 1; - } - } else $opt = array(); - } - /* - * phptype: Database backend used in PHP (mysql, odbc etc.) - * dbsyntax: Database used with regards to SQL syntax etc. - * protocol: Communication protocol to use (tcp, unix etc.) - * hostspec: Host specification (hostname[:port]) - * database: Database to use on the DBMS server - * username: User name for login - * password: Password for login - */ - if (!empty($ADODB_NEWCONNECTION)) { - $obj = $ADODB_NEWCONNECTION($db); - - } - - if(empty($obj)) { - - 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 ($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; - } - - $cls = 'ADODB_'.$db; - if (!class_exists($cls)) { - adodb_backtrace(); - return $false; - } - - $obj = new $cls(); - } - - # constructor should not fail - if ($obj) { - if ($errorfn) $obj->raiseErrorFn = $errorfn; - if (isset($dsna)) { - 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 'debug': $obj->debug = (integer) $v; break; - #ibase - case 'role': $obj->role = $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; - #ado - case 'charpage': $obj->charPage = $v; break; - #mysql, mysqli - case 'clientflags': $obj->clientFlags = $v; break; - #mysql, mysqli, postgres - case 'port': $obj->port = $v; break; - #mysqli - case 'socket': $obj->socket = $v; break; - #oci8 - case 'nls_date_format': $obj->NLS_DATE_FORMAT = $v; break; - case 'cachesecs': $obj->cacheSecs = $v; break; - case 'memcache': - $varr = explode(':',$v); - $vlen = sizeof($varr); - if ($vlen == 0) break; - $obj->memCache = true; - $obj->memCacheHost = explode(',',$varr[0]); - if ($vlen == 1) break; - $obj->memCachePort = $varr[1]; - if ($vlen == 2) break; - $obj->memCacheCompress = $varr[2] ? true : false; - break; - } - } - if (empty($persist)) - $ok = $obj->Connect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']); - else if (empty($nconnect)) - $ok = $obj->PConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']); - else - $ok = $obj->NConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']); - - if (!$ok) return $false; - } - } - return $obj; - } - - - - // $perf == true means called by NewPerfMonitor(), otherwise for data dictionary - 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; - } - - switch($drivername) { - case 'mysqlt': - case 'mysqli': - $drivername='mysql'; - break; - 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; - } - return $drivername; - } - - function NewPerfMonitor(&$conn) - { - $false = false; - $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true); - 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; - $perf = new $class($conn); - - return $perf; - } - - function NewDataDictionary(&$conn,$drivername=false) - { - $false = 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'); - $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php"; - - if (!file_exists($path)) { - ADOConnection::outp("Dictionary driver '$path' not available"); - return $false; - } - include_once($path); - $class = "ADODB2_$drivername"; - $dict = new $class(); - $dict->dataProvider = $conn->dataProvider; - $dict->connection = $conn; - $dict->upperName = strtoupper($drivername); - $dict->quote = $conn->nameQuote; - if (!empty($conn->_connectionID)) - $dict->serverInfo = $conn->ServerInfo(); - - return $dict; - } - - - - /* - Perform a print_r, with pre tags for better formatting. - */ - 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 - print_r($var); - - if ($as_string) { - $s = ob_get_contents(); - ob_end_clean(); - return $s; - } - } - - /* - Perform a stack-crawl and pretty print it. - - @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) - { - global $ADODB_INCLUDED_LIB; - if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php'); - return _adodb_backtrace($printOrArr,$levels,0,$ishtml); - } - - -} -?> \ No newline at end of file diff --git a/lib/adodb/drivers/adodb-mysql.inc.php b/lib/adodb/drivers/adodb-mysql.inc.php deleted file mode 100644 index 4b215e54..00000000 --- a/lib/adodb/drivers/adodb-mysql.inc.php +++ /dev/null @@ -1,795 +0,0 @@ -rsPrefix .= 'ext_'; - } - - function ServerInfo() - { - $arr['description'] = ADOConnection::GetOne("select version()"); - $arr['version'] = ADOConnection::_findvers($arr['description']); - return $arr; - } - - function IfNull( $field, $ifNull ) - { - return " IFNULL($field, $ifNull) "; // if MySQL - } - - - function MetaTables($ttype=false,$showSchema=false,$mask=false) - { - $save = $this->metaTablesSQL; - if ($showSchema && is_string($showSchema)) { - $this->metaTablesSQL .= " from $showSchema"; - } - - if ($mask) { - $mask = $this->qstr($mask); - $this->metaTablesSQL .= " like $mask"; - } - $ret = ADOConnection::MetaTables($ttype,$showSchema); - - $this->metaTablesSQL = $save; - return $ret; - } - - - 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); - } - - // get index details - $rs = $this->Execute(sprintf('SHOW INDEX FROM %s',$table)); - - // restore fetchmode - if (isset($savem)) { - $this->SetFetchMode($savem); - } - $ADODB_FETCH_MODE = $save; - - if (!is_object($rs)) { - 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]; - } - - // sort columns by order in the index - foreach ( array_keys ($indexes) as $index ) - { - ksort ($indexes[$index]['columns']); - } - - return $indexes; - } - - - // if magic quotes disabled, use mysql_real_escape_string() - function qstr($s,$magic_quotes=false) - { - if (is_null($s)) return 'NULL'; - if (!$magic_quotes) { - - if (ADODB_PHPVER >= 0x4300) { - if (is_resource($this->_connectionID)) - return "'".mysql_real_escape_string($s,$this->_connectionID)."'"; - } - 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() - { - return ADOConnection::GetOne('SELECT LAST_INSERT_ID()'); - //return mysql_insert_id($this->_connectionID); - } - - function GetOne($sql,$inputarr=false) - { - global $ADODB_GETONE_EOF; - if ($this->compat323 == false && strncasecmp($sql,'sele',4) == 0) { - $rs = $this->SelectLimit($sql,1,-1,$inputarr); - if ($rs) { - $rs->Close(); - if ($rs->EOF) return $ADODB_GETONE_EOF; - return reset($rs->fields); - } - } else { - return ADOConnection::GetOne($sql,$inputarr); - } - return false; - } - - function BeginTrans() - { - if ($this->debug) ADOConnection::outp("Transactions not supported in 'mysql' driver. Use 'mysqlt' or 'mysqli' driver"); - } - - function _affectedrows() - { - return mysql_affected_rows($this->_connectionID); - } - - // 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 $_genSeqCountSQL = "select count(*) from %s"; - var $_genSeq2SQL = "insert into %s values (%s)"; - var $_dropSeqSQL = "drop table %s"; - - function CreateSequence($seqname='adodbseq',$startID=1) - { - if (empty($this->_genSeqSQL)) return false; - $u = strtoupper($seqname); - - $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname)); - if (!$ok) return false; - return $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1)); - } - - - function GenID($seqname='adodbseq',$startID=1) - { - // post-nuke sets hasGenID to false - if (!$this->hasGenID) return false; - - $savelog = $this->_logsql; - $this->_logsql = false; - $getnext = sprintf($this->_genIDSQL,$seqname); - $holdtransOK = $this->_transOK; // save the current status - $rs = @$this->Execute($getnext); - if (!$rs) { - if ($holdtransOK) $this->_transOK = true; //if the status was ok before reset - $u = strtoupper($seqname); - $this->Execute(sprintf($this->_genSeqSQL,$seqname)); - $cnt = $this->GetOne(sprintf($this->_genSeqCountSQL,$seqname)); - if (!$cnt) $this->Execute(sprintf($this->_genSeq2SQL,$seqname,$startID-1)); - $rs = $this->Execute($getnext); - } - - if ($rs) { - $this->genID = mysql_insert_id($this->_connectionID); - $rs->Close(); - } else - $this->genID = 0; - - $this->_logsql = $savelog; - return $this->genID; - } - - function MetaDatabases() - { - $qid = mysql_list_dbs($this->_connectionID); - $arr = array(); - $i = 0; - $max = mysql_num_rows($qid); - while ($i < $max) { - $db = mysql_tablename($qid,$i); - if ($db != 'mysql') $arr[] = $db; - $i += 1; - } - return $arr; - } - - - // Format date column in sql string given an input format that understands Y M D - 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; - } - - - // returns concatenated string - // much easier to run "mysqld --ansi" or "mysqld --sql-mode=PIPES_AS_CONCAT" and use || operator - function Concat() - { - $s = ""; - $arr = func_get_args(); - - // suggestion by andrew005@mnogo.ru - $s = implode(',',$arr); - if (strlen($s) > 0) return "CONCAT($s)"; - else return ''; - } - - function OffsetDate($dayFraction,$date=false) - { - if (!$date) $date = $this->sysDate; - - $fraction = $dayFraction * 24 * 3600; - return '('. $date . ' + INTERVAL ' . $fraction.' SECOND)'; - -// return "from_unixtime(unix_timestamp($date)+$fraction)"; - } - - // returns true or false - function _connect($argHostname, $argUsername, $argPassword, $argDatabasename) - { - if (!empty($this->port)) $argHostname .= ":".$this->port; - - if (ADODB_PHPVER >= 0x4300) - $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword, - $this->forceNewConnect,$this->clientFlags); - else if (ADODB_PHPVER >= 0x4200) - $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword, - $this->forceNewConnect); - else - $this->_connectionID = mysql_connect($argHostname,$argUsername,$argPassword); - - if ($this->_connectionID === false) return false; - if ($argDatabasename) return $this->SelectDB($argDatabasename); - return true; - } - - // returns true or false - function _pconnect($argHostname, $argUsername, $argPassword, $argDatabasename) - { - if (!empty($this->port)) $argHostname .= ":".$this->port; - - if (ADODB_PHPVER >= 0x4300) - $this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword,$this->clientFlags); - else - $this->_connectionID = mysql_pconnect($argHostname,$argUsername,$argPassword); - if ($this->_connectionID === false) return false; - if ($this->autoRollback) $this->RollbackTrans(); - if ($argDatabasename) return $this->SelectDB($argDatabasename); - return true; - } - - function _nconnect($argHostname, $argUsername, $argPassword, $argDatabasename) - { - $this->forceNewConnect = true; - return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabasename); - } - - function MetaColumns($table, $normalize=true) - { - $this->_findschema($table,$schema); - if ($schema) { - $dbName = $this->database; - $this->SelectDB($schema); - } - global $ADODB_FETCH_MODE; - $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 ($schema) { - $this->SelectDB($dbName); - } - - if (isset($savem)) $this->SetFetchMode($savem); - $ADODB_FETCH_MODE = $save; - if (!is_object($rs)) { - $false = false; - return $false; - } - - $retarr = array(); - while (!$rs->EOF){ - $fld = new ADOFieldObject(); - $fld->name = $rs->fields[0]; - $type = $rs->fields[1]; - - // split type into type(length): - $fld->scale = null; - 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)) { - $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)) { - $fld->type = $query_array[1]; - $arr = explode(",",$query_array[2]); - $fld->enums = $arr; - $zlen = max(array_map("strlen",$arr)) - 2; // PHP >= 4.0.6 - $fld->max_length = ($zlen > 0) ? $zlen : 1; - } else { - $fld->type = $type; - $fld->max_length = -1; - } - $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 || strpos($type,'binary') !== false); - $fld->unsigned = (strpos($type,'unsigned') !== false); - $fld->zerofill = (strpos($type,'zerofill') !== false); - - if (!$fld->binary) { - $d = $rs->fields[4]; - if ($d != '' && $d != 'NULL') { - $fld->has_default = true; - $fld->default_value = $d; - } else { - $fld->has_default = false; - } - } - - if ($save == ADODB_FETCH_NUM) { - $retarr[] = $fld; - } else { - $retarr[strtoupper($fld->name)] = $fld; - } - $rs->MoveNext(); - } - - $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 - if ($this->_connectionID) { - return @mysql_select_db($dbName,$this->_connectionID); - } - else return false; - } - - // parameters use PostgreSQL convention, not MySQL - function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs=0) - { - $offsetStr =($offset>=0) ? ((integer)$offset)."," : ''; - // jason judge, see http://phplens.com/lens/lensforum/msgs.php?id=9220 - if ($nrows < 0) $nrows = '18446744073709551615'; - - if ($secs) - $rs = $this->CacheExecute($secs,$sql." LIMIT $offsetStr".((integer)$nrows),$inputarr); - else - $rs = $this->Execute($sql." LIMIT $offsetStr".((integer)$nrows),$inputarr); - return $rs; - } - - // returns queryID or false - function _query($sql,$inputarr=false) - { - //global $ADODB_COUNTRECS; - //if($ADODB_COUNTRECS) - return mysql_query($sql,$this->_connectionID); - //else return @mysql_unbuffered_query($sql,$this->_connectionID); // requires PHP >= 4.0.6 - } - - /* Returns: the last error message from previous database operation */ - function ErrorMsg() - { - - if ($this->_logsql) return $this->_errorMsg; - if (empty($this->_connectionID)) $this->_errorMsg = @mysql_error(); - else $this->_errorMsg = @mysql_error($this->_connectionID); - return $this->_errorMsg; - } - - /* Returns: the last error number from previous database operation */ - function ErrorNo() - { - if ($this->_logsql) return $this->_errorCode; - if (empty($this->_connectionID)) return @mysql_errno(); - else return @mysql_errno($this->_connectionID); - } - - // returns true or false - function _close() - { - @mysql_close($this->_connectionID); - $this->_connectionID = false; - } - - - /* - * Maximum size of C field - */ - function CharMax() - { - return 255; - } - - /* - * Maximum size of X field - */ - function TextMax() - { - return 4294967295; - } - - // "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]; - - $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 ( $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]}"; - } - } - } - - return $foreign_keys; - } - - -} - -/*-------------------------------------------------------------------------------------- - Class Name: Recordset ---------------------------------------------------------------------------------------*/ - - -class ADORecordSet_mysql extends ADORecordSet{ - - var $databaseType = "mysql"; - var $canSeek = true; - - function ADORecordSet_mysql($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); - } - - function _initrs() - { - //GLOBAL $ADODB_COUNTRECS; - // $this->_numOfRows = ($ADODB_COUNTRECS) ? @mysql_num_rows($this->_queryID):-1; - $this->_numOfRows = @mysql_num_rows($this->_queryID); - $this->_numOfFields = @mysql_num_fields($this->_queryID); - } - - function FetchField($fieldOffset = -1) - { - if ($fieldOffset != -1) { - $o = @mysql_fetch_field($this->_queryID, $fieldOffset); - $f = @mysql_field_flags($this->_queryID,$fieldOffset); - if ($o) $o->max_length = @mysql_field_len($this->_queryID,$fieldOffset); // suggested by: Jim Nicholson (jnich#att.com) - //$o->max_length = -1; // mysql returns the max length less spaces -- so it is unrealiable - if ($o) $o->binary = (strpos($f,'binary')!== false); - } - else if ($fieldOffset == -1) { /* 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 - } - - return $o; - } - - function GetRowAssoc($upper=true) - { - if ($this->fetchMode == MYSQL_ASSOC && !$upper) $row = $this->fields; - else $row = ADORecordSet::GetRowAssoc($upper); - return $row; - } - - /* Use associative array to get fields array */ - function Fields($colname) - { - // added @ by "Michael William Miller" - if ($this->fetchMode != MYSQL_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; - return @mysql_data_seek($this->_queryID,$row); - } - - function MoveNext() - { - //return adodb_movenext($this); - //if (defined('ADODB_EXTENSION')) return adodb_movenext($this); - if (@$this->fields = mysql_fetch_array($this->_queryID,$this->fetchMode)) { - $this->_currentRow += 1; - return true; - } - if (!$this->EOF) { - $this->_currentRow += 1; - $this->EOF = true; - } - return false; - } - - function _fetch() - { - $this->fields = @mysql_fetch_array($this->_queryID,$this->fetchMode); - return is_array($this->fields); - } - - function _close() { - @mysql_free_result($this->_queryID); - $this->_queryID = false; - } - - function MetaType($t,$len=-1,$fieldobj=false) - { - if (is_object($t)) { - $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': - if ($len <= $this->blobSize) return 'C'; - - case 'TEXT': - case 'LONGTEXT': - case 'MEDIUMTEXT': - return 'X'; - - // php_mysql extension always returns 'blob' even if 'text' - // so we have to check whether binary... - case 'IMAGE': - case 'LONGBLOB': - case 'BLOB': - case 'MEDIUMBLOB': - case 'BINARY': - return !empty($fieldobj->binary) ? 'B' : 'X'; - - case 'YEAR': - case 'DATE': return 'D'; - - case 'TIME': - case 'DATETIME': - case 'TIMESTAMP': return 'T'; - - case 'INT': - case 'INTEGER': - case 'BIGINT': - case 'TINYINT': - case 'MEDIUMINT': - case 'SMALLINT': - - if (!empty($fieldobj->primary_key)) return 'R'; - else return 'I'; - - default: return 'N'; - } - } - -} - -class ADORecordSet_ext_mysql extends ADORecordSet_mysql { - function ADORecordSet_ext_mysql($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); - } - - function MoveNext() - { - return @adodb_movenext($this); - } -} - - -} -?> \ No newline at end of file diff --git a/lib/adodb/drivers/adodb-postgres.inc.php b/lib/adodb/drivers/adodb-postgres.inc.php deleted file mode 100644 index 6f580ff6..00000000 --- a/lib/adodb/drivers/adodb-postgres.inc.php +++ /dev/null @@ -1,14 +0,0 @@ - \ No newline at end of file diff --git a/lib/adodb/drivers/adodb-postgres64.inc.php b/lib/adodb/drivers/adodb-postgres64.inc.php deleted file mode 100644 index 8258149c..00000000 --- a/lib/adodb/drivers/adodb-postgres64.inc.php +++ /dev/null @@ -1,1071 +0,0 @@ - - jlim - changed concat operator to || and data types to MetaType to match documented pgsql types - see http://www.postgresql.org/devel-corner/docs/postgres/datatype.htm - 22 Nov 2000 jlim - added changes to FetchField() and MetaTables() contributed by "raser" - 27 Nov 2000 jlim - added changes to _connect/_pconnect from ideas by "Lennie" - 15 Dec 2000 jlim - added changes suggested by Additional code changes by "Eric G. Werk" egw@netguide.dk. - 31 Jan 2002 jlim - finally installed postgresql. testing - 01 Mar 2001 jlim - Freek Dijkstra changes, also support for text type - - See http://www.varlena.com/varlena/GeneralBits/47.php - - -- What indexes are on my table? - select * from pg_indexes where tablename = 'tablename'; - - -- What triggers are on my table? - select c.relname as "Table", t.tgname as "Trigger Name", - t.tgconstrname as "Constraint Name", t.tgenabled as "Enabled", - t.tgisconstraint as "Is Constraint", cc.relname as "Referenced Table", - p.proname as "Function Name" - from pg_trigger t, pg_class c, pg_class cc, pg_proc p - where t.tgfoid = p.oid and t.tgrelid = c.oid - and t.tgconstrrelid = cc.oid - and c.relname = 'tablename'; - - -- What constraints are on my table? - select r.relname as "Table", c.conname as "Constraint Name", - contype as "Constraint Type", conkey as "Key Columns", - confkey as "Foreign Columns", consrc as "Source" - from pg_class r, pg_constraint c - where r.oid = c.conrelid - and relname = 'tablename'; - -*/ - -// security - hide paths -if (!defined('ADODB_DIR')) die(); - -function adodb_addslashes($s) -{ - $len = strlen($s); - if ($len == 0) return "''"; - if (strncmp($s,"'",1) === 0 && substr($s,$len-1) == "'") return $s; // already quoted - - return "'".addslashes($s)."'"; -} - -class ADODB_postgres64 extends ADOConnection{ - var $databaseType = 'postgres64'; - var $dataProvider = 'postgres'; - var $hasInsertID = true; - var $_resultid = false; - var $concat_operator='||'; - var $metaDatabasesSQL = "select datname from pg_database where datname not in ('template0','template1') order by 1"; - var $metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%' - and tablename not in ('sql_features', 'sql_implementation_info', 'sql_languages', - 'sql_packages', 'sql_sizing', 'sql_sizing_profiles') - union - select viewname,'V' from pg_views where viewname not like 'pg\_%'"; - //"select tablename from pg_tables where tablename not like 'pg_%' order by 1"; - var $isoDates = true; // accepts dates in ISO format - var $sysDate = "CURRENT_DATE"; - var $sysTimeStamp = "CURRENT_TIMESTAMP"; - var $blobEncodeType = 'C'; - var $metaColumnsSQL = "SELECT a.attname,t.typname,a.attlen,a.atttypmod,a.attnotnull,a.atthasdef,a.attnum - FROM pg_class c, pg_attribute a,pg_type t - WHERE relkind in ('r','v') AND (c.relname='%s' or c.relname = lower('%s')) and a.attname not like '....%%' -AND a.attnum > 0 AND a.atttypid = t.oid AND a.attrelid = c.oid ORDER BY a.attnum"; - - // used when schema defined - var $metaColumnsSQL1 = "SELECT a.attname, t.typname, a.attlen, a.atttypmod, a.attnotnull, a.atthasdef, a.attnum -FROM pg_class c, pg_attribute a, pg_type t, pg_namespace n -WHERE 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"; - - // get primary key etc -- from Freek Dijkstra - var $metaKeySQL = "SELECT ic.relname AS index_name, a.attname AS column_name,i.indisunique AS unique_key, i.indisprimary AS primary_key - FROM pg_class bc, pg_class ic, pg_index i, pg_attribute a WHERE bc.oid = i.indrelid AND ic.oid = i.indexrelid AND (i.indkey[0] = a.attnum OR i.indkey[1] = a.attnum OR i.indkey[2] = a.attnum OR i.indkey[3] = a.attnum OR i.indkey[4] = a.attnum OR i.indkey[5] = a.attnum OR i.indkey[6] = a.attnum OR i.indkey[7] = a.attnum) AND a.attrelid = bc.oid AND bc.relname = '%s'"; - - var $hasAffectedRows = true; - var $hasLimit = false; // set to true for pgsql 7 only. support pgsql/mysql SELECT * FROM TABLE LIMIT 10 - // below suggested by Freek Dijkstra - var $true = 'TRUE'; // string that represents TRUE for a database - var $false = 'FALSE'; // string that represents FALSE for a database - 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'"; // used by DBTimeStamp as the default timestamp fmt. - var $hasMoveFirst = true; - var $hasGenID = true; - var $_genIDSQL = "SELECT NEXTVAL('%s')"; - var $_genSeqSQL = "CREATE SEQUENCE %s START %s"; - var $_dropSeqSQL = "DROP SEQUENCE %s"; - var $metaDefaultsSQL = "SELECT d.adnum as num, d.adsrc as def from pg_attrdef d, pg_class c where d.adrelid=c.oid and c.relname='%s' order by d.adnum"; - var $random = 'random()'; /// random function - var $autoRollback = true; // apparently pgsql does not autorollback properly before php 4.3.4 - // http://bugs.php.net/bug.php?id=25404 - - var $uniqueIisR = true; - var $_bindInputArray = false; // requires postgresql 7.3+ and ability to modify database - var $disableBlobs = false; // set to true to disable blob checking, resulting in 2-5% improvement in performance. - - // The last (fmtTimeStamp is not entirely correct: - // PostgreSQL also has support for time zones, - // and writes these time in this format: "2001-03-01 18:59:26+02". - // There is no code for the "+02" time zone information, so I just left that out. - // I'm not familiar enough with both ADODB as well as Postgres - // to know what the concequences are. The other values are correct (wheren't in 0.94) - // -- Freek Dijkstra - - function ADODB_postgres64() - { - // changes the metaColumnsSQL, adds columns: attnum[6] - } - - function ServerInfo() - { - if (isset($this->version)) return $this->version; - - $arr['description'] = $this->GetOne("select version()"); - $arr['version'] = ADOConnection::_findvers($arr['description']); - $this->version = $arr; - return $arr; - } - - function IfNull( $field, $ifNull ) - { - return " coalesce($field, $ifNull) "; - } - - // get the last id - never tested - function pg_insert_id($tablename,$fieldname) - { - $result=pg_exec($this->_connectionID, "SELECT last_value FROM ${tablename}_${fieldname}_seq"); - if ($result) { - $arr = @pg_fetch_row($result,0); - pg_freeresult($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. */ - function _insertid($table,$column) - { - if (!is_resource($this->_resultid) || get_resource_type($this->_resultid) !== 'pgsql result') return false; - $oid = pg_getlastoid($this->_resultid); - // to really return the id, we need the table and column-name, else we can only return the oid != id - 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); - } - - - // returns true/false - function BeginTrans() - { - if ($this->transOff) return true; - $this->transCnt += 1; - return @pg_Exec($this->_connectionID, "begin ".$this->_transmode); - } - - function RowLock($tables,$where,$col='1 as adodbignore') - { - if (!$this->transCnt) $this->BeginTrans(); - return $this->GetOne("select $col from $tables where $where for update"); - } - - // returns true/false. - function CommitTrans($ok=true) - { - if ($this->transOff) return true; - if (!$ok) return $this->RollbackTrans(); - - $this->transCnt -= 1; - return @pg_Exec($this->_connectionID, "commit"); - } - - // returns true/false - function RollbackTrans() - { - if ($this->transOff) return true; - $this->transCnt -= 1; - return @pg_Exec($this->_connectionID, "rollback"); - } - - function MetaTables($ttype=false,$showSchema=false,$mask=false) - { - $info = $this->ServerInfo(); - if ($info['version'] >= 7.3) { - $this->metaTablesSQL = "select tablename,'T' from pg_tables where tablename not like 'pg\_%' - and schemaname not in ( 'pg_catalog','information_schema') - union - select viewname,'V' from pg_views where viewname not like 'pg\_%' and schemaname not in ( 'pg_catalog','information_schema') "; - } - if ($mask) { - $save = $this->metaTablesSQL; - $mask = $this->qstr(strtolower($mask)); - if ($info['version']>=7.3) - $this->metaTablesSQL = " -select tablename,'T' from pg_tables where tablename like $mask and schemaname not in ( 'pg_catalog','information_schema') - union -select viewname,'V' from pg_views where viewname like $mask and schemaname not in ( 'pg_catalog','information_schema') "; - else - $this->metaTablesSQL = " -select tablename,'T' from pg_tables where tablename like $mask - union -select viewname,'V' from pg_views where viewname like $mask"; - } - $ret = ADOConnection::MetaTables($ttype,$showSchema); - - if ($mask) { - $this->metaTablesSQL = $save; - } - return $ret; - } - - - // if magic quotes disabled, use pg_escape_string() - function qstr($s,$magic_quotes=false) - { - if (is_bool($s)) return $s ? 'true' : 'false'; - - if (!$magic_quotes) { - if (ADODB_PHPVER >= 0x5200) { - return "'".pg_escape_string($this->_connectionID,$s)."'"; - } - if (ADODB_PHPVER >= 0x4200) { - return "'".pg_escape_string($s)."'"; - } - if ($this->replaceQuote[0] == '\\'){ - $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\\000"),$s); - } - return "'".str_replace("'",$this->replaceQuote,$s)."'"; - } - - // undo magic quotes for " - $s = str_replace('\\"','"',$s); - return "'$s'"; - } - - - - // Format date column in sql string given an input format that understands Y M D - function SQLDate($fmt, $col=false) - { - if (!$col) $col = $this->sysTimeStamp; - $s = 'TO_CHAR('.$col.",'"; - - $len = strlen($fmt); - for ($i=0; $i < $len; $i++) { - $ch = $fmt[$i]; - switch($ch) { - case 'Y': - case 'y': - $s .= 'YYYY'; - break; - case 'Q': - case 'q': - $s .= 'Q'; - break; - - case 'M': - $s .= 'Mon'; - break; - - case 'm': - $s .= 'MM'; - break; - case 'D': - case 'd': - $s .= 'DD'; - break; - - case 'H': - $s.= 'HH24'; - break; - - case 'h': - $s .= 'HH'; - break; - - case 'i': - $s .= 'MI'; - break; - - case 's': - $s .= 'SS'; - break; - - case 'a': - case 'A': - $s .= 'AM'; - break; - - case 'w': - $s .= 'D'; - break; - - case 'l': - $s .= 'DAY'; - break; - - case 'W': - $s .= 'WW'; - break; - - default: - // handle escape characters... - if ($ch == '\\') { - $i++; - $ch = substr($fmt,$i,1); - } - if (strpos('-/.:;, ',$ch) !== false) $s .= $ch; - else $s .= '"'.$ch.'"'; - - } - } - return $s. "')"; - } - - - - /* - * Load a Large Object from a file - * - the procedure stores the object id in the table and imports the object using - * postgres proprietary blob handling routines - * - * contributed by Mattia Rossi mattia@technologist.com - * modified for safe mode by juraj chlebec - */ - function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB') - { - pg_exec ($this->_connectionID, "begin"); - - $fd = fopen($path,'r'); - $contents = fread($fd,filesize($path)); - fclose($fd); - - $oid = pg_lo_create($this->_connectionID); - $handle = pg_lo_open($this->_connectionID, $oid, 'w'); - pg_lo_write($handle, $contents); - pg_lo_close($handle); - - // $oid = pg_lo_import ($path); - pg_exec($this->_connectionID, "commit"); - $rs = ADOConnection::UpdateBlob($table,$column,$oid,$where,$blobtype); - $rez = !empty($rs); - return $rez; - } - - /* - * Deletes/Unlinks a Blob from the database, otherwise it - * will be left behind - * - * Returns TRUE on success or FALSE on failure. - * - * contributed by Todd Rogers todd#windfox.net - */ - function BlobDelete( $blob ) - { - pg_exec ($this->_connectionID, "begin"); - $result = @pg_lo_unlink($blob); - pg_exec ($this->_connectionID, "commit"); - return( $result ); - } - - /* - Hueristic - not guaranteed to work. - */ - function GuessOID($oid) - { - if (strlen($oid)>16) return false; - return is_numeric($oid); - } - - /* - * If an OID is detected, then we use pg_lo_* to open the oid file and read the - * real blob from the db using the oid supplied as a parameter. If you are storing - * blobs using bytea, we autodetect and process it so this function is not needed. - * - * contributed by Mattia Rossi mattia@technologist.com - * - * see http://www.postgresql.org/idocs/index.php?largeobjects.html - * - * Since adodb 4.54, this returns the blob, instead of sending it to stdout. Also - * added maxsize parameter, which defaults to $db->maxblobsize if not defined. - */ - function BlobDecode($blob,$maxsize=false,$hastrans=true) - { - if (!$this->GuessOID($blob)) return $blob; - - if ($hastrans) @pg_exec($this->_connectionID,"begin"); - $fd = @pg_lo_open($this->_connectionID,$blob,"r"); - if ($fd === false) { - if ($hastrans) @pg_exec($this->_connectionID,"commit"); - return $blob; - } - if (!$maxsize) $maxsize = $this->maxblobsize; - $realblob = @pg_loread($fd,$maxsize); - @pg_loclose($fd); - if ($hastrans) @pg_exec($this->_connectionID,"commit"); - return $realblob; - } - - /* - See http://www.postgresql.org/idocs/index.php?datatype-binary.html - - NOTE: SQL string literals (input strings) must be preceded with two backslashes - due to the fact that they must pass through two parsers in the PostgreSQL - backend. - */ - function BlobEncode($blob) - { - if (ADODB_PHPVER >= 0x5200) return pg_escape_bytea($this->_connectionID, $blob); - if (ADODB_PHPVER >= 0x4200) return pg_escape_bytea($blob); - - /*92=backslash, 0=null, 39=single-quote*/ - $badch = array(chr(92),chr(0),chr(39)); # \ null ' - $fixch = array('\\\\134','\\\\000','\\\\047'); - return adodb_str_replace($badch,$fixch,$blob); - - // note that there is a pg_escape_bytea function only for php 4.2.0 or later - } - - // assumes bytea for blob, and varchar for clob - function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB') - { - - if ($blobtype == 'CLOB') { - return $this->Execute("UPDATE $table SET $column=" . $this->qstr($val) . " WHERE $where"); - } - // do not use bind params which uses qstr(), as blobencode() already quotes data - return $this->Execute("UPDATE $table SET $column='".$this->BlobEncode($val)."'::bytea WHERE $where"); - } - - function OffsetDate($dayFraction,$date=false) - { - if (!$date) $date = $this->sysDate; - else if (strncmp($date,"'",1) == 0) { - $len = strlen($date); - if (10 <= $len && $len <= 12) $date = 'date '.$date; - else $date = 'timestamp '.$date; - } - - - return "($date+interval'".($dayFraction * 1440)." minutes')"; - #return "($date+interval'$dayFraction days')"; - } - - - // 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; - - $schema = false; - $false = false; - $this->_findschema($table,$schema); - - if ($normalize) $table = strtolower($table); - - $save = $ADODB_FETCH_MODE; - $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)); - if (isset($savem)) $this->SetFetchMode($savem); - $ADODB_FETCH_MODE = $save; - - if ($rs === false) { - return $false; - } - if (!empty($this->metaKeySQL)) { - // If we want the primary keys, we have to issue a separate query - // Of course, a modified version of the metaColumnsSQL query using a - // LEFT JOIN would have been much more elegant, but postgres does - // not support OUTER JOINS. So here is the clumsy way. - - $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; - - $rskey = $this->Execute(sprintf($this->metaKeySQL,($table))); - // fetch all result in once for performance. - $keys = $rskey->GetArray(); - if (isset($savem)) $this->SetFetchMode($savem); - $ADODB_FETCH_MODE = $save; - - $rskey->Close(); - unset($rskey); - } - - $rsdefa = array(); - if (!empty($this->metaDefaultsSQL)) { - $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC; - $sql = sprintf($this->metaDefaultsSQL, ($table)); - $rsdef = $this->Execute($sql); - if (isset($savem)) $this->SetFetchMode($savem); - $ADODB_FETCH_MODE = $save; - - if ($rsdef) { - while (!$rsdef->EOF) { - $num = $rsdef->fields['num']; - $s = $rsdef->fields['def']; - if (strpos($s,'::')===false && substr($s, 0, 1) == "'") { /* quoted strings hack... for now... fixme */ - $s = substr($s, 1); - $s = substr($s, 0, strlen($s) - 1); - } - - $rsdefa[$num] = $s; - $rsdef->MoveNext(); - } - } else { - ADOConnection::outp( "==> SQL => " . $sql); - } - unset($rsdef); - } - - $retarr = array(); - while (!$rs->EOF) { - $fld = new ADOFieldObject(); - $fld->name = $rs->fields[0]; - $fld->type = $rs->fields[1]; - $fld->max_length = $rs->fields[2]; - $fld->attnum = $rs->fields[6]; - - if ($fld->max_length <= 0) $fld->max_length = $rs->fields[3]-4; - if ($fld->max_length <= 0) $fld->max_length = -1; - if ($fld->type == 'numeric') { - $fld->scale = $fld->max_length & 0xFFFF; - $fld->max_length >>= 16; - } - // dannym - // 5 hasdefault; 6 num-of-column - $fld->has_default = ($rs->fields[5] == 't'); - if ($fld->has_default) { - $fld->default_value = $rsdefa[$rs->fields[6]]; - } - - //Freek - $fld->not_null = $rs->fields[4] == 't'; - - - // Freek - if (is_array($keys)) { - foreach($keys as $key) { - if ($fld->name == $key['column_name'] AND $key['primary_key'] == 't') - $fld->primary_key = true; - if ($fld->name == $key['column_name'] AND $key['unique_key'] == 't') - $fld->unique = true; // What name is more compatible? - } - } - - if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld; - else $retarr[($normalize) ? strtoupper($fld->name) : $fld->name] = $fld; - - $rs->MoveNext(); - } - $rs->Close(); - if (empty($retarr)) - return $false; - else - return $retarr; - - } - - function MetaIndexes ($table, $primary = FALSE, $owner = false) - { - global $ADODB_FETCH_MODE; - - $schema = false; - $this->_findschema($table,$schema); - - if ($schema) { // requires pgsql 7.3+ - pg_namespace used. - $sql = ' -SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns" -FROM pg_catalog.pg_class c -JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid -JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid - ,pg_namespace n -WHERE (c2.relname=\'%s\' or c2.relname=lower(\'%s\')) and c.relnamespace=c2.relnamespace and c.relnamespace=n.oid and n.nspname=\'%s\''; - } else { - $sql = ' -SELECT c.relname as "Name", i.indisunique as "Unique", i.indkey as "Columns" -FROM pg_catalog.pg_class c -JOIN pg_catalog.pg_index i ON i.indexrelid=c.oid -JOIN pg_catalog.pg_class c2 ON c2.oid=i.indrelid -WHERE (c2.relname=\'%s\' or c2.relname=lower(\'%s\'))'; - } - - if ($primary == FALSE) { - $sql .= ' AND i.indisprimary=false;'; - } - - $save = $ADODB_FETCH_MODE; - $ADODB_FETCH_MODE = ADODB_FETCH_NUM; - if ($this->fetchMode !== FALSE) { - $savem = $this->SetFetchMode(FALSE); - } - - $rs = $this->Execute(sprintf($sql,$table,$table,$schema)); - if (isset($savem)) { - $this->SetFetchMode($savem); - } - $ADODB_FETCH_MODE = $save; - - if (!is_object($rs)) { - $false = false; - return $false; - } - - $col_names = $this->MetaColumnNames($table,true,true); - //3rd param is use attnum, - // see http://sourceforge.net/tracker/index.php?func=detail&aid=1451245&group_id=42718&atid=433976 - $indexes = array(); - while ($row = $rs->FetchRow()) { - $columns = array(); - foreach (explode(' ', $row[2]) as $col) { - $columns[] = $col_names[$col]; - } - - $indexes[$row[0]] = array( - 'unique' => ($row[1] == 't'), - 'columns' => $columns - ); - } - return $indexes; - } - - // returns true or false - // - // examples: - // $db->Connect("host=host1 user=user1 password=secret port=4341"); - // $db->Connect('host1','user1','secret'); - function _connect($str,$user='',$pwd='',$db='',$ctype=0) - { - - if (!function_exists('pg_connect')) return null; - - $this->_errorMsg = false; - - if ($user || $pwd || $db) { - $user = adodb_addslashes($user); - $pwd = adodb_addslashes($pwd); - if (strlen($db) == 0) $db = 'template1'; - $db = adodb_addslashes($db); - if ($str) { - $host = explode(":", $str); - if ($host[0]) $str = "host=".adodb_addslashes($host[0]); - else $str = ''; - if (isset($host[1])) $str .= " port=$host[1]"; - else if (!empty($this->port)) $str .= " port=".$this->port; - } - if ($user) $str .= " user=".$user; - if ($pwd) $str .= " password=".$pwd; - if ($db) $str .= " dbname=".$db; - } - - //if ($user) $linea = "user=$user host=$linea password=$pwd dbname=$db port=5432"; - - if ($ctype === 1) { // persistent - $this->_connectionID = pg_pconnect($str); - } else { - if ($ctype === -1) { // nconnect, we trick pgsql ext by changing the connection str - static $ncnt; - - if (empty($ncnt)) $ncnt = 1; - else $ncnt += 1; - - $str .= str_repeat(' ',$ncnt); - } - $this->_connectionID = pg_connect($str); - } - if ($this->_connectionID === false) return false; - $this->Execute("set datestyle='ISO'"); - - $info = $this->ServerInfo(); - $this->pgVersion = (float) substr($info['version'],0,3); - if ($this->pgVersion >= 7.1) { // good till version 999 - $this->_nestedSQL = true; - } - return true; - } - - function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName) - { - return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName,-1); - } - - // returns true or false - // - // examples: - // $db->PConnect("host=host1 user=user1 password=secret port=4341"); - // $db->PConnect('host1','user1','secret'); - function _pconnect($str,$user='',$pwd='',$db='') - { - return $this->_connect($str,$user,$pwd,$db,1); - } - - - // returns queryID or false - function _query($sql,$inputarr=false) - { - $this->_errorMsg = false; - if ($inputarr) { - /* - It appears that PREPARE/EXECUTE is slower for many queries. - - For query executed 1000 times: - "select id,firstname,lastname from adoxyz - where firstname not like ? and lastname not like ? and id = ?" - - with plan = 1.51861286163 secs - no plan = 1.26903700829 secs - - - - */ - $plan = 'P'.md5($sql); - - $execp = ''; - foreach($inputarr as $v) { - if ($execp) $execp .= ','; - if (is_string($v)) { - if (strncmp($v,"'",1) !== 0) $execp .= $this->qstr($v); - } else { - $execp .= $v; - } - } - - if ($execp) $exsql = "EXECUTE $plan ($execp)"; - else $exsql = "EXECUTE $plan"; - - - $rez = @pg_exec($this->_connectionID,$exsql); - if (!$rez) { - # Perhaps plan does not exist? Prepare/compile plan. - $params = ''; - foreach($inputarr as $v) { - if ($params) $params .= ','; - if (is_string($v)) { - $params .= 'VARCHAR'; - } else if (is_integer($v)) { - $params .= 'INTEGER'; - } else { - $params .= "REAL"; - } - } - $sqlarr = explode('?',$sql); - //print_r($sqlarr); - $sql = ''; - $i = 1; - foreach($sqlarr as $v) { - $sql .= $v.' $'.$i; - $i++; - } - $s = "PREPARE $plan ($params) AS ".substr($sql,0,strlen($sql)-2); - //adodb_pr($s); - $rez = pg_exec($this->_connectionID,$s); - //echo $this->ErrorMsg(); - } - if ($rez) - $rez = pg_exec($this->_connectionID,$exsql); - } else { - //adodb_backtrace(); - $rez = pg_exec($this->_connectionID,$sql); - } - // check if no data returned, then no need to create real recordset - if ($rez && pg_numfields($rez) <= 0) { - if (is_resource($this->_resultid) && get_resource_type($this->_resultid) === 'pgsql result') { - pg_freeresult($this->_resultid); - } - $this->_resultid = $rez; - return true; - } - - return $rez; - } - - function _errconnect() - { - if (defined('DB_ERROR_CONNECT_FAILED')) return DB_ERROR_CONNECT_FAILED; - else return 'Database connection failed'; - } - - /* Returns: the last error message from previous database operation */ - function ErrorMsg() - { - if ($this->_errorMsg !== false) return $this->_errorMsg; - if (ADODB_PHPVER >= 0x4300) { - if (!empty($this->_resultid)) { - $this->_errorMsg = @pg_result_error($this->_resultid); - if ($this->_errorMsg) return $this->_errorMsg; - } - - if (!empty($this->_connectionID)) { - $this->_errorMsg = @pg_last_error($this->_connectionID); - } else $this->_errorMsg = $this->_errconnect(); - } else { - if (empty($this->_connectionID)) $this->_errconnect(); - else $this->_errorMsg = @pg_errormessage($this->_connectionID); - } - return $this->_errorMsg; - } - - function ErrorNo() - { - $e = $this->ErrorMsg(); - if (strlen($e)) { - return ADOConnection::MetaError($e); - } - return 0; - } - - // returns true or false - function _close() - { - if ($this->transCnt) $this->RollbackTrans(); - if ($this->_resultid) { - @pg_freeresult($this->_resultid); - $this->_resultid = false; - } - @pg_close($this->_connectionID); - $this->_connectionID = false; - return true; - } - - - /* - * Maximum size of C field - */ - function CharMax() - { - return 1000000000; // should be 1 Gb? - } - - /* - * Maximum size of X field - */ - function TextMax() - { - return 1000000000; // should be 1 Gb? - } - - -} - -/*-------------------------------------------------------------------------------------- - Class Name: Recordset ---------------------------------------------------------------------------------------*/ - -class ADORecordSet_postgres64 extends ADORecordSet{ - var $_blobArr; - var $databaseType = "postgres64"; - var $canSeek = true; - function ADORecordSet_postgres64($queryID,$mode=false) - { - if ($mode === false) { - global $ADODB_FETCH_MODE; - $mode = $ADODB_FETCH_MODE; - } - switch ($mode) - { - case ADODB_FETCH_NUM: $this->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); - } - - function GetRowAssoc($upper=true) - { - if ($this->fetchMode == PGSQL_ASSOC && !$upper) return $this->fields; - $row = ADORecordSet::GetRowAssoc($upper); - return $row; - } - - function _initrs() - { - global $ADODB_COUNTRECS; - $qid = $this->_queryID; - $this->_numOfRows = ($ADODB_COUNTRECS)? @pg_numrows($qid):-1; - $this->_numOfFields = @pg_numfields($qid); - - // cache types for blob decode check - // apparently pg_fieldtype 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); - } - } - } - - /* Use associative array to get fields array */ - function Fields($colname) - { - if ($this->fetchMode != PGSQL_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 FetchField($off = 0) - { - // offsets begin at 0 - - $o= new ADOFieldObject(); - $o->name = @pg_fieldname($this->_queryID,$off); - $o->type = @pg_fieldtype($this->_queryID,$off); - $o->max_length = @pg_fieldsize($this->_queryID,$off); - return $o; - } - - function _seek($row) - { - return @pg_fetch_row($this->_queryID,$row); - } - - function _decode($blob) - { - if ($blob === NULL) return NULL; - eval('$realblob="'.adodb_str_replace(array('"','$'),array('\"','\$'),$blob).'";'); - return $realblob; - } - - function _fixblobs() - { - if ($this->fetchMode == PGSQL_NUM || $this->fetchMode == PGSQL_BOTH) { - foreach($this->_blobArr as $k => $v) { - $this->fields[$k] = ADORecordSet_postgres64::_decode($this->fields[$k]); - } - } - if ($this->fetchMode == PGSQL_ASSOC || $this->fetchMode == PGSQL_BOTH) { - foreach($this->_blobArr as $k => $v) { - $this->fields[$v] = ADORecordSet_postgres64::_decode($this->fields[$v]); - } - } - } - - // 10% speedup to move MoveNext to child class - function MoveNext() - { - if (!$this->EOF) { - $this->_currentRow++; - if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) { - $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode); - if (is_array($this->fields) && $this->fields) { - if (isset($this->_blobArr)) $this->_fixblobs(); - return true; - } - } - $this->fields = false; - $this->EOF = true; - } - return false; - } - - function _fetch() - { - - if ($this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0) - return false; - - $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode); - - if ($this->fields && isset($this->_blobArr)) $this->_fixblobs(); - - return (is_array($this->fields)); - } - - function _close() - { - return @pg_freeresult($this->_queryID); - } - - function MetaType($t,$len=-1,$fieldobj=false) - { - if (is_object($t)) { - $fieldobj = $t; - $t = $fieldobj->type; - $len = $fieldobj->max_length; - } - switch (strtoupper($t)) { - case 'MONEY': // stupid, postgres expects money to be a string - case 'INTERVAL': - case 'CHAR': - case 'CHARACTER': - case 'VARCHAR': - case 'NAME': - case 'BPCHAR': - case '_VARCHAR': - case 'INET': - case 'MACADDR': - if ($len <= $this->blobSize) return 'C'; - - case 'TEXT': - return 'X'; - - case 'IMAGE': // user defined type - case 'BLOB': // user defined type - case 'BIT': // This is a bit string, not a single bit, so don't return 'L' - case 'VARBIT': - case 'BYTEA': - return 'B'; - - case 'BOOL': - case 'BOOLEAN': - return 'L'; - - case 'DATE': - return 'D'; - - - case 'TIMESTAMP WITHOUT TIME ZONE': - case 'TIME': - case 'DATETIME': - case 'TIMESTAMP': - case 'TIMESTAMPTZ': - return 'T'; - - case 'SMALLINT': - case 'BIGINT': - case 'INTEGER': - case 'INT8': - case 'INT4': - case 'INT2': - if (isset($fieldobj) && - empty($fieldobj->primary_key) && (!$this->connection->uniqueIisR || empty($fieldobj->unique))) return 'I'; - - case 'OID': - case 'SERIAL': - return 'R'; - - default: - return 'N'; - } - } - -} -?> \ No newline at end of file diff --git a/lib/adodb/drivers/adodb-postgres7.inc.php b/lib/adodb/drivers/adodb-postgres7.inc.php deleted file mode 100644 index eecfdc37..00000000 --- a/lib/adodb/drivers/adodb-postgres7.inc.php +++ /dev/null @@ -1,313 +0,0 @@ -ADODB_postgres64(); - if (ADODB_ASSOC_CASE !== 2) { - $this->rsPrefix .= 'assoc_'; - } - $this->_bindInputArray = PHP_VERSION >= 5.1; - } - - - // 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); - - return $rs; - } - /* - function Prepare($sql) - { - $info = $this->ServerInfo(); - if ($info['version']>=7.3) { - return array($sql,false); - } - 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] - */ - 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; - - } - - // from Edward Jaramilla, improved version - works on pg 7.4 - function _old_MetaForeignKeys($table, $owner=false, $upper=false) - { - $sql = 'SELECT t.tgargs as args - FROM - pg_trigger t,pg_class c,pg_proc p - WHERE - t.tgenabled AND - t.tgrelid = c.oid AND - t.tgfoid = p.oid AND - p.proname = \'RI_FKey_check_ins\' AND - c.relname = \''.strtolower($table).'\' - ORDER BY - t.tgrelid'; - - $rs = $this->Execute($sql); - - if (!$rs || $rs->EOF) return false; - - $arr = $rs->GetArray(); - $a = array(); - foreach($arr as $v) { - $data = explode(chr(0), $v['args']); - $size = count($data)-1; //-1 because the last node is empty - for($i = 4; $i < $size; $i++) { - if ($upper) - $a[strtoupper($data[2])][] = strtoupper($data[$i].'='.$data[++$i]); - else - $a[$data[2]][] = $data[$i].'='.$data[++$i]; - } - } - return $a; - } - - function _query($sql,$inputarr=false) - { - if (! $this->_bindInputArray) { - // We don't have native support for parameterized queries, so let's emulate it at the parent - return ADODB_postgres64::_query($sql, $inputarr); - } - $this->_errorMsg = false; - // -- added Cristiano da Cunha Duarte - if ($inputarr) { - $sqlarr = explode('?',trim($sql)); - $sql = ''; - $i = 1; - $last = sizeof($sqlarr)-1; - foreach($sqlarr as $v) { - if ($last < $i) $sql .= $v; - else $sql .= $v.' $'.$i; - $i++; - } - - $rez = pg_query_params($this->_connectionID,$sql, $inputarr); - } else { - $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 (is_resource($this->_resultid) && get_resource_type($this->_resultid) === 'pgsql result') { - pg_freeresult($this->_resultid); - } - $this->_resultid = $rez; - return true; - } - return $rez; - } - - // 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 - // the functions should work with Postgres 7.0 and above, the set of charsets supported - // depends on compile flags of postgres distribution - if no charsets were compiled into the server - // it will return 'SQL_ANSI' always - function GetCharSet() - { - //we will use ADO's builtin property charSet - $this->charSet = @pg_client_encoding($this->_connectionID); - if (!$this->charSet) { - return false; - } else { - return $this->charSet; - } - } - - // SetCharSet - switch the client encoding - function SetCharSet($charset_name) - { - $this->GetCharSet(); - if ($this->charSet !== $charset_name) { - $if = pg_set_client_encoding($this->_connectionID, $charset_name); - if ($if == "0" & $this->GetCharSet() == $charset_name) { - return true; - } else return false; - } else return true; - } - -} - -/*-------------------------------------------------------------------------------------- - Class Name: Recordset ---------------------------------------------------------------------------------------*/ - -class ADORecordSet_postgres7 extends ADORecordSet_postgres64{ - - var $databaseType = "postgres7"; - - - function ADORecordSet_postgres7($queryID,$mode=false) - { - $this->ADORecordSet_postgres64($queryID,$mode); - } - - // 10% speedup to move MoveNext to child class - function MoveNext() - { - if (!$this->EOF) { - $this->_currentRow++; - if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) { - $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode); - - if (is_array($this->fields)) { - if ($this->fields && isset($this->_blobArr)) $this->_fixblobs(); - return true; - } - } - $this->fields = false; - $this->EOF = true; - } - return false; - } - -} - -class ADORecordSet_assoc_postgres7 extends ADORecordSet_postgres64{ - - var $databaseType = "postgres7"; - - - function ADORecordSet_assoc_postgres7($queryID,$mode=false) - { - $this->ADORecordSet_postgres64($queryID,$mode); - } - - function _fetch() - { - if ($this->_currentRow >= $this->_numOfRows && $this->_numOfRows >= 0) - return false; - - $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode); - - if ($this->fields) { - if (isset($this->_blobArr)) $this->_fixblobs(); - $this->_updatefields(); - } - - 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) { - $this->_currentRow++; - if ($this->_numOfRows < 0 || $this->_numOfRows > $this->_currentRow) { - $this->fields = @pg_fetch_array($this->_queryID,$this->_currentRow,$this->fetchMode); - - if (is_array($this->fields)) { - if ($this->fields) { - if (isset($this->_blobArr)) $this->_fixblobs(); - - $this->_updatefields(); - } - return true; - } - } - - - $this->fields = false; - $this->EOF = true; - } - return false; - } -} -?> \ No newline at end of file diff --git a/lib/adodb/drivers/adodb-postgres8.inc.php b/lib/adodb/drivers/adodb-postgres8.inc.php deleted file mode 100644 index 3134e3c3..00000000 --- a/lib/adodb/drivers/adodb-postgres8.inc.php +++ /dev/null @@ -1,12 +0,0 @@ - \ No newline at end of file diff --git a/lib/adodb/drivers/adodb-sqlite.inc.php b/lib/adodb/drivers/adodb-sqlite.inc.php deleted file mode 100644 index bb95a42e..00000000 --- a/lib/adodb/drivers/adodb-sqlite.inc.php +++ /dev/null @@ -1,398 +0,0 @@ -fmtDate)."'"; - case 'sysTimeStamp' : return "'".date($this->sysTimeStamp)."'"; - } - }*/ - - function ServerInfo() - { - $arr['version'] = sqlite_libversion(); - $arr['description'] = 'SQLite '; - $arr['encoding'] = sqlite_libencoding(); - return $arr; - } - - function BeginTrans() - { - 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(); - $ret = $this->Execute("COMMIT"); - if ($this->transCnt>0)$this->transCnt -= 1; - return !empty($ret); - } - - function RollbackTrans() - { - if ($this->transOff) return true; - $ret = $this->Execute("ROLLBACK"); - 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 ($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); - } - - function _affectedrows() - { - return sqlite_changes($this->_connectionID); - } - - function ErrorMsg() - { - if ($this->_logsql) return $this->_errorMsg; - return ($this->_errorNo) ? sqlite_error_string($this->_errorNo) : ''; - } - - function ErrorNo() - { - return $this->_errorNo; - } - - function SQLDate($fmt, $col=false) - { - $fmt = $this->qstr($fmt); - return ($col) ? "adodb_date2($fmt,$col)" : "adodb_date($fmt)"; - } - - - function _createFunctions() - { - @sqlite_create_function($this->_connectionID, 'adodb_date', 'adodb_date', 1); - @sqlite_create_function($this->_connectionID, '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; - $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; - } - - // 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); - } - - return $rez; - } - - function SelectLimit($sql,$nrows=-1,$offset=-1,$inputarr=false,$secs2cache=0) - { - $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); - - return $rs; - } - - /* - This algorithm is not very efficient, but works even if table locking - is not available. - - Will return false if unable to generate an ID after $MAXLOOPS attempts. - */ - var $_genSeqSQL = "create table %s (id integer)"; - - function GenID($seq='adodbseq',$start=1) - { - // if you have to modify the parameter below, your database is overloaded, - // or you need to implement generation of id's yourself! - $MAXLOOPS = 100; - //$this->debug=1; - while (--$MAXLOOPS>=0) { - @($num = $this->GetOne("select id from $seq")); - if ($num === false) { - $this->Execute(sprintf($this->_genSeqSQL ,$seq)); - $start -= 1; - $num = '0'; - $ok = $this->Execute("insert into $seq values($start)"); - if (!$ok) return false; - } - $this->Execute("update $seq set id=id+1 where id=$num"); - - if ($this->affected_rows() > 0) { - $num += 1; - $this->genID = $num; - return $num; - } - } - if ($fn = $this->raiseErrorFn) { - $fn($this->databaseType,'GENID',-32000,"Unable to generate unique id after $MAXLOOPS attempts",$seq,$num); - } - return false; - } - - function CreateSequence($seqname='adodbseq',$start=1) - { - if (empty($this->_genSeqSQL)) return false; - $ok = $this->Execute(sprintf($this->_genSeqSQL,$seqname)); - if (!$ok) return false; - $start -= 1; - return $this->Execute("insert into $seqname values($start)"); - } - - var $_dropSeqSQL = 'drop table %s'; - function DropSequence($seqname) - { - if (empty($this->_dropSeqSQL)) return false; - return $this->Execute(sprintf($this->_dropSeqSQL,$seqname)); - } - - // returns true or false - function _close() - { - return @sqlite_close($this->_connectionID); - } - - function MetaIndexes($table, $primary = FALSE, $owner=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); - } - $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)) - $this->SetFetchMode($savem); - $ADODB_FETCH_MODE = $save; - 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()); - } - /** - * 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); - $ADODB_FETCH_MODE = $save; - } - return $indexes; - } - -} - -/*-------------------------------------------------------------------------------------- - Class Name: Recordset ---------------------------------------------------------------------------------------*/ - -class ADORecordset_sqlite extends ADORecordSet { - - var $databaseType = "sqlite"; - var $bind = false; - - function ADORecordset_sqlite($queryID,$mode=false) - { - - if ($mode === false) { - global $ADODB_FETCH_MODE; - $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; - } - $this->adodbFetchMode = $mode; - - $this->_queryID = $queryID; - - $this->_inited = true; - $this->fields = array(); - if ($queryID) { - $this->_currentRow = 0; - $this->EOF = !$this->_fetch(); - @$this->_initrs(); - } else { - $this->_numOfRows = 0; - $this->_numOfFields = 0; - $this->EOF = true; - } - - return $this->_queryID; - } - - - function FetchField($fieldOffset = -1) - { - $fld = new ADOFieldObject; - $fld->name = sqlite_field_name($this->_queryID, $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 Fields($colname) - { - if ($this->fetchMode != SQLITE_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) - { - return sqlite_seek($this->_queryID, $row); - } - - function _fetch($ignore_fields=false) - { - $this->fields = @sqlite_fetch_array($this->_queryID,$this->fetchMode); - return !empty($this->fields); - } - - function _close() - { - } - -} -?> \ No newline at end of file diff --git a/lib/adodb/drivers/adodb-sqlitepo.inc.php b/lib/adodb/drivers/adodb-sqlitepo.inc.php deleted file mode 100644 index 2bdb99a7..00000000 --- a/lib/adodb/drivers/adodb-sqlitepo.inc.php +++ /dev/null @@ -1,62 +0,0 @@ -ADODB_sqlite(); - } -} - -/*-------------------------------------------------------------------------------------- - Class Name: Recordset ---------------------------------------------------------------------------------------*/ - -class ADORecordset_sqlitepo extends ADORecordset_sqlite { - - var $databaseType = 'sqlitepo'; - - function ADORecordset_sqlitepo($queryID,$mode=false) - { - $this->ADORecordset_sqlite($queryID,$mode); - } - - // Modified to strip table names from returned fields - function _fetch($ignore_fields=false) - { - $this->fields = array(); - $fields = @sqlite_fetch_array($this->_queryID,$this->fetchMode); - if(is_array($fields)) - foreach($fields as $n => $v) - { - if(($p = strpos($n, ".")) !== false) - $n = substr($n, $p+1); - $this->fields[$n] = $v; - } - - return !empty($this->fields); - } -} -?> \ No newline at end of file diff --git a/lib/adodb/license.txt b/lib/adodb/license.txt deleted file mode 100644 index 2353871c..00000000 --- a/lib/adodb/license.txt +++ /dev/null @@ -1,182 +0,0 @@ -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 From 1d7b929871264c91e4c9846fee761e2f172929b1 Mon Sep 17 00:00:00 2001 From: Shish Date: Fri, 31 Dec 2010 19:29:15 +0000 Subject: [PATCH 02/16] convert parts of core/database to pdo --- core/database.class.php | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/core/database.class.php b/core/database.class.php index 3e7bcaf3..dc77f687 100644 --- a/core/database.class.php +++ b/core/database.class.php @@ -1,8 +1,5 @@ Execute("SET NAMES utf8;"); + $db->query("SET NAMES utf8;"); } public function scoreql_to_sql($data) { @@ -255,7 +252,7 @@ class APCCache implements CacheEngine { */ class Database { /** - * The ADODB database connection object, for anyone who wants direct access + * The PDO database connection object, for anyone who wants direct access */ var $db; @@ -276,17 +273,22 @@ class Database { public function Database() { global $database_dsn, $cache_dsn; - if(substr($database_dsn, 0, 5) == "mysql") { + # FIXME: translate database URI into something PDO compatible + #$db_proto = $database_dsn; + #$db_host = $database_dsn; + #$db_name = $database_dsn; + + if($db_proto == "mysql") { $this->engine = new MySQL(); } - else if(substr($database_dsn, 0, 5) == "pgsql") { + else if($db_proto == "pgsql") { $this->engine = new PostgreSQL(); } - else if(substr($database_dsn, 0, 6) == "sqlite") { + else if($db_proto == "sqlite") { $this->engine = new SQLite(); } - $this->db = @NewADOConnection($database_dsn); + $this->db = new PDO("$db_proto:host=$db_host;dbname=$db_name", $db_user, $db_pass); if(isset($cache_dsn) && !empty($cache_dsn)) { $matches = array(); @@ -303,7 +305,6 @@ class Database { } if($this->db) { - $this->db->SetFetchMode(ADODB_FETCH_ASSOC); $this->engine->init($this->db); } else { @@ -323,10 +324,10 @@ class Database { } /** - * Execute an SQL query and return an ADODB resultset + * Execute an SQL query and return an PDO resultset */ public function execute($query, $args=array()) { - $result = $this->db->Execute($query, $args); + $result = $this->db->query($query, $args); if($result === False) { print "SQL Error: " . $this->db->ErrorMsg(); print "
Query: $query"; From 8e63827c0fcc218e41428c7f325f5f45c840f33f Mon Sep 17 00:00:00 2001 From: Shish Date: Fri, 31 Dec 2010 19:56:28 +0000 Subject: [PATCH 03/16] PDO exceptions for error handling --- core/database.class.php | 41 ++++------------------------------------- index.php | 2 +- 2 files changed, 5 insertions(+), 38 deletions(-) diff --git a/core/database.class.php b/core/database.class.php index dc77f687..8fccb158 100644 --- a/core/database.class.php +++ b/core/database.class.php @@ -289,6 +289,7 @@ class Database { } $this->db = new PDO("$db_proto:host=$db_host;dbname=$db_name", $db_user, $db_pass); + $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); if(isset($cache_dsn) && !empty($cache_dsn)) { $matches = array(); @@ -304,23 +305,7 @@ class Database { $this->cache = new NoCache(); } - if($this->db) { - $this->engine->init($this->db); - } - else { - $version = VERSION; - print " - - - Internal error - Shimmie-$version - - - Internal error: Could not connect to database - - - "; - exit; - } + $this->engine->init($this->db); } /** @@ -328,12 +313,6 @@ class Database { */ public function execute($query, $args=array()) { $result = $this->db->query($query, $args); - if($result === False) { - print "SQL Error: " . $this->db->ErrorMsg(); - print "
Query: $query"; - print "
Args: "; print_r($args); - exit; - } return $result; } @@ -341,13 +320,7 @@ class Database { * Execute an SQL query and return a 2D array */ public function get_all($query, $args=array()) { - $result = $this->db->GetAll($query, $args); - if($result === False) { - print "SQL Error: " . $this->db->ErrorMsg(); - print "
Query: $query"; - print "
Args: "; print_r($args); - exit; - } + $result = $this->db->fetchAll($query, $args); return $result; } @@ -355,13 +328,7 @@ class Database { * Execute an SQL query and return a single row */ public function get_row($query, $args=array()) { - $result = $this->db->GetRow($query, $args); - if($result === False) { - print "SQL Error: " . $this->db->ErrorMsg(); - print "
Query: $query"; - print "
Args: "; print_r($args); - exit; - } + $result = $this->db->fetch($query, $args); if(count($result) == 0) { return null; } diff --git a/index.php b/index.php index 15a4e2c0..d8483295 100644 --- a/index.php +++ b/index.php @@ -84,7 +84,7 @@ try { // connect to the database $database = new Database(); - $database->db->fnExecute = '_count_execs'; + //$database->db->fnExecute = '_count_execs'; // FIXME: PDO equivalent $config = new DatabaseConfig($database); From d90016b9323766d05f47add54a6f7d62d83f9cd1 Mon Sep 17 00:00:00 2001 From: Shish Date: Fri, 31 Dec 2010 19:59:22 +0000 Subject: [PATCH 04/16] run each page view inside a transaction --- index.php | 11 +++-------- 1 file changed, 3 insertions(+), 8 deletions(-) diff --git a/index.php b/index.php index d8483295..f488a113 100644 --- a/index.php +++ b/index.php @@ -85,6 +85,7 @@ try { // connect to the database $database = new Database(); //$database->db->fnExecute = '_count_execs'; // FIXME: PDO equivalent + $database->db->beginTransaction(); $config = new DatabaseConfig($database); @@ -129,14 +130,7 @@ try { send_event(_get_page_request()); $page->display(); - - // for databases which support transactions - // XXX: removed since we never start a transaction, and postgres - // fills the disk with warnings about that - //if($database->engine->name != "sqlite") { - // $database->db->CommitTrans(true); - //} - + $database->db->commit(); _end_cache(); } catch(Exception $e) { @@ -154,5 +148,6 @@ catch(Exception $e) { EOD; + $database->db->rollback(); } ?> From ffb17622809f64b896583eed70e547f7df8ea76c Mon Sep 17 00:00:00 2001 From: Shish Date: Fri, 31 Dec 2010 20:00:56 +0000 Subject: [PATCH 05/16] Insert_ID -> lastInsertId --- ext/comment/main.php | 2 +- ext/image/main.php | 2 +- ext/user/main.php | 2 +- install.php | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/ext/comment/main.php b/ext/comment/main.php index 36196ede..f98ba3c7 100644 --- a/ext/comment/main.php +++ b/ext/comment/main.php @@ -451,7 +451,7 @@ class CommentList extends SimpleExtension { "INSERT INTO comments(image_id, owner_id, owner_ip, posted, comment) ". "VALUES(?, ?, ?, now(), ?)", array($image_id, $user->id, $_SERVER['REMOTE_ADDR'], $comment)); - $cid = $database->db->Insert_ID(); + $cid = $database->db->lastInsertId(); log_info("comment", "Comment #$cid added to Image #$image_id"); } } diff --git a/ext/image/main.php b/ext/image/main.php index 89da1730..5c4cad1d 100644 --- a/ext/image/main.php +++ b/ext/image/main.php @@ -243,7 +243,7 @@ class ImageIO extends SimpleExtension { $image->id = $database->db->GetOne("SELECT id FROM images WHERE hash=?", array($image->hash)); } else { - $image->id = $database->db->Insert_ID(); + $image->id = $database->db->lastInsertId(); } log_info("image", "Uploaded Image #{$image->id} ({$image->hash})"); diff --git a/ext/user/main.php b/ext/user/main.php index 70912700..949d3609 100644 --- a/ext/user/main.php +++ b/ext/user/main.php @@ -304,7 +304,7 @@ class UserPage extends SimpleExtension { $database->Execute( "INSERT INTO users (name, pass, joindate, email, admin) VALUES (?, ?, now(), ?, ?)", array($event->username, $hash, $email, $admin)); - $uid = $database->db->Insert_ID(); + $uid = $database->db->lastInsertId(); log_info("user", "Created User #$uid ({$event->username})"); } diff --git a/install.php b/install.php index 938d8493..c66f82c3 100644 --- a/install.php +++ b/install.php @@ -323,7 +323,7 @@ function insert_defaults($dsn) { // {{{ $user_insert = $db->Prepare("INSERT INTO users(name, pass, joindate, admin) VALUES(?, ?, now(), ?)"); $db->Execute($user_insert, Array('Anonymous', null, 'N')); - $db->Execute($config_insert, Array('anon_id', $db->Insert_ID())); + $db->Execute($config_insert, Array('anon_id', $db->lastInsertId())); if(check_im_version() > 0) { $db->Execute($config_insert, Array('thumb_engine', 'convert')); From 6b557983c48369a6828647ca06cd86ae32aee127 Mon Sep 17 00:00:00 2001 From: Shish Date: Fri, 31 Dec 2010 20:25:03 +0000 Subject: [PATCH 06/16] more PDO compat --- core/config.class.php | 2 +- core/database.class.php | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/core/config.class.php b/core/config.class.php index 1295da6a..f45c0628 100644 --- a/core/config.class.php +++ b/core/config.class.php @@ -175,7 +175,7 @@ class DatabaseConfig extends BaseConfig { $this->values = $cached; } else { - $this->values = $this->database->db->GetAssoc("SELECT name, value FROM config"); + $this->values = $this->database->db->query("SELECT name, value FROM config")->fetchAll(); $this->database->cache->set("config", $this->values); } } diff --git a/core/database.class.php b/core/database.class.php index 8fccb158..373e74a6 100644 --- a/core/database.class.php +++ b/core/database.class.php @@ -274,6 +274,7 @@ class Database { global $database_dsn, $cache_dsn; # FIXME: translate database URI into something PDO compatible + include "config.php"; #$db_proto = $database_dsn; #$db_host = $database_dsn; #$db_name = $database_dsn; @@ -320,7 +321,7 @@ class Database { * Execute an SQL query and return a 2D array */ public function get_all($query, $args=array()) { - $result = $this->db->fetchAll($query, $args); + $result = $this->db->query($query, $args)->fetchAll(); return $result; } @@ -328,12 +329,12 @@ class Database { * Execute an SQL query and return a single row */ public function get_row($query, $args=array()) { - $result = $this->db->fetch($query, $args); + $result = $this->db->query($query, $args)->fetchAll(); if(count($result) == 0) { return null; } else { - return $result; + return $result[0]; } } From 8b2e3262fe30902e771fadc378968ba909ab98d9 Mon Sep 17 00:00:00 2001 From: Shish Date: Sat, 1 Jan 2011 15:27:24 +0000 Subject: [PATCH 07/16] clean up database API for completeness and sensibleness --- core/database.class.php | 52 ++++++++++++++++++++++++++++++++--------- 1 file changed, 41 insertions(+), 11 deletions(-) diff --git a/core/database.class.php b/core/database.class.php index 373e74a6..a02132d8 100644 --- a/core/database.class.php +++ b/core/database.class.php @@ -313,31 +313,61 @@ class Database { * Execute an SQL query and return an PDO resultset */ public function execute($query, $args=array()) { - $result = $this->db->query($query, $args); - return $result; + try { + $stmt = $this->db->prepare($query); + foreach($args as $name=>$value) { + if(is_numeric($value)) { + $stmt->bindValue(":$name", $value, PDO::PARAM_INT); + } + else { + $stmt->bindValue(":$name", $value, PDO::PARAM_STR); + } + } + $stmt->execute(); + return $stmt; + } + catch(PDOException $pdoe) { + print "Message: ".$pdoe->getMessage(); + print "

Error: $query"; + exit; + } } /** * Execute an SQL query and return a 2D array */ public function get_all($query, $args=array()) { - $result = $this->db->query($query, $args)->fetchAll(); - return $result; + return $this->execute($query, $args)->fetchAll(); } /** * Execute an SQL query and return a single row */ public function get_row($query, $args=array()) { - $result = $this->db->query($query, $args)->fetchAll(); - if(count($result) == 0) { - return null; - } - else { - return $result[0]; - } + return $this->execute($query, $args)->fetch(); } + /** + * Execute an SQL query and return the first column of each row + */ + public function get_col($query, $args=array()) { + $stmt = $this->execute($query, $args); + $res = array(); + foreach($stmt as $row) { + $res[] = $row[0]; + } + return $res; + } + + /** + * Execute an SQL query and return a single value + */ + public function get_one($query, $args=array()) { + $row = $this->execute($query, $args)->fetch(); + return $row[0]; + } + + /** * Create a table from pseudo-SQL */ From 175ceac490a19ac789b2db7e6d22c95a74748268 Mon Sep 17 00:00:00 2001 From: Shish Date: Sat, 1 Jan 2011 15:28:30 +0000 Subject: [PATCH 08/16] PDO compat --- core/config.class.php | 9 ++++++--- core/imageboard.pack.php | 26 ++++++++++---------------- core/user.class.php | 6 +++--- 3 files changed, 19 insertions(+), 22 deletions(-) diff --git a/core/config.class.php b/core/config.class.php index f45c0628..2f918173 100644 --- a/core/config.class.php +++ b/core/config.class.php @@ -175,7 +175,10 @@ class DatabaseConfig extends BaseConfig { $this->values = $cached; } else { - $this->values = $this->database->db->query("SELECT name, value FROM config")->fetchAll(); + $this->values = array(); + foreach($this->database->get_all("SELECT name, value FROM config") as $row) { + $this->values[$row["name"]] = $row["value"]; + } $this->database->cache->set("config", $this->values); } } @@ -190,8 +193,8 @@ class DatabaseConfig extends BaseConfig { } } else { - $this->database->Execute("DELETE FROM config WHERE name = ?", array($name)); - $this->database->Execute("INSERT INTO config VALUES (?, ?)", array($name, $this->values[$name])); + $this->database->Execute("DELETE FROM config WHERE name = :name", array("name"=>$name)); + $this->database->Execute("INSERT INTO config VALUES (:name, :value)", array("name"=>$name, "value"=>$this->values[$name])); } $this->database->cache->delete("config"); } diff --git a/core/imageboard.pack.php b/core/imageboard.pack.php index 1eb9405e..08ac4371 100644 --- a/core/imageboard.pack.php +++ b/core/imageboard.pack.php @@ -66,7 +66,7 @@ class Image { assert(is_numeric($id)); global $database; $image = null; - $row = $database->get_row("SELECT * FROM images WHERE images.id=?", array($id)); + $row = $database->get_row("SELECT * FROM images WHERE images.id=:id", array("id"=>$id)); return ($row ? new Image($row) : null); } @@ -79,7 +79,7 @@ class Image { assert(is_string($hash)); global $database; $image = null; - $row = $database->db->GetRow("SELECT images.* FROM images WHERE hash=?", array($hash)); + $row = $database->db->GetRow("SELECT images.* FROM images WHERE hash=:hash", array("hash"=>$hash)); return ($row ? new Image($row) : null); } @@ -112,12 +112,11 @@ class Image { if($limit < 1) $limit = 1; $querylet = Image::build_search_querylet($tags); - $querylet->append(new Querylet("ORDER BY images.id DESC LIMIT ? OFFSET ?", array($limit, $start))); + $querylet->append(new Querylet("ORDER BY images.id DESC LIMIT :limit OFFSET :offset", array("limit"=>$limit, "offset"=>$start))); $result = $database->execute($querylet->sql, $querylet->variables); - while(!$result->EOF) { - $images[] = new Image($result->fields); - $result->MoveNext(); + while($row = $result->fetch()) { + $images[] = new Image($row); } return $images; } @@ -136,15 +135,15 @@ class Image { #return $database->db->GetOne("SELECT COUNT(*) FROM images"); $total = $database->cache->get("image-count"); if(!$total) { - $total = $database->db->GetOne("SELECT COUNT(*) FROM images"); + $total = $database->get_one("SELECT COUNT(*) FROM images"); $database->cache->set("image-count", $total, 600); } return $total; } else if(count($tags) == 1 && !preg_match("/[:=><]/", $tags[0])) { - return $database->db->GetOne( - $database->engine->scoreql_to_sql("SELECT count FROM tags WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(?)"), - $tags); + return $database->get_one( + $database->engine->scoreql_to_sql("SELECT count FROM tags WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(:tag)"), + array("tag"=>$tags[0])); } else { $querylet = Image::build_search_querylet($tags); @@ -230,12 +229,7 @@ class Image { if($cached) return $cached; if(!isset($this->tag_array)) { - $this->tag_array = Array(); - $row = $database->Execute("SELECT tag FROM image_tags JOIN tags ON image_tags.tag_id = tags.id WHERE image_id=? ORDER BY tag", array($this->id)); - while(!$row->EOF) { - $this->tag_array[] = $row->fields['tag']; - $row->MoveNext(); - } + $this->tag_array = $database->get_col("SELECT tag FROM image_tags JOIN tags ON image_tags.tag_id = tags.id WHERE image_id=:id ORDER BY tag", array("id"=>$this->id)); } $database->cache->set("image-{$this->id}-tags", $this->tag_array); diff --git a/core/user.class.php b/core/user.class.php index 1b5ff117..b1b9dc64 100644 --- a/core/user.class.php +++ b/core/user.class.php @@ -41,12 +41,12 @@ class User { public static function by_session($name, $session) { global $config, $database; if($database->engine->name == "mysql") { - $query = "SELECT * FROM users WHERE name = ? AND md5(concat(pass, ?)) = ?"; + $query = "SELECT * FROM users WHERE name = :name AND md5(concat(pass, :ip)) = :sess"; } else { - $query = "SELECT * FROM users WHERE name = ? AND md5(pass || ?) = ?"; + $query = "SELECT * FROM users WHERE name = :name AND md5(pass || :ip) = :sess"; } - $row = $database->get_row($query, array($name, get_session_ip($config), $session)); + $row = $database->get_row($query, array("name"=>$name, "ip"=>get_session_ip($config), "sess"=>$session)); return is_null($row) ? null : new User($row); } From 9e006759009372321c8f2a13f8897fa50144c8c2 Mon Sep 17 00:00:00 2001 From: Shish Date: Sat, 1 Jan 2011 15:28:38 +0000 Subject: [PATCH 09/16] pdo compat --- contrib/ipban/main.php | 6 +++--- ext/comment/main.php | 18 +++++++++--------- ext/tag_list/main.php | 42 +++++++++++++++++++++--------------------- index.php | 2 ++ 4 files changed, 35 insertions(+), 33 deletions(-) diff --git a/contrib/ipban/main.php b/contrib/ipban/main.php index 679678d4..0df30dbf 100644 --- a/contrib/ipban/main.php +++ b/contrib/ipban/main.php @@ -89,7 +89,7 @@ class IPBan implements Extension { } if($event instanceof RemoveIPBanEvent) { - $database->Execute("DELETE FROM bans WHERE id = ?", array($event->id)); + $database->Execute("DELETE FROM bans WHERE id = :id", array("id"=>$event->id)); $database->cache->delete("ip_bans"); } } @@ -211,9 +211,9 @@ class IPBan implements Extension { SELECT bans.*, users.name as banner_name FROM bans JOIN users ON banner_id = users.id - WHERE (end_timestamp > ?) OR (end_timestamp IS NULL) + WHERE (end_timestamp > :end_timestamp) OR (end_timestamp IS NULL) ORDER BY end_timestamp, bans.id - ", array(time())); + ", array("end_timestamp"=>time())); $database->cache->set("ip_bans", $bans, 600); diff --git a/ext/comment/main.php b/ext/comment/main.php index f98ba3c7..19c2d516 100644 --- a/ext/comment/main.php +++ b/ext/comment/main.php @@ -51,7 +51,7 @@ class Comment { public static function count_comments_by_user($user) { global $database; - return $database->db->GetOne("SELECT COUNT(*) AS count FROM comments WHERE owner_id=?", array($user->id)); + return $database->db->GetOne("SELECT COUNT(*) AS count FROM comments WHERE owner_id=:owner_id", array("owner_id"=>$user->id)); } public function get_owner() { @@ -180,7 +180,7 @@ class CommentList extends SimpleExtension { public function onImageDeletion(ImageDeletionEvent $event) { global $database; $image_id = $event->image->id; - $database->Execute("DELETE FROM comments WHERE image_id=?", array($image_id)); + $database->Execute("DELETE FROM comments WHERE image_id=:image_id", array("image_id"=>$image_id)); log_info("comment", "Deleting all comments for Image #$image_id"); } @@ -191,7 +191,7 @@ class CommentList extends SimpleExtension { public function onCommentDeletion(CommentDeletionEvent $event) { global $database; - $database->Execute("DELETE FROM comments WHERE id=?", array($event->comment_id)); + $database->Execute("DELETE FROM comments WHERE id=:comment_id", array("comment_id"=>$event->comment_id)); log_info("comment", "Deleting Comment #{$event->comment_id}"); } @@ -261,9 +261,9 @@ class CommentList extends SimpleExtension { FROM comments GROUP BY image_id ORDER BY latest DESC - LIMIT ? OFFSET ? + LIMIT :limit OFFSET :offset "; - $result = $database->Execute($get_threads, array($threads_per_page, $start)); + $result = $database->Execute($get_threads, array("limit"=>$threads_per_page, "offset"=>$start)); $total_pages = (int)($database->db->GetOne("SELECT COUNT(c1) FROM (SELECT COUNT(image_id) AS c1 FROM comments GROUP BY image_id) AS s1") / 10); @@ -297,8 +297,8 @@ class CommentList extends SimpleExtension { FROM comments LEFT JOIN users ON comments.owner_id=users.id ORDER BY comments.id DESC - LIMIT ? - ", array($config->get_int('comment_count'))); + LIMIT :limit + ", array("limit"=>$config->get_int('comment_count'))); $comments = array(); foreach($rows as $row) { $comments[] = new Comment($row); @@ -318,9 +318,9 @@ class CommentList extends SimpleExtension { comments.posted as posted FROM comments LEFT JOIN users ON comments.owner_id=users.id - WHERE comments.image_id=? + WHERE comments.image_id=:image_id ORDER BY comments.id ASC - ", array($i_image_id)); + ", array("image_id"=>$i_image_id)); $comments = array(); foreach($rows as $row) { $comments[] = new Comment($row); diff --git a/ext/tag_list/main.php b/ext/tag_list/main.php index 32000351..541a1696 100644 --- a/ext/tag_list/main.php +++ b/ext/tag_list/main.php @@ -46,8 +46,8 @@ class TagList implements Extension { if(($event instanceof PageRequestEvent) && $event->page_matches("api/internal/tag_list/complete")) { $all = $database->get_all( - "SELECT tag FROM tags WHERE tag LIKE ? AND count > 0 LIMIT 10", - array($_GET["s"]."%")); + "SELECT tag FROM tags WHERE tag LIKE :search AND count > 0 LIMIT 10", + array("search"=>$_GET["s"]."%")); $res = array(); foreach($all as $row) {$res[] = $row["tag"];} @@ -130,11 +130,11 @@ class TagList implements Extension { $result = $database->execute(" SELECT tag, - FLOOR(LOG(2.7, LOG(2.7, count - ? + 1)+1)*1.5*100)/100 AS scaled + FLOOR(LOG(2.7, LOG(2.7, count - :tags_min + 1)+1)*1.5*100)/100 AS scaled FROM tags - WHERE count >= ? + WHERE count >= :tags_min ORDER BY tag - ", array($tags_min, $tags_min)); + ", array("tags_min"=>$tags_min)); $tag_data = $result->GetArray(); $html = ""; @@ -154,8 +154,8 @@ class TagList implements Extension { $tags_min = $this->get_tags_min(); $result = $database->execute( - "SELECT tag,count FROM tags WHERE count >= ? ORDER BY tag", - array($tags_min)); + "SELECT tag,count FROM tags WHERE count >= :tags_min ORDER BY tag", + array("tags_min"=>$tags_min)); $tag_data = $result->GetArray(); $html = ""; @@ -179,8 +179,8 @@ class TagList implements Extension { $tags_min = $this->get_tags_min(); $result = $database->execute( - "SELECT tag,count,FLOOR(LOG(count)) AS scaled FROM tags WHERE count >= ? ORDER BY count DESC, tag ASC", - array($tags_min)); + "SELECT tag,count,FLOOR(LOG(count)) AS scaled FROM tags WHERE count >= :tags_min ORDER BY count DESC, tag ASC", + array("tags_min"=>$tags_min)); $tag_data = $result->GetArray(); $html = "Results grouped by loge(n)"; @@ -240,7 +240,7 @@ class TagList implements Extension { tags AS t1, tags AS t3 WHERE - it1.image_id=? + it1.image_id=:image_id AND it1.tag_id=it2.tag_id AND it2.image_id=it3.image_id AND t1.tag != 'tagme' @@ -249,9 +249,9 @@ class TagList implements Extension { AND t3.id = it3.tag_id GROUP BY it3.tag_id ORDER BY calc_count DESC - LIMIT ? + LIMIT :tag_list_length "; - $args = array($image->id, $config->get_int('tag_list_length')); + $args = array("image_id"=>$image->id, "tag_list_length"=>$config->get_int('tag_list_length')); $tags = $database->get_all($query, $args); if(count($tags) > 0) { @@ -267,11 +267,11 @@ class TagList implements Extension { SELECT tags.tag, tags.count as calc_count FROM tags, image_tags WHERE tags.id = image_tags.tag_id - AND image_tags.image_id = ? + AND image_tags.image_id = :image_id ORDER BY calc_count DESC - LIMIT ? + LIMIT :tag_list_length "; - $args = array($image->id, $config->get_int('tag_list_length')); + $args = array("image_id"=>$image->id, "tag_list_length"=>$config->get_int('tag_list_length')); $tags = $database->get_all($query, $args); if(count($tags) > 0) { @@ -288,9 +288,9 @@ class TagList implements Extension { FROM tags WHERE count > 0 ORDER BY count DESC - LIMIT ? + LIMIT :tag_list_length "; - $args = array($config->get_int('tag_list_length')); + $args = array("tag_list_length"=>$config->get_int('tag_list_length')); $tags = $database->get_all($query, $args); if(count($tags) > 0) { @@ -310,9 +310,9 @@ class TagList implements Extension { foreach($wild_tags as $tag) { $tag = str_replace("*", "%", $tag); $tag = str_replace("?", "_", $tag); - $tag_ids = $database->db->GetCol("SELECT id FROM tags WHERE tag LIKE ?", array($tag)); + $tag_ids = $database->db->GetCol("SELECT id FROM tags WHERE tag LIKE :tag", array("tag"=>$tag)); // $search_tags = array_merge($search_tags, - // $database->db->GetCol("SELECT tag FROM tags WHERE tag LIKE ?", array($tag))); + // $database->db->GetCol("SELECT tag FROM tags WHERE tag LIKE :tag", array("tag"=>$tag))); $tag_id_array = array_merge($tag_id_array, $tag_ids); $tags_ok = count($tag_ids) > 0; if(!$tags_ok) break; @@ -334,9 +334,9 @@ class TagList implements Extension { AND it2.tag_id = t2.id GROUP BY t2.tag ORDER BY calc_count - DESC LIMIT ? + DESC LIMIT :limit "; - $args = array($config->get_int('tag_list_length')); + $args = array("limit"=>$config->get_int('tag_list_length')); $related_tags = $database->get_all($query, $args); print $database->db->ErrorMsg(); diff --git a/index.php b/index.php index f488a113..4b04ef0f 100644 --- a/index.php +++ b/index.php @@ -136,6 +136,7 @@ try { catch(Exception $e) { $version = VERSION; $message = $e->getMessage(); + $trace = var_dump($e->getTrace()); header("HTTP/1.0 500 Internal Error"); print << @@ -145,6 +146,7 @@ catch(Exception $e) {

Internal Error

$message +

$trace EOD; From 8d978aa06af12dbd166fea7afc788fd89c2e719a Mon Sep 17 00:00:00 2001 From: Shish Date: Sat, 1 Jan 2011 15:58:09 +0000 Subject: [PATCH 10/16] more pdo compat --- core/imageboard.pack.php | 54 ++++++++++++++++++++-------------------- core/user.class.php | 15 ++++++----- ext/comment/main.php | 9 +++---- ext/tag_list/main.php | 3 +-- 4 files changed, 39 insertions(+), 42 deletions(-) diff --git a/core/imageboard.pack.php b/core/imageboard.pack.php index 08ac4371..73d0dfa9 100644 --- a/core/imageboard.pack.php +++ b/core/imageboard.pack.php @@ -148,7 +148,7 @@ class Image { else { $querylet = Image::build_search_querylet($tags); $result = $database->execute($querylet->sql, $querylet->variables); - return $result->RecordCount(); + return $result->rowCount(); } } @@ -365,7 +365,7 @@ class Image { public function set_source($source) { global $database; if(empty($source)) $source = null; - $database->execute("UPDATE images SET source=? WHERE id=?", array($source, $this->id)); + $database->execute("UPDATE images SET source=:source WHERE id=:id", array("source"=>$source, "id"=>$this->id)); } @@ -378,7 +378,7 @@ class Image { $sln = $database->engine->scoreql_to_sql("SCORE_BOOL_$ln"); $sln = str_replace("'", "", $sln); $sln = str_replace('"', "", $sln); - $database->execute("UPDATE images SET locked=? WHERE id=?", array($sln, $this->id)); + $database->execute("UPDATE images SET locked=:yn WHERE id=:id", array("yn"=>$sln, "id"=>$this->id)); } /** @@ -390,8 +390,8 @@ class Image { global $database; $database->execute( "UPDATE tags SET count = count - 1 WHERE id IN ". - "(SELECT tag_id FROM image_tags WHERE image_id = ?)", array($this->id)); - $database->execute("DELETE FROM image_tags WHERE image_id=?", array($this->id)); + "(SELECT tag_id FROM image_tags WHERE image_id = :id)", array("id"=>$this->id)); + $database->execute("DELETE FROM image_tags WHERE image_id=:id", array("id"=>$this->id)); } /** @@ -411,30 +411,30 @@ class Image { foreach($tags as $tag) { $id = $database->db->GetOne( $database->engine->scoreql_to_sql( - "SELECT id FROM tags WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(?)" + "SELECT id FROM tags WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(:tag)" ), - array($tag)); + array("tag"=>$tag)); if(empty($id)) { // a new tag $database->execute( - "INSERT INTO tags(tag) VALUES (?)", - array($tag)); + "INSERT INTO tags(tag) VALUES (:tag)", + array("tag"=>$tag)); $database->execute( "INSERT INTO image_tags(image_id, tag_id) - VALUES(?, (SELECT id FROM tags WHERE tag = ?))", - array($this->id, $tag)); + VALUES(:id, (SELECT id FROM tags WHERE tag = :tag))", + array("id"=>$this->id, "tag"=>$tag)); } else { // user of an existing tag $database->execute( - "INSERT INTO image_tags(image_id, tag_id) VALUES(?, ?)", - array($this->id, $id)); + "INSERT INTO image_tags(image_id, tag_id) VALUES(:iid, :tid)", + array("iid"=>$this->id, "tid"=>$id)); } $database->execute( $database->engine->scoreql_to_sql( - "UPDATE tags SET count = count + 1 WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(?)" + "UPDATE tags SET count = count + 1 WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(:tag)" ), - array($tag)); + array("tag"=>$tag)); } log_info("core-image", "Tags for Image #{$this->id} set to: ".implode(" ", $tags)); @@ -447,7 +447,7 @@ class Image { public function delete() { global $database; $this->delete_tags_from_image(); - $database->execute("DELETE FROM images WHERE id=?", array($this->id)); + $database->execute("DELETE FROM images WHERE id=:id", array("id"=>$this->id)); log_info("core-image", "Deleted Image #{$this->id} ({$this->hash})"); unlink($this->get_image_filename()); @@ -595,8 +595,8 @@ class Image { $query = new Querylet($database->engine->scoreql_to_sql(" SELECT images.* FROM images JOIN image_tags ON images.id = image_tags.image_id - WHERE tag_id = (SELECT tags.id FROM tags WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(?)) - "), array($tag_querylets[0]->tag)); + WHERE tag_id = (SELECT tags.id FROM tags WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(:tag)) + "), array("tag"=>$tag_querylets[0]->tag)); if(strlen($img_search->sql) > 0) { $query->append_sql(" AND "); @@ -613,9 +613,9 @@ class Image { foreach($tag_querylets as $tq) { $tag_ids = $database->db->GetCol( $database->engine->scoreql_to_sql( - "SELECT id FROM tags WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(?)" + "SELECT id FROM tags WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(:tag)" ), - array($tq->tag)); + array("tag"=>$tq->tag)); if($tq->positive) { $positive_tag_id_array = array_merge($positive_tag_id_array, $tag_ids); $tags_ok = count($tag_ids) > 0; @@ -728,8 +728,8 @@ class Image { $terms = array(); foreach($tag_querylets as $tq) { $sign = $tq->positive ? "+" : "-"; - $sql .= " $sign (tag LIKE ?)"; - $terms[] = $tq->tag; + $sql .= " $sign (tag LIKE :tag)"; + $terms["tag"] = $tq->tag; if($sign == "+") $positive_tag_count++; else $negative_tag_count++; @@ -768,7 +768,7 @@ class Image { SELECT images.*, UNIX_TIMESTAMP(posted) AS posted_timestamp FROM tags, image_tags, images WHERE - tag LIKE ? + tag LIKE :tag AND tags.id = image_tags.tag_id AND image_tags.image_id = images.id ", @@ -788,7 +788,7 @@ class Image { $tag_id_array = array(); $tags_ok = true; foreach($tag_search->variables as $tag) { - $tag_ids = $database->db->GetCol("SELECT id FROM tags WHERE tag LIKE ?", array($tag)); + $tag_ids = $database->get_col("SELECT id FROM tags WHERE tag LIKE :tag", array("tag"=>$tag)); $tag_id_array = array_merge($tag_id_array, $tag_ids); $tags_ok = count($tag_ids) > 0; if(!$tags_ok) break; @@ -803,10 +803,10 @@ class Image { JOIN tags ON image_tags.tag_id = tags.id WHERE tags.id IN ({$tag_id_list}) GROUP BY images.id - HAVING score = ?", + HAVING score = :score", array_merge( $tag_search->variables, - array($positive_tag_count) + array("score"=>$positive_tag_count) ) ); $query = new Querylet(" @@ -895,7 +895,7 @@ class Tag { assert(is_string($tag)); global $database; - $newtag = $database->db->GetOne("SELECT newtag FROM aliases WHERE oldtag=?", array($tag)); + $newtag = $database->get_one("SELECT newtag FROM aliases WHERE oldtag=:tag", array("tag"=>$tag)); if(!empty($newtag)) { return $newtag; } else { diff --git a/core/user.class.php b/core/user.class.php index b1b9dc64..27b792a9 100644 --- a/core/user.class.php +++ b/core/user.class.php @@ -53,14 +53,14 @@ class User { public static function by_id($id) { assert(is_numeric($id)); global $database; - $row = $database->get_row("SELECT * FROM users WHERE id = ?", array($id)); + $row = $database->get_row("SELECT * FROM users WHERE id = :id", array("id"=>$id)); return is_null($row) ? null : new User($row); } public static function by_name($name) { assert(is_string($name)); global $database; - $row = $database->get_row("SELECT * FROM users WHERE name = ?", array($name)); + $row = $database->get_row("SELECT * FROM users WHERE name = :name", array("name"=>$name)); return is_null($row) ? null : new User($row); } @@ -69,7 +69,7 @@ class User { assert(is_string($hash)); assert(strlen($hash) == 32); global $database; - $row = $database->get_row("SELECT * FROM users WHERE name = ? AND pass = ?", array($name, $hash)); + $row = $database->get_row("SELECT * FROM users WHERE name = :name AND pass = :hash", array("name"=>$name, "hash"=>$hash)); return is_null($row) ? null : new User($row); } @@ -77,7 +77,7 @@ class User { assert(is_numeric($offset)); assert(is_numeric($limit)); global $database; - $rows = $database->get_all("SELECT * FROM users WHERE id >= ? AND id < ?", array($offset, $offset+$limit)); + $rows = $database->get_all("SELECT * FROM users WHERE id >= :start AND id < :end", array("start"=>$offset, "end"=>$offset+$limit)); return array_map("_new_user", $rows); } @@ -119,20 +119,20 @@ class User { assert(is_bool($admin)); global $database; $yn = $admin ? 'Y' : 'N'; - $database->Execute("UPDATE users SET admin=? WHERE id=?", array($yn, $this->id)); + $database->Execute("UPDATE users SET admin=:yn WHERE id=:id", array("yn"=>$yn, "id"=>$this->id)); log_info("core-user", "Made {$this->name} admin=$yn"); } public function set_password($password) { global $database; $hash = md5(strtolower($this->name) . $password); - $database->Execute("UPDATE users SET pass=? WHERE id=?", array($hash, $this->id)); + $database->Execute("UPDATE users SET pass=:hash WHERE id=:id", array("hash"=>$hash, "id"=>$this->id)); log_info("core-user", "Set password for {$this->name}"); } public function set_email($address) { global $database; - $database->Execute("UPDATE users SET email=? WHERE id=?", array($address, $this->id)); + $database->Execute("UPDATE users SET email=:email WHERE id=:id", array("email"=>$address, "id"=>$this->id)); log_info("core-user", "Set email for {$this->name}"); } @@ -181,6 +181,5 @@ class User { public function check_auth_token() { return ($_POST["auth_token"] == $this->get_auth_token()); } - } ?> diff --git a/ext/comment/main.php b/ext/comment/main.php index 19c2d516..9fcbfd4a 100644 --- a/ext/comment/main.php +++ b/ext/comment/main.php @@ -51,7 +51,7 @@ class Comment { public static function count_comments_by_user($user) { global $database; - return $database->db->GetOne("SELECT COUNT(*) AS count FROM comments WHERE owner_id=:owner_id", array("owner_id"=>$user->id)); + return $database->get_one("SELECT COUNT(*) AS count FROM comments WHERE owner_id=:owner_id", array("owner_id"=>$user->id)); } public function get_owner() { @@ -265,12 +265,12 @@ class CommentList extends SimpleExtension { "; $result = $database->Execute($get_threads, array("limit"=>$threads_per_page, "offset"=>$start)); - $total_pages = (int)($database->db->GetOne("SELECT COUNT(c1) FROM (SELECT COUNT(image_id) AS c1 FROM comments GROUP BY image_id) AS s1") / 10); + $total_pages = (int)($database->get_one("SELECT COUNT(c1) FROM (SELECT COUNT(image_id) AS c1 FROM comments GROUP BY image_id) AS s1") / 10); $images = array(); - while(!$result->EOF) { - $image = Image::by_id($result->fields["image_id"]); + while($row = $result->fetch()) { + $image = Image::by_id($row["image_id"]); $comments = $this->get_comments($image->id); if(class_exists("Ratings")) { if(strpos($user_ratings, $image->rating) === FALSE) { @@ -278,7 +278,6 @@ class CommentList extends SimpleExtension { } } if(!is_null($image)) $images[] = array($image, $comments); - $result->MoveNext(); } $this->theme->display_comment_list($images, $current_page, $total_pages, $this->can_comment()); diff --git a/ext/tag_list/main.php b/ext/tag_list/main.php index 541a1696..53abb9c9 100644 --- a/ext/tag_list/main.php +++ b/ext/tag_list/main.php @@ -310,7 +310,7 @@ class TagList implements Extension { foreach($wild_tags as $tag) { $tag = str_replace("*", "%", $tag); $tag = str_replace("?", "_", $tag); - $tag_ids = $database->db->GetCol("SELECT id FROM tags WHERE tag LIKE :tag", array("tag"=>$tag)); + $tag_ids = $database->get_col("SELECT id FROM tags WHERE tag LIKE :tag", array("tag"=>$tag)); // $search_tags = array_merge($search_tags, // $database->db->GetCol("SELECT tag FROM tags WHERE tag LIKE :tag", array("tag"=>$tag))); $tag_id_array = array_merge($tag_id_array, $tag_ids); @@ -339,7 +339,6 @@ class TagList implements Extension { $args = array("limit"=>$config->get_int('tag_list_length')); $related_tags = $database->get_all($query, $args); - print $database->db->ErrorMsg(); if(count($related_tags) > 0) { $this->theme->display_refine_block($page, $related_tags, $wild_tags); } From 07959b1fc806855018dc3a73efd79eba71c0854a Mon Sep 17 00:00:00 2001 From: Shish Date: Sat, 1 Jan 2011 16:23:00 +0000 Subject: [PATCH 11/16] mime_type or ext, not type --- contrib/amazon_s3/main.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contrib/amazon_s3/main.php b/contrib/amazon_s3/main.php index 9cfa5a50..741b7378 100644 --- a/contrib/amazon_s3/main.php +++ b/contrib/amazon_s3/main.php @@ -52,8 +52,8 @@ class UploadS3 extends SimpleExtension { S3::ACL_PUBLIC_READ, array(), array( - "Content-Type" => "image/" . $event->image->type, - "Content-Disposition" => "inline; filename=image-" . $event->image->id . "." . $event->image->type, + "Content-Type" => $event->image->get_mime_type(), + "Content-Disposition" => "inline; filename=image-" . $event->image->id . "." . $event->image->ext, ) ); } From 7684def0f8feb29e17077dbfd871579ee1a2a073 Mon Sep 17 00:00:00 2001 From: Shish Date: Sat, 1 Jan 2011 16:27:56 +0000 Subject: [PATCH 12/16] add get_pairs --- core/database.class.php | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/core/database.class.php b/core/database.class.php index a02132d8..0d4e3927 100644 --- a/core/database.class.php +++ b/core/database.class.php @@ -359,6 +359,18 @@ class Database { return $res; } + /** + * Execute an SQL query and return the the first row => the second rown + */ + public function get_pairs($query, $args=array()) { + $stmt = $this->execute($query, $args); + $res = array(); + foreach($stmt as $row) { + $res[$row[0]] = $row[1]; + } + return $res; + } + /** * Execute an SQL query and return a single value */ From d6baeab977e6f2737e934c42f6473db7db81f66e Mon Sep 17 00:00:00 2001 From: Shish Date: Sat, 1 Jan 2011 16:28:04 +0000 Subject: [PATCH 13/16] more pdo compat --- contrib/artists/main.php | 16 ++++++------ contrib/et/main.php | 14 +++++------ contrib/et/theme.php | 3 ++- contrib/favorites/main.php | 2 +- contrib/forum/main.php | 8 +++--- contrib/image_hash_ban/main.php | 4 +-- contrib/log_db/main.php | 43 ++++++++++++++++----------------- contrib/notes/main.php | 10 ++++---- contrib/pools/main.php | 16 ++++++------ contrib/tag_history/main.php | 4 +-- contrib/wiki/main.php | 4 +-- core/imageboard.pack.php | 10 ++++---- ext/alias_editor/main.php | 10 ++++---- ext/comment/main.php | 2 +- ext/image/main.php | 17 +++++++++---- ext/user/main.php | 16 ++++++------ 16 files changed, 93 insertions(+), 86 deletions(-) diff --git a/contrib/artists/main.php b/contrib/artists/main.php index 93a8a27e..f035224a 100644 --- a/contrib/artists/main.php +++ b/contrib/artists/main.php @@ -434,7 +434,7 @@ class Artists implements Extension { { global $database; - $result = $database->db->GetOne("SELECT COUNT(1) FROM artist_urls WHERE url = ?", array(mysql_real_escape_string($url))); + $result = $database->get_one("SELECT COUNT(1) FROM artist_urls WHERE url = ?", array(mysql_real_escape_string($url))); return ($result != 0); } @@ -442,7 +442,7 @@ class Artists implements Extension { { global $database; - $result = $database->db->GetOne("SELECT COUNT(1) FROM artist_members WHERE name = ?", array(mysql_real_escape_string($member))); + $result = $database->get_one("SELECT COUNT(1) FROM artist_members WHERE name = ?", array(mysql_real_escape_string($member))); return ($result != 0); } @@ -450,7 +450,7 @@ class Artists implements Extension { { global $database; - $result = $database->db->GetOne("SELECT COUNT(1) FROM artist_alias WHERE alias = ?", array(mysql_real_escape_string($alias))); + $result = $database->get_one("SELECT COUNT(1) FROM artist_alias WHERE alias = ?", array(mysql_real_escape_string($alias))); return ($result != 0); } @@ -459,7 +459,7 @@ class Artists implements Extension { global $database; - $result = $database->db->GetOne("SELECT COUNT(1) FROM artist_alias WHERE artist_id = ? AND alias = ?", array( + $result = $database->get_one("SELECT COUNT(1) FROM artist_alias WHERE artist_id = ? AND alias = ?", array( $artistID , mysql_real_escape_string($alias) )); @@ -870,7 +870,7 @@ class Artists implements Extension { private function artist_exists($name){ global $database; - $result = $database->db->GetOne("SELECT COUNT(1) FROM artists WHERE name = ?" + $result = $database->get_one("SELECT COUNT(1) FROM artists WHERE name = ?" , array( mysql_real_escape_string($name) )); @@ -1046,7 +1046,7 @@ class Artists implements Extension { $listing[$i]["artist_name"] = stripslashes($listing[$i]["artist_name"]); } - $count = $database->db->GetOne( + $count = $database->get_one( "SELECT COUNT(1) FROM artists AS a LEFT OUTER JOIN artist_members AS am @@ -1170,7 +1170,7 @@ class Artists implements Extension { global $database; - $result = $database->db->GetOne("SELECT COUNT(1) FROM artist_members WHERE artist_id = ? AND name = ?" + $result = $database->get_one("SELECT COUNT(1) FROM artist_members WHERE artist_id = ? AND name = ?" , array( $artistID , mysql_real_escape_string($member) @@ -1184,7 +1184,7 @@ class Artists implements Extension { global $database; - $result = $database->db->GetOne("SELECT COUNT(1) FROM artist_urls WHERE artist_id = ? AND url = ?" + $result = $database->get_one("SELECT COUNT(1) FROM artist_urls WHERE artist_id = ? AND url = ?" , array( $artistID , mysql_real_escape_string($url) diff --git a/contrib/et/main.php b/contrib/et/main.php index 00dfd2ae..8b4c0099 100644 --- a/contrib/et/main.php +++ b/contrib/et/main.php @@ -50,14 +50,14 @@ class ET implements Extension { $info['sys_server'] = $_SERVER["SERVER_SOFTWARE"]; include "config.php"; // more magical hax $proto = preg_replace("#(.*)://.*#", "$1", $database_dsn); - $db = $database->db->ServerInfo(); - $info['sys_db'] = "$proto / {$db['version']}"; + #$db = $database->db->ServerInfo(); + #$info['sys_db'] = "$proto / {$db['version']}"; - $info['stat_images'] = $database->db->GetOne("SELECT COUNT(*) FROM images"); - $info['stat_comments'] = $database->db->GetOne("SELECT COUNT(*) FROM comments"); - $info['stat_users'] = $database->db->GetOne("SELECT COUNT(*) FROM users"); - $info['stat_tags'] = $database->db->GetOne("SELECT COUNT(*) FROM tags"); - $info['stat_image_tags'] = $database->db->GetOne("SELECT COUNT(*) FROM image_tags"); + $info['stat_images'] = $database->get_one("SELECT COUNT(*) FROM images"); + $info['stat_comments'] = $database->get_one("SELECT COUNT(*) FROM comments"); + $info['stat_users'] = $database->get_one("SELECT COUNT(*) FROM users"); + $info['stat_tags'] = $database->get_one("SELECT COUNT(*) FROM tags"); + $info['stat_image_tags'] = $database->get_one("SELECT COUNT(*) FROM image_tags"); $els = array(); foreach($_event_listeners as $el) { diff --git a/contrib/et/theme.php b/contrib/et/theme.php index 3ddd5786..802cabbf 100644 --- a/contrib/et/theme.php +++ b/contrib/et/theme.php @@ -14,6 +14,8 @@ class ETTheme extends Themelet { } protected function build_data_form($info) { + global $user; + $data = <<id; $image_id = $event->image->id; - $is_favorited = $database->db->GetOne( + $is_favorited = $database->get_one( "SELECT COUNT(*) AS ct FROM user_favorites WHERE user_id = ? AND image_id = ?", array($user_id, $image_id)) > 0; diff --git a/contrib/forum/main.php b/contrib/forum/main.php index c46fa006..7a0caed0 100644 --- a/contrib/forum/main.php +++ b/contrib/forum/main.php @@ -60,8 +60,8 @@ class Forum extends SimpleExtension { public function onUserPageBuilding($event) { global $page, $user, $database; - $threads_count = $database->db->GetOne("SELECT COUNT(*) FROM forum_threads WHERE user_id=?", array($event->display_user->id)); - $posts_count = $database->db->GetOne("SELECT COUNT(*) FROM forum_posts WHERE user_id=?", array($event->display_user->id)); + $threads_count = $database->get_one("SELECT COUNT(*) FROM forum_threads WHERE user_id=?", array($event->display_user->id)); + $posts_count = $database->get_one("SELECT COUNT(*) FROM forum_posts WHERE user_id=?", array($event->display_user->id)); $days_old = ((time() - strtotime($event->display_user->join_date)) / 86400) + 1; @@ -278,7 +278,7 @@ class Forum extends SimpleExtension { , array($pageNumber * $threadsPerPage, $threadsPerPage) ); - $totalPages = ceil($database->db->GetOne("SELECT COUNT(*) FROM forum_threads") / $threadsPerPage); + $totalPages = ceil($database->get_one("SELECT COUNT(*) FROM forum_threads") / $threadsPerPage); $this->theme->display_thread_list($page, $threads, $showAdminOptions, $pageNumber + 1, $totalPages); } @@ -309,7 +309,7 @@ class Forum extends SimpleExtension { , array($threadID, $pageNumber * $postsPerPage, $postsPerPage) ); - $totalPages = ceil($database->db->GetOne("SELECT COUNT(*) FROM forum_posts WHERE thread_id = ?", array($threadID)) / $postsPerPage); + $totalPages = ceil($database->get_one("SELECT COUNT(*) FROM forum_posts WHERE thread_id = ?", array($threadID)) / $postsPerPage); $threadTitle = $this->get_thread_title($threadID); diff --git a/contrib/image_hash_ban/main.php b/contrib/image_hash_ban/main.php index b973eb32..354cd4dc 100644 --- a/contrib/image_hash_ban/main.php +++ b/contrib/image_hash_ban/main.php @@ -45,7 +45,7 @@ class ImageBan extends SimpleExtension { public function onDataUpload(DataUploadEvent $event) { global $database; - $row = $database->db->GetRow("SELECT * FROM image_bans WHERE hash = ?", $event->hash); + $row = $database->get_row("SELECT * FROM image_bans WHERE hash = :hash", array("hash"=>$event->hash)); if($row) { log_info("image_hash_ban", "Blocked image ({$event->hash})"); throw new UploadException("Image ".html_escape($row["hash"])." has been banned, reason: ".format_text($row["reason"])); @@ -87,7 +87,7 @@ class ImageBan extends SimpleExtension { $page_num = int_escape($event->get_arg(1)); } $page_size = 100; - $page_count = ceil($database->db->getone("SELECT COUNT(id) FROM image_bans")/$page_size); + $page_count = ceil($database->get_one("SELECT COUNT(id) FROM image_bans")/$page_size); $this->theme->display_Image_hash_Bans($page, $page_num, $page_count, $this->get_image_hash_bans($page_num, $page_size)); } } diff --git a/contrib/log_db/main.php b/contrib/log_db/main.php index 6e4caf73..b77a20d4 100644 --- a/contrib/log_db/main.php +++ b/contrib/log_db/main.php @@ -49,38 +49,34 @@ class LogDatabase extends SimpleExtension { $page_num = int_escape($event->get_arg(0)); if($page_num <= 0) $page_num = 1; if(!empty($_GET["time"])) { - $wheres[] = "date_sent LIKE ?"; - $args[] = $_GET["time"]."%"; + $wheres[] = "date_sent LIKE :time"; + $args["time"] = $_GET["time"]."%"; } if(!empty($_GET["module"])) { - $wheres[] = "section = ?"; - $args[] = $_GET["module"]; + $wheres[] = "section = :module"; + $args["module"] = $_GET["module"]; } if(!empty($_GET["user"])) { if($database->engine->name == "pgsql") { if(preg_match("#\d+\.\d+\.\d+\.\d+(/\d+)?#", $_GET["user"])) { - $wheres[] = "(username = ? OR address << ?)"; - $args[] = $_GET["user"]; - $args[] = $_GET["user"]; + $wheres[] = "(username = :user OR address << :user)"; } else { - $wheres[] = "lower(username) = lower(?)"; - $args[] = $_GET["user"]; + $wheres[] = "lower(username) = lower(:user)"; } } else { - $wheres[] = "(username = ? OR address = ?)"; - $args[] = $_GET["user"]; - $args[] = $_GET["user"]; + $wheres[] = "(username = :user OR address = :user)"; } + $args["user"] = $_GET["user"]; } if(!empty($_GET["priority"])) { - $wheres[] = "priority >= ?"; - $args[] = int_escape($_GET["priority"]); + $wheres[] = "priority >= :priority"; + $args["priority"] = int_escape($_GET["priority"]); } else { - $wheres[] = "priority >= ?"; - $args[] = 20; + $wheres[] = "priority >= :priority"; + $args["priority"] = 20; } $where = ""; if(count($wheres) > 0) { @@ -92,16 +88,16 @@ class LogDatabase extends SimpleExtension { $offset = ($page_num-1) * $limit; $page_total = $database->cache->get("event_log_length"); if(!$page_total) { - $page_total = $database->db->GetOne("SELECT count(*) FROM score_log $where", $args); + $page_total = $database->get_one("SELECT count(*) FROM score_log $where", $args); // don't cache a length of zero when the extension is first installed if($page_total > 10) { $database->cache->set("event_log_length", 600); } } - $args[] = $limit; - $args[] = $offset; - $events = $database->get_all("SELECT * FROM score_log $where ORDER BY id DESC LIMIT ? OFFSET ?", $args); + $args["limit"] = $limit; + $args["offset"] = $offset; + $events = $database->get_all("SELECT * FROM score_log $where ORDER BY id DESC LIMIT :limit OFFSET :offset", $args); $this->theme->display_events($events, $page_num, 100); } @@ -124,8 +120,11 @@ class LogDatabase extends SimpleExtension { if($event->priority >= $config->get_int("log_db_priority")) { $database->execute(" INSERT INTO score_log(date_sent, section, priority, username, address, message) - VALUES(now(), ?, ?, ?, ?, ?) - ", array($event->section, $event->priority, $user->name, $_SERVER['REMOTE_ADDR'], $event->message)); + VALUES(now(), :section, :priority, :username, :address, :message) + ", array( + "section"=>$event->section, "priority"=>$event->priority, "username"=>$user->name, + "address"=>$_SERVER['REMOTE_ADDR'], "message"=>$event->message + )); } } } diff --git a/contrib/notes/main.php b/contrib/notes/main.php index 92da72fd..4c9dd8c8 100644 --- a/contrib/notes/main.php +++ b/contrib/notes/main.php @@ -436,7 +436,7 @@ class Notes extends SimpleExtension { $result = $database->Execute($get_notes, array(1, $pageNumber * $notesPerPage, $notesPerPage)); - $totalPages = ceil($database->db->GetOne("SELECT COUNT(DISTINCT image_id) FROM notes") / $notesPerPage); + $totalPages = ceil($database->get_one("SELECT COUNT(DISTINCT image_id) FROM notes") / $notesPerPage); $images = array(); while(!$result->EOF) { @@ -476,7 +476,7 @@ class Notes extends SimpleExtension { $result = $database->Execute($get_requests, array($pageNumber * $requestsPerPage, $requestsPerPage)); - $totalPages = ceil($database->db->GetOne("SELECT COUNT(*) FROM note_request") / $requestsPerPage); + $totalPages = ceil($database->get_one("SELECT COUNT(*) FROM note_request") / $requestsPerPage); $images = array(); while(!$result->EOF) { @@ -498,7 +498,7 @@ class Notes extends SimpleExtension { $userID = $user->id; - $reviewID = $database->db->GetOne("SELECT COUNT(*) FROM note_histories WHERE note_id = ?", array($noteID)); + $reviewID = $database->get_one("SELECT COUNT(*) FROM note_histories WHERE note_id = ?", array($noteID)); $reviewID = $reviewID + 1; $database->execute(" @@ -536,7 +536,7 @@ class Notes extends SimpleExtension { "ORDER BY date DESC LIMIT ?, ?", array($pageNumber * $histiriesPerPage, $histiriesPerPage)); - $totalPages = ceil($database->db->GetOne("SELECT COUNT(*) FROM note_histories") / $histiriesPerPage); + $totalPages = ceil($database->get_one("SELECT COUNT(*) FROM note_histories") / $histiriesPerPage); $this->theme->display_histories($histories, $pageNumber + 1, $totalPages); } @@ -569,7 +569,7 @@ class Notes extends SimpleExtension { "ORDER BY date DESC LIMIT ?, ?", array($noteID, $pageNumber * $histiriesPerPage, $histiriesPerPage)); - $totalPages = ceil($database->db->GetOne("SELECT COUNT(*) FROM note_histories WHERE note_id = ?", array($noteID)) / $histiriesPerPage); + $totalPages = ceil($database->get_one("SELECT COUNT(*) FROM note_histories WHERE note_id = ?", array($noteID)) / $histiriesPerPage); $this->theme->display_history($histories, $pageNumber + 1, $totalPages); } diff --git a/contrib/pools/main.php b/contrib/pools/main.php index 1891788a..3ba90405 100644 --- a/contrib/pools/main.php +++ b/contrib/pools/main.php @@ -284,7 +284,7 @@ class Pools extends SimpleExtension { ", array($poolsPerPage, $pageNumber * $poolsPerPage) ); - $totalPages = ceil($database->db->GetOne("SELECT COUNT(*) FROM pools") / $poolsPerPage); + $totalPages = ceil($database->get_one("SELECT COUNT(*) FROM pools") / $poolsPerPage); $this->theme->list_pools($page, $pools, $pageNumber + 1, $totalPages); } @@ -372,7 +372,7 @@ class Pools extends SimpleExtension { } if(!strlen($images) == 0) { - $count = $database->db->GetOne("SELECT COUNT(*) FROM pool_images WHERE pool_id=?", array($poolID)); + $count = $database->get_one("SELECT COUNT(*) FROM pool_images WHERE pool_id=?", array($poolID)); $this->add_history($poolID, 1, $images, $count); } @@ -418,7 +418,7 @@ class Pools extends SimpleExtension { $images .= " ".$imageID; } - $count = $database->db->GetOne("SELECT COUNT(*) FROM pool_images WHERE pool_id=?", array($poolID)); + $count = $database->get_one("SELECT COUNT(*) FROM pool_images WHERE pool_id=?", array($poolID)); $this->add_history($poolID, 0, $images, $count); return $poolID; } @@ -430,7 +430,7 @@ class Pools extends SimpleExtension { */ private function check_post($poolID, $imageID) { global $database; - $result = $database->db->GetOne("SELECT COUNT(*) FROM pool_images WHERE pool_id=? AND image_id=?", array($poolID, $imageID)); + $result = $database->get_one("SELECT COUNT(*) FROM pool_images WHERE pool_id=? AND image_id=?", array($poolID, $imageID)); return ($result != 0); } @@ -467,7 +467,7 @@ class Pools extends SimpleExtension { LIMIT ? OFFSET ?", array($poolID, $imagesPerPage, $pageNumber * $imagesPerPage)); - $totalPages = ceil($database->db->GetOne(" + $totalPages = ceil($database->get_one(" SELECT COUNT(*) FROM pool_images AS p INNER JOIN images AS i ON i.id = p.image_id @@ -482,7 +482,7 @@ class Pools extends SimpleExtension { ORDER BY image_order ASC LIMIT ? OFFSET ?", array($poolID, $imagesPerPage, $pageNumber * $imagesPerPage)); - $totalPages = ceil($database->db->GetOne("SELECT COUNT(*) FROM pool_images WHERE pool_id=?", array($poolID)) / $imagesPerPage); + $totalPages = ceil($database->get_one("SELECT COUNT(*) FROM pool_images WHERE pool_id=?", array($poolID)) / $imagesPerPage); } $images = array(); @@ -604,7 +604,7 @@ class Pools extends SimpleExtension { LIMIT ? OFFSET ? ", array($historiesPerPage, $pageNumber * $historiesPerPage)); - $totalPages = ceil($database->db->GetOne("SELECT COUNT(*) FROM pool_history") / $historiesPerPage); + $totalPages = ceil($database->get_one("SELECT COUNT(*) FROM pool_history") / $historiesPerPage); $this->theme->show_history($history, $pageNumber + 1, $totalPages); } @@ -645,7 +645,7 @@ class Pools extends SimpleExtension { } } - $count = $database->db->GetOne("SELECT COUNT(*) FROM pool_images WHERE pool_id=?", array($poolID)); + $count = $database->get_one("SELECT COUNT(*) FROM pool_images WHERE pool_id=?", array($poolID)); $this->add_history($poolID, $newAction, $imageArray, $count); } } diff --git a/contrib/tag_history/main.php b/contrib/tag_history/main.php index 07999d93..47f0e19a 100644 --- a/contrib/tag_history/main.php +++ b/contrib/tag_history/main.php @@ -213,11 +213,11 @@ class Tag_History implements Extension { // if needed remove oldest one if($allowed == -1) return; - $entries = $database->db->GetOne("SELECT COUNT(*) FROM tag_histories WHERE image_id = ?", array($image->id)); + $entries = $database->get_one("SELECT COUNT(*) FROM tag_histories WHERE image_id = ?", array($image->id)); if($entries > $allowed) { // TODO: Make these queries better - $min_id = $database->db->GetOne("SELECT MIN(id) FROM tag_histories WHERE image_id = ?", array($image->id)); + $min_id = $database->get_one("SELECT MIN(id) FROM tag_histories WHERE image_id = ?", array($image->id)); $database->execute("DELETE FROM tag_histories WHERE id = ?", array($min_id)); } } diff --git a/contrib/wiki/main.php b/contrib/wiki/main.php index 2955e4e9..3b66f6bb 100644 --- a/contrib/wiki/main.php +++ b/contrib/wiki/main.php @@ -198,7 +198,7 @@ class Wiki extends SimpleExtension { private function get_page($title, $revision=-1) { global $database; // first try and get the actual page - $row = $database->db->GetRow(" + $row = $database->get_row(" SELECT * FROM wiki_pages WHERE title LIKE ? @@ -206,7 +206,7 @@ class Wiki extends SimpleExtension { // fall back to wiki:default if(empty($row)) { - $row = $database->db->GetRow(" + $row = $database->get_row(" SELECT * FROM wiki_pages WHERE title LIKE ? diff --git a/core/imageboard.pack.php b/core/imageboard.pack.php index 73d0dfa9..8d6b2af4 100644 --- a/core/imageboard.pack.php +++ b/core/imageboard.pack.php @@ -79,7 +79,7 @@ class Image { assert(is_string($hash)); global $database; $image = null; - $row = $database->db->GetRow("SELECT images.* FROM images WHERE hash=:hash", array("hash"=>$hash)); + $row = $database->get_row("SELECT images.* FROM images WHERE hash=:hash", array("hash"=>$hash)); return ($row ? new Image($row) : null); } @@ -132,7 +132,7 @@ class Image { assert(is_array($tags)); global $database; if(count($tags) == 0) { - #return $database->db->GetOne("SELECT COUNT(*) FROM images"); + #return $database->get_one("SELECT COUNT(*) FROM images"); $total = $database->cache->get("image-count"); if(!$total) { $total = $database->get_one("SELECT COUNT(*) FROM images"); @@ -190,13 +190,13 @@ class Image { } if(count($tags) == 0) { - $row = $database->db->GetRow("SELECT images.* FROM images WHERE images.id $gtlt {$this->id} ORDER BY images.id $dir LIMIT 1"); + $row = $database->get_row("SELECT images.* FROM images WHERE images.id $gtlt {$this->id} ORDER BY images.id $dir LIMIT 1"); } else { $tags[] = "id$gtlt{$this->id}"; $querylet = Image::build_search_querylet($tags); $querylet->append_sql(" ORDER BY images.id $dir LIMIT 1"); - $row = $database->db->GetRow($querylet->sql, $querylet->variables); + $row = $database->get_row($querylet->sql, $querylet->variables); } return ($row ? new Image($row) : null); @@ -409,7 +409,7 @@ class Image { // insert each new tags foreach($tags as $tag) { - $id = $database->db->GetOne( + $id = $database->get_one( $database->engine->scoreql_to_sql( "SELECT id FROM tags WHERE SCORE_STRNORM(tag) = SCORE_STRNORM(:tag)" ), diff --git a/ext/alias_editor/main.php b/ext/alias_editor/main.php index a61d1275..0c46694b 100644 --- a/ext/alias_editor/main.php +++ b/ext/alias_editor/main.php @@ -67,12 +67,12 @@ class AliasEditor extends SimpleExtension { $alias_per_page = $config->get_int('alias_items_per_page', 30); - $query = "SELECT oldtag, newtag FROM aliases ORDER BY newtag ASC LIMIT ? OFFSET ?"; - $alias = $database->db->GetAssoc($query, - array($alias_per_page, $page_number * $alias_per_page) + $query = "SELECT oldtag, newtag FROM aliases ORDER BY newtag ASC LIMIT :limit OFFSET :offset"; + $alias = $database->get_pairs($query, + array("limit"=>$alias_per_page, "offset"=>$page_number * $alias_per_page) ); - $total_pages = ceil($database->db->GetOne("SELECT COUNT(*) FROM aliases") / $alias_per_page); + $total_pages = ceil($database->get_one("SELECT COUNT(*) FROM aliases") / $alias_per_page); $this->theme->display_aliases($page, $alias, $user->is_admin(), $page_number + 1, $total_pages); } @@ -104,7 +104,7 @@ class AliasEditor extends SimpleExtension { public function onAddAlias(AddAliasEvent $event) { global $database; $pair = array($event->oldtag, $event->newtag); - if($database->db->GetRow("SELECT * FROM aliases WHERE oldtag=? AND lower(newtag)=lower(?)", $pair)) { + if($database->get_row("SELECT * FROM aliases WHERE oldtag=? AND lower(newtag)=lower(?)", $pair)) { throw new AddAliasException("That alias already exists"); } else { diff --git a/ext/comment/main.php b/ext/comment/main.php index 9fcbfd4a..5d8c9a63 100644 --- a/ext/comment/main.php +++ b/ext/comment/main.php @@ -397,7 +397,7 @@ class CommentList extends SimpleExtension { private function is_dupe($image_id, $comment) { global $database; - return ($database->db->GetRow("SELECT * FROM comments WHERE image_id=? AND comment=?", array($image_id, $comment))); + return ($database->get_row("SELECT * FROM comments WHERE image_id=? AND comment=?", array($image_id, $comment))); } private function add_comment_wrapper($image_id, $user, $comment, $event) { diff --git a/ext/image/main.php b/ext/image/main.php index 5c4cad1d..7815649c 100644 --- a/ext/image/main.php +++ b/ext/image/main.php @@ -234,13 +234,20 @@ class ImageIO extends SimpleExtension { $database->Execute( "INSERT INTO images( owner_id, owner_ip, filename, filesize, - hash, ext, width, height, posted, source) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, now(), ?)", - array($user->id, $_SERVER['REMOTE_ADDR'], $image->filename, $image->filesize, - $image->hash, $image->ext, $image->width, $image->height, $image->source)); + hash, ext, width, height, posted, source + ) + VALUES ( + :owner_id, :owner_ip, :filename, :filesize, + :hash, :ext, :width, :height, now(), :source + )", + array( + "owner_id"=>$user->id, "owner_ip"=>$_SERVER['REMOTE_ADDR'], "filename"=>$image->filename, "filesize"=>$image->filesize, + "hash"=>$image->hash, "ext"=>$image->ext, "width"=>$image->width, "height"=>$image->height, "source"=>$image->source + ) + ); if($database->engine->name == "pgsql") { $database->Execute("UPDATE users SET image_count = image_count+1 WHERE id = ? ", array($user->id)); - $image->id = $database->db->GetOne("SELECT id FROM images WHERE hash=?", array($image->hash)); + $image->id = $database->get_one("SELECT id FROM images WHERE hash=?", array($image->hash)); } else { $image->id = $database->db->lastInsertId(); diff --git a/ext/user/main.php b/ext/user/main.php index 949d3609..d3eca23d 100644 --- a/ext/user/main.php +++ b/ext/user/main.php @@ -286,7 +286,7 @@ class UserPage extends SimpleExtension { "Username contains invalid characters. Allowed characters are ". "letters, numbers, dash, and underscore"); } - else if($database->db->GetRow("SELECT * FROM users WHERE name = ?", array($name))) { + else if($database->get_row("SELECT * FROM users WHERE name = ?", array($name))) { throw new UserCreationException("That username is already taken"); } } @@ -298,7 +298,7 @@ class UserPage extends SimpleExtension { $email = (!empty($event->email)) ? $event->email : null; // if there are currently no admins, the new user should be one - $need_admin = ($database->db->GetOne("SELECT COUNT(*) FROM users WHERE admin IN ('Y', 't', '1')") == 0); + $need_admin = ($database->get_one("SELECT COUNT(*) FROM users WHERE admin IN ('Y', 't', '1')") == 0); $admin = $need_admin ? 'Y' : 'N'; $database->Execute( @@ -427,28 +427,28 @@ class UserPage extends SimpleExtension { // ips {{{ private function count_upload_ips($duser) { global $database; - $rows = $database->db->GetAssoc(" + $rows = $database->get_pairs(" SELECT owner_ip, COUNT(images.id) AS count, MAX(posted) AS most_recent FROM images - WHERE owner_id=? + WHERE owner_id=:id GROUP BY owner_ip - ORDER BY most_recent DESC", array($duser->id), false, true); + ORDER BY most_recent DESC", array("id"=>$duser->id)); return $rows; } private function count_comment_ips($duser) { global $database; - $rows = $database->db->GetAssoc(" + $rows = $database->get_pairs(" SELECT owner_ip, COUNT(comments.id) AS count, MAX(posted) AS most_recent FROM comments - WHERE owner_id=? + WHERE owner_id=:id GROUP BY owner_ip - ORDER BY most_recent DESC", array($duser->id), false, true); + ORDER BY most_recent DESC", array("id"=>$duser->id)); return $rows; } // }}} From 2532091ae86ce95f31bdacdeaa799704c02d9063 Mon Sep 17 00:00:00 2001 From: Shish Date: Sat, 1 Jan 2011 16:59:10 +0000 Subject: [PATCH 14/16] PDO DSN handling (PS. PHP is retarded) --- core/database.class.php | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/core/database.class.php b/core/database.class.php index 0d4e3927..27603f93 100644 --- a/core/database.class.php +++ b/core/database.class.php @@ -273,12 +273,22 @@ class Database { public function Database() { global $database_dsn, $cache_dsn; - # FIXME: translate database URI into something PDO compatible - include "config.php"; - #$db_proto = $database_dsn; - #$db_host = $database_dsn; - #$db_name = $database_dsn; + # FIXME: detect ADODB URI, automatically translate PDO DSN + /* + * Why does the abstraction layer act differently depending on the + * back-end? Because PHP is deliberately retarded. + * + * http://stackoverflow.com/questions/237367 + */ + $matches = array(); $db_user=null; $db_pass=null; + if(preg_match("/user=([^;]*)/", $database_dsn, $matches)) $db_user=$matches[1]; + if(preg_match("/password=([^;]*)/", $database_dsn, $matches)) $db_pass=$matches[1]; + + $this->db = new PDO($database_dsn, $db_user, $db_pass); + $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + + $db_proto = $this->db->getAttribute(PDO::ATTR_DRIVER_NAME); if($db_proto == "mysql") { $this->engine = new MySQL(); } @@ -288,9 +298,9 @@ class Database { else if($db_proto == "sqlite") { $this->engine = new SQLite(); } - - $this->db = new PDO("$db_proto:host=$db_host;dbname=$db_name", $db_user, $db_pass); - $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); + else { + die("Unknown PDO driver: $db_proto"); + } if(isset($cache_dsn) && !empty($cache_dsn)) { $matches = array(); From 76286686e3f8672dd7ce6750229cc94b9c67c4d7 Mon Sep 17 00:00:00 2001 From: Shish Date: Sat, 1 Jan 2011 17:00:06 +0000 Subject: [PATCH 15/16] traces are appearing wrong --- index.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/index.php b/index.php index 4b04ef0f..588fccc5 100644 --- a/index.php +++ b/index.php @@ -136,7 +136,7 @@ try { catch(Exception $e) { $version = VERSION; $message = $e->getMessage(); - $trace = var_dump($e->getTrace()); + //$trace = var_dump($e->getTrace()); header("HTTP/1.0 500 Internal Error"); print << @@ -146,7 +146,6 @@ catch(Exception $e) {

Internal Error

$message -

$trace EOD; From 122885e2679da7d98e73a7ed141145edb81fa38f Mon Sep 17 00:00:00 2001 From: Shish Date: Sat, 1 Jan 2011 17:04:09 +0000 Subject: [PATCH 16/16] readme updates --- README.txt | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/README.txt b/README.txt index 5c99899d..c75d4230 100644 --- a/README.txt +++ b/README.txt @@ -39,9 +39,15 @@ Installation not, you should be given instructions on how to fix any errors~ -Upgrade from 2.2.X +Upgrade from 2.3.X ~~~~~~~~~~~~~~~~~~ -Should be automatic, just unzip into a clean folder and copy across +The database connection setting in config.php has changed; now using +PDO DSN format [1] rather than ADODB URI [2] + + [1] :user=;password=;host=;dbname= + [2] ://:@/ + +The rest should be automatic, just unzip into a clean folder and copy across config.php, images and thumbs folders from the old version. This includes automatically messing with the database -- back it up first! @@ -66,7 +72,7 @@ Contact ~~~~~~~ #shimmie on Freenode -- IRC webmaster at shishnet.org -- email -http://redmine.shishnet.org/projects/show/shimmie2 -- bug tracker +https://github.com/shish/shimmie2 -- bug tracker Licence