wpdb

WordPress Database Access Abstraction Object.

Defined (1)

The class is defined in the following location(s).

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