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


Generated : Mon Nov 30 08:20:01 2026 Cross-referenced by PHPXref