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