forked from ADOdb/ADOdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
adodb.inc.php
5833 lines (5176 loc) · 152 KB
/
adodb.inc.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* ADOdb Library main include file.
*
* This file is part of ADOdb, a Database Abstraction Layer library for PHP.
*
* @package ADOdb
* @link https://adodb.org Project's web site and documentation
* @link https://github.com/ADOdb/ADOdb Source code and issue tracker
*
* The ADOdb Library is dual-licensed, released under both the BSD 3-Clause
* and the GNU Lesser General Public Licence (LGPL) v2.1 or, at your option,
* any later version. This means you can use it in proprietary products.
* See the LICENSE.md file distributed with this source code for details.
* @license BSD-3-Clause
* @license LGPL-2.1-or-later
*
* @copyright 2000-2013 John Lim
* @copyright 2014 Damien Regad, Mark Newnham and the ADOdb community
*/
if (!defined('_ADODB_LAYER')) {
define('_ADODB_LAYER',1);
// The ADOdb extension is no longer maintained and effectively unsupported
// since v5.04. The library will not function properly if it is present.
if(defined('ADODB_EXTENSION')) {
$msg = "Unsupported ADOdb Extension (v" . ADODB_EXTENSION . ") detected! "
. "Disable it to use ADOdb";
$errorfn = defined('ADODB_ERROR_HANDLER') ? ADODB_ERROR_HANDLER : false;
if ($errorfn) {
$conn = false;
$errorfn('ADOdb', basename(__FILE__), -9999, $msg, null, null, $conn);
} else {
die($msg . PHP_EOL);
}
}
//==============================================================================================
// CONSTANT DEFINITIONS
//==============================================================================================
/**
* Set ADODB_DIR to the directory where this file resides...
* This constant was formerly called $ADODB_RootPath
*/
if (!defined('ADODB_DIR')) {
define('ADODB_DIR',dirname(__FILE__));
}
//==============================================================================================
// GLOBAL VARIABLES
//==============================================================================================
GLOBAL
$ADODB_vers, // database version
$ADODB_COUNTRECS, // count number of records returned - slows down query
$ADODB_CACHE_DIR, // directory to cache recordsets
$ADODB_CACHE,
$ADODB_CACHE_CLASS,
$ADODB_COMPAT_FETCH, // If $ADODB_COUNTRECS and this is true, $rs->fields is available on EOF
$ADODB_FETCH_MODE, // DEFAULT, NUM, ASSOC or BOTH. Default follows native driver default...
$ADODB_GETONE_EOF,
$ADODB_QUOTE_FIELDNAMES; // Allows you to force quotes (backticks) around field names in queries generated by getinsertsql and getupdatesql.
//==============================================================================================
// GLOBAL SETUP
//==============================================================================================
/*********************************************************
* Controls $ADODB_FORCE_TYPE mode. Default is ADODB_FORCE_VALUE (3).
* Used in GetUpdateSql and GetInsertSql functions. Thx to Niko, nuko#mbnet.fi
* @link https://adodb.org/dokuwiki/doku.php?id=v5:reference:adodb_force_type
*
* 0 = ignore empty fields. All empty fields in array are ignored.
* 1 = force null. All empty, php null and string 'null' fields are
* changed to sql NULL values.
* 2 = force empty. All empty, php null and string 'null' fields are
* changed to sql empty '' or 0 values.
* 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.
* 4 = force value. Like 1 but numeric empty fields are set to zero.
*/
define('ADODB_FORCE_IGNORE',0);
define('ADODB_FORCE_NULL',1);
define('ADODB_FORCE_EMPTY',2);
define('ADODB_FORCE_VALUE',3);
define('ADODB_FORCE_NULL_AND_ZERO',4);
// ********************************************************
/**
* Constants for returned values from the charMax and textMax methods.
* If not specifically defined in the driver, methods return the NOTSET value.
*/
define ('ADODB_STRINGMAX_NOTSET', -1);
define ('ADODB_STRINGMAX_NOLIMIT',-2);
/*
* Defines the the default meta type returned
* when ADOdb encounters a type that it is not
* defined in the metaTypes.
*/
if (!defined('ADODB_DEFAULT_METATYPE'))
define ('ADODB_DEFAULT_METATYPE','N');
define('ADODB_BAD_RS','<p>Bad $rs in %s. Connection or SQL invalid. Try using $connection->debug=true;</p>');
// allow [ ] @ ` " and . in table names
define('ADODB_TABLE_REGEX','([]0-9a-z_\:\"\`\.\@\[-]*)');
// prefetching used by oracle
if (!defined('ADODB_PREFETCH_ROWS')) {
define('ADODB_PREFETCH_ROWS',10);
}
/**
* Fetch mode
*
* Set global variable $ADODB_FETCH_MODE to one of these constants or use
* the SetFetchMode() method to control how recordset fields are returned
* when fetching data.
*
* - NUM: array()
* - ASSOC: array('id' => 456, 'name' => 'john')
* - BOTH: array(0 => 456, 'id' => 456, 1 => 'john', 'name' => 'john')
* - DEFAULT: driver-dependent
*/
define('ADODB_FETCH_DEFAULT', 0);
define('ADODB_FETCH_NUM', 1);
define('ADODB_FETCH_ASSOC', 2);
define('ADODB_FETCH_BOTH', 3);
/**
* Associative array case constants
*
* By defining the ADODB_ASSOC_CASE constant to one of these values, it is
* possible to control the case of field names (associative array's keys)
* when operating in ADODB_FETCH_ASSOC fetch mode.
* - LOWER: $rs->fields['orderid']
* - UPPER: $rs->fields['ORDERID']
* - NATIVE: $rs->fields['OrderID'] (or whatever the RDBMS will return)
*
* The default is to use native case-names.
*
* NOTE: This functionality is not implemented everywhere, it currently
* works only with: mssql, odbc, oci8 and ibase derived drivers
*/
define('ADODB_ASSOC_CASE_LOWER', 0);
define('ADODB_ASSOC_CASE_UPPER', 1);
define('ADODB_ASSOC_CASE_NATIVE', 2);
if (!defined('TIMESTAMP_FIRST_YEAR')) {
define('TIMESTAMP_FIRST_YEAR',100);
}
/**
* AutoExecute constants
* (moved from adodb-pear.inc.php since they are only used in here)
*/
define('DB_AUTOQUERY_INSERT', 1);
define('DB_AUTOQUERY_UPDATE', 2);
function ADODB_Setup() {
GLOBAL
$ADODB_vers, // database version
$ADODB_COUNTRECS, // count number of records returned - slows down query
$ADODB_CACHE_DIR, // directory to cache recordsets
$ADODB_FETCH_MODE,
$ADODB_CACHE,
$ADODB_CACHE_CLASS,
$ADODB_FORCE_TYPE,
$ADODB_GETONE_EOF,
$ADODB_QUOTE_FIELDNAMES;
if (empty($ADODB_CACHE_CLASS)) {
$ADODB_CACHE_CLASS = 'ADODB_Cache_File' ;
}
$ADODB_FETCH_MODE = ADODB_FETCH_DEFAULT;
$ADODB_FORCE_TYPE = ADODB_FORCE_VALUE;
$ADODB_GETONE_EOF = null;
if (!isset($ADODB_CACHE_DIR)) {
$ADODB_CACHE_DIR = '/tmp'; //(isset($_ENV['TMP'])) ? $_ENV['TMP'] : '/tmp';
} else {
// do not accept url based paths, eg. http:/ or ftp:/
if (strpos($ADODB_CACHE_DIR,'://') !== false) {
die("Illegal path http:// or ftp://");
}
}
/**
* ADODB version as a string.
*/
$ADODB_vers = 'v5.23.0-dev Unreleased';
/**
* Determines whether recordset->RecordCount() is used.
* Set to false for highest performance -- RecordCount() will always return -1 then
* for databases that provide "virtual" recordcounts...
*/
if (!isset($ADODB_COUNTRECS)) {
$ADODB_COUNTRECS = true;
}
}
//==============================================================================================
// CHANGE NOTHING BELOW UNLESS YOU ARE DESIGNING ADODB
//==============================================================================================
ADODB_Setup();
//==============================================================================================
// CLASS ADOFieldObject
//==============================================================================================
/**
* Helper class for FetchFields -- holds info on a column
*/
class ADOFieldObject {
/**
* @var string Field name
*/
public $name = '';
/**
* @var int Field size
*/
public $max_length = 0;
/**
* @var string Field type.
*/
public $type = '';
/**
* @var bool True if field can be NULL
*/
public $not_null = false;
/**
* @var bool True if field is a primary key
*/
public $primary_key = false;
/**
* @var bool True if field is unique key
*/
public $unique = false;
/**
* @var bool True if field has a default value
*/
public $has_default = false;
/**
* @var mixed Default value, if any and supported; check {@see $has_default} first.
*/
public $default_value;
}
/**
* Parse date string to prevent injection attack.
*
* @param string $s
*
* @return string
*/
function _adodb_safedate($s) {
return str_replace(array("'", '\\'), '', $s);
}
/**
* Parse date string to prevent injection attack.
* Date string will have one quote at beginning e.g. '3434343'
*
* @param string $s
*
* @return string
*/
function _adodb_safedateq($s) {
$len = strlen($s);
if ($s[0] !== "'") {
$s2 = "'".$s[0];
} else {
$s2 = "'";
}
for($i=1; $i<$len; $i++) {
$ch = $s[$i];
if ($ch === '\\') {
$s2 .= "'";
break;
} elseif ($ch === "'") {
$s2 .= $ch;
break;
}
$s2 .= $ch;
}
return strlen($s2) == 0 ? 'null' : $s2;
}
/**
* For transaction handling.
*
* @param $dbms
* @param $fn
* @param $errno
* @param $errmsg
* @param $p1
* @param $p2
* @param $thisConnection
*/
function ADODB_TransMonitor($dbms, $fn, $errno, $errmsg, $p1, $p2, &$thisConnection) {
//print "Errorno ($fn errno=$errno m=$errmsg) ";
$thisConnection->_transOK = false;
if ($thisConnection->_oldRaiseFn) {
$errfn = $thisConnection->_oldRaiseFn;
$errfn($dbms, $fn, $errno, $errmsg, $p1, $p2,$thisConnection);
}
}
/**
* Class ADODB_Cache_File
*/
class ADODB_Cache_File {
var $createdir = true; // requires creation of temp dirs
function __construct() {
global $ADODB_INCLUDED_CSV;
if (empty($ADODB_INCLUDED_CSV)) {
include_once(ADODB_DIR.'/adodb-csvlib.inc.php');
}
}
/**
* Write serialised RecordSet to cache item/file.
*
* @param $filename
* @param $contents
* @param $debug
* @param $secs2cache
*
* @return bool|int
*/
function writecache($filename, $contents, $debug, $secs2cache) {
return adodb_write_file($filename, $contents,$debug);
}
/**
* load serialised RecordSet and unserialise it
*
* @param $filename
* @param $err
* @param $secs2cache
* @param $rsClass
*
* @return ADORecordSet
*/
function &readcache($filename, &$err, $secs2cache, $rsClass) {
$rs = csv2rs($filename,$err,$secs2cache,$rsClass);
return $rs;
}
/**
* Flush all items in cache.
*
* @param bool $debug
*
* @return bool|void
*/
function flushall($debug=false) {
global $ADODB_CACHE_DIR;
$rez = false;
if (strlen($ADODB_CACHE_DIR) > 1) {
$rez = $this->_dirFlush($ADODB_CACHE_DIR);
if ($debug) {
ADOConnection::outp( "flushall: $ADODB_CACHE_DIR<br><pre>\n". $rez."</pre>");
}
}
return $rez;
}
/**
* Flush one file in cache.
*
* @param string $f
* @param bool $debug
*/
function flushcache($f, $debug=false) {
if (!@unlink($f)) {
if ($debug) {
ADOConnection::outp( "flushcache: failed for $f");
}
}
}
/**
* @param string $hash
*
* @return string
*/
function getdirname($hash) {
global $ADODB_CACHE_DIR;
if (!isset($this->notSafeMode)) {
$this->notSafeMode = !ini_get('safe_mode');
}
return ($this->notSafeMode) ? $ADODB_CACHE_DIR.'/'.substr($hash,0,2) : $ADODB_CACHE_DIR;
}
/**
* Create temp directories.
*
* @param string $hash
* @param bool $debug
*
* @return string
*/
function createdir($hash, $debug) {
global $ADODB_CACHE_PERMS;
$dir = $this->getdirname($hash);
if ($this->notSafeMode && !file_exists($dir)) {
$oldu = umask(0);
if (!@mkdir($dir, empty($ADODB_CACHE_PERMS) ? 0771 : $ADODB_CACHE_PERMS)) {
if(!is_dir($dir) && $debug) {
ADOConnection::outp("Cannot create $dir");
}
}
umask($oldu);
}
return $dir;
}
/**
* Private function to erase all of the files and subdirectories in a directory.
*
* Just specify the directory, and tell it if you want to delete the directory or just clear it out.
* Note: $kill_top_level is used internally in the function to flush subdirectories.
*/
function _dirFlush($dir, $kill_top_level = false) {
if(!$dh = @opendir($dir)) return;
while (($obj = readdir($dh))) {
if($obj=='.' || $obj=='..') continue;
$f = $dir.'/'.$obj;
if (strpos($obj,'.cache')) {
@unlink($f);
}
if (is_dir($f)) {
$this->_dirFlush($f, true);
}
}
if ($kill_top_level === true) {
@rmdir($dir);
}
return true;
}
}
//==============================================================================================
// CLASS ADOConnection
//==============================================================================================
/**
* Connection object. For connecting to databases, and executing queries.
*/
abstract class ADOConnection {
//
// PUBLIC VARS
//
var $dataProvider = 'native';
var $databaseType = ''; /// RDBMS currently in use, eg. odbc, mysql, mssql
var $database = ''; /// Name of database to be used.
/**
* @var string If the driver is PDO, then the dsnType is e.g. sqlsrv, otherwise empty
*/
public $dsnType = '';
var $host = ''; /// The hostname of the database server
var $port = ''; /// The port of the database server
var $user = ''; /// The username which is used to connect to the database server.
var $password = ''; /// Password for the username. For security, we no longer store it.
var $debug = false; /// if set to true will output sql statements
var $maxblobsize = 262144; /// maximum size of blobs or large text fields (262144 = 256K)-- some db's die otherwise like foxpro
var $concat_operator = '+'; /// default concat operator -- change to || for Oracle/Interbase
var $substr = 'substr'; /// substring operator
var $length = 'length'; /// string length ofperator
var $random = 'rand()'; /// random function
var $upperCase = 'upper'; /// uppercase function
var $fmtDate = "'Y-m-d'"; /// used by DBDate() as the default date format used by the database
var $fmtTimeStamp = "'Y-m-d, h:i:s A'"; /// used by DBTimeStamp as the default timestamp fmt.
var $true = '1'; /// string that represents TRUE for a database
var $false = '0'; /// string that represents FALSE for a database
var $replaceQuote = "\\'"; /// string to use to replace quotes
var $nameQuote = '"'; /// string to use to quote identifiers and names
var $leftBracket = '['; /// left square bracked for t-sql styled column names
var $rightBracket = ']'; /// right square bracked for t-sql styled column names
var $charSet=false; /// character set to use - only for interbase, postgres and oci8
var $metaDatabasesSQL = '';
var $metaTablesSQL = '';
var $uniqueOrderBy = false; /// All order by columns have to be unique
var $emptyDate = ' ';
var $emptyTimeStamp = ' ';
var $lastInsID = false;
//--
var $hasInsertID = false; /// supports autoincrement ID?
var $hasAffectedRows = false; /// supports affected rows for update/delete?
var $hasTop = false; /// support mssql/access SELECT TOP 10 * FROM TABLE
var $hasLimit = false; /// support pgsql/mysql SELECT * FROM TABLE LIMIT 10
var $readOnly = false; /// this is a readonly database - used by phpLens
var $hasMoveFirst = false; /// has ability to run MoveFirst(), scrolling backwards
var $hasGenID = false; /// can generate sequences using GenID();
var $hasTransactions = true; /// has transactions
//--
var $genID = 0; /// sequence id used by GenID();
/** @var bool|callable Error function to call */
var $raiseErrorFn = false;
var $isoDates = false; /// accepts dates in ISO format
var $cacheSecs = 3600; /// cache for 1 hour
/*****************************************
* memcached server options
******************************************/
/**
* Use memCache library instead of caching in files.
* @var bool $memCache
*/
public $memCache = false;
/**
* The memcache server(s) to connect to. Can be defined as:
* - a single host name/ip address
* - a list of hosts/ip addresses
* - an array of server connection data (weighted server groups).
* @link https://adodb.org/dokuwiki/doku.php?id=v5:userguide:memcached
* @var string|array $memCacheHost
*/
public $memCacheHost;
/**
* Default port number.
* The default port can be overridden if memcache server connection data
* is provided as an array {@see $memCacheHost}.
* @var int $memCachePort
*/
public $memCachePort = 11211;
/**
* Enable compression of stored items.
* @var bool $memCacheCompress
*/
public $memCacheCompress = false;
/**
* An array of memcached options.
* Only used with memcached; memcache ignores this setting.
* @link https://www.php.net/manual/en/memcached.constants.php
* @var array $memCacheOptions
*/
public $memCacheOptions = array();
var $sysDate = false; /// name of function that returns the current date
var $sysTimeStamp = false; /// name of function that returns the current timestamp
var $sysUTimeStamp = false; // name of function that returns the current timestamp accurate to the microsecond or nearest fraction
var $arrayClass = 'ADORecordSet_array'; /// name of class used to generate array recordsets, which are pre-downloaded recordsets
var $noNullStrings = false; /// oracle specific stuff - if true ensures that '' is converted to ' '
var $numCacheHits = 0;
var $numCacheMisses = 0;
var $pageExecuteCountRows = true;
var $uniqueSort = false; /// indicates that all fields in order by must be unique
var $leftOuter = false; /// operator to use for left outer join in WHERE clause
var $rightOuter = false; /// operator to use for right outer join in WHERE clause
var $ansiOuter = false; /// whether ansi outer join syntax supported
var $autoRollback = false; // autoRollback on PConnect().
var $poorAffectedRows = false; // affectedRows not working or unreliable
/** @var bool|callable Execute function to call */
var $fnExecute = false;
/** @var bool|callable Cache execution function to call */
var $fnCacheExecute = false;
var $blobEncodeType = false; // false=not required, 'I'=encode to integer, 'C'=encode to char
var $rsPrefix = "ADORecordSet_";
var $autoCommit = true; /// do not modify this yourself - actually private
var $transOff = 0; /// temporarily disable transactions
var $transCnt = 0; /// count of nested transactions
var $fetchMode=false;
var $null2null = 'null'; // in autoexecute/getinsertsql/getupdatesql, this value will be converted to a null
var $bulkBind = false; // enable 2D Execute array
//
// PRIVATE VARS
//
var $_oldRaiseFn = false;
var $_transOK = null;
/** @var resource Identifier for the native database connection */
var $_connectionID = false;
var $_errorMsg = false; /// A variable which was used to keep the returned last error message. The value will
/// then returned by the errorMsg() function
var $_errorCode = false; /// Last error code, not guaranteed to be used - only by oci8
var $_queryID = false; /// This variable keeps the last created result link identifier
var $_isPersistentConnection = false; /// A boolean variable to state whether its a persistent connection or normal connection. */
var $_bindInputArray = false; /// set to true if ADOConnection.Execute() permits binding of array parameters.
var $_evalAll = false;
var $_affected = false;
var $_logsql = false;
var $_transmode = ''; // transaction mode
/**
* Additional parameters that may be passed to drivers in the connect string.
*
* Data is stored as an array of arrays and not a simple associative array,
* because some drivers (e.g. mysql) allow multiple parameters with the same
* key to be set.
* @link https://github.com/ADOdb/ADOdb/issues/187
*
* @see setConnectionParameter()
*
* @var array $connectionParameters Set of ParameterName => Value pairs
*/
protected $connectionParameters = array();
/*
* A simple associative array of user-defined custom actual/meta types
*/
public $customActualTypes = array();
/*
* An array of user-defined custom meta/actual types.
* $this->customMetaTypes[$meta] = array(
* 'actual'=>'',
* 'dictionary'=>'',
* 'handler'=>'',
* 'callback'=>''
* );
*/
public $customMetaTypes = array();
/**
* Default Constructor.
* We define it even though it does not actually do anything. This avoids
* getting a PHP Fatal error: Cannot call constructor if a subclass tries
* to call its parent constructor.
*/
public function __construct()
{
}
/**
* Adds a parameter to the connection string.
*
* Parameters must be added before the connection is established;
* they are then passed on to the connect statement, which will.
* process them if the driver supports this feature.
*
* Example usage:
* - mssqlnative: setConnectionParameter('CharacterSet','UTF-8');
* - mysqli: setConnectionParameter(MYSQLI_SET_CHARSET_NAME,'utf8mb4');
*
* If used in a portable environment, parameters set in this manner should
* be predicated on the database provider, as unexpected results may occur
* if applied to the wrong database.
*
* @param string $parameter The name of the parameter to set
* @param string $value The value of the parameter
*
* @return bool True if success, false otherwise (e.g. parameter is not valid)
*/
public function setConnectionParameter($parameter, $value) {
$this->connectionParameters[] = array($parameter=>$value);
return true;
}
/**
* ADOdb version.
*
* @return string
*/
static function Version() {
global $ADODB_vers;
// Semantic Version number matching regex
$regex = '^[vV]?(\d+\.\d+\.\d+' // Version number (X.Y.Z) with optional 'V'
. '(?:-(?:' // Optional preprod version: a '-'
. 'dev|' // followed by 'dev'
. '(?:(?:alpha|beta|rc)(?:\.\d+))' // or a preprod suffix and version number
. '))?)(?:\s|$)'; // Whitespace or end of string
if (!preg_match("/$regex/", $ADODB_vers, $matches)) {
// This should normally not happen... Return whatever is between the start
// of the string and the first whitespace (or the end of the string).
self::outp("Invalid version number: '$ADODB_vers'", 'Version');
$regex = '^[vV]?(.*?)(?:\s|$)';
preg_match("/$regex/", $ADODB_vers, $matches);
}
return $matches[1];
}
/**
* Set a custom meta type with a corresponding actual
*
* @param string $metaType The Custom ADOdb metatype
* @param string $dictionaryType The database dictionary type
* @param string $actualType The database actual type
* @param bool $handleAsType handle like an existing Metatype
* @param mixed $callBack A pre-processing function
*
* @return bool success if the actual exists
*/
final public function setCustomMetaType(
$metaType,
$dictionaryType,
$actualType,
$handleAsType=false,
$callback=false){
$this->customMetaTypes[strtoupper($metaType)] = array(
'actual'=>$actualType,
'dictionary'=>strtoupper($dictionaryType),
'handler'=>$handleAsType,
'callback'=>$callback
);
/*
* Create a reverse lookup for the actualType
*/
$this->customActualTypes[$actualType] = $metaType;
return true;
}
/**
* Get a list of custom meta types.
*
* @return string[]
*/
final public function getCustomMetaTypes()
{
return $this->customMetaTypes;
}
/**
* Get server version info.
*
* @return string[] Array with 2 string elements: version and description
*/
function ServerInfo() {
return array('description' => '', 'version' => '');
}
/**
* Return true if connected to the database.
*
* @return bool
*/
function IsConnected() {
return !empty($this->_connectionID);
}
/**
* Find version string.
*
* @param string $str
*
* @return string
*/
function _findvers($str) {
if (preg_match('/([0-9]+\.([0-9\.])+)/',$str, $arr)) {
return $arr[1];
} else {
return '';
}
}
/**
* All error messages go through this bottleneck function.
*
* You can define your own handler by defining the function name in ADODB_OUTP.
*
* @param string $msg Message to print
* @param bool $newline True to add a newline after printing $msg
*/
static function outp($msg,$newline=true) {
global $ADODB_FLUSH,$ADODB_OUTP;
if (defined('ADODB_OUTP')) {
$fn = ADODB_OUTP;
$fn($msg,$newline);
return;
} else if (isset($ADODB_OUTP)) {
call_user_func($ADODB_OUTP,$msg,$newline);
return;
}
if ($newline) {
$msg .= "<br>\n";
}
if (isset($_SERVER['HTTP_USER_AGENT']) || !$newline) {
echo $msg;
} else {
echo strip_tags($msg);
}
if (!empty($ADODB_FLUSH) && ob_get_length() !== false) {
flush(); // do not flush if output buffering enabled - useless - thx to Jesse Mullan
}
}
/**
* Return the database server's current date and time.
* @return int|false
*/
function Time() {
$rs = $this->_Execute("select $this->sysTimeStamp");
if ($rs && !$rs->EOF) {
return $this->UnixTimeStamp(reset($rs->fields));
}
return false;
}
/**
* Parses the hostname to extract the port.
* Overwrites $this->host and $this->port, only if a port is specified.
* The Hostname can be fully or partially qualified,
* ie: "db.mydomain.com:5432" or "ldaps://ldap.mydomain.com:636"
* Any specified scheme such as ldap:// or ldaps:// is maintained.
*/
protected function parseHostNameAndPort() {
$parsed_url = parse_url($this->host);
if (is_array($parsed_url) && isset($parsed_url['host']) && isset($parsed_url['port'])) {
if ( isset($parsed_url['scheme']) ) {
// If scheme is specified (ie: ldap:// or ldaps://, make sure we retain that.
$this->host = $parsed_url['scheme'] . "://" . $parsed_url['host'];
} else {
$this->host = $parsed_url['host'];
}
$this->port = $parsed_url['port'];
}
}
/**
* Connect to database.
*
* @param string $argHostname Host to connect to
* @param string $argUsername Userid to login
* @param string $argPassword Associated password
* @param string $argDatabaseName Database name
* @param bool $forceNew Force new connection
*
* @return bool
*/
function Connect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "", $forceNew = false) {
if ($argHostname != "") {
$this->host = $argHostname;
}
// Overwrites $this->host and $this->port if a port is specified.
$this->parseHostNameAndPort();
if ($argUsername != "") {
$this->user = $argUsername;
}
if ($argPassword != "") {
$this->password = 'not stored'; // not stored for security reasons
}
if ($argDatabaseName != "") {
$this->database = $argDatabaseName;
}
$this->_isPersistentConnection = false;
if ($forceNew) {
if ($rez=$this->_nconnect($this->host, $this->user, $argPassword, $this->database)) {
return true;
}
} else {
if ($rez=$this->_connect($this->host, $this->user, $argPassword, $this->database)) {
return true;
}
}
if (isset($rez)) {
$err = $this->ErrorMsg();
$errno = $this->ErrorNo();
if (empty($err)) {
$err = "Connection error to server '$argHostname' with user '$argUsername'";
}
} else {
$err = "Missing extension for ".$this->dataProvider;
$errno = 0;
}
if ($fn = $this->raiseErrorFn) {
$fn($this->databaseType, 'CONNECT', $errno, $err, $this->host, $this->database, $this);
}
$this->_connectionID = false;
if ($this->debug) {
ADOConnection::outp( $this->host.': '.$err);
}
return false;
}
/**
* Always force a new connection to database.
*
* @param string $argHostname Host to connect to
* @param string $argUsername Userid to login
* @param string $argPassword Associated password
* @param string $argDatabaseName Database name
*
* @return bool
*/
function _nconnect($argHostname, $argUsername, $argPassword, $argDatabaseName) {
return $this->_connect($argHostname, $argUsername, $argPassword, $argDatabaseName);
}
/**
* Always force a new connection to database.
*
* Currently this only works with Oracle.
*
* @param string $argHostname Host to connect to
* @param string $argUsername Userid to login
* @param string $argPassword Associated password
* @param string $argDatabaseName Database name
*
* @return bool
*/
function NConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") {
return $this->Connect($argHostname, $argUsername, $argPassword, $argDatabaseName, true);
}
/**
* Establish persistent connection to database.
*
* @param string $argHostname Host to connect to
* @param string $argUsername Userid to login
* @param string $argPassword Associated password
* @param string $argDatabaseName Database name
*
* @return bool
*/
function PConnect($argHostname = "", $argUsername = "", $argPassword = "", $argDatabaseName = "") {
if (defined('ADODB_NEVER_PERSIST')) {
return $this->Connect($argHostname,$argUsername,$argPassword,$argDatabaseName);
}
if ($argHostname != "") {
$this->host = $argHostname;
}
// Overwrites $this->host and $this->port if a port is specified.
$this->parseHostNameAndPort();
if ($argUsername != "") {
$this->user = $argUsername;
}
if ($argPassword != "") {
$this->password = 'not stored';
}
if ($argDatabaseName != "") {
$this->database = $argDatabaseName;
}
$this->_isPersistentConnection = true;
if ($rez = $this->_pconnect($this->host, $this->user, $argPassword, $this->database)) {
return true;
}
if (isset($rez)) {
$err = $this->ErrorMsg();
if (empty($err)) {
$err = "Connection error to server '$argHostname' with user '$argUsername'";