home *** CD-ROM | disk | FTP | other *** search
/ Enter 2004 June / ENTER.ISO / files / xampp-win32-1.4.5-installer.exe / xampp / adodb.inc.php < prev    next >
Encoding:
PHP Script  |  2004-03-20  |  106.1 KB  |  3,672 lines

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