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