PageRenderTime 71ms CodeModel.GetById 15ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/wp-db.php

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

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