root/trunk/wp-includes/classes.php

Revision 1522, 43.2 kB (checked in by donncha, 3 days ago)

WP Merge with revision 9730

  • Property svn:eol-style set to native
Line 
1 <?php
2 /**
3  * Holds Most of the WordPress classes.
4  *
5  * Some of the other classes are contained in other files. For example, the
6  * WordPress cache is in cache.php and the WordPress roles API is in
7  * capabilities.php. The third party libraries are contained in their own
8  * separate files.
9  *
10  * @package WordPress
11  */
12
13 /**
14  * WordPress environment setup class.
15  *
16  * @package WordPress
17  * @since 2.0.0
18  */
19 class WP {
20     /**
21      * Public query variables.
22      *
23      * Long list of public query variables.
24      *
25      * @since 2.0.0
26      * @access public
27      * @var array
28      */
29     var $public_query_vars = array('m', 'p', 'posts', 'w', 'cat', 'withcomments', 'withoutcomments', 's', 'search', 'exact', 'sentence', 'debug', 'calendar', 'page', 'paged', 'more', 'tb', 'pb', 'author', 'order', 'orderby', 'year', 'monthnum', 'day', 'hour', 'minute', 'second', 'name', 'category_name', 'tag', 'feed', 'author_name', 'static', 'pagename', 'page_id', 'error', 'comments_popup', 'attachment', 'attachment_id', 'subpost', 'subpost_id', 'preview', 'robots', 'taxonomy', 'term', 'cpage');
30
31     /**
32      * Private query variables.
33      *
34      * Long list of private query variables.
35      *
36      * @since 2.0.0
37      * @var array
38      */
39     var $private_query_vars = array('offset', 'posts_per_page', 'posts_per_archive_page', 'what_to_show', 'showposts', 'nopaging', 'post_type', 'post_status', 'category__in', 'category__not_in', 'category__and', 'tag__in', 'tag__not_in', 'tag__and', 'tag_slug__in', 'tag_slug__and', 'tag_id', 'post_mime_type', 'perm', 'comments_per_page');
40
41     /**
42      * Extra query variables set by the user.
43      *
44      * @since 2.1.0
45      * @var array
46      */
47     var $extra_query_vars = array();
48
49     /**
50      * Query variables for setting up the WordPress Query Loop.
51      *
52      * @since 2.0.0
53      * @var array
54      */
55     var $query_vars;
56
57     /**
58      * String parsed to set the query variables.
59      *
60      * @since 2.0.0
61      * @var string
62      */
63     var $query_string;
64
65     /**
66      * Permalink or requested URI.
67      *
68      * @since 2.0.0
69      * @var string
70      */
71     var $request;
72
73     /**
74      * Rewrite rule the request matched.
75      *
76      * @since 2.0.0
77      * @var string
78      */
79     var $matched_rule;
80
81     /**
82      * Rewrite query the request matched.
83      *
84      * @since 2.0.0
85      * @var string
86      */
87     var $matched_query;
88
89     /**
90      * Whether already did the permalink.
91      *
92      * @since 2.0.0
93      * @var bool
94      */
95     var $did_permalink = false;
96
97     /**
98      * Add name to list of public query variables.
99      *
100      * @since 2.1.0
101      *
102      * @param string $qv Query variable name.
103      */
104     function add_query_var($qv) {
105         if ( !in_array($qv, $this->public_query_vars) )
106             $this->public_query_vars[] = $qv;
107     }
108
109     /**
110      * Set the value of a query variable.
111      *
112      * @since 2.3.0
113      *
114      * @param string $key Query variable name.
115      * @param mixed $value Query variable value.
116      */
117     function set_query_var($key, $value) {
118         $this->query_vars[$key] = $value;
119     }
120
121     /**
122      * Parse request to find correct WordPress query.
123      *
124      * Sets up the query variables based on the request. There are also many
125      * filters and actions that can be used to further manipulate the result.
126      *
127      * @since 2.0.0
128      *
129      * @param array|string $extra_query_vars Set the extra query variables.
130      */
131     function parse_request($extra_query_vars = '') {
132         global $wp_rewrite;
133
134         $this->query_vars = array();
135         $taxonomy_query_vars = array();
136
137         if ( is_array($extra_query_vars) )
138             $this->extra_query_vars = & $extra_query_vars;
139         else if (! empty($extra_query_vars))
140             parse_str($extra_query_vars, $this->extra_query_vars);
141
142         // Process PATH_INFO, REQUEST_URI, and 404 for permalinks.
143
144         // Fetch the rewrite rules.
145         $rewrite = $wp_rewrite->wp_rewrite_rules();
146
147         if (! empty($rewrite)) {
148             // If we match a rewrite rule, this will be cleared.
149             $error = '404';
150             $this->did_permalink = true;
151
152             if ( isset($_SERVER['PATH_INFO']) )
153                 $pathinfo = $_SERVER['PATH_INFO'];
154             else
155                 $pathinfo = '';
156             $pathinfo_array = explode('?', $pathinfo);
157             $pathinfo = str_replace("%", "%25", $pathinfo_array[0]);
158             $req_uri = $_SERVER['REQUEST_URI'];
159             $req_uri_array = explode('?', $req_uri);
160             $req_uri = $req_uri_array[0];
161             $self = $_SERVER['PHP_SELF'];
162             $home_path = parse_url(get_option('home'));
163             if ( isset($home_path['path']) )
164                 $home_path = $home_path['path'];
165             else
166                 $home_path = '';
167             $home_path = trim($home_path, '/');
168
169             // Trim path info from the end and the leading home path from the
170             // front.  For path info requests, this leaves us with the requesting
171             // filename, if any.  For 404 requests, this leaves us with the
172             // requested permalink.
173             $req_uri = str_replace($pathinfo, '', rawurldecode($req_uri));
174             $req_uri = trim($req_uri, '/');
175             $req_uri = preg_replace("|^$home_path|", '', $req_uri);
176             $req_uri = trim($req_uri, '/');
177             $pathinfo = trim($pathinfo, '/');
178             $pathinfo = preg_replace("|^$home_path|", '', $pathinfo);
179             $pathinfo = trim($pathinfo, '/');
180             $self = trim($self, '/');
181             $self = preg_replace("|^$home_path|", '', $self);
182             $self = trim($self, '/');
183
184             // The requested permalink is in $pathinfo for path info requests and
185             //  $req_uri for other requests.
186             if ( ! empty($pathinfo) && !preg_match('|^.*' . $wp_rewrite->index . '$|', $pathinfo) ) {
187                 $request = $pathinfo;
188             } else {
189                 // If the request uri is the index, blank it out so that we don't try to match it against a rule.
190                 if ( $req_uri == $wp_rewrite->index )
191                     $req_uri = '';
192                 $request = $req_uri;
193             }
194
195             $this->request = $request;
196
197             // Look for matches.
198             $request_match = $request;
199             foreach ( (array) $rewrite as $match => $query) {
200                 // Don't try to match against AtomPub calls
201                 if ( $req_uri == 'wp-app.php' )
202                     break;
203
204                 // If the requesting file is the anchor of the match, prepend it
205                 // to the path info.
206                 if ((! empty($req_uri)) && (strpos($match, $req_uri) === 0) && ($req_uri != $request)) {
207                     $request_match = $req_uri . '/' . $request;
208                 }
209
210                 if (preg_match("!^$match!", $request_match, $matches) ||
211                     preg_match("!^$match!", urldecode($request_match), $matches)) {
212                     // Got a match.
213                     $this->matched_rule = $match;
214
215                     // Trim the query of everything up to the '?'.
216                     $query = preg_replace("!^.+\?!", '', $query);
217
218                     // Substitute the substring matches into the query.
219                     eval("@\$query = \"" . addslashes($query) . "\";");
220
221                     $this->matched_query = $query;
222
223                     // Parse the query.
224                     parse_str($query, $perma_query_vars);
225
226                     // If we're processing a 404 request, clear the error var
227                     // since we found something.
228                     if (isset($_GET['error']))
229                         unset($_GET['error']);
230
231                     if (isset($error))
232                         unset($error);
233
234                     break;
235                 }
236             }
237
238             // If req_uri is empty or if it is a request for ourself, unset error.
239             if (empty($request) || $req_uri == $self || strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false) {
240                 if (isset($_GET['error']))
241                     unset($_GET['error']);
242
243                 if (isset($error))
244                     unset($error);
245
246                 if (isset($perma_query_vars) && strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false)
247                     unset($perma_query_vars);
248
249                 $this->did_permalink = false;
250             }
251         }
252
253         $this->public_query_vars = apply_filters('query_vars', $this->public_query_vars);
254
255         foreach ( $GLOBALS['wp_taxonomies'] as $taxonomy => $t )
256             if ( isset($t->query_var) )
257                 $taxonomy_query_vars[$t->query_var] = $taxonomy;
258
259         for ($i=0; $i<count($this->public_query_vars); $i += 1) {
260             $wpvar = $this->public_query_vars[$i];
261             if (isset($this->extra_query_vars[$wpvar]))
262                 $this->query_vars[$wpvar] = $this->extra_query_vars[$wpvar];
263             elseif (isset($GLOBALS[$wpvar]))
264                 $this->query_vars[$wpvar] = $GLOBALS[$wpvar];
265             elseif (!empty($_POST[$wpvar]))
266                 $this->query_vars[$wpvar] = $_POST[$wpvar];
267             elseif (!empty($_GET[$wpvar]))
268                 $this->query_vars[$wpvar] = $_GET[$wpvar];
269             elseif (!empty($perma_query_vars[$wpvar]))
270                 $this->query_vars[$wpvar] = $perma_query_vars[$wpvar];
271
272             if ( !empty( $this->query_vars[$wpvar] ) ) {
273                 $this->query_vars[$wpvar] = (string) $this->query_vars[$wpvar];
274                 if ( in_array( $wpvar, $taxonomy_query_vars ) ) {
275                     $this->query_vars['taxonomy'] = $taxonomy_query_vars[$wpvar];
276                     $this->query_vars['term'] = $this->query_vars[$wpvar];
277                 }
278             }
279         }
280
281         foreach ( (array) $this->private_query_vars as $var) {
282             if (isset($this->extra_query_vars[$var]))
283                 $this->query_vars[$var] = $this->extra_query_vars[$var];
284             elseif (isset($GLOBALS[$var]) && '' != $GLOBALS[$var])
285                 $this->query_vars[$var] = $GLOBALS[$var];
286         }
287
288         if ( isset($error) )
289             $this->query_vars['error'] = $error;
290
291         $this->query_vars = apply_filters('request', $this->query_vars);
292
293         do_action_ref_array('parse_request', array(&$this));
294     }
295
296     /**
297      * Send additional HTTP headers for caching, content type, etc.
298      *
299      * Sets the X-Pingback header, 404 status (if 404), Content-type. If showing
300      * a feed, it will also send last-modified, etag, and 304 status if needed.
301      *
302      * @since 2.0.0
303      */
304     function send_headers() {
305         @header('X-Pingback: '. get_bloginfo('pingback_url'));
306         if ( is_user_logged_in() )
307             nocache_headers();
308         if ( !empty($this->query_vars['error']) && '404' == $this->query_vars['error'] ) {
309             status_header( 404 );
310             if ( !is_user_logged_in() )
311                 nocache_headers();
312             @header('Content-Type: ' . get_option('html_type') . '; charset=' . get_option('blog_charset'));
313         } else if ( empty($this->query_vars['feed']) ) {
314             @header('Content-Type: ' . get_option('html_type') . '; charset=' . get_option('blog_charset'));
315         } else {
316             // We're showing a feed, so WP is indeed the only thing that last changed
317             if ( !empty($this->query_vars['withcomments'])
318                 || ( empty($this->query_vars['withoutcomments'])
319                     && ( !empty($this->query_vars['p'])
320                         || !empty($this->query_vars['name'])
321                         || !empty($this->query_vars['page_id'])
322                         || !empty($this->query_vars['pagename'])
323                         || !empty($this->query_vars['attachment'])
324                         || !empty($this->query_vars['attachment_id'])
325                     )
326                 )
327             )
328                 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastcommentmodified('GMT'), 0).' GMT';
329             else
330                 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT';
331             $wp_etag = '"' . md5($wp_last_modified) . '"';
332             @header("Last-Modified: $wp_last_modified");
333             @header("ETag: $wp_etag");
334
335             // Support for Conditional GET
336             if (isset($_SERVER['HTTP_IF_NONE_MATCH']))
337                 $client_etag = stripslashes(stripslashes($_SERVER['HTTP_IF_NONE_MATCH']));
338             else $client_etag = false;
339
340             $client_last_modified = empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? '' : trim($_SERVER['HTTP_IF_MODIFIED_SINCE']);
341             // If string is empty, return 0. If not, attempt to parse into a timestamp
342             $client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0;
343
344             // Make a timestamp for our most recent modification...
345             $wp_modified_timestamp = strtotime($wp_last_modified);
346
347             if ( ($client_last_modified && $client_etag) ?
348                      (($client_modified_timestamp >= $wp_modified_timestamp) && ($client_etag == $wp_etag)) :
349                      (($client_modified_timestamp >= $wp_modified_timestamp) || ($client_etag == $wp_etag)) ) {
350                 status_header( 304 );
351                 exit;
352             }
353         }
354
355         do_action_ref_array('send_headers', array(&$this));
356     }
357
358     /**
359      * Sets the query string property based off of the query variable property.
360      *
361      * The 'query_string' filter is deprecated, but still works. Plugins should
362      * use the 'request' filter instead.
363      *
364      * @since 2.0.0
365      */
366     function build_query_string() {
367         $this->query_string = '';
368         foreach ( (array) array_keys($this->query_vars) as $wpvar) {
369             if ( '' != $this->query_vars[$wpvar] ) {
370                 $this->query_string .= (strlen($this->query_string) < 1) ? '' : '&';
371                 if ( !is_scalar($this->query_vars[$wpvar]) ) // Discard non-scalars.
372                     continue;
373                 $this->query_string .= $wpvar . '=' . rawurlencode($this->query_vars[$wpvar]);
374             }
375         }
376
377         // query_string filter deprecated.  Use request filter instead.
378         if ( has_filter('query_string') ) {  // Don't bother filtering and parsing if no plugins are hooked in.
379             $this->query_string = apply_filters('query_string', $this->query_string);
380             parse_str($this->query_string, $this->query_vars);
381         }
382     }
383
384     /**
385      * Setup the WordPress Globals.
386      *
387      * The query_vars property will be extracted to the GLOBALS. So care should
388      * be taken when naming global variables that might interfere with the
389      * WordPress environment.
390      *
391      * @global string $query_string Query string for the loop.
392      * @global int $more Only set, if single page or post.
393      * @global int $single If single page or post. Only set, if single page or post.
394      *
395      * @since 2.0.0
396      */
397     function register_globals() {
398         global $wp_query;
399         // Extract updated query vars back into global namespace.
400         foreach ( (array) $wp_query->query_vars as $key => $value) {
401             $GLOBALS[$key] = $value;
402         }
403
404         $GLOBALS['query_string'] = & $this->query_string;
405         $GLOBALS['posts'] = & $wp_query->posts;
406         $GLOBALS['post'] = & $wp_query->post;
407         $GLOBALS['request'] = & $wp_query->request;
408
409         if ( is_single() || is_page() ) {
410             $GLOBALS['more'] = 1;
411             $GLOBALS['single'] = 1;
412         }
413     }
414
415     /**
416      * Setup the current user.
417      *
418      * @since 2.0.0
419      */
420     function init() {
421         wp_get_current_user();
422     }
423
424     /**
425      * Setup the Loop based on the query variables.
426      *
427      * @uses WP::$query_vars
428      * @since 2.0.0
429      */
430     function query_posts() {
431         global $wp_the_query;
432         $this->build_query_string();
433         $wp_the_query->query($this->query_vars);
434      }
435
436      /**
437       * Set the Headers for 404, if permalink is not found.
438      *
439      * Issue a 404 if a permalink request doesn't match any posts.  Don't issue
440      * a 404 if one was already issued, if the request was a search, or if the
441      * request was a regular query string request rather than a permalink
442      * request. Issues a 200, if not 404.
443      *
444      * @since 2.0.0
445       */
446     function handle_404() {
447         global $wp_query;
448
449         if ( (0 == count($wp_query->posts)) && !is_404() && !is_search() && ( $this->did_permalink || (!empty($_SERVER['QUERY_STRING']) && (false === strpos($_SERVER['REQUEST_URI'], '?'))) ) ) {
450             // Don't 404 for these queries if they matched an object.
451             if ( ( is_tag() || is_category() || is_author() ) && $wp_query->get_queried_object() ) {
452                 if ( !is_404() )
453                     status_header( 200 );
454                 return;
455             }
456             $wp_query->set_404();
457             status_header( 404 );
458             nocache_headers();
459         } elseif ( !is_404() ) {
460             status_header( 200 );
461         }
462     }
463
464     /**
465      * Sets up all of the variables required by the WordPress environment.
466      *
467      * The action 'wp' has one parameter that references the WP object. It
468      * allows for accessing the properties and methods to further manipulate the
469      * object.
470      *
471      * @since 2.0.0
472      *
473      * @param string|array $query_args Passed to {@link parse_request()}
474      */
475     function main($query_args = '') {
476         $this->init();
477         $this->parse_request($query_args);
478         $this->send_headers();
479         $this->query_posts();
480         $this->handle_404();
481         $this->register_globals();
482         do_action_ref_array('wp', array(&$this));
483     }
484
485     /**
486      * PHP4 Constructor - Does nothing.
487      *
488      * Call main() method when ready to run setup.
489      *
490      * @since 2.0.0
491      *
492      * @return WP
493      */
494     function WP() {
495         // Empty.
496     }
497 }
498
499 /**
500  * WordPress Error class.
501  *
502  * Container for checking for WordPress errors and error messages. Return
503  * WP_Error and use {@link is_wp_error()} to check if this class is returned.
504  * Many core WordPress functions pass this class in the event of an error and
505  * if not handled properly will result in code errors.
506  *
507  * @package WordPress
508  * @since 2.1.0
509  */
510 class WP_Error {
511     /**
512      * Stores the list of errors.
513      *<