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