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