-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.class.php
3480 lines (3070 loc) · 100 KB
/
db.class.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
/**
* iDB Class
*
* Version: 1.2
* Started: 02-02-2010
* Updated From WP: 12-04-2016
* Updated: 31-10-2024
*
* Original code from {@link http://php.justinvincent.com Justin Vincent (justin@visunet.ie)}
* and from wordpress {@link http://wordpress.org/}
*
* This is a clone of the wp db class
* https://github.com/WordPress/WordPress/blob/master/wp-includes/wp-db.php
*
* with some added file caching functionality
*
* from wp commit 78d729602e11dd251b434124969be8c6d6922c8f on 04/04/2024
*
* @source https://github.com/giannis/idb
*
*/
/**
* @since 0.71
*/
define( 'EZSQL_VERSION', 'WP1.25' );
/**
* @since 0.71
*/
define( 'OBJECT', 'OBJECT' );
// phpcs:ignore Generic.NamingConventions.UpperCaseConstantName.ConstantNotUpperCase
define( 'object', 'OBJECT' ); // Back compat.
/**
* @since 2.5.0
*/
define( 'OBJECT_K', 'OBJECT_K' );
/**
* @since 0.71
*/
define( 'ARRAY_A', 'ARRAY_A' );
/**
* @since 0.71
*/
define( 'ARRAY_N', 'ARRAY_N' );
/**
* Database access abstraction class.
*
* This class is used to interact with a database without needing to use raw SQL statements.
* By default, uses this class to instantiate the global $idb object, providing
* access to the database.
*
* @link https://github.com/giannis/idb
*
* @since 0.71
*/
#[AllowDynamicProperties]
class idb {
/**
* Whether to show SQL/DB errors.
*
* Default is to show errors if DEBUG evaluates to true.
*
* @since 0.71
*
* @var bool
*/
public $show_errors = false;
/**
* Whether to suppress errors during the DB bootstrapping. Default false.
*
* @since 2.5.0
*
* @var bool
*/
public $suppress_errors = false;
/**
* The error encountered during the last query.
*
* @since 2.5.0
*
* @var string
*/
public $last_error = '';
/**
* The number of queries made.
*
* @since 1.2.0
*
* @var int
*/
public $num_queries = 0;
/**
* Count of rows returned by the last query.
*
* @since 0.71
*
* @var int
*/
public $num_rows = 0;
/**
* Count of rows affected by the last query.
*
* @since 0.71
*
* @var int
*/
public $rows_affected = 0;
/**
* The ID generated for an AUTO_INCREMENT column by the last query (usually INSERT).
*
* @since 0.71
*
* @var int
*/
public $insert_id = 0;
/**
* The last query made.
*
* @since 0.71
*
* @var string
*/
public $last_query;
/**
* Results of the last query.
*
* @since 0.71
*
* @var stdClass[]|null
*/
public $last_result;
/**
* Database query result.
*
* Possible values:
*
* - `mysqli_result` instance for successful SELECT, SHOW, DESCRIBE, or EXPLAIN queries
* - `true` for other query types that were successful
* - `null` if a query is yet to be made or if the result has since been flushed
* - `false` if the query returned an error
*
* @since 0.71
*
* @var mysqli_result|bool|null
*/
protected $result;
/**
* Cached column info, for confidence checking data before inserting.
*
* @since 4.2.0
*
* @var array
*/
protected $col_meta = array();
/**
* Calculated character sets keyed by table name.
*
* @since 4.2.0
*
* @var string[]
*/
protected $table_charset = array();
/**
* Whether text fields in the current query need to be confidence checked.
*
* @since 4.2.0
*
* @var bool
*/
protected $check_current_query = true;
/**
* Flag to ensure we don't run into recursion problems when checking the collation.
*
* @since 4.2.0
*
* @see idb::check_safe_collation()
* @var bool
*/
private $checking_collation = false;
/**
* Saved info on the table column.
*
* @since 0.71
*
* @var array
*/
protected $col_info;
/**
* Log of queries that were executed, for debugging purposes.
*
* @since 1.5.0
* @since 2.5.0 The third element in each query log was added to record the calling functions.
* @since 5.1.0 The fourth element in each query log was added to record the start time.
* @since 5.3.0 The fifth element in each query log was added to record custom data.
*
* @var array[] {
* Array of arrays containing information about queries that were executed.
*
* @type array ...$0 {
* Data for each query.
*
* @type string $0 The query's SQL.
* @type float $1 Total time spent on the query, in seconds.
* @type string $2 Comma-separated list of the calling functions.
* @type float $3 Unix timestamp of the time at the start of the query.
* @type array $4 Custom query data.
* }
* }
*/
public $queries;
/**
* The number of times to retry reconnecting before dying. Default 5.
*
* @since 3.9.0
*
* @see idb::check_connection()
* @var int
*/
protected $reconnect_retries = 5;
/**
* Whether the database queries are ready to start executing.
*
* @since 2.3.2
*
* @var bool
*/
public $ready = false;
/**
* Format specifiers for DB columns. Columns not listed here default to %s. Initialized during load.
*
* Keys are column names, values are format types: 'ID' => '%d'
*
* @since 2.8.0
* @see idb:prepare()
* @see idb:insert()
* @see idb:update()
* @access public
* @var array
*/
public $field_types = array();
/**
* Database table columns charset.
*
* @since 2.2.0
*
* @var string
*/
public $charset;
/**
* Database table columns collate.
*
* @since 2.2.0
*
* @var string
*/
public $collate;
/**
* Database Username.
*
* @since 2.9.0
*
* @var string
*/
protected $dbuser;
/**
* Database Password.
*
* @since 3.1.0
*
* @var string
*/
protected $dbpassword;
/**
* Database Name.
*
* @since 3.1.0
*
* @var string
*/
protected $dbname;
/**
* Database Host.
*
* @since 3.1.0
*
* @var string
*/
protected $dbhost;
/**
* Database handle.
*
* Possible values:
*
* - `mysqli` instance during normal operation
* - `null` if the connection is yet to be made or has been closed
* - `false` if the connection has failed
*
* @since 0.71
*
* @var mysqli|false|null
*/
protected $dbh;
/**
* A textual description of the last query/get_row/get_var call.
*
* @since 3.0.0
*
* @var string
*/
public $func_call;
/**
* Whether MySQL is used as the database engine.
*
* Set in idb::db_connect() to true, by default. This is used when checking
* against the required MySQL version. Normally, a replacement
* database drop-in (db.php) will skip these checks, but setting this to true
* will force the checks to occur.
*
* @since 3.3.0
*
* @var bool
*/
public $is_mysql = null;
/**
* A list of incompatible SQL modes.
*
* @since 3.9.0
*
* @var string[]
*/
protected $incompatible_modes = array(
'NO_ZERO_DATE',
'ONLY_FULL_GROUP_BY',
'STRICT_TRANS_TABLES',
'STRICT_ALL_TABLES',
'TRADITIONAL',
'ANSI',
);
/**
* Backward compatibility, where idb::prepare() has not quoted formatted/argnum placeholders.
*
* This is often used for table/field names (before %i was supported), and sometimes string formatting, e.g.
*
* $idb->prepare( 'WHERE `%1$s` = "%2$s something %3$s" OR %1$s = "%4$-10s"', 'field_1', 'a', 'b', 'c' );
*
* But it's risky, e.g. forgetting to add quotes, resulting in SQL Injection vulnerabilities:
*
* $idb->prepare( 'WHERE (id = %1s) OR (id = %2$s)', $_GET['id'], $_GET['id'] ); // ?id=id
*
* This feature is preserved while plugin authors update their code to use safer approaches:
*
* $_GET['key'] = 'a`b';
*
* $idb->prepare( 'WHERE %1s = %s', $_GET['key'], $_GET['value'] ); // WHERE a`b = 'value'
* $idb->prepare( 'WHERE `%1$s` = "%2$s"', $_GET['key'], $_GET['value'] ); // WHERE `a`b` = "value"
*
* $idb->prepare( 'WHERE %i = %s', $_GET['key'], $_GET['value'] ); // WHERE `a``b` = 'value'
*
* While changing to false will be fine for queries not using formatted/argnum placeholders,
* any remaining cases are most likely going to result in SQL errors (good, in a way):
*
* $idb->prepare( 'WHERE %1$s = "%2$-10s"', 'my_field', 'my_value' );
* true = WHERE my_field = "my_value "
* false = WHERE 'my_field' = "'my_value '"
*
* But there may be some queries that result in an SQL Injection vulnerability:
*
* $idb->prepare( 'WHERE id = %1$s', $_GET['id'] ); // ?id=id
*
* @since 6.2.0
* @var bool
*/
private $allow_unsafe_unquoted_parameters = true;
/**
* Whether to use the mysqli extension over mysql. This is no longer used as the mysql
* extension is no longer supported.
*
* Default true.
*
* @since 3.9.0
* @since 6.4.0 This property was removed.
* @since 6.4.1 This property was reinstated and its default value was changed to true.
* The property is no longer used in core but may be accessed externally.
*
* @var bool
*/
private $use_mysqli = true;
/**
* Whether we've managed to successfully connect at some point.
*
* @since 3.9.0
*
* @var bool
*/
private $has_connected = false;
/**
* Time when the last query was performed.
*
* Only set when `SAVEQUERIES` is defined and truthy.
*
* @since 1.5.0
*
* @var float
*/
public $time_start = null;
/**
* The last SQL error that was encountered.
*
* @since 2.5.0
*
*/
public $error = null;
/**
* Database cache
*
* @since 3.1.0
* @access private
* @var Class
*/
var $cache;
/**
* Set to true to enable cache
*
* @since 1.1
* @access public
* @var boolean
*/
var $use_cache = false;
/**
* Set to disk
*
* @access public
* @var string
*/
var $cache_type = "disk";
/**
* Connects to the database server and selects a database.
*
* Does the actual setting up
* of the class properties and connection to the database.
*
* @since 2.0.8
*
* @link https://core.trac.wordpress.org/ticket/3354
*
* @param string $dbuser Database user.
* @param string $dbpassword Database password.
* @param string $dbname Database name.
* @param string $dbhost Database host.
*/
public function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
if (DEBUG) {
$this->show_errors();
}
$this->dbuser = $dbuser;
$this->dbpassword = $dbpassword;
$this->dbname = $dbname;
$this->dbhost = $dbhost;
$this->init_cache();
$this->db_connect();
}
/**
* Makes private properties readable for backward compatibility.
*
* @since 3.5.0
*
* @param string $name The private member to get, and optionally process.
* @return mixed The private member.
*/
public function __get( $name ) {
if ( 'col_info' === $name ) {
$this->load_col_info();
}
return $this->$name;
}
/**
* Makes private properties settable for backward compatibility.
*
* @since 3.5.0
*
* @param string $name The private member to set.
* @param mixed $value The value to set.
*/
public function __set( $name, $value ) {
$protected_members = array(
'col_meta',
'table_charset',
'check_current_query',
'allow_unsafe_unquoted_parameters',
);
if ( in_array( $name, $protected_members, true ) ) {
return;
}
$this->$name = $value;
}
/**
* Makes private properties check-able for backward compatibility.
*
* @since 3.5.0
*
* @param string $name The private member to check.
* @return bool If the member is set or not.
*/
public function __isset( $name ) {
return isset( $this->$name );
}
/**
* Makes private properties un-settable for backward compatibility.
*
* @since 3.5.0
*
* @param string $name The private member to unset
*/
public function __unset( $name ) {
unset( $this->$name );
}
/**
* Sets $this->charset and $this->collate.
*
* @since 3.1.0
*/
public function init_charset() {
$charset = '';
$collate = '';
if ( function_exists( 'is_multisite' ) && is_multisite() ) {
$charset = 'utf8';
if ( defined( 'DB_COLLATE' ) && DB_COLLATE ) {
$collate = DB_COLLATE;
} else {
$collate = 'utf8_general_ci';
}
} elseif ( defined( 'DB_COLLATE' ) ) {
$collate = DB_COLLATE;
}
if ( defined( 'DB_CHARSET' ) ) {
$charset = DB_CHARSET;
}
$charset_collate = $this->determine_charset( $charset, $collate );
$this->charset = $charset_collate['charset'];
$this->collate = $charset_collate['collate'];
}
/**
* Determines the best charset and collation to use given a charset and collation.
*
* For example, when able, utf8mb4 should be used instead of utf8.
*
* @since 4.6.0
*
* @param string $charset The character set to check.
* @param string $collate The collation to check.
* @return array {
* The most appropriate character set and collation to use.
*
* @type string $charset Character set.
* @type string $collate Collation.
* }
*/
public function determine_charset( $charset, $collate ) {
if ( ( ! ( $this->dbh instanceof mysqli ) ) || empty( $this->dbh ) ) {
return compact( 'charset', 'collate' );
}
if ( 'utf8' === $charset ) {
$charset = 'utf8mb4';
}
if ( 'utf8mb4' === $charset ) {
// _general_ is outdated, so we can upgrade it to _unicode_, instead.
if ( ! $collate || 'utf8_general_ci' === $collate ) {
$collate = 'utf8mb4_unicode_ci';
} else {
$collate = str_replace( 'utf8_', 'utf8mb4_', $collate );
}
}
// _unicode_520_ is a better collation, we should use that when it's available.
if ( $this->has_cap( 'utf8mb4_520' ) && 'utf8mb4_unicode_ci' === $collate ) {
$collate = 'utf8mb4_unicode_520_ci';
}
return compact( 'charset', 'collate' );
}
/**
* Sets the connection's character set.
*
* @since 3.1.0
*
* @param mysqli $dbh The connection returned by `mysqli_connect()`.
* @param string $charset Optional. The character set. Default null.
* @param string $collate Optional. The collation. Default null.
*/
public function set_charset( $dbh, $charset = null, $collate = null ) {
if ( ! isset( $charset ) ) {
$charset = $this->charset;
}
if ( ! isset( $collate ) ) {
$collate = $this->collate;
}
if ( $this->has_cap( 'collation' ) && ! empty( $charset ) ) {
$set_charset_succeeded = true;
if ( function_exists( 'mysqli_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
$set_charset_succeeded = mysqli_set_charset( $dbh, $charset );
}
if ( $set_charset_succeeded ) {
$query = $this->prepare( 'SET NAMES %s', $charset );
if ( ! empty( $collate ) ) {
$query .= $this->prepare( ' COLLATE %s', $collate );
}
mysqli_query( $dbh, $query );
}
}
}
/**
* Changes the current SQL mode, and ensures its compatibility.
*
* If no modes are passed, it will ensure the current MySQL server modes are compatible.
*
* @since 3.9.0
*
* @param array $modes Optional. A list of SQL modes to set. Default empty array.
*/
public function set_sql_mode( $modes = array() ) {
if ( empty( $modes ) ) {
$res = mysqli_query( $this->dbh, 'SELECT @@SESSION.sql_mode' );
if ( empty( $res ) ) {
return;
}
$modes_array = mysqli_fetch_array( $res );
if ( empty( $modes_array[0] ) ) {
return;
}
$modes_str = $modes_array[0];
if ( empty( $modes_str ) ) {
return;
}
$modes = explode( ',', $modes_str );
}
$modes = array_change_key_case( $modes, CASE_UPPER );
/**
* Filters the list of incompatible SQL modes to exclude.
*
* @since 3.9.0
*
* @param array $incompatible_modes An array of incompatible modes.
*/
$incompatible_modes = (array) apply_filters( 'incompatible_sql_modes', $this->incompatible_modes );
foreach ( $modes as $i => $mode ) {
if ( in_array( $mode, $incompatible_modes, true ) ) {
unset( $modes[ $i ] );
}
}
$modes_str = implode( ',', $modes );
mysqli_query( $this->dbh, "SET SESSION sql_mode='$modes_str'" );
}
/**
* Sets the cache
*
* @since 3.1.0
*/
public function init_cache() {
if (defined('DB_CACHE') && DB_CACHE)
$this->use_cache = DB_CACHE;
else
$this->use_cache = false;
if (defined('DB_CACHE_TYPE')) {
$this->cache_type = DB_CACHE_TYPE;
require_once __DIR__ . "/" . $this->cache_type . ".cache.class.php";
$this->cache = new iDB_Cache($this);
}
}
/**
* Clears the cache
*
* @since 1.12
*/
public function clear_cache() {
if (empty($this->cache)) {
return false;
}
return $this->cache->flush();
}
/**
* Selects a database using the current or provided database connection.
*
* The database name will be changed based on the current database connection.
* On failure, the execution will bail and display a DB error.
*
* @since 0.71
*
* @param string $db Database name.
* @param mysqli $dbh Optional. Database connection.
* Defaults to the current database handle.
*/
public function select( $db, $dbh = null ) {
if ( is_null( $dbh ) ) {
$dbh = $this->dbh;
}
$success = mysqli_select_db( $dbh, $db );
if ( ! $success ) {
$this->ready = false;
$this->bail(sprintf('
<h1>Can’t select database</h1>
<p>We were able to connect to the database server (which means your username and password is okay) but not able to select the <code>%1$s</code> database.</p>
<ul>
<li>Are you sure it exists?</li>
<li>Does the user <code>%2$s</code> have permission to use the <code>%1$s</code> database?</li>
<li>On some systems the name of your database is prefixed with your username, so it would be like <code>username_%1$s</code>. Could that be the problem?</li>
</ul>
<p>If you don\'t know how to set up a database you should <strong>contact your host</strong>.</p>', $db, $this->dbuser), 'db_select_fail');
return;
}
}
/**
* Real escape using mysqli_real_escape_string().
*
* @since 2.8.0
*
* @see mysqli_real_escape_string()
*
* @param string $data String to escape.
* @return string Escaped string.
*/
public function _real_escape( $data ) {
if ( ! is_scalar( $data ) ) {
return '';
}
if ( $this->dbh ) {
$escaped = mysqli_real_escape_string( $this->dbh, $data );
} else {
$class = get_class( $this );
trigger_error(sprintf( '%s must set a database connection for use with escaping.', $class ), E_USER_WARNING);
$escaped = addslashes( $data );
}
return $this->add_placeholder_escape( $escaped );
}
/**
* Escapes data. Works on arrays.
*
* @since 2.8.0
*
* @uses idb::_real_escape()
*
* @param string|array $data Data to escape.
* @return string|array Escaped data, in the same type as supplied.
*/
public function _escape( $data ) {
if ( is_array( $data ) ) {
foreach ( $data as $k => $v ) {
if ( is_array( $v ) ) {
$data[ $k ] = $this->_escape( $v );
} else {
$data[ $k ] = $this->_real_escape( $v );
}
}
} else {
$data = $this->_real_escape( $data );
}
return $data;
}
/**
* Escapes content by reference for insertion into the database, for security.
*
* @uses idb::_real_escape()
*
* @since 2.3.0
*
* @param string $data String to escape.
*/
public function escape_by_ref( &$data ) {
if ( ! is_float( $data ) ) {
$data = $this->_real_escape( $data );
}
}
/**
* Quotes an identifier for a MySQL database, e.g. table/field names.
*
* @since 6.2.0
*
* @param string $identifier Identifier to escape.
* @return string Escaped identifier.
*/
public function quote_identifier( $identifier ) {
return '`' . $this->_escape_identifier_value( $identifier ) . '`';
}
/**
* Escapes an identifier value without adding the surrounding quotes.
*
* - Permitted characters in quoted identifiers include the full Unicode
* Basic Multilingual Plane (BMP), except U+0000.
* - To quote the identifier itself, you need to double the character, e.g. `a``b`.
*
* @since 6.2.0
*
* @link https://dev.mysql.com/doc/refman/8.0/en/identifiers.html
*
* @param string $identifier Identifier to escape.
* @return string Escaped identifier.
*/
private function _escape_identifier_value( $identifier ) {
return str_replace( '`', '``', $identifier );
}
/**
* Prepares a SQL query for safe execution.
*
* Uses `sprintf()`-like syntax. The following placeholders can be used in the query string:
*
* - `%d` (integer)
* - `%f` (float)
* - `%s` (string)
* - `%i` (identifier, e.g. table/field names)
*
* All placeholders MUST be left unquoted in the query string. A corresponding argument
* MUST be passed for each placeholder.
*
* Note: There is one exception to the above: for compatibility with old behavior,
* numbered or formatted string placeholders (eg, `%1$s`, `%5s`) will not have quotes
* added by this function, so should be passed with appropriate quotes around them.
*
* Literal percentage signs (`%`) in the query string must be written as `%%`. Percentage wildcards
* (for example, to use in LIKE syntax) must be passed via a substitution argument containing
* the complete LIKE string, these cannot be inserted directly in the query string.
* Also see idb::esc_like().
*
* Arguments may be passed as individual arguments to the method, or as a single array
* containing all arguments. A combination of the two is not supported.
*
* Examples:
*
* $idb->prepare(
* "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d OR `other_field` LIKE %s",
* array( 'foo', 1337, '%bar' )
* );
*
* $idb->prepare(
* "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s",
* 'foo'
* );
*
* @since 2.3.0
* @since 5.3.0 Formalized the existing and already documented `...$args` parameter
* by updating the function signature. The second parameter was changed
* from `$args` to `...$args`.
* @since 6.2.0 Added `%i` for identifiers, e.g. table or field names.
* Check support via `idb::has_cap( 'identifier_placeholders' )`.
* This preserves compatibility with `sprintf()`, as the C version uses
* `%d` and `$i` as a signed integer, whereas PHP only supports `%d`.
*
* @link https://www.php.net/sprintf Description of syntax.
*
* @param string $query Query statement with `sprintf()`-like placeholders.
* @param array|mixed $args The array of variables to substitute into the query's placeholders
* if being called with an array of arguments, or the first variable
* to substitute into the query's placeholders if being called with
* individual arguments.
* @param mixed ...$args Further variables to substitute into the query's placeholders
* if being called with individual arguments.
* @return string|void Sanitized query string, if there is a query to prepare.
*/
public function prepare( $query, ...$args ) {
if ( is_null( $query ) ) {
return;
}
/*
* This is not meant to be foolproof -- but it will catch obviously incorrect usage.
*/
if ( false === strpos( $query, '%' ) ) {
trigger_error(
sprintf(
'The query argument of %s must have a placeholder. Query: %s',
'idb::prepare()',
$query
),
E_USER_WARNING
);
}
/*
* Specify the formatting allowed in a placeholder. The following are allowed:
*
* - Sign specifier, e.g. $+d
* - Numbered placeholders, e.g. %1$s
* - Padding specifier, including custom padding characters, e.g. %05s, %'#5s
* - Alignment specifier, e.g. %05-s
* - Precision specifier, e.g. %.2f
*/
$allowed_format = '(?:[1-9][0-9]*[$])?[-+0-9]*(?: |0|\'.)?[-+0-9]*(?:\.[0-9]+)?';
/*
* If a %s placeholder already has quotes around it, removing the existing quotes
* and re-inserting them ensures the quotes are consistent.
*
* For backward compatibility, this is only applied to %s, and not to placeholders like %1$s,
* which are frequently used in the middle of longer strings, or as table name placeholders.
*/
$query = str_replace( "'%s'", '%s', $query ); // Strip any existing single quotes.
$query = str_replace( '"%s"', '%s', $query ); // Strip any existing double quotes.
// Escape any unescaped percents (i.e. anything unrecognised).
$query = preg_replace( "/%(?:%|$|(?!($allowed_format)?[sdfFi]))/", '%%\\1', $query );
// Extract placeholders from the query.
$split_query = preg_split( "/(^|[^%]|(?:%%)+)(%(?:$allowed_format)?[sdfFi])/", $query, -1, PREG_SPLIT_DELIM_CAPTURE );
$split_query_count = count( $split_query );
/*
* Split always returns with 1 value before the first placeholder (even with $query = "%s"),