PageRenderTime 65ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/wp-db.php

https://github.com/ianloic/wordpress-svn
PHP | 586 lines | 363 code | 87 blank | 136 comment | 75 complexity | 9c36dfd2adb398148fedaeac2bc6f43c MD5 | raw file
  1. <?php
  2. // WordPress DB Class
  3. // ORIGINAL CODE FROM:
  4. // Justin Vincent (justin@visunet.ie)
  5. // http://php.justinvincent.com
  6. define('EZSQL_VERSION', 'WP1.25');
  7. define('OBJECT', 'OBJECT', true);
  8. define('OBJECT_K', 'OBJECT_K', false);
  9. define('ARRAY_A', 'ARRAY_A', false);
  10. define('ARRAY_N', 'ARRAY_N', false);
  11. if (!defined('SAVEQUERIES'))
  12. define('SAVEQUERIES', false);
  13. class wpdb {
  14. var $show_errors = false;
  15. var $suppress_errors = false;
  16. var $last_error = '';
  17. var $num_queries = 0;
  18. var $last_query;
  19. var $col_info;
  20. var $queries;
  21. var $prefix = '';
  22. var $ready = false;
  23. // Our tables
  24. var $posts;
  25. var $users;
  26. var $categories;
  27. var $post2cat;
  28. var $comments;
  29. var $links;
  30. var $options;
  31. var $postmeta;
  32. var $usermeta;
  33. var $terms;
  34. var $term_taxonomy;
  35. var $term_relationships;
  36. var $tables = array('users', 'usermeta', 'posts', 'categories', 'post2cat', 'comments', 'links', 'link2cat', 'options',
  37. 'postmeta', 'terms', 'term_taxonomy', 'term_relationships');
  38. var $charset;
  39. var $collate;
  40. /**
  41. * Connects to the database server and selects a database
  42. * @param string $dbuser
  43. * @param string $dbpassword
  44. * @param string $dbname
  45. * @param string $dbhost
  46. */
  47. function wpdb($dbuser, $dbpassword, $dbname, $dbhost) {
  48. return $this->__construct($dbuser, $dbpassword, $dbname, $dbhost);
  49. }
  50. function __construct($dbuser, $dbpassword, $dbname, $dbhost) {
  51. register_shutdown_function(array(&$this, "__destruct"));
  52. if ( defined('WP_DEBUG') and WP_DEBUG == true )
  53. $this->show_errors();
  54. if ( defined('DB_CHARSET') )
  55. $this->charset = DB_CHARSET;
  56. if ( defined('DB_COLLATE') )
  57. $this->collate = DB_COLLATE;
  58. $this->dbh = @mysql_connect($dbhost, $dbuser, $dbpassword, true);
  59. if (!$this->dbh) {
  60. $this->bail("
  61. <h1>Error establishing a database connection</h1>
  62. <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>
  63. <ul>
  64. <li>Are you sure you have the correct username and password?</li>
  65. <li>Are you sure that you have typed the correct hostname?</li>
  66. <li>Are you sure that the database server is running?</li>
  67. </ul>
  68. <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>
  69. ");
  70. return;
  71. }
  72. $this->ready = true;
  73. if ( $this->supports_collation() ) {
  74. $collation_query = '';
  75. if ( !empty($this->charset) ) {
  76. $collation_query = "SET NAMES '{$this->charset}'";
  77. if (!empty($this->collate) )
  78. $collation_query .= " COLLATE '{$this->collate}'";
  79. }
  80. if ( !empty($collation_query) )
  81. $this->query($collation_query);
  82. }
  83. $this->select($dbname);
  84. }
  85. function __destruct() {
  86. return true;
  87. }
  88. function set_prefix($prefix) {
  89. if ( preg_match('|[^a-z0-9_]|i', $prefix) )
  90. return new WP_Error('invalid_db_prefix', 'Invalid database prefix'); // No gettext here
  91. $old_prefix = $this->prefix;
  92. $this->prefix = $prefix;
  93. foreach ( $this->tables as $table )
  94. $this->$table = $this->prefix . $table;
  95. if ( defined('CUSTOM_USER_TABLE') )
  96. $this->users = CUSTOM_USER_TABLE;
  97. if ( defined('CUSTOM_USER_META_TABLE') )
  98. $this->usermeta = CUSTOM_USER_META_TABLE;
  99. return $old_prefix;
  100. }
  101. /**
  102. * Selects a database using the current class's $this->dbh
  103. * @param string $db name
  104. */
  105. function select($db) {
  106. if (!@mysql_select_db($db, $this->dbh)) {
  107. $this->ready = false;
  108. $this->bail("
  109. <h1>Can&#8217;t select database</h1>
  110. <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>$db</code> database.</p>
  111. <ul>
  112. <li>Are you sure it exists?</li>
  113. <li>Does the user <code>".DB_USER."</code> have permission to use the <code>$db</code> database?</li>
  114. <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>
  115. </ul>
  116. <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>");
  117. return;
  118. }
  119. }
  120. /**
  121. * Escapes content for insertion into the database, for security
  122. *
  123. * @param string $string
  124. * @return string query safe string
  125. */
  126. function escape($string) {
  127. return addslashes( $string );
  128. // Disable rest for now, causing problems
  129. /*
  130. if( !$this->dbh || version_compare( phpversion(), '4.3.0' ) == '-1' )
  131. return mysql_escape_string( $string );
  132. else
  133. return mysql_real_escape_string( $string, $this->dbh );
  134. */
  135. }
  136. /**
  137. * Escapes content by reference for insertion into the database, for security
  138. * @param string $s
  139. */
  140. function escape_by_ref(&$s) {
  141. $s = $this->escape($s);
  142. }
  143. /**
  144. * Prepares a SQL query for safe use, using sprintf() syntax
  145. */
  146. function prepare($args=NULL) {
  147. if ( NULL === $args )
  148. return;
  149. $args = func_get_args();
  150. $query = array_shift($args);
  151. $query = str_replace("'%s'", '%s', $query); // in case someone mistakenly already singlequoted it
  152. $query = str_replace('"%s"', '%s', $query); // doublequote unquoting
  153. $query = str_replace('%s', "'%s'", $query); // quote the strings
  154. array_walk($args, array(&$this, 'escape_by_ref'));
  155. return @vsprintf($query, $args);
  156. }
  157. // ==================================================================
  158. // Print SQL/DB error.
  159. function print_error($str = '') {
  160. global $EZSQL_ERROR;
  161. if (!$str) $str = mysql_error($this->dbh);
  162. $EZSQL_ERROR[] =
  163. array ('query' => $this->last_query, 'error_str' => $str);
  164. if ( $this->suppress_errors )
  165. return false;
  166. $error_str = "WordPress database error $str for query $this->last_query";
  167. if ( $caller = $this->get_caller() )
  168. $error_str .= " made by $caller";
  169. $log_error = true;
  170. if ( ! function_exists('error_log') )
  171. $log_error = false;
  172. $log_file = @ini_get('error_log');
  173. if ( !empty($log_file) && ('syslog' != $log_file) && !is_writable($log_file) )
  174. $log_error = false;
  175. if ( $log_error )
  176. @error_log($error_str, 0);
  177. // Is error output turned on or not..
  178. if ( !$this->show_errors )
  179. return false;
  180. $str = htmlspecialchars($str, ENT_QUOTES);
  181. $query = htmlspecialchars($this->last_query, ENT_QUOTES);
  182. // If there is an error then take note of it
  183. print "<div id='error'>
  184. <p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br />
  185. <code>$query</code></p>
  186. </div>";
  187. }
  188. // ==================================================================
  189. // Turn error handling on or off..
  190. function show_errors( $show = true ) {
  191. $errors = $this->show_errors;
  192. $this->show_errors = $show;
  193. return $errors;
  194. }
  195. function hide_errors() {
  196. $show = $this->show_errors;
  197. $this->show_errors = false;
  198. return $show;
  199. }
  200. function suppress_errors( $suppress = true ) {
  201. $errors = $this->suppress_errors;
  202. $this->suppress_errors = $suppress;
  203. return $errors;
  204. }
  205. // ==================================================================
  206. // Kill cached query results
  207. function flush() {
  208. $this->last_result = array();
  209. $this->col_info = null;
  210. $this->last_query = null;
  211. }
  212. // ==================================================================
  213. // Basic Query - see docs for more detail
  214. function query($query) {
  215. if ( ! $this->ready )
  216. return false;
  217. // filter the query, if filters are available
  218. // NOTE: some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
  219. if ( function_exists('apply_filters') )
  220. $query = apply_filters('query', $query);
  221. // initialise return
  222. $return_val = 0;
  223. $this->flush();
  224. // Log how the function was called
  225. $this->func_call = "\$db->query(\"$query\")";
  226. // Keep track of the last query for debug..
  227. $this->last_query = $query;
  228. // Perform the query via std mysql_query function..
  229. if (SAVEQUERIES)
  230. $this->timer_start();
  231. $this->result = @mysql_query($query, $this->dbh);
  232. ++$this->num_queries;
  233. if (SAVEQUERIES)
  234. $this->queries[] = array( $query, $this->timer_stop(), $this->get_caller() );
  235. // If there is an error then take note of it..
  236. if ( $this->last_error = mysql_error($this->dbh) ) {
  237. $this->print_error();
  238. return false;
  239. }
  240. if ( preg_match("/^\\s*(insert|delete|update|replace) /i",$query) ) {
  241. $this->rows_affected = mysql_affected_rows($this->dbh);
  242. // Take note of the insert_id
  243. if ( preg_match("/^\\s*(insert|replace) /i",$query) ) {
  244. $this->insert_id = mysql_insert_id($this->dbh);
  245. }
  246. // Return number of rows affected
  247. $return_val = $this->rows_affected;
  248. } else {
  249. $i = 0;
  250. while ($i < @mysql_num_fields($this->result)) {
  251. $this->col_info[$i] = @mysql_fetch_field($this->result);
  252. $i++;
  253. }
  254. $num_rows = 0;
  255. while ( $row = @mysql_fetch_object($this->result) ) {
  256. $this->last_result[$num_rows] = $row;
  257. $num_rows++;
  258. }
  259. @mysql_free_result($this->result);
  260. // Log number of rows the query returned
  261. $this->num_rows = $num_rows;
  262. // Return number of rows selected
  263. $return_val = $this->num_rows;
  264. }
  265. return $return_val;
  266. }
  267. /**
  268. * Insert an array of data into a table
  269. * @param string $table WARNING: not sanitized!
  270. * @param array $data should not already be SQL-escaped
  271. * @return mixed results of $this->query()
  272. */
  273. function insert($table, $data) {
  274. $data = add_magic_quotes($data);
  275. $fields = array_keys($data);
  276. return $this->query("INSERT INTO $table (`" . implode('`,`',$fields) . "`) VALUES ('".implode("','",$data)."')");
  277. }
  278. /**
  279. * Update a row in the table with an array of data
  280. * @param string $table WARNING: not sanitized!
  281. * @param array $data should not already be SQL-escaped
  282. * @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!
  283. * @return mixed results of $this->query()
  284. */
  285. function update($table, $data, $where){
  286. $data = add_magic_quotes($data);
  287. $bits = $wheres = array();
  288. foreach ( array_keys($data) as $k )
  289. $bits[] = "`$k` = '$data[$k]'";
  290. if ( is_array( $where ) )
  291. foreach ( $where as $c => $v )
  292. $wheres[] = "$c = '" . $this->escape( $v ) . "'";
  293. else
  294. return false;
  295. return $this->query( "UPDATE $table SET " . implode( ', ', $bits ) . ' WHERE ' . implode( ' AND ', $wheres ) . ' LIMIT 1' );
  296. }
  297. /**
  298. * Get one variable from the database
  299. * @param string $query (can be null as well, for caching, see codex)
  300. * @param int $x = 0 row num to return
  301. * @param int $y = 0 col num to return
  302. * @return mixed results
  303. */
  304. function get_var($query=null, $x = 0, $y = 0) {
  305. $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
  306. if ( $query )
  307. $this->query($query);
  308. // Extract var out of cached results based x,y vals
  309. if ( !empty( $this->last_result[$y] ) ) {
  310. $values = array_values(get_object_vars($this->last_result[$y]));
  311. }
  312. // If there is a value return it else return null
  313. return (isset($values[$x]) && $values[$x]!=='') ? $values[$x] : null;
  314. }
  315. /**
  316. * Get one row from the database
  317. * @param string $query
  318. * @param string $output ARRAY_A | ARRAY_N | OBJECT
  319. * @param int $y row num to return
  320. * @return mixed results
  321. */
  322. function get_row($query = null, $output = OBJECT, $y = 0) {
  323. $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
  324. if ( $query )
  325. $this->query($query);
  326. else
  327. return null;
  328. if ( !isset($this->last_result[$y]) )
  329. return null;
  330. if ( $output == OBJECT ) {
  331. return $this->last_result[$y] ? $this->last_result[$y] : null;
  332. } elseif ( $output == ARRAY_A ) {
  333. return $this->last_result[$y] ? get_object_vars($this->last_result[$y]) : null;
  334. } elseif ( $output == ARRAY_N ) {
  335. return $this->last_result[$y] ? array_values(get_object_vars($this->last_result[$y])) : null;
  336. } else {
  337. $this->print_error(" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N");
  338. }
  339. }
  340. /**
  341. * Gets one column from the database
  342. * @param string $query (can be null as well, for caching, see codex)
  343. * @param int $x col num to return
  344. * @return array results
  345. */
  346. function get_col($query = null , $x = 0) {
  347. if ( $query )
  348. $this->query($query);
  349. $new_array = array();
  350. // Extract the column values
  351. for ( $i=0; $i < count($this->last_result); $i++ ) {
  352. $new_array[$i] = $this->get_var(null, $x, $i);
  353. }
  354. return $new_array;
  355. }
  356. /**
  357. * Return an entire result set from the database
  358. * @param string $query (can also be null to pull from the cache)
  359. * @param string $output ARRAY_A | ARRAY_N | OBJECT_K | OBJECT
  360. * @return mixed results
  361. */
  362. function get_results($query = null, $output = OBJECT) {
  363. $this->func_call = "\$db->get_results(\"$query\", $output)";
  364. if ( $query )
  365. $this->query($query);
  366. else
  367. return null;
  368. if ( $output == OBJECT ) {
  369. // Return an integer-keyed array of row objects
  370. return $this->last_result;
  371. } elseif ( $output == OBJECT_K ) {
  372. // Return an array of row objects with keys from column 1
  373. // (Duplicates are discarded)
  374. foreach ( $this->last_result as $row ) {
  375. $key = array_shift( get_object_vars( $row ) );
  376. if ( !isset( $new_array[ $key ] ) )
  377. $new_array[ $key ] = $row;
  378. }
  379. return $new_array;
  380. } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
  381. // Return an integer-keyed array of...
  382. if ( $this->last_result ) {
  383. $i = 0;
  384. foreach( $this->last_result as $row ) {
  385. if ( $output == ARRAY_N ) {
  386. // ...integer-keyed row arrays
  387. $new_array[$i] = array_values( get_object_vars( $row ) );
  388. } else {
  389. // ...column name-keyed row arrays
  390. $new_array[$i] = get_object_vars( $row );
  391. }
  392. ++$i;
  393. }
  394. return $new_array;
  395. }
  396. }
  397. }
  398. /**
  399. * Grabs column metadata from the last query
  400. * @param string $info_type one of name, table, def, max_length, not_null, primary_key, multiple_key, unique_key, numeric, blob, type, unsigned, zerofill
  401. * @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
  402. * @return mixed results
  403. */
  404. function get_col_info($info_type = 'name', $col_offset = -1) {
  405. if ( $this->col_info ) {
  406. if ( $col_offset == -1 ) {
  407. $i = 0;
  408. foreach($this->col_info as $col ) {
  409. $new_array[$i] = $col->{$info_type};
  410. $i++;
  411. }
  412. return $new_array;
  413. } else {
  414. return $this->col_info[$col_offset]->{$info_type};
  415. }
  416. }
  417. }
  418. /**
  419. * Starts the timer, for debugging purposes
  420. */
  421. function timer_start() {
  422. $mtime = microtime();
  423. $mtime = explode(' ', $mtime);
  424. $this->time_start = $mtime[1] + $mtime[0];
  425. return true;
  426. }
  427. /**
  428. * Stops the debugging timer
  429. * @return int total time spent on the query, in milliseconds
  430. */
  431. function timer_stop() {
  432. $mtime = microtime();
  433. $mtime = explode(' ', $mtime);
  434. $time_end = $mtime[1] + $mtime[0];
  435. $time_total = $time_end - $this->time_start;
  436. return $time_total;
  437. }
  438. /**
  439. * Wraps fatal errors in a nice header and footer and dies.
  440. * @param string $message
  441. */
  442. function bail($message) { // Just wraps errors in a nice header and footer
  443. if ( !$this->show_errors ) {
  444. if ( class_exists('WP_Error') )
  445. $this->error = new WP_Error('500', $message);
  446. else
  447. $this->error = $message;
  448. return false;
  449. }
  450. wp_die($message);
  451. }
  452. /**
  453. * Checks wether of not the database version is high enough to support the features WordPress uses
  454. * @global $wp_version
  455. */
  456. function check_database_version()
  457. {
  458. global $wp_version;
  459. // Make sure the server has MySQL 4.0
  460. $mysql_version = preg_replace('|[^0-9\.]|', '', @mysql_get_server_info($this->dbh));
  461. if ( version_compare($mysql_version, '4.0.0', '<') )
  462. return new WP_Error('database_version',sprintf(__('<strong>ERROR</strong>: WordPress %s requires MySQL 4.0.0 or higher'), $wp_version));
  463. }
  464. /**
  465. * This function is called when WordPress is generating the table schema to determine wether or not the current database
  466. * supports or needs the collation statements.
  467. */
  468. function supports_collation()
  469. {
  470. return ( version_compare(mysql_get_server_info($this->dbh), '4.1.0', '>=') );
  471. }
  472. /**
  473. * Get the name of the function that called wpdb.
  474. * @return string the name of the calling function
  475. */
  476. function get_caller() {
  477. // requires PHP 4.3+
  478. if ( !is_callable('debug_backtrace') )
  479. return '';
  480. $bt = debug_backtrace();
  481. $caller = '';
  482. foreach ( $bt as $trace ) {
  483. if ( @$trace['class'] == __CLASS__ )
  484. continue;
  485. elseif ( strtolower(@$trace['function']) == 'call_user_func_array' )
  486. continue;
  487. elseif ( strtolower(@$trace['function']) == 'apply_filters' )
  488. continue;
  489. elseif ( strtolower(@$trace['function']) == 'do_action' )
  490. continue;
  491. $caller = $trace['function'];
  492. break;
  493. }
  494. return $caller;
  495. }
  496. }
  497. if ( ! isset($wpdb) )
  498. $wpdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
  499. ?>