• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

NathanGibbs3 / BASE / 590

pending completion
590

push

travis-ci-com

NathanGibbs3
20230420 Fix CI build breakage. 2

2755 of 16977 relevant lines covered (16.23%)

21.61 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

46.06
/includes/base_db.inc.php
1
<?php
2
/*******************************************************************************
3
** Basic Analysis and Security Engine (BASE)
4
** Copyright (C) 2004 BASE Project Team
5
** Copyright (C) 2000 Carnegie Mellon University
6
**
7
** (see the file 'base_main.php' for license details)
8
**
9
** Project Lead: Kevin Johnson <kjohnson@secureideas.net>
10
**                Sean Muller <samwise_diver@users.sourceforge.net>
11
** Built upon work by Roman Danyliw <rdd@cert.org>, <roman@danyliw.com>
12
**
13
** Purpose: Database abstraction layer
14
********************************************************************************
15
** Authors:
16
********************************************************************************
17
** Kevin Johnson <kjohnson@secureideas.net
18
**
19
********************************************************************************
20
*/
21
/** The below check is to make sure that the conf file has been loaded before this one....
22
 **  This should prevent someone from accessing the page directly. -- Kevin
23
 **/
24
defined( '_BASE_INC' ) or die( 'Accessing this file directly is not allowed.' );
25

