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