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

NathanGibbs3 / BASE / 628

pending completion
628

push

travis-ci-com

NathanGibbs3
Merge branch 'documentation' into devel

3240 of 17613 relevant lines covered (18.4%)

17.78 hits per line

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

54.55
/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
// Ensure the conf file has been loaded. Prevent direct access to this file.
22
defined('_BASE_INC') or die('Accessing this file directly is not allowed.');
23

24
class baseCon {
25
        var $DB = NULL; // ADOdb DB dirver specific object when set.
26
        var $DB_type = NULL; // ADOdb DB Driver.
27
        var $DB_name = NULL; // DB.
28
        var $DB_host = NULL; // DB Server.
29
        var $DB_port = NULL; // DB Server Port.
30
        var $DB_username = NULL; // DB User.
31
        var $lastSQL = ''; // Last SQL statement execution request.
32
        var $version = 0; // Default to Schema v0 on Init.
33
        var $sql_trace = NULL; // SQL Trace file handle.
34
        var $DB_class = NULL; // DB Class.
35
        var $Role = NULL; // Object Role Flag.
36
        var $FLOP = NULL; // FLoP Extended DB Flag.
37

38
        function __construct($type) { // PHP 5+ constructor Shim.
39
                // Class/Method agnostic shim code.
40
                $SCname = get_class();
336✔
41
                if ( method_exists($this, $SCname) ) {
336✔
42
                        $SCargs = func_get_args();
336✔
43
                        call_user_func_array(array($this, $SCname), $SCargs);
336✔
44
                }else{
154✔
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
        }
258✔
54
        function baseCon($type) { // PHP 4x constructor.
55
                $this->DB_type = $type;
336✔
56
                // Are we a Mysql type? Note it in Class structure.
57
                if( $type == 'mysql' || $type == 'mysqlt' || $type == 'maxsql' ){
336✔
58
                        $this->DB_class = 1;
261✔
59
                }else{
79✔
60
                        $this->DB_class = 0;
75✔
61
                }
62
        }
258✔
63
        function baseDBConnect(
64
                $method, $database, $host, $port, $username, $password, $force = 0
65
        ){
66
                GLOBAL $archive_dbname, $archive_host, $archive_port, $archive_user,
250✔
67
                $archive_password, $debug_mode, $et;
100✔
68
                $EMPfx = __FUNCTION__ . ': ';
325✔
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.
325✔
72
                        $DBDesc = 'Archive'; // Need to TD this in Issue #11 branch.
×
73
                        $this->Role = $DBDesc; // Set Object Role.
×
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.
325✔
82
                        $this->Role = $DBDesc; // Set Object Role.
325✔
83

84
      if ( $method == DB_CONNECT )
325✔
85
        $this->baseConnect($database, $host, $port, $username, $password);
150✔
86
      else
87
        $this->basePConnect($database, $host, $port, $username, $password);
325✔
88

89
                }
90
                if( $this->baseGetDBversion() > 105 ){ // FLoPS released after Schema v106
325✔
91
                        $this->baseSetFLOP(); // Detect FLoP Extended DB.
325✔
92
                }
150✔
93
                if( $debug_mode > 1 ){ // Need to TD these in Issue #11 branch.
325✔
94
                        ErrorMessage($EMPfx . "DB Connect: $DBDesc.", 'black', 1);
×
95
                }
96
                if( is_object($et) && $debug_mode > 1 ){
325✔
97
                        $et->Mark("DB Connect: $DBDesc.");
×
98
                }
99
        }
250✔
100

101
        function baseConnect ( $database, $host, $port, $username, $password ){
102
                GLOBAL $sql_trace_mode, $sql_trace_file;
4✔
103
                $this->DB = NewADOConnection();
7✔
104
                $this->DB_name = $database;
7✔
105
                $this->DB_host = $host;
7✔
106
                $this->DB_port = $port;
7✔
107
                $this->DB_username = $username;
7✔
108

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

119
     $db = $this->DB->Connect( ( ( $port == "") ? $host : ($host.":".$port) ),
7✔
120
                               $username, $password, $database); 
3✔
121

122
     if ( !$db )
7✔
123
     {
124
        $tmp_host = ( $port == "") ? $host : ($host.":".$port);
×
125
        echo '<P><B>'._ERRSQLCONNECT.' </B>'.
×
126
             $database.'@'. $tmp_host ._ERRSQLCONNECTINFO;
127

128
        echo $this->baseErrorMessage();
×
129
        die();
×
130
     } 
131

132
                $this->baseSetDBversion(); // Set Object DB schema version number.
7✔
133
     if ( $sql_trace_mode > 0 )
7✔
134
     {
135
        fwrite($this->sql_trace, 
×
136
              "\n--------------------------------------------------------------------------------\n");  
137
        fwrite($this->sql_trace, "Connect [".$this->DB_type."] ".$database."@".$host.":".$port." as ".$username."\n");
×
138
        fwrite($this->sql_trace, "[".date ("M d Y H:i:s", time())."] ".$_SERVER["SCRIPT_NAME"]." - db version ".$this->version);
×
139
        fwrite($this->sql_trace, 
×
140
              "\n--------------------------------------------------------------------------------\n\n");
141
        fflush($this->sql_trace);
×
142
     }     
143

144
                return $db;
7✔
145
        }
146

147
        function basePConnect ( $database, $host, $port, $username, $password ){
148
                GLOBAL $sql_trace_mode, $sql_trace_file;
254✔
149
                $this->DB = NewADOConnection();
332✔
150
                $this->DB_name = $database;
332✔
151
                $this->DB_host = $host;
332✔
152
                $this->DB_port = $port;
332✔
153
                $this->DB_username = $username;
332✔
154

155
     if ( $sql_trace_mode > 0 )
332✔
156
     {
150✔
157
        $this->sql_trace = fopen($sql_trace_file,"a");
×
158
        if ( !$this->sql_trace )
×
159
        {
160
           ErrorMessage(_ERRSQLTRACE." '".$sql_trace_file."'");
×
161
           die();
×
162
        }
163
     }
164

165
     $db = $this->DB->PConnect( ( ( $port == "") ? $host : ($host.":".$port) ),
332✔
166
                               $username, $password, $database); 
228✔
167

168
     if ( !$db )
332✔
169
     {
150✔
170
        $tmp_host = ( $port == "") ? $host : ($host.":".$port);
×
171
        echo '<P><B>'._ERRSQLPCONNECT.' </B>'.
×
172
             $database.'@'. $tmp_host ._ERRSQLCONNECTINFO;
173

174
        echo $this->baseErrorMessage();
×
175
        die();
×
176
     } 
177

178
                $this->baseSetDBversion(); // Set Object DB schema version number.
332✔
179
     if ( $sql_trace_mode > 0 )
332✔
180
     {
150✔
181
        fwrite($this->sql_trace, 
×
182
              "\n--------------------------------------------------------------------------------\n");  
183
        fwrite($this->sql_trace, "PConnect [".$this->DB_type."] ".$database."@".$host.":".$port." as ".$username."\n");
×
184
        fwrite($this->sql_trace, "[".date ("M d Y H:i:s", time())."] ".$_SERVER["SCRIPT_NAME"]." - db version ".$this->version);
×
185
        fwrite($this->sql_trace, 
×
186
              "\n--------------------------------------------------------------------------------\n\n");
187
        fflush($this->sql_trace);
×
188
     } 
189

190
                return $db;
332✔
191
        }
192

193
        function baseClose (){
194
                $this->DB->Close();
11✔
195
                $this->DB_host = NULL; // Issue #204
11✔
196
                $this->DB_name = NULL;
11✔
197
                $this->DB_port = NULL;
11✔
198
                $this->DB_username = NULL;
11✔
199
                $this->FLOP = NULL;
11✔
200
                $this->Role = NULL;
11✔
201
                $this->version = 0;
11✔
202
                $this->lastSQL = '';
11✔
203
        }
8✔
204

205
        function baseExecute(
206
                $sql, $start_row = 0, $num_rows = -1, $hard_error = true
207
        ){
208
                GLOBAL $debug_mode, $sql_trace_mode, $db_connect_method,
196✔
209
                        $alert_password, $archive_dbname, $archive_host, $archive_port,
76✔
210
                        $archive_user, $archive_password;
76✔
211
                $EPfx = 'BASE DB ';
253✔
212
                $tdt = $this->DB_type;
253✔
213
                $tdn = $this->DB_name;
253✔
214
                $DSN = $this->DB_host;
253✔
215
                $tdp = $this->DB_port;
253✔
216
                $tdu = $this->DB_username;
253✔
217
                $rs = false; // Default returns failure.
253✔
218
                if (
219
                        $DSN == $archive_host && $tdp == $archive_port
215✔
220
                        && $tdn == $archive_dbname && $tdu == $archive_user
215✔
221
                ){
120✔
222
                        $tdpw = $archive_password;
×
223
                }else{
224
                        $tdpw = $alert_password;
253✔
225
                }
226
                if ( $tdp != '' ){
253✔
227
                        $DSN = "$DSN:$tdp";
253✔
228
                }
120✔
229
                // Begin DB specific SQL fix-up.
230
                // @codeCoverageIgnoreStart
231
                // We have no way of testing Oracle or MsSQL functionality.
232
                if ( $this->DB_type == 'mssql' ){
233
                        $sql = preg_replace("/''/i", "NULL", $sql);
234
                }elseif ( $this->DB_type == 'oci8' ){
235
                        if (!strpos($sql, 'TRIGGER')){
236
                                if (substr($sql, strlen($sql)-1, strlen($sql))==';'){
237
                                        $sql=substr($sql, 0, strlen($sql)-1);
238
                                }
239
                        }
240
                }
241
                // @codeCoverageIgnoreEnd
242
                if( !$this->DB->isConnected() ){
253✔
243
                        // Check for connection before executing query.
244
                        // Try to reconnect of DB connection is down.
245
                        // Found via CI. Might be related to PHP 5.2x not supporting
246
                        // persistant DB connections.
247
                        error_log($EPfx."Disconnected: $tdt $tdn @ $DSN");
×
248
                        error_log($EPfx."Reconnecting: $tdt $tdn @ $DSN");
×
249
                        if ( $db_connect_method == DB_CONNECT ){
×
250
                                $db = $this->DB->Connect( $DSN, $tdu, $tdpw, $tdn);
×
251
                        }else{
252
                                $db = $this->DB->PConnect( $DSN, $tdu, $tdpw, $tdn);
×
253
                        }
254
                        if( !$this->DB->isConnected() ){
×
255
                                FatalError("$EPfx Reconnect Failed");
×
256
                        }else{
257
                                error_log("$EPfx Reconnected");
×
258
                        }
259
                }
260
                $this->lastSQL = $sql;
253✔
261
                $limit_str = '';
253✔
262
                if ( is_int($start_row) & is_int($num_rows) ){ // Issue #169
253✔
263
                        if ( $num_rows != -1 ){ // Do we add a LIMIT / TOP / ROWNUM clause.
238✔
264
                                if ( $this->DB_class == 1 ){
15✔
265
                                        $limit_str = " LIMIT ".$start_row.", ".$num_rows;
11✔
266
                                // @codeCoverageIgnoreStart
267
                                // We have no way of testing Oracle functionality.
268
                                }elseif ( $this->DB_type == "oci8" ){
269
                                        // $limit_str = " LIMIT ".$start_row.", ".$num_rows;
270
                                        // Why, we don't use it.
271
                                // @codeCoverageIgnoreEnd
272
                                }elseif ( $this->DB_type == "postgres" ){
4✔
273
                                        $limit_str = " LIMIT ".$num_rows." OFFSET ".$start_row;
130✔
274
                                }
4✔
275
                        }
8✔
276
                }else{ // Log error & quit.
112✔
277
                        $msg = $EPfx.'Query Halt: Invalid LIMIT.';
15✔
278
                        error_log($msg);
15✔
279
                        return $rs;
15✔
280
                }
281
                $qry = $sql.$limit_str;
238✔
282
                if ( $debug_mode > 1 ){
238✔
283
                        // See: https://github.com/NathanGibbs3/BASE/issues/113
284
                        // Some legecy code has " 1 = 1 " in the query string. Log it here.
285
                        if ( strstr($qry, ' 1 = 1 ') ){
×
286
                                error_log("Issue #113 $qry");
×
287
                                error_log('See: https://github.com/NathanGibbs3/BASE/issues/113');
×
288
                        }
289
                }
290
                // See: https://github.com/NathanGibbs3/BASE/issues/67
291
                // Legacy code assumed $this->DB->Execute() returns a valid recordset.
292
                // It returns false on error. Catch it here.
293
                $result = $this->DB->Execute($qry);
238✔
294
                if( $result ){
210✔
295
                        $rs = new baseRS($result, $this->DB_type);
143✔
296
                }
66✔
297
                // @codeCoverageIgnoreStart
298
                // We have no way of testing this functionality on these DB's
299
                if ( $num_rows != -1 && $limit_str == '' && $rs != false ){
300
                        // DB's which do not support LIMIT (e.g. MS SQL) natively must
301
                        // emulated it by walking the current row from the start of
302
                        // rowset to the desired start row.
303
                        $i = 0;
304
                        while ( ($i < $start_row) && $rs ){
305
                                if ( !$rs->row->EOF ){
306
                                        $rs->row->MoveNext();
307
                                }
308
                                $i++;
309
                        }
310
                }
311
                // @codeCoverageIgnoreEnd
312
     if ( $sql_trace_mode > 0 )
210✔
313
     {
98✔
314
        fputs($this->sql_trace, $sql."\n");
×
315
        fflush($this->sql_trace);
×
316
     }
317
                $tmp = $this->baseErrorMessage();
210✔
318
                if ( (!$rs || $tmp != '') && $hard_error ){
210✔
319
                        $msg = $EPfx.'Query Fail: ';
×
320
                        if ( !$rs ){
×
321
                                $msg .= 'NULL Recordset ';
×
322
                        }
323
                        if ( $tmp !='' ){
×
324
                                $msg .= $tmp;
×
325
                        }else{
326
                                $msg .= 'NO ADOdb Error Msg';
×
327
                        }
328
                        $msg = returnErrorMessage($msg,0,1);
×
329
                        if ( $debug_mode > 0
330
                                // Issue #5 Info Shim
331
                                || (
332
                                        getenv('TRAVIS')
×
333
                                        && version_compare(PHP_VERSION, "5.3.0", "<")
×
334
                                )
335
                        ){
336
                                $msg .= "<p>DB Engine: $tdt DB: $tdn @ $DSN</p>";
×
337
                                $msg .= '<p>SQL QUERY: <code>'.$qry.'</code></p>';
×
338
                        }
339
                        FatalError($msg);
×
340
                }else{
341
                        return $rs;
210✔
342
                }
343
        }
344
        function baseErrorMessage(){
345
                GLOBAL $debug_mode;
368✔
346
                $msg = '';
479✔
347
                $tmp = $this->DB->ErrorMsg();
479✔
348
                if ( $tmp ){
479✔
349
                        $msg = '<b>'._ERRSQLDB.'</b> ';
42✔
350
                        $msg .= $tmp;
42✔
351
                        if ( $debug_mode > 0 ){
42✔
352
                                $msg .= '<p><code>'.$this->lastSQL.'</code></p>';
13✔
353
                        }
6✔
354
                        // @codeCoverageIgnoreStart
355
                        // We have no way of testing MsSQL functionality.
356
                        // MsSQL Error messages that are not issues.
357
                        if ( $this->DB_type == 'mssql' && preg_match(
358
                                "/Changed (databas|languag)e (context|setting) to/", $tmp
359
                        )){
360
                                $msg = '';
361
                        }
362
                        // @codeCoverageIgnoreEnd
363
                }
21✔
364
                return $msg;
479✔
365
        }
366

367
        function baseSetFLOP ( ){ // Detect FLoP Extended DB.
368
                $EMPfx = __FUNCTION__ . ': ';
355✔
369
                $Ret = false;
355✔
370
                if( !is_null($this->DB) && $this->DB->isConnected() ){
355✔
371
                        if(
372
                                $this->baseFieldExists('schema', 'full_payload')
340✔
373
                                && $this->baseFieldExists('schema', 'reference')
340✔
374
                                && $this->baseFieldExists('event', 'reference')
340✔
375
                                && $this->baseFieldExists('data', 'pcap_header')
340✔
376
                                && $this->baseFieldExists('data', 'data_header')
340✔
377
                        ){
158✔
378
                                KML($EMPfx . 'FLoP DB detected', 1);
×
379
                                $Ret = true;
×
380
                        }
381
                        $this->FLOP = $Ret;
340✔
382
                }
158✔
383
                return $Ret;
355✔
384
        }
385

386
        function baseGetFLOP ( ){
387
                $Ret = false;
30✔
388
                if( !is_null($this->FLOP) ){
30✔
389
                        $Ret = $this->FLOP;
15✔
390
                }
8✔
391
                return $Ret;
30✔
392
        }
393

394
        function baseFieldExists ( $table, $field ){
395
                $Ret = false;
455✔
396
                if( !is_null($this->DB) && $this->DB->isConnected() ){
455✔
397
                        if( $this->baseTableExists($table) ){
455✔
398
                                if( in_array($field, $this->DB->metacolumnNames($table)) ){
440✔
399
                                        $Ret = true;
380✔
400
                                }
170✔
401
                        }
202✔
402
                }
210✔
403
                return $Ret;
455✔
404
        }
405

406
        function baseTableExists ( $table ){
407
                $Ret = false;
620✔
408
                if( !is_null($this->DB) && $this->DB->isConnected() ){
620✔
409
                        // @codeCoverageIgnoreStart
410
                        // We have no way of testing Oracle functionality.
411
                        if( $this->DB_type == 'oci8' ){
412
                                $table=strtoupper($table);
413
                        }
414
                        // @codeCoverageIgnoreEnd
415
                        if( in_array($table, $this->DB->MetaTables()) ){
620✔
416
                                $Ret = true;
545✔
417
                        }
258✔
418
                }
298✔
419
                return $Ret;
620✔
420
        }
421

422
        // This function is not used anywhere.
423
        function baseIndexExists ( $table, $index_name ){
424
                $Ret = false;
45✔
425
                if( !is_null($this->DB) && $this->DB->isConnected() ){
45✔
426
                        if( $this->baseTableExists($table) ){
45✔
427
                                $tmp = $this->DB->MetaIndexes($table);
30✔
428
                                if( $tmp != false ){
30✔
429
                                        foreach ($tmp as $key => $value) { // Iterate Index List
30✔
430
                                                if( is_key('columns', $value) ){
30✔
431
                                                        if(
432
                                                                in_array(
30✔
433
                                                                        $index_name,
24✔
434
                                                                        array_values($value['columns'])
30✔
435
                                                                )
16✔
436
                                                        ){
16✔
437
                                                                $Ret = true;
17✔
438
                                                        }
8✔
439
                                                }
16✔
440
                                        }
16✔
441
                                }
16✔
442
                        }
16✔
443
                }
24✔
444
                return $Ret;
45✔
445
        }
446

447
function baseInsertID (){
448
        // Getting the insert ID fails on certain databases (e.g. postgres), but
449
        // we may use it on the once it works on. This function returns -1 if the
450
        // dbtype is postgres, then we can run a kludge query to get the insert
451
        // ID. That query may vary depending upon which table you are looking at
452
        // and what variables you have set at the current point, so it can't be
453
        // here and needs to be in the actual script after calling this function.
454
        // srh (02/01/2001)
455
        if ( $this->DB_class == 1 || $this->DB_type == "mssql" )
×
456
        return $this->DB->Insert_ID();
×
457
     else if ($this->DB_type == "postgres" ||($this->DB_type == "oci8"))
×
458
        return -1;   
×
459

460
        }
461

462
  function baseTimestampFmt($timestamp)
463
  {
464
    // Not used anywhere????? -- Kevin
465
     return $this->DB->DBTimeStamp($timestamp);
×
466
  }
467

468
  function baseSQL_YEAR($func_param, $op, $timestamp)
469
  {
470
        if ( $this->DB_class == 1 || $this->DB_type == "mssql" )
×
471
        return " YEAR($func_param) $op $timestamp ";
×
472
     else if( $this->DB_type == "oci8" )
×
473
        return " to_number( to_char( $func_param, 'RRRR' ) ) $op $timestamp ";
×
474
     else if ( $this->DB_type == "postgres" )
×
475
        return " DATE_PART('year', $func_param) $op $timestamp ";  
×
476
  }
477

478
  function baseSQL_MONTH($func_param, $op, $timestamp)
479
  {
480
        if ( $this->DB_class == 1 || $this->DB_type == "mssql" )
×
481
        return " MONTH($func_param) $op $timestamp ";
×
482
     else if( $this->DB_type == "oci8" )
×
483
        return " to_number( to_char( $func_param, 'MM' ) ) $op $timestamp ";
×
484
     else if ( $this->DB_type == "postgres" )
×
485
        return " DATE_PART('month', $func_param) $op $timestamp "; 
×
486
  }
487

488
  function baseSQL_DAY($func_param, $op, $timestamp)
489
  {
490
        if ( $this->DB_class == 1 )
×
491
        return " DAYOFMONTH($func_param) $op $timestamp ";
×
492
     else if($this->DB_type == "oci8")
×
493
        return " to_number( to_char( $func_param, 'DD' ) ) $op $timestamp ";
×
494
     else if ( $this->DB_type == "postgres" )
×
495
        return " DATE_PART('day', $func_param) $op $timestamp "; 
×
496
     else if ( $this->DB_type == "mssql" )
×
497
        return " DAY($func_param) $op $timestamp ";        
×
498
  }
499

500
  function baseSQL_HOUR($func_param, $op, $timestamp)
501
  {
502
        if ( $this->DB_class == 1 )
×
503
        return " HOUR($func_param) $op $timestamp ";
×
504
     else if($this->DB_type == "oci8")
×
505
        return " to_number( to_char( $func_param, 'HH' ) ) $op $timestamp ";
×
506
     else if ( $this->DB_type == "postgres" )
×
507
        return " DATE_PART('hour', $func_param) $op $timestamp "; 
×
508
     else if ( $this->DB_type == "mssql" )
×
509
        return " DATEPART(hh, $func_param) $op $timestamp ";
×
510
  }
511

512
  function baseSQL_MINUTE($func_param, $op, $timestamp)
513
  {
514
        if ( $this->DB_class == 1 )
×
515
        return " MINUTE($func_param) $op $timestamp ";
×
516
     else if($this->DB_type == "oci8")
×
517
        return " to_number( to_char( $func_param, 'MI' ) ) $op $timestamp ";
×
518
     else if ( $this->DB_type == "postgres" )
×
519
        return " DATE_PART('minute', $func_param) $op $timestamp "; 
×
520
     else if ( $this->DB_type == "mssql" )
×
521
        return " DATEPART(mi, $func_param) $op $timestamp ";
×
522
  }
523

524
  function baseSQL_SECOND($func_param, $op, $timestamp)
525
  {
526
        if ( $this->DB_class == 1 )
×
527
        return " SECOND($func_param) $op $timestamp ";
×
528
     else if($this->DB_type == "oci8")
×
529
        return " to_number( to_char( $func_param, 'SS' ) ) $op $timestamp ";
×
530
     else if ( $this->DB_type == "postgres" )
×
531
        return " DATE_PART('second', $func_param) $op $timestamp "; 
×
532
     else if ( $this->DB_type == "mssql" )
×
533
        return " DATEPART(ss, $func_param) $op $timestamp ";
×
534
  }
535

536
  function baseSQL_UNIXTIME($func_param, $op, $timestamp)
537
  {
538
        if ( $this->DB_class == 1 ) {
×
539
        return " UNIX_TIMESTAMP($func_param) $op $timestamp ";
×
540
     }
541
     else if($this->DB_type == "oci8")
×
542
        return " to_number( $func_param ) $op $timestamp ";
×
543
     else if ( $this->DB_type == "postgres" )
×
544
     {
545
        if ( ($op == "") && ($timestamp == "") )
×
546
           /* Catches the case where I want to get the UNIXTIME of a constant
547
            *   i.e. DATE_PART('epoch', timestamp) > = DATE_PART('epoch', timestamp '20010124')
548
            *                                            (This one /\ )
549
            */
550
           return " DATE_PART('epoch', $func_param::timestamp) ";
×
551
        else
552
           return " DATE_PART('epoch', $func_param::timestamp) $op $timestamp ";
×
553
     } 
554
     else if ($this->DB_type == "mssql")
×
555
     {
556
           return " DATEDIFF(ss, '1970-1-1 00:00:00', $func_param) $op $timestamp ";
×
557
     }
558
     
559
  }
560

561
  function baseSQL_TIMESEC($func_param, $op, $timestamp)
562
  {
563
        if ( $this->DB_class == 1 )
×
564
        return " TIME_TO_SEC($func_param) $op $timestamp ";
×
565
     else if($this->DB_type == "oci8")
×
566
        return " to_number( $func_param ) $op $timestamp ";
×
567
     else if ( $this->DB_type == "postgres" )
×
568
     {
569
    
570
        if ( ($op == "") && ($timestamp == "") )
×
571
           return " DATE_PART('second', DATE_PART('day', '$func_param') ";
×
572
        else
573
           return " DATE_PART('second', DATE_PART('day', $func_param) ) $op $timestamp ";
×
574
     } 
575
     else if ( $this->DB_type == "mssql" )
×
576
     {
577
        if ( ($op == "") && ($timestamp == "") )
×
578
           return " DATEPART(ss, DATEPART(dd, $func_parm) ";
×
579
        else
580
           return " DATEPART(ss, DATE_PART(dd, $func_param) ) $op $timestamp ";
×
581
 
582
     }
583
     
584
  }
585

586
        function baseSetDBversion(){
587
                $EMPfx = __FUNCTION__ . ': ';
369✔
588
                $Ret = 0;
369✔
589
                if( !is_null($this->DB) && $this->DB->isConnected() ){
369✔
590
                        $EMPfx .= $this->Role . ' DB Schema ';
354✔
591
                        if( $this->baseFieldExists('schema', 'vseq') ){
354✔
592
                                // Get the database schema version number.
593
                                $tmp = 'schema';
354✔
594
                                if( $this->DB_class == 1 ){ // Mysql drivers.
354✔
595
                                        $tmp = "`$tmp`";
275✔
596
                                }else{
79✔
597
                                        // @codeCoverageIgnoreStart
598
                                        // We have no way of testing MsSQL functionality.
599
                                        if( $this->DB_type == 'mssql'){ // MsSQL driver.
600
                                                $tmp = "[$tmp]";
601
                                        }
602
                                        // @codeCoverageIgnoreEnd
603
                                }
604
                                $sql = "SELECT vseq FROM $tmp";
354✔
605
                                $rs = $this->DB->Execute($sql);
354✔
606
                                if (
607
                                        $rs != false
140✔
608
                                        && $this->baseErrorMessage() == ''
354✔
609
                                        && $rs->RecordCount() > 0
354✔
610
                                ){ // Error Check
158✔
611
                                        $myrow = $rs->fields;
354✔
612
                                        $Ret = intval($myrow[0]);
354✔
613
                                        $rs->Close();
354✔
614
                                }else{
158✔
615
                                        KML($EMPfx . 'Access error.', 1);
196✔
616
                                }
617
                        }else{
158✔
618
                                KML($EMPfx . 'undefined.', 1);
×
619
                        }
620
                        KML($EMPfx . "set to $Ret", 1);
354✔
621
                        $this->version = $Ret;
354✔
622
                }else{
158✔
623
                        KML($EMPfx . 'DB not connected.', 1);
15✔
624
                }
625
                return $Ret;
369✔
626
        }
627

628
        function baseGetDBversion(){
629
                return $this->version;
340✔
630
        }
631

632
        function getSafeSQLString($str){
633
   $t = str_replace("\\", "\\\\", $str);
×
634
   if ($this->DB_type != "mssql" && $this->DB_type != "oci8" )
×
635
     $t = str_replace("'", "\'", $t);
×
636
   else
637
     $t = str_replace("'", "''", $t);
×
638
   $t = str_replace("\"", "\\\\\"", $t);
×
639

640
   return $t;
×
641
        }
642
}
643

