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