215576c803d7c4cc11af8f24ace993aec1f85e9e
[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.14 8 Sept 2011 (c) 2000-2011 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.14 8 Sept 2011 (c) 2000-2011 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 $sysUTimeStamp = false; // name of function that returns the current timestamp accurate to the microsecond or nearest fraction
381 var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets
382
383 var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' '
384 var $numCacheHits = 0;
385 var $numCacheMisses = 0;
386 var $pageExecuteCountRows = true;
387 var $uniqueSort = false; /// indicates that all fields in order by must be unique
388 var $leftOuter = false; /// operator to use for left outer join in WHERE clause
389 var $rightOuter = false; /// operator to use for right outer join in WHERE clause
390 var $ansiOuter = false; /// whether ansi outer join syntax supported
391 var $autoRollback = false; // autoRollback on PConnect().
392 var $poorAffectedRows = false; // affectedRows not working or unreliable
393
394 var $fnExecute = false;
395 var $fnCacheExecute = false;
396 var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char
397 var $rsPrefix = "ADORecordSet_";
398
399 var $autoCommit = true; /// do not modify this yourself - actually private
400 var $transOff = 0; /// temporarily disable transactions
401 var $transCnt = 0; /// count of nested transactions
402
403 var $fetchMode=false;
404
405 var $null2null = 'null'; // in autoexecute/getinsertsql/getupdatesql, this value will be converted to a null
406 var $bulkBind = false; // enable 2D Execute array
407 //
408 // PRIVATE VARS
409 //
410 var $_oldRaiseFn = false;
411 var $_transOK = null;
412 var $_connectionID = false; /// The returned link identifier whenever a successful database connection is made.
413 var $_errorMsg = false; /// A variable which was used to keep the returned last error message. The value will
414 /// then returned by the errorMsg() function
415 var $_errorCode = false; /// Last error code, not guaranteed to be used - only by oci8
416 var $_queryID = false; /// This variable keeps the last created result link identifier
417
418 var $_isPersistentConnection = false; /// A boolean variable to state whether its a persistent connection or normal connection. */
419 var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters.
420 var $_evalAll = false;
421 var $_affected = false;
422 var $_logsql = false;
423 var $_transmode = ''; // transaction mode
424
425
426
427 /**
428 * Constructor
429 */
430 function ADOConnection()
431 {
432 die('Virtual Class -- cannot instantiate');
433 }
434
435 static function Version()
436 {
437 global $ADODB_vers;
438
439 $ok = preg_match( '/^[Vv]([0-9\.]+)/', $ADODB_vers, $matches );
440 if (!$ok) return (float) substr($ADODB_vers,1);
441 else return $matches[1];
442 }
443
444 /**
445 Get server version info...
446
447 @returns An array with 2 elements: $arr['string'] is the description string,
448 and $arr[version] is the version (also a string).
449 */
450 function ServerInfo()
451 {
452 return array('description' => '', 'version' => '');
453 }
454
455 function IsConnected()
456 {
457 return !empty($this->_connectionID);
458 }
459
460 function _findvers($str)
461 {
462 if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) return $arr[1];
463 else return '';
464 }
465
466 /**
467 * All error messages go through this bottleneck function.
468 * You can define your own handler by defining the function name in ADODB_OUTP.
469 */
470 static function outp($msg,$newline=true)
471 {
472 global $ADODB_FLUSH,$ADODB_OUTP;
473
474 if (defined('ADODB_OUTP')) {
475 $fn = ADODB_OUTP;
476 $fn($msg,$newline);
477 return;
478 } else if (isset($ADODB_OUTP)) {
479 $fn = $ADODB_OUTP;
480 $fn($msg,$newline);
481 return;
482 }
483
484 if ($newline) $msg .= "<br>\n";
485
486 if (isset($_SERVER['HTTP_USER_AGENT']) || !$newline) echo $msg;
487 else echo strip_tags($msg);
488
489
490 if (!empty($ADODB_FLUSH) && ob_get_length() !== false) flush(); // do not flush if output buffering enabled - useless - thx to Jesse Mullan
491
492 }
493
494 function Time()
495 {
496 $rs = $this->_Execute("select $this->sysTimeStamp");
497 if ($rs && !$rs->EOF) return $this->UnixTimeStamp(reset($rs->fields));
498
499 return false;
500 }
501
502 /**
503 * Connect to database
504 *
505 * @param [argHostname] Host to connect to
506 * @param [argUsername] Userid to login
507 * @param [argPassword] Associated password
508 * @param [argDatabaseName] database
509 * @param [forceNew] force new connection
510 *
511 * @return true or false
512 */
513 function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false)
514 {
515 if ($argHostname != "") $this->host = $argHostname;
516 if ($argUsername != "") $this->user = $argUsername;
517 if ($argPassword != "") $this->password = 'not stored'; // not stored for security reasons
518 if ($argDatabaseName != "") $this->database = $argDatabaseName;
519
520 $this->_isPersistentConnection = false;
521
522 if ($forceNew) {
523 if ($rez=$this->_nconnect($this->host, $this->user, $argPassword, $this->database)) return true;
524 } else {
525 if ($rez=$this->_connect($this->host, $this->user, $argPassword, $this->database)) return true;
526 }
527 if (isset($rez)) {
528 $err = $this->ErrorMsg();
529 if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
530 $ret = false;
531 } else {
532 $err = "Missing extension for ".$this->dataProvider;
533 $ret = 0;
534 }
535 if ($fn = $this->raiseErrorFn)
536 $fn($this->databaseType,'CONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
537
538
539 $this->_connectionID = false;
540 if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
541 return $ret;
542 }
543
544 function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName)
545 {
546 return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName);
547 }
548
549
550 /**
551 * Always force a new connection to database - currently only works with oracle
552 *
553 * @param [argHostname] Host to connect to
554 * @param [argUsername] Userid to login
555 * @param [argPassword] Associated password
556 * @param [argDatabaseName] database
557 *
558 * @return true or false
559 */
560 function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
561 {
562 return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true);
563 }
564
565 /**
566 * Establish persistent connect to database
567 *
568 * @param [argHostname] Host to connect to
569 * @param [argUsername] Userid to login
570 * @param [argPassword] Associated password
571 * @param [argDatabaseName] database
572 *
573 * @return return true or false
574 */
575 function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "")
576 {
577
578 if (defined('ADODB_NEVER_PERSIST'))
579 return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);
580
581 if ($argHostname != "") $this->host = $argHostname;
582 if ($argUsername != "") $this->user = $argUsername;
583 if ($argPassword != "") $this->password = 'not stored';
584 if ($argDatabaseName != "") $this->database = $argDatabaseName;
585
586 $this->_isPersistentConnection = true;
587
588 if ($rez = $this->_pconnect($this->host, $this->user, $argPassword, $this->database)) return true;
589 if (isset($rez)) {
590 $err = $this->ErrorMsg();
591 if (empty($err)) $err = "Connection error to server '$argHostname' with user '$argUsername'";
592 $ret = false;
593 } else {
594 $err = "Missing extension for ".$this->dataProvider;
595 $ret = 0;
596 }
597 if ($fn = $this->raiseErrorFn) {
598 $fn($this->databaseType,'PCONNECT',$this->ErrorNo(),$err,$this->host,$this->database,$this);
599 }
600
601 $this->_connectionID = false;
602 if ($this->debug) ADOConnection::outp( $this->host.': '.$err);
603 return $ret;
604 }
605
606 function outp_throw($msg,$src='WARN',$sql='')
607 {
608 if (defined('ADODB_ERROR_HANDLER') && ADODB_ERROR_HANDLER == 'adodb_throw') {
609 adodb_throw($this->databaseType,$src,-9999,$msg,$sql,false,$this);
610 return;
611 }
612 ADOConnection::outp($msg);
613 }
614
615 // create cache class. Code is backward compat with old memcache implementation
616 function _CreateCache()
617 {
618 global $ADODB_CACHE, $ADODB_CACHE_CLASS;
619
620 if ($this->memCache) {
621 global $ADODB_INCLUDED_MEMCACHE;
622
623 if (empty($ADODB_INCLUDED_MEMCACHE)) include(ADODB_DIR.'/adodb-memcache.lib.inc.php');
624 $ADODB_CACHE = new ADODB_Cache_MemCache($this);
625 } else
626 $ADODB_CACHE = new $ADODB_CACHE_CLASS($this);
627
628 }
629
630 // Format date column in sql string given an input format that understands Y M D
631 function SQLDate($fmt, $col=false)
632 {
633 if (!$col) $col = $this->sysDate;
634 return $col; // child class implement
635 }
636
637 /**
638 * Should prepare the sql statement and return the stmt resource.
639 * For databases that do not support this, we return the $sql. To ensure
640 * compatibility with databases that do not support prepare:
641 *
642 * $stmt = $db->Prepare("insert into table (id, name) values (?,?)");
643 * $db->Execute($stmt,array(1,'Jill')) or die('insert failed');
644 * $db->Execute($stmt,array(2,'Joe')) or die('insert failed');
645 *
646 * @param sql SQL to send to database
647 *
648 * @return return FALSE, or the prepared statement, or the original sql if
649 * if the database does not support prepare.
650 *
651 */
652 function Prepare($sql)
653 {
654 return $sql;
655 }
656
657 /**
658 * Some databases, eg. mssql require a different function for preparing
659 * stored procedures. So we cannot use Prepare().
660 *
661 * Should prepare the stored procedure and return the stmt resource.
662 * For databases that do not support this, we return the $sql. To ensure
663 * compatibility with databases that do not support prepare:
664 *
665 * @param sql SQL to send to database
666 *
667 * @return return FALSE, or the prepared statement, or the original sql if
668 * if the database does not support prepare.
669 *
670 */
671 function PrepareSP($sql,$param=true)
672 {
673 return $this->Prepare($sql,$param);
674 }
675
676 /**
677 * PEAR DB Compat
678 */
679 function Quote($s)
680 {
681 return $this->qstr($s,false);
682 }
683
684 /**
685 Requested by "Karsten Dambekalns" <k.dambekalns@fishfarm.de>
686 */
687 function QMagic($s)
688 {
689 return $this->qstr($s,get_magic_quotes_gpc());
690 }
691
692 function q(&$s)
693 {
694 #if (!empty($this->qNull)) if ($s == 'null') return $s;
695 $s = $this->qstr($s,false);
696 }
697
698 /**
699 * PEAR DB Compat - do not use internally.
700 */
701 function ErrorNative()
702 {
703 return $this->ErrorNo();
704 }
705
706
707 /**
708 * PEAR DB Compat - do not use internally.
709 */
710 function nextId($seq_name)
711 {
712 return $this->GenID($seq_name);
713 }
714
715 /**
716 * Lock a row, will escalate and lock the table if row locking not supported
717 * will normally free the lock at the end of the transaction
718 *
719 * @param $table name of table to lock
720 * @param $where where clause to use, eg: "WHERE row=12". If left empty, will escalate to table lock
721 */
722 function RowLock($table,$where,$col='1 as adodbignore')
723 {
724 return false;
725 }
726
727 function CommitLock($table)
728 {
729 return $this->CommitTrans();
730 }
731
732 function RollbackLock($table)
733 {
734 return $this->RollbackTrans();
735 }
736
737 /**
738 * PEAR DB Compat - do not use internally.
739 *
740 * The fetch modes for NUMERIC and ASSOC for PEAR DB and ADODB are identical
741 * for easy porting :-)
742 *
743 * @param mode The fetchmode ADODB_FETCH_ASSOC or ADODB_FETCH_NUM
744 * @returns The previous fetch mode
745 */
746 function SetFetchMode($mode)
747 {
748 $old = $this->fetchMode;
749 $this->fetchMode = $mode;
750
751 if ($old === false) {
752 global $ADODB_FETCH_MODE;
753 return $ADODB_FETCH_MODE;
754 }
755 return $old;
756 }
757
758
759 /**
760 * PEAR DB Compat - do not use internally.
761 */
762 function Query($sql, $inputarr=false)
763 {
764 $rs = $this->Execute($sql, $inputarr);
765 if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
766 return $rs;
767 }
768
769
770 /**
771 * PEAR DB Compat - do not use internally
772 */
773 function LimitQuery($sql, $offset, $count, $params=false)
774 {
775 $rs = $this->SelectLimit($sql, $count, $offset, $params);
776 if (!$rs && defined('ADODB_PEAR')) return ADODB_PEAR_Error();
777 return $rs;
778 }
779
780
781 /**
782 * PEAR DB Compat - do not use internally
783 */
784 function Disconnect()
785 {
786 return $this->Close();
787 }
788
789 /*
790 Returns placeholder for parameter, eg.
791 $DB->Param('a')
792
793 will return ':a' for Oracle, and '?' for most other databases...
794
795 For databases that require positioned params, eg $1, $2, $3 for postgresql,
796 pass in Param(false) before setting the first parameter.
797 */
798 function Param($name,$type='C')
799 {
800 return '?';
801 }
802
803 /*
804 InParameter and OutParameter are self-documenting versions of Parameter().
805 */
806 function InParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
807 {
808 return $this->Parameter($stmt,$var,$name,false,$maxLen,$type);
809 }
810
811 /*
812 */
813 function OutParameter(&$stmt,&$var,$name,$maxLen=4000,$type=false)
814 {
815 return $this->Parameter($stmt,$var,$name,true,$maxLen,$type);
816
817 }
818
819
820 /*
821 Usage in oracle
822 $stmt = $db->Prepare('select * from table where id =:myid and group=:group');
823 $db->Parameter($stmt,$id,'myid');
824 $db->Parameter($stmt,$group,'group',64);
825 $db->Execute();
826
827 @param $stmt Statement returned by Prepare() or PrepareSP().
828 @param $var PHP variable to bind to
829 @param $name Name of stored procedure variable name to bind to.
830 @param [$isOutput] Indicates direction of parameter 0/false=IN 1=OUT 2= IN/OUT. This is ignored in oci8.
831 @param [$maxLen] Holds an maximum length of the variable.
832 @param [$type] The data type of $var. Legal values depend on driver.
833
834 */
835 function Parameter(&$stmt,&$var,$name,$isOutput=false,$maxLen=4000,$type=false)
836 {
837 return false;
838 }
839
840
841 function IgnoreErrors($saveErrs=false)
842 {
843 if (!$saveErrs) {
844 $saveErrs = array($this->raiseErrorFn,$this->_transOK);
845 $this->raiseErrorFn = false;
846 return $saveErrs;
847 } else {
848 $this->raiseErrorFn = $saveErrs[0];
849 $this->_transOK = $saveErrs[1];
850 }
851 }
852
853 /**
854 Improved method of initiating a transaction. Used together with CompleteTrans().
855 Advantages include:
856
857 a. StartTrans/CompleteTrans is nestable, unlike BeginTrans/CommitTrans/RollbackTrans.
858 Only the outermost block is treated as a transaction.<br>
859 b. CompleteTrans auto-detects SQL errors, and will rollback on errors, commit otherwise.<br>
860 c. All BeginTrans/CommitTrans/RollbackTrans inside a StartTrans/CompleteTrans block
861 are disabled, making it backward compatible.
862 */
863 function StartTrans($errfn = 'ADODB_TransMonitor')
864 {
865 if ($this->transOff > 0) {
866 $this->transOff += 1;
867 return true;
868 }
869
870 $this->_oldRaiseFn = $this->raiseErrorFn;
871 $this->raiseErrorFn = $errfn;
872 $this->_transOK = true;
873
874 if ($this->debug && $this->transCnt > 0) ADOConnection::outp("Bad Transaction: StartTrans called within BeginTrans");
875 $ok = $this->BeginTrans();
876 $this->transOff = 1;
877 return $ok;
878 }
879
880
881 /**
882 Used together with StartTrans() to end a transaction. Monitors connection
883 for sql errors, and will commit or rollback as appropriate.
884
885 @autoComplete if true, monitor sql errors and commit and rollback as appropriate,
886 and if set to false force rollback even if no SQL error detected.
887 @returns true on commit, false on rollback.
888 */
889 function CompleteTrans($autoComplete = true)
890 {
891 if ($this->transOff > 1) {
892 $this->transOff -= 1;
893 return true;
894 }
895 $this->raiseErrorFn = $this->_oldRaiseFn;
896
897 $this->transOff = 0;
898 if ($this->_transOK && $autoComplete) {
899 if (!$this->CommitTrans()) {
900 $this->_transOK = false;
901 if ($this->debug) ADOConnection::outp("Smart Commit failed");
902 } else
903 if ($this->debug) ADOConnection::outp("Smart Commit occurred");
904 } else {
905 $this->_transOK = false;
906 $this->RollbackTrans();
907 if ($this->debug) ADOCOnnection::outp("Smart Rollback occurred");
908 }
909
910 return $this->_transOK;
911 }
912
913 /*
914 At the end of a StartTrans/CompleteTrans block, perform a rollback.
915 */
916 function FailTrans()
917 {
918 if ($this->debug)
919 if ($this->transOff == 0) {
920 ADOConnection::outp("FailTrans outside StartTrans/CompleteTrans");
921 } else {
922 ADOConnection::outp("FailTrans was called");
923 adodb_backtrace();
924 }
925 $this->_transOK = false;
926 }
927
928 /**
929 Check if transaction has failed, only for Smart Transactions.
930 */
931 function HasFailedTrans()
932 {
933 if ($this->transOff > 0) return $this->_transOK == false;
934 return false;
935 }
936
937 /**
938 * Execute SQL
939 *
940 * @param sql SQL statement to execute, or possibly an array holding prepared statement ($sql[0] will hold sql text)
941 * @param [inputarr] holds the input data to bind to. Null elements will be set to null.
942 * @return RecordSet or false
943 */
944 function Execute($sql,$inputarr=false)
945 {
946 if ($this->fnExecute) {
947 $fn = $this->fnExecute;
948 $ret = $fn($this,$sql,$inputarr);
949 if (isset($ret)) return $ret;
950 }
951 if ($inputarr) {
952 if (!is_array($inputarr)) $inputarr = array($inputarr);
953
954 $element0 = reset($inputarr);
955 # is_object check because oci8 descriptors can be passed in
956 $array_2d = $this->bulkBind && is_array($element0) && !is_object(reset($element0));
957
958 //remove extra memory copy of input -mikefedyk
959 unset($element0);
960
961 if (!is_array($sql) && !$this->_bindInputArray) {
962 $sqlarr = explode('?',$sql);
963 $nparams = sizeof($sqlarr)-1;
964 if (!$array_2d) $inputarr = array($inputarr);
965
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 (empty($ADODB_CACHE)) return false;
1714
1715 if (!$sql) {
1716 $ADODB_CACHE->flushall($this->debug);
1717 return;
1718 }
1719
1720 $f = $this->_gencachename($sql.serialize($inputarr),false);
1721 return $ADODB_CACHE->flushcache($f, $this->debug);
1722 }
1723
1724
1725 /**
1726 * Private function to generate filename for caching.
1727 * Filename is generated based on:
1728 *
1729 * - sql statement
1730 * - database type (oci8, ibase, ifx, etc)
1731 * - database name
1732 * - userid
1733 * - setFetchMode (adodb 4.23)
1734 *
1735 * When not in safe mode, we create 256 sub-directories in the cache directory ($ADODB_CACHE_DIR).
1736 * Assuming that we can have 50,000 files per directory with good performance,
1737 * then we can scale to 12.8 million unique cached recordsets. Wow!
1738 */
1739 function _gencachename($sql,$createdir)
1740 {
1741 global $ADODB_CACHE, $ADODB_CACHE_DIR;
1742
1743 if ($this->fetchMode === false) {
1744 global $ADODB_FETCH_MODE;
1745 $mode = $ADODB_FETCH_MODE;
1746 } else {
1747 $mode = $this->fetchMode;
1748 }
1749 $m = md5($sql.$this->databaseType.$this->database.$this->user.$mode);
1750 if (!$ADODB_CACHE->createdir) return $m;
1751 if (!$createdir) $dir = $ADODB_CACHE->getdirname($m);
1752 else $dir = $ADODB_CACHE->createdir($m, $this->debug);
1753
1754 return $dir.'/adodb_'.$m.'.cache';
1755 }
1756
1757
1758 /**
1759 * Execute SQL, caching recordsets.
1760 *
1761 * @param [secs2cache] seconds to cache data, set to 0 to force query.
1762 * This is an optional parameter.
1763 * @param sql SQL statement to execute
1764 * @param [inputarr] holds the input data to bind to
1765 * @return RecordSet or false
1766 */
1767 function CacheExecute($secs2cache,$sql=false,$inputarr=false)
1768 {
1769 global $ADODB_CACHE;
1770
1771 if (empty($ADODB_CACHE)) $this->_CreateCache();
1772
1773 if (!is_numeric($secs2cache)) {
1774 $inputarr = $sql;
1775 $sql = $secs2cache;
1776 $secs2cache = $this->cacheSecs;
1777 }
1778
1779 if (is_array($sql)) {
1780 $sqlparam = $sql;
1781 $sql = $sql[0];
1782 } else
1783 $sqlparam = $sql;
1784
1785
1786 $md5file = $this->_gencachename($sql.serialize($inputarr),true);
1787 $err = '';
1788
1789 if ($secs2cache > 0){
1790 $rs = $ADODB_CACHE->readcache($md5file,$err,$secs2cache,$this->arrayClass);
1791 $this->numCacheHits += 1;
1792 } else {
1793 $err='Timeout 1';
1794 $rs = false;
1795 $this->numCacheMisses += 1;
1796 }
1797
1798 if (!$rs) {
1799 // no cached rs found
1800 if ($this->debug) {
1801 if (get_magic_quotes_runtime() && !$this->memCache) {
1802 ADOConnection::outp("Please disable magic_quotes_runtime - it corrupts cache files :(");
1803 }
1804 if ($this->debug !== -1) ADOConnection::outp( " $md5file cache failure: $err (this is a notice and not an error)");
1805 }
1806
1807 $rs = $this->Execute($sqlparam,$inputarr);
1808
1809 if ($rs) {
1810
1811 $eof = $rs->EOF;
1812 $rs = $this->_rs2rs($rs); // read entire recordset into memory immediately
1813 $rs->timeCreated = time(); // used by caching
1814 $txt = _rs2serialize($rs,false,$sql); // serialize
1815
1816 $ok = $ADODB_CACHE->writecache($md5file,$txt,$this->debug, $secs2cache);
1817 if (!$ok) {
1818 if ($ok === false) {
1819 $em = 'Cache write error';
1820 $en = -32000;
1821
1822 if ($fn = $this->raiseErrorFn) {
1823 $fn($this->databaseType,'CacheExecute', $en, $em, $md5file,$sql,$this);
1824 }
1825 } else {
1826 $em = 'Cache file locked warning';
1827 $en = -32001;
1828 // do not call error handling for just a warning
1829 }
1830
1831 if ($this->debug) ADOConnection::outp( " ".$em);
1832 }
1833 if ($rs->EOF && !$eof) {
1834 $rs->MoveFirst();
1835 //$rs = csv2rs($md5file,$err);
1836 $rs->connection = $this; // Pablo suggestion
1837 }
1838
1839 } else if (!$this->memCache)
1840 $ADODB_CACHE->flushcache($md5file);
1841 } else {
1842 $this->_errorMsg = '';
1843 $this->_errorCode = 0;
1844
1845 if ($this->fnCacheExecute) {
1846 $fn = $this->fnCacheExecute;
1847 $fn($this, $secs2cache, $sql, $inputarr);
1848 }
1849 // ok, set cached object found
1850 $rs->connection = $this; // Pablo suggestion
1851 if ($this->debug){
1852 if ($this->debug == 99) adodb_backtrace();
1853 $inBrowser = isset($_SERVER['HTTP_USER_AGENT']);
1854 $ttl = $rs->timeCreated + $secs2cache - time();
1855 $s = is_array($sql) ? $sql[0] : $sql;
1856 if ($inBrowser) $s = '<i>'.htmlspecialchars($s).'</i>';
1857
1858 ADOConnection::outp( " $md5file reloaded, ttl=$ttl [ $s ]");
1859 }
1860 }
1861 return $rs;
1862 }
1863
1864
1865 /*
1866 Similar to PEAR DB's autoExecute(), except that
1867 $mode can be 'INSERT' or 'UPDATE' or DB_AUTOQUERY_INSERT or DB_AUTOQUERY_UPDATE
1868 If $mode == 'UPDATE', then $where is compulsory as a safety measure.
1869
1870 $forceUpdate means that even if the data has not changed, perform update.
1871 */
1872 function AutoExecute($table, $fields_values, $mode = 'INSERT', $where = FALSE, $forceUpdate=true, $magicq=false)
1873 {
1874 $false = false;
1875 $sql = 'SELECT * FROM '.$table;
1876 if ($where!==FALSE) $sql .= ' WHERE '.$where;
1877 else if ($mode == 'UPDATE' || $mode == 2 /* DB_AUTOQUERY_UPDATE */) {
1878 $this->outp_throw('AutoExecute: Illegal mode=UPDATE with empty WHERE clause','AutoExecute');
1879 return $false;
1880 }
1881
1882 $rs = $this->SelectLimit($sql,1);
1883 if (!$rs) return $false; // table does not exist
1884 $rs->tableName = $table;
1885 $rs->sql = $sql;
1886
1887 switch((string) $mode) {
1888 case 'UPDATE':
1889 case '2':
1890 $sql = $this->GetUpdateSQL($rs, $fields_values, $forceUpdate, $magicq);
1891 break;
1892 case 'INSERT':
1893 case '1':
1894 $sql = $this->GetInsertSQL($rs, $fields_values, $magicq);
1895 break;
1896 default:
1897 $this->outp_throw("AutoExecute: Unknown mode=$mode",'AutoExecute');
1898 return $false;
1899 }
1900 $ret = false;
1901 if ($sql) $ret = $this->Execute($sql);
1902 if ($ret) $ret = true;
1903 return $ret;
1904 }
1905
1906
1907 /**
1908 * Generates an Update Query based on an existing recordset.
1909 * $arrFields is an associative array of fields with the value
1910 * that should be assigned.
1911 *
1912 * Note: This function should only be used on a recordset
1913 * that is run against a single table and sql should only
1914 * be a simple select stmt with no groupby/orderby/limit
1915 *
1916 * "Jonathan Younger" <jyounger@unilab.com>
1917 */
1918 function GetUpdateSQL(&$rs, $arrFields,$forceUpdate=false,$magicq=false,$force=null)
1919 {
1920 global $ADODB_INCLUDED_LIB;
1921
1922 //********************************************************//
1923 //This is here to maintain compatibility
1924 //with older adodb versions. Sets force type to force nulls if $forcenulls is set.
1925 if (!isset($force)) {
1926 global $ADODB_FORCE_TYPE;
1927 $force = $ADODB_FORCE_TYPE;
1928 }
1929 //********************************************************//
1930
1931 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
1932 return _adodb_getupdatesql($this,$rs,$arrFields,$forceUpdate,$magicq,$force);
1933 }
1934
1935 /**
1936 * Generates an Insert Query based on an existing recordset.
1937 * $arrFields is an associative array of fields with the value
1938 * that should be assigned.
1939 *
1940 * Note: This function should only be used on a recordset
1941 * that is run against a single table.
1942 */
1943 function GetInsertSQL(&$rs, $arrFields,$magicq=false,$force=null)
1944 {
1945 global $ADODB_INCLUDED_LIB;
1946 if (!isset($force)) {
1947 global $ADODB_FORCE_TYPE;
1948 $force = $ADODB_FORCE_TYPE;
1949
1950 }
1951 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
1952 return _adodb_getinsertsql($this,$rs,$arrFields,$magicq,$force);
1953 }
1954
1955
1956 /**
1957 * Update a blob column, given a where clause. There are more sophisticated
1958 * blob handling functions that we could have implemented, but all require
1959 * a very complex API. Instead we have chosen something that is extremely
1960 * simple to understand and use.
1961 *
1962 * Note: $blobtype supports 'BLOB' and 'CLOB', default is BLOB of course.
1963 *
1964 * Usage to update a $blobvalue which has a primary key blob_id=1 into a
1965 * field blobtable.blobcolumn:
1966 *
1967 * UpdateBlob('blobtable', 'blobcolumn', $blobvalue, 'blob_id=1');
1968 *
1969 * Insert example:
1970 *
1971 * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
1972 * $conn->UpdateBlob('blobtable','blobcol',$blob,'id=1');
1973 */
1974
1975 function UpdateBlob($table,$column,$val,$where,$blobtype='BLOB')
1976 {
1977 return $this->Execute("UPDATE $table SET $column=? WHERE $where",array($val)) != false;
1978 }
1979
1980 /**
1981 * Usage:
1982 * UpdateBlob('TABLE', 'COLUMN', '/path/to/file', 'ID=1');
1983 *
1984 * $blobtype supports 'BLOB' and 'CLOB'
1985 *
1986 * $conn->Execute('INSERT INTO blobtable (id, blobcol) VALUES (1, null)');
1987 * $conn->UpdateBlob('blobtable','blobcol',$blobpath,'id=1');
1988 */
1989 function UpdateBlobFile($table,$column,$path,$where,$blobtype='BLOB')
1990 {
1991 $fd = fopen($path,'rb');
1992 if ($fd === false) return false;
1993 $val = fread($fd,filesize($path));
1994 fclose($fd);
1995 return $this->UpdateBlob($table,$column,$val,$where,$blobtype);
1996 }
1997
1998 function BlobDecode($blob)
1999 {
2000 return $blob;
2001 }
2002
2003 function BlobEncode($blob)
2004 {
2005 return $blob;
2006 }
2007
2008 function SetCharSet($charset)
2009 {
2010 return false;
2011 }
2012
2013 function IfNull( $field, $ifNull )
2014 {
2015 return " CASE WHEN $field is null THEN $ifNull ELSE $field END ";
2016 }
2017
2018 function LogSQL($enable=true)
2019 {
2020 include_once(ADODB_DIR.'/adodb-perf.inc.php');
2021
2022 if ($enable) $this->fnExecute = 'adodb_log_sql';
2023 else $this->fnExecute = false;
2024
2025 $old = $this->_logsql;
2026 $this->_logsql = $enable;
2027 if ($enable && !$old) $this->_affected = false;
2028 return $old;
2029 }
2030
2031 function GetCharSet()
2032 {
2033 return false;
2034 }
2035
2036 /**
2037 * Usage:
2038 * UpdateClob('TABLE', 'COLUMN', $var, 'ID=1', 'CLOB');
2039 *
2040 * $conn->Execute('INSERT INTO clobtable (id, clobcol) VALUES (1, null)');
2041 * $conn->UpdateClob('clobtable','clobcol',$clob,'id=1');
2042 */
2043 function UpdateClob($table,$column,$val,$where)
2044 {
2045 return $this->UpdateBlob($table,$column,$val,$where,'CLOB');
2046 }
2047
2048 // not the fastest implementation - quick and dirty - jlim
2049 // for best performance, use the actual $rs->MetaType().
2050 function MetaType($t,$len=-1,$fieldobj=false)
2051 {
2052
2053 if (empty($this->_metars)) {
2054 $rsclass = $this->rsPrefix.$this->databaseType;
2055 $this->_metars = new $rsclass(false,$this->fetchMode);
2056 $this->_metars->connection = $this;
2057 }
2058 return $this->_metars->MetaType($t,$len,$fieldobj);
2059 }
2060
2061
2062 /**
2063 * Change the SQL connection locale to a specified locale.
2064 * This is used to get the date formats written depending on the client locale.
2065 */
2066 function SetDateLocale($locale = 'En')
2067 {
2068 $this->locale = $locale;
2069 switch (strtoupper($locale))
2070 {
2071 case 'EN':
2072 $this->fmtDate="'Y-m-d'";
2073 $this->fmtTimeStamp = "'Y-m-d H:i:s'";
2074 break;
2075
2076 case 'US':
2077 $this->fmtDate = "'m-d-Y'";
2078 $this->fmtTimeStamp = "'m-d-Y H:i:s'";
2079 break;
2080
2081 case 'PT_BR':
2082 case 'NL':
2083 case 'FR':
2084 case 'RO':
2085 case 'IT':
2086 $this->fmtDate="'d-m-Y'";
2087 $this->fmtTimeStamp = "'d-m-Y H:i:s'";
2088 break;
2089
2090 case 'GE':
2091 $this->fmtDate="'d.m.Y'";
2092 $this->fmtTimeStamp = "'d.m.Y H:i:s'";
2093 break;
2094
2095 default:
2096 $this->fmtDate="'Y-m-d'";
2097 $this->fmtTimeStamp = "'Y-m-d H:i:s'";
2098 break;
2099 }
2100 }
2101
2102 /**
2103 * GetActiveRecordsClass Performs an 'ALL' query
2104 *
2105 * @param mixed $class This string represents the class of the current active record
2106 * @param mixed $table Table used by the active record object
2107 * @param mixed $whereOrderBy Where, order, by clauses
2108 * @param mixed $bindarr
2109 * @param mixed $primkeyArr
2110 * @param array $extra Query extras: limit, offset...
2111 * @param mixed $relations Associative array: table's foreign name, "hasMany", "belongsTo"
2112 * @access public
2113 * @return void
2114 */
2115 function GetActiveRecordsClass(
2116 $class, $table,$whereOrderBy=false,$bindarr=false, $primkeyArr=false,
2117 $extra=array(),
2118 $relations=array())
2119 {
2120 global $_ADODB_ACTIVE_DBS;
2121 ## reduce overhead of adodb.inc.php -- moved to adodb-active-record.inc.php
2122 ## if adodb-active-recordx is loaded -- should be no issue as they will probably use Find()
2123 if (!isset($_ADODB_ACTIVE_DBS))include_once(ADODB_DIR.'/adodb-active-record.inc.php');
2124 return adodb_GetActiveRecordsClass($this, $class, $table, $whereOrderBy, $bindarr, $primkeyArr, $extra, $relations);
2125 }
2126
2127 function GetActiveRecords($table,$where=false,$bindarr=false,$primkeyArr=false)
2128 {
2129 $arr = $this->GetActiveRecordsClass('ADODB_Active_Record', $table, $where, $bindarr, $primkeyArr);
2130 return $arr;
2131 }
2132
2133 /**
2134 * Close Connection
2135 */
2136 function Close()
2137 {
2138 $rez = $this->_close();
2139 $this->_connectionID = false;
2140 return $rez;
2141 }
2142
2143 /**
2144 * Begin a Transaction. Must be followed by CommitTrans() or RollbackTrans().
2145 *
2146 * @return true if succeeded or false if database does not support transactions
2147 */
2148 function BeginTrans()
2149 {
2150 if ($this->debug) ADOConnection::outp("BeginTrans: Transactions not supported for this driver");
2151 return false;
2152 }
2153
2154 /* set transaction mode */
2155 function SetTransactionMode( $transaction_mode )
2156 {
2157 $transaction_mode = $this->MetaTransaction($transaction_mode, $this->dataProvider);
2158 $this->_transmode = $transaction_mode;
2159 }
2160 /*
2161 http://msdn2.microsoft.com/en-US/ms173763.aspx
2162 http://dev.mysql.com/doc/refman/5.0/en/innodb-transaction-isolation.html
2163 http://www.postgresql.org/docs/8.1/interactive/sql-set-transaction.html
2164 http://www.stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_10005.htm
2165 */
2166 function MetaTransaction($mode,$db)
2167 {
2168 $mode = strtoupper($mode);
2169 $mode = str_replace('ISOLATION LEVEL ','',$mode);
2170
2171 switch($mode) {
2172
2173 case 'READ UNCOMMITTED':
2174 switch($db) {
2175 case 'oci8':
2176 case 'oracle':
2177 return 'ISOLATION LEVEL READ COMMITTED';
2178 default:
2179 return 'ISOLATION LEVEL READ UNCOMMITTED';
2180 }
2181 break;
2182
2183 case 'READ COMMITTED':
2184 return 'ISOLATION LEVEL READ COMMITTED';
2185 break;
2186
2187 case 'REPEATABLE READ':
2188 switch($db) {
2189 case 'oci8':
2190 case 'oracle':
2191 return 'ISOLATION LEVEL SERIALIZABLE';
2192 default:
2193 return 'ISOLATION LEVEL REPEATABLE READ';
2194 }
2195 break;
2196
2197 case 'SERIALIZABLE':
2198 return 'ISOLATION LEVEL SERIALIZABLE';
2199 break;
2200
2201 default:
2202 return $mode;
2203 }
2204 }
2205
2206 /**
2207 * If database does not support transactions, always return true as data always commited
2208 *
2209 * @param $ok set to false to rollback transaction, true to commit
2210 *
2211 * @return true/false.
2212 */
2213 function CommitTrans($ok=true)
2214 { return true;}
2215
2216
2217 /**
2218 * If database does not support transactions, rollbacks always fail, so return false
2219 *
2220 * @return true/false.
2221 */
2222 function RollbackTrans()
2223 { return false;}
2224
2225
2226 /**
2227 * return the databases that the driver can connect to.
2228 * Some databases will return an empty array.
2229 *
2230 * @return an array of database names.
2231 */
2232 function MetaDatabases()
2233 {
2234 global $ADODB_FETCH_MODE;
2235
2236 if ($this->metaDatabasesSQL) {
2237 $save = $ADODB_FETCH_MODE;
2238 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
2239
2240 if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
2241
2242 $arr = $this->GetCol($this->metaDatabasesSQL);
2243 if (isset($savem)) $this->SetFetchMode($savem);
2244 $ADODB_FETCH_MODE = $save;
2245
2246 return $arr;
2247 }
2248
2249 return false;
2250 }
2251
2252
2253 /**
2254 * @param ttype can either be 'VIEW' or 'TABLE' or false.
2255 * If false, both views and tables are returned.
2256 * "VIEW" returns only views
2257 * "TABLE" returns only tables
2258 * @param showSchema returns the schema/user with the table name, eg. USER.TABLE
2259 * @param mask is the input mask - only supported by oci8 and postgresql
2260 *
2261 * @return array of tables for current database.
2262 */
2263 function MetaTables($ttype=false,$showSchema=false,$mask=false)
2264 {
2265 global $ADODB_FETCH_MODE;
2266
2267
2268 $false = false;
2269 if ($mask) {
2270 return $false;
2271 }
2272 if ($this->metaTablesSQL) {
2273 $save = $ADODB_FETCH_MODE;
2274 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
2275
2276 if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
2277
2278 $rs = $this->Execute($this->metaTablesSQL);
2279 if (isset($savem)) $this->SetFetchMode($savem);
2280 $ADODB_FETCH_MODE = $save;
2281
2282 if ($rs === false) return $false;
2283 $arr = $rs->GetArray();
2284 $arr2 = array();
2285
2286 if ($hast = ($ttype && isset($arr[0][1]))) {
2287 $showt = strncmp($ttype,'T',1);
2288 }
2289
2290 for ($i=0; $i < sizeof($arr); $i++) {
2291 if ($hast) {
2292 if ($showt == 0) {
2293 if (strncmp($arr[$i][1],'T',1) == 0) $arr2[] = trim($arr[$i][0]);
2294 } else {
2295 if (strncmp($arr[$i][1],'V',1) == 0) $arr2[] = trim($arr[$i][0]);
2296 }
2297 } else
2298 $arr2[] = trim($arr[$i][0]);
2299 }
2300 $rs->Close();
2301 return $arr2;
2302 }
2303 return $false;
2304 }
2305
2306
2307 function _findschema(&$table,&$schema)
2308 {
2309 if (!$schema && ($at = strpos($table,'.')) !== false) {
2310 $schema = substr($table,0,$at);
2311 $table = substr($table,$at+1);
2312 }
2313 }
2314
2315 /**
2316 * List columns in a database as an array of ADOFieldObjects.
2317 * See top of file for definition of object.
2318 *
2319 * @param $table table name to query
2320 * @param $normalize makes table name case-insensitive (required by some databases)
2321 * @schema is optional database schema to use - not supported by all databases.
2322 *
2323 * @return array of ADOFieldObjects for current table.
2324 */
2325 function MetaColumns($table,$normalize=true)
2326 {
2327 global $ADODB_FETCH_MODE;
2328
2329 $false = false;
2330
2331 if (!empty($this->metaColumnsSQL)) {
2332
2333 $schema = false;
2334 $this->_findschema($table,$schema);
2335
2336 $save = $ADODB_FETCH_MODE;
2337 $ADODB_FETCH_MODE = ADODB_FETCH_NUM;
2338 if ($this->fetchMode !== false) $savem = $this->SetFetchMode(false);
2339 $rs = $this->Execute(sprintf($this->metaColumnsSQL,($normalize)?strtoupper($table):$table));
2340 if (isset($savem)) $this->SetFetchMode($savem);
2341 $ADODB_FETCH_MODE = $save;
2342 if ($rs === false || $rs->EOF) return $false;
2343
2344 $retarr = array();
2345 while (!$rs->EOF) { //print_r($rs->fields);
2346 $fld = new ADOFieldObject();
2347 $fld->name = $rs->fields[0];
2348 $fld->type = $rs->fields[1];
2349 if (isset($rs->fields[3]) && $rs->fields[3]) {
2350 if ($rs->fields[3]>0) $fld->max_length = $rs->fields[3];
2351 $fld->scale = $rs->fields[4];
2352 if ($fld->scale>0) $fld->max_length += 1;
2353 } else
2354 $fld->max_length = $rs->fields[2];
2355
2356 if ($ADODB_FETCH_MODE == ADODB_FETCH_NUM) $retarr[] = $fld;
2357 else $retarr[strtoupper($fld->name)] = $fld;
2358 $rs->MoveNext();
2359 }
2360 $rs->Close();
2361 return $retarr;
2362 }
2363 return $false;
2364 }
2365
2366 /**
2367 * List indexes on a table as an array.
2368 * @param table table name to query
2369 * @param primary true to only show primary keys. Not actually used for most databases
2370 *
2371 * @return array of indexes on current table. Each element represents an index, and is itself an associative array.
2372
2373 Array (
2374 [name_of_index] => Array
2375 (
2376 [unique] => true or false
2377 [columns] => Array
2378 (
2379 [0] => firstname
2380 [1] => lastname
2381 )
2382 )
2383 */
2384 function MetaIndexes($table, $primary = false, $owner = false)
2385 {
2386 $false = false;
2387 return $false;
2388 }
2389
2390 /**
2391 * List columns names in a table as an array.
2392 * @param table table name to query
2393 *
2394 * @return array of column names for current table.
2395 */
2396 function MetaColumnNames($table, $numIndexes=false,$useattnum=false /* only for postgres */)
2397 {
2398 $objarr = $this->MetaColumns($table);
2399 if (!is_array($objarr)) {
2400 $false = false;
2401 return $false;
2402 }
2403 $arr = array();
2404 if ($numIndexes) {
2405 $i = 0;
2406 if ($useattnum) {
2407 foreach($objarr as $v)
2408 $arr[$v->attnum] = $v->name;
2409
2410 } else
2411 foreach($objarr as $v) $arr[$i++] = $v->name;
2412 } else
2413 foreach($objarr as $v) $arr[strtoupper($v->name)] = $v->name;
2414
2415 return $arr;
2416 }
2417
2418 /**
2419 * Different SQL databases used different methods to combine strings together.
2420 * This function provides a wrapper.
2421 *
2422 * param s variable number of string parameters
2423 *
2424 * Usage: $db->Concat($str1,$str2);
2425 *
2426 * @return concatenated string
2427 */
2428 function Concat()
2429 {
2430 $arr = func_get_args();
2431 return implode($this->concat_operator, $arr);
2432 }
2433
2434
2435 /**
2436 * Converts a date "d" to a string that the database can understand.
2437 *
2438 * @param d a date in Unix date time format.
2439 *
2440 * @return date string in database date format
2441 */
2442 function DBDate($d, $isfld=false)
2443 {
2444 if (empty($d) && $d !== 0) return 'null';
2445 if ($isfld) return $d;
2446
2447 if (is_object($d)) return $d->format($this->fmtDate);
2448
2449
2450 if (is_string($d) && !is_numeric($d)) {
2451 if ($d === 'null' || strncmp($d,"'",1) === 0) return $d;
2452 if ($this->isoDates) return "'$d'";
2453 $d = ADOConnection::UnixDate($d);
2454 }
2455
2456 return adodb_date($this->fmtDate,$d);
2457 }
2458
2459 function BindDate($d)
2460 {
2461 $d = $this->DBDate($d);
2462 if (strncmp($d,"'",1)) return $d;
2463
2464 return substr($d,1,strlen($d)-2);
2465 }
2466
2467 function BindTimeStamp($d)
2468 {
2469 $d = $this->DBTimeStamp($d);
2470 if (strncmp($d,"'",1)) return $d;
2471
2472 return substr($d,1,strlen($d)-2);
2473 }
2474
2475
2476 /**
2477 * Converts a timestamp "ts" to a string that the database can understand.
2478 *
2479 * @param ts a timestamp in Unix date time format.
2480 *
2481 * @return timestamp string in database timestamp format
2482 */
2483 function DBTimeStamp($ts,$isfld=false)
2484 {
2485 if (empty($ts) && $ts !== 0) return 'null';
2486 if ($isfld) return $ts;
2487 if (is_object($ts)) return $ts->format($this->fmtTimeStamp);
2488
2489 # strlen(14) allows YYYYMMDDHHMMSS format
2490 if (!is_string($ts) || (is_numeric($ts) && strlen($ts)<14))
2491 return adodb_date($this->fmtTimeStamp,$ts);
2492
2493 if ($ts === 'null') return $ts;
2494 if ($this->isoDates && strlen($ts) !== 14) return "'$ts'";
2495
2496 $ts = ADOConnection::UnixTimeStamp($ts);
2497 return adodb_date($this->fmtTimeStamp,$ts);
2498 }
2499
2500 /**
2501 * Also in ADORecordSet.
2502 * @param $v is a date string in YYYY-MM-DD format
2503 *
2504 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
2505 */
2506 static function UnixDate($v)
2507 {
2508 if (is_object($v)) {
2509 // odbtp support
2510 //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
2511 return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year);
2512 }
2513
2514 if (is_numeric($v) && strlen($v) !== 8) return $v;
2515 if (!preg_match( "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})|",
2516 ($v), $rr)) return false;
2517
2518 if ($rr[1] <= TIMESTAMP_FIRST_YEAR) return 0;
2519 // h-m-s-MM-DD-YY
2520 return @adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
2521 }
2522
2523
2524 /**
2525 * Also in ADORecordSet.
2526 * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
2527 *
2528 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
2529 */
2530 static function UnixTimeStamp($v)
2531 {
2532 if (is_object($v)) {
2533 // odbtp support
2534 //( [year] => 2004 [month] => 9 [day] => 4 [hour] => 12 [minute] => 44 [second] => 8 [fraction] => 0 )
2535 return adodb_mktime($v->hour,$v->minute,$v->second,$v->month,$v->day, $v->year);
2536 }
2537
2538 if (!preg_match(
2539 "|^([0-9]{4})[-/\.]?([0-9]{1,2})[-/\.]?([0-9]{1,2})[ ,-]*(([0-9]{1,2}):?([0-9]{1,2}):?([0-9\.]{1,4}))?|",
2540 ($v), $rr)) return false;
2541
2542 if ($rr[1] <= TIMESTAMP_FIRST_YEAR && $rr[2]<= 1) return 0;
2543
2544 // h-m-s-MM-DD-YY
2545 if (!isset($rr[5])) return adodb_mktime(0,0,0,$rr[2],$rr[3],$rr[1]);
2546 return @adodb_mktime($rr[5],$rr[6],$rr[7],$rr[2],$rr[3],$rr[1]);
2547 }
2548
2549 /**
2550 * Also in ADORecordSet.
2551 *
2552 * Format database date based on user defined format.
2553 *
2554 * @param v is the character date in YYYY-MM-DD format, returned by database
2555 * @param fmt is the format to apply to it, using date()
2556 *
2557 * @return a date formated as user desires
2558 */
2559
2560 function UserDate($v,$fmt='Y-m-d',$gmt=false)
2561 {
2562 $tt = $this->UnixDate($v);
2563
2564 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
2565 if (($tt === false || $tt == -1) && $v != false) return $v;
2566 else if ($tt == 0) return $this->emptyDate;
2567 else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
2568 }
2569
2570 return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
2571
2572 }
2573
2574 /**
2575 *
2576 * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
2577 * @param fmt is the format to apply to it, using date()
2578 *
2579 * @return a timestamp formated as user desires
2580 */
2581 function UserTimeStamp($v,$fmt='Y-m-d H:i:s',$gmt=false)
2582 {
2583 if (!isset($v)) return $this->emptyTimeStamp;
2584 # strlen(14) allows YYYYMMDDHHMMSS format
2585 if (is_numeric($v) && strlen($v)<14) return ($gmt) ? adodb_gmdate($fmt,$v) : adodb_date($fmt,$v);
2586 $tt = $this->UnixTimeStamp($v);
2587 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
2588 if (($tt === false || $tt == -1) && $v != false) return $v;
2589 if ($tt == 0) return $this->emptyTimeStamp;
2590 return ($gmt) ? adodb_gmdate($fmt,$tt) : adodb_date($fmt,$tt);
2591 }
2592
2593 function escape($s,$magic_quotes=false)
2594 {
2595 return $this->addq($s,$magic_quotes);
2596 }
2597
2598 /**
2599 * Quotes a string, without prefixing nor appending quotes.
2600 */
2601 function addq($s,$magic_quotes=false)
2602 {
2603 if (!$magic_quotes) {
2604
2605 if ($this->replaceQuote[0] == '\\'){
2606 // only since php 4.0.5
2607 $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
2608 //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
2609 }
2610 return str_replace("'",$this->replaceQuote,$s);
2611 }
2612
2613 // undo magic quotes for "
2614 $s = str_replace('\\"','"',$s);
2615
2616 if ($this->replaceQuote == "\\'" || ini_get('magic_quotes_sybase')) // ' already quoted, no need to change anything
2617 return $s;
2618 else {// change \' to '' for sybase/mssql
2619 $s = str_replace('\\\\','\\',$s);
2620 return str_replace("\\'",$this->replaceQuote,$s);
2621 }
2622 }
2623
2624 /**
2625 * Correctly quotes a string so that all strings are escaped. We prefix and append
2626 * to the string single-quotes.
2627 * An example is $db->qstr("Don't bother",magic_quotes_runtime());
2628 *
2629 * @param s the string to quote
2630 * @param [magic_quotes] if $s is GET/POST var, set to get_magic_quotes_gpc().
2631 * This undoes the stupidity of magic quotes for GPC.
2632 *
2633 * @return quoted string to be sent back to database
2634 */
2635 function qstr($s,$magic_quotes=false)
2636 {
2637 if (!$magic_quotes) {
2638
2639 if ($this->replaceQuote[0] == '\\'){
2640 // only since php 4.0.5
2641 $s = adodb_str_replace(array('\\',"\0"),array('\\\\',"\\\0"),$s);
2642 //$s = str_replace("\0","\\\0", str_replace('\\','\\\\',$s));
2643 }
2644 return "'".str_replace("'",$this->replaceQuote,$s)."'";
2645 }
2646
2647 // undo magic quotes for "
2648 $s = str_replace('\\"','"',$s);
2649
2650 if ($this->replaceQuote == "\\'" || ini_get('magic_quotes_sybase')) // ' already quoted, no need to change anything
2651 return "'$s'";
2652 else {// change \' to '' for sybase/mssql
2653 $s = str_replace('\\\\','\\',$s);
2654 return "'".str_replace("\\'",$this->replaceQuote,$s)."'";
2655 }
2656 }
2657
2658
2659 /**
2660 * Will select the supplied $page number from a recordset, given that it is paginated in pages of
2661 * $nrows rows per page. It also saves two boolean values saying if the given page is the first
2662 * and/or last one of the recordset. Added by Iv�n Oliva to provide recordset pagination.
2663 *
2664 * See readme.htm#ex8 for an example of usage.
2665 *
2666 * @param sql
2667 * @param nrows is the number of rows per page to get
2668 * @param page is the page number to get (1-based)
2669 * @param [inputarr] array of bind variables
2670 * @param [secs2cache] is a private parameter only used by jlim
2671 * @return the recordset ($rs->databaseType == 'array')
2672 *
2673 * NOTE: phpLens uses a different algorithm and does not use PageExecute().
2674 *
2675 */
2676 function PageExecute($sql, $nrows, $page, $inputarr=false, $secs2cache=0)
2677 {
2678 global $ADODB_INCLUDED_LIB;
2679 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
2680 if ($this->pageExecuteCountRows) $rs = _adodb_pageexecute_all_rows($this, $sql, $nrows, $page, $inputarr, $secs2cache);
2681 else $rs = _adodb_pageexecute_no_last_page($this, $sql, $nrows, $page, $inputarr, $secs2cache);
2682 return $rs;
2683 }
2684
2685
2686 /**
2687 * Will select the supplied $page number from a recordset, given that it is paginated in pages of
2688 * $nrows rows per page. It also saves two boolean values saying if the given page is the first
2689 * and/or last one of the recordset. Added by Iv�n Oliva to provide recordset pagination.
2690 *
2691 * @param secs2cache seconds to cache data, set to 0 to force query
2692 * @param sql
2693 * @param nrows is the number of rows per page to get
2694 * @param page is the page number to get (1-based)
2695 * @param [inputarr] array of bind variables
2696 * @return the recordset ($rs->databaseType == 'array')
2697 */
2698 function CachePageExecute($secs2cache, $sql, $nrows, $page,$inputarr=false)
2699 {
2700 /*switch($this->dataProvider) {
2701 case 'postgres':
2702 case 'mysql':
2703 break;
2704 default: $secs2cache = 0; break;
2705 }*/
2706 $rs = $this->PageExecute($sql,$nrows,$page,$inputarr,$secs2cache);
2707 return $rs;
2708 }
2709
2710 } // end class ADOConnection
2711
2712
2713
2714 //==============================================================================================
2715 // CLASS ADOFetchObj
2716 //==============================================================================================
2717
2718 /**
2719 * Internal placeholder for record objects. Used by ADORecordSet->FetchObj().
2720 */
2721 class ADOFetchObj {
2722 };
2723
2724 //==============================================================================================
2725 // CLASS ADORecordSet_empty
2726 //==============================================================================================
2727
2728 class ADODB_Iterator_empty implements Iterator {
2729
2730 private $rs;
2731
2732 function __construct($rs)
2733 {
2734 $this->rs = $rs;
2735 }
2736 function rewind()
2737 {
2738 }
2739
2740 function valid()
2741 {
2742 return !$this->rs->EOF;
2743 }
2744
2745 function key()
2746 {
2747 return false;
2748 }
2749
2750 function current()
2751 {
2752 return false;
2753 }
2754
2755 function next()
2756 {
2757 }
2758
2759 function __call($func, $params)
2760 {
2761 return call_user_func_array(array($this->rs, $func), $params);
2762 }
2763
2764 function hasMore()
2765 {
2766 return false;
2767 }
2768
2769 }
2770
2771
2772 /**
2773 * Lightweight recordset when there are no records to be returned
2774 */
2775 class ADORecordSet_empty implements IteratorAggregate
2776 {
2777 var $dataProvider = 'empty';
2778 var $databaseType = false;
2779 var $EOF = true;
2780 var $_numOfRows = 0;
2781 var $fields = false;
2782 var $connection = false;
2783 function RowCount() {return 0;}
2784 function RecordCount() {return 0;}
2785 function PO_RecordCount(){return 0;}
2786 function Close(){return true;}
2787 function FetchRow() {return false;}
2788 function FieldCount(){ return 0;}
2789 function Init() {}
2790 function getIterator() {return new ADODB_Iterator_empty($this);}
2791 }
2792
2793 //==============================================================================================
2794 // DATE AND TIME FUNCTIONS
2795 //==============================================================================================
2796 if (!defined('ADODB_DATE_VERSION')) include(ADODB_DIR.'/adodb-time.inc.php');
2797
2798 //==============================================================================================
2799 // CLASS ADORecordSet
2800 //==============================================================================================
2801
2802 class ADODB_Iterator implements Iterator {
2803
2804 private $rs;
2805
2806 function __construct($rs)
2807 {
2808 $this->rs = $rs;
2809 }
2810 function rewind()
2811 {
2812 $this->rs->MoveFirst();
2813 }
2814
2815 function valid()
2816 {
2817 return !$this->rs->EOF;
2818 }
2819
2820 function key()
2821 {
2822 return $this->rs->_currentRow;
2823 }
2824
2825 function current()
2826 {
2827 return $this->rs->fields;
2828 }
2829
2830 function next()
2831 {
2832 $this->rs->MoveNext();
2833 }
2834
2835 function __call($func, $params)
2836 {
2837 return call_user_func_array(array($this->rs, $func), $params);
2838 }
2839
2840
2841 function hasMore()
2842 {
2843 return !$this->rs->EOF;
2844 }
2845
2846 }
2847
2848
2849
2850 /**
2851 * RecordSet class that represents the dataset returned by the database.
2852 * To keep memory overhead low, this class holds only the current row in memory.
2853 * No prefetching of data is done, so the RecordCount() can return -1 ( which
2854 * means recordcount not known).
2855 */
2856 class ADORecordSet implements IteratorAggregate {
2857 /*
2858 * public variables
2859 */
2860 var $dataProvider = "native";
2861 var $fields = false; /// holds the current row data
2862 var $blobSize = 100; /// any varchar/char field this size or greater is treated as a blob
2863 /// in other words, we use a text area for editing.
2864 var $canSeek = false; /// indicates that seek is supported
2865 var $sql; /// sql text
2866 var $EOF = false; /// Indicates that the current record position is after the last record in a Recordset object.
2867
2868 var $emptyTimeStamp = '&nbsp;'; /// what to display when $time==0
2869 var $emptyDate = '&nbsp;'; /// what to display when $time==0
2870 var $debug = false;
2871 var $timeCreated=0; /// datetime in Unix format rs created -- for cached recordsets
2872
2873 var $bind = false; /// used by Fields() to hold array - should be private?
2874 var $fetchMode; /// default fetch mode
2875 var $connection = false; /// the parent connection
2876 /*
2877 * private variables
2878 */
2879 var $_numOfRows = -1; /** number of rows, or -1 */
2880 var $_numOfFields = -1; /** number of fields in recordset */
2881 var $_queryID = -1; /** This variable keeps the result link identifier. */
2882 var $_currentRow = -1; /** This variable keeps the current row in the Recordset. */
2883 var $_closed = false; /** has recordset been closed */
2884 var $_inited = false; /** Init() should only be called once */
2885 var $_obj; /** Used by FetchObj */
2886 var $_names; /** Used by FetchObj */
2887
2888 var $_currentPage = -1; /** Added by Iv�n Oliva to implement recordset pagination */
2889 var $_atFirstPage = false; /** Added by Iv�n Oliva to implement recordset pagination */
2890 var $_atLastPage = false; /** Added by Iv�n Oliva to implement recordset pagination */
2891 var $_lastPageNo = -1;
2892 var $_maxRecordCount = 0;
2893 var $datetime = false;
2894
2895 /**
2896 * Constructor
2897 *
2898 * @param queryID this is the queryID returned by ADOConnection->_query()
2899 *
2900 */
2901 function ADORecordSet($queryID)
2902 {
2903 $this->_queryID = $queryID;
2904 }
2905
2906 function getIterator()
2907 {
2908 return new ADODB_Iterator($this);
2909 }
2910
2911 /* this is experimental - i don't really know what to return... */
2912 function __toString()
2913 {
2914 include_once(ADODB_DIR.'/toexport.inc.php');
2915 return _adodb_export($this,',',',',false,true);
2916 }
2917
2918
2919 function Init()
2920 {
2921 if ($this->_inited) return;
2922 $this->_inited = true;
2923 if ($this->_queryID) @$this->_initrs();
2924 else {
2925 $this->_numOfRows = 0;
2926 $this->_numOfFields = 0;
2927 }
2928 if ($this->_numOfRows != 0 && $this->_numOfFields && $this->_currentRow == -1) {
2929
2930 $this->_currentRow = 0;
2931 if ($this->EOF = ($this->_fetch() === false)) {
2932 $this->_numOfRows = 0; // _numOfRows could be -1
2933 }
2934 } else {
2935 $this->EOF = true;
2936 }
2937 }
2938
2939
2940 /**
2941 * Generate a SELECT tag string from a recordset, and return the string.
2942 * If the recordset has 2 cols, we treat the 1st col as the containing
2943 * the text to display to the user, and 2nd col as the return value. Default
2944 * strings are compared with the FIRST column.
2945 *
2946 * @param name name of SELECT tag
2947 * @param [defstr] the value to hilite. Use an array for multiple hilites for listbox.
2948 * @param [blank1stItem] true to leave the 1st item in list empty
2949 * @param [multiple] true for listbox, false for popup
2950 * @param [size] #rows to show for listbox. not used by popup
2951 * @param [selectAttr] additional attributes to defined for SELECT tag.
2952 * useful for holding javascript onChange='...' handlers.
2953 & @param [compareFields0] when we have 2 cols in recordset, we compare the defstr with
2954 * column 0 (1st col) if this is true. This is not documented.
2955 *
2956 * @return HTML
2957 *
2958 * changes by glen.davies@cce.ac.nz to support multiple hilited items
2959 */
2960 function GetMenu($name,$defstr='',$blank1stItem=true,$multiple=false,
2961 $size=0, $selectAttr='',$compareFields0=true)
2962 {
2963 global $ADODB_INCLUDED_LIB;
2964 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
2965 return _adodb_getmenu($this, $name,$defstr,$blank1stItem,$multiple,
2966 $size, $selectAttr,$compareFields0);
2967 }
2968
2969
2970
2971 /**
2972 * Generate a SELECT tag string from a recordset, and return the string.
2973 * If the recordset has 2 cols, we treat the 1st col as the containing
2974 * the text to display to the user, and 2nd col as the return value. Default
2975 * strings are compared with the SECOND column.
2976 *
2977 */
2978 function GetMenu2($name,$defstr='',$blank1stItem=true,$multiple=false,$size=0, $selectAttr='')
2979 {
2980 return $this->GetMenu($name,$defstr,$blank1stItem,$multiple,
2981 $size, $selectAttr,false);
2982 }
2983
2984 /*
2985 Grouped Menu
2986 */
2987 function GetMenu3($name,$defstr='',$blank1stItem=true,$multiple=false,
2988 $size=0, $selectAttr='')
2989 {
2990 global $ADODB_INCLUDED_LIB;
2991 if (empty($ADODB_INCLUDED_LIB)) include(ADODB_DIR.'/adodb-lib.inc.php');
2992 return _adodb_getmenu_gp($this, $name,$defstr,$blank1stItem,$multiple,
2993 $size, $selectAttr,false);
2994 }
2995
2996 /**
2997 * return recordset as a 2-dimensional array.
2998 *
2999 * @param [nRows] is the number of rows to return. -1 means every row.
3000 *
3001 * @return an array indexed by the rows (0-based) from the recordset
3002 */
3003 function GetArray($nRows = -1)
3004 {
3005 global $ADODB_EXTENSION; if ($ADODB_EXTENSION) {
3006 $results = adodb_getall($this,$nRows);
3007 return $results;
3008 }
3009 $results = array();
3010 $cnt = 0;
3011 while (!$this->EOF && $nRows != $cnt) {
3012 $results[] = $this->fields;
3013 $this->MoveNext();
3014 $cnt++;
3015 }
3016 return $results;
3017 }
3018
3019 function GetAll($nRows = -1)
3020 {
3021 $arr = $this->GetArray($nRows);
3022 return $arr;
3023 }
3024
3025 /*
3026 * Some databases allow multiple recordsets to be returned. This function
3027 * will return true if there is a next recordset, or false if no more.
3028 */
3029 function NextRecordSet()
3030 {
3031 return false;
3032 }
3033
3034 /**
3035 * return recordset as a 2-dimensional array.
3036 * Helper function for ADOConnection->SelectLimit()
3037 *
3038 * @param offset is the row to start calculations from (1-based)
3039 * @param [nrows] is the number of rows to return
3040 *
3041 * @return an array indexed by the rows (0-based) from the recordset
3042 */
3043 function GetArrayLimit($nrows,$offset=-1)
3044 {
3045 if ($offset <= 0) {
3046 $arr = $this->GetArray($nrows);
3047 return $arr;
3048 }
3049
3050 $this->Move($offset);
3051
3052 $results = array();
3053 $cnt = 0;
3054 while (!$this->EOF && $nrows != $cnt) {
3055 $results[$cnt++] = $this->fields;
3056 $this->MoveNext();
3057 }
3058
3059 return $results;
3060 }
3061
3062
3063 /**
3064 * Synonym for GetArray() for compatibility with ADO.
3065 *
3066 * @param [nRows] is the number of rows to return. -1 means every row.
3067 *
3068 * @return an array indexed by the rows (0-based) from the recordset
3069 */
3070 function GetRows($nRows = -1)
3071 {
3072 $arr = $this->GetArray($nRows);
3073 return $arr;
3074 }
3075
3076 /**
3077 * return whole recordset as a 2-dimensional associative array if there are more than 2 columns.
3078 * The first column is treated as the key and is not included in the array.
3079 * If there is only 2 columns, it will return a 1 dimensional array of key-value pairs unless
3080 * $force_array == true.
3081 *
3082 * @param [force_array] has only meaning if we have 2 data columns. If false, a 1 dimensional
3083 * array is returned, otherwise a 2 dimensional array is returned. If this sounds confusing,
3084 * read the source.
3085 *
3086 * @param [first2cols] means if there are more than 2 cols, ignore the remaining cols and
3087 * instead of returning array[col0] => array(remaining cols), return array[col0] => col1
3088 *
3089 * @return an associative array indexed by the first column of the array,
3090 * or false if the data has less than 2 cols.
3091 */
3092 function GetAssoc($force_array = false, $first2cols = false)
3093 {
3094 global $ADODB_EXTENSION;
3095
3096 $cols = $this->_numOfFields;
3097 if ($cols < 2) {
3098 $false = false;
3099 return $false;
3100 }
3101 $numIndex = isset($this->fields[0]);
3102 $results = array();
3103
3104 if (!$first2cols && ($cols > 2 || $force_array)) {
3105 if ($ADODB_EXTENSION) {
3106 if ($numIndex) {
3107 while (!$this->EOF) {
3108 $results[trim($this->fields[0])] = array_slice($this->fields, 1);
3109 adodb_movenext($this);
3110 }
3111 } else {
3112 while (!$this->EOF) {
3113 // Fix for array_slice re-numbering numeric associative keys
3114 $keys = array_slice(array_keys($this->fields), 1);
3115 $sliced_array = array();
3116
3117 foreach($keys as $key) {
3118 $sliced_array[$key] = $this->fields[$key];
3119 }
3120
3121 $results[trim(reset($this->fields))] = $sliced_array;
3122 adodb_movenext($this);
3123 }
3124 }
3125 } else {
3126 if ($numIndex) {
3127 while (!$this->EOF) {
3128 $results[trim($this->fields[0])] = array_slice($this->fields, 1);
3129 $this->MoveNext();
3130 }
3131 } else {
3132 while (!$this->EOF) {
3133 // Fix for array_slice re-numbering numeric associative keys
3134 $keys = array_slice(array_keys($this->fields), 1);
3135 $sliced_array = array();
3136
3137 foreach($keys as $key) {
3138 $sliced_array[$key] = $this->fields[$key];
3139 }
3140
3141 $results[trim(reset($this->fields))] = $sliced_array;
3142 $this->MoveNext();
3143 }
3144 }
3145 }
3146 } else {
3147 if ($ADODB_EXTENSION) {
3148 // return scalar values
3149 if ($numIndex) {
3150 while (!$this->EOF) {
3151 // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
3152 $results[trim(($this->fields[0]))] = $this->fields[1];
3153 adodb_movenext($this);
3154 }
3155 } else {
3156 while (!$this->EOF) {
3157 // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
3158 $v1 = trim(reset($this->fields));
3159 $v2 = ''.next($this->fields);
3160 $results[$v1] = $v2;
3161 adodb_movenext($this);
3162 }
3163 }
3164 } else {
3165 if ($numIndex) {
3166 while (!$this->EOF) {
3167 // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
3168 $results[trim(($this->fields[0]))] = $this->fields[1];
3169 $this->MoveNext();
3170 }
3171 } else {
3172 while (!$this->EOF) {
3173 // some bug in mssql PHP 4.02 -- doesn't handle references properly so we FORCE creating a new string
3174 $v1 = trim(reset($this->fields));
3175 $v2 = ''.next($this->fields);
3176 $results[$v1] = $v2;
3177 $this->MoveNext();
3178 }
3179 }
3180 }
3181 }
3182
3183 $ref = $results; # workaround accelerator incompat with PHP 4.4 :(
3184 return $ref;
3185 }
3186
3187
3188 /**
3189 *
3190 * @param v is the character timestamp in YYYY-MM-DD hh:mm:ss format
3191 * @param fmt is the format to apply to it, using date()
3192 *
3193 * @return a timestamp formated as user desires
3194 */
3195 function UserTimeStamp($v,$fmt='Y-m-d H:i:s')
3196 {
3197 if (is_numeric($v) && strlen($v)<14) return adodb_date($fmt,$v);
3198 $tt = $this->UnixTimeStamp($v);
3199 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
3200 if (($tt === false || $tt == -1) && $v != false) return $v;
3201 if ($tt === 0) return $this->emptyTimeStamp;
3202 return adodb_date($fmt,$tt);
3203 }
3204
3205
3206 /**
3207 * @param v is the character date in YYYY-MM-DD format, returned by database
3208 * @param fmt is the format to apply to it, using date()
3209 *
3210 * @return a date formated as user desires
3211 */
3212 function UserDate($v,$fmt='Y-m-d')
3213 {
3214 $tt = $this->UnixDate($v);
3215 // $tt == -1 if pre TIMESTAMP_FIRST_YEAR
3216 if (($tt === false || $tt == -1) && $v != false) return $v;
3217 else if ($tt == 0) return $this->emptyDate;
3218 else if ($tt == -1) { // pre-TIMESTAMP_FIRST_YEAR
3219 }
3220 return adodb_date($fmt,$tt);
3221 }
3222
3223
3224 /**
3225 * @param $v is a date string in YYYY-MM-DD format
3226 *
3227 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
3228 */
3229 static function UnixDate($v)
3230 {
3231 return ADOConnection::UnixDate($v);
3232 }
3233
3234
3235 /**
3236 * @param $v is a timestamp string in YYYY-MM-DD HH-NN-SS format
3237 *
3238 * @return date in unix timestamp format, or 0 if before TIMESTAMP_FIRST_YEAR, or false if invalid date format
3239 */
3240 static function UnixTimeStamp($v)
3241 {
3242 return ADOConnection::UnixTimeStamp($v);
3243 }
3244
3245
3246 /**