]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/class-wp.php
WordPress 4.3-scripts
[autoinstalls/wordpress.git] / wp-includes / class-wp.php
1 <?php
2 /**
3  * WordPress environment setup class.
4  *
5  * @package WordPress
6  * @since 2.0.0
7  */
8 class WP {
9         /**
10          * Public query variables.
11          *
12          * Long list of public query variables.
13          *
14          * @since 2.0.0
15          * @access public
16          * @var array
17          */
18         public $public_query_vars = array('m', 'p', 'posts', 'w', 'cat', 'withcomments', 'withoutcomments', 's', 'search', 'exact', 'sentence', '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', 'post_type');
19
20         /**
21          * Private query variables.
22          *
23          * Long list of private query variables.
24          *
25          * @since 2.0.0
26          * @var array
27          */
28         public $private_query_vars = array( 'offset', 'posts_per_page', 'posts_per_archive_page', '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', 'post__in', 'post__not_in', 'post_parent', 'post_parent__in', 'post_parent__not_in' );
29
30         /**
31          * Extra query variables set by the user.
32          *
33          * @since 2.1.0
34          * @var array
35          */
36         public $extra_query_vars = array();
37
38         /**
39          * Query variables for setting up the WordPress Query Loop.
40          *
41          * @since 2.0.0
42          * @var array
43          */
44         public $query_vars;
45
46         /**
47          * String parsed to set the query variables.
48          *
49          * @since 2.0.0
50          * @var string
51          */
52         public $query_string;
53
54         /**
55          * Permalink or requested URI.
56          *
57          * @since 2.0.0
58          * @var string
59          */
60         public $request;
61
62         /**
63          * Rewrite rule the request matched.
64          *
65          * @since 2.0.0
66          * @var string
67          */
68         public $matched_rule;
69
70         /**
71          * Rewrite query the request matched.
72          *
73          * @since 2.0.0
74          * @var string
75          */
76         public $matched_query;
77
78         /**
79          * Whether already did the permalink.
80          *
81          * @since 2.0.0
82          * @var bool
83          */
84         public $did_permalink = false;
85
86         /**
87          * Add name to list of public query variables.
88          *
89          * @since 2.1.0
90          *
91          * @param string $qv Query variable name.
92          */
93         public function add_query_var($qv) {
94                 if ( !in_array($qv, $this->public_query_vars) )
95                         $this->public_query_vars[] = $qv;
96         }
97
98         /**
99          * Set the value of a query variable.
100          *
101          * @since 2.3.0
102          *
103          * @param string $key Query variable name.
104          * @param mixed $value Query variable value.
105          */
106         public function set_query_var($key, $value) {
107                 $this->query_vars[$key] = $value;
108         }
109
110         /**
111          * Parse request to find correct WordPress query.
112          *
113          * Sets up the query variables based on the request. There are also many
114          * filters and actions that can be used to further manipulate the result.
115          *
116          * @since 2.0.0
117          *
118          * @global WP_Rewrite $wp_rewrite
119          *
120          * @param array|string $extra_query_vars Set the extra query variables.
121          */
122         public function parse_request($extra_query_vars = '') {
123                 global $wp_rewrite;
124
125                 /**
126                  * Filter whether to parse the request.
127                  *
128                  * @since 3.5.0
129                  *
130                  * @param bool         $bool             Whether or not to parse the request. Default true.
131                  * @param WP           $this             Current WordPress environment instance.
132                  * @param array|string $extra_query_vars Extra passed query variables.
133                  */
134                 if ( ! apply_filters( 'do_parse_request', true, $this, $extra_query_vars ) )
135                         return;
136
137                 $this->query_vars = array();
138                 $post_type_query_vars = array();
139
140                 if ( is_array( $extra_query_vars ) ) {
141                         $this->extra_query_vars = & $extra_query_vars;
142                 } elseif ( ! empty( $extra_query_vars ) ) {
143                         parse_str( $extra_query_vars, $this->extra_query_vars );
144                 }
145                 // Process PATH_INFO, REQUEST_URI, and 404 for permalinks.
146
147                 // Fetch the rewrite rules.
148                 $rewrite = $wp_rewrite->wp_rewrite_rules();
149
150                 if ( ! empty($rewrite) ) {
151                         // If we match a rewrite rule, this will be cleared.
152                         $error = '404';
153                         $this->did_permalink = true;
154
155                         $pathinfo = isset( $_SERVER['PATH_INFO'] ) ? $_SERVER['PATH_INFO'] : '';
156                         list( $pathinfo ) = explode( '?', $pathinfo );
157                         $pathinfo = str_replace( "%", "%25", $pathinfo );
158
159                         list( $req_uri ) = explode( '?', $_SERVER['REQUEST_URI'] );
160                         $self = $_SERVER['PHP_SELF'];
161                         $home_path = trim( parse_url( home_url(), PHP_URL_PATH ), '/' );
162                         $home_path_regex = sprintf( '|^%s|i', preg_quote( $home_path, '|' ) );
163
164                         // Trim path info from the end and the leading home path from the
165                         // front. For path info requests, this leaves us with the requesting
166                         // filename, if any. For 404 requests, this leaves us with the
167                         // requested permalink.
168                         $req_uri = str_replace($pathinfo, '', $req_uri);
169                         $req_uri = trim($req_uri, '/');
170                         $req_uri = preg_replace( $home_path_regex, '', $req_uri );
171                         $req_uri = trim($req_uri, '/');
172                         $pathinfo = trim($pathinfo, '/');
173                         $pathinfo = preg_replace( $home_path_regex, '', $pathinfo );
174                         $pathinfo = trim($pathinfo, '/');
175                         $self = trim($self, '/');
176                         $self = preg_replace( $home_path_regex, '', $self );
177                         $self = trim($self, '/');
178
179                         // The requested permalink is in $pathinfo for path info requests and
180                         //  $req_uri for other requests.
181                         if ( ! empty($pathinfo) && !preg_match('|^.*' . $wp_rewrite->index . '$|', $pathinfo) ) {
182                                 $request = $pathinfo;
183                         } else {
184                                 // If the request uri is the index, blank it out so that we don't try to match it against a rule.
185                                 if ( $req_uri == $wp_rewrite->index )
186                                         $req_uri = '';
187                                 $request = $req_uri;
188                         }
189
190                         $this->request = $request;
191
192                         // Look for matches.
193                         $request_match = $request;
194                         if ( empty( $request_match ) ) {
195                                 // An empty request could only match against ^$ regex
196                                 if ( isset( $rewrite['$'] ) ) {
197                                         $this->matched_rule = '$';
198                                         $query = $rewrite['$'];
199                                         $matches = array('');
200                                 }
201                         } else {
202                                 foreach ( (array) $rewrite as $match => $query ) {
203                                         // If the requesting file is the anchor of the match, prepend it to the path info.
204                                         if ( ! empty($req_uri) && strpos($match, $req_uri) === 0 && $req_uri != $request )
205                                                 $request_match = $req_uri . '/' . $request;
206
207                                         if ( preg_match("#^$match#", $request_match, $matches) ||
208                                                 preg_match("#^$match#", urldecode($request_match), $matches) ) {
209
210                                                 if ( $wp_rewrite->use_verbose_page_rules && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch ) ) {
211                                                         // This is a verbose page match, let's check to be sure about it.
212                                                         if ( ! get_page_by_path( $matches[ $varmatch[1] ] ) )
213                                                                 continue;
214                                                 }
215
216                                                 // Got a match.
217                                                 $this->matched_rule = $match;
218                                                 break;
219                                         }
220                                 }
221                         }
222
223                         if ( isset( $this->matched_rule ) ) {
224                                 // Trim the query of everything up to the '?'.
225                                 $query = preg_replace("!^.+\?!", '', $query);
226
227                                 // Substitute the substring matches into the query.
228                                 $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
229
230                                 $this->matched_query = $query;
231
232                                 // Parse the query.
233                                 parse_str($query, $perma_query_vars);
234
235                                 // If we're processing a 404 request, clear the error var since we found something.
236                                 if ( '404' == $error )
237                                         unset( $error, $_GET['error'] );
238                         }
239
240                         // If req_uri is empty or if it is a request for ourself, unset error.
241                         if ( empty($request) || $req_uri == $self || strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false ) {
242                                 unset( $error, $_GET['error'] );
243
244                                 if ( isset($perma_query_vars) && strpos($_SERVER['PHP_SELF'], 'wp-admin/') !== false )
245                                         unset( $perma_query_vars );
246
247                                 $this->did_permalink = false;
248                         }
249                 }
250
251                 /**
252                  * Filter the query variables whitelist before processing.
253                  *
254                  * Allows (publicly allowed) query vars to be added, removed, or changed prior
255                  * to executing the query. Needed to allow custom rewrite rules using your own arguments
256                  * to work, or any other custom query variables you want to be publicly available.
257                  *
258                  * @since 1.5.0
259                  *
260                  * @param array $public_query_vars The array of whitelisted query variables.
261                  */
262                 $this->public_query_vars = apply_filters( 'query_vars', $this->public_query_vars );
263
264                 foreach ( get_post_types( array(), 'objects' ) as $post_type => $t )
265                         if ( $t->query_var )
266                                 $post_type_query_vars[$t->query_var] = $post_type;
267
268                 foreach ( $this->public_query_vars as $wpvar ) {
269                         if ( isset( $this->extra_query_vars[$wpvar] ) )
270                                 $this->query_vars[$wpvar] = $this->extra_query_vars[$wpvar];
271                         elseif ( isset( $_POST[$wpvar] ) )
272                                 $this->query_vars[$wpvar] = $_POST[$wpvar];
273                         elseif ( isset( $_GET[$wpvar] ) )
274                                 $this->query_vars[$wpvar] = $_GET[$wpvar];
275                         elseif ( isset( $perma_query_vars[$wpvar] ) )
276                                 $this->query_vars[$wpvar] = $perma_query_vars[$wpvar];
277
278                         if ( !empty( $this->query_vars[$wpvar] ) ) {
279                                 if ( ! is_array( $this->query_vars[$wpvar] ) ) {
280                                         $this->query_vars[$wpvar] = (string) $this->query_vars[$wpvar];
281                                 } else {
282                                         foreach ( $this->query_vars[$wpvar] as $vkey => $v ) {
283                                                 if ( !is_object( $v ) ) {
284                                                         $this->query_vars[$wpvar][$vkey] = (string) $v;
285                                                 }
286                                         }
287                                 }
288
289                                 if ( isset($post_type_query_vars[$wpvar] ) ) {
290                                         $this->query_vars['post_type'] = $post_type_query_vars[$wpvar];
291                                         $this->query_vars['name'] = $this->query_vars[$wpvar];
292                                 }
293                         }
294                 }
295
296                 // Convert urldecoded spaces back into +
297                 foreach ( get_taxonomies( array() , 'objects' ) as $taxonomy => $t )
298                         if ( $t->query_var && isset( $this->query_vars[$t->query_var] ) )
299                                 $this->query_vars[$t->query_var] = str_replace( ' ', '+', $this->query_vars[$t->query_var] );
300
301                 // Limit publicly queried post_types to those that are publicly_queryable
302                 if ( isset( $this->query_vars['post_type']) ) {
303                         $queryable_post_types = get_post_types( array('publicly_queryable' => true) );
304                         if ( ! is_array( $this->query_vars['post_type'] ) ) {
305                                 if ( ! in_array( $this->query_vars['post_type'], $queryable_post_types ) )
306                                         unset( $this->query_vars['post_type'] );
307                         } else {
308                                 $this->query_vars['post_type'] = array_intersect( $this->query_vars['post_type'], $queryable_post_types );
309                         }
310                 }
311
312                 // Resolve conflicts between posts with numeric slugs and date archive queries.
313                 $this->query_vars = wp_resolve_numeric_slug_conflicts( $this->query_vars );
314
315                 foreach ( (array) $this->private_query_vars as $var) {
316                         if ( isset($this->extra_query_vars[$var]) )
317                                 $this->query_vars[$var] = $this->extra_query_vars[$var];
318                 }
319
320                 if ( isset($error) )
321                         $this->query_vars['error'] = $error;
322
323                 /**
324                  * Filter the array of parsed query variables.
325                  *
326                  * @since 2.1.0
327                  *
328                  * @param array $query_vars The array of requested query variables.
329                  */
330                 $this->query_vars = apply_filters( 'request', $this->query_vars );
331
332                 /**
333                  * Fires once all query variables for the current request have been parsed.
334                  *
335                  * @since 2.1.0
336                  *
337                  * @param WP &$this Current WordPress environment instance (passed by reference).
338                  */
339                 do_action_ref_array( 'parse_request', array( &$this ) );
340         }
341
342         /**
343          * Send additional HTTP headers for caching, content type, etc.
344          *
345          * Sets the X-Pingback header, 404 status (if 404), Content-type. If showing
346          * a feed, it will also send last-modified, etag, and 304 status if needed.
347          *
348          * @since 2.0.0
349          */
350         public function send_headers() {
351                 $headers = array('X-Pingback' => get_bloginfo('pingback_url'));
352                 $status = null;
353                 $exit_required = false;
354
355                 if ( is_user_logged_in() )
356                         $headers = array_merge($headers, wp_get_nocache_headers());
357                 if ( ! empty( $this->query_vars['error'] ) ) {
358                         $status = (int) $this->query_vars['error'];
359                         if ( 404 === $status ) {
360                                 if ( ! is_user_logged_in() )
361                                         $headers = array_merge($headers, wp_get_nocache_headers());
362                                 $headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset');
363                         } elseif ( in_array( $status, array( 403, 500, 502, 503 ) ) ) {
364                                 $exit_required = true;
365                         }
366                 } elseif ( empty( $this->query_vars['feed'] ) ) {
367                         $headers['Content-Type'] = get_option('html_type') . '; charset=' . get_option('blog_charset');
368                 } else {
369                         // We're showing a feed, so WP is indeed the only thing that last changed
370                         if ( !empty($this->query_vars['withcomments'])
371                                 || false !== strpos( $this->query_vars['feed'], 'comments-' )
372                                 || ( empty($this->query_vars['withoutcomments'])
373                                         && ( !empty($this->query_vars['p'])
374                                                 || !empty($this->query_vars['name'])
375                                                 || !empty($this->query_vars['page_id'])
376                                                 || !empty($this->query_vars['pagename'])
377                                                 || !empty($this->query_vars['attachment'])
378                                                 || !empty($this->query_vars['attachment_id'])
379                                         )
380                                 )
381                         )
382                                 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastcommentmodified('GMT'), 0).' GMT';
383                         else
384                                 $wp_last_modified = mysql2date('D, d M Y H:i:s', get_lastpostmodified('GMT'), 0).' GMT';
385                         $wp_etag = '"' . md5($wp_last_modified) . '"';
386                         $headers['Last-Modified'] = $wp_last_modified;
387                         $headers['ETag'] = $wp_etag;
388
389                         // Support for Conditional GET
390                         if (isset($_SERVER['HTTP_IF_NONE_MATCH']))
391                                 $client_etag = wp_unslash( $_SERVER['HTTP_IF_NONE_MATCH'] );
392                         else $client_etag = false;
393
394                         $client_last_modified = empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? '' : trim($_SERVER['HTTP_IF_MODIFIED_SINCE']);
395                         // If string is empty, return 0. If not, attempt to parse into a timestamp
396                         $client_modified_timestamp = $client_last_modified ? strtotime($client_last_modified) : 0;
397
398                         // Make a timestamp for our most recent modification...
399                         $wp_modified_timestamp = strtotime($wp_last_modified);
400
401                         if ( ($client_last_modified && $client_etag) ?
402                                          (($client_modified_timestamp >= $wp_modified_timestamp) && ($client_etag == $wp_etag)) :
403                                          (($client_modified_timestamp >= $wp_modified_timestamp) || ($client_etag == $wp_etag)) ) {
404                                 $status = 304;
405                                 $exit_required = true;
406                         }
407                 }
408
409                 /**
410                  * Filter the HTTP headers before they're sent to the browser.
411                  *
412                  * @since 2.8.0
413                  *
414                  * @param array $headers The list of headers to be sent.
415                  * @param WP    $this    Current WordPress environment instance.
416                  */
417                 $headers = apply_filters( 'wp_headers', $headers, $this );
418
419                 if ( ! empty( $status ) )
420                         status_header( $status );
421
422                 // If Last-Modified is set to false, it should not be sent (no-cache situation).
423                 if ( isset( $headers['Last-Modified'] ) && false === $headers['Last-Modified'] ) {
424                         unset( $headers['Last-Modified'] );
425
426                         // In PHP 5.3+, make sure we are not sending a Last-Modified header.
427                         if ( function_exists( 'header_remove' ) ) {
428                                 @header_remove( 'Last-Modified' );
429                         } else {
430                                 // In PHP 5.2, send an empty Last-Modified header, but only as a
431                                 // last resort to override a header already sent. #WP23021
432                                 foreach ( headers_list() as $header ) {
433                                         if ( 0 === stripos( $header, 'Last-Modified' ) ) {
434                                                 $headers['Last-Modified'] = '';
435                                                 break;
436                                         }
437                                 }
438                         }
439                 }
440
441                 foreach( (array) $headers as $name => $field_value )
442                         @header("{$name}: {$field_value}");
443
444                 if ( $exit_required )
445                         exit();
446
447                 /**
448                  * Fires once the requested HTTP headers for caching, content type, etc. have been sent.
449                  *
450                  * @since 2.1.0
451                  *
452                  * @param WP &$this Current WordPress environment instance (passed by reference).
453                  */
454                 do_action_ref_array( 'send_headers', array( &$this ) );
455         }
456
457         /**
458          * Sets the query string property based off of the query variable property.
459          *
460          * The 'query_string' filter is deprecated, but still works. Plugins should
461          * use the 'request' filter instead.
462          *
463          * @since 2.0.0
464          */
465         public function build_query_string() {
466                 $this->query_string = '';
467                 foreach ( (array) array_keys($this->query_vars) as $wpvar) {
468                         if ( '' != $this->query_vars[$wpvar] ) {
469                                 $this->query_string .= (strlen($this->query_string) < 1) ? '' : '&';
470                                 if ( !is_scalar($this->query_vars[$wpvar]) ) // Discard non-scalars.
471                                         continue;
472                                 $this->query_string .= $wpvar . '=' . rawurlencode($this->query_vars[$wpvar]);
473                         }
474                 }
475
476                 if ( has_filter( 'query_string' ) ) {  // Don't bother filtering and parsing if no plugins are hooked in.
477                         /**
478                          * Filter the query string before parsing.
479                          *
480                          * @since 1.5.0
481                          * @deprecated 2.1.0 Use 'query_vars' or 'request' filters instead.
482                          *
483                          * @param string $query_string The query string to modify.
484                          */
485                         $this->query_string = apply_filters( 'query_string', $this->query_string );
486                         parse_str($this->query_string, $this->query_vars);
487                 }
488         }
489
490         /**
491          * Set up the WordPress Globals.
492          *
493          * The query_vars property will be extracted to the GLOBALS. So care should
494          * be taken when naming global variables that might interfere with the
495          * WordPress environment.
496          *
497          * @global WP_Query     $wp_query
498          * @global string       $query_string Query string for the loop.
499          * @global array        $posts The found posts.
500          * @global WP_Post|null $post The current post, if available.
501          * @global string       $request The SQL statement for the request.
502          * @global int          $more Only set, if single page or post.
503          * @global int          $single If single page or post. Only set, if single page or post.
504          * @global WP_User      $authordata Only set, if author archive.
505          *
506          * @since 2.0.0
507          */
508         public function register_globals() {
509                 global $wp_query;
510
511                 // Extract updated query vars back into global namespace.
512                 foreach ( (array) $wp_query->query_vars as $key => $value ) {
513                         $GLOBALS[ $key ] = $value;
514                 }
515
516                 $GLOBALS['query_string'] = $this->query_string;
517                 $GLOBALS['posts'] = & $wp_query->posts;
518                 $GLOBALS['post'] = isset( $wp_query->post ) ? $wp_query->post : null;
519                 $GLOBALS['request'] = $wp_query->request;
520
521                 if ( $wp_query->is_single() || $wp_query->is_page() ) {
522                         $GLOBALS['more']   = 1;
523                         $GLOBALS['single'] = 1;
524                 }
525
526                 if ( $wp_query->is_author() && isset( $wp_query->post ) )
527                         $GLOBALS['authordata'] = get_userdata( $wp_query->post->post_author );
528         }
529
530         /**
531          * Set up the current user.
532          *
533          * @since 2.0.0
534          */
535         public function init() {
536                 wp_get_current_user();
537         }
538
539         /**
540          * Set up the Loop based on the query variables.
541          *
542          * @since 2.0.0
543          *
544          * @global WP_Query $wp_the_query
545          */
546         public function query_posts() {
547                 global $wp_the_query;
548                 $this->build_query_string();
549                 $wp_the_query->query($this->query_vars);
550         }
551
552         /**
553          * Set the Headers for 404, if nothing is found for requested URL.
554          *
555          * Issue a 404 if a request doesn't match any posts and doesn't match
556          * any object (e.g. an existing-but-empty category, tag, author) and a 404 was not already
557          * issued, and if the request was not a search or the homepage.
558          *
559          * Otherwise, issue a 200.
560          *
561          * @since 2.0.0
562          *
563          * @global WP_Query $wp_query
564          */
565         public function handle_404() {
566                 global $wp_query;
567
568                 // If we've already issued a 404, bail.
569                 if ( is_404() )
570                         return;
571
572                 // Never 404 for the admin, robots, or if we found posts.
573                 if ( is_admin() || is_robots() || $wp_query->posts ) {
574                         status_header( 200 );
575                         return;
576                 }
577
578                 // We will 404 for paged queries, as no posts were found.
579                 if ( ! is_paged() ) {
580
581                         // Don't 404 for authors without posts as long as they matched an author on this site.
582                         $author = get_query_var( 'author' );
583                         if ( is_author() && is_numeric( $author ) && $author > 0 && is_user_member_of_blog( $author ) ) {
584                                 status_header( 200 );
585                                 return;
586                         }
587
588                         // Don't 404 for these queries if they matched an object.
589                         if ( ( is_tag() || is_category() || is_tax() || is_post_type_archive() ) && get_queried_object() ) {
590                                 status_header( 200 );
591                                 return;
592                         }
593
594                         // Don't 404 for these queries either.
595                         if ( is_home() || is_search() || is_feed() ) {
596                                 status_header( 200 );
597                                 return;
598                         }
599                 }
600
601                 // Guess it's time to 404.
602                 $wp_query->set_404();
603                 status_header( 404 );
604                 nocache_headers();
605         }
606
607         /**
608          * Sets up all of the variables required by the WordPress environment.
609          *
610          * The action 'wp' has one parameter that references the WP object. It
611          * allows for accessing the properties and methods to further manipulate the
612          * object.
613          *
614          * @since 2.0.0
615          *
616          * @param string|array $query_args Passed to {@link parse_request()}
617          */
618         public function main($query_args = '') {
619                 $this->init();
620                 $this->parse_request($query_args);
621                 $this->send_headers();
622                 $this->query_posts();
623                 $this->handle_404();
624                 $this->register_globals();
625
626                 /**
627                  * Fires once the WordPress environment has been set up.
628                  *
629                  * @since 2.1.0
630                  *
631                  * @param WP &$this Current WordPress environment instance (passed by reference).
632                  */
633                 do_action_ref_array( 'wp', array( &$this ) );
634         }
635 }
636
637 /**
638  * Helper class to remove the need to use eval to replace $matches[] in query strings.
639  *
640  * @since 2.9.0
641  */
642 class WP_MatchesMapRegex {
643         /**
644          * store for matches
645          *
646          * @access private
647          * @var array
648          */
649         private $_matches;
650
651         /**
652          * store for mapping result
653          *
654          * @access public
655          * @var string
656          */
657         public $output;
658
659         /**
660          * subject to perform mapping on (query string containing $matches[] references
661          *
662          * @access private
663          * @var string
664          */
665         private $_subject;
666
667         /**
668          * regexp pattern to match $matches[] references
669          *
670          * @var string
671          */
672         public $_pattern = '(\$matches\[[1-9]+[0-9]*\])'; // magic number
673
674         /**
675          * constructor
676          *
677          * @param string $subject subject if regex
678          * @param array  $matches data to use in map
679          */
680         public function __construct($subject, $matches) {
681                 $this->_subject = $subject;
682                 $this->_matches = $matches;
683                 $this->output = $this->_map();
684         }
685
686         /**
687          * Substitute substring matches in subject.
688          *
689          * static helper function to ease use
690          *
691          * @static
692          * @access public
693          *
694          * @param string $subject subject
695          * @param array  $matches data used for substitution
696          * @return string
697          */
698         public static function apply($subject, $matches) {
699                 $oSelf = new WP_MatchesMapRegex($subject, $matches);
700                 return $oSelf->output;
701         }
702
703         /**
704          * do the actual mapping
705          *
706          * @access private
707          * @return string
708          */
709         private function _map() {
710                 $callback = array($this, 'callback');
711                 return preg_replace_callback($this->_pattern, $callback, $this->_subject);
712         }
713
714         /**
715          * preg_replace_callback hook
716          *
717          * @access public
718          * @param  array $matches preg_replace regexp matches
719          * @return string
720          */
721         public function callback($matches) {
722                 $index = intval(substr($matches[0], 9, -1));
723                 return ( isset( $this->_matches[$index] ) ? urlencode($this->_matches[$index]) : '' );
724         }
725 }