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

NathanGibbs3 / BASE / 624

pending completion
624

push

travis-ci-com

NathanGibbs3
Merge branch 'devel'

562 of 562 new or added lines in 28 files covered. (100.0%)

3145 of 17504 relevant lines covered (17.97%)

23.22 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
// 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;
26
        var $DB_type;
27
        var $DB_name;
28
        var $DB_host;
29
        var $DB_port;
30
        var $DB_username;
31
        var $lastSQL;
32
        var $version;
33
        var $sql_trace;
34
        var $DB_class;
35

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

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

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

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

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

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

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

122
        echo $this->baseErrorMessage();
×
123
        die();
×
124
     } 
125

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

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

152
     return $db;
×
153
  }
154

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

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

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

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

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

184
        echo $this->baseErrorMessage();
×
185
        die();
×
186
     } 
187

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

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

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

214
     return $db;
460✔
215
  }
216

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