home *** CD-ROM | disk | FTP | other *** search
/ PC Professionell 2005 June / PCpro_2005_06.ISO / files / opensource / xamp / xampp-win32.exe / xampp / adodb-lib.inc.php < prev    next >
Encoding:
PHP Script  |  2005-01-24  |  28.2 KB  |  897 lines

  1. <?php
  2.  
  3. // security - hide paths
  4. if (!defined('ADODB_DIR')) die();
  5.  
  6. global $ADODB_INCLUDED_LIB;
  7. $ADODB_INCLUDED_LIB = 1;
  8.  
  9. /* 
  10.  @version V4.60 24 Jan 2005 (c) 2000-2005 John Lim (jlim\@natsoft.com.my). All rights reserved.
  11.   Released under both BSD license and Lesser GPL library license. 
  12.   Whenever there is any discrepancy between the two licenses, 
  13.   the BSD license will take precedence. See License.txt. 
  14.   Set tabs to 4 for best viewing.
  15.   
  16.   Less commonly used functions are placed here to reduce size of adodb.inc.php. 
  17. */ 
  18.  
  19.  
  20. // Force key to upper. 
  21. // See also http://www.php.net/manual/en/function.array-change-key-case.php
  22. function _array_change_key_case($an_array)
  23. {
  24.     if (is_array($an_array)) {
  25.         $new_array = array();
  26.         foreach($an_array as $key=>$value)
  27.             $new_array[strtoupper($key)] = $value;
  28.  
  29.            return $new_array;
  30.    }
  31.  
  32.     return $an_array;
  33. }
  34.  
  35. function _adodb_replace(&$zthis, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc)
  36. {
  37.         if (count($fieldArray) == 0) return 0;
  38.         $first = true;
  39.         $uSet = '';
  40.         
  41.         if (!is_array($keyCol)) {
  42.             $keyCol = array($keyCol);
  43.         }
  44.         foreach($fieldArray as $k => $v) {
  45.             if ($autoQuote && !is_numeric($v) and strncmp($v,"'",1) !== 0 and strcasecmp($v,'null')!=0) {
  46.                 $v = $zthis->qstr($v);
  47.                 $fieldArray[$k] = $v;
  48.             }
  49.             if (in_array($k,$keyCol)) continue; // skip UPDATE if is key
  50.             
  51.             if ($first) {
  52.                 $first = false;            
  53.                 $uSet = "$k=$v";
  54.             } else
  55.                 $uSet .= ",$k=$v";
  56.         }
  57.          
  58.         $where = false;
  59.         foreach ($keyCol as $v) {
  60.             if ($where) $where .= " and $v=$fieldArray[$v]";
  61.             else $where = "$v=$fieldArray[$v]";
  62.         }
  63.         
  64.         if ($uSet && $where) {
  65.             $update = "UPDATE $table SET $uSet WHERE $where";
  66.  
  67.             $rs = $zthis->Execute($update);
  68.             
  69.             
  70.             if ($rs) {
  71.                 if ($zthis->poorAffectedRows) {
  72.                 /*
  73.                  The Select count(*) wipes out any errors that the update would have returned. 
  74.                 http://phplens.com/lens/lensforum/msgs.php?id=5696
  75.                 */
  76.                     if ($zthis->ErrorNo()<>0) return 0;
  77.                     
  78.                 # affected_rows == 0 if update field values identical to old values
  79.                 # for mysql - which is silly. 
  80.             
  81.                     $cnt = $zthis->GetOne("select count(*) from $table where $where");
  82.                     if ($cnt > 0) return 1; // record already exists
  83.                 } else {
  84.                 
  85.                     if (($zthis->Affected_Rows()>0)) return 1;
  86.                 }
  87.             } else
  88.                 return 0;
  89.         }
  90.         
  91.     //    print "<p>Error=".$this->ErrorNo().'<p>';
  92.         $first = true;
  93.         foreach($fieldArray as $k => $v) {
  94.             if ($has_autoinc && in_array($k,$keyCol)) continue; // skip autoinc col
  95.             
  96.             if ($first) {
  97.                 $first = false;            
  98.                 $iCols = "$k";
  99.                 $iVals = "$v";
  100.             } else {
  101.                 $iCols .= ",$k";
  102.                 $iVals .= ",$v";
  103.             }                
  104.         }
  105.         $insert = "INSERT INTO $table ($iCols) VALUES ($iVals)"; 
  106.         $rs = $zthis->Execute($insert);
  107.         return ($rs) ? 2 : 0;
  108. }
  109.  
  110. // Requires $ADODB_FETCH_MODE = ADODB_FETCH_NUM
  111. function _adodb_getmenu(&$zthis, $name,$defstr='',$blank1stItem=true,$multiple=false,
  112.             $size=0, $selectAttr='',$compareFields0=true)
  113. {
  114.     $hasvalue = false;
  115.  
  116.     if ($multiple or is_array($defstr)) {
  117.         if ($size==0) $size=5;
  118.         $attr = ' multiple size="'.$size.'"';
  119.         if (!strpos($name,'[]')) $name .= '[]';
  120.     } else if ($size) $attr = ' size="'.$size.'"';
  121.     else $attr ='';
  122.     
  123.     $s = '<select name="'.$name.'"'.$attr.' '.$selectAttr.'>';
  124.     if ($blank1stItem) 
  125.         if (is_string($blank1stItem))  {
  126.             $barr = explode(':',$blank1stItem);
  127.             if (sizeof($barr) == 1) $barr[] = '';
  128.             $s .= "\n<option value=\"".$barr[0]."\">".$barr[1]."</option>";
  129.         } else $s .= "\n<option></option>";
  130.  
  131.     if ($zthis->FieldCount() > 1) $hasvalue=true;
  132.     else $compareFields0 = true;
  133.     
  134.     $value = '';
  135.     while(!$zthis->EOF) {
  136.         $zval = rtrim(reset($zthis->fields));
  137.         if (sizeof($zthis->fields) > 1) {
  138.             if (isset($zthis->fields[1]))
  139.                 $zval2 = rtrim($zthis->fields[1]);
  140.             else
  141.                 $zval2 = rtrim(next($zthis->fields));
  142.         }
  143.         $selected = ($compareFields0) ? $zval : $zval2;
  144.         
  145.         if ($blank1stItem && $zval=="") {
  146.             $zthis->MoveNext();
  147.             continue;
  148.         }
  149.         if ($hasvalue) 
  150.             $value = " value='".htmlspecialchars($zval2)."'";
  151.         
  152.         if (is_array($defstr))  {
  153.             
  154.             if (in_array($selected,$defstr)) 
  155.                 $s .= "<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
  156.             else 
  157.                 $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
  158.         }
  159.         else {
  160.             if (strcasecmp($selected,$defstr)==0) 
  161.                 $s .= "<option selected='selected'$value>".htmlspecialchars($zval).'</option>';
  162.             else
  163.                 $s .= "\n<option".$value.'>'.htmlspecialchars($zval).'</option>';
  164.         }
  165.         $zthis->MoveNext();
  166.     } // while
  167.     
  168.     return $s ."\n</select>\n";
  169. }
  170.  
  171. /*
  172.     Count the number of records this sql statement will return by using
  173.     query rewriting techniques...
  174.     
  175.     Does not work with UNIONs.
  176. */
  177. function _adodb_getcount(&$zthis, $sql,$inputarr=false,$secs2cache=0) 
  178. {
  179.     $qryRecs = 0;
  180.     
  181.      if (preg_match("/^\s*SELECT\s+DISTINCT/is", $sql) || preg_match('/\s+GROUP\s+BY\s+/is',$sql)) {
  182.         // ok, has SELECT DISTINCT or GROUP BY so see if we can use a table alias
  183.         // but this is only supported by oracle and postgresql...
  184.         if ($zthis->dataProvider == 'oci8') {
  185.             
  186.             $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);
  187.             
  188.             // Allow Oracle hints to be used for query optimization, Chris Wrye
  189.             if (preg_match('#/\\*+.*?\\*\\/#', $sql, $hint)) {
  190.                 $rewritesql = "SELECT ".$hint[0]." COUNT(*) FROM (".$rewritesql.")"; 
  191.             } else
  192.                 $rewritesql = "SELECT COUNT(*) FROM (".$rewritesql.")"; 
  193.             
  194.         } else if ( $zthis->databaseType == 'postgres' || $zthis->databaseType == 'postgres7')  {
  195.             
  196.             $info = $zthis->ServerInfo();
  197.             if (substr($info['version'],0,3) >= 7.1) { // good till version 999
  198.                 $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql);
  199.                 $rewritesql = "SELECT COUNT(*) FROM ($rewritesql) _ADODB_ALIAS_";
  200.             }
  201.         }
  202.     } else { 
  203.         // now replace SELECT ... FROM with SELECT COUNT(*) FROM
  204.         
  205.         $rewritesql = preg_replace(
  206.                     '/^\s*SELECT\s.*\s+FROM\s/Uis','SELECT COUNT(*) FROM ',$sql);
  207.         
  208.         // fix by alexander zhukov, alex#unipack.ru, because count(*) and 'order by' fails 
  209.         // with mssql, access and postgresql. Also a good speedup optimization - skips sorting!
  210.         $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$rewritesql); 
  211.     }
  212.     
  213.     if (isset($rewritesql) && $rewritesql != $sql) {
  214.         if ($secs2cache) {
  215.             // we only use half the time of secs2cache because the count can quickly
  216.             // become inaccurate if new records are added
  217.             $qryRecs = $zthis->CacheGetOne($secs2cache/2,$rewritesql,$inputarr);
  218.             
  219.         } else {
  220.             $qryRecs = $zthis->GetOne($rewritesql,$inputarr);
  221.           }
  222.         if ($qryRecs !== false) return $qryRecs;
  223.     }
  224.     //--------------------------------------------
  225.     // query rewrite failed - so try slower way...
  226.     
  227.     // strip off unneeded ORDER BY if no UNION
  228.     if (preg_match('/\s*UNION\s*/is', $sql)) $rewritesql = $sql;
  229.     else $rewritesql = preg_replace('/(\sORDER\s+BY\s.*)/is','',$sql); 
  230.     
  231.     $rstest = &$zthis->Execute($rewritesql,$inputarr);
  232.     if ($rstest) {
  233.               $qryRecs = $rstest->RecordCount();
  234.         if ($qryRecs == -1) { 
  235.         global $ADODB_EXTENSION;
  236.         // some databases will return -1 on MoveLast() - change to MoveNext()
  237.             if ($ADODB_EXTENSION) {
  238.                 while(!$rstest->EOF) {
  239.                     adodb_movenext($rstest);
  240.                 }
  241.             } else {
  242.                 while(!$rstest->EOF) {
  243.                     $rstest->MoveNext();
  244.                 }
  245.             }
  246.             $qryRecs = $rstest->_currentRow;
  247.         }
  248.         $rstest->Close();
  249.         if ($qryRecs == -1) return 0;
  250.     }
  251.     
  252.     return $qryRecs;
  253. }
  254.  
  255. /*
  256.      Code originally from "Cornel G" <conyg@fx.ro>
  257.  
  258.     This code will not work with SQL that has UNION in it    
  259.     
  260.     Also if you are using CachePageExecute(), there is a strong possibility that
  261.     data will get out of synch. use CachePageExecute() only with tables that
  262.     rarely change.
  263. */
  264. function &_adodb_pageexecute_all_rows(&$zthis, $sql, $nrows, $page, 
  265.                         $inputarr=false, $secs2cache=0) 
  266. {
  267.     $atfirstpage = false;
  268.     $atlastpage = false;
  269.     $lastpageno=1;
  270.  
  271.     // If an invalid nrows is supplied, 
  272.     // we assume a default value of 10 rows per page
  273.     if (!isset($nrows) || $nrows <= 0) $nrows = 10;
  274.  
  275.     $qryRecs = false; //count records for no offset
  276.     
  277.     $qryRecs = _adodb_getcount($zthis,$sql,$inputarr,$secs2cache);
  278.     $lastpageno = (int) ceil($qryRecs / $nrows);
  279.     $zthis->_maxRecordCount = $qryRecs;
  280.     
  281.  
  282.  
  283.     // ***** Here we check whether $page is the last page or 
  284.     // whether we are trying to retrieve 
  285.     // a page number greater than the last page number.
  286.     if ($page >= $lastpageno) {
  287.         $page = $lastpageno;
  288.         $atlastpage = true;
  289.     }
  290.     
  291.     // If page number <= 1, then we are at the first page
  292.     if (empty($page) || $page <= 1) {    
  293.         $page = 1;
  294.         $atfirstpage = true;
  295.     }
  296.     
  297.     // We get the data we want
  298.     $offset = $nrows * ($page-1);
  299.     if ($secs2cache > 0) 
  300.         $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
  301.     else 
  302.         $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
  303.  
  304.     
  305.     // Before returning the RecordSet, we set the pagination properties we need
  306.     if ($rsreturn) {
  307.         $rsreturn->_maxRecordCount = $qryRecs;
  308.         $rsreturn->rowsPerPage = $nrows;
  309.         $rsreturn->AbsolutePage($page);
  310.         $rsreturn->AtFirstPage($atfirstpage);
  311.         $rsreturn->AtLastPage($atlastpage);
  312.         $rsreturn->LastPageNo($lastpageno);
  313.     }
  314.     return $rsreturn;
  315. }
  316.  
  317. // Ivßn Oliva version
  318. function &_adodb_pageexecute_no_last_page(&$zthis, $sql, $nrows, $page, $inputarr=false, $secs2cache=0) 
  319. {
  320.  
  321.     $atfirstpage = false;
  322.     $atlastpage = false;
  323.     
  324.     if (!isset($page) || $page <= 1) {    // If page number <= 1, then we are at the first page
  325.         $page = 1;
  326.         $atfirstpage = true;
  327.     }
  328.     if ($nrows <= 0) $nrows = 10;    // If an invalid nrows is supplied, we assume a default value of 10 rows per page
  329.     
  330.     // ***** Here we check whether $page is the last page or whether we are trying to retrieve a page number greater than 
  331.     // the last page number.
  332.     $pagecounter = $page + 1;
  333.     $pagecounteroffset = ($pagecounter * $nrows) - $nrows;
  334.     if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
  335.     else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
  336.     if ($rstest) {
  337.         while ($rstest && $rstest->EOF && $pagecounter>0) {
  338.             $atlastpage = true;
  339.             $pagecounter--;
  340.             $pagecounteroffset = $nrows * ($pagecounter - 1);
  341.             $rstest->Close();
  342.             if ($secs2cache>0) $rstest = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $pagecounteroffset, $inputarr);
  343.             else $rstest = &$zthis->SelectLimit($sql, $nrows, $pagecounteroffset, $inputarr, $secs2cache);
  344.         }
  345.         if ($rstest) $rstest->Close();
  346.     }
  347.     if ($atlastpage) {    // If we are at the last page or beyond it, we are going to retrieve it
  348.         $page = $pagecounter;
  349.         if ($page == 1) $atfirstpage = true;    // We have to do this again in case the last page is the same as the first
  350.             //... page, that is, the recordset has only 1 page.
  351.     }
  352.     
  353.     // We get the data we want
  354.     $offset = $nrows * ($page-1);
  355.     if ($secs2cache > 0) $rsreturn = &$zthis->CacheSelectLimit($secs2cache, $sql, $nrows, $offset, $inputarr);
  356.     else $rsreturn = &$zthis->SelectLimit($sql, $nrows, $offset, $inputarr, $secs2cache);
  357.     
  358.     // Before returning the RecordSet, we set the pagination properties we need
  359.     if ($rsreturn) {
  360.         $rsreturn->rowsPerPage = $nrows;
  361.         $rsreturn->AbsolutePage($page);
  362.         $rsreturn->AtFirstPage($atfirstpage);
  363.         $rsreturn->AtLastPage($atlastpage);
  364.     }
  365.     return $rsreturn;
  366. }
  367.  
  368. function _adodb_getupdatesql(&$zthis,&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=2)
  369. {
  370.         if (!$rs) {
  371.             printf(ADODB_BAD_RS,'GetUpdateSQL');
  372.             return false;
  373.         }
  374.     
  375.         $fieldUpdatedCount = 0;
  376.         $arrFields = _array_change_key_case($arrFields);
  377.  
  378.         $hasnumeric = isset($rs->fields[0]);
  379.         $setFields = '';
  380.         
  381.         // Loop through all of the fields in the recordset
  382.         for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
  383.             // Get the field from the recordset
  384.             $field = $rs->FetchField($i);
  385.  
  386.             // If the recordset field is one
  387.             // of the fields passed in then process.
  388.             $upperfname = strtoupper($field->name);
  389.             if (adodb_key_exists($upperfname,$arrFields,$force)) {
  390.                 
  391.                 // If the existing field value in the recordset
  392.                 // is different from the value passed in then
  393.                 // go ahead and append the field name and new value to
  394.                 // the update query.
  395.                 
  396.                 if ($hasnumeric) $val = $rs->fields[$i];
  397.                 else if (isset($rs->fields[$upperfname])) $val = $rs->fields[$upperfname];
  398.                 else if (isset($rs->fields[$field->name])) $val =  $rs->fields[$field->name];
  399.                 else if (isset($rs->fields[strtolower($upperfname)])) $val =  $rs->fields[strtolower($upperfname)];
  400.                 else $val = '';
  401.                 
  402.             
  403.                 if ($forceUpdate || strcmp($val, $arrFields[$upperfname])) {
  404.                     // Set the counter for the number of fields that will be updated.
  405.                     $fieldUpdatedCount++;
  406.  
  407.                     // Based on the datatype of the field
  408.                     // Format the value properly for the database
  409.                     $type = $rs->MetaType($field->type);
  410.                         
  411.  
  412.                     if ($type == 'null') {
  413.                         $type = 'C';
  414.                     }
  415.                     
  416.                     if (strpos($upperfname,' ') !== false)
  417.                         $fnameq = $zthis->nameQuote.$upperfname.$zthis->nameQuote;
  418.                     else
  419.                         $fnameq = $upperfname;
  420.                     
  421.                     
  422.                 // is_null requires php 4.0.4
  423.                 //********************************************************//
  424.                 if (is_null($arrFields[$upperfname])
  425.                     || (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0)
  426.                     || $arrFields[$upperfname] === 'null'
  427.                     )
  428.                 {
  429.                     switch ($force) {
  430.  
  431.                         //case 0:
  432.                         //    //Ignore empty values. This is allready handled in "adodb_key_exists" function.
  433.                         //break;
  434.  
  435.                         case 1:
  436.                             //Set null
  437.                             $setFields .= $field->name . " = null, ";
  438.                         break;
  439.                             
  440.                         case 2:
  441.                             //Set empty
  442.                             $arrFields[$upperfname] = "";
  443.                             $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,$arrFields, $magicq);
  444.                         break;
  445.                         default:
  446.                         case 3:
  447.                             //Set the value that was given in array, so you can give both null and empty values
  448.                             if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === 'null') {
  449.                                 $setFields .= $field->name . " = null, ";
  450.                             } else {
  451.                                 $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,$arrFields, $magicq);
  452.                             }
  453.                         break;
  454.                     }
  455.                 //********************************************************//
  456.                 } else {
  457.                         //we do this so each driver can customize the sql for
  458.                         //DB specific column types. 
  459.                         //Oracle needs BLOB types to be handled with a returning clause
  460.                         //postgres has special needs as well
  461.                         $setFields .= _adodb_column_sql($zthis, 'U', $type, $upperfname, $fnameq,
  462.                                                           $arrFields, $magicq);
  463.                     }
  464.                 }
  465.             }
  466.         }
  467.  
  468.         // If there were any modified fields then build the rest of the update query.
  469.         if ($fieldUpdatedCount > 0 || $forceUpdate) {
  470.                     // Get the table name from the existing query.
  471.             preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName);
  472.     
  473.             // Get the full where clause excluding the word "WHERE" from
  474.             // the existing query.
  475.             preg_match('/\sWHERE\s(.*)/is', $rs->sql, $whereClause);
  476.             
  477.             $discard = false;
  478.             // not a good hack, improvements?
  479.             if ($whereClause) {
  480.                 if (preg_match('/\s(ORDER\s.*)/is', $whereClause[1], $discard));
  481.                 else if (preg_match('/\s(LIMIT\s.*)/is', $whereClause[1], $discard));
  482.                 else preg_match('/\s(FOR UPDATE.*)/is', $whereClause[1], $discard);
  483.             } else
  484.                 $whereClause = array(false,false);
  485.                 
  486.             if ($discard)
  487.                 $whereClause[1] = substr($whereClause[1], 0, strlen($whereClause[1]) - strlen($discard[1]));
  488.             
  489.         $sql = 'UPDATE '.$tableName[1].' SET '.substr($setFields, 0, -2);
  490.         if (strlen($whereClause[1]) > 0) 
  491.             $sql .= ' WHERE '.$whereClause[1];
  492.  
  493.         return $sql;
  494.  
  495.         } else {
  496.             return false;
  497.     }
  498. }
  499.  
  500. function adodb_key_exists($key, &$arr,$force=2)
  501. {
  502.     if ($force<=0) {
  503.         // the following is the old behaviour where null or empty fields are ignored
  504.         return (!empty($arr[$key])) || (isset($arr[$key]) && strlen($arr[$key])>0);
  505.     }
  506.  
  507.     if (isset($arr[$key])) return true;
  508.     ## null check below
  509.     if (ADODB_PHPVER >= 0x4010) return array_key_exists($key,$arr);
  510.     return false;
  511. }
  512.  
  513. /**
  514.  * There is a special case of this function for the oci8 driver.
  515.  * The proper way to handle an insert w/ a blob in oracle requires
  516.  * a returning clause with bind variables and a descriptor blob.
  517.  * 
  518.  * 
  519.  */
  520. function _adodb_getinsertsql(&$zthis,&$rs,$arrFields,$magicq=false,$force=2)
  521. {
  522. static $cacheRS = false;
  523. static $cacheSig = 0;
  524. static $cacheCols;
  525.  
  526.     $tableName = '';
  527.     $values = '';
  528.     $fields = '';
  529.     $recordSet = null;
  530.     $arrFields = _array_change_key_case($arrFields);
  531.     $fieldInsertedCount = 0;
  532.     
  533.     if (is_string($rs)) {
  534.         //ok we have a table name
  535.         //try and get the column info ourself.
  536.         $tableName = $rs;            
  537.     
  538.         //we need an object for the recordSet
  539.         //because we have to call MetaType.
  540.         //php can't do a $rsclass::MetaType()
  541.         $rsclass = $zthis->rsPrefix.$zthis->databaseType;
  542.         $recordSet =& new $rsclass(-1,$zthis->fetchMode);
  543.         $recordSet->connection = &$zthis;
  544.         
  545.         if (is_string($cacheRS) && $cacheRS == $rs) {
  546.             $columns =& $cacheCols;
  547.         } else {
  548.             $columns = $zthis->MetaColumns( $tableName );
  549.             $cacheRS = $tableName;
  550.             $cacheCols = $columns;
  551.         }
  552.     } else if (is_subclass_of($rs, 'adorecordset')) {
  553.         if (isset($rs->insertSig) && is_integer($cacheRS) && $cacheRS == $rs->insertSig) {
  554.             $columns =& $cacheCols;
  555.         } else {
  556.             for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) 
  557.                 $columns[] = $rs->FetchField($i);
  558.             $cacheRS = $cacheSig;
  559.             $cacheCols = $columns;
  560.             $rs->insertSig = $cacheSig++;
  561.         }
  562.         $recordSet =& $rs;
  563.     
  564.     } else {
  565.         printf(ADODB_BAD_RS,'GetInsertSQL');
  566.         return false;
  567.     }
  568.  
  569.     // Loop through all of the fields in the recordset
  570.     foreach( $columns as $field ) { 
  571.         $upperfname = strtoupper($field->name);
  572.         if (adodb_key_exists($upperfname,$arrFields,$force)) {
  573.             $bad = false;
  574.             if (strpos($upperfname,' ') !== false)
  575.                 $fnameq = $zthis->nameQuote.$upperfname.$zthis->nameQuote;
  576.             else
  577.                 $fnameq = $upperfname;
  578.             
  579.             $type = $recordSet->MetaType($field->type);
  580.             
  581.             /********************************************************/
  582.             if (is_null($arrFields[$upperfname])
  583.                 || (empty($arrFields[$upperfname]) && strlen($arrFields[$upperfname]) == 0)
  584.                 || $arrFields[$upperfname] === 'null'
  585.                 )
  586.                {
  587.                     switch ($force) {
  588.  
  589.                         case 0: // we must always set null if missing
  590.                             $bad = true;
  591.                             break;
  592.                             
  593.                         case 1:
  594.                             $values  .= "null, ";
  595.                         break;
  596.         
  597.                         case 2:
  598.                             //Set empty
  599.                             $arrFields[$upperfname] = "";
  600.                             $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq,$arrFields, $magicq);
  601.                         break;
  602.  
  603.                         default:
  604.                         case 3:
  605.                             //Set the value that was given in array, so you can give both null and empty values
  606.                             if (is_null($arrFields[$upperfname]) || $arrFields[$upperfname] === 'null') { 
  607.                                 $values  .= "null, ";
  608.                             } else {
  609.                                 $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq, $arrFields, $magicq);
  610.                              }
  611.                           break;
  612.                      } // switch
  613.  
  614.             /*********************************************************/
  615.             } else {
  616.                 //we do this so each driver can customize the sql for
  617.                 //DB specific column types. 
  618.                 //Oracle needs BLOB types to be handled with a returning clause
  619.                 //postgres has special needs as well
  620.                 $values .= _adodb_column_sql($zthis, 'I', $type, $upperfname, $fnameq,
  621.                                                $arrFields, $magicq);
  622.             }
  623.             
  624.             if ($bad) continue;
  625.             // Set the counter for the number of fields that will be inserted.
  626.             $fieldInsertedCount++;
  627.             
  628.             
  629.             // Get the name of the fields to insert
  630.             $fields .= $fnameq . ", ";
  631.         }
  632.     }
  633.  
  634.  
  635.     // If there were any inserted fields then build the rest of the insert query.
  636.     if ($fieldInsertedCount <= 0)  return false;
  637.     
  638.     // Get the table name from the existing query.
  639.     if (!$tableName) {
  640.         if (preg_match("/FROM\s+".ADODB_TABLE_REGEX."/is", $rs->sql, $tableName))
  641.             $tableName = $tableName[1];
  642.         else 
  643.             return false;
  644.     }        
  645.  
  646.     // Strip off the comma and space on the end of both the fields
  647.     // and their values.
  648.     $fields = substr($fields, 0, -2);
  649.     $values = substr($values, 0, -2);
  650.  
  651.     // Append the fields and their values to the insert query.
  652.     return 'INSERT INTO '.$tableName.' ( '.$fields.' ) VALUES ( '.$values.' )';
  653. }
  654.  
  655.  
  656. /**
  657.  * This private method is used to help construct
  658.  * the update/sql which is generated by GetInsertSQL and GetUpdateSQL.
  659.  * It handles the string construction of 1 column -> sql string based on
  660.  * the column type.  We want to do 'safe' handling of BLOBs
  661.  * 
  662.  * @param string the type of sql we are trying to create
  663.  *                'I' or 'U'. 
  664.  * @param string column data type from the db::MetaType() method  
  665.  * @param string the column name
  666.  * @param array the column value
  667.  * 
  668.  * @return string
  669.  * 
  670.  */
  671. function _adodb_column_sql_oci8(&$zthis,$action, $type, $fname, $fnameq, $arrFields, $magicq) 
  672. {
  673.     $sql = '';
  674.     
  675.     // Based on the datatype of the field
  676.     // Format the value properly for the database
  677.     switch($type) {
  678.     case 'B':
  679.         //in order to handle Blobs correctly, we need
  680.         //to do some magic for Oracle
  681.  
  682.         //we need to create a new descriptor to handle 
  683.         //this properly
  684.         if (!empty($zthis->hasReturningInto)) {
  685.             if ($action == 'I') {
  686.                 $sql = 'empty_blob(), ';
  687.             } else {
  688.                 $sql = $fnameq. '=empty_blob(), ';
  689.             }
  690.             //add the variable to the returning clause array
  691.             //so the user can build this later in
  692.             //case they want to add more to it
  693.             $zthis->_returningArray[$fname] = ':xx'.$fname.'xx';
  694.         } else if (empty($arrFields[$fname])){
  695.             if ($action == 'I') {
  696.                 $sql = 'empty_blob(), ';
  697.             } else {
  698.                 $sql = $fnameq. '=empty_blob(), ';
  699.             }            
  700.         } else {
  701.             //this is to maintain compatibility
  702.             //with older adodb versions.
  703.             $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false);
  704.         }
  705.         break;
  706.  
  707.     case "X":
  708.         //we need to do some more magic here for long variables
  709.         //to handle these correctly in oracle.
  710.  
  711.         //create a safe bind var name
  712.         //to avoid conflicts w/ dupes.
  713.        if (!empty($zthis->hasReturningInto)) {
  714.             if ($action == 'I') {
  715.                 $sql = ':xx'.$fname.'xx, ';                
  716.             } else {
  717.                 $sql = $fnameq.'=:xx'.$fname.'xx, ';
  718.             }
  719.             //add the variable to the returning clause array
  720.             //so the user can build this later in
  721.             //case they want to add more to it
  722.             $zthis->_returningArray[$fname] = ':xx'.$fname.'xx';
  723.         } else {
  724.             //this is to maintain compatibility
  725.             //with older adodb versions.
  726.             $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq,false);
  727.         }            
  728.         break;
  729.         
  730.     default:
  731.         $sql = _adodb_column_sql($zthis, $action, $type, $fname, $fnameq,  $arrFields, $magicq,false);
  732.         break;
  733.     }
  734.     
  735.     return $sql;
  736. }    
  737.     
  738. function _adodb_column_sql(&$zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq, $recurse=true) 
  739. {
  740.  
  741.     if ($recurse) {
  742.         switch($zthis->dataProvider)  {
  743.         case 'postgres':
  744.             if ($type == 'L') $type = 'C';
  745.             break;
  746.         case 'oci8':
  747.             return _adodb_column_sql_oci8($zthis, $action, $type, $fname, $fnameq, $arrFields, $magicq);
  748.             
  749.         }
  750.     }
  751.     
  752.     $sql = '';
  753.         
  754.     switch($type) {
  755.         case "C":
  756.         case "X":
  757.         case 'B':
  758.             if ($action == 'I') {
  759.                 $sql = $zthis->qstr($arrFields[$fname],$magicq) . ", ";
  760.             } else {
  761.                 $sql .= $fnameq . "=" . $zthis->qstr($arrFields[$fname],$magicq) . ", ";
  762.             }
  763.           break;
  764.  
  765.         case "D":
  766.             if ($action == 'I') {
  767.                 $sql = $zthis->DBDate($arrFields[$fname]) . ", ";
  768.             } else {
  769.                 $sql .= $fnameq . "=" . $zthis->DBDate($arrFields[$fname]) . ", ";
  770.             }
  771.             break;
  772.  
  773.         case "T":
  774.             if ($action == 'I') {
  775.                 $sql = $zthis->DBTimeStamp($arrFields[$fname]) . ", ";
  776.             } else {
  777.                 $sql .= $fnameq . "=" . $zthis->DBTimeStamp($arrFields[$fname]) . ", ";
  778.             }
  779.             break;
  780.  
  781.         default:
  782.             $val = $arrFields[$fname];
  783.             if (empty($val)) $val = '0';
  784.  
  785.  
  786.             if ($action == 'I') {
  787.                 $sql .= $val . ", ";
  788.             } else {
  789.                 $sql .= $fnameq . "=" . $val  . ", ";
  790.             }
  791.             break;
  792.     }
  793.  
  794.     return $sql;
  795. }
  796.  
  797.  
  798.  
  799. function _adodb_debug_execute(&$zthis, $sql, $inputarr)
  800. {
  801. global $HTTP_SERVER_VARS;
  802.  
  803.     $ss = '';
  804.     if ($inputarr) {
  805.         foreach($inputarr as $kk=>$vv) {
  806.             if (is_string($vv) && strlen($vv)>64) $vv = substr($vv,0,64).'...';
  807.             $ss .= "($kk=>'$vv') ";
  808.         }
  809.         $ss = "[ $ss ]";
  810.     }
  811.     $sqlTxt = str_replace(',',', ',is_array($sql) ? $sql[0] : $sql);
  812.  
  813.     // check if running from browser or command-line
  814.     $inBrowser = isset($HTTP_SERVER_VARS['HTTP_USER_AGENT']);
  815.     
  816.     if ($inBrowser) {
  817.         $ss = htmlspecialchars($ss);
  818.         if ($zthis->debug === -1)
  819.             ADOConnection::outp( "<br>\n($zthis->databaseType): ".htmlspecialchars($sqlTxt)."   <code>$ss</code>\n<br>\n",false);
  820.         else 
  821.             ADOConnection::outp( "<hr>\n($zthis->databaseType): ".htmlspecialchars($sqlTxt)."   <code>$ss</code>\n<hr>\n",false);
  822.     } else {
  823.         ADOConnection::outp("-----\n($zthis->databaseType): ".$sqlTxt."\n-----\n",false);
  824.     }
  825.     
  826.     $qID = $zthis->_query($sql,$inputarr);
  827.     
  828.     /* 
  829.         Alexios Fakios notes that ErrorMsg() must be called before ErrorNo() for mssql
  830.         because ErrorNo() calls Execute('SELECT @ERROR'), causing recursion
  831.     */
  832.     if ($zthis->databaseType == 'mssql') { 
  833.     // ErrorNo is a slow function call in mssql, and not reliable in PHP 4.0.6
  834.         if($emsg = $zthis->ErrorMsg()) {
  835.             if ($err = $zthis->ErrorNo()) ADOConnection::outp($err.': '.$emsg);
  836.         }
  837.     } else if (!$qID) {
  838.         ADOConnection::outp($zthis->ErrorNo() .': '. $zthis->ErrorMsg());
  839.     }
  840.     
  841.     return $qID;
  842. }
  843.  
  844.  
  845. function _adodb_backtrace($printOrArr=true,$levels=9999)
  846. {
  847.     if (PHPVERSION() < 4.3) return '';
  848.      
  849.     $html =  (isset($_SERVER['HTTP_USER_AGENT']));
  850.     $fmt =  ($html) ? "</font><font color=#808080 size=-1> %% line %4d, file: <a href=\"file:/%s\">%s</a></font>" : "%% line %4d, file: %s";
  851.  
  852.     $MAXSTRLEN = 128;
  853.  
  854.     $s = ($html) ? '<pre align=left>' : '';
  855.     
  856.     if (is_array($printOrArr)) $traceArr = $printOrArr;
  857.     else $traceArr = debug_backtrace();
  858.     array_shift($traceArr);
  859.     array_shift($traceArr);
  860.     $tabs = sizeof($traceArr)-2;
  861.     
  862.     foreach ($traceArr as $arr) {
  863.         $levels -= 1;
  864.         if ($levels < 0) break;
  865.         
  866.         $args = array();
  867.         for ($i=0; $i < $tabs; $i++) $s .=  ($html) ? '   ' : "\t";
  868.         $tabs -= 1;
  869.         if ($html) $s .= '<font face="Courier New,Courier">';
  870.         if (isset($arr['class'])) $s .= $arr['class'].'.';
  871.         if (isset($arr['args']))
  872.          foreach($arr['args'] as $v) {
  873.             if (is_null($v)) $args[] = 'null';
  874.             else if (is_array($v)) $args[] = 'Array['.sizeof($v).']';
  875.             else if (is_object($v)) $args[] = 'Object:'.get_class($v);
  876.             else if (is_bool($v)) $args[] = $v ? 'true' : 'false';
  877.             else {
  878.                 $v = (string) @$v;
  879.                 $str = htmlspecialchars(substr($v,0,$MAXSTRLEN));
  880.                 if (strlen($v) > $MAXSTRLEN) $str .= '...';
  881.                 $args[] = $str;
  882.             }
  883.         }
  884.         $s .= $arr['function'].'('.implode(', ',$args).')';
  885.         
  886.         
  887.         $s .= @sprintf($fmt, $arr['line'],$arr['file'],basename($arr['file']));
  888.             
  889.         $s .= "\n";
  890.     }    
  891.     if ($html) $s .= '</pre>';
  892.     if ($printOrArr) print $s;
  893.     
  894.     return $s;
  895. }
  896.  
  897. ?>