]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/wp-db.php
WordPress 4.6.1
[autoinstalls/wordpress.git] / wp-includes / wp-db.php
1 <?php
2 /**
3  * WordPress DB Class
4  *
5  * Original code from {@link http://php.justinvincent.com Justin Vincent (justin@visunet.ie)}
6  *
7  * @package WordPress
8  * @subpackage Database
9  * @since 0.71
10  */
11
12 /**
13  * @since 0.71
14  */
15 define( 'EZSQL_VERSION', 'WP1.25' );
16
17 /**
18  * @since 0.71
19  */
20 define( 'OBJECT', 'OBJECT' );
21 define( 'object', 'OBJECT' ); // Back compat.
22
23 /**
24  * @since 2.5.0
25  */
26 define( 'OBJECT_K', 'OBJECT_K' );
27
28 /**
29  * @since 0.71
30  */
31 define( 'ARRAY_A', 'ARRAY_A' );
32
33 /**
34  * @since 0.71
35  */
36 define( 'ARRAY_N', 'ARRAY_N' );
37
38 /**
39  * WordPress Database Access Abstraction Object
40  *
41  * It is possible to replace this class with your own
42  * by setting the $wpdb global variable in wp-content/db.php
43  * file to your class. The wpdb class will still be included,
44  * so you can extend it or simply use your own.
45  *
46  * @link https://codex.wordpress.org/Function_Reference/wpdb_Class
47  *
48  * @package WordPress
49  * @subpackage Database
50  * @since 0.71
51  */
52 class wpdb {
53
54         /**
55          * Whether to show SQL/DB errors.
56          *
57          * Default behavior is to show errors if both WP_DEBUG and WP_DEBUG_DISPLAY
58          * evaluated to true.
59          *
60          * @since 0.71
61          * @access private
62          * @var bool
63          */
64         var $show_errors = false;
65
66         /**
67          * Whether to suppress errors during the DB bootstrapping.
68          *
69          * @access private
70          * @since 2.5.0
71          * @var bool
72          */
73         var $suppress_errors = false;
74
75         /**
76          * The last error during query.
77          *
78          * @since 2.5.0
79          * @var string
80          */
81         public $last_error = '';
82
83         /**
84          * Amount of queries made
85          *
86          * @since 1.2.0
87          * @access public
88          * @var int
89          */
90         public $num_queries = 0;
91
92         /**
93          * Count of rows returned by previous query
94          *
95          * @since 0.71
96          * @access public
97          * @var int
98          */
99         public $num_rows = 0;
100
101         /**
102          * Count of affected rows by previous query
103          *
104          * @since 0.71
105          * @access private
106          * @var int
107          */
108         var $rows_affected = 0;
109
110         /**
111          * The ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
112          *
113          * @since 0.71
114          * @access public
115          * @var int
116          */
117         public $insert_id = 0;
118
119         /**
120          * Last query made
121          *
122          * @since 0.71
123          * @access private
124          * @var array
125          */
126         var $last_query;
127
128         /**
129          * Results of the last query made
130          *
131          * @since 0.71
132          * @access private
133          * @var array|null
134          */
135         var $last_result;
136
137         /**
138          * MySQL result, which is either a resource or boolean.
139          *
140          * @since 0.71
141          * @access protected
142          * @var mixed
143          */
144         protected $result;
145
146         /**
147          * Cached column info, for sanity checking data before inserting
148          *
149          * @since 4.2.0
150          * @access protected
151          * @var array
152          */
153         protected $col_meta = array();
154
155         /**
156          * Calculated character sets on tables
157          *
158          * @since 4.2.0
159          * @access protected
160          * @var array
161          */
162         protected $table_charset = array();
163
164         /**
165          * Whether text fields in the current query need to be sanity checked.
166          *
167          * @since 4.2.0
168          * @access protected
169          * @var bool
170          */
171         protected $check_current_query = true;
172
173         /**
174          * Flag to ensure we don't run into recursion problems when checking the collation.
175          *
176          * @since 4.2.0
177          * @access private
178          * @see wpdb::check_safe_collation()
179          * @var bool
180          */
181         private $checking_collation = false;
182
183         /**
184          * Saved info on the table column
185          *
186          * @since 0.71
187          * @access protected
188          * @var array
189          */
190         protected $col_info;
191
192         /**
193          * Saved queries that were executed
194          *
195          * @since 1.5.0
196          * @access private
197          * @var array
198          */
199         var $queries;
200
201         /**
202          * The number of times to retry reconnecting before dying.
203          *
204          * @since 3.9.0
205          * @access protected
206          * @see wpdb::check_connection()
207          * @var int
208          */
209         protected $reconnect_retries = 5;
210
211         /**
212          * WordPress table prefix
213          *
214          * You can set this to have multiple WordPress installations
215          * in a single database. The second reason is for possible
216          * security precautions.
217          *
218          * @since 2.5.0
219          * @access public
220          * @var string
221          */
222         public $prefix = '';
223
224         /**
225          * WordPress base table prefix.
226          *
227          * @since 3.0.0
228          * @access public
229          * @var string
230          */
231          public $base_prefix;
232
233         /**
234          * Whether the database queries are ready to start executing.
235          *
236          * @since 2.3.2
237          * @access private
238          * @var bool
239          */
240         var $ready = false;
241
242         /**
243          * Blog ID.
244          *
245          * @since 3.0.0
246          * @access public
247          * @var int
248          */
249         public $blogid = 0;
250
251         /**
252          * Site ID.
253          *
254          * @since 3.0.0
255          * @access public
256          * @var int
257          */
258         public $siteid = 0;
259
260         /**
261          * List of WordPress per-blog tables
262          *
263          * @since 2.5.0
264          * @access private
265          * @see wpdb::tables()
266          * @var array
267          */
268         var $tables = array( 'posts', 'comments', 'links', 'options', 'postmeta',
269                 'terms', 'term_taxonomy', 'term_relationships', 'termmeta', 'commentmeta' );
270
271         /**
272          * List of deprecated WordPress tables
273          *
274          * categories, post2cat, and link2cat were deprecated in 2.3.0, db version 5539
275          *
276          * @since 2.9.0
277          * @access private
278          * @see wpdb::tables()
279          * @var array
280          */
281         var $old_tables = array( 'categories', 'post2cat', 'link2cat' );
282
283         /**
284          * List of WordPress global tables
285          *
286          * @since 3.0.0
287          * @access private
288          * @see wpdb::tables()
289          * @var array
290          */
291         var $global_tables = array( 'users', 'usermeta' );
292
293         /**
294          * List of Multisite global tables
295          *
296          * @since 3.0.0
297          * @access private
298          * @see wpdb::tables()
299          * @var array
300          */
301         var $ms_global_tables = array( 'blogs', 'signups', 'site', 'sitemeta',
302                 'sitecategories', 'registration_log', 'blog_versions' );
303
304         /**
305          * WordPress Comments table
306          *
307          * @since 1.5.0
308          * @access public
309          * @var string
310          */
311         public $comments;
312
313         /**
314          * WordPress Comment Metadata table
315          *
316          * @since 2.9.0
317          * @access public
318          * @var string
319          */
320         public $commentmeta;
321
322         /**
323          * WordPress Links table
324          *
325          * @since 1.5.0
326          * @access public
327          * @var string
328          */
329         public $links;
330
331         /**
332          * WordPress Options table
333          *
334          * @since 1.5.0
335          * @access public
336          * @var string
337          */
338         public $options;
339
340         /**
341          * WordPress Post Metadata table
342          *
343          * @since 1.5.0
344          * @access public
345          * @var string
346          */
347         public $postmeta;
348
349         /**
350          * WordPress Posts table
351          *
352          * @since 1.5.0
353          * @access public
354          * @var string
355          */
356         public $posts;
357
358         /**
359          * WordPress Terms table
360          *
361          * @since 2.3.0
362          * @access public
363          * @var string
364          */
365         public $terms;
366
367         /**
368          * WordPress Term Relationships table
369          *
370          * @since 2.3.0
371          * @access public
372          * @var string
373          */
374         public $term_relationships;
375
376         /**
377          * WordPress Term Taxonomy table
378          *
379          * @since 2.3.0
380          * @access public
381          * @var string
382          */
383         public $term_taxonomy;
384
385         /**
386          * WordPress Term Meta table.
387          *
388          * @since 4.4.0
389          * @access public
390          * @var string
391          */
392         public $termmeta;
393
394         //
395         // Global and Multisite tables
396         //
397
398         /**
399          * WordPress User Metadata table
400          *
401          * @since 2.3.0
402          * @access public
403          * @var string
404          */
405         public $usermeta;
406
407         /**
408          * WordPress Users table
409          *
410          * @since 1.5.0
411          * @access public
412          * @var string
413          */
414         public $users;
415
416         /**
417          * Multisite Blogs table
418          *
419          * @since 3.0.0
420          * @access public
421          * @var string
422          */
423         public $blogs;
424
425         /**
426          * Multisite Blog Versions table
427          *
428          * @since 3.0.0
429          * @access public
430          * @var string
431          */
432         public $blog_versions;
433
434         /**
435          * Multisite Registration Log table
436          *
437          * @since 3.0.0
438          * @access public
439          * @var string
440          */
441         public $registration_log;
442
443         /**
444          * Multisite Signups table
445          *
446          * @since 3.0.0
447          * @access public
448          * @var string
449          */
450         public $signups;
451
452         /**
453          * Multisite Sites table
454          *
455          * @since 3.0.0
456          * @access public
457          * @var string
458          */
459         public $site;
460
461         /**
462          * Multisite Sitewide Terms table
463          *
464          * @since 3.0.0
465          * @access public
466          * @var string
467          */
468         public $sitecategories;
469
470         /**
471          * Multisite Site Metadata table
472          *
473          * @since 3.0.0
474          * @access public
475          * @var string
476          */
477         public $sitemeta;
478
479         /**
480          * Format specifiers for DB columns. Columns not listed here default to %s. Initialized during WP load.
481          *
482          * Keys are column names, values are format types: 'ID' => '%d'
483          *
484          * @since 2.8.0
485          * @see wpdb::prepare()
486          * @see wpdb::insert()
487          * @see wpdb::update()
488          * @see wpdb::delete()
489          * @see wp_set_wpdb_vars()
490          * @access public
491          * @var array
492          */
493         public $field_types = array();
494
495         /**
496          * Database table columns charset
497          *
498          * @since 2.2.0
499          * @access public
500          * @var string
501          */
502         public $charset;
503
504         /**
505          * Database table columns collate
506          *
507          * @since 2.2.0
508          * @access public
509          * @var string
510          */
511         public $collate;
512
513         /**
514          * Database Username
515          *
516          * @since 2.9.0
517          * @access protected
518          * @var string
519          */
520         protected $dbuser;
521
522         /**
523          * Database Password
524          *
525          * @since 3.1.0
526          * @access protected
527          * @var string
528          */
529         protected $dbpassword;
530
531         /**
532          * Database Name
533          *
534          * @since 3.1.0
535          * @access protected
536          * @var string
537          */
538         protected $dbname;
539
540         /**
541          * Database Host
542          *
543          * @since 3.1.0
544          * @access protected
545          * @var string
546          */
547         protected $dbhost;
548
549         /**
550          * Database Handle
551          *
552          * @since 0.71
553          * @access protected
554          * @var string
555          */
556         protected $dbh;
557
558         /**
559          * A textual description of the last query/get_row/get_var call
560          *
561          * @since 3.0.0
562          * @access public
563          * @var string
564          */
565         public $func_call;
566
567         /**
568          * Whether MySQL is used as the database engine.
569          *
570          * Set in WPDB::db_connect() to true, by default. This is used when checking
571          * against the required MySQL version for WordPress. Normally, a replacement
572          * database drop-in (db.php) will skip these checks, but setting this to true
573          * will force the checks to occur.
574          *
575          * @since 3.3.0
576          * @access public
577          * @var bool
578          */
579         public $is_mysql = null;
580
581         /**
582          * A list of incompatible SQL modes.
583          *
584          * @since 3.9.0
585          * @access protected
586          * @var array
587          */
588         protected $incompatible_modes = array( 'NO_ZERO_DATE', 'ONLY_FULL_GROUP_BY',
589                 'STRICT_TRANS_TABLES', 'STRICT_ALL_TABLES', 'TRADITIONAL' );
590
591         /**
592          * Whether to use mysqli over mysql.
593          *
594          * @since 3.9.0
595          * @access private
596          * @var bool
597          */
598         private $use_mysqli = false;
599
600         /**
601          * Whether we've managed to successfully connect at some point
602          *
603          * @since 3.9.0
604          * @access private
605          * @var bool
606          */
607         private $has_connected = false;
608
609         /**
610          * Connects to the database server and selects a database
611          *
612          * PHP5 style constructor for compatibility with PHP5. Does
613          * the actual setting up of the class properties and connection
614          * to the database.
615          *
616          * @link https://core.trac.wordpress.org/ticket/3354
617          * @since 2.0.8
618          *
619          * @global string $wp_version
620          *
621          * @param string $dbuser     MySQL database user
622          * @param string $dbpassword MySQL database password
623          * @param string $dbname     MySQL database name
624          * @param string $dbhost     MySQL database host
625          */
626         public function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
627                 register_shutdown_function( array( $this, '__destruct' ) );
628
629                 if ( WP_DEBUG && WP_DEBUG_DISPLAY )
630                         $this->show_errors();
631
632                 /* Use ext/mysqli if it exists and:
633                  *  - WP_USE_EXT_MYSQL is defined as false, or
634                  *  - We are a development version of WordPress, or
635                  *  - We are running PHP 5.5 or greater, or
636                  *  - ext/mysql is not loaded.
637                  */
638                 if ( function_exists( 'mysqli_connect' ) ) {
639                         if ( defined( 'WP_USE_EXT_MYSQL' ) ) {
640                                 $this->use_mysqli = ! WP_USE_EXT_MYSQL;
641                         } elseif ( version_compare( phpversion(), '5.5', '>=' ) || ! function_exists( 'mysql_connect' ) ) {
642                                 $this->use_mysqli = true;
643                         } elseif ( false !== strpos( $GLOBALS['wp_version'], '-' ) ) {
644                                 $this->use_mysqli = true;
645                         }
646                 }
647
648                 $this->dbuser = $dbuser;
649                 $this->dbpassword = $dbpassword;
650                 $this->dbname = $dbname;
651                 $this->dbhost = $dbhost;
652
653                 // wp-config.php creation will manually connect when ready.
654                 if ( defined( 'WP_SETUP_CONFIG' ) ) {
655                         return;
656                 }
657
658                 $this->db_connect();
659         }
660
661         /**
662          * PHP5 style destructor and will run when database object is destroyed.
663          *
664          * @see wpdb::__construct()
665          * @since 2.0.8
666          * @return true
667          */
668         public function __destruct() {
669                 return true;
670         }
671
672         /**
673          * Makes private properties readable for backward compatibility.
674          *
675          * @since 3.5.0
676          *
677          * @param string $name The private member to get, and optionally process
678          * @return mixed The private member
679          */
680         public function __get( $name ) {
681                 if ( 'col_info' === $name )
682                         $this->load_col_info();
683
684                 return $this->$name;
685         }
686
687         /**
688          * Makes private properties settable for backward compatibility.
689          *
690          * @since 3.5.0
691          *
692          * @param string $name  The private member to set
693          * @param mixed  $value The value to set
694          */
695         public function __set( $name, $value ) {
696                 $protected_members = array(
697                         'col_meta',
698                         'table_charset',
699                         'check_current_query',
700                 );
701                 if (  in_array( $name, $protected_members, true ) ) {
702                         return;
703                 }
704                 $this->$name = $value;
705         }
706
707         /**
708          * Makes private properties check-able for backward compatibility.
709          *
710          * @since 3.5.0
711          *
712          * @param string $name  The private member to check
713          *
714          * @return bool If the member is set or not
715          */
716         public function __isset( $name ) {
717                 return isset( $this->$name );
718         }
719
720         /**
721          * Makes private properties un-settable for backward compatibility.
722          *
723          * @since 3.5.0
724          *
725          * @param string $name  The private member to unset
726          */
727         public function __unset( $name ) {
728                 unset( $this->$name );
729         }
730
731         /**
732          * Set $this->charset and $this->collate
733          *
734          * @since 3.1.0
735          */
736         public function init_charset() {
737                 $charset = '';
738                 $collate = '';
739
740                 if ( function_exists('is_multisite') && is_multisite() ) {
741                         $charset = 'utf8';
742                         if ( defined( 'DB_COLLATE' ) && DB_COLLATE ) {
743                                 $collate = DB_COLLATE;
744                         } else {
745                                 $collate = 'utf8_general_ci';
746                         }
747                 } elseif ( defined( 'DB_COLLATE' ) ) {
748                         $collate = DB_COLLATE;
749                 }
750
751                 if ( defined( 'DB_CHARSET' ) ) {
752                         $charset = DB_CHARSET;
753                 }
754
755                 $charset_collate = $this->determine_charset( $charset, $collate );
756
757                 $this->charset = $charset_collate['charset'];
758                 $this->collate = $charset_collate['collate'];
759         }
760
761         /**
762          * Determines the best charset and collation to use given a charset and collation.
763          *
764          * For example, when able, utf8mb4 should be used instead of utf8.
765          *
766          * @since 4.6.0
767          * @access public
768          *
769          * @param string $charset The character set to check.
770          * @param string $collate The collation to check.
771          * @return array The most appropriate character set and collation to use.
772          */
773         public function determine_charset( $charset, $collate ) {
774                 if ( ( $this->use_mysqli && ! ( $this->dbh instanceof mysqli ) ) || empty( $this->dbh ) ) {
775                         return compact( 'charset', 'collate' );
776                 }
777
778                 if ( 'utf8' === $charset && $this->has_cap( 'utf8mb4' ) ) {
779                         $charset = 'utf8mb4';
780                 }
781
782                 if ( 'utf8mb4' === $charset ) {
783                         // _general_ is outdated, so we can upgrade it to _unicode_, instead.
784                         if ( ! $collate || 'utf8_general_ci' === $collate ) {
785                                 $collate = 'utf8mb4_unicode_ci';
786                         } else {
787                                 $collate = str_replace( 'utf8_', 'utf8mb4_', $collate );
788                         }
789                 }
790
791                 // _unicode_520_ is a better collation, we should use that when it's available.
792                 if ( $this->has_cap( 'utf8mb4_520' ) && 'utf8mb4_unicode_ci' === $collate ) {
793                         $collate = 'utf8mb4_unicode_520_ci';
794                 }
795
796                 return compact( 'charset', 'collate' );
797         }
798
799         /**
800          * Sets the connection's character set.
801          *
802          * @since 3.1.0
803          *
804          * @param resource $dbh     The resource given by mysql_connect
805          * @param string   $charset Optional. The character set. Default null.
806          * @param string   $collate Optional. The collation. Default null.
807          */
808         public function set_charset( $dbh, $charset = null, $collate = null ) {
809                 if ( ! isset( $charset ) )
810                         $charset = $this->charset;
811                 if ( ! isset( $collate ) )
812                         $collate = $this->collate;
813                 if ( $this->has_cap( 'collation' ) && ! empty( $charset ) ) {
814                         $set_charset_succeeded = true;
815
816                         if ( $this->use_mysqli ) {
817                                 if ( function_exists( 'mysqli_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
818                                         $set_charset_succeeded = mysqli_set_charset( $dbh, $charset );
819                                 }
820
821                                 if ( $set_charset_succeeded ) {
822                                         $query = $this->prepare( 'SET NAMES %s', $charset );
823                                         if ( ! empty( $collate ) )
824                                                 $query .= $this->prepare( ' COLLATE %s', $collate );
825                                         mysqli_query( $dbh, $query );
826                                 }
827                         } else {
828                                 if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
829                                         $set_charset_succeeded = mysql_set_charset( $charset, $dbh );
830                                 }
831                                 if ( $set_charset_succeeded ) {
832                                         $query = $this->prepare( 'SET NAMES %s', $charset );
833                                         if ( ! empty( $collate ) )
834                                                 $query .= $this->prepare( ' COLLATE %s', $collate );
835                                         mysql_query( $query, $dbh );
836                                 }
837                         }
838                 }
839         }
840
841         /**
842          * Change the current SQL mode, and ensure its WordPress compatibility.
843          *
844          * If no modes are passed, it will ensure the current MySQL server
845          * modes are compatible.
846          *
847          * @since 3.9.0
848          *
849          * @param array $modes Optional. A list of SQL modes to set.
850          */
851         public function set_sql_mode( $modes = array() ) {
852                 if ( empty( $modes ) ) {
853                         if ( $this->use_mysqli ) {
854                                 $res = mysqli_query( $this->dbh, 'SELECT @@SESSION.sql_mode' );
855                         } else {
856                                 $res = mysql_query( 'SELECT @@SESSION.sql_mode', $this->dbh );
857                         }
858
859                         if ( empty( $res ) ) {
860                                 return;
861                         }
862
863                         if ( $this->use_mysqli ) {
864                                 $modes_array = mysqli_fetch_array( $res );
865                                 if ( empty( $modes_array[0] ) ) {
866                                         return;
867                                 }
868                                 $modes_str = $modes_array[0];
869                         } else {
870                                 $modes_str = mysql_result( $res, 0 );
871                         }
872
873                         if ( empty( $modes_str ) ) {
874                                 return;
875                         }
876
877                         $modes = explode( ',', $modes_str );
878                 }
879
880                 $modes = array_change_key_case( $modes, CASE_UPPER );
881
882                 /**
883                  * Filters the list of incompatible SQL modes to exclude.
884                  *
885                  * @since 3.9.0
886                  *
887                  * @param array $incompatible_modes An array of incompatible modes.
888                  */
889                 $incompatible_modes = (array) apply_filters( 'incompatible_sql_modes', $this->incompatible_modes );
890
891                 foreach ( $modes as $i => $mode ) {
892                         if ( in_array( $mode, $incompatible_modes ) ) {
893                                 unset( $modes[ $i ] );
894                         }
895                 }
896
897                 $modes_str = implode( ',', $modes );
898
899                 if ( $this->use_mysqli ) {
900                         mysqli_query( $this->dbh, "SET SESSION sql_mode='$modes_str'" );
901                 } else {
902                         mysql_query( "SET SESSION sql_mode='$modes_str'", $this->dbh );
903                 }
904         }
905
906         /**
907          * Sets the table prefix for the WordPress tables.
908          *
909          * @since 2.5.0
910          *
911          * @param string $prefix          Alphanumeric name for the new prefix.
912          * @param bool   $set_table_names Optional. Whether the table names, e.g. wpdb::$posts, should be updated or not.
913          * @return string|WP_Error Old prefix or WP_Error on error
914          */
915         public function set_prefix( $prefix, $set_table_names = true ) {
916
917                 if ( preg_match( '|[^a-z0-9_]|i', $prefix ) )
918                         return new WP_Error('invalid_db_prefix', 'Invalid database prefix' );
919
920                 $old_prefix = is_multisite() ? '' : $prefix;
921
922                 if ( isset( $this->base_prefix ) )
923                         $old_prefix = $this->base_prefix;
924
925                 $this->base_prefix = $prefix;
926
927                 if ( $set_table_names ) {
928                         foreach ( $this->tables( 'global' ) as $table => $prefixed_table )
929                                 $this->$table = $prefixed_table;
930
931                         if ( is_multisite() && empty( $this->blogid ) )
932                                 return $old_prefix;
933
934                         $this->prefix = $this->get_blog_prefix();
935
936                         foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
937                                 $this->$table = $prefixed_table;
938
939                         foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
940                                 $this->$table = $prefixed_table;
941                 }
942                 return $old_prefix;
943         }
944
945         /**
946          * Sets blog id.
947          *
948          * @since 3.0.0
949          * @access public
950          *
951          * @param int $blog_id
952          * @param int $site_id Optional.
953          * @return int previous blog id
954          */
955         public function set_blog_id( $blog_id, $site_id = 0 ) {
956                 if ( ! empty( $site_id ) )
957                         $this->siteid = $site_id;
958
959                 $old_blog_id  = $this->blogid;
960                 $this->blogid = $blog_id;
961
962                 $this->prefix = $this->get_blog_prefix();
963
964                 foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
965                         $this->$table = $prefixed_table;
966
967                 foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
968                         $this->$table = $prefixed_table;
969
970                 return $old_blog_id;
971         }
972
973         /**
974          * Gets blog prefix.
975          *
976          * @since 3.0.0
977          * @param int $blog_id Optional.
978          * @return string Blog prefix.
979          */
980         public function get_blog_prefix( $blog_id = null ) {
981                 if ( is_multisite() ) {
982                         if ( null === $blog_id )
983                                 $blog_id = $this->blogid;
984                         $blog_id = (int) $blog_id;
985                         if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) )
986                                 return $this->base_prefix;
987                         else
988                                 return $this->base_prefix . $blog_id . '_';
989                 } else {
990                         return $this->base_prefix;
991                 }
992         }
993
994         /**
995          * Returns an array of WordPress tables.
996          *
997          * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
998          * override the WordPress users and usermeta tables that would otherwise
999          * be determined by the prefix.
1000          *
1001          * The scope argument can take one of the following:
1002          *
1003          * 'all' - returns 'all' and 'global' tables. No old tables are returned.
1004          * 'blog' - returns the blog-level tables for the queried blog.
1005          * 'global' - returns the global tables for the installation, returning multisite tables only if running multisite.
1006          * 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
1007          * 'old' - returns tables which are deprecated.
1008          *
1009          * @since 3.0.0
1010          * @uses wpdb::$tables
1011          * @uses wpdb::$old_tables
1012          * @uses wpdb::$global_tables
1013          * @uses wpdb::$ms_global_tables
1014          *
1015          * @param string $scope   Optional. Can be all, global, ms_global, blog, or old tables. Defaults to all.
1016          * @param bool   $prefix  Optional. Whether to include table prefixes. Default true. If blog
1017          *                        prefix is requested, then the custom users and usermeta tables will be mapped.
1018          * @param int    $blog_id Optional. The blog_id to prefix. Defaults to wpdb::$blogid. Used only when prefix is requested.
1019          * @return array Table names. When a prefix is requested, the key is the unprefixed table name.
1020          */
1021         public function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
1022                 switch ( $scope ) {
1023                         case 'all' :
1024                                 $tables = array_merge( $this->global_tables, $this->tables );
1025                                 if ( is_multisite() )
1026                                         $tables = array_merge( $tables, $this->ms_global_tables );
1027                                 break;
1028                         case 'blog' :
1029                                 $tables = $this->tables;
1030                                 break;
1031                         case 'global' :
1032                                 $tables = $this->global_tables;
1033                                 if ( is_multisite() )
1034                                         $tables = array_merge( $tables, $this->ms_global_tables );
1035                                 break;
1036                         case 'ms_global' :
1037                                 $tables = $this->ms_global_tables;
1038                                 break;
1039                         case 'old' :
1040                                 $tables = $this->old_tables;
1041                                 break;
1042                         default :
1043                                 return array();
1044                 }
1045
1046                 if ( $prefix ) {
1047                         if ( ! $blog_id )
1048                                 $blog_id = $this->blogid;
1049                         $blog_prefix = $this->get_blog_prefix( $blog_id );
1050                         $base_prefix = $this->base_prefix;
1051                         $global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
1052                         foreach ( $tables as $k => $table ) {
1053                                 if ( in_array( $table, $global_tables ) )
1054                                         $tables[ $table ] = $base_prefix . $table;
1055                                 else
1056                                         $tables[ $table ] = $blog_prefix . $table;
1057                                 unset( $tables[ $k ] );
1058                         }
1059
1060                         if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) )
1061                                 $tables['users'] = CUSTOM_USER_TABLE;
1062
1063                         if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) )
1064                                 $tables['usermeta'] = CUSTOM_USER_META_TABLE;
1065                 }
1066
1067                 return $tables;
1068         }
1069
1070         /**
1071          * Selects a database using the current database connection.
1072          *
1073          * The database name will be changed based on the current database
1074          * connection. On failure, the execution will bail and display an DB error.
1075          *
1076          * @since 0.71
1077          *
1078          * @param string        $db  MySQL database name
1079          * @param resource|null $dbh Optional link identifier.
1080          */
1081         public function select( $db, $dbh = null ) {
1082                 if ( is_null($dbh) )
1083                         $dbh = $this->dbh;
1084
1085                 if ( $this->use_mysqli ) {
1086                         $success = mysqli_select_db( $dbh, $db );
1087                 } else {
1088                         $success = mysql_select_db( $db, $dbh );
1089                 }
1090                 if ( ! $success ) {
1091                         $this->ready = false;
1092                         if ( ! did_action( 'template_redirect' ) ) {
1093                                 wp_load_translations_early();
1094
1095                                 $message = '<h1>' . __( 'Can&#8217;t select database' ) . "</h1>\n";
1096
1097                                 $message .= '<p>' . sprintf(
1098                                         /* translators: %s: database name */
1099                                         __( 'We were able to connect to the database server (which means your username and password is okay) but not able to select the %s database.' ),
1100                                         '<code>' . htmlspecialchars( $db, ENT_QUOTES ) . '</code>'
1101                                 ) . "</p>\n";
1102
1103                                 $message .= "<ul>\n";
1104                                 $message .= '<li>' . __( 'Are you sure it exists?' ) . "</li>\n";
1105
1106                                 $message .= '<li>' . sprintf(
1107                                         /* translators: 1: database user, 2: database name */
1108                                         __( 'Does the user %1$s have permission to use the %2$s database?' ),
1109                                         '<code>' . htmlspecialchars( $this->dbuser, ENT_QUOTES )  . '</code>',
1110                                         '<code>' . htmlspecialchars( $db, ENT_QUOTES ) . '</code>'
1111                                 ) . "</li>\n";
1112
1113                                 $message .= '<li>' . sprintf(
1114                                         /* translators: %s: database name */
1115                                         __( '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?' ),
1116                                         htmlspecialchars( $db, ENT_QUOTES )
1117                                 ). "</li>\n";
1118
1119                                 $message .= "</ul>\n";
1120
1121                                 $message .= '<p>' . sprintf(
1122                                         /* translators: %s: support forums URL */
1123                                         __( 'If you don&#8217;t know how to set up a database you should <strong>contact your host</strong>. If all else fails you may find help at the <a href="%s">WordPress Support Forums</a>.' ),
1124                                         __( 'https://wordpress.org/support/' )
1125                                 ) . "</p>\n";
1126
1127                                 $this->bail( $message, 'db_select_fail' );
1128                         }
1129                 }
1130         }
1131
1132         /**
1133          * Do not use, deprecated.
1134          *
1135          * Use esc_sql() or wpdb::prepare() instead.
1136          *
1137          * @since 2.8.0
1138          * @deprecated 3.6.0 Use wpdb::prepare()
1139          * @see wpdb::prepare
1140          * @see esc_sql()
1141          * @access private
1142          *
1143          * @param string $string
1144          * @return string
1145          */
1146         function _weak_escape( $string ) {
1147                 if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) )
1148                         _deprecated_function( __METHOD__, '3.6.0', 'wpdb::prepare() or esc_sql()' );
1149                 return addslashes( $string );
1150         }
1151
1152         /**
1153          * Real escape, using mysqli_real_escape_string() or mysql_real_escape_string()
1154          *
1155          * @see mysqli_real_escape_string()
1156          * @see mysql_real_escape_string()
1157          * @since 2.8.0
1158          * @access private
1159          *
1160          * @param  string $string to escape
1161          * @return string escaped
1162          */
1163         function _real_escape( $string ) {
1164                 if ( $this->dbh ) {
1165                         if ( $this->use_mysqli ) {
1166                                 return mysqli_real_escape_string( $this->dbh, $string );
1167                         } else {
1168                                 return mysql_real_escape_string( $string, $this->dbh );
1169                         }
1170                 }
1171
1172                 $class = get_class( $this );
1173                 if ( function_exists( '__' ) ) {
1174                         /* translators: %s: database access abstraction class, usually wpdb or a class extending wpdb */
1175                         _doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), '3.6.0' );
1176                 } else {
1177                         _doing_it_wrong( $class, sprintf( '%s must set a database connection for use with escaping.', $class ), '3.6.0' );
1178                 }
1179                 return addslashes( $string );
1180         }
1181
1182         /**
1183          * Escape data. Works on arrays.
1184          *
1185          * @uses wpdb::_real_escape()
1186          * @since  2.8.0
1187          * @access private
1188          *
1189          * @param  string|array $data
1190          * @return string|array escaped
1191          */
1192         function _escape( $data ) {
1193                 if ( is_array( $data ) ) {
1194                         foreach ( $data as $k => $v ) {
1195                                 if ( is_array($v) )
1196                                         $data[$k] = $this->_escape( $v );
1197                                 else
1198                                         $data[$k] = $this->_real_escape( $v );
1199                         }
1200                 } else {
1201                         $data = $this->_real_escape( $data );
1202                 }
1203
1204                 return $data;
1205         }
1206
1207         /**
1208          * Do not use, deprecated.
1209          *
1210          * Use esc_sql() or wpdb::prepare() instead.
1211          *
1212          * @since 0.71
1213          * @deprecated 3.6.0 Use wpdb::prepare()
1214          * @see wpdb::prepare()
1215          * @see esc_sql()
1216          *
1217          * @param mixed $data
1218          * @return mixed
1219          */
1220         public function escape( $data ) {
1221                 if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) )
1222                         _deprecated_function( __METHOD__, '3.6.0', 'wpdb::prepare() or esc_sql()' );
1223                 if ( is_array( $data ) ) {
1224                         foreach ( $data as $k => $v ) {
1225                                 if ( is_array( $v ) )
1226                                         $data[$k] = $this->escape( $v, 'recursive' );
1227                                 else
1228                                         $data[$k] = $this->_weak_escape( $v, 'internal' );
1229                         }
1230                 } else {
1231                         $data = $this->_weak_escape( $data, 'internal' );
1232                 }
1233
1234                 return $data;
1235         }
1236
1237         /**
1238          * Escapes content by reference for insertion into the database, for security
1239          *
1240          * @uses wpdb::_real_escape()
1241          *
1242          * @since 2.3.0
1243          *
1244          * @param string $string to escape
1245          */
1246         public function escape_by_ref( &$string ) {
1247                 if ( ! is_float( $string ) )
1248                         $string = $this->_real_escape( $string );
1249         }
1250
1251         /**
1252          * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
1253          *
1254          * The following directives can be used in the query format string:
1255          *   %d (integer)
1256          *   %f (float)
1257          *   %s (string)
1258          *   %% (literal percentage sign - no argument needed)
1259          *
1260          * All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
1261          * Literals (%) as parts of the query must be properly written as %%.
1262          *
1263          * This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
1264          * Does not support sign, padding, alignment, width or precision specifiers.
1265          * Does not support argument numbering/swapping.
1266          *
1267          * May be called like {@link https://secure.php.net/sprintf sprintf()} or like {@link https://secure.php.net/vsprintf vsprintf()}.
1268          *
1269          * Both %d and %s should be left unquoted in the query string.
1270          *
1271          *     wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
1272          *     wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
1273          *
1274          * @link https://secure.php.net/sprintf Description of syntax.
1275          * @since 2.3.0
1276          *
1277          * @param string      $query    Query statement with sprintf()-like placeholders
1278          * @param array|mixed $args     The array of variables to substitute into the query's placeholders if being called like
1279          *                              {@link https://secure.php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
1280          *                              being called like {@link https://secure.php.net/sprintf sprintf()}.
1281          * @param mixed       $args,... further variables to substitute into the query's placeholders if being called like
1282          *                              {@link https://secure.php.net/sprintf sprintf()}.
1283          * @return string|void Sanitized query string, if there is a query to prepare.
1284          */
1285         public function prepare( $query, $args ) {
1286                 if ( is_null( $query ) )
1287                         return;
1288
1289                 // This is not meant to be foolproof -- but it will catch obviously incorrect usage.
1290                 if ( strpos( $query, '%' ) === false ) {
1291                         _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'The query argument of %s must have a placeholder.' ), 'wpdb::prepare()' ), '3.9.0' );
1292                 }
1293
1294                 $args = func_get_args();
1295                 array_shift( $args );
1296                 // If args were passed as an array (as in vsprintf), move them up
1297                 if ( isset( $args[0] ) && is_array($args[0]) )
1298                         $args = $args[0];
1299                 $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
1300                 $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
1301                 $query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware
1302                 $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
1303                 array_walk( $args, array( $this, 'escape_by_ref' ) );
1304                 return @vsprintf( $query, $args );
1305         }
1306
1307         /**
1308          * First half of escaping for LIKE special characters % and _ before preparing for MySQL.
1309          *
1310          * Use this only before wpdb::prepare() or esc_sql().  Reversing the order is very bad for security.
1311          *
1312          * Example Prepared Statement:
1313          *
1314          *     $wild = '%';
1315          *     $find = 'only 43% of planets';
1316          *     $like = $wild . $wpdb->esc_like( $find ) . $wild;
1317          *     $sql  = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_content LIKE '%s'", $like );
1318          *
1319          * Example Escape Chain:
1320          *
1321          *     $sql  = esc_sql( $wpdb->esc_like( $input ) );
1322          *
1323          * @since 4.0.0
1324          * @access public
1325          *
1326          * @param string $text The raw text to be escaped. The input typed by the user should have no
1327          *                     extra or deleted slashes.
1328          * @return string Text in the form of a LIKE phrase. The output is not SQL safe. Call $wpdb::prepare()
1329          *                or real_escape next.
1330          */
1331         public function esc_like( $text ) {
1332                 return addcslashes( $text, '_%\\' );
1333         }
1334
1335         /**
1336          * Print SQL/DB error.
1337          *
1338          * @since 0.71
1339          * @global array $EZSQL_ERROR Stores error information of query and error string
1340          *
1341          * @param string $str The error to display
1342          * @return false|void False if the showing of errors is disabled.
1343          */
1344         public function print_error( $str = '' ) {
1345                 global $EZSQL_ERROR;
1346
1347                 if ( !$str ) {
1348                         if ( $this->use_mysqli ) {
1349                                 $str = mysqli_error( $this->dbh );
1350                         } else {
1351                                 $str = mysql_error( $this->dbh );
1352                         }
1353                 }
1354                 $EZSQL_ERROR[] = array( 'query' => $this->last_query, 'error_str' => $str );
1355
1356                 if ( $this->suppress_errors )
1357                         return false;
1358
1359                 wp_load_translations_early();
1360
1361                 if ( $caller = $this->get_caller() )
1362                         $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s made by %3$s' ), $str, $this->last_query, $caller );
1363                 else
1364                         $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s' ), $str, $this->last_query );
1365
1366                 error_log( $error_str );
1367
1368                 // Are we showing errors?
1369                 if ( ! $this->show_errors )
1370                         return false;
1371
1372                 // If there is an error then take note of it
1373                 if ( is_multisite() ) {
1374                         $msg = sprintf(
1375                                 "%s [%s]\n%s\n",
1376                                 __( 'WordPress database error:' ),
1377                                 $str,
1378                                 $this->last_query
1379                         );
1380
1381                         if ( defined( 'ERRORLOGFILE' ) ) {
1382                                 error_log( $msg, 3, ERRORLOGFILE );
1383                         }
1384                         if ( defined( 'DIEONDBERROR' ) ) {
1385                                 wp_die( $msg );
1386                         }
1387                 } else {
1388                         $str   = htmlspecialchars( $str, ENT_QUOTES );
1389                         $query = htmlspecialchars( $this->last_query, ENT_QUOTES );
1390
1391                         printf(
1392                                 '<div id="error"><p class="wpdberror"><strong>%s</strong> [%s]<br /><code>%s</code></p></div>',
1393                                 __( 'WordPress database error:' ),
1394                                 $str,
1395                                 $query
1396                         );
1397                 }
1398         }
1399
1400         /**
1401          * Enables showing of database errors.
1402          *
1403          * This function should be used only to enable showing of errors.
1404          * wpdb::hide_errors() should be used instead for hiding of errors. However,
1405          * this function can be used to enable and disable showing of database
1406          * errors.
1407          *
1408          * @since 0.71
1409          * @see wpdb::hide_errors()
1410          *
1411          * @param bool $show Whether to show or hide errors
1412          * @return bool Old value for showing errors.
1413          */
1414         public function show_errors( $show = true ) {
1415                 $errors = $this->show_errors;
1416                 $this->show_errors = $show;
1417                 return $errors;
1418         }
1419
1420         /**
1421          * Disables showing of database errors.
1422          *
1423          * By default database errors are not shown.
1424          *
1425          * @since 0.71
1426          * @see wpdb::show_errors()
1427          *
1428          * @return bool Whether showing of errors was active
1429          */
1430         public function hide_errors() {
1431                 $show = $this->show_errors;
1432                 $this->show_errors = false;
1433                 return $show;
1434         }
1435
1436         /**
1437          * Whether to suppress database errors.
1438          *
1439          * By default database errors are suppressed, with a simple
1440          * call to this function they can be enabled.
1441          *
1442          * @since 2.5.0
1443          * @see wpdb::hide_errors()
1444          * @param bool $suppress Optional. New value. Defaults to true.
1445          * @return bool Old value
1446          */
1447         public function suppress_errors( $suppress = true ) {
1448                 $errors = $this->suppress_errors;
1449                 $this->suppress_errors = (bool) $suppress;
1450                 return $errors;
1451         }
1452
1453         /**
1454          * Kill cached query results.
1455          *
1456          * @since 0.71
1457          */
1458         public function flush() {
1459                 $this->last_result = array();
1460                 $this->col_info    = null;
1461                 $this->last_query  = null;
1462                 $this->rows_affected = $this->num_rows = 0;
1463                 $this->last_error  = '';
1464
1465                 if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
1466                         mysqli_free_result( $this->result );
1467                         $this->result = null;
1468
1469                         // Sanity check before using the handle
1470                         if ( empty( $this->dbh ) || !( $this->dbh instanceof mysqli ) ) {
1471                                 return;
1472                         }
1473
1474                         // Clear out any results from a multi-query
1475                         while ( mysqli_more_results( $this->dbh ) ) {
1476                                 mysqli_next_result( $this->dbh );
1477                         }
1478                 } elseif ( is_resource( $this->result ) ) {
1479                         mysql_free_result( $this->result );
1480                 }
1481         }
1482
1483         /**
1484          * Connect to and select database.
1485          *
1486          * If $allow_bail is false, the lack of database connection will need
1487          * to be handled manually.
1488          *
1489          * @since 3.0.0
1490          * @since 3.9.0 $allow_bail parameter added.
1491          *
1492          * @param bool $allow_bail Optional. Allows the function to bail. Default true.
1493          * @return bool True with a successful connection, false on failure.
1494          */
1495         public function db_connect( $allow_bail = true ) {
1496                 $this->is_mysql = true;
1497
1498                 /*
1499                  * Deprecated in 3.9+ when using MySQLi. No equivalent
1500                  * $new_link parameter exists for mysqli_* functions.
1501                  */
1502                 $new_link = defined( 'MYSQL_NEW_LINK' ) ? MYSQL_NEW_LINK : true;
1503                 $client_flags = defined( 'MYSQL_CLIENT_FLAGS' ) ? MYSQL_CLIENT_FLAGS : 0;
1504
1505                 if ( $this->use_mysqli ) {
1506                         $this->dbh = mysqli_init();
1507
1508                         // mysqli_real_connect doesn't support the host param including a port or socket
1509                         // like mysql_connect does. This duplicates how mysql_connect detects a port and/or socket file.
1510                         $port = null;
1511                         $socket = null;
1512                         $host = $this->dbhost;
1513                         $port_or_socket = strstr( $host, ':' );
1514                         if ( ! empty( $port_or_socket ) ) {
1515                                 $host = substr( $host, 0, strpos( $host, ':' ) );
1516                                 $port_or_socket = substr( $port_or_socket, 1 );
1517                                 if ( 0 !== strpos( $port_or_socket, '/' ) ) {
1518                                         $port = intval( $port_or_socket );
1519                                         $maybe_socket = strstr( $port_or_socket, ':' );
1520                                         if ( ! empty( $maybe_socket ) ) {
1521                                                 $socket = substr( $maybe_socket, 1 );
1522                                         }
1523                                 } else {
1524                                         $socket = $port_or_socket;
1525                                 }
1526                         }
1527
1528                         if ( WP_DEBUG ) {
1529                                 mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
1530                         } else {
1531                                 @mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
1532                         }
1533
1534                         if ( $this->dbh->connect_errno ) {
1535                                 $this->dbh = null;
1536
1537                                 /* It's possible ext/mysqli is misconfigured. Fall back to ext/mysql if:
1538                                  *  - We haven't previously connected, and
1539                                  *  - WP_USE_EXT_MYSQL isn't set to false, and
1540                                  *  - ext/mysql is loaded.
1541                                  */
1542                                 $attempt_fallback = true;
1543
1544                                 if ( $this->has_connected ) {
1545                                         $attempt_fallback = false;
1546                                 } elseif ( defined( 'WP_USE_EXT_MYSQL' ) && ! WP_USE_EXT_MYSQL ) {
1547                                         $attempt_fallback = false;
1548                                 } elseif ( ! function_exists( 'mysql_connect' ) ) {
1549                                         $attempt_fallback = false;
1550                                 }
1551
1552                                 if ( $attempt_fallback ) {
1553                                         $this->use_mysqli = false;
1554                                         return $this->db_connect( $allow_bail );
1555                                 }
1556                         }
1557                 } else {
1558                         if ( WP_DEBUG ) {
1559                                 $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
1560                         } else {
1561                                 $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
1562                         }
1563                 }
1564
1565                 if ( ! $this->dbh && $allow_bail ) {
1566                         wp_load_translations_early();
1567
1568                         // Load custom DB error template, if present.
1569                         if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
1570                                 require_once( WP_CONTENT_DIR . '/db-error.php' );
1571                                 die();
1572                         }
1573
1574                         $message = '<h1>' . __( 'Error establishing a database connection' ) . "</h1>\n";
1575
1576                         $message .= '<p>' . sprintf(
1577                                 /* translators: 1: wp-config.php. 2: database host */
1578                                 __( 'This either means that the username and password information in your %1$s file is incorrect or we can&#8217;t contact the database server at %2$s. This could mean your host&#8217;s database server is down.' ),
1579                                 '<code>wp-config.php</code>',
1580                                 '<code>' . htmlspecialchars( $this->dbhost, ENT_QUOTES ) . '</code>'
1581                         ) . "</p>\n";
1582
1583                         $message .= "<ul>\n";
1584                         $message .= '<li>' . __( 'Are you sure you have the correct username and password?' ) . "</li>\n";
1585                         $message .= '<li>' . __( 'Are you sure that you have typed the correct hostname?' ) . "</li>\n";
1586                         $message .= '<li>' . __( 'Are you sure that the database server is running?' ) . "</li>\n";
1587                         $message .= "</ul>\n";
1588
1589                         $message .= '<p>' . sprintf(
1590                                 /* translators: %s: support forums URL */
1591                                 __( 'If you&#8217;re unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href="%s">WordPress Support Forums</a>.' ),
1592                                 __( 'https://wordpress.org/support/' )
1593                         ) . "</p>\n";
1594
1595                         $this->bail( $message, 'db_connect_fail' );
1596
1597                         return false;
1598                 } elseif ( $this->dbh ) {
1599                         if ( ! $this->has_connected ) {
1600                                 $this->init_charset();
1601                         }
1602
1603                         $this->has_connected = true;
1604
1605                         $this->set_charset( $this->dbh );
1606
1607                         $this->ready = true;
1608                         $this->set_sql_mode();
1609                         $this->select( $this->dbname, $this->dbh );
1610
1611                         return true;
1612                 }
1613
1614                 return false;
1615         }
1616
1617         /**
1618          * Checks that the connection to the database is still up. If not, try to reconnect.
1619          *
1620          * If this function is unable to reconnect, it will forcibly die, or if after the
1621          * the {@see 'template_redirect'} hook has been fired, return false instead.
1622          *
1623          * If $allow_bail is false, the lack of database connection will need
1624          * to be handled manually.
1625          *
1626          * @since 3.9.0
1627          *
1628          * @param bool $allow_bail Optional. Allows the function to bail. Default true.
1629          * @return bool|void True if the connection is up.
1630          */
1631         public function check_connection( $allow_bail = true ) {
1632                 if ( $this->use_mysqli ) {
1633                         if ( ! empty( $this->dbh ) && mysqli_ping( $this->dbh ) ) {
1634                                 return true;
1635                         }
1636                 } else {
1637                         if ( ! empty( $this->dbh ) && mysql_ping( $this->dbh ) ) {
1638                                 return true;
1639                         }
1640                 }
1641
1642                 $error_reporting = false;
1643
1644                 // Disable warnings, as we don't want to see a multitude of "unable to connect" messages
1645                 if ( WP_DEBUG ) {
1646                         $error_reporting = error_reporting();
1647                         error_reporting( $error_reporting & ~E_WARNING );
1648                 }
1649
1650                 for ( $tries = 1; $tries <= $this->reconnect_retries; $tries++ ) {
1651                         // On the last try, re-enable warnings. We want to see a single instance of the
1652                         // "unable to connect" message on the bail() screen, if it appears.
1653                         if ( $this->reconnect_retries === $tries && WP_DEBUG ) {
1654                                 error_reporting( $error_reporting );
1655                         }
1656
1657                         if ( $this->db_connect( false ) ) {
1658                                 if ( $error_reporting ) {
1659                                         error_reporting( $error_reporting );
1660                                 }
1661
1662                                 return true;
1663                         }
1664
1665                         sleep( 1 );
1666                 }
1667
1668                 // If template_redirect has already happened, it's too late for wp_die()/dead_db().
1669                 // Let's just return and hope for the best.
1670                 if ( did_action( 'template_redirect' ) ) {
1671                         return false;
1672                 }
1673
1674                 if ( ! $allow_bail ) {
1675                         return false;
1676                 }
1677
1678                 wp_load_translations_early();
1679
1680                 $message = '<h1>' . __( 'Error reconnecting to the database' ) . "</h1>\n";
1681
1682                 $message .= '<p>' . sprintf(
1683                         /* translators: %s: database host */
1684                         __( 'This means that we lost contact with the database server at %s. This could mean your host&#8217;s database server is down.' ),
1685                         '<code>' . htmlspecialchars( $this->dbhost, ENT_QUOTES ) . '</code>'
1686                 ) . "</p>\n";
1687
1688                 $message .= "<ul>\n";
1689                 $message .= '<li>' . __( 'Are you sure that the database server is running?' ) . "</li>\n";
1690                 $message .= '<li>' . __( 'Are you sure that the database server is not under particularly heavy load?' ) . "</li>\n";
1691                 $message .= "</ul>\n";
1692
1693                 $message .= '<p>' . sprintf(
1694                         /* translators: %s: support forums URL */
1695                         __( 'If you&#8217;re unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href="%s">WordPress Support Forums</a>.' ),
1696                         __( 'https://wordpress.org/support/' )
1697                 ) . "</p>\n";
1698
1699                 // We weren't able to reconnect, so we better bail.
1700                 $this->bail( $message, 'db_connect_fail' );
1701
1702                 // Call dead_db() if bail didn't die, because this database is no more. It has ceased to be (at least temporarily).
1703                 dead_db();
1704         }
1705
1706         /**
1707          * Perform a MySQL database query, using current database connection.
1708          *
1709          * More information can be found on the codex page.
1710          *
1711          * @since 0.71
1712          *
1713          * @param string $query Database query
1714          * @return int|false Number of rows affected/selected or false on error
1715          */
1716         public function query( $query ) {
1717                 if ( ! $this->ready ) {
1718                         $this->check_current_query = true;
1719                         return false;
1720                 }
1721
1722                 /**
1723                  * Filters the database query.
1724                  *
1725                  * Some queries are made before the plugins have been loaded,
1726                  * and thus cannot be filtered with this method.
1727                  *
1728                  * @since 2.1.0
1729                  *
1730                  * @param string $query Database query.
1731                  */
1732                 $query = apply_filters( 'query', $query );
1733
1734                 $this->flush();
1735
1736                 // Log how the function was called
1737                 $this->func_call = "\$db->query(\"$query\")";
1738
1739                 // If we're writing to the database, make sure the query will write safely.
1740                 if ( $this->check_current_query && ! $this->check_ascii( $query ) ) {
1741                         $stripped_query = $this->strip_invalid_text_from_query( $query );
1742                         // strip_invalid_text_from_query() can perform queries, so we need
1743                         // to flush again, just to make sure everything is clear.
1744                         $this->flush();
1745                         if ( $stripped_query !== $query ) {
1746                                 $this->insert_id = 0;
1747                                 return false;
1748                         }
1749                 }
1750
1751                 $this->check_current_query = true;
1752
1753                 // Keep track of the last query for debug.
1754                 $this->last_query = $query;
1755
1756                 $this->_do_query( $query );
1757
1758                 // MySQL server has gone away, try to reconnect.
1759                 $mysql_errno = 0;
1760                 if ( ! empty( $this->dbh ) ) {
1761                         if ( $this->use_mysqli ) {
1762                                 if ( $this->dbh instanceof mysqli ) {
1763                                         $mysql_errno = mysqli_errno( $this->dbh );
1764                                 } else {
1765                                         // $dbh is defined, but isn't a real connection.
1766                                         // Something has gone horribly wrong, let's try a reconnect.
1767                                         $mysql_errno = 2006;
1768                                 }
1769                         } else {
1770                                 if ( is_resource( $this->dbh ) ) {
1771                                         $mysql_errno = mysql_errno( $this->dbh );
1772                                 } else {
1773                                         $mysql_errno = 2006;
1774                                 }
1775                         }
1776                 }
1777
1778                 if ( empty( $this->dbh ) || 2006 == $mysql_errno ) {
1779                         if ( $this->check_connection() ) {
1780                                 $this->_do_query( $query );
1781                         } else {
1782                                 $this->insert_id = 0;
1783                                 return false;
1784                         }
1785                 }
1786
1787                 // If there is an error then take note of it.
1788                 if ( $this->use_mysqli ) {
1789                         if ( $this->dbh instanceof mysqli ) {
1790                                 $this->last_error = mysqli_error( $this->dbh );
1791                         } else {
1792                                 $this->last_error = __( 'Unable to retrieve the error message from MySQL' );
1793                         }
1794                 } else {
1795                         if ( is_resource( $this->dbh ) ) {
1796                                 $this->last_error = mysql_error( $this->dbh );
1797                         } else {
1798                                 $this->last_error = __( 'Unable to retrieve the error message from MySQL' );
1799                         }
1800                 }
1801
1802                 if ( $this->last_error ) {
1803                         // Clear insert_id on a subsequent failed insert.
1804                         if ( $this->insert_id && preg_match( '/^\s*(insert|replace)\s/i', $query ) )
1805                                 $this->insert_id = 0;
1806
1807                         $this->print_error();
1808                         return false;
1809                 }
1810
1811                 if ( preg_match( '/^\s*(create|alter|truncate|drop)\s/i', $query ) ) {
1812                         $return_val = $this->result;
1813                 } elseif ( preg_match( '/^\s*(insert|delete|update|replace)\s/i', $query ) ) {
1814                         if ( $this->use_mysqli ) {
1815                                 $this->rows_affected = mysqli_affected_rows( $this->dbh );
1816                         } else {
1817                                 $this->rows_affected = mysql_affected_rows( $this->dbh );
1818                         }
1819                         // Take note of the insert_id
1820                         if ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
1821                                 if ( $this->use_mysqli ) {
1822                                         $this->insert_id = mysqli_insert_id( $this->dbh );
1823                                 } else {
1824                                         $this->insert_id = mysql_insert_id( $this->dbh );
1825                                 }
1826                         }
1827                         // Return number of rows affected
1828                         $return_val = $this->rows_affected;
1829                 } else {
1830                         $num_rows = 0;
1831                         if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
1832                                 while ( $row = mysqli_fetch_object( $this->result ) ) {
1833                                         $this->last_result[$num_rows] = $row;
1834                                         $num_rows++;
1835                                 }
1836                         } elseif ( is_resource( $this->result ) ) {
1837                                 while ( $row = mysql_fetch_object( $this->result ) ) {
1838                                         $this->last_result[$num_rows] = $row;
1839                                         $num_rows++;
1840                                 }
1841                         }
1842
1843                         // Log number of rows the query returned
1844                         // and return number of rows selected
1845                         $this->num_rows = $num_rows;
1846                         $return_val     = $num_rows;
1847                 }
1848
1849                 return $return_val;
1850         }
1851
1852         /**
1853          * Internal function to perform the mysql_query() call.
1854          *
1855          * @since 3.9.0
1856          *
1857          * @access private
1858          * @see wpdb::query()
1859          *
1860          * @param string $query The query to run.
1861          */
1862         private function _do_query( $query ) {
1863                 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
1864                         $this->timer_start();
1865                 }
1866
1867                 if ( ! empty( $this->dbh ) && $this->use_mysqli ) {
1868                         $this->result = mysqli_query( $this->dbh, $query );
1869                 } elseif ( ! empty( $this->dbh ) ) {
1870                         $this->result = mysql_query( $query, $this->dbh );
1871                 }
1872                 $this->num_queries++;
1873
1874                 if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
1875                         $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
1876                 }
1877         }
1878
1879         /**
1880          * Insert a row into a table.
1881          *
1882          *     wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1883          *     wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1884          *
1885          * @since 2.5.0
1886          * @see wpdb::prepare()
1887          * @see wpdb::$field_types
1888          * @see wp_set_wpdb_vars()
1889          *
1890          * @param string       $table  Table name
1891          * @param array        $data   Data to insert (in column => value pairs).
1892          *                             Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1893          *                             Sending a null value will cause the column to be set to NULL - the corresponding format is ignored in this case.
1894          * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
1895          *                             If string, that format will be used for all of the values in $data.
1896          *                             A format is one of '%d', '%f', '%s' (integer, float, string).
1897          *                             If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
1898          * @return int|false The number of rows inserted, or false on error.
1899          */
1900         public function insert( $table, $data, $format = null ) {
1901                 return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
1902         }
1903
1904         /**
1905          * Replace a row into a table.
1906          *
1907          *     wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
1908          *     wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
1909          *
1910          * @since 3.0.0
1911          * @see wpdb::prepare()
1912          * @see wpdb::$field_types
1913          * @see wp_set_wpdb_vars()
1914          *
1915          * @param string       $table  Table name
1916          * @param array        $data   Data to insert (in column => value pairs).
1917          *                             Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1918          *                             Sending a null value will cause the column to be set to NULL - the corresponding format is ignored in this case.
1919          * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
1920          *                             If string, that format will be used for all of the values in $data.
1921          *                             A format is one of '%d', '%f', '%s' (integer, float, string).
1922          *                             If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
1923          * @return int|false The number of rows affected, or false on error.
1924          */
1925         public function replace( $table, $data, $format = null ) {
1926                 return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
1927         }
1928
1929         /**
1930          * Helper function for insert and replace.
1931          *
1932          * Runs an insert or replace query based on $type argument.
1933          *
1934          * @access private
1935          * @since 3.0.0
1936          * @see wpdb::prepare()
1937          * @see wpdb::$field_types
1938          * @see wp_set_wpdb_vars()
1939          *
1940          * @param string       $table  Table name
1941          * @param array        $data   Data to insert (in column => value pairs).
1942          *                             Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1943          *                             Sending a null value will cause the column to be set to NULL - the corresponding format is ignored in this case.
1944          * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
1945          *                             If string, that format will be used for all of the values in $data.
1946          *                             A format is one of '%d', '%f', '%s' (integer, float, string).
1947          *                             If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
1948          * @param string $type         Optional. What type of operation is this? INSERT or REPLACE. Defaults to INSERT.
1949          * @return int|false The number of rows affected, or false on error.
1950          */
1951         function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
1952                 $this->insert_id = 0;
1953
1954                 if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) ) {
1955                         return false;
1956                 }
1957
1958                 $data = $this->process_fields( $table, $data, $format );
1959                 if ( false === $data ) {
1960                         return false;
1961                 }
1962
1963                 $formats = $values = array();
1964                 foreach ( $data as $value ) {
1965                         if ( is_null( $value['value'] ) ) {
1966                                 $formats[] = 'NULL';
1967                                 continue;
1968                         }
1969
1970                         $formats[] = $value['format'];
1971                         $values[]  = $value['value'];
1972                 }
1973
1974                 $fields  = '`' . implode( '`, `', array_keys( $data ) ) . '`';
1975                 $formats = implode( ', ', $formats );
1976
1977                 $sql = "$type INTO `$table` ($fields) VALUES ($formats)";
1978
1979                 $this->check_current_query = false;
1980                 return $this->query( $this->prepare( $sql, $values ) );
1981         }
1982
1983         /**
1984          * Update a row in the table
1985          *
1986          *     wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
1987          *     wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
1988          *
1989          * @since 2.5.0
1990          * @see wpdb::prepare()
1991          * @see wpdb::$field_types
1992          * @see wp_set_wpdb_vars()
1993          *
1994          * @param string       $table        Table name
1995          * @param array        $data         Data to update (in column => value pairs).
1996          *                                   Both $data columns and $data values should be "raw" (neither should be SQL escaped).
1997          *                                   Sending a null value will cause the column to be set to NULL - the corresponding
1998          *                                   format is ignored in this case.
1999          * @param array        $where        A named array of WHERE clauses (in column => value pairs).
2000          *                                   Multiple clauses will be joined with ANDs.
2001          *                                   Both $where columns and $where values should be "raw".
2002          *                                   Sending a null value will create an IS NULL comparison - the corresponding format will be ignored in this case.
2003          * @param array|string $format       Optional. An array of formats to be mapped to each of the values in $data.
2004          *                                   If string, that format will be used for all of the values in $data.
2005          *                                   A format is one of '%d', '%f', '%s' (integer, float, string).
2006          *                                   If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
2007          * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where.
2008          *                                   If string, that format will be used for all of the items in $where.
2009          *                                   A format is one of '%d', '%f', '%s' (integer, float, string).
2010          *                                   If omitted, all values in $where will be treated as strings.
2011          * @return int|false The number of rows updated, or false on error.
2012          */
2013         public function update( $table, $data, $where, $format = null, $where_format = null ) {
2014                 if ( ! is_array( $data ) || ! is_array( $where ) ) {
2015                         return false;
2016                 }
2017
2018                 $data = $this->process_fields( $table, $data, $format );
2019                 if ( false === $data ) {
2020                         return false;
2021                 }
2022                 $where = $this->process_fields( $table, $where, $where_format );
2023                 if ( false === $where ) {
2024                         return false;
2025                 }
2026
2027                 $fields = $conditions = $values = array();
2028                 foreach ( $data as $field => $value ) {
2029                         if ( is_null( $value['value'] ) ) {
2030                                 $fields[] = "`$field` = NULL";
2031                                 continue;
2032                         }
2033
2034                         $fields[] = "`$field` = " . $value['format'];
2035                         $values[] = $value['value'];
2036                 }
2037                 foreach ( $where as $field => $value ) {
2038                         if ( is_null( $value['value'] ) ) {
2039                                 $conditions[] = "`$field` IS NULL";
2040                                 continue;
2041                         }
2042
2043                         $conditions[] = "`$field` = " . $value['format'];
2044                         $values[] = $value['value'];
2045                 }
2046
2047                 $fields = implode( ', ', $fields );
2048                 $conditions = implode( ' AND ', $conditions );
2049
2050                 $sql = "UPDATE `$table` SET $fields WHERE $conditions";
2051
2052                 $this->check_current_query = false;
2053                 return $this->query( $this->prepare( $sql, $values ) );
2054         }
2055
2056         /**
2057          * Delete a row in the table
2058          *
2059          *     wpdb::delete( 'table', array( 'ID' => 1 ) )
2060          *     wpdb::delete( 'table', array( 'ID' => 1 ), array( '%d' ) )
2061          *
2062          * @since 3.4.0
2063          * @see wpdb::prepare()
2064          * @see wpdb::$field_types
2065          * @see wp_set_wpdb_vars()
2066          *
2067          * @param string       $table        Table name
2068          * @param array        $where        A named array of WHERE clauses (in column => value pairs).
2069          *                                   Multiple clauses will be joined with ANDs.
2070          *                                   Both $where columns and $where values should be "raw".
2071          *                                   Sending a null value will create an IS NULL comparison - the corresponding format will be ignored in this case.
2072          * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where.
2073          *                                   If string, that format will be used for all of the items in $where.
2074          *                                   A format is one of '%d', '%f', '%s' (integer, float, string).
2075          *                                   If omitted, all values in $where will be treated as strings unless otherwise specified in wpdb::$field_types.
2076          * @return int|false The number of rows updated, or false on error.
2077          */
2078         public function delete( $table, $where, $where_format = null ) {
2079                 if ( ! is_array( $where ) ) {
2080                         return false;
2081                 }
2082
2083                 $where = $this->process_fields( $table, $where, $where_format );
2084                 if ( false === $where ) {
2085                         return false;
2086                 }
2087
2088                 $conditions = $values = array();
2089                 foreach ( $where as $field => $value ) {
2090                         if ( is_null( $value['value'] ) ) {
2091                                 $conditions[] = "`$field` IS NULL";
2092                                 continue;
2093                         }
2094
2095                         $conditions[] = "`$field` = " . $value['format'];
2096                         $values[] = $value['value'];
2097                 }
2098
2099                 $conditions = implode( ' AND ', $conditions );
2100
2101                 $sql = "DELETE FROM `$table` WHERE $conditions";
2102
2103                 $this->check_current_query = false;
2104                 return $this->query( $this->prepare( $sql, $values ) );
2105         }
2106
2107         /**
2108          * Processes arrays of field/value pairs and field formats.
2109          *
2110          * This is a helper method for wpdb's CRUD methods, which take field/value
2111          * pairs for inserts, updates, and where clauses. This method first pairs
2112          * each value with a format. Then it determines the charset of that field,
2113          * using that to determine if any invalid text would be stripped. If text is
2114          * stripped, then field processing is rejected and the query fails.
2115          *
2116          * @since 4.2.0
2117          * @access protected
2118          *
2119          * @param string $table  Table name.
2120          * @param array  $data   Field/value pair.
2121          * @param mixed  $format Format for each field.
2122          * @return array|false Returns an array of fields that contain paired values
2123          *                    and formats. Returns false for invalid values.
2124          */
2125         protected function process_fields( $table, $data, $format ) {
2126                 $data = $this->process_field_formats( $data, $format );
2127                 if ( false === $data ) {
2128                         return false;
2129                 }
2130
2131                 $data = $this->process_field_charsets( $data, $table );
2132                 if ( false === $data ) {
2133                         return false;
2134                 }
2135
2136                 $data = $this->process_field_lengths( $data, $table );
2137                 if ( false === $data ) {
2138                         return false;
2139                 }
2140
2141                 $converted_data = $this->strip_invalid_text( $data );
2142
2143                 if ( $data !== $converted_data ) {
2144                         return false;
2145                 }
2146
2147                 return $data;
2148         }
2149
2150         /**
2151          * Prepares arrays of value/format pairs as passed to wpdb CRUD methods.
2152          *
2153          * @since 4.2.0
2154          * @access protected
2155          *
2156          * @param array $data   Array of fields to values.
2157          * @param mixed $format Formats to be mapped to the values in $data.
2158          * @return array Array, keyed by field names with values being an array
2159          *               of 'value' and 'format' keys.
2160          */
2161         protected function process_field_formats( $data, $format ) {
2162                 $formats = $original_formats = (array) $format;
2163
2164                 foreach ( $data as $field => $value ) {
2165                         $value = array(
2166                                 'value'  => $value,
2167                                 'format' => '%s',
2168                         );
2169
2170                         if ( ! empty( $format ) ) {
2171                                 $value['format'] = array_shift( $formats );
2172                                 if ( ! $value['format'] ) {
2173                                         $value['format'] = reset( $original_formats );
2174                                 }
2175                         } elseif ( isset( $this->field_types[ $field ] ) ) {
2176                                 $value['format'] = $this->field_types[ $field ];
2177                         }
2178
2179                         $data[ $field ] = $value;
2180                 }
2181
2182                 return $data;
2183         }
2184
2185         /**
2186          * Adds field charsets to field/value/format arrays generated by
2187          * the wpdb::process_field_formats() method.
2188          *
2189          * @since 4.2.0
2190          * @access protected
2191          *
2192          * @param array  $data  As it comes from the wpdb::process_field_formats() method.
2193          * @param string $table Table name.
2194          * @return array|false The same array as $data with additional 'charset' keys.
2195          */
2196         protected function process_field_charsets( $data, $table ) {
2197                 foreach ( $data as $field => $value ) {
2198                         if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
2199                                 /*
2200                                  * We can skip this field if we know it isn't a string.
2201                                  * This checks %d/%f versus ! %s because its sprintf() could take more.
2202                                  */
2203                                 $value['charset'] = false;
2204                         } else {
2205                                 $value['charset'] = $this->get_col_charset( $table, $field );
2206                                 if ( is_wp_error( $value['charset'] ) ) {
2207                                         return false;
2208                                 }
2209                         }
2210
2211                         $data[ $field ] = $value;
2212                 }
2213
2214                 return $data;
2215         }
2216
2217         /**
2218          * For string fields, record the maximum string length that field can safely save.
2219          *
2220          * @since 4.2.1
2221          * @access protected
2222          *
2223          * @param array  $data  As it comes from the wpdb::process_field_charsets() method.
2224          * @param string $table Table name.
2225          * @return array|false The same array as $data with additional 'length' keys, or false if
2226          *                     any of the values were too long for their corresponding field.
2227          */
2228         protected function process_field_lengths( $data, $table ) {
2229                 foreach ( $data as $field => $value ) {
2230                         if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
2231                                 /*
2232                                  * We can skip this field if we know it isn't a string.
2233                                  * This checks %d/%f versus ! %s because its sprintf() could take more.
2234                                  */
2235                                 $value['length'] = false;
2236                         } else {
2237                                 $value['length'] = $this->get_col_length( $table, $field );
2238                                 if ( is_wp_error( $value['length'] ) ) {
2239                                         return false;
2240                                 }
2241                         }
2242
2243                         $data[ $field ] = $value;
2244                 }
2245
2246                 return $data;
2247         }
2248
2249         /**
2250          * Retrieve one variable from the database.
2251          *
2252          * Executes a SQL query and returns the value from the SQL result.
2253          * If the SQL result contains more than one column and/or more than one row, this function returns the value in the column and row specified.
2254          * If $query is null, this function returns the value in the specified column and row from the previous SQL result.
2255          *
2256          * @since 0.71
2257          *
2258          * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
2259          * @param int         $x     Optional. Column of value to return. Indexed from 0.
2260          * @param int         $y     Optional. Row of value to return. Indexed from 0.
2261          * @return string|null Database query result (as string), or null on failure
2262          */
2263         public function get_var( $query = null, $x = 0, $y = 0 ) {
2264                 $this->func_call = "\$db->get_var(\"$query\", $x, $y)";
2265
2266                 if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
2267                         $this->check_current_query = false;
2268                 }
2269
2270                 if ( $query ) {
2271                         $this->query( $query );
2272                 }
2273
2274                 // Extract var out of cached results based x,y vals
2275                 if ( !empty( $this->last_result[$y] ) ) {
2276                         $values = array_values( get_object_vars( $this->last_result[$y] ) );
2277                 }
2278
2279                 // If there is a value return it else return null
2280                 return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null;
2281         }
2282
2283         /**
2284          * Retrieve one row from the database.
2285          *
2286          * Executes a SQL query and returns the row from the SQL result.
2287          *
2288          * @since 0.71
2289          *
2290          * @param string|null $query  SQL query.
2291          * @param string      $output Optional. one of ARRAY_A | ARRAY_N | OBJECT constants.
2292          *                            Return an associative array (column => value, ...),
2293          *                            a numerically indexed array (0 => value, ...) or
2294          *                            an object ( ->column = value ), respectively.
2295          * @param int         $y      Optional. Row to return. Indexed from 0.
2296          * @return array|object|null|void Database query result in format specified by $output or null on failure
2297          */
2298         public function get_row( $query = null, $output = OBJECT, $y = 0 ) {
2299                 $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
2300
2301                 if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
2302                         $this->check_current_query = false;
2303                 }
2304
2305                 if ( $query ) {
2306                         $this->query( $query );
2307                 } else {
2308                         return null;
2309                 }
2310
2311                 if ( !isset( $this->last_result[$y] ) )
2312                         return null;
2313
2314                 if ( $output == OBJECT ) {
2315                         return $this->last_result[$y] ? $this->last_result[$y] : null;
2316                 } elseif ( $output == ARRAY_A ) {
2317                         return $this->last_result[$y] ? get_object_vars( $this->last_result[$y] ) : null;
2318                 } elseif ( $output == ARRAY_N ) {
2319                         return $this->last_result[$y] ? array_values( get_object_vars( $this->last_result[$y] ) ) : null;
2320                 } elseif ( strtoupper( $output ) === OBJECT ) {
2321                         // Back compat for OBJECT being previously case insensitive.
2322                         return $this->last_result[$y] ? $this->last_result[$y] : null;
2323                 } else {
2324                         $this->print_error( " \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N" );
2325                 }
2326         }
2327
2328         /**
2329          * Retrieve one column from the database.
2330          *
2331          * Executes a SQL query and returns the column from the SQL result.
2332          * If the SQL result contains more than one column, this function returns the column specified.
2333          * If $query is null, this function returns the specified column from the previous SQL result.
2334          *
2335          * @since 0.71
2336          *
2337          * @param string|null $query Optional. SQL query. Defaults to previous query.
2338          * @param int         $x     Optional. Column to return. Indexed from 0.
2339          * @return array Database query result. Array indexed from 0 by SQL result row number.
2340          */
2341         public function get_col( $query = null , $x = 0 ) {
2342                 if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
2343                         $this->check_current_query = false;
2344                 }
2345
2346                 if ( $query ) {
2347                         $this->query( $query );
2348                 }
2349
2350                 $new_array = array();
2351                 // Extract the column values
2352                 for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
2353                         $new_array[$i] = $this->get_var( null, $x, $i );
2354                 }
2355                 return $new_array;
2356         }
2357
2358         /**
2359          * Retrieve an entire SQL result set from the database (i.e., many rows)
2360          *
2361          * Executes a SQL query and returns the entire SQL result.
2362          *
2363          * @since 0.71
2364          *
2365          * @param string $query  SQL query.
2366          * @param string $output Optional. Any of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants.
2367          *                       With one of the first three, return an array of rows indexed from 0 by SQL result row number.
2368          *                       Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively.
2369          *                       With OBJECT_K, return an associative array of row objects keyed by the value of each row's first column's value.
2370          *                       Duplicate keys are discarded.
2371          * @return array|object|null Database query results
2372          */
2373         public function get_results( $query = null, $output = OBJECT ) {
2374                 $this->func_call = "\$db->get_results(\"$query\", $output)";
2375
2376                 if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
2377                         $this->check_current_query = false;
2378                 }
2379
2380                 if ( $query ) {
2381                         $this->query( $query );
2382                 } else {
2383                         return null;
2384                 }
2385
2386                 $new_array = array();
2387                 if ( $output == OBJECT ) {
2388                         // Return an integer-keyed array of row objects
2389                         return $this->last_result;
2390                 } elseif ( $output == OBJECT_K ) {
2391                         // Return an array of row objects with keys from column 1
2392                         // (Duplicates are discarded)
2393                         foreach ( $this->last_result as $row ) {
2394                                 $var_by_ref = get_object_vars( $row );
2395                                 $key = array_shift( $var_by_ref );
2396                                 if ( ! isset( $new_array[ $key ] ) )
2397                                         $new_array[ $key ] = $row;
2398                         }
2399                         return $new_array;
2400                 } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
2401                         // Return an integer-keyed array of...
2402                         if ( $this->last_result ) {
2403                                 foreach ( (array) $this->last_result as $row ) {
2404                                         if ( $output == ARRAY_N ) {
2405                                                 // ...integer-keyed row arrays
2406                                                 $new_array[] = array_values( get_object_vars( $row ) );
2407                                         } else {
2408                                                 // ...column name-keyed row arrays
2409                                                 $new_array[] = get_object_vars( $row );
2410                                         }
2411                                 }
2412                         }
2413                         return $new_array;
2414                 } elseif ( strtoupper( $output ) === OBJECT ) {
2415                         // Back compat for OBJECT being previously case insensitive.
2416                         return $this->last_result;
2417                 }
2418                 return null;
2419         }
2420
2421         /**
2422          * Retrieves the character set for the given table.
2423          *
2424          * @since 4.2.0
2425          * @access protected
2426          *
2427          * @param string $table Table name.
2428          * @return string|WP_Error Table character set, WP_Error object if it couldn't be found.
2429          */
2430         protected function get_table_charset( $table ) {
2431                 $tablekey = strtolower( $table );
2432
2433                 /**
2434                  * Filters the table charset value before the DB is checked.
2435                  *
2436                  * Passing a non-null value to the filter will effectively short-circuit
2437                  * checking the DB for the charset, returning that value instead.
2438                  *
2439                  * @since 4.2.0
2440                  *
2441                  * @param string $charset The character set to use. Default null.
2442                  * @param string $table   The name of the table being checked.
2443                  */
2444                 $charset = apply_filters( 'pre_get_table_charset', null, $table );
2445                 if ( null !== $charset ) {
2446                         return $charset;
2447                 }
2448
2449                 if ( isset( $this->table_charset[ $tablekey ] ) ) {
2450                         return $this->table_charset[ $tablekey ];
2451                 }
2452
2453                 $charsets = $columns = array();
2454
2455                 $table_parts = explode( '.', $table );
2456                 $table = '`' . implode( '`.`', $table_parts ) . '`';
2457                 $results = $this->get_results( "SHOW FULL COLUMNS FROM $table" );
2458                 if ( ! $results ) {
2459                         return new WP_Error( 'wpdb_get_table_charset_failure' );
2460                 }
2461
2462                 foreach ( $results as $column ) {
2463                         $columns[ strtolower( $column->Field ) ] = $column;
2464                 }
2465
2466                 $this->col_meta[ $tablekey ] = $columns;
2467
2468                 foreach ( $columns as $column ) {
2469                         if ( ! empty( $column->Collation ) ) {
2470                                 list( $charset ) = explode( '_', $column->Collation );
2471
2472                                 // If the current connection can't support utf8mb4 characters, let's only send 3-byte utf8 characters.
2473                                 if ( 'utf8mb4' === $charset && ! $this->has_cap( 'utf8mb4' ) ) {
2474                                         $charset = 'utf8';
2475                                 }
2476
2477                                 $charsets[ strtolower( $charset ) ] = true;
2478                         }
2479
2480                         list( $type ) = explode( '(', $column->Type );
2481
2482                         // A binary/blob means the whole query gets treated like this.
2483                         if ( in_array( strtoupper( $type ), array( 'BINARY', 'VARBINARY', 'TINYBLOB', 'MEDIUMBLOB', 'BLOB', 'LONGBLOB' ) ) ) {
2484                                 $this->table_charset[ $tablekey ] = 'binary';
2485                                 return 'binary';
2486                         }
2487                 }
2488
2489                 // utf8mb3 is an alias for utf8.
2490                 if ( isset( $charsets['utf8mb3'] ) ) {
2491                         $charsets['utf8'] = true;
2492                         unset( $charsets['utf8mb3'] );
2493                 }
2494
2495                 // Check if we have more than one charset in play.
2496                 $count = count( $charsets );
2497                 if ( 1 === $count ) {
2498                         $charset = key( $charsets );
2499                 } elseif ( 0 === $count ) {
2500                         // No charsets, assume this table can store whatever.
2501                         $charset = false;
2502                 } else {
2503                         // More than one charset. Remove latin1 if present and recalculate.
2504                         unset( $charsets['latin1'] );
2505                         $count = count( $charsets );
2506                         if ( 1 === $count ) {
2507                                 // Only one charset (besides latin1).
2508                                 $charset = key( $charsets );
2509                         } elseif ( 2 === $count && isset( $charsets['utf8'], $charsets['utf8mb4'] ) ) {
2510                                 // Two charsets, but they're utf8 and utf8mb4, use utf8.
2511                                 $charset = 'utf8';
2512                         } else {
2513                                 // Two mixed character sets. ascii.
2514                                 $charset = 'ascii';
2515                         }
2516                 }
2517
2518                 $this->table_charset[ $tablekey ] = $charset;
2519                 return $charset;
2520         }
2521
2522         /**
2523          * Retrieves the character set for the given column.
2524          *
2525          * @since 4.2.0
2526          * @access public
2527          *
2528          * @param string $table  Table name.
2529          * @param string $column Column name.
2530          * @return string|false|WP_Error Column character set as a string. False if the column has no
2531          *                               character set. WP_Error object if there was an error.
2532          */
2533         public function get_col_charset( $table, $column ) {
2534                 $tablekey = strtolower( $table );
2535                 $columnkey = strtolower( $column );
2536
2537                 /**
2538                  * Filters the column charset value before the DB is checked.
2539                  *
2540                  * Passing a non-null value to the filter will short-circuit
2541                  * checking the DB for the charset, returning that value instead.
2542                  *
2543                  * @since 4.2.0
2544                  *
2545                  * @param string $charset The character set to use. Default null.
2546                  * @param string $table   The name of the table being checked.
2547                  * @param string $column  The name of the column being checked.
2548                  */
2549                 $charset = apply_filters( 'pre_get_col_charset', null, $table, $column );
2550                 if ( null !== $charset ) {
2551                         return $charset;
2552                 }
2553
2554                 // Skip this entirely if this isn't a MySQL database.
2555                 if ( empty( $this->is_mysql ) ) {
2556                         return false;
2557                 }
2558
2559                 if ( empty( $this->table_charset[ $tablekey ] ) ) {
2560                         // This primes column information for us.
2561                         $table_charset = $this->get_table_charset( $table );
2562                         if ( is_wp_error( $table_charset ) ) {
2563                                 return $table_charset;
2564                         }
2565                 }
2566
2567                 // If still no column information, return the table charset.
2568                 if ( empty( $this->col_meta[ $tablekey ] ) ) {
2569                         return $this->table_charset[ $tablekey ];
2570                 }
2571
2572                 // If this column doesn't exist, return the table charset.
2573                 if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
2574                         return $this->table_charset[ $tablekey ];
2575                 }
2576
2577                 // Return false when it's not a string column.
2578                 if ( empty( $this->col_meta[ $tablekey ][ $columnkey ]->Collation ) ) {
2579                         return false;
2580                 }
2581
2582                 list( $charset ) = explode( '_', $this->col_meta[ $tablekey ][ $columnkey ]->Collation );
2583                 return $charset;
2584         }
2585
2586         /**
2587          * Retrieve the maximum string length allowed in a given column.
2588          * The length may either be specified as a byte length or a character length.
2589          *
2590          * @since 4.2.1
2591          * @access public
2592          *
2593          * @param string $table  Table name.
2594          * @param string $column Column name.
2595          * @return array|false|WP_Error array( 'length' => (int), 'type' => 'byte' | 'char' )
2596          *                              false if the column has no length (for example, numeric column)
2597          *                              WP_Error object if there was an error.
2598          */
2599         public function get_col_length( $table, $column ) {
2600                 $tablekey = strtolower( $table );
2601                 $columnkey = strtolower( $column );
2602
2603                 // Skip this entirely if this isn't a MySQL database.
2604                 if ( empty( $this->is_mysql ) ) {
2605                         return false;
2606                 }
2607
2608                 if ( empty( $this->col_meta[ $tablekey ] ) ) {
2609                         // This primes column information for us.
2610                         $table_charset = $this->get_table_charset( $table );
2611                         if ( is_wp_error( $table_charset ) ) {
2612                                 return $table_charset;
2613                         }
2614                 }
2615
2616                 if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
2617                         return false;
2618                 }
2619
2620                 $typeinfo = explode( '(', $this->col_meta[ $tablekey ][ $columnkey ]->Type );
2621
2622                 $type = strtolower( $typeinfo[0] );
2623                 if ( ! empty( $typeinfo[1] ) ) {
2624                         $length = trim( $typeinfo[1], ')' );
2625                 } else {
2626                         $length = false;
2627                 }
2628
2629                 switch( $type ) {
2630                         case 'char':
2631                         case 'varchar':
2632                                 return array(
2633                                         'type'   => 'char',
2634                                         'length' => (int) $length,
2635                                 );
2636
2637                         case 'binary':
2638                         case 'varbinary':
2639                                 return array(
2640                                         'type'   => 'byte',
2641                                         'length' => (int) $length,
2642                                 );
2643
2644                         case 'tinyblob':
2645                         case 'tinytext':
2646                                 return array(
2647                                         'type'   => 'byte',
2648                                         'length' => 255,        // 2^8 - 1
2649                                 );
2650
2651                         case 'blob':
2652                         case 'text':
2653                                 return array(
2654                                         'type'   => 'byte',
2655                                         'length' => 65535,      // 2^16 - 1
2656                                 );
2657
2658                         case 'mediumblob':
2659                         case 'mediumtext':
2660                                 return array(
2661                                         'type'   => 'byte',
2662                                         'length' => 16777215,   // 2^24 - 1
2663                                 );
2664
2665                         case 'longblob':
2666                         case 'longtext':
2667                                 return array(
2668                                         'type'   => 'byte',
2669                                         'length' => 4294967295, // 2^32 - 1
2670                                 );
2671
2672                         default:
2673                                 return false;
2674                 }
2675         }
2676
2677         /**
2678          * Check if a string is ASCII.
2679          *
2680          * The negative regex is faster for non-ASCII strings, as it allows
2681          * the search to finish as soon as it encounters a non-ASCII character.
2682          *
2683          * @since 4.2.0
2684          * @access protected
2685          *
2686          * @param string $string String to check.
2687          * @return bool True if ASCII, false if not.
2688          */
2689         protected function check_ascii( $string ) {
2690                 if ( function_exists( 'mb_check_encoding' ) ) {
2691                         if ( mb_check_encoding( $string, 'ASCII' ) ) {
2692                                 return true;
2693                         }
2694                 } elseif ( ! preg_match( '/[^\x00-\x7F]/', $string ) ) {
2695                         return true;
2696                 }
2697
2698                 return false;
2699         }
2700
2701         /**
2702          * Check if the query is accessing a collation considered safe on the current version of MySQL.
2703          *
2704          * @since 4.2.0
2705          * @access protected
2706          *
2707          * @param string $query The query to check.
2708          * @return bool True if the collation is safe, false if it isn't.
2709          */
2710         protected function check_safe_collation( $query ) {
2711                 if ( $this->checking_collation ) {
2712                         return true;
2713                 }
2714
2715                 // We don't need to check the collation for queries that don't read data.
2716                 $query = ltrim( $query, "\r\n\t (" );
2717                 if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN|CREATE)\s/i', $query ) ) {
2718                         return true;
2719                 }
2720
2721                 // All-ASCII queries don't need extra checking.
2722                 if ( $this->check_ascii( $query ) ) {
2723                         return true;
2724                 }
2725
2726                 $table = $this->get_table_from_query( $query );
2727                 if ( ! $table ) {
2728                         return false;
2729                 }
2730
2731                 $this->checking_collation = true;
2732                 $collation = $this->get_table_charset( $table );
2733                 $this->checking_collation = false;
2734
2735                 // Tables with no collation, or latin1 only, don't need extra checking.
2736                 if ( false === $collation || 'latin1' === $collation ) {
2737                         return true;
2738                 }
2739
2740                 $table = strtolower( $table );
2741                 if ( empty( $this->col_meta[ $table ] ) ) {
2742                         return false;
2743                 }
2744
2745                 // If any of the columns don't have one of these collations, it needs more sanity checking.
2746                 foreach ( $this->col_meta[ $table ] as $col ) {
2747                         if ( empty( $col->Collation ) ) {
2748                                 continue;
2749                         }
2750
2751                         if ( ! in_array( $col->Collation, array( 'utf8_general_ci', 'utf8_bin', 'utf8mb4_general_ci', 'utf8mb4_bin' ), true ) ) {
2752                                 return false;
2753                         }
2754                 }
2755
2756                 return true;
2757         }
2758
2759         /**
2760          * Strips any invalid characters based on value/charset pairs.
2761          *
2762          * @since 4.2.0
2763          * @access protected
2764          *
2765          * @param array $data Array of value arrays. Each value array has the keys
2766          *                    'value' and 'charset'. An optional 'ascii' key can be
2767          *                    set to false to avoid redundant ASCII checks.
2768          * @return array|WP_Error The $data parameter, with invalid characters removed from
2769          *                        each value. This works as a passthrough: any additional keys
2770          *                        such as 'field' are retained in each value array. If we cannot
2771          *                        remove invalid characters, a WP_Error object is returned.
2772          */
2773         protected function strip_invalid_text( $data ) {
2774                 $db_check_string = false;
2775
2776                 foreach ( $data as &$value ) {
2777                         $charset = $value['charset'];
2778
2779                         if ( is_array( $value['length'] ) ) {
2780                                 $length = $value['length']['length'];
2781                                 $truncate_by_byte_length = 'byte' === $value['length']['type'];
2782                         } else {
2783                                 $length = false;
2784                                 // Since we have no length, we'll never truncate.
2785                                 // Initialize the variable to false. true would take us
2786                                 // through an unnecessary (for this case) codepath below.
2787                                 $truncate_by_byte_length = false;
2788                         }
2789
2790                         // There's no charset to work with.
2791                         if ( false === $charset ) {
2792                                 continue;
2793                         }
2794
2795                         // Column isn't a string.
2796                         if ( ! is_string( $value['value'] ) ) {
2797                                 continue;
2798                         }
2799
2800                         $needs_validation = true;
2801                         if (
2802                                 // latin1 can store any byte sequence
2803                                 'latin1' === $charset
2804                         ||
2805                                 // ASCII is always OK.
2806                                 ( ! isset( $value['ascii'] ) && $this->check_ascii( $value['value'] ) )
2807                         ) {
2808                                 $truncate_by_byte_length = true;
2809                                 $needs_validation = false;
2810                         }
2811
2812                         if ( $truncate_by_byte_length ) {
2813                                 mbstring_binary_safe_encoding();
2814                                 if ( false !== $length && strlen( $value['value'] ) > $length ) {
2815                                         $value['value'] = substr( $value['value'], 0, $length );
2816                                 }
2817                                 reset_mbstring_encoding();
2818
2819                                 if ( ! $needs_validation ) {
2820                                         continue;
2821                                 }
2822                         }
2823
2824                         // utf8 can be handled by regex, which is a bunch faster than a DB lookup.
2825                         if ( ( 'utf8' === $charset || 'utf8mb3' === $charset || 'utf8mb4' === $charset ) && function_exists( 'mb_strlen' ) ) {
2826                                 $regex = '/
2827                                         (
2828                                                 (?: [\x00-\x7F]                  # single-byte sequences   0xxxxxxx
2829                                                 |   [\xC2-\xDF][\x80-\xBF]       # double-byte sequences   110xxxxx 10xxxxxx
2830                                                 |   \xE0[\xA0-\xBF][\x80-\xBF]   # triple-byte sequences   1110xxxx 10xxxxxx * 2
2831                                                 |   [\xE1-\xEC][\x80-\xBF]{2}
2832                                                 |   \xED[\x80-\x9F][\x80-\xBF]
2833                                                 |   [\xEE-\xEF][\x80-\xBF]{2}';
2834
2835                                 if ( 'utf8mb4' === $charset ) {
2836                                         $regex .= '
2837                                                 |    \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences   11110xxx 10xxxxxx * 3
2838                                                 |    [\xF1-\xF3][\x80-\xBF]{3}
2839                                                 |    \xF4[\x80-\x8F][\x80-\xBF]{2}
2840                                         ';
2841                                 }
2842
2843                                 $regex .= '){1,40}                          # ...one or more times
2844                                         )
2845                                         | .                                  # anything else
2846                                         /x';
2847                                 $value['value'] = preg_replace( $regex, '$1', $value['value'] );
2848
2849
2850                                 if ( false !== $length && mb_strlen( $value['value'], 'UTF-8' ) > $length ) {
2851                                         $value['value'] = mb_substr( $value['value'], 0, $length, 'UTF-8' );
2852                                 }
2853                                 continue;
2854                         }
2855
2856                         // We couldn't use any local conversions, send it to the DB.
2857                         $value['db'] = $db_check_string = true;
2858                 }
2859                 unset( $value ); // Remove by reference.
2860
2861                 if ( $db_check_string ) {
2862                         $queries = array();
2863                         foreach ( $data as $col => $value ) {
2864                                 if ( ! empty( $value['db'] ) ) {
2865                                         // We're going to need to truncate by characters or bytes, depending on the length value we have.
2866                                         if ( 'byte' === $value['length']['type'] ) {
2867                                                 // Using binary causes LEFT() to truncate by bytes.
2868                                                 $charset = 'binary';
2869                                         } else {
2870                                                 $charset = $value['charset'];
2871                                         }
2872
2873                                         if ( $this->charset ) {
2874                                                 $connection_charset = $this->charset;
2875                                         } else {
2876                                                 if ( $this->use_mysqli ) {
2877                                                         $connection_charset = mysqli_character_set_name( $this->dbh );
2878                                                 } else {
2879                                                         $connection_charset = mysql_client_encoding();
2880                                                 }
2881                                         }
2882
2883                                         if ( is_array( $value['length'] ) ) {
2884                                                 $queries[ $col ] = $this->prepare( "CONVERT( LEFT( CONVERT( %s USING $charset ), %.0f ) USING $connection_charset )", $value['value'], $value['length']['length'] );
2885                                         } else if ( 'binary' !== $charset ) {
2886                                                 // If we don't have a length, there's no need to convert binary - it will always return the same result.
2887                                                 $queries[ $col ] = $this->prepare( "CONVERT( CONVERT( %s USING $charset ) USING $connection_charset )", $value['value'] );
2888                                         }
2889
2890                                         unset( $data[ $col ]['db'] );
2891                                 }
2892                         }
2893
2894                         $sql = array();
2895                         foreach ( $queries as $column => $query ) {
2896                                 if ( ! $query ) {
2897                                         continue;
2898                                 }
2899
2900                                 $sql[] = $query . " AS x_$column";
2901                         }
2902
2903                         $this->check_current_query = false;
2904                         $row = $this->get_row( "SELECT " . implode( ', ', $sql ), ARRAY_A );
2905                         if ( ! $row ) {
2906                                 return new WP_Error( 'wpdb_strip_invalid_text_failure' );
2907                         }
2908
2909                         foreach ( array_keys( $data ) as $column ) {
2910                                 if ( isset( $row["x_$column"] ) ) {
2911                                         $data[ $column ]['value'] = $row["x_$column"];
2912                                 }
2913                         }
2914                 }
2915
2916                 return $data;
2917         }
2918
2919         /**
2920          * Strips any invalid characters from the query.
2921          *
2922          * @since 4.2.0
2923          * @access protected
2924          *
2925          * @param string $query Query to convert.
2926          * @return string|WP_Error The converted query, or a WP_Error object if the conversion fails.
2927          */
2928         protected function strip_invalid_text_from_query( $query ) {
2929                 // We don't need to check the collation for queries that don't read data.
2930                 $trimmed_query = ltrim( $query, "\r\n\t (" );
2931                 if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN|CREATE)\s/i', $trimmed_query ) ) {
2932                         return $query;
2933                 }
2934
2935                 $table = $this->get_table_from_query( $query );
2936                 if ( $table ) {
2937                         $charset = $this->get_table_charset( $table );
2938                         if ( is_wp_error( $charset ) ) {
2939                                 return $charset;
2940                         }
2941
2942                         // We can't reliably strip text from tables containing binary/blob columns
2943                         if ( 'binary' === $charset ) {
2944                                 return $query;
2945                         }
2946                 } else {
2947                         $charset = $this->charset;
2948                 }
2949
2950                 $data = array(
2951                         'value'   => $query,
2952                         'charset' => $charset,
2953                         'ascii'   => false,
2954                         'length'  => false,
2955                 );
2956
2957                 $data = $this->strip_invalid_text( array( $data ) );
2958                 if ( is_wp_error( $data ) ) {
2959                         return $data;
2960                 }
2961
2962                 return $data[0]['value'];
2963         }
2964
2965         /**
2966          * Strips any invalid characters from the string for a given table and column.
2967          *
2968          * @since 4.2.0
2969          * @access public
2970          *
2971          * @param string $table  Table name.
2972          * @param string $column Column name.
2973          * @param string $value  The text to check.
2974          * @return string|WP_Error The converted string, or a WP_Error object if the conversion fails.
2975          */
2976         public function strip_invalid_text_for_column( $table, $column, $value ) {
2977                 if ( ! is_string( $value ) ) {
2978                         return $value;
2979                 }
2980
2981                 $charset = $this->get_col_charset( $table, $column );
2982                 if ( ! $charset ) {
2983                         // Not a string column.
2984                         return $value;
2985                 } elseif ( is_wp_error( $charset ) ) {
2986                         // Bail on real errors.
2987                         return $charset;
2988                 }
2989
2990                 $data = array(
2991                         $column => array(
2992                                 'value'   => $value,
2993                                 'charset' => $charset,
2994                                 'length'  => $this->get_col_length( $table, $column ),
2995                         )
2996                 );
2997
2998                 $data = $this->strip_invalid_text( $data );
2999                 if ( is_wp_error( $data ) ) {
3000                         return $data;
3001                 }
3002
3003                 return $data[ $column ]['value'];
3004         }
3005
3006         /**
3007          * Find the first table name referenced in a query.
3008          *
3009          * @since 4.2.0
3010          * @access protected
3011          *
3012          * @param string $query The query to search.
3013          * @return string|false $table The table name found, or false if a table couldn't be found.
3014          */
3015         protected function get_table_from_query( $query ) {
3016                 // Remove characters that can legally trail the table name.
3017                 $query = rtrim( $query, ';/-#' );
3018
3019                 // Allow (select...) union [...] style queries. Use the first query's table name.
3020                 $query = ltrim( $query, "\r\n\t (" );
3021
3022                 // Strip everything between parentheses except nested selects.
3023                 $query = preg_replace( '/\((?!\s*select)[^(]*?\)/is', '()', $query );
3024
3025                 // Quickly match most common queries.
3026                 if ( preg_match( '/^\s*(?:'
3027                                 . 'SELECT.*?\s+FROM'
3028                                 . '|INSERT(?:\s+LOW_PRIORITY|\s+DELAYED|\s+HIGH_PRIORITY)?(?:\s+IGNORE)?(?:\s+INTO)?'
3029                                 . '|REPLACE(?:\s+LOW_PRIORITY|\s+DELAYED)?(?:\s+INTO)?'
3030                                 . '|UPDATE(?:\s+LOW_PRIORITY)?(?:\s+IGNORE)?'
3031                                 . '|DELETE(?:\s+LOW_PRIORITY|\s+QUICK|\s+IGNORE)*(?:\s+FROM)?'
3032                                 . ')\s+((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)/is', $query, $maybe ) ) {
3033                         return str_replace( '`', '', $maybe[1] );
3034                 }
3035
3036                 // SHOW TABLE STATUS and SHOW TABLES
3037                 if ( preg_match( '/^\s*(?:'
3038                                 . 'SHOW\s+TABLE\s+STATUS.+(?:LIKE\s+|WHERE\s+Name\s*=\s*)'
3039                                 . '|SHOW\s+(?:FULL\s+)?TABLES.+(?:LIKE\s+|WHERE\s+Name\s*=\s*)'
3040                                 . ')\W((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)\W/is', $query, $maybe ) ) {
3041                         return str_replace( '`', '', $maybe[1] );
3042                 }
3043
3044                 // Big pattern for the rest of the table-related queries.
3045                 if ( preg_match( '/^\s*(?:'
3046                                 . '(?:EXPLAIN\s+(?:EXTENDED\s+)?)?SELECT.*?\s+FROM'
3047                                 . '|DESCRIBE|DESC|EXPLAIN|HANDLER'
3048                                 . '|(?:LOCK|UNLOCK)\s+TABLE(?:S)?'
3049                                 . '|(?:RENAME|OPTIMIZE|BACKUP|RESTORE|CHECK|CHECKSUM|ANALYZE|REPAIR).*\s+TABLE'
3050                                 . '|TRUNCATE(?:\s+TABLE)?'
3051                                 . '|CREATE(?:\s+TEMPORARY)?\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?'
3052                                 . '|ALTER(?:\s+IGNORE)?\s+TABLE'
3053                                 . '|DROP\s+TABLE(?:\s+IF\s+EXISTS)?'
3054                                 . '|CREATE(?:\s+\w+)?\s+INDEX.*\s+ON'
3055                                 . '|DROP\s+INDEX.*\s+ON'
3056                                 . '|LOAD\s+DATA.*INFILE.*INTO\s+TABLE'
3057                                 . '|(?:GRANT|REVOKE).*ON\s+TABLE'
3058                                 . '|SHOW\s+(?:.*FROM|.*TABLE)'
3059                                 . ')\s+\(*\s*((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)\s*\)*/is', $query, $maybe ) ) {
3060                         return str_replace( '`', '', $maybe[1] );
3061                 }
3062
3063                 return false;
3064         }
3065
3066         /**
3067          * Load the column metadata from the last query.
3068          *
3069          * @since 3.5.0
3070          *
3071          * @access protected
3072          */
3073         protected function load_col_info() {
3074                 if ( $this->col_info )
3075                         return;
3076
3077                 if ( $this->use_mysqli ) {
3078                         $num_fields = mysqli_num_fields( $this->result );
3079                         for ( $i = 0; $i < $num_fields; $i++ ) {
3080                                 $this->col_info[ $i ] = mysqli_fetch_field( $this->result );
3081                         }
3082                 } else {
3083                         $num_fields = mysql_num_fields( $this->result );
3084                         for ( $i = 0; $i < $num_fields; $i++ ) {
3085                                 $this->col_info[ $i ] = mysql_fetch_field( $this->result, $i );
3086                         }
3087                 }
3088         }
3089
3090         /**
3091          * Retrieve column metadata from the last query.
3092          *
3093          * @since 0.71
3094          *
3095          * @param string $info_type  Optional. Type one of name, table, def, max_length, not_null, primary_key, multiple_key, unique_key, numeric, blob, type, unsigned, zerofill
3096          * @param int    $col_offset Optional. 0: col name. 1: which table the col's in. 2: col's max length. 3: if the col is numeric. 4: col's type
3097          * @return mixed Column Results
3098          */
3099         public function get_col_info( $info_type = 'name', $col_offset = -1 ) {
3100                 $this->load_col_info();
3101
3102                 if ( $this->col_info ) {
3103                         if ( $col_offset == -1 ) {
3104                                 $i = 0;
3105                                 $new_array = array();
3106                                 foreach ( (array) $this->col_info as $col ) {
3107                                         $new_array[$i] = $col->{$info_type};
3108                                         $i++;
3109                                 }
3110                                 return $new_array;
3111                         } else {
3112                                 return $this->col_info[$col_offset]->{$info_type};
3113                         }
3114                 }
3115         }
3116
3117         /**
3118          * Starts the timer, for debugging purposes.
3119          *
3120          * @since 1.5.0
3121          *
3122          * @return true
3123          */
3124         public function timer_start() {
3125                 $this->time_start = microtime( true );
3126                 return true;
3127         }
3128
3129         /**
3130          * Stops the debugging timer.
3131          *
3132          * @since 1.5.0
3133          *
3134          * @return float Total time spent on the query, in seconds
3135          */
3136         public function timer_stop() {
3137                 return ( microtime( true ) - $this->time_start );
3138         }
3139
3140         /**
3141          * Wraps errors in a nice header and footer and dies.
3142          *
3143          * Will not die if wpdb::$show_errors is false.
3144          *
3145          * @since 1.5.0
3146          *
3147          * @param string $message    The Error message
3148          * @param string $error_code Optional. A Computer readable string to identify the error.
3149          * @return false|void
3150          */
3151         public function bail( $message, $error_code = '500' ) {
3152                 if ( !$this->show_errors ) {
3153                         if ( class_exists( 'WP_Error', false ) ) {
3154                                 $this->error = new WP_Error($error_code, $message);
3155                         } else {
3156                                 $this->error = $message;
3157                         }
3158                         return false;
3159                 }
3160                 wp_die($message);
3161         }
3162
3163
3164         /**
3165          * Closes the current database connection.
3166          *
3167          * @since 4.5.0
3168          * @access public
3169          *
3170          * @return bool True if the connection was successfully closed, false if it wasn't,
3171          *              or the connection doesn't exist.
3172          */
3173         public function close() {
3174                 if ( ! $this->dbh ) {
3175                         return false;
3176                 }
3177
3178                 if ( $this->use_mysqli ) {
3179                         $closed = mysqli_close( $this->dbh );
3180                 } else {
3181                         $closed = mysql_close( $this->dbh );
3182                 }
3183
3184                 if ( $closed ) {
3185                         $this->dbh = null;
3186                         $this->ready = false;
3187                         $this->has_connected = false;
3188                 }
3189
3190                 return $closed;
3191         }
3192
3193         /**
3194          * Whether MySQL database is at least the required minimum version.
3195          *
3196          * @since 2.5.0
3197          *
3198          * @global string $wp_version
3199          * @global string $required_mysql_version
3200          *
3201          * @return WP_Error|void
3202          */
3203         public function check_database_version() {
3204                 global $wp_version, $required_mysql_version;
3205                 // Make sure the server has the required MySQL version
3206                 if ( version_compare($this->db_version(), $required_mysql_version, '<') )
3207                         return new WP_Error('database_version', sprintf( __( '<strong>ERROR</strong>: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ));
3208         }
3209
3210         /**
3211          * Whether the database supports collation.
3212          *
3213          * Called when WordPress is generating the table scheme.
3214          *
3215          * Use `wpdb::has_cap( 'collation' )`.
3216          *
3217          * @since 2.5.0
3218          * @deprecated 3.5.0 Use wpdb::has_cap()
3219          *
3220          * @return bool True if collation is supported, false if version does not
3221          */
3222         public function supports_collation() {
3223                 _deprecated_function( __FUNCTION__, '3.5.0', 'wpdb::has_cap( \'collation\' )' );
3224                 return $this->has_cap( 'collation' );
3225         }
3226
3227         /**
3228          * The database character collate.
3229          *
3230          * @since 3.5.0
3231          *
3232          * @return string The database character collate.
3233          */
3234         public function get_charset_collate() {
3235                 $charset_collate = '';
3236
3237                 if ( ! empty( $this->charset ) )
3238                         $charset_collate = "DEFAULT CHARACTER SET $this->charset";
3239                 if ( ! empty( $this->collate ) )
3240                         $charset_collate .= " COLLATE $this->collate";
3241
3242                 return $charset_collate;
3243         }
3244
3245         /**
3246          * Determine if a database supports a particular feature.
3247          *
3248          * @since 2.7.0
3249          * @since 4.1.0 Added support for the 'utf8mb4' feature.
3250          * @since 4.6.0 Added support for the 'utf8mb4_520' feature.
3251          *
3252          * @see wpdb::db_version()
3253          *
3254          * @param string $db_cap The feature to check for. Accepts 'collation',
3255          *                       'group_concat', 'subqueries', 'set_charset',
3256          *                       or 'utf8mb4'.
3257          * @return int|false Whether the database feature is supported, false otherwise.
3258          */
3259         public function has_cap( $db_cap ) {
3260                 $version = $this->db_version();
3261
3262                 switch ( strtolower( $db_cap ) ) {
3263                         case 'collation' :    // @since 2.5.0
3264                         case 'group_concat' : // @since 2.7.0
3265                         case 'subqueries' :   // @since 2.7.0
3266                                 return version_compare( $version, '4.1', '>=' );
3267                         case 'set_charset' :
3268                                 return version_compare( $version, '5.0.7', '>=' );
3269                         case 'utf8mb4' :      // @since 4.1.0
3270                                 if ( version_compare( $version, '5.5.3', '<' ) ) {
3271                                         return false;
3272                                 }
3273                                 if ( $this->use_mysqli ) {
3274                                         $client_version = mysqli_get_client_info();
3275                                 } else {
3276                                         $client_version = mysql_get_client_info();
3277                                 }
3278
3279                                 /*
3280                                  * libmysql has supported utf8mb4 since 5.5.3, same as the MySQL server.
3281                                  * mysqlnd has supported utf8mb4 since 5.0.9.
3282                                  */
3283                                 if ( false !== strpos( $client_version, 'mysqlnd' ) ) {
3284                                         $client_version = preg_replace( '/^\D+([\d.]+).*/', '$1', $client_version );
3285                                         return version_compare( $client_version, '5.0.9', '>=' );
3286                                 } else {
3287                                         return version_compare( $client_version, '5.5.3', '>=' );
3288                                 }
3289                         case 'utf8mb4_520' : // @since 4.6.0
3290                                 return version_compare( $version, '5.6', '>=' );
3291                 }
3292
3293                 return false;
3294         }
3295
3296         /**
3297          * Retrieve the name of the function that called wpdb.
3298          *
3299          * Searches up the list of functions until it reaches
3300          * the one that would most logically had called this method.
3301          *
3302          * @since 2.5.0
3303          *
3304          * @return string|array The name of the calling function
3305          */
3306         public function get_caller() {
3307                 return wp_debug_backtrace_summary( __CLASS__ );
3308         }
3309
3310         /**
3311          * Retrieves the MySQL server version.
3312          *
3313          * @since 2.7.0
3314          *
3315          * @return null|string Null on failure, version number on success.
3316          */
3317         public function db_version() {
3318                 if ( $this->use_mysqli ) {
3319                         $server_info = mysqli_get_server_info( $this->dbh );
3320                 } else {
3321                         $server_info = mysql_get_server_info( $this->dbh );
3322                 }
3323                 return preg_replace( '/[^0-9.].*/', '', $server_info );
3324         }
3325 }