26
class baseCon {
27
        var $DB;
28
        var $DB_type;
29
        var $DB_name;
30
        var $DB_host;
31
        var $DB_port;
32
        var $DB_username;
33
        var $lastSQL;
34
        var $version;
35
        var $sql_trace;
36
        var $DB_class;
37

38
        function __construct($type) { // PHP 5+ constructor Shim.
39
                // Class/Method agnostic shim code.
40
                $SCname = get_class();
460✔
41
                if ( method_exists($this, $SCname) ) {
460✔
42
                        $SCargs = func_get_args();
460✔
43
                        call_user_func_array(array($this, $SCname), $SCargs);
460✔
44
                }else{
138✔
45
                        // @codeCoverageIgnoreStart
46
                        // Should never execute.
47
                        trigger_error( // Will need to add this message to the TD.
48
                                "Class: $SCname No Legacy Constructor.\n",
49
                                E_USER_ERROR
50
                        );
51
                        // @codeCoverageIgnoreEnd
52
                }
53
        }
322✔
54
        function baseCon($type) { // PHP 4x constructor.
55
                $this->DB_type = $type;
460✔
56
                // Are we a Mysql type? Note it in Class structure.
57
                if ( $type == "mysql" || $type == "mysqlt" || $type == "maxsql" ) {
460✔
58
                        $this->DB_class = 1;
230✔
59
                }else{
69✔
60
                        $this->DB_class = 0;
230✔
61
                }
62
        }
322✔
63
        function baseDBConnect(
64
                $method, $database, $host, $port, $username, $password, $force = 0
65
        ){
66
                GLOBAL $archive_dbname, $archive_host, $archive_port, $archive_user,
322✔
67
                $archive_password, $debug_mode, $et;
184✔
68
                $EMPfx = __FUNCTION__ . '(): ';
460✔
69
                // Check archive cookie to see if we need to use the archive tables.
70
                // Only honnor cookie if not forced to use specified database.
71
                if ( $force != 1 && ChkArchive() ){ // Connect to archive DB.
460✔
72
                        $DBDesc = 'Archive'; // Need to TD this in Issue #11 branch.
×
73

74
      if ( $method == DB_CONNECT )
×
75
        $this->baseConnect($archive_dbname, $archive_host, $archive_port, $archive_user, $archive_password);
×
76
      else
77
        $this->basePConnect($archive_dbname, $archive_host, $archive_port, $archive_user, $archive_password);
×
78

79
                }else{ // Connect to the main alert tables
80
                        $DBDesc = 'Alert'; // Need to TD this in Issue #11 branch.
460✔
81

82
      if ( $method == DB_CONNECT )
460✔
83
        $this->baseConnect($database, $host, $port, $username, $password);
138✔
84
      else
85
        $this->basePConnect($database, $host, $port, $username, $password);
460✔
86
        }
87
        // Need to TD these in Issue #11 branch.
88
        if ($debug_mode > 1){
460✔
89
                ErrorMessage($EMPfx ."DB Connect to $DBDesc.",'black',1);
×
90
        }
91
        if ( is_object($et) && $debug_mode > 1 ){
460✔
92
                $et->Mark("DB Connect: $DBDesc.");
×
93
        }
94
}
322✔
95
  function baseConnect($database, $host, $port, $username, $password)
96
  {
97
     GLOBAL $sql_trace_mode, $sql_trace_file;
98
 
99
     $this->DB = NewADOConnection();
×
100
     $this->DB_name = $database;
×
101
     $this->DB_host = $host;
×
102
     $this->DB_port = $port;
×
103
     $this->DB_username = $username;
×
104

105
     if ( $sql_trace_mode > 0 )
×
106
     {
107
        $this->sql_trace = fopen($sql_trace_file,"a");
×
108
        if ( !$this->sql_trace )
×
109
        {
110
           ErrorMessage(_ERRSQLTRACE." '".$sql_trace_file."'");
×
111
           die();
×
112
        }
113
     }
114

115
     $db = $this->DB->Connect( ( ( $port == "") ? $host : ($host.":".$port) ),
×
116
                               $username, $password, $database); 
117

118
     if ( !$db )
×
119
     {
120
        $tmp_host = ( $port == "") ? $host : ($host.":".$port);
×
121
        echo '<P><B>'._ERRSQLCONNECT.' </B>'.
×
122
             $database.'@'. $tmp_host ._ERRSQLCONNECTINFO;
123

124
        echo $this->baseErrorMessage();
×
125
        die();
×
126
     } 
127

128
     /* Set the database schema version number */
129
     $sql = "SELECT vseq FROM schema";
×
130
        if ( $this->DB_class == 1 ) $sql = "SELECT vseq FROM `schema`";
×
131
     if ($this->DB_type == "mssql") $sql = "SELECT vseq FROM [schema]";
×
132

133
     $result = $this->DB->Execute($sql);
×
134
     if ( $this->baseErrorMessage() != "" )
×
135
        $this->version = 0;
×
136
     else
137
     {
138
        $myrow = $result->fields;
×
139
        $this->version = $myrow[0];
×
140
        $result->Close();
×
141
     }
142
     
143
     if ( $sql_trace_mode > 0 )
×
144
     {
145
        fwrite($this->sql_trace, 
×
146
              "\n--------------------------------------------------------------------------------\n");  
147
        fwrite($this->sql_trace, "Connect [".$this->DB_type."] ".$database."@".$host.":".$port." as ".$username."\n");
×
148
        fwrite($this->sql_trace, "[".date ("M d Y H:i:s", time())."] ".$_SERVER["SCRIPT_NAME"]." - db version ".$this->version);
×
149
        fwrite($this->sql_trace, 
×
150
              "\n--------------------------------------------------------------------------------\n\n");
151
        fflush($this->sql_trace);
×
152
     }     
153

154
     return $db;
×
155
  }
156

157
  function basePConnect($database, $host, $port, $username, $password)
158
  {
159
     GLOBAL $sql_trace_mode, $sql_trace_file; 
322✔
160

161
     $this->DB = NewADOConnection();
460✔
162
     $this->DB_name = $database;
460✔
163
     $this->DB_host = $host;
460✔
164
     $this->DB_port = $port;
460✔
165
     $this->DB_username = $username;
460✔
166

167
     if ( $sql_trace_mode > 0 )
460✔
168
     {
138✔
169
        $this->sql_trace = fopen($sql_trace_file,"a");
×
170
        if ( !$this->sql_trace )
×
171
        {
172
           ErrorMessage(_ERRSQLTRACE." '".$sql_trace_file."'");
×
173
           die();
×
174
        }
175
     }
176

177
     $db = $this->DB->PConnect( ( ( $port == "") ? $host : ($host.":".$port) ),
460✔
178
                               $username, $password, $database); 
276✔
179

180
     if ( !$db )
460✔
181
     {
138✔
182
        $tmp_host = ( $port == "") ? $host : ($host.":".$port);
×
183
        echo '<P><B>'._ERRSQLPCONNECT.' </B>'.
×
184
             $database.'@'. $tmp_host ._ERRSQLCONNECTINFO;
185

186
        echo $this->baseErrorMessage();
×
187
        die();
×
188
     } 
189

190
     /* Set the database schema version number */
191
     $sql = "SELECT vseq FROM schema"; 
460✔
192
     if ($this->DB_type == "mssql") $sql = "SELECT vseq FROM [schema]";
460✔
193
        if ( $this->DB_class == 1 ) $sql = "SELECT vseq FROM `schema`";
460✔
194

195
     $result = $this->DB->Execute($sql);
460✔
196
     if ( $this->baseErrorMessage() != "" )
460✔
197
        $this->version = 0;
138✔
198
     else
199
     {
200
        $myrow = $result->fields;
460✔
201
        $this->version = $myrow[0];
460✔
202
        $result->Close();
460✔
203
     }
204

205
     if ( $sql_trace_mode > 0 )
460✔
206
     {
138✔
207
        fwrite($this->sql_trace, 
×
208
              "\n--------------------------------------------------------------------------------\n");  
209
        fwrite($this->sql_trace, "PConnect [".$this->DB_type."] ".$database."@".$host.":".$port." as ".$username."\n");
×
210
        fwrite($this->sql_trace, "[".date ("M d Y H:i:s", time())."] ".$_SERVER["SCRIPT_NAME"]." - db version ".$this->version);
×
211
        fwrite($this->sql_trace, 
×
212
              "\n--------------------------------------------------------------------------------\n\n");
213
        fflush($this->sql_trace);
×
214
     } 
215

216
     return $db;
460✔
217
  }
218

219
  function baseClose()
220
  {
221
     $this->DB->Close();
×
222
  }
223
        function baseExecute(
224
                $sql, $start_row = 0, $num_rows = -1, $hard_error = true
225
        ){
226
                GLOBAL $debug_mode, $sql_trace_mode, $db_connect_method,
252✔
227
                        $alert_password, $archive_dbname, $archive_host, $archive_port,
144✔
228
                        $archive_user, $archive_password;
144✔
229
                $EPfx = 'BASE DB ';
360✔
230
                $tdt = $this->DB_type;
360✔
231
                $tdn = $this->DB_name;
360✔
232
                $DSN = $this->DB_host;
360✔
233
                $tdp = $this->DB_port;
360✔
234
                $tdu = $this->DB_username;
360✔
235
                $rs = false; // Default returns failure.
360✔
236
                if (
237
                        $DSN == $archive_host && $tdp == $archive_port
288✔
238
                        && $tdn == $archive_dbname && $tdu == $archive_user
288✔
239
                ){
108✔
240
                        $tdpw = $archive_password;
×
241
                }else{
242
                        $tdpw = $alert_password;
360✔
243
                }
244
                if ( $tdp != '' ){
360✔
245
                        $DSN = "$DSN:$tdp";
360✔
246
                }
108✔
247
                // Begin DB specific SQL fix-up.
248
                // @codeCoverageIgnoreStart
249
                // We have no way of testing Oracle or Ms-SQL functionality.
250
                if ( $this->DB_type == 'mssql' ){
251
                        $sql = preg_replace("/''/i", "NULL", $sql);
252
                }elseif ( $this->DB_type == 'oci8' ){
253
                        if (!strpos($sql, 'TRIGGER')){
254
                                if (substr($sql, strlen($sql)-1, strlen($sql))==';'){
255
                                        $sql=substr($sql, 0, strlen($sql)-1);
256
                                }
257
                        }
258
                }
259
                // @codeCoverageIgnoreEnd
260
                if ( !$this->DB->isConnected() ){
360✔
261
                        // Check for connection before executing query.
262
                        // Try to reconnect of DB connection is down.
263
                        // Found via CI. Might be related to PHP 5.2x not supporting
264
                        // persistant DB connections.
265
                        error_log($EPfx."Disconnected: $tdt $tdn @ $DSN");
×
266
                        error_log($EPfx."Reconnecting: $tdt $tdn @ $DSN");
×
267
                        if ( $db_connect_method == DB_CONNECT ){
×
268
                                $db = $this->DB->Connect( $DSN, $tdu, $tdpw, $tdn);
×
269
                        }else{
270
                                $db = $this->DB->PConnect( $DSN, $tdu, $tdpw, $tdn);
×
271
                        }
272
                        if ( !$this->DB->isConnected() ){
×
273
                                FatalError("$EPfx Reconnect Failed");
×
274
                        }else{
275
                                error_log("$EPfx Reconnected");
×
276
                        }
277
                }
278
                $this->lastSQL = $sql;
360✔
279
                $limit_str = '';
360✔
280
                if ( is_int($start_row) & is_int($num_rows) ){ // Issue #169
360✔
281
                        if ( $num_rows != -1 ){ // Do we add a LIMIT / TOP / ROWNUM clause.
340✔
282
                                if ( $this->DB_class == 1 ){
20✔
283
                                        $limit_str = " LIMIT ".$start_row.", ".$num_rows;
10✔
284
                                // @codeCoverageIgnoreStart
285
                                // We have no way of testing Oracle functionality.
286
                                }elseif ( $this->DB_type == "oci8" ){
287
                                        // $limit_str = " LIMIT ".$start_row.", ".$num_rows;
288
                                        // Why, we don't use it.
289
                                // @codeCoverageIgnoreEnd
290
                                }elseif ( $this->DB_type == "postgres" ){
10✔
291
                                        $limit_str = " LIMIT ".$num_rows." OFFSET ".$start_row;
241✔
292
                                }
3✔
293
                        }
6✔
294
                }else{ // Log error & quit.
102✔
295
                        $msg = $EPfx.'Query Halt: Invalid LIMIT.';
20✔
296
                        error_log($msg);
20✔
297
                        return $rs;
20✔
298
                }
299
                $qry = $sql.$limit_str;
340✔
300
                if ( $debug_mode > 1 ){
340✔
301
                        // See: https://github.com/NathanGibbs3/BASE/issues/113
302
                        // Some legecy code has " 1 = 1 " in the query string. Log it here.
303
                        if ( strstr($qry, ' 1 = 1 ') ){
×
304
                                error_log("Issue #113 $qry");
×
305
                                error_log('See: https://github.com/NathanGibbs3/BASE/issues/113');
×
306
                        }
307
                }
308
                // See: https://github.com/NathanGibbs3/BASE/issues/67
309
                // Legacy code assumed $this->DB->Execute() returns a valid recordset.
310
                // It returns false on error. Catch it here.
311
                $result = $this->DB->Execute($qry);
340✔
312
                if ( $result ){
300✔
313
                        $rs = new baseRS($result, $this->DB_type);
200✔
314
                }
60✔
315
                // @codeCoverageIgnoreStart
316
                // We have no way of testing this functionality on these DB's
317
                if ( $num_rows != -1 && $limit_str == '' && $rs != false ){
318
                        // DB's which do not support LIMIT (e.g. MS SQL) natively must
319
                        // emulated it by walking the current row from the start of
320
                        // rowset to the desired start row.
321
                        $i = 0;
322
                        while ( ($i < $start_row) && $rs ){
323
                                if ( !$rs->row->EOF ){
324
                                        $rs->row->MoveNext();
325
                                }
326
                                $i++;
327
                        }
328
                }
329
                // @codeCoverageIgnoreEnd
330
     if ( $sql_trace_mode > 0 )
300✔
331
     {
90✔
332
        fputs($this->sql_trace, $sql."\n");
×
333
        fflush($this->sql_trace);
×
334
     }
335
                $tmp = $this->baseErrorMessage();
300✔
336
                if ( (!$rs || $tmp != '') && $hard_error ){
300✔
337
                        $msg = $EPfx.'Query Fail: ';
×
338
                        if ( !$rs ){
×
339
                                $msg .= 'NULL Recordset ';
×
340
                        }
341
                        if ( $tmp !='' ){
×
342
                                $msg .= $tmp;
×
343
                        }else{
344
                                $msg .= 'NO ADOdb Error Msg';
×
345
                        }
346
                        $msg = returnErrorMessage($msg,0,1);
×
347
                        if ( $debug_mode > 0
348
                                // Issue #5 Info Shim
349
                                || (
350
                                        getenv('TRAVIS')
×
351
                                        && version_compare(PHP_VERSION, "5.3.0", "<")
×
352
                                )
353
                        ){
354
                                $msg .= "<p>DB Engine: $tdt DB: $tdn @ $DSN</p>";
×
355
                                $msg .= '<p>SQL QUERY: <code>'.$qry.'</code></p>';
×
356
                        }
357
                        FatalError ($msg);
×
358
                }else{
359
                        return $rs;
300✔
360
                }
361
        }
362
        function baseErrorMessage(){
363
                GLOBAL $debug_mode;
448✔
364
                $msg = '';
640✔
365
                $tmp = $this->DB->ErrorMsg();
640✔
366
                if ( $tmp ){
640✔
367
                        $msg = '<b>'._ERRSQLDB.'</b> ';
62✔
368
                        $msg .= $tmp;
62✔
369
                        if ( $debug_mode > 0 ){
62✔
370
                                $msg .= '<p><code>'.$this->lastSQL.'</code></p>';
20✔
371
                        }
6✔
372
                        // @codeCoverageIgnoreStart
373
                        // We have no way of testing Ms-SQL functionality.
374
                        // MS-SQL Error messages that are not issues.
375
                        if ( $this->DB_type == 'mssql' && preg_match(
376
                                "/Changed (databas|languag)e (context|setting) to/", $tmp
377
                        )){
378
                                $msg = '';
379
                        }
380
                        // @codeCoverageIgnoreEnd
381
                }
20✔
382
                return $msg;
640✔
383
        }
384
        function baseFieldExists($table,$field){
385
                $Ret = 0;
167✔
386
                if ( $this->baseTableExists($table) ){
167✔
387
                        if ( in_array($field, $this->DB->metacolumnNames($table)) ){
150✔
388
                                $Ret = 1;
90✔
389
                        }
27✔
390
                }
45✔
391
                return $Ret;
167✔
392
        }
393
        function baseTableExists($table){
394
                $Ret = 0;
387✔
395
                // @codeCoverageIgnoreStart
396
                // We have no way of testing Oracle functionality.
397
                if ( $this->DB_type == 'oci8' ){
398
                        $table=strtoupper($table);
399
                }
400
                // @codeCoverageIgnoreEnd
401
                if ( in_array($table, $this->DB->MetaTables()) ){
387✔
402
                        $Ret = 1;
290✔
403
                }
87✔
404
                return $Ret;
387✔
405
        }
406
        // This function is not used anywhere.
407
        function baseIndexExists($table, $index_name){
408
                $Ret = 0;
60✔
409
                if ( $this->baseTableExists($table) ){
60✔
410
                        $tmp = $this->DB->MetaIndexes($table);
40✔
411
                        if ( $tmp != false ){
40✔
412
                                foreach ($tmp as $key => $value) { // Iterate Index List
40✔
413
                                        if ( base_array_key_exists('columns', $value) ){
40✔
414
                                                if ( in_array(
40✔
415
                                                                $index_name,
28✔
416
                                                                array_values($value['columns'])
40✔
417
                                                ) ){
12✔
418
                                                        $Ret = 1;
24✔
419
                                                }
6✔
420
                                        }
12✔
421
                                }
12✔
422
                        }
12✔
423
                }
12✔
424
                return $Ret;
60✔
425
        }
426
  function baseInsertID()
427
  {
428
  /* Getting the insert ID fails on certain databases (e.g. postgres), but we may use it on the once it works
429
   * on.  This function returns -1 if the dbtype is postgres, then we can run a kludge query to get the insert 
430
   * ID.  That query may vary depending upon which table you are looking at and what variables you have set at
431
   * the current point, so it can't be here and needs to be in the actual script after calling this function
432
   *  -- srh (02/01/2001)
433
   */
434
        if ( $this->DB_class == 1 || $this->DB_type == "mssql" )
×
435
        return $this->DB->Insert_ID();
×
436
     else if ($this->DB_type == "postgres" ||($this->DB_type == "oci8"))
×
437
        return -1;   
×
438
  }
439

440
  function baseTimestampFmt($timestamp)
441
  {
442
    // Not used anywhere????? -- Kevin
443
     return $this->DB->DBTimeStamp($timestamp);
×
444
  }
445

446
  function baseSQL_YEAR($func_param, $op, $timestamp)
447
  {
448
        if ( $this->DB_class == 1 || $this->DB_type == "mssql" )
×
449
        return " YEAR($func_param) $op $timestamp ";
×
450
     else if( $this->DB_type == "oci8" )
×
451
        return " to_number( to_char( $func_param, 'RRRR' ) ) $op $timestamp ";
×
452
     else if ( $this->DB_type == "postgres" )
×
453
        return " DATE_PART('year', $func_param) $op $timestamp ";  
×
454
  }
455

456
  function baseSQL_MONTH($func_param, $op, $timestamp)
457
  {
458
        if ( $this->DB_class == 1 || $this->DB_type == "mssql" )
×
459
        return " MONTH($func_param) $op $timestamp ";
×
460
     else if( $this->DB_type == "oci8" )
×
461
        return " to_number( to_char( $func_param, 'MM' ) ) $op $timestamp ";
×
462
     else if ( $this->DB_type == "postgres" )
×
463
        return " DATE_PART('month', $func_param) $op $timestamp "; 
×
464
  }
465

466
  function baseSQL_DAY($func_param, $op, $timestamp)
467
  {
468
        if ( $this->DB_class == 1 )
×
469
        return " DAYOFMONTH($func_param) $op $timestamp ";
×
470
     else if($this->DB_type == "oci8")
×
471
        return " to_number( to_char( $func_param, 'DD' ) ) $op $timestamp ";
×
472
     else if ( $this->DB_type == "postgres" )
×
473
        return " DATE_PART('day', $func_param) $op $timestamp "; 
×
474
     else if ( $this->DB_type == "mssql" )
×
475
        return " DAY($func_param) $op $timestamp ";        
×
476
  }
477

478
  function baseSQL_HOUR($func_param, $op, $timestamp)
479
  {
480
        if ( $this->DB_class == 1 )
×
481
        return " HOUR($func_param) $op $timestamp ";
×
482
     else if($this->DB_type == "oci8")
×
483
        return " to_number( to_char( $func_param, 'HH' ) ) $op $timestamp ";
×
484
     else if ( $this->DB_type == "postgres" )
×
485
        return " DATE_PART('hour', $func_param) $op $timestamp "; 
×
486
     else if ( $this->DB_type == "mssql" )
×
487
        return " DATEPART(hh, $func_param) $op $timestamp ";
×
488
  }
489

490
  function baseSQL_MINUTE($func_param, $op, $timestamp)
491
  {
492
        if ( $this->DB_class == 1 )
×
493
        return " MINUTE($func_param) $op $timestamp ";
×
494
     else if($this->DB_type == "oci8")
×
495
        return " to_number( to_char( $func_param, 'MI' ) ) $op $timestamp ";
×
496
     else if ( $this->DB_type == "postgres" )
×
497
        return " DATE_PART('minute', $func_param) $op $timestamp "; 
×
498
     else if ( $this->DB_type == "mssql" )
×
499
        return " DATEPART(mi, $func_param) $op $timestamp ";
×
500
  }
501

502
  function baseSQL_SECOND($func_param, $op, $timestamp)
503
  {
504
        if ( $this->DB_class == 1 )
×
505
        return " SECOND($func_param) $op $timestamp ";
×
506
     else if($this->DB_type == "oci8")
×
507
        return " to_number( to_char( $func_param, 'SS' ) ) $op $timestamp ";
×
508
     else if ( $this->DB_type == "postgres" )
×
509
        return " DATE_PART('second', $func_param) $op $timestamp "; 
×
510
     else if ( $this->DB_type == "mssql" )
×
511
        return " DATEPART(ss, $func_param) $op $timestamp ";
×
512
  }
513

514
  function baseSQL_UNIXTIME($func_param, $op, $timestamp)
515
  {
516
        if ( $this->DB_class == 1 ) {
×
517
        return " UNIX_TIMESTAMP($func_param) $op $timestamp ";
×
518
     }
519
     else if($this->DB_type == "oci8")
×
520
        return " to_number( $func_param ) $op $timestamp ";
×
521
     else if ( $this->DB_type == "postgres" )
×
522
     {
523
        if ( ($op == "") && ($timestamp == "") )
×
524
           /* Catches the case where I want to get the UNIXTIME of a constant
525
            *   i.e. DATE_PART('epoch', timestamp) > = DATE_PART('epoch', timestamp '20010124')
526
            *                                            (This one /\ )
527
            */
528
           return " DATE_PART('epoch', $func_param::timestamp) ";
×
529
        else
530
           return " DATE_PART('epoch', $func_param::timestamp) $op $timestamp ";
×
531
     } 
532
     else if ($this->DB_type == "mssql")
×
533
     {
534
           return " DATEDIFF(ss, '1970-1-1 00:00:00', $func_param) $op $timestamp ";
×
535
     }
536
     
537
  }
538

539
  function baseSQL_TIMESEC($func_param, $op, $timestamp)
540
  {
541
        if ( $this->DB_class == 1 )
×
542
        return " TIME_TO_SEC($func_param) $op $timestamp ";
×
543
     else if($this->DB_type == "oci8")
×
544
        return " to_number( $func_param ) $op $timestamp ";
×
545
     else if ( $this->DB_type == "postgres" )
×
546
     {
547
    
548
        if ( ($op == "") && ($timestamp == "") )
×
549
           return " DATE_PART('second', DATE_PART('day', '$func_param') ";
×
550
        else
551
           return " DATE_PART('second', DATE_PART('day', $func_param) ) $op $timestamp ";
×
552
     } 
553
     else if ( $this->DB_type == "mssql" )
×
554
     {
555
        if ( ($op == "") && ($timestamp == "") )
×
556
           return " DATEPART(ss, DATEPART(dd, $func_parm) ";
×
557
        else
558
           return " DATEPART(ss, DATE_PART(dd, $func_param) ) $op $timestamp ";
×
559
 
560
     }
561
     
562
  }
563

564
  function baseGetDBversion()
565
  {
566
     return $this->version;
×
567
  }
568

569
        function getSafeSQLString($str){
570
   $t = str_replace("\\", "\\\\", $str);
×
571
   if ($this->DB_type != "mssql" && $this->DB_type != "oci8" )
×
572
     $t = str_replace("'", "\'", $t);
×
573
   else
574
     $t = str_replace("'", "''", $t);
×
575
   $t = str_replace("\"", "\\\\\"", $t);
×
576

577
   return $t;
×
578
        }
579
}
580

