PageRenderTime 75ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/wp-db.php

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