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

/wp-includes/wp-db.php

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