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


Generated : Thu Oct 29 08:20:35 2026 Cross-referenced by PHPXref