PageRenderTime 64ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/old/wp-includes/wp-db.php

https://bitbucket.org/reareaf/blubberwasser-com
PHP | 3430 lines | 1680 code | 396 blank | 1354 comment | 359 complexity | 763ab7190021ef175121303a61dcd568 MD5 | raw file
Possible License(s): Apache-2.0, BSD-3-Clause, MIT

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

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