Ticket #5951: 5951_wp_db_php.txt

File 5951_wp_db_php.txt, 12.6 KB (added by MichaelH, 4 years ago)

A suggested fixed wp_db.php that sometimes works and sometimes does not work.

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