PageRenderTime 76ms CodeModel.GetById 22ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/wp-db.php

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