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


Generated: Sun Oct 24 01:00:03 2021 Cross-referenced by PHPXref 0.7.1