PageRenderTime 61ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 0ms

/sandbox/wp-includes/wp-db.php

https://bitbucket.org/stephenharris/stephenharris
PHP | 3105 lines | 1494 code | 332 blank | 1279 comment | 311 complexity | ccc3c9fc31afd42091eace715ccb6ad5 MD5 | raw file

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

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

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