/
expDatabase.php
2340 lines (2132 loc) · 76.7 KB
/
expDatabase.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
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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
##################################################
#
# Copyright (c) 2004-2023 OIC Group, Inc.
#
# This file is part of Exponent
#
# Exponent is free software; you can redistribute
# it and/or modify it under the terms of the GNU
# General Public License as published by the Free
# Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# GPL: http://www.gnu.org/licenses/gpl.txt
#
##################################################
/**
* This is the expDatabase subsystem
* Handles all database abstraction in Exponent.
*
* @package Subsystems
* @subpackage Subsystems
*/
class expDatabase {
/**
* Connect to the Exponent database
*
* This function attempts to connect to the exponent database,
* and then returns the database object to the caller.
*
* @param string $username the database username
* @param string $password the database password
* @param string $hostname the url of the database server
* @param string $database the name of the database
* @param string $dbclass
* @param bool $new
* @param null $log
*
* @return _database|database|stdClass
*/
public static function connect($username,$password,$hostname,$database,$dbclass = '',$new=false,$log=null) {
if (!defined('DB_ENGINE')) {
$backends = array_keys(self::backends(1));
if (count($backends)) {
define('DB_ENGINE',$backends[0]);
} else {
define('DB_ENGINE','NOTSUPPORTED');
}
}
(include_once(BASE.'framework/core/subsystems/database/'.DB_ENGINE.'.php')) or exit(gt('None of the installed Exponent Database Backends will work with this server\'s version of PHP.'));
if ($dbclass == '' || $dbclass == null) $dbclass = DB_ENGINE;
(include_once(BASE.'framework/core/subsystems/database/'.$dbclass.'.php')) or exit(gt('The specified database backend').' ('.$dbclass.') '.gt('is not supported by Exponent'));
$dbclass .= '_database';
if ($username !== 'not_configured') {
$newdb = new $dbclass($username,$password,$hostname,$database,$new,$log);
if (!$newdb->tableExists('user')) {
$newdb->havedb = false;
}
} else {
$newdb = new stdClass();
$newdb->havedb = false;
}
return $newdb;
}
/**
* List all available database backends
*
* This function looks for available database engines,
* and then returns an array to the caller.
*
* @param int $valid_only
* @return array An associative array of engine identifiers.
* The internal engine name is the key, and the external
* descriptive name is the value.
*/
public static function backends($valid_only = 1) {
$options = array();
$dh = opendir(BASE.'framework/core/subsystems/database');
while (($file = readdir($dh)) !== false) {
if (is_file(BASE.'framework/core/subsystems/database/'.$file) && is_readable(BASE.'framework/core/subsystems/database/'.$file) && substr($file,-9,9) === '.info.php') {
$info = include(BASE.'framework/core/subsystems/database/'.$file);
if ($info['is_valid'] == 1 || !$valid_only) {
$options[substr($file,0,-9)] = $info['name'];
}
}
}
return $options;
}
public static function fix_table_names() {
global $db;
// fix table names
$tablenames = array (
'content_expcats'=>'content_expCats',
'content_expcomments'=>'content_expComments',
'content_expdefinablefields'=>'content_expDefinableFields',
'content_expdefinablefields_value'=>'content_expDefinableFields_value',
'content_expfiles'=>'content_expFiles',
'content_expratings'=>'content_expRatings',
'content_expsimplenote'=>'content_expSimpleNote',
'content_exptags'=>'content_expTags',
'expcats'=>'expCats',
'expcomments'=>'expComments',
'expdefinablefields'=>'expDefinableFields',
'expealerts'=>'expeAlerts',
'expealerts_temp'=>'expeAlerts_temp',
'expfiles'=>'expFiles',
'expratings'=>'expRatings',
'exprss'=>'expRss',
'expsimplenote'=>'expSimpleNote',
'exptags'=>'expTags',
'bing_product_types_storecategories'=>'bing_product_types_storeCategories',
'google_product_types_storecategories'=>'google_product_types_storeCategories',
'nextag_product_types_storecategories'=>'nextag_product_types_storeCategories',
'pricegrabber_product_types_storecategories'=>'pricegrabber_product_types_storeCategories',
'shopping_product_types_storecategories'=>'shopping_product_types_storeCategories',
'shopzilla_product_types_storecategories'=>'shopzilla_product_types_storeCategories',
'crosssellitem_product'=>'crosssellItem_product',
'product_storecategories'=>'product_storeCategories',
'storecategories'=>'storeCategories',
);
$renamed = array();
foreach ($tablenames as $oldtablename=>$newtablename) {
if (!$db->tableExists($newtablename)) {
$db->sql('RENAME TABLE ' . $db->tableStmt($oldtablename) . ' TO ' . $db->tableStmt($newtablename));
$renamed[] = $newtablename;
}
}
return $renamed;
}
public static function install_dbtables($aggressive=false, $workflow=ENABLE_WORKFLOW) {
global $db;
if ($db->havedb == true)
expSession::clearAllUsersSessionCache();
$tables = array();
// first the core definitions
$coredefs = BASE.'framework/core/definitions';
if (is_readable($coredefs)) {
$dh = opendir($coredefs);
while (($file = readdir($dh)) !== false) {
if (is_readable("$coredefs/$file") && is_file("$coredefs/$file") && substr($file,-4,4) === ".php" && substr($file,-9,9) !== ".info.php") {
$tablename = substr($file,0,-4);
$dd = include("$coredefs/$file");
$info = null;
if (is_readable("$coredefs/$tablename.info.php")) $info = include("$coredefs/$tablename.info.php");
if (!$db->tableExists($tablename)) {
foreach ($db->createTable($tablename, $dd, $info) as $key=>$status) {
$tables[$key] = $status;
}
} else {
foreach ($db->alterTable($tablename, $dd, $info, $aggressive) as $key=>$status) {
// if (isset($tables[$key])) echo "$tablename, $key<br>"; //FIXME we shouldn't echo this, already installed?
if ($status == TABLE_ALTER_FAILED){
$tables[$key] = $status;
} else {
$tables[$key] = ($status == TABLE_ALTER_NOT_NEEDED ? DATABASE_TABLE_EXISTED : DATABASE_TABLE_ALTERED);
}
}
}
}
}
}
// then search for module definitions
$moddefs = array(
BASE."framework/modules",
BASE.'themes/'.DISPLAY_THEME.'/modules',
);
$models = expModules::initializeModels();
foreach ($moddefs as $moddef) {
if (is_readable($moddef)) {
$dh = opendir($moddef);
while (($file = readdir($dh)) !== false) {
if (is_dir($moddef.'/'.$file) && ($file !== '..' && $file !== '.')) {
$dirpath = $moddef.'/'.$file.'/definitions';
if (file_exists($dirpath)) {
$def_dir = opendir($dirpath);
while (($def = readdir($def_dir)) !== false) {
// eDebug("$dirpath/$def");
if (is_readable("$dirpath/$def") && is_file("$dirpath/$def") && substr($def,-4,4) === ".php" && substr($def,-9,9) !== ".info.php") {
$tablename = substr($def,0,-4);
$dd = include("$dirpath/$def");
$info = null;
// foreach ($models as $modelname=>$modelpath) {
$rev_aggressive = $aggressive;
// add workflow fields
if (!empty($models[substr($def,0,-4)])) {
$modelname = substr($def,0,-4);
$model = new $modelname();
if ($model->supports_revisions && $workflow) {
$dd['revision_id'] = array(
DB_FIELD_TYPE=>DB_DEF_INTEGER,
DB_PRIMARY=>true,
DB_DEFAULT=>1,
);
$dd['approved'] = array(
DB_FIELD_TYPE=>DB_DEF_BOOLEAN
);
$rev_aggressive = true;
}
}
if (is_readable("$dirpath/$tablename.info.php")) $info = include("$dirpath/$tablename.info.php");
if (!$db->tableExists($tablename)) {
foreach ($db->createTable($tablename, $dd, $info) as $key=>$status) {
$tables[$key] = $status;
}
} else {
foreach ($db->alterTable($tablename, $dd, $info, $rev_aggressive) as $key=>$status) {
// if (isset($tables[$key])) echo "$tablename, $key<br>"; //FIXME we shouldn't echo this, already installed?
if ($status == TABLE_ALTER_FAILED){
$tables[$key] = $status;
} else {
$tables[$key] = ($status == TABLE_ALTER_NOT_NEEDED ? DATABASE_TABLE_EXISTED : DATABASE_TABLE_ALTERED);
}
}
}
}
}
}
}
}
}
}
return $tables;
}
//}
//
//class SSP { //note tacked into expDatabase for standardization and customized for Exponent
/**
* Create the data output array for the DataTables rows
*
* @param array $columns Column information array
* @param array $data Data from the SQL get
* @return array Formatted data in a row based format
*/
static function data_output ( $columns, $data )
{
$out = array();
for ( $i=0, $ien=count($data) ; $i<$ien ; $i++ ) {
$row = array();
for ( $j=0, $jen=count($columns) ; $j<$jen ; $j++ ) {
$column = $columns[$j];
// Is there a formatter?
if ( isset( $column['formatter'] ) ) {
if(empty($column['db'])){
$row[ $column['dt'] ] = $column['formatter']( $data[$i] );
}
else{
$row[ $column['dt'] ] = $column['formatter']( $data[$i][ $column['db'] ], $data[$i] );
}
}
else {
if(!empty($column['db'])){
$row[ $column['dt'] ] = $data[$i][ $columns[$j]['db'] ];
}
else{
$row[ $column['dt'] ] = "";
}
}
}
$out[] = $row;
}
return $out;
}
/**
* Paging
*
* Construct the LIMIT clause for server-side processing SQL query
*
* @param array $request Data sent to server by DataTables
* @param array $columns Column information array
* @return string SQL limit clause
*/
static function limit ( $request )
{
global $db;
return $db::limit_pdo($request);
// $limit = '';
//
// if ( isset($request['start']) && $request['length'] != -1 ) {
// $limit = "LIMIT ".(int)($request['start']).", ".(int)($request['length']);
// }
//
// return $limit;
}
/**
* Ordering
*
* Construct the ORDER BY clause for server-side processing SQL query
*
* @param array $request Data sent to server by DataTables
* @param array $columns Column information array
* @return string SQL order by clause
*/
static function order ( $request, $columns )
{
global $db;
return $db::order_pdo($request, $columns);
// $order = '';
//
// if ( isset($request['order']) && count($request['order']) ) {
// $orderBy = array();
// $dtColumns = self::pluck( $columns, 'dt' );
//
// for ( $i=0, $ien=count($request['order']) ; $i<$ien ; $i++ ) {
// // Convert the column index into the column data property
// $columnIdx = (int)($request['order'][$i]['column']);
// $requestColumn = $request['columns'][$columnIdx];
//
// $columnIdx = array_search( $requestColumn['data'], $dtColumns );
// $column = $columns[ $columnIdx ];
//
//// if ( $requestColumn['orderable'] === 'true' ) { //fixme allows us to initially sort an unsortable column
// $dir = $request['order'][$i]['dir'] === 'asc' ?
// 'ASC' :
// 'DESC';
//
// $orderBy[] = '`'.$column['db'].'` '.$dir;
//// }
// }
//
// if ( count( $orderBy ) ) {
// $order = 'ORDER BY '.implode(', ', $orderBy);
// }
// }
//
// return $order;
}
/**
* Searching / Filtering
*
* Construct the WHERE clause for server-side processing SQL query.
*
* NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here performance on large
* databases would be very poor
*
* @param array $request Data sent to server by DataTables
* @param array $columns Column information array
* @param array $bindings Array of values for PDO bindings, used in the
* sql_exec() function
* @return string SQL where clause
*/
static function filter ( $request, $columns, &$bindings )
{
global $db;
return $db::filter_pdo( $request, $columns, $bindings);
// $globalSearch = array();
// $columnSearch = array();
// $dtColumns = self::pluck( $columns, 'dt' );
//
// if ( isset($request['search']) && $request['search']['value'] != '' ) {
// $str = $request['search']['value'];
//
// for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
// $requestColumn = $request['columns'][$i];
// $columnIdx = array_search( $requestColumn['data'], $dtColumns );
// $column = $columns[ $columnIdx ];
//
// if ( $requestColumn['searchable'] === 'true' ) {
// if (stripos($str, '-yadcf_delim-') !== false) {
// $val = explode('-yadcf_delim-', $str);
// if (empty($val[0])) {
// $val[0] = '0';
// } elseif (expDateTime::is_date($val[0])) {
// $val[0] = strtotime($val[0]);
// }
// if (empty($val[1])) {
// $val[1] = time();
// } elseif (expDateTime::is_date($val[1])) {
// $val[1] = strtotime($val[1]);
// }
// $binding0 = self::bind( $bindings, $val[0], PDO::PARAM_STR );
// $binding1 = self::bind( $bindings, $val[1], PDO::PARAM_STR );
// $globalSearch[] = "`".$column['db']."` BETWEEN ".$binding0." AND ".$binding1;
// } else {
// $binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
// $globalSearch[] = "`".$column['db']."` LIKE ".$binding;
// }
// }
// }
// }
//
// // Individual column filtering
// if ( isset( $request['columns'] ) ) {
// for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
// $requestColumn = $request['columns'][$i];
// $columnIdx = array_search( $requestColumn['data'], $dtColumns );
// $column = $columns[ $columnIdx ];
//
// $str = $requestColumn['search']['value'];
//
// if ( $requestColumn['searchable'] === 'true' && $str != '' ) {
// if (stripos($str, '-yadcf_delim-') !== false) {
// $val = explode('-yadcf_delim-', $str);
// if (empty($val[0])) {
// $val[0] = '0';
// } elseif (expDateTime::is_date($val[0])) {
// $val[0] = strtotime($val[0]);
// }
// if (empty($val[1])) {
// $val[1] = time();
// } elseif (expDateTime::is_date($val[1])) {
// $val[1] = strtotime($val[1]);
// }
// $binding0 = self::bind( $bindings, $val[0], PDO::PARAM_STR );
// $binding1 = self::bind( $bindings, $val[1], PDO::PARAM_STR );
// $columnSearch[] = "`".$column['db']."` BETWEEN ".$binding0." AND ".$binding1;
// } else {
// $binding = self::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
// $columnSearch[] = "`".$column['db']."` LIKE ".$binding;
// }
// }
// }
// }
//
// // Combine the filters into a single string
// $where = '';
//
// if ( count( $globalSearch ) ) {
// $where = '('.implode(' OR ', $globalSearch).')';
// }
//
// if ( count( $columnSearch ) ) {
// $where = $where === '' ?
// implode(' AND ', $columnSearch) :
// $where .' AND '. implode(' AND ', $columnSearch);
// }
//
// if ( $where !== '' ) {
// $where = 'WHERE '.$where;
// }
//
// return $where;
}
/**
* Perform the SQL queries needed for an server-side processing requested,
* utilising the helper functions of this class, limit(), order() and
* filter() among others. The returned array is ready to be encoded as JSON
* in response to an SSP request, or can be modified if needed before
* sending back to the client.
*
* @param array $request Data sent to server by DataTables
* @param string $table SQL table to query
* @param string $primaryKey Primary key of the table
* @param array $columns Column information array
* @return array Server-side processing response array
*/
static function simple ( $request, $table, $primaryKey, $columns )
{
global $db;
return $db::simple_pdo($request, $table, $primaryKey, $columns);
// $bindings = array();
// $dbpdo = self::sql_connect();
//
// // Build the SQL query string from the request
// $limit = self::limit( $request );
// $order = self::order( $request, $columns );
// $where = self::filter( $request, $columns, $bindings );
//
// // Main query to actually get the data
// $data = self::sql_exec( $dbpdo, $bindings,
// "SELECT `".implode("`, `", self::pluck($columns, 'db'))."`
// FROM $table
// $where
// $order
// $limit"
// );
//
// // Data set length after filtering
// $resFilterLength = self::sql_exec( $dbpdo, $bindings,
// "SELECT COUNT(`{$primaryKey}`)
// FROM $table
// $where"
// );
// $recordsFiltered = $resFilterLength[0][0];
//
// // Total data set length
// $resTotalLength = self::sql_exec( $dbpdo,
// "SELECT COUNT(`{$primaryKey}`)
// FROM $table"
// );
// $recordsTotal = $resTotalLength[0][0];
//
// /*
// * Output
// */
// return array(
// "draw" => isset ( $request['draw'] ) ?
// (int)( $request['draw'] ) :
// 0,
// "recordsTotal" => (int)( $recordsTotal ),
// "recordsFiltered" => (int)( $recordsFiltered ),
// "data" => self::data_output( $columns, $data )
// );
}
/**
* The difference between this method and the `simple` one, is that you can
* apply additional `where` conditions to the SQL queries. These can be in
* one of two forms:
*
* * 'Result condition' - This is applied to the result set, but not the
* overall paging information query - i.e. it will not effect the number
* of records that a user sees they can have access to. This should be
* used when you want apply a filtering condition that the user has sent.
* * 'All condition' - This is applied to all queries that are made and
* reduces the number of records that the user can access. This should be
* used in conditions where you don't want the user to ever have access to
* particular records (for example, restricting by a login id).
*
* @param array $request Data sent to server by DataTables
* @param string $table SQL table to query
* @param string $primaryKey Primary key of the table
* @param array $columns Column information array
* @param string $whereResult WHERE condition to apply to the result set
* @param string $whereAll WHERE condition to apply to all queries
*
* @return array Server-side processing response array
*/
static function complex ( $request, $table, $primaryKey, $columns, $whereResult=null, $whereAll=null )
{
global $db;
return $db::complex_pdo($request, $table, $primaryKey, $columns, $whereResult, $whereAll);
// $bindings = array();
// $dbpdo = self::sql_connect();
// $whereAllSql = '';
//
// // Build the SQL query string from the request
// $limit = self::limit( $request );
// $order = self::order( $request, $columns );
// $where = self::filter( $request, $columns, $bindings );
//
// $whereResult = self::_flatten( $whereResult );
// $whereAll = self::_flatten( $whereAll );
//
// if ( $whereResult ) {
// $where = $where ?
// $where .' AND '.$whereResult :
// 'WHERE '.$whereResult;
// }
//
// if ( $whereAll ) {
// $where = $where ?
// $where .' AND '.$whereAll :
// 'WHERE '.$whereAll;
//
// $whereAllSql = 'WHERE '.$whereAll;
// }
//
// // Main query to actually get the data
// $data = self::sql_exec( $dbpdo, $bindings,
// "SELECT `".implode("`, `", self::pluck($columns, 'db'))."`
// FROM $table
// $where
// $order
// $limit"
// );
//
// // Data set length after filtering
// $resFilterLength = self::sql_exec( $dbpdo, $bindings,
// "SELECT COUNT(`{$primaryKey}`)
// FROM $table
// $where"
// );
// $recordsFiltered = $resFilterLength[0][0];
//
// // Total data set length
// $resTotalLength = self::sql_exec( $dbpdo, $bindings,
// "SELECT COUNT(`{$primaryKey}`)
// FROM $table ".
// $whereAllSql
// );
// $recordsTotal = $resTotalLength[0][0];
//
// /*
// * Output
// */
// return array(
// "draw" => isset ( $request['draw'] ) ?
// (int)( $request['draw'] ) :
// 0,
// "recordsTotal" => (int)( $recordsTotal ),
// "recordsFiltered" => (int)( $recordsFiltered ),
// "data" => self::data_output( $columns, $data )
// );
}
/**
* Connect to the database by PDO
*
* @return PDO Database connection handle
*/
static function sql_connect ()
{
global $db;
return $db->sql_connect_pdo();
}
/**
* Execute an SQL query on the database
*
* @param resource/PDO $dbpdo Database handler
* @param array $bindings Array of PDO binding values from bind() to be
* used for safely escaping strings. Note that this can be given as the
* SQL query string if no bindings are required.
* @param string $sql SQL query to execute.
* @return array Result from the query (all rows)
*/
static function sql_exec ( $dbpdo, $bindings, $sql=null )
{
// Argument shifting
if ( $sql === null ) {
$sql = $bindings;
}
$stmt = $dbpdo->prepare( $sql );
//echo $sql;
// Bind parameters
if ( is_array( $bindings ) ) {
for ( $i=0, $ien=count($bindings) ; $i<$ien ; $i++ ) {
$binding = $bindings[$i];
$stmt->bindValue( $binding['key'], $binding['val'], $binding['type'] );
}
}
// Execute
try {
$stmt->execute();
}
catch (PDOException $e) {
self::fatal( "An SQL error occurred: ".$e->getMessage() );
}
// Return all
return $stmt->fetchAll( PDO::FETCH_BOTH );
}
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Internal methods
*/
/**
* Throw a fatal error.
*
* This writes out an error message in a JSON string which DataTables will
* see and show to the user in the browser.
*
* @param string $msg Message to send to the client
*/
static function fatal ( $msg )
{
echo json_encode( array(
"error" => $msg
) );
exit(0);
}
/**
* Create a PDO binding key which can be used for escaping variables safely
* when executing a query with sql_exec()
*
* @param array &$a Array of bindings
* @param * $val Value to bind
* @param int $type PDO field type
* @return string Bound key to be used in the SQL where this parameter
* would be used.
*/
static function bind ( &$a, $val, $type )
{
$key = ':binding_'.count( $a );
$a[] = array(
'key' => $key,
'val' => $val,
'type' => $type
);
return $key;
}
/**
* Pull a particular property from each assoc. array in a numeric array,
* returning and array of the property values from each item.
*
* @param array $a Array to get data from
* @param string $prop Property to read
* @return array Array of property values
*/
static function pluck ( $a, $prop )
{
$out = array();
for ( $i=0, $len=count($a) ; $i<$len ; $i++ ) {
if(empty($a[$i][$prop])){
continue;
}
//removing the $out array index confuses the filter method in doing proper binding,
//adding it ensures that the array data are mapped correctly
$out[$i] = $a[$i][$prop];
}
return $out;
}
/**
* Return a string from an array or a string
*
* @param array|string $a Array to join
* @param string $join Glue for the concatenation
* @return string Joined string
*/
static function _flatten ( $a, $join = ' AND ' )
{
if ( ! $a ) {
return '';
}
elseif ( $a && is_array($a) ) {
return implode( $join, $a );
}
return $a;
}
}
/**
* This is the abstract class database
*
* This is the generic implementation of the database class.
* @subpackage Database
* @package Subsystems
*/
#[AllowDynamicProperties]
abstract class database {
/**
* @var string $connection Database connection string
*/
var $connection = null;
/**
* @var boolean $havedb
*/
var $havedb = false;
/**
* @var string $prefix Database prefix
*/
var $prefix = "";
/**
* Make a connection to the Database Server
*
* Takes the supplied credentials (username / password) and tries to
* connect to the server and select the given database. All the rules
* governing database connect also govern this method.
*
* @param string $username The username to connect to the server as.
* @param string $password The password for $username
* @param string $hostname The hostname of the database server. If
* localhost is specified, a local socket connection will be attempted.
* @param string $database The name of the database to use. Multi-database
* sites are still not yet supported.
* @param bool $new Whether or not to force the PHP connection function to establish
* a distinctly new connection handle to the server.
*/
// function connect ($username, $password, $hostname, $database, $new=false) {
abstract function __construct($username, $password, $hostname, $database, $new=false);
/** Begin SSP Methods */
/**
* Connect to the database by PDO
*
* @return PDO Database connection handle
*/
abstract function sql_connect_pdo();
/**
* Paging
*
* Construct the LIMIT clause for server-side processing SQL query
*
* @param array $request Data sent to server by DataTables
* @return string SQL limit clause
*/
static function limit_pdo ( $request )
{
$limit = '';
if ( isset($request['start']) && $request['length'] != -1 ) {
$limit = "LIMIT ".(int)($request['start']).", ".(int)($request['length']);
}
return $limit;
}
/**
* Ordering
*
* Construct the ORDER BY clause for server-side processing SQL query
*
* @param array $request Data sent to server by DataTables
* @param array $columns Column information array
* @return string SQL order by clause
*/
static function order_pdo ( $request, $columns )
{
$order = '';
if ( isset($request['order']) && count($request['order']) ) {
$orderBy = array();
$dtColumns = expDatabase::pluck( $columns, 'dt' );
for ( $i=0, $ien=count($request['order']) ; $i<$ien ; $i++ ) {
// Convert the column index into the column data property
$columnIdx = (int)($request['order'][$i]['column']);
$requestColumn = $request['columns'][$columnIdx];
$columnIdx = array_search( $requestColumn['data'], $dtColumns );
$column = $columns[ $columnIdx ];
// if ( $requestColumn['orderable'] === 'true' ) { //fixme allows us to initially sort an unsortable column
$dir = $request['order'][$i]['dir'] === 'asc' ?
'ASC' :
'DESC';
$orderBy[] = '`'.$column['db'].'` '.$dir;
// }
}
if ( count( $orderBy ) ) {
$order = 'ORDER BY '.implode(', ', $orderBy);
}
}
return $order;
}
/**
* Searching / Filtering
*
* Construct the WHERE clause for server-side processing SQL query.
*
* NOTE this does not match the built-in DataTables filtering which does it
* word by word on any field. It's possible to do here performance on large
* databases would be very poor
*
* @param array $request Data sent to server by DataTables
* @param array $columns Column information array
* @param array $bindings Array of values for PDO bindings, used in the
* sql_exec() function
* @return string SQL where clause
*/
static function filter_pdo ( $request, $columns, &$bindings )
{
$globalSearch = array();
$columnSearch = array();
$dtColumns = expDatabase::pluck( $columns, 'dt' );
if ( isset($request['search']) && $request['search']['value'] != '' ) {
$str = $request['search']['value'];
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
$requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns );
$column = $columns[ $columnIdx ];
if ( $requestColumn['searchable'] === 'true' ) {
if (stripos($str, '-yadcf_delim-') !== false) {
$val = explode('-yadcf_delim-', $str);
if (empty($val[0])) {
$val[0] = '0';
} elseif (expDateTime::is_date($val[0])) {
$val[0] = strtotime($val[0]);
}
if (empty($val[1])) {
$val[1] = time();
} elseif (expDateTime::is_date($val[1])) {
$val[1] = strtotime($val[1]);
}
$binding0 = expDatabase::bind( $bindings, $val[0], PDO::PARAM_STR );
$binding1 = expDatabase::bind( $bindings, $val[1], PDO::PARAM_STR );
$globalSearch[] = "`".$column['db']."` BETWEEN ".$binding0." AND ".$binding1;
} else {
$binding = expDatabase::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
$globalSearch[] = "`".$column['db']."` LIKE ".$binding;
}
}
}
}
// Individual column filtering
if ( isset( $request['columns'] ) ) {
for ( $i=0, $ien=count($request['columns']) ; $i<$ien ; $i++ ) {
$requestColumn = $request['columns'][$i];
$columnIdx = array_search( $requestColumn['data'], $dtColumns );
$column = $columns[ $columnIdx ];
$str = $requestColumn['search']['value'];
if ( $requestColumn['searchable'] === 'true' && $str != '' ) {
if (stripos($str, '-yadcf_delim-') !== false) {
$val = explode('-yadcf_delim-', $str);
if (empty($val[0])) {
$val[0] = '0';
} elseif (expDateTime::is_date($val[0])) {
$val[0] = strtotime($val[0]);
}
if (empty($val[1])) {
$val[1] = time();
} elseif (expDateTime::is_date($val[1])) {
$val[1] = strtotime($val[1]);
}
$binding0 = expDatabase::bind( $bindings, $val[0], PDO::PARAM_STR );
$binding1 = expDatabase::bind( $bindings, $val[1], PDO::PARAM_STR );
$columnSearch[] = "`".$column['db']."` BETWEEN ".$binding0." AND ".$binding1;
} else {
$binding = expDatabase::bind( $bindings, '%'.$str.'%', PDO::PARAM_STR );
$columnSearch[] = "`".$column['db']."` LIKE ".$binding;
}
}
}
}
// Combine the filters into a single string
$where = '';
if ( count( $globalSearch ) ) {
$where = '('.implode(' OR ', $globalSearch).')';
}
if ( count( $columnSearch ) ) {
$where = $where === '' ?
implode(' AND ', $columnSearch) :
$where .' AND '. implode(' AND ', $columnSearch);
}
if ( $where !== '' ) {
$where = 'WHERE '.$where;
}
return $where;
}
/**
* Perform the SQL queries needed for an server-side processing requested,
* utilising the helper functions of this class, limit(), order() and
* filter() among others. The returned array is ready to be encoded as JSON
* in response to an SSP request, or can be modified if needed before
* sending back to the client.
*
* @param array $request Data sent to server by DataTables
* @param string $table SQL table to query
* @param string $primaryKey Primary key of the table
* @param array $columns Column information array
* @return array Server-side processing response array
*/
static function simple_pdo ( $request, $table, $primaryKey, $columns )
{
$bindings = array();
$dbpdo = expDatabase::sql_connect();
// Build the SQL query string from the request
$limit = expDatabase::limit( $request );
$order = expDatabase::order( $request, $columns );
$where = expDatabase::filter( $request, $columns, $bindings );