[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

title

Body

[close]

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

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


Generated: Tue Oct 22 08:20:01 2019 Cross-referenced by PHPXref 0.7