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

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