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