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