PageRenderTime 55ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 1ms

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

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