PageRenderTime 68ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

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

https://bitbucket.org/stephenharris/stephenharris
PHP | 3105 lines | 1494 code | 332 blank | 1279 comment | 311 complexity | ccc3c9fc31afd42091eace715ccb6ad5 MD5 | raw file
  1. <?php
  2. /**
  3. * WordPress DB Class
  4. *
  5. * Original code from {@link http://php.justinvincent.com Justin Vincent (justin@visunet.ie)}
  6. *
  7. * @package WordPress
  8. * @subpackage Database
  9. * @since 0.71
  10. */
  11. /**
  12. * @since 0.71
  13. */
  14. define( 'EZSQL_VERSION', 'WP1.25' );
  15. /**
  16. * @since 0.71
  17. */
  18. define( 'OBJECT', 'OBJECT' );
  19. define( 'object', 'OBJECT' ); // Back compat.
  20. /**
  21. * @since 2.5.0
  22. */
  23. define( 'OBJECT_K', 'OBJECT_K' );
  24. /**
  25. * @since 0.71
  26. */
  27. define( 'ARRAY_A', 'ARRAY_A' );
  28. /**
  29. * @since 0.71
  30. */
  31. define( 'ARRAY_N', 'ARRAY_N' );
  32. /**
  33. * WordPress Database Access Abstraction Object
  34. *
  35. * It is possible to replace this class with your own
  36. * by setting the $wpdb global variable in wp-content/db.php
  37. * file to your class. The wpdb class will still be included,
  38. * so you can extend it or simply use your own.
  39. *
  40. * @link https://codex.wordpress.org/Function_Reference/wpdb_Class
  41. *
  42. * @package WordPress
  43. * @subpackage Database
  44. * @since 0.71
  45. */
  46. class wpdb {
  47. /**
  48. * Whether to show SQL/DB errors.
  49. *
  50. * Default behavior is to show errors if both WP_DEBUG and WP_DEBUG_DISPLAY
  51. * evaluated to true.
  52. *
  53. * @since 0.71
  54. * @access private
  55. * @var bool
  56. */
  57. var $show_errors = false;
  58. /**
  59. * Whether to suppress errors during the DB bootstrapping.
  60. *
  61. * @access private
  62. * @since 2.5.0
  63. * @var bool
  64. */
  65. var $suppress_errors = false;
  66. /**
  67. * The last error during query.
  68. *
  69. * @since 2.5.0
  70. * @var string
  71. */
  72. public $last_error = '';
  73. /**
  74. * Amount of queries made
  75. *
  76. * @since 1.2.0
  77. * @access private
  78. * @var int
  79. */
  80. var $num_queries = 0;
  81. /**
  82. * Count of rows returned by previous query
  83. *
  84. * @since 0.71
  85. * @access private
  86. * @var int
  87. */
  88. var $num_rows = 0;
  89. /**
  90. * Count of affected rows by previous query
  91. *
  92. * @since 0.71
  93. * @access private
  94. * @var int
  95. */
  96. var $rows_affected = 0;
  97. /**
  98. * The ID generated for an AUTO_INCREMENT column by the previous query (usually INSERT).
  99. *
  100. * @since 0.71
  101. * @access public
  102. * @var int
  103. */
  104. var $insert_id = 0;
  105. /**
  106. * Last query made
  107. *
  108. * @since 0.71
  109. * @access private
  110. * @var array
  111. */
  112. var $last_query;
  113. /**
  114. * Results of the last query made
  115. *
  116. * @since 0.71
  117. * @access private
  118. * @var array|null
  119. */
  120. var $last_result;
  121. /**
  122. * MySQL result, which is either a resource or boolean.
  123. *
  124. * @since 0.71
  125. * @access protected
  126. * @var mixed
  127. */
  128. protected $result;
  129. /**
  130. * Cached column info, for sanity checking data before inserting
  131. *
  132. * @since 4.2.0
  133. * @access protected
  134. * @var array
  135. */
  136. protected $col_meta = array();
  137. /**
  138. * Calculated character sets on tables
  139. *
  140. * @since 4.2.0
  141. * @access protected
  142. * @var array
  143. */
  144. protected $table_charset = array();
  145. /**
  146. * Whether text fields in the current query need to be sanity checked.
  147. *
  148. * @since 4.2.0
  149. * @access protected
  150. * @var bool
  151. */
  152. protected $check_current_query = true;
  153. /**
  154. * Flag to ensure we don't run into recursion problems when checking the collation.
  155. *
  156. * @since 4.2.0
  157. * @access private
  158. * @see wpdb::check_safe_collation()
  159. * @var boolean
  160. */
  161. private $checking_collation = false;
  162. /**
  163. * Saved info on the table column
  164. *
  165. * @since 0.71
  166. * @access protected
  167. * @var array
  168. */
  169. protected $col_info;
  170. /**
  171. * Saved queries that were executed
  172. *
  173. * @since 1.5.0
  174. * @access private
  175. * @var array
  176. */
  177. var $queries;
  178. /**
  179. * The number of times to retry reconnecting before dying.
  180. *
  181. * @since 3.9.0
  182. * @access protected
  183. * @see wpdb::check_connection()
  184. * @var int
  185. */
  186. protected $reconnect_retries = 5;
  187. /**
  188. * WordPress table prefix
  189. *
  190. * You can set this to have multiple WordPress installations
  191. * in a single database. The second reason is for possible
  192. * security precautions.
  193. *
  194. * @since 2.5.0
  195. * @access private
  196. * @var string
  197. */
  198. var $prefix = '';
  199. /**
  200. * WordPress base table prefix.
  201. *
  202. * @since 3.0.0
  203. * @access public
  204. * @var string
  205. */
  206. public $base_prefix;
  207. /**
  208. * Whether the database queries are ready to start executing.
  209. *
  210. * @since 2.3.2
  211. * @access private
  212. * @var bool
  213. */
  214. var $ready = false;
  215. /**
  216. * Blog ID.
  217. *
  218. * @since 3.0.0
  219. * @access public
  220. * @var int
  221. */
  222. public $blogid = 0;
  223. /**
  224. * Site ID.
  225. *
  226. * @since 3.0.0
  227. * @access public
  228. * @var int
  229. */
  230. public $siteid = 0;
  231. /**
  232. * List of WordPress per-blog tables
  233. *
  234. * @since 2.5.0
  235. * @access private
  236. * @see wpdb::tables()
  237. * @var array
  238. */
  239. var $tables = array( 'posts', 'comments', 'links', 'options', 'postmeta',
  240. 'terms', 'term_taxonomy', 'term_relationships', 'commentmeta' );
  241. /**
  242. * List of deprecated WordPress tables
  243. *
  244. * categories, post2cat, and link2cat were deprecated in 2.3.0, db version 5539
  245. *
  246. * @since 2.9.0
  247. * @access private
  248. * @see wpdb::tables()
  249. * @var array
  250. */
  251. var $old_tables = array( 'categories', 'post2cat', 'link2cat' );
  252. /**
  253. * List of WordPress global tables
  254. *
  255. * @since 3.0.0
  256. * @access private
  257. * @see wpdb::tables()
  258. * @var array
  259. */
  260. var $global_tables = array( 'users', 'usermeta' );
  261. /**
  262. * List of Multisite global tables
  263. *
  264. * @since 3.0.0
  265. * @access private
  266. * @see wpdb::tables()
  267. * @var array
  268. */
  269. var $ms_global_tables = array( 'blogs', 'signups', 'site', 'sitemeta',
  270. 'sitecategories', 'registration_log', 'blog_versions' );
  271. /**
  272. * WordPress Comments table
  273. *
  274. * @since 1.5.0
  275. * @access public
  276. * @var string
  277. */
  278. public $comments;
  279. /**
  280. * WordPress Comment Metadata table
  281. *
  282. * @since 2.9.0
  283. * @access public
  284. * @var string
  285. */
  286. public $commentmeta;
  287. /**
  288. * WordPress Links table
  289. *
  290. * @since 1.5.0
  291. * @access public
  292. * @var string
  293. */
  294. public $links;
  295. /**
  296. * WordPress Options table
  297. *
  298. * @since 1.5.0
  299. * @access public
  300. * @var string
  301. */
  302. public $options;
  303. /**
  304. * WordPress Post Metadata table
  305. *
  306. * @since 1.5.0
  307. * @access public
  308. * @var string
  309. */
  310. public $postmeta;
  311. /**
  312. * WordPress Posts table
  313. *
  314. * @since 1.5.0
  315. * @access public
  316. * @var string
  317. */
  318. public $posts;
  319. /**
  320. * WordPress Terms table
  321. *
  322. * @since 2.3.0
  323. * @access public
  324. * @var string
  325. */
  326. public $terms;
  327. /**
  328. * WordPress Term Relationships table
  329. *
  330. * @since 2.3.0
  331. * @access public
  332. * @var string
  333. */
  334. public $term_relationships;
  335. /**
  336. * WordPress Term Taxonomy table
  337. *
  338. * @since 2.3.0
  339. * @access public
  340. * @var string
  341. */
  342. public $term_taxonomy;
  343. /*
  344. * Global and Multisite tables
  345. */
  346. /**
  347. * WordPress User Metadata table
  348. *
  349. * @since 2.3.0
  350. * @access public
  351. * @var string
  352. */
  353. public $usermeta;
  354. /**
  355. * WordPress Users table
  356. *
  357. * @since 1.5.0
  358. * @access public
  359. * @var string
  360. */
  361. public $users;
  362. /**
  363. * Multisite Blogs table
  364. *
  365. * @since 3.0.0
  366. * @access public
  367. * @var string
  368. */
  369. public $blogs;
  370. /**
  371. * Multisite Blog Versions table
  372. *
  373. * @since 3.0.0
  374. * @access public
  375. * @var string
  376. */
  377. public $blog_versions;
  378. /**
  379. * Multisite Registration Log table
  380. *
  381. * @since 3.0.0
  382. * @access public
  383. * @var string
  384. */
  385. public $registration_log;
  386. /**
  387. * Multisite Signups table
  388. *
  389. * @since 3.0.0
  390. * @access public
  391. * @var string
  392. */
  393. public $signups;
  394. /**
  395. * Multisite Sites table
  396. *
  397. * @since 3.0.0
  398. * @access public
  399. * @var string
  400. */
  401. public $site;
  402. /**
  403. * Multisite Sitewide Terms table
  404. *
  405. * @since 3.0.0
  406. * @access public
  407. * @var string
  408. */
  409. public $sitecategories;
  410. /**
  411. * Multisite Site Metadata table
  412. *
  413. * @since 3.0.0
  414. * @access public
  415. * @var string
  416. */
  417. public $sitemeta;
  418. /**
  419. * Format specifiers for DB columns. Columns not listed here default to %s. Initialized during WP load.
  420. *
  421. * Keys are column names, values are format types: 'ID' => '%d'
  422. *
  423. * @since 2.8.0
  424. * @see wpdb::prepare()
  425. * @see wpdb::insert()
  426. * @see wpdb::update()
  427. * @see wpdb::delete()
  428. * @see wp_set_wpdb_vars()
  429. * @access public
  430. * @var array
  431. */
  432. public $field_types = array();
  433. /**
  434. * Database table columns charset
  435. *
  436. * @since 2.2.0
  437. * @access public
  438. * @var string
  439. */
  440. public $charset;
  441. /**
  442. * Database table columns collate
  443. *
  444. * @since 2.2.0
  445. * @access public
  446. * @var string
  447. */
  448. public $collate;
  449. /**
  450. * Database Username
  451. *
  452. * @since 2.9.0
  453. * @access protected
  454. * @var string
  455. */
  456. protected $dbuser;
  457. /**
  458. * Database Password
  459. *
  460. * @since 3.1.0
  461. * @access protected
  462. * @var string
  463. */
  464. protected $dbpassword;
  465. /**
  466. * Database Name
  467. *
  468. * @since 3.1.0
  469. * @access protected
  470. * @var string
  471. */
  472. protected $dbname;
  473. /**
  474. * Database Host
  475. *
  476. * @since 3.1.0
  477. * @access protected
  478. * @var string
  479. */
  480. protected $dbhost;
  481. /**
  482. * Database Handle
  483. *
  484. * @since 0.71
  485. * @access protected
  486. * @var string
  487. */
  488. protected $dbh;
  489. /**
  490. * A textual description of the last query/get_row/get_var call
  491. *
  492. * @since 3.0.0
  493. * @access public
  494. * @var string
  495. */
  496. public $func_call;
  497. /**
  498. * Whether MySQL is used as the database engine.
  499. *
  500. * Set in WPDB::db_connect() to true, by default. This is used when checking
  501. * against the required MySQL version for WordPress. Normally, a replacement
  502. * database drop-in (db.php) will skip these checks, but setting this to true
  503. * will force the checks to occur.
  504. *
  505. * @since 3.3.0
  506. * @access public
  507. * @var bool
  508. */
  509. public $is_mysql = null;
  510. /**
  511. * A list of incompatible SQL modes.
  512. *
  513. * @since 3.9.0
  514. * @access protected
  515. * @var array
  516. */
  517. protected $incompatible_modes = array( 'NO_ZERO_DATE', 'ONLY_FULL_GROUP_BY',
  518. 'STRICT_TRANS_TABLES', 'STRICT_ALL_TABLES', 'TRADITIONAL' );
  519. /**
  520. * Whether to use mysqli over mysql.
  521. *
  522. * @since 3.9.0
  523. * @access private
  524. * @var bool
  525. */
  526. private $use_mysqli = false;
  527. /**
  528. * Whether we've managed to successfully connect at some point
  529. *
  530. * @since 3.9.0
  531. * @access private
  532. * @var bool
  533. */
  534. private $has_connected = false;
  535. /**
  536. * Connects to the database server and selects a database
  537. *
  538. * PHP5 style constructor for compatibility with PHP5. Does
  539. * the actual setting up of the class properties and connection
  540. * to the database.
  541. *
  542. * @link https://core.trac.wordpress.org/ticket/3354
  543. * @since 2.0.8
  544. *
  545. * @param string $dbuser MySQL database user
  546. * @param string $dbpassword MySQL database password
  547. * @param string $dbname MySQL database name
  548. * @param string $dbhost MySQL database host
  549. */
  550. public function __construct( $dbuser, $dbpassword, $dbname, $dbhost ) {
  551. register_shutdown_function( array( $this, '__destruct' ) );
  552. if ( WP_DEBUG && WP_DEBUG_DISPLAY )
  553. $this->show_errors();
  554. /* Use ext/mysqli if it exists and:
  555. * - WP_USE_EXT_MYSQL is defined as false, or
  556. * - We are a development version of WordPress, or
  557. * - We are running PHP 5.5 or greater, or
  558. * - ext/mysql is not loaded.
  559. */
  560. if ( function_exists( 'mysqli_connect' ) ) {
  561. if ( defined( 'WP_USE_EXT_MYSQL' ) ) {
  562. $this->use_mysqli = ! WP_USE_EXT_MYSQL;
  563. } elseif ( version_compare( phpversion(), '5.5', '>=' ) || ! function_exists( 'mysql_connect' ) ) {
  564. $this->use_mysqli = true;
  565. } elseif ( false !== strpos( $GLOBALS['wp_version'], '-' ) ) {
  566. $this->use_mysqli = true;
  567. }
  568. }
  569. $this->dbuser = $dbuser;
  570. $this->dbpassword = $dbpassword;
  571. $this->dbname = $dbname;
  572. $this->dbhost = $dbhost;
  573. // wp-config.php creation will manually connect when ready.
  574. if ( defined( 'WP_SETUP_CONFIG' ) ) {
  575. return;
  576. }
  577. $this->db_connect();
  578. }
  579. /**
  580. * PHP5 style destructor and will run when database object is destroyed.
  581. *
  582. * @see wpdb::__construct()
  583. * @since 2.0.8
  584. * @return bool true
  585. */
  586. public function __destruct() {
  587. return true;
  588. }
  589. /**
  590. * PHP5 style magic getter, used to lazy-load expensive data.
  591. *
  592. * @since 3.5.0
  593. *
  594. * @param string $name The private member to get, and optionally process
  595. * @return mixed The private member
  596. */
  597. public function __get( $name ) {
  598. if ( 'col_info' === $name )
  599. $this->load_col_info();
  600. return $this->$name;
  601. }
  602. /**
  603. * Magic function, for backwards compatibility.
  604. *
  605. * @since 3.5.0
  606. *
  607. * @param string $name The private member to set
  608. * @param mixed $value The value to set
  609. */
  610. public function __set( $name, $value ) {
  611. $protected_members = array(
  612. 'col_meta',
  613. 'table_charset',
  614. 'check_current_query',
  615. );
  616. if ( in_array( $name, $protected_members, true ) ) {
  617. return;
  618. }
  619. $this->$name = $value;
  620. }
  621. /**
  622. * Magic function, for backwards compatibility.
  623. *
  624. * @since 3.5.0
  625. *
  626. * @param string $name The private member to check
  627. *
  628. * @return bool If the member is set or not
  629. */
  630. public function __isset( $name ) {
  631. return isset( $this->$name );
  632. }
  633. /**
  634. * Magic function, for backwards compatibility.
  635. *
  636. * @since 3.5.0
  637. *
  638. * @param string $name The private member to unset
  639. */
  640. public function __unset( $name ) {
  641. unset( $this->$name );
  642. }
  643. /**
  644. * Set $this->charset and $this->collate
  645. *
  646. * @since 3.1.0
  647. */
  648. public function init_charset() {
  649. if ( function_exists('is_multisite') && is_multisite() ) {
  650. $this->charset = 'utf8';
  651. if ( defined( 'DB_COLLATE' ) && DB_COLLATE ) {
  652. $this->collate = DB_COLLATE;
  653. } else {
  654. $this->collate = 'utf8_general_ci';
  655. }
  656. } elseif ( defined( 'DB_COLLATE' ) ) {
  657. $this->collate = DB_COLLATE;
  658. }
  659. if ( defined( 'DB_CHARSET' ) ) {
  660. $this->charset = DB_CHARSET;
  661. }
  662. if ( ( $this->use_mysqli && ! ( $this->dbh instanceof mysqli ) )
  663. || ( empty( $this->dbh ) || ! ( $this->dbh instanceof mysqli ) ) ) {
  664. return;
  665. }
  666. if ( 'utf8' === $this->charset && $this->has_cap( 'utf8mb4' ) ) {
  667. $this->charset = 'utf8mb4';
  668. }
  669. if ( 'utf8mb4' === $this->charset && ( ! $this->collate || stripos( $this->collate, 'utf8_' ) === 0 ) ) {
  670. $this->collate = 'utf8mb4_unicode_ci';
  671. }
  672. }
  673. /**
  674. * Sets the connection's character set.
  675. *
  676. * @since 3.1.0
  677. *
  678. * @param resource $dbh The resource given by mysql_connect
  679. * @param string $charset Optional. The character set. Default null.
  680. * @param string $collate Optional. The collation. Default null.
  681. */
  682. public function set_charset( $dbh, $charset = null, $collate = null ) {
  683. if ( ! isset( $charset ) )
  684. $charset = $this->charset;
  685. if ( ! isset( $collate ) )
  686. $collate = $this->collate;
  687. if ( $this->has_cap( 'collation' ) && ! empty( $charset ) ) {
  688. if ( $this->use_mysqli ) {
  689. if ( function_exists( 'mysqli_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
  690. mysqli_set_charset( $dbh, $charset );
  691. } else {
  692. $query = $this->prepare( 'SET NAMES %s', $charset );
  693. if ( ! empty( $collate ) )
  694. $query .= $this->prepare( ' COLLATE %s', $collate );
  695. mysqli_query( $dbh, $query );
  696. }
  697. } else {
  698. if ( function_exists( 'mysql_set_charset' ) && $this->has_cap( 'set_charset' ) ) {
  699. mysql_set_charset( $charset, $dbh );
  700. } else {
  701. $query = $this->prepare( 'SET NAMES %s', $charset );
  702. if ( ! empty( $collate ) )
  703. $query .= $this->prepare( ' COLLATE %s', $collate );
  704. mysql_query( $query, $dbh );
  705. }
  706. }
  707. }
  708. }
  709. /**
  710. * Change the current SQL mode, and ensure its WordPress compatibility.
  711. *
  712. * If no modes are passed, it will ensure the current MySQL server
  713. * modes are compatible.
  714. *
  715. * @since 3.9.0
  716. *
  717. * @param array $modes Optional. A list of SQL modes to set.
  718. */
  719. public function set_sql_mode( $modes = array() ) {
  720. if ( empty( $modes ) ) {
  721. if ( $this->use_mysqli ) {
  722. $res = mysqli_query( $this->dbh, 'SELECT @@SESSION.sql_mode' );
  723. } else {
  724. $res = mysql_query( 'SELECT @@SESSION.sql_mode', $this->dbh );
  725. }
  726. if ( empty( $res ) ) {
  727. return;
  728. }
  729. if ( $this->use_mysqli ) {
  730. $modes_array = mysqli_fetch_array( $res );
  731. if ( empty( $modes_array[0] ) ) {
  732. return;
  733. }
  734. $modes_str = $modes_array[0];
  735. } else {
  736. $modes_str = mysql_result( $res, 0 );
  737. }
  738. if ( empty( $modes_str ) ) {
  739. return;
  740. }
  741. $modes = explode( ',', $modes_str );
  742. }
  743. $modes = array_change_key_case( $modes, CASE_UPPER );
  744. /**
  745. * Filter the list of incompatible SQL modes to exclude.
  746. *
  747. * @since 3.9.0
  748. *
  749. * @param array $incompatible_modes An array of incompatible modes.
  750. */
  751. $incompatible_modes = (array) apply_filters( 'incompatible_sql_modes', $this->incompatible_modes );
  752. foreach( $modes as $i => $mode ) {
  753. if ( in_array( $mode, $incompatible_modes ) ) {
  754. unset( $modes[ $i ] );
  755. }
  756. }
  757. $modes_str = implode( ',', $modes );
  758. if ( $this->use_mysqli ) {
  759. mysqli_query( $this->dbh, "SET SESSION sql_mode='$modes_str'" );
  760. } else {
  761. mysql_query( "SET SESSION sql_mode='$modes_str'", $this->dbh );
  762. }
  763. }
  764. /**
  765. * Sets the table prefix for the WordPress tables.
  766. *
  767. * @since 2.5.0
  768. *
  769. * @param string $prefix Alphanumeric name for the new prefix.
  770. * @param bool $set_table_names Optional. Whether the table names, e.g. wpdb::$posts, should be updated or not.
  771. * @return string|WP_Error Old prefix or WP_Error on error
  772. */
  773. public function set_prefix( $prefix, $set_table_names = true ) {
  774. if ( preg_match( '|[^a-z0-9_]|i', $prefix ) )
  775. return new WP_Error('invalid_db_prefix', 'Invalid database prefix' );
  776. $old_prefix = is_multisite() ? '' : $prefix;
  777. if ( isset( $this->base_prefix ) )
  778. $old_prefix = $this->base_prefix;
  779. $this->base_prefix = $prefix;
  780. if ( $set_table_names ) {
  781. foreach ( $this->tables( 'global' ) as $table => $prefixed_table )
  782. $this->$table = $prefixed_table;
  783. if ( is_multisite() && empty( $this->blogid ) )
  784. return $old_prefix;
  785. $this->prefix = $this->get_blog_prefix();
  786. foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
  787. $this->$table = $prefixed_table;
  788. foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
  789. $this->$table = $prefixed_table;
  790. }
  791. return $old_prefix;
  792. }
  793. /**
  794. * Sets blog id.
  795. *
  796. * @since 3.0.0
  797. * @access public
  798. * @param int $blog_id
  799. * @param int $site_id Optional.
  800. * @return int previous blog id
  801. */
  802. public function set_blog_id( $blog_id, $site_id = 0 ) {
  803. if ( ! empty( $site_id ) )
  804. $this->siteid = $site_id;
  805. $old_blog_id = $this->blogid;
  806. $this->blogid = $blog_id;
  807. $this->prefix = $this->get_blog_prefix();
  808. foreach ( $this->tables( 'blog' ) as $table => $prefixed_table )
  809. $this->$table = $prefixed_table;
  810. foreach ( $this->tables( 'old' ) as $table => $prefixed_table )
  811. $this->$table = $prefixed_table;
  812. return $old_blog_id;
  813. }
  814. /**
  815. * Gets blog prefix.
  816. *
  817. * @since 3.0.0
  818. * @param int $blog_id Optional.
  819. * @return string Blog prefix.
  820. */
  821. public function get_blog_prefix( $blog_id = null ) {
  822. if ( is_multisite() ) {
  823. if ( null === $blog_id )
  824. $blog_id = $this->blogid;
  825. $blog_id = (int) $blog_id;
  826. if ( defined( 'MULTISITE' ) && ( 0 == $blog_id || 1 == $blog_id ) )
  827. return $this->base_prefix;
  828. else
  829. return $this->base_prefix . $blog_id . '_';
  830. } else {
  831. return $this->base_prefix;
  832. }
  833. }
  834. /**
  835. * Returns an array of WordPress tables.
  836. *
  837. * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
  838. * override the WordPress users and usermeta tables that would otherwise
  839. * be determined by the prefix.
  840. *
  841. * The scope argument can take one of the following:
  842. *
  843. * 'all' - returns 'all' and 'global' tables. No old tables are returned.
  844. * 'blog' - returns the blog-level tables for the queried blog.
  845. * 'global' - returns the global tables for the installation, returning multisite tables only if running multisite.
  846. * 'ms_global' - returns the multisite global tables, regardless if current installation is multisite.
  847. * 'old' - returns tables which are deprecated.
  848. *
  849. * @since 3.0.0
  850. * @uses wpdb::$tables
  851. * @uses wpdb::$old_tables
  852. * @uses wpdb::$global_tables
  853. * @uses wpdb::$ms_global_tables
  854. *
  855. * @param string $scope Optional. Can be all, global, ms_global, blog, or old tables. Defaults to all.
  856. * @param bool $prefix Optional. Whether to include table prefixes. Default true. If blog
  857. * prefix is requested, then the custom users and usermeta tables will be mapped.
  858. * @param int $blog_id Optional. The blog_id to prefix. Defaults to wpdb::$blogid. Used only when prefix is requested.
  859. * @return array Table names. When a prefix is requested, the key is the unprefixed table name.
  860. */
  861. public function tables( $scope = 'all', $prefix = true, $blog_id = 0 ) {
  862. switch ( $scope ) {
  863. case 'all' :
  864. $tables = array_merge( $this->global_tables, $this->tables );
  865. if ( is_multisite() )
  866. $tables = array_merge( $tables, $this->ms_global_tables );
  867. break;
  868. case 'blog' :
  869. $tables = $this->tables;
  870. break;
  871. case 'global' :
  872. $tables = $this->global_tables;
  873. if ( is_multisite() )
  874. $tables = array_merge( $tables, $this->ms_global_tables );
  875. break;
  876. case 'ms_global' :
  877. $tables = $this->ms_global_tables;
  878. break;
  879. case 'old' :
  880. $tables = $this->old_tables;
  881. break;
  882. default :
  883. return array();
  884. }
  885. if ( $prefix ) {
  886. if ( ! $blog_id )
  887. $blog_id = $this->blogid;
  888. $blog_prefix = $this->get_blog_prefix( $blog_id );
  889. $base_prefix = $this->base_prefix;
  890. $global_tables = array_merge( $this->global_tables, $this->ms_global_tables );
  891. foreach ( $tables as $k => $table ) {
  892. if ( in_array( $table, $global_tables ) )
  893. $tables[ $table ] = $base_prefix . $table;
  894. else
  895. $tables[ $table ] = $blog_prefix . $table;
  896. unset( $tables[ $k ] );
  897. }
  898. if ( isset( $tables['users'] ) && defined( 'CUSTOM_USER_TABLE' ) )
  899. $tables['users'] = CUSTOM_USER_TABLE;
  900. if ( isset( $tables['usermeta'] ) && defined( 'CUSTOM_USER_META_TABLE' ) )
  901. $tables['usermeta'] = CUSTOM_USER_META_TABLE;
  902. }
  903. return $tables;
  904. }
  905. /**
  906. * Selects a database using the current database connection.
  907. *
  908. * The database name will be changed based on the current database
  909. * connection. On failure, the execution will bail and display an DB error.
  910. *
  911. * @since 0.71
  912. *
  913. * @param string $db MySQL database name
  914. * @param resource $dbh Optional link identifier.
  915. * @return null Always null.
  916. */
  917. public function select( $db, $dbh = null ) {
  918. if ( is_null($dbh) )
  919. $dbh = $this->dbh;
  920. if ( $this->use_mysqli ) {
  921. $success = @mysqli_select_db( $dbh, $db );
  922. } else {
  923. $success = @mysql_select_db( $db, $dbh );
  924. }
  925. if ( ! $success ) {
  926. $this->ready = false;
  927. if ( ! did_action( 'template_redirect' ) ) {
  928. wp_load_translations_early();
  929. $this->bail( sprintf( __( '<h1>Can&#8217;t select database</h1>
  930. <p>We were able to connect to the database server (which means your username and password is okay) but not able to select the <code>%1$s</code> database.</p>
  931. <ul>
  932. <li>Are you sure it exists?</li>
  933. <li>Does the user <code>%2$s</code> have permission to use the <code>%1$s</code> database?</li>
  934. <li>On some systems the name of your database is prefixed with your username, so it would be like <code>username_%1$s</code>. Could that be the problem?</li>
  935. </ul>
  936. <p>If you don\'t know how to set up a database you should <strong>contact your host</strong>. If all else fails you may find help at the <a href="https://wordpress.org/support/">WordPress Support Forums</a>.</p>' ), htmlspecialchars( $db, ENT_QUOTES ), htmlspecialchars( $this->dbuser, ENT_QUOTES ) ), 'db_select_fail' );
  937. }
  938. return;
  939. }
  940. }
  941. /**
  942. * Do not use, deprecated.
  943. *
  944. * Use esc_sql() or wpdb::prepare() instead.
  945. *
  946. * @since 2.8.0
  947. * @deprecated 3.6.0
  948. * @see wpdb::prepare
  949. * @see esc_sql()
  950. * @access private
  951. *
  952. * @param string $string
  953. * @return string
  954. */
  955. function _weak_escape( $string ) {
  956. if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) )
  957. _deprecated_function( __METHOD__, '3.6', 'wpdb::prepare() or esc_sql()' );
  958. return addslashes( $string );
  959. }
  960. /**
  961. * Real escape, using mysqli_real_escape_string() or mysql_real_escape_string()
  962. *
  963. * @see mysqli_real_escape_string()
  964. * @see mysql_real_escape_string()
  965. * @since 2.8.0
  966. * @access private
  967. *
  968. * @param string $string to escape
  969. * @return string escaped
  970. */
  971. function _real_escape( $string ) {
  972. if ( $this->dbh ) {
  973. if ( $this->use_mysqli ) {
  974. return mysqli_real_escape_string( $this->dbh, $string );
  975. } else {
  976. return mysql_real_escape_string( $string, $this->dbh );
  977. }
  978. }
  979. $class = get_class( $this );
  980. if ( function_exists( '__' ) ) {
  981. _doing_it_wrong( $class, sprintf( __( '%s must set a database connection for use with escaping.' ), $class ), E_USER_NOTICE );
  982. } else {
  983. _doing_it_wrong( $class, sprintf( '%s must set a database connection for use with escaping.', $class ), E_USER_NOTICE );
  984. }
  985. return addslashes( $string );
  986. }
  987. /**
  988. * Escape data. Works on arrays.
  989. *
  990. * @uses wpdb::_real_escape()
  991. * @since 2.8.0
  992. * @access private
  993. *
  994. * @param string|array $data
  995. * @return string|array escaped
  996. */
  997. function _escape( $data ) {
  998. if ( is_array( $data ) ) {
  999. foreach ( $data as $k => $v ) {
  1000. if ( is_array($v) )
  1001. $data[$k] = $this->_escape( $v );
  1002. else
  1003. $data[$k] = $this->_real_escape( $v );
  1004. }
  1005. } else {
  1006. $data = $this->_real_escape( $data );
  1007. }
  1008. return $data;
  1009. }
  1010. /**
  1011. * Do not use, deprecated.
  1012. *
  1013. * Use esc_sql() or wpdb::prepare() instead.
  1014. *
  1015. * @since 0.71
  1016. * @deprecated 3.6.0
  1017. * @see wpdb::prepare()
  1018. * @see esc_sql()
  1019. *
  1020. * @param mixed $data
  1021. * @return mixed
  1022. */
  1023. public function escape( $data ) {
  1024. if ( func_num_args() === 1 && function_exists( '_deprecated_function' ) )
  1025. _deprecated_function( __METHOD__, '3.6', 'wpdb::prepare() or esc_sql()' );
  1026. if ( is_array( $data ) ) {
  1027. foreach ( $data as $k => $v ) {
  1028. if ( is_array( $v ) )
  1029. $data[$k] = $this->escape( $v, 'recursive' );
  1030. else
  1031. $data[$k] = $this->_weak_escape( $v, 'internal' );
  1032. }
  1033. } else {
  1034. $data = $this->_weak_escape( $data, 'internal' );
  1035. }
  1036. return $data;
  1037. }
  1038. /**
  1039. * Escapes content by reference for insertion into the database, for security
  1040. *
  1041. * @uses wpdb::_real_escape()
  1042. * @since 2.3.0
  1043. * @param string $string to escape
  1044. * @return void
  1045. */
  1046. public function escape_by_ref( &$string ) {
  1047. if ( ! is_float( $string ) )
  1048. $string = $this->_real_escape( $string );
  1049. }
  1050. /**
  1051. * Prepares a SQL query for safe execution. Uses sprintf()-like syntax.
  1052. *
  1053. * The following directives can be used in the query format string:
  1054. * %d (integer)
  1055. * %f (float)
  1056. * %s (string)
  1057. * %% (literal percentage sign - no argument needed)
  1058. *
  1059. * All of %d, %f, and %s are to be left unquoted in the query string and they need an argument passed for them.
  1060. * Literals (%) as parts of the query must be properly written as %%.
  1061. *
  1062. * This function only supports a small subset of the sprintf syntax; it only supports %d (integer), %f (float), and %s (string).
  1063. * Does not support sign, padding, alignment, width or precision specifiers.
  1064. * Does not support argument numbering/swapping.
  1065. *
  1066. * May be called like {@link http://php.net/sprintf sprintf()} or like {@link http://php.net/vsprintf vsprintf()}.
  1067. *
  1068. * Both %d and %s should be left unquoted in the query string.
  1069. *
  1070. * wpdb::prepare( "SELECT * FROM `table` WHERE `column` = %s AND `field` = %d", 'foo', 1337 )
  1071. * wpdb::prepare( "SELECT DATE_FORMAT(`field`, '%%c') FROM `table` WHERE `column` = %s", 'foo' );
  1072. *
  1073. * @link http://php.net/sprintf Description of syntax.
  1074. * @since 2.3.0
  1075. *
  1076. * @param string $query Query statement with sprintf()-like placeholders
  1077. * @param array|mixed $args The array of variables to substitute into the query's placeholders if being called like
  1078. * {@link http://php.net/vsprintf vsprintf()}, or the first variable to substitute into the query's placeholders if
  1079. * being called like {@link http://php.net/sprintf sprintf()}.
  1080. * @param mixed $args,... further variables to substitute into the query's placeholders if being called like
  1081. * {@link http://php.net/sprintf sprintf()}.
  1082. * @return null|false|string Sanitized query string, null if there is no query, false if there is an error and string
  1083. * if there was something to prepare
  1084. */
  1085. public function prepare( $query, $args ) {
  1086. if ( is_null( $query ) )
  1087. return;
  1088. // This is not meant to be foolproof -- but it will catch obviously incorrect usage.
  1089. if ( strpos( $query, '%' ) === false ) {
  1090. _doing_it_wrong( 'wpdb::prepare', sprintf( __( 'The query argument of %s must have a placeholder.' ), 'wpdb::prepare()' ), '3.9' );
  1091. }
  1092. $args = func_get_args();
  1093. array_shift( $args );
  1094. // If args were passed as an array (as in vsprintf), move them up
  1095. if ( isset( $args[0] ) && is_array($args[0]) )
  1096. $args = $args[0];
  1097. $query = str_replace( "'%s'", '%s', $query ); // in case someone mistakenly already singlequoted it
  1098. $query = str_replace( '"%s"', '%s', $query ); // doublequote unquoting
  1099. $query = preg_replace( '|(?<!%)%f|' , '%F', $query ); // Force floats to be locale unaware
  1100. $query = preg_replace( '|(?<!%)%s|', "'%s'", $query ); // quote the strings, avoiding escaped strings like %%s
  1101. array_walk( $args, array( $this, 'escape_by_ref' ) );
  1102. return @vsprintf( $query, $args );
  1103. }
  1104. /**
  1105. * First half of escaping for LIKE special characters % and _ before preparing for MySQL.
  1106. *
  1107. * Use this only before wpdb::prepare() or esc_sql(). Reversing the order is very bad for security.
  1108. *
  1109. * Example Prepared Statement:
  1110. * $wild = '%';
  1111. * $find = 'only 43% of planets';
  1112. * $like = $wild . $wpdb->esc_like( $find ) . $wild;
  1113. * $sql = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_content LIKE %s", $like );
  1114. *
  1115. * Example Escape Chain:
  1116. * $sql = esc_sql( $wpdb->esc_like( $input ) );
  1117. *
  1118. * @since 4.0.0
  1119. * @access public
  1120. *
  1121. * @param string $text The raw text to be escaped. The input typed by the user should have no
  1122. * extra or deleted slashes.
  1123. * @return string Text in the form of a LIKE phrase. The output is not SQL safe. Call $wpdb::prepare()
  1124. * or real_escape next.
  1125. */
  1126. public function esc_like( $text ) {
  1127. return addcslashes( $text, '_%\\' );
  1128. }
  1129. /**
  1130. * Print SQL/DB error.
  1131. *
  1132. * @since 0.71
  1133. * @global array $EZSQL_ERROR Stores error information of query and error string
  1134. *
  1135. * @param string $str The error to display
  1136. * @return false|null False if the showing of errors is disabled.
  1137. */
  1138. public function print_error( $str = '' ) {
  1139. global $EZSQL_ERROR;
  1140. if ( !$str ) {
  1141. if ( $this->use_mysqli ) {
  1142. $str = mysqli_error( $this->dbh );
  1143. } else {
  1144. $str = mysql_error( $this->dbh );
  1145. }
  1146. }
  1147. $EZSQL_ERROR[] = array( 'query' => $this->last_query, 'error_str' => $str );
  1148. if ( $this->suppress_errors )
  1149. return false;
  1150. wp_load_translations_early();
  1151. if ( $caller = $this->get_caller() )
  1152. $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s made by %3$s' ), $str, $this->last_query, $caller );
  1153. else
  1154. $error_str = sprintf( __( 'WordPress database error %1$s for query %2$s' ), $str, $this->last_query );
  1155. error_log( $error_str );
  1156. // Are we showing errors?
  1157. if ( ! $this->show_errors )
  1158. return false;
  1159. // If there is an error then take note of it
  1160. if ( is_multisite() ) {
  1161. $msg = "WordPress database error: [$str]\n{$this->last_query}\n";
  1162. if ( defined( 'ERRORLOGFILE' ) )
  1163. error_log( $msg, 3, ERRORLOGFILE );
  1164. if ( defined( 'DIEONDBERROR' ) )
  1165. wp_die( $msg );
  1166. } else {
  1167. $str = htmlspecialchars( $str, ENT_QUOTES );
  1168. $query = htmlspecialchars( $this->last_query, ENT_QUOTES );
  1169. print "<div id='error'>
  1170. <p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br />
  1171. <code>$query</code></p>
  1172. </div>";
  1173. }
  1174. }
  1175. /**
  1176. * Enables showing of database errors.
  1177. *
  1178. * This function should be used only to enable showing of errors.
  1179. * wpdb::hide_errors() should be used instead for hiding of errors. However,
  1180. * this function can be used to enable and disable showing of database
  1181. * errors.
  1182. *
  1183. * @since 0.71
  1184. * @see wpdb::hide_errors()
  1185. *
  1186. * @param bool $show Whether to show or hide errors
  1187. * @return bool Old value for showing errors.
  1188. */
  1189. public function show_errors( $show = true ) {
  1190. $errors = $this->show_errors;
  1191. $this->show_errors = $show;
  1192. return $errors;
  1193. }
  1194. /**
  1195. * Disables showing of database errors.
  1196. *
  1197. * By default database errors are not shown.
  1198. *
  1199. * @since 0.71
  1200. * @see wpdb::show_errors()
  1201. *
  1202. * @return bool Whether showing of errors was active
  1203. */
  1204. public function hide_errors() {
  1205. $show = $this->show_errors;
  1206. $this->show_errors = false;
  1207. return $show;
  1208. }
  1209. /**
  1210. * Whether to suppress database errors.
  1211. *
  1212. * By default database errors are suppressed, with a simple
  1213. * call to this function they can be enabled.
  1214. *
  1215. * @since 2.5.0
  1216. * @see wpdb::hide_errors()
  1217. * @param bool $suppress Optional. New value. Defaults to true.
  1218. * @return bool Old value
  1219. */
  1220. public function suppress_errors( $suppress = true ) {
  1221. $errors = $this->suppress_errors;
  1222. $this->suppress_errors = (bool) $suppress;
  1223. return $errors;
  1224. }
  1225. /**
  1226. * Kill cached query results.
  1227. *
  1228. * @since 0.71
  1229. * @return void
  1230. */
  1231. public function flush() {
  1232. $this->last_result = array();
  1233. $this->col_info = null;
  1234. $this->last_query = null;
  1235. $this->rows_affected = $this->num_rows = 0;
  1236. $this->last_error = '';
  1237. if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
  1238. mysqli_free_result( $this->result );
  1239. $this->result = null;
  1240. // Sanity check before using the handle
  1241. if ( empty( $this->dbh ) || !( $this->dbh instanceof mysqli ) ) {
  1242. return;
  1243. }
  1244. // Clear out any results from a multi-query
  1245. while ( mysqli_more_results( $this->dbh ) ) {
  1246. mysqli_next_result( $this->dbh );
  1247. }
  1248. } elseif ( is_resource( $this->result ) ) {
  1249. mysql_free_result( $this->result );
  1250. }
  1251. }
  1252. /**
  1253. * Connect to and select database.
  1254. *
  1255. * If $allow_bail is false, the lack of database connection will need
  1256. * to be handled manually.
  1257. *
  1258. * @since 3.0.0
  1259. * @since 3.9.0 $allow_bail parameter added.
  1260. *
  1261. * @param bool $allow_bail Optional. Allows the function to bail. Default true.
  1262. * @return null|bool True with a successful connection, false on failure.
  1263. */
  1264. public function db_connect( $allow_bail = true ) {
  1265. $this->is_mysql = true;
  1266. /*
  1267. * Deprecated in 3.9+ when using MySQLi. No equivalent
  1268. * $new_link parameter exists for mysqli_* functions.
  1269. */
  1270. $new_link = defined( 'MYSQL_NEW_LINK' ) ? MYSQL_NEW_LINK : true;
  1271. $client_flags = defined( 'MYSQL_CLIENT_FLAGS' ) ? MYSQL_CLIENT_FLAGS : 0;
  1272. if ( $this->use_mysqli ) {
  1273. $this->dbh = mysqli_init();
  1274. // mysqli_real_connect doesn't support the host param including a port or socket
  1275. // like mysql_connect does. This duplicates how mysql_connect detects a port and/or socket file.
  1276. $port = null;
  1277. $socket = null;
  1278. $host = $this->dbhost;
  1279. $port_or_socket = strstr( $host, ':' );
  1280. if ( ! empty( $port_or_socket ) ) {
  1281. $host = substr( $host, 0, strpos( $host, ':' ) );
  1282. $port_or_socket = substr( $port_or_socket, 1 );
  1283. if ( 0 !== strpos( $port_or_socket, '/' ) ) {
  1284. $port = intval( $port_or_socket );
  1285. $maybe_socket = strstr( $port_or_socket, ':' );
  1286. if ( ! empty( $maybe_socket ) ) {
  1287. $socket = substr( $maybe_socket, 1 );
  1288. }
  1289. } else {
  1290. $socket = $port_or_socket;
  1291. }
  1292. }
  1293. if ( WP_DEBUG ) {
  1294. mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
  1295. } else {
  1296. @mysqli_real_connect( $this->dbh, $host, $this->dbuser, $this->dbpassword, null, $port, $socket, $client_flags );
  1297. }
  1298. if ( $this->dbh->connect_errno ) {
  1299. $this->dbh = null;
  1300. /* It's possible ext/mysqli is misconfigured. Fall back to ext/mysql if:
  1301. * - We haven't previously connected, and
  1302. * - WP_USE_EXT_MYSQL isn't set to false, and
  1303. * - ext/mysql is loaded.
  1304. */
  1305. $attempt_fallback = true;
  1306. if ( $this->has_connected ) {
  1307. $attempt_fallback = false;
  1308. } elseif ( defined( 'WP_USE_EXT_MYSQL' ) && ! WP_USE_EXT_MYSQL ) {
  1309. $attempt_fallback = false;
  1310. } elseif ( ! function_exists( 'mysql_connect' ) ) {
  1311. $attempt_fallback = false;
  1312. }
  1313. if ( $attempt_fallback ) {
  1314. $this->use_mysqli = false;
  1315. $this->db_connect();
  1316. }
  1317. }
  1318. } else {
  1319. if ( WP_DEBUG ) {
  1320. $this->dbh = mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
  1321. } else {
  1322. $this->dbh = @mysql_connect( $this->dbhost, $this->dbuser, $this->dbpassword, $new_link, $client_flags );
  1323. }
  1324. }
  1325. if ( ! $this->dbh && $allow_bail ) {
  1326. wp_load_translations_early();
  1327. // Load custom DB error template, if present.
  1328. if ( file_exists( WP_CONTENT_DIR . '/db-error.php' ) ) {
  1329. require_once( WP_CONTENT_DIR . '/db-error.php' );
  1330. die();
  1331. }
  1332. $this->bail( sprintf( __( "
  1333. <h1>Error establishing a database connection</h1>
  1334. <p>This either means that the username and password information in your <code>wp-config.php</code> file is incorrect or we can't contact the database server at <code>%s</code>. This could mean your host's database server is down.</p>
  1335. <ul>
  1336. <li>Are you sure you have the correct username and password?</li>
  1337. <li>Are you sure that you have typed the correct hostname?</li>
  1338. <li>Are you sure that the database server is running?</li>
  1339. </ul>
  1340. <p>If you're unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href='https://wordpress.org/support/'>WordPress Support Forums</a>.</p>
  1341. " ), htmlspecialchars( $this->dbhost, ENT_QUOTES ) ), 'db_connect_fail' );
  1342. return false;
  1343. } elseif ( $this->dbh ) {
  1344. if ( ! $this->has_connected ) {
  1345. $this->init_charset();
  1346. }
  1347. $this->has_connected = true;
  1348. $this->set_charset( $this->dbh );
  1349. $this->ready = true;
  1350. $this->set_sql_mode();
  1351. $this->select( $this->dbname, $this->dbh );
  1352. return true;
  1353. }
  1354. return false;
  1355. }
  1356. /**
  1357. * Check that the connection to the database is still up. If not, try to reconnect.
  1358. *
  1359. * If this function is unable to reconnect, it will forcibly die, or if after the
  1360. * the template_redirect hook has been fired, return false instead.
  1361. *
  1362. * If $allow_bail is false, the lack of database connection will need
  1363. * to be handled manually.
  1364. *
  1365. * @since 3.9.0
  1366. *
  1367. * @param bool $allow_bail Optional. Allows the function to bail. Default true.
  1368. * @return bool|null True if the connection is up.
  1369. */
  1370. public function check_connection( $allow_bail = true ) {
  1371. if ( $this->use_mysqli ) {
  1372. if ( @mysqli_ping( $this->dbh ) ) {
  1373. return true;
  1374. }
  1375. } else {
  1376. if ( @mysql_ping( $this->dbh ) ) {
  1377. return true;
  1378. }
  1379. }
  1380. $error_reporting = false;
  1381. // Disable warnings, as we don't want to see a multitude of "unable to connect" messages
  1382. if ( WP_DEBUG ) {
  1383. $error_reporting = error_reporting();
  1384. error_reporting( $error_reporting & ~E_WARNING );
  1385. }
  1386. for ( $tries = 1; $tries <= $this->reconnect_retries; $tries++ ) {
  1387. // On the last try, re-enable warnings. We want to see a single instance of the
  1388. // "unable to connect" message on the bail() screen, if it appears.
  1389. if ( $this->reconnect_retries === $tries && WP_DEBUG ) {
  1390. error_reporting( $error_reporting );
  1391. }
  1392. if ( $this->db_connect( false ) ) {
  1393. if ( $error_reporting ) {
  1394. error_reporting( $error_reporting );
  1395. }
  1396. return true;
  1397. }
  1398. sleep( 1 );
  1399. }
  1400. // If template_redirect has already happened, it's too late for wp_die()/dead_db().
  1401. // Let's just return and hope for the best.
  1402. if ( did_action( 'template_redirect' ) ) {
  1403. return false;
  1404. }
  1405. if ( ! $allow_bail ) {
  1406. return false;
  1407. }
  1408. // We weren't able to reconnect, so we better bail.
  1409. $this->bail( sprintf( ( "
  1410. <h1>Error reconnecting to the database</h1>
  1411. <p>This means that we lost contact with the database server at <code>%s</code>. This could mean your host's database server is down.</p>
  1412. <ul>
  1413. <li>Are you sure that the database server is running?</li>
  1414. <li>Are you sure that the database server is not under particularly heavy load?</li>
  1415. </ul>
  1416. <p>If you're unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href='https://wordpress.org/support/'>WordPress Support Forums</a>.</p>
  1417. " ), htmlspecialchars( $this->dbhost, ENT_QUOTES ) ), 'db_connect_fail' );
  1418. // Call dead_db() if bail didn't die, because this database is no more. It has ceased to be (at least temporarily).
  1419. dead_db();
  1420. }
  1421. /**
  1422. * Perform a MySQL database query, using current database connection.
  1423. *
  1424. * More information can be found on the codex page.
  1425. *
  1426. * @since 0.71
  1427. *
  1428. * @param string $query Database query
  1429. * @return int|false Number of rows affected/selected or false on error
  1430. */
  1431. public function query( $query ) {
  1432. if ( ! $this->ready ) {
  1433. $this->check_current_query = true;
  1434. return false;
  1435. }
  1436. /**
  1437. * Filter the database query.
  1438. *
  1439. * Some queries are made before the plugins have been loaded,
  1440. * and thus cannot be filtered with this method.
  1441. *
  1442. * @since 2.1.0
  1443. *
  1444. * @param string $query Database query.
  1445. */
  1446. $query = apply_filters( 'query', $query );
  1447. $this->flush();
  1448. // Log how the function was called
  1449. $this->func_call = "\$db->query(\"$query\")";
  1450. // If we're writing to the database, make sure the query will write safely.
  1451. if ( $this->check_current_query && ! $this->check_ascii( $query ) ) {
  1452. $stripped_query = $this->strip_invalid_text_from_query( $query );
  1453. // strip_invalid_text_from_query() can perform queries, so we need
  1454. // to flush again, just to make sure everything is clear.
  1455. $this->flush();
  1456. if ( $stripped_query !== $query ) {
  1457. $this->insert_id = 0;
  1458. return false;
  1459. }
  1460. }
  1461. $this->check_current_query = true;
  1462. // Keep track of the last query for debug..
  1463. $this->last_query = $query;
  1464. $this->_do_query( $query );
  1465. // MySQL server has gone away, try to reconnect
  1466. $mysql_errno = 0;
  1467. if ( ! empty( $this->dbh ) ) {
  1468. if ( $this->use_mysqli ) {
  1469. $mysql_errno = mysqli_errno( $this->dbh );
  1470. } else {
  1471. $mysql_errno = mysql_errno( $this->dbh );
  1472. }
  1473. }
  1474. if ( empty( $this->dbh ) || 2006 == $mysql_errno ) {
  1475. if ( $this->check_connection() ) {
  1476. $this->_do_query( $query );
  1477. } else {
  1478. $this->insert_id = 0;
  1479. return false;
  1480. }
  1481. }
  1482. // If there is an error then take note of it..
  1483. if ( $this->use_mysqli ) {
  1484. $this->last_error = mysqli_error( $this->dbh );
  1485. } else {
  1486. $this->last_error = mysql_error( $this->dbh );
  1487. }
  1488. if ( $this->last_error ) {
  1489. // Clear insert_id on a subsequent failed insert.
  1490. if ( $this->insert_id && preg_match( '/^\s*(insert|replace)\s/i', $query ) )
  1491. $this->insert_id = 0;
  1492. $this->print_error();
  1493. return false;
  1494. }
  1495. if ( preg_match( '/^\s*(create|alter|truncate|drop)\s/i', $query ) ) {
  1496. $return_val = $this->result;
  1497. } elseif ( preg_match( '/^\s*(insert|delete|update|replace)\s/i', $query ) ) {
  1498. if ( $this->use_mysqli ) {
  1499. $this->rows_affected = mysqli_affected_rows( $this->dbh );
  1500. } else {
  1501. $this->rows_affected = mysql_affected_rows( $this->dbh );
  1502. }
  1503. // Take note of the insert_id
  1504. if ( preg_match( '/^\s*(insert|replace)\s/i', $query ) ) {
  1505. if ( $this->use_mysqli ) {
  1506. $this->insert_id = mysqli_insert_id( $this->dbh );
  1507. } else {
  1508. $this->insert_id = mysql_insert_id( $this->dbh );
  1509. }
  1510. }
  1511. // Return number of rows affected
  1512. $return_val = $this->rows_affected;
  1513. } else {
  1514. $num_rows = 0;
  1515. if ( $this->use_mysqli && $this->result instanceof mysqli_result ) {
  1516. while ( $row = @mysqli_fetch_object( $this->result ) ) {
  1517. $this->last_result[$num_rows] = $row;
  1518. $num_rows++;
  1519. }
  1520. } elseif ( is_resource( $this->result ) ) {
  1521. while ( $row = @mysql_fetch_object( $this->result ) ) {
  1522. $this->last_result[$num_rows] = $row;
  1523. $num_rows++;
  1524. }
  1525. }
  1526. // Log number of rows the query returned
  1527. // and return number of rows selected
  1528. $this->num_rows = $num_rows;
  1529. $return_val = $num_rows;
  1530. }
  1531. return $return_val;
  1532. }
  1533. /**
  1534. * Internal function to perform the mysql_query() call.
  1535. *
  1536. * @since 3.9.0
  1537. *
  1538. * @access private
  1539. * @see wpdb::query()
  1540. *
  1541. * @param string $query The query to run.
  1542. */
  1543. private function _do_query( $query ) {
  1544. if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
  1545. $this->timer_start();
  1546. }
  1547. if ( $this->use_mysqli ) {
  1548. $this->result = @mysqli_query( $this->dbh, $query );
  1549. } else {
  1550. $this->result = @mysql_query( $query, $this->dbh );
  1551. }
  1552. $this->num_queries++;
  1553. if ( defined( 'SAVEQUERIES' ) && SAVEQUERIES ) {
  1554. $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
  1555. }
  1556. }
  1557. /**
  1558. * Insert a row into a table.
  1559. *
  1560. * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
  1561. * wpdb::insert( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
  1562. *
  1563. * @since 2.5.0
  1564. * @see wpdb::prepare()
  1565. * @see wpdb::$field_types
  1566. * @see wp_set_wpdb_vars()
  1567. *
  1568. * @param string $table table name
  1569. * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  1570. * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data. If string, that format will be used for all of the values in $data.
  1571. * A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
  1572. * @return int|false The number of rows inserted, or false on error.
  1573. */
  1574. public function insert( $table, $data, $format = null ) {
  1575. return $this->_insert_replace_helper( $table, $data, $format, 'INSERT' );
  1576. }
  1577. /**
  1578. * Replace a row into a table.
  1579. *
  1580. * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 'bar' ) )
  1581. * wpdb::replace( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( '%s', '%d' ) )
  1582. *
  1583. * @since 3.0.0
  1584. * @see wpdb::prepare()
  1585. * @see wpdb::$field_types
  1586. * @see wp_set_wpdb_vars()
  1587. *
  1588. * @param string $table table name
  1589. * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  1590. * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data. If string, that format will be used for all of the values in $data.
  1591. * A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
  1592. * @return int|false The number of rows affected, or false on error.
  1593. */
  1594. public function replace( $table, $data, $format = null ) {
  1595. return $this->_insert_replace_helper( $table, $data, $format, 'REPLACE' );
  1596. }
  1597. /**
  1598. * Helper function for insert and replace.
  1599. *
  1600. * Runs an insert or replace query based on $type argument.
  1601. *
  1602. * @access private
  1603. * @since 3.0.0
  1604. * @see wpdb::prepare()
  1605. * @see wpdb::$field_types
  1606. * @see wp_set_wpdb_vars()
  1607. *
  1608. * @param string $table table name
  1609. * @param array $data Data to insert (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  1610. * @param array|string $format Optional. An array of formats to be mapped to each of the value in $data. If string, that format will be used for all of the values in $data.
  1611. * A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
  1612. * @param string $type Optional. What type of operation is this? INSERT or REPLACE. Defaults to INSERT.
  1613. * @return int|false The number of rows affected, or false on error.
  1614. */
  1615. function _insert_replace_helper( $table, $data, $format = null, $type = 'INSERT' ) {
  1616. $this->insert_id = 0;
  1617. if ( ! in_array( strtoupper( $type ), array( 'REPLACE', 'INSERT' ) ) ) {
  1618. return false;
  1619. }
  1620. $data = $this->process_fields( $table, $data, $format );
  1621. if ( false === $data ) {
  1622. return false;
  1623. }
  1624. $formats = $values = array();
  1625. foreach ( $data as $value ) {
  1626. $formats[] = $value['format'];
  1627. $values[] = $value['value'];
  1628. }
  1629. $fields = '`' . implode( '`, `', array_keys( $data ) ) . '`';
  1630. $formats = implode( ', ', $formats );
  1631. $sql = "$type INTO `$table` ($fields) VALUES ($formats)";
  1632. $this->check_current_query = false;
  1633. return $this->query( $this->prepare( $sql, $values ) );
  1634. }
  1635. /**
  1636. * Update a row in the table
  1637. *
  1638. * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 'bar' ), array( 'ID' => 1 ) )
  1639. * wpdb::update( 'table', array( 'column' => 'foo', 'field' => 1337 ), array( 'ID' => 1 ), array( '%s', '%d' ), array( '%d' ) )
  1640. *
  1641. * @since 2.5.0
  1642. * @see wpdb::prepare()
  1643. * @see wpdb::$field_types
  1644. * @see wp_set_wpdb_vars()
  1645. *
  1646. * @param string $table table name
  1647. * @param array $data Data to update (in column => value pairs). Both $data columns and $data values should be "raw" (neither should be SQL escaped).
  1648. * @param array $where A named array of WHERE clauses (in column => value pairs). Multiple clauses will be joined with ANDs. Both $where columns and $where values should be "raw".
  1649. * @param array|string $format Optional. An array of formats to be mapped to each of the values in $data. If string, that format will be used for all of the values in $data.
  1650. * A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $data will be treated as strings unless otherwise specified in wpdb::$field_types.
  1651. * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where. If string, that format will be used for all of the items in $where. A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $where will be treated as strings.
  1652. * @return int|false The number of rows updated, or false on error.
  1653. */
  1654. public function update( $table, $data, $where, $format = null, $where_format = null ) {
  1655. if ( ! is_array( $data ) || ! is_array( $where ) ) {
  1656. return false;
  1657. }
  1658. $data = $this->process_fields( $table, $data, $format );
  1659. if ( false === $data ) {
  1660. return false;
  1661. }
  1662. $where = $this->process_fields( $table, $where, $where_format );
  1663. if ( false === $where ) {
  1664. return false;
  1665. }
  1666. $fields = $conditions = $values = array();
  1667. foreach ( $data as $field => $value ) {
  1668. $fields[] = "`$field` = " . $value['format'];
  1669. $values[] = $value['value'];
  1670. }
  1671. foreach ( $where as $field => $value ) {
  1672. $conditions[] = "`$field` = " . $value['format'];
  1673. $values[] = $value['value'];
  1674. }
  1675. $fields = implode( ', ', $fields );
  1676. $conditions = implode( ' AND ', $conditions );
  1677. $sql = "UPDATE `$table` SET $fields WHERE $conditions";
  1678. $this->check_current_query = false;
  1679. return $this->query( $this->prepare( $sql, $values ) );
  1680. }
  1681. /**
  1682. * Delete a row in the table
  1683. *
  1684. * wpdb::delete( 'table', array( 'ID' => 1 ) )
  1685. * wpdb::delete( 'table', array( 'ID' => 1 ), array( '%d' ) )
  1686. *
  1687. * @since 3.4.0
  1688. * @see wpdb::prepare()
  1689. * @see wpdb::$field_types
  1690. * @see wp_set_wpdb_vars()
  1691. *
  1692. * @param string $table table name
  1693. * @param array $where A named array of WHERE clauses (in column => value pairs). Multiple clauses will be joined with ANDs. Both $where columns and $where values should be "raw".
  1694. * @param array|string $where_format Optional. An array of formats to be mapped to each of the values in $where. If string, that format will be used for all of the items in $where. A format is one of '%d', '%f', '%s' (integer, float, string). If omitted, all values in $where will be treated as strings unless otherwise specified in wpdb::$field_types.
  1695. * @return int|false The number of rows updated, or false on error.
  1696. */
  1697. public function delete( $table, $where, $where_format = null ) {
  1698. if ( ! is_array( $where ) ) {
  1699. return false;
  1700. }
  1701. $where = $this->process_fields( $table, $where, $where_format );
  1702. if ( false === $where ) {
  1703. return false;
  1704. }
  1705. $conditions = $values = array();
  1706. foreach ( $where as $field => $value ) {
  1707. $conditions[] = "`$field` = " . $value['format'];
  1708. $values[] = $value['value'];
  1709. }
  1710. $conditions = implode( ' AND ', $conditions );
  1711. $sql = "DELETE FROM `$table` WHERE $conditions";
  1712. $this->check_current_query = false;
  1713. return $this->query( $this->prepare( $sql, $values ) );
  1714. }
  1715. /**
  1716. * Processes arrays of field/value pairs and field formats.
  1717. *
  1718. * This is a helper method for wpdb's CRUD methods, which take field/value
  1719. * pairs for inserts, updates, and where clauses. This method first pairs
  1720. * each value with a format. Then it determines the charset of that field,
  1721. * using that to determine if any invalid text would be stripped. If text is
  1722. * stripped, then field processing is rejected and the query fails.
  1723. *
  1724. * @since 4.2.0
  1725. * @access protected
  1726. *
  1727. * @param string $table Table name.
  1728. * @param array $data Field/value pair.
  1729. * @param mixed $format Format for each field.
  1730. * @return array|bool Returns an array of fields that contain paired values
  1731. * and formats. Returns false for invalid values.
  1732. */
  1733. protected function process_fields( $table, $data, $format ) {
  1734. $data = $this->process_field_formats( $data, $format );
  1735. if ( false === $data ) {
  1736. return false;
  1737. }
  1738. $data = $this->process_field_charsets( $data, $table );
  1739. if ( false === $data ) {
  1740. return false;
  1741. }
  1742. $data = $this->process_field_lengths( $data, $table );
  1743. if ( false === $data ) {
  1744. return false;
  1745. }
  1746. $converted_data = $this->strip_invalid_text( $data );
  1747. if ( $data !== $converted_data ) {
  1748. return false;
  1749. }
  1750. return $data;
  1751. }
  1752. /**
  1753. * Prepares arrays of value/format pairs as passed to wpdb CRUD methods.
  1754. *
  1755. * @since 4.2.0
  1756. * @access protected
  1757. *
  1758. * @param array $data Array of fields to values.
  1759. * @param mixed $format Formats to be mapped to the values in $data.
  1760. * @return array Array, keyed by field names with values being an array
  1761. * of 'value' and 'format' keys.
  1762. */
  1763. protected function process_field_formats( $data, $format ) {
  1764. $formats = $original_formats = (array) $format;
  1765. foreach ( $data as $field => $value ) {
  1766. $value = array(
  1767. 'value' => $value,
  1768. 'format' => '%s',
  1769. );
  1770. if ( ! empty( $format ) ) {
  1771. $value['format'] = array_shift( $formats );
  1772. if ( ! $value['format'] ) {
  1773. $value['format'] = reset( $original_formats );
  1774. }
  1775. } elseif ( isset( $this->field_types[ $field ] ) ) {
  1776. $value['format'] = $this->field_types[ $field ];
  1777. }
  1778. $data[ $field ] = $value;
  1779. }
  1780. return $data;
  1781. }
  1782. /**
  1783. * Adds field charsets to field/value/format arrays generated by
  1784. * the wpdb::process_field_formats() method.
  1785. *
  1786. * @since 4.2.0
  1787. * @access protected
  1788. *
  1789. * @param array $data As it comes from the wpdb::process_field_formats() method.
  1790. * @param string $table Table name.
  1791. * @return The same array as $data with additional 'charset' keys.
  1792. */
  1793. protected function process_field_charsets( $data, $table ) {
  1794. foreach ( $data as $field => $value ) {
  1795. if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
  1796. // We can skip this field if we know it isn't a string.
  1797. // This checks %d/%f versus ! %s because it's sprintf() could take more.
  1798. $value['charset'] = false;
  1799. } else {
  1800. $value['charset'] = $this->get_col_charset( $table, $field );
  1801. if ( is_wp_error( $value['charset'] ) ) {
  1802. return false;
  1803. }
  1804. }
  1805. $data[ $field ] = $value;
  1806. }
  1807. return $data;
  1808. }
  1809. /**
  1810. * For string fields, record the maximum string length that field can safely save.
  1811. *
  1812. * @since 4.2.1
  1813. * @access protected
  1814. *
  1815. * @param array $data As it comes from the wpdb::process_field_charsets() method.
  1816. * @param string $table Table name.
  1817. * @return array|False The same array as $data with additional 'length' keys, or false if
  1818. * any of the values were too long for their corresponding field.
  1819. */
  1820. protected function process_field_lengths( $data, $table ) {
  1821. foreach ( $data as $field => $value ) {
  1822. if ( '%d' === $value['format'] || '%f' === $value['format'] ) {
  1823. // We can skip this field if we know it isn't a string.
  1824. // This checks %d/%f versus ! %s because it's sprintf() could take more.
  1825. $value['length'] = false;
  1826. } else {
  1827. $value['length'] = $this->get_col_length( $table, $field );
  1828. if ( is_wp_error( $value['length'] ) ) {
  1829. return false;
  1830. }
  1831. }
  1832. $data[ $field ] = $value;
  1833. }
  1834. return $data;
  1835. }
  1836. /**
  1837. * Retrieve one variable from the database.
  1838. *
  1839. * Executes a SQL query and returns the value from the SQL result.
  1840. * If the SQL result contains more than one column and/or more than one row, this function returns the value in the column and row specified.
  1841. * If $query is null, this function returns the value in the specified column and row from the previous SQL result.
  1842. *
  1843. * @since 0.71
  1844. *
  1845. * @param string|null $query Optional. SQL query. Defaults to null, use the result from the previous query.
  1846. * @param int $x Optional. Column of value to return. Indexed from 0.
  1847. * @param int $y Optional. Row of value to return. Indexed from 0.
  1848. * @return string|null Database query result (as string), or null on failure
  1849. */
  1850. public function get_var( $query = null, $x = 0, $y = 0 ) {
  1851. $this->func_call = "\$db->get_var(\"$query\", $x, $y)";
  1852. if ( $this->check_safe_collation( $query ) ) {
  1853. $this->check_current_query = false;
  1854. }
  1855. if ( $query ) {
  1856. $this->query( $query );
  1857. }
  1858. // Extract var out of cached results based x,y vals
  1859. if ( !empty( $this->last_result[$y] ) ) {
  1860. $values = array_values( get_object_vars( $this->last_result[$y] ) );
  1861. }
  1862. // If there is a value return it else return null
  1863. return ( isset( $values[$x] ) && $values[$x] !== '' ) ? $values[$x] : null;
  1864. }
  1865. /**
  1866. * Retrieve one row from the database.
  1867. *
  1868. * Executes a SQL query and returns the row from the SQL result.
  1869. *
  1870. * @since 0.71
  1871. *
  1872. * @param string|null $query SQL query.
  1873. * @param string $output Optional. one of ARRAY_A | ARRAY_N | OBJECT constants. Return an associative array (column => value, ...),
  1874. * a numerically indexed array (0 => value, ...) or an object ( ->column = value ), respectively.
  1875. * @param int $y Optional. Row to return. Indexed from 0.
  1876. * @return mixed Database query result in format specified by $output or null on failure
  1877. */
  1878. public function get_row( $query = null, $output = OBJECT, $y = 0 ) {
  1879. $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
  1880. if ( $this->check_safe_collation( $query ) ) {
  1881. $this->check_current_query = false;
  1882. }
  1883. if ( $query ) {
  1884. $this->query( $query );
  1885. } else {
  1886. return null;
  1887. }
  1888. if ( !isset( $this->last_result[$y] ) )
  1889. return null;
  1890. if ( $output == OBJECT ) {
  1891. return $this->last_result[$y] ? $this->last_result[$y] : null;
  1892. } elseif ( $output == ARRAY_A ) {
  1893. return $this->last_result[$y] ? get_object_vars( $this->last_result[$y] ) : null;
  1894. } elseif ( $output == ARRAY_N ) {
  1895. return $this->last_result[$y] ? array_values( get_object_vars( $this->last_result[$y] ) ) : null;
  1896. } elseif ( strtoupper( $output ) === OBJECT ) {
  1897. // Back compat for OBJECT being previously case insensitive.
  1898. return $this->last_result[$y] ? $this->last_result[$y] : null;
  1899. } else {
  1900. $this->print_error( " \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N" );
  1901. }
  1902. }
  1903. /**
  1904. * Retrieve one column from the database.
  1905. *
  1906. * Executes a SQL query and returns the column from the SQL result.
  1907. * If the SQL result contains more than one column, this function returns the column specified.
  1908. * If $query is null, this function returns the specified column from the previous SQL result.
  1909. *
  1910. * @since 0.71
  1911. *
  1912. * @param string|null $query Optional. SQL query. Defaults to previous query.
  1913. * @param int $x Optional. Column to return. Indexed from 0.
  1914. * @return array Database query result. Array indexed from 0 by SQL result row number.
  1915. */
  1916. public function get_col( $query = null , $x = 0 ) {
  1917. if ( $this->check_safe_collation( $query ) ) {
  1918. $this->check_current_query = false;
  1919. }
  1920. if ( $query ) {
  1921. $this->query( $query );
  1922. }
  1923. $new_array = array();
  1924. // Extract the column values
  1925. for ( $i = 0, $j = count( $this->last_result ); $i < $j; $i++ ) {
  1926. $new_array[$i] = $this->get_var( null, $x, $i );
  1927. }
  1928. return $new_array;
  1929. }
  1930. /**
  1931. * Retrieve an entire SQL result set from the database (i.e., many rows)
  1932. *
  1933. * Executes a SQL query and returns the entire SQL result.
  1934. *
  1935. * @since 0.71
  1936. *
  1937. * @param string $query SQL query.
  1938. * @param string $output Optional. Any of ARRAY_A | ARRAY_N | OBJECT | OBJECT_K constants. With one of the first three, return an array of rows indexed from 0 by SQL result row number.
  1939. * Each row is an associative array (column => value, ...), a numerically indexed array (0 => value, ...), or an object. ( ->column = value ), respectively.
  1940. * With OBJECT_K, return an associative array of row objects keyed by the value of each row's first column's value. Duplicate keys are discarded.
  1941. * @return mixed Database query results
  1942. */
  1943. public function get_results( $query = null, $output = OBJECT ) {
  1944. $this->func_call = "\$db->get_results(\"$query\", $output)";
  1945. if ( $this->check_safe_collation( $query ) ) {
  1946. $this->check_current_query = false;
  1947. }
  1948. if ( $query ) {
  1949. $this->query( $query );
  1950. } else {
  1951. return null;
  1952. }
  1953. $new_array = array();
  1954. if ( $output == OBJECT ) {
  1955. // Return an integer-keyed array of row objects
  1956. return $this->last_result;
  1957. } elseif ( $output == OBJECT_K ) {
  1958. // Return an array of row objects with keys from column 1
  1959. // (Duplicates are discarded)
  1960. foreach ( $this->last_result as $row ) {
  1961. $var_by_ref = get_object_vars( $row );
  1962. $key = array_shift( $var_by_ref );
  1963. if ( ! isset( $new_array[ $key ] ) )
  1964. $new_array[ $key ] = $row;
  1965. }
  1966. return $new_array;
  1967. } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
  1968. // Return an integer-keyed array of...
  1969. if ( $this->last_result ) {
  1970. foreach( (array) $this->last_result as $row ) {
  1971. if ( $output == ARRAY_N ) {
  1972. // ...integer-keyed row arrays
  1973. $new_array[] = array_values( get_object_vars( $row ) );
  1974. } else {
  1975. // ...column name-keyed row arrays
  1976. $new_array[] = get_object_vars( $row );
  1977. }
  1978. }
  1979. }
  1980. return $new_array;
  1981. } elseif ( strtoupper( $output ) === OBJECT ) {
  1982. // Back compat for OBJECT being previously case insensitive.
  1983. return $this->last_result;
  1984. }
  1985. return null;
  1986. }
  1987. /**
  1988. * Retrieves the character set for the given table.
  1989. *
  1990. * @since 4.2.0
  1991. * @access protected
  1992. *
  1993. * @param string $table Table name.
  1994. * @return string|WP_Error Table character set, WP_Error object if it couldn't be found.
  1995. */
  1996. protected function get_table_charset( $table ) {
  1997. $tablekey = strtolower( $table );
  1998. /**
  1999. * Filter the table charset value before the DB is checked.
  2000. *
  2001. * Passing a non-null value to the filter will effectively short-circuit
  2002. * checking the DB for the charset, returning that value instead.
  2003. *
  2004. * @since 4.2.0
  2005. *
  2006. * @param string $charset The character set to use. Default null.
  2007. * @param string $table The name of the table being checked.
  2008. */
  2009. $charset = apply_filters( 'pre_get_table_charset', null, $table );
  2010. if ( null !== $charset ) {
  2011. return $charset;
  2012. }
  2013. if ( isset( $this->table_charset[ $tablekey ] ) ) {
  2014. return $this->table_charset[ $tablekey ];
  2015. }
  2016. $charsets = $columns = array();
  2017. $table_parts = explode( '.', $table );
  2018. $table = '`' . implode( '`.`', $table_parts ) . '`';
  2019. $results = $this->get_results( "SHOW FULL COLUMNS FROM $table" );
  2020. if ( ! $results ) {
  2021. return new WP_Error( 'wpdb_get_table_charset_failure' );
  2022. }
  2023. foreach ( $results as $column ) {
  2024. $columns[ strtolower( $column->Field ) ] = $column;
  2025. }
  2026. $this->col_meta[ $tablekey ] = $columns;
  2027. foreach ( $columns as $column ) {
  2028. if ( ! empty( $column->Collation ) ) {
  2029. list( $charset ) = explode( '_', $column->Collation );
  2030. // If the current connection can't support utf8mb4 characters, let's only send 3-byte utf8 characters.
  2031. if ( 'utf8mb4' === $charset && ! $this->has_cap( 'utf8mb4' ) ) {
  2032. $charset = 'utf8';
  2033. }
  2034. $charsets[ strtolower( $charset ) ] = true;
  2035. }
  2036. list( $type ) = explode( '(', $column->Type );
  2037. // A binary/blob means the whole query gets treated like this.
  2038. if ( in_array( strtoupper( $type ), array( 'BINARY', 'VARBINARY', 'TINYBLOB', 'MEDIUMBLOB', 'BLOB', 'LONGBLOB' ) ) ) {
  2039. $this->table_charset[ $tablekey ] = 'binary';
  2040. return 'binary';
  2041. }
  2042. }
  2043. // utf8mb3 is an alias for utf8.
  2044. if ( isset( $charsets['utf8mb3'] ) ) {
  2045. $charsets['utf8'] = true;
  2046. unset( $charsets['utf8mb3'] );
  2047. }
  2048. // Check if we have more than one charset in play.
  2049. $count = count( $charsets );
  2050. if ( 1 === $count ) {
  2051. $charset = key( $charsets );
  2052. } elseif ( 0 === $count ) {
  2053. // No charsets, assume this table can store whatever.
  2054. $charset = false;
  2055. } else {
  2056. // More than one charset. Remove latin1 if present and recalculate.
  2057. unset( $charsets['latin1'] );
  2058. $count = count( $charsets );
  2059. if ( 1 === $count ) {
  2060. // Only one charset (besides latin1).
  2061. $charset = key( $charsets );
  2062. } elseif ( 2 === $count && isset( $charsets['utf8'], $charsets['utf8mb4'] ) ) {
  2063. // Two charsets, but they're utf8 and utf8mb4, use utf8.
  2064. $charset = 'utf8';
  2065. } else {
  2066. // Two mixed character sets. ascii.
  2067. $charset = 'ascii';
  2068. }
  2069. }
  2070. $this->table_charset[ $tablekey ] = $charset;
  2071. return $charset;
  2072. }
  2073. /**
  2074. * Retrieves the character set for the given column.
  2075. *
  2076. * @since 4.2.0
  2077. * @access public
  2078. *
  2079. * @param string $table Table name.
  2080. * @param string $column Column name.
  2081. * @return mixed Column character set as a string. False if the column has no
  2082. * character set. WP_Error object if there was an error.
  2083. */
  2084. public function get_col_charset( $table, $column ) {
  2085. $tablekey = strtolower( $table );
  2086. $columnkey = strtolower( $column );
  2087. /**
  2088. * Filter the column charset value before the DB is checked.
  2089. *
  2090. * Passing a non-null value to the filter will short-circuit
  2091. * checking the DB for the charset, returning that value instead.
  2092. *
  2093. * @since 4.2.0
  2094. *
  2095. * @param string $charset The character set to use. Default null.
  2096. * @param string $table The name of the table being checked.
  2097. * @param string $column The name of the column being checked.
  2098. */
  2099. $charset = apply_filters( 'pre_get_col_charset', null, $table, $column );
  2100. if ( null !== $charset ) {
  2101. return $charset;
  2102. }
  2103. // Skip this entirely if this isn't a MySQL database.
  2104. if ( false === $this->is_mysql ) {
  2105. return false;
  2106. }
  2107. if ( empty( $this->table_charset[ $tablekey ] ) ) {
  2108. // This primes column information for us.
  2109. $table_charset = $this->get_table_charset( $table );
  2110. if ( is_wp_error( $table_charset ) ) {
  2111. return $table_charset;
  2112. }
  2113. }
  2114. // If still no column information, return the table charset.
  2115. if ( empty( $this->col_meta[ $tablekey ] ) ) {
  2116. return $this->table_charset[ $tablekey ];
  2117. }
  2118. // If this column doesn't exist, return the table charset.
  2119. if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
  2120. return $this->table_charset[ $tablekey ];
  2121. }
  2122. // Return false when it's not a string column.
  2123. if ( empty( $this->col_meta[ $tablekey ][ $columnkey ]->Collation ) ) {
  2124. return false;
  2125. }
  2126. list( $charset ) = explode( '_', $this->col_meta[ $tablekey ][ $columnkey ]->Collation );
  2127. return $charset;
  2128. }
  2129. /**
  2130. * Retrieve the maximum string length allowed in a given column.
  2131. * The length may either be specified as a byte length or a character length.
  2132. *
  2133. * @since 4.2.1
  2134. * @access public
  2135. *
  2136. * @param string $table Table name.
  2137. * @param string $column Column name.
  2138. * @return mixed array( 'length' => (int), 'type' => 'byte' | 'char' )
  2139. * false if the column has no length (for example, numeric column)
  2140. * WP_Error object if there was an error.
  2141. */
  2142. public function get_col_length( $table, $column ) {
  2143. $tablekey = strtolower( $table );
  2144. $columnkey = strtolower( $column );
  2145. // Skip this entirely if this isn't a MySQL database.
  2146. if ( false === $this->is_mysql ) {
  2147. return false;
  2148. }
  2149. if ( empty( $this->col_meta[ $tablekey ] ) ) {
  2150. // This primes column information for us.
  2151. $table_charset = $this->get_table_charset( $table );
  2152. if ( is_wp_error( $table_charset ) ) {
  2153. return $table_charset;
  2154. }
  2155. }
  2156. if ( empty( $this->col_meta[ $tablekey ][ $columnkey ] ) ) {
  2157. return false;
  2158. }
  2159. $typeinfo = explode( '(', $this->col_meta[ $tablekey ][ $columnkey ]->Type );
  2160. $type = strtolower( $typeinfo[0] );
  2161. if ( ! empty( $typeinfo[1] ) ) {
  2162. $length = trim( $typeinfo[1], ')' );
  2163. } else {
  2164. $length = false;
  2165. }
  2166. switch( $type ) {
  2167. case 'char':
  2168. case 'varchar':
  2169. return array(
  2170. 'type' => 'char',
  2171. 'length' => (int) $length,
  2172. );
  2173. break;
  2174. case 'binary':
  2175. case 'varbinary':
  2176. return array(
  2177. 'type' => 'byte',
  2178. 'length' => (int) $length,
  2179. );
  2180. break;
  2181. case 'tinyblob':
  2182. case 'tinytext':
  2183. return array(
  2184. 'type' => 'byte',
  2185. 'length' => 255, // 2^8 - 1
  2186. );
  2187. break;
  2188. case 'blob':
  2189. case 'text':
  2190. return array(
  2191. 'type' => 'byte',
  2192. 'length' => 65535, // 2^16 - 1
  2193. );
  2194. break;
  2195. case 'mediumblob':
  2196. case 'mediumtext':
  2197. return array(
  2198. 'type' => 'byte',
  2199. 'length' => 16777215, // 2^24 - 1
  2200. );
  2201. break;
  2202. case 'longblob':
  2203. case 'longtext':
  2204. return array(
  2205. 'type' => 'byte',
  2206. 'length' => 4294967295, // 2^32 - 1
  2207. );
  2208. break;
  2209. default:
  2210. return false;
  2211. }
  2212. return false;
  2213. }
  2214. /**
  2215. * Check if a string is ASCII.
  2216. *
  2217. * The negative regex is faster for non-ASCII strings, as it allows
  2218. * the search to finish as soon as it encounters a non-ASCII character.
  2219. *
  2220. * @since 4.2.0
  2221. * @access protected
  2222. *
  2223. * @param string $string String to check.
  2224. * @return bool True if ASCII, false if not.
  2225. */
  2226. protected function check_ascii( $string ) {
  2227. if ( function_exists( 'mb_check_encoding' ) ) {
  2228. if ( mb_check_encoding( $string, 'ASCII' ) ) {
  2229. return true;
  2230. }
  2231. } elseif ( ! preg_match( '/[^\x00-\x7F]/', $string ) ) {
  2232. return true;
  2233. }
  2234. return false;
  2235. }
  2236. /**
  2237. * Check if the query is accessing a collation considered safe on the current version of MySQL.
  2238. *
  2239. * @since 4.2.0
  2240. * @access protected
  2241. *
  2242. * @param string $query The query to check.
  2243. * @return bool True if the collation is safe, false if it isn't.
  2244. */
  2245. protected function check_safe_collation( $query ) {
  2246. if ( $this->checking_collation ) {
  2247. return true;
  2248. }
  2249. // We don't need to check the collation for queries that don't read data.
  2250. $query = ltrim( $query, "\r\n\t (" );
  2251. if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN|CREATE)\s/i', $query ) ) {
  2252. return true;
  2253. }
  2254. // All-ASCII queries don't need extra checking.
  2255. if ( $this->check_ascii( $query ) ) {
  2256. return true;
  2257. }
  2258. $table = $this->get_table_from_query( $query );
  2259. if ( ! $table ) {
  2260. return false;
  2261. }
  2262. $this->checking_collation = true;
  2263. $collation = $this->get_table_charset( $table );
  2264. $this->checking_collation = false;
  2265. // Tables with no collation, or latin1 only, don't need extra checking.
  2266. if ( false === $collation || 'latin1' === $collation ) {
  2267. return true;
  2268. }
  2269. $table = strtolower( $table );
  2270. if ( empty( $this->col_meta[ $table ] ) ) {
  2271. return false;
  2272. }
  2273. // If any of the columns don't have one of these collations, it needs more sanity checking.
  2274. foreach( $this->col_meta[ $table ] as $col ) {
  2275. if ( empty( $col->Collation ) ) {
  2276. continue;
  2277. }
  2278. if ( ! in_array( $col->Collation, array( 'utf8_general_ci', 'utf8_bin', 'utf8mb4_general_ci', 'utf8mb4_bin' ), true ) ) {
  2279. return false;
  2280. }
  2281. }
  2282. return true;
  2283. }
  2284. /**
  2285. * Strips any invalid characters based on value/charset pairs.
  2286. *
  2287. * @since 4.2.0
  2288. * @access protected
  2289. *
  2290. * @param array $data Array of value arrays. Each value array has the keys
  2291. * 'value' and 'charset'. An optional 'ascii' key can be
  2292. * set to false to avoid redundant ASCII checks.
  2293. * @return array|WP_Error The $data parameter, with invalid characters removed from
  2294. * each value. This works as a passthrough: any additional keys
  2295. * such as 'field' are retained in each value array. If we cannot
  2296. * remove invalid characters, a WP_Error object is returned.
  2297. */
  2298. protected function strip_invalid_text( $data ) {
  2299. $db_check_string = false;
  2300. foreach ( $data as &$value ) {
  2301. $charset = $value['charset'];
  2302. if ( is_array( $value['length'] ) ) {
  2303. $length = $value['length']['length'];
  2304. } else {
  2305. $length = false;
  2306. }
  2307. // There's no charset to work with.
  2308. if ( false === $charset ) {
  2309. continue;
  2310. }
  2311. // Column isn't a string.
  2312. if ( ! is_string( $value['value'] ) ) {
  2313. continue;
  2314. }
  2315. $truncate_by_byte_length = 'byte' === $value['length']['type'];
  2316. $needs_validation = true;
  2317. if (
  2318. // latin1 can store any byte sequence
  2319. 'latin1' === $charset
  2320. ||
  2321. // ASCII is always OK.
  2322. ( ! isset( $value['ascii'] ) && $this->check_ascii( $value['value'] ) )
  2323. ) {
  2324. $truncate_by_byte_length = true;
  2325. $needs_validation = false;
  2326. }
  2327. if ( $truncate_by_byte_length ) {
  2328. mbstring_binary_safe_encoding();
  2329. if ( false !== $length && strlen( $value['value'] ) > $length ) {
  2330. $value['value'] = substr( $value['value'], 0, $length );
  2331. }
  2332. reset_mbstring_encoding();
  2333. if ( ! $needs_validation ) {
  2334. continue;
  2335. }
  2336. }
  2337. // utf8 can be handled by regex, which is a bunch faster than a DB lookup.
  2338. if ( ( 'utf8' === $charset || 'utf8mb3' === $charset || 'utf8mb4' === $charset ) && function_exists( 'mb_strlen' ) ) {
  2339. $regex = '/
  2340. (
  2341. (?: [\x00-\x7F] # single-byte sequences 0xxxxxxx
  2342. | [\xC2-\xDF][\x80-\xBF] # double-byte sequences 110xxxxx 10xxxxxx
  2343. | \xE0[\xA0-\xBF][\x80-\xBF] # triple-byte sequences 1110xxxx 10xxxxxx * 2
  2344. | [\xE1-\xEC][\x80-\xBF]{2}
  2345. | \xED[\x80-\x9F][\x80-\xBF]
  2346. | [\xEE-\xEF][\x80-\xBF]{2}';
  2347. if ( 'utf8mb4' === $charset ) {
  2348. $regex .= '
  2349. | \xF0[\x90-\xBF][\x80-\xBF]{2} # four-byte sequences 11110xxx 10xxxxxx * 3
  2350. | [\xF1-\xF3][\x80-\xBF]{3}
  2351. | \xF4[\x80-\x8F][\x80-\xBF]{2}
  2352. ';
  2353. }
  2354. $regex .= '){1,40} # ...one or more times
  2355. )
  2356. | . # anything else
  2357. /x';
  2358. $value['value'] = preg_replace( $regex, '$1', $value['value'] );
  2359. if ( false !== $length && mb_strlen( $value['value'], 'UTF-8' ) > $length ) {
  2360. $value['value'] = mb_substr( $value['value'], 0, $length, 'UTF-8' );
  2361. }
  2362. continue;
  2363. }
  2364. // We couldn't use any local conversions, send it to the DB.
  2365. $value['db'] = $db_check_string = true;
  2366. }
  2367. unset( $value ); // Remove by reference.
  2368. if ( $db_check_string ) {
  2369. $queries = array();
  2370. foreach ( $data as $col => $value ) {
  2371. if ( ! empty( $value['db'] ) ) {
  2372. if ( ! isset( $queries[ $value['charset'] ] ) ) {
  2373. $queries[ $value['charset'] ] = array();
  2374. }
  2375. // We're going to need to truncate by characters or bytes, depending on the length value we have.
  2376. if ( 'byte' === $value['length']['type'] ) {
  2377. // Split the CONVERT() calls by charset, so we can make sure the connection is right
  2378. $queries[ $value['charset'] ][ $col ] = $this->prepare( "CONVERT( LEFT( CONVERT( %s USING binary ), %d ) USING {$value['charset']} )", $value['value'], $value['length']['length'] );
  2379. } else {
  2380. $queries[ $value['charset'] ][ $col ] = $this->prepare( "LEFT( CONVERT( %s USING {$value['charset']} ), %d )", $value['value'], $value['length']['length'] );
  2381. }
  2382. unset( $data[ $col ]['db'] );
  2383. }
  2384. }
  2385. $connection_charset = $this->charset;
  2386. foreach ( $queries as $charset => $query ) {
  2387. if ( ! $query ) {
  2388. continue;
  2389. }
  2390. // Change the charset to match the string(s) we're converting
  2391. if ( $charset !== $connection_charset ) {
  2392. $connection_charset = $charset;
  2393. $this->set_charset( $this->dbh, $charset );
  2394. }
  2395. $this->check_current_query = false;
  2396. $sql = array();
  2397. foreach ( $query as $column => $column_query ) {
  2398. $sql[] = $column_query . " AS x_$column";
  2399. }
  2400. $row = $this->get_row( "SELECT " . implode( ', ', $sql ), ARRAY_A );
  2401. if ( ! $row ) {
  2402. $this->set_charset( $this->dbh, $connection_charset );
  2403. return new WP_Error( 'wpdb_strip_invalid_text_failure' );
  2404. }
  2405. foreach ( array_keys( $query ) as $column ) {
  2406. $data[ $column ]['value'] = $row["x_$column"];
  2407. }
  2408. }
  2409. // Don't forget to change the charset back!
  2410. if ( $connection_charset !== $this->charset ) {
  2411. $this->set_charset( $this->dbh );
  2412. }
  2413. }
  2414. return $data;
  2415. }
  2416. /**
  2417. * Strips any invalid characters from the query.
  2418. *
  2419. * @since 4.2.0
  2420. * @access protected
  2421. *
  2422. * @param string $query Query to convert.
  2423. * @return string|WP_Error The converted query, or a WP_Error object if the conversion fails.
  2424. */
  2425. protected function strip_invalid_text_from_query( $query ) {
  2426. // We don't need to check the collation for queries that don't read data.
  2427. $trimmed_query = ltrim( $query, "\r\n\t (" );
  2428. if ( preg_match( '/^(?:SHOW|DESCRIBE|DESC|EXPLAIN|CREATE)\s/i', $trimmed_query ) ) {
  2429. return $query;
  2430. }
  2431. $table = $this->get_table_from_query( $query );
  2432. if ( $table ) {
  2433. $charset = $this->get_table_charset( $table );
  2434. if ( is_wp_error( $charset ) ) {
  2435. return $charset;
  2436. }
  2437. // We can't reliably strip text from tables containing binary/blob columns
  2438. if ( 'binary' === $charset ) {
  2439. return $query;
  2440. }
  2441. } else {
  2442. $charset = $this->charset;
  2443. }
  2444. $data = array(
  2445. 'value' => $query,
  2446. 'charset' => $charset,
  2447. 'ascii' => false,
  2448. 'length' => false,
  2449. );
  2450. $data = $this->strip_invalid_text( array( $data ) );
  2451. if ( is_wp_error( $data ) ) {
  2452. return $data;
  2453. }
  2454. return $data[0]['value'];
  2455. }
  2456. /**
  2457. * Strips any invalid characters from the string for a given table and column.
  2458. *
  2459. * @since 4.2.0
  2460. * @access public
  2461. *
  2462. * @param string $table Table name.
  2463. * @param string $column Column name.
  2464. * @param string $value The text to check.
  2465. * @return string|WP_Error The converted string, or a WP_Error object if the conversion fails.
  2466. */
  2467. public function strip_invalid_text_for_column( $table, $column, $value ) {
  2468. if ( ! is_string( $value ) ) {
  2469. return $value;
  2470. }
  2471. $charset = $this->get_col_charset( $table, $column );
  2472. if ( ! $charset ) {
  2473. // Not a string column.
  2474. return $value;
  2475. } elseif ( is_wp_error( $charset ) ) {
  2476. // Bail on real errors.
  2477. return $charset;
  2478. }
  2479. $data = array(
  2480. $column => array(
  2481. 'value' => $value,
  2482. 'charset' => $charset,
  2483. 'length' => $this->get_col_length( $table, $column ),
  2484. )
  2485. );
  2486. $data = $this->strip_invalid_text( $data );
  2487. if ( is_wp_error( $data ) ) {
  2488. return $data;
  2489. }
  2490. return $data[ $column ]['value'];
  2491. }
  2492. /**
  2493. * Find the first table name referenced in a query.
  2494. *
  2495. * @since 4.2.0
  2496. * @access protected
  2497. *
  2498. * @param string $query The query to search.
  2499. * @return string|false $table The table name found, or false if a table couldn't be found.
  2500. */
  2501. protected function get_table_from_query( $query ) {
  2502. // Remove characters that can legally trail the table name.
  2503. $query = rtrim( $query, ';/-#' );
  2504. // Allow (select...) union [...] style queries. Use the first query's table name.
  2505. $query = ltrim( $query, "\r\n\t (" );
  2506. /*
  2507. * Strip everything between parentheses except nested selects and use only 1,000
  2508. * chars of the query.
  2509. */
  2510. $query = preg_replace( '/\((?!\s*select)[^(]*?\)/is', '()', substr( $query, 0, 1000 ) );
  2511. // Quickly match most common queries.
  2512. if ( preg_match( '/^\s*(?:'
  2513. . 'SELECT.*?\s+FROM'
  2514. . '|INSERT(?:\s+LOW_PRIORITY|\s+DELAYED|\s+HIGH_PRIORITY)?(?:\s+IGNORE)?(?:\s+INTO)?'
  2515. . '|REPLACE(?:\s+LOW_PRIORITY|\s+DELAYED)?(?:\s+INTO)?'
  2516. . '|UPDATE(?:\s+LOW_PRIORITY)?(?:\s+IGNORE)?'
  2517. . '|DELETE(?:\s+LOW_PRIORITY|\s+QUICK|\s+IGNORE)*(?:\s+FROM)?'
  2518. . ')\s+((?:[0-9a-zA-Z$_.`]|[\xC2-\xDF][\x80-\xBF])+)/is', $query, $maybe ) ) {
  2519. return str_replace( '`', '', $maybe[1] );
  2520. }
  2521. // SHOW TABLE STATUS and SHOW TABLES
  2522. if ( preg_match( '/^\s*(?:'
  2523. . 'SHOW\s+TABLE\s+STATUS.+(?:LIKE\s+|WHERE\s+Name\s*=\s*)'
  2524. . '|SHOW\s+(?:FULL\s+)?TABLES.+(?:LIKE\s+|WHERE\s+Name\s*=\s*)'
  2525. . ')\W((?:[0-9a-zA-Z$_.`]|[\xC2-\xDF][\x80-\xBF])+)\W/is', $query, $maybe ) ) {
  2526. return str_replace( '`', '', $maybe[1] );
  2527. }
  2528. // Big pattern for the rest of the table-related queries.
  2529. if ( preg_match( '/^\s*(?:'
  2530. . '(?:EXPLAIN\s+(?:EXTENDED\s+)?)?SELECT.*?\s+FROM'
  2531. . '|DESCRIBE|DESC|EXPLAIN|HANDLER'
  2532. . '|(?:LOCK|UNLOCK)\s+TABLE(?:S)?'
  2533. . '|(?:RENAME|OPTIMIZE|BACKUP|RESTORE|CHECK|CHECKSUM|ANALYZE|REPAIR).*\s+TABLE'
  2534. . '|TRUNCATE(?:\s+TABLE)?'
  2535. . '|CREATE(?:\s+TEMPORARY)?\s+TABLE(?:\s+IF\s+NOT\s+EXISTS)?'
  2536. . '|ALTER(?:\s+IGNORE)?\s+TABLE'
  2537. . '|DROP\s+TABLE(?:\s+IF\s+EXISTS)?'
  2538. . '|CREATE(?:\s+\w+)?\s+INDEX.*\s+ON'
  2539. . '|DROP\s+INDEX.*\s+ON'
  2540. . '|LOAD\s+DATA.*INFILE.*INTO\s+TABLE'
  2541. . '|(?:GRANT|REVOKE).*ON\s+TABLE'
  2542. . '|SHOW\s+(?:.*FROM|.*TABLE)'
  2543. . ')\s+\(*\s*((?:[0-9a-zA-Z$_.`]|[\xC2-\xDF][\x80-\xBF])+)\s*\)*/is', $query, $maybe ) ) {
  2544. return str_replace( '`', '', $maybe[1] );
  2545. }
  2546. return false;
  2547. }
  2548. /**
  2549. * Load the column metadata from the last query.
  2550. *
  2551. * @since 3.5.0
  2552. *
  2553. * @access protected
  2554. */
  2555. protected function load_col_info() {
  2556. if ( $this->col_info )
  2557. return;
  2558. if ( $this->use_mysqli ) {
  2559. for ( $i = 0; $i < @mysqli_num_fields( $this->result ); $i++ ) {
  2560. $this->col_info[ $i ] = @mysqli_fetch_field( $this->result );
  2561. }
  2562. } else {
  2563. for ( $i = 0; $i < @mysql_num_fields( $this->result ); $i++ ) {
  2564. $this->col_info[ $i ] = @mysql_fetch_field( $this->result, $i );
  2565. }
  2566. }
  2567. }
  2568. /**
  2569. * Retrieve column metadata from the last query.
  2570. *
  2571. * @since 0.71
  2572. *
  2573. * @param string $info_type Optional. Type one of name, table, def, max_length, not_null, primary_key, multiple_key, unique_key, numeric, blob, type, unsigned, zerofill
  2574. * @param int $col_offset Optional. 0: col name. 1: which table the col's in. 2: col's max length. 3: if the col is numeric. 4: col's type
  2575. * @return mixed Column Results
  2576. */
  2577. public function get_col_info( $info_type = 'name', $col_offset = -1 ) {
  2578. $this->load_col_info();
  2579. if ( $this->col_info ) {
  2580. if ( $col_offset == -1 ) {
  2581. $i = 0;
  2582. $new_array = array();
  2583. foreach( (array) $this->col_info as $col ) {
  2584. $new_array[$i] = $col->{$info_type};
  2585. $i++;
  2586. }
  2587. return $new_array;
  2588. } else {
  2589. return $this->col_info[$col_offset]->{$info_type};
  2590. }
  2591. }
  2592. }
  2593. /**
  2594. * Starts the timer, for debugging purposes.
  2595. *
  2596. * @since 1.5.0
  2597. *
  2598. * @return bool
  2599. */
  2600. public function timer_start() {
  2601. $this->time_start = microtime( true );
  2602. return true;
  2603. }
  2604. /**
  2605. * Stops the debugging timer.
  2606. *
  2607. * @since 1.5.0
  2608. *
  2609. * @return float Total time spent on the query, in seconds
  2610. */
  2611. public function timer_stop() {
  2612. return ( microtime( true ) - $this->time_start );
  2613. }
  2614. /**
  2615. * Wraps errors in a nice header and footer and dies.
  2616. *
  2617. * Will not die if wpdb::$show_errors is false.
  2618. *
  2619. * @since 1.5.0
  2620. *
  2621. * @param string $message The Error message
  2622. * @param string $error_code Optional. A Computer readable string to identify the error.
  2623. * @return false|void
  2624. */
  2625. public function bail( $message, $error_code = '500' ) {
  2626. if ( !$this->show_errors ) {
  2627. if ( class_exists( 'WP_Error' ) )
  2628. $this->error = new WP_Error($error_code, $message);
  2629. else
  2630. $this->error = $message;
  2631. return false;
  2632. }
  2633. wp_die($message);
  2634. }
  2635. /**
  2636. * Whether MySQL database is at least the required minimum version.
  2637. *
  2638. * @since 2.5.0
  2639. * @uses $wp_version
  2640. * @uses $required_mysql_version
  2641. *
  2642. * @return WP_Error
  2643. */
  2644. public function check_database_version() {
  2645. global $wp_version, $required_mysql_version;
  2646. // Make sure the server has the required MySQL version
  2647. if ( version_compare($this->db_version(), $required_mysql_version, '<') )
  2648. return new WP_Error('database_version', sprintf( __( '<strong>ERROR</strong>: WordPress %1$s requires MySQL %2$s or higher' ), $wp_version, $required_mysql_version ));
  2649. }
  2650. /**
  2651. * Whether the database supports collation.
  2652. *
  2653. * Called when WordPress is generating the table scheme.
  2654. *
  2655. * @since 2.5.0
  2656. * @deprecated 3.5.0
  2657. * @deprecated Use wpdb::has_cap( 'collation' )
  2658. *
  2659. * @return bool True if collation is supported, false if version does not
  2660. */
  2661. public function supports_collation() {
  2662. _deprecated_function( __FUNCTION__, '3.5', 'wpdb::has_cap( \'collation\' )' );
  2663. return $this->has_cap( 'collation' );
  2664. }
  2665. /**
  2666. * The database character collate.
  2667. *
  2668. * @since 3.5.0
  2669. *
  2670. * @return string The database character collate.
  2671. */
  2672. public function get_charset_collate() {
  2673. $charset_collate = '';
  2674. if ( ! empty( $this->charset ) )
  2675. $charset_collate = "DEFAULT CHARACTER SET $this->charset";
  2676. if ( ! empty( $this->collate ) )
  2677. $charset_collate .= " COLLATE $this->collate";
  2678. return $charset_collate;
  2679. }
  2680. /**
  2681. * Determine if a database supports a particular feature.
  2682. *
  2683. * @since 2.7.0
  2684. * @since 4.1.0 Support was added for the 'utf8mb4' feature.
  2685. *
  2686. * @see wpdb::db_version()
  2687. *
  2688. * @param string $db_cap The feature to check for. Accepts 'collation',
  2689. * 'group_concat', 'subqueries', 'set_charset',
  2690. * or 'utf8mb4'.
  2691. * @return bool Whether the database feature is supported, false otherwise.
  2692. */
  2693. public function has_cap( $db_cap ) {
  2694. $version = $this->db_version();
  2695. switch ( strtolower( $db_cap ) ) {
  2696. case 'collation' : // @since 2.5.0
  2697. case 'group_concat' : // @since 2.7.0
  2698. case 'subqueries' : // @since 2.7.0
  2699. return version_compare( $version, '4.1', '>=' );
  2700. case 'set_charset' :
  2701. return version_compare( $version, '5.0.7', '>=' );
  2702. case 'utf8mb4' : // @since 4.1.0
  2703. if ( version_compare( $version, '5.5.3', '<' ) ) {
  2704. return false;
  2705. }
  2706. if ( $this->use_mysqli ) {
  2707. $client_version = mysqli_get_client_info();
  2708. } else {
  2709. $client_version = mysql_get_client_info();
  2710. }
  2711. /*
  2712. * libmysql has supported utf8mb4 since 5.5.3, same as the MySQL server.
  2713. * mysqlnd has supported utf8mb4 since 5.0.9.
  2714. */
  2715. if ( false !== strpos( $client_version, 'mysqlnd' ) ) {
  2716. $client_version = preg_replace( '/^\D+([\d.]+).*/', '$1', $client_version );
  2717. return version_compare( $client_version, '5.0.9', '>=' );
  2718. } else {
  2719. return version_compare( $client_version, '5.5.3', '>=' );
  2720. }
  2721. }
  2722. return false;
  2723. }
  2724. /**
  2725. * Retrieve the name of the function that called wpdb.
  2726. *
  2727. * Searches up the list of functions until it reaches
  2728. * the one that would most logically had called this method.
  2729. *
  2730. * @since 2.5.0
  2731. *
  2732. * @return string The name of the calling function
  2733. */
  2734. public function get_caller() {
  2735. return wp_debug_backtrace_summary( __CLASS__ );
  2736. }
  2737. /**
  2738. * The database version number.
  2739. *
  2740. * @since 2.7.0
  2741. *
  2742. * @return null|string Null on failure, version number on success.
  2743. */
  2744. public function db_version() {
  2745. if ( $this->use_mysqli ) {
  2746. $server_info = mysqli_get_server_info( $this->dbh );
  2747. } else {
  2748. $server_info = mysql_get_server_info( $this->dbh );
  2749. }
  2750. return preg_replace( '/[^0-9.].*/', '', $server_info );
  2751. }
  2752. }