forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmoodle_database.php
2529 lines (2307 loc) · 103 KB
/
moodle_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
// This file is part of Moodle - http://moodle.org/
//
// Moodle 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 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* Abstract database driver class.
*
* @package core_dml
* @copyright 2008 Petr Skoda (http://skodak.org)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
require_once(__DIR__.'/database_column_info.php');
require_once(__DIR__.'/moodle_recordset.php');
require_once(__DIR__.'/moodle_transaction.php');
/** SQL_PARAMS_NAMED - Bitmask, indicates :name type parameters are supported by db backend. */
define('SQL_PARAMS_NAMED', 1);
/** SQL_PARAMS_QM - Bitmask, indicates ? type parameters are supported by db backend. */
define('SQL_PARAMS_QM', 2);
/** SQL_PARAMS_DOLLAR - Bitmask, indicates $1, $2, ... type parameters are supported by db backend. */
define('SQL_PARAMS_DOLLAR', 4);
/** SQL_QUERY_SELECT - Normal select query, reading only. */
define('SQL_QUERY_SELECT', 1);
/** SQL_QUERY_INSERT - Insert select query, writing. */
define('SQL_QUERY_INSERT', 2);
/** SQL_QUERY_UPDATE - Update select query, writing. */
define('SQL_QUERY_UPDATE', 3);
/** SQL_QUERY_STRUCTURE - Query changing db structure, writing. */
define('SQL_QUERY_STRUCTURE', 4);
/** SQL_QUERY_AUX - Auxiliary query done by driver, setting connection config, getting table info, etc. */
define('SQL_QUERY_AUX', 5);
/**
* Abstract class representing moodle database interface.
* @link http://docs.moodle.org/dev/DML_functions
*
* @package core_dml
* @copyright 2008 Petr Skoda (http://skodak.org)
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
abstract class moodle_database {
/** @var database_manager db manager which allows db structure modifications. */
protected $database_manager;
/** @var moodle_temptables temptables manager to provide cross-db support for temp tables. */
protected $temptables;
/** @var array Cache of table info. */
protected $tables = null;
// db connection options
/** @var string db host name. */
protected $dbhost;
/** @var string db host user. */
protected $dbuser;
/** @var string db host password. */
protected $dbpass;
/** @var string db name. */
protected $dbname;
/** @var string Prefix added to table names. */
protected $prefix;
/** @var array Database or driver specific options, such as sockets or TCP/IP db connections. */
protected $dboptions;
/** @var bool True means non-moodle external database used.*/
protected $external;
/** @var int The database reads (performance counter).*/
protected $reads = 0;
/** @var int The database writes (performance counter).*/
protected $writes = 0;
/** @var float Time queries took to finish, seconds with microseconds.*/
protected $queriestime = 0;
/** @var int Debug level. */
protected $debug = 0;
/** @var string Last used query sql. */
protected $last_sql;
/** @var array Last query parameters. */
protected $last_params;
/** @var int Last query type. */
protected $last_type;
/** @var string Last extra info. */
protected $last_extrainfo;
/** @var float Last time in seconds with millisecond precision. */
protected $last_time;
/** @var bool Flag indicating logging of query in progress. This helps prevent infinite loops. */
private $loggingquery = false;
/** @var bool True if the db is used for db sessions. */
protected $used_for_db_sessions = false;
/** @var array Array containing open transactions. */
private $transactions = array();
/** @var bool Flag used to force rollback of all current transactions. */
private $force_rollback = false;
/** @var string MD5 of settings used for connection. Used by MUC as an identifier. */
private $settingshash;
/** @var cache_application for column info */
protected $metacache;
/** @var bool flag marking database instance as disposed */
protected $disposed;
/**
* @var int internal temporary variable used to fix params. Its used by {@link _fix_sql_params_dollar_callback()}.
*/
private $fix_sql_params_i;
/**
* @var int internal temporary variable used to guarantee unique parameters in each request. Its used by {@link get_in_or_equal()}.
*/
private $inorequaluniqueindex = 1;
/**
* Constructor - Instantiates the database, specifying if it's external (connect to other systems) or not (Moodle DB).
* Note that this affects the decision of whether prefix checks must be performed or not.
* @param bool $external True means that an external database is used.
*/
public function __construct($external=false) {
$this->external = $external;
}
/**
* Destructor - cleans up and flushes everything needed.
*/
public function __destruct() {
$this->dispose();
}
/**
* Detects if all needed PHP stuff are installed for DB connectivity.
* Note: can be used before connect()
* @return mixed True if requirements are met, otherwise a string if something isn't installed.
*/
public abstract function driver_installed();
/**
* Returns database table prefix
* Note: can be used before connect()
* @return string The prefix used in the database.
*/
public function get_prefix() {
return $this->prefix;
}
/**
* Loads and returns a database instance with the specified type and library.
*
* The loaded class is within lib/dml directory and of the form: $type.'_'.$library.'_moodle_database'
*
* @param string $type Database driver's type. (eg: mysqli, pgsql, mssql, sqldrv, oci, etc.)
* @param string $library Database driver's library (native, pdo, etc.)
* @param bool $external True if this is an external database.
* @return moodle_database driver object or null if error, for example of driver object see {@link mysqli_native_moodle_database}
*/
public static function get_driver_instance($type, $library, $external = false) {
global $CFG;
$classname = $type.'_'.$library.'_moodle_database';
$libfile = "$CFG->libdir/dml/$classname.php";
if (!file_exists($libfile)) {
return null;
}
require_once($libfile);
return new $classname($external);
}
/**
* Returns the database vendor.
* Note: can be used before connect()
* @return string The db vendor name, usually the same as db family name.
*/
public function get_dbvendor() {
return $this->get_dbfamily();
}
/**
* Returns the database family type. (This sort of describes the SQL 'dialect')
* Note: can be used before connect()
* @return string The db family name (mysql, postgres, mssql, oracle, etc.)
*/
public abstract function get_dbfamily();
/**
* Returns a more specific database driver type
* Note: can be used before connect()
* @return string The db type mysqli, pgsql, oci, mssql, sqlsrv
*/
protected abstract function get_dbtype();
/**
* Returns the general database library name
* Note: can be used before connect()
* @return string The db library type - pdo, native etc.
*/
protected abstract function get_dblibrary();
/**
* Returns the localised database type name
* Note: can be used before connect()
* @return string
*/
public abstract function get_name();
/**
* Returns the localised database configuration help.
* Note: can be used before connect()
* @return string
*/
public abstract function get_configuration_help();
/**
* Returns the localised database description
* Note: can be used before connect()
* @deprecated since 2.6
* @return string
*/
public function get_configuration_hints() {
debugging('$DB->get_configuration_hints() method is deprecated, use $DB->get_configuration_help() instead');
return $this->get_configuration_help();
}
/**
* Returns the db related part of config.php
* @return stdClass
*/
public function export_dbconfig() {
$cfg = new stdClass();
$cfg->dbtype = $this->get_dbtype();
$cfg->dblibrary = $this->get_dblibrary();
$cfg->dbhost = $this->dbhost;
$cfg->dbname = $this->dbname;
$cfg->dbuser = $this->dbuser;
$cfg->dbpass = $this->dbpass;
$cfg->prefix = $this->prefix;
if ($this->dboptions) {
$cfg->dboptions = $this->dboptions;
}
return $cfg;
}
/**
* Diagnose database and tables, this function is used
* to verify database and driver settings, db engine types, etc.
*
* @return string null means everything ok, string means problem found.
*/
public function diagnose() {
return null;
}
/**
* Connects to the database.
* Must be called before other methods.
* @param string $dbhost The database host.
* @param string $dbuser The database user to connect as.
* @param string $dbpass The password to use when connecting to the database.
* @param string $dbname The name of the database being connected to.
* @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
* @param array $dboptions driver specific options
* @return bool true
* @throws dml_connection_exception if error
*/
public abstract function connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null);
/**
* Store various database settings
* @param string $dbhost The database host.
* @param string $dbuser The database user to connect as.
* @param string $dbpass The password to use when connecting to the database.
* @param string $dbname The name of the database being connected to.
* @param mixed $prefix string means moodle db prefix, false used for external databases where prefix not used
* @param array $dboptions driver specific options
* @return void
*/
protected function store_settings($dbhost, $dbuser, $dbpass, $dbname, $prefix, array $dboptions=null) {
$this->dbhost = $dbhost;
$this->dbuser = $dbuser;
$this->dbpass = $dbpass;
$this->dbname = $dbname;
$this->prefix = $prefix;
$this->dboptions = (array)$dboptions;
}
/**
* Returns a hash for the settings used during connection.
*
* If not already requested it is generated and stored in a private property.
*
* @return string
*/
protected function get_settings_hash() {
if (empty($this->settingshash)) {
$this->settingshash = md5($this->dbhost . $this->dbuser . $this->dbname . $this->prefix);
}
return $this->settingshash;
}
/**
* Attempt to create the database
* @param string $dbhost The database host.
* @param string $dbuser The database user to connect as.
* @param string $dbpass The password to use when connecting to the database.
* @param string $dbname The name of the database being connected to.
* @param array $dboptions An array of optional database options (eg: dbport)
*
* @return bool success True for successful connection. False otherwise.
*/
public function create_database($dbhost, $dbuser, $dbpass, $dbname, array $dboptions=null) {
return false;
}
/**
* Returns transaction trace for debugging purposes.
* @private to be used by core only
* @return array or null if not in transaction.
*/
public function get_transaction_start_backtrace() {
if (!$this->transactions) {
return null;
}
$lowesttransaction = end($this->transactions);
return $lowesttransaction->get_backtrace();
}
/**
* Closes the database connection and releases all resources
* and memory (especially circular memory references).
* Do NOT use connect() again, create a new instance if needed.
* @return void
*/
public function dispose() {
if ($this->disposed) {
return;
}
$this->disposed = true;
if ($this->transactions) {
$this->force_transaction_rollback();
}
if ($this->temptables) {
$this->temptables->dispose();
$this->temptables = null;
}
if ($this->database_manager) {
$this->database_manager->dispose();
$this->database_manager = null;
}
$this->tables = null;
}
/**
* This should be called before each db query.
* @param string $sql The query string.
* @param array $params An array of parameters.
* @param int $type The type of query. ( SQL_QUERY_SELECT | SQL_QUERY_AUX | SQL_QUERY_INSERT | SQL_QUERY_UPDATE | SQL_QUERY_STRUCTURE )
* @param mixed $extrainfo This is here for any driver specific extra information.
* @return void
*/
protected function query_start($sql, array $params=null, $type, $extrainfo=null) {
if ($this->loggingquery) {
return;
}
$this->last_sql = $sql;
$this->last_params = $params;
$this->last_type = $type;
$this->last_extrainfo = $extrainfo;
$this->last_time = microtime(true);
switch ($type) {
case SQL_QUERY_SELECT:
case SQL_QUERY_AUX:
$this->reads++;
break;
case SQL_QUERY_INSERT:
case SQL_QUERY_UPDATE:
case SQL_QUERY_STRUCTURE:
$this->writes++;
}
$this->print_debug($sql, $params);
}
/**
* This should be called immediately after each db query. It does a clean up of resources.
* It also throws exceptions if the sql that ran produced errors.
* @param mixed $result The db specific result obtained from running a query.
* @throws dml_read_exception | dml_write_exception | ddl_change_structure_exception
* @return void
*/
protected function query_end($result) {
if ($this->loggingquery) {
return;
}
if ($result !== false) {
$this->query_log();
// free memory
$this->last_sql = null;
$this->last_params = null;
$this->print_debug_time();
return;
}
// remember current info, log queries may alter it
$type = $this->last_type;
$sql = $this->last_sql;
$params = $this->last_params;
$error = $this->get_last_error();
$this->query_log($error);
switch ($type) {
case SQL_QUERY_SELECT:
case SQL_QUERY_AUX:
throw new dml_read_exception($error, $sql, $params);
case SQL_QUERY_INSERT:
case SQL_QUERY_UPDATE:
throw new dml_write_exception($error, $sql, $params);
case SQL_QUERY_STRUCTURE:
$this->get_manager(); // includes ddl exceptions classes ;-)
throw new ddl_change_structure_exception($error, $sql);
}
}
/**
* This logs the last query based on 'logall', 'logslow' and 'logerrors' options configured via $CFG->dboptions .
* @param string|bool $error or false if not error
* @return void
*/
public function query_log($error=false) {
$logall = !empty($this->dboptions['logall']);
$logslow = !empty($this->dboptions['logslow']) ? $this->dboptions['logslow'] : false;
$logerrors = !empty($this->dboptions['logerrors']);
$iserror = ($error !== false);
$time = $this->query_time();
// Will be shown or not depending on MDL_PERF values rather than in dboptions['log*].
$this->queriestime = $this->queriestime + $time;
if ($logall or ($logslow and ($logslow < ($time+0.00001))) or ($iserror and $logerrors)) {
$this->loggingquery = true;
try {
$backtrace = debug_backtrace();
if ($backtrace) {
//remove query_log()
array_shift($backtrace);
}
if ($backtrace) {
//remove query_end()
array_shift($backtrace);
}
$log = new stdClass();
$log->qtype = $this->last_type;
$log->sqltext = $this->last_sql;
$log->sqlparams = var_export((array)$this->last_params, true);
$log->error = (int)$iserror;
$log->info = $iserror ? $error : null;
$log->backtrace = format_backtrace($backtrace, true);
$log->exectime = $time;
$log->timelogged = time();
$this->insert_record('log_queries', $log);
} catch (Exception $ignored) {
}
$this->loggingquery = false;
}
}
/**
* Returns the time elapsed since the query started.
* @return float Seconds with microseconds
*/
protected function query_time() {
return microtime(true) - $this->last_time;
}
/**
* Returns database server info array
* @return array Array containing 'description' and 'version' at least.
*/
public abstract function get_server_info();
/**
* Returns supported query parameter types
* @return int bitmask of accepted SQL_PARAMS_*
*/
protected abstract function allowed_param_types();
/**
* Returns the last error reported by the database engine.
* @return string The error message.
*/
public abstract function get_last_error();
/**
* Prints sql debug info
* @param string $sql The query which is being debugged.
* @param array $params The query parameters. (optional)
* @param mixed $obj The library specific object. (optional)
* @return void
*/
protected function print_debug($sql, array $params=null, $obj=null) {
if (!$this->get_debug()) {
return;
}
if (CLI_SCRIPT) {
echo "--------------------------------\n";
echo $sql."\n";
if (!is_null($params)) {
echo "[".var_export($params, true)."]\n";
}
echo "--------------------------------\n";
} else {
echo "<hr />\n";
echo s($sql)."\n";
if (!is_null($params)) {
echo "[".s(var_export($params, true))."]\n";
}
echo "<hr />\n";
}
}
/**
* Prints the time a query took to run.
* @return void
*/
protected function print_debug_time() {
if (!$this->get_debug()) {
return;
}
$time = $this->query_time();
$message = "Query took: {$time} seconds.\n";
if (CLI_SCRIPT) {
echo $message;
echo "--------------------------------\n";
} else {
echo s($message);
echo "<hr />\n";
}
}
/**
* Returns the SQL WHERE conditions.
* @param string $table The table name that these conditions will be validated against.
* @param array $conditions The conditions to build the where clause. (must not contain numeric indexes)
* @throws dml_exception
* @return array An array list containing sql 'where' part and 'params'.
*/
protected function where_clause($table, array $conditions=null) {
// We accept nulls in conditions
$conditions = is_null($conditions) ? array() : $conditions;
// Some checks performed under debugging only
if (debugging()) {
$columns = $this->get_columns($table);
if (empty($columns)) {
// no supported columns means most probably table does not exist
throw new dml_exception('ddltablenotexist', $table);
}
foreach ($conditions as $key=>$value) {
if (!isset($columns[$key])) {
$a = new stdClass();
$a->fieldname = $key;
$a->tablename = $table;
throw new dml_exception('ddlfieldnotexist', $a);
}
$column = $columns[$key];
if ($column->meta_type == 'X') {
//ok so the column is a text column. sorry no text columns in the where clause conditions
throw new dml_exception('textconditionsnotallowed', $conditions);
}
}
}
$allowed_types = $this->allowed_param_types();
if (empty($conditions)) {
return array('', array());
}
$where = array();
$params = array();
foreach ($conditions as $key=>$value) {
if (is_int($key)) {
throw new dml_exception('invalidnumkey');
}
if (is_null($value)) {
$where[] = "$key IS NULL";
} else {
if ($allowed_types & SQL_PARAMS_NAMED) {
// Need to verify key names because they can contain, originally,
// spaces and other forbidden chars when using sql_xxx() functions and friends.
$normkey = trim(preg_replace('/[^a-zA-Z0-9_-]/', '_', $key), '-_');
if ($normkey !== $key) {
debugging('Invalid key found in the conditions array.');
}
$where[] = "$key = :$normkey";
$params[$normkey] = $value;
} else {
$where[] = "$key = ?";
$params[] = $value;
}
}
}
$where = implode(" AND ", $where);
return array($where, $params);
}
/**
* Returns SQL WHERE conditions for the ..._list group of methods.
*
* @param string $field the name of a field.
* @param array $values the values field might take.
* @return array An array containing sql 'where' part and 'params'
*/
protected function where_clause_list($field, array $values) {
if (empty($values)) {
return array("1 = 2", array()); // Fake condition, won't return rows ever. MDL-17645
}
// Note: Do not use get_in_or_equal() because it can not deal with bools and nulls.
$params = array();
$select = "";
$values = (array)$values;
foreach ($values as $value) {
if (is_bool($value)) {
$value = (int)$value;
}
if (is_null($value)) {
$select = "$field IS NULL";
} else {
$params[] = $value;
}
}
if ($params) {
if ($select !== "") {
$select = "$select OR ";
}
$count = count($params);
if ($count == 1) {
$select = $select."$field = ?";
} else {
$qs = str_repeat(',?', $count);
$qs = ltrim($qs, ',');
$select = $select."$field IN ($qs)";
}
}
return array($select, $params);
}
/**
* Constructs 'IN()' or '=' sql fragment
* @param mixed $items A single value or array of values for the expression.
* @param int $type Parameter bounding type : SQL_PARAMS_QM or SQL_PARAMS_NAMED.
* @param string $prefix Named parameter placeholder prefix (a unique counter value is appended to each parameter name).
* @param bool $equal True means we want to equate to the constructed expression, false means we don't want to equate to it.
* @param mixed $onemptyitems This defines the behavior when the array of items provided is empty. Defaults to false,
* meaning throw exceptions. Other values will become part of the returned SQL fragment.
* @throws coding_exception | dml_exception
* @return array A list containing the constructed sql fragment and an array of parameters.
*/
public function get_in_or_equal($items, $type=SQL_PARAMS_QM, $prefix='param', $equal=true, $onemptyitems=false) {
// default behavior, throw exception on empty array
if (is_array($items) and empty($items) and $onemptyitems === false) {
throw new coding_exception('moodle_database::get_in_or_equal() does not accept empty arrays');
}
// handle $onemptyitems on empty array of items
if (is_array($items) and empty($items)) {
if (is_null($onemptyitems)) { // Special case, NULL value
$sql = $equal ? ' IS NULL' : ' IS NOT NULL';
return (array($sql, array()));
} else {
$items = array($onemptyitems); // Rest of cases, prepare $items for std processing
}
}
if ($type == SQL_PARAMS_QM) {
if (!is_array($items) or count($items) == 1) {
$sql = $equal ? '= ?' : '<> ?';
$items = (array)$items;
$params = array_values($items);
} else {
if ($equal) {
$sql = 'IN ('.implode(',', array_fill(0, count($items), '?')).')';
} else {
$sql = 'NOT IN ('.implode(',', array_fill(0, count($items), '?')).')';
}
$params = array_values($items);
}
} else if ($type == SQL_PARAMS_NAMED) {
if (empty($prefix)) {
$prefix = 'param';
}
if (!is_array($items)){
$param = $prefix.$this->inorequaluniqueindex++;
$sql = $equal ? "= :$param" : "<> :$param";
$params = array($param=>$items);
} else if (count($items) == 1) {
$param = $prefix.$this->inorequaluniqueindex++;
$sql = $equal ? "= :$param" : "<> :$param";
$item = reset($items);
$params = array($param=>$item);
} else {
$params = array();
$sql = array();
foreach ($items as $item) {
$param = $prefix.$this->inorequaluniqueindex++;
$params[$param] = $item;
$sql[] = ':'.$param;
}
if ($equal) {
$sql = 'IN ('.implode(',', $sql).')';
} else {
$sql = 'NOT IN ('.implode(',', $sql).')';
}
}
} else {
throw new dml_exception('typenotimplement');
}
return array($sql, $params);
}
/**
* Converts short table name {tablename} to the real prefixed table name in given sql.
* @param string $sql The sql to be operated on.
* @return string The sql with tablenames being prefixed with $CFG->prefix
*/
protected function fix_table_names($sql) {
return preg_replace('/\{([a-z][a-z0-9_]*)\}/', $this->prefix.'$1', $sql);
}
/**
* Internal private utitlity function used to fix parameters.
* Used with {@link preg_replace_callback()}
* @param array $match Refer to preg_replace_callback usage for description.
* @return string
*/
private function _fix_sql_params_dollar_callback($match) {
$this->fix_sql_params_i++;
return "\$".$this->fix_sql_params_i;
}
/**
* Detects object parameters and throws exception if found
* @param mixed $value
* @return void
* @throws coding_exception if object detected
*/
protected function detect_objects($value) {
if (is_object($value)) {
throw new coding_exception('Invalid database query parameter value', 'Objects are are not allowed: '.get_class($value));
}
}
/**
* Normalizes sql query parameters and verifies parameters.
* @param string $sql The query or part of it.
* @param array $params The query parameters.
* @return array (sql, params, type of params)
*/
public function fix_sql_params($sql, array $params=null) {
$params = (array)$params; // mke null array if needed
$allowed_types = $this->allowed_param_types();
// convert table names
$sql = $this->fix_table_names($sql);
// cast booleans to 1/0 int and detect forbidden objects
foreach ($params as $key => $value) {
$this->detect_objects($value);
$params[$key] = is_bool($value) ? (int)$value : $value;
}
// NICOLAS C: Fixed regexp for negative backwards look-ahead of double colons. Thanks for Sam Marshall's help
$named_count = preg_match_all('/(?<!:):[a-z][a-z0-9_]*/', $sql, $named_matches); // :: used in pgsql casts
$dollar_count = preg_match_all('/\$[1-9][0-9]*/', $sql, $dollar_matches);
$q_count = substr_count($sql, '?');
$count = 0;
if ($named_count) {
$type = SQL_PARAMS_NAMED;
$count = $named_count;
}
if ($dollar_count) {
if ($count) {
throw new dml_exception('mixedtypesqlparam');
}
$type = SQL_PARAMS_DOLLAR;
$count = $dollar_count;
}
if ($q_count) {
if ($count) {
throw new dml_exception('mixedtypesqlparam');
}
$type = SQL_PARAMS_QM;
$count = $q_count;
}
if (!$count) {
// ignore params
if ($allowed_types & SQL_PARAMS_NAMED) {
return array($sql, array(), SQL_PARAMS_NAMED);
} else if ($allowed_types & SQL_PARAMS_QM) {
return array($sql, array(), SQL_PARAMS_QM);
} else {
return array($sql, array(), SQL_PARAMS_DOLLAR);
}
}
if ($count > count($params)) {
$a = new stdClass;
$a->expected = $count;
$a->actual = count($params);
throw new dml_exception('invalidqueryparam', $a);
}
$target_type = $allowed_types;
if ($type & $allowed_types) { // bitwise AND
if ($count == count($params)) {
if ($type == SQL_PARAMS_QM) {
return array($sql, array_values($params), SQL_PARAMS_QM); // 0-based array required
} else {
//better do the validation of names below
}
}
// needs some fixing or validation - there might be more params than needed
$target_type = $type;
}
if ($type == SQL_PARAMS_NAMED) {
$finalparams = array();
foreach ($named_matches[0] as $key) {
$key = trim($key, ':');
if (!array_key_exists($key, $params)) {
throw new dml_exception('missingkeyinsql', $key, '');
}
if (strlen($key) > 30) {
throw new coding_exception(
"Placeholder names must be 30 characters or shorter. '" .
$key . "' is too long.", $sql);
}
$finalparams[$key] = $params[$key];
}
if ($count != count($finalparams)) {
throw new dml_exception('duplicateparaminsql');
}
if ($target_type & SQL_PARAMS_QM) {
$sql = preg_replace('/(?<!:):[a-z][a-z0-9_]*/', '?', $sql);
return array($sql, array_values($finalparams), SQL_PARAMS_QM); // 0-based required
} else if ($target_type & SQL_PARAMS_NAMED) {
return array($sql, $finalparams, SQL_PARAMS_NAMED);
} else { // $type & SQL_PARAMS_DOLLAR
//lambda-style functions eat memory - we use globals instead :-(
$this->fix_sql_params_i = 0;
$sql = preg_replace_callback('/(?<!:):[a-z][a-z0-9_]*/', array($this, '_fix_sql_params_dollar_callback'), $sql);
return array($sql, array_values($finalparams), SQL_PARAMS_DOLLAR); // 0-based required
}
} else if ($type == SQL_PARAMS_DOLLAR) {
if ($target_type & SQL_PARAMS_DOLLAR) {
return array($sql, array_values($params), SQL_PARAMS_DOLLAR); // 0-based required
} else if ($target_type & SQL_PARAMS_QM) {
$sql = preg_replace('/\$[0-9]+/', '?', $sql);
return array($sql, array_values($params), SQL_PARAMS_QM); // 0-based required
} else { //$target_type & SQL_PARAMS_NAMED
$sql = preg_replace('/\$([0-9]+)/', ':param\\1', $sql);
$finalparams = array();
foreach ($params as $key=>$param) {
$key++;
$finalparams['param'.$key] = $param;
}
return array($sql, $finalparams, SQL_PARAMS_NAMED);
}
} else { // $type == SQL_PARAMS_QM
if (count($params) != $count) {
$params = array_slice($params, 0, $count);
}
if ($target_type & SQL_PARAMS_QM) {
return array($sql, array_values($params), SQL_PARAMS_QM); // 0-based required
} else if ($target_type & SQL_PARAMS_NAMED) {
$finalparams = array();
$pname = 'param0';
$parts = explode('?', $sql);
$sql = array_shift($parts);
foreach ($parts as $part) {
$param = array_shift($params);
$pname++;
$sql .= ':'.$pname.$part;
$finalparams[$pname] = $param;
}
return array($sql, $finalparams, SQL_PARAMS_NAMED);
} else { // $type & SQL_PARAMS_DOLLAR
//lambda-style functions eat memory - we use globals instead :-(
$this->fix_sql_params_i = 0;
$sql = preg_replace_callback('/\?/', array($this, '_fix_sql_params_dollar_callback'), $sql);
return array($sql, array_values($params), SQL_PARAMS_DOLLAR); // 0-based required
}
}
}
/**
* Ensures that limit params are numeric and positive integers, to be passed to the database.
* We explicitly treat null, '' and -1 as 0 in order to provide compatibility with how limit
* values have been passed historically.
*
* @param int $limitfrom Where to start results from
* @param int $limitnum How many results to return
* @return array Normalised limit params in array($limitfrom, $limitnum)
*/
protected function normalise_limit_from_num($limitfrom, $limitnum) {
global $CFG;
// We explicilty treat these cases as 0.
if ($limitfrom === null || $limitfrom === '' || $limitfrom === -1) {
$limitfrom = 0;
}
if ($limitnum === null || $limitnum === '' || $limitnum === -1) {
$limitnum = 0;
}
if ($CFG->debugdeveloper) {
if (!is_numeric($limitfrom)) {
$strvalue = var_export($limitfrom, true);
debugging("Non-numeric limitfrom parameter detected: $strvalue, did you pass the correct arguments?",
DEBUG_DEVELOPER);
} else if ($limitfrom < 0) {
debugging("Negative limitfrom parameter detected: $limitfrom, did you pass the correct arguments?",
DEBUG_DEVELOPER);
}
if (!is_numeric($limitnum)) {
$strvalue = var_export($limitnum, true);
debugging("Non-numeric limitnum parameter detected: $strvalue, did you pass the correct arguments?",
DEBUG_DEVELOPER);
} else if ($limitnum < 0) {
debugging("Negative limitnum parameter detected: $limitnum, did you pass the correct arguments?",
DEBUG_DEVELOPER);
}
}
$limitfrom = (int)$limitfrom;
$limitnum = (int)$limitnum;
$limitfrom = max(0, $limitfrom);
$limitnum = max(0, $limitnum);
return array($limitfrom, $limitnum);
}
/**
* Return tables in database WITHOUT current prefix.
* @param bool $usecache if true, returns list of cached tables.
* @return array of table names in lowercase and without prefix
*/
public abstract function get_tables($usecache=true);
/**
* Return table indexes - everything lowercased.
* @param string $table The table we want to get indexes from.
* @return array An associative array of indexes containing 'unique' flag and 'columns' being indexed
*/
public abstract function get_indexes($table);