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;
// If an invalid nrows is supplied,
// we assume a default value of 10 rows per page
if (!isset($nrows) || $nrows <= 0) $nrows = 10;
$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) {
// If an invalid nrows is supplied, we assume a default value of 10 rows per page
$nrows = 10;
}
$pagecounteroffset = ($page * $nrows) - $nrows;
// To find out if there are more pages of rows, simply increase the limit or
// nrows by 1 and see if that number of records was returned. If it was,
// then we know there is at least one more page left, otherwise we are on
// the last page. Therefore allow non-Count() paging with single queries
// rather than three queries as was done before.
$test_nrows = $nrows + 1;
if ($secs2cache > 0) {
$rsreturn = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
} else {
$rsreturn = $zthis->SelectLimit($sql, $test_nrows, $pagecounteroffset, $inputarr, $secs2cache);
}
// Now check to see if the number of rows returned was the higher value we asked for or not.
if ( $rsreturn->_numOfRows == $test_nrows ) {
// Still at least 1 more row, so we are not on last page yet...
// Remove the last row from the RS.
$rsreturn->_numOfRows = ( $rsreturn->_numOfRows - 1 );
} elseif ( $rsreturn->_numOfRows == 0 && $page > 1 ) {
// Likely requested a page that doesn't exist, so need to find the last
// page and return it. Revert to original method and loop through pages
// until we find some data...
$pagecounter = $page + 1;
$rstest = $rsreturn;
if ($rstest) {
while ($rstest && $rstest->EOF && $pagecounter > 0) {
$atlastpage = true;
$pagecounter--;
$pagecounteroffset = $nrows * ($pagecounter - 1);
$rstest->Close();
if ($secs2cache>0) {
$rstest = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
}
else {
$rstest = $zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
}
}
if ($rstest) $rstest->Close();
}
if ($atlastpage) {
// If we are at the last page or beyond it, we are going to retrieve it
$page = $pagecounter;
if ($page == 1) {
// We have to do this again in case the last page is the same as
// the first page, that is, the recordset has only 1 page.
$atfirstpage = true;
}
}
// We get the data we want
$offset = $nrows * ($page-1);
if ($secs2cache > 0) {
$rsreturn = $zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
}
else {
$rsreturn = $zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
}
} elseif ( $rsreturn->_numOfRows < $test_nrows ) {
// Rows is less than what we asked for, so must be at the last page.
$atlastpage = true;
}
// Before returning the RecordSet, we set the pagination properties we need
if ($rsreturn) {
$rsreturn->rowsPerPage = $nrows;
$rsreturn->AbsolutePage($page);
$rsreturn->AtFirstPage($atfirstpage);
$rsreturn->AtLastPage($atlastpage);
}
return $rsreturn;
}
/**
* Performs case conversion and quoting of the given field name.
*
* See Global variable $ADODB_QUOTE_FIELDNAMES.
*
* @param ADOConnection $zthis
* @param string $fieldName
*
* @return string Quoted field name
*/
function _adodb_quote_fieldname($zthis, $fieldName)
{
global $ADODB_QUOTE_FIELDNAMES;
// Case conversion - defaults to UPPER
$case = is_bool($ADODB_QUOTE_FIELDNAMES) ? 'UPPER' : $ADODB_QUOTE_FIELDNAMES;
switch ($case) {
case 'LOWER':
$fieldName = strtolower($fieldName);
break;
case 'NATIVE':
// Do nothing
break;
case 'UPPER':
case 'BRACKETS':
default:
$fieldName = strtoupper($fieldName);
break;
}
// Quote field if requested, or necessary (field contains space)
if ($ADODB_QUOTE_FIELDNAMES || strpos($fieldName, ' ') !== false ) {
if ($ADODB_QUOTE_FIELDNAMES === 'BRACKETS') {
return $zthis->leftBracket . $fieldName . $zthis->rightBracket;
} else {
return $zthis->nameQuote . $fieldName . $zthis->nameQuote;
}
} else {
return $fieldName;
}
}
function _adodb_getupdatesql(&$zthis, $rs, $arrFields, $forceUpdate=false, $force=2)
{
if (!$rs) {
printf(ADODB_BAD_RS,'GetUpdateSQL');
return false;
}
$fieldUpdatedCount = 0;
if (is_array($arrFields))
$arrFields = array_change_key_case($arrFields,CASE_UPPER);
$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 || $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';
}
$fnameq = _adodb_quote_fieldname($zthis, $field->name);
//********************************************************//
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 already handled in "adodb_key_exists" function.
// break;
case 1:
// set null
$setFields .= $fnameq . " = null, ";
break;
case 2:
// set empty
$arrFields[$upperfname] = "";
$setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq, $arrFields);
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 .= $fnameq . " = null, ";
} else {
$setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq, $arrFields);
}
break;
case ADODB_FORCE_NULL_AND_ZERO:
switch ($type) {
case 'N':
case 'I':
case 'L':
$setFields .= $fnameq . ' = 0, ';
break;
default:
$setFields .= $fnameq . ' = null, ';
break;
}
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);
}
}
}
}
// 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) {
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 https://sourceforge.net/p/adodb/bugs/37/
} 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
return array_key_exists($key,$arr);
}
/**
* 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, $force=2)
{
static $cacheRS = false;
static $cacheSig = 0;
static $cacheCols;
$tableName = '';
$values = '';
$fields = '';
if (is_array($arrFields))
$arrFields = array_change_key_case($arrFields,CASE_UPPER);
$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(ADORecordSet::DUMMY_QUERY_ID, $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 {
$columns = [];
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;
$fnameq = _adodb_quote_fieldname($zthis, $field->name);
$type = $recordSet->MetaType($field->type);
/********************************************************/
if (is_null($arrFields[$upperfname])
|| (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0)
|| $arrFields[$upperfname] === $zthis->null2null
) {
switch ($force) {
case ADODB_FORCE_IGNORE: // we must always set null if missing
$bad = true;
break;
case ADODB_FORCE_NULL:
$values .= "null, ";
break;
case ADODB_FORCE_EMPTY:
//Set empty
$arrFields[$upperfname] = "";
$values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq, $arrFields);
break;
default:
case ADODB_FORCE_VALUE:
//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);
}
break;
case ADODB_FORCE_NULL_AND_ZERO:
switch ($type) {
case 'N':
case 'I':
case 'L':
$values .= '0, ';
break;
default:
$values .= "null, ";
break;
}
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);
}
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)
{
// 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, 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, false);
}
break;
default:
$sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, false);
break;
}
return $sql;
}
function _adodb_column_sql(&$zthis, $action, $type, $fname, $fnameq, $arrFields, $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);
}
}
switch($type) {
case "C":
case "X":
case 'B':
$val = $zthis->qstr($arrFields[$fname]);
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
{
if (is_array($vv))
{
$vv = sprintf("Array Of Values: [%s]", implode(',',$vv));
}
$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();
$s .= str_repeat($html ? ' ' : "\t", $tabs >= 0 ? $tabs : 0 );
$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;
}