644
class baseRS {
645
        var $row;
646
        var $DB_type;
647
        var $DB_class;
648

649
        function __construct($id, $type) { // PHP 5+ constructor Shim.
650
                // Class/Method agnostic shim code.
651
                $SCname = get_class();
98✔
652
                if ( method_exists($this, $SCname) ) {
98✔
653
                        $SCargs = func_get_args();
98✔
654
                        call_user_func_array(array($this, $SCname), $SCargs);
98✔
655
                }else{
42✔
656
                        // @codeCoverageIgnoreStart
657
                        // Should never execute.
658
                        trigger_error( // Will need to add this message to the TD.
659
                                "Class: $SCname No Legacy Constructor.\n",
660
                                E_USER_ERROR
661
                        );
662
                        // @codeCoverageIgnoreEnd
663
                }
664
        }
74✔
665
        function baseRS($id, $type) {
666
                $this->row = $id;
98✔
667
                $this->DB_type = $type;
98✔
668
                // Are we a Mysql type? Note it in Class structure.
669
                if( $type == 'mysql' || $type == 'mysqlt' || $type == 'maxsql' ){
98✔
670
                        $this->DB_class = 1;
80✔
671
                }else{
24✔
672
                        $this->DB_class = 0;
18✔
673
                }
674
        }
74✔
675
        function baseFetchRow(){
676
                GLOBAL $debug_mode;
74✔
677
                $Ret = '';
98✔
678
                if ( !is_object($this->row) ){
98✔
679
                        // Workaround for the problem, that the database may contain NULL
680
                        // whereas "NOT NULL" has been defined, when it was created.
681
                        if ( $debug_mode > 1 ){
×
682
         echo "<BR><BR>" . __FILE__ . ':' . __LINE__ . ": ERROR: \$this->row is not an object (1)<BR><PRE>";
×
683
         debug_print_backtrace();
×
684
         echo "<BR><BR>";
×
685
         echo "var_dump(\$this):<BR>";
×
686
         var_dump($this);
×
687
         echo "<BR><BR>";
×
688
         echo "var_dump(\$this->row):<BR>";
×
689
         var_dump($this->row);
×
690
         echo "</PRE><BR><BR>";
×
691
                        }
692
                }else{
693
                        if ( !$this->row->EOF ){
98✔
694
                                $Ret = $this->row->fields;
78✔
695
                                $this->row->MoveNext();
78✔
696
                        }
36✔
697
                }
698
                return $Ret;
98✔
699
        }
700
  function baseColCount()
701
  {
702
    // Not called anywhere???? -- Kevin
703
     return $this->row->FieldCount();
×
704
  }
705

706
  function baseRecordCount()
707
  {  
708
    GLOBAL $debug_mode;
20✔
709

710
    if (!is_object($this->row))
26✔
711
    {
12✔
712
      if ($debug_mode > 1)
×
713
      {
714
        echo '<BR><BR>';
×
715
        echo __FILE__ . ':' . __LINE__ . ': ERROR: $this->row is not an object (2).';
×
716
        echo '<BR><PRE>';
×
717
        debug_print_backtrace();
×
718
        echo '<BR><BR>var_dump($this):<BR>';
×
719
        var_dump($this);
×
720
        echo '<BR><BR>var_dump($this->row):<BR>';
×
721
        var_dump($this->row);
×
722
        echo '</PRE><BR><BR>';
×
723
      }
724

725
      return 0;
×
726
    }
727
 
728
     // Is This if statement necessary?  -- Kevin
729
     /* MS SQL Server 7, MySQL, Sybase, and Postgres natively support this function */ 
730
        if ( $this->DB_class == 1 ||
26✔
731
          ($this->DB_type == "mssql") || ($this->DB_type == "sybase") || ($this->DB_type == "postgres") || ($this->DB_type == "oci8"))
20✔
732
        return $this->row->RecordCount();
26✔
733

734
     /* Otherwise we need to emulate this functionality */
735
     else 
736
     {
737
          $i = 0;
×
738
          while ( !$this->row->EOF )
×
739
          {
740
             ++$i;
×
741
             $this->row->MoveNext();
×
742
          }
743

744
          return $i;
×
745
     }
746
  }
747

748
  function baseFreeRows()
749
  {
750
    GLOBAL $debug_mode;
20✔
751

752
    /* Workaround for the problem, that the database may contain NULL,
753
     * although "NOT NULL" had been defined when it had been created. 
754
     * In such a case there's nothing to free(). So we can ignore this
755
     * row and don't have anything to do. */
756
    if (!is_object($this->row))
26✔
757
    {
12✔
758
      if ($debug_mode > 1)
×
759
      {
760
        echo '<BR><BR>';
×
761
        echo __FILE__ . ':' . __LINE__ . ': ERROR: $this->row is not an object (3).';
×
762
        echo '<BR><PRE>';
×
763
        debug_print_backtrace();
×
764
        echo '<BR><BR>var_dump($this):<BR>';
×
765
        var_dump($this);
×
766
        echo '<BR><BR>var_dump($this->row):<BR>';
×
767
        var_dump($this->row);
×
768
        echo '</PRE><BR><BR>';
×
769
      }
770
    }
771
    else
772
    {
773
      $this->row->Close();
26✔
774
    }
775
  }
20✔
776
}
777
function NewBASEDBConnection($path, $type){
778
        GLOBAL $debug_mode, $et;
258✔
779
        $PHPVer = GetPHPSV();
336✔
780
        $Wtype = NULL; // Working type.
336✔
781
        $EMPfx = __FUNCTION__ . ': ';
336✔
782
        $AXtype = XSSPrintSafe($type);
336✔
783
        if ( LoadedString($type) ){ // Normalize DB type.
336✔
784
                if ( $debug_mode > 1 ){
336✔
785
                        ErrorMessage($EMPfx . "Req DB type: $AXtype",'black',1);
×
786
                }
787
                $type = strtolower($type);
336✔
788
                if ( preg_match("/^(postgres(s)?|(postgre(s)?|pg)sql)$/", $type) ){
336✔
789
                        $type = 'postgres';
75✔
790
                }elseif ( preg_match("/^oracle/", $type) ){
336✔
791
                        $type = 'oci8';
×
792
                }elseif ( preg_match("/^m(s|icrosoft)/", $type) ){
261✔
793
                        $type = 'mssql';
×
794
                }
795
                $AXtype = XSSPrintSafe($type);
336✔
796
                // Set DB driver type.
797
                $Wtype = $type;
336✔
798
                if( $type == 'mysql' || $type == 'mysqlt' || $type == 'maxsql' ){
336✔
799
                        // On PHP 5.5+, use mysqli ADODB driver & gracefully deprecate
800
                        // the mysql, mysqlt & maxsql drivers.
801
                        if ( $PHPVer[0] > 5 || ( $PHPVer[0] == 5 && $PHPVer[1] > 4) ){
261✔
802
                                mysqli_report(MYSQLI_REPORT_OFF); // Issue #162 temp fix.
234✔
803
                                $Wtype = "mysqli";
234✔
804
                        }
52✔
805
                }
79✔
806
                if ( $debug_mode > 1 ){
336✔
807
                        ErrorMessage($EMPfx ."FIN DB type: $AXtype",0,1);
×
808
                        ErrorMessage($EMPfx ."DB Driver: $Wtype",0,1);
×
809
                }
810
        }
154✔
811
        if (
812
                !LoadedString($Wtype) ||
336✔
813
                !preg_match("/^(m(y|s|ax)sql|mysqlt|postgres|oci8)$/", $type)
336✔
814
        ){
154✔
815
                $msg = "<b>"._ERRSQLDBTYPE."</b>"."<p>:"._ERRSQLDBTYPEINFO1.
×
816
                "<code>'$AXtype'</code>. "._ERRSQLDBTYPEINFO2;
×
817
                FatalError ($msg);
×
818
        }
819
        $sc = DIRECTORY_SEPARATOR;
336✔
820
        if ( !LoadedString($path) ){ // Setup default for PHP module include.
336✔
821
                $path = 'adodb';
×
822
                if ( $debug_mode > 1 ){
×
823
                        ErrorMessage($EMPfx ."Def DAL path = '$path'",0,1);
×
824
                }
825
        }else{ // We are given a path.
826
                if ( $debug_mode > 1 ){
336✔
827
                        ErrorMessage (
×
828
                                $EMPfx ."Req DAL path = '".XSSPrintSafe($path)."'",'black',1
×
829
                        );
830
                }
831
                if ( $path != 'adodb' ){ // Export ADODB_DIR for use by ADODB.
336✔
832
                        SetConst('ADODB_DIR', $path);
336✔
833
                }
154✔
834
        }
835
        $AXpath = XSSPrintSafe($path);
336✔
836
        if ( $debug_mode > 1 ){
336✔
837
                ErrorMessage($EMPfx ."DAL Load: '".$AXpath."adodb.inc.php'",0,1);
×
838
        }
839
        $GLOBALS['ADODB_DIR'] = ADODB_DIR;
336✔
840
        SetConst('ADODB_ERROR_HANDLER_TYPE',E_USER_NOTICE);
336✔
841
//        Unit Tests had ADODB error logging in their output.
842
//        Solution Make ADODB error logging configurable.
843
//        See: https://github.com/NathanGibbs3/BASE/issues/68
844
//        Commented out this line for now.
845
//        SetConst('ADODB_ERROR_LOG_TYPE',0);
846
        // Load ADODB Error Handler.
847
        $LibFile = 'adodb-errorhandler.inc';
336✔
848
        if ( $path != 'adodb' ){
336✔
849
                $tmp = ChkLib($path, '' , $LibFile);
336✔
850
        }else{
154✔
851
                $tmp = ChkLib('', $path , $LibFile);
×
852
        }
853
        $DEH = false;
336✔
854
        if ( LoadedString($tmp) == true ){
336✔
855
                $DEH = include_once($tmp);
336✔
856
        }
154✔
857
        // Load ADODB Library.
858
        $LibFile = 'adodb.inc';
336✔
859
        $Lib = implode( $sc, array($path, $LibFile) ).'.php';
336✔
860
        if ( $debug_mode > 1 ){
336✔
861
                ErrorMessage(
×
862
                        $EMPfx . _DBALCHECK." '".XSSPrintSafe($Lib)."'",'black',1
×
863
                );
864
        }
865
        if ( $path != 'adodb' ){
336✔
866
                $tmp = ChkLib($path, '' , $LibFile);
336✔
867
        }else{
154✔
868
                $tmp = ChkLib('', $path , $LibFile);
×
869
        }
870
        $DAL = false;
336✔
871
        if ( LoadedString($tmp) == true ){
336✔
872
                $DAL = include_once($tmp);
336✔
873
        }
154✔
874
        if( $DEH == false || $DAL == false ){
336✔
875
                // @codeCoverageIgnoreStart
876
                $tmp = 'https://';
877
                if( $PHPVer[0] > 5 || ($PHPVer[0] == 5 && $PHPVer[1] > 1) ){
878
                        $tmp .= 'github.com/ADOdb/ADOdb';
879
                }else{
880
                        $tmp .= 'sourceforge.net/projects/adodb';
881
                }
882
                // TD this msg when we get to _ERRSQLDBALLOAD2 on Issue#11
883
                $msg = 'Check the DB abstraction library variable <code>$DBlib_path'
884
                . '</code> in <code>base_conf.php</code>.';
885
                // TD the first param when we get to _ERRSQLDBALLOAD1 on Issue#11
886
                LibIncError('DB Abstraction', $AXpath, $Lib, $msg, 'ADOdb', $tmp, 1);
887
                // @codeCoverageIgnoreEnd
888
        }
889
        ADOLoadCode($Wtype);
336✔
890
        if( is_object($et) && $debug_mode > 2 ){
336✔
891
                $et->Mark('DB Object Created.'); // TD this in Issue #11 branch.
×
892
        }
893
        return new baseCon($type);
336✔
894
}
895

