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