PageRenderTime 64ms CodeModel.GetById 21ms 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

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * WordPress database access abstraction class
  4. *
  5. * Original code from {@link http://php.justinvincent.com Justin Vincent (justin@visunet.ie)}
  6. *
  7. * @package WordPress
  8. * @subpackage Database
  9. * @since 0.71
  10. */
  11. /**
  12. * @since 0.71
  13. */
  14. define( 'EZSQL_VERSION', 'WP1.25' );
  15. /**
  16. * @since 0.71
  17. */
  18. define( 'OBJECT', 'OBJECT' );
  19. // phpcs:ignore Generic.NamingConventions.UpperCaseConstantName.ConstantNotUpperCase
  20. define( 'object', 'OBJECT' ); // Back compat.
  21. /**
  22. * @since 2.5.0
  23. */
  24. define( 'OBJECT_K', 'OBJECT_K' );
  25. /**
  26. * @since 0.71
  27. */
  28. define( 'ARRAY_A', 'ARRAY_A' );
  29. /**
  30. * @since 0.71
  31. */
  32. define( 'ARRAY_N', 'ARRAY_N' );
  33. /**
  34. * WordPress database access abstraction class.
  35. *
  36. * This class is used to interact with a database without needing to use raw SQL statements.
  37. * By default, WordPress uses this class to instantiate the global $wpdb object, providing
  38. * access to the WordPress database.
  39. *
  40. * It is possible to replace this class with your own by setting the $wpdb global variable
  41. * in wp-content/db.php file to your class. The wpdb class will still be included, so you can
  42. * extend it or simply use your own.
  43. *
  44. * @link https://developer.wordpress.org/reference/classes/wpdb/
  45. *
  46. * @since 0.71
  47. */
  48. class wpdb {
  49. /**
  50. * Whether to show SQL/DB errors.
  51. *
  52. * Default is to show errors if both WP_DEBUG and WP_DEBUG_DISPLAY evaluate to true.
  53. *
  54. * @since 0.71
  55. * @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;

Large files files are truncated, but you can click here to view the full file