-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.php
2369 lines (1899 loc) · 80.5 KB
/
database.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
/*
* Coding copyright Martin Lucas-Smith, University of Cambridge, 2003-17
* Version 3.0.6
* Uses prepared statements (see https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php ) where possible
* Distributed under the terms of the GNU Public Licence - https://www.gnu.org/copyleft/gpl.html
* Requires PHP 4.1+ with register_globals set to 'off'
* Download latest from: http://download.geog.cam.ac.uk/projects/database/
*/
# Class containing basic generalised database manipulation functions for PDO
class database
{
# General class properties
public $connection = NULL;
private $preparedStatement = NULL;
private $query = NULL;
private $queryValues = NULL;
private $strictWhere = false;
private $fieldsCache = array ();
# Error logger properties
private $errorLoggerCallback = NULL;
private $errorLoggerCustomCode = NULL;
private $errorLoggerCustomCodeText = NULL;
private $errorLoggerEntryFunction = NULL;
# Function to connect to the database
public function __construct ($hostname, $username, $password, $database = NULL, $vendor = 'mysql', $logFile = false, $userForLogging = false, $nativeTypes = false /* NB: a future release will change this to true */, $setNamesUtf8 = true, $driverOptions = array ())
{
# Assign the user for logging
$this->logFile = $logFile;
$this->userForLogging = $userForLogging;
# Make attributes available for querying by calling applications
$this->hostname = $hostname;
$this->vendor = $vendor;
# Convert localhost to 127.0.0.1
if ($hostname == 'localhost') {
if (version_compare (PHP_VERSION, '5.3.0', '>=')) {
// Previously believed only to affect Windows Vista, but not the case. On PHP 5.3.x on Windows (Vista) see http://bugs.php.net/45150
// if (substr (PHP_OS, 0, 3) == 'WIN') {
$hostname = '127.0.0.1';
// }
}
}
# Enable native types if required; currently implemented and tested only for MySQL; note that this requires the pdo-mysqlnd driver to be installed
if ($nativeTypes) {
if ($vendor == 'mysql') {
$driverOptions[PDO::ATTR_EMULATE_PREPARES] = false; // #!# This seems to cause problems with e.g. "SHOW DATABASES LIKE"; see point 3 at: http://stackoverflow.com/a/10455228/180733 and http://stackoverflow.com/a/12202218/180733
$driverOptions[PDO::ATTR_STRINGIFY_FETCHES] = false; // This seems to be the default anyway
}
}
# Enable exception throwing; see: http://php.net/pdo.error-handling
$driverOptions[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
# Connect to the database and return the status
if ($vendor == 'sqlite') {
$dsn = 'sqlite:' . $database; // Database should be a filename with absolute path
$setNamesUtf8 = false;
} else {
$dsn = "{$vendor}:host={$hostname}" . ($database ? ";dbname={$database}" : '');
}
try {
$this->connection = new PDO ($dsn, $username, $password, $driverOptions);
} catch (PDOException $e) { // "PDO::__construct() will always throw a PDOException if the connection fails regardless of which PDO::ATTR_ERRMODE is currently set." noted at http://php.net/pdo.error-handling
// error_log ("{$e} {$dsn}, {$username}, {$password}"); // Not enabled by default as $e can contain passwords which get dumped to the webserver's error log
return false;
}
# Set transfers to UTF-8
if ($setNamesUtf8) {
$this->_execute ("SET NAMES 'utf8'");
// # The following is a more portable version that could be used instead
//$charset = $this->getVariable ('character_set_database');
//$this->_execute ("SET NAMES '{$charset}';");
}
}
# Function to disconnect from the database
public function close ()
{
# Close the connection
$this->connection = NULL;
}
# Function to enable whether automatically-constructed WHERE=... clauses do proper, exact comparisons, so that id="1 x" doesn't match against id value 1 in the database
public function setStrictWhere ($boolean = true)
{
$this->strictWhere = $boolean;
}
# Function to register an error logger callback; the callback should either be a function name or specified as an array (object instance, publicly-visible method)
public function registerErrorLogger ($callback)
{
# Register the callback
$this->errorLoggerCallback = $callback;
}
# Function to set a custom error code and text that will be applied to the following call only
public function errorCode ($code = NULL, $text = NULL)
{
# Register the code and text
$this->errorLoggerCustomCode = $code;
$this->errorLoggerCustomCodeText = $text;
}
# Function to reset any custom error code
private function resetErrorCode ()
{
# Reset the values
$this->errorCode ();
}
# Function to call the error logger, if it is defined; currently this supports only an external callback
private function logError ($forcedErrorText = false)
{
# Ignore this functionality if no callback
if (!$this->errorLoggerCallback) {return;}
# Append forced error text if required
if ($forcedErrorText) {
$divider = ($this->errorLoggerCustomCodeText ? (substr ($this->errorLoggerCustomCodeText, -1) == '.' ? '' : ';') . ' ' : '');
$this->errorLoggerCustomCodeText .= $divider . $forcedErrorText;
}
# Call the logger, sending back the called function (e.g. 'query', 'getData', 'select', etc.) and the error details
if (is_array ($this->errorLoggerCallback)) {
$class = $this->errorLoggerCallback[0];
$method = $this->errorLoggerCallback[1];
$class->$method ($this->errorLoggerEntryFunction, $this->error (), $this->errorLoggerCustomCode, $this->errorLoggerCustomCodeText);
} else {
$callback = $this->errorLoggerCallback;
$callback ($this->errorLoggerEntryFunction, $this->error (), $this->errorLoggerCustomCode, $this->errorLoggerCustomCodeText);
}
# Reset any custom error code and text
$this->resetErrorCode ();
}
# Function to do a generic SQL query
#!# Currently no ability to enable logging for write-based queries; need to allow external callers to specify this, but without this affecting internal use of this function
public function query ($query, $preparedStatementValues = array (), $debug = false)
{
# Register this as the public entry point
$this->errorLoggerEntryFunction = __FUNCTION__;
# Hand off to the implementation
$result = $this->_query ($query, $preparedStatementValues, $debug);
# Reset any custom error code and text
$this->resetErrorCode ();
# Return the result
return $result;
}
# Implementation for query
private function _query ($query, $preparedStatementValues = array (), $debug = false)
{
return $this->queryOrExecute (__FUNCTION__, $query, $preparedStatementValues, $debug);
}
# Function to execute a generic SQL query
#!# Currently no ability to enable logging for write-based queries; need to allow external callers to specify this, but without this affecting internal use of this function
public function execute ($query, $preparedStatementValues = array (), $debug = false)
{
# Register this as the public entry point
$this->errorLoggerEntryFunction = __FUNCTION__;
# Hand off to the implementation
$result = $this->_execute ($query, $preparedStatementValues, $debug);
# Reset any custom error code and text
$this->resetErrorCode ();
# Return the result
return $result;
}
# Implementation for execute
private function _execute ($query, $preparedStatementValues = array (), $debug = false)
{
return $this->queryOrExecute (__FUNCTION__, $query, $preparedStatementValues, $debug);
}
# Function used by both query and execute
private function queryOrExecute ($mode, $query, $preparedStatementValues = array (), $debug = false)
{
# Global the query and any values
$this->query = $query;
$this->queryValues = $preparedStatementValues;
# Show the query if debugging
#!# Deprecate this
if ($debug) {
echo $query . "<br />";
}
# If using prepared statements, prepare then execute
$this->preparedStatement = NULL; // Always clear to avoid the error() function returning results of a previous statement
if ($preparedStatementValues) {
# Execute the statement (ending if there is an error in the query or parameters)
try {
$this->preparedStatement = $this->connection->prepare ($query);
$result = $this->preparedStatement->execute ($preparedStatementValues);
} catch (PDOException $e) { // Enabled by PDO::ERRMODE_EXCEPTION in constructor
$this->logError ();
return false;
}
# In execute mode, get the number of affected rows
if ($mode == '_execute') {
$result = $this->preparedStatement->rowCount ();
}
} else {
# Execute the query and get the number of affected rows
$function = ($mode == '_query' ? 'query' : 'exec');
try {
$result = $this->connection->$function ($query);
} catch (PDOException $e) { // Enabled by PDO::ERRMODE_EXCEPTION in constructor
if ($debug) {echo $e;}
$this->logError ();
return false;
}
}
# Return the result (either boolean, or the number of affected rows)
return $result;
}
# Function to get the data where only one item will be returned; this function has the same signature as getData
# Uses prepared statement approach if a fourth parameter providing the placeholder values is supplied
public function getOne ($query, $associative = false, $keyed = true, $preparedStatementValues = array ())
{
# Register this as the public entry point
$this->errorLoggerEntryFunction = __FUNCTION__;
# Hand off to the implementation
$result = $this->_getOne ($query, $associative, $keyed, $preparedStatementValues);
# Reset any custom error code and text
$this->resetErrorCode ();
# Return the result
return $result;
}
# Implementation for getOne
private function _getOne ($query, $associative = false, $keyed = true, $preparedStatementValues = array (), $expectMode = false)
{
# Get the data; NB this is not done in expect mode as that is handled explicitly below with a more customised error message
$data = $this->_getData ($query, $associative, $keyed, $preparedStatementValues, array ());
# Ensure that only one item is returned
if (count ($data) > 1) {
$this->logError ("Query produces more than one result, in {$this->errorLoggerEntryFunction}().");
return NULL;
}
if (count ($data) !== 1) {
if ($expectMode) {
$this->logError ("Expected exactly one result, in {$this->errorLoggerEntryFunction}().");
}
return false;
}
# Return the data, taking the first (and now confirmed as the only) item; $data[0] would fail when using $associative
foreach ($data as $keyOrIndex => $item) {
return $item;
}
}
# Return the value of the field column from the single-result query
public function getOneField ($query, $field, $preparedStatementValues = array ())
{
# Register this as the public entry point
$this->errorLoggerEntryFunction = __FUNCTION__;
# Hand off to the implementation
$result = $this->_getOneField ($query, $field, $preparedStatementValues);
# Reset any custom error code and text
$this->resetErrorCode ();
# Return the result
return $result;
}
# Implementation for getOneField
private function _getOneField ($query, $field, $preparedStatementValues = array (), $expectMode = false)
{
# Get the result or end (returning NULL or false)
if (!$result = $this->_getOne ($query, false, true, $preparedStatementValues, $expectMode)) {
return $result;
}
# If the field doesn't exist, return false
if (!isSet ($result[$field])) {
$this->logError ("Field '{$field}' doesn't exist.");
return false;
}
# Return the field value
return $result[$field];
}
# Gets results from the query, returning false if there are none (never an empty array)
public function expectData ($query)
{
# Register this as the public entry point
$this->errorLoggerEntryFunction = __FUNCTION__;
# Get the data or end; expectMode will have caused a logError to have been thrown
if (!$result = $this->_getData ($query, false, true, array (), array (), $expectMode = true)) {
return false;
}
# Reset any custom error code and text
$this->resetErrorCode ();
# Return the result
return $result;
}
# A single row of data from the query is expected and returned; otherwise false is returned (never NULL)
public function expectOne ($query)
{
# Register this as the public entry point
$this->errorLoggerEntryFunction = __FUNCTION__;
# Get the data or end; expectMode will have caused a logError to have been thrown
if (!$result = $this->_getOne ($query, false, true, array (), $expectMode = true)) {
return false;
}
# Reset any custom error code and text
$this->resetErrorCode ();
# Return the result
return $result;
}
# A single field of data from the query is expected and returned; otherwise false is returned (never NULL)
public function expectOneField ($query, $field, $preparedStatementValues = array ())
{
# Register this as the public entry point
$this->errorLoggerEntryFunction = __FUNCTION__;
# Get the data
$result = $this->_getOneField ($query, $field, $preparedStatementValues, $expectMode = true);
# NULL is an error condition indicating that there was more than one result; expectMode will have caused a logError to have been thrown
if (is_null ($result)) {
return false;
}
# Reset any custom error code and text
$this->resetErrorCode ();
# Return the result
return $result;
}
# Function to get the data where either (i) only one column per item will be returned, resulting in index => value, or (ii) two columns are returned, resulting in col1 => col2
# Uses prepared statement approach if a third parameter providing the placeholder values is supplied
public function getPairs ($query, $unique = false, $preparedStatementValues = array ())
{
# Get the data
$data = $this->_getData ($query, false, $keyed = false, $preparedStatementValues);
# Convert to pairs
$pairs = $this->toPairs ($data, $unique);
# Return the data
return $pairs;
}
# Helper function to convert data to pairs; assumes that the values in each item are not associative
private function toPairs ($data, $unique = false)
{
# Loop through each item in the data to allocate a key/value pair
$pairs = array ();
foreach ($data as $key => $item) {
# If more than one item, use the first two in the list as the key and value
if (count ($item) == 1) {
$value = $item[0];
} else {
$key = $item[0];
$value = $item[1];
}
# Trim the value
$value = trim ($value);
# Add to output data
$pairs[$key] = $value;
}
# Unique the data if necessary; note that this is unlikely to be wanted if the main keys are associative
if ($unique) {$pairs = array_unique ($pairs);}
# Return the data
return $pairs;
}
# Function to get data from an SQL query and return it as an array; $associative should be false or a string "{$database}.{$table}" (which reindexes the data to the field containing the unique key) or a supplied fieldname to avoid a SHOW FULL FIELDS lookup
# Uses prepared statement approach if a fourth parameter providing the placeholder values is supplied
public function getData ($query, $associative = false, $keyed = true, $preparedStatementValues = array (), $onlyFields = array ())
{
# Register this as the public entry point
$this->errorLoggerEntryFunction = __FUNCTION__;
# Hand off to the implementation
$data = $this->_getData ($query, $associative, $keyed, $preparedStatementValues, $onlyFields);
# Reset any custom error code and text
$this->resetErrorCode ();
# Return the data
return $data;
}
# Implementation for getData
private function _getData ($query, $associative = false, $keyed = true, $preparedStatementValues = array (), $onlyFields = array (), $expectMode = false)
{
# Global the query and any values
$this->query = $query;
$this->queryValues = $preparedStatementValues;
# Create an empty array to hold the data
$data = array ();
# Set fetch mode
$mode = ($keyed ? PDO::FETCH_ASSOC : PDO::FETCH_NUM);
# If using prepared statements, prepare then execute
$this->preparedStatement = NULL; // Always clear to avoid the error() function returning results of a previous statement
if ($preparedStatementValues) {
# Execute the statement (ending if there is an error in the query or parameters)
try {
$this->preparedStatement = $this->connection->prepare ($query);
$this->preparedStatement->execute ($preparedStatementValues);
} catch (PDOException $e) { // Enabled by PDO::ERRMODE_EXCEPTION in constructor
$this->logError ();
return $data;
}
# Fetch the data
$this->preparedStatement->setFetchMode ($mode);
$data = $this->preparedStatement->fetchAll ();
} else {
# Assign the query
try {
$statement = $this->connection->query ($query);
} catch (PDOException $e) { // Enabled by PDO::ERRMODE_EXCEPTION in constructor
$this->logError ();
return $data;
}
# Loop through each row and add the data to it
$statement->setFetchMode ($mode);
while ($row = $statement->fetch ()) {
$data[] = $row;
}
}
# Reassign the keys to being the unique field's name, in associative mode
if ($associative) {
# Get the unique field name, looking it up if supplied as 'database.table'; otherwise use the id directly
if (strpos ($associative, '.') !== false) {
list ($database, $table) = explode ('.', $associative, 2);
$uniqueField = $this->getUniqueField ($database, $table);
} else {
$uniqueField = $associative;
}
# Return as non-keyed data if no unique field
if (!$uniqueField) {
$this->logError ();
return $data;
}
# Re-key with the field name
$newData = array ();
foreach ($data as $key => $attributes) {
#!# This causes offsets if the key is not amongst the fields requested
$newData[$attributes[$uniqueField]] = $attributes;
}
# Entirely replace the dataset; doing on a key-by-key basis doesn't work because the auto-generated keys can clash with real id key names
$data = $newData;
}
# Filter only to specified fields if required
if ($onlyFields) {
foreach ($data as $index => $record) {
foreach ($record as $key => $value) {
if (!in_array ($key, $onlyFields)) {
unset ($data[$index][$key]);
}
}
}
}
# In expect mode, if there is no result, treat that as an error case
if ($expectMode) {
if (!$data) {
$this->logError ("Expected result(s), but none were obtained, in {$this->errorLoggerEntryFunction}().");
return $data;
}
}
# Return the array
return $data;
}
# Function to export data served as a CSV, optimised to use low memory; this is a combination of database::getData() and csv::serve
public function serveCsv ($query, $preparedStatementValues = array (), $filenameBase = 'data', $timestamp = true, $headerLabels = array (), $zipped = false /* false, or true (zip), or 'zip'/'gz') */, $saveToDirectory = false /* or full directory path, slash-terminated */, $includeHeaderRow = true, $chunksOf = 500)
{
# Global the query and any values
$this->query = $query;
$this->queryValues = $preparedStatementValues;
# Execute the statement (ending if there is an error in the query or parameters)
try {
$this->preparedStatement = $this->connection->prepare ($query);
if ($this->vendor == 'mysql') {
$this->connection->setAttribute (PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);
}
$this->preparedStatement->execute ($preparedStatementValues);
} catch (PDOException $e) { // Enabled by PDO::ERRMODE_EXCEPTION in constructor
return false;
}
# Add a timestamp to the filename if required
if ($timestamp) {
$filenameBase .= '_savedAt' . date ('Ymd-His');
}
# Determine the directory save location
$directory = ($saveToDirectory ? $saveToDirectory : sys_get_temp_dir () . '/');
# Determine filename; the routine always writes to a file, even if this is subsequently removed, to avoid over-length strings (internal string size is max 2GB)
$filename = $filenameBase . '.csv';
$file = $directory . $filename;
# Delete any existing file, e.g. from an improperly-terminated run
if (is_file ($file)) {
unlink ($file);
}
# Add CSV processing support
require_once ('csv.php');
# Set chunking state
$data = array ();
$i = 0;
# Fetch the data
$this->preparedStatement->setFetchMode (PDO::FETCH_ASSOC);
while ($row = $this->preparedStatement->fetch ()) {
$data[] = $row;
$i++;
# Add data periodically by processing the chunk when limit required
if ($i == $chunksOf) {
$csvChunk = csv::dataToCsv ($data, '', ',', $headerLabels, $includeHeaderRow);
file_put_contents ($file, $csvChunk, FILE_APPEND);
# Reset chunking state
$data = array ();
$i = 0;
$includeHeaderRow = false; // Only the first iteration should have headers
}
}
# Add residual data to the CSV if any left over (which will usually happen, unless the amount of data is exactly divisible by $chunksOf
if ($data) {
$csvChunk = csv::dataToCsv ($data, '', ',', $headerLabels, $includeHeaderRow);
file_put_contents ($file, $csvChunk, FILE_APPEND);
}
# If zipped, emit the data in a zip enclosure
#!# Note that this leaves the original CSV file present, which may or may not be desirable
if ($zipped) {
$supportedFormats = array ('zip', 'gz');
$format = (is_string ($zipped) && in_array ($zipped, $supportedFormats) ? $zipped : $supportedFormats[0]); // Default to first, zip
require_once ('application.php');
application::createZip ($file, $filename, $saveToDirectory, $format);
return;
}
# If required to save the file, leave the generated file in place, return at this point
if ($saveToDirectory) {
return $file;
}
# Publish, by sending a header and then echoing the data
header ('Content-type: application/octet-stream');
header ('Content-Disposition: attachment; filename="' . $filename . '"');
readfile ($file);
# Delete the file
unlink ($file);
}
# Function to do getData via pagination
public function getDataViaPagination ($query, $associative = false /* or string as "{$database}.{$table}" */, $keyed = true, $preparedStatementValues = array (), $onlyFields = array (), $paginationRecordsPerPage, $page = 1, $searchResultsMaximumLimit = false, $knownTotalAvailable = false)
{
# Trim the query to ensure that placeholder matching works consistently
$query = trim ($query);
# If the total is already known, use that
if ($knownTotalAvailable) {
$totalAvailable = $knownTotalAvailable;
} else {
# Prepare the counting query; use a negative lookahead to match the section between SELECT ... FROM - see http://stackoverflow.com/questions/406230
#!# "ORDER BY generatedcolumn, ..." will cause a failure, but we cannot wipe out '/\s+ORDER\s+BY\s+.+$/isU' because a LIMIT clause may follow
#!# TRIM(... FROM ...) in the SELECT clause will a failure
$placeholders = array (
'/^SELECT\s+(?!\s+FROM\s).+\s+FROM/isU' => 'SELECT COUNT(*) AS total FROM',
# This works but isn't in use anywhere, so enable if/when needed with more testing '/^SELECT\s+DISTINCT\(([^)]+)\)\s+(?!\s+FROM ).+\s+FROM/' => 'SELECT COUNT(DISTINCT(\1)) AS total FROM',
);
$countingQuery = preg_replace (array_keys ($placeholders), array_values ($placeholders), $query);
# If any named placeholders are not now in the counting query, remove them from the list
$countingPreparedStatementValues = $preparedStatementValues;
foreach ($countingPreparedStatementValues as $key => $value) {
if (substr_count ($query, ':' . $key) && !substr_count ($countingQuery, ':' . $key)) {
unset ($countingPreparedStatementValues[$key]);
}
}
# Perform a count first
$totalAvailable = $this->_getOneField ($countingQuery, 'total', $countingPreparedStatementValues);
}
# Enforce a maximum limit if required, by overwriting the total available, which the pagination mechanism will automatically adjust to
$actualMatchesReachedMaximum = false;
if ($searchResultsMaximumLimit) {
if ($totalAvailable > $searchResultsMaximumLimit) {
$actualMatchesReachedMaximum = $totalAvailable; // Assign the number of the actual total available, which will evaluate to true
$totalAvailable = $searchResultsMaximumLimit;
}
}
# Get the requested page and calculate the pagination
require_once ('pagination.php');
if (is_int ($page)) {$page = (string) $page;} // If page is actually an int, ctype_digit would not properly detect it as numeric
$requestedPage = (ctype_digit ($page) ? $page : 1);
list ($totalPages, $offset, $items, $limitPerPage, $page) = pagination::getPagerData ($totalAvailable, $paginationRecordsPerPage, $requestedPage);
# Now construct the main query
$placeholders = array (
'/;$/' => " LIMIT {$offset}, {$limitPerPage};",
);
$dataQuery = preg_replace (array_keys ($placeholders), array_values ($placeholders), $query);
# Get the data
$data = $this->_getData ($dataQuery, $associative, $keyed, $preparedStatementValues, $onlyFields);
# Return the data and metadata
return array ($data, (int) $totalAvailable, $totalPages, $page, $actualMatchesReachedMaximum);
}
# Function to count the number of records
public function getTotal ($database, $table, $restrictionSql = '')
{
# Check that the table exists
$tables = $this->getTables ($database);
if (!in_array ($table, $tables)) {return false;}
# Get the total
#!# 'WHERE' should be within this here, not part of the supplied parameter
$query = "SELECT COUNT(*) AS total FROM `{$database}`.`{$table}` {$restrictionSql};";
$data = $this->_getOne ($query);
# Return the value
return $data['total'];
}
# Function to get fields
public function getFields ($database, $table, $addSimpleType = false, $matchingRegexpNoForwardSlashes = false, $asTotal = false, $excludeAuto = false)
{
# If the raw fields list is already in the fields cache, use that to avoid a pointless SHOW FULL FIELDS lookup
if (isSet ($this->fieldsCache[$database]) && isSet ($this->fieldsCache[$database][$table])) {
$data = $this->fieldsCache[$database][$table];
} else {
# Cache the global query and its values, if either exist, so that they can be reinstated when this function is called by another function internally
$cachedQuery = ($this->query ? $this->query : NULL);
$cachedQueryValues = (!is_null ($this->queryValues) ? $this->queryValues : NULL);
# Get the data
if ($this->vendor == 'sqlite') {
$query = "PRAGMA {$database}.table_info({$table});";
} else {
$query = "SHOW FULL FIELDS FROM `{$database}`.`{$table}`;";
}
$data = $this->_getData ($query);
# Restablish the catched query and its values if there is one
if (!is_null ($cachedQuery)) {$this->query = $cachedQuery;}
if (!is_null ($cachedQuery)) {$this->queryValues = $cachedQueryValues;}
# Add the result to the fields cache, in case there is another request for getFields for this database table
$this->fieldsCache[$database][$table] = $data;
}
# For SQLite, map the structure to emulate the MySQL format
if ($this->vendor == 'sqlite') {
$data = $this->sqliteTableStructureEmulation ($data, $table);
}
# Convert the field name to be the key name
$fields = array ();
foreach ($data as $key => $attributes) {
$fields[$attributes['Field']] = $attributes;
}
# Add a simple type description if required
if ($addSimpleType) {
foreach ($data as $key => $attributes) {
$fields[$attributes['Field']]['_type'] = $this->simpleType ($attributes['Type']);
}
}
# Expand ENUM/SET field values
foreach ($data as $key => $attributes) {
if (preg_match ('/^(enum|set)\(\'(.+)\'\)$/i', $attributes['Type'], $matches)) {
$fields[$attributes['Field']]['_values'] = explode ("','", $matches[2]);
} else {
$fields[$attributes['Field']]['_values'] = NULL;
}
}
# Filter by regexp if required
if ($matchingRegexpNoForwardSlashes) {
foreach ($fields as $field => $attributes) {
if (!preg_match ("/{$matchingRegexpNoForwardSlashes}/", $field)) {
unset ($fields[$field]);
}
}
}
# Exclude automatic fields if required
if ($excludeAuto) {
foreach ($fields as $field => $attributes) {
if ($attributes['Extra'] == 'auto_increment' || $attributes['Default'] == 'CURRENT_TIMESTAMP') {
unset ($fields[$field]);
}
}
}
# If returning as a total, convert to a count
if ($asTotal) {
$fields = count ($fields);
}
# Return the result
return $fields;
}
# Function to emulate an SQLite table structure in MySQL format
private function sqliteTableStructureEmulation ($data, $table)
{
# Obtain the comments and whether the field is unique by obtaining the original CREATE TABLE SQL
$ddlQuery = "SELECT name, sql FROM sqlite_master WHERE type='table' AND name='{$table}' ORDER BY name;";
$originalCreateTableQuery = $this->_getOneField ($ddlQuery, 'sql');
$lines = explode ("\n", trim ($originalCreateTableQuery));
$comments = array ();
$unique = array ();
foreach ($lines as $id => $line) {
$line = str_replace ('`', '', trim ($line));
if (preg_match ('/^([^\s]+)\s.+--\s(.+)$/', $line, $matches)) {
$comments[$matches[1]] = $matches[2];
}
if (substr_count ($line, 'UNIQUE')) {
$unique[$matches[1]] = true;
}
}
# Map the structure, replacing the SQLite
foreach ($data as $index => $field) {
$data[$index] = array (
'Field' => $field['name'],
'Type' => $field['type'],
'Collation' => NULL, // No support for this in SQLite
'Null' => !$field['notnull'],
'Key' => ($field['pk'] == '1' ? 'PRI' : (isSet ($unique[$field['name']]) ? 'UNI' : false)),
'Default' => $field['dflt_value'],
'Extra' => ($field['type'] == 'INTEGER' && $field['pk'] == '1' ? 'auto_increment' : NULL),
'Privileges' => NULL, // No support for this in SQLite
'Comment' => $comments[$field['name']],
);
}
# Return the data
return $data;
}
# Function to detect values that should not be quoted
private function valueIsFunctionCall ($string)
{
# Normalise the string
$string = strtoupper ($string);
$string = str_replace (' (', '(', $string);
# Detect keywords
if ($string == 'NOW()') {return true;}
if (preg_match ('/^(ST_)?(GEOMCOLL|GEOMETRYCOLLECTION|GEOM|GEOMETRY|LINE|LINESTRING|MLINE|MULTILINESTRING|MPOINT|MULTIPOINT|MPOLY|MULTIPOLYGON|POINT|POLY|POLYGON)FROMTEXT\(/', $string)) {return true;}
// Add more here
# Treat as standard string if not detected
return false;
}
# Function to determine if the data is hierarchical
public function isHierarchical ($database, $table)
{
# Determine if there is a parentId field and return whether it is present
$fields = $this->getFields ($database, $table);
return (isSet ($fields['parentId']));
}
# Function to create a simple type for fields
private function simpleType ($type)
{
# Detect the type and give a simplified description of it
switch (true) {
case preg_match ('/^varchar/', $type):
return 'string';
case preg_match ('/text/', $type):
return 'text';
case preg_match ('/^(float|double|int)/', $type):
return 'numeric';
case preg_match ('/^(enum|set)/', $type):
return 'list';
case preg_match ('/^(date|year)/', $type):
return 'date';
}
# Otherwise pass through the original
return $type;
}
# Function to get the unique field name
public function getUniqueField ($database, $table, $fields = false)
{
# Get the fields if not already supplied
if (!$fields) {$fields = $this->getFields ($database, $table);}
# Loop through to find the unique one
foreach ($fields as $field => $attributes) {
if ($attributes['Key'] == 'PRI') {
return $field;
}
}
# Otherwise return false, indicating no unique field
return false;
}
# Function to get field names
public function getFieldNames ($database, $table, $fields = false, $matchingRegexpNoForwardSlashes = false, $excludeAuto = false)
{
# Get the fields if not already supplied
if (!$fields) {$fields = $this->getFields ($database, $table, false, $matchingRegexpNoForwardSlashes, false, $excludeAuto);}
#!# Bug: $matchingRegexpNoForwardSlashes is not used if $fields is supplied
# Get the array keys of the fields
return array_keys ($fields);
}
# Function to get field descriptions as a simple associative array
public function getHeadings ($database, $table, $fields = false, $useFieldnameIfEmpty = true, $commentsAsHeadings = true, $excludeAuto = false)
{
# Get the fields if not already supplied
if (!$fields) {$fields = $this->getFields ($database, $table, false, false, false, $excludeAuto);}
# Rearrange the data
$headings = array ();
foreach ($fields as $field => $attributes) {
$headings[$field] = ((((empty ($attributes['Comment']) && $useFieldnameIfEmpty)) || !$commentsAsHeadings) ? $field : $attributes['Comment']);
}
# Return the headings
return $headings;
}
# Function to obtain a list of databases on the server
public function getDatabases ($omitReserved = array ('cluster', 'information_schema', 'mysql'))
{
# Get the data
$query = "SHOW DATABASES;";
$data = $this->_getData ($query);
# Sort the list
if ($data) {sort ($data);}
# Rearrange
$databases = array ();
foreach ($data as $index => $attributes) {
if ($omitReserved && in_array ($attributes['Database'], $omitReserved)) {continue;}
$databases[] = $attributes['Database'];
}
# Return the data
return $databases;
}
# Function to return whether a database (or match using %) exists (for which the caller has privileges)
public function databaseExists ($database)
{
# Register this as the public entry point
$this->errorLoggerEntryFunction = __FUNCTION__;
# Hand off to the implementation
$result = $this->_databaseExists ($database);
# Reset any custom error code and text
$this->resetErrorCode ();
# Return the result
return $result;
}
# Implementation for databaseExists
private function _databaseExists ($database)
{
# Get the data; note that this uses getData rather than getOne - getOne would return false if there was more than one match when using %; note that the caller will only be able to see those databases for which it has some kind of privilege, unless it has the global SHOW DATABASES privilege
$query = "SHOW DATABASES LIKE :database;";
$preparedStatementValues = array ('database' => $database);
$data = $this->_getData ($query, false, true, $preparedStatementValues);
# Return boolean result of whether there was a result (or more than one match)
return (bool) $data;
}
# Function to obtain a list of tables in a database
# $matchingRegexp enables filtering, e.g. '/tablename([0-9]+)/' ; if there is a capture (...) within this, then that will be used for the keys
public function getTables ($database, $matchingRegexp = false)
{
# Get the data
$query = "SHOW TABLES FROM `{$database}`;";
$data = $this->_getData ($query);