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