forked from Automattic/HyperDB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.php
1693 lines (1397 loc) · 50 KB
/
db.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
/*
Plugin Name: LudacrisDB
Plugin URI: https://github.com/justinmaurerdotdev/HyperDB
Description: An advanced database class that supports replication, failover, load balancing, and partitioning.
Author: Automattic, Justin Maurer
License: GPLv2 or later
Version: 1.10
*/
// phpcs:disable Squiz.PHP.CommentedOutCode.Found
/** This file should be installed at ABSPATH/wp-content/db.php **/
/**
* @var wpdb|true
* @psalm-suppress InvalidGlobal
*/
global $wpdb;
/** Load the wpdb class while preventing instantiation **/
$wpdb = true; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
if ( defined( 'WPDB_PATH' ) ) {
/** @psalm-suppress UnresolvableInclude */
require_once WPDB_PATH;
} elseif ( file_exists( ABSPATH . WPINC . '/class-wpdb.php' ) ) {
// WP 6.1 and later.
/** @psalm-suppress UnresolvableInclude */
require_once ABSPATH . WPINC . '/class-wpdb.php';
} else {
// WP 6.0 and earlier.
/** @psalm-suppress UnresolvableInclude */
require_once ABSPATH . WPINC . '/wp-db.php';
}
// phpcs:ignore Generic.CodeAnalysis.EmptyStatement.DetectedIf
if ( defined( 'DB_CONFIG_FILE' ) && file_exists( DB_CONFIG_FILE ) ) {
/** The config file was defined earlier. **/
} elseif ( file_exists( ABSPATH . 'db-config.php' ) ) {
/** The config file resides in ABSPATH. **/
define( 'DB_CONFIG_FILE', ABSPATH . 'db-config.php' );
} elseif ( file_exists( dirname( ABSPATH ) . '/db-config.php' ) && ! file_exists( dirname( ABSPATH ) . '/wp-settings.php' ) ) {
/** The config file resides one level above ABSPATH but is not part of another install. **/
define( 'DB_CONFIG_FILE', dirname( ABSPATH ) . '/db-config.php' );
} else {
/** Lacking a config file, revert to the standard database class. **/
$wpdb = new wpdb( DB_USER, DB_PASSWORD, DB_NAME, DB_HOST ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
return;
}
/**
* Common definitions
*/
define( 'HYPERDB_LAG_OK', 1 );
define( 'HYPERDB_LAG_BEHIND', 2 );
define( 'HYPERDB_LAG_UNKNOWN', 3 );
define( 'HYPERDB_ER_OPTION_PREVENTS_STATEMENT', 1290 ); // The MySQL server is running with the %s option so it cannot execute this statement
define( 'HYPERDB_CONNNECTION_ERROR', 2002 ); // Can't connect to local MySQL server through socket '%s' (%d)
define( 'HYPERDB_CONN_HOST_ERROR', 2003 ); // Can't connect to MySQL server on '%s' (%d)
define( 'HYPERDB_SERVER_GONE_ERROR', 2006 ); // MySQL server has gone away
// phpcs:ignore PEAR.NamingConventions.ValidClassName.StartWithCapital
class hyperdb extends wpdb {
/**
* The last table that was queried
* @var string
*/
public $last_table;
/**
* After any SQL_CALC_FOUND_ROWS query, the query "SELECT FOUND_ROWS()"
* is sent and the mysql result resource stored here. The next query
* for FOUND_ROWS() will retrieve this. We do this to prevent any
* intervening queries from making FOUND_ROWS() inaccessible. You may
* prevent this by adding "NO_SELECT_FOUND_ROWS" in a comment.
* @var resource
*/
public $last_found_rows_result;
/**
* Whether to store queries in an array. Useful for debugging and profiling.
* @var bool
*/
public $save_queries = false;
/**
* The current mysql link resource
* @var mysqli|resource|false|null
*/
protected $dbh;
/**
* Associative array (dbhname => dbh) for established mysql connections
* @var array
*/
public $dbhs;
/**
* The multi-dimensional array of datasets and servers
* @var array
*/
public $hyper_servers = array();
/**
* Optional directory of tables and their datasets
* @var array
*/
public $hyper_tables = array();
/**
* Optional directory of callbacks to determine datasets from queries
* @var array
*/
public $hyper_callbacks = array();
/**
* Custom callback to save debug info in $this->queries
* @var callable
*/
public $save_query_callback = null;
/**
* Whether to use persistent connections
* @var bool
*/
public $persistent = false;
/**
* The maximum number of db links to keep open. The least-recently used
* link will be closed when the number of links exceeds this.
* @var int
*/
public $max_connections = 10;
/**
* Whether to check with fsockopen prior to connecting to mysql.
* @var bool
*/
public $check_tcp_responsiveness = true;
/**
* Minimum number of connections to try before bailing
* @var int
*/
public $min_tries = 3;
/**
* Send Reads To Masters. This disables slave connections while true.
* Otherwise it is an array of written tables.
* @var array
*/
public $srtm = array();
/**
* The log of db connections made and the time each one took
* @var array
*/
public $db_connections = array();
/**
* The list of unclosed connections sorted by LRU
*/
public $open_connections = array();
/**
* The last server used and the database name selected
* @var array
*/
public $last_used_server;
/**
* Lookup array (dbhname => (server, db name) ) for re-selecting the db
* when a link is re-used.
* @var array
*/
public $used_servers = array();
/**
* Lookup array (dbhname => int) of the number of unique servers in the config
* @var array
*/
public $unique_servers = array();
/**
* A list of servers we found to be read-only
* @var array
*/
public $read_only_servers = array();
/**
* A list of servers' state
* @var array
*/
public $servers_state = array();
/**
* Whether to save debug_backtrace in save_query_callback. You may wish
* to disable this, e.g. when tracing out-of-memory problems.
*/
public $save_backtrace = true;
/**
* Maximum lag in seconds. Set null to disable. Requires callbacks.
* @var integer
*/
public $default_lag_threshold = null;
/**
* Lookup array (dbhname => host:port)
* @var array
*/
public $dbh2host = array();
/**
* Keeps track of the dbhname usage and errors.
*/
public $dbhname_heartbeats = array();
/**
* Counter for how many queries have failed during the life of the $wpdb object
*/
public $num_failed_queries = 0;
/**
* Gets ready to make database connections
* @param array db class vars
*/
public function __construct( $args = null ) {
if ( is_array( $args ) ) {
foreach ( get_class_vars( __CLASS__ ) as $var => $value ) {
if ( isset( $args[ $var ] ) ) {
$this->$var = $args[ $var ];
}
}
}
$this->use_mysqli = $this->should_use_mysqli();
if ( $this->use_mysqli ) {
mysqli_report( MYSQLI_REPORT_OFF );
}
$this->init_charset();
}
/**
* Add the connection parameters for a database
*/
public function add_database( $db ) {
extract( $db, EXTR_SKIP );
if ( ! isset( $dataset ) ) {
$dataset = 'global';
}
if ( ! isset( $read ) ) {
$read = 1;
}
if ( ! isset( $write ) ) {
$write = 1;
}
unset( $db['dataset'] );
if ( $read ) {
$this->hyper_servers[ $dataset ]['read'][ $read ][] = $db;
}
if ( $write ) {
$this->hyper_servers[ $dataset ]['write'][ $write ][] = $db;
}
}
/**
* Specify the dateset where a table is found
*/
public function add_table( $dataset, $table ) {
$this->hyper_tables[ $table ] = $dataset;
}
/**
* Add a callback to a group of callbacks.
* The default group is 'dataset', used to examine
* queries and determine dataset.
*/
public function add_callback( $callback, $group = 'dataset' ) {
$this->hyper_callbacks[ $group ][] = $callback;
}
/**
* Find the table to be used for query routing. Falls back on
* core get_table_from_query after checking for special cases.
* @param string query
* @return string table
*/
public function get_table_from_query( $q ) {
// Remove characters that can legally trail the table name
$q = rtrim( $q, ';/-#' );
// allow (select...) union [...] style queries. Use the first queries table name.
$q = ltrim( $q, "\t (" );
// Strip everything between parentheses except nested
// selects and use only 1500 chars of the query
$q = preg_replace( '/\((?!\s*select)[^(]*?\)/is', '()', substr( $q, 0, 1500 ) );
// SELECT FOUND_ROWS() refers to the previous SELECT query
if ( preg_match( '/^\s*SELECT.*?\s+FOUND_ROWS\(\)/is', $q ) ) {
return $this->last_table;
}
// SELECT FROM information_schema.* WHERE TABLE_NAME = 'wp_12345_foo'
if ( preg_match('/^\s*'
. 'SELECT.*?\s+FROM\s+`?information_schema`?\.'
. '.*\s+TABLE_NAME\s*=\s*["\']([\w-]+)["\']/is', $q, $maybe) ) {
return $maybe[1];
}
// Transaction support, requires a table hint via comment: IN_TABLE=table_name
if ( preg_match('/^\s*'
. '(?:START\s+TRANSACTION|COMMIT|ROLLBACK)\s*\/[*]\s*IN_TABLE\s*=\s*'
. "'?([\w-]+)'?/is", $q, $maybe) ) {
return $maybe[1];
}
$this->last_table = parent::get_table_from_query( $q );
return $this->last_table;
}
/**
* Determine the likelihood that this query could alter anything
* @param string query
* @return bool
*/
public function is_write_query( $q ) {
// Quick and dirty: only SELECT statements are considered read-only.
$q = ltrim( $q, "\r\n\t (" );
return (
! preg_match( '/^(?:SELECT|SHOW|DESCRIBE|DESC|EXPLAIN)\s/i', $q )
|| preg_match( '/(\sFOR UPDATE)/i', $q )
);
}
/**
* Set a flag to prevent reading from slaves which might be lagging after a write
*/
public function send_reads_to_masters() {
$this->srtm = true;
}
/**
* Callbacks are executed in the order in which they are registered until one
* of them returns something other than null.
*/
public function run_callbacks( $group, $args = null ) {
if ( ! isset( $this->hyper_callbacks[ $group ] ) || ! is_array( $this->hyper_callbacks[ $group ] ) ) {
return null;
}
if ( ! isset( $args ) ) {
$args = array( $this );
} elseif ( is_array( $args ) ) {
// 8.0+ changed the behavior of call_user_func_array(), associative arrays would turn into named attributes
// Here we discard the keys and hope for the best
$args = array_values( $args );
$args[] = $this;
} else {
$args = array( $args, $this );
}
foreach ( $this->hyper_callbacks[ $group ] as $func ) {
$result = call_user_func_array( $func, $args );
if ( isset( $result ) ) {
return $result;
}
}
}
/**
* Figure out which database server should handle the query, and connect to it.
* @param string query
* @return resource mysql database connection
*/
public function db_connect( $query = '' ) {
if ( empty( $query ) ) {
return false;
}
$this->table = $this->get_table_from_query( $query );
if ( isset( $this->hyper_tables[ $this->table ] ) ) {
$dataset = $this->hyper_tables[ $this->table ];
$this->callback_result = null;
} else {
$this->callback_result = $this->run_callbacks( 'dataset', $query );
if ( null !== $this->callback_result ) {
if ( is_array( $this->callback_result ) ) {
extract( $this->callback_result, EXTR_OVERWRITE );
} else {
$dataset = $this->callback_result;
}
}
}
if ( ! isset( $dataset ) ) {
$dataset = 'global';
}
if ( ! $dataset ) {
return $this->log_and_bail( "Unable to determine dataset (for table: $this->table)" );
} else {
$this->dataset = $dataset;
}
$this->run_callbacks( 'dataset_found', $dataset );
if ( empty( $this->hyper_servers ) ) {
if ( $this->is_mysql_connection( $this->dbh ) ) {
return $this->dbh;
}
if (
! defined( 'DB_HOST' )
|| ! defined( 'DB_USER' )
|| ! defined( 'DB_PASSWORD' )
|| ! defined( 'DB_NAME' ) ) {
return $this->log_and_bail( 'We were unable to query because there was no database defined' );
}
$this->dbh = $this->ex_mysql_connect( DB_HOST, DB_USER, DB_PASSWORD, $this->persistent );
if ( ! $this->is_mysql_connection( $this->dbh ) ) {
return $this->log_and_bail( 'We were unable to connect to the database. (DB_HOST)' );
}
if ( ! $this->ex_mysql_select_db( DB_NAME, $this->dbh ) ) {
return $this->log_and_bail( 'We were unable to select the database' );
}
if ( ! empty( $this->charset ) ) {
$collation_query = "SET NAMES '$this->charset'";
if ( ! empty( $this->collate ) ) {
$collation_query .= " COLLATE '$this->collate'";
}
$this->ex_mysql_query( $collation_query, $this->dbh );
}
return $this->dbh;
}
// Determine whether the query must be sent to the master (a writable server)
if ( ! empty( $use_master ) || true === $this->srtm || isset( $this->srtm[ $this->table ] ) ) {
$use_master = true;
} elseif ( $this->is_write_query( $query ) ) {
$use_master = true;
if ( is_array( $this->srtm ) ) {
$this->srtm[ $this->table ] = true;
}
} elseif ( ! isset( $use_master ) && is_array( $this->srtm ) && ! empty( $this->srtm ) ) {
// Detect queries that have a join in the srtm array.
$use_master = false;
$query_match = substr( $query, 0, 1000 );
foreach ( $this->srtm as $key => $value ) {
if ( false !== stripos( $query_match, $key ) ) {
$use_master = true;
break;
}
}
} else {
$use_master = false;
}
if ( $use_master ) {
$dbhname = $dataset . '__w';
$this->dbhname = $dbhname;
$operation = 'write';
} else {
$dbhname = $dataset . '__r';
$this->dbhname = $dbhname;
$operation = 'read';
}
// Try to reuse an existing connection
while ( isset( $this->dbhs[ $dbhname ] ) && $this->is_mysql_connection( $this->dbhs[ $dbhname ] ) ) {
// Find the connection for incrementing counters
foreach ( array_keys( $this->db_connections ) as $i ) {
if ( $this->db_connections[ $i ]['dbhname'] == $dbhname ) {
$conn =& $this->db_connections[ $i ];
}
}
if ( isset( $server['name'] ) ) {
$name = $server['name'];
// A callback has specified a database name so it's possible the existing connection selected a different one.
if ( $name != $this->used_servers[ $dbhname ]['name'] ) {
if ( ! $this->ex_mysql_select_db( $name, $this->dbhs[ $dbhname ] ) ) {
// this can happen when the user varies and lacks permission on the $name database
if ( isset( $conn['disconnect (select failed)'] ) ) {
++$conn['disconnect (select failed)'];
} else {
$conn['disconnect (select failed)'] = 1;
}
$this->disconnect( $dbhname );
break;
}
$this->used_servers[ $dbhname ]['name'] = $name;
}
} else {
$name = $this->used_servers[ $dbhname ]['name'];
}
$this->current_host = $this->dbh2host[ $dbhname ];
// Keep this connection at the top of the stack to prevent disconnecting frequently-used connections
$k = array_search( $dbhname, $this->open_connections );
if ( $k ) {
unset( $this->open_connections[ $k ] );
$this->open_connections[] = $dbhname;
}
$this->last_used_server = $this->used_servers[ $dbhname ];
$this->last_connection = compact( 'dbhname', 'name' );
if ( $this->should_mysql_ping() && ! $this->ex_mysql_ping( $this->dbhs[ $dbhname ] ) ) {
if ( isset( $conn['disconnect (ping failed)'] ) ) {
++$conn['disconnect (ping failed)'];
} else {
$conn['disconnect (ping failed)'] = 1;
}
$this->disconnect( $dbhname );
break;
}
if ( isset( $conn['queries'] ) ) {
++$conn['queries'];
} else {
$conn['queries'] = 1;
}
return $this->dbhs[ $dbhname ];
}
if ( $use_master && defined( 'MASTER_DB_DEAD' ) ) {
return $this->bail( "We're updating the database, please try back in 5 minutes. If you are posting to your blog please hit the refresh button on your browser in a few minutes to post the data again. It will be posted as soon as the database is back online again." );
}
if ( empty( $this->hyper_servers[ $dataset ][ $operation ] ) ) {
return $this->log_and_bail( "No databases available with $this->table ($dataset)" );
}
// Put the groups in order by priority
ksort( $this->hyper_servers[ $dataset ][ $operation ] );
// Make a list of at least $this->min_tries connections to try, repeating as necessary.
$servers = array();
$this->unique_servers[ $dbhname ] = array();
do {
foreach ( $this->hyper_servers[ $dataset ][ $operation ] as $group => $items ) {
$keys = array_keys( $items );
shuffle( $keys );
foreach ( $keys as $key ) {
$servers[] = compact( 'group', 'key' );
if ( ! isset( $this->unique_servers[ $dbhname ][ $items[ $key ]['host'] ] ) ) {
$this->unique_servers[ $dbhname ][ $items[ $key ]['host'] ] = true;
}
}
}
if ( 0 === count( $this->unique_servers[ $dbhname ] ) ) {
return $this->log_and_bail( "No database servers were found to match the query ($this->table, $dataset)" );
}
} while ( count( $servers ) < $this->min_tries ); // phpcs:ignore Squiz.PHP.DisallowSizeFunctionsInLoops.Found
// Connect to a database server
do {
$unique_lagged_slaves = array();
$unique_readonly_masters = array();
$success = false;
$tries_remaining = count( $servers );
foreach ( $servers as $group_key ) {
--$tries_remaining;
// Variables: $group, $key
extract( $group_key, EXTR_OVERWRITE );
// Variables: $host, $user, $password, $name, $read, $write [, $lag_threshold, $timeout ]
extract( $this->hyper_servers[ $dataset ][ $operation ][ $group ][ $key ], EXTR_OVERWRITE );
$port = null;
// Split host:port into $host and $port
if ( strpos( $host, ':' ) ) {
list($host, $port) = explode( ':', $host );
}
// Overlay $server if it was extracted from a callback
if ( isset( $server ) && is_array( $server ) ) {
extract( $server, EXTR_OVERWRITE );
}
// Split again in case $server had host:port
if ( strpos( $host, ':' ) ) {
list($host, $port) = explode( ':', $host );
}
// Make sure there's always a port number
if ( empty( $port ) ) {
$port = 3306;
}
// Use a default timeout of 200ms
if ( ! isset( $timeout ) ) {
$timeout = 0.2;
}
// Get the minimum group here, in case $server rewrites it
if ( ! isset( $min_group ) || $min_group > $group ) {
$min_group = $group;
}
// If a master is read-only and we have others which might not be RO, go to the next one
if ( $use_master && $this->unique_servers[ $dbhname ] > 1 && empty( $ignore_server_read_only ) ) {
if ( count( $unique_readonly_masters ) == count( $this->unique_servers[ $dbhname ] ) ) {
$ignore_server_read_only = true; // All are read-only, ignore RO and retry
continue 2;
}
if ( $this->is_server_marked_read_only( $host, $port ) ) {
$unique_readonly_masters[ "$host:$port" ] = true;
continue;
}
}
// Can be used by the lag callbacks
$this->lag_cache_key = "$host:$port";
$this->lag_threshold = isset( $lag_threshold ) ? $lag_threshold : $this->default_lag_threshold;
// Check for a lagged slave, if applicable
if ( ! $use_master && ! $write && ! isset( $ignore_slave_lag )
&& isset( $this->lag_threshold ) && ! isset( $server['host'] )
// phpcs:ignore Squiz.PHP.DisallowMultipleAssignments.FoundInControlStructure
&& ( $lagged_status = $this->get_lag_cache() ) === HYPERDB_LAG_BEHIND
) {
// If it is the last lagged slave and it is with the best preference we will ignore its lag
if ( ! isset( $unique_lagged_slaves[ "$host:$port" ] )
&& count( $unique_lagged_slaves ) + 1 == count( $this->unique_servers[ $dbhname ] )
&& $group == $min_group ) {
$this->lag_threshold = null;
} else {
$unique_lagged_slaves[ "$host:$port" ] = $this->lag;
continue;
}
}
$this->timer_start();
// Connect if necessary or possible
$server_state = null;
if ( $use_master || ! $tries_remaining ||
// phpcs:ignore Squiz.PHP.DisallowMultipleAssignments.FoundInControlStructure
'up' === ( $server_state = $this->get_server_state( $host, $port, $dbhname, $timeout ) ) ) {
$this->set_connect_timeout( 'pre_connect', $use_master, $tries_remaining );
$this->dbhs[ $dbhname ] = $this->ex_mysql_connect( "$host:$port", $user, $password, $this->persistent );
$this->set_connect_timeout( 'post_connect', $use_master, $tries_remaining );
} else {
$this->dbhs[ $dbhname ] = false;
}
$elapsed = $this->timer_stop();
if ( $this->is_mysql_connection( $this->dbhs[ $dbhname ] ) ) {
/**
* If we care about lag, disconnect lagged slaves and try to find others.
* We don't disconnect if it is the last lagged slave and it is with the best preference.
*/
if ( ! $use_master && ! $write && ! isset( $ignore_slave_lag )
&& isset( $this->lag_threshold ) && ! isset( $server['host'] )
&& HYPERDB_LAG_OK !== $lagged_status
&& ( $lagged_status = $this->get_lag() ) === HYPERDB_LAG_BEHIND // phpcs:ignore Squiz.PHP.DisallowMultipleAssignments.FoundInControlStructure
&& ! (
! isset( $unique_lagged_slaves[ "$host:$port" ] )
&& count( $unique_lagged_slaves ) + 1 === count( $this->unique_servers[ $dbhname ] )
&& $group == $min_group
)
) {
$success = false;
$unique_lagged_slaves[ "$host:$port" ] = $this->lag;
$this->disconnect( $dbhname );
$this->dbhs[ $dbhname ] = false;
$msg = "Replication lag of {$this->lag}s on $host:$port ($dbhname)";
$this->print_error( $msg );
continue;
} elseif ( $this->ex_mysql_select_db( $name, $this->dbhs[ $dbhname ] ) ) {
$success = true;
$this->current_host = "$host:$port";
$this->dbh2host[ $dbhname ] = "$host:$port";
$queries = 1;
$lag = isset( $this->lag ) ? $this->lag : 0;
$this->last_connection = compact( 'dbhname', 'host', 'port', 'user', 'name', 'server_state', 'elapsed', 'success', 'queries', 'lag' );
$this->db_connections[] = $this->last_connection;
$this->open_connections[] = $dbhname;
break;
}
}
if ( 'down' == $server_state ) {
continue; // don't flood the logs if already down
}
$errno = $this->ex_mysql_errno();
if ( ( HYPERDB_CONN_HOST_ERROR == $errno || HYPERDB_CONNNECTION_ERROR == $errno ) &&
( 'up' == $server_state || ! $tries_remaining ) ) {
$this->mark_server_as_down( $host, $port );
$server_state = 'down';
}
$referrer = '';
if ( ! empty( $_SERVER['HTTP_HOST'] ) ) {
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- print_error() will sanitize the entire message
$referrer .= (string) $_SERVER['HTTP_HOST'];
}
if ( ! empty( $_SERVER['REQUEST_URI'] ) ) {
// phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- print_error() will sanitize the entire message
$referrer .= (string) $_SERVER['REQUEST_URI'];
}
if ( ! isset( $tcp ) ) {
$tcp = '';
}
if ( ! isset( $server ) ) {
$server = '';
}
$success = false;
$this->last_connection = compact( 'dbhname', 'host', 'port', 'user', 'name', 'tcp', 'elapsed', 'success' );
$this->db_connections[] = $this->last_connection;
$msg = date( 'Y-m-d H:i:s' ) . " Can't select $dbhname - \n"; // phpcs:ignore WordPress.DateTime.RestrictedFunctions.date_date
$msg .= "'referrer' => '{$referrer}',\n";
$msg .= "'server' => {$server},\n";
$msg .= "'host' => {$host},\n";
$msg .= "'error' => " . $this->ex_mysql_error() . ",\n";
$msg .= "'errno' => " . $this->ex_mysql_errno() . ",\n";
$msg .= "'server_state' => $server_state\n";
$msg .= "'lagged_status' => " . ( isset( $lagged_status ) ? $lagged_status : HYPERDB_LAG_UNKNOWN );
$this->print_error( $msg );
}
if ( ! $success || ! isset( $this->dbhs[ $dbhname ] ) || ! $this->is_mysql_connection( $this->dbhs[ $dbhname ] ) ) {
if ( ! isset( $ignore_slave_lag ) && count( $unique_lagged_slaves ) ) {
// Lagged slaves were not used. Ignore the lag for this connection attempt and retry.
$ignore_slave_lag = true;
continue;
}
$error_details = array(
'host' => $host,
'port' => $port,
'operation' => $operation,
'table' => $this->table,
'dataset' => $dataset,
'dbhname' => $dbhname,
);
$this->run_callbacks( 'db_connection_error', $error_details );
return $this->bail( "Unable to connect to $host:$port to $operation table '$this->table' ($dataset)" );
}
break;
} while ( true );
if ( ! isset( $charset ) ) {
$charset = null;
}
if ( ! isset( $collate ) ) {
$collate = null;
}
$this->set_charset( $this->dbhs[ $dbhname ], $charset, $collate );
$this->dbh = $this->dbhs[ $dbhname ]; // needed by $wpdb->_real_escape()
$this->last_used_server = compact( 'host', 'user', 'name', 'read', 'write' );
$this->used_servers[ $dbhname ] = $this->last_used_server;
// phpcs:ignore Squiz.PHP.DisallowSizeFunctionsInLoops.Found
while ( ! $this->persistent && count( $this->open_connections ) > $this->max_connections ) {
$oldest_connection = array_shift( $this->open_connections );
if ( $this->dbhs[ $oldest_connection ] != $this->dbhs[ $dbhname ] ) {
$this->disconnect( $oldest_connection );
}
}
return $this->dbhs[ $dbhname ];
}
/**
* Sets the connection's character set.
* @param resource $dbh The resource given by ex_mysql_connect
* @param string $charset The character set (optional)
* @param string $collate The collation (optional)
*/
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', $dbh ) || empty( $charset ) ) {
return;
}
if ( ! in_array( strtolower( $charset ), array( 'utf8', 'utf8mb4', 'latin1' ) ) ) {
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
wp_die( sprintf( "%s charset isn't supported in HyperDB for security reasons", htmlspecialchars( $charset ) ) );
}
if ( $this->is_mysql_set_charset_callable() && $this->has_cap( 'set_charset', $dbh ) ) {
$this->ex_mysql_set_charset( $charset, $dbh );
$this->real_escape = true;
} else {
$query = $this->prepare( 'SET NAMES %s', $charset );
if ( ! empty( $collate ) ) {
$query .= $this->prepare( ' COLLATE %s', $collate );
}
$this->ex_mysql_query( $query, $dbh );
}
}
/**
* Force addslashes() for the escapes.
*
* HyperDB makes connections when a query is made
* which is why we can't use mysql_real_escape_string() for escapes.
* This is also the reason why we don't allow certain charsets. See set_charset().
*/
public function _real_escape( $string ) { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore
$escaped = addslashes( (string) $string );
if ( method_exists( get_parent_class( $this ), 'add_placeholder_escape' ) ) {
$escaped = $this->add_placeholder_escape( $escaped );
}
return $escaped;
}
/**
* Disconnect and remove connection from open connections list
* @param string $tdbhname
*/
public function disconnect( $dbhname ) {
$k = array_search( $dbhname, $this->open_connections );
if ( false !== $k ) {
unset( $this->open_connections[ $k ] );
}
foreach ( array_keys( $this->db_connections ) as $i ) {
if ( $this->db_connections[ $i ]['dbhname'] == $dbhname ) {
unset( $this->db_connections[ $i ] );
}
}
if ( $this->is_mysql_connection( $this->dbhs[ $dbhname ] ) ) {
$this->ex_mysql_close( $this->dbhs[ $dbhname ] );
}
unset( $this->dbhs[ $dbhname ] );
}
/**
* Kill cached query results
*/
public function flush() {
$this->last_error = '';
$this->last_errno = 0;
$this->num_rows = 0;
parent::flush();
}
/**
* Basic query. See docs for more details.
* @param string $query
* @return int number of rows
*/
public function query( $query ) {
// some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
if ( function_exists( 'apply_filters' ) ) {
$query = apply_filters( 'query', $query );
}
// initialise return
$return_val = 0;
$this->flush();
// Log how the function was called
$this->func_call = "\$db->query(\"$query\")";
// Keep track of the last query for debug..
$this->last_query = $query;
if ( preg_match( '/^\s*SELECT\s+FOUND_ROWS(\s*)/i', $query ) ) {
if ( $this->is_mysql_result( $this->last_found_rows_result ) ) {
$this->result = $this->last_found_rows_result;
$this->last_found_rows_result = null;
$elapsed = 0;
} else {
$this->print_error( 'Attempted SELECT FOUND_ROWS() without prior SQL_CALC_FOUND_ROWS.' );
return false;
}
} else {
$this->dbh = $this->db_connect( $query );
if ( ! $this->is_mysql_connection( $this->dbh ) ) {
$this->check_current_query = true;
$this->last_error = 'Database connection failed';
$this->num_failed_queries++;
if ( function_exists( 'do_action' ) ) {
do_action( 'sql_query_log', $query, false, $this->last_error );
}
return false;
}
$query_comment = $this->run_callbacks( 'get_query_comment', $query );
if ( ! empty( $query_comment ) ) {
$query = rtrim( $query, ";\t \n\r" ) . ' /* ' . $query_comment . ' */';
}
// If we're writing to the database, make sure the query will write safely.
if ( $this->check_current_query && method_exists( $this, 'check_ascii' ) && ! $this->check_ascii( $query ) ) {
$stripped_query = $this->strip_invalid_text_from_query( $query );
if ( $stripped_query !== $query ) {
$this->insert_id = 0;
$this->last_error = 'Invalid query';
$this->num_failed_queries++;
if ( function_exists( 'do_action' ) ) {
do_action( 'sql_query_log', $query, false, $this->last_error );
}
return false;
}
}
$this->check_current_query = true;
// Inject setup and teardown statements
$statement_before_query = $this->run_callbacks( 'statement_before_query' );
$statement_after_query = $this->run_callbacks( 'statement_after_query' );
$query_for_log = $query;
$this->timer_start();
if ( $statement_before_query ) {
$query_for_log = "$statement_before_query; $query_for_log";
$this->ex_mysql_query( $statement_before_query, $this->dbh );
}
$this->result = $this->ex_mysql_query( $query, $this->dbh );
if ( $statement_after_query ) {
$query_for_log = "$query_for_log; $statement_after_query";
$this->ex_mysql_query( $statement_after_query, $this->dbh );
}
$elapsed = $this->timer_stop();
++$this->num_queries;
if ( preg_match( '/^\s*SELECT\s+SQL_CALC_FOUND_ROWS\s/i', $query ) ) {
if ( false === strpos( $query, 'NO_SELECT_FOUND_ROWS' ) ) {
$this->timer_start();
$this->last_found_rows_result = $this->ex_mysql_query( 'SELECT FOUND_ROWS()', $this->dbh );
$elapsed += $this->timer_stop();
++$this->num_queries;
$query .= '; SELECT FOUND_ROWS()';
}
} else {
$this->last_found_rows_result = null;
}
$this->dbhname_heartbeats[ $this->dbhname ]['last_used'] = microtime( true );
if ( $this->save_queries ) {
if ( is_callable( $this->save_query_callback ) ) {
// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_debug_backtrace
$saved_query = call_user_func_array( $this->save_query_callback, array( $query_for_log, $elapsed, $this->save_backtrace ? debug_backtrace( DEBUG_BACKTRACE_IGNORE_ARGS ) : null, $this ) );
if ( null !== $saved_query ) {
$this->queries[] = $saved_query;
}
} else {
$this->queries[] = array( $query_for_log, $elapsed, $this->get_caller() );
}
}
}