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


Generated: Tue Apr 7 01:00:07 2020 Cross-referenced by PHPXref 0.7.1