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


Generated : Sat Jun 7 08:20:01 2025 Cross-referenced by PHPXref