896
function MssqlKludgeValue( $text ){
897
        $Ret = '';
15✔
898
        for ( $i = 0; $i < strlen($text); $i++ ){
15✔
899
                $Ret .= '[' . substr($text,$i, 1) . ']';
15✔
900
        }
8✔
901
        return $Ret;
15✔
902
}
903
function RepairDBTables($db)
904
{
905
  /* This function was completely commented in original....
906
    I will be searching to see where it was called from if at all */
907
}
908
// @codeCoverageIgnoreStart
909
// Don't Unit Test this.
910
function ClearDataTables( $db ){
911
  $db->baseExecute("DELETE FROM acid_event");
912
  $db->baseExecute("DELETE FROM data");
913
  $db->baseExecute("DELETE FROM event");
914
  $db->baseExecute("DELETE FROM icmphdr");
915
  $db->baseExecute("DELETE FROM iphdr");
916
  $db->baseExecute("DELETE FROM reference");
917
  $db->baseExecute("DELETE FROM sensor");
918
  $db->baseExecute("DELETE FROM sig_class");
919
  $db->baseExecute("DELETE FROM sig_reference");
920
  $db->baseExecute("DELETE FROM signature");
921
  $db->baseExecute("DELETE FROM tcphdr");
922
  $db->baseExecute("DELETE FROM udphdr");
923
}
924
// @codeCoverageIgnoreEnd
925
// Get Max Length of field in table.
926
function GetFieldLength($db,$table,$field){
927
        $Epfx = 'BASE ' . __FUNCTION__ . '() ';
281✔
928
        $Emsg = '';
281✔
929
        $Ret = 0;
281✔
930
        if ( !(is_object($db)) ){
281✔
931
                $Emsg = $Epfx."Invalid DB Object.";
30✔
932
        }else{
16✔
933
                if ( !(LoadedString($table) && $db->baseTableExists($table)) ){
251✔
934
                        $Emsg = $Epfx."Invalid Table.";
90✔
935
                }elseif (
48✔
936
                        !(LoadedString($field) && $db->baseFieldExists($table,$field))
161✔
937
                ){
70✔
938
                        $Emsg = $Epfx."Invalid Field.";
90✔
939
                }
48✔
940
        }
941
        if ( $Emsg != ''){
281✔
942
                trigger_error($Emsg);
210✔
943
        }else{
56✔
944
                $wresult = $db->DB->metacolumns($table);
71✔
945
                $wf = strtoupper($field);
71✔
946
                $tmp = $wresult[$wf];
71✔
947
                $Ret = $tmp->max_length;
71✔
948
        }
949
        return $Ret;
176✔
950
}
951
?>
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