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