home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2008 February / PCWFEB08.iso / Software / Resources / Developers / XAMPP 1.5.4 / Windows installer / xampp-win32-1.5.4-installer.exe / xampp / php / pear / adodb / adodb.inc.php < prev    next >
Encoding:
PHP Script  |  2006-08-02  |  114.5 KB  |  4,106 lines

  1. <?php 
  2. /*
  3.  * Set tabs to 4 for best viewing.
  4.  * 
  5.  * Latest version is available at http://adodb.sourceforge.net
  6.  * 
  7.  * This is the main include file for ADOdb.
  8.  * Database specific drivers are stored in the adodb/drivers/adodb-*.inc.php
  9.  *
  10.  * The ADOdb files are formatted so that doxygen can be used to generate documentation.
  11.  * Doxygen is a documentation generation tool and can be downloaded from http://doxygen.org/
  12.  */
  13.  
  14. /**
  15.     \mainpage     
  16.     
  17.      @version V4.91 2 Aug 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved.
  18.  
  19.     Released under both BSD license and Lesser GPL library license. You can choose which license
  20.     you prefer.
  21.     
  22.     PHP's database access functions are not standardised. This creates a need for a database 
  23.     class library to hide the differences between the different database API's (encapsulate 
  24.     the differences) so we can easily switch databases.
  25.  
  26.     We currently support MySQL, Oracle, Microsoft SQL Server, Sybase, Sybase SQL Anywhere, DB2,
  27.     Informix, PostgreSQL, FrontBase, Interbase (Firebird and Borland variants), Foxpro, Access,
  28.     ADO, SAP DB, SQLite and ODBC. We have had successful reports of connecting to Progress and
  29.     other databases via ODBC.
  30.  
  31.     Latest Download at http://adodb.sourceforge.net/
  32.       
  33.  */
  34.  
  35.  if (!defined('_ADODB_LAYER')) {
  36.      define('_ADODB_LAYER',1);
  37.     
  38.     //==============================================================================================    
  39.     // CONSTANT DEFINITIONS
  40.     //==============================================================================================    
  41.  
  42.  
  43.     /** 
  44.      * Set ADODB_DIR to the directory where this file resides...
  45.      * This constant was formerly called $ADODB_RootPath
  46.      */
  47.     if (!defined('ADODB_DIR')) define('ADODB_DIR',dirname(__FILE__));
  48.     
  49.     //==============================================================================================    
  50.     // GLOBAL VARIABLES
  51.     //==============================================================================================    
  52.  
  53.     GLOBAL 
  54.         $ADODB_vers,         // database version
  55.         $ADODB_COUNTRECS,    // count number of records returned - slows down query
  56.         $ADODB_CACHE_DIR,    // directory to cache recordsets
  57.         $ADODB_EXTENSION,   // ADODB extension installed
  58.         $ADODB_COMPAT_FETCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF
  59.          $ADODB_FETCH_MODE;    // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...
  60.     
  61.     //==============================================================================================    
  62.     // GLOBAL SETUP
  63.     //==============================================================================================    
  64.     
  65.     $ADODB_EXTENSION = defined('ADODB_EXTENSION');
  66.     
  67.     //********************************************************//
  68.     /*
  69.     Controls $ADODB_FORCE_TYPE mode. Default is ADODB_FORCE_VALUE (3).
  70.     Used in GetUpdateSql and GetInsertSql functions. Thx to Niko, nuko#mbnet.fi
  71.  
  72.          0 = ignore empty fields. All empty fields in array are ignored.
  73.         1 = force null. All empty, php null and string 'null' fields are changed to sql NULL values.
  74.         2 = force empty. All empty, php null and string 'null' fields are changed to sql empty '' or 0 values.
  75.         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.
  76.     */
  77.         define('ADODB_FORCE_IGNORE',0);
  78.         define('ADODB_FORCE_NULL',1);
  79.         define('ADODB_FORCE_EMPTY',2);
  80.         define('ADODB_FORCE_VALUE',3);
  81.     //********************************************************//
  82.  
  83.  
  84.     if (!$ADODB_EXTENSION || ADODB_EXTENSION < 4.0) {
  85.         
  86.         define('ADODB_BAD_RS','<p>Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;</p>');
  87.     
  88.     // allow [ ] @ ` " and . in table names
  89.         define('ADODB_TABLE_REGEX','([]0-9a-z_\:\"\`\.\@\[-]*)');
  90.     
  91.     // prefetching used by oracle
  92.         if (!defined('ADODB_PREFETCH_ROWS')) define('ADODB_PREFETCH_ROWS',10);
  93.     
  94.     
  95.     /*
  96.     Controls ADODB_FETCH_ASSOC field-name case. Default is 2, use native case-names.
  97.     This currently works only with mssql, odbc, oci8po and ibase derived drivers.
  98.     
  99.          0 = assoc lowercase field names. $rs->fields['orderid']
  100.         1 = assoc uppercase field names. $rs->fields['ORDERID']
  101.         2 = use native-case field names. $rs->fields['OrderID']
  102.     */
  103.     
  104.         define('ADODB_FETCH_DEFAULT',0);
  105.         define('ADODB_FETCH_NUM',1);
  106.         define('ADODB_FETCH_ASSOC',2);
  107.         define('ADODB_FETCH_BOTH',3);
  108.         
  109.         if (!defined('TIMESTAMP_FIRST_YEAR')) define('TIMESTAMP_FIRST_YEAR',100);
  110.     
  111.         // PHP's version scheme makes converting to numbers difficult - workaround
  112.         $_adodb_ver = (float) PHP_VERSION;
  113.         if ($_adodb_ver >= 5.0) {
  114.             define('ADODB_PHPVER',0x5000);
  115.         } else if ($_adodb_ver > 4.299999) { # 4.3
  116.             define('ADODB_PHPVER',0x4300);
  117.         } else if ($_adodb_ver > 4.199999) { # 4.2
  118.             define('ADODB_PHPVER',0x4200);
  119.         } else if (strnatcmp(PHP_VERSION,'4.0.5')>=0) {
  120.             define('ADODB_PHPVER',0x4050);
  121.         } else {
  122.             define('ADODB_PHPVER',0x4000);
  123.         }
  124.     }
  125.     
  126.     //if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
  127.  
  128.     
  129.     /**
  130.          Accepts $src and $dest arrays, replacing string $data
  131.     */
  132.     function ADODB_str_replace($src, $dest, $data)
  133.     {
  134.         if (ADODB_PHPVER >= 0x4050) return str_replace($src,$dest,$data);
  135.         
  136.         $s = reset($src);
  137.         $d = reset($dest);
  138.         while ($s !== false) {
  139.             $data = str_replace($s,$d,$data);
  140.             $s = next($src);
  141.             $d = next($dest);
  142.         }
  143.         return $data;
  144.     }
  145.     
  146.     function ADODB_Setup()
  147.     {
  148.     GLOBAL 
  149.         $ADODB_vers,         // database version
  150.         $ADODB_COUNTRECS,    // count number of records returned - slows down query
  151.         $ADODB_CACHE_DIR,    // directory to cache recordsets
  152.          $ADODB_FETCH_MODE,
  153.         $ADODB_FORCE_TYPE;
  154.         
  155.         $ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT;
  156.         $ADODB_FORCE_TYPE = ADODB_FORCE_VALUE;
  157.  
  158.  
  159.         if (!isset($ADODB_CACHE_DIR)) {
  160.             $ADODB_CACHE_DIR = '/tmp'; //(isset($_ENV['TMP'])) ? $_ENV['TMP'] : '/tmp';
  161.         } else {
  162.             // do not accept url based paths, eg. http:/ or ftp:/
  163.             if (strpos($ADODB_CACHE_DIR,'://') !== false) 
  164.                 die("Illegal path http:// or ftp://");
  165.         }
  166.         
  167.             
  168.         // Initialize random number generator for randomizing cache flushes
  169.         srand(((double)microtime())*1000000);
  170.         
  171.         /**
  172.          * ADODB version as a string.
  173.          */
  174.         $ADODB_vers = 'V4.91 2 Aug 2006  (c) 2000-2006 John Lim (jlim#natsoft.com.my). All rights reserved. Released BSD & LGPL.';
  175.     
  176.         /**
  177.          * Determines whether recordset->RecordCount() is used. 
  178.          * Set to false for highest performance -- RecordCount() will always return -1 then
  179.          * for databases that provide "virtual" recordcounts...
  180.          */
  181.         if (!isset($ADODB_COUNTRECS)) $ADODB_COUNTRECS = true; 
  182.     }
  183.     
  184.     
  185.     //==============================================================================================    
  186.     // CHANGE NOTHING BELOW UNLESS YOU ARE DESIGNING ADODB
  187.     //==============================================================================================    
  188.     
  189.     ADODB_Setup();
  190.  
  191.     //==============================================================================================    
  192.     // CLASS ADOFieldObject
  193.     //==============================================================================================    
  194.     /**
  195.      * Helper class for FetchFields -- holds info on a column
  196.      */
  197.     class ADOFieldObject { 
  198.         var $name = '';
  199.         var $max_length=0;
  200.         var $type="";
  201. /*
  202.         // additional fields by dannym... (danny_milo@yahoo.com)
  203.         var $not_null = false; 
  204.         // actually, this has already been built-in in the postgres, fbsql AND mysql module? ^-^
  205.         // so we can as well make not_null standard (leaving it at "false" does not harm anyways)
  206.  
  207.         var $has_default = false; // this one I have done only in mysql and postgres for now ... 
  208.             // others to come (dannym)
  209.         var $default_value; // default, if any, and supported. Check has_default first.
  210. */
  211.     }
  212.     
  213.  
  214.     
  215.     function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection)
  216.     {
  217.         //print "Errorno ($fn errno=$errno m=$errmsg) ";
  218.         $thisConnection->_transOK = false;
  219.         if ($thisConnection->_oldRaiseFn) {
  220.             $fn = $thisConnection->_oldRaiseFn;
  221.             $fn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection);
  222.         }
  223.     }
  224.     
  225.     //==============================================================================================    
  226.     // CLASS ADOConnection
  227.     //==============================================================================================    
  228.     
  229.     /**
  230.      * Connection object. For connecting to databases, and executing queries.
  231.      */ 
  232.     class ADOConnection {
  233.     //
  234.     // PUBLIC VARS 
  235.     //
  236.     var $dataProvider = 'native';
  237.     var $databaseType = '';        /// RDBMS currently in use, eg. odbc, mysql, mssql                    
  238.     var $database = '';            /// Name of database to be used.    
  239.     var $host = '';             /// The hostname of the database server    
  240.     var $user = '';             /// The username which is used to connect to the database server. 
  241.     var $password = '';         /// Password for the username. For security, we no longer store it.
  242.     var $debug = false;         /// if set to true will output sql statements
  243.     var $maxblobsize = 262144;     /// maximum size of blobs or large text fields (262144 = 256K)-- some db's die otherwise like foxpro
  244.     var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase    
  245.     var $substr = 'substr';        /// substring operator
  246.     var $length = 'length';        /// string length ofperator
  247.     var $random = 'rand()';        /// random function
  248.     var $upperCase = 'upper';        /// uppercase function
  249.     var $fmtDate = "'Y-m-d'";    /// used by DBDate() as the default date format used by the database
  250.     var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt.
  251.     var $true = '1';             /// string that represents TRUE for a database
  252.     var $false = '0';             /// string that represents FALSE for a database
  253.     var $replaceQuote = "\\'";     /// string to use to replace quotes
  254.     var $nameQuote = '"';        /// string to use to quote identifiers and names
  255.     var $charSet=false;         /// character set to use - only for interbase, postgres and oci8
  256.     var $metaDatabasesSQL = '';
  257.     var $metaTablesSQL = '';
  258.     var $uniqueOrderBy = false; /// All order by columns have to be unique
  259.     var $emptyDate = ' ';
  260.     var $emptyTimeStamp = ' ';
  261.     var $lastInsID = false;
  262.     //--
  263.     var $hasInsertID = false;         /// supports autoincrement ID?
  264.     var $hasAffectedRows = false;     /// supports affected rows for update/delete?
  265.     var $hasTop = false;            /// support mssql/access SELECT TOP 10 * FROM TABLE
  266.     var $hasLimit = false;            /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10
  267.     var $readOnly = false;             /// this is a readonly database - used by phpLens
  268.     var $hasMoveFirst = false;  /// has ability to run MoveFirst(), scrolling backwards
  269.     var $hasGenID = false;         /// can generate sequences using GenID();
  270.     var $hasTransactions = true; /// has transactions
  271.     //--
  272.     var $genID = 0;             /// sequence id used by GenID();
  273.     var $raiseErrorFn = false;     /// error function to call
  274.     var $isoDates = false; /// accepts dates in ISO format
  275.     var $cacheSecs = 3600; /// cache for 1 hour
  276.     var $sysDate = false; /// name of function that returns the current date
  277.     var $sysTimeStamp = false; /// name of function that returns the current timestamp
  278.     var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets
  279.     
  280.     var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' '
  281.     var $numCacheHits = 0; 
  282.     var $numCacheMisses = 0;
  283.     var $pageExecuteCountRows = true;
  284.     var $uniqueSort = false; /// indicates that all fields in order by must be unique
  285.     var $leftOuter = false; /// operator to use for left outer join in WHERE clause
  286.     var $rightOuter = false; /// operator to use for right outer join in WHERE clause
  287.     var $ansiOuter = false; /// whether ansi outer join syntax supported
  288.     var $autoRollback = false; // autoRollback on PConnect().
  289.     var $poorAffectedRows = false; // affectedRows not working or unreliable
  290.     
  291.     var $fnExecute = false;
  292.     var $fnCacheExecute = false;
  293.     var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char
  294.     var $rsPrefix = "ADORecordSet_";
  295.     
  296.     var $autoCommit = true;     /// do not modify this yourself - actually private
  297.     var $transOff = 0;             /// temporarily disable transactions
  298.     var $transCnt = 0;             /// count of nested transactions
  299.     
  300.     var $fetchMode=false;
  301.      //
  302.      // PRIVATE VARS
  303.      //
  304.     var $_oldRaiseFn =  false;
  305.     var $_transOK = null;
  306.     var $_connectionID    = false;    /// The returned link identifier whenever a successful database connection is made.    
  307.     var $_errorMsg = false;        /// A variable which was used to keep the returned last error message.  The value will
  308.                                 /// then returned by the errorMsg() function    
  309.     var $_errorCode = false;    /// Last error code, not guaranteed to be used - only by oci8                    
  310.     var $_queryID = false;        /// This variable keeps the last created result link identifier
  311.     
  312.     var $_isPersistentConnection = false;    /// A boolean variable to state whether its a persistent connection or normal connection.    */
  313.     var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters.
  314.     var $_evalAll = false;
  315.     var $_affected = false;
  316.     var $_logsql = false;
  317.     var $_transmode = ''; // transaction mode
  318.     
  319.     /**
  320.      * Constructor
  321.      */
  322.     function ADOConnection()            
  323.     {
  324.         die('Virtual Class -- cannot instantiate');
  325.     }
  326.     
  327.     function Version()
  328.     {
  329.     global $ADODB_vers;
  330.     
  331.         return (float) substr($ADODB_vers,1);
  332.     }
  333.     
  334.     /**
  335.         Get server version info...
  336.         
  337.         @returns An array with 2 elements: $arr['string'] is the description string, 
  338.             and $arr[version] is the version (also a string).
  339.     */
  340.     function ServerInfo()
  341.     {
  342.         return array('description' => '', 'version' => '');
  343.     }
  344.     
  345.     function IsConnected()
  346.     {
  347.         return !empty($this->_connectionID);
  348.     }
  349.     
  350.     function _findvers($str)
  351.     {
  352.         if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1];
  353.         else return '';
  354.     }
  355.     
  356.     /**
  357.     * All error messages go through this bottleneck function.
  358.     * You can define your own handler by defining the function name in ADODB_OUTP.
  359.     */
  360.     function outp($msg,$newline=true)
  361.     {
  362.     global $ADODB_FLUSH,$ADODB_OUTP;
  363.     
  364.         if (defined('ADODB_OUTP')) {
  365.             $fn = ADODB_OUTP;
  366.             $fn($msg,$newline);
  367.             return;
  368.         } else if (isset($ADODB_OUTP)) {
  369.             $fn = $ADODB_OUTP;
  370.             $fn($msg,$newline);
  371.             return;
  372.         }
  373.         
  374.         if ($newline) $msg .= "<br>\n";
  375.         
  376.         if (isset($_SERVER['HTTP_USER_AGENT']) || !$newline) echo $msg;
  377.         else echo strip_tags($msg);
  378.     
  379.         
  380.         if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); //  do not flush if output buffering enabled - useless - thx to Jesse Mullan 
  381.         
  382.     }
  383.     
  384.     function Time()
  385.     {
  386.         $rs =& $this->_Execute("select $this->sysTimeStamp");
  387.         if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields));
  388.         
  389.         return false;
  390.     }
  391.     
  392.     /**
  393.      * Connect to database
  394.      *
  395.      * @param [argHostname]        Host to connect to
  396.      * @param [argUsername]        Userid to login
  397.      * @param [argPassword]        Associated password
  398.      * @param [argDatabaseName]    database
  399.      * @param [forceNew]        force new connection
  400.      *
  401.      * @return true or false
  402.      */      
  403.     function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false) 
  404.     {
  405.         if ($argHostname != "") $this->host = $argHostname;
  406.         if ($argUsername != "") $this->user = $argUsername;
  407.         if ($argPassword != "") $this->password = $argPassword; // not stored for security reasons
  408.         if ($argDatabaseName != "") $this->database = $argDatabaseName;        
  409.         
  410.         $this->_isPersistentConnection = false;    
  411.         if ($forceNew) {
  412.             if ($rez=$this->_nconnect($this->host, $this->user, $this->password, $this->database)) return true;
  413.         } else {
  414.              if ($rez=$this->_connect($this->host, $this->user, $this->password, $this->database)) return true;
  415.         }
  416.         if (isset($rez)) {
  417.             $err = $this->ErrorMsg();
  418.             if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
  419.             $ret = false;
  420.         } else {
  421.             $err = "Missing extension for ".$this->dataProvider;
  422.             $ret = 0;
  423.         }
  424.         if ($fn = $this->raiseErrorFn) 
  425.             $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
  426.         
  427.         
  428.         $this->_connectionID = false;
  429.         if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
  430.         return $ret;
  431.     }    
  432.     
  433.     function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
  434.     {
  435.         return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName);
  436.     }
  437.     
  438.     
  439.     /**
  440.      * Always force a new connection to database - currently only works with oracle
  441.      *
  442.      * @param [argHostname]        Host to connect to
  443.      * @param [argUsername]        Userid to login
  444.      * @param [argPassword]        Associated password
  445.      * @param [argDatabaseName]    database
  446.      *
  447.      * @return true or false
  448.      */      
  449.     function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") 
  450.     {
  451.         return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true);
  452.     }
  453.     
  454.     /**
  455.      * Establish persistent connect to database
  456.      *
  457.      * @param [argHostname]        Host to connect to
  458.      * @param [argUsername]        Userid to login
  459.      * @param [argPassword]        Associated password
  460.      * @param [argDatabaseName]    database
  461.      *
  462.      * @return return true or false
  463.      */    
  464.     function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
  465.     {
  466.         if (defined('ADODB_NEVER_PERSIST')) 
  467.             return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);
  468.         
  469.         if ($argHostname != "") $this->host = $argHostname;
  470.         if ($argUsername != "") $this->user = $argUsername;
  471.         if ($argPassword != "") $this->password = $argPassword;
  472.         if ($argDatabaseName != "") $this->database = $argDatabaseName;        
  473.             
  474.         $this->_isPersistentConnection = true;    
  475.         if ($rez = $this->_pconnect($this->host, $this->user, $this->password, $this->database)) return true;
  476.         if (isset($rez)) {
  477.             $err = $this->ErrorMsg();
  478.             if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
  479.             $ret = false;
  480.         } else {
  481.             $err = "Missing extension for ".$this->dataProvider;
  482.             $ret = 0;
  483.         }
  484.         if ($fn = $this->raiseErrorFn) {
  485.             $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
  486.         }
  487.         
  488.         $this->_connectionID = false;
  489.         if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
  490.         return $ret;
  491.     }
  492.  
  493.     // Format date column in sql string given an input format that understands Y M D
  494.     function SQLDate($fmt, $col=false)
  495.     {    
  496.         if (!$col) $col = $this->sysDate;
  497.         return $col; // child class implement
  498.     }
  499.     
  500.     /**
  501.      * Should prepare the sql statement and return the stmt resource.
  502.      * For databases that do not support this, we return the $sql. To ensure
  503.      * compatibility with databases that do not support prepare:
  504.      *
  505.      *   $stmt = $db->Prepare("insert into table (id, name) values (?,?)");
  506.      *   $db->Execute($stmt,array(1,'Jill')) or die('insert failed');
  507.      *   $db->Execute($stmt,array(2,'Joe')) or die('insert failed');
  508.      *
  509.      * @param sql    SQL to send to database
  510.      *
  511.      * @return return FALSE, or the prepared statement, or the original sql if
  512.      *             if the database does not support prepare.
  513.      *
  514.      */    
  515.     function Prepare($sql)
  516.     {
  517.         return $sql;
  518.     }
  519.     
  520.     /**
  521.      * Some databases, eg. mssql require a different function for preparing
  522.      * stored procedures. So we cannot use Prepare().
  523.      *
  524.      * Should prepare the stored procedure  and return the stmt resource.
  525.      * For databases that do not support this, we return the $sql. To ensure
  526.      * compatibility with databases that do not support prepare:
  527.      *
  528.      * @param sql    SQL to send to database
  529.      *
  530.      * @return return FALSE, or the prepared statement, or the original sql if
  531.      *             if the database does not support prepare.
  532.      *
  533.      */    
  534.     function PrepareSP($sql,$param=true)
  535.     {
  536.         return $this->Prepare($sql,$param);
  537.     }
  538.     
  539.     /**
  540.     * PEAR DB Compat
  541.     */
  542.     function Quote($s)
  543.     {
  544.         return $this->qstr($s,false);
  545.     }
  546.     
  547.     /**
  548.      Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de>
  549.     */
  550.     function QMagic($s)
  551.     {
  552.         return $this->qstr($s,get_magic_quotes_gpc());
  553.     }
  554.  
  555.     function q(&$s)
  556.     {
  557.         #if (!empty($this->qNull)) if ($s == 'null') return $s;
  558.         $s = $this->qstr($s,false);
  559.     }
  560.     
  561.     /**
  562.     * PEAR DB Compat - do not use internally. 
  563.     */
  564.     function ErrorNative()
  565.     {
  566.         return $this->ErrorNo();
  567.     }
  568.  
  569.     
  570.    /**
  571.     * PEAR DB Compat - do not use internally. 
  572.     */
  573.     function nextId($seq_name)
  574.     {
  575.         return $this->GenID($seq_name);
  576.     }
  577.  
  578.     /**
  579.     *     Lock a row, will escalate and lock the table if row locking not supported
  580.     *    will normally free the lock at the end of the transaction
  581.     *
  582.     *  @param $table    name of table to lock
  583.     *  @param $where    where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock
  584.     */
  585.     function RowLock($table,$where)
  586.     {
  587.         return false;
  588.     }
  589.     
  590.     function CommitLock($table)
  591.     {
  592.         return $this->CommitTrans();
  593.     }
  594.     
  595.     function RollbackLock($table)
  596.     {
  597.         return $this->RollbackTrans();
  598.     }
  599.     
  600.     /**
  601.     * PEAR DB Compat - do not use internally. 
  602.     *
  603.     * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical
  604.     *     for easy porting :-)
  605.     *
  606.     * @param mode    The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM
  607.     * @returns        The previous fetch mode
  608.     */
  609.     function SetFetchMode($mode)
  610.     {    
  611.         $old = $this->fetchMode;
  612.         $this->fetchMode = $mode;
  613.         
  614.         if ($old === false) {
  615.         global $ADODB_FETCH_MODE;
  616.             return $ADODB_FETCH_MODE;
  617.         }
  618.         return $old;
  619.     }
  620.     
  621.  
  622.     /**
  623.     * PEAR DB Compat - do not use internally. 
  624.     */
  625.     function &Query($sql, $inputarr=false)
  626.     {
  627.         $rs = &$this->Execute($sql, $inputarr);
  628.         if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
  629.         return $rs;
  630.     }
  631.  
  632.     
  633.     /**
  634.     * PEAR DB Compat - do not use internally
  635.     */
  636.     function &LimitQuery($sql, $offset, $count, $params=false)
  637.     {
  638.         $rs = &$this->SelectLimit($sql, $count, $offset, $params); 
  639.         if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
  640.         return $rs;
  641.     }
  642.  
  643.     
  644.     /**
  645.     * PEAR DB Compat - do not use internally
  646.     */
  647.     function Disconnect()
  648.     {
  649.         return $this->Close();
  650.     }
  651.     
  652.     /*
  653.          Returns placeholder for parameter, eg.
  654.          $DB->Param('a')
  655.          
  656.          will return ':a' for Oracle, and '?' for most other databases...
  657.          
  658.          For databases that require positioned params, eg $1, $2, $3 for postgresql,
  659.              pass in Param(false) before setting the first parameter.
  660.     */
  661.     function Param($name,$type='C')
  662.     {
  663.         return '?';
  664.     }
  665.     
  666.     /*
  667.         InParameter and OutParameter are self-documenting versions of Parameter().
  668.     */
  669.     function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
  670.     {
  671.         return $this->Parameter($stmt,$var,$name,false,$maxLen,$type);
  672.     }
  673.     
  674.     /*
  675.     */
  676.     function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
  677.     {
  678.         return $this->Parameter($stmt,$var,$name,true,$maxLen,$type);
  679.     
  680.     }
  681.     
  682.     /* 
  683.     Usage in oracle
  684.         $stmt = $db->Prepare('select * from table where id =:myid and group=:group');
  685.         $db->Parameter($stmt,$id,'myid');
  686.         $db->Parameter($stmt,$group,'group',64);
  687.         $db->Execute();
  688.         
  689.         @param $stmt Statement returned by Prepare() or PrepareSP().
  690.         @param $var PHP variable to bind to
  691.         @param $name Name of stored procedure variable name to bind to.
  692.         @param [$isOutput] Indicates direction of parameter 0/false=IN  1=OUT  2= IN/OUT. This is ignored in oci8.
  693.         @param [$maxLen] Holds an maximum length of the variable.
  694.         @param [$type] The data type of $var. Legal values depend on driver.
  695.  
  696.     */
  697.     function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
  698.     {
  699.         return false;
  700.     }
  701.     
  702.     /**
  703.         Improved method of initiating a transaction. Used together with CompleteTrans().
  704.         Advantages include:
  705.         
  706.         a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.
  707.            Only the outermost block is treated as a transaction.<br>
  708.         b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>
  709.         c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block
  710.            are disabled, making it backward compatible.
  711.     */
  712.     function StartTrans($errfn = 'ADODB_TransMonitor')
  713.     {
  714.         if ($this->transOff > 0) {
  715.             $this->transOff += 1;
  716.             return;
  717.         }
  718.         
  719.         $this->_oldRaiseFn = $this->raiseErrorFn;
  720.         $this->raiseErrorFn = $errfn;
  721.         $this->_transOK = true;
  722.         
  723.         if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
  724.         $this->BeginTrans();
  725.         $this->transOff = 1;
  726.     }
  727.     
  728.     
  729.     /**
  730.         Used together with StartTrans() to end a transaction. Monitors connection
  731.         for sql errors, and will commit or rollback as appropriate.
  732.         
  733.         @autoComplete if true, monitor sql errors and commit and rollback as appropriate, 
  734.         and if set to false force rollback even if no SQL error detected.
  735.         @returns true on commit, false on rollback.
  736.     */
  737.     function CompleteTrans($autoComplete = true)
  738.     {
  739.         if ($this->transOff > 1) {
  740.             $this->transOff -= 1;
  741.             return true;
  742.         }
  743.         $this->raiseErrorFn = $this->_oldRaiseFn;
  744.         
  745.         $this->transOff = 0;
  746.         if ($this->_transOK && $autoComplete) {
  747.             if (!$this->CommitTrans()) {
  748.                 $this->_transOK = false;
  749.                 if ($this->debug) ADOConnection::outp("Smart Commit failed");
  750.             } else
  751.                 if ($this->debug) ADOConnection::outp("Smart Commit occurred");
  752.         } else {
  753.             $this->_transOK = false;
  754.             $this->RollbackTrans();
  755.             if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred");
  756.         }
  757.         
  758.         return $this->_transOK;
  759.     }
  760.     
  761.     /*
  762.         At the end of a StartTrans/CompleteTrans block, perform a rollback.
  763.     */
  764.     function FailTrans()
  765.     {
  766.         if ($this->debug) 
  767.             if ($this->transOff == 0) {
  768.                 ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
  769.             } else {
  770.                 ADOConnection::outp("FailTrans was called");
  771.                 adodb_backtrace();
  772.             }
  773.         $this->_transOK = false;
  774.     }
  775.     
  776.     /**
  777.         Check if transaction has failed, only for Smart Transactions.
  778.     */
  779.     function HasFailedTrans()
  780.     {
  781.         if ($this->transOff > 0) return $this->_transOK == false;
  782.         return false;
  783.     }
  784.     
  785.     /**
  786.      * Execute SQL 
  787.      *
  788.      * @param sql        SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
  789.      * @param [inputarr]    holds the input data to bind to. Null elements will be set to null.
  790.      * @return         RecordSet or false
  791.      */
  792.     function &Execute($sql,$inputarr=false) 
  793.     {
  794.         if ($this->fnExecute) {
  795.             $fn = $this->fnExecute;
  796.             $ret =& $fn($this,$sql,$inputarr);
  797.             if (isset($ret)) return $ret;
  798.         }
  799.         if ($inputarr) {
  800.             if (!is_array($inputarr)) $inputarr = array($inputarr);
  801.             
  802.             $element0 = reset($inputarr);
  803.             # is_object check because oci8 descriptors can be passed in
  804.             $array_2d = is_array($element0) && !is_object(reset($element0));
  805.             //remove extra memory copy of input -mikefedyk
  806.             unset($element0);
  807.             
  808.             if (!is_array($sql) && !$this->_bindInputArray) {
  809.                 $sqlarr = explode('?',$sql);
  810.                     
  811.                 if (!$array_2d) $inputarr = array($inputarr);
  812.                 foreach($inputarr as $arr) {
  813.                     $sql = ''; $i = 0;
  814.                     //Use each() instead of foreach to reduce memory usage -mikefedyk
  815.                     while(list(, $v) = each($arr)) {
  816.                         $sql .= $sqlarr[$i];
  817.                         // from Ron Baldwin <ron.baldwin#sourceprose.com>
  818.                         // Only quote string types    
  819.                         $typ = gettype($v);
  820.                         if ($typ == 'string')
  821.                             //New memory copy of input created here -mikefedyk
  822.                             $sql .= $this->qstr($v);
  823.                         else if ($typ == 'double')
  824.                             $sql .= str_replace(',','.',$v); // locales fix so 1.1 does not get converted to 1,1
  825.                         else if ($typ == 'boolean')
  826.                             $sql .= $v ? $this->true : $this->false;
  827.                         else if ($typ == 'object') {
  828.                             if (method_exists($v, '__toString')) $sql .= $this->qstr($v->__toString());
  829.                             else $sql .= $this->qstr((string) $v);
  830.                         } else if ($v === null)
  831.                             $sql .= 'NULL';
  832.                         else
  833.                             $sql .= $v;
  834.                         $i += 1;
  835.                     }
  836.                     if (isset($sqlarr[$i])) {
  837.                         $sql .= $sqlarr[$i];
  838.                         if ($i+1 != sizeof($sqlarr)) ADOConnection::outp( "Input Array does not match ?: ".htmlspecialchars($sql));
  839.                     } else if ($i != sizeof($sqlarr))    
  840.                         ADOConnection::outp( "Input array does not match ?: ".htmlspecialchars($sql));
  841.         
  842.                     $ret =& $this->_Execute($sql);
  843.                     if (!$ret) return $ret;
  844.                 }    
  845.             } else {
  846.                 if ($array_2d) {
  847.                     if (is_string($sql))
  848.                         $stmt = $this->Prepare($sql);
  849.                     else
  850.                         $stmt = $sql;
  851.                         
  852.                     foreach($inputarr as $arr) {
  853.                         $ret =& $this->_Execute($stmt,$arr);
  854.                         if (!$ret) return $ret;
  855.                     }
  856.                 } else {
  857.                     $ret =& $this->_Execute($sql,$inputarr);
  858.                 }
  859.             }
  860.         } else {
  861.             $ret =& $this->_Execute($sql,false);
  862.         }
  863.  
  864.         return $ret;
  865.     }
  866.     
  867.     
  868.     function &_Execute($sql,$inputarr=false)
  869.     {
  870.         if ($this->debug) {
  871.             global $ADODB_INCLUDED_LIB;
  872.             if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  873.             $this->_queryID = _adodb_debug_execute($this, $sql,$inputarr);
  874.         } else {
  875.             $this->_queryID = @$this->_query($sql,$inputarr);
  876.         }
  877.         
  878.         /************************
  879.         // OK, query executed
  880.         *************************/
  881.  
  882.         if ($this->_queryID === false) { // error handling if query fails
  883.             if ($this->debug == 99) adodb_backtrace(true,5);    
  884.             $fn = $this->raiseErrorFn;
  885.             if ($fn) {
  886.                 $fn($this->databaseType,'EXECUTE',$this->ErrorNo(),$this->ErrorMsg(),$sql,$inputarr,$this);
  887.             } 
  888.             $false = false;
  889.             return $false;
  890.         } 
  891.         
  892.         if ($this->_queryID === true) { // return simplified recordset for inserts/updates/deletes with lower overhead
  893.             $rs =& new ADORecordSet_empty();
  894.             return $rs;
  895.         }
  896.         
  897.         // return real recordset from select statement
  898.         $rsclass = $this->rsPrefix.$this->databaseType;
  899.         $rs = new $rsclass($this->_queryID,$this->fetchMode);
  900.         $rs->connection = &$this; // Pablo suggestion
  901.         $rs->Init();
  902.         if (is_array($sql)) $rs->sql = $sql[0];
  903.         else $rs->sql = $sql;
  904.         if ($rs->_numOfRows <= 0) {
  905.         global $ADODB_COUNTRECS;
  906.             if ($ADODB_COUNTRECS) {
  907.                 if (!$rs->EOF) { 
  908.                     $rs = &$this->_rs2rs($rs,-1,-1,!is_array($sql));
  909.                     $rs->_queryID = $this->_queryID;
  910.                 } else
  911.                     $rs->_numOfRows = 0;
  912.             }
  913.         }
  914.         return $rs;
  915.     }
  916.  
  917.     function CreateSequence($seqname='adodbseq',$startID=1)
  918.     {
  919.         if (empty($this->_genSeqSQL)) return false;
  920.         return $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
  921.     }
  922.  
  923.     function DropSequence($seqname='adodbseq')
  924.     {
  925.         if (empty($this->_dropSeqSQL)) return false;
  926.         return $this->Execute(sprintf($this->_dropSeqSQL,$seqname));
  927.     }
  928.  
  929.     /**
  930.      * Generates a sequence id and stores it in $this->genID;
  931.      * GenID is only available if $this->hasGenID = true;
  932.      *
  933.      * @param seqname        name of sequence to use
  934.      * @param startID        if sequence does not exist, start at this ID
  935.      * @return        0 if not supported, otherwise a sequence id
  936.      */
  937.     function GenID($seqname='adodbseq',$startID=1)
  938.     {
  939.         if (!$this->hasGenID) {
  940.             return 0; // formerly returns false pre 1.60
  941.         }
  942.         
  943.         $getnext = sprintf($this->_genIDSQL,$seqname);
  944.         
  945.         $holdtransOK = $this->_transOK;
  946.         
  947.         $save_handler = $this->raiseErrorFn;
  948.         $this->raiseErrorFn = '';
  949.         @($rs = $this->Execute($getnext));
  950.         $this->raiseErrorFn = $save_handler;
  951.         
  952.         if (!$rs) {
  953.             $this->_transOK = $holdtransOK; //if the status was ok before reset
  954.             $createseq = $this->Execute(sprintf($this->_genSeqSQL,$seqname,$startID));
  955.             $rs = $this->Execute($getnext);
  956.         }
  957.         if ($rs && !$rs->EOF) $this->genID = reset($rs->fields);
  958.         else $this->genID = 0; // false
  959.     
  960.         if ($rs) $rs->Close();
  961.  
  962.         return $this->genID;
  963.     }    
  964.  
  965.     /**
  966.      * @param $table string name of the table, not needed by all databases (eg. mysql), default ''
  967.      * @param $column string name of the column, not needed by all databases (eg. mysql), default ''
  968.      * @return  the last inserted ID. Not all databases support this.
  969.      */ 
  970.     function Insert_ID($table='',$column='')
  971.     {
  972.         if ($this->_logsql && $this->lastInsID) return $this->lastInsID;
  973.         if ($this->hasInsertID) return $this->_insertid($table,$column);
  974.         if ($this->debug) {
  975.             ADOConnection::outp( '<p>Insert_ID error</p>');
  976.             adodb_backtrace();
  977.         }
  978.         return false;
  979.     }
  980.  
  981.  
  982.     /**
  983.      * Portable Insert ID. Pablo Roca <pabloroca#mvps.org>
  984.      *
  985.      * @return  the last inserted ID. All databases support this. But aware possible
  986.      * problems in multiuser environments. Heavy test this before deploying.
  987.      */ 
  988.     function PO_Insert_ID($table="", $id="") 
  989.     {
  990.        if ($this->hasInsertID){
  991.            return $this->Insert_ID($table,$id);
  992.        } else {
  993.            return $this->GetOne("SELECT MAX($id) FROM $table");
  994.        }
  995.     }
  996.  
  997.     /**
  998.     * @return # rows affected by UPDATE/DELETE
  999.     */ 
  1000.     function Affected_Rows()
  1001.     {
  1002.         if ($this->hasAffectedRows) {
  1003.             if ($this->fnExecute === 'adodb_log_sql') {
  1004.                 if ($this->_logsql && $this->_affected !== false) return $this->_affected;
  1005.             }
  1006.             $val = $this->_affectedrows();
  1007.             return ($val < 0) ? false : $val;
  1008.         }
  1009.                   
  1010.         if ($this->debug) ADOConnection::outp( '<p>Affected_Rows error</p>',false);
  1011.         return false;
  1012.     }
  1013.     
  1014.     
  1015.     /**
  1016.      * @return  the last error message
  1017.      */
  1018.     function ErrorMsg()
  1019.     {
  1020.         if ($this->_errorMsg) return '!! '.strtoupper($this->dataProvider.' '.$this->databaseType).': '.$this->_errorMsg;
  1021.         else return '';
  1022.     }
  1023.     
  1024.     
  1025.     /**
  1026.      * @return the last error number. Normally 0 means no error.
  1027.      */
  1028.     function ErrorNo() 
  1029.     {
  1030.         return ($this->_errorMsg) ? -1 : 0;
  1031.     }
  1032.     
  1033.     function MetaError($err=false)
  1034.     {
  1035.         include_once(ADODB_DIR."/adodb-error.inc.php");
  1036.         if ($err === false) $err = $this->ErrorNo();
  1037.         return adodb_error($this->dataProvider,$this->databaseType,$err);
  1038.     }
  1039.     
  1040.     function MetaErrorMsg($errno)
  1041.     {
  1042.         include_once(ADODB_DIR."/adodb-error.inc.php");
  1043.         return adodb_errormsg($errno);
  1044.     }
  1045.     
  1046.     /**
  1047.      * @returns an array with the primary key columns in it.
  1048.      */
  1049.     function MetaPrimaryKeys($table, $owner=false)
  1050.     {
  1051.     // owner not used in base class - see oci8
  1052.         $p = array();
  1053.         $objs =& $this->MetaColumns($table);
  1054.         if ($objs) {
  1055.             foreach($objs as $v) {
  1056.                 if (!empty($v->primary_key))
  1057.                     $p[] = $v->name;
  1058.             }
  1059.         }
  1060.         if (sizeof($p)) return $p;
  1061.         if (function_exists('ADODB_VIEW_PRIMARYKEYS'))
  1062.             return ADODB_VIEW_PRIMARYKEYS($this->databaseType, $this->database, $table, $owner);
  1063.         return false;
  1064.     }
  1065.     
  1066.     /**
  1067.      * @returns assoc array where keys are tables, and values are foreign keys
  1068.      */
  1069.     function MetaForeignKeys($table, $owner=false, $upper=false)
  1070.     {
  1071.         return false;
  1072.     }
  1073.     /**
  1074.      * Choose a database to connect to. Many databases do not support this.
  1075.      *
  1076.      * @param dbName     is the name of the database to select
  1077.      * @return         true or false
  1078.      */
  1079.     function SelectDB($dbName) 
  1080.     {return false;}
  1081.     
  1082.     
  1083.     /**
  1084.     * Will select, getting rows from $offset (1-based), for $nrows. 
  1085.     * This simulates the MySQL "select * from table limit $offset,$nrows" , and
  1086.     * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
  1087.     * MySQL and PostgreSQL parameter ordering is the opposite of the other.
  1088.     * eg. 
  1089.     *  SelectLimit('select * from table',3); will return rows 1 to 3 (1-based)
  1090.     *  SelectLimit('select * from table',3,2); will return rows 3 to 5 (1-based)
  1091.     *
  1092.     * Uses SELECT TOP for Microsoft databases (when $this->hasTop is set)
  1093.     * BUG: Currently SelectLimit fails with $sql with LIMIT or TOP clause already set
  1094.     *
  1095.     * @param sql
  1096.     * @param [offset]    is the row to start calculations from (1-based)
  1097.     * @param [nrows]        is the number of rows to get
  1098.     * @param [inputarr]    array of bind variables
  1099.     * @param [secs2cache]        is a private parameter only used by jlim
  1100.     * @return        the recordset ($rs->databaseType == 'array')
  1101.      */
  1102.     function &SelectLimit($sql,$nrows=-1,$offset=-1, $inputarr=false,$secs2cache=0)
  1103.     {
  1104.         if ($this->hasTop && $nrows > 0) {
  1105.         // suggested by Reinhard Balling. Access requires top after distinct 
  1106.          // Informix requires first before distinct - F Riosa
  1107.             $ismssql = (strpos($this->databaseType,'mssql') !== false);
  1108.             if ($ismssql) $isaccess = false;
  1109.             else $isaccess = (strpos($this->databaseType,'access') !== false);
  1110.             
  1111.             if ($offset <= 0) {
  1112.                 
  1113.                     // access includes ties in result
  1114.                     if ($isaccess) {
  1115.                         $sql = preg_replace(
  1116.                         '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
  1117.  
  1118.                         if ($secs2cache >= 0) {
  1119.                             $ret =& $this->CacheExecute($secs2cache, $sql,$inputarr);
  1120.                         } else {
  1121.                             $ret =& $this->Execute($sql,$inputarr);
  1122.                         }
  1123.                         return $ret; // PHP5 fix
  1124.                     } else if ($ismssql){
  1125.                         $sql = preg_replace(
  1126.                         '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
  1127.                     } else {
  1128.                         $sql = preg_replace(
  1129.                         '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.((integer)$nrows).' ',$sql);
  1130.                     }
  1131.             } else {
  1132.                 $nn = $nrows + $offset;
  1133.                 if ($isaccess || $ismssql) {
  1134.                     $sql = preg_replace(
  1135.                     '/(^\s*select\s+(distinctrow|distinct)?)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
  1136.                 } else {
  1137.                     $sql = preg_replace(
  1138.                     '/(^\s*select\s)/i','\\1 '.$this->hasTop.' '.$nn.' ',$sql);
  1139.                 }
  1140.             }
  1141.         }
  1142.         
  1143.         // if $offset>0, we want to skip rows, and $ADODB_COUNTRECS is set, we buffer  rows
  1144.         // 0 to offset-1 which will be discarded anyway. So we disable $ADODB_COUNTRECS.
  1145.         global $ADODB_COUNTRECS;
  1146.         
  1147.         $savec = $ADODB_COUNTRECS;
  1148.         $ADODB_COUNTRECS = false;
  1149.             
  1150.         if ($offset>0){
  1151.             if ($secs2cache >= 0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
  1152.             else $rs = &$this->Execute($sql,$inputarr);
  1153.         } else {
  1154.             if ($secs2cache >= 0) $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
  1155.             else $rs = &$this->Execute($sql,$inputarr);
  1156.         }
  1157.         $ADODB_COUNTRECS = $savec;
  1158.         if ($rs && !$rs->EOF) {
  1159.             $rs =& $this->_rs2rs($rs,$nrows,$offset);
  1160.         }
  1161.         //print_r($rs);
  1162.         return $rs;
  1163.     }
  1164.     
  1165.     /**
  1166.     * Create serializable recordset. Breaks rs link to connection.
  1167.     *
  1168.     * @param rs            the recordset to serialize
  1169.     */
  1170.     function &SerializableRS(&$rs)
  1171.     {
  1172.         $rs2 =& $this->_rs2rs($rs);
  1173.         $ignore = false;
  1174.         $rs2->connection =& $ignore;
  1175.         
  1176.         return $rs2;
  1177.     }
  1178.     
  1179.     /**
  1180.     * Convert database recordset to an array recordset
  1181.     * input recordset's cursor should be at beginning, and
  1182.     * old $rs will be closed.
  1183.     *
  1184.     * @param rs            the recordset to copy
  1185.     * @param [nrows]      number of rows to retrieve (optional)
  1186.     * @param [offset]     offset by number of rows (optional)
  1187.     * @return             the new recordset
  1188.     */
  1189.     function &_rs2rs(&$rs,$nrows=-1,$offset=-1,$close=true)
  1190.     {
  1191.         if (! $rs) {
  1192.             $false = false;
  1193.             return $false;
  1194.         }
  1195.         $dbtype = $rs->databaseType;
  1196.         if (!$dbtype) {
  1197.             $rs = &$rs;  // required to prevent crashing in 4.2.1, but does not happen in 4.3.1 -- why ?
  1198.             return $rs;
  1199.         }
  1200.         if (($dbtype == 'array' || $dbtype == 'csv') && $nrows == -1 && $offset == -1) {
  1201.             $rs->MoveFirst();
  1202.             $rs = &$rs; // required to prevent crashing in 4.2.1, but does not happen in 4.3.1-- why ?
  1203.             return $rs;
  1204.         }
  1205.         $flds = array();
  1206.         for ($i=0, $max=$rs->FieldCount(); $i < $max; $i++) {
  1207.             $flds[] = $rs->FetchField($i);
  1208.         }
  1209.  
  1210.         $arr =& $rs->GetArrayLimit($nrows,$offset);
  1211.         //print_r($arr);
  1212.         if ($close) $rs->Close();
  1213.         
  1214.         $arrayClass = $this->arrayClass;
  1215.         
  1216.         $rs2 = new $arrayClass();
  1217.         $rs2->connection = &$this;
  1218.         $rs2->sql = $rs->sql;
  1219.         $rs2->dataProvider = $this->dataProvider;
  1220.         $rs2->InitArrayFields($arr,$flds);
  1221.         $rs2->fetchMode = isset($rs->adodbFetchMode) ? $rs->adodbFetchMode : $rs->fetchMode;
  1222.         return $rs2;
  1223.     }
  1224.     
  1225.     /*
  1226.     * Return all rows. Compat with PEAR DB
  1227.     */
  1228.     function &GetAll($sql, $inputarr=false)
  1229.     {
  1230.         $arr =& $this->GetArray($sql,$inputarr);
  1231.         return $arr;
  1232.     }
  1233.     
  1234.     function &GetAssoc($sql, $inputarr=false,$force_array = false, $first2cols = false)
  1235.     {
  1236.         $rs =& $this->Execute($sql, $inputarr);
  1237.         if (!$rs) {
  1238.             $false = false;
  1239.             return $false;
  1240.         }
  1241.         $arr =& $rs->GetAssoc($force_array,$first2cols);
  1242.         return $arr;
  1243.     }
  1244.     
  1245.     function &CacheGetAssoc($secs2cache, $sql=false, $inputarr=false,$force_array = false, $first2cols = false)
  1246.     {
  1247.         if (!is_numeric($secs2cache)) {
  1248.             $first2cols = $force_array;
  1249.             $force_array = $inputarr;
  1250.         }
  1251.         $rs =& $this->CacheExecute($secs2cache, $sql, $inputarr);
  1252.         if (!$rs) {
  1253.             $false = false;
  1254.             return $false;
  1255.         }
  1256.         $arr =& $rs->GetAssoc($force_array,$first2cols);
  1257.         return $arr;
  1258.     }
  1259.     
  1260.     /**
  1261.     * Return first element of first row of sql statement. Recordset is disposed
  1262.     * for you.
  1263.     *
  1264.     * @param sql            SQL statement
  1265.     * @param [inputarr]        input bind array
  1266.     */
  1267.     function GetOne($sql,$inputarr=false)
  1268.     {
  1269.     global $ADODB_COUNTRECS;
  1270.         $crecs = $ADODB_COUNTRECS;
  1271.         $ADODB_COUNTRECS = false;
  1272.         
  1273.         $ret = false;
  1274.         $rs = &$this->Execute($sql,$inputarr);
  1275.         if ($rs) {    
  1276.             if (!$rs->EOF) $ret = reset($rs->fields);
  1277.             $rs->Close();
  1278.         }
  1279.         $ADODB_COUNTRECS = $crecs;
  1280.         return $ret;
  1281.     }
  1282.     
  1283.     function CacheGetOne($secs2cache,$sql=false,$inputarr=false)
  1284.     {
  1285.         $ret = false;
  1286.         $rs = &$this->CacheExecute($secs2cache,$sql,$inputarr);
  1287.         if ($rs) {        
  1288.             if (!$rs->EOF) $ret = reset($rs->fields);
  1289.             $rs->Close();
  1290.         } 
  1291.         
  1292.         return $ret;
  1293.     }
  1294.     
  1295.     function GetCol($sql, $inputarr = false, $trim = false)
  1296.     {
  1297.           $rv = false;
  1298.           $rs = &$this->Execute($sql, $inputarr);
  1299.           if ($rs) {
  1300.             $rv = array();
  1301.                if ($trim) {
  1302.                 while (!$rs->EOF) {
  1303.                     $rv[] = trim(reset($rs->fields));
  1304.                     $rs->MoveNext();
  1305.                    }
  1306.             } else {
  1307.                 while (!$rs->EOF) {
  1308.                     $rv[] = reset($rs->fields);
  1309.                     $rs->MoveNext();
  1310.                    }
  1311.             }
  1312.                $rs->Close();
  1313.           }
  1314.           return $rv;
  1315.     }
  1316.     
  1317.     function CacheGetCol($secs, $sql = false, $inputarr = false,$trim=false)
  1318.     {
  1319.           $rv = false;
  1320.           $rs = &$this->CacheExecute($secs, $sql, $inputarr);
  1321.           if ($rs) {
  1322.             if ($trim) {
  1323.                 while (!$rs->EOF) {
  1324.                     $rv[] = trim(reset($rs->fields));
  1325.                     $rs->MoveNext();
  1326.                    }
  1327.             } else {
  1328.                 while (!$rs->EOF) {
  1329.                     $rv[] = reset($rs->fields);
  1330.                     $rs->MoveNext();
  1331.                    }
  1332.             }
  1333.                $rs->Close();
  1334.           }
  1335.           return $rv;
  1336.     }
  1337.  
  1338.     /*
  1339.         Calculate the offset of a date for a particular database and generate
  1340.             appropriate SQL. Useful for calculating future/past dates and storing
  1341.             in a database.
  1342.             
  1343.         If dayFraction=1.5 means 1.5 days from now, 1.0/24 for 1 hour.
  1344.     */
  1345.     function OffsetDate($dayFraction,$date=false)
  1346.     {        
  1347.         if (!$date) $date = $this->sysDate;
  1348.         return  '('.$date.'+'.$dayFraction.')';
  1349.     }
  1350.     
  1351.     /**
  1352.     *
  1353.     * @param sql            SQL statement
  1354.     * @param [inputarr]        input bind array
  1355.     */
  1356.     function &GetArray($sql,$inputarr=false)
  1357.     {
  1358.     global $ADODB_COUNTRECS;
  1359.         
  1360.         $savec = $ADODB_COUNTRECS;
  1361.         $ADODB_COUNTRECS = false;
  1362.         $rs =& $this->Execute($sql,$inputarr);
  1363.         $ADODB_COUNTRECS = $savec;
  1364.         if (!$rs) 
  1365.             if (defined('ADODB_PEAR')) {
  1366.                 $cls = ADODB_PEAR_Error();
  1367.                 return $cls;
  1368.             } else {
  1369.                 $false = false;
  1370.                 return $false;
  1371.             }
  1372.         $arr =& $rs->GetArray();
  1373.         $rs->Close();
  1374.         return $arr;
  1375.     }
  1376.     
  1377.     function &CacheGetAll($secs2cache,$sql=false,$inputarr=false)
  1378.     {
  1379.         return $this->CacheGetArray($secs2cache,$sql,$inputarr);
  1380.     }
  1381.     
  1382.     function &CacheGetArray($secs2cache,$sql=false,$inputarr=false)
  1383.     {
  1384.     global $ADODB_COUNTRECS;
  1385.         
  1386.         $savec = $ADODB_COUNTRECS;
  1387.         $ADODB_COUNTRECS = false;
  1388.         $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
  1389.         $ADODB_COUNTRECS = $savec;
  1390.         
  1391.         if (!$rs) 
  1392.             if (defined('ADODB_PEAR')) {
  1393.                 $cls = ADODB_PEAR_Error();
  1394.                 return $cls;
  1395.             } else {
  1396.                 $false = false;
  1397.                 return $false;
  1398.             }
  1399.         $arr =& $rs->GetArray();
  1400.         $rs->Close();
  1401.         return $arr;
  1402.     }
  1403.     
  1404.     
  1405.     
  1406.     /**
  1407.     * Return one row of sql statement. Recordset is disposed for you.
  1408.     *
  1409.     * @param sql            SQL statement
  1410.     * @param [inputarr]        input bind array
  1411.     */
  1412.     function &GetRow($sql,$inputarr=false)
  1413.     {
  1414.     global $ADODB_COUNTRECS;
  1415.         $crecs = $ADODB_COUNTRECS;
  1416.         $ADODB_COUNTRECS = false;
  1417.         
  1418.         $rs =& $this->Execute($sql,$inputarr);
  1419.         
  1420.         $ADODB_COUNTRECS = $crecs;
  1421.         if ($rs) {
  1422.             if (!$rs->EOF) $arr = $rs->fields;
  1423.             else $arr = array();
  1424.             $rs->Close();
  1425.             return $arr;
  1426.         }
  1427.         
  1428.         $false = false;
  1429.         return $false;
  1430.     }
  1431.     
  1432.     function &CacheGetRow($secs2cache,$sql=false,$inputarr=false)
  1433.     {
  1434.         $rs =& $this->CacheExecute($secs2cache,$sql,$inputarr);
  1435.         if ($rs) {
  1436.             $arr = false;
  1437.             if (!$rs->EOF) $arr = $rs->fields;
  1438.             $rs->Close();
  1439.             return $arr;
  1440.         }
  1441.         $false = false;
  1442.         return $false;
  1443.     }
  1444.     
  1445.     /**
  1446.     * Insert or replace a single record. Note: this is not the same as MySQL's replace. 
  1447.     * ADOdb's Replace() uses update-insert semantics, not insert-delete-duplicates of MySQL.
  1448.     * Also note that no table locking is done currently, so it is possible that the
  1449.     * record be inserted twice by two programs...
  1450.     *
  1451.     * $this->Replace('products', array('prodname' =>"'Nails'","price" => 3.99), 'prodname');
  1452.     *
  1453.     * $table        table name
  1454.     * $fieldArray    associative array of data (you must quote strings yourself).
  1455.     * $keyCol        the primary key field name or if compound key, array of field names
  1456.     * autoQuote        set to true to use a hueristic to quote strings. Works with nulls and numbers
  1457.     *                    but does not work with dates nor SQL functions.
  1458.     * has_autoinc    the primary key is an auto-inc field, so skip in insert.
  1459.     *
  1460.     * Currently blob replace not supported
  1461.     *
  1462.     * returns 0 = fail, 1 = update, 2 = insert 
  1463.     */
  1464.     
  1465.     function Replace($table, $fieldArray, $keyCol, $autoQuote=false, $has_autoinc=false)
  1466.     {
  1467.         global $ADODB_INCLUDED_LIB;
  1468.         if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  1469.         
  1470.         return _adodb_replace($this, $table, $fieldArray, $keyCol, $autoQuote, $has_autoinc);
  1471.     }
  1472.     
  1473.     
  1474.     /**
  1475.     * Will select, getting rows from $offset (1-based), for $nrows. 
  1476.     * This simulates the MySQL "select * from table limit $offset,$nrows" , and
  1477.     * the PostgreSQL "select * from table limit $nrows offset $offset". Note that
  1478.     * MySQL and PostgreSQL parameter ordering is the opposite of the other.
  1479.     * eg. 
  1480.     *  CacheSelectLimit(15,'select * from table',3); will return rows 1 to 3 (1-based)
  1481.     *  CacheSelectLimit(15,'select * from table',3,2); will return rows 3 to 5 (1-based)
  1482.     *
  1483.     * BUG: Currently CacheSelectLimit fails with $sql with LIMIT or TOP clause already set
  1484.     *
  1485.     * @param [secs2cache]    seconds to cache data, set to 0 to force query. This is optional
  1486.     * @param sql
  1487.     * @param [offset]    is the row to start calculations from (1-based)
  1488.     * @param [nrows]    is the number of rows to get
  1489.     * @param [inputarr]    array of bind variables
  1490.     * @return        the recordset ($rs->databaseType == 'array')
  1491.      */
  1492.     function &CacheSelectLimit($secs2cache,$sql,$nrows=-1,$offset=-1,$inputarr=false)
  1493.     {    
  1494.         if (!is_numeric($secs2cache)) {
  1495.             if ($sql === false) $sql = -1;
  1496.             if ($offset == -1) $offset = false;
  1497.                                       // sql,    nrows, offset,inputarr
  1498.             $rs =& $this->SelectLimit($secs2cache,$sql,$nrows,$offset,$this->cacheSecs);
  1499.         } else {
  1500.             if ($sql === false) ADOConnection::outp( "Warning: \$sql missing from CacheSelectLimit()");
  1501.             $rs =& $this->SelectLimit($sql,$nrows,$offset,$inputarr,$secs2cache);
  1502.         }
  1503.         return $rs;
  1504.     }
  1505.     
  1506.     
  1507.     /**
  1508.     * Flush cached recordsets that match a particular $sql statement. 
  1509.     * If $sql == false, then we purge all files in the cache.
  1510.      */
  1511.     
  1512.     /**
  1513.    * Flush cached recordsets that match a particular $sql statement. 
  1514.    * If $sql == false, then we purge all files in the cache.
  1515.     */
  1516.     function CacheFlush($sql=false,$inputarr=false)
  1517.     {
  1518.     global $ADODB_CACHE_DIR;
  1519.     
  1520.         if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
  1521.          /*if (strncmp(PHP_OS,'WIN',3) === 0)
  1522.             $dir = str_replace('/', '\\', $ADODB_CACHE_DIR);
  1523.          else */
  1524.             $dir = $ADODB_CACHE_DIR;
  1525.             
  1526.          if ($this->debug) {
  1527.             ADOConnection::outp( "CacheFlush: $dir<br><pre>\n", $this->_dirFlush($dir),"</pre>");
  1528.          } else {
  1529.             $this->_dirFlush($dir);
  1530.          }
  1531.          return;
  1532.       } 
  1533.       
  1534.       global $ADODB_INCLUDED_CSV;
  1535.       if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
  1536.       
  1537.       $f = $this->_gencachename($sql.serialize($inputarr),false);
  1538.       adodb_write_file($f,''); // is adodb_write_file needed?
  1539.       if (!@unlink($f)) {
  1540.          if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");
  1541.       }
  1542.    }
  1543.    
  1544.    /**
  1545.    * Private function to erase all of the files and subdirectories in a directory.
  1546.    *
  1547.    * Just specify the directory, and tell it if you want to delete the directory or just clear it out.
  1548.    * Note: $kill_top_level is used internally in the function to flush subdirectories.
  1549.    */
  1550.    function _dirFlush($dir, $kill_top_level = false) {
  1551.       if(!$dh = @opendir($dir)) return;
  1552.       
  1553.       while (($obj = readdir($dh))) {
  1554.          if($obj=='.' || $obj=='..')
  1555.             continue;
  1556.             
  1557.          if (!@unlink($dir.'/'.$obj))
  1558.               $this->_dirFlush($dir.'/'.$obj, true);
  1559.       }
  1560.       if ($kill_top_level === true)
  1561.          @rmdir($dir);
  1562.       return true;
  1563.    }
  1564.    
  1565.    
  1566.     function xCacheFlush($sql=false,$inputarr=false)
  1567.     {
  1568.     global $ADODB_CACHE_DIR;
  1569.     
  1570.         if (strlen($ADODB_CACHE_DIR) > 1 && !$sql) {
  1571.             if (strncmp(PHP_OS,'WIN',3) === 0) {
  1572.                 $cmd = 'del /s '.str_replace('/','\\',$ADODB_CACHE_DIR).'\adodb_*.cache';
  1573.             } else {
  1574.                 //$cmd = 'find "'.$ADODB_CACHE_DIR.'" -type f -maxdepth 1 -print0 | xargs -0 rm -f';
  1575.                 $cmd = 'rm -rf '.$ADODB_CACHE_DIR.'/[0-9a-f][0-9a-f]/'; 
  1576.                 // old version 'rm -f `find '.$ADODB_CACHE_DIR.' -name adodb_*.cache`';
  1577.             }
  1578.             if ($this->debug) {
  1579.                 ADOConnection::outp( "CacheFlush: $cmd<br><pre>\n", system($cmd),"</pre>");
  1580.             } else {
  1581.                 exec($cmd);
  1582.             }
  1583.             return;
  1584.         } 
  1585.         
  1586.         global $ADODB_INCLUDED_CSV;
  1587.         if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
  1588.         
  1589.         $f = $this->_gencachename($sql.serialize($inputarr),false);
  1590.         adodb_write_file($f,''); // is adodb_write_file needed?
  1591.         if (!@unlink($f)) {
  1592.             if ($this->debug) ADOConnection::outp( "CacheFlush: failed for $f");
  1593.         }
  1594.     }
  1595.     
  1596.     /**
  1597.     * Private function to generate filename for caching.
  1598.     * Filename is generated based on:
  1599.     *
  1600.     *  - sql statement
  1601.     *  - database type (oci8, ibase, ifx, etc)
  1602.     *  - database name
  1603.     *  - userid
  1604.     *  - setFetchMode (adodb 4.23)
  1605.     *
  1606.     * When not in safe mode, we create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR). 
  1607.     * Assuming that we can have 50,000 files per directory with good performance, 
  1608.     * then we can scale to 12.8 million unique cached recordsets. Wow!
  1609.      */
  1610.     function _gencachename($sql,$createdir)
  1611.     {
  1612.     global $ADODB_CACHE_DIR;
  1613.     static $notSafeMode;
  1614.         
  1615.         if ($this->fetchMode === false) { 
  1616.         global $ADODB_FETCH_MODE;
  1617.             $mode = $ADODB_FETCH_MODE;
  1618.         } else {
  1619.             $mode = $this->fetchMode;
  1620.         }
  1621.         $m = md5($sql.$this->databaseType.$this->database.$this->user.$mode);
  1622.         
  1623.         if (!isset($notSafeMode)) $notSafeMode = !ini_get('safe_mode');
  1624.         $dir = ($notSafeMode) ? $ADODB_CACHE_DIR.'/'.substr($m,0,2) : $ADODB_CACHE_DIR;
  1625.             
  1626.         if ($createdir && $notSafeMode && !file_exists($dir)) {
  1627.             $oldu = umask(0);
  1628.             if (!mkdir($dir,0771)) 
  1629.                 if ($this->debug) ADOConnection::outp( "Unable to mkdir $dir for $sql");
  1630.             umask($oldu);
  1631.         }
  1632.         return $dir.'/adodb_'.$m.'.cache';
  1633.     }
  1634.     
  1635.     
  1636.     /**
  1637.      * Execute SQL, caching recordsets.
  1638.      *
  1639.      * @param [secs2cache]    seconds to cache data, set to 0 to force query. 
  1640.      *                      This is an optional parameter.
  1641.      * @param sql        SQL statement to execute
  1642.      * @param [inputarr]    holds the input data  to bind to
  1643.      * @return         RecordSet or false
  1644.      */
  1645.     function &CacheExecute($secs2cache,$sql=false,$inputarr=false)
  1646.     {
  1647.  
  1648.             
  1649.         if (!is_numeric($secs2cache)) {
  1650.             $inputarr = $sql;
  1651.             $sql = $secs2cache;
  1652.             $secs2cache = $this->cacheSecs;
  1653.         }
  1654.         
  1655.         if (is_array($sql)) {
  1656.             $sqlparam = $sql;
  1657.             $sql = $sql[0];
  1658.         } else
  1659.             $sqlparam = $sql;
  1660.             
  1661.         global $ADODB_INCLUDED_CSV;
  1662.         if (empty($ADODB_INCLUDED_CSV)) include(ADODB_DIR.'/adodb-csvlib.inc.php');
  1663.         
  1664.         $md5file = $this->_gencachename($sql.serialize($inputarr),true);
  1665.         $err = '';
  1666.         
  1667.         if ($secs2cache > 0){
  1668.             $rs = &csv2rs($md5file,$err,$secs2cache,$this->arrayClass);
  1669.             $this->numCacheHits += 1;
  1670.         } else {
  1671.             $err='Timeout 1';
  1672.             $rs = false;
  1673.             $this->numCacheMisses += 1;
  1674.         }
  1675.         if (!$rs) {
  1676.         // no cached rs found
  1677.             if ($this->debug) {
  1678.                 if (get_magic_quotes_runtime()) {
  1679.                     ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :(");
  1680.                 }
  1681.                 if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (see sql below)");
  1682.             }
  1683.             
  1684.             $rs = &$this->Execute($sqlparam,$inputarr);
  1685.  
  1686.             if ($rs) {
  1687.                 $eof = $rs->EOF;
  1688.                 $rs = &$this->_rs2rs($rs); // read entire recordset into memory immediately
  1689.                 $txt = _rs2serialize($rs,false,$sql); // serialize
  1690.         
  1691.                 if (!adodb_write_file($md5file,$txt,$this->debug)) {
  1692.                     if ($fn = $this->raiseErrorFn) {
  1693.                         $fn($this->databaseType,'CacheExecute',-32000,"Cache write error",$md5file,$sql,$this);
  1694.                     }
  1695.                     if ($this->debug) ADOConnection::outp( " Cache write error");
  1696.                 }
  1697.                 if ($rs->EOF && !$eof) {
  1698.                     $rs->MoveFirst();
  1699.                     //$rs = &csv2rs($md5file,$err);        
  1700.                     $rs->connection = &$this; // Pablo suggestion
  1701.                 }  
  1702.                 
  1703.             } else
  1704.                 @unlink($md5file);
  1705.         } else {
  1706.             $this->_errorMsg = '';
  1707.             $this->_errorCode = 0;
  1708.             
  1709.             if ($this->fnCacheExecute) {
  1710.                 $fn = $this->fnCacheExecute;
  1711.                 $fn($this, $secs2cache, $sql, $inputarr);
  1712.             }
  1713.         // ok, set cached object found
  1714.             $rs->connection = &$this; // Pablo suggestion
  1715.             if ($this->debug){ 
  1716.                     
  1717.                 $inBrowser = isset($_SERVER['HTTP_USER_AGENT']);
  1718.                 $ttl = $rs->timeCreated + $secs2cache - time();
  1719.                 $s = is_array($sql) ? $sql[0] : $sql;
  1720.                 if ($inBrowser) $s = '<i>'.htmlspecialchars($s).'</i>';
  1721.                 
  1722.                 ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]");
  1723.             }
  1724.         }
  1725.         return $rs;
  1726.     }
  1727.     
  1728.     
  1729.     /* 
  1730.         Similar to PEAR DB's autoExecute(), except that 
  1731.         $mode can be 'INSERT' or 'UPDATE' or DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE
  1732.         If $mode == 'UPDATE', then $where is compulsory as a safety measure.
  1733.         
  1734.         $forceUpdate means that even if the data has not changed, perform update.
  1735.      */
  1736.     function& AutoExecute($table, $fields_values, $mode = 'INSERT', $where = FALSE, $forceUpdate=true, $magicq=false) 
  1737.     {
  1738.         $false = false;
  1739.         $sql = 'SELECT * FROM '.$table;  
  1740.         if ($where!==FALSE) $sql .= ' WHERE '.$where;
  1741.         else if ($mode == 'UPDATE' || $mode == 2 /* DB_AUTOQUERY_UPDATE */) {
  1742.             ADOConnection::outp('AutoExecute: Illegal mode=UPDATE with empty WHERE clause');
  1743.             return $false;
  1744.         }
  1745.  
  1746.         $rs =& $this->SelectLimit($sql,1);
  1747.         if (!$rs) return $false; // table does not exist
  1748.         $rs->tableName = $table;
  1749.         
  1750.         switch((string) $mode) {
  1751.         case 'UPDATE':
  1752.         case '2':
  1753.             $sql = $this->GetUpdateSQL($rs, $fields_values, $forceUpdate, $magicq);
  1754.             break;
  1755.         case 'INSERT':
  1756.         case '1':
  1757.             $sql = $this->GetInsertSQL($rs, $fields_values, $magicq);
  1758.             break;
  1759.         default:
  1760.             ADOConnection::outp("AutoExecute: Unknown mode=$mode");
  1761.             return $false;
  1762.         }
  1763.         $ret = false;
  1764.         if ($sql) $ret = $this->Execute($sql);
  1765.         if ($ret) $ret = true;
  1766.         return $ret;
  1767.     }
  1768.     
  1769.     
  1770.     /**
  1771.      * Generates an Update Query based on an existing recordset.
  1772.      * $arrFields is an associative array of fields with the value
  1773.      * that should be assigned.
  1774.      *
  1775.      * Note: This function should only be used on a recordset
  1776.      *       that is run against a single table and sql should only 
  1777.      *         be a simple select stmt with no groupby/orderby/limit
  1778.      *
  1779.      * "Jonathan Younger" <jyounger@unilab.com>
  1780.        */
  1781.     function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=null)
  1782.     {
  1783.         global $ADODB_INCLUDED_LIB;
  1784.  
  1785.         //********************************************************//
  1786.         //This is here to maintain compatibility
  1787.         //with older adodb versions. Sets force type to force nulls if $forcenulls is set.
  1788.         if (!isset($force)) {
  1789.                 global $ADODB_FORCE_TYPE;
  1790.                 $force = $ADODB_FORCE_TYPE;
  1791.         }
  1792.         //********************************************************//
  1793.  
  1794.         if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  1795.         return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq,$force);
  1796.     }
  1797.  
  1798.     /**
  1799.      * Generates an Insert Query based on an existing recordset.
  1800.      * $arrFields is an associative array of fields with the value
  1801.      * that should be assigned.
  1802.      *
  1803.      * Note: This function should only be used on a recordset
  1804.      *       that is run against a single table.
  1805.        */
  1806.     function GetInsertSQL(&$rs, $arrFields,$magicq=false,$force=null)
  1807.     {    
  1808.         global $ADODB_INCLUDED_LIB;
  1809.         if (!isset($force)) {
  1810.             global $ADODB_FORCE_TYPE;
  1811.             $force = $ADODB_FORCE_TYPE;
  1812.             
  1813.         }
  1814.         if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  1815.         return _adodb_getinsertsql($this,$rs,$arrFields,$magicq,$force);
  1816.     }
  1817.     
  1818.  
  1819.     /**
  1820.     * Update a blob column, given a where clause. There are more sophisticated
  1821.     * blob handling functions that we could have implemented, but all require
  1822.     * a very complex API. Instead we have chosen something that is extremely
  1823.     * simple to understand and use. 
  1824.     *
  1825.     * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course.
  1826.     *
  1827.     * Usage to update a $blobvalue which has a primary key blob_id=1 into a 
  1828.     * field blobtable.blobcolumn:
  1829.     *
  1830.     *    UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1');
  1831.     *
  1832.     * Insert example:
  1833.     *
  1834.     *    $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
  1835.     *    $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
  1836.     */
  1837.     
  1838.     function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
  1839.     {
  1840.         return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
  1841.     }
  1842.  
  1843.     /**
  1844.     * Usage:
  1845.     *    UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1');
  1846.     *    
  1847.     *    $blobtype supports 'BLOB' and 'CLOB'
  1848.     *
  1849.     *    $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
  1850.     *    $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1');
  1851.     */
  1852.     function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
  1853.     {
  1854.         $fd = fopen($path,'rb');
  1855.         if ($fd === false) return false;
  1856.         $val = fread($fd,filesize($path));
  1857.         fclose($fd);
  1858.         return $this->UpdateBlob($table,$column,$val,$where,$blobtype);
  1859.     }
  1860.     
  1861.     function BlobDecode($blob)
  1862.     {
  1863.         return $blob;
  1864.     }
  1865.     
  1866.     function BlobEncode($blob)
  1867.     {
  1868.         return $blob;
  1869.     }
  1870.     
  1871.     function SetCharSet($charset)
  1872.     {
  1873.         return false;
  1874.     }
  1875.     
  1876.     function IfNull( $field, $ifNull ) 
  1877.     {
  1878.         return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";
  1879.     }
  1880.     
  1881.     function LogSQL($enable=true)
  1882.     {
  1883.         include_once(ADODB_DIR.'/adodb-perf.inc.php');
  1884.         
  1885.         if ($enable) $this->fnExecute = 'adodb_log_sql';
  1886.         else $this->fnExecute = false;
  1887.         
  1888.         $old = $this->_logsql;    
  1889.         $this->_logsql = $enable;
  1890.         if ($enable && !$old) $this->_affected = false;
  1891.         return $old;
  1892.     }
  1893.     
  1894.     function GetCharSet()
  1895.     {
  1896.         return false;
  1897.     }
  1898.     
  1899.     /**
  1900.     * Usage:
  1901.     *    UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB');
  1902.     *
  1903.     *    $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');
  1904.     *    $conn->UpdateClob('clobtable','clobcol',$clob,'id=1');
  1905.     */
  1906.     function UpdateClob($table,$column,$val,$where)
  1907.     {
  1908.         return $this->UpdateBlob($table,$column,$val,$where,'CLOB');
  1909.     }
  1910.     
  1911.     // not the fastest implementation - quick and dirty - jlim
  1912.     // for best performance, use the actual $rs->MetaType().
  1913.     function MetaType($t,$len=-1,$fieldobj=false)
  1914.     {
  1915.         
  1916.         if (empty($this->_metars)) {
  1917.             $rsclass = $this->rsPrefix.$this->databaseType;
  1918.             $this->_metars =& new $rsclass(false,$this->fetchMode); 
  1919.             $this->_metars->connection =& $this;
  1920.         }
  1921.         return $this->_metars->MetaType($t,$len,$fieldobj);
  1922.     }
  1923.     
  1924.     
  1925.     /**
  1926.     *  Change the SQL connection locale to a specified locale.
  1927.     *  This is used to get the date formats written depending on the client locale.
  1928.     */
  1929.     function SetDateLocale($locale = 'En')
  1930.     {
  1931.         $this->locale = $locale;
  1932.         switch (strtoupper($locale))
  1933.         {
  1934.             case 'EN':
  1935.                 $this->fmtDate="'Y-m-d'";
  1936.                 $this->fmtTimeStamp = "'Y-m-d H:i:s'";
  1937.                 break;
  1938.                 
  1939.             case 'US':
  1940.                 $this->fmtDate = "'m-d-Y'";
  1941.                 $this->fmtTimeStamp = "'m-d-Y H:i:s'";
  1942.                 break;
  1943.                 
  1944.             case 'NL':
  1945.             case 'FR':
  1946.             case 'RO':
  1947.             case 'IT':
  1948.                 $this->fmtDate="'d-m-Y'";
  1949.                 $this->fmtTimeStamp = "'d-m-Y H:i:s'";
  1950.                 break;
  1951.                 
  1952.             case 'GE':
  1953.                 $this->fmtDate="'d.m.Y'";
  1954.                 $this->fmtTimeStamp = "'d.m.Y H:i:s'";
  1955.                 break;
  1956.                 
  1957.             default:
  1958.                 $this->fmtDate="'Y-m-d'";
  1959.                 $this->fmtTimeStamp = "'Y-m-d H:i:s'";
  1960.                 break;
  1961.         }
  1962.     }
  1963.  
  1964.     function &GetActiveRecordsClass($class, $table,$whereOrderBy=false,$bindarr=false, $primkeyArr=false)
  1965.     {
  1966.     global $_ADODB_ACTIVE_DBS;
  1967.     
  1968.         $save = $this->SetFetchMode(ADODB_FETCH_NUM);
  1969.         if (empty($whereOrderBy)) $whereOrderBy = '1=1';
  1970.         $rows = $this->GetAll("select * from ".$table.' WHERE '.$whereOrderBy,$bindarr);
  1971.         $this->SetFetchMode($save);
  1972.         
  1973.         $false = false;
  1974.         
  1975.         if ($rows === false) {    
  1976.             return $false;
  1977.         }
  1978.         
  1979.         
  1980.         if (!isset($_ADODB_ACTIVE_DBS)) {
  1981.             include(ADODB_DIR.'/adodb-active-record.inc.php');
  1982.         }    
  1983.         if (!class_exists($class)) {
  1984.             ADOConnection::outp("Unknown class $class in GetActiveRcordsClass()");
  1985.             return $false;
  1986.         }
  1987.         $arr = array();
  1988.         foreach($rows as $row) {
  1989.         
  1990.             $obj =& new $class($table,$primkeyArr,$this);
  1991.             if ($obj->ErrorMsg()){
  1992.                 $this->_errorMsg = $obj->ErrorMsg();
  1993.                 return $false;
  1994.             }
  1995.             $obj->Set($row);
  1996.             $arr[] =& $obj;
  1997.         }
  1998.         return $arr;
  1999.     }
  2000.     
  2001.     function &GetActiveRecords($table,$where=false,$bindarr=false,$primkeyArr=false)
  2002.     {
  2003.         $arr =& $this->GetActiveRecordsClass('ADODB_Active_Record', $table, $where, $bindarr, $primkeyArr);
  2004.         return $arr;
  2005.     }
  2006.     
  2007.     /**
  2008.      * Close Connection
  2009.      */
  2010.     function Close()
  2011.     {
  2012.         $rez = $this->_close();
  2013.         $this->_connectionID = false;
  2014.         return $rez;
  2015.     }
  2016.     
  2017.     /**
  2018.      * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans().
  2019.      *
  2020.      * @return true if succeeded or false if database does not support transactions
  2021.      */
  2022.     function BeginTrans() {return false;}
  2023.     
  2024.     /* set transaction mode */
  2025.     function SetTransactionMode( $transaction_mode ) 
  2026.     {
  2027.         $transaction_mode = $this->MetaTransaction($transaction_mode, $this->dataProvider);
  2028.         $this->_transmode  = $transaction_mode;
  2029.     }
  2030. /*
  2031. http://msdn2.microsoft.com/en-US/ms173763.aspx
  2032. http://dev.mysql.com/doc/refman/5.0/en/innodb-transaction-isolation.html
  2033. http://www.postgresql.org/docs/8.1/interactive/sql-set-transaction.html
  2034. http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_10005.htm
  2035. */
  2036.     function MetaTransaction($mode,$db)
  2037.     {
  2038.         $mode = strtoupper($mode);
  2039.         $mode = str_replace('ISOLATION LEVEL ','',$mode);
  2040.         
  2041.         switch($mode) {
  2042.  
  2043.         case 'READ UNCOMMITTED':
  2044.             switch($db) { 
  2045.             case 'oci8':
  2046.             case 'oracle':
  2047.                 return 'ISOLATION LEVEL READ COMMITTED';
  2048.             default:
  2049.                 return 'ISOLATION LEVEL READ UNCOMMITTED';
  2050.             }
  2051.             break;
  2052.                     
  2053.         case 'READ COMMITTED':
  2054.                 return 'ISOLATION LEVEL READ COMMITTED';
  2055.             break;
  2056.             
  2057.         case 'REPEATABLE READ':
  2058.             switch($db) {
  2059.             case 'oci8':
  2060.             case 'oracle':
  2061.                 return 'ISOLATION LEVEL SERIALIZABLE';
  2062.             default:
  2063.                 return 'ISOLATION LEVEL REPEATABLE READ';
  2064.             }
  2065.             break;
  2066.             
  2067.         case 'SERIALIZABLE':
  2068.                 return 'ISOLATION LEVEL SERIALIZABLE';
  2069.             break;
  2070.             
  2071.         default:
  2072.             return $mode;
  2073.         }
  2074.     }
  2075.     
  2076.     /**
  2077.      * If database does not support transactions, always return true as data always commited
  2078.      *
  2079.      * @param $ok  set to false to rollback transaction, true to commit
  2080.      *
  2081.      * @return true/false.
  2082.      */
  2083.     function CommitTrans($ok=true) 
  2084.     { return true;}
  2085.     
  2086.     
  2087.     /**
  2088.      * If database does not support transactions, rollbacks always fail, so return false
  2089.      *
  2090.      * @return true/false.
  2091.      */
  2092.     function RollbackTrans() 
  2093.     { return false;}
  2094.  
  2095.  
  2096.     /**
  2097.      * return the databases that the driver can connect to. 
  2098.      * Some databases will return an empty array.
  2099.      *
  2100.      * @return an array of database names.
  2101.      */
  2102.         function MetaDatabases() 
  2103.         {
  2104.         global $ADODB_FETCH_MODE;
  2105.         
  2106.             if ($this->metaDatabasesSQL) {
  2107.                 $save = $ADODB_FETCH_MODE; 
  2108.                 $ADODB_FETCH_MODE = ADODB_FETCH_NUM; 
  2109.                 
  2110.                 if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
  2111.                 
  2112.                 $arr = $this->GetCol($this->metaDatabasesSQL);
  2113.                 if (isset($savem)) $this->SetFetchMode($savem);
  2114.                 $ADODB_FETCH_MODE = $save; 
  2115.             
  2116.                 return $arr;
  2117.             }
  2118.             
  2119.             return false;
  2120.         }
  2121.     
  2122.         
  2123.     /**
  2124.      * @param ttype can either be 'VIEW' or 'TABLE' or false. 
  2125.      *         If false, both views and tables are returned.
  2126.      *        "VIEW" returns only views
  2127.      *        "TABLE" returns only tables
  2128.      * @param showSchema returns the schema/user with the table name, eg. USER.TABLE
  2129.      * @param mask  is the input mask - only supported by oci8 and postgresql
  2130.      *
  2131.      * @return  array of tables for current database.
  2132.      */ 
  2133.     function &MetaTables($ttype=false,$showSchema=false,$mask=false) 
  2134.     {
  2135.     global $ADODB_FETCH_MODE;
  2136.     
  2137.         
  2138.         $false = false;
  2139.         if ($mask) {
  2140.             return $false;
  2141.         }
  2142.         if ($this->metaTablesSQL) {
  2143.             $save = $ADODB_FETCH_MODE; 
  2144.             $ADODB_FETCH_MODE = ADODB_FETCH_NUM; 
  2145.             
  2146.             if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
  2147.             
  2148.             $rs = $this->Execute($this->metaTablesSQL);
  2149.             if (isset($savem)) $this->SetFetchMode($savem);
  2150.             $ADODB_FETCH_MODE = $save; 
  2151.             
  2152.             if ($rs === false) return $false;
  2153.             $arr =& $rs->GetArray();
  2154.             $arr2 = array();
  2155.             
  2156.             if ($hast = ($ttype && isset($arr[0][1]))) { 
  2157.                 $showt = strncmp($ttype,'T',1);
  2158.             }
  2159.             
  2160.             for ($i=0; $i < sizeof($arr); $i++) {
  2161.                 if ($hast) {
  2162.                     if ($showt == 0) {
  2163.                         if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);
  2164.                     } else {
  2165.                         if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);
  2166.                     }
  2167.                 } else
  2168.                     $arr2[] = trim($arr[$i][0]);
  2169.             }
  2170.             $rs->Close();
  2171.             return $arr2;
  2172.         }
  2173.         return $false;
  2174.     }
  2175.     
  2176.     
  2177.     function _findschema(&$table,&$schema)
  2178.     {
  2179.         if (!$schema && ($at = strpos($table,'.')) !== false) {
  2180.             $schema = substr($table,0,$at);
  2181.             $table = substr($table,$at+1);
  2182.         }
  2183.     }
  2184.     
  2185.     /**
  2186.      * List columns in a database as an array of ADOFieldObjects. 
  2187.      * See top of file for definition of object.
  2188.      *
  2189.      * @param $table    table name to query
  2190.      * @param $normalize    makes table name case-insensitive (required by some databases)
  2191.      * @schema is optional database schema to use - not supported by all databases.
  2192.      *
  2193.      * @return  array of ADOFieldObjects for current table.
  2194.      */
  2195.     function &MetaColumns($table,$normalize=true) 
  2196.     {
  2197.     global $ADODB_FETCH_MODE;
  2198.         
  2199.         $false = false;
  2200.         
  2201.         if (!empty($this->metaColumnsSQL)) {
  2202.         
  2203.             $schema = false;
  2204.             $this->_findschema($table,$schema);
  2205.         
  2206.             $save = $ADODB_FETCH_MODE;
  2207.             $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
  2208.             if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
  2209.             $rs = $this->Execute(sprintf($this->metaColumnsSQL,($normalize)?strtoupper($table):$table));
  2210.             if (isset($savem)) $this->SetFetchMode($savem);
  2211.             $ADODB_FETCH_MODE = $save;
  2212.             if ($rs === false || $rs->EOF) return $false;
  2213.  
  2214.             $retarr = array();
  2215.             while (!$rs->EOF) { //print_r($rs->fields);
  2216.                 $fld = new ADOFieldObject();
  2217.                 $fld->name = $rs->fields[0];
  2218.                 $fld->type = $rs->fields[1];
  2219.                 if (isset($rs->fields[3]) && $rs->fields[3]) {
  2220.                     if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3];
  2221.                     $fld->scale = $rs->fields[4];
  2222.                     if ($fld->scale>0) $fld->max_length += 1;
  2223.                 } else
  2224.                     $fld->max_length = $rs->fields[2];
  2225.                     
  2226.                 if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;    
  2227.                 else $retarr[strtoupper($fld->name)] = $fld;
  2228.                 $rs->MoveNext();
  2229.             }
  2230.             $rs->Close();
  2231.             return $retarr;    
  2232.         }
  2233.         return $false;
  2234.     }
  2235.     
  2236.     /**
  2237.       * List indexes on a table as an array.
  2238.       * @param table  table name to query
  2239.       * @param primary true to only show primary keys. Not actually used for most databases
  2240.       *
  2241.       * @return array of indexes on current table. Each element represents an index, and is itself an associative array.
  2242.       
  2243.          Array (
  2244.             [name_of_index] => Array
  2245.               (
  2246.               [unique] => true or false
  2247.               [columns] => Array
  2248.               (
  2249.                   [0] => firstname
  2250.                   [1] => lastname
  2251.               )
  2252.         )        
  2253.       */
  2254.      function &MetaIndexes($table, $primary = false, $owner = false)
  2255.      {
  2256.              $false = false;
  2257.             return $false;
  2258.      }
  2259.  
  2260.     /**
  2261.      * List columns names in a table as an array. 
  2262.      * @param table    table name to query
  2263.      *
  2264.      * @return  array of column names for current table.
  2265.      */ 
  2266.     function &MetaColumnNames($table, $numIndexes=false,$useattnum=false /* only for postgres */) 
  2267.     {
  2268.         $objarr =& $this->MetaColumns($table);
  2269.         if (!is_array($objarr)) {
  2270.             $false = false;
  2271.             return $false;
  2272.         }
  2273.         $arr = array();
  2274.         if ($numIndexes) {
  2275.             $i = 0;
  2276.             if ($useattnum) {
  2277.                 foreach($objarr as $v) 
  2278.                     $arr[$v->attnum] = $v->name;
  2279.                 
  2280.             } else
  2281.                 foreach($objarr as $v) $arr[$i++] = $v->name;
  2282.         } else
  2283.             foreach($objarr as $v) $arr[strtoupper($v->name)] = $v->name;
  2284.         
  2285.         return $arr;
  2286.     }
  2287.             
  2288.     /**
  2289.      * Different SQL databases used different methods to combine strings together.
  2290.      * This function provides a wrapper. 
  2291.      * 
  2292.      * param s    variable number of string parameters
  2293.      *
  2294.      * Usage: $db->Concat($str1,$str2);
  2295.      * 
  2296.      * @return concatenated string
  2297.      */      
  2298.     function Concat()
  2299.     {    
  2300.         $arr = func_get_args();
  2301.         return implode($this->concat_operator, $arr);
  2302.     }
  2303.     
  2304.     
  2305.     /**
  2306.      * Converts a date "d" to a string that the database can understand.
  2307.      *
  2308.      * @param d    a date in Unix date time format.
  2309.      *
  2310.      * @return  date string in database date format
  2311.      */
  2312.     function DBDate($d)
  2313.     {
  2314.         if (empty($d) && $d !== 0) return 'null';
  2315.  
  2316.         if (is_string($d) && !is_numeric($d)) {
  2317.             if ($d === 'null' || strncmp($d,"'",1) === 0) return $d;
  2318.             if ($this->isoDates) return "'$d'";
  2319.             $d = ADOConnection::UnixDate($d);
  2320.         }
  2321.  
  2322.         return adodb_date($this->fmtDate,$d);
  2323.     }
  2324.     
  2325.     function BindDate($d)
  2326.     {
  2327.         $d = $this->DBDate($d);
  2328.         if (strncmp($d,"'",1)) return $d;
  2329.         
  2330.         return substr($d,1,strlen($d)-2);
  2331.     }
  2332.     
  2333.     function BindTimeStamp($d)
  2334.     {
  2335.         $d = $this->DBTimeStamp($d);
  2336.         if (strncmp($d,"'",1)) return $d;
  2337.         
  2338.         return substr($d,1,strlen($d)-2);
  2339.     }
  2340.     
  2341.     
  2342.     /**
  2343.      * Converts a timestamp "ts" to a string that the database can understand.
  2344.      *
  2345.      * @param ts    a timestamp in Unix date time format.
  2346.      *
  2347.      * @return  timestamp string in database timestamp format
  2348.      */
  2349.     function DBTimeStamp($ts)
  2350.     {
  2351.         if (empty($ts) && $ts !== 0) return 'null';
  2352.  
  2353.         # strlen(14) allows YYYYMMDDHHMMSS format
  2354.         if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14)) 
  2355.             return adodb_date($this->fmtTimeStamp,$ts);
  2356.         
  2357.         if ($ts === 'null') return $ts;
  2358.         if ($this->isoDates && strlen($ts) !== 14) return "'$ts'";
  2359.         
  2360.         $ts = ADOConnection::UnixTimeStamp($ts);
  2361.         return adodb_date($this->fmtTimeStamp,$ts);
  2362.     }
  2363.     
  2364.     /**
  2365.      * Also in ADORecordSet.
  2366.      * @param $v is a date string in YYYY-MM-DD format
  2367.      *
  2368.      * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
  2369.      */
  2370.     function UnixDate($v)
  2371.     {
  2372.         if (is_object($v)) {
  2373.         // odbtp support
  2374.         //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
  2375.             return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year);
  2376.         }
  2377.     
  2378.         if (is_numeric($v) && strlen($v) !== 8) return $v;
  2379.         if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|", 
  2380.             ($v), $rr)) return false;
  2381.  
  2382.         if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;
  2383.         // h-m-s-MM-DD-YY
  2384.         return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
  2385.     }
  2386.     
  2387.  
  2388.     /**
  2389.      * Also in ADORecordSet.
  2390.      * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
  2391.      *
  2392.      * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
  2393.      */
  2394.     function UnixTimeStamp($v)
  2395.     {
  2396.         if (is_object($v)) {
  2397.         // odbtp support
  2398.         //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
  2399.             return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year);
  2400.         }
  2401.         
  2402.         if (!preg_match( 
  2403.             "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|", 
  2404.             ($v), $rr)) return false;
  2405.             
  2406.         if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
  2407.     
  2408.         // h-m-s-MM-DD-YY
  2409.         if (!isset($rr[5])) return  adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
  2410.         return  @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
  2411.     }
  2412.     
  2413.     /**
  2414.      * Also in ADORecordSet.
  2415.      *
  2416.      * Format database date based on user defined format.
  2417.      *
  2418.      * @param v      is the character date in YYYY-MM-DD format, returned by database
  2419.      * @param fmt     is the format to apply to it, using date()
  2420.      *
  2421.      * @return a date formated as user desires
  2422.      */
  2423.      
  2424.     function UserDate($v,$fmt='Y-m-d',$gmt=false)
  2425.     {
  2426.         $tt = $this->UnixDate($v);
  2427.  
  2428.         // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
  2429.         if (($tt === false || $tt == -1) && $v != false) return $v;
  2430.         else if ($tt == 0) return $this->emptyDate;
  2431.         else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
  2432.         }
  2433.         
  2434.         return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
  2435.     
  2436.     }
  2437.     
  2438.         /**
  2439.      *
  2440.      * @param v      is the character timestamp in YYYY-MM-DD hh:mm:ss format
  2441.      * @param fmt     is the format to apply to it, using date()
  2442.      *
  2443.      * @return a timestamp formated as user desires
  2444.      */
  2445.     function UserTimeStamp($v,$fmt='Y-m-d H:i:s',$gmt=false)
  2446.     {
  2447.         if (!isset($v)) return $this->emptyTimeStamp;
  2448.         # strlen(14) allows YYYYMMDDHHMMSS format
  2449.         if (is_numeric($v) && strlen($v)<14) return ($gmt) ? adodb_gmdate($fmt,$v) : adodb_date($fmt,$v);
  2450.         $tt = $this->UnixTimeStamp($v);
  2451.         // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
  2452.         if (($tt === false || $tt == -1) && $v != false) return $v;
  2453.         if ($tt == 0) return $this->emptyTimeStamp;
  2454.         return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
  2455.     }
  2456.     
  2457.     function escape($s,$magic_quotes=false)
  2458.     {
  2459.         return $this->addq($s,$magic_quotes);
  2460.     }
  2461.     
  2462.     /**
  2463.     * Quotes a string, without prefixing nor appending quotes. 
  2464.     */
  2465.     function addq($s,$magic_quotes=false)
  2466.     {
  2467.         if (!$magic_quotes) {
  2468.         
  2469.             if ($this->replaceQuote[0] == '\\'){
  2470.                 // only since php 4.0.5
  2471.                 $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
  2472.                 //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
  2473.             }
  2474.             return  str_replace("'",$this->replaceQuote,$s);
  2475.         }
  2476.         
  2477.         // undo magic quotes for "
  2478.         $s = str_replace('\\"','"',$s);
  2479.         
  2480.         if ($this->replaceQuote == "\\'")  // ' already quoted, no need to change anything
  2481.             return $s;
  2482.         else {// change \' to '' for sybase/mssql
  2483.             $s = str_replace('\\\\','\\',$s);
  2484.             return str_replace("\\'",$this->replaceQuote,$s);
  2485.         }
  2486.     }
  2487.     
  2488.     /**
  2489.      * Correctly quotes a string so that all strings are escaped. We prefix and append
  2490.      * to the string single-quotes.
  2491.      * An example is  $db->qstr("Don't bother",magic_quotes_runtime());
  2492.      * 
  2493.      * @param s            the string to quote
  2494.      * @param [magic_quotes]    if $s is GET/POST var, set to get_magic_quotes_gpc().
  2495.      *                This undoes the stupidity of magic quotes for GPC.
  2496.      *
  2497.      * @return  quoted string to be sent back to database
  2498.      */
  2499.     function qstr($s,$magic_quotes=false)
  2500.     {    
  2501.         if (!$magic_quotes) {
  2502.         
  2503.             if ($this->replaceQuote[0] == '\\'){
  2504.                 // only since php 4.0.5
  2505.                 $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
  2506.                 //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
  2507.             }
  2508.             return  "'".str_replace("'",$this->replaceQuote,$s)."'";
  2509.         }
  2510.         
  2511.         // undo magic quotes for "
  2512.         $s = str_replace('\\"','"',$s);
  2513.         
  2514.         if ($this->replaceQuote == "\\'")  // ' already quoted, no need to change anything
  2515.             return "'$s'";
  2516.         else {// change \' to '' for sybase/mssql
  2517.             $s = str_replace('\\\\','\\',$s);
  2518.             return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
  2519.         }
  2520.     }
  2521.     
  2522.     
  2523.     /**
  2524.     * Will select the supplied $page number from a recordset, given that it is paginated in pages of 
  2525.     * $nrows rows per page. It also saves two boolean values saying if the given page is the first 
  2526.     * and/or last one of the recordset. Added by Ivßn Oliva to provide recordset pagination.
  2527.     *
  2528.     * See readme.htm#ex8 for an example of usage.
  2529.     *
  2530.     * @param sql
  2531.     * @param nrows        is the number of rows per page to get
  2532.     * @param page        is the page number to get (1-based)
  2533.     * @param [inputarr]    array of bind variables
  2534.     * @param [secs2cache]        is a private parameter only used by jlim
  2535.     * @return        the recordset ($rs->databaseType == 'array')
  2536.     *
  2537.     * NOTE: phpLens uses a different algorithm and does not use PageExecute().
  2538.     *
  2539.     */
  2540.     function &PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0) 
  2541.     {
  2542.         global $ADODB_INCLUDED_LIB;
  2543.         if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  2544.         if ($this->pageExecuteCountRows) $rs =& _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache);
  2545.         else $rs =& _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache);
  2546.         return $rs;
  2547.     }
  2548.     
  2549.         
  2550.     /**
  2551.     * Will select the supplied $page number from a recordset, given that it is paginated in pages of 
  2552.     * $nrows rows per page. It also saves two boolean values saying if the given page is the first 
  2553.     * and/or last one of the recordset. Added by Ivßn Oliva to provide recordset pagination.
  2554.     *
  2555.     * @param secs2cache    seconds to cache data, set to 0 to force query
  2556.     * @param sql
  2557.     * @param nrows        is the number of rows per page to get
  2558.     * @param page        is the page number to get (1-based)
  2559.     * @param [inputarr]    array of bind variables
  2560.     * @return        the recordset ($rs->databaseType == 'array')
  2561.     */
  2562.     function &CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false) 
  2563.     {
  2564.         /*switch($this->dataProvider) {
  2565.         case 'postgres':
  2566.         case 'mysql': 
  2567.             break;
  2568.         default: $secs2cache = 0; break;
  2569.         }*/
  2570.         $rs =& $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache);
  2571.         return $rs;
  2572.     }
  2573.  
  2574. } // end class ADOConnection
  2575.     
  2576.     
  2577.     
  2578.     //==============================================================================================    
  2579.     // CLASS ADOFetchObj
  2580.     //==============================================================================================    
  2581.         
  2582.     /**
  2583.     * Internal placeholder for record objects. Used by ADORecordSet->FetchObj().
  2584.     */
  2585.     class ADOFetchObj {
  2586.     };
  2587.     
  2588.     //==============================================================================================    
  2589.     // CLASS ADORecordSet_empty
  2590.     //==============================================================================================    
  2591.     
  2592.     /**
  2593.     * Lightweight recordset when there are no records to be returned
  2594.     */
  2595.     class ADORecordSet_empty
  2596.     {
  2597.         var $dataProvider = 'empty';
  2598.         var $databaseType = false;
  2599.         var $EOF = true;
  2600.         var $_numOfRows = 0;
  2601.         var $fields = false;
  2602.         var $connection = false;
  2603.         function RowCount() {return 0;}
  2604.         function RecordCount() {return 0;}
  2605.         function PO_RecordCount(){return 0;}
  2606.         function Close(){return true;}
  2607.         function FetchRow() {return false;}
  2608.         function FieldCount(){ return 0;}
  2609.         function Init() {}
  2610.     }
  2611.     
  2612.     //==============================================================================================    
  2613.     // DATE AND TIME FUNCTIONS
  2614.     //==============================================================================================    
  2615.     if (!defined('ADODB_DATE_VERSION')) include(ADODB_DIR.'/adodb-time.inc.php');
  2616.     
  2617.     //==============================================================================================    
  2618.     // CLASS ADORecordSet
  2619.     //==============================================================================================    
  2620.  
  2621.     if (PHP_VERSION < 5) include_once(ADODB_DIR.'/adodb-php4.inc.php');
  2622.     else include_once(ADODB_DIR.'/adodb-iterator.inc.php');
  2623.    /**
  2624.      * RecordSet class that represents the dataset returned by the database.
  2625.      * To keep memory overhead low, this class holds only the current row in memory.
  2626.      * No prefetching of data is done, so the RecordCount() can return -1 ( which
  2627.      * means recordcount not known).
  2628.      */
  2629.     class ADORecordSet extends ADODB_BASE_RS {
  2630.     /*
  2631.      * public variables    
  2632.      */
  2633.     var $dataProvider = "native";
  2634.     var $fields = false;     /// holds the current row data
  2635.     var $blobSize = 100;     /// any varchar/char field this size or greater is treated as a blob
  2636.                             /// in other words, we use a text area for editing.
  2637.     var $canSeek = false;     /// indicates that seek is supported
  2638.     var $sql;                 /// sql text
  2639.     var $EOF = false;        /// Indicates that the current record position is after the last record in a Recordset object. 
  2640.     
  2641.     var $emptyTimeStamp = ' '; /// what to display when $time==0
  2642.     var $emptyDate = ' '; /// what to display when $time==0
  2643.     var $debug = false;
  2644.     var $timeCreated=0;     /// datetime in Unix format rs created -- for cached recordsets
  2645.  
  2646.     var $bind = false;         /// used by Fields() to hold array - should be private?
  2647.     var $fetchMode;            /// default fetch mode
  2648.     var $connection = false; /// the parent connection
  2649.     /*
  2650.      *    private variables    
  2651.      */
  2652.     var $_numOfRows = -1;    /** number of rows, or -1 */
  2653.     var $_numOfFields = -1;    /** number of fields in recordset */
  2654.     var $_queryID = -1;        /** This variable keeps the result link identifier.    */
  2655.     var $_currentRow = -1;    /** This variable keeps the current row in the Recordset.    */
  2656.     var $_closed = false;     /** has recordset been closed */
  2657.     var $_inited = false;     /** Init() should only be called once */
  2658.     var $_obj;                 /** Used by FetchObj */
  2659.     var $_names;            /** Used by FetchObj */
  2660.     
  2661.     var $_currentPage = -1;    /** Added by Ivßn Oliva to implement recordset pagination */
  2662.     var $_atFirstPage = false;    /** Added by Ivßn Oliva to implement recordset pagination */
  2663.     var $_atLastPage = false;    /** Added by Ivßn Oliva to implement recordset pagination */
  2664.     var $_lastPageNo = -1; 
  2665.     var $_maxRecordCount = 0;
  2666.     var $datetime = false;
  2667.     
  2668.     /**
  2669.      * Constructor
  2670.      *
  2671.      * @param queryID      this is the queryID returned by ADOConnection->_query()
  2672.      *
  2673.      */
  2674.     function ADORecordSet($queryID) 
  2675.     {
  2676.         $this->_queryID = $queryID;
  2677.     }
  2678.     
  2679.     
  2680.     
  2681.     function Init()
  2682.     {
  2683.         if ($this->_inited) return;
  2684.         $this->_inited = true;
  2685.         if ($this->_queryID) @$this->_initrs();
  2686.         else {
  2687.             $this->_numOfRows = 0;
  2688.             $this->_numOfFields = 0;
  2689.         }
  2690.         if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) {
  2691.             
  2692.             $this->_currentRow = 0;
  2693.             if ($this->EOF = ($this->_fetch() === false)) {
  2694.                 $this->_numOfRows = 0; // _numOfRows could be -1
  2695.             }
  2696.         } else {
  2697.             $this->EOF = true;
  2698.         }
  2699.     }
  2700.     
  2701.     
  2702.     /**
  2703.      * Generate a SELECT tag string from a recordset, and return the string.
  2704.      * If the recordset has 2 cols, we treat the 1st col as the containing 
  2705.      * the text to display to the user, and 2nd col as the return value. Default
  2706.      * strings are compared with the FIRST column.
  2707.      *
  2708.      * @param name          name of SELECT tag
  2709.      * @param [defstr]        the value to hilite. Use an array for multiple hilites for listbox.
  2710.      * @param [blank1stItem]    true to leave the 1st item in list empty
  2711.      * @param [multiple]        true for listbox, false for popup
  2712.      * @param [size]        #rows to show for listbox. not used by popup
  2713.      * @param [selectAttr]        additional attributes to defined for SELECT tag.
  2714.      *                useful for holding javascript onChange='...' handlers.
  2715.      & @param [compareFields0]    when we have 2 cols in recordset, we compare the defstr with 
  2716.      *                column 0 (1st col) if this is true. This is not documented.
  2717.      *
  2718.      * @return HTML
  2719.      *
  2720.      * changes by glen.davies@cce.ac.nz to support multiple hilited items
  2721.      */
  2722.     function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false,
  2723.             $size=0, $selectAttr='',$compareFields0=true)
  2724.     {
  2725.         global $ADODB_INCLUDED_LIB;
  2726.         if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  2727.         return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple,
  2728.             $size, $selectAttr,$compareFields0);
  2729.     }
  2730.     
  2731.  
  2732.     
  2733.     /**
  2734.      * Generate a SELECT tag string from a recordset, and return the string.
  2735.      * If the recordset has 2 cols, we treat the 1st col as the containing 
  2736.      * the text to display to the user, and 2nd col as the return value. Default
  2737.      * strings are compared with the SECOND column.
  2738.      *
  2739.      */
  2740.     function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='')    
  2741.     {
  2742.         return $this->GetMenu($name,$defstr,$blank1stItem,$multiple,
  2743.             $size, $selectAttr,false);
  2744.     }
  2745.     
  2746.     /*
  2747.         Grouped Menu
  2748.     */
  2749.     function GetMenu3($name,$defstr='',$blank1stItem=true,$multiple=false,
  2750.             $size=0, $selectAttr='')
  2751.     {
  2752.         global $ADODB_INCLUDED_LIB;
  2753.         if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  2754.         return _adodb_getmenu_gp($this, $name,$defstr,$blank1stItem,$multiple,
  2755.             $size, $selectAttr,false);
  2756.     }
  2757.  
  2758.     /**
  2759.      * return recordset as a 2-dimensional array.
  2760.      *
  2761.      * @param [nRows]  is the number of rows to return. -1 means every row.
  2762.      *
  2763.      * @return an array indexed by the rows (0-based) from the recordset
  2764.      */
  2765.     function &GetArray($nRows = -1) 
  2766.     {
  2767.     global $ADODB_EXTENSION; if ($ADODB_EXTENSION) {
  2768.         $results = adodb_getall($this,$nRows);
  2769.         return $results;
  2770.     }
  2771.         $results = array();
  2772.         $cnt = 0;
  2773.         while (!$this->EOF && $nRows != $cnt) {
  2774.             $results[] = $this->fields;
  2775.             $this->MoveNext();
  2776.             $cnt++;
  2777.         }
  2778.         return $results;
  2779.     }
  2780.     
  2781.     function &GetAll($nRows = -1)
  2782.     {
  2783.         $arr =& $this->GetArray($nRows);
  2784.         return $arr;
  2785.     }
  2786.     
  2787.     /*
  2788.     * Some databases allow multiple recordsets to be returned. This function
  2789.     * will return true if there is a next recordset, or false if no more.
  2790.     */
  2791.     function NextRecordSet()
  2792.     {
  2793.         return false;
  2794.     }
  2795.     
  2796.     /**
  2797.      * return recordset as a 2-dimensional array. 
  2798.      * Helper function for ADOConnection->SelectLimit()
  2799.      *
  2800.      * @param offset    is the row to start calculations from (1-based)
  2801.      * @param [nrows]    is the number of rows to return
  2802.      *
  2803.      * @return an array indexed by the rows (0-based) from the recordset
  2804.      */
  2805.     function &GetArrayLimit($nrows,$offset=-1) 
  2806.     {    
  2807.         if ($offset <= 0) {
  2808.             $arr =& $this->GetArray($nrows);
  2809.             return $arr;
  2810.         } 
  2811.         
  2812.         $this->Move($offset);
  2813.         
  2814.         $results = array();
  2815.         $cnt = 0;
  2816.         while (!$this->EOF && $nrows != $cnt) {
  2817.             $results[$cnt++] = $this->fields;
  2818.             $this->MoveNext();
  2819.         }
  2820.         
  2821.         return $results;
  2822.     }
  2823.     
  2824.     
  2825.     /**
  2826.      * Synonym for GetArray() for compatibility with ADO.
  2827.      *
  2828.      * @param [nRows]  is the number of rows to return. -1 means every row.
  2829.      *
  2830.      * @return an array indexed by the rows (0-based) from the recordset
  2831.      */
  2832.     function &GetRows($nRows = -1) 
  2833.     {
  2834.         $arr =& $this->GetArray($nRows);
  2835.         return $arr;
  2836.     }
  2837.     
  2838.     /**
  2839.      * return whole recordset as a 2-dimensional associative array if there are more than 2 columns. 
  2840.      * The first column is treated as the key and is not included in the array. 
  2841.      * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless
  2842.      * $force_array == true.
  2843.      *
  2844.      * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional
  2845.      *     array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing,
  2846.      *     read the source.
  2847.      *
  2848.      * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and 
  2849.      * instead of returning array[col0] => array(remaining cols), return array[col0] => col1
  2850.      *
  2851.      * @return an associative array indexed by the first column of the array, 
  2852.      *     or false if the  data has less than 2 cols.
  2853.      */
  2854.     function &GetAssoc($force_array = false, $first2cols = false) 
  2855.     {
  2856.     global $ADODB_EXTENSION;
  2857.     
  2858.         $cols = $this->_numOfFields;
  2859.         if ($cols < 2) {
  2860.             $false = false;
  2861.             return $false;
  2862.         }
  2863.         $numIndex = isset($this->fields[0]);
  2864.         $results = array();
  2865.         
  2866.         if (!$first2cols && ($cols > 2 || $force_array)) {
  2867.             if ($ADODB_EXTENSION) {
  2868.                 if ($numIndex) {
  2869.                     while (!$this->EOF) {
  2870.                         // $results[trim($this->fields[0])] = array_slice($this->fields, 1);
  2871.                         // Fix for array_slice re-numbering numeric associative keys in PHP5
  2872.                         $keys = array_slice(array_keys($this->fields), 1);
  2873.                         $sliced_array = array();
  2874.  
  2875.                         foreach($keys as $key) {
  2876.                             $sliced_array[$key] = $this->fields[$key];
  2877.                         }
  2878.                         
  2879.                         $results[trim(reset($this->fields))] = $sliced_array;
  2880.  
  2881.                         adodb_movenext($this);
  2882.                     }
  2883.                 } else {
  2884.                     while (!$this->EOF) {
  2885.                         $results[trim(reset($this->fields))] = array_slice($this->fields, 1);
  2886.                         adodb_movenext($this);
  2887.                     }
  2888.                 }
  2889.             } else {
  2890.                 if ($numIndex) {
  2891.                     while (!$this->EOF) {
  2892.                         //$results[trim($this->fields[0])] = array_slice($this->fields, 1);
  2893.                         // Fix for array_slice re-numbering numeric associative keys in PHP5
  2894.                         $keys = array_slice(array_keys($this->fields), 1);
  2895.                         $sliced_array = array();
  2896.  
  2897.                         foreach($keys as $key) {
  2898.                             $sliced_array[$key] = $this->fields[$key];
  2899.                         }
  2900.                         
  2901.                         $results[trim(reset($this->fields))] = $sliced_array;
  2902.                         $this->MoveNext();
  2903.                     }
  2904.                 } else {
  2905.                     while (!$this->EOF) {
  2906.                         $results[trim(reset($this->fields))] = array_slice($this->fields, 1);
  2907.                         $this->MoveNext();
  2908.                     }
  2909.                 }
  2910.             }
  2911.         } else {
  2912.             if ($ADODB_EXTENSION) {
  2913.                 // return scalar values
  2914.                 if ($numIndex) {
  2915.                     while (!$this->EOF) {
  2916.                     // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
  2917.                         $results[trim(($this->fields[0]))] = $this->fields[1];
  2918.                         adodb_movenext($this);
  2919.                     }
  2920.                 } else {
  2921.                     while (!$this->EOF) {
  2922.                     // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
  2923.                         $v1 = trim(reset($this->fields));
  2924.                         $v2 = ''.next($this->fields); 
  2925.                         $results[$v1] = $v2;
  2926.                         adodb_movenext($this);
  2927.                     }
  2928.                 }
  2929.             } else {
  2930.                 if ($numIndex) {
  2931.                     while (!$this->EOF) {
  2932.                     // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
  2933.                         $results[trim(($this->fields[0]))] = $this->fields[1];
  2934.                         $this->MoveNext();
  2935.                     }
  2936.                 } else {
  2937.                     while (!$this->EOF) {
  2938.                     // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
  2939.                         $v1 = trim(reset($this->fields));
  2940.                         $v2 = ''.next($this->fields); 
  2941.                         $results[$v1] = $v2;
  2942.                         $this->MoveNext();
  2943.                     }
  2944.                 }
  2945.             }
  2946.         }
  2947.         
  2948.         $ref =& $results; # workaround accelerator incompat with PHP 4.4 :(
  2949.         return $ref; 
  2950.     }
  2951.     
  2952.     
  2953.     /**
  2954.      *
  2955.      * @param v      is the character timestamp in YYYY-MM-DD hh:mm:ss format
  2956.      * @param fmt     is the format to apply to it, using date()
  2957.      *
  2958.      * @return a timestamp formated as user desires
  2959.      */
  2960.     function UserTimeStamp($v,$fmt='Y-m-d H:i:s')
  2961.     {
  2962.         if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);
  2963.         $tt = $this->UnixTimeStamp($v);
  2964.         // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
  2965.         if (($tt === false || $tt == -1) && $v != false) return $v;
  2966.         if ($tt === 0) return $this->emptyTimeStamp;
  2967.         return adodb_date($fmt,$tt);
  2968.     }
  2969.     
  2970.     
  2971.     /**
  2972.      * @param v      is the character date in YYYY-MM-DD format, returned by database
  2973.      * @param fmt     is the format to apply to it, using date()
  2974.      *
  2975.      * @return a date formated as user desires
  2976.      */
  2977.     function UserDate($v,$fmt='Y-m-d')
  2978.     {
  2979.         $tt = $this->UnixDate($v);
  2980.         // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
  2981.         if (($tt === false || $tt == -1) && $v != false) return $v;
  2982.         else if ($tt == 0) return $this->emptyDate;
  2983.         else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
  2984.         }
  2985.         return adodb_date($fmt,$tt);
  2986.     }
  2987.     
  2988.     
  2989.     /**
  2990.      * @param $v is a date string in YYYY-MM-DD format
  2991.      *
  2992.      * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
  2993.      */
  2994.     function UnixDate($v)
  2995.     {
  2996.         return ADOConnection::UnixDate($v);
  2997.     }
  2998.     
  2999.  
  3000.     /**
  3001.      * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
  3002.      *
  3003.      * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
  3004.      */
  3005.     function UnixTimeStamp($v)
  3006.     {
  3007.         return ADOConnection::UnixTimeStamp($v);
  3008.     }
  3009.     
  3010.     
  3011.     /**
  3012.     * PEAR DB Compat - do not use internally
  3013.     */
  3014.     function Free()
  3015.     {
  3016.         return $this->Close();
  3017.     }
  3018.     
  3019.     
  3020.     /**
  3021.     * PEAR DB compat, number of rows
  3022.     */
  3023.     function NumRows()
  3024.     {
  3025.         return $this->_numOfRows;
  3026.     }
  3027.     
  3028.     
  3029.     /**
  3030.     * PEAR DB compat, number of cols
  3031.     */
  3032.     function NumCols()
  3033.     {
  3034.         return $this->_numOfFields;
  3035.     }
  3036.     
  3037.     /**
  3038.     * Fetch a row, returning false if no more rows. 
  3039.     * This is PEAR DB compat mode.
  3040.     *
  3041.     * @return false or array containing the current record
  3042.     */
  3043.     function &FetchRow()
  3044.     {
  3045.         if ($this->EOF) {
  3046.             $false = false;
  3047.             return $false;
  3048.         }
  3049.         $arr = $this->fields;
  3050.         $this->_currentRow++;
  3051.         if (!$this->_fetch()) $this->EOF = true;
  3052.         return $arr;
  3053.     }
  3054.     
  3055.     
  3056.     /**
  3057.     * Fetch a row, returning PEAR_Error if no more rows. 
  3058.     * This is PEAR DB compat mode.
  3059.     *
  3060.     * @return DB_OK or error object
  3061.     */
  3062.     function FetchInto(&$arr)
  3063.     {
  3064.         if ($this->EOF) return (defined('PEAR_ERROR_RETURN')) ? new PEAR_Error('EOF',-1): false;
  3065.         $arr = $this->fields;
  3066.         $this->MoveNext();
  3067.         return 1; // DB_OK
  3068.     }
  3069.     
  3070.     
  3071.     /**
  3072.      * Move to the first row in the recordset. Many databases do NOT support this.
  3073.      *
  3074.      * @return true or false
  3075.      */
  3076.     function MoveFirst() 
  3077.     {
  3078.         if ($this->_currentRow == 0) return true;
  3079.         return $this->Move(0);            
  3080.     }            
  3081.  
  3082.     
  3083.     /**
  3084.      * Move to the last row in the recordset. 
  3085.      *
  3086.      * @return true or false
  3087.      */
  3088.     function MoveLast() 
  3089.     {
  3090.         if ($this->_numOfRows >= 0) return $this->Move($this->_numOfRows-1);
  3091.         if ($this->EOF) return false;
  3092.         while (!$this->EOF) {
  3093.             $f = $this->fields;
  3094.             $this->MoveNext();
  3095.         }
  3096.         $this->fields = $f;
  3097.         $this->EOF = false;
  3098.         return true;
  3099.     }
  3100.     
  3101.     
  3102.     /**
  3103.      * Move to next record in the recordset.
  3104.      *
  3105.      * @return true if there still rows available, or false if there are no more rows (EOF).
  3106.      */
  3107.     function MoveNext() 
  3108.     {
  3109.         if (!$this->EOF) {
  3110.             $this->_currentRow++;
  3111.             if ($this->_fetch()) return true;
  3112.         }
  3113.         $this->EOF = true;
  3114.         /* -- tested error handling when scrolling cursor -- seems useless.
  3115.         $conn = $this->connection;
  3116.         if ($conn && $conn->raiseErrorFn && ($errno = $conn->ErrorNo())) {
  3117.             $fn = $conn->raiseErrorFn;
  3118.             $fn($conn->databaseType,'MOVENEXT',$errno,$conn->ErrorMsg().' ('.$this->sql.')',$conn->host,$conn->database);
  3119.         }
  3120.         */
  3121.         return false;
  3122.     }
  3123.     
  3124.     
  3125.     /**
  3126.      * Random access to a specific row in the recordset. Some databases do not support
  3127.      * access to previous rows in the databases (no scrolling backwards).
  3128.      *
  3129.      * @param rowNumber is the row to move to (0-based)
  3130.      *
  3131.      * @return true if there still rows available, or false if there are no more rows (EOF).
  3132.      */
  3133.     function Move($rowNumber = 0) 
  3134.     {
  3135.         $this->EOF = false;
  3136.         if ($rowNumber == $this->_currentRow) return true;
  3137.         if ($rowNumber >= $this->_numOfRows)
  3138.                if ($this->_numOfRows != -1) $rowNumber = $this->_numOfRows-2;
  3139.                   
  3140.         if ($this->canSeek) { 
  3141.     
  3142.             if ($this->_seek($rowNumber)) {
  3143.                 $this->_currentRow = $rowNumber;
  3144.                 if ($this->_fetch()) {
  3145.                     return true;
  3146.                 }
  3147.             } else {
  3148.                 $this->EOF = true;
  3149.                 return false;
  3150.             }
  3151.         } else {
  3152.             if ($rowNumber < $this->_currentRow) return false;
  3153.             global $ADODB_EXTENSION;
  3154.             if ($ADODB_EXTENSION) {
  3155.                 while (!$this->EOF && $this->_currentRow < $rowNumber) {
  3156.                     adodb_movenext($this);
  3157.                 }
  3158.             } else {
  3159.             
  3160.                 while (! $this->EOF && $this->_currentRow < $rowNumber) {
  3161.                     $this->_currentRow++;
  3162.                     
  3163.                     if (!$this->_fetch()) $this->EOF = true;
  3164.                 }
  3165.             }
  3166.             return !($this->EOF);
  3167.         }
  3168.         
  3169.         $this->fields = false;    
  3170.         $this->EOF = true;
  3171.         return false;
  3172.     }
  3173.     
  3174.         
  3175.     /**
  3176.      * Get the value of a field in the current row by column name.
  3177.      * Will not work if ADODB_FETCH_MODE is set to ADODB_FETCH_NUM.
  3178.      * 
  3179.      * @param colname  is the field to access
  3180.      *
  3181.      * @return the value of $colname column
  3182.      */
  3183.     function Fields($colname)
  3184.     {
  3185.         return $this->fields[$colname];
  3186.     }
  3187.     
  3188.     function GetAssocKeys($upper=true)
  3189.     {
  3190.         $this->bind = array();
  3191.         for ($i=0; $i < $this->_numOfFields; $i++) {
  3192.             $o = $this->FetchField($i);
  3193.             if ($upper === 2) $this->bind[$o->name] = $i;
  3194.             else $this->bind[($upper) ? strtoupper($o->name) : strtolower($o->name)] = $i;
  3195.         }
  3196.     }
  3197.     
  3198.   /**
  3199.    * Use associative array to get fields array for databases that do not support
  3200.    * associative arrays. Submitted by Paolo S. Asioli paolo.asioli#libero.it
  3201.    *
  3202.    * If you don't want uppercase cols, set $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC
  3203.    * before you execute your SQL statement, and access $rs->fields['col'] directly.
  3204.    *
  3205.    * $upper  0 = lowercase, 1 = uppercase, 2 = whatever is returned by FetchField
  3206.    */
  3207.     function &GetRowAssoc($upper=1)
  3208.     {
  3209.         $record = array();
  3210.      //    if (!$this->fields) return $record;
  3211.         
  3212.            if (!$this->bind) {
  3213.             $this->GetAssocKeys($upper);
  3214.         }
  3215.         
  3216.         foreach($this->bind as $k => $v) {
  3217.             $record[$k] = $this->fields[$v];
  3218.         }
  3219.  
  3220.         return $record;
  3221.     }
  3222.     
  3223.     
  3224.     /**
  3225.      * Clean up recordset
  3226.      *
  3227.      * @return true or false
  3228.      */
  3229.     function Close() 
  3230.     {
  3231.         // free connection object - this seems to globally free the object
  3232.         // and not merely the reference, so don't do this...
  3233.         // $this->connection = false; 
  3234.         if (!$this->_closed) {
  3235.             $this->_closed = true;
  3236.             return $this->_close();        
  3237.         } else
  3238.             return true;
  3239.     }
  3240.     
  3241.     /**
  3242.      * synonyms RecordCount and RowCount    
  3243.      *
  3244.      * @return the number of rows or -1 if this is not supported
  3245.      */
  3246.     function RecordCount() {return $this->_numOfRows;}
  3247.     
  3248.     
  3249.     /*
  3250.     * If we are using PageExecute(), this will return the maximum possible rows
  3251.     * that can be returned when paging a recordset.
  3252.     */
  3253.     function MaxRecordCount()
  3254.     {
  3255.         return ($this->_maxRecordCount) ? $this->_maxRecordCount : $this->RecordCount();
  3256.     }
  3257.     
  3258.     /**
  3259.      * synonyms RecordCount and RowCount    
  3260.      *
  3261.      * @return the number of rows or -1 if this is not supported
  3262.      */
  3263.     function RowCount() {return $this->_numOfRows;} 
  3264.     
  3265.  
  3266.      /**
  3267.      * Portable RecordCount. Pablo Roca <pabloroca@mvps.org>
  3268.      *
  3269.      * @return  the number of records from a previous SELECT. All databases support this.
  3270.      *
  3271.      * But aware possible problems in multiuser environments. For better speed the table
  3272.      * must be indexed by the condition. Heavy test this before deploying.
  3273.      */ 
  3274.     function PO_RecordCount($table="", $condition="") {
  3275.         
  3276.         $lnumrows = $this->_numOfRows;
  3277.         // the database doesn't support native recordcount, so we do a workaround
  3278.         if ($lnumrows == -1 && $this->connection) {
  3279.             IF ($table) {
  3280.                 if ($condition) $condition = " WHERE " . $condition; 
  3281.                 $resultrows = &$this->connection->Execute("SELECT COUNT(*) FROM $table $condition");
  3282.                 if ($resultrows) $lnumrows = reset($resultrows->fields);
  3283.             }
  3284.         }
  3285.         return $lnumrows;
  3286.     }
  3287.     
  3288.     
  3289.     /**
  3290.      * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
  3291.      */
  3292.     function CurrentRow() {return $this->_currentRow;}
  3293.     
  3294.     /**
  3295.      * synonym for CurrentRow -- for ADO compat
  3296.      *
  3297.      * @return the current row in the recordset. If at EOF, will return the last row. 0-based.
  3298.      */
  3299.     function AbsolutePosition() {return $this->_currentRow;}
  3300.     
  3301.     /**
  3302.      * @return the number of columns in the recordset. Some databases will set this to 0
  3303.      * if no records are returned, others will return the number of columns in the query.
  3304.      */
  3305.     function FieldCount() {return $this->_numOfFields;}   
  3306.  
  3307.  
  3308.     /**
  3309.      * Get the ADOFieldObject of a specific column.
  3310.      *
  3311.      * @param fieldoffset    is the column position to access(0-based).
  3312.      *
  3313.      * @return the ADOFieldObject for that column, or false.
  3314.      */
  3315.     function &FetchField($fieldoffset) 
  3316.     {
  3317.         // must be defined by child class
  3318.     }    
  3319.     
  3320.     /**
  3321.      * Get the ADOFieldObjects of all columns in an array.
  3322.      *
  3323.      */
  3324.     function& FieldTypesArray()
  3325.     {
  3326.         $arr = array();
  3327.         for ($i=0, $max=$this->_numOfFields; $i < $max; $i++) 
  3328.             $arr[] = $this->FetchField($i);
  3329.         return $arr;
  3330.     }
  3331.     
  3332.     /**
  3333.     * Return the fields array of the current row as an object for convenience.
  3334.     * The default case is lowercase field names.
  3335.     *
  3336.     * @return the object with the properties set to the fields of the current row
  3337.     */
  3338.     function &FetchObj()
  3339.     {
  3340.         $o =& $this->FetchObject(false);
  3341.         return $o;
  3342.     }
  3343.     
  3344.     /**
  3345.     * Return the fields array of the current row as an object for convenience.
  3346.     * The default case is uppercase.
  3347.     * 
  3348.     * @param $isupper to set the object property names to uppercase
  3349.     *
  3350.     * @return the object with the properties set to the fields of the current row
  3351.     */
  3352.     function &FetchObject($isupper=true)
  3353.     {
  3354.         if (empty($this->_obj)) {
  3355.             $this->_obj = new ADOFetchObj();
  3356.             $this->_names = array();
  3357.             for ($i=0; $i <$this->_numOfFields; $i++) {
  3358.                 $f = $this->FetchField($i);
  3359.                 $this->_names[] = $f->name;
  3360.             }
  3361.         }
  3362.         $i = 0;
  3363.         if (PHP_VERSION >= 5) $o = clone($this->_obj);
  3364.         else $o = $this->_obj;
  3365.     
  3366.         for ($i=0; $i <$this->_numOfFields; $i++) {
  3367.             $name = $this->_names[$i];
  3368.             if ($isupper) $n = strtoupper($name);
  3369.             else $n = $name;
  3370.             
  3371.             $o->$n = $this->Fields($name);
  3372.         }
  3373.         return $o;
  3374.     }
  3375.     
  3376.     /**
  3377.     * Return the fields array of the current row as an object for convenience.
  3378.     * The default is lower-case field names.
  3379.     * 
  3380.     * @return the object with the properties set to the fields of the current row,
  3381.     *     or false if EOF
  3382.     *
  3383.     * Fixed bug reported by tim@orotech.net
  3384.     */
  3385.     function &FetchNextObj()
  3386.     {
  3387.         $o =& $this->FetchNextObject(false);
  3388.         return $o;
  3389.     }
  3390.     
  3391.     
  3392.     /**
  3393.     * Return the fields array of the current row as an object for convenience. 
  3394.     * The default is upper case field names.
  3395.     * 
  3396.     * @param $isupper to set the object property names to uppercase
  3397.     *
  3398.     * @return the object with the properties set to the fields of the current row,
  3399.     *     or false if EOF
  3400.     *
  3401.     * Fixed bug reported by tim@orotech.net
  3402.     */
  3403.     function &FetchNextObject($isupper=true)
  3404.     {
  3405.         $o = false;
  3406.         if ($this->_numOfRows != 0 && !$this->EOF) {
  3407.             $o = $this->FetchObject($isupper);    
  3408.             $this->_currentRow++;
  3409.             if ($this->_fetch()) return $o;
  3410.         }
  3411.         $this->EOF = true;
  3412.         return $o;
  3413.     }
  3414.     
  3415.     /**
  3416.      * Get the metatype of the column. This is used for formatting. This is because
  3417.      * many databases use different names for the same type, so we transform the original
  3418.      * type to our standardised version which uses 1 character codes:
  3419.      *
  3420.      * @param t  is the type passed in. Normally is ADOFieldObject->type.
  3421.      * @param len is the maximum length of that field. This is because we treat character
  3422.      *     fields bigger than a certain size as a 'B' (blob).
  3423.      * @param fieldobj is the field object returned by the database driver. Can hold
  3424.      *    additional info (eg. primary_key for mysql).
  3425.      * 
  3426.      * @return the general type of the data: 
  3427.      *    C for character < 250 chars
  3428.      *    X for teXt (>= 250 chars)
  3429.      *    B for Binary
  3430.      *     N for numeric or floating point
  3431.      *    D for date
  3432.      *    T for timestamp
  3433.      *     L for logical/Boolean
  3434.      *    I for integer
  3435.      *    R for autoincrement counter/integer
  3436.      * 
  3437.      *
  3438.     */
  3439.     function MetaType($t,$len=-1,$fieldobj=false)
  3440.     {
  3441.         if (is_object($t)) {
  3442.             $fieldobj = $t;
  3443.             $t = $fieldobj->type;
  3444.             $len = $fieldobj->max_length;
  3445.         }
  3446.     // changed in 2.32 to hashing instead of switch stmt for speed...
  3447.     static $typeMap = array(
  3448.         'VARCHAR' => 'C',
  3449.         'VARCHAR2' => 'C',
  3450.         'CHAR' => 'C',
  3451.         'C' => 'C',
  3452.         'STRING' => 'C',
  3453.         'NCHAR' => 'C',
  3454.         'NVARCHAR' => 'C',
  3455.         'VARYING' => 'C',
  3456.         'BPCHAR' => 'C',
  3457.         'CHARACTER' => 'C',
  3458.         'INTERVAL' => 'C',  # Postgres
  3459.         'MACADDR' => 'C', # postgres
  3460.         ##
  3461.         'LONGCHAR' => 'X',
  3462.         'TEXT' => 'X',
  3463.         'NTEXT' => 'X',
  3464.         'M' => 'X',
  3465.         'X' => 'X',
  3466.         'CLOB' => 'X',
  3467.         'NCLOB' => 'X',
  3468.         'LVARCHAR' => 'X',
  3469.         ##
  3470.         'BLOB' => 'B',
  3471.         'IMAGE' => 'B',
  3472.         'BINARY' => 'B',
  3473.         'VARBINARY' => 'B',
  3474.         'LONGBINARY' => 'B',
  3475.         'B' => 'B',
  3476.         ##
  3477.         'YEAR' => 'D', // mysql
  3478.         'DATE' => 'D',
  3479.         'D' => 'D',
  3480.         ##
  3481.         'TIME' => 'T',
  3482.         'TIMESTAMP' => 'T',
  3483.         'DATETIME' => 'T',
  3484.         'TIMESTAMPTZ' => 'T',
  3485.         'T' => 'T',
  3486.         'TIMESTAMP WITHOUT TIME ZONE' => 'T', // postgresql
  3487.         ##
  3488.         'BOOL' => 'L',
  3489.         'BOOLEAN' => 'L', 
  3490.         'BIT' => 'L',
  3491.         'L' => 'L',
  3492.         ##
  3493.         'COUNTER' => 'R',
  3494.         'R' => 'R',
  3495.         'SERIAL' => 'R', // ifx
  3496.         'INT IDENTITY' => 'R',
  3497.         ##
  3498.         'INT' => 'I',
  3499.         'INT2' => 'I',
  3500.         'INT4' => 'I',
  3501.         'INT8' => 'I',
  3502.         'INTEGER' => 'I',
  3503.         'INTEGER UNSIGNED' => 'I',
  3504.         'SHORT' => 'I',
  3505.         'TINYINT' => 'I',
  3506.         'SMALLINT' => 'I',
  3507.         'I' => 'I',
  3508.         ##
  3509.         'LONG' => 'N', // interbase is numeric, oci8 is blob
  3510.         'BIGINT' => 'N', // this is bigger than PHP 32-bit integers
  3511.         'DECIMAL' => 'N',
  3512.         'DEC' => 'N',
  3513.         'REAL' => 'N',
  3514.         'DOUBLE' => 'N',
  3515.         'DOUBLE PRECISION' => 'N',
  3516.         'SMALLFLOAT' => 'N',
  3517.         'FLOAT' => 'N',
  3518.         'NUMBER' => 'N',
  3519.         'NUM' => 'N',
  3520.         'NUMERIC' => 'N',
  3521.         'MONEY' => 'N',
  3522.         
  3523.         ## informix 9.2
  3524.         'SQLINT' => 'I', 
  3525.         'SQLSERIAL' => 'I', 
  3526.         'SQLSMINT' => 'I', 
  3527.         'SQLSMFLOAT' => 'N', 
  3528.         'SQLFLOAT' => 'N', 
  3529.         'SQLMONEY' => 'N', 
  3530.         'SQLDECIMAL' => 'N', 
  3531.         'SQLDATE' => 'D', 
  3532.         'SQLVCHAR' => 'C', 
  3533.         'SQLCHAR' => 'C', 
  3534.         'SQLDTIME' => 'T', 
  3535.         'SQLINTERVAL' => 'N', 
  3536.         'SQLBYTES' => 'B', 
  3537.         'SQLTEXT' => 'X' 
  3538.         );
  3539.         
  3540.         $tmap = false;
  3541.         $t = strtoupper($t);
  3542.         $tmap = (isset($typeMap[$t])) ? $typeMap[$t] : 'N';
  3543.         switch ($tmap) {
  3544.         case 'C':
  3545.         
  3546.             // is the char field is too long, return as text field... 
  3547.             if ($this->blobSize >= 0) {
  3548.                 if ($len > $this->blobSize) return 'X';
  3549.             } else if ($len > 250) {
  3550.                 return 'X';
  3551.             }
  3552.             return 'C';
  3553.             
  3554.         case 'I':
  3555.             if (!empty($fieldobj->primary_key)) return 'R';
  3556.             return 'I';
  3557.         
  3558.         case false:
  3559.             return 'N';
  3560.             
  3561.         case 'B':
  3562.              if (isset($fieldobj->binary)) 
  3563.                  return ($fieldobj->binary) ? 'B' : 'X';
  3564.             return 'B';
  3565.         
  3566.         case 'D':
  3567.             if (!empty($this->connection) && !empty($this->connection->datetime)) return 'T';
  3568.             return 'D';
  3569.             
  3570.         default: 
  3571.             if ($t == 'LONG' && $this->dataProvider == 'oci8') return 'B';
  3572.             return $tmap;
  3573.         }
  3574.     }
  3575.     
  3576.     function _close() {}
  3577.     
  3578.     /**
  3579.      * set/returns the current recordset page when paginating
  3580.      */
  3581.     function AbsolutePage($page=-1)
  3582.     {
  3583.         if ($page != -1) $this->_currentPage = $page;
  3584.         return $this->_currentPage;
  3585.     }
  3586.     
  3587.     /**
  3588.      * set/returns the status of the atFirstPage flag when paginating
  3589.      */
  3590.     function AtFirstPage($status=false)
  3591.     {
  3592.         if ($status != false) $this->_atFirstPage = $status;
  3593.         return $this->_atFirstPage;
  3594.     }
  3595.     
  3596.     function LastPageNo($page = false)
  3597.     {
  3598.         if ($page != false) $this->_lastPageNo = $page;
  3599.         return $this->_lastPageNo;
  3600.     }
  3601.     
  3602.     /**
  3603.      * set/returns the status of the atLastPage flag when paginating
  3604.      */
  3605.     function AtLastPage($status=false)
  3606.     {
  3607.         if ($status != false) $this->_atLastPage = $status;
  3608.         return $this->_atLastPage;
  3609.     }
  3610.     
  3611. } // end class ADORecordSet
  3612.     
  3613.     //==============================================================================================    
  3614.     // CLASS ADORecordSet_array
  3615.     //==============================================================================================    
  3616.     
  3617.     /**
  3618.      * This class encapsulates the concept of a recordset created in memory
  3619.      * as an array. This is useful for the creation of cached recordsets.
  3620.      * 
  3621.      * Note that the constructor is different from the standard ADORecordSet
  3622.      */
  3623.     
  3624.     class ADORecordSet_array extends ADORecordSet
  3625.     {
  3626.         var $databaseType = 'array';
  3627.  
  3628.         var $_array;     // holds the 2-dimensional data array
  3629.         var $_types;    // the array of types of each column (C B I L M)
  3630.         var $_colnames;    // names of each column in array
  3631.         var $_skiprow1;    // skip 1st row because it holds column names
  3632.         var $_fieldarr; // holds array of field objects
  3633.         var $canSeek = true;
  3634.         var $affectedrows = false;
  3635.         var $insertid = false;
  3636.         var $sql = '';
  3637.         var $compat = false;
  3638.         /**
  3639.          * Constructor
  3640.          *
  3641.          */
  3642.         function ADORecordSet_array($fakeid=1)
  3643.         {
  3644.         global $ADODB_FETCH_MODE,$ADODB_COMPAT_FETCH;
  3645.         
  3646.             // fetch() on EOF does not delete $this->fields
  3647.             $this->compat = !empty($ADODB_COMPAT_FETCH);
  3648.             $this->ADORecordSet($fakeid); // fake queryID        
  3649.             $this->fetchMode = $ADODB_FETCH_MODE;
  3650.         }
  3651.         
  3652.         
  3653.         /**
  3654.          * Setup the array.
  3655.          *
  3656.          * @param array        is a 2-dimensional array holding the data.
  3657.          *            The first row should hold the column names 
  3658.          *            unless paramter $colnames is used.
  3659.          * @param typearr    holds an array of types. These are the same types 
  3660.          *            used in MetaTypes (C,B,L,I,N).
  3661.          * @param [colnames]    array of column names. If set, then the first row of
  3662.          *            $array should not hold the column names.
  3663.          */
  3664.         function InitArray($array,$typearr,$colnames=false)
  3665.         {
  3666.             $this->_array = $array;
  3667.             $this->_types = $typearr;    
  3668.             if ($colnames) {
  3669.                 $this->_skiprow1 = false;
  3670.                 $this->_colnames = $colnames;
  3671.             } else  {
  3672.                 $this->_skiprow1 = true;
  3673.                 $this->_colnames = $array[0];
  3674.             }
  3675.             $this->Init();
  3676.         }
  3677.         /**
  3678.          * Setup the Array and datatype file objects
  3679.          *
  3680.          * @param array        is a 2-dimensional array holding the data.
  3681.          *            The first row should hold the column names 
  3682.          *            unless paramter $colnames is used.
  3683.          * @param fieldarr    holds an array of ADOFieldObject's.
  3684.          */
  3685.         function InitArrayFields(&$array,&$fieldarr)
  3686.         {
  3687.             $this->_array =& $array;
  3688.             $this->_skiprow1= false;
  3689.             if ($fieldarr) {
  3690.                 $this->_fieldobjects =& $fieldarr;
  3691.             } 
  3692.             $this->Init();
  3693.         }
  3694.         
  3695.         function &GetArray($nRows=-1)
  3696.         {
  3697.             if ($nRows == -1 && $this->_currentRow <= 0 && !$this->_skiprow1) {
  3698.                 return $this->_array;
  3699.             } else {
  3700.                 $arr =& ADORecordSet::GetArray($nRows);
  3701.                 return $arr;
  3702.             }
  3703.         }
  3704.         
  3705.         function _initrs()
  3706.         {
  3707.             $this->_numOfRows =  sizeof($this->_array);
  3708.             if ($this->_skiprow1) $this->_numOfRows -= 1;
  3709.         
  3710.             $this->_numOfFields =(isset($this->_fieldobjects)) ?
  3711.                  sizeof($this->_fieldobjects):sizeof($this->_types);
  3712.         }
  3713.         
  3714.         /* Use associative array to get fields array */
  3715.         function Fields($colname)
  3716.         {
  3717.             $mode = isset($this->adodbFetchMode) ? $this->adodbFetchMode : $this->fetchMode;
  3718.             
  3719.             if ($mode & ADODB_FETCH_ASSOC) {
  3720.                 if (!isset($this->fields[$colname])) $colname = strtolower($colname);
  3721.                 return $this->fields[$colname];
  3722.             }
  3723.             if (!$this->bind) {
  3724.                 $this->bind = array();
  3725.                 for ($i=0; $i < $this->_numOfFields; $i++) {
  3726.                     $o = $this->FetchField($i);
  3727.                     $this->bind[strtoupper($o->name)] = $i;
  3728.                 }
  3729.             }
  3730.             return $this->fields[$this->bind[strtoupper($colname)]];
  3731.         }
  3732.         
  3733.         function &FetchField($fieldOffset = -1) 
  3734.         {
  3735.             if (isset($this->_fieldobjects)) {
  3736.                 return $this->_fieldobjects[$fieldOffset];
  3737.             }
  3738.             $o =  new ADOFieldObject();
  3739.             $o->name = $this->_colnames[$fieldOffset];
  3740.             $o->type =  $this->_types[$fieldOffset];
  3741.             $o->max_length = -1; // length not known
  3742.             
  3743.             return $o;
  3744.         }
  3745.             
  3746.         function _seek($row)
  3747.         {
  3748.             if (sizeof($this->_array) && 0 <= $row && $row < $this->_numOfRows) {
  3749.                 $this->_currentRow = $row;
  3750.                 if ($this->_skiprow1) $row += 1;
  3751.                 $this->fields = $this->_array[$row];
  3752.                 return true;
  3753.             }
  3754.             return false;
  3755.         }
  3756.         
  3757.         function MoveNext() 
  3758.         {
  3759.             if (!$this->EOF) {        
  3760.                 $this->_currentRow++;
  3761.                 
  3762.                 $pos = $this->_currentRow;
  3763.                 
  3764.                 if ($this->_numOfRows <= $pos) {
  3765.                     if (!$this->compat) $this->fields = false;
  3766.                 } else {
  3767.                     if ($this->_skiprow1) $pos += 1;
  3768.                     $this->fields = $this->_array[$pos];
  3769.                     return true;
  3770.                 }        
  3771.                 $this->EOF = true;
  3772.             }
  3773.             
  3774.             return false;
  3775.         }    
  3776.     
  3777.         function _fetch()
  3778.         {
  3779.             $pos = $this->_currentRow;
  3780.             
  3781.             if ($this->_numOfRows <= $pos) {
  3782.                 if (!$this->compat) $this->fields = false;
  3783.                 return false;
  3784.             }
  3785.             if ($this->_skiprow1) $pos += 1;
  3786.             $this->fields = $this->_array[$pos];
  3787.             return true;
  3788.         }
  3789.         
  3790.         function _close() 
  3791.         {
  3792.             return true;    
  3793.         }
  3794.     
  3795.     } // ADORecordSet_array
  3796.  
  3797.     //==============================================================================================    
  3798.     // HELPER FUNCTIONS
  3799.     //==============================================================================================            
  3800.     
  3801.     /**
  3802.      * Synonym for ADOLoadCode. Private function. Do not use.
  3803.      *
  3804.      * @deprecated
  3805.      */
  3806.     function ADOLoadDB($dbType) 
  3807.     { 
  3808.         return ADOLoadCode($dbType);
  3809.     }
  3810.         
  3811.     /**
  3812.      * Load the code for a specific database driver. Private function. Do not use.
  3813.      */
  3814.     function ADOLoadCode($dbType) 
  3815.     {
  3816.     global $ADODB_LASTDB;
  3817.     
  3818.         if (!$dbType) return false;
  3819.         $db = strtolower($dbType);
  3820.         switch ($db) {
  3821.             case 'ado': 
  3822.                 if (PHP_VERSION >= 5) $db = 'ado5';
  3823.                 $class = 'ado'; 
  3824.                 break;
  3825.             case 'ifx':
  3826.             case 'maxsql': $class = $db = 'mysqlt'; break;
  3827.             case 'postgres':
  3828.             case 'postgres8':
  3829.             case 'pgsql': $class = $db = 'postgres7'; break;
  3830.             default:
  3831.                 $class = $db; break;
  3832.         }
  3833.         
  3834.         $file = ADODB_DIR."/drivers/adodb-".$db.".inc.php";
  3835.         @include_once($file);
  3836.         $ADODB_LASTDB = $class;
  3837.         if (class_exists("ADODB_" . $class)) return $class;
  3838.         
  3839.         //ADOConnection::outp(adodb_pr(get_declared_classes(),true));
  3840.         if (!file_exists($file)) ADOConnection::outp("Missing file: $file");
  3841.         else ADOConnection::outp("Syntax error in file: $file");
  3842.         return false;
  3843.     }
  3844.  
  3845.     /**
  3846.      * synonym for ADONewConnection for people like me who cannot remember the correct name
  3847.      */
  3848.     function &NewADOConnection($db='')
  3849.     {
  3850.         $tmp =& ADONewConnection($db);
  3851.         return $tmp;
  3852.     }
  3853.     
  3854.     /**
  3855.      * Instantiate a new Connection class for a specific database driver.
  3856.      *
  3857.      * @param [db]  is the database Connection object to create. If undefined,
  3858.      *     use the last database driver that was loaded by ADOLoadCode().
  3859.      *
  3860.      * @return the freshly created instance of the Connection class.
  3861.      */
  3862.     function &ADONewConnection($db='')
  3863.     {
  3864.     GLOBAL $ADODB_NEWCONNECTION, $ADODB_LASTDB;
  3865.         
  3866.         if (!defined('ADODB_ASSOC_CASE')) define('ADODB_ASSOC_CASE',2);
  3867.         $errorfn = (defined('ADODB_ERROR_HANDLER')) ? ADODB_ERROR_HANDLER : false;
  3868.         $false = false;
  3869.         if ($at = strpos($db,'://')) {
  3870.             $origdsn = $db;
  3871.             if (PHP_VERSION < 5) $dsna = @parse_url($db);
  3872.             else {
  3873.                 $fakedsn = 'fake'.substr($db,$at);
  3874.                 $dsna = @parse_url($fakedsn);
  3875.                 $dsna['scheme'] = substr($db,0,$at);
  3876.             
  3877.                 if (strncmp($db,'pdo',3) == 0) {
  3878.                     $sch = explode('_',$dsna['scheme']);
  3879.                     if (sizeof($sch)>1) {
  3880.                         $dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : '';
  3881.                         $dsna['host'] = rawurlencode($sch[1].':host='.rawurldecode($dsna['host']));
  3882.                         $dsna['scheme'] = 'pdo';
  3883.                     }
  3884.                 }
  3885.             }
  3886.             
  3887.             if (!$dsna) {
  3888.                 // special handling of oracle, which might not have host
  3889.                 $db = str_replace('@/','@adodb-fakehost/',$db);
  3890.                 $dsna = parse_url($db);
  3891.                 if (!$dsna) return $false;
  3892.                 $dsna['host'] = '';
  3893.             }
  3894.             $db = @$dsna['scheme'];
  3895.             if (!$db) return $false;
  3896.             $dsna['host'] = isset($dsna['host']) ? rawurldecode($dsna['host']) : '';
  3897.             $dsna['user'] = isset($dsna['user']) ? rawurldecode($dsna['user']) : '';
  3898.             $dsna['pass'] = isset($dsna['pass']) ? rawurldecode($dsna['pass']) : '';
  3899.             $dsna['path'] = isset($dsna['path']) ? rawurldecode(substr($dsna['path'],1)) : ''; # strip off initial /
  3900.             
  3901.             if (isset($dsna['query'])) {
  3902.                 $opt1 = explode('&',$dsna['query']);
  3903.                 foreach($opt1 as $k => $v) {
  3904.                     $arr = explode('=',$v);
  3905.                     $opt[$arr[0]] = isset($arr[1]) ? rawurldecode($arr[1]) : 1;
  3906.                 }
  3907.             } else $opt = array();
  3908.         }
  3909.     /*
  3910.      *  phptype: Database backend used in PHP (mysql, odbc etc.)
  3911.      *  dbsyntax: Database used with regards to SQL syntax etc.
  3912.      *  protocol: Communication protocol to use (tcp, unix etc.)
  3913.      *  hostspec: Host specification (hostname[:port])
  3914.      *  database: Database to use on the DBMS server
  3915.      *  username: User name for login
  3916.      *  password: Password for login
  3917.      */
  3918.         if (!empty($ADODB_NEWCONNECTION)) {
  3919.             $obj = $ADODB_NEWCONNECTION($db);
  3920.  
  3921.         } else {
  3922.         
  3923.             if (!isset($ADODB_LASTDB)) $ADODB_LASTDB = '';
  3924.             if (empty($db)) $db = $ADODB_LASTDB;
  3925.             
  3926.             if ($db != $ADODB_LASTDB) $db = ADOLoadCode($db);
  3927.             
  3928.             if (!$db) {
  3929.                 if (isset($origdsn)) $db = $origdsn;
  3930.                 if ($errorfn) {
  3931.                     // raise an error
  3932.                     $ignore = false;
  3933.                     $errorfn('ADONewConnection', 'ADONewConnection', -998,
  3934.                              "could not load the database driver for '$db'",
  3935.                              $db,false,$ignore);
  3936.                 } else
  3937.                      ADOConnection::outp( "<p>ADONewConnection: Unable to load database driver '$db'</p>",false);
  3938.                     
  3939.                 return $false;
  3940.             }
  3941.             
  3942.             $cls = 'ADODB_'.$db;
  3943.             if (!class_exists($cls)) {
  3944.                 adodb_backtrace();
  3945.                 return $false;
  3946.             }
  3947.             
  3948.             $obj = new $cls();
  3949.         }
  3950.         
  3951.         # constructor should not fail
  3952.         if ($obj) {
  3953.             if ($errorfn)  $obj->raiseErrorFn = $errorfn;
  3954.             if (isset($dsna)) {
  3955.                 if (isset($dsna['port'])) $obj->port = $dsna['port'];
  3956.                 foreach($opt as $k => $v) {
  3957.                     switch(strtolower($k)) {
  3958.                     case 'new':
  3959.                                         $nconnect = true; $persist = true; break;
  3960.                     case 'persist':
  3961.                     case 'persistent':     $persist = $v; break;
  3962.                     case 'debug':        $obj->debug = (integer) $v; break;
  3963.                     #ibase
  3964.                     case 'role':        $obj->role = $v; break;
  3965.                     case 'dialect':     $obj->dialect = (integer) $v; break;
  3966.                     case 'charset':        $obj->charset = $v; $obj->charSet=$v; break;
  3967.                     case 'buffers':        $obj->buffers = $v; break;
  3968.                     case 'fetchmode':   $obj->SetFetchMode($v); break;
  3969.                     #ado
  3970.                     case 'charpage':    $obj->charPage = $v; break;
  3971.                     #mysql, mysqli
  3972.                     case 'clientflags': $obj->clientFlags = $v; break;
  3973.                     #mysql, mysqli, postgres
  3974.                     case 'port': $obj->port = $v; break;
  3975.                     #mysqli
  3976.                     case 'socket': $obj->socket = $v; break;
  3977.                     #oci8
  3978.                     case 'nls_date_format': $obj->NLS_DATE_FORMAT = $v; break;
  3979.                     }
  3980.                 }
  3981.                 if (empty($persist))
  3982.                     $ok = $obj->Connect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
  3983.                 else if (empty($nconnect))
  3984.                     $ok = $obj->PConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
  3985.                 else
  3986.                     $ok = $obj->NConnect($dsna['host'], $dsna['user'], $dsna['pass'], $dsna['path']);
  3987.                     
  3988.                 if (!$ok) return $false;
  3989.             }
  3990.         }
  3991.         return $obj;
  3992.     }
  3993.     
  3994.     
  3995.     
  3996.     // $perf == true means called by NewPerfMonitor(), otherwise for data dictionary
  3997.     function _adodb_getdriver($provider,$drivername,$perf=false)
  3998.     {
  3999.         switch ($provider) {
  4000.         case 'odbtp':   if (strncmp('odbtp_',$drivername,6)==0) return substr($drivername,6); 
  4001.         case 'odbc' :   if (strncmp('odbc_',$drivername,5)==0) return substr($drivername,5); 
  4002.         case 'ado'  :   if (strncmp('ado_',$drivername,4)==0) return substr($drivername,4);
  4003.         case 'native':  break;
  4004.         default:
  4005.             return $provider;
  4006.         }
  4007.         
  4008.         switch($drivername) {
  4009.         case 'mysqlt':
  4010.         case 'mysqli': 
  4011.                 $drivername='mysql'; 
  4012.                 break;
  4013.         case 'postgres7':
  4014.         case 'postgres8':
  4015.                 $drivername = 'postgres'; 
  4016.                 break;    
  4017.         case 'firebird15': $drivername = 'firebird'; break;
  4018.         case 'oracle': $drivername = 'oci8'; break;
  4019.         case 'access': if ($perf) $drivername = ''; break;
  4020.         case 'db2'   : break;
  4021.         case 'sapdb' : break;
  4022.         default:
  4023.             $drivername = 'generic';
  4024.             break;
  4025.         }
  4026.         return $drivername;
  4027.     }
  4028.     
  4029.     function &NewPerfMonitor(&$conn)
  4030.     {
  4031.         $false = false;
  4032.         $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType,true);
  4033.         if (!$drivername || $drivername == 'generic') return $false;
  4034.         include_once(ADODB_DIR.'/adodb-perf.inc.php');
  4035.         @include_once(ADODB_DIR."/perf/perf-$drivername.inc.php");
  4036.         $class = "Perf_$drivername";
  4037.         if (!class_exists($class)) return $false;
  4038.         $perf = new $class($conn);
  4039.         
  4040.         return $perf;
  4041.     }
  4042.     
  4043.     function &NewDataDictionary(&$conn,$drivername=false)
  4044.     {
  4045.         $false = false;
  4046.         if (!$drivername) $drivername = _adodb_getdriver($conn->dataProvider,$conn->databaseType);
  4047.  
  4048.         include_once(ADODB_DIR.'/adodb-lib.inc.php');
  4049.         include_once(ADODB_DIR.'/adodb-datadict.inc.php');
  4050.         $path = ADODB_DIR."/datadict/datadict-$drivername.inc.php";
  4051.  
  4052.         if (!file_exists($path)) {
  4053.             ADOConnection::outp("Dictionary driver '$path' not available");
  4054.             return $false;
  4055.         }
  4056.         include_once($path);
  4057.         $class = "ADODB2_$drivername";
  4058.         $dict = new $class();
  4059.         $dict->dataProvider = $conn->dataProvider;
  4060.         $dict->connection = &$conn;
  4061.         $dict->upperName = strtoupper($drivername);
  4062.         $dict->quote = $conn->nameQuote;
  4063.         if (!empty($conn->_connectionID))
  4064.             $dict->serverInfo = $conn->ServerInfo();
  4065.         
  4066.         return $dict;
  4067.     }
  4068.  
  4069.  
  4070.     
  4071.     /*
  4072.         Perform a print_r, with pre tags for better formatting.
  4073.     */
  4074.     function adodb_pr($var,$as_string=false)
  4075.     {
  4076.         if ($as_string) ob_start();
  4077.         
  4078.         if (isset($_SERVER['HTTP_USER_AGENT'])) { 
  4079.             echo " <pre>\n";print_r($var);echo "</pre>\n";
  4080.         } else
  4081.             print_r($var);
  4082.             
  4083.         if ($as_string) {
  4084.             $s = ob_get_contents();
  4085.             ob_end_clean();
  4086.             return $s;
  4087.         }
  4088.     }
  4089.     
  4090.     /*
  4091.         Perform a stack-crawl and pretty print it.
  4092.         
  4093.         @param printOrArr  Pass in a boolean to indicate print, or an $exception->trace array (assumes that print is true then).
  4094.         @param levels Number of levels to display
  4095.     */
  4096.     function adodb_backtrace($printOrArr=true,$levels=9999)
  4097.     {
  4098.         global $ADODB_INCLUDED_LIB;
  4099.         if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
  4100.         return _adodb_backtrace($printOrArr,$levels);
  4101.     }
  4102.  
  4103.  
  4104. }
  4105. ?>
  4106.