PageRenderTime 51ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-includes/wp-db.php

https://gitlab.com/geyson/geyson
PHP | 3131 lines | 1496 code | 328 blank | 1307 comment | 315 complexity | 29bb91f8c26d89f8f438ef235c21922c MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0

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 public
  78. * @var int
  79. */
  80. public $num_queries = 0;
  81. /**
  82. * Count of rows returned by previous query
  83. *
  84. * @since 0.71
  85. * @access public
  86. * @var int
  87. */
  88. public $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. public $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 bool
  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 public
  196. * @var string
  197. */
  198. public $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. * @global string $wp_version
  546. *
  547. * @param string $dbuser MySQL database user
  548. * @param string $dbpassword MySQL database password
  549. * @param string $dbname MySQL database name
  550. * @param string $dbhost MySQL database host
  551. */
  552. public function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
  553. register_shutdown_function( array( $this, '__destruct' ) );
  554. if ( WP_DEBUG && WP_DEBUG_DISPLAY )
  555. $this->show_errors();
  556. /* Use ext/mysqli if it exists and:
  557. * - WP_USE_EXT_MYSQL is defined as false, or
  558. * - We are a development version of WordPress, or
  559. * - We are running PHP 5.5 or greater, or
  560. * - ext/mysql is not loaded.
  561. */
  562. if ( function_exists( 'mysqli_connect' ) ) {
  563. if ( defined( 'WP_USE_EXT_MYSQL' ) ) {
  564. $this->use_mysqli = ! WP_USE_EXT_MYSQL;
  565. } elseif ( version_compare( phpversion(), '5.5', '>=' ) || ! function_exists( 'mysql_connect' ) ) {
  566. $this->use_mysqli = true;
  567. } elseif ( false !== strpos( $GLOBALS['wp_version'], '-' ) ) {
  568. $this->use_mysqli = true;
  569. }
  570. }
  571. $this->dbuser = $dbuser;
  572. $this->dbpassword = $dbpassword;
  573. $this->dbname = $dbname;
  574. $this->dbhost = $dbhost;
  575. // wp-config.php creation will manually connect when ready.
  576. if ( defined( 'WP_SETUP_CONFIG' ) ) {
  577. return;
  578. }
  579. $this->db_connect();
  580. }
  581. /**
  582. * PHP5 style destructor and will run when database object is destroyed.
  583. *
  584. * @see wpdb::__construct()
  585. * @since 2.0.8
  586. * @return true
  587. */
  588. public function __destruct() {
  589. return true;
  590. }
  591. /**
  592. * PHP5 style magic getter, used to lazy-load expensive data.
  593. *
  594. * @since 3.5.0
  595. *
  596. * @param string $name The private member to get, and optionally process
  597. * @return mixed The private member
  598. */
  599. public function __get( $name ) {
  600. if ( 'col_info' === $name )
  601. $this->load_col_info();
  602. return $this->$name;
  603. }
  604. /**
  605. * Magic function, for backwards compatibility.
  606. *
  607. * @since 3.5.0
  608. *
  609. * @param string $name The private member to set
  610. * @param mixed $value The value to set
  611. */
  612. public function __set( $name, $value ) {
  613. $protected_members = array(
  614. 'col_meta',
  615. 'table_charset',
  616. 'check_current_query',
  617. );
  618. if ( in_array( $name, $protected_members, true ) ) {
  619. return;
  620. }
  621. $this->$name = $value;
  622. }
  623. /**
  624. * Magic function, for backwards compatibility.
  625. *
  626. * @since 3.5.0
  627. *
  628. * @param string $name The private member to check
  629. *
  630. * @return bool If the member is set or not
  631. */
  632. public function __isset( $name ) {
  633. return isset( $this->$name );
  634. }
  635. /**
  636. * Magic function, for backwards compatibility.
  637. *
  638. * @since 3.5.0
  639. *
  640. * @param string $name The private member to unset
  641. */
  642. public function __unset( $name ) {
  643. unset( $this->$name );
  644. }
  645. /**
  646. * Set $this->charset and $this->collate
  647. *
  648. * @since 3.1.0
  649. */
  650. public function init_charset() {
  651. if ( function_exists('is_multisite') && is_multisite() ) {
  652. $this->charset = 'utf8';
  653. if ( defined( 'DB_COLLATE' ) && DB_COLLATE ) {
  654. $this->collate = DB_COLLATE;
  655. } else {
  656. $this->collate = 'utf8_general_ci';
  657. }
  658. } elseif ( defined( 'DB_COLLATE' ) ) {
  659. $this->collate = DB_COLLATE;
  660. }
  661. if ( defined( 'DB_CHARSET' ) ) {
  662. $this->charset = DB_CHARSET;
  663. }
  664. if ( ( $this->use_mysqli && ! ( $this->dbh instanceof mysqli ) ) || empty( $this->dbh ) ) {
  665. return;
  666. }
  667. if ( 'utf8' === $this->charset && $this->has_cap( 'utf8mb4' ) ) {
  668. $this->charset = 'utf8mb4';
  669. }
  670. if ( 'utf8mb4' === $this->charset && ( ! $this->collate || stripos( $this->collate, 'utf8_' ) === 0 ) ) {
  671. $this->collate = 'utf8mb4_unicode_ci';
  672. }
  673. }
  674. /**
  675. * Sets the connection's character set.
  676. *
  677. * @since 3.1.0
  678. *
  679. * @param resource $dbh The resource given by mysql_connect
  680. * @param string $charset Optional. The character set. Default null.
  681. * @param string $collate Optional. The collation. Default null.
  682. */
  683. public function set_charset( $dbh, $charset = null, $collate = null ) {
  684. if ( ! isset( $charset ) )
  685. $charset = $this->charset;
  686. if ( ! isset( $collate ) )
  687. $collate = $this->collate;
  688. if ( $this->has_cap( 'collation' ) && ! empty( $charset ) ) {
  689. if ( $this->use_mysqli ) {
  690. if ( function_exists( 'mysqli_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
  691. mysqli_set_charset( $dbh, $charset );
  692. } else {
  693. $query = $this->prepare( 'SET NAMES %s', $charset );
  694. if ( ! empty( $collate ) )
  695. $query .= $this->prepare( ' COLLATE %s', $collate );
  696. mysqli_query( $dbh, $query );
  697. }
  698. } else {
  699. if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
  700. mysql_set_charset( $charset, $dbh );
  701. } else {
  702. $query = $this->prepare( 'SET NAMES %s', $charset );
  703. if ( ! empty( $collate ) )
  704. $query .= $this->prepare( ' COLLATE %s', $collate );
  705. mysql_query( $query, $dbh );
  706. }
  707. }
  708. }
  709. }
  710. /**
  711. * Change the current SQL mode, and ensure its WordPress compatibility.
  712. *
  713. * If no modes are passed, it will ensure the current MySQL server
  714. * modes are compatible.
  715. *
  716. * @since 3.9.0
  717. *
  718. * @param array $modes Optional. A list of SQL modes to set.
  719. */
  720. public function set_sql_mode( $modes = array() ) {
  721. if ( empty( $modes ) ) {
  722. if ( $this->use_mysqli ) {
  723. $res = mysqli_query( $this->dbh, 'SELECT @@SESSION.sql_mode' );
  724. } else {
  725. $res = mysql_query( 'SELECT @@SESSION.sql_mode', $this->dbh );
  726. }
  727. if ( empty( $res ) ) {
  728. return;
  729. }
  730. if ( $this->use_mysqli ) {
  731. $modes_array = mysqli_fetch_array( $res );
  732. if ( empty( $modes_array[0] ) ) {
  733. return;
  734. }
  735. $modes_str = $modes_array[0];
  736. } else {
  737. $modes_str = mysql_result( $res, 0 );
  738. }
  739. if ( empty( $modes_str ) ) {
  740. return;
  741. }
  742. $modes = explode( ',', $modes_str );
  743. }
  744. $modes = array_change_key_case( $modes, CASE_UPPER );
  745. /**
  746. * Filter the list of incompatible SQL modes to exclude.
  747. *
  748. * @since 3.9.0
  749. *
  750. * @param array $incompatible_modes An array of incompatible modes.
  751. */
  752. $incompatible_modes = (array) apply_filters( 'incompatible_sql_modes', $this->incompatible_modes );
  753. foreach( $modes as $i => $mode ) {
  754. if ( in_array( $mode, $incompatible_modes ) ) {
  755. unset( $modes[ $i ] );
  756. }
  757. }
  758. $modes_str = implode( ',', $modes );
  759. if ( $this->use_mysqli ) {
  760. mysqli_query( $this->dbh, "SET SESSION sql_mode='$modes_str'" );
  761. } else {
  762. mysql_query( "SET SESSION sql_mode='$modes_str'", $this->dbh );
  763. }
  764. }
  765. /**
  766. * Sets the table prefix for the WordPress tables.
  767. *
  768. * @since 2.5.0
  769. *
  770. * @param string $prefix Alphanumeric name for the new prefix.
  771. * @param bool $set_table_names Optional. Whether the table names, e.g. wpdb::$posts, should be updated or not.
  772. * @return string|WP_Error Old prefix or WP_Error on error
  773. */
  774. public function set_prefix( $prefix, $set_table_names = true ) {
  775. if ( preg_match( '|[^a-z0-9_]|i', $prefix ) )
  776. return new WP_Error('invalid_db_prefix', 'Invalid database prefix' );
  777. $old_prefix = is_multisite() ? '' : $prefix;
  778. if ( isset( $this->base_prefix ) )
  779. $old_prefix = $this->base_prefix;
  780. $this->base_prefix = $prefix;
  781. if ( $set_table_names ) {
  782. foreach ( $this->tables( 'global' ) as $table => $prefixed_table )
  783. $this->$table = $prefixed_table;
  784. if ( is_multisite() && empty( $this->blogid ) )
  785. return $old_prefix;
  786. $this->prefix = $this->get_blog_prefix();
  787. foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
  788. $this->$table = $prefixed_table;
  789. foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
  790. $this->$table = $prefixed_table;
  791. }
  792. return $old_prefix;
  793. }
  794. /**
  795. * Sets blog id.
  796. *
  797. * @since 3.0.0
  798. * @access public
  799. *
  800. * @param int $blog_id
  801. * @param int $site_id Optional.
  802. * @return int previous blog id
  803. */
  804. public function set_blog_id( $blog_id, $site_id = 0 ) {
  805. if ( ! empty( $site_id ) )
  806. $this->siteid = $site_id;
  807. $old_blog_id = $this->blogid;
  808. $this->blogid = $blog_id;
  809. $this->prefix = $this->get_blog_prefix();
  810. foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
  811. $this->$table = $prefixed_table;
  812. foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
  813. $this->$table = $prefixed_table;
  814. return $old_blog_id;
  815. }
  816. /**
  817. * Gets blog prefix.
  818. *
  819. * @since 3.0.0
  820. * @param int $blog_id Optional.
  821. * @return string Blog prefix.
  822. */
  823. public function get_blog_prefix( $blog_id = null ) {
  824. if ( is_multisite() ) {
  825. if ( null === $blog_id )
  826. $blog_id = $this->blogid;
  827. $blog_id = (int) $blog_id;
  828. if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) )
  829. return $this->base_prefix;
  830. else
  831. return $this->base_prefix . $blog_id . '_';
  832. } else {
  833. return $this->base_prefix;
  834. }
  835. }
  836. /**
  837. * Returns an array of WordPress tables.
  838. *
  839. * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
  840. * override the WordPress users and usermeta tables that would otherwise
  841. * be determined by the prefix.
  842. *
  843. * The scope argument can take one of the following:
  844. *
  845. * 'all' - returns 'all' and 'global' tables. No old tables are returned.
  846. * 'blog' - returns the blog-level tables for the queried blog.
  847. * 'global' - returns the global tables for the installation, returning multisite tables only if running multisite.
  848. * 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
  849. * 'old' - returns tables which are deprecated.
  850. *
  851. * @since 3.0.0
  852. * @uses wpdb::$tables
  853. * @uses wpdb::$old_tables
  854. * @uses wpdb::$global_tables
  855. * @uses wpdb::$ms_global_tables
  856. *
  857. * @param string $scope Optional. Can be all, global, ms_global, blog, or old tables. Defaults to all.
  858. * @param bool $prefix Optional. Whether to include table prefixes. Default true. If blog
  859. * prefix is requested, then the custom users and usermeta tables will be mapped.
  860. * @param int $blog_id Optional. The blog_id to prefix. Defaults to wpdb::$blogid. Used only when prefix is requested.
  861. * @return array Table names. When a prefix is requested, the key is the unprefixed table name.
  862. */
  863. public function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
  864. switch ( $scope ) {
  865. case 'all' :
  866. $tables = array_merge( $this->global_tables, $this->tables );
  867. if ( is_multisite() )
  868. $tables = array_merge( $tables, $this->ms_global_tables );
  869. break;
  870. case 'blog' :
  871. $tables = $this->tables;
  872. break;
  873. case 'global' :
  874. $tables = $this->global_tables;
  875. if ( is_multisite() )
  876. $tables = array_merge( $tables, $this->ms_global_tables );
  877. break;
  878. case 'ms_global' :
  879. $tables = $this->ms_global_tables;
  880. break;
  881. case 'old' :
  882. $tables = $this->old_tables;
  883. break;
  884. default :
  885. return array();
  886. }
  887. if ( $prefix ) {
  888. if ( ! $blog_id )
  889. $blog_id = $this->blogid;
  890. $blog_prefix = $this->get_blog_prefix( $blog_id );
  891. $base_prefix = $this->base_prefix;
  892. $global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
  893. foreach ( $tables as $k => $table ) {
  894. if ( in_array( $table, $global_tables ) )
  895. $tables[ $table ] = $base_prefix . $table;
  896. else
  897. $tables[ $table ] = $blog_prefix . $table;
  898. unset( $tables[ $k ] );
  899. }
  900. if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) )
  901. $tables['users'] = CUSTOM_USER_TABLE;
  902. if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) )
  903. $tables['usermeta'] = CUSTOM_USER_META_TABLE;
  904. }
  905. return $tables;
  906. }
  907. /**
  908. * Selects a database using the current database connection.
  909. *
  910. * The database name will be changed based on the current database
  911. * connection. On failure, the execution will bail and display an DB error.
  912. *
  913. * @since 0.71
  914. *
  915. * @param string $db MySQL database name
  916. * @param resource|null $dbh Optional link identifier.
  917. */
  918. public function select( $db, $dbh = null ) {
  919. if ( is_null($dbh) )
  920. $dbh = $this->dbh;
  921. if ( $this->use_mysqli ) {
  922. $success = @mysqli_select_db( $dbh, $db );
  923. } else {
  924. $success = @mysql_select_db( $db, $dbh );
  925. }
  926. if ( ! $success ) {
  927. $this->ready = false;
  928. if ( ! did_action( 'template_redirect' ) ) {
  929. wp_load_translations_early();
  930. $this->bail( sprintf( __( '<h1>Can&#8217;t select database</h1>
  931. <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>
  932. <ul>
  933. <li>Are you sure it exists?</li>
  934. <li>Does the user <code>%2$s</code> have permission to use the <code>%1$s</code> database?</li>
  935. <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>
  936. </ul>
  937. <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' );
  938. }
  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. *
  1043. * @since 2.3.0
  1044. *
  1045. * @param string $string to escape
  1046. */
  1047. public function escape_by_ref( &$string ) {
  1048. if ( ! is_float( $string ) )
  1049. $string = $this->_real_escape( $string );
  1050. }
  1051. /**
  1052. * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
  1053. *
  1054. * The following directives can be used in the query format string:
  1055. * %d (integer)
  1056. * %f (float)
  1057. * %s (string)
  1058. * %% (literal percentage sign - no argument needed)
  1059. *
  1060. * All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
  1061. * Literals (%) as parts of the query must be properly written as %%.
  1062. *
  1063. * This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
  1064. * Does not support sign, padding, alignment, width or precision specifiers.
  1065. * Does not support argument numbering/swapping.
  1066. *
  1067. * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
  1068. *
  1069. * Both %d and %s should be left unquoted in the query string.
  1070. *
  1071. * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
  1072. * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
  1073. *
  1074. * @link http://php.net/sprintf Description of syntax.
  1075. * @since 2.3.0
  1076. *
  1077. * @param string $query Query statement with sprintf()-like placeholders
  1078. * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
  1079. * {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
  1080. * being called like {@link http://php.net/sprintf sprintf()}.
  1081. * @param mixed $args,... further variables to substitute into the query's placeholders if being called like
  1082. * {@link http://php.net/sprintf sprintf()}.
  1083. * @return string|void Sanitized query string, if there is a query 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|void 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 = sprintf(
  1162. "%s [%s]\n%s\n",
  1163. __( 'WordPress database error:' ),
  1164. $str,
  1165. $this->last_query
  1166. );
  1167. if ( defined( 'ERRORLOGFILE' ) ) {
  1168. error_log( $msg, 3, ERRORLOGFILE );
  1169. }
  1170. if ( defined( 'DIEONDBERROR' ) ) {
  1171. wp_die( $msg );
  1172. }
  1173. } else {
  1174. $str = htmlspecialchars( $str, ENT_QUOTES );
  1175. $query = htmlspecialchars( $this->last_query, ENT_QUOTES );
  1176. printf(
  1177. '<div id="error"><p class="wpdberror"><strong>%s</strong> [%s]<br /><code>%s</code></p></div>',
  1178. __( 'WordPress database error:' ),
  1179. $str,
  1180. $query
  1181. );
  1182. }
  1183. }
  1184. /**
  1185. * Enables showing of database errors.
  1186. *
  1187. * This function should be used only to enable showing of errors.
  1188. * wpdb::hide_errors() should be used instead for hiding of errors. However,
  1189. * this function can be used to enable and disable showing of database
  1190. * errors.
  1191. *
  1192. * @since 0.71
  1193. * @see wpdb::hide_errors()
  1194. *
  1195. * @param bool $show Whether to show or hide errors
  1196. * @return bool Old value for showing errors.
  1197. */
  1198. public function show_errors( $show = true ) {
  1199. $errors = $this->show_errors;
  1200. $this->show_errors = $show;
  1201. return $errors;
  1202. }
  1203. /**
  1204. * Disables showing of database errors.
  1205. *
  1206. * By default database errors are not shown.
  1207. *
  1208. * @since 0.71
  1209. * @see wpdb::show_errors()
  1210. *
  1211. * @return bool Whether showing of errors was active
  1212. */
  1213. public function hide_errors() {
  1214. $show = $this->show_errors;
  1215. $this->show_errors = false;
  1216. return $show;
  1217. }
  1218. /**
  1219. * Whether to suppress database errors.
  1220. *
  1221. * By default database errors are suppressed, with a simple
  1222. * call to this function they can be enabled.
  1223. *
  1224. * @since 2.5.0
  1225. * @see wpdb::hide_errors()
  1226. * @param bool $suppress Optional. New value. Defaults to true.
  1227. * @return bool Old value
  1228. */
  1229. public function suppress_errors( $suppress = true ) {
  1230. $errors = $this->suppress_errors;
  1231. $this->suppress_errors = (bool) $suppress;
  1232. return $errors;
  1233. }
  1234. /**
  1235. * Kill cached query results.
  1236. *
  1237. * @since 0.71
  1238. */
  1239. public function flush() {
  1240. $this->last_result = array();
  1241. $this->col_info = null;
  1242. $this->last_query = null;
  1243. $this->rows_affected = $this->num_rows = 0;
  1244. $this->last_error = '';
  1245. if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
  1246. mysqli_free_result( $this->result );
  1247. $this->result = null;
  1248. // Sanity check before using the handle
  1249. if ( empty( $this->dbh ) || !( $this->dbh instanceof mysqli ) ) {
  1250. return;
  1251. }
  1252. // Clear out any results from a multi-query
  1253. while ( mysqli_more_results( $this->dbh ) ) {
  1254. mysqli_next_result( $this->dbh );
  1255. }
  1256. } elseif ( is_resource( $this->result ) ) {
  1257. mysql_free_result( $this->result );
  1258. }
  1259. }
  1260. /**
  1261. * Connect to and select database.
  1262. *
  1263. * If $allow_bail is false, the lack of database connection will need
  1264. * to be handled manually.
  1265. *
  1266. * @since 3.0.0
  1267. * @since 3.9.0 $allow_bail parameter added.
  1268. *
  1269. * @param bool $allow_bail Optional. Allows the function to bail. Default true.
  1270. * @return bool True with a successful connection, false on failure.
  1271. */
  1272. public function db_connect( $allow_bail = true ) {
  1273. $this->is_mysql = true;
  1274. /*
  1275. * Deprecated in 3.9+ when using MySQLi. No equivalent
  1276. * $new_link parameter exists for mysqli_* functions.
  1277. */
  1278. $new_link = defined( 'MYSQL_NEW_LINK' ) ? MYSQL_NEW_LINK : true;
  1279. $client_flags = defined( 'MYSQL_CLIENT_FLAGS' ) ? MYSQL_CLIENT_FLAGS : 0;
  1280. if ( $this->use_mysqli ) {
  1281. $this->dbh = mysqli_init();
  1282. // mysqli_real_connect doesn't support the host param including a port or socket
  1283. // like mysql_connect does. This duplicates how mysql_connect detects a port and/or socket file.
  1284. $port = null;
  1285. $socket = null;
  1286. $host = $this->dbhost;
  1287. $port_or_socket = strstr( $host, ':' );
  1288. if ( ! empty( $port_or_socket ) ) {
  1289. $host = substr( $host, 0, strpos( $host, ':' ) );
  1290. $port_or_socket = substr( $port_or_socket, 1 );
  1291. if ( 0 !== strpos( $port_or_socket, '/' ) ) {
  1292. $port = intval( $port_or_socket );
  1293. $maybe_socket = strstr( $port_or_socket, ':' );
  1294. if ( ! empty( $maybe_socket ) ) {
  1295. $socket = substr( $maybe_socket, 1 );
  1296. }
  1297. } else {
  1298. $socket = $port_or_socket;
  1299. }
  1300. }
  1301. if ( WP_DEBUG ) {
  1302. mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
  1303. } else {
  1304. @mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
  1305. }
  1306. if ( $this->dbh->connect_errno ) {
  1307. $this->dbh = null;
  1308. /* It's possible ext/mysqli is misconfigured. Fall back to ext/mysql if:
  1309. * - We haven't previously connected, and
  1310. * - WP_USE_EXT_MYSQL isn't set to false, and
  1311. * - ext/mysql is loaded.
  1312. */
  1313. $attempt_fallback = true;
  1314. if ( $this->has_connected ) {
  1315. $attempt_fallback = false;
  1316. } elseif ( defined( 'WP_USE_EXT_MYSQL' ) && ! WP_USE_EXT_MYSQL ) {
  1317. $attempt_fallback = false;
  1318. } elseif ( ! function_exists( 'mysql_connect' ) ) {
  1319. $attempt_fallback = false;
  1320. }
  1321. if ( $attempt_fallback ) {
  1322. $this->use_mysqli = false;
  1323. $this->db_connect();
  1324. }
  1325. }
  1326. } else {
  1327. if ( WP_DEBUG ) {
  1328. $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
  1329. } else {
  1330. $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
  1331. }
  1332. }
  1333. if ( ! $this->dbh && $allow_bail ) {
  1334. wp_load_translations_early();
  1335. // Load custom DB error template, if present.
  1336. if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
  1337. require_once( WP_CONTENT_DIR . '/db-error.php' );
  1338. die();
  1339. }
  1340. $this->bail( sprintf( __( "
  1341. <h1>Error establishing a database connection</h1>
  1342. <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>
  1343. <ul>
  1344. <li>Are you sure you have the correct username and password?</li>
  1345. <li>Are you sure that you have typed the correct hostname?</li>
  1346. <li>Are you sure that the database server is running?</li>
  1347. </ul>
  1348. <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>
  1349. " ), htmlspecialchars( $this->dbhost, ENT_QUOTES ) ), 'db_connect_fail' );
  1350. return false;
  1351. } elseif ( $this->dbh ) {
  1352. if ( ! $this->has_connected ) {
  1353. $this->init_charset();
  1354. }
  1355. $this->has_connected = true;
  1356. $this->set_charset( $this->dbh );
  1357. $this->ready = true;
  1358. $this->set_sql_mode();
  1359. $this->select( $this->dbname, $this->dbh );
  1360. return true;
  1361. }
  1362. return false;
  1363. }
  1364. /**
  1365. * Check that the connection to the database is still up. If not, try to reconnect.
  1366. *
  1367. * If this function is unable to reconnect, it will forcibly die, or if after the
  1368. * the template_redirect hook has been fired, return false instead.
  1369. *
  1370. * If $allow_bail is false, the lack of database connection will need
  1371. * to be handled manually.
  1372. *
  1373. * @since 3.9.0
  1374. *
  1375. * @param bool $allow_bail Optional. Allows the function to bail. Default true.
  1376. * @return bool|void True if the connection is up.
  1377. */
  1378. public function check_connection( $allow_bail = true ) {
  1379. if ( $this->use_mysqli ) {
  1380. if ( @mysqli_ping( $this->dbh ) ) {
  1381. return true;
  1382. }
  1383. } else {
  1384. if ( @mysql_ping( $this->dbh ) ) {
  1385. return true;
  1386. }
  1387. }
  1388. $error_reporting = false;
  1389. // Disable warnings, as we don't want to see a multitude of "unable to connect" messages
  1390. if ( WP_DEBUG ) {
  1391. $error_reporting = error_reporting();
  1392. error_reporting( $error_reporting & ~E_WARNING );
  1393. }
  1394. for ( $tries = 1; $tries <= $this->reconnect_retries; $tries++ ) {
  1395. // On the last try, re-enable warnings. We want to see a single instance of the
  1396. // "unable to connect" message on the bail() screen, if it appears.
  1397. if ( $this->reconnect_retries === $tries && WP_DEBUG ) {
  1398. error_reporting( $error_reporting );
  1399. }
  1400. if ( $this->db_connect( false ) ) {
  1401. if ( $error_reporting ) {
  1402. error_reporting( $error_reporting );
  1403. }
  1404. return true;
  1405. }
  1406. sleep( 1 );
  1407. }
  1408. // If template_redirect has already happened, it's too late for wp_die()/dead_db().
  1409. // Let's just return and hope for the best.
  1410. if ( did_action( 'template_redirect' ) ) {
  1411. return false;
  1412. }
  1413. if ( ! $allow_bail ) {
  1414. return false;
  1415. }
  1416. // We weren't able to reconnect, so we better bail.
  1417. $this->bail( sprintf( ( "
  1418. <h1>Error reconnecting to the database</h1>
  1419. <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>
  1420. <ul>
  1421. <li>Are you sure that the database server is running?</li>
  1422. <li>Are you sure that the database server is not under particularly heavy load?</li>
  1423. </ul>
  1424. <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>
  1425. " ), htmlspecialchars( $this->dbhost, ENT_QUOTES ) ), 'db_connect_fail' );
  1426. // Call dead_db() if bail didn't die, because this database is no more. It has ceased to be (at least temporarily).
  1427. dead_db();
  1428. }
  1429. /**
  1430. * Perform a MySQL database query, using current database connection.
  1431. *
  1432. * More information can be found on the codex page.
  1433. *
  1434. * @since 0.71
  1435. *
  1436. * @param string $query Database query
  1437. * @return int|false Number of rows affected/selected or false on error
  1438. */
  1439. public function query( $query ) {
  1440. if ( ! $this->ready ) {
  1441. $this->check_current_query = true;
  1442. return false;
  1443. }
  1444. /**
  1445. * Filter the database query.
  1446. *
  1447. * Some queries are made before the plugins have been loaded,
  1448. * and thus cannot be filtered with this method.
  1449. *
  1450. * @since 2.1.0
  1451. *
  1452. * @param string $query Database query.
  1453. */
  1454. $query = apply_filters( 'query', $query );
  1455. $this->flush();
  1456. // Log how the function was called
  1457. $this->func_call = "\$db->query(\"$query\")";
  1458. // If we're writing to the database, make sure the query will write safely.
  1459. if ( $this->check_current_query && ! $this->check_ascii( $query ) ) {
  1460. $stripped_query = $this->strip_invalid_text_from_query( $query );
  1461. // strip_invalid_text_from_query() can perform queries, so we need
  1462. // to flush again, just to make sure everything is clear.
  1463. $this->flush();
  1464. if ( $stripped_query !== $query ) {
  1465. $this->insert_id = 0;
  1466. return false;
  1467. }
  1468. }
  1469. $this->check_current_query = true;
  1470. // Keep track of the last query for debug..
  1471. $this->last_query = $query;
  1472. $this->_do_query( $query );
  1473. // MySQL server has gone away, try to reconnect
  1474. $mysql_errno = 0;
  1475. if ( ! empty( $this->dbh ) ) {
  1476. if ( $this->use_mysqli ) {
  1477. $mysql_errno = mysqli_errno( $this->dbh );
  1478. } else {
  1479. $mysql_errno = mysql_errno( $this->dbh );
  1480. }
  1481. }
  1482. if ( empty( $this->dbh ) || 2006 == $mysql_errno ) {
  1483. if ( $this->check_connection() ) {
  1484. $this->_do_query( $query );
  1485. } else {
  1486. $this->insert_id = 0;
  1487. return false;
  1488. }
  1489. }
  1490. // If there is an error then take note of it..
  1491. if ( $this->use_mysqli ) {
  1492. $this->last_error = mysqli_error( $this->dbh );
  1493. } else {
  1494. $this->last_error = mysql_error( $this->dbh );
  1495. }
  1496. if ( $this->last_error ) {
  1497. // Clear insert_id on a subsequent failed insert.
  1498. if ( $this->insert_id && preg_match( '/^\s*(insert|replace)\s/i', $query ) )
  1499. $this->insert_id = 0;
  1500. $this->print_error();
  1501. return false;
  1502. }
  1503. if ( preg_match( '/^\s*(create|alter|truncate|drop)\s/i', $query ) ) {
  1504. $return_val = $this->result;
  1505. } elseif ( preg_match( '/^\s*(insert|delete|update|replace)\s/i', $query ) ) {
  1506. if ( $this->use_mysqli ) {
  1507. $this->rows_affected = mysqli_affected_rows( $this->dbh );
  1508. } else {
  1509. $this->rows_affected = mysql_affected_rows( $this->dbh );
  1510. }
  1511. // Take note of the insert_id
  1512. if ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
  1513. if ( $this->use_mysqli ) {
  1514. $this->insert_id = mysqli_insert_id( $this->dbh );
  1515. } else {
  1516. $this->insert_id = mysql_insert_id( $this->dbh );
  1517. }
  1518. }
  1519. // Return number of rows affected
  1520. $return_val = $this->rows_affected;
  1521. } else {
  1522. $num_rows = 0;
  1523. if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
  1524. while ( $row = @mysqli_fetch_object( $this->result ) ) {
  1525. $this->last_result[$num_rows] = $row;
  1526. $num_rows++;
  1527. }
  1528. } elseif ( is_resource( $this->result ) ) {
  1529. while ( $row = @mysql_fetch_object( $this->result ) ) {
  1530. $this->last_result[$num_rows] = $row;
  1531. $num_rows++;
  1532. }
  1533. }
  1534. // Log number of rows the query returned
  1535. // and return number of rows selected
  1536. $this->num_rows = $num_rows;
  1537. $return_val = $num_rows;
  1538. }
  1539. return $return_val;
  1540. }
  1541. /**
  1542. * Internal function to perform the mysql_query() call.
  1543. *
  1544. * @since 3.9.0
  1545. *
  1546. * @access private
  1547. * @see wpdb::query()
  1548. *
  1549. * @param string $query The query to run.
  1550. */
  1551. private function _do_query( $query ) {
  1552. if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
  1553. $this->timer_start();
  1554. }
  1555. if ( $this->use_mysqli ) {
  1556. $this->result = @mysqli_query( $this->dbh, $query );
  1557. } else {
  1558. $this->result = @mysql_query( $query, $this->dbh );
  1559. }
  1560. $this->num_queries++;
  1561. if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
  1562. $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
  1563. }
  1564. }
  1565. /**
  1566. * Insert a row into a table.
  1567. *
  1568. * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
  1569. * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
  1570. *
  1571. * @since 2.5.0
  1572. * @see wpdb::prepare()
  1573. * @see wpdb::$field_types
  1574. * @see wp_set_wpdb_vars()
  1575. *
  1576. * @param string $table Table name
  1577. * @param array $data Data to insert (in column => value pairs).
  1578. * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  1579. * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
  1580. * If string, that format will be used for all of the values in $data.
  1581. * A format is one of '%d', '%f', '%s' (integer, float, string).
  1582. * If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
  1583. * @return int|false The number of rows inserted, or false on error.
  1584. */
  1585. public function insert( $table, $data, $format = null ) {
  1586. return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
  1587. }
  1588. /**
  1589. * Replace a row into a table.
  1590. *
  1591. * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
  1592. * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
  1593. *
  1594. * @since 3.0.0
  1595. * @see wpdb::prepare()
  1596. * @see wpdb::$field_types
  1597. * @see wp_set_wpdb_vars()
  1598. *
  1599. * @param string $table Table name
  1600. * @param array $data Data to insert (in column => value pairs).
  1601. * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  1602. * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
  1603. * If string, that format will be used for all of the values in $data.
  1604. * A format is one of '%d', '%f', '%s' (integer, float, string).
  1605. * If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
  1606. * @return int|false The number of rows affected, or false on error.
  1607. */
  1608. public function replace( $table, $data, $format = null ) {
  1609. return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
  1610. }
  1611. /**
  1612. * Helper function for insert and replace.
  1613. *
  1614. * Runs an insert or replace query based on $type argument.
  1615. *
  1616. * @access private
  1617. * @since 3.0.0
  1618. * @see wpdb::prepare()
  1619. * @see wpdb::$field_types
  1620. * @see wp_set_wpdb_vars()
  1621. *
  1622. * @param string $table Table name
  1623. * @param array $data Data to insert (in column => value pairs).
  1624. * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  1625. * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data.
  1626. * If string, that format will be used for all of the values in $data.
  1627. * A format is one of '%d', '%f', '%s' (integer, float, string).
  1628. * If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
  1629. * @param string $type Optional. What type of operation is this? INSERT or REPLACE. Defaults to INSERT.
  1630. * @return int|false The number of rows affected, or false on error.
  1631. */
  1632. function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
  1633. $this->insert_id = 0;
  1634. if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) ) {
  1635. return false;
  1636. }
  1637. $data = $this->process_fields( $table, $data, $format );
  1638. if ( false === $data ) {
  1639. return false;
  1640. }
  1641. $formats = $values = array();
  1642. foreach ( $data as $value ) {
  1643. $formats[] = $value['format'];
  1644. $values[] = $value['value'];
  1645. }
  1646. $fields = '`' . implode( '`, `', array_keys( $data ) ) . '`';
  1647. $formats = implode( ', ', $formats );
  1648. $sql = "$type INTO `$table` ($fields) VALUES ($formats)";
  1649. $this->check_current_query = false;
  1650. return $this->query( $this->prepare( $sql, $values ) );
  1651. }
  1652. /**
  1653. * Update a row in the table
  1654. *
  1655. * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
  1656. * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
  1657. *
  1658. * @since 2.5.0
  1659. * @see wpdb::prepare()
  1660. * @see wpdb::$field_types
  1661. * @see wp_set_wpdb_vars()
  1662. *
  1663. * @param string $table Table name
  1664. * @param array $data Data to update (in column => value pairs).
  1665. * Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  1666. * @param array $where A named array of WHERE clauses (in column => value pairs).
  1667. * Multiple clauses will be joined with ANDs.
  1668. * Both $where columns and $where values should be "raw".
  1669. * @param array|string $format Optional. An array of formats to be mapped to each of the values in $data.
  1670. * If string, that format will be used for all of the values in $data.
  1671. * A format is one of '%d', '%f', '%s' (integer, float, string).
  1672. * If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
  1673. * @param array|string $where_format Opt…

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