PageRenderTime 43ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/wp-db.php

https://github.com/markjaquith/WordPress
PHP | 3819 lines | 1856 code | 417 blank | 1546 comment | 365 complexity | 3bc413271e20a7f48a7b1fff5b741410 MD5 | raw file
Possible License(s): GPL-2.0, AGPL-1.0, LGPL-2.1
  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 host. If you still need help you can always visit the <a href="%s">WordPress Support Forums</a>.' ),
  1749. __( 'https://wordpress.org/support/forums/' )
  1750. ) . "</p>\n";
  1751. // We weren't able to reconnect, so we better bail.
  1752. $this->bail( $message, 'db_connect_fail' );
  1753. // Call dead_db() if bail didn't die, because this database is no more.
  1754. // It has ceased to be (at least temporarily).
  1755. dead_db();
  1756. }
  1757. /**
  1758. * Performs a database query, using current database connection.
  1759. *
  1760. * More information can be found on the documentation page.
  1761. *
  1762. * @since 0.71
  1763. *
  1764. * @link https://developer.wordpress.org/reference/classes/wpdb/
  1765. *
  1766. * @param string $query Database query.
  1767. * @return int|bool Boolean true for CREATE, ALTER, TRUNCATE and DROP queries. Number of rows
  1768. * affected/selected for all other queries. Boolean false on error.
  1769. */
  1770. public function query( $query ) {
  1771. if ( ! $this->ready ) {
  1772. $this->check_current_query = true;
  1773. return false;
  1774. }
  1775. /**
  1776. * Filters the database query.
  1777. *
  1778. * Some queries are made before the plugins have been loaded,
  1779. * and thus cannot be filtered with this method.
  1780. *
  1781. * @since 2.1.0
  1782. *
  1783. * @param string $query Database query.
  1784. */
  1785. $query = apply_filters( 'query', $query );
  1786. if ( ! $query ) {
  1787. $this->insert_id = 0;
  1788. return false;
  1789. }
  1790. $this->flush();
  1791. // Log how the function was called.
  1792. $this->func_call = "\$db->query(\"$query\")";
  1793. // If we're writing to the database, make sure the query will write safely.
  1794. if ( $this->check_current_query && ! $this->check_ascii( $query ) ) {
  1795. $stripped_query = $this->strip_invalid_text_from_query( $query );
  1796. // strip_invalid_text_from_query() can perform queries, so we need
  1797. // to flush again, just to make sure everything is clear.
  1798. $this->flush();
  1799. if ( $stripped_query !== $query ) {
  1800. $this->insert_id = 0;
  1801. $this->last_query = $query;
  1802. wp_load_translations_early();
  1803. $this->last_error = __( 'WordPress database error: Could not perform query because it contains invalid data.' );
  1804. return false;
  1805. }
  1806. }
  1807. $this->check_current_query = true;
  1808. // Keep track of the last query for debug.
  1809. $this->last_query = $query;
  1810. $this->_do_query( $query );
  1811. // Database server has gone away, try to reconnect.
  1812. $mysql_errno = 0;
  1813. if ( ! empty( $this->dbh ) ) {
  1814. if ( $this->use_mysqli ) {
  1815. if ( $this->dbh instanceof mysqli ) {
  1816. $mysql_errno = mysqli_errno( $this->dbh );
  1817. } else {
  1818. // $dbh is defined, but isn't a real connection.
  1819. // Something has gone horribly wrong, let's try a reconnect.
  1820. $mysql_errno = 2006;
  1821. }
  1822. } else {
  1823. if ( is_resource( $this->dbh ) ) {
  1824. $mysql_errno = mysql_errno( $this->dbh );
  1825. } else {
  1826. $mysql_errno = 2006;
  1827. }
  1828. }
  1829. }
  1830. if ( empty( $this->dbh ) || 2006 === $mysql_errno ) {
  1831. if ( $this->check_connection() ) {
  1832. $this->_do_query( $query );
  1833. } else {
  1834. $this->insert_id = 0;
  1835. return false;
  1836. }
  1837. }
  1838. // If there is an error then take note of it.
  1839. if ( $this->use_mysqli ) {
  1840. if ( $this->dbh instanceof mysqli ) {
  1841. $this->last_error = mysqli_error( $this->dbh );
  1842. } else {
  1843. $this->last_error = __( 'Unable to retrieve the error message from MySQL' );
  1844. }
  1845. } else {
  1846. if ( is_resource( $this->dbh ) ) {
  1847. $this->last_error = mysql_error( $this->dbh );
  1848. } else {
  1849. $this->last_error = __( 'Unable to retrieve the error message from MySQL' );
  1850. }
  1851. }
  1852. if ( $this->last_error ) {
  1853. // Clear insert_id on a subsequent failed insert.
  1854. if ( $this->insert_id && preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
  1855. $this->insert_id = 0;
  1856. }
  1857. $this->print_error();
  1858. return false;
  1859. }
  1860. if ( preg_match( '/^\s*(create|alter|truncate|drop)\s/i', $query ) ) {
  1861. $return_val = $this->result;
  1862. } elseif ( preg_match( '/^\s*(insert|delete|update|replace)\s/i', $query ) ) {
  1863. if ( $this->use_mysqli ) {
  1864. $this->rows_affected = mysqli_affected_rows( $this->dbh );
  1865. } else {
  1866. $this->rows_affected = mysql_affected_rows( $this->dbh );
  1867. }
  1868. // Take note of the insert_id.
  1869. if ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
  1870. if ( $this->use_mysqli ) {
  1871. $this->insert_id = mysqli_insert_id( $this->dbh );
  1872. } else {
  1873. $this->insert_id = mysql_insert_id( $this->dbh );
  1874. }
  1875. }
  1876. // Return number of rows affected.
  1877. $return_val = $this->rows_affected;
  1878. } else {
  1879. $num_rows = 0;
  1880. if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
  1881. while ( $row = mysqli_fetch_object( $this->result ) ) {
  1882. $this->last_result[ $num_rows ] = $row;
  1883. $num_rows++;
  1884. }
  1885. } elseif ( is_resource( $this->result ) ) {
  1886. while ( $row = mysql_fetch_object( $this->result ) ) {
  1887. $this->last_result[ $num_rows ] = $row;
  1888. $num_rows++;
  1889. }
  1890. }
  1891. // Log and return the number of rows selected.
  1892. $this->num_rows = $num_rows;
  1893. $return_val = $num_rows;
  1894. }
  1895. return $return_val;
  1896. }
  1897. /**
  1898. * Internal function to perform the mysql_query() call.
  1899. *
  1900. * @since 3.9.0
  1901. *
  1902. * @see wpdb::query()
  1903. *
  1904. * @param string $query The query to run.
  1905. */
  1906. private function _do_query( $query ) {
  1907. if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
  1908. $this->timer_start();
  1909. }
  1910. if ( ! empty( $this->dbh ) && $this->use_mysqli ) {
  1911. $this->result = mysqli_query( $this->dbh, $query );
  1912. } elseif ( ! empty( $this->dbh ) ) {
  1913. $this->result = mysql_query( $query, $this->dbh );
  1914. }
  1915. $this->num_queries++;
  1916. if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
  1917. $this->log_query(
  1918. $query,
  1919. $this->timer_stop(),
  1920. $this->get_caller(),
  1921. $this->time_start,
  1922. array()
  1923. );
  1924. }
  1925. }
  1926. /**
  1927. * Logs query data.
  1928. *
  1929. * @since 5.3.0
  1930. *
  1931. * @param string $query The query's SQL.
  1932. * @param float $query_time Total time spent on the query, in seconds.
  1933. * @param string $query_callstack Comma-separated list of the calling functions.
  1934. * @param float $query_start Unix timestamp of the time at the start of the query.
  1935. * @param array $query_data Custom query data.
  1936. */
  1937. public function log_query( $query, $query_time, $query_callstack, $query_start, $query_data ) {
  1938. /**
  1939. * Filters the custom data to log alongside a query.
  1940. *
  1941. * Caution should be used when modifying any of this data, it is recommended that any additional
  1942. * information you need to store about a query be added as a new associative array element.
  1943. *
  1944. * @since 5.3.0
  1945. *
  1946. * @param array $query_data Custom query data.
  1947. * @param string $query The query's SQL.
  1948. * @param float $query_time Total time spent on the query, in seconds.
  1949. * @param string $query_callstack Comma-separated list of the calling functions.
  1950. * @param float $query_start Unix timestamp of the time at the start of the query.
  1951. */
  1952. $query_data = apply_filters( 'log_query_custom_data', $query_data, $query, $query_time, $query_callstack, $query_start );
  1953. $this->queries[] = array(
  1954. $query,
  1955. $query_time,
  1956. $query_callstack,
  1957. $query_start,
  1958. $query_data,
  1959. );
  1960. }
  1961. /**
  1962. * Generates and returns a placeholder escape string for use in queries returned by ::prepare().
  1963. *
  1964. * @since 4.8.3
  1965. *
  1966. * @return string String to escape placeholders.
  1967. */
  1968. public function placeholder_escape() {
  1969. static $placeholder;
  1970. if ( ! $placeholder ) {
  1971. // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
  1972. $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
  1973. // Old WP installs may not have AUTH_SALT defined.
  1974. $salt = defined( 'AUTH_SALT' ) && AUTH_SALT ? AUTH_SALT : (string) rand();
  1975. $placeholder = '{' . hash_hmac( $algo, uniqid( $salt, true ), $salt ) . '}';
  1976. }
  1977. /*
  1978. * Add the filter to remove the placeholder escaper. Uses priority 0, so that anything
  1979. * else attached to this filter will receive the query with the placeholder string removed.
  1980. */
  1981. if ( false === has_filter( 'query', array( $this, 'remove_placeholder_escape' ) ) ) {
  1982. add_filter( 'query', array( $this, 'remove_placeholder_escape' ), 0 );
  1983. }
  1984. return $placeholder;
  1985. }
  1986. /**
  1987. * Adds a placeholder escape string, to escape anything that resembles a printf() placeholder.
  1988. *
  1989. * @since 4.8.3
  1990. *
  1991. * @param string $query The query to escape.
  1992. * @return string The query with the placeholder escape string inserted where necessary.
  1993. */
  1994. public function add_placeholder_escape( $query ) {
  1995. /*
  1996. * To prevent returning anything that even vaguely resembles a placeholder,
  1997. * we clobber every % we can find.
  1998. */
  1999. return str_replace( '%', $this->placeholder_escape(), $query );
  2000. }
  2001. /**
  2002. * Removes the placeholder escape strings from a query.
  2003. *
  2004. * @since 4.8.3
  2005. *
  2006. * @param string $query The query from which the placeholder will be removed.
  2007. * @return string The query with the placeholder removed.
  2008. */
  2009. public function remove_placeholder_escape( $query ) {
  2010. return str_replace( $this->placeholder_escape(), '%', $query );
  2011. }
  2012. /**
  2013. * Inserts a row into the table.
  2014. *
  2015. * Examples:
  2016. *
  2017. * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
  2018. * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
  2019. *
  2020. * @since 2.5.0
  2021. *
  2022. * @see wpdb::prepare()
  2023. * @see wpdb::$field_types
  2024. * @see wp_set_wpdb_vars()
  2025. *
  2026. * @param string $table Table name.
  2027. * @param array $data Data to insert (in column => value pairs).
  2028. * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  2029. * Sending a null value will cause the column to be set to NULL - the corresponding
  2030. * format is ignored in this case.
  2031. * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
  2032. * If string, that format will be used for all of the values in $data.
  2033. * A format is one of '%d', '%f', '%s' (integer, float, string).
  2034. * If omitted, all values in $data will be treated as strings unless otherwise
  2035. * specified in wpdb::$field_types.
  2036. * @return int|false The number of rows inserted, or false on error.
  2037. */
  2038. public function insert( $table, $data, $format = null ) {
  2039. return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
  2040. }
  2041. /**
  2042. * Replaces a row in the table.
  2043. *
  2044. * Examples:
  2045. *
  2046. * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
  2047. * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
  2048. *
  2049. * @since 3.0.0
  2050. *
  2051. * @see wpdb::prepare()
  2052. * @see wpdb::$field_types
  2053. * @see wp_set_wpdb_vars()
  2054. *
  2055. * @param string $table Table name.
  2056. * @param array $data Data to insert (in column => value pairs).
  2057. * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  2058. * Sending a null value will cause the column to be set to NULL - the corresponding
  2059. * format is ignored in this case.
  2060. * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
  2061. * If string, that format will be used for all of the values in $data.
  2062. * A format is one of '%d', '%f', '%s' (integer, float, string).
  2063. * If omitted, all values in $data will be treated as strings unless otherwise
  2064. * specified in wpdb::$field_types.
  2065. * @return int|false The number of rows affected, or false on error.
  2066. */
  2067. public function replace( $table, $data, $format = null ) {
  2068. return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
  2069. }
  2070. /**
  2071. * Helper function for insert and replace.
  2072. *
  2073. * Runs an insert or replace query based on $type argument.
  2074. *
  2075. * @since 3.0.0
  2076. *
  2077. * @see wpdb::prepare()
  2078. * @see wpdb::$field_types
  2079. * @see wp_set_wpdb_vars()
  2080. *
  2081. * @param string $table Table name.
  2082. * @param array $data Data to insert (in column => value pairs).
  2083. * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  2084. * Sending a null value will cause the column to be set to NULL - the corresponding
  2085. * format is ignored in this case.
  2086. * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
  2087. * If string, that format will be used for all of the values in $data.
  2088. * A format is one of '%d', '%f', '%s' (integer, float, string).
  2089. * If omitted, all values in $data will be treated as strings unless otherwise
  2090. * specified in wpdb::$field_types.
  2091. * @param string $type Optional. Type of operation. Possible values include 'INSERT' or 'REPLACE'.
  2092. * Default 'INSERT'.
  2093. * @return int|false The number of rows affected, or false on error.
  2094. */
  2095. public function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
  2096. $this->insert_id = 0;
  2097. if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ), true ) ) {
  2098. return false;
  2099. }
  2100. $data = $this->process_fields( $table, $data, $format );
  2101. if ( false === $data ) {
  2102. return false;
  2103. }
  2104. $formats = array();
  2105. $values = array();
  2106. foreach ( $data as $value ) {
  2107. if ( is_null( $value['value'] ) ) {
  2108. $formats[] = 'NULL';
  2109. continue;
  2110. }
  2111. $formats[] = $value['format'];
  2112. $values[] = $value['value'];
  2113. }
  2114. $fields = '`' . implode( '`, `', array_keys( $data ) ) . '`';
  2115. $formats = implode( ', ', $formats );
  2116. $sql = "$type INTO `$table` ($fields) VALUES ($formats)";
  2117. $this->check_current_query = false;
  2118. return $this->query( $this->prepare( $sql, $values ) );
  2119. }
  2120. /**
  2121. * Updates a row in the table.
  2122. *
  2123. * Examples:
  2124. *
  2125. * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
  2126. * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
  2127. *
  2128. * @since 2.5.0
  2129. *
  2130. * @see wpdb::prepare()
  2131. * @see wpdb::$field_types
  2132. * @see wp_set_wpdb_vars()
  2133. *
  2134. * @param string $table Table name.
  2135. * @param array $data Data to update (in column => value pairs).
  2136. * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  2137. * Sending a null value will cause the column to be set to NULL - the corresponding
  2138. * format is ignored in this case.
  2139. * @param array $where A named array of WHERE clauses (in column => value pairs).
  2140. * Multiple clauses will be joined with ANDs.
  2141. * Both $where columns and $where values should be "raw".
  2142. * Sending a null value will create an IS NULL comparison - the corresponding
  2143. * format will be ignored in this case.
  2144. * @param array|string $format Optional. An array of formats to be mapped to each of the values in $data.
  2145. * If string, that format will be used for all of the values in $data.
  2146. * A format is one of '%d', '%f', '%s' (integer, float, string).
  2147. * If omitted, all values in $data will be treated as strings unless otherwise
  2148. * specified in wpdb::$field_types.
  2149. * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where.
  2150. * If string, that format will be used for all of the items in $where.
  2151. * A format is one of '%d', '%f', '%s' (integer, float, string).
  2152. * If omitted, all values in $where will be treated as strings.
  2153. * @return int|false The number of rows updated, or false on error.
  2154. */
  2155. public function update( $table, $data, $where, $format = null, $where_format = null ) {
  2156. if ( ! is_array( $data ) || ! is_array( $where ) ) {
  2157. return false;
  2158. }
  2159. $data = $this->process_fields( $table, $data, $format );
  2160. if ( false === $data ) {
  2161. return false;
  2162. }
  2163. $where = $this->process_fields( $table, $where, $where_format );
  2164. if ( false === $where ) {
  2165. return false;
  2166. }
  2167. $fields = array();
  2168. $conditions = array();
  2169. $values = array();
  2170. foreach ( $data as $field => $value ) {
  2171. if ( is_null( $value['value'] ) ) {
  2172. $fields[] = "`$field` = NULL";
  2173. continue;
  2174. }
  2175. $fields[] = "`$field` = " . $value['format'];
  2176. $values[] = $value['value'];
  2177. }
  2178. foreach ( $where as $field => $value ) {
  2179. if ( is_null( $value['value'] ) ) {
  2180. $conditions[] = "`$field` IS NULL";
  2181. continue;
  2182. }
  2183. $conditions[] = "`$field` = " . $value['format'];
  2184. $values[] = $value['value'];
  2185. }
  2186. $fields = implode( ', ', $fields );
  2187. $conditions = implode( ' AND ', $conditions );
  2188. $sql = "UPDATE `$table` SET $fields WHERE $conditions";
  2189. $this->check_current_query = false;
  2190. return $this->query( $this->prepare( $sql, $values ) );
  2191. }
  2192. /**
  2193. * Deletes a row in the table.
  2194. *
  2195. * Examples:
  2196. *
  2197. * wpdb::delete( 'table', array( 'ID' => 1 ) )
  2198. * wpdb::delete( 'table', array( 'ID' => 1 ), array( '%d' ) )
  2199. *
  2200. * @since 3.4.0
  2201. *
  2202. * @see wpdb::prepare()
  2203. * @see wpdb::$field_types
  2204. * @see wp_set_wpdb_vars()
  2205. *
  2206. * @param string $table Table name.
  2207. * @param array $where A named array of WHERE clauses (in column => value pairs).
  2208. * Multiple clauses will be joined with ANDs.
  2209. * Both $where columns and $where values should be "raw".
  2210. * Sending a null value will create an IS NULL comparison - the corresponding
  2211. * format will be ignored in this case.
  2212. * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where.
  2213. * If string, that format will be used for all of the items in $where.
  2214. * A format is one of '%d', '%f', '%s' (integer, float, string).
  2215. * If omitted, all values in $data will be treated as strings unless otherwise
  2216. * specified in wpdb::$field_types.
  2217. * @return int|false The number of rows updated, or false on error.
  2218. */
  2219. public function delete( $table, $where, $where_format = null ) {
  2220. if ( ! is_array( $where ) ) {
  2221. return false;
  2222. }
  2223. $where = $this->process_fields( $table, $where, $where_format );
  2224. if ( false === $where ) {
  2225. return false;
  2226. }
  2227. $conditions = array();
  2228. $values = array();
  2229. foreach ( $where as $field => $value ) {
  2230. if ( is_null( $value['value'] ) ) {
  2231. $conditions[] = "`$field` IS NULL";
  2232. continue;
  2233. }
  2234. $conditions[] = "`$field` = " . $value['format'];
  2235. $values[] = $value['value'];
  2236. }
  2237. $conditions = implode( ' AND ', $conditions );
  2238. $sql = "DELETE FROM `$table` WHERE $conditions";
  2239. $this->check_current_query = false;
  2240. return $this->query( $this->prepare( $sql, $values ) );
  2241. }
  2242. /**
  2243. * Processes arrays of field/value pairs and field formats.
  2244. *
  2245. * This is a helper method for wpdb's CRUD methods, which take field/value pairs
  2246. * for inserts, updates, and where clauses. This method first pairs each value
  2247. * with a format. Then it determines the charset of that field, using that
  2248. * to determine if any invalid text would be stripped. If text is stripped,
  2249. * then field processing is rejected and the query fails.
  2250. *
  2251. * @since 4.2.0
  2252. *
  2253. * @param string $table Table name.
  2254. * @param array $data Field/value pair.
  2255. * @param mixed $format Format for each field.
  2256. * @return array|false An array of fields that contain paired value and formats.
  2257. * False for invalid values.
  2258. */
  2259. protected function process_fields( $table, $data, $format ) {
  2260. $data = $this->process_field_formats( $data, $format );
  2261. if ( false === $data ) {
  2262. return false;
  2263. }
  2264. $data = $this->process_field_charsets( $data, $table );
  2265. if ( false === $data ) {
  2266. return false;
  2267. }
  2268. $data = $this->process_field_lengths( $data, $table );
  2269. if ( false === $data ) {
  2270. return false;
  2271. }
  2272. $converted_data = $this->strip_invalid_text( $data );
  2273. if ( $data !== $converted_data ) {
  2274. $problem_fields = array();
  2275. foreach ( $data as $field => $value ) {
  2276. if ( $value !== $converted_data[ $field ] ) {
  2277. $problem_fields[] = $field;
  2278. }
  2279. }
  2280. wp_load_translations_early();
  2281. if ( 1 === count( $problem_fields ) ) {
  2282. $this->last_error = sprintf(
  2283. /* translators: %s: Database field where the error occurred. */
  2284. __( 'WordPress database error: Processing the value for the following field failed: %s. The supplied value may be too long or contains invalid data.' ),
  2285. reset( $problem_fields )
  2286. );
  2287. } else {
  2288. $this->last_error = sprintf(
  2289. /* translators: %s: Database fields where the error occurred. */
  2290. __( 'WordPress database error: Processing the values for the following fields failed: %s. The supplied values may be too long or contain invalid data.' ),
  2291. implode( ', ', $problem_fields )
  2292. );
  2293. }
  2294. return false;
  2295. }
  2296. return $data;
  2297. }
  2298. /**
  2299. * Prepares arrays of value/format pairs as passed to wpdb CRUD methods.
  2300. *
  2301. * @since 4.2.0
  2302. *
  2303. * @param array $data Array of fields to values.
  2304. * @param mixed $format Formats to be mapped to the values in $data.
  2305. * @return array Array, keyed by field names with values being an array
  2306. * of 'value' and 'format' keys.
  2307. */
  2308. protected function process_field_formats( $data, $format ) {
  2309. $formats = (array) $format;
  2310. $original_formats = $formats;
  2311. foreach ( $data as $field => $value ) {
  2312. $value = array(
  2313. 'value' => $value,
  2314. 'format' => '%s',
  2315. );
  2316. if ( ! empty( $format ) ) {
  2317. $value['format'] = array_shift( $formats );
  2318. if ( ! $value['format'] ) {
  2319. $value['format'] = reset( $original_formats );
  2320. }
  2321. } elseif ( isset( $this->field_types[ $field ] ) ) {
  2322. $value['format'] = $this->field_types[ $field ];
  2323. }
  2324. $data[ $field ] = $value;
  2325. }
  2326. return $data;
  2327. }
  2328. /**
  2329. * Adds field charsets to field/value/format arrays generated by wpdb::process_field_formats().
  2330. *
  2331. * @since 4.2.0
  2332. *
  2333. * @param array $data As it comes from the wpdb::process_field_formats() method.
  2334. * @param string $table Table name.
  2335. * @return array|false The same array as $data with additional 'charset' keys.
  2336. * False on failure.
  2337. */
  2338. protected function process_field_charsets( $data, $table ) {
  2339. foreach ( $data as $field => $value ) {
  2340. if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
  2341. /*
  2342. * We can skip this field if we know it isn't a string.
  2343. * This checks %d/%f versus ! %s because its sprintf() could take more.
  2344. */
  2345. $value['charset'] = false;
  2346. } else {
  2347. $value['charset'] = $this->get_col_charset( $table, $field );
  2348. if ( is_wp_error( $value['charset'] ) ) {
  2349. return false;
  2350. }
  2351. }
  2352. $data[ $field ] = $value;
  2353. }
  2354. return $data;
  2355. }
  2356. /**
  2357. * For string fields, records the maximum string length that field can safely save.
  2358. *
  2359. * @since 4.2.1
  2360. *
  2361. * @param array $data As it comes from the wpdb::process_field_charsets() method.
  2362. * @param string $table Table name.
  2363. * @return array|false The same array as $data with additional 'length' keys, or false if
  2364. * any of the values were too long for their corresponding field.
  2365. */
  2366. protected function process_field_lengths( $data, $table ) {
  2367. foreach ( $data as $field => $value ) {
  2368. if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
  2369. /*
  2370. * We can skip this field if we know it isn't a string.
  2371. * This checks %d/%f versus ! %s because its sprintf() could take more.
  2372. */
  2373. $value['length'] = false;
  2374. } else {
  2375. $value['length'] = $this->get_col_length( $table, $field );
  2376. if ( is_wp_error( $value['length'] ) ) {
  2377. return false;
  2378. }
  2379. }
  2380. $data[ $field ] = $value;
  2381. }
  2382. return $data;
  2383. }
  2384. /**
  2385. * Retrieves one variable from the database.
  2386. *
  2387. * Executes a SQL query and returns the value from the SQL result.
  2388. * If the SQL result contains more than one column and/or more than one row,
  2389. * the value in the column and row specified is returned. If $query is null,
  2390. * the value in the specified column and row from the previous SQL result is returned.
  2391. *
  2392. * @since 0.71
  2393. *
  2394. * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
  2395. * @param int $x Optional. Column of value to return. Indexed from 0.
  2396. * @param int $y Optional. Row of value to return. Indexed from 0.
  2397. * @return string|null Database query result (as string), or null on failure.
  2398. */
  2399. public function get_var( $query = null, $x = 0, $y = 0 ) {
  2400. $this->func_call = "\$db->get_var(\"$query\", $x, $y)";
  2401. if ( $query ) {
  2402. if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
  2403. $this->check_current_query = false;
  2404. }
  2405. $this->query( $query );
  2406. }
  2407. // Extract var out of cached results based on x,y vals.
  2408. if ( ! empty( $this->last_result[ $y ] ) ) {
  2409. $values = array_values( get_object_vars( $this->last_result[ $y ] ) );
  2410. }
  2411. // If there is a value return it, else return null.
  2412. return ( isset( $values[ $x ] ) && '' !== $values[ $x ] ) ? $values[ $x ] : null;
  2413. }
  2414. /**
  2415. * Retrieves one row from the database.
  2416. *
  2417. * Executes a SQL query and returns the row from the SQL result.
  2418. *
  2419. * @since 0.71
  2420. *
  2421. * @param string|null $query SQL query.
  2422. * @param string $output Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which
  2423. * correspond to an stdClass object, an associative array, or a numeric array,
  2424. * respectively. Default OBJECT.
  2425. * @param int $y Optional. Row to return. Indexed from 0.
  2426. * @return array|object|null|void Database query result in format specified by $output or null on failure.
  2427. */
  2428. public function get_row( $query = null, $output = OBJECT, $y = 0 ) {
  2429. $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
  2430. if ( $query ) {
  2431. if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
  2432. $this->check_current_query = false;
  2433. }
  2434. $this->query( $query );
  2435. } else {
  2436. return null;
  2437. }
  2438. if ( ! isset( $this->last_result[ $y ] ) ) {
  2439. return null;
  2440. }
  2441. if ( OBJECT === $output ) {
  2442. return $this->last_result[ $y ] ? $this->last_result[ $y ] : null;
  2443. } elseif ( ARRAY_A === $output ) {
  2444. return $this->last_result[ $y ] ? get_object_vars( $this->last_result[ $y ] ) : null;
  2445. } elseif ( ARRAY_N === $output ) {
  2446. return $this->last_result[ $y ] ? array_values( get_object_vars( $this->last_result[ $y ] ) ) : null;
  2447. } elseif ( OBJECT === strtoupper( $output ) ) {
  2448. // Back compat for OBJECT being previously case-insensitive.
  2449. return $this->last_result[ $y ] ? $this->last_result[ $y ] : null;
  2450. } else {
  2451. $this->print_error( ' $db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N' );
  2452. }
  2453. }
  2454. /**
  2455. * Retrieves one column from the database.
  2456. *
  2457. * Executes a SQL query and returns the column from the SQL result.
  2458. * If the SQL result contains more than one column, the column specified is returned.
  2459. * If $query is null, the specified column from the previous SQL result is returned.
  2460. *
  2461. * @since 0.71
  2462. *
  2463. * @param string|null $query Optional. SQL query. Defaults to previous query.
  2464. * @param int $x Optional. Column to return. Indexed from 0.
  2465. * @return array Database query result. Array indexed from 0 by SQL result row number.
  2466. */
  2467. public function get_col( $query = null, $x = 0 ) {
  2468. if ( $query ) {
  2469. if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
  2470. $this->check_current_query = false;
  2471. }
  2472. $this->query( $query );
  2473. }
  2474. $new_array = array();
  2475. // Extract the column values.
  2476. if ( $this->last_result ) {
  2477. for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
  2478. $new_array[ $i ] = $this->get_var( null, $x, $i );
  2479. }
  2480. }
  2481. return $new_array;
  2482. }
  2483. /**
  2484. * Retrieves an entire SQL result set from the database (i.e., many rows).
  2485. *
  2486. * Executes a SQL query and returns the entire SQL result.
  2487. *
  2488. * @since 0.71
  2489. *
  2490. * @param string $query SQL query.
  2491. * @param string $output Optional. Any of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants.
  2492. * With one of the first three, return an array of rows indexed
  2493. * from 0 by SQL result row number. Each row is an associative array
  2494. * (column => value, ...), a numerically indexed array (0 => value, ...),
  2495. * or an object ( ->column = value ), respectively. With OBJECT_K,
  2496. * return an associative array of row objects keyed by the value
  2497. * of each row's first column's value. Duplicate keys are discarded.
  2498. * @return array|object|null Database query results.
  2499. */
  2500. public function get_results( $query = null, $output = OBJECT ) {
  2501. $this->func_call = "\$db->get_results(\"$query\", $output)";
  2502. if ( $query ) {
  2503. if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
  2504. $this->check_current_query = false;
  2505. }
  2506. $this->query( $query );
  2507. } else {
  2508. return null;
  2509. }
  2510. $new_array = array();
  2511. if ( OBJECT === $output ) {
  2512. // Return an integer-keyed array of row objects.
  2513. return $this->last_result;
  2514. } elseif ( OBJECT_K === $output ) {
  2515. // Return an array of row objects with keys from column 1.
  2516. // (Duplicates are discarded.)
  2517. if ( $this->last_result ) {
  2518. foreach ( $this->last_result as $row ) {
  2519. $var_by_ref = get_object_vars( $row );
  2520. $key = array_shift( $var_by_ref );
  2521. if ( ! isset( $new_array[ $key ] ) ) {
  2522. $new_array[ $key ] = $row;
  2523. }
  2524. }
  2525. }
  2526. return $new_array;
  2527. } elseif ( ARRAY_A === $output || ARRAY_N === $output ) {
  2528. // Return an integer-keyed array of...
  2529. if ( $this->last_result ) {
  2530. foreach ( (array) $this->last_result as $row ) {
  2531. if ( ARRAY_N === $output ) {
  2532. // ...integer-keyed row arrays.
  2533. $new_array[] = array_values( get_object_vars( $row ) );
  2534. } else {
  2535. // ...column name-keyed row arrays.
  2536. $new_array[] = get_object_vars( $row );
  2537. }
  2538. }
  2539. }
  2540. return $new_array;
  2541. } elseif ( strtoupper( $output ) === OBJECT ) {
  2542. // Back compat for OBJECT being previously case-insensitive.
  2543. return $this->last_result;
  2544. }
  2545. return null;
  2546. }
  2547. /**
  2548. * Retrieves the character set for the given table.
  2549. *
  2550. * @since 4.2.0
  2551. *
  2552. * @param string $table Table name.
  2553. * @return string|WP_Error Table character set, WP_Error object if it couldn't be found.
  2554. */
  2555. protected function get_table_charset( $table ) {
  2556. $tablekey = strtolower( $table );
  2557. /**
  2558. * Filters the table charset value before the DB is checked.
  2559. *
  2560. * Returning a non-null value from the filter will effectively short-circuit
  2561. * checking the DB for the charset, returning that value instead.
  2562. *
  2563. * @since 4.2.0
  2564. *
  2565. * @param string|WP_Error|null $charset The character set to use, WP_Error object
  2566. * if it couldn't be found. Default null.
  2567. * @param string $table The name of the table being checked.
  2568. */
  2569. $charset = apply_filters( 'pre_get_table_charset', null, $table );
  2570. if ( null !== $charset ) {
  2571. return $charset;
  2572. }
  2573. if ( isset( $this->table_charset[ $tablekey ] ) ) {
  2574. return $this->table_charset[ $tablekey ];
  2575. }
  2576. $charsets = array();
  2577. $columns = array();
  2578. $table_parts = explode( '.', $table );
  2579. $table = '`' . implode( '`.`', $table_parts ) . '`';
  2580. $results = $this->get_results( "SHOW FULL COLUMNS FROM $table" );
  2581. if ( ! $results ) {
  2582. return new WP_Error( 'wpdb_get_table_charset_failure', __( 'Could not retrieve table charset.' ) );
  2583. }
  2584. foreach ( $results as $column ) {
  2585. $columns[ strtolower( $column->Field ) ] = $column;
  2586. }
  2587. $this->col_meta[ $tablekey ] = $columns;
  2588. foreach ( $columns as $column ) {
  2589. if ( ! empty( $column->Collation ) ) {
  2590. list( $charset ) = explode( '_', $column->Collation );
  2591. // If the current connection can't support utf8mb4 characters, let's only send 3-byte utf8 characters.
  2592. if ( 'utf8mb4' === $charset && ! $this->has_cap( 'utf8mb4' ) ) {
  2593. $charset = 'utf8';
  2594. }
  2595. $charsets[ strtolower( $charset ) ] = true;
  2596. }
  2597. list( $type ) = explode( '(', $column->Type );
  2598. // A binary/blob means the whole query gets treated like this.
  2599. if ( in_array( strtoupper( $type ), array( 'BINARY', 'VARBINARY', 'TINYBLOB', 'MEDIUMBLOB', 'BLOB', 'LONGBLOB' ), true ) ) {
  2600. $this->table_charset[ $tablekey ] = 'binary';
  2601. return 'binary';
  2602. }
  2603. }
  2604. // utf8mb3 is an alias for utf8.
  2605. if ( isset( $charsets['utf8mb3'] ) ) {
  2606. $charsets['utf8'] = true;
  2607. unset( $charsets['utf8mb3'] );
  2608. }
  2609. // Check if we have more than one charset in play.
  2610. $count = count( $charsets );
  2611. if ( 1 === $count ) {
  2612. $charset = key( $charsets );
  2613. } elseif ( 0 === $count ) {
  2614. // No charsets, assume this table can store whatever.
  2615. $charset = false;
  2616. } else {
  2617. // More than one charset. Remove latin1 if present and recalculate.
  2618. unset( $charsets['latin1'] );
  2619. $count = count( $charsets );
  2620. if ( 1 === $count ) {
  2621. // Only one charset (besides latin1).
  2622. $charset = key( $charsets );
  2623. } elseif ( 2 === $count && isset( $charsets['utf8'], $charsets['utf8mb4'] ) ) {
  2624. // Two charsets, but they're utf8 and utf8mb4, use utf8.
  2625. $charset = 'utf8';
  2626. } else {
  2627. // Two mixed character sets. ascii.
  2628. $charset = 'ascii';
  2629. }
  2630. }
  2631. $this->table_charset[ $tablekey ] = $charset;
  2632. return $charset;
  2633. }
  2634. /**
  2635. * Retrieves the character set for the given column.
  2636. *
  2637. * @since 4.2.0
  2638. *
  2639. * @param string $table Table name.
  2640. * @param string $column Column name.
  2641. * @return string|false|WP_Error Column character set as a string. False if the column has
  2642. * no character set. WP_Error object if there was an error.
  2643. */
  2644. public function get_col_charset( $table, $column ) {
  2645. $tablekey = strtolower( $table );
  2646. $columnkey = strtolower( $column );
  2647. /**
  2648. * Filters the column charset value before the DB is checked.
  2649. *
  2650. * Passing a non-null value to the filter will short-circuit
  2651. * checking the DB for the charset, returning that value instead.
  2652. *
  2653. * @since 4.2.0
  2654. *
  2655. * @param string|null $charset The character set to use. Default null.
  2656. * @param string $table The name of the table being checked.
  2657. * @param string $column The name of the column being checked.
  2658. */
  2659. $charset = apply_filters( 'pre_get_col_charset', null, $table, $column );
  2660. if ( null !== $charset ) {
  2661. return $charset;
  2662. }
  2663. // Skip this entirely if this isn't a MySQL database.
  2664. if ( empty( $this->is_mysql ) ) {
  2665. return false;
  2666. }
  2667. if ( empty( $this->table_charset[ $tablekey ] ) ) {
  2668. // This primes column information for us.
  2669. $table_charset = $this->get_table_charset( $table );
  2670. if ( is_wp_error( $table_charset ) ) {
  2671. return $table_charset;
  2672. }
  2673. }
  2674. // If still no column information, return the table charset.
  2675. if ( empty( $this->col_meta[ $tablekey ] ) ) {
  2676. return $this->table_charset[ $tablekey ];
  2677. }
  2678. // If this column doesn't exist, return the table charset.
  2679. if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
  2680. return $this->table_charset[ $tablekey ];
  2681. }
  2682. // Return false when it's not a string column.
  2683. if ( empty( $this->col_meta[ $tablekey ][ $columnkey ]->Collation ) ) {
  2684. return false;
  2685. }
  2686. list( $charset ) = explode( '_', $this->col_meta[ $tablekey ][ $columnkey ]->Collation );
  2687. return $charset;
  2688. }
  2689. /**
  2690. * Retrieves the maximum string length allowed in a given column.
  2691. *
  2692. * The length may either be specified as a byte length or a character length.
  2693. *
  2694. * @since 4.2.1
  2695. *
  2696. * @param string $table Table name.
  2697. * @param string $column Column name.
  2698. * @return array|false|WP_Error array( 'length' => (int), 'type' => 'byte' | 'char' ).
  2699. * False if the column has no length (for example, numeric column).
  2700. * WP_Error object if there was an error.
  2701. */
  2702. public function get_col_length( $table, $column ) {
  2703. $tablekey = strtolower( $table );
  2704. $columnkey = strtolower( $column );
  2705. // Skip this entirely if this isn't a MySQL database.
  2706. if ( empty( $this->is_mysql ) ) {
  2707. return false;
  2708. }
  2709. if ( empty( $this->col_meta[ $tablekey ] ) ) {
  2710. // This primes column information for us.
  2711. $table_charset = $this->get_table_charset( $table );
  2712. if ( is_wp_error( $table_charset ) ) {
  2713. return $table_charset;
  2714. }
  2715. }
  2716. if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
  2717. return false;
  2718. }
  2719. $typeinfo = explode( '(', $this->col_meta[ $tablekey ][ $columnkey ]->Type );
  2720. $type = strtolower( $typeinfo[0] );
  2721. if ( ! empty( $typeinfo[1] ) ) {
  2722. $length = trim( $typeinfo[1], ')' );
  2723. } else {
  2724. $length = false;
  2725. }
  2726. switch ( $type ) {
  2727. case 'char':
  2728. case 'varchar':
  2729. return array(
  2730. 'type' => 'char',
  2731. 'length' => (int) $length,
  2732. );
  2733. case 'binary':
  2734. case 'varbinary':
  2735. return array(
  2736. 'type' => 'byte',
  2737. 'length' => (int) $length,
  2738. );
  2739. case 'tinyblob':
  2740. case 'tinytext':
  2741. return array(
  2742. 'type' => 'byte',
  2743. 'length' => 255, // 2^8 - 1
  2744. );
  2745. case 'blob':
  2746. case 'text':
  2747. return array(
  2748. 'type' => 'byte',
  2749. 'length' => 65535, // 2^16 - 1
  2750. );
  2751. case 'mediumblob':
  2752. case 'mediumtext':
  2753. return array(
  2754. 'type' => 'byte',
  2755. 'length' => 16777215, // 2^24 - 1
  2756. );
  2757. case 'longblob':
  2758. case 'longtext':
  2759. return array(
  2760. 'type' => 'byte',
  2761. 'length' => 4294967295, // 2^32 - 1
  2762. );
  2763. default:
  2764. return false;
  2765. }
  2766. }
  2767. /**
  2768. * Checks if a string is ASCII.
  2769. *
  2770. * The negative regex is faster for non-ASCII strings, as it allows
  2771. * the search to finish as soon as it encounters a non-ASCII character.
  2772. *
  2773. * @since 4.2.0
  2774. *
  2775. * @param string $string String to check.
  2776. * @return bool True if ASCII, false if not.
  2777. */
  2778. protected function check_ascii( $string ) {
  2779. if ( function_exists( 'mb_check_encoding' ) ) {
  2780. if ( mb_check_encoding( $string, 'ASCII' ) ) {
  2781. return true;
  2782. }
  2783. } elseif ( ! preg_match( '/[^\x00-\x7F]/', $string ) ) {
  2784. return true;
  2785. }
  2786. return false;
  2787. }
  2788. /**
  2789. * Checks if the query is accessing a collation considered safe on the current version of MySQL.
  2790. *
  2791. * @since 4.2.0
  2792. *
  2793. * @param string $query The query to check.
  2794. * @return bool True if the collation is safe, false if it isn't.
  2795. */
  2796. protected function check_safe_collation( $query ) {
  2797. if ( $this->checking_collation ) {
  2798. return true;
  2799. }
  2800. // We don't need to check the collation for queries that don't read data.
  2801. $query = ltrim( $query, "\r\n\t (" );
  2802. if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN|CREATE)\s/i', $query ) ) {
  2803. return true;
  2804. }
  2805. // All-ASCII queries don't need extra checking.
  2806. if ( $this->check_ascii( $query ) ) {
  2807. return true;
  2808. }
  2809. $table = $this->get_table_from_query( $query );
  2810. if ( ! $table ) {
  2811. return false;
  2812. }
  2813. $this->checking_collation = true;
  2814. $collation = $this->get_table_charset( $table );
  2815. $this->checking_collation = false;
  2816. // Tables with no collation, or latin1 only, don't need extra checking.
  2817. if ( false === $collation || 'latin1' === $collation ) {
  2818. return true;
  2819. }
  2820. $table = strtolower( $table );
  2821. if ( empty( $this->col_meta[ $table ] ) ) {
  2822. return false;
  2823. }
  2824. // If any of the columns don't have one of these collations, it needs more sanity checking.
  2825. foreach ( $this->col_meta[ $table ] as $col ) {
  2826. if ( empty( $col->Collation ) ) {
  2827. continue;
  2828. }
  2829. if ( ! in_array( $col->Collation, array( 'utf8_general_ci', 'utf8_bin', 'utf8mb4_general_ci', 'utf8mb4_bin' ), true ) ) {
  2830. return false;
  2831. }
  2832. }
  2833. return true;
  2834. }
  2835. /**
  2836. * Strips any invalid characters based on value/charset pairs.
  2837. *
  2838. * @since 4.2.0
  2839. *
  2840. * @param array $data Array of value arrays. Each value array has the keys 'value' and 'charset'.
  2841. * An optional 'ascii' key can be set to false to avoid redundant ASCII checks.
  2842. * @return array|WP_Error The $data parameter, with invalid characters removed from each value.
  2843. * This works as a passthrough: any additional keys such as 'field' are
  2844. * retained in each value array. If we cannot remove invalid characters,
  2845. * a WP_Error object is returned.
  2846. */
  2847. protected function strip_invalid_text( $data ) {
  2848. $db_check_string = false;
  2849. foreach ( $data as &$value ) {
  2850. $charset = $value['charset'];
  2851. if ( is_array( $value['length'] ) ) {
  2852. $length = $value['length']['length'];
  2853. $truncate_by_byte_length = 'byte' === $value['length']['type'];
  2854. } else {
  2855. $length = false;
  2856. // Since we have no length, we'll never truncate. Initialize the variable to false.
  2857. // True would take us through an unnecessary (for this case) codepath below.
  2858. $truncate_by_byte_length = false;
  2859. }
  2860. // There's no charset to work with.
  2861. if ( false === $charset ) {
  2862. continue;
  2863. }
  2864. // Column isn't a string.
  2865. if ( ! is_string( $value['value'] ) ) {
  2866. continue;
  2867. }
  2868. $needs_validation = true;
  2869. if (
  2870. // latin1 can store any byte sequence.
  2871. 'latin1' === $charset
  2872. ||
  2873. // ASCII is always OK.
  2874. ( ! isset( $value['ascii'] ) && $this->check_ascii( $value['value'] ) )
  2875. ) {
  2876. $truncate_by_byte_length = true;
  2877. $needs_validation = false;
  2878. }
  2879. if ( $truncate_by_byte_length ) {
  2880. mbstring_binary_safe_encoding();
  2881. if ( false !== $length && strlen( $value['value'] ) > $length ) {
  2882. $value['value'] = substr( $value['value'], 0, $length );
  2883. }
  2884. reset_mbstring_encoding();
  2885. if ( ! $needs_validation ) {
  2886. continue;
  2887. }
  2888. }
  2889. // utf8 can be handled by regex, which is a bunch faster than a DB lookup.
  2890. if ( ( 'utf8' === $charset || 'utf8mb3' === $charset || 'utf8mb4' === $charset ) && function_exists( 'mb_strlen' ) ) {
  2891. $regex = '/
  2892. (
  2893. (?: [\x00-\x7F] # single-byte sequences 0xxxxxxx
  2894. | [\xC2-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
  2895. | \xE0[\xA0-\xBF][\x80-\xBF] # triple-byte sequences 1110xxxx 10xxxxxx * 2
  2896. | [\xE1-\xEC][\x80-\xBF]{2}
  2897. | \xED[\x80-\x9F][\x80-\xBF]
  2898. | [\xEE-\xEF][\x80-\xBF]{2}';
  2899. if ( 'utf8mb4' === $charset ) {
  2900. $regex .= '
  2901. | \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences 11110xxx 10xxxxxx * 3
  2902. | [\xF1-\xF3][\x80-\xBF]{3}
  2903. | \xF4[\x80-\x8F][\x80-\xBF]{2}
  2904. ';
  2905. }
  2906. $regex .= '){1,40} # ...one or more times
  2907. )
  2908. | . # anything else
  2909. /x';
  2910. $value['value'] = preg_replace( $regex, '$1', $value['value'] );
  2911. if ( false !== $length && mb_strlen( $value['value'], 'UTF-8' ) > $length ) {
  2912. $value['value'] = mb_substr( $value['value'], 0, $length, 'UTF-8' );
  2913. }
  2914. continue;
  2915. }
  2916. // We couldn't use any local conversions, send it to the DB.
  2917. $value['db'] = true;
  2918. $db_check_string = true;
  2919. }
  2920. unset( $value ); // Remove by reference.
  2921. if ( $db_check_string ) {
  2922. $queries = array();
  2923. foreach ( $data as $col => $value ) {
  2924. if ( ! empty( $value['db'] ) ) {
  2925. // We're going to need to truncate by characters or bytes, depending on the length value we have.
  2926. if ( isset( $value['length']['type'] ) && 'byte' === $value['length']['type'] ) {
  2927. // Using binary causes LEFT() to truncate by bytes.
  2928. $charset = 'binary';
  2929. } else {
  2930. $charset = $value['charset'];
  2931. }
  2932. if ( $this->charset ) {
  2933. $connection_charset = $this->charset;
  2934. } else {
  2935. if ( $this->use_mysqli ) {
  2936. $connection_charset = mysqli_character_set_name( $this->dbh );
  2937. } else {
  2938. $connection_charset = mysql_client_encoding();
  2939. }
  2940. }
  2941. if ( is_array( $value['length'] ) ) {
  2942. $length = sprintf( '%.0f', $value['length']['length'] );
  2943. $queries[ $col ] = $this->prepare( "CONVERT( LEFT( CONVERT( %s USING $charset ), $length ) USING $connection_charset )", $value['value'] );
  2944. } elseif ( 'binary' !== $charset ) {
  2945. // If we don't have a length, there's no need to convert binary - it will always return the same result.
  2946. $queries[ $col ] = $this->prepare( "CONVERT( CONVERT( %s USING $charset ) USING $connection_charset )", $value['value'] );
  2947. }
  2948. unset( $data[ $col ]['db'] );
  2949. }
  2950. }
  2951. $sql = array();
  2952. foreach ( $queries as $column => $query ) {
  2953. if ( ! $query ) {
  2954. continue;
  2955. }
  2956. $sql[] = $query . " AS x_$column";
  2957. }
  2958. $this->check_current_query = false;
  2959. $row = $this->get_row( 'SELECT ' . implode( ', ', $sql ), ARRAY_A );
  2960. if ( ! $row ) {
  2961. return new WP_Error( 'wpdb_strip_invalid_text_failure', __( 'Could not strip invalid text.' ) );
  2962. }
  2963. foreach ( array_keys( $data ) as $column ) {
  2964. if ( isset( $row[ "x_$column" ] ) ) {
  2965. $data[ $column ]['value'] = $row[ "x_$column" ];
  2966. }
  2967. }
  2968. }
  2969. return $data;
  2970. }
  2971. /**
  2972. * Strips any invalid characters from the query.
  2973. *
  2974. * @since 4.2.0
  2975. *
  2976. * @param string $query Query to convert.
  2977. * @return string|WP_Error The converted query, or a WP_Error object if the conversion fails.
  2978. */
  2979. protected function strip_invalid_text_from_query( $query ) {
  2980. // We don't need to check the collation for queries that don't read data.
  2981. $trimmed_query = ltrim( $query, "\r\n\t (" );
  2982. if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN|CREATE)\s/i', $trimmed_query ) ) {
  2983. return $query;
  2984. }
  2985. $table = $this->get_table_from_query( $query );
  2986. if ( $table ) {
  2987. $charset = $this->get_table_charset( $table );
  2988. if ( is_wp_error( $charset ) ) {
  2989. return $charset;
  2990. }
  2991. // We can't reliably strip text from tables containing binary/blob columns.
  2992. if ( 'binary' === $charset ) {
  2993. return $query;
  2994. }
  2995. } else {
  2996. $charset = $this->charset;
  2997. }
  2998. $data = array(
  2999. 'value' => $query,
  3000. 'charset' => $charset,
  3001. 'ascii' => false,
  3002. 'length' => false,
  3003. );
  3004. $data = $this->strip_invalid_text( array( $data ) );
  3005. if ( is_wp_error( $data ) ) {
  3006. return $data;
  3007. }
  3008. return $data[0]['value'];
  3009. }
  3010. /**
  3011. * Strips any invalid characters from the string for a given table and column.
  3012. *
  3013. * @since 4.2.0
  3014. *
  3015. * @param string $table Table name.
  3016. * @param string $column Column name.
  3017. * @param string $value The text to check.
  3018. * @return string|WP_Error The converted string, or a WP_Error object if the conversion fails.
  3019. */
  3020. public function strip_invalid_text_for_column( $table, $column, $value ) {
  3021. if ( ! is_string( $value ) ) {
  3022. return $value;
  3023. }
  3024. $charset = $this->get_col_charset( $table, $column );
  3025. if ( ! $charset ) {
  3026. // Not a string column.
  3027. return $value;
  3028. } elseif ( is_wp_error( $charset ) ) {
  3029. // Bail on real errors.
  3030. return $charset;
  3031. }
  3032. $data = array(
  3033. $column => array(
  3034. 'value' => $value,
  3035. 'charset' => $charset,
  3036. 'length' => $this->get_col_length( $table, $column ),
  3037. ),
  3038. );
  3039. $data = $this->strip_invalid_text( $data );
  3040. if ( is_wp_error( $data ) ) {
  3041. return $data;
  3042. }
  3043. return $data[ $column ]['value'];
  3044. }
  3045. /**
  3046. * Finds the first table name referenced in a query.
  3047. *
  3048. * @since 4.2.0
  3049. *
  3050. * @param string $query The query to search.
  3051. * @return string|false The table name found, or false if a table couldn't be found.
  3052. */
  3053. protected function get_table_from_query( $query ) {
  3054. // Remove characters that can legally trail the table name.
  3055. $query = rtrim( $query, ';/-#' );
  3056. // Allow (select...) union [...] style queries. Use the first query's table name.
  3057. $query = ltrim( $query, "\r\n\t (" );
  3058. // Strip everything between parentheses except nested selects.
  3059. $query = preg_replace( '/\((?!\s*select)[^(]*?\)/is', '()', $query );
  3060. // Quickly match most common queries.
  3061. if ( preg_match(
  3062. '/^\s*(?:'
  3063. . 'SELECT.*?\s+FROM'
  3064. . '|INSERT(?:\s+LOW_PRIORITY|\s+DELAYED|\s+HIGH_PRIORITY)?(?:\s+IGNORE)?(?:\s+INTO)?'
  3065. . '|REPLACE(?:\s+LOW_PRIORITY|\s+DELAYED)?(?:\s+INTO)?'
  3066. . '|UPDATE(?:\s+LOW_PRIORITY)?(?:\s+IGNORE)?'
  3067. . '|DELETE(?:\s+LOW_PRIORITY|\s+QUICK|\s+IGNORE)*(?:.+?FROM)?'
  3068. . ')\s+((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)/is',
  3069. $query,
  3070. $maybe
  3071. ) ) {
  3072. return str_replace( '`', '', $maybe[1] );
  3073. }
  3074. // SHOW TABLE STATUS and SHOW TABLES WHERE Name = 'wp_posts'
  3075. 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 ) ) {
  3076. return $maybe[2];
  3077. }
  3078. /*
  3079. * SHOW TABLE STATUS LIKE and SHOW TABLES LIKE 'wp\_123\_%'
  3080. * This quoted LIKE operand seldom holds a full table name.
  3081. * It is usually a pattern for matching a prefix so we just
  3082. * strip the trailing % and unescape the _ to get 'wp_123_'
  3083. * which drop-ins can use for routing these SQL statements.
  3084. */
  3085. 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 ) ) {
  3086. return str_replace( '\\_', '_', $maybe[2] );
  3087. }
  3088. // Big pattern for the rest of the table-related queries.
  3089. if ( preg_match(
  3090. '/^\s*(?:'
  3091. . '(?:EXPLAIN\s+(?:EXTENDED\s+)?)?SELECT.*?\s+FROM'
  3092. . '|DESCRIBE|DESC|EXPLAIN|HANDLER'
  3093. . '|(?:LOCK|UNLOCK)\s+TABLE(?:S)?'
  3094. . '|(?:RENAME|OPTIMIZE|BACKUP|RESTORE|CHECK|CHECKSUM|ANALYZE|REPAIR).*\s+TABLE'
  3095. . '|TRUNCATE(?:\s+TABLE)?'
  3096. . '|CREATE(?:\s+TEMPORARY)?\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?'
  3097. . '|ALTER(?:\s+IGNORE)?\s+TABLE'
  3098. . '|DROP\s+TABLE(?:\s+IF\s+EXISTS)?'
  3099. . '|CREATE(?:\s+\w+)?\s+INDEX.*\s+ON'
  3100. . '|DROP\s+INDEX.*\s+ON'
  3101. . '|LOAD\s+DATA.*INFILE.*INTO\s+TABLE'
  3102. . '|(?:GRANT|REVOKE).*ON\s+TABLE'
  3103. . '|SHOW\s+(?:.*FROM|.*TABLE)'
  3104. . ')\s+\(*\s*((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)\s*\)*/is',
  3105. $query,
  3106. $maybe
  3107. ) ) {
  3108. return str_replace( '`', '', $maybe[1] );
  3109. }
  3110. return false;
  3111. }
  3112. /**
  3113. * Loads the column metadata from the last query.
  3114. *
  3115. * @since 3.5.0
  3116. */
  3117. protected function load_col_info() {
  3118. if ( $this->col_info ) {
  3119. return;
  3120. }
  3121. if ( $this->use_mysqli ) {
  3122. $num_fields = mysqli_num_fields( $this->result );
  3123. for ( $i = 0; $i < $num_fields; $i++ ) {
  3124. $this->col_info[ $i ] = mysqli_fetch_field( $this->result );
  3125. }
  3126. } else {
  3127. $num_fields = mysql_num_fields( $this->result );
  3128. for ( $i = 0; $i < $num_fields; $i++ ) {
  3129. $this->col_info[ $i ] = mysql_fetch_field( $this->result, $i );
  3130. }
  3131. }
  3132. }
  3133. /**
  3134. * Retrieves column metadata from the last query.
  3135. *
  3136. * @since 0.71
  3137. *
  3138. * @param string $info_type Optional. Possible values include 'name', 'table', 'def', 'max_length',
  3139. * 'not_null', 'primary_key', 'multiple_key', 'unique_key', 'numeric',
  3140. * 'blob', 'type', 'unsigned', 'zerofill'. Default 'name'.
  3141. * @param int $col_offset Optional. 0: col name. 1: which table the col's in. 2: col's max length.
  3142. * 3: if the col is numeric. 4: col's type. Default -1.
  3143. * @return mixed Column results.
  3144. */
  3145. public function get_col_info( $info_type = 'name', $col_offset = -1 ) {
  3146. $this->load_col_info();
  3147. if ( $this->col_info ) {
  3148. if ( -1 === $col_offset ) {
  3149. $i = 0;
  3150. $new_array = array();
  3151. foreach ( (array) $this->col_info as $col ) {
  3152. $new_array[ $i ] = $col->{$info_type};
  3153. $i++;
  3154. }
  3155. return $new_array;
  3156. } else {
  3157. return $this->col_info[ $col_offset ]->{$info_type};
  3158. }
  3159. }
  3160. }
  3161. /**
  3162. * Starts the timer, for debugging purposes.
  3163. *
  3164. * @since 1.5.0
  3165. *
  3166. * @return true
  3167. */
  3168. public function timer_start() {
  3169. $this->time_start = microtime( true );
  3170. return true;
  3171. }
  3172. /**
  3173. * Stops the debugging timer.
  3174. *
  3175. * @since 1.5.0
  3176. *
  3177. * @return float Total time spent on the query, in seconds.
  3178. */
  3179. public function timer_stop() {
  3180. return ( microtime( true ) - $this->time_start );
  3181. }
  3182. /**
  3183. * Wraps errors in a nice header and footer and dies.
  3184. *
  3185. * Will not die if wpdb::$show_errors is false.
  3186. *
  3187. * @since 1.5.0
  3188. *
  3189. * @param string $message The error message.
  3190. * @param string $error_code Optional. A computer-readable string to identify the error.
  3191. * Default '500'.
  3192. * @return void|false Void if the showing of errors is enabled, false if disabled.
  3193. */
  3194. public function bail( $message, $error_code = '500' ) {
  3195. if ( $this->show_errors ) {
  3196. $error = '';
  3197. if ( $this->use_mysqli ) {
  3198. if ( $this->dbh instanceof mysqli ) {
  3199. $error = mysqli_error( $this->dbh );
  3200. } elseif ( mysqli_connect_errno() ) {
  3201. $error = mysqli_connect_error();
  3202. }
  3203. } else {
  3204. if ( is_resource( $this->dbh ) ) {
  3205. $error = mysql_error( $this->dbh );
  3206. } else {
  3207. $error = mysql_error();
  3208. }
  3209. }
  3210. if ( $error ) {
  3211. $message = '<p><code>' . $error . "</code></p>\n" . $message;
  3212. }
  3213. wp_die( $message );
  3214. } else {
  3215. if ( class_exists( 'WP_Error', false ) ) {
  3216. $this->error = new WP_Error( $error_code, $message );
  3217. } else {
  3218. $this->error = $message;
  3219. }
  3220. return false;
  3221. }
  3222. }
  3223. /**
  3224. * Closes the current database connection.
  3225. *
  3226. * @since 4.5.0
  3227. *
  3228. * @return bool True if the connection was successfully closed,
  3229. * false if it wasn't, or if the connection doesn't exist.
  3230. */
  3231. public function close() {
  3232. if ( ! $this->dbh ) {
  3233. return false;
  3234. }
  3235. if ( $this->use_mysqli ) {
  3236. $closed = mysqli_close( $this->dbh );
  3237. } else {
  3238. $closed = mysql_close( $this->dbh );
  3239. }
  3240. if ( $closed ) {
  3241. $this->dbh = null;
  3242. $this->ready = false;
  3243. $this->has_connected = false;
  3244. }
  3245. return $closed;
  3246. }
  3247. /**
  3248. * Determines whether MySQL database is at least the required minimum version.
  3249. *
  3250. * @since 2.5.0
  3251. *
  3252. * @global string $wp_version The WordPress version string.
  3253. * @global string $required_mysql_version The required MySQL version string.
  3254. * @return void|WP_Error
  3255. */
  3256. public function check_database_version() {
  3257. global $wp_version, $required_mysql_version;
  3258. // Make sure the server has the required MySQL version.
  3259. if ( version_compare( $this->db_version(), $required_mysql_version, '<' ) ) {
  3260. /* translators: 1: WordPress version number, 2: Minimum required MySQL version number. */
  3261. return new WP_Error( 'database_version', sprintf( __( '<strong>Error</strong>: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ) );
  3262. }
  3263. }
  3264. /**
  3265. * Determines whether the database supports collation.
  3266. *
  3267. * Called when WordPress is generating the table scheme.
  3268. *
  3269. * Use `wpdb::has_cap( 'collation' )`.
  3270. *
  3271. * @since 2.5.0
  3272. * @deprecated 3.5.0 Use wpdb::has_cap()
  3273. *
  3274. * @return bool True if collation is supported, false if not.
  3275. */
  3276. public function supports_collation() {
  3277. _deprecated_function( __FUNCTION__, '3.5.0', 'wpdb::has_cap( \'collation\' )' );
  3278. return $this->has_cap( 'collation' );
  3279. }
  3280. /**
  3281. * Retrieves the database character collate.
  3282. *
  3283. * @since 3.5.0
  3284. *
  3285. * @return string The database character collate.
  3286. */
  3287. public function get_charset_collate() {
  3288. $charset_collate = '';
  3289. if ( ! empty( $this->charset ) ) {
  3290. $charset_collate = "DEFAULT CHARACTER SET $this->charset";
  3291. }
  3292. if ( ! empty( $this->collate ) ) {
  3293. $charset_collate .= " COLLATE $this->collate";
  3294. }
  3295. return $charset_collate;
  3296. }
  3297. /**
  3298. * Determines if a database supports a particular feature.
  3299. *
  3300. * @since 2.7.0
  3301. * @since 4.1.0 Added support for the 'utf8mb4' feature.
  3302. * @since 4.6.0 Added support for the 'utf8mb4_520' feature.
  3303. *
  3304. * @see wpdb::db_version()
  3305. *
  3306. * @param string $db_cap The feature to check for. Accepts 'collation', 'group_concat',
  3307. * 'subqueries', 'set_charset', 'utf8mb4', or 'utf8mb4_520'.
  3308. * @return int|false Whether the database feature is supported, false otherwise.
  3309. */
  3310. public function has_cap( $db_cap ) {
  3311. $version = $this->db_version();
  3312. switch ( strtolower( $db_cap ) ) {
  3313. case 'collation': // @since 2.5.0
  3314. case 'group_concat': // @since 2.7.0
  3315. case 'subqueries': // @since 2.7.0
  3316. return version_compare( $version, '4.1', '>=' );
  3317. case 'set_charset':
  3318. return version_compare( $version, '5.0.7', '>=' );
  3319. case 'utf8mb4': // @since 4.1.0
  3320. if ( version_compare( $version, '5.5.3', '<' ) ) {
  3321. return false;
  3322. }
  3323. if ( $this->use_mysqli ) {
  3324. $client_version = mysqli_get_client_info();
  3325. } else {
  3326. $client_version = mysql_get_client_info();
  3327. }
  3328. /*
  3329. * libmysql has supported utf8mb4 since 5.5.3, same as the MySQL server.
  3330. * mysqlnd has supported utf8mb4 since 5.0.9.
  3331. */
  3332. if ( false !== strpos( $client_version, 'mysqlnd' ) ) {
  3333. $client_version = preg_replace( '/^\D+([\d.]+).*/', '$1', $client_version );
  3334. return version_compare( $client_version, '5.0.9', '>=' );
  3335. } else {
  3336. return version_compare( $client_version, '5.5.3', '>=' );
  3337. }
  3338. case 'utf8mb4_520': // @since 4.6.0
  3339. return version_compare( $version, '5.6', '>=' );
  3340. }
  3341. return false;
  3342. }
  3343. /**
  3344. * Retrieves a comma-separated list of the names of the functions that called wpdb.
  3345. *
  3346. * @since 2.5.0
  3347. *
  3348. * @return string Comma-separated list of the calling functions.
  3349. */
  3350. public function get_caller() {
  3351. return wp_debug_backtrace_summary( __CLASS__ );
  3352. }
  3353. /**
  3354. * Retrieves the database server version.
  3355. *
  3356. * @since 2.7.0
  3357. *
  3358. * @return string|null Version number on success, null on failure.
  3359. */
  3360. public function db_version() {
  3361. return preg_replace( '/[^0-9.].*/', '', $this->db_server_info() );
  3362. }
  3363. /**
  3364. * Retrieves full database server information.
  3365. *
  3366. * @since 5.5.0
  3367. *
  3368. * @return string|false Server info on success, false on failure.
  3369. */
  3370. public function db_server_info() {
  3371. if ( $this->use_mysqli ) {
  3372. $server_info = mysqli_get_server_info( $this->dbh );
  3373. } else {
  3374. $server_info = mysql_get_server_info( $this->dbh );
  3375. }
  3376. return $server_info;
  3377. }
  3378. }