[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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


Generated: Mon Nov 18 01:00:04 2019 Cross-referenced by PHPXref 0.7.1