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

NathanGibbs3 / BASE / 584

pending completion
584

push

travis-ci-com

NathanGibbs3
20230412 Fix CI build breakage.
         Related Issue(s) #158

2 of 2 new or added lines in 1 file covered. (100.0%)

2594 of 16816 relevant lines covered (15.43%)

20.97 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 && ChkCookie ('archive', 1) ){
460✔
72
                        // Connect to the archive tables.
73
                        $DBDesc = 'Archive'; // Need to TD this in Issue #11 branch.
×
74

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

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

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

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

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

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

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

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

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

155
     return $db;
×
156
  }
157

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

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

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

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

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

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

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

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

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

217
     return $db;
460✔
218
  }
219

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

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

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

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

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

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

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

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

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

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

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

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

578
   return $t;
×
579
        }
580
}
581

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

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

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

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

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

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

682
          return $i;
×
683
     }
684
  }
685

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

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