/wp-includes/wp-db.php

https://github.com/markjaquith/WordPress · PHP · 3819 lines · 1750 code · 441 blank · 1628 comment · 380 complexity · 3bc413271e20a7f48a7b1fff5b741410 MD5 · raw file

Large files are truncated click here to view the full file

  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. * @since 0.71
  13. */
  14. define( 'EZSQL_VERSION', 'WP1.25' );
  15. /**
  16. * @since 0.71
  17. */
  18. define( 'OBJECT', 'OBJECT' );
  19. // phpcs:ignore Generic.NamingConventions.UpperCaseConstantName.ConstantNotUpperCase
  20. define( 'object', 'OBJECT' ); // Back compat.
  21. /**
  22. * @since 2.5.0
  23. */
  24. define( 'OBJECT_K', 'OBJECT_K' );
  25. /**
  26. * @since 0.71
  27. */
  28. define( 'ARRAY_A', 'ARRAY_A' );
  29. /**
  30. * @since 0.71
  31. */
  32. define( 'ARRAY_N', 'ARRAY_N' );
  33. /**
  34. * WordPress database access abstraction class.
  35. *
  36. * This class is used to interact with a database without needing to use raw SQL statements.
  37. * By default, WordPress uses this class to instantiate the global $wpdb object, providing
  38. * access to the WordPress database.
  39. *
  40. * It is possible to replace this class with your own by setting the $wpdb global variable
  41. * in wp-content/db.php file to your class. The wpdb class will still be included, so you can
  42. * extend it or simply use your own.
  43. *
  44. * @link https://developer.wordpress.org/reference/classes/wpdb/
  45. *
  46. * @since 0.71
  47. */
  48. class wpdb {
  49. /**
  50. * Whether to show SQL/DB errors.
  51. *
  52. * Default is to show errors if both WP_DEBUG and WP_DEBUG_DISPLAY evaluate to true.
  53. *
  54. * @since 0.71
  55. *
  56. * @var bool
  57. */
  58. public $show_errors = false;
  59. /**
  60. * Whether to suppress errors during the DB bootstrapping. Default false.
  61. *
  62. * @since 2.5.0
  63. *
  64. * @var bool
  65. */
  66. public $suppress_errors = false;
  67. /**
  68. * The error encountered during the last query.
  69. *
  70. * @since 2.5.0
  71. *
  72. * @var string
  73. */
  74. public $last_error = '';
  75. /**
  76. * The number of queries made.
  77. *
  78. * @since 1.2.0
  79. *
  80. * @var int
  81. */
  82. public $num_queries = 0;
  83. /**
  84. * Count of rows returned by the last query.
  85. *
  86. * @since 0.71
  87. *
  88. * @var int
  89. */
  90. public $num_rows = 0;
  91. /**
  92. * Count of rows affected by the last query.
  93. *
  94. * @since 0.71
  95. *
  96. * @var int
  97. */
  98. public $rows_affected = 0;
  99. /**
  100. * The ID generated for an AUTO_INCREMENT column by the last query (usually INSERT).
  101. *
  102. * @since 0.71
  103. *
  104. * @var int
  105. */
  106. public $insert_id = 0;
  107. /**
  108. * The last query made.
  109. *
  110. * @since 0.71
  111. *
  112. * @var string
  113. */
  114. public $last_query;
  115. /**
  116. * Results of the last query.
  117. *
  118. * @since 0.71
  119. *
  120. * @var stdClass[]|null
  121. */
  122. public $last_result;
  123. /**
  124. * Database query result.
  125. *
  126. * Possible values:
  127. *
  128. * - For successful SELECT, SHOW, DESCRIBE, or EXPLAIN queries:
  129. * - `mysqli_result` instance when the `mysqli` driver is in use
  130. * - `resource` when the older `mysql` driver is in use
  131. * - `true` for other query types that were successful
  132. * - `null` if a query is yet to be made or if the result has since been flushed
  133. * - `false` if the query returned an error
  134. *
  135. * @since 0.71
  136. *
  137. * @var mysqli_result|resource|bool|null
  138. */
  139. protected $result;
  140. /**
  141. * Cached column info, for sanity checking data before inserting.
  142. *
  143. * @since 4.2.0
  144. *
  145. * @var array
  146. */
  147. protected $col_meta = array();
  148. /**
  149. * Calculated character sets keyed by table name.
  150. *
  151. * @since 4.2.0
  152. *
  153. * @var string[]
  154. */
  155. protected $table_charset = array();
  156. /**
  157. * Whether text fields in the current query need to be sanity checked.
  158. *
  159. * @since 4.2.0
  160. *
  161. * @var bool
  162. */
  163. protected $check_current_query = true;
  164. /**
  165. * Flag to ensure we don't run into recursion problems when checking the collation.
  166. *
  167. * @since 4.2.0
  168. *
  169. * @see wpdb::check_safe_collation()
  170. * @var bool
  171. */
  172. private $checking_collation = false;
  173. /**
  174. * Saved info on the table column.
  175. *
  176. * @since 0.71
  177. *
  178. * @var array
  179. */
  180. protected $col_info;
  181. /**
  182. * Log of queries that were executed, for debugging purposes.
  183. *
  184. * @since 1.5.0
  185. * @since 2.5.0 The third element in each query log was added to record the calling functions.
  186. * @since 5.1.0 The fourth element in each query log was added to record the start time.
  187. * @since 5.3.0 The fifth element in each query log was added to record custom data.
  188. *
  189. * @var array[] {
  190. * Array of arrays containing information about queries that were executed.
  191. *
  192. * @type array ...$0 {
  193. * Data for each query.
  194. *
  195. * @type string $0 The query's SQL.
  196. * @type float $1 Total time spent on the query, in seconds.
  197. * @type string $2 Comma-separated list of the calling functions.
  198. * @type float $3 Unix timestamp of the time at the start of the query.
  199. * @type array $4 Custom query data.
  200. * }
  201. * }
  202. */
  203. public $queries;
  204. /**
  205. * The number of times to retry reconnecting before dying. Default 5.
  206. *
  207. * @since 3.9.0
  208. *
  209. * @see wpdb::check_connection()
  210. * @var int
  211. */
  212. protected $reconnect_retries = 5;
  213. /**
  214. * WordPress table prefix.
  215. *
  216. * You can set this to have multiple WordPress installations in a single database.
  217. * The second reason is for possible security precautions.
  218. *
  219. * @since 2.5.0
  220. *
  221. * @var string
  222. */
  223. public $prefix = '';
  224. /**
  225. * WordPress base table prefix.
  226. *
  227. * @since 3.0.0
  228. *
  229. * @var string
  230. */
  231. public $base_prefix;
  232. /**
  233. * Whether the database queries are ready to start executing.
  234. *
  235. * @since 2.3.2
  236. *
  237. * @var bool
  238. */
  239. public $ready = false;
  240. /**
  241. * Blog ID.
  242. *
  243. * @since 3.0.0
  244. *
  245. * @var int
  246. */
  247. public $blogid = 0;
  248. /**
  249. * Site ID.
  250. *
  251. * @since 3.0.0
  252. *
  253. * @var int
  254. */
  255. public $siteid = 0;
  256. /**
  257. * List of WordPress per-site tables.
  258. *
  259. * @since 2.5.0
  260. *
  261. * @see wpdb::tables()
  262. * @var string[]
  263. */
  264. public $tables = array(
  265. 'posts',
  266. 'comments',
  267. 'links',
  268. 'options',
  269. 'postmeta',
  270. 'terms',
  271. 'term_taxonomy',
  272. 'term_relationships',
  273. 'termmeta',
  274. 'commentmeta',
  275. );
  276. /**
  277. * List of deprecated WordPress tables.
  278. *
  279. * 'categories', 'post2cat', and 'link2cat' were deprecated in 2.3.0, db version 5539.
  280. *
  281. * @since 2.9.0
  282. *
  283. * @see wpdb::tables()
  284. * @var string[]
  285. */
  286. public $old_tables = array( 'categories', 'post2cat', 'link2cat' );
  287. /**
  288. * List of WordPress global tables.
  289. *
  290. * @since 3.0.0
  291. *
  292. * @see wpdb::tables()
  293. * @var string[]
  294. */
  295. public $global_tables = array( 'users', 'usermeta' );
  296. /**
  297. * List of Multisite global tables.
  298. *
  299. * @since 3.0.0
  300. *
  301. * @see wpdb::tables()
  302. * @var string[]
  303. */
  304. public $ms_global_tables = array(
  305. 'blogs',
  306. 'blogmeta',
  307. 'signups',
  308. 'site',
  309. 'sitemeta',
  310. 'sitecategories',
  311. 'registration_log',
  312. );
  313. /**
  314. * WordPress Comments table.
  315. *
  316. * @since 1.5.0
  317. *
  318. * @var string
  319. */
  320. public $comments;
  321. /**
  322. * WordPress Comment Metadata table.
  323. *
  324. * @since 2.9.0
  325. *
  326. * @var string
  327. */
  328. public $commentmeta;
  329. /**
  330. * WordPress Links table.
  331. *
  332. * @since 1.5.0
  333. *
  334. * @var string
  335. */
  336. public $links;
  337. /**
  338. * WordPress Options table.
  339. *
  340. * @since 1.5.0
  341. *
  342. * @var string
  343. */
  344. public $options;
  345. /**
  346. * WordPress Post Metadata table.
  347. *
  348. * @since 1.5.0
  349. *
  350. * @var string
  351. */
  352. public $postmeta;
  353. /**
  354. * WordPress Posts table.
  355. *
  356. * @since 1.5.0
  357. *
  358. * @var string
  359. */
  360. public $posts;
  361. /**
  362. * WordPress Terms table.
  363. *
  364. * @since 2.3.0
  365. *
  366. * @var string
  367. */
  368. public $terms;
  369. /**
  370. * WordPress Term Relationships table.
  371. *
  372. * @since 2.3.0
  373. *
  374. * @var string
  375. */
  376. public $term_relationships;
  377. /**
  378. * WordPress Term Taxonomy table.
  379. *
  380. * @since 2.3.0
  381. *
  382. * @var string
  383. */
  384. public $term_taxonomy;
  385. /**
  386. * WordPress Term Meta table.
  387. *
  388. * @since 4.4.0
  389. *
  390. * @var string
  391. */
  392. public $termmeta;
  393. //
  394. // Global and Multisite tables
  395. //
  396. /**
  397. * WordPress User Metadata table.
  398. *
  399. * @since 2.3.0
  400. *
  401. * @var string
  402. */
  403. public $usermeta;
  404. /**
  405. * WordPress Users table.
  406. *
  407. * @since 1.5.0
  408. *
  409. * @var string
  410. */
  411. public $users;
  412. /**
  413. * Multisite Blogs table.
  414. *
  415. * @since 3.0.0
  416. *
  417. * @var string
  418. */
  419. public $blogs;
  420. /**
  421. * Multisite Blog Metadata table.
  422. *
  423. * @since 5.1.0
  424. *
  425. * @var string
  426. */
  427. public $blogmeta;
  428. /**
  429. * Multisite Registration Log table.
  430. *
  431. * @since 3.0.0
  432. *
  433. * @var string
  434. */
  435. public $registration_log;
  436. /**
  437. * Multisite Signups table.
  438. *
  439. * @since 3.0.0
  440. *
  441. * @var string
  442. */
  443. public $signups;
  444. /**
  445. * Multisite Sites table.
  446. *
  447. * @since 3.0.0
  448. *
  449. * @var string
  450. */
  451. public $site;
  452. /**
  453. * Multisite Sitewide Terms table.
  454. *
  455. * @since 3.0.0
  456. *
  457. * @var string
  458. */
  459. public $sitecategories;
  460. /**
  461. * Multisite Site Metadata table.
  462. *
  463. * @since 3.0.0
  464. *
  465. * @var string
  466. */
  467. public $sitemeta;
  468. /**
  469. * Format specifiers for DB columns.
  470. *
  471. * Columns not listed here default to %s. Initialized during WP load.
  472. * Keys are column names, values are format types: 'ID' => '%d'.
  473. *
  474. * @since 2.8.0
  475. *
  476. * @see wpdb::prepare()
  477. * @see wpdb::insert()
  478. * @see wpdb::update()
  479. * @see wpdb::delete()
  480. * @see wp_set_wpdb_vars()
  481. * @var array
  482. */
  483. public $field_types = array();
  484. /**
  485. * Database table columns charset.
  486. *
  487. * @since 2.2.0
  488. *
  489. * @var string
  490. */
  491. public $charset;
  492. /**
  493. * Database table columns collate.
  494. *
  495. * @since 2.2.0
  496. *
  497. * @var string
  498. */
  499. public $collate;
  500. /**
  501. * Database Username.
  502. *
  503. * @since 2.9.0
  504. *
  505. * @var string
  506. */
  507. protected $dbuser;
  508. /**
  509. * Database Password.
  510. *
  511. * @since 3.1.0
  512. *
  513. * @var string
  514. */
  515. protected $dbpassword;
  516. /**
  517. * Database Name.
  518. *
  519. * @since 3.1.0
  520. *
  521. * @var string
  522. */
  523. protected $dbname;
  524. /**
  525. * Database Host.
  526. *
  527. * @since 3.1.0
  528. *
  529. * @var string
  530. */
  531. protected $dbhost;
  532. /**
  533. * Database handle.
  534. *
  535. * Possible values:
  536. *
  537. * - `mysqli` instance when the `mysqli` driver is in use
  538. * - `resource` when the older `mysql` driver is in use
  539. * - `null` if the connection is yet to be made or has been closed
  540. * - `false` if the connection has failed
  541. *
  542. * @since 0.71
  543. *
  544. * @var mysqli|resource|false|null
  545. */
  546. protected $dbh;
  547. /**
  548. * A textual description of the last query/get_row/get_var call.
  549. *
  550. * @since 3.0.0
  551. *
  552. * @var string
  553. */
  554. public $func_call;
  555. /**
  556. * Whether MySQL is used as the database engine.
  557. *
  558. * Set in wpdb::db_connect() to true, by default. This is used when checking
  559. * against the required MySQL version for WordPress. Normally, a replacement
  560. * database drop-in (db.php) will skip these checks, but setting this to true
  561. * will force the checks to occur.
  562. *
  563. * @since 3.3.0
  564. *
  565. * @var bool
  566. */
  567. public $is_mysql = null;
  568. /**
  569. * A list of incompatible SQL modes.
  570. *
  571. * @since 3.9.0
  572. *
  573. * @var string[]
  574. */
  575. protected $incompatible_modes = array(
  576. 'NO_ZERO_DATE',
  577. 'ONLY_FULL_GROUP_BY',
  578. 'STRICT_TRANS_TABLES',
  579. 'STRICT_ALL_TABLES',
  580. 'TRADITIONAL',
  581. 'ANSI',
  582. );
  583. /**
  584. * Whether to use mysqli over mysql. Default false.
  585. *
  586. * @since 3.9.0
  587. *
  588. * @var bool
  589. */
  590. private $use_mysqli = false;
  591. /**
  592. * Whether we've managed to successfully connect at some point.
  593. *
  594. * @since 3.9.0
  595. *
  596. * @var bool
  597. */
  598. private $has_connected = false;
  599. /**
  600. * Time when the last query was performed.
  601. *
  602. * Only set when `SAVEQUERIES` is defined and truthy.
  603. *
  604. * @since 1.5.0
  605. *
  606. * @var float
  607. */
  608. public $time_start = null;
  609. /**
  610. * The last SQL error that was encountered.
  611. *
  612. * @since 2.5.0
  613. *
  614. * @var WP_Error|string
  615. */
  616. public $error = null;
  617. /**
  618. * Connects to the database server and selects a database.
  619. *
  620. * Does the actual setting up
  621. * of the class properties and connection to the database.
  622. *
  623. * @since 2.0.8
  624. *
  625. * @link https://core.trac.wordpress.org/ticket/3354
  626. *
  627. * @param string $dbuser Database user.
  628. * @param string $dbpassword Database password.
  629. * @param string $dbname Database name.
  630. * @param string $dbhost Database host.
  631. */
  632. public function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
  633. if ( WP_DEBUG && WP_DEBUG_DISPLAY ) {
  634. $this->show_errors();
  635. }
  636. // Use the `mysqli` extension if it exists unless `WP_USE_EXT_MYSQL` is defined as true.
  637. if ( function_exists( 'mysqli_connect' ) ) {
  638. $this->use_mysqli = true;
  639. if ( defined( 'WP_USE_EXT_MYSQL' ) ) {
  640. $this->use_mysqli = ! WP_USE_EXT_MYSQL;
  641. }
  642. }
  643. $this->dbuser = $dbuser;
  644. $this->dbpassword = $dbpassword;
  645. $this->dbname = $dbname;
  646. $this->dbhost = $dbhost;
  647. // wp-config.php creation will manually connect when ready.
  648. if ( defined( 'WP_SETUP_CONFIG' ) ) {
  649. return;
  650. }
  651. $this->db_connect();
  652. }
  653. /**
  654. * Makes private properties readable for backward compatibility.
  655. *
  656. * @since 3.5.0
  657. *
  658. * @param string $name The private member to get, and optionally process.
  659. * @return mixed The private member.
  660. */
  661. public function __get( $name ) {
  662. if ( 'col_info' === $name ) {
  663. $this->load_col_info();
  664. }
  665. return $this->$name;
  666. }
  667. /**
  668. * Makes private properties settable for backward compatibility.
  669. *
  670. * @since 3.5.0
  671. *
  672. * @param string $name The private member to set.
  673. * @param mixed $value The value to set.
  674. */
  675. public function __set( $name, $value ) {
  676. $protected_members = array(
  677. 'col_meta',
  678. 'table_charset',
  679. 'check_current_query',
  680. );
  681. if ( in_array( $name, $protected_members, true ) ) {
  682. return;
  683. }
  684. $this->$name = $value;
  685. }
  686. /**
  687. * Makes private properties check-able for backward compatibility.
  688. *
  689. * @since 3.5.0
  690. *
  691. * @param string $name The private member to check.
  692. * @return bool If the member is set or not.
  693. */
  694. public function __isset( $name ) {
  695. return isset( $this->$name );
  696. }
  697. /**
  698. * Makes private properties un-settable for backward compatibility.
  699. *
  700. * @since 3.5.0
  701. *
  702. * @param string $name The private member to unset
  703. */
  704. public function __unset( $name ) {
  705. unset( $this->$name );
  706. }
  707. /**
  708. * Sets $this->charset and $this->collate.
  709. *
  710. * @since 3.1.0
  711. */
  712. public function init_charset() {
  713. $charset = '';
  714. $collate = '';
  715. if ( function_exists( 'is_multisite' ) && is_multisite() ) {
  716. $charset = 'utf8';
  717. if ( defined( 'DB_COLLATE' ) && DB_COLLATE ) {
  718. $collate = DB_COLLATE;
  719. } else {
  720. $collate = 'utf8_general_ci';
  721. }
  722. } elseif ( defined( 'DB_COLLATE' ) ) {
  723. $collate = DB_COLLATE;
  724. }
  725. if ( defined( 'DB_CHARSET' ) ) {
  726. $charset = DB_CHARSET;
  727. }
  728. $charset_collate = $this->determine_charset( $charset, $collate );
  729. $this->charset = $charset_collate['charset'];
  730. $this->collate = $charset_collate['collate'];
  731. }
  732. /**
  733. * Determines the best charset and collation to use given a charset and collation.
  734. *
  735. * For example, when able, utf8mb4 should be used instead of utf8.
  736. *
  737. * @since 4.6.0
  738. *
  739. * @param string $charset The character set to check.
  740. * @param string $collate The collation to check.
  741. * @return array {
  742. * The most appropriate character set and collation to use.
  743. *
  744. * @type string $charset Character set.
  745. * @type string $collate Collation.
  746. * }
  747. */
  748. public function determine_charset( $charset, $collate ) {
  749. if ( ( $this->use_mysqli && ! ( $this->dbh instanceof mysqli ) ) || empty( $this->dbh ) ) {
  750. return compact( 'charset', 'collate' );
  751. }
  752. if ( 'utf8' === $charset && $this->has_cap( 'utf8mb4' ) ) {
  753. $charset = 'utf8mb4';
  754. }
  755. if ( 'utf8mb4' === $charset && ! $this->has_cap( 'utf8mb4' ) ) {
  756. $charset = 'utf8';
  757. $collate = str_replace( 'utf8mb4_', 'utf8_', $collate );
  758. }
  759. if ( 'utf8mb4' === $charset ) {
  760. // _general_ is outdated, so we can upgrade it to _unicode_, instead.
  761. if ( ! $collate || 'utf8_general_ci' === $collate ) {
  762. $collate = 'utf8mb4_unicode_ci';
  763. } else {
  764. $collate = str_replace( 'utf8_', 'utf8mb4_', $collate );
  765. }
  766. }
  767. // _unicode_520_ is a better collation, we should use that when it's available.
  768. if ( $this->has_cap( 'utf8mb4_520' ) && 'utf8mb4_unicode_ci' === $collate ) {
  769. $collate = 'utf8mb4_unicode_520_ci';
  770. }
  771. return compact( 'charset', 'collate' );
  772. }
  773. /**
  774. * Sets the connection's character set.
  775. *
  776. * @since 3.1.0
  777. *
  778. * @param mysqli|resource $dbh The connection returned by `mysqli_connect()` or `mysql_connect()`.
  779. * @param string $charset Optional. The character set. Default null.
  780. * @param string $collate Optional. The collation. Default null.
  781. */
  782. public function set_charset( $dbh, $charset = null, $collate = null ) {
  783. if ( ! isset( $charset ) ) {
  784. $charset = $this->charset;
  785. }
  786. if ( ! isset( $collate ) ) {
  787. $collate = $this->collate;
  788. }
  789. if ( $this->has_cap( 'collation' ) && ! empty( $charset ) ) {
  790. $set_charset_succeeded = true;
  791. if ( $this->use_mysqli ) {
  792. if ( function_exists( 'mysqli_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
  793. $set_charset_succeeded = mysqli_set_charset( $dbh, $charset );
  794. }
  795. if ( $set_charset_succeeded ) {
  796. $query = $this->prepare( 'SET NAMES %s', $charset );
  797. if ( ! empty( $collate ) ) {
  798. $query .= $this->prepare( ' COLLATE %s', $collate );
  799. }
  800. mysqli_query( $dbh, $query );
  801. }
  802. } else {
  803. if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
  804. $set_charset_succeeded = mysql_set_charset( $charset, $dbh );
  805. }
  806. if ( $set_charset_succeeded ) {
  807. $query = $this->prepare( 'SET NAMES %s', $charset );
  808. if ( ! empty( $collate ) ) {
  809. $query .= $this->prepare( ' COLLATE %s', $collate );
  810. }
  811. mysql_query( $query, $dbh );
  812. }
  813. }
  814. }
  815. }
  816. /**
  817. * Changes the current SQL mode, and ensures its WordPress compatibility.
  818. *
  819. * If no modes are passed, it will ensure the current MySQL server modes are compatible.
  820. *
  821. * @since 3.9.0
  822. *
  823. * @param array $modes Optional. A list of SQL modes to set. Default empty array.
  824. */
  825. public function set_sql_mode( $modes = array() ) {
  826. if ( empty( $modes ) ) {
  827. if ( $this->use_mysqli ) {
  828. $res = mysqli_query( $this->dbh, 'SELECT @@SESSION.sql_mode' );
  829. } else {
  830. $res = mysql_query( 'SELECT @@SESSION.sql_mode', $this->dbh );
  831. }
  832. if ( empty( $res ) ) {
  833. return;
  834. }
  835. if ( $this->use_mysqli ) {
  836. $modes_array = mysqli_fetch_array( $res );
  837. if ( empty( $modes_array[0] ) ) {
  838. return;
  839. }
  840. $modes_str = $modes_array[0];
  841. } else {
  842. $modes_str = mysql_result( $res, 0 );
  843. }
  844. if ( empty( $modes_str ) ) {
  845. return;
  846. }
  847. $modes = explode( ',', $modes_str );
  848. }
  849. $modes = array_change_key_case( $modes, CASE_UPPER );
  850. /**
  851. * Filters the list of incompatible SQL modes to exclude.
  852. *
  853. * @since 3.9.0
  854. *
  855. * @param array $incompatible_modes An array of incompatible modes.
  856. */
  857. $incompatible_modes = (array) apply_filters( 'incompatible_sql_modes', $this->incompatible_modes );
  858. foreach ( $modes as $i => $mode ) {
  859. if ( in_array( $mode, $incompatible_modes, true ) ) {
  860. unset( $modes[ $i ] );
  861. }
  862. }
  863. $modes_str = implode( ',', $modes );
  864. if ( $this->use_mysqli ) {
  865. mysqli_query( $this->dbh, "SET SESSION sql_mode='$modes_str'" );
  866. } else {
  867. mysql_query( "SET SESSION sql_mode='$modes_str'", $this->dbh );
  868. }
  869. }
  870. /**
  871. * Sets the table prefix for the WordPress tables.
  872. *
  873. * @since 2.5.0
  874. *
  875. * @param string $prefix Alphanumeric name for the new prefix.
  876. * @param bool $set_table_names Optional. Whether the table names, e.g. wpdb::$posts,
  877. * should be updated or not. Default true.
  878. * @return string|WP_Error Old prefix or WP_Error on error.
  879. */
  880. public function set_prefix( $prefix, $set_table_names = true ) {
  881. if ( preg_match( '|[^a-z0-9_]|i', $prefix ) ) {
  882. return new WP_Error( 'invalid_db_prefix', 'Invalid database prefix' );
  883. }
  884. $old_prefix = is_multisite() ? '' : $prefix;
  885. if ( isset( $this->base_prefix ) ) {
  886. $old_prefix = $this->base_prefix;
  887. }
  888. $this->base_prefix = $prefix;
  889. if ( $set_table_names ) {
  890. foreach ( $this->tables( 'global' ) as $table => $prefixed_table ) {
  891. $this->$table = $prefixed_table;
  892. }
  893. if ( is_multisite() && empty( $this->blogid ) ) {
  894. return $old_prefix;
  895. }
  896. $this->prefix = $this->get_blog_prefix();
  897. foreach ( $this->tables( 'blog' ) as $table => $prefixed_table ) {
  898. $this->$table = $prefixed_table;
  899. }
  900. foreach ( $this->tables( 'old' ) as $table => $prefixed_table ) {
  901. $this->$table = $prefixed_table;
  902. }
  903. }
  904. return $old_prefix;
  905. }
  906. /**
  907. * Sets blog ID.
  908. *
  909. * @since 3.0.0
  910. *
  911. * @param int $blog_id
  912. * @param int $network_id Optional.
  913. * @return int Previous blog ID.
  914. */
  915. public function set_blog_id( $blog_id, $network_id = 0 ) {
  916. if ( ! empty( $network_id ) ) {
  917. $this->siteid = $network_id;
  918. }
  919. $old_blog_id = $this->blogid;
  920. $this->blogid = $blog_id;
  921. $this->prefix = $this->get_blog_prefix();
  922. foreach ( $this->tables( 'blog' ) as $table => $prefixed_table ) {
  923. $this->$table = $prefixed_table;
  924. }
  925. foreach ( $this->tables( 'old' ) as $table => $prefixed_table ) {
  926. $this->$table = $prefixed_table;
  927. }
  928. return $old_blog_id;
  929. }
  930. /**
  931. * Gets blog prefix.
  932. *
  933. * @since 3.0.0
  934. *
  935. * @param int $blog_id Optional.
  936. * @return string Blog prefix.
  937. */
  938. public function get_blog_prefix( $blog_id = null ) {
  939. if ( is_multisite() ) {
  940. if ( null === $blog_id ) {
  941. $blog_id = $this->blogid;
  942. }
  943. $blog_id = (int) $blog_id;
  944. if ( defined( 'MULTISITE' ) && ( 0 === $blog_id || 1 === $blog_id ) ) {
  945. return $this->base_prefix;
  946. } else {
  947. return $this->base_prefix . $blog_id . '_';
  948. }
  949. } else {
  950. return $this->base_prefix;
  951. }
  952. }
  953. /**
  954. * Returns an array of WordPress tables.
  955. *
  956. * Also allows for the `CUSTOM_USER_TABLE` and `CUSTOM_USER_META_TABLE` to override the WordPress users
  957. * and usermeta tables that would otherwise be determined by the prefix.
  958. *
  959. * The `$scope` argument can take one of the following:
  960. *
  961. * - 'all' - returns 'all' and 'global' tables. No old tables are returned.
  962. * - 'blog' - returns the blog-level tables for the queried blog.
  963. * - 'global' - returns the global tables for the installation, returning multisite tables only on multisite.
  964. * - 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
  965. * - 'old' - returns tables which are deprecated.
  966. *
  967. * @since 3.0.0
  968. *
  969. * @uses wpdb::$tables
  970. * @uses wpdb::$old_tables
  971. * @uses wpdb::$global_tables
  972. * @uses wpdb::$ms_global_tables
  973. *
  974. * @param string $scope Optional. Possible values include 'all', 'global', 'ms_global', 'blog',
  975. * or 'old' tables. Default 'all'.
  976. * @param bool $prefix Optional. Whether to include table prefixes. If blog prefix is requested,
  977. * then the custom users and usermeta tables will be mapped. Default true.
  978. * @param int $blog_id Optional. The blog_id to prefix. Used only when prefix is requested.
  979. * Defaults to `wpdb::$blogid`.
  980. * @return string[] Table names. When a prefix is requested, the key is the unprefixed table name.
  981. */
  982. public function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
  983. switch ( $scope ) {
  984. case 'all':
  985. $tables = array_merge( $this->global_tables, $this->tables );
  986. if ( is_multisite() ) {
  987. $tables = array_merge( $tables, $this->ms_global_tables );
  988. }
  989. break;
  990. case 'blog':
  991. $tables = $this->tables;
  992. break;
  993. case 'global':
  994. $tables = $this->global_tables;
  995. if ( is_multisite() ) {
  996. $tables = array_merge( $tables, $this->ms_global_tables );
  997. }
  998. break;
  999. case 'ms_global':
  1000. $tables = $this->ms_global_tables;
  1001. break;
  1002. case 'old':
  1003. $tables = $this->old_tables;
  1004. break;
  1005. default:
  1006. return array();
  1007. }
  1008. if ( $prefix ) {
  1009. if ( ! $blog_id ) {
  1010. $blog_id = $this->blogid;
  1011. }
  1012. $blog_prefix = $this->get_blog_prefix( $blog_id );
  1013. $base_prefix = $this->base_prefix;
  1014. $global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
  1015. foreach ( $tables as $k => $table ) {
  1016. if ( in_array( $table, $global_tables, true ) ) {
  1017. $tables[ $table ] = $base_prefix . $table;
  1018. } else {
  1019. $tables[ $table ] = $blog_prefix . $table;
  1020. }
  1021. unset( $tables[ $k ] );
  1022. }
  1023. if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) ) {
  1024. $tables['users'] = CUSTOM_USER_TABLE;
  1025. }
  1026. if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) ) {
  1027. $tables['usermeta'] = CUSTOM_USER_META_TABLE;
  1028. }
  1029. }
  1030. return $tables;
  1031. }
  1032. /**
  1033. * Selects a database using the current or provided database connection.
  1034. *
  1035. * The database name will be changed based on the current database connection.
  1036. * On failure, the execution will bail and display a DB error.
  1037. *
  1038. * @since 0.71
  1039. *
  1040. * @param string $db Database name.
  1041. * @param mysqli|resource $dbh Optional database connection.
  1042. */
  1043. public function select( $db, $dbh = null ) {
  1044. if ( is_null( $dbh ) ) {
  1045. $dbh = $this->dbh;
  1046. }
  1047. if ( $this->use_mysqli ) {
  1048. $success = mysqli_select_db( $dbh, $db );
  1049. } else {
  1050. $success = mysql_select_db( $db, $dbh );
  1051. }
  1052. if ( ! $success ) {
  1053. $this->ready = false;
  1054. if ( ! did_action( 'template_redirect' ) ) {
  1055. wp_load_translations_early();
  1056. $message = '<h1>' . __( 'Can&#8217;t select database' ) . "</h1>\n";
  1057. $message .= '<p>' . sprintf(
  1058. /* translators: %s: Database name. */
  1059. __( 'We were able to connect to the database server (which means your username and password is okay) but not able to select the %s database.' ),
  1060. '<code>' . htmlspecialchars( $db, ENT_QUOTES ) . '</code>'
  1061. ) . "</p>\n";
  1062. $message .= "<ul>\n";
  1063. $message .= '<li>' . __( 'Are you sure it exists?' ) . "</li>\n";
  1064. $message .= '<li>' . sprintf(
  1065. /* translators: 1: Database user, 2: Database name. */
  1066. __( 'Does the user %1$s have permission to use the %2$s database?' ),
  1067. '<code>' . htmlspecialchars( $this->dbuser, ENT_QUOTES ) . '</code>',
  1068. '<code>' . htmlspecialchars( $db, ENT_QUOTES ) . '</code>'
  1069. ) . "</li>\n";
  1070. $message .= '<li>' . sprintf(
  1071. /* translators: %s: Database name. */
  1072. __( '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?' ),
  1073. htmlspecialchars( $db, ENT_QUOTES )
  1074. ) . "</li>\n";
  1075. $message .= "</ul>\n";
  1076. $message .= '<p>' . sprintf(
  1077. /* translators: %s: Support forums URL. */
  1078. __( 'If you don&#8217;t 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>.' ),
  1079. __( 'https://wordpress.org/support/forums/' )
  1080. ) . "</p>\n";
  1081. $this->bail( $message, 'db_select_fail' );
  1082. }
  1083. }
  1084. }
  1085. /**
  1086. * Do not use, deprecated.
  1087. *
  1088. * Use esc_sql() or wpdb::prepare() instead.
  1089. *
  1090. * @since 2.8.0
  1091. * @deprecated 3.6.0 Use wpdb::prepare()
  1092. * @see wpdb::prepare()
  1093. * @see esc_sql()
  1094. *
  1095. * @param string $string
  1096. * @return string
  1097. */
  1098. public function _weak_escape( $string ) {
  1099. if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) ) {
  1100. _deprecated_function( __METHOD__, '3.6.0', 'wpdb::prepare() or esc_sql()' );
  1101. }
  1102. return addslashes( $string );
  1103. }
  1104. /**
  1105. * Real escape, using mysqli_real_escape_string() or mysql_real_escape_string().
  1106. *
  1107. * @since 2.8.0
  1108. *
  1109. * @see mysqli_real_escape_string()
  1110. * @see mysql_real_escape_string()
  1111. *
  1112. * @param string $string String to escape.
  1113. * @return string Escaped string.
  1114. */
  1115. public function _real_escape( $string ) {
  1116. if ( ! is_scalar( $string ) ) {
  1117. return '';
  1118. }
  1119. if ( $this->dbh ) {
  1120. if ( $this->use_mysqli ) {
  1121. $escaped = mysqli_real_escape_string( $this->dbh, $string );
  1122. } else {
  1123. $escaped = mysql_real_escape_string( $string, $this->dbh );
  1124. }
  1125. } else {
  1126. $class = get_class( $this );
  1127. wp_load_translations_early();
  1128. /* translators: %s: Database access abstraction class, usually wpdb or a class extending wpdb. */
  1129. _doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), '3.6.0' );
  1130. $escaped = addslashes( $string );
  1131. }
  1132. return $this->add_placeholder_escape( $escaped );
  1133. }
  1134. /**
  1135. * Escapes data. Works on arrays.
  1136. *
  1137. * @since 2.8.0
  1138. *
  1139. * @uses wpdb::_real_escape()
  1140. *
  1141. * @param string|array $data Data to escape.
  1142. * @return string|array Escaped data, in the same type as supplied.
  1143. */
  1144. public function _escape( $data ) {
  1145. if ( is_array( $data ) ) {
  1146. foreach ( $data as $k => $v ) {
  1147. if ( is_array( $v ) ) {
  1148. $data[ $k ] = $this->_escape( $v );
  1149. } else {
  1150. $data[ $k ] = $this->_real_escape( $v );
  1151. }
  1152. }
  1153. } else {
  1154. $data = $this->_real_escape( $data );
  1155. }
  1156. return $data;
  1157. }
  1158. /**
  1159. * Do not use, deprecated.
  1160. *
  1161. * Use esc_sql() or wpdb::prepare() instead.
  1162. *
  1163. * @since 0.71
  1164. * @deprecated 3.6.0 Use wpdb::prepare()
  1165. * @see wpdb::prepare()
  1166. * @see esc_sql()
  1167. *
  1168. * @param string|array $data Data to escape.
  1169. * @return string|array Escaped data, in the same type as supplied.
  1170. */
  1171. public function escape( $data ) {
  1172. if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) ) {
  1173. _deprecated_function( __METHOD__, '3.6.0', 'wpdb::prepare() or esc_sql()' );
  1174. }
  1175. if ( is_array( $data ) ) {
  1176. foreach ( $data as $k => $v ) {
  1177. if ( is_array( $v ) ) {
  1178. $data[ $k ] = $this->escape( $v, 'recursive' );
  1179. } else {
  1180. $data[ $k ] = $this->_weak_escape( $v, 'internal' );
  1181. }
  1182. }
  1183. } else {
  1184. $data = $this->_weak_escape( $data, 'internal' );
  1185. }
  1186. return $data;
  1187. }
  1188. /**
  1189. * Escapes content by reference for insertion into the database, for security.
  1190. *
  1191. * @uses wpdb::_real_escape()
  1192. *
  1193. * @since 2.3.0
  1194. *
  1195. * @param string $string String to escape.
  1196. */
  1197. public function escape_by_ref( &$string ) {
  1198. if ( ! is_float( $string ) ) {
  1199. $string = $this->_real_escape( $string );
  1200. }
  1201. }
  1202. /**
  1203. * Prepares a SQL query for safe execution.
  1204. *
  1205. * Uses sprintf()-like syntax. The following placeholders can be used in the query string:
  1206. *
  1207. * - %d (integer)
  1208. * - %f (float)
  1209. * - %s (string)
  1210. *
  1211. * All placeholders MUST be left unquoted in the query string. A corresponding argument
  1212. * MUST be passed for each placeholder.
  1213. *
  1214. * Note: There is one exception to the above: for compatibility with old behavior,
  1215. * numbered or formatted string placeholders (eg, `%1$s`, `%5s`) will not have quotes
  1216. * added by this function, so should be passed with appropriate quotes around them.
  1217. *
  1218. * Literal percentage signs (`%`) in the query string must be written as `%%`. Percentage wildcards
  1219. * (for example, to use in LIKE syntax) must be passed via a substitution argument containing
  1220. * the complete LIKE string, these cannot be inserted directly in the query string.
  1221. * Also see wpdb::esc_like().
  1222. *
  1223. * Arguments may be passed as individual arguments to the method, or as a single array
  1224. * containing all arguments. A combination of the two is not supported.
  1225. *
  1226. * Examples:
  1227. *
  1228. * $wpdb->prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d OR `other_field` LIKE %s", array( 'foo', 1337, '%bar' ) );
  1229. * $wpdb->prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
  1230. *
  1231. * @since 2.3.0
  1232. * @since 5.3.0 Formalized the existing and already documented `...$args` parameter
  1233. * by updating the function signature. The second parameter was changed
  1234. * from `$args` to `...$args`.
  1235. *
  1236. * @link https://www.php.net/sprintf Description of syntax.
  1237. *
  1238. * @param string $query Query statement with sprintf()-like placeholders.
  1239. * @param array|mixed $args The array of variables to substitute into the query's placeholders
  1240. * if being called with an array of arguments, or the first variable
  1241. * to substitute into the query's placeholders if being called with
  1242. * individual arguments.
  1243. * @param mixed ...$args Further variables to substitute into the query's placeholders
  1244. * if being called with individual arguments.
  1245. * @return string|void Sanitized query string, if there is a query to prepare.
  1246. */
  1247. public function prepare( $query, ...$args ) {
  1248. if ( is_null( $query ) ) {
  1249. return;
  1250. }
  1251. // This is not meant to be foolproof -- but it will catch obviously incorrect usage.
  1252. if ( strpos( $query, '%' ) === false ) {
  1253. wp_load_translations_early();
  1254. _doing_it_wrong(
  1255. 'wpdb::prepare',
  1256. sprintf(
  1257. /* translators: %s: wpdb::prepare() */
  1258. __( 'The query argument of %s must have a placeholder.' ),
  1259. 'wpdb::prepare()'
  1260. ),
  1261. '3.9.0'
  1262. );
  1263. }
  1264. // If args were passed as an array (as in vsprintf), move them up.
  1265. $passed_as_array = false;
  1266. if ( isset( $args[0] ) && is_array( $args[0] ) && 1 === count( $args ) ) {
  1267. $passed_as_array = true;
  1268. $args = $args[0];
  1269. }
  1270. foreach ( $args as $arg ) {
  1271. if ( ! is_scalar( $arg ) && ! is_null( $arg ) ) {
  1272. wp_load_translations_early();
  1273. _doing_it_wrong(
  1274. 'wpdb::prepare',
  1275. sprintf(
  1276. /* translators: %s: Value type. */
  1277. __( 'Unsupported value type (%s).' ),
  1278. gettype( $arg )
  1279. ),
  1280. '4.8.2'
  1281. );
  1282. }
  1283. }
  1284. /*
  1285. * Specify the formatting allowed in a placeholder. The following are allowed:
  1286. *
  1287. * - Sign specifier. eg, $+d
  1288. * - Numbered placeholders. eg, %1$s
  1289. * - Padding specifier, including custom padding characters. eg, %05s, %'#5s
  1290. * - Alignment specifier. eg, %05-s
  1291. * - Precision specifier. eg, %.2f
  1292. */
  1293. $allowed_format = '(?:[1-9][0-9]*[$])?[-+0-9]*(?: |0|\'.)?[-+0-9]*(?:\.[0-9]+)?';
  1294. /*
  1295. * If a %s placeholder already has quotes around it, removing the existing quotes and re-inserting them
  1296. * ensures the quotes are consistent.
  1297. *
  1298. * For backward compatibility, this is only applied to %s, and not to placeholders like %1$s, which are frequently
  1299. * used in the middle of longer strings, or as table name placeholders.
  1300. */
  1301. $query = str_replace( "'%s'", '%s', $query ); // Strip any existing single quotes.
  1302. $query = str_replace( '"%s"', '%s', $query ); // Strip any existing double quotes.
  1303. $query = preg_replace( '/(?<!%)%s/', "'%s'", $query ); // Quote the strings, avoiding escaped strings like %%s.
  1304. $query = preg_replace( "/(?<!%)(%($allowed_format)?f)/", '%\\2F', $query ); // Force floats to be locale-unaware.
  1305. $query = preg_replace( "/%(?:%|$|(?!($allowed_format)?[sdF]))/", '%%\\1', $query ); // Escape any unescaped percents.
  1306. // Count the number of valid placeholders in the query.
  1307. $placeholders = preg_match_all( "/(^|[^%]|(%%)+)%($allowed_format)?[sdF]/", $query, $matches );
  1308. $args_count = count( $args );
  1309. if ( $args_count !== $placeholders ) {
  1310. if ( 1 === $placeholders && $passed_as_array ) {
  1311. // If the passed query only expected one argument, but the wrong number of arguments were sent as an array, bail.
  1312. wp_load_translations_early();
  1313. _doing_it_wrong(
  1314. 'wpdb::prepare',
  1315. __( 'The query only expected one placeholder, but an array of multiple placeholders was sent.' ),
  1316. '4.9.0'
  1317. );
  1318. return;
  1319. } else {
  1320. /*
  1321. * If we don't have the right number of placeholders, but they were passed as individual arguments,
  1322. * or we were expecting multiple arguments in an array, throw a warning.
  1323. */
  1324. wp_load_translations_early();
  1325. _doing_it_wrong(
  1326. 'wpdb::prepare',
  1327. sprintf(
  1328. /* translators: 1: Number of placeholders, 2: Number of arguments passed. */
  1329. __( 'The query does not contain the correct number of placeholders (%1$d) for the number of arguments passed (%2$d).' ),
  1330. $placeholders,
  1331. $args_count
  1332. ),
  1333. '4.8.3'
  1334. );
  1335. /*
  1336. * If we don't have enough arguments to match the placeholders,
  1337. * return an empty string to avoid a fatal error on PHP 8.
  1338. */
  1339. if ( $args_count < $placeholders ) {
  1340. $max_numbered_placeholder = ! empty( $matches[3] ) ? max( array_map( 'intval', $matches[3] ) ) : 0;
  1341. if ( ! $max_numbered_placeholder || $args_count < $max_numbered_placeholder ) {
  1342. return '';
  1343. }
  1344. }
  1345. }
  1346. }
  1347. array_walk( $args, array( $this, 'escape_by_ref' ) );
  1348. $query = vsprintf( $query, $args );
  1349. return $this->add_placeholder_escape( $query );
  1350. }
  1351. /**
  1352. * First half of escaping for `LIKE` special characters `%` and `_` before preparing for SQL.
  1353. *
  1354. * Use this only before wpdb::prepare() or esc_sql(). Reversing the order is very bad for security.
  1355. *
  1356. * Example Prepared Statement:
  1357. *
  1358. * $wild = '%';
  1359. * $find = 'only 43% of planets';
  1360. * $like = $wild . $wpdb->esc_like( $find ) . $wild;
  1361. * $sql = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_content LIKE %s", $like );
  1362. *
  1363. * Example Escape Chain:
  1364. *
  1365. * $sql = esc_sql( $wpdb->esc_like( $input ) );
  1366. *
  1367. * @since 4.0.0
  1368. *
  1369. * @param string $text The raw text to be escaped. The input typed by the user
  1370. * should have no extra or deleted slashes.
  1371. * @return string Text in the form of a LIKE phrase. The output is not SQL safe.
  1372. * Call wpdb::prepare() or wpdb::_real_escape() next.
  1373. */
  1374. public function esc_like( $text ) {
  1375. return addcslashes( $text, '_%\\' );
  1376. }
  1377. /**
  1378. * Prints SQL/DB error.
  1379. *
  1380. * @since 0.71
  1381. *
  1382. * @global array $EZSQL_ERROR Stores error information of query and error string.
  1383. *
  1384. * @param string $str The error to display.
  1385. * @return void|false Void if the showing of errors is enabled, false if disabled.
  1386. */
  1387. public function print_error( $str = '' ) {
  1388. global $EZSQL_ERROR;
  1389. if ( ! $str ) {
  1390. if ( $this->use_mysqli ) {
  1391. $str = mysqli_error( $this->dbh );
  1392. } else {
  1393. $str = mysql_error( $this->dbh );
  1394. }
  1395. }
  1396. $EZSQL_ERROR[] = array(
  1397. 'query' => $this->last_query,
  1398. 'error_str' => $str,
  1399. );
  1400. if ( $this->suppress_errors ) {
  1401. return false;
  1402. }
  1403. wp_load_translations_early();
  1404. $caller = $this->get_caller();
  1405. if ( $caller ) {
  1406. /* translators: 1: Database error message, 2: SQL query, 3: Name of the calling function. */
  1407. $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s made by %3$s' ), $str, $this->last_query, $caller );
  1408. } else {
  1409. /* translators: 1: Database error message, 2: SQL query. */
  1410. $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s' ), $str, $this->last_query );
  1411. }
  1412. error_log( $error_str );
  1413. // Are we showing errors?
  1414. if ( ! $this->show_errors ) {
  1415. return false;
  1416. }
  1417. // If there is an error then take note of it.
  1418. if ( is_multisite() ) {
  1419. $msg = sprintf(
  1420. "%s [%s]\n%s\n",
  1421. __( 'WordPress database error:' ),
  1422. $str,
  1423. $this->last_query
  1424. );
  1425. if ( defined( 'ERRORLOGFILE' ) ) {
  1426. error_log( $msg, 3, ERRORLOGFILE );
  1427. }
  1428. if ( defined( 'DIEONDBERROR' ) ) {
  1429. wp_die( $msg );
  1430. }
  1431. } else {
  1432. $str = htmlspecialchars( $str, ENT_QUOTES );
  1433. $query = htmlspecialchars( $this->last_query, ENT_QUOTES );
  1434. printf(
  1435. '<div id="error"><p class="wpdberror"><strong>%s</strong> [%s]<br /><code>%s</code></p></div>',
  1436. __( 'WordPress database error:' ),
  1437. $str,
  1438. $query
  1439. );
  1440. }
  1441. }
  1442. /**
  1443. * Enables showing of database errors.
  1444. *
  1445. * This function should be used only to enable showing of errors.
  1446. * wpdb::hide_errors() should be used instead for hiding errors.
  1447. *
  1448. * @since 0.71
  1449. *
  1450. * @see wpdb::hide_errors()
  1451. *
  1452. * @param bool $show Optional. Whether to show errors. Default true.
  1453. * @return bool Whether showing of errors was previously active.
  1454. */
  1455. public function show_errors( $show = true ) {
  1456. $errors = $this->show_errors;
  1457. $this->show_errors = $show;
  1458. return $errors;
  1459. }
  1460. /**
  1461. * Disables showing of database errors.
  1462. *
  1463. * By default database errors are not shown.
  1464. *
  1465. * @since 0.71
  1466. *
  1467. * @see wpdb::show_errors()
  1468. *
  1469. * @return bool Whether showing of errors was previously active.
  1470. */
  1471. public function hide_errors() {
  1472. $show = $this->show_errors;
  1473. $this->show_errors = false;
  1474. return $show;
  1475. }
  1476. /**
  1477. * Enables or disables suppressing of database errors.
  1478. *
  1479. * By default database errors are suppressed.
  1480. *
  1481. * @since 2.5.0
  1482. *
  1483. * @see wpdb::hide_errors()
  1484. *
  1485. * @param bool $suppress Optional. Whether to suppress errors. Default true.
  1486. * @return bool Whether suppressing of errors was previously active.
  1487. */
  1488. public function suppress_errors( $suppress = true ) {
  1489. $errors = $this->suppress_errors;
  1490. $this->suppress_errors = (bool) $suppress;
  1491. return $errors;
  1492. }
  1493. /**
  1494. * Kills cached query results.
  1495. *
  1496. * @since 0.71
  1497. */
  1498. public function flush() {
  1499. $this->last_result = array();
  1500. $this->col_info = null;
  1501. $this->last_query = null;
  1502. $this->rows_affected = 0;
  1503. $this->num_rows = 0;
  1504. $this->last_error = '';
  1505. if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
  1506. mysqli_free_result( $this->result );
  1507. $this->result = null;
  1508. // Sanity check before using the handle.
  1509. if ( empty( $this->dbh ) || ! ( $this->dbh instanceof mysqli ) ) {
  1510. return;
  1511. }
  1512. // Clear out any results from a multi-query.
  1513. while ( mysqli_more_results( $this->dbh ) ) {
  1514. mysqli_next_result( $this->dbh );
  1515. }
  1516. } elseif ( is_resource( $this->result ) ) {
  1517. mysql_free_result( $this->result );
  1518. }
  1519. }
  1520. /**
  1521. * Connects to and selects database.
  1522. *
  1523. * If `$allow_bail` is false, the lack of database connection will need to be handled manually.
  1524. *
  1525. * @since 3.0.0
  1526. * @since 3.9.0 $allow_bail parameter added.
  1527. *
  1528. * @param bool $allow_bail Optional. Allows the function to bail. Default true.
  1529. * @return bool True with a successful connection, false on failure.
  1530. */
  1531. public function db_connect( $allow_bail = true ) {
  1532. $this->is_mysql = true;
  1533. /*
  1534. * Deprecated in 3.9+ when using MySQLi. No equivalent
  1535. * $new_link parameter exists for mysqli_* functions.
  1536. */
  1537. $new_link = defined( 'MYSQL_NEW_LINK' ) ? MYSQL_NEW_LINK : true;
  1538. $client_flags = defined( 'MYSQL_CLIENT_FLAGS' ) ? MYSQL_CLIENT_FLAGS : 0;
  1539. if ( $this->use_mysqli ) {
  1540. /*
  1541. * Set the MySQLi error reporting off because WordPress handles its own.
  1542. * This is due to the default value change from `MYSQLI_REPORT_OFF`
  1543. * to `MYSQLI_REPORT_ERROR|MYSQLI_REPORT_STRICT` in PHP 8.1.
  1544. */
  1545. mysqli_report( MYSQLI_REPORT_OFF );
  1546. $this->dbh = mysqli_init();
  1547. $host = $this->dbhost;
  1548. $port = null;
  1549. $socket = null;
  1550. $is_ipv6 = false;
  1551. $host_data = $this->parse_db_host( $this->dbhost );
  1552. if ( $host_data ) {
  1553. list( $host, $port, $socket, $is_ipv6 ) = $host_data;
  1554. }
  1555. /*
  1556. * If using the `mysqlnd` library, the IPv6 address needs to be enclosed
  1557. * in square brackets, whereas it doesn't while using the `libmysqlclient` library.
  1558. * @see https://bugs.php.net/bug.php?id=67563
  1559. */
  1560. if ( $is_ipv6 && extension_loaded( 'mysqlnd' ) ) {
  1561. $host = "[$host]";
  1562. }
  1563. if ( WP_DEBUG ) {
  1564. mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
  1565. } else {
  1566. // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
  1567. @mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
  1568. }
  1569. if ( $this->dbh->connect_errno ) {
  1570. $this->dbh = null;
  1571. /*
  1572. * It's possible ext/mysqli is misconfigured. Fall back to ext/mysql if:
  1573. * - We haven't previously connected, and
  1574. * - WP_USE_EXT_MYSQL isn't set to false, and
  1575. * - ext/mysql is loaded.
  1576. */
  1577. $attempt_fallback = true;
  1578. if ( $this->has_connected ) {
  1579. $attempt_fallback = false;
  1580. } elseif ( defined( 'WP_USE_EXT_MYSQL' ) && ! WP_USE_EXT_MYSQL ) {
  1581. $attempt_fallback = false;
  1582. } elseif ( ! function_exists( 'mysql_connect' ) ) {
  1583. $attempt_fallback = false;
  1584. }
  1585. if ( $attempt_fallback ) {
  1586. $this->use_mysqli = false;
  1587. return $this->db_connect( $allow_bail );
  1588. }
  1589. }
  1590. } else {
  1591. if ( WP_DEBUG ) {
  1592. $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
  1593. } else {
  1594. // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
  1595. $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
  1596. }
  1597. }
  1598. if ( ! $this->dbh && $allow_bail ) {
  1599. wp_load_translations_early();
  1600. // Load custom DB error template, if present.
  1601. if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
  1602. require_once WP_CONTENT_DIR . '/db-error.php';
  1603. die();
  1604. }
  1605. $message = '<h1>' . __( 'Error establishing a database connection' ) . "</h1>\n";
  1606. $message .= '<p>' . sprintf(
  1607. /* translators: 1: wp-config.php, 2: Database host. */
  1608. __( 'This either means that the username and password information in your %1$s file is incorrect or we can&#8217;t contact the database server at %2$s. This could mean your host&#8217;s database server is down.' ),
  1609. '<code>wp-config.php</code>',
  1610. '<code>' . htmlspecialchars( $this->dbhost, ENT_QUOTES ) . '</code>'
  1611. ) . "</p>\n";
  1612. $message .= "<ul>\n";
  1613. $message .= '<li>' . __( 'Are you sure you have the correct username and password?' ) . "</li>\n";
  1614. $message .= '<li>' . __( 'Are you sure you have typed the correct hostname?' ) . "</li>\n";
  1615. $message .= '<li>' . __( 'Are you sure the database server is running?' ) . "</li>\n";
  1616. $message .= "</ul>\n";
  1617. $message .= '<p>' . sprintf(
  1618. /* translators: %s: Support forums URL. */
  1619. __( 'If you&#8217;re 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>.' ),
  1620. __( 'https://wordpress.org/support/forums/' )
  1621. ) . "</p>\n";
  1622. $this->bail( $message, 'db_connect_fail' );
  1623. return false;
  1624. } elseif ( $this->dbh ) {
  1625. if ( ! $this->has_connected ) {
  1626. $this->init_charset();
  1627. }
  1628. $this->has_connected = true;
  1629. $this->set_charset( $this->dbh );
  1630. $this->ready = true;
  1631. $this->set_sql_mode();
  1632. $this->select( $this->dbname, $this->dbh );
  1633. return true;
  1634. }
  1635. return false;
  1636. }
  1637. /**
  1638. * Parses the DB_HOST setting to interpret it for mysqli_real_connect().
  1639. *
  1640. * mysqli_real_connect() doesn't support the host param including a port or socket
  1641. * like mysql_connect() does. This duplicates how mysql_connect() detects a port
  1642. * and/or socket file.
  1643. *
  1644. * @since 4.9.0
  1645. *
  1646. * @param string $host The DB_HOST setting to parse.
  1647. * @return array|false Array containing the host, the port, the socket and
  1648. * whether it is an IPv6 address, in that order.
  1649. * False if $host couldn't be parsed.
  1650. */
  1651. public function parse_db_host( $host ) {
  1652. $port = null;
  1653. $socket = null;
  1654. $is_ipv6 = false;
  1655. // First peel off the socket parameter from the right, if it exists.
  1656. $socket_pos = strpos( $host, ':/' );
  1657. if ( false !== $socket_pos ) {
  1658. $socket = substr( $host, $socket_pos + 1 );
  1659. $host = substr( $host, 0, $socket_pos );
  1660. }
  1661. // We need to check for an IPv6 address first.
  1662. // An IPv6 address will always contain at least two colons.
  1663. if ( substr_count( $host, ':' ) > 1 ) {
  1664. $pattern = '#^(?:\[)?(?P<host>[0-9a-fA-F:]+)(?:\]:(?P<port>[\d]+))?#';
  1665. $is_ipv6 = true;
  1666. } else {
  1667. // We seem to be dealing with an IPv4 address.
  1668. $pattern = '#^(?P<host>[^:/]*)(?::(?P<port>[\d]+))?#';
  1669. }
  1670. $matches = array();
  1671. $result = preg_match( $pattern, $host, $matches );
  1672. if ( 1 !== $result ) {
  1673. // Couldn't parse the address, bail.
  1674. return false;
  1675. }
  1676. $host = '';
  1677. foreach ( array( 'host', 'port' ) as $component ) {
  1678. if ( ! empty( $matches[ $component ] ) ) {
  1679. $$component = $matches[ $component ];
  1680. }
  1681. }
  1682. return array( $host, $port, $socket, $is_ipv6 );
  1683. }
  1684. /**
  1685. * Checks that the connection to the database is still up. If not, try to reconnect.
  1686. *
  1687. * If this function is unable to reconnect, it will forcibly die, or if called
  1688. * after the {@see 'template_redirect'} hook has been fired, return false instead.
  1689. *
  1690. * If `$allow_bail` is false, the lack of database connection will need to be handled manually.
  1691. *
  1692. * @since 3.9.0
  1693. *
  1694. * @param bool $allow_bail Optional. Allows the function to bail. Default true.
  1695. * @return bool|void True if the connection is up.
  1696. */
  1697. public function check_connection( $allow_bail = true ) {
  1698. if ( $this->use_mysqli ) {
  1699. if ( ! empty( $this->dbh ) && mysqli_ping( $this->dbh ) ) {
  1700. return true;
  1701. }
  1702. } else {
  1703. if ( ! empty( $this->dbh ) && mysql_ping( $this->dbh ) ) {
  1704. return true;
  1705. }
  1706. }
  1707. $error_reporting = false;
  1708. // Disable warnings, as we don't want to see a multitude of "unable to connect" messages.
  1709. if ( WP_DEBUG ) {
  1710. $error_reporting = error_reporting();
  1711. error_reporting( $error_reporting & ~E_WARNING );
  1712. }
  1713. for ( $tries = 1; $tries <= $this->reconnect_retries; $tries++ ) {
  1714. // On the last try, re-enable warnings. We want to see a single instance
  1715. // of the "unable to connect" message on the bail() screen, if it appears.
  1716. if ( $this->reconnect_retries === $tries && WP_DEBUG ) {
  1717. error_reporting( $error_reporting );
  1718. }
  1719. if ( $this->db_connect( false ) ) {
  1720. if ( $error_reporting ) {
  1721. error_reporting( $error_reporting );
  1722. }
  1723. return true;
  1724. }
  1725. sleep( 1 );
  1726. }
  1727. // If template_redirect has already happened, it's too late for wp_die()/dead_db().
  1728. // Let's just return and hope for the best.
  1729. if ( did_action( 'template_redirect' ) ) {
  1730. return false;
  1731. }
  1732. if ( ! $allow_bail ) {
  1733. return false;
  1734. }
  1735. wp_load_translations_early();
  1736. $message = '<h1>' . __( 'Error reconnecting to the database' ) . "</h1>\n";
  1737. $message .= '<p>' . sprintf(
  1738. /* translators: %s: Database host. */
  1739. __( 'This means that we lost contact with the database server at %s. This could mean your host&#8217;s database server is down.' ),
  1740. '<code>' . htmlspecialchars( $this->dbhost, ENT_QUOTES ) . '</code>'
  1741. ) . "</p>\n";
  1742. $message .= "<ul>\n";
  1743. $message .= '<li>' . __( 'Are you sure the database server is running?' ) . "</li>\n";
  1744. $message .= '<li>' . __( 'Are you sure the database server is not under particularly heavy load?' ) . "</li>\n";
  1745. $message .= "</ul>\n";
  1746. $message .= '<p>' . sprintf(
  1747. /* translators: %s: Support forums URL. */
  1748. __( 'If you&#8217;re unsure what these terms mean you should probably contact your h…