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