PageRenderTime 66ms CodeModel.GetById 33ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-includes/wp-db.php

https://github.com/alx/blogsfera
PHP | 1071 lines | 449 code | 120 blank | 502 comment | 106 complexity | bb811da688058bd5c6c2e593768726b4 MD5 | raw file
Possible License(s): CC-BY-SA-3.0, GPL-2.0
  1. <?php
  2. /**
  3. * WordPress DB Class
  4. *
  5. * Original code from {@link http://php.justinvincent.com Justin Vincent (justin@visunet.ie)}
  6. *
  7. * @package WordPress
  8. * @subpackage Database
  9. * @since 0.71
  10. */
  11. /**
  12. * @since 0.71
  13. */
  14. define('EZSQL_VERSION', 'WP1.25');
  15. /**
  16. * @since 0.71
  17. */
  18. define('OBJECT', 'OBJECT', true);
  19. /**
  20. * @since {@internal Version Unknown}}
  21. */
  22. define('OBJECT_K', 'OBJECT_K', false);
  23. /**
  24. * @since 0.71
  25. */
  26. define('ARRAY_A', 'ARRAY_A', false);
  27. /**
  28. * @since 0.71
  29. */
  30. define('ARRAY_N', 'ARRAY_N', false);
  31. /**
  32. * WordPress Database Access Abstraction Object
  33. *
  34. * It is possible to replace this class with your own
  35. * by setting the $wpdb global variable in wp-content/wpdb.php
  36. * file with your class. You can name it wpdb also, since
  37. * this file will not be included, if the other file is
  38. * available.
  39. *
  40. * @link http://codex.wordpress.org/Function_Reference/wpdb_Class
  41. *
  42. * @package WordPress
  43. * @subpackage Database
  44. * @since 0.71
  45. * @final
  46. */
  47. class wpdb {
  48. /**
  49. * Whether to show SQL/DB errors
  50. *
  51. * @since 0.71
  52. * @access private
  53. * @var bool
  54. */
  55. var $show_errors = false;
  56. /**
  57. * Whether to suppress errors during the DB bootstrapping.
  58. *
  59. * @access private
  60. * @since {@internal Version Unknown}}
  61. * @var bool
  62. */
  63. var $suppress_errors = false;
  64. /**
  65. * The last error during query.
  66. *
  67. * @since {@internal Version Unknown}}
  68. * @var string
  69. */
  70. var $last_error = '';
  71. /**
  72. * Amount of queries made
  73. *
  74. * @since 1.2.0
  75. * @access private
  76. * @var int
  77. */
  78. var $num_queries = 0;
  79. /**
  80. * Saved result of the last query made
  81. *
  82. * @since 1.2.0
  83. * @access private
  84. * @var array
  85. */
  86. var $last_query;
  87. /**
  88. * Saved info on the table column
  89. *
  90. * @since 1.2.0
  91. * @access private
  92. * @var array
  93. */
  94. var $col_info;
  95. /**
  96. * Saved queries that were executed
  97. *
  98. * @since 1.5.0
  99. * @access private
  100. * @var array
  101. */
  102. var $queries;
  103. /**
  104. * WordPress table prefix
  105. *
  106. * You can set this to have multiple WordPress installations
  107. * in a single database. The second reason is for possible
  108. * security precautions.
  109. *
  110. * @since 0.71
  111. * @access private
  112. * @var string
  113. */
  114. var $prefix = '';
  115. /**
  116. * Whether the database queries are ready to start executing.
  117. *
  118. * @since 2.5.0
  119. * @access private
  120. * @var bool
  121. */
  122. var $ready = false;
  123. var $blogid = 0;
  124. var $siteid = 0;
  125. var $blogs;
  126. var $signups;
  127. var $site;
  128. var $sitemeta;
  129. var $sitecategories;
  130. var $global_tables = array('blogs', 'signups', 'site', 'sitemeta', 'users', 'usermeta', 'sitecategories', 'registration_log', 'blog_versions');
  131. /**
  132. * WordPress Posts table
  133. *
  134. * @since 1.5.0
  135. * @access public
  136. * @var string
  137. */
  138. var $posts;
  139. /**
  140. * WordPress Users table
  141. *
  142. * @since 1.5.0
  143. * @access public
  144. * @var string
  145. */
  146. var $users;
  147. /**
  148. * WordPress Categories table
  149. *
  150. * @since 1.5.0
  151. * @access public
  152. * @var string
  153. */
  154. var $categories;
  155. /**
  156. * WordPress Post to Category table
  157. *
  158. * @since 1.5.0
  159. * @access public
  160. * @var string
  161. */
  162. var $post2cat;
  163. /**
  164. * WordPress Comments table
  165. *
  166. * @since 1.5.0
  167. * @access public
  168. * @var string
  169. */
  170. var $comments;
  171. /**
  172. * WordPress Links table
  173. *
  174. * @since 1.5.0
  175. * @access public
  176. * @var string
  177. */
  178. var $links;
  179. /**
  180. * WordPress Options table
  181. *
  182. * @since 1.5.0
  183. * @access public
  184. * @var string
  185. */
  186. var $options;
  187. /**
  188. * WordPress Post Metadata table
  189. *
  190. * @since {@internal Version Unknown}}
  191. * @access public
  192. * @var string
  193. */
  194. var $postmeta;
  195. /**
  196. * WordPress User Metadata table
  197. *
  198. * @since 2.3.0
  199. * @access public
  200. * @var string
  201. */
  202. var $usermeta;
  203. /**
  204. * WordPress Terms table
  205. *
  206. * @since 2.3.0
  207. * @access public
  208. * @var string
  209. */
  210. var $terms;
  211. /**
  212. * WordPress Term Taxonomy table
  213. *
  214. * @since 2.3.0
  215. * @access public
  216. * @var string
  217. */
  218. var $term_taxonomy;
  219. /**
  220. * WordPress Term Relationships table
  221. *
  222. * @since 2.3.0
  223. * @access public
  224. * @var string
  225. */
  226. var $term_relationships;
  227. /**
  228. * List of WordPress tables
  229. *
  230. * @since {@internal Version Unknown}}
  231. * @access private
  232. * @var array
  233. */
  234. var $blog_tables = array('posts', 'categories', 'post2cat', 'comments', 'links', 'link2cat', 'options',
  235. 'postmeta', 'terms', 'term_taxonomy', 'term_relationships');
  236. /**
  237. * Database table columns charset
  238. *
  239. * @since 2.2.0
  240. * @access public
  241. * @var string
  242. */
  243. var $charset;
  244. /**
  245. * Database table columns collate
  246. *
  247. * @since 2.2.0
  248. * @access public
  249. * @var string
  250. */
  251. var $collate;
  252. /**
  253. * Connects to the database server and selects a database
  254. *
  255. * PHP4 compatibility layer for calling the PHP5 constructor.
  256. *
  257. * @uses wpdb::__construct() Passes parameters and returns result
  258. * @since 0.71
  259. *
  260. * @param string $dbuser MySQL database user
  261. * @param string $dbpassword MySQL database password
  262. * @param string $dbname MySQL database name
  263. * @param string $dbhost MySQL database host
  264. */
  265. function wpdb($dbuser, $dbpassword, $dbname, $dbhost) {
  266. if( defined( "WP_USE_MULTIPLE_DB" ) && CONSTANT( "WP_USE_MULTIPLE_DB" ) == true )
  267. $this->db_connect();
  268. return $this->__construct($dbuser, $dbpassword, $dbname, $dbhost);
  269. }
  270. /**
  271. * Connects to the database server and selects a database
  272. *
  273. * PHP5 style constructor for compatibility with PHP5. Does
  274. * the actual setting up of the class properties and connection
  275. * to the database.
  276. *
  277. * @since 2.0.8
  278. *
  279. * @param string $dbuser MySQL database user
  280. * @param string $dbpassword MySQL database password
  281. * @param string $dbname MySQL database name
  282. * @param string $dbhost MySQL database host
  283. */
  284. function __construct($dbuser, $dbpassword, $dbname, $dbhost) {
  285. register_shutdown_function(array(&$this, "__destruct"));
  286. if ( defined('WP_DEBUG') and WP_DEBUG == true )
  287. $this->show_errors();
  288. $this->charset = 'utf8';
  289. if( defined( 'DB_COLLATE' ) && constant( 'DB_COLLATE' ) != '' ) {
  290. $this->collate = constant( 'DB_COLLATE' );
  291. } else {
  292. $this->collate = 'utf8_general_ci';
  293. }
  294. if ( defined('DB_CHARSET') )
  295. $this->charset = DB_CHARSET;
  296. if ( defined('DB_COLLATE') )
  297. $this->collate = DB_COLLATE;
  298. $this->dbh = @mysql_connect($dbhost, $dbuser, $dbpassword, true);
  299. if (!$this->dbh) {
  300. $this->bail(sprintf(/*WP_I18N_DB_CONN_ERROR*/"
  301. <h1>Error establishing a database connection</h1>
  302. <p>This either means that the username and password information in your <code>wp-config.php</code> file is incorrect or we can't contact the database server at <code>%s</code>. This could mean your host's database server is down.</p>
  303. <ul>
  304. <li>Are you sure you have the correct username and password?</li>
  305. <li>Are you sure that you have typed the correct hostname?</li>
  306. <li>Are you sure that the database server is running?</li>
  307. </ul>
  308. <p>If you're unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href='http://wordpress.org/support/'>WordPress Support Forums</a>.</p>
  309. "/*/WP_I18N_DB_CONN_ERROR*/, $dbhost));
  310. return;
  311. }
  312. $this->ready = true;
  313. if ( $this->supports_collation() ) {
  314. $collation_query = '';
  315. if ( !empty($this->charset) ) {
  316. $collation_query = "SET NAMES '{$this->charset}'";
  317. if (!empty($this->collate) )
  318. $collation_query .= " COLLATE '{$this->collate}'";
  319. }
  320. if ( !empty($collation_query) )
  321. $this->query($collation_query);
  322. }
  323. $this->select($dbname, $this->dbh);
  324. }
  325. /**
  326. * PHP5 style destructor and will run when database object is destroyed.
  327. *
  328. * @since 2.0.8
  329. *
  330. * @return bool Always true
  331. */
  332. function __destruct() {
  333. return true;
  334. }
  335. /**
  336. * Sets the table prefix for the WordPress tables.
  337. *
  338. * Also allows for the CUSTOM_USER_TABLE and CUSTOM_USER_META_TABLE to
  339. * override the WordPress users and usersmeta tables.
  340. *
  341. * @since 2.5.0
  342. *
  343. * @param string $prefix Alphanumeric name for the new prefix.
  344. * @return string Old prefix
  345. */
  346. function set_prefix($prefix) {
  347. if ( preg_match('|[^a-z0-9_]|i', $prefix) )
  348. return new WP_Error('invalid_db_prefix', /*WP_I18N_DB_BAD_PREFIX*/'Invalid database prefix'/*/WP_I18N_DB_BAD_PREFIX*/);
  349. $old_prefix = $this->base_prefix;
  350. $this->base_prefix = $prefix;
  351. foreach ( $this->global_tables as $table )
  352. $this->$table = $prefix . $table;
  353. if ( empty($this->blogid) )
  354. return $old_prefix;
  355. $this->prefix = $this->base_prefix . $this->blogid . '_';
  356. foreach ( $this->blog_tables as $table )
  357. $this->$table = $this->prefix . $table;
  358. if ( defined('CUSTOM_USER_TABLE') )
  359. $this->users = CUSTOM_USER_TABLE;
  360. if ( defined('CUSTOM_USER_META_TABLE') )
  361. $this->usermeta = CUSTOM_USER_META_TABLE;
  362. return $old_prefix;
  363. }
  364. function set_blog_id($blog_id, $site_id = '') {
  365. if ( !empty($site_id) )
  366. $this->siteid = $site_id;
  367. $old_blog_id = $this->blogid;
  368. $this->blogid = $blog_id;
  369. $this->prefix = $this->base_prefix . $this->blogid . '_';
  370. foreach ( $this->blog_tables as $table )
  371. $this->$table = $this->prefix . $table;
  372. return $old_blog_id;
  373. }
  374. /**
  375. * Selects a database using the current database connection.
  376. *
  377. * The database name will be changed based on the current database
  378. * connection. On failure, the execution will bail and display an DB error.
  379. *
  380. * @since 0.71
  381. *
  382. * @param string $db MySQL database name
  383. * @return null Always null.
  384. */
  385. function select($db, &$dbh) {
  386. if (!@mysql_select_db($db, $dbh)) {
  387. $this->ready = false;
  388. $this->bail(sprintf(/*WP_I18N_DB_SELECT_DB*/'
  389. <h1>Can&#8217;t select database</h1>
  390. <p>We were able to connect to the database server (which means your username and password is okay) but not able to select the <code>%1$s</code> database.</p>
  391. <ul>
  392. <li>Are you sure it exists?</li>
  393. <li>Does the user <code>%2$s</code> have permission to use the <code>%1$s</code> database?</li>
  394. <li>On some systems the name of your database is prefixed with your username, so it would be like username_wordpress. Could that be the problem?</li>
  395. </ul>
  396. <p>If you don\'t know how to setup a database you should <strong>contact your host</strong>. If all else fails you may find help at the <a href="http://wordpress.org/support/">WordPress Support Forums</a>.</p>'/*/WP_I18N_DB_SELECT_DB*/, $db, DB_USER));
  397. return;
  398. }
  399. }
  400. /**
  401. * Escapes content for insertion into the database, for security
  402. *
  403. * @since 0.71
  404. *
  405. * @param string $string
  406. * @return string query safe string
  407. */
  408. function escape($string) {
  409. return addslashes( $string );
  410. // Disable rest for now, causing problems
  411. /*
  412. if( !$this->dbh || version_compare( phpversion(), '4.3.0' ) == '-1' )
  413. return mysql_escape_string( $string );
  414. else
  415. return mysql_real_escape_string( $string, $this->dbh );
  416. */
  417. }
  418. /**
  419. * Escapes content by reference for insertion into the database, for security
  420. *
  421. * @since 2.3.0
  422. *
  423. * @param string $s
  424. */
  425. function escape_by_ref(&$s) {
  426. $s = $this->escape($s);
  427. }
  428. /**
  429. * Prepares a SQL query for safe use, using sprintf() syntax.
  430. *
  431. * @link http://php.net/sprintf See for syntax to use for query string.
  432. * @since 2.3.0
  433. *
  434. * @param null|string $args If string, first parameter must be query statement
  435. * @param mixed $args,... If additional parameters, they will be set inserted into the query.
  436. * @return null|string Sanitized query string
  437. */
  438. function prepare($args=null) {
  439. if ( is_null( $args ) )
  440. return;
  441. $args = func_get_args();
  442. $query = array_shift($args);
  443. $query = str_replace("'%s'", '%s', $query); // in case someone mistakenly already singlequoted it
  444. $query = str_replace('"%s"', '%s', $query); // doublequote unquoting
  445. $query = str_replace('%s', "'%s'", $query); // quote the strings
  446. array_walk($args, array(&$this, 'escape_by_ref'));
  447. return @vsprintf($query, $args);
  448. }
  449. /**
  450. * Print SQL/DB error.
  451. *
  452. * @since 0.71
  453. * @global array $EZSQL_ERROR Stores error information of query and error string
  454. *
  455. * @param string $str The error to display
  456. * @return bool False if the showing of errors is disabled.
  457. */
  458. function print_error($str = '') {
  459. global $EZSQL_ERROR;
  460. if (!$str) $str = mysql_error($this->dbh);
  461. $EZSQL_ERROR[] = array ('query' => $this->last_query, 'error_str' => $str);
  462. if ( $this->suppress_errors )
  463. return false;
  464. if ( $caller = $this->get_caller() )
  465. $error_str = sprintf(/*WP_I18N_DB_QUERY_ERROR_FULL*/'WordPress database error %1$s for query %2$s made by %3$s'/*/WP_I18N_DB_QUERY_ERROR_FULL*/, $str, $this->last_query, $caller);
  466. else
  467. $error_str = sprintf(/*WP_I18N_DB_QUERY_ERROR*/'WordPress database error %1$s for query %2$s'/*/WP_I18N_DB_QUERY_ERROR*/, $str, $this->last_query);
  468. $log_error = true;
  469. if ( ! function_exists('error_log') )
  470. $log_error = false;
  471. $log_file = @ini_get('error_log');
  472. if ( !empty($log_file) && ('syslog' != $log_file) && !is_writable($log_file) )
  473. $log_error = false;
  474. if ( $log_error )
  475. @error_log($error_str, 0);
  476. // Is error output turned on or not..
  477. if ( !$this->show_errors )
  478. return false;
  479. // If there is an error then take note of it
  480. $msg = "WordPress database error: [$str]\n{$this->query}\n";
  481. if( defined( 'ERRORLOGFILE' ) )
  482. error_log( $msg, 3, CONSTANT( 'ERRORLOGFILE' ) );
  483. if( defined( 'DIEONDBERROR' ) )
  484. die( $msg );
  485. }
  486. /**
  487. * Enables showing of database errors.
  488. *
  489. * This function should be used only to enable showing of errors.
  490. * wpdb::hide_errors() should be used instead for hiding of errors. However,
  491. * this function can be used to enable and disable showing of database
  492. * errors.
  493. *
  494. * @since 0.71
  495. *
  496. * @param bool $show Whether to show or hide errors
  497. * @return bool Old value for showing errors.
  498. */
  499. function show_errors( $show = true ) {
  500. $errors = $this->show_errors;
  501. $this->show_errors = $show;
  502. return $errors;
  503. }
  504. /**
  505. * Disables showing of database errors.
  506. *
  507. * @since 0.71
  508. *
  509. * @return bool Whether showing of errors was active or not
  510. */
  511. function hide_errors() {
  512. $show = $this->show_errors;
  513. $this->show_errors = false;
  514. return $show;
  515. }
  516. /**
  517. * Whether to suppress database errors.
  518. *
  519. * @param unknown_type $suppress
  520. * @return unknown
  521. */
  522. function suppress_errors( $suppress = true ) {
  523. $errors = $this->suppress_errors;
  524. $this->suppress_errors = $suppress;
  525. return $errors;
  526. }
  527. /**
  528. * Kill cached query results.
  529. *
  530. * @since 0.71
  531. */
  532. function flush() {
  533. $this->last_result = array();
  534. $this->col_info = null;
  535. $this->last_query = null;
  536. }
  537. function db_connect( $query = "SELECT" ) {
  538. global $db_list, $global_db_list;
  539. if( is_array( $db_list ) == false )
  540. return true;
  541. if( $this->blogs != '' && preg_match("/(" . $this->blogs . "|" . $this->users . "|" . $this->usermeta . "|" . $this->site . "|" . $this->sitemeta . "|" . $this->sitecategories . ")/i",$query) ) {
  542. $action = 'global';
  543. $details = $global_db_list[ mt_rand( 0, count( $global_db_list ) -1 ) ];
  544. $this->db_global = $details;
  545. } elseif ( preg_match("/^\\s*(alter table|create|insert|delete|update|replace) /i",$query) ) {
  546. $action = 'write';
  547. $details = $db_list[ 'write' ][ mt_rand( 0, count( $db_list[ 'write' ] ) -1 ) ];
  548. $this->db_write = $details;
  549. } else {
  550. $action = '';
  551. $details = $db_list[ 'read' ][ mt_rand( 0, count( $db_list[ 'read' ] ) -1 ) ];
  552. $this->db_read = $details;
  553. }
  554. $dbhname = "dbh" . $action;
  555. $this->$dbhname = @mysql_connect( $details[ 'db_host' ], $details[ 'db_user' ], $details[ 'db_password' ] );
  556. if (!$this->$dbhname ) {
  557. $this->bail("
  558. <h1>Error establishing a database connection</h1>
  559. <p>This either means that the username and password information in your <code>wp-config.php</code> file is incorrect or we can't contact the database server at <code>$dbhost</code>. This could mean your host's database server is down.</p>
  560. <ul>
  561. <li>Are you sure you have the correct username and password?</li>
  562. <li>Are you sure that you have typed the correct hostname?</li>
  563. <li>Are you sure that the database server is running?</li>
  564. </ul>
  565. <p>If you're unsure what these terms mean you should probably contact your host. If you still need help you can always visit the <a href='http://wordpress.org/support/'>WordPress Support Forums</a>.</p>
  566. ");
  567. }
  568. $this->select( $details[ 'db_name' ], $this->$dbhname );
  569. }
  570. /**
  571. * Perform a MySQL database query, using current database connection.
  572. *
  573. * More information can be found on the codex page.
  574. *
  575. * @since 0.71
  576. *
  577. * @param string $query
  578. * @return unknown
  579. */
  580. function query($query) {
  581. if ( ! $this->ready )
  582. return false;
  583. // filter the query, if filters are available
  584. // NOTE: some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
  585. if ( function_exists('apply_filters') )
  586. $query = apply_filters('query', $query);
  587. // initialise return
  588. $return_val = 0;
  589. $this->flush();
  590. // Log how the function was called
  591. $this->func_call = "\$db->query(\"$query\")";
  592. // Keep track of the last query for debug..
  593. $this->last_query = $query;
  594. // Perform the query via std mysql_query function..
  595. if ( defined('SAVEQUERIES') && SAVEQUERIES )
  596. $this->timer_start();
  597. // use $this->dbh for read ops, and $this->dbhwrite for write ops
  598. // use $this->dbhglobal for gloal table ops
  599. unset( $dbh );
  600. if( defined( "WP_USE_MULTIPLE_DB" ) && CONSTANT( "WP_USE_MULTIPLE_DB" ) == true ) {
  601. if( $this->blogs != '' && preg_match("/(" . $this->blogs . "|" . $this->users . "|" . $this->usermeta . "|" . $this->site . "|" . $this->sitemeta . "|" . $this->sitecategories . ")/i",$query) ) {
  602. if( false == isset( $this->dbhglobal ) ) {
  603. $this->db_connect( $query );
  604. }
  605. $dbh =& $this->dbhglobal;
  606. $this->last_db_used = "global";
  607. } elseif ( preg_match("/^\\s*(alter table|create|insert|delete|update|replace) /i",$query) ) {
  608. if( false == isset( $this->dbhwrite ) ) {
  609. $this->db_connect( $query );
  610. }
  611. $dbh =& $this->dbhwrite;
  612. $this->last_db_used = "write";
  613. } else {
  614. $dbh =& $this->dbh;
  615. $this->last_db_used = "read";
  616. }
  617. } else {
  618. $dbh =& $this->dbh;
  619. $this->last_db_used = "other/read";
  620. }
  621. $this->result = @mysql_query($query, $dbh);
  622. ++$this->num_queries;
  623. if ( defined('SAVEQUERIES') && SAVEQUERIES )
  624. $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
  625. // If there is an error then take note of it..
  626. if( $dbh ) {
  627. if ( mysql_error( $dbh ) ) {
  628. $this->print_error( mysql_error( $dbh ));
  629. return false;
  630. }
  631. }
  632. if ( preg_match("/^\\s*(insert|delete|update|replace) /i",$query) ) {
  633. $this->rows_affected = mysql_affected_rows($dbh);
  634. // Take note of the insert_id
  635. if ( preg_match("/^\\s*(insert|replace) /i",$query) ) {
  636. $this->insert_id = mysql_insert_id($dbh);
  637. }
  638. // Return number of rows affected
  639. $return_val = $this->rows_affected;
  640. } else {
  641. $i = 0;
  642. while ($i < @mysql_num_fields($this->result)) {
  643. $this->col_info[$i] = @mysql_fetch_field($this->result);
  644. $i++;
  645. }
  646. $num_rows = 0;
  647. while ( $row = @mysql_fetch_object($this->result) ) {
  648. $this->last_result[$num_rows] = $row;
  649. $num_rows++;
  650. }
  651. @mysql_free_result($this->result);
  652. // Log number of rows the query returned
  653. $this->num_rows = $num_rows;
  654. // Return number of rows selected
  655. $return_val = $this->num_rows;
  656. }
  657. return $return_val;
  658. }
  659. /**
  660. * Insert an array of data into a table.
  661. *
  662. * @since 2.5.0
  663. *
  664. * @param string $table WARNING: not sanitized!
  665. * @param array $data Should not already be SQL-escaped
  666. * @return mixed Results of $this->query()
  667. */
  668. function insert($table, $data) {
  669. $data = add_magic_quotes($data);
  670. $fields = array_keys($data);
  671. return $this->query("INSERT INTO $table (`" . implode('`,`',$fields) . "`) VALUES ('".implode("','",$data)."')");
  672. }
  673. /**
  674. * Update a row in the table with an array of data.
  675. *
  676. * @since 2.5.0
  677. *
  678. * @param string $table WARNING: not sanitized!
  679. * @param array $data Should not already be SQL-escaped
  680. * @param array $where A named array of WHERE column => value relationships. Multiple member pairs will be joined with ANDs. WARNING: the column names are not currently sanitized!
  681. * @return mixed Results of $this->query()
  682. */
  683. function update($table, $data, $where){
  684. $data = add_magic_quotes($data);
  685. $bits = $wheres = array();
  686. foreach ( array_keys($data) as $k )
  687. $bits[] = "`$k` = '$data[$k]'";
  688. if ( is_array( $where ) )
  689. foreach ( $where as $c => $v )
  690. $wheres[] = "$c = '" . $this->escape( $v ) . "'";
  691. else
  692. return false;
  693. return $this->query( "UPDATE $table SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres ) );
  694. }
  695. /**
  696. * Retrieve one variable from the database.
  697. *
  698. * This combines the functionality of wpdb::get_row() and wpdb::get_col(),
  699. * so both the column and row can be picked.
  700. *
  701. * It is possible to use this function without executing more queries. If
  702. * you already made a query, you can set the $query to 'null' value and just
  703. * retrieve either the column and row of the last query result.
  704. *
  705. * @since 0.71
  706. *
  707. * @param string $query Can be null as well, for caching
  708. * @param int $x Column num to return
  709. * @param int $y Row num to return
  710. * @return mixed Database query results
  711. */
  712. function get_var($query=null, $x = 0, $y = 0) {
  713. $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
  714. if ( $query )
  715. $this->query($query);
  716. // Extract var out of cached results based x,y vals
  717. if ( !empty( $this->last_result[$y] ) ) {
  718. $values = array_values(get_object_vars($this->last_result[$y]));
  719. }
  720. // If there is a value return it else return null
  721. return (isset($values[$x]) && $values[$x]!=='') ? $values[$x] : null;
  722. }
  723. /**
  724. * Retrieve one row from the database.
  725. *
  726. * @since 0.71
  727. *
  728. * @param string $query SQL query
  729. * @param string $output ARRAY_A | ARRAY_N | OBJECT
  730. * @param int $y Row num to return
  731. * @return mixed Database query results
  732. */
  733. function get_row($query = null, $output = OBJECT, $y = 0) {
  734. $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
  735. if ( $query )
  736. $this->query($query);
  737. else
  738. return null;
  739. if ( !isset($this->last_result[$y]) )
  740. return null;
  741. if ( $output == OBJECT ) {
  742. return $this->last_result[$y] ? $this->last_result[$y] : null;
  743. } elseif ( $output == ARRAY_A ) {
  744. return $this->last_result[$y] ? get_object_vars($this->last_result[$y]) : null;
  745. } elseif ( $output == ARRAY_N ) {
  746. return $this->last_result[$y] ? array_values(get_object_vars($this->last_result[$y])) : null;
  747. } else {
  748. $this->print_error(/*WP_I18N_DB_GETROW_ERROR*/" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N"/*/WP_I18N_DB_GETROW_ERROR*/);
  749. }
  750. }
  751. /**
  752. * Retrieve one column from the database.
  753. *
  754. * @since 0.71
  755. *
  756. * @param string $query Can be null as well, for caching
  757. * @param int $x Col num to return. Starts from 0.
  758. * @return array Column results
  759. */
  760. function get_col($query = null , $x = 0) {
  761. if ( $query )
  762. $this->query($query);
  763. $new_array = array();
  764. // Extract the column values
  765. for ( $i=0; $i < count($this->last_result); $i++ ) {
  766. $new_array[$i] = $this->get_var(null, $x, $i);
  767. }
  768. return $new_array;
  769. }
  770. /**
  771. * Retrieve an entire result set from the database.
  772. *
  773. * @since 0.71
  774. *
  775. * @param string|null $query Can also be null to pull from the cache
  776. * @param string $output ARRAY_A | ARRAY_N | OBJECT_K | OBJECT
  777. * @return mixed Database query results
  778. */
  779. function get_results($query = null, $output = OBJECT) {
  780. $this->func_call = "\$db->get_results(\"$query\", $output)";
  781. if ( $query )
  782. $this->query($query);
  783. else
  784. return null;
  785. if ( $output == OBJECT ) {
  786. // Return an integer-keyed array of row objects
  787. return $this->last_result;
  788. } elseif ( $output == OBJECT_K ) {
  789. // Return an array of row objects with keys from column 1
  790. // (Duplicates are discarded)
  791. foreach ( $this->last_result as $row ) {
  792. $key = array_shift( get_object_vars( $row ) );
  793. if ( !isset( $new_array[ $key ] ) )
  794. $new_array[ $key ] = $row;
  795. }
  796. return $new_array;
  797. } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
  798. // Return an integer-keyed array of...
  799. if ( $this->last_result ) {
  800. $i = 0;
  801. foreach( $this->last_result as $row ) {
  802. if ( $output == ARRAY_N ) {
  803. // ...integer-keyed row arrays
  804. $new_array[$i] = array_values( get_object_vars( $row ) );
  805. } else {
  806. // ...column name-keyed row arrays
  807. $new_array[$i] = get_object_vars( $row );
  808. }
  809. ++$i;
  810. }
  811. return $new_array;
  812. }
  813. }
  814. }
  815. /**
  816. * Retrieve column metadata from the last query.
  817. *
  818. * @since 0.71
  819. *
  820. * @param string $info_type one of name, table, def, max_length, not_null, primary_key, multiple_key, unique_key, numeric, blob, type, unsigned, zerofill
  821. * @param int $col_offset 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
  822. * @return mixed Column Results
  823. */
  824. function get_col_info($info_type = 'name', $col_offset = -1) {
  825. if ( $this->col_info ) {
  826. if ( $col_offset == -1 ) {
  827. $i = 0;
  828. foreach($this->col_info as $col ) {
  829. $new_array[$i] = $col->{$info_type};
  830. $i++;
  831. }
  832. return $new_array;
  833. } else {
  834. return $this->col_info[$col_offset]->{$info_type};
  835. }
  836. }
  837. }
  838. /**
  839. * Starts the timer, for debugging purposes.
  840. *
  841. * @since 1.5.0
  842. *
  843. * @return bool Always returns true
  844. */
  845. function timer_start() {
  846. $mtime = microtime();
  847. $mtime = explode(' ', $mtime);
  848. $this->time_start = $mtime[1] + $mtime[0];
  849. return true;
  850. }
  851. /**
  852. * Stops the debugging timer.
  853. *
  854. * @since 1.5.0
  855. *
  856. * @return int Total time spent on the query, in milliseconds
  857. */
  858. function timer_stop() {
  859. $mtime = microtime();
  860. $mtime = explode(' ', $mtime);
  861. $time_end = $mtime[1] + $mtime[0];
  862. $time_total = $time_end - $this->time_start;
  863. return $time_total;
  864. }
  865. /**
  866. * Wraps fatal errors in a nice header and footer and dies.
  867. *
  868. * @since 1.5.0
  869. *
  870. * @param string $message
  871. * @return unknown
  872. */
  873. function bail($message) {
  874. if ( !$this->show_errors ) {
  875. if ( class_exists('WP_Error') )
  876. $this->error = new WP_Error('500', $message);
  877. else
  878. $this->error = $message;
  879. return false;
  880. }
  881. wp_die($message);
  882. }
  883. /**
  884. * Whether or not MySQL database is minimal required version.
  885. *
  886. * @since 2.5.0
  887. * @uses $wp_version
  888. *
  889. * @return WP_Error
  890. */
  891. function check_database_version()
  892. {
  893. global $wp_version;
  894. // Make sure the server has MySQL 4.0
  895. $mysql_version = preg_replace('|[^0-9\.]|', '', @mysql_get_server_info($this->dbh));
  896. if ( version_compare($mysql_version, '4.0.0', '<') )
  897. return new WP_Error('database_version',sprintf(__('<strong>ERROR</strong>: WordPress %s requires MySQL 4.0.0 or higher'), $wp_version));
  898. }
  899. /**
  900. * Whether of not the database version supports collation.
  901. *
  902. * Called when WordPress is generating the table scheme.
  903. *
  904. * @since 2.5.0
  905. *
  906. * @return bool True if collation is supported, false if version does not
  907. */
  908. function supports_collation()
  909. {
  910. return ( version_compare(mysql_get_server_info($this->dbh), '4.1.0', '>=') );
  911. }
  912. /**
  913. * Retrieve the name of the function that called wpdb.
  914. *
  915. * Requires PHP 4.3 and searches up the list of functions until it reaches
  916. * the one that would most logically had called this method.
  917. *
  918. * @since 2.5.0
  919. *
  920. * @return string The name of the calling function
  921. */
  922. function get_caller() {
  923. // requires PHP 4.3+
  924. if ( !is_callable('debug_backtrace') )
  925. return '';
  926. $bt = debug_backtrace();
  927. $caller = '';
  928. foreach ( $bt as $trace ) {
  929. if ( @$trace['class'] == __CLASS__ )
  930. continue;
  931. elseif ( strtolower(@$trace['function']) == 'call_user_func_array' )
  932. continue;
  933. elseif ( strtolower(@$trace['function']) == 'apply_filters' )
  934. continue;
  935. elseif ( strtolower(@$trace['function']) == 'do_action' )
  936. continue;
  937. $caller = $trace['function'];
  938. break;
  939. }
  940. return $caller;
  941. }
  942. }
  943. if ( ! isset($wpdb) ) {
  944. /**
  945. * WordPress Database Object, if it isn't set already in wp-content/wpdb.php
  946. * @global object $wpdb Creates a new wpdb object based on wp-config.php Constants for the database
  947. * @since 0.71
  948. */
  949. $wpdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
  950. }
  951. ?>