[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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


Generated : Wed Sep 9 08:20:27 2026 Cross-referenced by PHPXref