PageRenderTime 68ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/wp-db.php

http://github.com/markjaquith/WordPress
PHP | 3665 lines | 1815 code | 400 blank | 1450 comment | 371 complexity | a787f58312b2b6a79c6b2b4ab0754577 MD5 | raw file
Possible License(s): 0BSD
  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. * @var bool
  56. */
  57. var $show_errors = false;
  58. /**
  59. * Whether to suppress errors during the DB bootstrapping. Default false.
  60. *
  61. * @since 2.5.0
  62. * @var bool
  63. */
  64. var $suppress_errors = false;
  65. /**
  66. * The error encountered during the last query.
  67. *
  68. * @since 2.5.0
  69. * @var string
  70. */
  71. public $last_error = '';
  72. /**
  73. * The number of queries made.
  74. *
  75. * @since 1.2.0
  76. * @var int
  77. */
  78. public $num_queries = 0;
  79. /**
  80. * Count of rows returned by the last query.
  81. *
  82. * @since 0.71
  83. * @var int
  84. */
  85. public $num_rows = 0;
  86. /**
  87. * Count of rows affected by the last query.
  88. *
  89. * @since 0.71
  90. * @var int
  91. */
  92. var $rows_affected = 0;
  93. /**
  94. * The ID generated for an AUTO_INCREMENT column by the last query (usually INSERT).
  95. *
  96. * @since 0.71
  97. * @var int
  98. */
  99. public $insert_id = 0;
  100. /**
  101. * The last query made.
  102. *
  103. * @since 0.71
  104. * @var string
  105. */
  106. var $last_query;
  107. /**
  108. * Results of the last query.
  109. *
  110. * @since 0.71
  111. * @var array|null
  112. */
  113. var $last_result;
  114. /**
  115. * MySQL result, which is either a resource or boolean.
  116. *
  117. * @since 0.71
  118. * @var mixed
  119. */
  120. protected $result;
  121. /**
  122. * Cached column info, for sanity checking data before inserting.
  123. *
  124. * @since 4.2.0
  125. * @var array
  126. */
  127. protected $col_meta = array();
  128. /**
  129. * Calculated character sets on tables.
  130. *
  131. * @since 4.2.0
  132. * @var array
  133. */
  134. protected $table_charset = array();
  135. /**
  136. * Whether text fields in the current query need to be sanity checked. Default false.
  137. *
  138. * @since 4.2.0
  139. * @var bool
  140. */
  141. protected $check_current_query = true;
  142. /**
  143. * Flag to ensure we don't run into recursion problems when checking the collation.
  144. *
  145. * @since 4.2.0
  146. * @see wpdb::check_safe_collation()
  147. * @var bool
  148. */
  149. private $checking_collation = false;
  150. /**
  151. * Saved info on the table column.
  152. *
  153. * @since 0.71
  154. * @var array
  155. */
  156. protected $col_info;
  157. /**
  158. * Log of queries that were executed, for debugging purposes.
  159. *
  160. * @since 1.5.0
  161. * @since 2.5.0 The third element in each query log was added to record the calling functions.
  162. * @since 5.1.0 The fourth element in each query log was added to record the start time.
  163. * @since 5.3.0 The fifth element in each query log was added to record custom data.
  164. *
  165. * @var array[] {
  166. * Array of queries that were executed.
  167. *
  168. * @type array ...$0 {
  169. * Data for each query.
  170. *
  171. * @type string $0 The query's SQL.
  172. * @type float $1 Total time spent on the query, in seconds.
  173. * @type string $2 Comma-separated list of the calling functions.
  174. * @type float $3 Unix timestamp of the time at the start of the query.
  175. * @type array $4 Custom query data.
  176. * }
  177. * }
  178. */
  179. var $queries;
  180. /**
  181. * The number of times to retry reconnecting before dying. Default 5.
  182. *
  183. * @since 3.9.0
  184. * @see wpdb::check_connection()
  185. * @var int
  186. */
  187. protected $reconnect_retries = 5;
  188. /**
  189. * WordPress table prefix
  190. *
  191. * You can set this to have multiple WordPress installations in a single database.
  192. * The second reason is for possible security precautions.
  193. *
  194. * @since 2.5.0
  195. * @var string
  196. */
  197. public $prefix = '';
  198. /**
  199. * WordPress base table prefix.
  200. *
  201. * @since 3.0.0
  202. * @var string
  203. */
  204. public $base_prefix;
  205. /**
  206. * Whether the database queries are ready to start executing.
  207. *
  208. * @since 2.3.2
  209. * @var bool
  210. */
  211. var $ready = false;
  212. /**
  213. * Blog ID.
  214. *
  215. * @since 3.0.0
  216. * @var int
  217. */
  218. public $blogid = 0;
  219. /**
  220. * Site ID.
  221. *
  222. * @since 3.0.0
  223. * @var int
  224. */
  225. public $siteid = 0;
  226. /**
  227. * List of WordPress per-blog tables.
  228. *
  229. * @since 2.5.0
  230. * @see wpdb::tables()
  231. * @var array
  232. */
  233. var $tables = array(
  234. 'posts',
  235. 'comments',
  236. 'links',
  237. 'options',
  238. 'postmeta',
  239. 'terms',
  240. 'term_taxonomy',
  241. 'term_relationships',
  242. 'termmeta',
  243. 'commentmeta',
  244. );
  245. /**
  246. * List of deprecated WordPress tables.
  247. *
  248. * 'categories', 'post2cat', and 'link2cat' were deprecated in 2.3.0, db version 5539.
  249. *
  250. * @since 2.9.0
  251. * @see wpdb::tables()
  252. * @var array
  253. */
  254. var $old_tables = array( 'categories', 'post2cat', 'link2cat' );
  255. /**
  256. * List of WordPress global tables.
  257. *
  258. * @since 3.0.0
  259. * @see wpdb::tables()
  260. * @var array
  261. */
  262. var $global_tables = array( 'users', 'usermeta' );
  263. /**
  264. * List of Multisite global tables.
  265. *
  266. * @since 3.0.0
  267. * @see wpdb::tables()
  268. * @var array
  269. */
  270. var $ms_global_tables = array(
  271. 'blogs',
  272. 'blogmeta',
  273. 'signups',
  274. 'site',
  275. 'sitemeta',
  276. 'sitecategories',
  277. 'registration_log',
  278. );
  279. /**
  280. * WordPress Comments table.
  281. *
  282. * @since 1.5.0
  283. * @var string
  284. */
  285. public $comments;
  286. /**
  287. * WordPress Comment Metadata table.
  288. *
  289. * @since 2.9.0
  290. * @var string
  291. */
  292. public $commentmeta;
  293. /**
  294. * WordPress Links table.
  295. *
  296. * @since 1.5.0
  297. * @var string
  298. */
  299. public $links;
  300. /**
  301. * WordPress Options table.
  302. *
  303. * @since 1.5.0
  304. * @var string
  305. */
  306. public $options;
  307. /**
  308. * WordPress Post Metadata table.
  309. *
  310. * @since 1.5.0
  311. * @var string
  312. */
  313. public $postmeta;
  314. /**
  315. * WordPress Posts table.
  316. *
  317. * @since 1.5.0
  318. * @var string
  319. */
  320. public $posts;
  321. /**
  322. * WordPress Terms table.
  323. *
  324. * @since 2.3.0
  325. * @var string
  326. */
  327. public $terms;
  328. /**
  329. * WordPress Term Relationships table.
  330. *
  331. * @since 2.3.0
  332. * @var string
  333. */
  334. public $term_relationships;
  335. /**
  336. * WordPress Term Taxonomy table.
  337. *
  338. * @since 2.3.0
  339. * @var string
  340. */
  341. public $term_taxonomy;
  342. /**
  343. * WordPress Term Meta table.
  344. *
  345. * @since 4.4.0
  346. * @var string
  347. */
  348. public $termmeta;
  349. //
  350. // Global and Multisite tables
  351. //
  352. /**
  353. * WordPress User Metadata table.
  354. *
  355. * @since 2.3.0
  356. * @var string
  357. */
  358. public $usermeta;
  359. /**
  360. * WordPress Users table.
  361. *
  362. * @since 1.5.0
  363. * @var string
  364. */
  365. public $users;
  366. /**
  367. * Multisite Blogs table.
  368. *
  369. * @since 3.0.0
  370. * @var string
  371. */
  372. public $blogs;
  373. /**
  374. * Multisite Blog Metadata table.
  375. *
  376. * @since 5.1.0
  377. * @var string
  378. */
  379. public $blogmeta;
  380. /**
  381. * Multisite Registration Log table.
  382. *
  383. * @since 3.0.0
  384. * @var string
  385. */
  386. public $registration_log;
  387. /**
  388. * Multisite Signups table.
  389. *
  390. * @since 3.0.0
  391. * @var string
  392. */
  393. public $signups;
  394. /**
  395. * Multisite Sites table.
  396. *
  397. * @since 3.0.0
  398. * @var string
  399. */
  400. public $site;
  401. /**
  402. * Multisite Sitewide Terms table.
  403. *
  404. * @since 3.0.0
  405. * @var string
  406. */
  407. public $sitecategories;
  408. /**
  409. * Multisite Site Metadata table.
  410. *
  411. * @since 3.0.0
  412. * @var string
  413. */
  414. public $sitemeta;
  415. /**
  416. * Format specifiers for DB columns.
  417. *
  418. * Columns not listed here default to %s. Initialized during WP load.
  419. * Keys are column names, values are format types: 'ID' => '%d'.
  420. *
  421. * @since 2.8.0
  422. * @see wpdb::prepare()
  423. * @see wpdb::insert()
  424. * @see wpdb::update()
  425. * @see wpdb::delete()
  426. * @see wp_set_wpdb_vars()
  427. * @var array
  428. */
  429. public $field_types = array();
  430. /**
  431. * Database table columns charset.
  432. *
  433. * @since 2.2.0
  434. * @var string
  435. */
  436. public $charset;
  437. /**
  438. * Database table columns collate.
  439. *
  440. * @since 2.2.0
  441. * @var string
  442. */
  443. public $collate;
  444. /**
  445. * Database Username.
  446. *
  447. * @since 2.9.0
  448. * @var string
  449. */
  450. protected $dbuser;
  451. /**
  452. * Database Password.
  453. *
  454. * @since 3.1.0
  455. * @var string
  456. */
  457. protected $dbpassword;
  458. /**
  459. * Database Name.
  460. *
  461. * @since 3.1.0
  462. * @var string
  463. */
  464. protected $dbname;
  465. /**
  466. * Database Host.
  467. *
  468. * @since 3.1.0
  469. * @var string
  470. */
  471. protected $dbhost;
  472. /**
  473. * Database Handle.
  474. *
  475. * @since 0.71
  476. * @var string
  477. */
  478. protected $dbh;
  479. /**
  480. * A textual description of the last query/get_row/get_var call.
  481. *
  482. * @since 3.0.0
  483. * @var string
  484. */
  485. public $func_call;
  486. /**
  487. * Whether MySQL is used as the database engine.
  488. *
  489. * Set in wpdb::db_connect() to true, by default. This is used when checking
  490. * against the required MySQL version for WordPress. Normally, a replacement
  491. * database drop-in (db.php) will skip these checks, but setting this to true
  492. * will force the checks to occur.
  493. *
  494. * @since 3.3.0
  495. * @var bool
  496. */
  497. public $is_mysql = null;
  498. /**
  499. * A list of incompatible SQL modes.
  500. *
  501. * @since 3.9.0
  502. * @var array
  503. */
  504. protected $incompatible_modes = array(
  505. 'NO_ZERO_DATE',
  506. 'ONLY_FULL_GROUP_BY',
  507. 'STRICT_TRANS_TABLES',
  508. 'STRICT_ALL_TABLES',
  509. 'TRADITIONAL',
  510. 'ANSI',
  511. );
  512. /**
  513. * Whether to use mysqli over mysql. Default false.
  514. *
  515. * @since 3.9.0
  516. * @var bool
  517. */
  518. private $use_mysqli = false;
  519. /**
  520. * Whether we've managed to successfully connect at some point.
  521. *
  522. * @since 3.9.0
  523. * @var bool
  524. */
  525. private $has_connected = false;
  526. /**
  527. * Connects to the database server and selects a database.
  528. *
  529. * PHP5 style constructor for compatibility with PHP5. Does the actual setting up
  530. * of the class properties and connection to the database.
  531. *
  532. * @since 2.0.8
  533. *
  534. * @link https://core.trac.wordpress.org/ticket/3354
  535. * @global string $wp_version The WordPress version string.
  536. *
  537. * @param string $dbuser MySQL database user.
  538. * @param string $dbpassword MySQL database password.
  539. * @param string $dbname MySQL database name.
  540. * @param string $dbhost MySQL database host.
  541. */
  542. public function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
  543. if ( WP_DEBUG && WP_DEBUG_DISPLAY ) {
  544. $this->show_errors();
  545. }
  546. // Use ext/mysqli if it exists unless WP_USE_EXT_MYSQL is defined as true.
  547. if ( function_exists( 'mysqli_connect' ) ) {
  548. $this->use_mysqli = true;
  549. if ( defined( 'WP_USE_EXT_MYSQL' ) ) {
  550. $this->use_mysqli = ! WP_USE_EXT_MYSQL;
  551. }
  552. }
  553. $this->dbuser = $dbuser;
  554. $this->dbpassword = $dbpassword;
  555. $this->dbname = $dbname;
  556. $this->dbhost = $dbhost;
  557. // wp-config.php creation will manually connect when ready.
  558. if ( defined( 'WP_SETUP_CONFIG' ) ) {
  559. return;
  560. }
  561. $this->db_connect();
  562. }
  563. /**
  564. * Makes private properties readable for backward compatibility.
  565. *
  566. * @since 3.5.0
  567. *
  568. * @param string $name The private member to get, and optionally process.
  569. * @return mixed The private member.
  570. */
  571. public function __get( $name ) {
  572. if ( 'col_info' === $name ) {
  573. $this->load_col_info();
  574. }
  575. return $this->$name;
  576. }
  577. /**
  578. * Makes private properties settable for backward compatibility.
  579. *
  580. * @since 3.5.0
  581. *
  582. * @param string $name The private member to set.
  583. * @param mixed $value The value to set.
  584. */
  585. public function __set( $name, $value ) {
  586. $protected_members = array(
  587. 'col_meta',
  588. 'table_charset',
  589. 'check_current_query',
  590. );
  591. if ( in_array( $name, $protected_members, true ) ) {
  592. return;
  593. }
  594. $this->$name = $value;
  595. }
  596. /**
  597. * Makes private properties check-able for backward compatibility.
  598. *
  599. * @since 3.5.0
  600. *
  601. * @param string $name The private member to check.
  602. * @return bool If the member is set or not.
  603. */
  604. public function __isset( $name ) {
  605. return isset( $this->$name );
  606. }
  607. /**
  608. * Makes private properties un-settable for backward compatibility.
  609. *
  610. * @since 3.5.0
  611. *
  612. * @param string $name The private member to unset
  613. */
  614. public function __unset( $name ) {
  615. unset( $this->$name );
  616. }
  617. /**
  618. * Sets $this->charset and $this->collate.
  619. *
  620. * @since 3.1.0
  621. */
  622. public function init_charset() {
  623. $charset = '';
  624. $collate = '';
  625. if ( function_exists( 'is_multisite' ) && is_multisite() ) {
  626. $charset = 'utf8';
  627. if ( defined( 'DB_COLLATE' ) && DB_COLLATE ) {
  628. $collate = DB_COLLATE;
  629. } else {
  630. $collate = 'utf8_general_ci';
  631. }
  632. } elseif ( defined( 'DB_COLLATE' ) ) {
  633. $collate = DB_COLLATE;
  634. }
  635. if ( defined( 'DB_CHARSET' ) ) {
  636. $charset = DB_CHARSET;
  637. }
  638. $charset_collate = $this->determine_charset( $charset, $collate );
  639. $this->charset = $charset_collate['charset'];
  640. $this->collate = $charset_collate['collate'];
  641. }
  642. /**
  643. * Determines the best charset and collation to use given a charset and collation.
  644. *
  645. * For example, when able, utf8mb4 should be used instead of utf8.
  646. *
  647. * @since 4.6.0
  648. *
  649. * @param string $charset The character set to check.
  650. * @param string $collate The collation to check.
  651. * @return array {
  652. * The most appropriate character set and collation to use.
  653. *
  654. * @type string $charset Character set.
  655. * @type string $collate Collation.
  656. * }
  657. */
  658. public function determine_charset( $charset, $collate ) {
  659. if ( ( $this->use_mysqli && ! ( $this->dbh instanceof mysqli ) ) || empty( $this->dbh ) ) {
  660. return compact( 'charset', 'collate' );
  661. }
  662. if ( 'utf8' === $charset && $this->has_cap( 'utf8mb4' ) ) {
  663. $charset = 'utf8mb4';
  664. }
  665. if ( 'utf8mb4' === $charset && ! $this->has_cap( 'utf8mb4' ) ) {
  666. $charset = 'utf8';
  667. $collate = str_replace( 'utf8mb4_', 'utf8_', $collate );
  668. }
  669. if ( 'utf8mb4' === $charset ) {
  670. // _general_ is outdated, so we can upgrade it to _unicode_, instead.
  671. if ( ! $collate || 'utf8_general_ci' === $collate ) {
  672. $collate = 'utf8mb4_unicode_ci';
  673. } else {
  674. $collate = str_replace( 'utf8_', 'utf8mb4_', $collate );
  675. }
  676. }
  677. // _unicode_520_ is a better collation, we should use that when it's available.
  678. if ( $this->has_cap( 'utf8mb4_520' ) && 'utf8mb4_unicode_ci' === $collate ) {
  679. $collate = 'utf8mb4_unicode_520_ci';
  680. }
  681. return compact( 'charset', 'collate' );
  682. }
  683. /**
  684. * Sets the connection's character set.
  685. *
  686. * @since 3.1.0
  687. *
  688. * @param resource $dbh The resource given by mysql_connect.
  689. * @param string $charset Optional. The character set. Default null.
  690. * @param string $collate Optional. The collation. Default null.
  691. */
  692. public function set_charset( $dbh, $charset = null, $collate = null ) {
  693. if ( ! isset( $charset ) ) {
  694. $charset = $this->charset;
  695. }
  696. if ( ! isset( $collate ) ) {
  697. $collate = $this->collate;
  698. }
  699. if ( $this->has_cap( 'collation' ) && ! empty( $charset ) ) {
  700. $set_charset_succeeded = true;
  701. if ( $this->use_mysqli ) {
  702. if ( function_exists( 'mysqli_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
  703. $set_charset_succeeded = mysqli_set_charset( $dbh, $charset );
  704. }
  705. if ( $set_charset_succeeded ) {
  706. $query = $this->prepare( 'SET NAMES %s', $charset );
  707. if ( ! empty( $collate ) ) {
  708. $query .= $this->prepare( ' COLLATE %s', $collate );
  709. }
  710. mysqli_query( $dbh, $query );
  711. }
  712. } else {
  713. if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
  714. $set_charset_succeeded = mysql_set_charset( $charset, $dbh );
  715. }
  716. if ( $set_charset_succeeded ) {
  717. $query = $this->prepare( 'SET NAMES %s', $charset );
  718. if ( ! empty( $collate ) ) {
  719. $query .= $this->prepare( ' COLLATE %s', $collate );
  720. }
  721. mysql_query( $query, $dbh );
  722. }
  723. }
  724. }
  725. }
  726. /**
  727. * Changes the current SQL mode, and ensures its WordPress compatibility.
  728. *
  729. * If no modes are passed, it will ensure the current MySQL server modes are compatible.
  730. *
  731. * @since 3.9.0
  732. *
  733. * @param array $modes Optional. A list of SQL modes to set. Default empty array.
  734. */
  735. public function set_sql_mode( $modes = array() ) {
  736. if ( empty( $modes ) ) {
  737. if ( $this->use_mysqli ) {
  738. $res = mysqli_query( $this->dbh, 'SELECT @@SESSION.sql_mode' );
  739. } else {
  740. $res = mysql_query( 'SELECT @@SESSION.sql_mode', $this->dbh );
  741. }
  742. if ( empty( $res ) ) {
  743. return;
  744. }
  745. if ( $this->use_mysqli ) {
  746. $modes_array = mysqli_fetch_array( $res );
  747. if ( empty( $modes_array[0] ) ) {
  748. return;
  749. }
  750. $modes_str = $modes_array[0];
  751. } else {
  752. $modes_str = mysql_result( $res, 0 );
  753. }
  754. if ( empty( $modes_str ) ) {
  755. return;
  756. }
  757. $modes = explode( ',', $modes_str );
  758. }
  759. $modes = array_change_key_case( $modes, CASE_UPPER );
  760. /**
  761. * Filters the list of incompatible SQL modes to exclude.
  762. *
  763. * @since 3.9.0
  764. *
  765. * @param array $incompatible_modes An array of incompatible modes.
  766. */
  767. $incompatible_modes = (array) apply_filters( 'incompatible_sql_modes', $this->incompatible_modes );
  768. foreach ( $modes as $i => $mode ) {
  769. if ( in_array( $mode, $incompatible_modes, true ) ) {
  770. unset( $modes[ $i ] );
  771. }
  772. }
  773. $modes_str = implode( ',', $modes );
  774. if ( $this->use_mysqli ) {
  775. mysqli_query( $this->dbh, "SET SESSION sql_mode='$modes_str'" );
  776. } else {
  777. mysql_query( "SET SESSION sql_mode='$modes_str'", $this->dbh );
  778. }
  779. }
  780. /**
  781. * Sets the table prefix for the WordPress tables.
  782. *
  783. * @since 2.5.0
  784. *
  785. * @param string $prefix Alphanumeric name for the new prefix.
  786. * @param bool $set_table_names Optional. Whether the table names, e.g. wpdb::$posts,
  787. * should be updated or not. Default true.
  788. * @return string|WP_Error Old prefix or WP_Error on error.
  789. */
  790. public function set_prefix( $prefix, $set_table_names = true ) {
  791. if ( preg_match( '|[^a-z0-9_]|i', $prefix ) ) {
  792. return new WP_Error( 'invalid_db_prefix', 'Invalid database prefix' );
  793. }
  794. $old_prefix = is_multisite() ? '' : $prefix;
  795. if ( isset( $this->base_prefix ) ) {
  796. $old_prefix = $this->base_prefix;
  797. }
  798. $this->base_prefix = $prefix;
  799. if ( $set_table_names ) {
  800. foreach ( $this->tables( 'global' ) as $table => $prefixed_table ) {
  801. $this->$table = $prefixed_table;
  802. }
  803. if ( is_multisite() && empty( $this->blogid ) ) {
  804. return $old_prefix;
  805. }
  806. $this->prefix = $this->get_blog_prefix();
  807. foreach ( $this->tables( 'blog' ) as $table => $prefixed_table ) {
  808. $this->$table = $prefixed_table;
  809. }
  810. foreach ( $this->tables( 'old' ) as $table => $prefixed_table ) {
  811. $this->$table = $prefixed_table;
  812. }
  813. }
  814. return $old_prefix;
  815. }
  816. /**
  817. * Sets blog id.
  818. *
  819. * @since 3.0.0
  820. *
  821. * @param int $blog_id
  822. * @param int $network_id Optional.
  823. * @return int Previous blog id.
  824. */
  825. public function set_blog_id( $blog_id, $network_id = 0 ) {
  826. if ( ! empty( $network_id ) ) {
  827. $this->siteid = $network_id;
  828. }
  829. $old_blog_id = $this->blogid;
  830. $this->blogid = $blog_id;
  831. $this->prefix = $this->get_blog_prefix();
  832. foreach ( $this->tables( 'blog' ) as $table => $prefixed_table ) {
  833. $this->$table = $prefixed_table;
  834. }
  835. foreach ( $this->tables( 'old' ) as $table => $prefixed_table ) {
  836. $this->$table = $prefixed_table;
  837. }
  838. return $old_blog_id;
  839. }
  840. /**
  841. * Gets blog prefix.
  842. *
  843. * @since 3.0.0
  844. *
  845. * @param int $blog_id Optional.
  846. * @return string Blog prefix.
  847. */
  848. public function get_blog_prefix( $blog_id = null ) {
  849. if ( is_multisite() ) {
  850. if ( null === $blog_id ) {
  851. $blog_id = $this->blogid;
  852. }
  853. $blog_id = (int) $blog_id;
  854. if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) ) {
  855. return $this->base_prefix;
  856. } else {
  857. return $this->base_prefix . $blog_id . '_';
  858. }
  859. } else {
  860. return $this->base_prefix;
  861. }
  862. }
  863. /**
  864. * Returns an array of WordPress tables.
  865. *
  866. * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to override the WordPress users
  867. * and usermeta tables that would otherwise be determined by the prefix.
  868. *
  869. * The $scope argument can take one of the following:
  870. *
  871. * 'all' - returns 'all' and 'global' tables. No old tables are returned.
  872. * 'blog' - returns the blog-level tables for the queried blog.
  873. * 'global' - returns the global tables for the installation, returning multisite tables only on multisite.
  874. * 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
  875. * 'old' - returns tables which are deprecated.
  876. *
  877. * @since 3.0.0
  878. *
  879. * @uses wpdb::$tables
  880. * @uses wpdb::$old_tables
  881. * @uses wpdb::$global_tables
  882. * @uses wpdb::$ms_global_tables
  883. *
  884. * @param string $scope Optional. Possible values include 'all', 'global', 'ms_global', 'blog',
  885. * or 'old' tables. Default 'all'.
  886. * @param bool $prefix Optional. Whether to include table prefixes. If blog prefix is requested,
  887. * then the custom users and usermeta tables will be mapped. Default true.
  888. * @param int $blog_id Optional. The blog_id to prefix. Used only when prefix is requested.
  889. * Defaults to wpdb::$blogid.
  890. * @return array Table names. When a prefix is requested, the key is the unprefixed table name.
  891. */
  892. public function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
  893. switch ( $scope ) {
  894. case 'all':
  895. $tables = array_merge( $this->global_tables, $this->tables );
  896. if ( is_multisite() ) {
  897. $tables = array_merge( $tables, $this->ms_global_tables );
  898. }
  899. break;
  900. case 'blog':
  901. $tables = $this->tables;
  902. break;
  903. case 'global':
  904. $tables = $this->global_tables;
  905. if ( is_multisite() ) {
  906. $tables = array_merge( $tables, $this->ms_global_tables );
  907. }
  908. break;
  909. case 'ms_global':
  910. $tables = $this->ms_global_tables;
  911. break;
  912. case 'old':
  913. $tables = $this->old_tables;
  914. break;
  915. default:
  916. return array();
  917. }
  918. if ( $prefix ) {
  919. if ( ! $blog_id ) {
  920. $blog_id = $this->blogid;
  921. }
  922. $blog_prefix = $this->get_blog_prefix( $blog_id );
  923. $base_prefix = $this->base_prefix;
  924. $global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
  925. foreach ( $tables as $k => $table ) {
  926. if ( in_array( $table, $global_tables, true ) ) {
  927. $tables[ $table ] = $base_prefix . $table;
  928. } else {
  929. $tables[ $table ] = $blog_prefix . $table;
  930. }
  931. unset( $tables[ $k ] );
  932. }
  933. if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) ) {
  934. $tables['users'] = CUSTOM_USER_TABLE;
  935. }
  936. if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) ) {
  937. $tables['usermeta'] = CUSTOM_USER_META_TABLE;
  938. }
  939. }
  940. return $tables;
  941. }
  942. /**
  943. * Selects a database using the current database connection.
  944. *
  945. * The database name will be changed based on the current database connection.
  946. * On failure, the execution will bail and display a DB error.
  947. *
  948. * @since 0.71
  949. *
  950. * @param string $db MySQL database name.
  951. * @param resource|null $dbh Optional link identifier.
  952. */
  953. public function select( $db, $dbh = null ) {
  954. if ( is_null( $dbh ) ) {
  955. $dbh = $this->dbh;
  956. }
  957. if ( $this->use_mysqli ) {
  958. $success = mysqli_select_db( $dbh, $db );
  959. } else {
  960. $success = mysql_select_db( $db, $dbh );
  961. }
  962. if ( ! $success ) {
  963. $this->ready = false;
  964. if ( ! did_action( 'template_redirect' ) ) {
  965. wp_load_translations_early();
  966. $message = '<h1>' . __( 'Can&#8217;t select database' ) . "</h1>\n";
  967. $message .= '<p>' . sprintf(
  968. /* translators: %s: Database name. */
  969. __( '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.' ),
  970. '<code>' . htmlspecialchars( $db, ENT_QUOTES ) . '</code>'
  971. ) . "</p>\n";
  972. $message .= "<ul>\n";
  973. $message .= '<li>' . __( 'Are you sure it exists?' ) . "</li>\n";
  974. $message .= '<li>' . sprintf(
  975. /* translators: 1: Database user, 2: Database name. */
  976. __( 'Does the user %1$s have permission to use the %2$s database?' ),
  977. '<code>' . htmlspecialchars( $this->dbuser, ENT_QUOTES ) . '</code>',
  978. '<code>' . htmlspecialchars( $db, ENT_QUOTES ) . '</code>'
  979. ) . "</li>\n";
  980. $message .= '<li>' . sprintf(
  981. /* translators: %s: Database name. */
  982. __( '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?' ),
  983. htmlspecialchars( $db, ENT_QUOTES )
  984. ) . "</li>\n";
  985. $message .= "</ul>\n";
  986. $message .= '<p>' . sprintf(
  987. /* translators: %s: Support forums URL. */
  988. __( '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>.' ),
  989. __( 'https://wordpress.org/support/forums/' )
  990. ) . "</p>\n";
  991. $this->bail( $message, 'db_select_fail' );
  992. }
  993. }
  994. }
  995. /**
  996. * Do not use, deprecated.
  997. *
  998. * Use esc_sql() or wpdb::prepare() instead.
  999. *
  1000. * @since 2.8.0
  1001. * @deprecated 3.6.0 Use wpdb::prepare()
  1002. * @see wpdb::prepare()
  1003. * @see esc_sql()
  1004. *
  1005. * @param string $string
  1006. * @return string
  1007. */
  1008. function _weak_escape( $string ) {
  1009. if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) ) {
  1010. _deprecated_function( __METHOD__, '3.6.0', 'wpdb::prepare() or esc_sql()' );
  1011. }
  1012. return addslashes( $string );
  1013. }
  1014. /**
  1015. * Real escape, using mysqli_real_escape_string() or mysql_real_escape_string().
  1016. *
  1017. * @since 2.8.0
  1018. *
  1019. * @see mysqli_real_escape_string()
  1020. * @see mysql_real_escape_string()
  1021. *
  1022. * @param string $string String to escape.
  1023. * @return string Escaped string.
  1024. */
  1025. function _real_escape( $string ) {
  1026. if ( $this->dbh ) {
  1027. if ( $this->use_mysqli ) {
  1028. $escaped = mysqli_real_escape_string( $this->dbh, $string );
  1029. } else {
  1030. $escaped = mysql_real_escape_string( $string, $this->dbh );
  1031. }
  1032. } else {
  1033. $class = get_class( $this );
  1034. if ( function_exists( '__' ) ) {
  1035. /* translators: %s: Database access abstraction class, usually wpdb or a class extending wpdb. */
  1036. _doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), '3.6.0' );
  1037. } else {
  1038. _doing_it_wrong( $class, sprintf( '%s must set a database connection for use with escaping.', $class ), '3.6.0' );
  1039. }
  1040. $escaped = addslashes( $string );
  1041. }
  1042. return $this->add_placeholder_escape( $escaped );
  1043. }
  1044. /**
  1045. * Escapes data. Works on arrays.
  1046. *
  1047. * @since 2.8.0
  1048. *
  1049. * @uses wpdb::_real_escape()
  1050. *
  1051. * @param string|array $data Data to escape.
  1052. * @return string|array Escaped data, in the same type as supplied.
  1053. */
  1054. public function _escape( $data ) {
  1055. if ( is_array( $data ) ) {
  1056. foreach ( $data as $k => $v ) {
  1057. if ( is_array( $v ) ) {
  1058. $data[ $k ] = $this->_escape( $v );
  1059. } else {
  1060. $data[ $k ] = $this->_real_escape( $v );
  1061. }
  1062. }
  1063. } else {
  1064. $data = $this->_real_escape( $data );
  1065. }
  1066. return $data;
  1067. }
  1068. /**
  1069. * Do not use, deprecated.
  1070. *
  1071. * Use esc_sql() or wpdb::prepare() instead.
  1072. *
  1073. * @since 0.71
  1074. * @deprecated 3.6.0 Use wpdb::prepare()
  1075. * @see wpdb::prepare()
  1076. * @see esc_sql()
  1077. *
  1078. * @param string|array $data Data to escape.
  1079. * @return string|array Escaped data, in the same type as supplied.
  1080. */
  1081. public function escape( $data ) {
  1082. if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) ) {
  1083. _deprecated_function( __METHOD__, '3.6.0', 'wpdb::prepare() or esc_sql()' );
  1084. }
  1085. if ( is_array( $data ) ) {
  1086. foreach ( $data as $k => $v ) {
  1087. if ( is_array( $v ) ) {
  1088. $data[ $k ] = $this->escape( $v, 'recursive' );
  1089. } else {
  1090. $data[ $k ] = $this->_weak_escape( $v, 'internal' );
  1091. }
  1092. }
  1093. } else {
  1094. $data = $this->_weak_escape( $data, 'internal' );
  1095. }
  1096. return $data;
  1097. }
  1098. /**
  1099. * Escapes content by reference for insertion into the database, for security.
  1100. *
  1101. * @uses wpdb::_real_escape()
  1102. *
  1103. * @since 2.3.0
  1104. *
  1105. * @param string $string String to escape.
  1106. */
  1107. public function escape_by_ref( &$string ) {
  1108. if ( ! is_float( $string ) ) {
  1109. $string = $this->_real_escape( $string );
  1110. }
  1111. }
  1112. /**
  1113. * Prepares a SQL query for safe execution.
  1114. *
  1115. * Uses sprintf()-like syntax. The following placeholders can be used in the query string:
  1116. * %d (integer)
  1117. * %f (float)
  1118. * %s (string)
  1119. *
  1120. * All placeholders MUST be left unquoted in the query string. A corresponding argument
  1121. * MUST be passed for each placeholder.
  1122. *
  1123. * Note: There is one exception to the above: for compatibility with old behavior,
  1124. * numbered or formatted string placeholders (eg, %1$s, %5s) will not have quotes
  1125. * added by this function, so should be passed with appropriate quotes around them.
  1126. *
  1127. * Literal percentage signs (%) in the query string must be written as %%. Percentage wildcards
  1128. * (for example, to use in LIKE syntax) must be passed via a substitution argument containing
  1129. * the complete LIKE string, these cannot be inserted directly in the query string.
  1130. * Also see wpdb::esc_like().
  1131. *
  1132. * Arguments may be passed as individual arguments to the method, or as a single array
  1133. * containing all arguments. A combination of the two is not supported.
  1134. *
  1135. * Examples:
  1136. * $wpdb->prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d OR `other_field` LIKE %s", array( 'foo', 1337, '%bar' ) );
  1137. * $wpdb->prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
  1138. *
  1139. * @since 2.3.0
  1140. * @since 5.3.0 Formalized the existing and already documented `...$args` parameter
  1141. * by updating the function signature. The second parameter was changed
  1142. * from `$args` to `...$args`.
  1143. *
  1144. * @link https://www.php.net/sprintf Description of syntax.
  1145. *
  1146. * @param string $query Query statement with sprintf()-like placeholders.
  1147. * @param array|mixed $args The array of variables to substitute into the query's placeholders
  1148. * if being called with an array of arguments, or the first variable
  1149. * to substitute into the query's placeholders if being called with
  1150. * individual arguments.
  1151. * @param mixed ...$args Further variables to substitute into the query's placeholders
  1152. * if being called with individual arguments.
  1153. * @return string|void Sanitized query string, if there is a query to prepare.
  1154. */
  1155. public function prepare( $query, ...$args ) {
  1156. if ( is_null( $query ) ) {
  1157. return;
  1158. }
  1159. // This is not meant to be foolproof -- but it will catch obviously incorrect usage.
  1160. if ( strpos( $query, '%' ) === false ) {
  1161. wp_load_translations_early();
  1162. _doing_it_wrong(
  1163. 'wpdb::prepare',
  1164. sprintf(
  1165. /* translators: %s: wpdb::prepare() */
  1166. __( 'The query argument of %s must have a placeholder.' ),
  1167. 'wpdb::prepare()'
  1168. ),
  1169. '3.9.0'
  1170. );
  1171. }
  1172. // If args were passed as an array (as in vsprintf), move them up.
  1173. $passed_as_array = false;
  1174. if ( is_array( $args[0] ) && count( $args ) == 1 ) {
  1175. $passed_as_array = true;
  1176. $args = $args[0];
  1177. }
  1178. foreach ( $args as $arg ) {
  1179. if ( ! is_scalar( $arg ) && ! is_null( $arg ) ) {
  1180. wp_load_translations_early();
  1181. _doing_it_wrong(
  1182. 'wpdb::prepare',
  1183. sprintf(
  1184. /* translators: %s: Value type. */
  1185. __( 'Unsupported value type (%s).' ),
  1186. gettype( $arg )
  1187. ),
  1188. '4.8.2'
  1189. );
  1190. }
  1191. }
  1192. /*
  1193. * Specify the formatting allowed in a placeholder. The following are allowed:
  1194. *
  1195. * - Sign specifier. eg, $+d
  1196. * - Numbered placeholders. eg, %1$s
  1197. * - Padding specifier, including custom padding characters. eg, %05s, %'#5s
  1198. * - Alignment specifier. eg, %05-s
  1199. * - Precision specifier. eg, %.2f
  1200. */
  1201. $allowed_format = '(?:[1-9][0-9]*[$])?[-+0-9]*(?: |0|\'.)?[-+0-9]*(?:\.[0-9]+)?';
  1202. /*
  1203. * If a %s placeholder already has quotes around it, removing the existing quotes and re-inserting them
  1204. * ensures the quotes are consistent.
  1205. *
  1206. * For backward compatibility, this is only applied to %s, and not to placeholders like %1$s, which are frequently
  1207. * used in the middle of longer strings, or as table name placeholders.
  1208. */
  1209. $query = str_replace( "'%s'", '%s', $query ); // Strip any existing single quotes.
  1210. $query = str_replace( '"%s"', '%s', $query ); // Strip any existing double quotes.
  1211. $query = preg_replace( '/(?<!%)%s/', "'%s'", $query ); // Quote the strings, avoiding escaped strings like %%s.
  1212. $query = preg_replace( "/(?<!%)(%($allowed_format)?f)/", '%\\2F', $query ); // Force floats to be locale-unaware.
  1213. $query = preg_replace( "/%(?:%|$|(?!($allowed_format)?[sdF]))/", '%%\\1', $query ); // Escape any unescaped percents.
  1214. // Count the number of valid placeholders in the query.
  1215. $placeholders = preg_match_all( "/(^|[^%]|(%%)+)%($allowed_format)?[sdF]/", $query, $matches );
  1216. if ( count( $args ) !== $placeholders ) {
  1217. if ( 1 === $placeholders && $passed_as_array ) {
  1218. // If the passed query only expected one argument, but the wrong number of arguments were sent as an array, bail.
  1219. wp_load_translations_early();
  1220. _doing_it_wrong(
  1221. 'wpdb::prepare',
  1222. __( 'The query only expected one placeholder, but an array of multiple placeholders was sent.' ),
  1223. '4.9.0'
  1224. );
  1225. return;
  1226. } else {
  1227. /*
  1228. * If we don't have the right number of placeholders, but they were passed as individual arguments,
  1229. * or we were expecting multiple arguments in an array, throw a warning.
  1230. */
  1231. wp_load_translations_early();
  1232. _doing_it_wrong(
  1233. 'wpdb::prepare',
  1234. sprintf(
  1235. /* translators: 1: Number of placeholders, 2: Number of arguments passed. */
  1236. __( 'The query does not contain the correct number of placeholders (%1$d) for the number of arguments passed (%2$d).' ),
  1237. $placeholders,
  1238. count( $args )
  1239. ),
  1240. '4.8.3'
  1241. );
  1242. }
  1243. }
  1244. array_walk( $args, array( $this, 'escape_by_ref' ) );
  1245. $query = vsprintf( $query, $args );
  1246. return $this->add_placeholder_escape( $query );
  1247. }
  1248. /**
  1249. * First half of escaping for LIKE special characters % and _ before preparing for MySQL.
  1250. *
  1251. * Use this only before wpdb::prepare() or esc_sql(). Reversing the order is very bad for security.
  1252. *
  1253. * Example Prepared Statement:
  1254. *
  1255. * $wild = '%';
  1256. * $find = 'only 43% of planets';
  1257. * $like = $wild . $wpdb->esc_like( $find ) . $wild;
  1258. * $sql = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_content LIKE %s", $like );
  1259. *
  1260. * Example Escape Chain:
  1261. *
  1262. * $sql = esc_sql( $wpdb->esc_like( $input ) );
  1263. *
  1264. * @since 4.0.0
  1265. *
  1266. * @param string $text The raw text to be escaped. The input typed by the user
  1267. * should have no extra or deleted slashes.
  1268. * @return string Text in the form of a LIKE phrase. The output is not SQL safe.
  1269. * Call wpdb::prepare() or wpdb::_real_escape() next.
  1270. */
  1271. public function esc_like( $text ) {
  1272. return addcslashes( $text, '_%\\' );
  1273. }
  1274. /**
  1275. * Prints SQL/DB error.
  1276. *
  1277. * @since 0.71
  1278. *
  1279. * @global array $EZSQL_ERROR Stores error information of query and error string.
  1280. *
  1281. * @param string $str The error to display.
  1282. * @return void|false Void if the showing of errors is enabled, false if disabled.
  1283. */
  1284. public function print_error( $str = '' ) {
  1285. global $EZSQL_ERROR;
  1286. if ( ! $str ) {
  1287. if ( $this->use_mysqli ) {
  1288. $str = mysqli_error( $this->dbh );
  1289. } else {
  1290. $str = mysql_error( $this->dbh );
  1291. }
  1292. }
  1293. $EZSQL_ERROR[] = array(
  1294. 'query' => $this->last_query,
  1295. 'error_str' => $str,
  1296. );
  1297. if ( $this->suppress_errors ) {
  1298. return false;
  1299. }
  1300. wp_load_translations_early();
  1301. $caller = $this->get_caller();
  1302. if ( $caller ) {
  1303. /* translators: 1: Database error message, 2: SQL query, 3: Name of the calling function. */
  1304. $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s made by %3$s' ), $str, $this->last_query, $caller );
  1305. } else {
  1306. /* translators: 1: Database error message, 2: SQL query. */
  1307. $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s' ), $str, $this->last_query );
  1308. }
  1309. error_log( $error_str );
  1310. // Are we showing errors?
  1311. if ( ! $this->show_errors ) {
  1312. return false;
  1313. }
  1314. // If there is an error then take note of it.
  1315. if ( is_multisite() ) {
  1316. $msg = sprintf(
  1317. "%s [%s]\n%s\n",
  1318. __( 'WordPress database error:' ),
  1319. $str,
  1320. $this->last_query
  1321. );
  1322. if ( defined( 'ERRORLOGFILE' ) ) {
  1323. error_log( $msg, 3, ERRORLOGFILE );
  1324. }
  1325. if ( defined( 'DIEONDBERROR' ) ) {
  1326. wp_die( $msg );
  1327. }
  1328. } else {
  1329. $str = htmlspecialchars( $str, ENT_QUOTES );
  1330. $query = htmlspecialchars( $this->last_query, ENT_QUOTES );
  1331. printf(
  1332. '<div id="error"><p class="wpdberror"><strong>%s</strong> [%s]<br /><code>%s</code></p></div>',
  1333. __( 'WordPress database error:' ),
  1334. $str,
  1335. $query
  1336. );
  1337. }
  1338. }
  1339. /**
  1340. * Enables showing of database errors.
  1341. *
  1342. * This function should be used only to enable showing of errors.
  1343. * wpdb::hide_errors() should be used instead for hiding errors.
  1344. *
  1345. * @since 0.71
  1346. *
  1347. * @see wpdb::hide_errors()
  1348. *
  1349. * @param bool $show Optional. Whether to show errors. Default true.
  1350. * @return bool Whether showing of errors was previously active.
  1351. */
  1352. public function show_errors( $show = true ) {
  1353. $errors = $this->show_errors;
  1354. $this->show_errors = $show;
  1355. return $errors;
  1356. }
  1357. /**
  1358. * Disables showing of database errors.
  1359. *
  1360. * By default database errors are not shown.
  1361. *
  1362. * @since 0.71
  1363. *
  1364. * @see wpdb::show_errors()
  1365. *
  1366. * @return bool Whether showing of errors was previously active.
  1367. */
  1368. public function hide_errors() {
  1369. $show = $this->show_errors;
  1370. $this->show_errors = false;
  1371. return $show;
  1372. }
  1373. /**
  1374. * Enables or disables suppressing of database errors.
  1375. *
  1376. * By default database errors are suppressed.
  1377. *
  1378. * @since 2.5.0
  1379. *
  1380. * @see wpdb::hide_errors()
  1381. *
  1382. * @param bool $suppress Optional. Whether to suppress errors. Default true.
  1383. * @return bool Whether suppressing of errors was previously active.
  1384. */
  1385. public function suppress_errors( $suppress = true ) {
  1386. $errors = $this->suppress_errors;
  1387. $this->suppress_errors = (bool) $suppress;
  1388. return $errors;
  1389. }
  1390. /**
  1391. * Kills cached query results.
  1392. *
  1393. * @since 0.71
  1394. */
  1395. public function flush() {
  1396. $this->last_result = array();
  1397. $this->col_info = null;
  1398. $this->last_query = null;
  1399. $this->rows_affected = 0;
  1400. $this->num_rows = 0;
  1401. $this->last_error = '';
  1402. if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
  1403. mysqli_free_result( $this->result );
  1404. $this->result = null;
  1405. // Sanity check before using the handle.
  1406. if ( empty( $this->dbh ) || ! ( $this->dbh instanceof mysqli ) ) {
  1407. return;
  1408. }
  1409. // Clear out any results from a multi-query.
  1410. while ( mysqli_more_results( $this->dbh ) ) {
  1411. mysqli_next_result( $this->dbh );
  1412. }
  1413. } elseif ( is_resource( $this->result ) ) {
  1414. mysql_free_result( $this->result );
  1415. }
  1416. }
  1417. /**
  1418. * Connects to and selects database.
  1419. *
  1420. * If $allow_bail is false, the lack of database connection will need to be handled manually.
  1421. *
  1422. * @since 3.0.0
  1423. * @since 3.9.0 $allow_bail parameter added.
  1424. *
  1425. * @param bool $allow_bail Optional. Allows the function to bail. Default true.
  1426. * @return bool True with a successful connection, false on failure.
  1427. */
  1428. public function db_connect( $allow_bail = true ) {
  1429. $this->is_mysql = true;
  1430. /*
  1431. * Deprecated in 3.9+ when using MySQLi. No equivalent
  1432. * $new_link parameter exists for mysqli_* functions.
  1433. */
  1434. $new_link = defined( 'MYSQL_NEW_LINK' ) ? MYSQL_NEW_LINK : true;
  1435. $client_flags = defined( 'MYSQL_CLIENT_FLAGS' ) ? MYSQL_CLIENT_FLAGS : 0;
  1436. if ( $this->use_mysqli ) {
  1437. $this->dbh = mysqli_init();
  1438. $host = $this->dbhost;
  1439. $port = null;
  1440. $socket = null;
  1441. $is_ipv6 = false;
  1442. $host_data = $this->parse_db_host( $this->dbhost );
  1443. if ( $host_data ) {
  1444. list( $host, $port, $socket, $is_ipv6 ) = $host_data;
  1445. }
  1446. /*
  1447. * If using the `mysqlnd` library, the IPv6 address needs to be enclosed
  1448. * in square brackets, whereas it doesn't while using the `libmysqlclient` library.
  1449. * @see https://bugs.php.net/bug.php?id=67563
  1450. */
  1451. if ( $is_ipv6 && extension_loaded( 'mysqlnd' ) ) {
  1452. $host = "[$host]";
  1453. }
  1454. if ( WP_DEBUG ) {
  1455. mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
  1456. } else {
  1457. // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
  1458. @mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
  1459. }
  1460. if ( $this->dbh->connect_errno ) {
  1461. $this->dbh = null;
  1462. /*
  1463. * It's possible ext/mysqli is misconfigured. Fall back to ext/mysql if:
  1464. * - We haven't previously connected, and
  1465. * - WP_USE_EXT_MYSQL isn't set to false, and
  1466. * - ext/mysql is loaded.
  1467. */
  1468. $attempt_fallback = true;
  1469. if ( $this->has_connected ) {
  1470. $attempt_fallback = false;
  1471. } elseif ( defined( 'WP_USE_EXT_MYSQL' ) && ! WP_USE_EXT_MYSQL ) {
  1472. $attempt_fallback = false;
  1473. } elseif ( ! function_exists( 'mysql_connect' ) ) {
  1474. $attempt_fallback = false;
  1475. }
  1476. if ( $attempt_fallback ) {
  1477. $this->use_mysqli = false;
  1478. return $this->db_connect( $allow_bail );
  1479. }
  1480. }
  1481. } else {
  1482. if ( WP_DEBUG ) {
  1483. $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
  1484. } else {
  1485. // phpcs:ignore WordPress.PHP.NoSilencedErrors.Discouraged
  1486. $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
  1487. }
  1488. }
  1489. if ( ! $this->dbh && $allow_bail ) {
  1490. wp_load_translations_early();
  1491. // Load custom DB error template, if present.
  1492. if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
  1493. require_once WP_CONTENT_DIR . '/db-error.php';
  1494. die();
  1495. }
  1496. $message = '<h1>' . __( 'Error establishing a database connection' ) . "</h1>\n";
  1497. $message .= '<p>' . sprintf(
  1498. /* translators: 1: wp-config.php, 2: Database host. */
  1499. __( '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.' ),
  1500. '<code>wp-config.php</code>',
  1501. '<code>' . htmlspecialchars( $this->dbhost, ENT_QUOTES ) . '</code>'
  1502. ) . "</p>\n";
  1503. $message .= "<ul>\n";
  1504. $message .= '<li>' . __( 'Are you sure you have the correct username and password?' ) . "</li>\n";
  1505. $message .= '<li>' . __( 'Are you sure you have typed the correct hostname?' ) . "</li>\n";
  1506. $message .= '<li>' . __( 'Are you sure the database server is running?' ) . "</li>\n";
  1507. $message .= "</ul>\n";
  1508. $message .= '<p>' . sprintf(
  1509. /* translators: %s: Support forums URL. */
  1510. __( '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>.' ),
  1511. __( 'https://wordpress.org/support/forums/' )
  1512. ) . "</p>\n";
  1513. $this->bail( $message, 'db_connect_fail' );
  1514. return false;
  1515. } elseif ( $this->dbh ) {
  1516. if ( ! $this->has_connected ) {
  1517. $this->init_charset();
  1518. }
  1519. $this->has_connected = true;
  1520. $this->set_charset( $this->dbh );
  1521. $this->ready = true;
  1522. $this->set_sql_mode();
  1523. $this->select( $this->dbname, $this->dbh );
  1524. return true;
  1525. }
  1526. return false;
  1527. }
  1528. /**
  1529. * Parses the DB_HOST setting to interpret it for mysqli_real_connect().
  1530. *
  1531. * mysqli_real_connect() doesn't support the host param including a port or socket
  1532. * like mysql_connect() does. This duplicates how mysql_connect() detects a port
  1533. * and/or socket file.
  1534. *
  1535. * @since 4.9.0
  1536. *
  1537. * @param string $host The DB_HOST setting to parse.
  1538. * @return array|false Array containing the host, the port, the socket and
  1539. * whether it is an IPv6 address, in that order.
  1540. * False if $host couldn't be parsed.
  1541. */
  1542. public function parse_db_host( $host ) {
  1543. $port = null;
  1544. $socket = null;
  1545. $is_ipv6 = false;
  1546. // First peel off the socket parameter from the right, if it exists.
  1547. $socket_pos = strpos( $host, ':/' );
  1548. if ( false !== $socket_pos ) {
  1549. $socket = substr( $host, $socket_pos + 1 );
  1550. $host = substr( $host, 0, $socket_pos );
  1551. }
  1552. // We need to check for an IPv6 address first.
  1553. // An IPv6 address will always contain at least two colons.
  1554. if ( substr_count( $host, ':' ) > 1 ) {
  1555. $pattern = '#^(?:\[)?(?P<host>[0-9a-fA-F:]+)(?:\]:(?P<port>[\d]+))?#';
  1556. $is_ipv6 = true;
  1557. } else {
  1558. // We seem to be dealing with an IPv4 address.
  1559. $pattern = '#^(?P<host>[^:/]*)(?::(?P<port>[\d]+))?#';
  1560. }
  1561. $matches = array();
  1562. $result = preg_match( $pattern, $host, $matches );
  1563. if ( 1 !== $result ) {
  1564. // Couldn't parse the address, bail.
  1565. return false;
  1566. }
  1567. $host = '';
  1568. foreach ( array( 'host', 'port' ) as $component ) {
  1569. if ( ! empty( $matches[ $component ] ) ) {
  1570. $$component = $matches[ $component ];
  1571. }
  1572. }
  1573. return array( $host, $port, $socket, $is_ipv6 );
  1574. }
  1575. /**
  1576. * Checks that the connection to the database is still up. If not, try to reconnect.
  1577. *
  1578. * If this function is unable to reconnect, it will forcibly die, or if called
  1579. * after the {@see 'template_redirect'} hook has been fired, return false instead.
  1580. *
  1581. * If $allow_bail is false, the lack of database connection will need to be handled manually.
  1582. *
  1583. * @since 3.9.0
  1584. *
  1585. * @param bool $allow_bail Optional. Allows the function to bail. Default true.
  1586. * @return bool|void True if the connection is up.
  1587. */
  1588. public function check_connection( $allow_bail = true ) {
  1589. if ( $this->use_mysqli ) {
  1590. if ( ! empty( $this->dbh ) && mysqli_ping( $this->dbh ) ) {
  1591. return true;
  1592. }
  1593. } else {
  1594. if ( ! empty( $this->dbh ) && mysql_ping( $this->dbh ) ) {
  1595. return true;
  1596. }
  1597. }
  1598. $error_reporting = false;
  1599. // Disable warnings, as we don't want to see a multitude of "unable to connect" messages.
  1600. if ( WP_DEBUG ) {
  1601. $error_reporting = error_reporting();
  1602. error_reporting( $error_reporting & ~E_WARNING );
  1603. }
  1604. for ( $tries = 1; $tries <= $this->reconnect_retries; $tries++ ) {
  1605. // On the last try, re-enable warnings. We want to see a single instance
  1606. // of the "unable to connect" message on the bail() screen, if it appears.
  1607. if ( $this->reconnect_retries === $tries && WP_DEBUG ) {
  1608. error_reporting( $error_reporting );
  1609. }
  1610. if ( $this->db_connect( false ) ) {
  1611. if ( $error_reporting ) {
  1612. error_reporting( $error_reporting );
  1613. }
  1614. return true;
  1615. }
  1616. sleep( 1 );
  1617. }
  1618. // If template_redirect has already happened, it's too late for wp_die()/dead_db().
  1619. // Let's just return and hope for the best.
  1620. if ( did_action( 'template_redirect' ) ) {
  1621. return false;
  1622. }
  1623. if ( ! $allow_bail ) {
  1624. return false;
  1625. }
  1626. wp_load_translations_early();
  1627. $message = '<h1>' . __( 'Error reconnecting to the database' ) . "</h1>\n";
  1628. $message .= '<p>' . sprintf(
  1629. /* translators: %s: Database host. */
  1630. __( 'This means that we lost contact with the database server at %s. This could mean your host&#8217;s database server is down.' ),
  1631. '<code>' . htmlspecialchars( $this->dbhost, ENT_QUOTES ) . '</code>'
  1632. ) . "</p>\n";
  1633. $message .= "<ul>\n";
  1634. $message .= '<li>' . __( 'Are you sure the database server is running?' ) . "</li>\n";
  1635. $message .= '<li>' . __( 'Are you sure the database server is not under particularly heavy load?' ) . "</li>\n";
  1636. $message .= "</ul>\n";
  1637. $message .= '<p>' . sprintf(
  1638. /* translators: %s: Support forums URL. */
  1639. __( '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>.' ),
  1640. __( 'https://wordpress.org/support/forums/' )
  1641. ) . "</p>\n";
  1642. // We weren't able to reconnect, so we better bail.
  1643. $this->bail( $message, 'db_connect_fail' );
  1644. // Call dead_db() if bail didn't die, because this database is no more.
  1645. // It has ceased to be (at least temporarily).
  1646. dead_db();
  1647. }
  1648. /**
  1649. * Performs a MySQL database query, using current database connection.
  1650. *
  1651. * More information can be found on the Codex page.
  1652. *
  1653. * @since 0.71
  1654. *
  1655. * @link https://codex.wordpress.org/Function_Reference/wpdb_Class
  1656. *
  1657. * @param string $query Database query.
  1658. * @return int|bool Boolean true for CREATE, ALTER, TRUNCATE and DROP queries. Number of rows
  1659. * affected/selected for all other queries. Boolean false on error.
  1660. */
  1661. public function query( $query ) {
  1662. if ( ! $this->ready ) {
  1663. $this->check_current_query = true;
  1664. return false;
  1665. }
  1666. /**
  1667. * Filters the database query.
  1668. *
  1669. * Some queries are made before the plugins have been loaded,
  1670. * and thus cannot be filtered with this method.
  1671. *
  1672. * @since 2.1.0
  1673. *
  1674. * @param string $query Database query.
  1675. */
  1676. $query = apply_filters( 'query', $query );
  1677. $this->flush();
  1678. // Log how the function was called.
  1679. $this->func_call = "\$db->query(\"$query\")";
  1680. // If we're writing to the database, make sure the query will write safely.
  1681. if ( $this->check_current_query && ! $this->check_ascii( $query ) ) {
  1682. $stripped_query = $this->strip_invalid_text_from_query( $query );
  1683. // strip_invalid_text_from_query() can perform queries, so we need
  1684. // to flush again, just to make sure everything is clear.
  1685. $this->flush();
  1686. if ( $stripped_query !== $query ) {
  1687. $this->insert_id = 0;
  1688. return false;
  1689. }
  1690. }
  1691. $this->check_current_query = true;
  1692. // Keep track of the last query for debug.
  1693. $this->last_query = $query;
  1694. $this->_do_query( $query );
  1695. // MySQL server has gone away, try to reconnect.
  1696. $mysql_errno = 0;
  1697. if ( ! empty( $this->dbh ) ) {
  1698. if ( $this->use_mysqli ) {
  1699. if ( $this->dbh instanceof mysqli ) {
  1700. $mysql_errno = mysqli_errno( $this->dbh );
  1701. } else {
  1702. // $dbh is defined, but isn't a real connection.
  1703. // Something has gone horribly wrong, let's try a reconnect.
  1704. $mysql_errno = 2006;
  1705. }
  1706. } else {
  1707. if ( is_resource( $this->dbh ) ) {
  1708. $mysql_errno = mysql_errno( $this->dbh );
  1709. } else {
  1710. $mysql_errno = 2006;
  1711. }
  1712. }
  1713. }
  1714. if ( empty( $this->dbh ) || 2006 == $mysql_errno ) {
  1715. if ( $this->check_connection() ) {
  1716. $this->_do_query( $query );
  1717. } else {
  1718. $this->insert_id = 0;
  1719. return false;
  1720. }
  1721. }
  1722. // If there is an error then take note of it.
  1723. if ( $this->use_mysqli ) {
  1724. if ( $this->dbh instanceof mysqli ) {
  1725. $this->last_error = mysqli_error( $this->dbh );
  1726. } else {
  1727. $this->last_error = __( 'Unable to retrieve the error message from MySQL' );
  1728. }
  1729. } else {
  1730. if ( is_resource( $this->dbh ) ) {
  1731. $this->last_error = mysql_error( $this->dbh );
  1732. } else {
  1733. $this->last_error = __( 'Unable to retrieve the error message from MySQL' );
  1734. }
  1735. }
  1736. if ( $this->last_error ) {
  1737. // Clear insert_id on a subsequent failed insert.
  1738. if ( $this->insert_id && preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
  1739. $this->insert_id = 0;
  1740. }
  1741. $this->print_error();
  1742. return false;
  1743. }
  1744. if ( preg_match( '/^\s*(create|alter|truncate|drop)\s/i', $query ) ) {
  1745. $return_val = $this->result;
  1746. } elseif ( preg_match( '/^\s*(insert|delete|update|replace)\s/i', $query ) ) {
  1747. if ( $this->use_mysqli ) {
  1748. $this->rows_affected = mysqli_affected_rows( $this->dbh );
  1749. } else {
  1750. $this->rows_affected = mysql_affected_rows( $this->dbh );
  1751. }
  1752. // Take note of the insert_id.
  1753. if ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
  1754. if ( $this->use_mysqli ) {
  1755. $this->insert_id = mysqli_insert_id( $this->dbh );
  1756. } else {
  1757. $this->insert_id = mysql_insert_id( $this->dbh );
  1758. }
  1759. }
  1760. // Return number of rows affected.
  1761. $return_val = $this->rows_affected;
  1762. } else {
  1763. $num_rows = 0;
  1764. if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
  1765. while ( $row = mysqli_fetch_object( $this->result ) ) {
  1766. $this->last_result[ $num_rows ] = $row;
  1767. $num_rows++;
  1768. }
  1769. } elseif ( is_resource( $this->result ) ) {
  1770. while ( $row = mysql_fetch_object( $this->result ) ) {
  1771. $this->last_result[ $num_rows ] = $row;
  1772. $num_rows++;
  1773. }
  1774. }
  1775. // Log and return the number of rows selected.
  1776. $this->num_rows = $num_rows;
  1777. $return_val = $num_rows;
  1778. }
  1779. return $return_val;
  1780. }
  1781. /**
  1782. * Internal function to perform the mysql_query() call.
  1783. *
  1784. * @since 3.9.0
  1785. *
  1786. * @see wpdb::query()
  1787. *
  1788. * @param string $query The query to run.
  1789. */
  1790. private function _do_query( $query ) {
  1791. if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
  1792. $this->timer_start();
  1793. }
  1794. if ( ! empty( $this->dbh ) && $this->use_mysqli ) {
  1795. $this->result = mysqli_query( $this->dbh, $query );
  1796. } elseif ( ! empty( $this->dbh ) ) {
  1797. $this->result = mysql_query( $query, $this->dbh );
  1798. }
  1799. $this->num_queries++;
  1800. if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
  1801. $this->log_query(
  1802. $query,
  1803. $this->timer_stop(),
  1804. $this->get_caller(),
  1805. $this->time_start,
  1806. array()
  1807. );
  1808. }
  1809. }
  1810. /**
  1811. * Logs query data.
  1812. *
  1813. * @since 5.3.0
  1814. *
  1815. * @param string $query The query's SQL.
  1816. * @param float $query_time Total time spent on the query, in seconds.
  1817. * @param string $query_callstack Comma-separated list of the calling functions.
  1818. * @param float $query_start Unix timestamp of the time at the start of the query.
  1819. * @param array $query_data Custom query data.
  1820. */
  1821. public function log_query( $query, $query_time, $query_callstack, $query_start, $query_data ) {
  1822. /**
  1823. * Filters the custom query data being logged.
  1824. *
  1825. * Caution should be used when modifying any of this data, it is recommended that any additional
  1826. * information you need to store about a query be added as a new associative entry to the fourth
  1827. * element $query_data.
  1828. *
  1829. * @since 5.3.0
  1830. *
  1831. * @param array $query_data Custom query data.
  1832. * @param string $query The query's SQL.
  1833. * @param float $query_time Total time spent on the query, in seconds.
  1834. * @param string $query_callstack Comma-separated list of the calling functions.
  1835. * @param float $query_start Unix timestamp of the time at the start of the query.
  1836. */
  1837. $query_data = apply_filters( 'log_query_custom_data', $query_data, $query, $query_time, $query_callstack, $query_start );
  1838. $this->queries[] = array(
  1839. $query,
  1840. $query_time,
  1841. $query_callstack,
  1842. $query_start,
  1843. $query_data,
  1844. );
  1845. }
  1846. /**
  1847. * Generates and returns a placeholder escape string for use in queries returned by ::prepare().
  1848. *
  1849. * @since 4.8.3
  1850. *
  1851. * @return string String to escape placeholders.
  1852. */
  1853. public function placeholder_escape() {
  1854. static $placeholder;
  1855. if ( ! $placeholder ) {
  1856. // If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
  1857. $algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
  1858. // Old WP installs may not have AUTH_SALT defined.
  1859. $salt = defined( 'AUTH_SALT' ) && AUTH_SALT ? AUTH_SALT : (string) rand();
  1860. $placeholder = '{' . hash_hmac( $algo, uniqid( $salt, true ), $salt ) . '}';
  1861. }
  1862. /*
  1863. * Add the filter to remove the placeholder escaper. Uses priority 0, so that anything
  1864. * else attached to this filter will receive the query with the placeholder string removed.
  1865. */
  1866. if ( false === has_filter( 'query', array( $this, 'remove_placeholder_escape' ) ) ) {
  1867. add_filter( 'query', array( $this, 'remove_placeholder_escape' ), 0 );
  1868. }
  1869. return $placeholder;
  1870. }
  1871. /**
  1872. * Adds a placeholder escape string, to escape anything that resembles a printf() placeholder.
  1873. *
  1874. * @since 4.8.3
  1875. *
  1876. * @param string $query The query to escape.
  1877. * @return string The query with the placeholder escape string inserted where necessary.
  1878. */
  1879. public function add_placeholder_escape( $query ) {
  1880. /*
  1881. * To prevent returning anything that even vaguely resembles a placeholder,
  1882. * we clobber every % we can find.
  1883. */
  1884. return str_replace( '%', $this->placeholder_escape(), $query );
  1885. }
  1886. /**
  1887. * Removes the placeholder escape strings from a query.
  1888. *
  1889. * @since 4.8.3
  1890. *
  1891. * @param string $query The query from which the placeholder will be removed.
  1892. * @return string The query with the placeholder removed.
  1893. */
  1894. public function remove_placeholder_escape( $query ) {
  1895. return str_replace( $this->placeholder_escape(), '%', $query );
  1896. }
  1897. /**
  1898. * Inserts a row into the table.
  1899. *
  1900. * Examples:
  1901. * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
  1902. * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
  1903. *
  1904. * @since 2.5.0
  1905. *
  1906. * @see wpdb::prepare()
  1907. * @see wpdb::$field_types
  1908. * @see wp_set_wpdb_vars()
  1909. *
  1910. * @param string $table Table name.
  1911. * @param array $data Data to insert (in column => value pairs).
  1912. * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  1913. * Sending a null value will cause the column to be set to NULL - the corresponding
  1914. * format is ignored in this case.
  1915. * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
  1916. * If string, that format will be used for all of the values in $data.
  1917. * A format is one of '%d', '%f', '%s' (integer, float, string).
  1918. * If omitted, all values in $data will be treated as strings unless otherwise
  1919. * specified in wpdb::$field_types.
  1920. * @return int|false The number of rows inserted, or false on error.
  1921. */
  1922. public function insert( $table, $data, $format = null ) {
  1923. return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
  1924. }
  1925. /**
  1926. * Replaces a row in the table.
  1927. *
  1928. * Examples:
  1929. * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
  1930. * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
  1931. *
  1932. * @since 3.0.0
  1933. *
  1934. * @see wpdb::prepare()
  1935. * @see wpdb::$field_types
  1936. * @see wp_set_wpdb_vars()
  1937. *
  1938. * @param string $table Table name.
  1939. * @param array $data Data to insert (in column => value pairs).
  1940. * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  1941. * Sending a null value will cause the column to be set to NULL - the corresponding
  1942. * format is ignored in this case.
  1943. * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
  1944. * If string, that format will be used for all of the values in $data.
  1945. * A format is one of '%d', '%f', '%s' (integer, float, string).
  1946. * If omitted, all values in $data will be treated as strings unless otherwise
  1947. * specified in wpdb::$field_types.
  1948. * @return int|false The number of rows affected, or false on error.
  1949. */
  1950. public function replace( $table, $data, $format = null ) {
  1951. return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
  1952. }
  1953. /**
  1954. * Helper function for insert and replace.
  1955. *
  1956. * Runs an insert or replace query based on $type argument.
  1957. *
  1958. * @since 3.0.0
  1959. *
  1960. * @see wpdb::prepare()
  1961. * @see wpdb::$field_types
  1962. * @see wp_set_wpdb_vars()
  1963. *
  1964. * @param string $table Table name.
  1965. * @param array $data Data to insert (in column => value pairs).
  1966. * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  1967. * Sending a null value will cause the column to be set to NULL - the corresponding
  1968. * format is ignored in this case.
  1969. * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
  1970. * If string, that format will be used for all of the values in $data.
  1971. * A format is one of '%d', '%f', '%s' (integer, float, string).
  1972. * If omitted, all values in $data will be treated as strings unless otherwise
  1973. * specified in wpdb::$field_types.
  1974. * @param string $type Optional. Type of operation. Possible values include 'INSERT' or 'REPLACE'.
  1975. * Default 'INSERT'.
  1976. * @return int|false The number of rows affected, or false on error.
  1977. */
  1978. function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
  1979. $this->insert_id = 0;
  1980. if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ), true ) ) {
  1981. return false;
  1982. }
  1983. $data = $this->process_fields( $table, $data, $format );
  1984. if ( false === $data ) {
  1985. return false;
  1986. }
  1987. $formats = array();
  1988. $values = array();
  1989. foreach ( $data as $value ) {
  1990. if ( is_null( $value['value'] ) ) {
  1991. $formats[] = 'NULL';
  1992. continue;
  1993. }
  1994. $formats[] = $value['format'];
  1995. $values[] = $value['value'];
  1996. }
  1997. $fields = '`' . implode( '`, `', array_keys( $data ) ) . '`';
  1998. $formats = implode( ', ', $formats );
  1999. $sql = "$type INTO `$table` ($fields) VALUES ($formats)";
  2000. $this->check_current_query = false;
  2001. return $this->query( $this->prepare( $sql, $values ) );
  2002. }
  2003. /**
  2004. * Updates a row in the table.
  2005. *
  2006. * Examples:
  2007. * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
  2008. * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
  2009. *
  2010. * @since 2.5.0
  2011. *
  2012. * @see wpdb::prepare()
  2013. * @see wpdb::$field_types
  2014. * @see wp_set_wpdb_vars()
  2015. *
  2016. * @param string $table Table name.
  2017. * @param array $data Data to update (in column => value pairs).
  2018. * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  2019. * Sending a null value will cause the column to be set to NULL - the corresponding
  2020. * format is ignored in this case.
  2021. * @param array $where A named array of WHERE clauses (in column => value pairs).
  2022. * Multiple clauses will be joined with ANDs.
  2023. * Both $where columns and $where values should be "raw".
  2024. * Sending a null value will create an IS NULL comparison - the corresponding
  2025. * format will be ignored in this case.
  2026. * @param array|string $format Optional. An array of formats to be mapped to each of the values in $data.
  2027. * If string, that format will be used for all of the values in $data.
  2028. * A format is one of '%d', '%f', '%s' (integer, float, string).
  2029. * If omitted, all values in $data will be treated as strings unless otherwise
  2030. * specified in wpdb::$field_types.
  2031. * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where.
  2032. * If string, that format will be used for all of the items in $where.
  2033. * A format is one of '%d', '%f', '%s' (integer, float, string).
  2034. * If omitted, all values in $where will be treated as strings.
  2035. * @return int|false The number of rows updated, or false on error.
  2036. */
  2037. public function update( $table, $data, $where, $format = null, $where_format = null ) {
  2038. if ( ! is_array( $data ) || ! is_array( $where ) ) {
  2039. return false;
  2040. }
  2041. $data = $this->process_fields( $table, $data, $format );
  2042. if ( false === $data ) {
  2043. return false;
  2044. }
  2045. $where = $this->process_fields( $table, $where, $where_format );
  2046. if ( false === $where ) {
  2047. return false;
  2048. }
  2049. $fields = array();
  2050. $conditions = array();
  2051. $values = array();
  2052. foreach ( $data as $field => $value ) {
  2053. if ( is_null( $value['value'] ) ) {
  2054. $fields[] = "`$field` = NULL";
  2055. continue;
  2056. }
  2057. $fields[] = "`$field` = " . $value['format'];
  2058. $values[] = $value['value'];
  2059. }
  2060. foreach ( $where as $field => $value ) {
  2061. if ( is_null( $value['value'] ) ) {
  2062. $conditions[] = "`$field` IS NULL";
  2063. continue;
  2064. }
  2065. $conditions[] = "`$field` = " . $value['format'];
  2066. $values[] = $value['value'];
  2067. }
  2068. $fields = implode( ', ', $fields );
  2069. $conditions = implode( ' AND ', $conditions );
  2070. $sql = "UPDATE `$table` SET $fields WHERE $conditions";
  2071. $this->check_current_query = false;
  2072. return $this->query( $this->prepare( $sql, $values ) );
  2073. }
  2074. /**
  2075. * Deletes a row in the table.
  2076. *
  2077. * Examples:
  2078. * wpdb::delete( 'table', array( 'ID' => 1 ) )
  2079. * wpdb::delete( 'table', array( 'ID' => 1 ), array( '%d' ) )
  2080. *
  2081. * @since 3.4.0
  2082. *
  2083. * @see wpdb::prepare()
  2084. * @see wpdb::$field_types
  2085. * @see wp_set_wpdb_vars()
  2086. *
  2087. * @param string $table Table name.
  2088. * @param array $where A named array of WHERE clauses (in column => value pairs).
  2089. * Multiple clauses will be joined with ANDs.
  2090. * Both $where columns and $where values should be "raw".
  2091. * Sending a null value will create an IS NULL comparison - the corresponding
  2092. * format will be ignored in this case.
  2093. * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where.
  2094. * If string, that format will be used for all of the items in $where.
  2095. * A format is one of '%d', '%f', '%s' (integer, float, string).
  2096. * If omitted, all values in $data will be treated as strings unless otherwise
  2097. * specified in wpdb::$field_types.
  2098. * @return int|false The number of rows updated, or false on error.
  2099. */
  2100. public function delete( $table, $where, $where_format = null ) {
  2101. if ( ! is_array( $where ) ) {
  2102. return false;
  2103. }
  2104. $where = $this->process_fields( $table, $where, $where_format );
  2105. if ( false === $where ) {
  2106. return false;
  2107. }
  2108. $conditions = array();
  2109. $values = array();
  2110. foreach ( $where as $field => $value ) {
  2111. if ( is_null( $value['value'] ) ) {
  2112. $conditions[] = "`$field` IS NULL";
  2113. continue;
  2114. }
  2115. $conditions[] = "`$field` = " . $value['format'];
  2116. $values[] = $value['value'];
  2117. }
  2118. $conditions = implode( ' AND ', $conditions );
  2119. $sql = "DELETE FROM `$table` WHERE $conditions";
  2120. $this->check_current_query = false;
  2121. return $this->query( $this->prepare( $sql, $values ) );
  2122. }
  2123. /**
  2124. * Processes arrays of field/value pairs and field formats.
  2125. *
  2126. * This is a helper method for wpdb's CRUD methods, which take field/value pairs
  2127. * for inserts, updates, and where clauses. This method first pairs each value
  2128. * with a format. Then it determines the charset of that field, using that
  2129. * to determine if any invalid text would be stripped. If text is stripped,
  2130. * then field processing is rejected and the query fails.
  2131. *
  2132. * @since 4.2.0
  2133. *
  2134. * @param string $table Table name.
  2135. * @param array $data Field/value pair.
  2136. * @param mixed $format Format for each field.
  2137. * @return array|false An array of fields that contain paired value and formats.
  2138. * False for invalid values.
  2139. */
  2140. protected function process_fields( $table, $data, $format ) {
  2141. $data = $this->process_field_formats( $data, $format );
  2142. if ( false === $data ) {
  2143. return false;
  2144. }
  2145. $data = $this->process_field_charsets( $data, $table );
  2146. if ( false === $data ) {
  2147. return false;
  2148. }
  2149. $data = $this->process_field_lengths( $data, $table );
  2150. if ( false === $data ) {
  2151. return false;
  2152. }
  2153. $converted_data = $this->strip_invalid_text( $data );
  2154. if ( $data !== $converted_data ) {
  2155. return false;
  2156. }
  2157. return $data;
  2158. }
  2159. /**
  2160. * Prepares arrays of value/format pairs as passed to wpdb CRUD methods.
  2161. *
  2162. * @since 4.2.0
  2163. *
  2164. * @param array $data Array of fields to values.
  2165. * @param mixed $format Formats to be mapped to the values in $data.
  2166. * @return array Array, keyed by field names with values being an array
  2167. * of 'value' and 'format' keys.
  2168. */
  2169. protected function process_field_formats( $data, $format ) {
  2170. $formats = (array) $format;
  2171. $original_formats = $formats;
  2172. foreach ( $data as $field => $value ) {
  2173. $value = array(
  2174. 'value' => $value,
  2175. 'format' => '%s',
  2176. );
  2177. if ( ! empty( $format ) ) {
  2178. $value['format'] = array_shift( $formats );
  2179. if ( ! $value['format'] ) {
  2180. $value['format'] = reset( $original_formats );
  2181. }
  2182. } elseif ( isset( $this->field_types[ $field ] ) ) {
  2183. $value['format'] = $this->field_types[ $field ];
  2184. }
  2185. $data[ $field ] = $value;
  2186. }
  2187. return $data;
  2188. }
  2189. /**
  2190. * Adds field charsets to field/value/format arrays generated by wpdb::process_field_formats().
  2191. *
  2192. * @since 4.2.0
  2193. *
  2194. * @param array $data As it comes from the wpdb::process_field_formats() method.
  2195. * @param string $table Table name.
  2196. * @return array|false The same array as $data with additional 'charset' keys.
  2197. * False on failure.
  2198. */
  2199. protected function process_field_charsets( $data, $table ) {
  2200. foreach ( $data as $field => $value ) {
  2201. if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
  2202. /*
  2203. * We can skip this field if we know it isn't a string.
  2204. * This checks %d/%f versus ! %s because its sprintf() could take more.
  2205. */
  2206. $value['charset'] = false;
  2207. } else {
  2208. $value['charset'] = $this->get_col_charset( $table, $field );
  2209. if ( is_wp_error( $value['charset'] ) ) {
  2210. return false;
  2211. }
  2212. }
  2213. $data[ $field ] = $value;
  2214. }
  2215. return $data;
  2216. }
  2217. /**
  2218. * For string fields, records the maximum string length that field can safely save.
  2219. *
  2220. * @since 4.2.1
  2221. *
  2222. * @param array $data As it comes from the wpdb::process_field_charsets() method.
  2223. * @param string $table Table name.
  2224. * @return array|false The same array as $data with additional 'length' keys, or false if
  2225. * any of the values were too long for their corresponding field.
  2226. */
  2227. protected function process_field_lengths( $data, $table ) {
  2228. foreach ( $data as $field => $value ) {
  2229. if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
  2230. /*
  2231. * We can skip this field if we know it isn't a string.
  2232. * This checks %d/%f versus ! %s because its sprintf() could take more.
  2233. */
  2234. $value['length'] = false;
  2235. } else {
  2236. $value['length'] = $this->get_col_length( $table, $field );
  2237. if ( is_wp_error( $value['length'] ) ) {
  2238. return false;
  2239. }
  2240. }
  2241. $data[ $field ] = $value;
  2242. }
  2243. return $data;
  2244. }
  2245. /**
  2246. * Retrieves one variable from the database.
  2247. *
  2248. * Executes a SQL query and returns the value from the SQL result.
  2249. * If the SQL result contains more than one column and/or more than one row,
  2250. * the value in the column and row specified is returned. If $query is null,
  2251. * the value in the specified column and row from the previous SQL result is returned.
  2252. *
  2253. * @since 0.71
  2254. *
  2255. * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
  2256. * @param int $x Optional. Column of value to return. Indexed from 0.
  2257. * @param int $y Optional. Row of value to return. Indexed from 0.
  2258. * @return string|null Database query result (as string), or null on failure.
  2259. */
  2260. public function get_var( $query = null, $x = 0, $y = 0 ) {
  2261. $this->func_call = "\$db->get_var(\"$query\", $x, $y)";
  2262. if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
  2263. $this->check_current_query = false;
  2264. }
  2265. if ( $query ) {
  2266. $this->query( $query );
  2267. }
  2268. // Extract var out of cached results based on x,y vals.
  2269. if ( ! empty( $this->last_result[ $y ] ) ) {
  2270. $values = array_values( get_object_vars( $this->last_result[ $y ] ) );
  2271. }
  2272. // If there is a value return it, else return null.
  2273. return ( isset( $values[ $x ] ) && '' !== $values[ $x ] ) ? $values[ $x ] : null;
  2274. }
  2275. /**
  2276. * Retrieves one row from the database.
  2277. *
  2278. * Executes a SQL query and returns the row from the SQL result.
  2279. *
  2280. * @since 0.71
  2281. *
  2282. * @param string|null $query SQL query.
  2283. * @param string $output Optional. The required return type. Possible values include
  2284. * OBJECT, ARRAY_A, or ARRAY_N, which correspond to an stdClass object,
  2285. * an associative array, or a numeric array, respectively. Default OBJECT.
  2286. * @param int $y Optional. Row to return. Indexed from 0.
  2287. * @return array|object|null|void Database query result in format specified by $output or null on failure.
  2288. */
  2289. public function get_row( $query = null, $output = OBJECT, $y = 0 ) {
  2290. $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
  2291. if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
  2292. $this->check_current_query = false;
  2293. }
  2294. if ( $query ) {
  2295. $this->query( $query );
  2296. } else {
  2297. return null;
  2298. }
  2299. if ( ! isset( $this->last_result[ $y ] ) ) {
  2300. return null;
  2301. }
  2302. if ( OBJECT == $output ) {
  2303. return $this->last_result[ $y ] ? $this->last_result[ $y ] : null;
  2304. } elseif ( ARRAY_A == $output ) {
  2305. return $this->last_result[ $y ] ? get_object_vars( $this->last_result[ $y ] ) : null;
  2306. } elseif ( ARRAY_N == $output ) {
  2307. return $this->last_result[ $y ] ? array_values( get_object_vars( $this->last_result[ $y ] ) ) : null;
  2308. } elseif ( OBJECT === strtoupper( $output ) ) {
  2309. // Back compat for OBJECT being previously case-insensitive.
  2310. return $this->last_result[ $y ] ? $this->last_result[ $y ] : null;
  2311. } else {
  2312. $this->print_error( ' $db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N' );
  2313. }
  2314. }
  2315. /**
  2316. * Retrieves one column from the database.
  2317. *
  2318. * Executes a SQL query and returns the column from the SQL result.
  2319. * If the SQL result contains more than one column, the column specified is returned.
  2320. * If $query is null, the specified column from the previous SQL result is returned.
  2321. *
  2322. * @since 0.71
  2323. *
  2324. * @param string|null $query Optional. SQL query. Defaults to previous query.
  2325. * @param int $x Optional. Column to return. Indexed from 0.
  2326. * @return array Database query result. Array indexed from 0 by SQL result row number.
  2327. */
  2328. public function get_col( $query = null, $x = 0 ) {
  2329. if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
  2330. $this->check_current_query = false;
  2331. }
  2332. if ( $query ) {
  2333. $this->query( $query );
  2334. }
  2335. $new_array = array();
  2336. // Extract the column values.
  2337. if ( $this->last_result ) {
  2338. for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
  2339. $new_array[ $i ] = $this->get_var( null, $x, $i );
  2340. }
  2341. }
  2342. return $new_array;
  2343. }
  2344. /**
  2345. * Retrieves an entire SQL result set from the database (i.e., many rows).
  2346. *
  2347. * Executes a SQL query and returns the entire SQL result.
  2348. *
  2349. * @since 0.71
  2350. *
  2351. * @param string $query SQL query.
  2352. * @param string $output Optional. Any of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants.
  2353. * With one of the first three, return an array of rows indexed
  2354. * from 0 by SQL result row number. Each row is an associative array
  2355. * (column => value, ...), a numerically indexed array (0 => value, ...),
  2356. * or an object ( ->column = value ), respectively. With OBJECT_K,
  2357. * return an associative array of row objects keyed by the value
  2358. * of each row's first column's value. Duplicate keys are discarded.
  2359. * @return array|object|null Database query results.
  2360. *
  2361. */
  2362. public function get_results( $query = null, $output = OBJECT ) {
  2363. $this->func_call = "\$db->get_results(\"$query\", $output)";
  2364. if ( $this->check_current_query && $this->check_safe_collation( $query ) ) {
  2365. $this->check_current_query = false;
  2366. }
  2367. if ( $query ) {
  2368. $this->query( $query );
  2369. } else {
  2370. return null;
  2371. }
  2372. $new_array = array();
  2373. if ( OBJECT == $output ) {
  2374. // Return an integer-keyed array of row objects.
  2375. return $this->last_result;
  2376. } elseif ( OBJECT_K == $output ) {
  2377. // Return an array of row objects with keys from column 1.
  2378. // (Duplicates are discarded.)
  2379. if ( $this->last_result ) {
  2380. foreach ( $this->last_result as $row ) {
  2381. $var_by_ref = get_object_vars( $row );
  2382. $key = array_shift( $var_by_ref );
  2383. if ( ! isset( $new_array[ $key ] ) ) {
  2384. $new_array[ $key ] = $row;
  2385. }
  2386. }
  2387. }
  2388. return $new_array;
  2389. } elseif ( ARRAY_A == $output || ARRAY_N == $output ) {
  2390. // Return an integer-keyed array of...
  2391. if ( $this->last_result ) {
  2392. foreach ( (array) $this->last_result as $row ) {
  2393. if ( ARRAY_N == $output ) {
  2394. // ...integer-keyed row arrays.
  2395. $new_array[] = array_values( get_object_vars( $row ) );
  2396. } else {
  2397. // ...column name-keyed row arrays.
  2398. $new_array[] = get_object_vars( $row );
  2399. }
  2400. }
  2401. }
  2402. return $new_array;
  2403. } elseif ( strtoupper( $output ) === OBJECT ) {
  2404. // Back compat for OBJECT being previously case-insensitive.
  2405. return $this->last_result;
  2406. }
  2407. return null;
  2408. }
  2409. /**
  2410. * Retrieves the character set for the given table.
  2411. *
  2412. * @since 4.2.0
  2413. *
  2414. * @param string $table Table name.
  2415. * @return string|WP_Error Table character set, WP_Error object if it couldn't be found.
  2416. */
  2417. protected function get_table_charset( $table ) {
  2418. $tablekey = strtolower( $table );
  2419. /**
  2420. * Filters the table charset value before the DB is checked.
  2421. *
  2422. * Passing a non-null value to the filter will effectively short-circuit
  2423. * checking the DB for the charset, returning that value instead.
  2424. *
  2425. * @since 4.2.0
  2426. *
  2427. * @param string|null $charset The character set to use. Default null.
  2428. * @param string $table The name of the table being checked.
  2429. */
  2430. $charset = apply_filters( 'pre_get_table_charset', null, $table );
  2431. if ( null !== $charset ) {
  2432. return $charset;
  2433. }
  2434. if ( isset( $this->table_charset[ $tablekey ] ) ) {
  2435. return $this->table_charset[ $tablekey ];
  2436. }
  2437. $charsets = array();
  2438. $columns = array();
  2439. $table_parts = explode( '.', $table );
  2440. $table = '`' . implode( '`.`', $table_parts ) . '`';
  2441. $results = $this->get_results( "SHOW FULL COLUMNS FROM $table" );
  2442. if ( ! $results ) {
  2443. return new WP_Error( 'wpdb_get_table_charset_failure' );
  2444. }
  2445. foreach ( $results as $column ) {
  2446. $columns[ strtolower( $column->Field ) ] = $column;
  2447. }
  2448. $this->col_meta[ $tablekey ] = $columns;
  2449. foreach ( $columns as $column ) {
  2450. if ( ! empty( $column->Collation ) ) {
  2451. list( $charset ) = explode( '_', $column->Collation );
  2452. // If the current connection can't support utf8mb4 characters, let's only send 3-byte utf8 characters.
  2453. if ( 'utf8mb4' === $charset && ! $this->has_cap( 'utf8mb4' ) ) {
  2454. $charset = 'utf8';
  2455. }
  2456. $charsets[ strtolower( $charset ) ] = true;
  2457. }
  2458. list( $type ) = explode( '(', $column->Type );
  2459. // A binary/blob means the whole query gets treated like this.
  2460. if ( in_array( strtoupper( $type ), array( 'BINARY', 'VARBINARY', 'TINYBLOB', 'MEDIUMBLOB', 'BLOB', 'LONGBLOB' ), true ) ) {
  2461. $this->table_charset[ $tablekey ] = 'binary';
  2462. return 'binary';
  2463. }
  2464. }
  2465. // utf8mb3 is an alias for utf8.
  2466. if ( isset( $charsets['utf8mb3'] ) ) {
  2467. $charsets['utf8'] = true;
  2468. unset( $charsets['utf8mb3'] );
  2469. }
  2470. // Check if we have more than one charset in play.
  2471. $count = count( $charsets );
  2472. if ( 1 === $count ) {
  2473. $charset = key( $charsets );
  2474. } elseif ( 0 === $count ) {
  2475. // No charsets, assume this table can store whatever.
  2476. $charset = false;
  2477. } else {
  2478. // More than one charset. Remove latin1 if present and recalculate.
  2479. unset( $charsets['latin1'] );
  2480. $count = count( $charsets );
  2481. if ( 1 === $count ) {
  2482. // Only one charset (besides latin1).
  2483. $charset = key( $charsets );
  2484. } elseif ( 2 === $count && isset( $charsets['utf8'], $charsets['utf8mb4'] ) ) {
  2485. // Two charsets, but they're utf8 and utf8mb4, use utf8.
  2486. $charset = 'utf8';
  2487. } else {
  2488. // Two mixed character sets. ascii.
  2489. $charset = 'ascii';
  2490. }
  2491. }
  2492. $this->table_charset[ $tablekey ] = $charset;
  2493. return $charset;
  2494. }
  2495. /**
  2496. * Retrieves the character set for the given column.
  2497. *
  2498. * @since 4.2.0
  2499. *
  2500. * @param string $table Table name.
  2501. * @param string $column Column name.
  2502. * @return string|false|WP_Error Column character set as a string. False if the column has
  2503. * no character set. WP_Error object if there was an error.
  2504. */
  2505. public function get_col_charset( $table, $column ) {
  2506. $tablekey = strtolower( $table );
  2507. $columnkey = strtolower( $column );
  2508. /**
  2509. * Filters the column charset value before the DB is checked.
  2510. *
  2511. * Passing a non-null value to the filter will short-circuit
  2512. * checking the DB for the charset, returning that value instead.
  2513. *
  2514. * @since 4.2.0
  2515. *
  2516. * @param string|null $charset The character set to use. Default null.
  2517. * @param string $table The name of the table being checked.
  2518. * @param string $column The name of the column being checked.
  2519. */
  2520. $charset = apply_filters( 'pre_get_col_charset', null, $table, $column );
  2521. if ( null !== $charset ) {
  2522. return $charset;
  2523. }
  2524. // Skip this entirely if this isn't a MySQL database.
  2525. if ( empty( $this->is_mysql ) ) {
  2526. return false;
  2527. }
  2528. if ( empty( $this->table_charset[ $tablekey ] ) ) {
  2529. // This primes column information for us.
  2530. $table_charset = $this->get_table_charset( $table );
  2531. if ( is_wp_error( $table_charset ) ) {
  2532. return $table_charset;
  2533. }
  2534. }
  2535. // If still no column information, return the table charset.
  2536. if ( empty( $this->col_meta[ $tablekey ] ) ) {
  2537. return $this->table_charset[ $tablekey ];
  2538. }
  2539. // If this column doesn't exist, return the table charset.
  2540. if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
  2541. return $this->table_charset[ $tablekey ];
  2542. }
  2543. // Return false when it's not a string column.
  2544. if ( empty( $this->col_meta[ $tablekey ][ $columnkey ]->Collation ) ) {
  2545. return false;
  2546. }
  2547. list( $charset ) = explode( '_', $this->col_meta[ $tablekey ][ $columnkey ]->Collation );
  2548. return $charset;
  2549. }
  2550. /**
  2551. * Retrieves the maximum string length allowed in a given column.
  2552. *
  2553. * The length may either be specified as a byte length or a character length.
  2554. *
  2555. * @since 4.2.1
  2556. *
  2557. * @param string $table Table name.
  2558. * @param string $column Column name.
  2559. * @return array|false|WP_Error array( 'length' => (int), 'type' => 'byte' | 'char' ).
  2560. * False if the column has no length (for example, numeric column).
  2561. * WP_Error object if there was an error.
  2562. */
  2563. public function get_col_length( $table, $column ) {
  2564. $tablekey = strtolower( $table );
  2565. $columnkey = strtolower( $column );
  2566. // Skip this entirely if this isn't a MySQL database.
  2567. if ( empty( $this->is_mysql ) ) {
  2568. return false;
  2569. }
  2570. if ( empty( $this->col_meta[ $tablekey ] ) ) {
  2571. // This primes column information for us.
  2572. $table_charset = $this->get_table_charset( $table );
  2573. if ( is_wp_error( $table_charset ) ) {
  2574. return $table_charset;
  2575. }
  2576. }
  2577. if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
  2578. return false;
  2579. }
  2580. $typeinfo = explode( '(', $this->col_meta[ $tablekey ][ $columnkey ]->Type );
  2581. $type = strtolower( $typeinfo[0] );
  2582. if ( ! empty( $typeinfo[1] ) ) {
  2583. $length = trim( $typeinfo[1], ')' );
  2584. } else {
  2585. $length = false;
  2586. }
  2587. switch ( $type ) {
  2588. case 'char':
  2589. case 'varchar':
  2590. return array(
  2591. 'type' => 'char',
  2592. 'length' => (int) $length,
  2593. );
  2594. case 'binary':
  2595. case 'varbinary':
  2596. return array(
  2597. 'type' => 'byte',
  2598. 'length' => (int) $length,
  2599. );
  2600. case 'tinyblob':
  2601. case 'tinytext':
  2602. return array(
  2603. 'type' => 'byte',
  2604. 'length' => 255, // 2^8 - 1
  2605. );
  2606. case 'blob':
  2607. case 'text':
  2608. return array(
  2609. 'type' => 'byte',
  2610. 'length' => 65535, // 2^16 - 1
  2611. );
  2612. case 'mediumblob':
  2613. case 'mediumtext':
  2614. return array(
  2615. 'type' => 'byte',
  2616. 'length' => 16777215, // 2^24 - 1
  2617. );
  2618. case 'longblob':
  2619. case 'longtext':
  2620. return array(
  2621. 'type' => 'byte',
  2622. 'length' => 4294967295, // 2^32 - 1
  2623. );
  2624. default:
  2625. return false;
  2626. }
  2627. }
  2628. /**
  2629. * Checks if a string is ASCII.
  2630. *
  2631. * The negative regex is faster for non-ASCII strings, as it allows
  2632. * the search to finish as soon as it encounters a non-ASCII character.
  2633. *
  2634. * @since 4.2.0
  2635. *
  2636. * @param string $string String to check.
  2637. * @return bool True if ASCII, false if not.
  2638. */
  2639. protected function check_ascii( $string ) {
  2640. if ( function_exists( 'mb_check_encoding' ) ) {
  2641. if ( mb_check_encoding( $string, 'ASCII' ) ) {
  2642. return true;
  2643. }
  2644. } elseif ( ! preg_match( '/[^\x00-\x7F]/', $string ) ) {
  2645. return true;
  2646. }
  2647. return false;
  2648. }
  2649. /**
  2650. * Checks if the query is accessing a collation considered safe on the current version of MySQL.
  2651. *
  2652. * @since 4.2.0
  2653. *
  2654. * @param string $query The query to check.
  2655. * @return bool True if the collation is safe, false if it isn't.
  2656. */
  2657. protected function check_safe_collation( $query ) {
  2658. if ( $this->checking_collation ) {
  2659. return true;
  2660. }
  2661. // We don't need to check the collation for queries that don't read data.
  2662. $query = ltrim( $query, "\r\n\t (" );
  2663. if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN|CREATE)\s/i', $query ) ) {
  2664. return true;
  2665. }
  2666. // All-ASCII queries don't need extra checking.
  2667. if ( $this->check_ascii( $query ) ) {
  2668. return true;
  2669. }
  2670. $table = $this->get_table_from_query( $query );
  2671. if ( ! $table ) {
  2672. return false;
  2673. }
  2674. $this->checking_collation = true;
  2675. $collation = $this->get_table_charset( $table );
  2676. $this->checking_collation = false;
  2677. // Tables with no collation, or latin1 only, don't need extra checking.
  2678. if ( false === $collation || 'latin1' === $collation ) {
  2679. return true;
  2680. }
  2681. $table = strtolower( $table );
  2682. if ( empty( $this->col_meta[ $table ] ) ) {
  2683. return false;
  2684. }
  2685. // If any of the columns don't have one of these collations, it needs more sanity checking.
  2686. foreach ( $this->col_meta[ $table ] as $col ) {
  2687. if ( empty( $col->Collation ) ) {
  2688. continue;
  2689. }
  2690. if ( ! in_array( $col->Collation, array( 'utf8_general_ci', 'utf8_bin', 'utf8mb4_general_ci', 'utf8mb4_bin' ), true ) ) {
  2691. return false;
  2692. }
  2693. }
  2694. return true;
  2695. }
  2696. /**
  2697. * Strips any invalid characters based on value/charset pairs.
  2698. *
  2699. * @since 4.2.0
  2700. *
  2701. * @param array $data Array of value arrays. Each value array has the keys 'value' and 'charset'.
  2702. * An optional 'ascii' key can be set to false to avoid redundant ASCII checks.
  2703. * @return array|WP_Error The $data parameter, with invalid characters removed from each value.
  2704. * This works as a passthrough: any additional keys such as 'field' are
  2705. * retained in each value array. If we cannot remove invalid characters,
  2706. * a WP_Error object is returned.
  2707. */
  2708. protected function strip_invalid_text( $data ) {
  2709. $db_check_string = false;
  2710. foreach ( $data as &$value ) {
  2711. $charset = $value['charset'];
  2712. if ( is_array( $value['length'] ) ) {
  2713. $length = $value['length']['length'];
  2714. $truncate_by_byte_length = 'byte' === $value['length']['type'];
  2715. } else {
  2716. $length = false;
  2717. // Since we have no length, we'll never truncate. Initialize the variable to false.
  2718. // True would take us through an unnecessary (for this case) codepath below.
  2719. $truncate_by_byte_length = false;
  2720. }
  2721. // There's no charset to work with.
  2722. if ( false === $charset ) {
  2723. continue;
  2724. }
  2725. // Column isn't a string.
  2726. if ( ! is_string( $value['value'] ) ) {
  2727. continue;
  2728. }
  2729. $needs_validation = true;
  2730. if (
  2731. // latin1 can store any byte sequence.
  2732. 'latin1' === $charset
  2733. ||
  2734. // ASCII is always OK.
  2735. ( ! isset( $value['ascii'] ) && $this->check_ascii( $value['value'] ) )
  2736. ) {
  2737. $truncate_by_byte_length = true;
  2738. $needs_validation = false;
  2739. }
  2740. if ( $truncate_by_byte_length ) {
  2741. mbstring_binary_safe_encoding();
  2742. if ( false !== $length && strlen( $value['value'] ) > $length ) {
  2743. $value['value'] = substr( $value['value'], 0, $length );
  2744. }
  2745. reset_mbstring_encoding();
  2746. if ( ! $needs_validation ) {
  2747. continue;
  2748. }
  2749. }
  2750. // utf8 can be handled by regex, which is a bunch faster than a DB lookup.
  2751. if ( ( 'utf8' === $charset || 'utf8mb3' === $charset || 'utf8mb4' === $charset ) && function_exists( 'mb_strlen' ) ) {
  2752. $regex = '/
  2753. (
  2754. (?: [\x00-\x7F] # single-byte sequences 0xxxxxxx
  2755. | [\xC2-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
  2756. | \xE0[\xA0-\xBF][\x80-\xBF] # triple-byte sequences 1110xxxx 10xxxxxx * 2
  2757. | [\xE1-\xEC][\x80-\xBF]{2}
  2758. | \xED[\x80-\x9F][\x80-\xBF]
  2759. | [\xEE-\xEF][\x80-\xBF]{2}';
  2760. if ( 'utf8mb4' === $charset ) {
  2761. $regex .= '
  2762. | \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences 11110xxx 10xxxxxx * 3
  2763. | [\xF1-\xF3][\x80-\xBF]{3}
  2764. | \xF4[\x80-\x8F][\x80-\xBF]{2}
  2765. ';
  2766. }
  2767. $regex .= '){1,40} # ...one or more times
  2768. )
  2769. | . # anything else
  2770. /x';
  2771. $value['value'] = preg_replace( $regex, '$1', $value['value'] );
  2772. if ( false !== $length && mb_strlen( $value['value'], 'UTF-8' ) > $length ) {
  2773. $value['value'] = mb_substr( $value['value'], 0, $length, 'UTF-8' );
  2774. }
  2775. continue;
  2776. }
  2777. // We couldn't use any local conversions, send it to the DB.
  2778. $value['db'] = true;
  2779. $db_check_string = true;
  2780. }
  2781. unset( $value ); // Remove by reference.
  2782. if ( $db_check_string ) {
  2783. $queries = array();
  2784. foreach ( $data as $col => $value ) {
  2785. if ( ! empty( $value['db'] ) ) {
  2786. // We're going to need to truncate by characters or bytes, depending on the length value we have.
  2787. if ( isset( $value['length']['type'] ) && 'byte' === $value['length']['type'] ) {
  2788. // Using binary causes LEFT() to truncate by bytes.
  2789. $charset = 'binary';
  2790. } else {
  2791. $charset = $value['charset'];
  2792. }
  2793. if ( $this->charset ) {
  2794. $connection_charset = $this->charset;
  2795. } else {
  2796. if ( $this->use_mysqli ) {
  2797. $connection_charset = mysqli_character_set_name( $this->dbh );
  2798. } else {
  2799. $connection_charset = mysql_client_encoding();
  2800. }
  2801. }
  2802. if ( is_array( $value['length'] ) ) {
  2803. $length = sprintf( '%.0f', $value['length']['length'] );
  2804. $queries[ $col ] = $this->prepare( "CONVERT( LEFT( CONVERT( %s USING $charset ), $length ) USING $connection_charset )", $value['value'] );
  2805. } elseif ( 'binary' !== $charset ) {
  2806. // If we don't have a length, there's no need to convert binary - it will always return the same result.
  2807. $queries[ $col ] = $this->prepare( "CONVERT( CONVERT( %s USING $charset ) USING $connection_charset )", $value['value'] );
  2808. }
  2809. unset( $data[ $col ]['db'] );
  2810. }
  2811. }
  2812. $sql = array();
  2813. foreach ( $queries as $column => $query ) {
  2814. if ( ! $query ) {
  2815. continue;
  2816. }
  2817. $sql[] = $query . " AS x_$column";
  2818. }
  2819. $this->check_current_query = false;
  2820. $row = $this->get_row( 'SELECT ' . implode( ', ', $sql ), ARRAY_A );
  2821. if ( ! $row ) {
  2822. return new WP_Error( 'wpdb_strip_invalid_text_failure' );
  2823. }
  2824. foreach ( array_keys( $data ) as $column ) {
  2825. if ( isset( $row[ "x_$column" ] ) ) {
  2826. $data[ $column ]['value'] = $row[ "x_$column" ];
  2827. }
  2828. }
  2829. }
  2830. return $data;
  2831. }
  2832. /**
  2833. * Strips any invalid characters from the query.
  2834. *
  2835. * @since 4.2.0
  2836. *
  2837. * @param string $query Query to convert.
  2838. * @return string|WP_Error The converted query, or a WP_Error object if the conversion fails.
  2839. */
  2840. protected function strip_invalid_text_from_query( $query ) {
  2841. // We don't need to check the collation for queries that don't read data.
  2842. $trimmed_query = ltrim( $query, "\r\n\t (" );
  2843. if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN|CREATE)\s/i', $trimmed_query ) ) {
  2844. return $query;
  2845. }
  2846. $table = $this->get_table_from_query( $query );
  2847. if ( $table ) {
  2848. $charset = $this->get_table_charset( $table );
  2849. if ( is_wp_error( $charset ) ) {
  2850. return $charset;
  2851. }
  2852. // We can't reliably strip text from tables containing binary/blob columns.
  2853. if ( 'binary' === $charset ) {
  2854. return $query;
  2855. }
  2856. } else {
  2857. $charset = $this->charset;
  2858. }
  2859. $data = array(
  2860. 'value' => $query,
  2861. 'charset' => $charset,
  2862. 'ascii' => false,
  2863. 'length' => false,
  2864. );
  2865. $data = $this->strip_invalid_text( array( $data ) );
  2866. if ( is_wp_error( $data ) ) {
  2867. return $data;
  2868. }
  2869. return $data[0]['value'];
  2870. }
  2871. /**
  2872. * Strips any invalid characters from the string for a given table and column.
  2873. *
  2874. * @since 4.2.0
  2875. *
  2876. * @param string $table Table name.
  2877. * @param string $column Column name.
  2878. * @param string $value The text to check.
  2879. * @return string|WP_Error The converted string, or a WP_Error object if the conversion fails.
  2880. */
  2881. public function strip_invalid_text_for_column( $table, $column, $value ) {
  2882. if ( ! is_string( $value ) ) {
  2883. return $value;
  2884. }
  2885. $charset = $this->get_col_charset( $table, $column );
  2886. if ( ! $charset ) {
  2887. // Not a string column.
  2888. return $value;
  2889. } elseif ( is_wp_error( $charset ) ) {
  2890. // Bail on real errors.
  2891. return $charset;
  2892. }
  2893. $data = array(
  2894. $column => array(
  2895. 'value' => $value,
  2896. 'charset' => $charset,
  2897. 'length' => $this->get_col_length( $table, $column ),
  2898. ),
  2899. );
  2900. $data = $this->strip_invalid_text( $data );
  2901. if ( is_wp_error( $data ) ) {
  2902. return $data;
  2903. }
  2904. return $data[ $column ]['value'];
  2905. }
  2906. /**
  2907. * Finds the first table name referenced in a query.
  2908. *
  2909. * @since 4.2.0
  2910. *
  2911. * @param string $query The query to search.
  2912. * @return string|false $table The table name found, or false if a table couldn't be found.
  2913. */
  2914. protected function get_table_from_query( $query ) {
  2915. // Remove characters that can legally trail the table name.
  2916. $query = rtrim( $query, ';/-#' );
  2917. // Allow (select...) union [...] style queries. Use the first query's table name.
  2918. $query = ltrim( $query, "\r\n\t (" );
  2919. // Strip everything between parentheses except nested selects.
  2920. $query = preg_replace( '/\((?!\s*select)[^(]*?\)/is', '()', $query );
  2921. // Quickly match most common queries.
  2922. if ( preg_match(
  2923. '/^\s*(?:'
  2924. . 'SELECT.*?\s+FROM'
  2925. . '|INSERT(?:\s+LOW_PRIORITY|\s+DELAYED|\s+HIGH_PRIORITY)?(?:\s+IGNORE)?(?:\s+INTO)?'
  2926. . '|REPLACE(?:\s+LOW_PRIORITY|\s+DELAYED)?(?:\s+INTO)?'
  2927. . '|UPDATE(?:\s+LOW_PRIORITY)?(?:\s+IGNORE)?'
  2928. . '|DELETE(?:\s+LOW_PRIORITY|\s+QUICK|\s+IGNORE)*(?:.+?FROM)?'
  2929. . ')\s+((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)/is',
  2930. $query,
  2931. $maybe
  2932. ) ) {
  2933. return str_replace( '`', '', $maybe[1] );
  2934. }
  2935. // SHOW TABLE STATUS and SHOW TABLES WHERE Name = 'wp_posts'
  2936. 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 ) ) {
  2937. return $maybe[2];
  2938. }
  2939. /*
  2940. * SHOW TABLE STATUS LIKE and SHOW TABLES LIKE 'wp\_123\_%'
  2941. * This quoted LIKE operand seldom holds a full table name.
  2942. * It is usually a pattern for matching a prefix so we just
  2943. * strip the trailing % and unescape the _ to get 'wp_123_'
  2944. * which drop-ins can use for routing these SQL statements.
  2945. */
  2946. 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 ) ) {
  2947. return str_replace( '\\_', '_', $maybe[2] );
  2948. }
  2949. // Big pattern for the rest of the table-related queries.
  2950. if ( preg_match(
  2951. '/^\s*(?:'
  2952. . '(?:EXPLAIN\s+(?:EXTENDED\s+)?)?SELECT.*?\s+FROM'
  2953. . '|DESCRIBE|DESC|EXPLAIN|HANDLER'
  2954. . '|(?:LOCK|UNLOCK)\s+TABLE(?:S)?'
  2955. . '|(?:RENAME|OPTIMIZE|BACKUP|RESTORE|CHECK|CHECKSUM|ANALYZE|REPAIR).*\s+TABLE'
  2956. . '|TRUNCATE(?:\s+TABLE)?'
  2957. . '|CREATE(?:\s+TEMPORARY)?\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?'
  2958. . '|ALTER(?:\s+IGNORE)?\s+TABLE'
  2959. . '|DROP\s+TABLE(?:\s+IF\s+EXISTS)?'
  2960. . '|CREATE(?:\s+\w+)?\s+INDEX.*\s+ON'
  2961. . '|DROP\s+INDEX.*\s+ON'
  2962. . '|LOAD\s+DATA.*INFILE.*INTO\s+TABLE'
  2963. . '|(?:GRANT|REVOKE).*ON\s+TABLE'
  2964. . '|SHOW\s+(?:.*FROM|.*TABLE)'
  2965. . ')\s+\(*\s*((?:[0-9a-zA-Z$_.`-]|[\xC2-\xDF][\x80-\xBF])+)\s*\)*/is',
  2966. $query,
  2967. $maybe
  2968. ) ) {
  2969. return str_replace( '`', '', $maybe[1] );
  2970. }
  2971. return false;
  2972. }
  2973. /**
  2974. * Loads the column metadata from the last query.
  2975. *
  2976. * @since 3.5.0
  2977. */
  2978. protected function load_col_info() {
  2979. if ( $this->col_info ) {
  2980. return;
  2981. }
  2982. if ( $this->use_mysqli ) {
  2983. $num_fields = mysqli_num_fields( $this->result );
  2984. for ( $i = 0; $i < $num_fields; $i++ ) {
  2985. $this->col_info[ $i ] = mysqli_fetch_field( $this->result );
  2986. }
  2987. } else {
  2988. $num_fields = mysql_num_fields( $this->result );
  2989. for ( $i = 0; $i < $num_fields; $i++ ) {
  2990. $this->col_info[ $i ] = mysql_fetch_field( $this->result, $i );
  2991. }
  2992. }
  2993. }
  2994. /**
  2995. * Retrieves column metadata from the last query.
  2996. *
  2997. * @since 0.71
  2998. *
  2999. * @param string $info_type Optional. Possible values include 'name', 'table', 'def', 'max_length',
  3000. * 'not_null', 'primary_key', 'multiple_key', 'unique_key', 'numeric',
  3001. * 'blob', 'type', 'unsigned', 'zerofill'. Default 'name'.
  3002. * @param int $col_offset Optional. 0: col name. 1: which table the col's in. 2: col's max length.
  3003. * 3: if the col is numeric. 4: col's type. Default -1.
  3004. * @return mixed Column results.
  3005. */
  3006. public function get_col_info( $info_type = 'name', $col_offset = -1 ) {
  3007. $this->load_col_info();
  3008. if ( $this->col_info ) {
  3009. if ( -1 == $col_offset ) {
  3010. $i = 0;
  3011. $new_array = array();
  3012. foreach ( (array) $this->col_info as $col ) {
  3013. $new_array[ $i ] = $col->{$info_type};
  3014. $i++;
  3015. }
  3016. return $new_array;
  3017. } else {
  3018. return $this->col_info[ $col_offset ]->{$info_type};
  3019. }
  3020. }
  3021. }
  3022. /**
  3023. * Starts the timer, for debugging purposes.
  3024. *
  3025. * @since 1.5.0
  3026. *
  3027. * @return true
  3028. */
  3029. public function timer_start() {
  3030. $this->time_start = microtime( true );
  3031. return true;
  3032. }
  3033. /**
  3034. * Stops the debugging timer.
  3035. *
  3036. * @since 1.5.0
  3037. *
  3038. * @return float Total time spent on the query, in seconds.
  3039. */
  3040. public function timer_stop() {
  3041. return ( microtime( true ) - $this->time_start );
  3042. }
  3043. /**
  3044. * Wraps errors in a nice header and footer and dies.
  3045. *
  3046. * Will not die if wpdb::$show_errors is false.
  3047. *
  3048. * @since 1.5.0
  3049. *
  3050. * @param string $message The error message.
  3051. * @param string $error_code Optional. A computer-readable string to identify the error.
  3052. * Default '500'.
  3053. * @return void|false Void if the showing of errors is enabled, false if disabled.
  3054. */
  3055. public function bail( $message, $error_code = '500' ) {
  3056. if ( $this->show_errors ) {
  3057. $error = '';
  3058. if ( $this->use_mysqli ) {
  3059. if ( $this->dbh instanceof mysqli ) {
  3060. $error = mysqli_error( $this->dbh );
  3061. } elseif ( mysqli_connect_errno() ) {
  3062. $error = mysqli_connect_error();
  3063. }
  3064. } else {
  3065. if ( is_resource( $this->dbh ) ) {
  3066. $error = mysql_error( $this->dbh );
  3067. } else {
  3068. $error = mysql_error();
  3069. }
  3070. }
  3071. if ( $error ) {
  3072. $message = '<p><code>' . $error . "</code></p>\n" . $message;
  3073. }
  3074. wp_die( $message );
  3075. } else {
  3076. if ( class_exists( 'WP_Error', false ) ) {
  3077. $this->error = new WP_Error( $error_code, $message );
  3078. } else {
  3079. $this->error = $message;
  3080. }
  3081. return false;
  3082. }
  3083. }
  3084. /**
  3085. * Closes the current database connection.
  3086. *
  3087. * @since 4.5.0
  3088. *
  3089. * @return bool True if the connection was successfully closed,
  3090. * false if it wasn't, or if the connection doesn't exist.
  3091. */
  3092. public function close() {
  3093. if ( ! $this->dbh ) {
  3094. return false;
  3095. }
  3096. if ( $this->use_mysqli ) {
  3097. $closed = mysqli_close( $this->dbh );
  3098. } else {
  3099. $closed = mysql_close( $this->dbh );
  3100. }
  3101. if ( $closed ) {
  3102. $this->dbh = null;
  3103. $this->ready = false;
  3104. $this->has_connected = false;
  3105. }
  3106. return $closed;
  3107. }
  3108. /**
  3109. * Determines whether MySQL database is at least the required minimum version.
  3110. *
  3111. * @since 2.5.0
  3112. *
  3113. * @global string $wp_version The WordPress version string.
  3114. * @global string $required_mysql_version The required MySQL version string.
  3115. * @return void|WP_Error
  3116. */
  3117. public function check_database_version() {
  3118. global $wp_version, $required_mysql_version;
  3119. // Make sure the server has the required MySQL version.
  3120. if ( version_compare( $this->db_version(), $required_mysql_version, '<' ) ) {
  3121. /* translators: 1: WordPress version number, 2: Minimum required MySQL version number. */
  3122. return new WP_Error( 'database_version', sprintf( __( '<strong>Error</strong>: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ) );
  3123. }
  3124. }
  3125. /**
  3126. * Determines whether the database supports collation.
  3127. *
  3128. * Called when WordPress is generating the table scheme.
  3129. *
  3130. * Use `wpdb::has_cap( 'collation' )`.
  3131. *
  3132. * @since 2.5.0
  3133. * @deprecated 3.5.0 Use wpdb::has_cap()
  3134. *
  3135. * @return bool True if collation is supported, false if not.
  3136. */
  3137. public function supports_collation() {
  3138. _deprecated_function( __FUNCTION__, '3.5.0', 'wpdb::has_cap( \'collation\' )' );
  3139. return $this->has_cap( 'collation' );
  3140. }
  3141. /**
  3142. * Retrieves the database character collate.
  3143. *
  3144. * @since 3.5.0
  3145. *
  3146. * @return string The database character collate.
  3147. */
  3148. public function get_charset_collate() {
  3149. $charset_collate = '';
  3150. if ( ! empty( $this->charset ) ) {
  3151. $charset_collate = "DEFAULT CHARACTER SET $this->charset";
  3152. }
  3153. if ( ! empty( $this->collate ) ) {
  3154. $charset_collate .= " COLLATE $this->collate";
  3155. }
  3156. return $charset_collate;
  3157. }
  3158. /**
  3159. * Determines if a database supports a particular feature.
  3160. *
  3161. * @since 2.7.0
  3162. * @since 4.1.0 Added support for the 'utf8mb4' feature.
  3163. * @since 4.6.0 Added support for the 'utf8mb4_520' feature.
  3164. *
  3165. * @see wpdb::db_version()
  3166. *
  3167. * @param string $db_cap The feature to check for. Accepts 'collation', 'group_concat',
  3168. * 'subqueries', 'set_charset', 'utf8mb4', or 'utf8mb4_520'.
  3169. * @return int|false Whether the database feature is supported, false otherwise.
  3170. */
  3171. public function has_cap( $db_cap ) {
  3172. $version = $this->db_version();
  3173. switch ( strtolower( $db_cap ) ) {
  3174. case 'collation': // @since 2.5.0
  3175. case 'group_concat': // @since 2.7.0
  3176. case 'subqueries': // @since 2.7.0
  3177. return version_compare( $version, '4.1', '>=' );
  3178. case 'set_charset':
  3179. return version_compare( $version, '5.0.7', '>=' );
  3180. case 'utf8mb4': // @since 4.1.0
  3181. if ( version_compare( $version, '5.5.3', '<' ) ) {
  3182. return false;
  3183. }
  3184. if ( $this->use_mysqli ) {
  3185. $client_version = mysqli_get_client_info();
  3186. } else {
  3187. $client_version = mysql_get_client_info();
  3188. }
  3189. /*
  3190. * libmysql has supported utf8mb4 since 5.5.3, same as the MySQL server.
  3191. * mysqlnd has supported utf8mb4 since 5.0.9.
  3192. */
  3193. if ( false !== strpos( $client_version, 'mysqlnd' ) ) {
  3194. $client_version = preg_replace( '/^\D+([\d.]+).*/', '$1', $client_version );
  3195. return version_compare( $client_version, '5.0.9', '>=' );
  3196. } else {
  3197. return version_compare( $client_version, '5.5.3', '>=' );
  3198. }
  3199. case 'utf8mb4_520': // @since 4.6.0
  3200. return version_compare( $version, '5.6', '>=' );
  3201. }
  3202. return false;
  3203. }
  3204. /**
  3205. * Retrieves the name of the function that called wpdb.
  3206. *
  3207. * Searches up the list of functions until it reaches the one that would
  3208. * most logically had called this method.
  3209. *
  3210. * @since 2.5.0
  3211. *
  3212. * @return string Comma-separated list of the calling functions.
  3213. */
  3214. public function get_caller() {
  3215. return wp_debug_backtrace_summary( __CLASS__ );
  3216. }
  3217. /**
  3218. * Retrieves the MySQL server version.
  3219. *
  3220. * @since 2.7.0
  3221. *
  3222. * @return string|null Version number on success, null on failure.
  3223. */
  3224. public function db_version() {
  3225. return preg_replace( '/[^0-9.].*/', '', $this->db_server_info() );
  3226. }
  3227. /**
  3228. * Retrieves full MySQL server information.
  3229. *
  3230. * @since 5.5.0
  3231. *
  3232. * @return string|false Server info on success, false on failure.
  3233. */
  3234. public function db_server_info() {
  3235. if ( $this->use_mysqli ) {
  3236. $server_info = mysqli_get_server_info( $this->dbh );
  3237. } else {
  3238. $server_info = mysql_get_server_info( $this->dbh );
  3239. }
  3240. return $server_info;
  3241. }
  3242. }