]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/wp-db.php
WordPress 4.1.3
[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                 $data = $this->process_field_charsets( $data, $table );
1930                 if ( false === $data ) {
1931                         return false;
1932                 }
1933
1934                 $converted_data = $this->strip_invalid_text( $data );
1935
1936                 if ( $data !== $converted_data ) {
1937                         return false;
1938                 }
1939
1940                 return $data;
1941         }
1942
1943         /**
1944          * Prepares arrays of value/format pairs as passed to wpdb CRUD methods.
1945          *
1946          * @since 4.2.0
1947          * @access protected
1948          *
1949          * @param array $data   Array of fields to values.
1950          * @param mixed $format Formats to be mapped to the values in $data.
1951          * @return array Array, keyed by field names with values being an array
1952          *               of 'value' and 'format' keys.
1953          */
1954         protected function process_field_formats( $data, $format ) {
1955                 $formats = $original_formats = (array) $format;
1956
1957                 foreach ( $data as $field => $value ) {
1958                         $value = array(
1959                                 'value'  => $value,
1960                                 'format' => '%s',
1961                         );
1962
1963                         if ( ! empty( $format ) ) {
1964                                 $value['format'] = array_shift( $formats );
1965                                 if ( ! $value['format'] ) {
1966                                         $value['format'] = reset( $original_formats );
1967                                 }
1968                         } elseif ( isset( $this->field_types[ $field ] ) ) {
1969                                 $value['format'] = $this->field_types[ $field ];
1970                         }
1971
1972                         $data[ $field ] = $value;
1973                 }
1974
1975                 return $data;
1976         }
1977
1978         /**
1979          * Adds field charsets to field/value/format arrays generated by
1980          * the {@see wpdb::process_field_formats()} method.
1981          *
1982          * @since 4.2.0
1983          * @access protected
1984          *
1985          * @param array  $data  As it comes from the {@see wpdb::process_field_formats()} method.
1986          * @param string $table Table name.
1987          * @return The same array as $data with additional 'charset' keys.
1988          */
1989         protected function process_field_charsets( $data, $table ) {
1990                 foreach ( $data as $field => $value ) {
1991                         if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
1992                                 // We can skip this field if we know it isn't a string.
1993                                 // This checks %d/%f versus ! %s because it's sprintf() could take more.
1994                                 $value['charset'] = false;
1995                         } elseif ( $this->check_ascii( $value['value'] ) ) {
1996                                 // If it's ASCII, then we don't need the charset. We can skip this field.
1997                                 $value['charset'] = false;
1998                         } else {
1999                                 $value['charset'] = $this->get_col_charset( $table, $field );
2000                                 if ( is_wp_error( $value['charset'] ) ) {
2001                                         return false;
2002                                 }
2003
2004                                 // This isn't ASCII. Don't have strip_invalid_text() re-check.
2005                                 $value['ascii'] = false;
2006                         }
2007
2008                         $data[ $field ] = $value;
2009                 }
2010
2011                 return $data;
2012         }
2013
2014         /**
2015          * Retrieve one variable from the database.
2016          *
2017          * Executes a SQL query and returns the value from the SQL result.
2018          * 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.
2019          * If $query is null, this function returns the value in the specified column and row from the previous SQL result.
2020          *
2021          * @since 0.71
2022          *
2023          * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
2024          * @param int $x Optional. Column of value to return. Indexed from 0.
2025          * @param int $y Optional. Row of value to return. Indexed from 0.
2026          * @return string|null Database query result (as string), or null on failure
2027          */
2028         public function get_var( $query = null, $x = 0, $y = 0 ) {
2029                 $this->func_call = "\$db->get_var(\"$query\", $x, $y)";
2030
2031                 if ( $this->check_safe_collation( $query ) ) {
2032                         $this->check_current_query = false;
2033                 }
2034
2035                 if ( $query ) {
2036                         $this->query( $query );
2037                 }
2038
2039                 // Extract var out of cached results based x,y vals
2040                 if ( !empty( $this->last_result[$y] ) ) {
2041                         $values = array_values( get_object_vars( $this->last_result[$y] ) );
2042                 }
2043
2044                 // If there is a value return it else return null
2045                 return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null;
2046         }
2047
2048         /**
2049          * Retrieve one row from the database.
2050          *
2051          * Executes a SQL query and returns the row from the SQL result.
2052          *
2053          * @since 0.71
2054          *
2055          * @param string|null $query SQL query.
2056          * @param string $output Optional. one of ARRAY_A | ARRAY_N | OBJECT constants. Return an associative array (column => value, ...),
2057          *      a numerically indexed array (0 => value, ...) or an object ( ->column = value ), respectively.
2058          * @param int $y Optional. Row to return. Indexed from 0.
2059          * @return mixed Database query result in format specified by $output or null on failure
2060          */
2061         public function get_row( $query = null, $output = OBJECT, $y = 0 ) {
2062                 $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
2063
2064                 if ( $this->check_safe_collation( $query ) ) {
2065                         $this->check_current_query = false;
2066                 }
2067
2068                 if ( $query ) {
2069                         $this->query( $query );
2070                 } else {
2071                         return null;
2072                 }
2073
2074                 if ( !isset( $this->last_result[$y] ) )
2075                         return null;
2076
2077                 if ( $output == OBJECT ) {
2078                         return $this->last_result[$y] ? $this->last_result[$y] : null;
2079                 } elseif ( $output == ARRAY_A ) {
2080                         return $this->last_result[$y] ? get_object_vars( $this->last_result[$y] ) : null;
2081                 } elseif ( $output == ARRAY_N ) {
2082                         return $this->last_result[$y] ? array_values( get_object_vars( $this->last_result[$y] ) ) : null;
2083                 } elseif ( strtoupper( $output ) === OBJECT ) {
2084                         // Back compat for OBJECT being previously case insensitive.
2085                         return $this->last_result[$y] ? $this->last_result[$y] : null;
2086                 } else {
2087                         $this->print_error( " \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N" );
2088                 }
2089         }
2090
2091         /**
2092          * Retrieve one column from the database.
2093          *
2094          * Executes a SQL query and returns the column from the SQL result.
2095          * If the SQL result contains more than one column, this function returns the column specified.
2096          * If $query is null, this function returns the specified column from the previous SQL result.
2097          *
2098          * @since 0.71
2099          *
2100          * @param string|null $query Optional. SQL query. Defaults to previous query.
2101          * @param int $x Optional. Column to return. Indexed from 0.
2102          * @return array Database query result. Array indexed from 0 by SQL result row number.
2103          */
2104         public function get_col( $query = null , $x = 0 ) {
2105                 if ( $this->check_safe_collation( $query ) ) {
2106                         $this->check_current_query = false;
2107                 }
2108
2109                 if ( $query ) {
2110                         $this->query( $query );
2111                 }
2112
2113                 $new_array = array();
2114                 // Extract the column values
2115                 for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
2116                         $new_array[$i] = $this->get_var( null, $x, $i );
2117                 }
2118                 return $new_array;
2119         }
2120
2121         /**
2122          * Retrieve an entire SQL result set from the database (i.e., many rows)
2123          *
2124          * Executes a SQL query and returns the entire SQL result.
2125          *
2126          * @since 0.71
2127          *
2128          * @param string $query SQL query.
2129          * @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.
2130          *      Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively.
2131          *      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.
2132          * @return mixed Database query results
2133          */
2134         public function get_results( $query = null, $output = OBJECT ) {
2135                 $this->func_call = "\$db->get_results(\"$query\", $output)";
2136
2137                 if ( $this->check_safe_collation( $query ) ) {
2138                         $this->check_current_query = false;
2139                 }
2140
2141                 if ( $query ) {
2142                         $this->query( $query );
2143                 } else {
2144                         return null;
2145                 }
2146
2147                 $new_array = array();
2148                 if ( $output == OBJECT ) {
2149                         // Return an integer-keyed array of row objects
2150                         return $this->last_result;
2151                 } elseif ( $output == OBJECT_K ) {
2152                         // Return an array of row objects with keys from column 1
2153                         // (Duplicates are discarded)
2154                         foreach ( $this->last_result as $row ) {
2155                                 $var_by_ref = get_object_vars( $row );
2156                                 $key = array_shift( $var_by_ref );
2157                                 if ( ! isset( $new_array[ $key ] ) )
2158                                         $new_array[ $key ] = $row;
2159                         }
2160                         return $new_array;
2161                 } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
2162                         // Return an integer-keyed array of...
2163                         if ( $this->last_result ) {
2164                                 foreach( (array) $this->last_result as $row ) {
2165                                         if ( $output == ARRAY_N ) {
2166                                                 // ...integer-keyed row arrays
2167                                                 $new_array[] = array_values( get_object_vars( $row ) );
2168                                         } else {
2169                                                 // ...column name-keyed row arrays
2170                                                 $new_array[] = get_object_vars( $row );
2171                                         }
2172                                 }
2173                         }
2174                         return $new_array;
2175                 } elseif ( strtoupper( $output ) === OBJECT ) {
2176                         // Back compat for OBJECT being previously case insensitive.
2177                         return $this->last_result;
2178                 }
2179                 return null;
2180         }
2181
2182         /**
2183          * Retrieves the character set for the given table.
2184          *
2185          * @since 4.2.0
2186          * @access protected
2187          *
2188          * @param string $table Table name.
2189          * @return string|WP_Error Table character set, {@see WP_Error} object if it couldn't be found.
2190          */
2191         protected function get_table_charset( $table ) {
2192                 $tablekey = strtolower( $table );
2193
2194                 /**
2195                  * Filter the table charset value before the DB is checked.
2196                  *
2197                  * Passing a non-null value to the filter will effectively short-circuit
2198                  * checking the DB for the charset, returning that value instead.
2199                  *
2200                  * @since 4.2.0
2201                  *
2202                  * @param string $charset The character set to use. Default null.
2203                  * @param string $table   The name of the table being checked.
2204                  */
2205                 $charset = apply_filters( 'pre_get_table_charset', null, $table );
2206                 if ( null !== $charset ) {
2207                         return $charset;
2208                 }
2209
2210                 if ( isset( $this->table_charset[ $tablekey ] ) ) {
2211                         return $this->table_charset[ $tablekey ];
2212                 }
2213
2214                 $charsets = $columns = array();
2215                 $results = $this->get_results( "SHOW FULL COLUMNS FROM `$table`" );
2216                 if ( ! $results ) {
2217                         return new WP_Error( 'wpdb_get_table_charset_failure' );
2218                 }
2219
2220                 foreach ( $results as $column ) {
2221                         $columns[ strtolower( $column->Field ) ] = $column;
2222                 }
2223
2224                 $this->col_meta[ $tablekey ] = $columns;
2225
2226                 foreach ( $columns as $column ) {
2227                         if ( ! empty( $column->Collation ) ) {
2228                                 list( $charset ) = explode( '_', $column->Collation );
2229                                 $charsets[ strtolower( $charset ) ] = true;
2230                         }
2231
2232                         list( $type ) = explode( '(', $column->Type );
2233
2234                         // A binary/blob means the whole query gets treated like this.
2235                         if ( in_array( strtoupper( $type ), array( 'BINARY', 'VARBINARY', 'TINYBLOB', 'MEDIUMBLOB', 'BLOB', 'LONGBLOB' ) ) ) {
2236                                 $this->table_charset[ $tablekey ] = 'binary';
2237                                 return 'binary';
2238                         }
2239                 }
2240
2241                 // utf8mb3 is an alias for utf8.
2242                 if ( isset( $charsets['utf8mb3'] ) ) {
2243                         $charsets['utf8'] = true;
2244                         unset( $charsets['utf8mb3'] );
2245                 }
2246
2247                 // Check if we have more than one charset in play.
2248                 $count = count( $charsets );
2249                 if ( 1 === $count ) {
2250                         $charset = key( $charsets );
2251                 } elseif ( 0 === $count ) {
2252                         // No charsets, assume this table can store whatever.
2253                         $charset = false;
2254                 } else {
2255                         // More than one charset. Remove latin1 if present and recalculate.
2256                         unset( $charsets['latin1'] );
2257                         $count = count( $charsets );
2258                         if ( 1 === $count ) {
2259                                 // Only one charset (besides latin1).
2260                                 $charset = key( $charsets );
2261                         } elseif ( 2 === $count && isset( $charsets['utf8'], $charsets['utf8mb4'] ) ) {
2262                                 // Two charsets, but they're utf8 and utf8mb4, use utf8.
2263                                 $charset = 'utf8';
2264                         } else {
2265                                 // Two mixed character sets. ascii.
2266                                 $charset = 'ascii';
2267                         }
2268                 }
2269
2270                 $this->table_charset[ $tablekey ] = $charset;
2271                 return $charset;
2272         }
2273
2274         /**
2275          * Retrieves the character set for the given column.
2276          *
2277          * @since 4.2.0
2278          * @access public
2279          *
2280          * @param string $table  Table name.
2281          * @param string $column Column name.
2282          * @return mixed Column character set as a string. False if the column has no
2283          *               character set. {@see WP_Error} object if there was an error.
2284          */
2285         public function get_col_charset( $table, $column ) {
2286                 $tablekey = strtolower( $table );
2287                 $columnkey = strtolower( $column );
2288
2289                 /**
2290                  * Filter the column charset value before the DB is checked.
2291                  *
2292                  * Passing a non-null value to the filter will short-circuit
2293                  * checking the DB for the charset, returning that value instead.
2294                  *
2295                  * @since 4.2.0
2296                  *
2297                  * @param string $charset The character set to use. Default null.
2298                  * @param string $table   The name of the table being checked.
2299                  * @param string $column  The name of the column being checked.
2300                  */
2301                 $charset = apply_filters( 'pre_get_col_charset', null, $table, $column );
2302                 if ( null !== $charset ) {
2303                         return $charset;
2304                 }
2305
2306                 // Skip this entirely if this isn't a MySQL database.
2307                 if ( false === $this->is_mysql ) {
2308                         return false;
2309                 }
2310
2311                 if ( empty( $this->table_charset[ $tablekey ] ) ) {
2312                         // This primes column information for us.
2313                         $table_charset = $this->get_table_charset( $table );
2314                         if ( is_wp_error( $table_charset ) ) {
2315                                 return $table_charset;
2316                         }
2317                 }
2318
2319                 // If still no column information, return the table charset.
2320                 if ( empty( $this->col_meta[ $tablekey ] ) ) {
2321                         return $this->table_charset[ $tablekey ];
2322                 }
2323
2324                 // If this column doesn't exist, return the table charset.
2325                 if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
2326                         return $this->table_charset[ $tablekey ];
2327                 }
2328
2329                 // Return false when it's not a string column.
2330                 if ( empty( $this->col_meta[ $tablekey ][ $columnkey ]->Collation ) ) {
2331                         return false;
2332                 }
2333
2334                 list( $charset ) = explode( '_', $this->col_meta[ $tablekey ][ $columnkey ]->Collation );
2335                 return $charset;
2336         }
2337
2338         /**
2339          * Check if a string is ASCII.
2340          *
2341          * The negative regex is faster for non-ASCII strings, as it allows
2342          * the search to finish as soon as it encounters a non-ASCII character.
2343          *
2344          * @since 4.2.0
2345          * @access protected
2346          *
2347          * @param string $string String to check.
2348          * @return bool True if ASCII, false if not.
2349          */
2350         protected function check_ascii( $string ) {
2351                 if ( function_exists( 'mb_check_encoding' ) ) {
2352                         if ( mb_check_encoding( $string, 'ASCII' ) ) {
2353                                 return true;
2354                         }
2355                 } elseif ( ! preg_match( '/[^\x00-\x7F]/', $string ) ) {
2356                         return true;
2357                 }
2358
2359                 return false;
2360         }
2361
2362         /**
2363          * Check if the query is accessing a collation considered safe on the current version of MySQL.
2364          *
2365          * @since 4.2.0
2366          * @access protected
2367          *
2368          * @param string $query The query to check.
2369          * @return bool True if the collation is safe, false if it isn't.
2370          */
2371         protected function check_safe_collation( $query ) {
2372                 if ( $this->checking_collation ) {
2373                         return true;
2374                 }
2375
2376                 // We don't need to check the collation for queries that don't read data.
2377                 $query = ltrim( $query, "\r\n\t (" );
2378                 if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN)\s/i', $query ) ) {
2379                         return true;
2380                 }
2381
2382                 // All-ASCII queries don't need extra checking.
2383                 if ( $this->check_ascii( $query ) ) {
2384                         return true;
2385                 }
2386
2387                 $table = $this->get_table_from_query( $query );
2388                 if ( ! $table ) {
2389                         return false;
2390                 }
2391
2392                 $this->checking_collation = true;
2393                 $collation = $this->get_table_charset( $table );
2394                 $this->checking_collation = false;
2395
2396                 // Tables with no collation, or latin1 only, don't need extra checking.
2397                 if ( false === $collation || 'latin1' === $collation ) {
2398                         return true;
2399                 }
2400
2401                 $table = strtolower( $table );
2402                 if ( empty( $this->col_meta[ $table ] ) ) {
2403                         return false;
2404                 }
2405
2406                 // If any of the columns don't have one of these collations, it needs more sanity checking.
2407                 foreach( $this->col_meta[ $table ] as $col ) {
2408                         if ( empty( $col->Collation ) ) {
2409                                 continue;
2410                         }
2411
2412                         if ( ! in_array( $col->Collation, array( 'utf8_general_ci', 'utf8_bin', 'utf8mb4_general_ci', 'utf8mb4_bin' ), true ) ) {
2413                                 return false;
2414                         }
2415                 }
2416
2417                 return true;
2418         }
2419
2420         /**
2421          * Strips any invalid characters based on value/charset pairs.
2422          *
2423          * @since 4.2.0
2424          * @access protected
2425          *
2426          * @param array $data Array of value arrays. Each value array has the keys
2427          *                    'value' and 'charset'. An optional 'ascii' key can be
2428          *                    set to false to avoid redundant ASCII checks.
2429          * @return array|WP_Error The $data parameter, with invalid characters removed from
2430          *                        each value. This works as a passthrough: any additional keys
2431          *                        such as 'field' are retained in each value array. If we cannot
2432          *                        remove invalid characters, a {@see WP_Error} object is returned.
2433          */
2434                 // If any of the columns don't have one of these collations, it needs more sanity checking.
2435         protected function strip_invalid_text( $data ) {
2436                 // Some multibyte character sets that we can check in PHP.
2437                 $mb_charsets = array(
2438                         'ascii'   => 'ASCII',
2439                         'big5'    => 'BIG-5',
2440                         'eucjpms' => 'eucJP-win',
2441                         'gb2312'  => 'EUC-CN',
2442                         'ujis'    => 'EUC-JP',
2443                         'utf32'   => 'UTF-32',
2444                 );
2445
2446                 $supported_charsets = array();
2447                 if ( function_exists( 'mb_list_encodings' ) ) {
2448                         $supported_charsets = mb_list_encodings();
2449                 }
2450
2451                 $db_check_string = false;
2452
2453                 foreach ( $data as &$value ) {
2454                         $charset = $value['charset'];
2455
2456                         // Column isn't a string, or is latin1, which will will happily store anything.
2457                         if ( false === $charset || 'latin1' === $charset ) {
2458                                 continue;
2459                         }
2460
2461                         if ( ! is_string( $value['value'] ) ) {
2462                                 continue;
2463                         }
2464
2465                         // ASCII is always OK.
2466                         if ( ! isset( $value['ascii'] ) && $this->check_ascii( $value['value'] ) ) {
2467                                 continue;
2468                         }
2469
2470                         // Convert the text locally.
2471                         if ( $supported_charsets ) {
2472                                 if ( isset( $mb_charsets[ $charset ] ) && in_array( $mb_charsets[ $charset ], $supported_charsets ) ) {
2473                                         $value['value'] = mb_convert_encoding( $value['value'], $mb_charsets[ $charset ], $mb_charsets[ $charset ] );
2474                                         continue;
2475                                 }
2476                         }
2477
2478                         // utf8 can be handled by regex, which is a bunch faster than a DB lookup.
2479                         if ( 'utf8' === $charset || 'utf8mb3' === $charset || 'utf8mb4' === $charset ) {
2480                                 $regex = '/
2481                                         (
2482                                                 (?: [\x00-\x7F]                  # single-byte sequences   0xxxxxxx
2483                                                 |   [\xC2-\xDF][\x80-\xBF]       # double-byte sequences   110xxxxx 10xxxxxx
2484                                                 |   \xE0[\xA0-\xBF][\x80-\xBF]   # triple-byte sequences   1110xxxx 10xxxxxx * 2
2485                                                 |   [\xE1-\xEC][\x80-\xBF]{2}
2486                                                 |   \xED[\x80-\x9F][\x80-\xBF]
2487                                                 |   [\xEE-\xEF][\x80-\xBF]{2}';
2488
2489                                 if ( 'utf8mb4' === $charset) {
2490                                         $regex .= '
2491                                                 |    \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences   11110xxx 10xxxxxx * 3
2492                                                 |    [\xF1-\xF3][\x80-\xBF]{3}
2493                                                 |    \xF4[\x80-\x8F][\x80-\xBF]{2}
2494                                         ';
2495                                 }
2496
2497                                 $regex .= '){1,50}                          # ...one or more times
2498                                         )
2499                                         | .                                  # anything else
2500                                         /x';
2501                                 $value['value'] = preg_replace( $regex, '$1', $value['value'] );
2502                                 continue;
2503                         }
2504
2505                         // We couldn't use any local conversions, send it to the DB.
2506                         $value['db'] = $db_check_string = true;
2507                 }
2508                 unset( $value ); // Remove by reference.
2509
2510                 if ( $db_check_string ) {
2511                         $queries = array();
2512                         foreach ( $data as $col => $value ) {
2513                                 if ( ! empty( $value['db'] ) ) {
2514                                         if ( ! isset( $queries[ $value['charset'] ] ) ) {
2515                                                 $queries[ $value['charset'] ] = array();
2516                                         }
2517
2518                                         // Split the CONVERT() calls by charset, so we can make sure the connection is right
2519                                         $queries[ $value['charset'] ][ $col ] = $this->prepare( "CONVERT( %s USING {$value['charset']} )", $value['value'] );
2520                                         unset( $data[ $col ]['db'] );
2521                                 }
2522                         }
2523
2524                         $connection_charset = $this->charset;
2525                         foreach ( $queries as $charset => $query ) {
2526                                 if ( ! $query ) {
2527                                         continue;
2528                                 }
2529
2530                                 // Change the charset to match the string(s) we're converting
2531                                 if ( $charset !== $connection_charset ) {
2532                                         $connection_charset = $charset;
2533                                         $this->set_charset( $this->dbh, $charset );
2534                                 }
2535
2536                                 $this->check_current_query = false;
2537
2538                                 $row = $this->get_row( "SELECT " . implode( ', ', $query ), ARRAY_N );
2539                                 if ( ! $row ) {
2540                                         $this->set_charset( $this->dbh, $connection_charset );
2541                                         return new WP_Error( 'wpdb_strip_invalid_text_failure' );
2542                                 }
2543
2544                                 $cols = array_keys( $query );
2545                                 $col_count = count( $cols );
2546                                 for ( $ii = 0; $ii < $col_count; $ii++ ) {
2547                                         $data[ $cols[ $ii ] ]['value'] = $row[ $ii ];
2548                                 }
2549                         }
2550
2551                         // Don't forget to change the charset back!
2552                         if ( $connection_charset !== $this->charset ) {
2553                                 $this->set_charset( $this->dbh );
2554                         }
2555                 }
2556
2557                 return $data;
2558         }
2559
2560         /**
2561          * Strips any invalid characters from the query.
2562          *
2563          * @since 4.2.0
2564          * @access protected
2565          *
2566          * @param string $query Query to convert.
2567          * @return string|WP_Error The converted query, or a {@see WP_Error} object if the conversion fails.
2568          */
2569         protected function strip_invalid_text_from_query( $query ) {
2570                 $table = $this->get_table_from_query( $query );
2571                 if ( $table ) {
2572                         $charset = $this->get_table_charset( $table );
2573                         if ( is_wp_error( $charset ) ) {
2574                                 return $charset;
2575                         }
2576
2577                         // We can't reliably strip text from tables containing binary/blob columns
2578                         if ( 'binary' === $charset ) {
2579                                 return $query;
2580                         }
2581                 } else {
2582                         $charset = $this->charset;
2583                 }
2584
2585                 $data = array(
2586                         'value'   => $query,
2587                         'charset' => $charset,
2588                         'ascii'   => false,
2589                 );
2590
2591                 $data = $this->strip_invalid_text( array( $data ) );
2592                 if ( is_wp_error( $data ) ) {
2593                         return $data;
2594                 }
2595
2596                 return $data[0]['value'];
2597         }
2598
2599         /**
2600          * Strips any invalid characters from the string for a given table and column.
2601          *
2602          * @since 4.2.0
2603          * @access public
2604          *
2605          * @param string $table  Table name.
2606          * @param string $column Column name.
2607          * @param string $value  The text to check.
2608          * @return string|WP_Error The converted string, or a `WP_Error` object if the conversion fails.
2609          */
2610         public function strip_invalid_text_for_column( $table, $column, $value ) {
2611                 if ( ! is_string( $value ) || $this->check_ascii( $value ) ) {
2612                         return $value;
2613                 }
2614
2615                 $charset = $this->get_col_charset( $table, $column );
2616                 if ( ! $charset ) {
2617                         // Not a string column.
2618                         return $value;
2619                 } elseif ( is_wp_error( $charset ) ) {
2620                         // Bail on real errors.
2621                         return $charset;
2622                 }
2623
2624                 $data = array(
2625                         $column => array(
2626                                 'value'   => $value,
2627                                 'charset' => $charset,
2628                                 'ascii'   => false,
2629                         )
2630                 );
2631
2632                 $data = $this->strip_invalid_text( $data );
2633                 if ( is_wp_error( $data ) ) {
2634                         return $data;
2635                 }
2636
2637                 return $data[ $column ]['value'];
2638         }
2639
2640         /**
2641          * Find the first table name referenced in a query.
2642          *
2643          * @since 4.2.0
2644          * @access protected
2645          *
2646          * @param string $query The query to search.
2647          * @return string|false $table The table name found, or false if a table couldn't be found.
2648          */
2649         protected function get_table_from_query( $query ) {
2650                 // Remove characters that can legally trail the table name.
2651                 $query = rtrim( $query, ';/-#' );
2652
2653                 // Allow (select...) union [...] style queries. Use the first query's table name.
2654                 $query = ltrim( $query, "\r\n\t (" );
2655
2656                 /*
2657                  * Strip everything between parentheses except nested selects and use only 1,000
2658                  * chars of the query.
2659                  */
2660                 $query = preg_replace( '/\((?!\s*select)[^(]*?\)/is', '()', substr( $query, 0, 1000 ) );
2661
2662                 // Quickly match most common queries.
2663                 if ( preg_match( '/^\s*(?:'
2664                                 . 'SELECT.*?\s+FROM'
2665                                 . '|INSERT(?:\s+LOW_PRIORITY|\s+DELAYED|\s+HIGH_PRIORITY)?(?:\s+IGNORE)?(?:\s+INTO)?'
2666                                 . '|REPLACE(?:\s+LOW_PRIORITY|\s+DELAYED)?(?:\s+INTO)?'
2667                                 . '|UPDATE(?:\s+LOW_PRIORITY)?(?:\s+IGNORE)?'
2668                                 . '|DELETE(?:\s+LOW_PRIORITY|\s+QUICK|\s+IGNORE)*(?:\s+FROM)?'
2669                                 . ')\s+`?([\w-]+)`?/is', $query, $maybe ) ) {
2670                         return $maybe[1];
2671                 }
2672
2673                 // SHOW TABLE STATUS and SHOW TABLES
2674                 if ( preg_match( '/^\s*(?:'
2675                                 . 'SHOW\s+TABLE\s+STATUS.+(?:LIKE\s+|WHERE\s+Name\s*=\s*)'
2676                                 . '|SHOW\s+(?:FULL\s+)?TABLES.+(?:LIKE\s+|WHERE\s+Name\s*=\s*)'
2677                                 . ')\W([\w-]+)\W/is', $query, $maybe ) ) {
2678                         return $maybe[1];
2679                 }
2680
2681                 // Big pattern for the rest of the table-related queries.
2682                 if ( preg_match( '/^\s*(?:'
2683                                 . '(?:EXPLAIN\s+(?:EXTENDED\s+)?)?SELECT.*?\s+FROM'
2684                                 . '|DESCRIBE|DESC|EXPLAIN|HANDLER'
2685                                 . '|(?:LOCK|UNLOCK)\s+TABLE(?:S)?'
2686                                 . '|(?:RENAME|OPTIMIZE|BACKUP|RESTORE|CHECK|CHECKSUM|ANALYZE|REPAIR).*\s+TABLE'
2687                                 . '|TRUNCATE(?:\s+TABLE)?'
2688                                 . '|CREATE(?:\s+TEMPORARY)?\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?'
2689                                 . '|ALTER(?:\s+IGNORE)?\s+TABLE'
2690                                 . '|DROP\s+TABLE(?:\s+IF\s+EXISTS)?'
2691                                 . '|CREATE(?:\s+\w+)?\s+INDEX.*\s+ON'
2692                                 . '|DROP\s+INDEX.*\s+ON'
2693                                 . '|LOAD\s+DATA.*INFILE.*INTO\s+TABLE'
2694                                 . '|(?:GRANT|REVOKE).*ON\s+TABLE'
2695                                 . '|SHOW\s+(?:.*FROM|.*TABLE)'
2696                                 . ')\s+\(*\s*`?([\w-]+)`?\s*\)*/is', $query, $maybe ) ) {
2697                         return $maybe[1];
2698                 }
2699
2700                 return false;
2701         }
2702
2703         /**
2704          * Load the column metadata from the last query.
2705          *
2706          * @since 3.5.0
2707          *
2708          * @access protected
2709          */
2710         protected function load_col_info() {
2711                 if ( $this->col_info )
2712                         return;
2713
2714                 if ( $this->use_mysqli ) {
2715                         for ( $i = 0; $i < @mysqli_num_fields( $this->result ); $i++ ) {
2716                                 $this->col_info[ $i ] = @mysqli_fetch_field( $this->result );
2717                         }
2718                 } else {
2719                         for ( $i = 0; $i < @mysql_num_fields( $this->result ); $i++ ) {
2720                                 $this->col_info[ $i ] = @mysql_fetch_field( $this->result, $i );
2721                         }
2722                 }
2723         }
2724
2725         /**
2726          * Retrieve column metadata from the last query.
2727          *
2728          * @since 0.71
2729          *
2730          * @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
2731          * @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
2732          * @return mixed Column Results
2733          */
2734         public function get_col_info( $info_type = 'name', $col_offset = -1 ) {
2735                 $this->load_col_info();
2736
2737                 if ( $this->col_info ) {
2738                         if ( $col_offset == -1 ) {
2739                                 $i = 0;
2740                                 $new_array = array();
2741                                 foreach( (array) $this->col_info as $col ) {
2742                                         $new_array[$i] = $col->{$info_type};
2743                                         $i++;
2744                                 }
2745                                 return $new_array;
2746                         } else {
2747                                 return $this->col_info[$col_offset]->{$info_type};
2748                         }
2749                 }
2750         }
2751
2752         /**
2753          * Starts the timer, for debugging purposes.
2754          *
2755          * @since 1.5.0
2756          *
2757          * @return bool
2758          */
2759         public function timer_start() {
2760                 $this->time_start = microtime( true );
2761                 return true;
2762         }
2763
2764         /**
2765          * Stops the debugging timer.
2766          *
2767          * @since 1.5.0
2768          *
2769          * @return float Total time spent on the query, in seconds
2770          */
2771         public function timer_stop() {
2772                 return ( microtime( true ) - $this->time_start );
2773         }
2774
2775         /**
2776          * Wraps errors in a nice header and footer and dies.
2777          *
2778          * Will not die if wpdb::$show_errors is false.
2779          *
2780          * @since 1.5.0
2781          *
2782          * @param string $message The Error message
2783          * @param string $error_code Optional. A Computer readable string to identify the error.
2784          * @return false|void
2785          */
2786         public function bail( $message, $error_code = '500' ) {
2787                 if ( !$this->show_errors ) {
2788                         if ( class_exists( 'WP_Error' ) )
2789                                 $this->error = new WP_Error($error_code, $message);
2790                         else
2791                                 $this->error = $message;
2792                         return false;
2793                 }
2794                 wp_die($message);
2795         }
2796
2797         /**
2798          * Whether MySQL database is at least the required minimum version.
2799          *
2800          * @since 2.5.0
2801          * @uses $wp_version
2802          * @uses $required_mysql_version
2803          *
2804          * @return WP_Error
2805          */
2806         public function check_database_version() {
2807                 global $wp_version, $required_mysql_version;
2808                 // Make sure the server has the required MySQL version
2809                 if ( version_compare($this->db_version(), $required_mysql_version, '<') )
2810                         return new WP_Error('database_version', sprintf( __( '<strong>ERROR</strong>: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ));
2811         }
2812
2813         /**
2814          * Whether the database supports collation.
2815          *
2816          * Called when WordPress is generating the table scheme.
2817          *
2818          * @since 2.5.0
2819          * @deprecated 3.5.0
2820          * @deprecated Use wpdb::has_cap( 'collation' )
2821          *
2822          * @return bool True if collation is supported, false if version does not
2823          */
2824         public function supports_collation() {
2825                 _deprecated_function( __FUNCTION__, '3.5', 'wpdb::has_cap( \'collation\' )' );
2826                 return $this->has_cap( 'collation' );
2827         }
2828
2829         /**
2830          * The database character collate.
2831          *
2832          * @since 3.5.0
2833          *
2834          * @return string The database character collate.
2835          */
2836         public function get_charset_collate() {
2837                 $charset_collate = '';
2838
2839                 if ( ! empty( $this->charset ) )
2840                         $charset_collate = "DEFAULT CHARACTER SET $this->charset";
2841                 if ( ! empty( $this->collate ) )
2842                         $charset_collate .= " COLLATE $this->collate";
2843
2844                 return $charset_collate;
2845         }
2846
2847         /**
2848          * Determine if a database supports a particular feature.
2849          *
2850          * @since 2.7.0
2851          * @since 4.1.0 Support was added for the 'utf8mb4' feature.
2852          *
2853          * @see wpdb::db_version()
2854          *
2855          * @param string $db_cap The feature to check for. Accepts 'collation',
2856          *                       'group_concat', 'subqueries', 'set_charset',
2857          *                       or 'utf8mb4'.
2858          * @return bool Whether the database feature is supported, false otherwise.
2859          */
2860         public function has_cap( $db_cap ) {
2861                 $version = $this->db_version();
2862
2863                 switch ( strtolower( $db_cap ) ) {
2864                         case 'collation' :    // @since 2.5.0
2865                         case 'group_concat' : // @since 2.7.0
2866                         case 'subqueries' :   // @since 2.7.0
2867                                 return version_compare( $version, '4.1', '>=' );
2868                         case 'set_charset' :
2869                                 return version_compare( $version, '5.0.7', '>=' );
2870                         case 'utf8mb4' :      // @since 4.1.0
2871                                 return version_compare( $version, '5.5.3', '>=' );
2872                 }
2873
2874                 return false;
2875         }
2876
2877         /**
2878          * Retrieve the name of the function that called wpdb.
2879          *
2880          * Searches up the list of functions until it reaches
2881          * the one that would most logically had called this method.
2882          *
2883          * @since 2.5.0
2884          *
2885          * @return string The name of the calling function
2886          */
2887         public function get_caller() {
2888                 return wp_debug_backtrace_summary( __CLASS__ );
2889         }
2890
2891         /**
2892          * The database version number.
2893          *
2894          * @since 2.7.0
2895          *
2896          * @return null|string Null on failure, version number on success.
2897          */
2898         public function db_version() {
2899                 if ( $this->use_mysqli ) {
2900                         $server_info = mysqli_get_server_info( $this->dbh );
2901                 } else {
2902                         $server_info = mysql_get_server_info( $this->dbh );
2903                 }
2904                 return preg_replace( '/[^0-9.].*/', '', $server_info );
2905         }
2906 }