[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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


Generated: Tue Jan 28 01:00:03 2020 Cross-referenced by PHPXref 0.7.1