581
class baseRS {
582
        var $row;
583
        var $DB_type;
584
        var $DB_class;
585

586
        function __construct($id, $type) { // PHP 5+ constructor Shim.
587
                // Class/Method agnostic shim code.
588
                $SCname = get_class();
140✔
589
                if ( method_exists($this, $SCname) ) {
140✔
590
                        $SCargs = func_get_args();
140✔
591
                        call_user_func_array(array($this, $SCname), $SCargs);
140✔
592
                }else{
42✔
593
                        // @codeCoverageIgnoreStart
594
                        // Should never execute.
595
                        trigger_error( // Will need to add this message to the TD.
596
                                "Class: $SCname No Legacy Constructor.\n",
597
                                E_USER_ERROR
598
                        );
599
                        // @codeCoverageIgnoreEnd
600
                }
601
        }
98✔
602
        function baseRS($id, $type) {
603
                $this->row = $id;
140✔
604
                $this->DB_type = $type;
140✔
605
                // Are we a Mysql type? Note it in Class structure.
606
                if ( $type == "mysql" || $type == "mysqlt" || $type == "maxsql" ) {
140✔
607
                        $this->DB_class = 1;
80✔
608
                }else{
24✔
609
                        $this->DB_class = 0;
60✔
610
                }
611
        }
98✔
612
        function baseFetchRow(){
613
                GLOBAL $debug_mode;
98✔
614
                $Ret = '';
140✔
615
                if ( !is_object($this->row) ){
140✔
616
                        // Workaround for the problem, that the database may contain NULL
617
                        // whereas "NOT NULL" has been defined, when it was created.
618
                        if ( $debug_mode > 1 ){
×
619
         echo "<BR><BR>" . __FILE__ . ':' . __LINE__ . ": ERROR: \$this->row is not an object (1)<BR><PRE>";
×
620
         debug_print_backtrace();
×
621
         echo "<BR><BR>";
×
622
         echo "var_dump(\$this):<BR>";
×
623
         var_dump($this);
×
624
         echo "<BR><BR>";
×
625
         echo "var_dump(\$this->row):<BR>";
×
626
         var_dump($this->row);
×
627
         echo "</PRE><BR><BR>";
×
628
                        }
629
                }else{
630
                        if ( !$this->row->EOF ){
140✔
631
                                $Ret = $this->row->fields;
120✔
632
                                $this->row->MoveNext();
120✔
633
                        }
36✔
634
                }
635
                return $Ret;
140✔
636
        }
637
  function baseColCount()
638
  {
639
    // Not called anywhere???? -- Kevin
640
     return $this->row->FieldCount();
×
641
  }
642

643
  function baseRecordCount()
644
  {  
645
    GLOBAL $debug_mode;
28✔
646

647
    if (!is_object($this->row))
40✔
648
    {
12✔
649
      if ($debug_mode > 1)
×
650
      {
651
        echo '<BR><BR>';
×
652
        echo __FILE__ . ':' . __LINE__ . ': ERROR: $this->row is not an object (2).';
×
653
        echo '<BR><PRE>';
×
654
        debug_print_backtrace();
×
655
        echo '<BR><BR>var_dump($this):<BR>';
×
656
        var_dump($this);
×
657
        echo '<BR><BR>var_dump($this->row):<BR>';
×
658
        var_dump($this->row);
×
659
        echo '</PRE><BR><BR>';
×
660
      }
661

662
      return 0;
×
663
    }
664
 
665
     // Is This if statement necessary?  -- Kevin
666
     /* MS SQL Server 7, MySQL, Sybase, and Postgres natively support this function */ 
667
        if ( $this->DB_class == 1 ||
40✔
668
          ($this->DB_type == "mssql") || ($this->DB_type == "sybase") || ($this->DB_type == "postgres") || ($this->DB_type == "oci8"))
34✔
669
        return $this->row->RecordCount();
40✔
670

671
     /* Otherwise we need to emulate this functionality */
672
     else 
673
     {
674
          $i = 0;
×
675
          while ( !$this->row->EOF )
×
676
          {
677
             ++$i;
×
678
             $this->row->MoveNext();
×
679
          }
680

681
          return $i;
×
682
     }
683
  }
684

685
  function baseFreeRows()
686
  {
687
    GLOBAL $debug_mode;
28✔
688

689
    /* Workaround for the problem, that the database may contain NULL,
690
     * although "NOT NULL" had been defined when it had been created. 
691
     * In such a case there's nothing to free(). So we can ignore this
692
     * row and don't have anything to do. */
693
    if (!is_object($this->row))
40✔
694
    {
12✔
695
      if ($debug_mode > 1)
×
696
      {
697
        echo '<BR><BR>';
×
698
        echo __FILE__ . ':' . __LINE__ . ': ERROR: $this->row is not an object (3).';
×
699
        echo '<BR><PRE>';
×
700
        debug_print_backtrace();
×
701
        echo '<BR><BR>var_dump($this):<BR>';
×
702
        var_dump($this);
×
703
        echo '<BR><BR>var_dump($this->row):<BR>';
×
704
        var_dump($this->row);
×
705
        echo '</PRE><BR><BR>';
×
706
      }
707
    }
708
    else
709
    {
710
      $this->row->Close();
40✔
711
    }
712
  }
28✔
713
}
714
function NewBASEDBConnection($path, $type){
715
        GLOBAL $debug_mode, $et;
322✔
716
        $version = explode( '.', phpversion() );
460✔
717
        $Wtype = NULL; // Working type.
460✔
718
        $EMPfx = __FUNCTION__ . ': ';
460✔
719
        $AXtype = XSSPrintSafe($type);
460✔
720
        if ( LoadedString($type) ){ // Normalize DB type.
460✔
721
                if ( $debug_mode > 1 ){
460✔
722
                        ErrorMessage($EMPfx . "Req DB type: $AXtype",'black',1);
×
723
                }
724
                $type = strtolower($type);
460✔
725
                if ( preg_match("/^(postgres(s)?|(postgre(s)?|pg)sql)$/", $type) ){
460✔
726
                        $type = 'postgres';
230✔
727
                }elseif ( preg_match("/^oracle/", $type) ){
299✔
728
                        $type = 'oci8';
×
729
                }elseif ( preg_match("/^m(s|icrosoft)/", $type) ){
230✔
730
                        $type = 'mssql';
×
731
                }
732
                $AXtype = XSSPrintSafe($type);
460✔
733
                // Set DB driver type.
734
                $Wtype = $type;
460✔
735
                if ( $type == "mysql" || $type == "mysqlt" || $type == "maxsql" ){
460✔
736
                        // On PHP 5.5+, use mysqli ADODB driver & gracefully deprecate
737
                        // the mysql, mysqlt & maxsql drivers.
738
                        if ( $version[0] > 5 || ( $version[0] == 5 && $version[1] > 4) ){
230✔
739
                                mysqli_report(MYSQLI_REPORT_OFF); // Issue #162 temp fix.
207✔
740
                                $Wtype = "mysqli";
207✔
741
                        }
46✔
742
                }
69✔
743
                if ( $debug_mode > 1 ){
460✔
744
                        ErrorMessage($EMPfx ."FIN DB type: $AXtype",0,1);
×
745
                        ErrorMessage($EMPfx ."DB Driver: $Wtype",0,1);
×
746
                }
747
        }
138✔
748
        if (
749
                !LoadedString($Wtype) ||
460✔
750
                !preg_match("/^(m(y|s|ax)sql|mysqlt|postgres|oci8)$/", $type)
460✔
751
        ){
138✔
752
                $msg = "<b>"._ERRSQLDBTYPE."</b>"."<p>:"._ERRSQLDBTYPEINFO1.
×
753
                "<code>'$AXtype'</code>. "._ERRSQLDBTYPEINFO2;
×
754
                FatalError ($msg);
×
755
        }
756
        $sc = DIRECTORY_SEPARATOR;
460✔
757
        if ( !LoadedString($path) ){ // Setup default for PHP module include.
460✔
758
                $path = 'adodb';
×
759
                if ( $debug_mode > 1 ){
×
760
                        ErrorMessage($EMPfx ."Def DAL path = '$path'",0,1);
×
761
                }
762
        }else{ // We are given a path.
763
                if ( $debug_mode > 1 ){
460✔
764
                        ErrorMessage (
×
765
                                $EMPfx ."Req DAL path = '".XSSPrintSafe($path)."'",'black',1
×
766
                        );
767
                }
768
                if ( $path != 'adodb' ){ // Export ADODB_DIR for use by ADODB.
460✔
769
                        SetConst('ADODB_DIR', $path);
460✔
770
                }
138✔
771
        }
772
        $AXpath = XSSPrintSafe($path);
460✔
773
        if ( $debug_mode > 1 ){
460✔
774
                ErrorMessage($EMPfx ."DAL Load: '".$AXpath."adodb.inc.php'",0,1);
×
775
        }
776
        $GLOBALS['ADODB_DIR'] = ADODB_DIR;
460✔
777
        SetConst('ADODB_ERROR_HANDLER_TYPE',E_USER_NOTICE);
460✔
778
//        Unit Tests had ADODB error logging in their output.
779
//        Solution Make ADODB error logging configurable.
780
//        See: https://github.com/NathanGibbs3/BASE/issues/68
781
//        Commented out this line for now.
782
//        SetConst('ADODB_ERROR_LOG_TYPE',0);
783
        // Load ADODB Error Handler.
784
        $LibFile = 'adodb-errorhandler.inc';
460✔
785
        if ( $path != 'adodb' ){
460✔
786
                $tmp = ChkLib($path, '' , $LibFile);
460✔
787
        }else{
138✔
788
                $tmp = ChkLib('', $path , $LibFile);
×
789
        }
790
        $DEH = false;
460✔
791
        if ( LoadedString($tmp) == true ){
460✔
792
                $DEH = include_once($tmp);
460✔
793
        }
138✔
794
        // Load ADODB Library.
795
        $LibFile = 'adodb.inc';
460✔
796
        $Lib = implode( $sc, array($path, $LibFile) ).'.php';
460✔
797
        if ( $debug_mode > 1 ){
460✔
798
                ErrorMessage(
×
799
                        $EMPfx . _DBALCHECK." '".XSSPrintSafe($Lib)."'",'black',1
×
800
                );
801
        }
802
        if ( $path != 'adodb' ){
460✔
803
                $tmp = ChkLib($path, '' , $LibFile);
460✔
804
        }else{
138✔
805
                $tmp = ChkLib('', $path , $LibFile);
×
806
        }
807
        $DAL = false;
460✔
808
        if ( LoadedString($tmp) == true ){
460✔
809
                $DAL = include_once($tmp);
460✔
810
        }
138✔
811
        if ( $DEH == false || $DAL == false ){
460✔
812
                // @codeCoverageIgnoreStart
813
                $tmp = 'https://';
814
                if ( $version[0] > 5 || ( $version[0] == 5 && $version[1] > 1) ){
815
                        $tmp .= 'github.com/ADOdb/ADOdb';
816
                }else{
817
                        $tmp .= 'sourceforge.net/projects/adodb';
818
                }
819
                // Translation data this msg when we get to _ERRSQLDBALLOAD2 on Issue#11
820
                $msg = 'Check the DB abstraction library variable <code>$DBlib_path</code> in <code>base_conf.php</code>.';
821
                // Translation data the first param when we get to _ERRSQLDBALLOAD1
822
                // on Issue#11
823
                LibIncError ('DB Abstraction', $AXpath, $Lib, $msg, 'ADOdb', $tmp, 1 );
824
                // @codeCoverageIgnoreEnd
825
        }
826
        ADOLoadCode($Wtype);
460✔
827
        if ( is_object($et) && $debug_mode > 2 ){
460✔
828
                // Need to TD this in Issue #11 branch.
829
                $et->Mark('DB Object Created.');
×
830
        }
831
        return new baseCon($type);
460✔
832
}
833
function MssqlKludgeValue( $text ){
834
        $Ret = '';
20✔
835
        for ( $i = 0; $i < strlen($text); $i++ ){
20✔
836
                $Ret .= '[' . substr($text,$i, 1) . ']';
20✔
837
        }
6✔
838
        return $Ret;
20✔
839
}
840
function RepairDBTables($db)
841
{
842
  /* This function was completely commented in original....
843
    I will be searching to see where it was called from if at all */
844
}
845
// @codeCoverageIgnoreStart
846
// Don't Unit Test this.
847
function ClearDataTables( $db ){
848
  $db->baseExecute("DELETE FROM acid_event");
849
  $db->baseExecute("DELETE FROM data");
850
  $db->baseExecute("DELETE FROM event");
851
  $db->baseExecute("DELETE FROM icmphdr");
852
  $db->baseExecute("DELETE FROM iphdr");
853
  $db->baseExecute("DELETE FROM reference");
854
  $db->baseExecute("DELETE FROM sensor");
855
  $db->baseExecute("DELETE FROM sig_class");
856
  $db->baseExecute("DELETE FROM sig_reference");
857
  $db->baseExecute("DELETE FROM signature");
858
  $db->baseExecute("DELETE FROM tcphdr");
859
  $db->baseExecute("DELETE FROM udphdr");
860
}
861
// @codeCoverageIgnoreEnd
862
// Get Max Length of field in table.
863
function GetFieldLength($db,$table,$field){
864
        $Epfx = 'BASE ' . __FUNCTION__ . '() ';
350✔
865
        $Emsg = '';
350✔
866
        $Ret = 0;
350✔
867
        if ( !(is_object($db)) ){
350✔
868
                $Emsg = $Epfx."Invalid DB Object.";
40✔
869
        }else{
12✔
870
                if ( !(LoadedString($table) && $db->baseTableExists($table)) ){
310✔
871
                        $Emsg = $Epfx."Invalid Table.";
120✔
872
                }elseif (
36✔
873
                        !(LoadedString($field) && $db->baseFieldExists($table,$field))
190✔
874
                ){
57✔
875
                        $Emsg = $Epfx."Invalid Field.";
120✔
876
                }
36✔
877
        }
878
        if ( $Emsg != ''){
350✔
879
                trigger_error($Emsg);
280✔
880
        }else{
42✔
881
                $wresult = $db->DB->metacolumns($table);
70✔
882
                $wf = strtoupper($field);
70✔
883
                $tmp = $wresult[$wf];
70✔
884
                $Ret = $tmp->max_length;
70✔
885
        }
886
        return $Ret;
210✔
887
}
888
?>
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc