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