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