[ Index ]

PHP Cross Reference of WordPress

title

Body

[close]

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

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


Generated: Thu Jul 16 01:00:03 2020 Cross-referenced by PHPXref 0.7.1