-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathdatabase.php
More file actions
713 lines (617 loc) · 21.4 KB
/
Copy pathdatabase.php
File metadata and controls
713 lines (617 loc) · 21.4 KB
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
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
<?php
/**
* File for database manipulation
*
* @package eFront
*/
//This file cannot be called directly, only included.
if (str_replace(DIRECTORY_SEPARATOR, "/", __FILE__) == $_SERVER['SCRIPT_FILENAME']) {
exit;
}
/**
* Initialization part
*
* This part is used for database initialization.
*/
/** Maximum query size is 500K. Lower it in case of query problems (like 'server has gone away' in large inserts)*/
define("G_MAXIMUMQUERYSIZE", 500000);
/**ADODB database abstraction class*/
require_once('adodb/adodb.inc.php');
require_once('adodb/adodb-exceptions.inc.php');
//require_once('adodb/adodb-memcache.lib.inc.php');
$ADODB_CACHE_DIR = $path."adodb/cache";
$ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
if (!isset($GLOBALS['db']) || !$GLOBALS['db']) {
if(function_exists('mysqli_connect') && G_DBTYPE == 'mysql') {
$GLOBALS['db'] = ADONewConnection('mysqli');
} else {
$GLOBALS['db'] = ADONewConnection(G_DBTYPE);
}
/*
$GLOBALS['db']->cacheSecs = 30;
$GLOBALS['db']->memCache = true;
$GLOBALS['db']->memCacheHost = array('127.0.0.1'); /// $GLOBALS['db']->memCacheHost = $ip1; will work too
$GLOBALS['db']->memCachePort = 11211; /// this is default memCache port
$GLOBALS['db']->memCacheCompress = false; /// Use 'true' to store the item compressed (uses zlib)
*/
$GLOBALS['db'] -> Connect(G_DBHOST, G_DBUSER, G_DBPASSWD, G_DBNAME);
}
//$perf = NewPerfMonitor($GLOBALS['db']);$perf->UI($pollsecs=5);
if (G_DBTYPE == 'mysql') {
$GLOBALS['db'] -> Execute("SET NAMES 'UTF8'");
$GLOBALS['db'] -> charSet = 'utf8';
}
$GLOBALS['db'] -> databaseTime = 0;
$GLOBALS['db'] -> databaseQueries = 0;
//pr($GLOBALS['db']);exit;
/**
* Execute mySQL code
*
* This function is used to execute an arbitrary SQL query
* <br>Example:
* <code>
* $result = eF_execute('SELECT * FROM users WHERE id = 1');
* </code>
*
* @param string $sql the SQL query
* @return mixed The result, formed in a MySQL resource
* @version 1.0
* @deprecated
*/
function eF_executeNew($sql)
{
$thisQuery = microtime(true);
$result = $GLOBALS['db'] -> Execute($sql);
if (!$result && G_DEBUG) {
eF_printMessage(_PROBLEMQUERYINGDATABASE.": '".$sql."'<br> ".$GLOBALS['db'] -> ErrorMsg());
}
logProcess($thisQuery, $sql);
return $result;
}
/**
* Alias for eF_executeNew
* @see eF_executeNew
*/
function eF_executeQuery($sql) {
return eF_executeNew($sql);
}
/**
* Execute code directly -- Changed to an alias of eF_executeNew
*
* @deprecated
* @param $sql
* @return unknown_type
*/
function eF_execute($sql)
{
return eF_executeNew($sql);
}
/**
* Insert data to a database table
*
* This function is used to insert data to a database table. The data is formed as an associative
* array, where the keys are column names and the values are the column data. The function returns
* the auto_increment value of the insertion id, if one exists
* <br>Example:
* <code>
* $fields = array('name' => 'john', 'surname' => 'doe');
* $result = eF_insertTableData('users', $fields);
* </code>
* @param string $table The table to insert data into
* @param array $fields An associative array with the table cell data
* @return mixed The id of the insertion, if an AUTO_INCREMENT id field is set. Otherwise, true in success and false on failure
* @version 1.0
*/
function eF_insertTableData($table, $fields)
{
$thisQuery = microtime(true);
//Prepend prefix to the table
$table = G_DBPREFIX.$table;
if (sizeof($fields) < 1) {
trigger_error(_EMPTYFIELDSLIST, E_USER_WARNING);
return false;
}
isset($fields['id']) ? $customId = $fields['id'] : $customId = 0;
$fields = eF_addSlashes($fields);
array_walk($fields, create_function('&$v, $k', 'if (is_string($v)) $v = "\'".$v."\'"; else if (is_null($v)) $v = "null"; else if ($v === false) $v = 0; else if ($v === true) $v = 1;'));
$sql = "insert into $table (".implode(",", array_keys($fields)).") values (".implode(",", ($fields)).")";
$result = $GLOBALS['db'] -> Execute($sql);
logProcess($thisQuery, $sql);
if ($result) {
if (!$customId) {
$id = $GLOBALS['db'] -> Insert_ID();
} else {
$id = $customId;
}
if ($id == 0) {
return true;
} else {
return $id;
}
} else {
return false;
}
}
/**
* Insert mutiple values
*
* This function is used to insert multiple database values at once.
* The values are specified in an array of arrays.
* <br/>Example:
* <code>
* $data[] = array('users_LOGIN' => 'admin',
* 'timestamp' => '1111111111',
* 'action' => 'lastmove',
* 'comments' => '0',
* 'session_ip' => '7f000001');
* $data[] = array('users_LOGIN' => 'admin',
* 'timestamp' => '2222222222',
* 'action' => 'lastmove1',
* 'comments' => '0',
* 'session_ip' => '7f000001');
* eF_insertTableDataMultiple('logs', $data);
* </code>
*
* @param string $table The table to insert values into
* @param array $fields An array of arrays with fields
* @param boolean $checkGpc Whether to perform a magic_quotes_gpc check
* @return boolean True if everything is ok
* @since 3.5.0
*/
function eF_insertTableDataMultiple($table, $fields, $checkGpc = true) {
$thisQuery = microtime(true);
//Prepend prefix to the table
$table = G_DBPREFIX.$table;
if (sizeof($fields) == 0) {
return false;
}
if (!is_array($fields[0])) { //If we specified a 1-dimensional array, convert it to 2-dimensional
$fields = array($fields);
}
$columns = array();
foreach ($fields[0] as $key => $value) {
if (!preg_match("/^`.*`$/", $key)) {
$columns[] = "`$key`";
}
}
$count = 0;
$sqlArray2 = array();
$sql = "INSERT INTO ".$table." (".implode(",", $columns).") values ";
$currentLength[$table] = 0;
foreach ($fields as $value) {
$value = eF_addSlashes($value, $checkGpc);
//Quote strings and insert "null" where the value is null
//$anon = create_function('&$v, $k', 'if (is_string($v)) $v = "\'".$v."\'"; else if (is_null($v)) $v = "null";');
array_walk($value, 'eF_NullifyRecursive');
$valuesString = implode(",", $value);
$currentLength[$table] += mb_strlen("('".$valuesString."')");
if ($currentLength[$table] > G_MAXIMUMQUERYSIZE) {
$count++;
$currentLength[$table] = 0;
}
$sqlArray2[$count][] = "(".$valuesString.")";
$sqlArray[] = "(".$valuesString.")";
}
$bigSqlQuery = $sql.implode(",", $sqlArray);
foreach ($sqlArray2 as $query) {
$bigSqlQuery2[] = $sql.implode(",", $query);
}
foreach ($bigSqlQuery2 as $value) {
$result = $GLOBALS['db'] -> Execute($value);
}
logProcess($thisQuery, $sql);
if ($result) {
return true;
} else {
return false;
}
}
/**
* Convert empty strings to nulls
* This function is used as a callback to from eF_insertTableDataMultiple
* to convert empty strings to null values, as they should
*
* @param $v array value
* @param $k array key
* @return mixed the nullified value
* @since 3.5
*/
function eF_NullifyRecursive(&$v, $k) {
if (is_string($v)) $v = "'".$v."'"; else if (is_null($v)) $v = "null";else if ($v === false) $v = 0; else if ($v === true) $v = 1;
}
/**
* Update table data
*
* This function is used to update data to a database table. The data is formed as an associative
* array, where the keys are column names and the values are the column data.
* <br>Example:
* <code>
* $fields = array('name' => 'john', 'surname' => 'doe');
* $result = eF_updateTableData('users', $fields, 'login=jdoe');
* </code>
* @param string $table The table to update data to
* @param array $fields An associative array with the table cell data
* @param string $where The where clause of the SQL Update.
* @return mixed The query result, usually true or false.
* @version 1.0
*/
function eF_updateTableData($table, $fields, $where = "")
{
$thisQuery = microtime(true);
//Prepend prefix to the table
$table = G_DBPREFIX.$table;
if (sizeof($fields) < 1) {
trigger_error(_EMPTYFIELDSLIST, E_USER_WARNING);
return false;
}
$fields = eF_addSlashes($fields);
//array_walk($fields, create_function('&$v, $k', 'if (is_string($v)) $v = "\'".$v."\'"; else if (is_null($v)) $v = "null"; $v=$k."=".$v;'));
array_walk($fields, create_function('&$v, $k', 'if (is_string($v)) $v = "\'".$v."\'"; else if (is_null($v)) $v = "null"; else if ($v === false) $v = 0; else if ($v === true) $v = 1; $v=$k."=".$v;'));
$sql = "update $table set ".implode(",", $fields);
if ($where) {
$sql.=" where ".$where;
}
$result = $GLOBALS['db'] -> Execute($sql);
logProcess($thisQuery, $sql);
return $result;
}
/**
* Delete database data
*
* This function is used to delete the database data specified by the where clause.
* <br>Example
* <code>
* $result = eF_deleteTableData('users'); //Equivalent to truncate table "users".
* $result = eF_deleteTableData('users', 'id = 1'); //Delete data from table users, where id = 1.
* </code>
* @param string $table The table to dekete data from
* @param string $where The where clause of the SQL Delete.
* @return mixed The query result, usually true/false.
* @version 1.0
*/
function eF_deleteTableData($table, $where="")
{
//Prepend prefix to the table
$table = G_DBPREFIX.$table;
$thisQuery = microtime(true);
$sql = "DELETE FROM ".$table;
if ($where != "") {
$sql .= " WHERE ".$where;
}
$result = $GLOBALS['db'] -> Execute($sql);
logProcess($thisQuery, $sql);
return $result;
}
/**
* Retrieve database data.
*
* This function is used to perform a SELECT query. Multiple parameters may be used, to
* specify the ordering, length and grouping of the data set. It returns an array of associative arrays,
* where each of these arrays holds the column name and the corresponding value for the result row
* <br>Example:
* <code>
* //Retrieve all data from table users:
* $result = eF_getTableData('users');
* //Retrieve all rows from table users, but only columns "name" and "surname"
* $result = eF_getTableData('users', 'name, surname');
* //Get the "name" and "surname" for user with login "jdoe"
* $result = eF_getTableData('users', 'name, surname', 'login=jdoe');
* //Get the same information, but this time ordered by "name"
* $result = eF_getTableData('users', 'name, surname', 'login=jdoe', 'name');
* //Get the same information, but this time grouped by "surname"
* $result = eF_getTableData('users', 'name, surname', 'login=jdoe', '', 'surname');
* </code>
* @param string $table The table to retrieve data from
* @param string $fields The fields to retrive, comma-separated string, defaults to *.
* @param string $where The where clause of the SQL Select.
* @param string $order The order by clause of the SQL Select.
* @param string $group The group by clause of the SQL Select.
* @param string $limit The limit clause of the SQL Select.
* @return mixed an array holding the query result.
* @version 1.0
*/
function eF_getTableData($table, $fields = "*", $where = "", $order = "", $group = "", $limit = "")
{
$thisQuery = microtime(true);
$sql = prepareGetTableData($table, $fields, $where, $order, $group, $limit);
$result = $GLOBALS['db'] -> GetAll($sql);
logProcess($thisQuery, $sql);
if ($result == false) {
return array();
} else {
return $result;
}
}
function eF_countTableData($table, $fields = "*", $where = "", $order = "", $group = "", $limit = "")
{
$thisQuery = microtime(true);
$sql = prepareGetTableData($table, $fields, $where, $order, $group, $limit);
$result = $GLOBALS['db'] -> GetAll("select count(*) as count from ($sql) count_query");
logProcess($thisQuery, $sql);
if ($result == false) {
return array();
} else {
return $result;
}
}
function prepareGetTableData($table, $fields = "*", $where = "", $order = "", $group = "", $limit = "") {
$tables = explode(",", $table);
foreach ($tables as $key => $value) {
//Prepend prefix to the table
$tables[$key] = G_DBPREFIX.trim($value);
}
$table = implode(",", $tables);
$table = str_ireplace(" join ", " join ".G_DBPREFIX, $table);
$sql = "SELECT ".$fields." FROM ".$table;
if ($where != "") {
$sql .= " WHERE ".$where;
}
if ($group != "") {
$sql .= " GROUP BY ".$group;
}
if ($order != "") {
$sql .= " ORDER BY ".$order;
}
if ($limit != "") {
$sql .= " limit ".$limit;
}
return $sql;
}
/**
* Retrieve table contents Flat
*
* This function, much similar to the eF_getTableData(), retrieves data from the designated
* database table. The main difference lies at the result array format: This time, each
* field in the result set corresponds to an array in the result array.
* <br/>Example:
* <code>
* $result = eF_getTableDataFlat("users", "name, surname");
* print_r($result);
* </code>
* Returns:
* <code>
* Array
* (
* [name] => Array
* (
* [0] => 'john',
* [1] => 'joe',
* [2] => 'mary'
* )
* [surname] => Array
* (
* [0] => 'white',
* [1] => 'black',
* [2] => 'green'
* )
* )
* </code>
*
* @param string $table The database table name.
* @param string $fields Comma separated list of the fields to retrieve, defaults to *.
* @param string $where The where clause of the SQL query.
* @return array The query result table.
* @version 2.0
* @see eF_getTableData()
* Changes from 1.0 to 2.0:
* - Rewritten function in order to accelerate execution. It now uses eF_getTableData()
*/
function eF_getTableDataFlat($table, $fields="*", $where="", $order="", $group="")
{
$thisQuery = microtime(true);
$sql = "SELECT ".$fields." FROM ".$table;
if ($where != "") {
$sql .= " WHERE ".$where;
}
if ($order != "") {
$sql .= " ORDER BY ".$order;
}
if ($group != "") {
$sql .= " GROUP BY ".$group;
}
$result = eF_getTableData($table, $fields, $where, $order, $group);
$temp = array();
for ($i = 0; $i < sizeof($result); $i++) {
foreach ($result[$i] as $key => $value) {
$temp[$key][] = $value;
}
}
logProcess($thisQuery, $sql);
return $temp;
}
/**
* Describes a table field
*
* This function returns the description of a table field, or the whole table if
* a field is not specified.
* <br />Example:
* <code>
* $desc = eF_describeTable("logs", array(0 => "id", "comments"));
* print_r($desc);
* //Prints something like:
* Array
* (
* [0] => Array
* (
* [Field] => id
* [Type] => int(10) unsigned
* [Null] =>
* [Key] => PRI
* [Default] =>
* [Extra] => auto_increment
* )
*
* [1] => Array
* (
* [Field] => comments
* [Type] => varchar(255)
* [Null] =>
* [Key] => PRI
* [Default] => 0
* [Extra] =>
* )
*
* )
* </code>
*
* @param string $table The table to describe
* @param array $fields The fields to describe
* @return array The field description
* @version 1.0
*/
function eF_describeTable($table, $fields = false) {
//Prepend prefix to the table
$table = G_DBPREFIX.$table;
if (!$fields) {
$desc = $GLOBALS['db'] -> GetAll("describe $table");
} else {
$desc = array();
foreach ($fields as $field) {
//$result = eF_executeNew("describe $table $field");
$desc = array_merge($desc, $GLOBALS['db'] -> GetAll("describe $table $field"));
}
}
return $desc;
}
/**
* Get table fields
*
* This function returns the desgnated table's fields
*
* @param string $table The database table
* @return array The table fields
* @version 1.0
*/
function eF_getTableFields($table) {
//Prepend prefix to the table
$table = G_DBPREFIX.$table;
$result = $GLOBALS['db'] -> GetCol("describe $table");
return $result;
}
/**
* Show all tables in the database
*
* @return array The database tables
* @since 3.6.0
*/
function eF_showTables() {
$tables = array();
//Get the database tables
$result = $GLOBALS['db'] -> Execute("show table status");
while (!$result->EOF) {
$tables[] = $result -> fields['Name'];
$result -> MoveNext();
}
return $tables;
}
/**
* Perform an update or insert, depending on whether the entry
* actually exists in the database
*
* @param string $table The table to update data to
* @param array $fields An associative array with the table cell data
* @param string $where The where clause of the SQL Update.
* @return mixed The query result, usually true or false.
* @since 3.6.0
*/
function eF_insertOrupdateTableData($table, $fields, $where)
{
//Prepend prefix to the table
$table = G_DBPREFIX.$table;
$result = eF_getTableData($table, '*', $where);
if (!empty($result)) {
eF_updateTableData($table, $fields, $where);
} else {
eF_insertTableData($table, $fields);
}
}
/**
* Add slashes to parameter
*
* This function is used to conditionally perform an addslashes() to the specfified parameter,
* based on the get_magic_quotes_gpc directive status. If the parameter is an array, then the
* function is applied recursively to all its elements
* If $checkGpc is false, eF_addSlashes calls addslashes without checking get_magic_quotes_gpc
* $checkGpc should be false if Quickform exportValues is used (because exportValues performs a stripslashes operation)
* <br>Example:
* <code>
* $values = eF_addSlashes($form -> exportValues(), false); //slash POST variables from HTML_Quickform
* </code>
*
* @param mixed $param The value to add slashes to, can be either a string or an array
* @param bool $checkGpc If false function does not check get_magic_quotes_gpc directive status
* @return mixed the slashed parameter
* @since 3.5.1
*/
function eF_addSlashes($param, $checkGpc = true) {
if (get_magic_quotes_gpc() && $checkGpc) {
return $param;
} else {
if (is_array($param)) {
//$anon = create_function('&$v, $k', 'is_string($v) ? $v = addslashes($v) : null;');
array_walk_recursive($param, 'eF_addSlashesAux'); //We put the check here because addslashes returns string, thus destroying the real data type
return $param;
} else {
return addslashes($param);
}
}
}
/**
* Auxiliary function used by eF_addSlashes
*
* @param $v
* @param $k
* @return unknown_type
*/
function eF_addSlashesAux(&$v, $k) {
is_string($v) ? $v = addslashes($v) : null;
}
function logProcess($thisQuery, $sql) {
if ($GLOBALS['db'] -> debug == true) {
echo '<span style = "color:red">Time spent on this query: '.(microtime(true) - $thisQuery).'</span>';
}
$GLOBALS['db'] -> databaseTime = $GLOBALS['db'] -> databaseTime + microtime(true) - $thisQuery;
$GLOBALS['db'] -> databaseQueries++;
if (G_DEBUG) {
$GLOBALS['db'] -> queries[$GLOBALS['db'] -> databaseQueries]['times'] = microtime(true) - $thisQuery;
$GLOBALS['db'] -> queries[$GLOBALS['db'] -> databaseQueries]['sql'] = $sql;
foreach (debug_backtrace(false) as $value) {
if (isset($value['file'])) {
$backtrace[] = basename(dirname($value['file'])).'/'.basename($value['file']).':'.$value['line'];
}
}
$GLOBALS['db'] -> queries[$GLOBALS['db'] -> databaseQueries]['trace'] = print_r($backtrace, true);
}
}
class EfrontDB
{
public $databaseTime = 0;
public $databaseQueries = 0;
public $queries = array();
public function __construct($db) {
$this -> db = $db;
}
public function cacheGetTableData($table, $fields = "*", $where = "", $order = "", $group = "") {
$this -> initializeStats();
$sql = $this -> createSQL($table, $fields = "*", $where = "", $order = "", $group = "");
$result = $this -> db -> GetAll($sql);
$result OR $result = array();
$this -> calculateStats();
return $result;
}
private function createSQL($table, $fields = "*", $where = "", $order = "", $group = "") {
$sql = "SELECT ".$fields." FROM ".$table;
!$where OR $sql .= " WHERE ".$where;
!$order OR $sql .= " ORDER BY ".$order;
!$group OR $sql .= " GROUP BY ".$group;
return $sql;
}
private function initializeStats() {
$this -> queryTime = microtime(true);
}
private function calculateStats() {
$this -> db -> databaseTime = $this -> db -> databaseTime + microtime(true) - $this -> queryTime;
$this -> db -> databaseQueries++;
$this -> db -> queries[$sql][] = microtime(true) - $this -> queryTime;
}
}