/
database_api.php
575 lines (473 loc) · 15.1 KB
/
database_api.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
<?php
# Mantis - a php based bugtracking system
# Copyright (C) 2000 - 2002 Kenzaburo Ito - kenito@300baud.org
# Copyright (C) 2002 - 2007 Mantis Team - mantisbt-dev@lists.sourceforge.net
# This program is distributed under the terms and conditions of the GPL
# See the README and LICENSE files for details
# --------------------------------------------------------
# $Id: database_api.php,v 1.56 2007-05-22 07:13:42 vboctor Exp $
# --------------------------------------------------------
### Database ###
# This is the general interface for all database calls.
# Use this as a starting point to port to other databases
$t_core_dir = dirname( __FILE__ ).DIRECTORY_SEPARATOR;
# Do not explicitly include $t_core_dir to allow using system ADODB by including
# it in include path and removing the one distributed with Mantis (see #7907).
require_once( 'adodb/adodb.inc.php' );
# An array in which all executed queries are stored. This is used for profiling
$g_queries_array = array();
# Stores whether a database connection was succesfully opened.
$g_db_connected = false;
# set adodb fetch mode
# most drivers don't implement this, but for mysql there is a small internal php performance gain for using it
if( $g_db_type == 'mysql' ) {
$ADODB_FETCH_MODE = ADODB_FETCH_BOTH;
}
# --------------------
# Make a connection to the database
function db_connect( $p_dsn, $p_hostname = null, $p_username = null, $p_password = null, $p_database_name = null ) {
global $g_db_connected, $g_db;
if( $p_dsn === false ) {
$g_db = ADONewConnection( config_get_global( 'db_type' ) );
$t_result = $g_db->Connect($p_hostname, $p_username, $p_password, $p_database_name );
} else {
$g_db = ADONewConnection( $p_dsn );
$t_result = $g_db->IsConnected();
}
if ( !$t_result ) {
db_error();
trigger_error( ERROR_DB_CONNECT_FAILED, ERROR );
return false;
}
$g_db_connected = true;
return true;
}
# --------------------
# Make a persistent connection to the database
function db_pconnect( $p_dsn, $p_hostname = null, $p_username = null, $p_password = null, $p_database_name = null ) {
global $g_db_connected, $g_db;
if( $p_dsn === false ) {
$g_db = ADONewConnection( config_get_global( 'db_type' ) );
$t_result = $g_db->PConnect($p_hostname, $p_username, $p_password, $p_database_name );
} else {
$g_db = ADONewConnection( $p_dsn );
$t_result = $g_db->IsConnected();
}
if ( !$t_result ) {
db_error();
trigger_error( ERROR_DB_CONNECT_FAILED, ERROR );
return false;
}
$g_db_connected = true;
return true;
}
# --------------------
# Returns whether a connection to the database exists
function db_is_connected() {
global $g_db_connected;
return $g_db_connected;
}
# --------------------
# Check is the database is PostgreSQL
function db_is_pgsql() {
$t_db_type = config_get( 'db_type' );
switch( $t_db_type ) {
case 'postgres':
case 'postgres64':
case 'postgres7':
case 'pgsql':
return true;
}
return false;
}
# --------------------
# timer analysis
function microtime_float() {
list( $usec, $sec ) = explode( " ", microtime() );
return ( (float)$usec + (float)$sec );
}
# --------------------
# execute query, requires connection to be opened
# If $p_error_on_failure is true (default) an error will be triggered
# if there is a problem executing the query.
function db_query( $p_query, $p_limit = -1, $p_offset = -1 ) {
global $g_queries_array, $g_db;
$t_start = microtime_float();
if ( ( $p_limit != -1 ) || ( $p_offset != -1 ) ) {
$t_result = $g_db->SelectLimit( $p_query, $p_limit, $p_offset );
} else {
$t_result = $g_db->Execute( $p_query );
}
$t_elapsed = number_format( microtime_float() - $t_start, 4);
array_push ( $g_queries_array, array( $p_query, $t_elapsed ) );
if ( !$t_result ) {
db_error($p_query);
trigger_error( ERROR_DB_QUERY_FAILED, ERROR );
return false;
} else {
return $t_result;
}
}
# --------------------
function db_num_rows( $p_result ) {
global $g_db;
return $p_result->RecordCount( );
}
# --------------------
function db_affected_rows() {
global $g_db;
return $g_db->Affected_Rows( );
}
# --------------------
function db_fetch_array( & $p_result ) {
global $g_db, $g_db_type;
if ( $p_result->EOF ) {
return false;
}
# mysql obeys FETCH_MODE_BOTH, hence ->fields works, other drivers do not support this
if( $g_db_type == 'mysql' ) {
$t_array = $p_result->fields;
$p_result->MoveNext();
return $t_array;
} else {
$test = $p_result->GetRowAssoc(false);
$p_result->MoveNext();
return $test;
}
}
# --------------------
function db_result( $p_result, $p_index1=0, $p_index2=0 ) {
global $g_db;
if ( $p_result && ( db_num_rows( $p_result ) > 0 ) ) {
$p_result->Move($p_index1);
$t_result = $p_result->GetArray();
return $t_result[0][$p_index2];
} else {
return false;
}
}
# --------------------
# return the last inserted id
function db_insert_id($p_table = null) {
global $g_db;
if ( isset($p_table) && db_is_pgsql() ) {
$query = "SELECT currval('".$p_table."_id_seq')";
$result = db_query( $query );
return db_result($result);
}
return $g_db->Insert_ID( );
}
# --------------------
function db_table_exists( $p_table_name ) {
global $g_db;
return in_array ( $p_table_name , $g_db->MetaTables( "TABLE" ) ) ;
}
# --------------------
function db_field_exists( $p_field_name, $p_table_name ) {
global $g_db;
return in_array ( $p_field_name , $g_db->MetaColumnNames( $p_table_name ) ) ;
}
# --------------------
function db_field_names( $p_table_name ) {
global $g_db;
return $g_db->MetaColumnNames( $p_table_name );
}
# --------------------
# Check if there is an index defined on the specified table/field and with
# the specified type.
#
# @@@ thraxisp - this only works with MySQL
#
# $p_table: Name of table to check
# $p_field: Name of field to check
# $p_key: key type to check for (eg: PRI, MUL, ...etc)
function db_key_exists_on_field( $p_table, $p_field, $p_key ) {
$c_table = db_prepare_string( $p_table );
$c_field = db_prepare_string( $p_field );
$c_key = db_prepare_string( $p_key );
$query = "DESCRIBE $c_table";
$result = db_query( $query );
$count = db_num_rows( $result );
for ( $i=0 ; $i < $count ; $i++ ) {
$row = db_fetch_array( $result );
if ( $row['Field'] == $c_field ) {
return ( $row['Key'] == $c_key );
}
}
return false;
}
# --------------------
function db_error_num() {
global $g_db;
return $g_db->ErrorNo();
}
# --------------------
function db_error_msg() {
global $g_db;
return $g_db->ErrorMsg();
}
# --------------------
# display both the error num and error msg
function db_error( $p_query=null ) {
if ( null !== $p_query ) {
error_parameters( db_error_num(), db_error_msg(), $p_query );
} else {
error_parameters( db_error_num(), db_error_msg() );
}
}
# --------------------
# close the connection.
# Not really necessary most of the time since a connection is
# automatically closed when a page finishes loading.
function db_close() {
global $g_db;
$t_result = $g_db->Close();
}
# --------------------
# prepare a string before DB insertion
# @@@ should default be return addslashes( $p_string ); or generate an error
# @@@ Consider using ADODB escaping for all databases.
function db_prepare_string( $p_string ) {
global $g_db;
$t_db_type = config_get( 'db_type' );
switch( $t_db_type ) {
case 'mssql':
case 'odbc_mssql':
case 'ado_mssql':
if( ini_get( 'magic_quotes_sybase' ) ) {
return addslashes( $p_string );
} else {
ini_set( 'magic_quotes_sybase', true );
$t_string = addslashes( $p_string );
ini_set( 'magic_quotes_sybase', false );
return $t_string;
}
case 'mysql':
# mysql_escape_string was deprecated in v4.3.0
if ( php_version_at_least( '4.3.0' ) ) {
return mysql_real_escape_string( $p_string );
} else {
return mysql_escape_string( $p_string );
}
# For some reason mysqli_escape_string( $p_string ) always returns an empty
# string. This is happening with PHP v5.0.2.
case 'mysqli':
$t_escaped = $g_db->qstr( $p_string, false );
return substr( $t_escaped, 1, strlen( $t_escaped ) - 2 );
case 'postgres':
case 'postgres64':
case 'postgres7':
case 'pgsql':
return pg_escape_string( $p_string );
default:
error_parameters( 'db_type', $t_db_type );
trigger_error( ERROR_CONFIG_OPT_INVALID, ERROR );
}
}
# --------------------
# prepare a time string in "[h]h:mm" to an integer (minutes) before DB insertion
function db_prepare_time( $p_hhmm ) {
if ( is_blank( $p_hhmm ) ) {
return 0;
}
$t_a = explode( ':', $p_hhmm );
$t_min = 0;
// time can be composed of max 3 parts (hh:mm:ss)
if ( count( $t_a ) > 3 ) {
error_parameters( 'p_hhmm', $p_hhmm );
trigger_error( ERROR_CONFIG_OPT_INVALID, ERROR );
}
for ( $i = 0; $i < count( $t_a ); $i++ ) {
// all time parts should be integers and non-negative.
if ( !is_numeric( $t_a[$i] ) || ( (integer)$t_a[$i] < 0) ) {
error_parameters( 'p_hhmm', $p_hhmm );
trigger_error( ERROR_CONFIG_OPT_INVALID, ERROR );
}
// minutes and seconds are not allowed to exceed 59.
if ( ( $i > 0 ) && ( $t_a[$i] > 59 ) ) {
error_parameters( 'p_hhmm', $p_hhmm );
trigger_error( ERROR_CONFIG_OPT_INVALID, ERROR );
}
}
switch ( count( $t_a ) )
{
case 1:
$t_min = (integer)$t_a[0];
break;
case 2:
$t_min = (integer)$t_a[0] * 60 + (integer)$t_a[1];
break;
case 3: // if seconds included, approxiate it to minutes
$t_min = (integer)$t_a[0] * 60 + (integer)$t_a[1];
if ( (integer)$t_a[2] >= 30 ) {
$t_min++;
}
break;
}
return (int)$t_min;
}
# --------------------
# prepare a date string in "yyyy-mm-dd"
function db_prepare_date( $p_yyyymmdd ) {
if ( is_blank( $p_yyyymmdd ) ) {
return "";
}
$t_a = explode( '-', $p_yyyymmdd );
// date can be composed of max 3 parts (yyyy-mm-dd)
if ( count( $t_a ) > 3 ) {
error_parameters( 'p_yyyymmdd', $p_yyyymmdd );
trigger_error( ERROR_CONFIG_OPT_INVALID, ERROR );
}
// Check years
if ( !is_numeric( $t_a[0] ) || ( (integer)$t_a[0] < 1900 || (integer)$t_a[0] > 2100) ) {
error_parameters( 'p_yyyymmdd', $p_yyyymmdd );
trigger_error( ERROR_CONFIG_OPT_INVALID, ERROR );
}
// Check months
if ( !is_numeric( $t_a[1] ) || ( (integer)$t_a[1] < 1 || (integer)$t_a[1] > 12) ) {
error_parameters( 'p_yyyymmdd', $p_yyyymmdd );
trigger_error( ERROR_CONFIG_OPT_INVALID, ERROR );
}
// Check days
if ( !is_numeric( $t_a[2] ) || ( (integer)$t_a[2] < 1 || (integer)$t_a[2] > 31) ) {
error_parameters( 'p_yyyymmdd', $p_yyyymmdd );
trigger_error( ERROR_CONFIG_OPT_INVALID, ERROR );
}
// Format
$t_formatted = $t_a[0] . '-';
$t_formatted .= ($t_a[1] < 10 ? "0" . $t_a[1] : $t_a[1]) . '-';
$t_formatted .= ($t_a[2] < 10 ? "0" . $t_a[2] : $t_a[2]);
return $t_formatted;
}
# --------------------
# prepare an integer before DB insertion
function db_prepare_int( $p_int ) {
return (int)$p_int;
}
# --------------------
# prepare a double before DB insertion
function db_prepare_double( $p_double ) {
return (double)$p_double;
}
# --------------------
# prepare a boolean before DB insertion
function db_prepare_bool( $p_bool ) {
return (int)(bool)$p_bool;
}
# --------------------
# return current timestamp for DB
function db_now() {
global $g_db;
return $g_db->DBTimeStamp(time());
}
# --------------------
# generate a unixtimestamp of a date
# > SELECT UNIX_TIMESTAMP();
# -> 882226357
# > SELECT UNIX_TIMESTAMP('1997-10-04 22:23:00');
# -> 875996580
function db_timestamp( $p_date=null ) {
global $g_db;
if ( null !== $p_date ) {
$p_timestamp = $g_db->UnixTimeStamp($p_date);
} else {
$p_timestamp = time();
}
return $g_db->DBTimeStamp($p_timestamp) ;
}
function db_unixtimestamp( $p_date=null ) {
global $g_db;
if ( null !== $p_date ) {
$p_timestamp = $g_db->UnixTimeStamp($p_date);
} else {
$p_timestamp = time();
}
return $p_timestamp ;
}
# --------------------
# convert minutes to a time format [h]h:mm
function db_minutes_to_hhmm( $p_min = 0 ) {
return sprintf( '%02d:%02d', $p_min / 60, $p_min % 60 );
}
# --------------------
# A helper function that generates a case-sensitive or case-insensitive like phrase based on the current db type.
# $p_field_name - The name of the field to filter on.
# $p_value - The value that includes the pattern (can include % for wild cards) - not including the quotations.
# $p_case_sensitive - true: case sensitive, false: case insensitive
# returns (field LIKE 'value') OR (field ILIKE 'value')
# The field name and value are assumed to be safe to insert in a query (i.e. already cleaned).
function db_helper_like( $p_field_name, $p_value, $p_case_sensitive = false ) {
$t_like_keyword = 'LIKE';
if ( $p_case_sensitive === false ) {
if ( db_is_pgsql() ) {
$t_like_keyword = 'ILIKE';
}
}
return "($p_field_name $t_like_keyword '$p_value')";
}
# --------------------
# helper function to compare two dates against a certain number of days
# limitstring can be '> 1' '<= 2 ' etc
# @@@ Check if there is a way to do that using ADODB rather than implementing it here.
function db_helper_compare_days($p_date1, $p_date2, $p_limitstring) {
$t_db_type = config_get( 'db_type' );
switch( $t_db_type ) {
case 'mssql':
case 'odbc_mssql':
case 'ado_mssql':
return "(DATEDIFF(day, $p_date2, $p_date1) ". $p_limitstring . ")";
case 'mysql':
case 'mysqli':
return "(TO_DAYS($p_date1) - TO_DAYS($p_date2) ". $p_limitstring . ")";
case 'postgres':
case 'postgres64':
case 'postgres7':
case 'pgsql':
return "(date_mi($p_date1::date, $p_date2::date) ". $p_limitstring . ")";
case 'oci8':
return "(($p_date1 - $p_date2)" . $p_limitstring . ")";
default:
error_parameters( 'db_type', $t_db_type );
trigger_error( ERROR_CONFIG_OPT_INVALID, ERROR );
}
}
# --------------------
# count queries
function db_count_queries () {
global $g_queries_array;
return count( $g_queries_array );
}
# --------------------
# count unique queries
function db_count_unique_queries () {
global $g_queries_array;
$t_unique_queries = 0;
$t_shown_queries = array();
foreach ($g_queries_array as $t_val_array) {
if ( ! in_array( $t_val_array[0], $t_shown_queries ) ) {
$t_unique_queries++;
array_push( $t_shown_queries, $t_val_array[0] );
}
}
return $t_unique_queries;
}
# --------------------
# get total time for queries
function db_time_queries () {
global $g_queries_array;
$t_count = count( $g_queries_array );
$t_total = 0;
for ( $i = 0; $i < $t_count; $i++ ) {
$t_total += $g_queries_array[$i][1];
}
return $t_total;
}
# --------------------
if ( !isset( $g_skip_open_db ) ) {
if ( OFF == $g_use_persistent_connections ) {
db_connect( config_get_global( 'dsn', false ), $g_hostname, $g_db_username, $g_db_password, $g_database_name );
} else {
db_pconnect( config_get_global( 'dsn', false ), $g_hostname, $g_db_username, $g_db_password, $g_database_name );
}
}
?>