[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

/wp-includes/ -> wp-db.php (source)

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


Generated: Sat Sep 21 01:00:03 2019 Cross-referenced by PHPXref 0.7.1