]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/wp-db.php
Wordpress 2.3.2-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('ARRAY_A', 'ARRAY_A', false);
11 define('ARRAY_N', 'ARRAY_N', false);
12
13 if (!defined('SAVEQUERIES'))
14         define('SAVEQUERIES', false);
15
16 class wpdb {
17
18         var $show_errors = false;
19         var $num_queries = 0;
20         var $last_query;
21         var $col_info;
22         var $queries;
23         var $ready = false;
24
25         // Our tables
26         var $posts;
27         var $users;
28         var $categories;
29         var $post2cat;
30         var $comments;
31         var $links;
32         var $options;
33         var $optiontypes;
34         var $optionvalues;
35         var $optiongroups;
36         var $optiongroup_options;
37         var $postmeta;
38         var $usermeta;
39         var $terms;
40         var $term_taxonomy;
41         var $term_relationships;
42
43         var $charset;
44         var $collate;
45
46         /**
47          * Connects to the database server and selects a database
48          * @param string $dbuser
49          * @param string $dbpassword
50          * @param string $dbname
51          * @param string $dbhost
52          */
53         function wpdb($dbuser, $dbpassword, $dbname, $dbhost) {
54                 return $this->__construct($dbuser, $dbpassword, $dbname, $dbhost);
55         }
56
57         function __construct($dbuser, $dbpassword, $dbname, $dbhost) {
58                 register_shutdown_function(array(&$this, "__destruct"));
59
60                 if ( defined('WP_DEBUG') and WP_DEBUG == true )
61                         $this->show_errors();
62
63                 if ( defined('DB_CHARSET') )
64                         $this->charset = DB_CHARSET;
65
66                 if ( defined('DB_COLLATE') )
67                         $this->collate = DB_COLLATE;
68
69                 $this->dbh = @mysql_connect($dbhost, $dbuser, $dbpassword);
70                 if (!$this->dbh) {
71                         $this->bail("
72 <h1>Error establishing a database connection</h1>
73 <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>
74 <ul>
75         <li>Are you sure you have the correct username and password?</li>
76         <li>Are you sure that you have typed the correct hostname?</li>
77         <li>Are you sure that the database server is running?</li>
78 </ul>
79 <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>
80 ");
81                         return;
82                 }
83
84                 $this->ready = true;
85
86                 if ( !empty($this->charset) && version_compare(mysql_get_server_info(), '4.1.0', '>=') )
87                         $this->query("SET NAMES '$this->charset'");
88
89                 $this->select($dbname);
90         }
91
92         function __destruct() {
93                 return true;
94         }
95
96         /**
97          * Selects a database using the current class's $this->dbh
98          * @param string $db name
99          */
100         function select($db) {
101                 if (!@mysql_select_db($db, $this->dbh)) {
102                         $this->ready = false;
103                         $this->bail("
104 <h1>Can&#8217;t select database</h1>
105 <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>
106 <ul>
107 <li>Are you sure it exists?</li>
108 <li>Does the user <code>".DB_USER."</code> have permission to use the <code>$db</code> database?</li>
109 <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>
110 </ul>
111 <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>");
112                         return;
113                 }
114         }
115
116         /**
117          * Escapes content for insertion into the database, for security
118          *
119          * @param string $string
120          * @return string query safe string
121          */
122         function escape($string) {
123                 return addslashes( $string ); // Disable rest for now, causing problems
124                 if( !$this->dbh || version_compare( phpversion(), '4.3.0' ) == '-1' )
125                         return mysql_escape_string( $string );
126                 else
127                         return mysql_real_escape_string( $string, $this->dbh );
128         }
129
130         /**
131          * Escapes content by reference for insertion into the database, for security
132          * @param string $s
133          */
134         function escape_by_ref(&$s) {
135                 $s = $this->escape($s);
136         }
137
138         /**
139          * Prepares a SQL query for safe use, using sprintf() syntax
140          */
141         function prepare($args=NULL) {
142                 if ( NULL === $args )
143                         return;
144                 $args = func_get_args();
145                 $query = array_shift($args);
146                 $query = str_replace("'%s'", '%s', $query); // in case someone mistakenly already singlequoted it
147                 $query = str_replace('"%s"', '%s', $query); // doublequote unquoting
148                 $query = str_replace('%s', "'%s'", $query); // quote the strings
149                 array_walk($args, array(&$this, 'escape_by_ref'));
150                 return @vsprintf($query, $args);
151         }
152
153         // ==================================================================
154         //      Print SQL/DB error.
155
156         function print_error($str = '') {
157                 global $EZSQL_ERROR;
158                 if (!$str) $str = mysql_error($this->dbh);
159                 $EZSQL_ERROR[] =
160                 array ('query' => $this->last_query, 'error_str' => $str);
161
162                 $error_str = "WordPress database error $str for query $this->last_query";
163                 error_log($error_str, 0);
164
165                 // Is error output turned on or not..
166                 if ( !$this->show_errors )
167                         return false;
168
169                 $str = htmlspecialchars($str, ENT_QUOTES);
170                 $query = htmlspecialchars($this->last_query, ENT_QUOTES);
171
172                 // If there is an error then take note of it
173                 print "<div id='error'>
174                 <p class='wpdberror'><strong>WordPress database error:</strong> [$str]<br />
175                 <code>$query</code></p>
176                 </div>";
177         }
178
179         // ==================================================================
180         //      Turn error handling on or off..
181
182         function show_errors( $show = true ) {
183                 $errors = $this->show_errors;
184                 $this->show_errors = $show;
185                 return $errors;
186         }
187
188         function hide_errors() {
189                 $show = $this->show_errors;
190                 $this->show_errors = false;
191                 return $show;
192         }
193
194         // ==================================================================
195         //      Kill cached query results
196
197         function flush() {
198                 $this->last_result = array();
199                 $this->col_info = null;
200                 $this->last_query = null;
201         }
202
203         // ==================================================================
204         //      Basic Query     - see docs for more detail
205
206         function query($query) {
207                 if ( ! $this->ready )
208                         return false;
209
210                 // filter the query, if filters are available
211                 // NOTE: some queries are made before the plugins have been loaded, and thus cannot be filtered with this method
212                 if ( function_exists('apply_filters') )
213                         $query = apply_filters('query', $query);
214
215                 // initialise return
216                 $return_val = 0;
217                 $this->flush();
218
219                 // Log how the function was called
220                 $this->func_call = "\$db->query(\"$query\")";
221
222                 // Keep track of the last query for debug..
223                 $this->last_query = $query;
224
225                 // Perform the query via std mysql_query function..
226                 if (SAVEQUERIES)
227                         $this->timer_start();
228
229                 $this->result = @mysql_query($query, $this->dbh);
230                 ++$this->num_queries;
231
232                 if (SAVEQUERIES)
233                         $this->queries[] = array( $query, $this->timer_stop() );
234
235                 // If there is an error then take note of it..
236                 if ( mysql_error($this->dbh) ) {
237                         $this->print_error();
238                         return false;
239                 }
240
241                 if ( preg_match("/^\\s*(insert|delete|update|replace) /i",$query) ) {
242                         $this->rows_affected = mysql_affected_rows($this->dbh);
243                         // Take note of the insert_id
244                         if ( preg_match("/^\\s*(insert|replace) /i",$query) ) {
245                                 $this->insert_id = mysql_insert_id($this->dbh);
246                         }
247                         // Return number of rows affected
248                         $return_val = $this->rows_affected;
249                 } else {
250                         $i = 0;
251                         while ($i < @mysql_num_fields($this->result)) {
252                                 $this->col_info[$i] = @mysql_fetch_field($this->result);
253                                 $i++;
254                         }
255                         $num_rows = 0;
256                         while ( $row = @mysql_fetch_object($this->result) ) {
257                                 $this->last_result[$num_rows] = $row;
258                                 $num_rows++;
259                         }
260
261                         @mysql_free_result($this->result);
262
263                         // Log number of rows the query returned
264                         $this->num_rows = $num_rows;
265
266                         // Return number of rows selected
267                         $return_val = $this->num_rows;
268                 }
269
270                 return $return_val;
271         }
272
273         /**
274          * Get one variable from the database
275          * @param string $query (can be null as well, for caching, see codex)
276          * @param int $x = 0 row num to return
277          * @param int $y = 0 col num to return
278          * @return mixed results
279          */
280         function get_var($query=null, $x = 0, $y = 0) {
281                 $this->func_call = "\$db->get_var(\"$query\",$x,$y)";
282                 if ( $query )
283                         $this->query($query);
284
285                 // Extract var out of cached results based x,y vals
286                 if ( $this->last_result[$y] ) {
287                         $values = array_values(get_object_vars($this->last_result[$y]));
288                 }
289
290                 // If there is a value return it else return null
291                 return (isset($values[$x]) && $values[$x]!=='') ? $values[$x] : null;
292         }
293
294         /**
295          * Get one row from the database
296          * @param string $query
297          * @param string $output ARRAY_A | ARRAY_N | OBJECT
298          * @param int $y row num to return
299          * @return mixed results
300          */
301         function get_row($query = null, $output = OBJECT, $y = 0) {
302                 $this->func_call = "\$db->get_row(\"$query\",$output,$y)";
303                 if ( $query )
304                         $this->query($query);
305                 else
306                         return null;
307
308                 if ( !isset($this->last_result[$y]) )
309                         return null;
310
311                 if ( $output == OBJECT ) {
312                         return $this->last_result[$y] ? $this->last_result[$y] : null;
313                 } elseif ( $output == ARRAY_A ) {
314                         return $this->last_result[$y] ? get_object_vars($this->last_result[$y]) : null;
315                 } elseif ( $output == ARRAY_N ) {
316                         return $this->last_result[$y] ? array_values(get_object_vars($this->last_result[$y])) : null;
317                 } else {
318                         $this->print_error(" \$db->get_row(string query, output type, int offset) -- Output type must be one of: OBJECT, ARRAY_A, ARRAY_N");
319                 }
320         }
321
322         /**
323          * Gets one column from the database
324          * @param string $query (can be null as well, for caching, see codex)
325          * @param int $x col num to return
326          * @return array results
327          */
328         function get_col($query = null , $x = 0) {
329                 if ( $query )
330                         $this->query($query);
331
332                 $new_array = array();
333                 // Extract the column values
334                 for ( $i=0; $i < count($this->last_result); $i++ ) {
335                         $new_array[$i] = $this->get_var(null, $x, $i);
336                 }
337                 return $new_array;
338         }
339
340         /**
341          * Return an entire result set from the database
342          * @param string $query (can also be null to pull from the cache)
343          * @param string $output ARRAY_A | ARRAY_N | OBJECT
344          * @return mixed results
345          */
346         function get_results($query = null, $output = OBJECT) {
347                 $this->func_call = "\$db->get_results(\"$query\", $output)";
348
349                 if ( $query )
350                         $this->query($query);
351                 else
352                         return null;
353
354                 // Send back array of objects. Each row is an object
355                 if ( $output == OBJECT ) {
356                         return $this->last_result;
357                 } elseif ( $output == ARRAY_A || $output == ARRAY_N ) {
358                         if ( $this->last_result ) {
359                                 $i = 0;
360                                 foreach( $this->last_result as $row ) {
361                                         $new_array[$i] = (array) $row;
362                                         if ( $output == ARRAY_N ) {
363                                                 $new_array[$i] = array_values($new_array[$i]);
364                                         }
365                                         $i++;
366                                 }
367                                 return $new_array;
368                         } else {
369                                 return null;
370                         }
371                 }
372         }
373
374         /**
375          * Grabs column metadata from the last query
376          * @param string $info_type one of name, table, def, max_length, not_null, primary_key, multiple_key, unique_key, numeric, blob, type, unsigned, zerofill
377          * @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
378          * @return mixed results
379          */
380         function get_col_info($info_type = 'name', $col_offset = -1) {
381                 if ( $this->col_info ) {
382                         if ( $col_offset == -1 ) {
383                                 $i = 0;
384                                 foreach($this->col_info as $col ) {
385                                         $new_array[$i] = $col->{$info_type};
386                                         $i++;
387                                 }
388                                 return $new_array;
389                         } else {
390                                 return $this->col_info[$col_offset]->{$info_type};
391                         }
392                 }
393         }
394
395         /**
396          * Starts the timer, for debugging purposes
397          */
398         function timer_start() {
399                 $mtime = microtime();
400                 $mtime = explode(' ', $mtime);
401                 $this->time_start = $mtime[1] + $mtime[0];
402                 return true;
403         }
404
405         /**
406          * Stops the debugging timer
407          * @return int total time spent on the query, in milliseconds
408          */
409         function timer_stop() {
410                 $mtime = microtime();
411                 $mtime = explode(' ', $mtime);
412                 $time_end = $mtime[1] + $mtime[0];
413                 $time_total = $time_end - $this->time_start;
414                 return $time_total;
415         }
416
417         /**
418          * Wraps fatal errors in a nice header and footer and dies.
419          * @param string $message
420          */
421         function bail($message) { // Just wraps errors in a nice header and footer
422                 if ( !$this->show_errors ) {
423                         if ( class_exists('WP_Error') )
424                                 $this->error = new WP_Error('500', $message);
425                         else
426                                 $this->error = $message;
427                         return false;
428                 }
429                 wp_die($message);
430         }
431 }
432
433 if ( ! isset($wpdb) )
434         $wpdb = new wpdb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
435 ?>