]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/rewrite.php
WordPress 3.8-scripts
[autoinstalls/wordpress.git] / wp-includes / rewrite.php
1 <?php
2 /**
3  * WordPress Rewrite API
4  *
5  * @package WordPress
6  * @subpackage Rewrite
7  */
8
9 /**
10  * Add a straight rewrite rule.
11  *
12  * @see WP_Rewrite::add_rule() for long description.
13  * @since 2.1.0
14  *
15  * @param string $regex Regular Expression to match request against.
16  * @param string $redirect Page to redirect to.
17  * @param string $after Optional, default is 'bottom'. Where to add rule, can also be 'top'.
18  */
19 function add_rewrite_rule($regex, $redirect, $after = 'bottom') {
20         global $wp_rewrite;
21         $wp_rewrite->add_rule($regex, $redirect, $after);
22 }
23
24 /**
25  * Add a new rewrite tag (like %postname%).
26  *
27  * The $query parameter is optional. If it is omitted you must ensure that
28  * you call this on, or before, the 'init' hook. This is because $query defaults
29  * to "$tag=", and for this to work a new query var has to be added.
30  *
31  * @see WP_Rewrite::add_rewrite_tag()
32  * @since 2.1.0
33  *
34  * @param string $tag Name of the new rewrite tag.
35  * @param string $regex Regular expression to substitute the tag for in rewrite rules.
36  * @param string $query String to append to the rewritten query. Must end in '='. Optional.
37  */
38 function add_rewrite_tag( $tag, $regex, $query = '' ) {
39         // validate the tag's name
40         if ( strlen( $tag ) < 3 || $tag[0] != '%' || $tag[ strlen($tag) - 1 ] != '%' )
41                 return;
42
43         global $wp_rewrite, $wp;
44
45         if ( empty( $query ) ) {
46                 $qv = trim( $tag, '%' );
47                 $wp->add_query_var( $qv );
48                 $query = $qv . '=';
49         }
50
51         $wp_rewrite->add_rewrite_tag( $tag, $regex, $query );
52 }
53
54 /**
55  * Add permalink structure.
56  *
57  * @see WP_Rewrite::add_permastruct()
58  * @since 3.0.0
59  *
60  * @param string $name Name for permalink structure.
61  * @param string $struct Permalink structure.
62  * @param array $args Optional configuration for building the rules from the permalink structure,
63  *     see {@link WP_Rewrite::add_permastruct()} for full details.
64  */
65 function add_permastruct( $name, $struct, $args = array() ) {
66         global $wp_rewrite;
67
68         // backwards compatibility for the old parameters: $with_front and $ep_mask
69         if ( ! is_array( $args ) )
70                 $args = array( 'with_front' => $args );
71         if ( func_num_args() == 4 )
72                 $args['ep_mask'] = func_get_arg( 3 );
73
74         return $wp_rewrite->add_permastruct( $name, $struct, $args );
75 }
76
77 /**
78  * Add a new feed type like /atom1/.
79  *
80  * @since 2.1.0
81  *
82  * @param string $feedname
83  * @param callback $function Callback to run on feed display.
84  * @return string Feed action name.
85  */
86 function add_feed($feedname, $function) {
87         global $wp_rewrite;
88         if ( ! in_array($feedname, $wp_rewrite->feeds) ) //override the file if it is
89                 $wp_rewrite->feeds[] = $feedname;
90         $hook = 'do_feed_' . $feedname;
91         // Remove default function hook
92         remove_action($hook, $hook);
93         add_action($hook, $function, 10, 1);
94         return $hook;
95 }
96
97 /**
98  * Remove rewrite rules and then recreate rewrite rules.
99  *
100  * @see WP_Rewrite::flush_rules()
101  * @since 3.0.0
102  *
103  * @param bool $hard Whether to update .htaccess (hard flush) or just update
104  *      rewrite_rules transient (soft flush). Default is true (hard).
105  */
106 function flush_rewrite_rules( $hard = true ) {
107         global $wp_rewrite;
108         $wp_rewrite->flush_rules( $hard );
109 }
110
111 /**
112  * Endpoint Mask for default, which is nothing.
113  *
114  * @since 2.1.0
115  */
116 define('EP_NONE', 0);
117
118 /**
119  * Endpoint Mask for Permalink.
120  *
121  * @since 2.1.0
122  */
123 define('EP_PERMALINK', 1);
124
125 /**
126  * Endpoint Mask for Attachment.
127  *
128  * @since 2.1.0
129  */
130 define('EP_ATTACHMENT', 2);
131
132 /**
133  * Endpoint Mask for date.
134  *
135  * @since 2.1.0
136  */
137 define('EP_DATE', 4);
138
139 /**
140  * Endpoint Mask for year
141  *
142  * @since 2.1.0
143  */
144 define('EP_YEAR', 8);
145
146 /**
147  * Endpoint Mask for month.
148  *
149  * @since 2.1.0
150  */
151 define('EP_MONTH', 16);
152
153 /**
154  * Endpoint Mask for day.
155  *
156  * @since 2.1.0
157  */
158 define('EP_DAY', 32);
159
160 /**
161  * Endpoint Mask for root.
162  *
163  * @since 2.1.0
164  */
165 define('EP_ROOT', 64);
166
167 /**
168  * Endpoint Mask for comments.
169  *
170  * @since 2.1.0
171  */
172 define('EP_COMMENTS', 128);
173
174 /**
175  * Endpoint Mask for searches.
176  *
177  * @since 2.1.0
178  */
179 define('EP_SEARCH', 256);
180
181 /**
182  * Endpoint Mask for categories.
183  *
184  * @since 2.1.0
185  */
186 define('EP_CATEGORIES', 512);
187
188 /**
189  * Endpoint Mask for tags.
190  *
191  * @since 2.3.0
192  */
193 define('EP_TAGS', 1024);
194
195 /**
196  * Endpoint Mask for authors.
197  *
198  * @since 2.1.0
199  */
200 define('EP_AUTHORS', 2048);
201
202 /**
203  * Endpoint Mask for pages.
204  *
205  * @since 2.1.0
206  */
207 define('EP_PAGES', 4096);
208
209 /**
210  * Endpoint Mask for all archive views.
211  *
212  * @since 3.7.0
213  */
214 define( 'EP_ALL_ARCHIVES', EP_DATE | EP_YEAR | EP_MONTH | EP_DAY | EP_CATEGORIES | EP_TAGS | EP_AUTHORS );
215
216 /**
217  * Endpoint Mask for everything.
218  *
219  * @since 2.1.0
220  */
221 define( 'EP_ALL', EP_PERMALINK | EP_ATTACHMENT | EP_ROOT | EP_COMMENTS | EP_SEARCH | EP_PAGES | EP_ALL_ARCHIVES );
222
223 /**
224  * Add an endpoint, like /trackback/.
225  *
226  * Adding an endpoint creates extra rewrite rules for each of the matching
227  * places specified by the provided bitmask. For example:
228  *
229  * <code>
230  * add_rewrite_endpoint( 'json', EP_PERMALINK | EP_PAGES );
231  * </code>
232  *
233  * will add a new rewrite rule ending with "json(/(.*))?/?$" for every permastruct
234  * that describes a permalink (post) or page. This is rewritten to "json=$match"
235  * where $match is the part of the URL matched by the endpoint regex (e.g. "foo" in
236  * "<permalink>/json/foo/").
237  *
238  * A new query var with the same name as the endpoint will also be created.
239  *
240  * When specifying $places ensure that you are using the EP_* constants (or a
241  * combination of them using the bitwise OR operator) as their values are not
242  * guaranteed to remain static (especially EP_ALL).
243  *
244  * Be sure to flush the rewrite rules - flush_rewrite_rules() - when your plugin gets
245  * activated and deactivated.
246  *
247  * @since 2.1.0
248  * @see WP_Rewrite::add_endpoint()
249  * @global object $wp_rewrite
250  *
251  * @param string $name Name of the endpoint.
252  * @param int $places Endpoint mask describing the places the endpoint should be added.
253  */
254 function add_rewrite_endpoint( $name, $places ) {
255         global $wp_rewrite;
256         $wp_rewrite->add_endpoint( $name, $places );
257 }
258
259 /**
260  * Filter the URL base for taxonomies.
261  *
262  * To remove any manually prepended /index.php/.
263  *
264  * @access private
265  * @since 2.6.0
266  *
267  * @param string $base The taxonomy base that we're going to filter
268  * @return string
269  */
270 function _wp_filter_taxonomy_base( $base ) {
271         if ( !empty( $base ) ) {
272                 $base = preg_replace( '|^/index\.php/|', '', $base );
273                 $base = trim( $base, '/' );
274         }
275         return $base;
276 }
277
278 /**
279  * Examine a url and try to determine the post ID it represents.
280  *
281  * Checks are supposedly from the hosted site blog.
282  *
283  * @since 1.0.0
284  *
285  * @param string $url Permalink to check.
286  * @return int Post ID, or 0 on failure.
287  */
288 function url_to_postid($url) {
289         global $wp_rewrite;
290
291         $url = apply_filters('url_to_postid', $url);
292
293         // First, check to see if there is a 'p=N' or 'page_id=N' to match against
294         if ( preg_match('#[?&](p|page_id|attachment_id)=(\d+)#', $url, $values) )       {
295                 $id = absint($values[2]);
296                 if ( $id )
297                         return $id;
298         }
299
300         // Check to see if we are using rewrite rules
301         $rewrite = $wp_rewrite->wp_rewrite_rules();
302
303         // Not using rewrite rules, and 'p=N' and 'page_id=N' methods failed, so we're out of options
304         if ( empty($rewrite) )
305                 return 0;
306
307         // Get rid of the #anchor
308         $url_split = explode('#', $url);
309         $url = $url_split[0];
310
311         // Get rid of URL ?query=string
312         $url_split = explode('?', $url);
313         $url = $url_split[0];
314
315         // Add 'www.' if it is absent and should be there
316         if ( false !== strpos(home_url(), '://www.') && false === strpos($url, '://www.') )
317                 $url = str_replace('://', '://www.', $url);
318
319         // Strip 'www.' if it is present and shouldn't be
320         if ( false === strpos(home_url(), '://www.') )
321                 $url = str_replace('://www.', '://', $url);
322
323         // Strip 'index.php/' if we're not using path info permalinks
324         if ( !$wp_rewrite->using_index_permalinks() )
325                 $url = str_replace( $wp_rewrite->index . '/', '', $url );
326
327         if ( false !== strpos( trailingslashit( $url ), home_url( '/' ) ) ) {
328                 // Chop off http://domain.com/[path]
329                 $url = str_replace(home_url(), '', $url);
330         } else {
331                 // Chop off /path/to/blog
332                 $home_path = parse_url( home_url( '/' ) );
333                 $home_path = isset( $home_path['path'] ) ? $home_path['path'] : '' ;
334                 $url = preg_replace( sprintf( '#^%s#', preg_quote( $home_path ) ), '', trailingslashit( $url ) );
335         }
336
337         // Trim leading and lagging slashes
338         $url = trim($url, '/');
339
340         $request = $url;
341         $post_type_query_vars = array();
342
343         foreach ( get_post_types( array() , 'objects' ) as $post_type => $t ) {
344                 if ( ! empty( $t->query_var ) )
345                         $post_type_query_vars[ $t->query_var ] = $post_type;
346         }
347
348         // Look for matches.
349         $request_match = $request;
350         foreach ( (array)$rewrite as $match => $query) {
351
352                 // If the requesting file is the anchor of the match, prepend it
353                 // to the path info.
354                 if ( !empty($url) && ($url != $request) && (strpos($match, $url) === 0) )
355                         $request_match = $url . '/' . $request;
356
357                 if ( preg_match("!^$match!", $request_match, $matches) ) {
358
359                         if ( $wp_rewrite->use_verbose_page_rules && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch ) ) {
360                                 // this is a verbose page match, lets check to be sure about it
361                                 if ( ! get_page_by_path( $matches[ $varmatch[1] ] ) )
362                                         continue;
363                         }
364
365                         // Got a match.
366                         // Trim the query of everything up to the '?'.
367                         $query = preg_replace("!^.+\?!", '', $query);
368
369                         // Substitute the substring matches into the query.
370                         $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
371
372                         // Filter out non-public query vars
373                         global $wp;
374                         parse_str( $query, $query_vars );
375                         $query = array();
376                         foreach ( (array) $query_vars as $key => $value ) {
377                                 if ( in_array( $key, $wp->public_query_vars ) ){
378                                         $query[$key] = $value;
379                                         if ( isset( $post_type_query_vars[$key] ) ) {
380                                                 $query['post_type'] = $post_type_query_vars[$key];
381                                                 $query['name'] = $value;
382                                         }
383                                 }
384                         }
385
386                         // Do the query
387                         $query = new WP_Query( $query );
388                         if ( ! empty( $query->posts ) && $query->is_singular )
389                                 return $query->post->ID;
390                         else
391                                 return 0;
392                 }
393         }
394         return 0;
395 }
396
397 /**
398  * WordPress Rewrite Component.
399  *
400  * The WordPress Rewrite class writes the rewrite module rules to the .htaccess
401  * file. It also handles parsing the request to get the correct setup for the
402  * WordPress Query class.
403  *
404  * The Rewrite along with WP class function as a front controller for WordPress.
405  * You can add rules to trigger your page view and processing using this
406  * component. The full functionality of a front controller does not exist,
407  * meaning you can't define how the template files load based on the rewrite
408  * rules.
409  *
410  * @since 1.5.0
411  */
412 class WP_Rewrite {
413         /**
414          * Permalink structure for posts.
415          *
416          * @since 1.5.0
417          * @access private
418          * @var string
419          */
420         var $permalink_structure;
421
422         /**
423          * Whether to add trailing slashes.
424          *
425          * @since 2.2.0
426          * @access private
427          * @var bool
428          */
429         var $use_trailing_slashes;
430
431         /**
432          * Base for the author permalink structure (example.com/$author_base/authorname).
433          *
434          * @since 1.5.0
435          * @access private
436          * @var string
437          */
438         var $author_base = 'author';
439
440         /**
441          * Permalink structure for author archives.
442          *
443          * @since 1.5.0
444          * @access private
445          * @var string
446          */
447         var $author_structure;
448
449         /**
450          * Permalink structure for date archives.
451          *
452          * @since 1.5.0
453          * @access private
454          * @var string
455          */
456         var $date_structure;
457
458         /**
459          * Permalink structure for pages.
460          *
461          * @since 1.5.0
462          * @access private
463          * @var string
464          */
465         var $page_structure;
466
467         /**
468          * Base of the search permalink structure (example.com/$search_base/query).
469          *
470          * @since 1.5.0
471          * @access private
472          * @var string
473          */
474         var $search_base = 'search';
475
476         /**
477          * Permalink structure for searches.
478          *
479          * @since 1.5.0
480          * @access private
481          * @var string
482          */
483         var $search_structure;
484
485         /**
486          * Comments permalink base.
487          *
488          * @since 1.5.0
489          * @access private
490          * @var string
491          */
492         var $comments_base = 'comments';
493
494         /**
495          * Pagination permalink base.
496          *
497          * @since 3.1.0
498          * @access private
499          * @var string
500          */
501         var $pagination_base = 'page';
502
503         /**
504          * Feed permalink base.
505          *
506          * @since 1.5.0
507          * @access private
508          * @var string
509          */
510         var $feed_base = 'feed';
511
512         /**
513          * Comments feed permalink structure.
514          *
515          * @since 1.5.0
516          * @access private
517          * @var string
518          */
519         var $comments_feed_structure;
520
521         /**
522          * Feed request permalink structure.
523          *
524          * @since 1.5.0
525          * @access private
526          * @var string
527          */
528         var $feed_structure;
529
530         /**
531          * The static portion of the post permalink structure.
532          *
533          * If the permalink structure is "/archive/%post_id%" then the front
534          * is "/archive/". If the permalink structure is "/%year%/%postname%/"
535          * then the front is "/".
536          *
537          * @see WP_Rewrite::init()
538          * @since 1.5.0
539          * @access private
540          * @var string
541          */
542         var $front;
543
544         /**
545          * The prefix for all permalink structures.
546          *
547          * If PATHINFO/index permalinks are in use then the root is the value of
548          * {@link WP_Rewrite::$index} with a trailing slash appended. Otherwise
549          * the root will be empty.
550          *
551          * @see WP_Rewrite::init()
552          * @see WP_Rewrite::using_index_permalinks()
553          * @since 1.5.0
554          * @access private
555          * @var string
556          */
557         var $root = '';
558
559         /**
560          * The name of the index file which is the entry point to all requests.
561          *
562          * @since 1.5.0
563          * @access public
564          * @var string
565          */
566         var $index = 'index.php';
567
568         /**
569          * Variable name to use for regex matches in the rewritten query.
570          *
571          * @since 1.5.0
572          * @access private
573          * @var string
574          */
575         var $matches = '';
576
577         /**
578          * Rewrite rules to match against the request to find the redirect or query.
579          *
580          * @since 1.5.0
581          * @access private
582          * @var array
583          */
584         var $rules;
585
586         /**
587          * Additional rules added external to the rewrite class.
588          *
589          * Those not generated by the class, see add_rewrite_rule().
590          *
591          * @since 2.1.0
592          * @access private
593          * @var array
594          */
595         var $extra_rules = array();
596
597         /**
598          * Additional rules that belong at the beginning to match first.
599          *
600          * Those not generated by the class, see add_rewrite_rule().
601          *
602          * @since 2.3.0
603          * @access private
604          * @var array
605          */
606         var $extra_rules_top = array();
607
608         /**
609          * Rules that don't redirect to WordPress' index.php.
610          *
611          * These rules are written to the mod_rewrite portion of the .htaccess,
612          * and are added by {@link add_external_rule()}.
613          *
614          * @since 2.1.0
615          * @access private
616          * @var array
617          */
618         var $non_wp_rules = array();
619
620         /**
621          * Extra permalink structures, e.g. categories, added by {@link add_permastruct()}.
622          *
623          * @since 2.1.0
624          * @access private
625          * @var array
626          */
627         var $extra_permastructs = array();
628
629         /**
630          * Endpoints (like /trackback/) added by {@link add_rewrite_endpoint()}.
631          *
632          * @since 2.1.0
633          * @access private
634          * @var array
635          */
636         var $endpoints;
637
638         /**
639          * Whether to write every mod_rewrite rule for WordPress into the .htaccess file.
640          *
641          * This is off by default, turning it on might print a lot of rewrite rules
642          * to the .htaccess file.
643          *
644          * @see WP_Rewrite::mod_rewrite_rules()
645          * @since 2.0.0
646          * @access public
647          * @var bool
648          */
649         var $use_verbose_rules = false;
650
651         /**
652          * Could post permalinks be confused with those of pages?
653          *
654          * If the first rewrite tag in the post permalink structure is one that could
655          * also match a page name (e.g. %postname% or %author%) then this flag is
656          * set to true. Prior to WordPress 3.3 this flag indicated that every page
657          * would have a set of rules added to the top of the rewrite rules array.
658          * Now it tells {@link WP::parse_request()} to check if a URL matching the
659          * page permastruct is actually a page before accepting it.
660          *
661          * @link http://core.trac.wordpress.org/ticket/16687
662          * @see WP_Rewrite::init()
663          * @since 2.5.0
664          * @access public
665          * @var bool
666          */
667         var $use_verbose_page_rules = true;
668
669         /**
670          * Rewrite tags that can be used in permalink structures.
671          *
672          * These are translated into the regular expressions stored in
673          * {@link WP_Rewrite::$rewritereplace} and are rewritten to the
674          * query variables listed in {@link WP_Rewrite::$queryreplace}.
675          *
676          * Additional tags can be added with {@link add_rewrite_tag()}.
677          *
678          * @since 1.5.0
679          * @access private
680          * @var array
681          */
682         var $rewritecode = array(
683                 '%year%',
684                 '%monthnum%',
685                 '%day%',
686                 '%hour%',
687                 '%minute%',
688                 '%second%',
689                 '%postname%',
690                 '%post_id%',
691                 '%author%',
692                 '%pagename%',
693                 '%search%'
694         );
695
696         /**
697          * Regular expressions to be substituted into rewrite rules in place
698          * of rewrite tags, see {@link WP_Rewrite::$rewritecode}.
699          *
700          * @since 1.5.0
701          * @access private
702          * @var array
703          */
704         var $rewritereplace = array(
705                 '([0-9]{4})',
706                 '([0-9]{1,2})',
707                 '([0-9]{1,2})',
708                 '([0-9]{1,2})',
709                 '([0-9]{1,2})',
710                 '([0-9]{1,2})',
711                 '([^/]+)',
712                 '([0-9]+)',
713                 '([^/]+)',
714                 '([^/]+?)',
715                 '(.+)'
716         );
717
718         /**
719          * Query variables that rewrite tags map to, see {@link WP_Rewrite::$rewritecode}.
720          *
721          * @since 1.5.0
722          * @access private
723          * @var array
724          */
725         var $queryreplace = array(
726                 'year=',
727                 'monthnum=',
728                 'day=',
729                 'hour=',
730                 'minute=',
731                 'second=',
732                 'name=',
733                 'p=',
734                 'author_name=',
735                 'pagename=',
736                 's='
737         );
738
739         /**
740          * Supported default feeds.
741          *
742          * @since 1.5.0
743          * @access private
744          * @var array
745          */
746         var $feeds = array( 'feed', 'rdf', 'rss', 'rss2', 'atom' );
747
748         /**
749          * Whether permalinks are being used.
750          *
751          * This can be either rewrite module or permalink in the HTTP query string.
752          *
753          * @since 1.5.0
754          * @access public
755          *
756          * @return bool True, if permalinks are enabled.
757          */
758         function using_permalinks() {
759                 return ! empty($this->permalink_structure);
760         }
761
762         /**
763          * Whether permalinks are being used and rewrite module is not enabled.
764          *
765          * Means that permalink links are enabled and index.php is in the URL.
766          *
767          * @since 1.5.0
768          * @access public
769          *
770          * @return bool
771          */
772         function using_index_permalinks() {
773                 if ( empty($this->permalink_structure) )
774                         return false;
775
776                 // If the index is not in the permalink, we're using mod_rewrite.
777                 if ( preg_match('#^/*' . $this->index . '#', $this->permalink_structure) )
778                         return true;
779
780                 return false;
781         }
782
783         /**
784          * Whether permalinks are being used and rewrite module is enabled.
785          *
786          * Using permalinks and index.php is not in the URL.
787          *
788          * @since 1.5.0
789          * @access public
790          *
791          * @return bool
792          */
793         function using_mod_rewrite_permalinks() {
794                 if ( $this->using_permalinks() && ! $this->using_index_permalinks() )
795                         return true;
796                 else
797                         return false;
798         }
799
800         /**
801          * Index for matches for usage in preg_*() functions.
802          *
803          * The format of the string is, with empty matches property value, '$NUM'.
804          * The 'NUM' will be replaced with the value in the $number parameter. With
805          * the matches property not empty, the value of the returned string will
806          * contain that value of the matches property. The format then will be
807          * '$MATCHES[NUM]', with MATCHES as the value in the property and NUM the
808          * value of the $number parameter.
809          *
810          * @since 1.5.0
811          * @access public
812          *
813          * @param int $number Index number.
814          * @return string
815          */
816         function preg_index($number) {
817                 $match_prefix = '$';
818                 $match_suffix = '';
819
820                 if ( ! empty($this->matches) ) {
821                         $match_prefix = '$' . $this->matches . '[';
822                         $match_suffix = ']';
823                 }
824
825                 return "$match_prefix$number$match_suffix";
826         }
827
828         /**
829          * Retrieve all page and attachments for pages URIs.
830          *
831          * The attachments are for those that have pages as parents and will be
832          * retrieved.
833          *
834          * @since 2.5.0
835          * @access public
836          *
837          * @return array Array of page URIs as first element and attachment URIs as second element.
838          */
839         function page_uri_index() {
840                 global $wpdb;
841
842                 //get pages in order of hierarchy, i.e. children after parents
843                 $pages = $wpdb->get_results("SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_type = 'page' AND post_status != 'auto-draft'");
844                 $posts = get_page_hierarchy( $pages );
845
846                 // If we have no pages get out quick
847                 if ( !$posts )
848                         return array( array(), array() );
849
850                 //now reverse it, because we need parents after children for rewrite rules to work properly
851                 $posts = array_reverse($posts, true);
852
853                 $page_uris = array();
854                 $page_attachment_uris = array();
855
856                 foreach ( $posts as $id => $post ) {
857                         // URL => page name
858                         $uri = get_page_uri($id);
859                         $attachments = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_type = 'attachment' AND post_parent = %d", $id ));
860                         if ( !empty($attachments) ) {
861                                 foreach ( $attachments as $attachment ) {
862                                         $attach_uri = get_page_uri($attachment->ID);
863                                         $page_attachment_uris[$attach_uri] = $attachment->ID;
864                                 }
865                         }
866
867                         $page_uris[$uri] = $id;
868                 }
869
870                 return array( $page_uris, $page_attachment_uris );
871         }
872
873         /**
874          * Retrieve all of the rewrite rules for pages.
875          *
876          * @since 1.5.0
877          * @access public
878          *
879          * @return array
880          */
881         function page_rewrite_rules() {
882                 // the extra .? at the beginning prevents clashes with other regular expressions in the rules array
883                 $this->add_rewrite_tag( '%pagename%', '(.?.+?)', 'pagename=' );
884
885                 return $this->generate_rewrite_rules( $this->get_page_permastruct(), EP_PAGES, true, true, false, false );
886         }
887
888         /**
889          * Retrieve date permalink structure, with year, month, and day.
890          *
891          * The permalink structure for the date, if not set already depends on the
892          * permalink structure. It can be one of three formats. The first is year,
893          * month, day; the second is day, month, year; and the last format is month,
894          * day, year. These are matched against the permalink structure for which
895          * one is used. If none matches, then the default will be used, which is
896          * year, month, day.
897          *
898          * Prevents post ID and date permalinks from overlapping. In the case of
899          * post_id, the date permalink will be prepended with front permalink with
900          * 'date/' before the actual permalink to form the complete date permalink
901          * structure.
902          *
903          * @since 1.5.0
904          * @access public
905          *
906          * @return bool|string False on no permalink structure. Date permalink structure.
907          */
908         function get_date_permastruct() {
909                 if ( isset($this->date_structure) )
910                         return $this->date_structure;
911
912                 if ( empty($this->permalink_structure) ) {
913                         $this->date_structure = '';
914                         return false;
915                 }
916
917                 // The date permalink must have year, month, and day separated by slashes.
918                 $endians = array('%year%/%monthnum%/%day%', '%day%/%monthnum%/%year%', '%monthnum%/%day%/%year%');
919
920                 $this->date_structure = '';
921                 $date_endian = '';
922
923                 foreach ( $endians as $endian ) {
924                         if ( false !== strpos($this->permalink_structure, $endian) ) {
925                                 $date_endian= $endian;
926                                 break;
927                         }
928                 }
929
930                 if ( empty($date_endian) )
931                         $date_endian = '%year%/%monthnum%/%day%';
932
933                 // Do not allow the date tags and %post_id% to overlap in the permalink
934                 // structure. If they do, move the date tags to $front/date/.
935                 $front = $this->front;
936                 preg_match_all('/%.+?%/', $this->permalink_structure, $tokens);
937                 $tok_index = 1;
938                 foreach ( (array) $tokens[0] as $token) {
939                         if ( '%post_id%' == $token && ($tok_index <= 3) ) {
940                                 $front = $front . 'date/';
941                                 break;
942                         }
943                         $tok_index++;
944                 }
945
946                 $this->date_structure = $front . $date_endian;
947
948                 return $this->date_structure;
949         }
950
951         /**
952          * Retrieve the year permalink structure without month and day.
953          *
954          * Gets the date permalink structure and strips out the month and day
955          * permalink structures.
956          *
957          * @since 1.5.0
958          * @access public
959          *
960          * @return bool|string False on failure. Year structure on success.
961          */
962         function get_year_permastruct() {
963                 $structure = $this->get_date_permastruct();
964
965                 if ( empty($structure) )
966                         return false;
967
968                 $structure = str_replace('%monthnum%', '', $structure);
969                 $structure = str_replace('%day%', '', $structure);
970
971                 $structure = preg_replace('#/+#', '/', $structure);
972
973                 return $structure;
974         }
975
976         /**
977          * Retrieve the month permalink structure without day and with year.
978          *
979          * Gets the date permalink structure and strips out the day permalink
980          * structures. Keeps the year permalink structure.
981          *
982          * @since 1.5.0
983          * @access public
984          *
985          * @return bool|string False on failure. Year/Month structure on success.
986          */
987         function get_month_permastruct() {
988                 $structure = $this->get_date_permastruct();
989
990                 if ( empty($structure) )
991                         return false;
992
993                 $structure = str_replace('%day%', '', $structure);
994
995                 $structure = preg_replace('#/+#', '/', $structure);
996
997                 return $structure;
998         }
999
1000         /**
1001          * Retrieve the day permalink structure with month and year.
1002          *
1003          * Keeps date permalink structure with all year, month, and day.
1004          *
1005          * @since 1.5.0
1006          * @access public
1007          *
1008          * @return bool|string False on failure. Year/Month/Day structure on success.
1009          */
1010         function get_day_permastruct() {
1011                 return $this->get_date_permastruct();
1012         }
1013
1014         /**
1015          * Retrieve the permalink structure for categories.
1016          *
1017          * If the category_base property has no value, then the category structure
1018          * will have the front property value, followed by 'category', and finally
1019          * '%category%'. If it does, then the root property will be used, along with
1020          * the category_base property value.
1021          *
1022          * @since 1.5.0
1023          * @access public
1024          *
1025          * @return bool|string False on failure. Category permalink structure.
1026          */
1027         function get_category_permastruct() {
1028                 return $this->get_extra_permastruct('category');
1029         }
1030
1031         /**
1032          * Retrieve the permalink structure for tags.
1033          *
1034          * If the tag_base property has no value, then the tag structure will have
1035          * the front property value, followed by 'tag', and finally '%tag%'. If it
1036          * does, then the root property will be used, along with the tag_base
1037          * property value.
1038          *
1039          * @since 2.3.0
1040          * @access public
1041          *
1042          * @return bool|string False on failure. Tag permalink structure.
1043          */
1044         function get_tag_permastruct() {
1045                 return $this->get_extra_permastruct('post_tag');
1046         }
1047
1048         /**
1049          * Retrieve extra permalink structure by name.
1050          *
1051          * @since 2.5.0
1052          * @access public
1053          *
1054          * @param string $name Permalink structure name.
1055          * @return string|bool False if not found. Permalink structure string.
1056          */
1057         function get_extra_permastruct($name) {
1058                 if ( empty($this->permalink_structure) )
1059                         return false;
1060
1061                 if ( isset($this->extra_permastructs[$name]) )
1062                         return $this->extra_permastructs[$name]['struct'];
1063
1064                 return false;
1065         }
1066
1067         /**
1068          * Retrieve the author permalink structure.
1069          *
1070          * The permalink structure is front property, author base, and finally
1071          * '/%author%'. Will set the author_structure property and then return it
1072          * without attempting to set the value again.
1073          *
1074          * @since 1.5.0
1075          * @access public
1076          *
1077          * @return string|bool False if not found. Permalink structure string.
1078          */
1079         function get_author_permastruct() {
1080                 if ( isset($this->author_structure) )
1081                         return $this->author_structure;
1082
1083                 if ( empty($this->permalink_structure) ) {
1084                         $this->author_structure = '';
1085                         return false;
1086                 }
1087
1088                 $this->author_structure = $this->front . $this->author_base . '/%author%';
1089
1090                 return $this->author_structure;
1091         }
1092
1093         /**
1094          * Retrieve the search permalink structure.
1095          *
1096          * The permalink structure is root property, search base, and finally
1097          * '/%search%'. Will set the search_structure property and then return it
1098          * without attempting to set the value again.
1099          *
1100          * @since 1.5.0
1101          * @access public
1102          *
1103          * @return string|bool False if not found. Permalink structure string.
1104          */
1105         function get_search_permastruct() {
1106                 if ( isset($this->search_structure) )
1107                         return $this->search_structure;
1108
1109                 if ( empty($this->permalink_structure) ) {
1110                         $this->search_structure = '';
1111                         return false;
1112                 }
1113
1114                 $this->search_structure = $this->root . $this->search_base . '/%search%';
1115
1116                 return $this->search_structure;
1117         }
1118
1119         /**
1120          * Retrieve the page permalink structure.
1121          *
1122          * The permalink structure is root property, and '%pagename%'. Will set the
1123          * page_structure property and then return it without attempting to set the
1124          * value again.
1125          *
1126          * @since 1.5.0
1127          * @access public
1128          *
1129          * @return string|bool False if not found. Permalink structure string.
1130          */
1131         function get_page_permastruct() {
1132                 if ( isset($this->page_structure) )
1133                         return $this->page_structure;
1134
1135                 if (empty($this->permalink_structure)) {
1136                         $this->page_structure = '';
1137                         return false;
1138                 }
1139
1140                 $this->page_structure = $this->root . '%pagename%';
1141
1142                 return $this->page_structure;
1143         }
1144
1145         /**
1146          * Retrieve the feed permalink structure.
1147          *
1148          * The permalink structure is root property, feed base, and finally
1149          * '/%feed%'. Will set the feed_structure property and then return it
1150          * without attempting to set the value again.
1151          *
1152          * @since 1.5.0
1153          * @access public
1154          *
1155          * @return string|bool False if not found. Permalink structure string.
1156          */
1157         function get_feed_permastruct() {
1158                 if ( isset($this->feed_structure) )
1159                         return $this->feed_structure;
1160
1161                 if ( empty($this->permalink_structure) ) {
1162                         $this->feed_structure = '';
1163                         return false;
1164                 }
1165
1166                 $this->feed_structure = $this->root . $this->feed_base . '/%feed%';
1167
1168                 return $this->feed_structure;
1169         }
1170
1171         /**
1172          * Retrieve the comment feed permalink structure.
1173          *
1174          * The permalink structure is root property, comment base property, feed
1175          * base and finally '/%feed%'. Will set the comment_feed_structure property
1176          * and then return it without attempting to set the value again.
1177          *
1178          * @since 1.5.0
1179          * @access public
1180          *
1181          * @return string|bool False if not found. Permalink structure string.
1182          */
1183         function get_comment_feed_permastruct() {
1184                 if ( isset($this->comment_feed_structure) )
1185                         return $this->comment_feed_structure;
1186
1187                 if (empty($this->permalink_structure)) {
1188                         $this->comment_feed_structure = '';
1189                         return false;
1190                 }
1191
1192                 $this->comment_feed_structure = $this->root . $this->comments_base . '/' . $this->feed_base . '/%feed%';
1193
1194                 return $this->comment_feed_structure;
1195         }
1196
1197         /**
1198          * Add or update existing rewrite tags (e.g. %postname%).
1199          *
1200          * If the tag already exists, replace the existing pattern and query for
1201          * that tag, otherwise add the new tag.
1202          *
1203          * @see WP_Rewrite::$rewritecode
1204          * @see WP_Rewrite::$rewritereplace
1205          * @see WP_Rewrite::$queryreplace
1206          * @since 1.5.0
1207          * @access public
1208          *
1209          * @param string $tag Name of the rewrite tag to add or update.
1210          * @param string $regex Regular expression to substitute the tag for in rewrite rules.
1211          * @param string $query String to append to the rewritten query. Must end in '='.
1212          */
1213         function add_rewrite_tag( $tag, $regex, $query ) {
1214                 $position = array_search( $tag, $this->rewritecode );
1215                 if ( false !== $position && null !== $position ) {
1216                         $this->rewritereplace[ $position ] = $regex;
1217                         $this->queryreplace[ $position ] = $query;
1218                 } else {
1219                         $this->rewritecode[] = $tag;
1220                         $this->rewritereplace[] = $regex;
1221                         $this->queryreplace[] = $query;
1222                 }
1223         }
1224
1225         /**
1226          * Generate rewrite rules from a permalink structure.
1227          *
1228          * The main WP_Rewrite function for building the rewrite rule list. The
1229          * contents of the function is a mix of black magic and regular expressions,
1230          * so best just ignore the contents and move to the parameters.
1231          *
1232          * @since 1.5.0
1233          * @access public
1234          *
1235          * @param string $permalink_structure The permalink structure.
1236          * @param int $ep_mask Endpoint mask defining what endpoints are added to the structure. Default is EP_NONE.
1237          * @param bool $paged Should archive pagination rules be added for the structure? Default is true.
1238          * @param bool $feed Should feed rewrite rules be added for the structure? Default is true.
1239          * @param bool $forcomments Should the feed rules be a query for a comments feed? Default is false.
1240          * @param bool $walk_dirs Should the 'directories' making up the structure be walked over and rewrite rules
1241          *                        built for each in turn? Default is true.
1242          * @param bool $endpoints Should endpoints be applied to the generated rewrite rules? Default is true.
1243          * @return array Rewrite rule list.
1244          */
1245         function generate_rewrite_rules($permalink_structure, $ep_mask = EP_NONE, $paged = true, $feed = true, $forcomments = false, $walk_dirs = true, $endpoints = true) {
1246                 //build a regex to match the feed section of URLs, something like (feed|atom|rss|rss2)/?
1247                 $feedregex2 = '';
1248                 foreach ( (array) $this->feeds as $feed_name)
1249                         $feedregex2 .= $feed_name . '|';
1250                 $feedregex2 = '(' . trim($feedregex2, '|') . ')/?$';
1251
1252                 //$feedregex is identical but with /feed/ added on as well, so URLs like <permalink>/feed/atom
1253                 //and <permalink>/atom are both possible
1254                 $feedregex = $this->feed_base . '/' . $feedregex2;
1255
1256                 //build a regex to match the trackback and page/xx parts of URLs
1257                 $trackbackregex = 'trackback/?$';
1258                 $pageregex = $this->pagination_base . '/?([0-9]{1,})/?$';
1259                 $commentregex = 'comment-page-([0-9]{1,})/?$';
1260
1261                 //build up an array of endpoint regexes to append => queries to append
1262                 if ( $endpoints ) {
1263                         $ep_query_append = array ();
1264                         foreach ( (array) $this->endpoints as $endpoint) {
1265                                 //match everything after the endpoint name, but allow for nothing to appear there
1266                                 $epmatch = $endpoint[1] . '(/(.*))?/?$';
1267                                 //this will be appended on to the rest of the query for each dir
1268                                 $epquery = '&' . $endpoint[1] . '=';
1269                                 $ep_query_append[$epmatch] = array ( $endpoint[0], $epquery );
1270                         }
1271                 }
1272
1273                 //get everything up to the first rewrite tag
1274                 $front = substr($permalink_structure, 0, strpos($permalink_structure, '%'));
1275                 //build an array of the tags (note that said array ends up being in $tokens[0])
1276                 preg_match_all('/%.+?%/', $permalink_structure, $tokens);
1277
1278                 $num_tokens = count($tokens[0]);
1279
1280                 $index = $this->index; //probably 'index.php'
1281                 $feedindex = $index;
1282                 $trackbackindex = $index;
1283                 //build a list from the rewritecode and queryreplace arrays, that will look something like
1284                 //tagname=$matches[i] where i is the current $i
1285                 for ( $i = 0; $i < $num_tokens; ++$i ) {
1286                         if ( 0 < $i )
1287                                 $queries[$i] = $queries[$i - 1] . '&';
1288                         else
1289                                 $queries[$i] = '';
1290
1291                         $query_token = str_replace($this->rewritecode, $this->queryreplace, $tokens[0][$i]) . $this->preg_index($i+1);
1292                         $queries[$i] .= $query_token;
1293                 }
1294
1295                 //get the structure, minus any cruft (stuff that isn't tags) at the front
1296                 $structure = $permalink_structure;
1297                 if ( $front != '/' )
1298                         $structure = str_replace($front, '', $structure);
1299
1300                 //create a list of dirs to walk over, making rewrite rules for each level
1301                 //so for example, a $structure of /%year%/%monthnum%/%postname% would create
1302                 //rewrite rules for /%year%/, /%year%/%monthnum%/ and /%year%/%monthnum%/%postname%
1303                 $structure = trim($structure, '/');
1304                 $dirs = $walk_dirs ? explode('/', $structure) : array( $structure );
1305                 $num_dirs = count($dirs);
1306
1307                 //strip slashes from the front of $front
1308                 $front = preg_replace('|^/+|', '', $front);
1309
1310                 //the main workhorse loop
1311                 $post_rewrite = array();
1312                 $struct = $front;
1313                 for ( $j = 0; $j < $num_dirs; ++$j ) {
1314                         //get the struct for this dir, and trim slashes off the front
1315                         $struct .= $dirs[$j] . '/'; //accumulate. see comment near explode('/', $structure) above
1316                         $struct = ltrim($struct, '/');
1317
1318                         //replace tags with regexes
1319                         $match = str_replace($this->rewritecode, $this->rewritereplace, $struct);
1320
1321                         //make a list of tags, and store how many there are in $num_toks
1322                         $num_toks = preg_match_all('/%.+?%/', $struct, $toks);
1323
1324                         //get the 'tagname=$matches[i]'
1325                         $query = ( isset($queries) && is_array($queries) && !empty($num_toks) ) ? $queries[$num_toks - 1] : '';
1326
1327                         //set up $ep_mask_specific which is used to match more specific URL types
1328                         switch ( $dirs[$j] ) {
1329                                 case '%year%':
1330                                         $ep_mask_specific = EP_YEAR;
1331                                         break;
1332                                 case '%monthnum%':
1333                                         $ep_mask_specific = EP_MONTH;
1334                                         break;
1335                                 case '%day%':
1336                                         $ep_mask_specific = EP_DAY;
1337                                         break;
1338                                 default:
1339                                         $ep_mask_specific = EP_NONE;
1340                         }
1341
1342                         //create query for /page/xx
1343                         $pagematch = $match . $pageregex;
1344                         $pagequery = $index . '?' . $query . '&paged=' . $this->preg_index($num_toks + 1);
1345
1346                         //create query for /comment-page-xx
1347                         $commentmatch = $match . $commentregex;
1348                         $commentquery = $index . '?' . $query . '&cpage=' . $this->preg_index($num_toks + 1);
1349
1350                         if ( get_option('page_on_front') ) {
1351                                 //create query for Root /comment-page-xx
1352                                 $rootcommentmatch = $match . $commentregex;
1353                                 $rootcommentquery = $index . '?' . $query . '&page_id=' . get_option('page_on_front') . '&cpage=' . $this->preg_index($num_toks + 1);
1354                         }
1355
1356                         //create query for /feed/(feed|atom|rss|rss2|rdf)
1357                         $feedmatch = $match . $feedregex;
1358                         $feedquery = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1);
1359
1360                         //create query for /(feed|atom|rss|rss2|rdf) (see comment near creation of $feedregex)
1361                         $feedmatch2 = $match . $feedregex2;
1362                         $feedquery2 = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1);
1363
1364                         //if asked to, turn the feed queries into comment feed ones
1365                         if ( $forcomments ) {
1366                                 $feedquery .= '&withcomments=1';
1367                                 $feedquery2 .= '&withcomments=1';
1368                         }
1369
1370                         //start creating the array of rewrites for this dir
1371                         $rewrite = array();
1372                         if ( $feed ) //...adding on /feed/ regexes => queries
1373                                 $rewrite = array($feedmatch => $feedquery, $feedmatch2 => $feedquery2);
1374                         if ( $paged ) //...and /page/xx ones
1375                                 $rewrite = array_merge($rewrite, array($pagematch => $pagequery));
1376
1377                         //only on pages with comments add ../comment-page-xx/
1378                         if ( EP_PAGES & $ep_mask || EP_PERMALINK & $ep_mask )
1379                                 $rewrite = array_merge($rewrite, array($commentmatch => $commentquery));
1380                         else if ( EP_ROOT & $ep_mask && get_option('page_on_front') )
1381                                 $rewrite = array_merge($rewrite, array($rootcommentmatch => $rootcommentquery));
1382
1383                         //do endpoints
1384                         if ( $endpoints ) {
1385                                 foreach ( (array) $ep_query_append as $regex => $ep) {
1386                                         //add the endpoints on if the mask fits
1387                                         if ( $ep[0] & $ep_mask || $ep[0] & $ep_mask_specific )
1388                                                 $rewrite[$match . $regex] = $index . '?' . $query . $ep[1] . $this->preg_index($num_toks + 2);
1389                                 }
1390                         }
1391
1392                         //if we've got some tags in this dir
1393                         if ( $num_toks ) {
1394                                 $post = false;
1395                                 $page = false;
1396
1397                                 //check to see if this dir is permalink-level: i.e. the structure specifies an
1398                                 //individual post. Do this by checking it contains at least one of 1) post name,
1399                                 //2) post ID, 3) page name, 4) timestamp (year, month, day, hour, second and
1400                                 //minute all present). Set these flags now as we need them for the endpoints.
1401                                 if ( strpos($struct, '%postname%') !== false
1402                                                 || strpos($struct, '%post_id%') !== false
1403                                                 || strpos($struct, '%pagename%') !== false
1404                                                 || (strpos($struct, '%year%') !== false && strpos($struct, '%monthnum%') !== false && strpos($struct, '%day%') !== false && strpos($struct, '%hour%') !== false && strpos($struct, '%minute%') !== false && strpos($struct, '%second%') !== false)
1405                                                 ) {
1406                                         $post = true;
1407                                         if ( strpos($struct, '%pagename%') !== false )
1408                                                 $page = true;
1409                                 }
1410
1411                                 if ( ! $post ) {
1412                                         // For custom post types, we need to add on endpoints as well.
1413                                         foreach ( get_post_types( array('_builtin' => false ) ) as $ptype ) {
1414                                                 if ( strpos($struct, "%$ptype%") !== false ) {
1415                                                         $post = true;
1416                                                         $page = is_post_type_hierarchical( $ptype ); // This is for page style attachment url's
1417                                                         break;
1418                                                 }
1419                                         }
1420                                 }
1421
1422                                 //if we're creating rules for a permalink, do all the endpoints like attachments etc
1423                                 if ( $post ) {
1424                                         //create query and regex for trackback
1425                                         $trackbackmatch = $match . $trackbackregex;
1426                                         $trackbackquery = $trackbackindex . '?' . $query . '&tb=1';
1427                                         //trim slashes from the end of the regex for this dir
1428                                         $match = rtrim($match, '/');
1429                                         //get rid of brackets
1430                                         $submatchbase = str_replace( array('(', ')'), '', $match);
1431
1432                                         //add a rule for at attachments, which take the form of <permalink>/some-text
1433                                         $sub1 = $submatchbase . '/([^/]+)/';
1434                                         $sub1tb = $sub1 . $trackbackregex; //add trackback regex <permalink>/trackback/...
1435                                         $sub1feed = $sub1 . $feedregex; //and <permalink>/feed/(atom|...)
1436                                         $sub1feed2 = $sub1 . $feedregex2; //and <permalink>/(feed|atom...)
1437                                         $sub1comment = $sub1 . $commentregex; //and <permalink>/comment-page-xx
1438
1439                                         //add another rule to match attachments in the explicit form:
1440                                         //<permalink>/attachment/some-text
1441                                         $sub2 = $submatchbase . '/attachment/([^/]+)/';
1442                                         $sub2tb = $sub2 . $trackbackregex; //and add trackbacks <permalink>/attachment/trackback
1443                                         $sub2feed = $sub2 . $feedregex;    //feeds, <permalink>/attachment/feed/(atom|...)
1444                                         $sub2feed2 = $sub2 . $feedregex2;  //and feeds again on to this <permalink>/attachment/(feed|atom...)
1445                                         $sub2comment = $sub2 . $commentregex; //and <permalink>/comment-page-xx
1446
1447                                         //create queries for these extra tag-ons we've just dealt with
1448                                         $subquery = $index . '?attachment=' . $this->preg_index(1);
1449                                         $subtbquery = $subquery . '&tb=1';
1450                                         $subfeedquery = $subquery . '&feed=' . $this->preg_index(2);
1451                                         $subcommentquery = $subquery . '&cpage=' . $this->preg_index(2);
1452
1453                                         //do endpoints for attachments
1454                                         if ( !empty($endpoints) ) {
1455                                                 foreach ( (array) $ep_query_append as $regex => $ep ) {
1456                                                         if ( $ep[0] & EP_ATTACHMENT ) {
1457                                                                 $rewrite[$sub1 . $regex] = $subquery . $ep[1] . $this->preg_index(3);
1458                                                                 $rewrite[$sub2 . $regex] = $subquery . $ep[1] . $this->preg_index(3);
1459                                                         }
1460                                                 }
1461                                         }
1462
1463                                         //now we've finished with endpoints, finish off the $sub1 and $sub2 matches
1464                                         //add a ? as we don't have to match that last slash, and finally a $ so we
1465                                         //match to the end of the URL
1466                                         $sub1 .= '?$';
1467                                         $sub2 .= '?$';
1468
1469                                         //post pagination, e.g. <permalink>/2/
1470                                         $match = $match . '(/[0-9]+)?/?$';
1471                                         $query = $index . '?' . $query . '&page=' . $this->preg_index($num_toks + 1);
1472                                 } else { //not matching a permalink so this is a lot simpler
1473                                         //close the match and finalise the query
1474                                         $match .= '?$';
1475                                         $query = $index . '?' . $query;
1476                                 }
1477
1478                                 //create the final array for this dir by joining the $rewrite array (which currently
1479                                 //only contains rules/queries for trackback, pages etc) to the main regex/query for
1480                                 //this dir
1481                                 $rewrite = array_merge($rewrite, array($match => $query));
1482
1483                                 //if we're matching a permalink, add those extras (attachments etc) on
1484                                 if ( $post ) {
1485                                         //add trackback
1486                                         $rewrite = array_merge(array($trackbackmatch => $trackbackquery), $rewrite);
1487
1488                                         //add regexes/queries for attachments, attachment trackbacks and so on
1489                                         if ( ! $page ) //require <permalink>/attachment/stuff form for pages because of confusion with subpages
1490                                                 $rewrite = array_merge($rewrite, array($sub1 => $subquery, $sub1tb => $subtbquery, $sub1feed => $subfeedquery, $sub1feed2 => $subfeedquery, $sub1comment => $subcommentquery));
1491                                         $rewrite = array_merge(array($sub2 => $subquery, $sub2tb => $subtbquery, $sub2feed => $subfeedquery, $sub2feed2 => $subfeedquery, $sub2comment => $subcommentquery), $rewrite);
1492                                 }
1493                         } //if($num_toks)
1494                         //add the rules for this dir to the accumulating $post_rewrite
1495                         $post_rewrite = array_merge($rewrite, $post_rewrite);
1496                 } //foreach ($dir)
1497                 return $post_rewrite; //the finished rules. phew!
1498         }
1499
1500         /**
1501          * Generate Rewrite rules with permalink structure and walking directory only.
1502          *
1503          * Shorten version of {@link WP_Rewrite::generate_rewrite_rules()} that
1504          * allows for shorter list of parameters. See the method for longer
1505          * description of what generating rewrite rules does.
1506          *
1507          * @uses WP_Rewrite::generate_rewrite_rules() See for long description and rest of parameters.
1508          * @since 1.5.0
1509          * @access public
1510          *
1511          * @param string $permalink_structure The permalink structure to generate rules.
1512          * @param bool $walk_dirs Optional, default is false. Whether to create list of directories to walk over.
1513          * @return array
1514          */
1515         function generate_rewrite_rule($permalink_structure, $walk_dirs = false) {
1516                 return $this->generate_rewrite_rules($permalink_structure, EP_NONE, false, false, false, $walk_dirs);
1517         }
1518
1519         /**
1520          * Construct rewrite matches and queries from permalink structure.
1521          *
1522          * Runs the action 'generate_rewrite_rules' with the parameter that is an
1523          * reference to the current WP_Rewrite instance to further manipulate the
1524          * permalink structures and rewrite rules. Runs the 'rewrite_rules_array'
1525          * filter on the full rewrite rule array.
1526          *
1527          * There are two ways to manipulate the rewrite rules, one by hooking into
1528          * the 'generate_rewrite_rules' action and gaining full control of the
1529          * object or just manipulating the rewrite rule array before it is passed
1530          * from the function.
1531          *
1532          * @since 1.5.0
1533          * @access public
1534          *
1535          * @return array An associate array of matches and queries.
1536          */
1537         function rewrite_rules() {
1538                 $rewrite = array();
1539
1540                 if ( empty($this->permalink_structure) )
1541                         return $rewrite;
1542
1543                 // robots.txt -only if installed at the root
1544                 $home_path = parse_url( home_url() );
1545                 $robots_rewrite = ( empty( $home_path['path'] ) || '/' == $home_path['path'] ) ? array( 'robots\.txt$' => $this->index . '?robots=1' ) : array();
1546
1547                 // Old feed and service files
1548                 $deprecated_files = array(
1549                         '.*wp-(atom|rdf|rss|rss2|feed|commentsrss2)\.php$' => $this->index . '?feed=old',
1550                         '.*wp-app\.php(/.*)?$' => $this->index . '?error=403',
1551                 );
1552
1553                 // Registration rules
1554                 $registration_pages = array();
1555                 if ( is_multisite() && is_main_site() ) {
1556                         $registration_pages['.*wp-signup.php$'] = $this->index . '?signup=true';
1557                         $registration_pages['.*wp-activate.php$'] = $this->index . '?activate=true';
1558                 }
1559                 $registration_pages['.*wp-register.php$'] = $this->index . '?register=true'; // Deprecated
1560
1561                 // Post
1562                 $post_rewrite = $this->generate_rewrite_rules( $this->permalink_structure, EP_PERMALINK );
1563                 $post_rewrite = apply_filters('post_rewrite_rules', $post_rewrite);
1564
1565                 // Date
1566                 $date_rewrite = $this->generate_rewrite_rules($this->get_date_permastruct(), EP_DATE);
1567                 $date_rewrite = apply_filters('date_rewrite_rules', $date_rewrite);
1568
1569                 // Root
1570                 $root_rewrite = $this->generate_rewrite_rules($this->root . '/', EP_ROOT);
1571                 $root_rewrite = apply_filters('root_rewrite_rules', $root_rewrite);
1572
1573                 // Comments
1574                 $comments_rewrite = $this->generate_rewrite_rules($this->root . $this->comments_base, EP_COMMENTS, false, true, true, false);
1575                 $comments_rewrite = apply_filters('comments_rewrite_rules', $comments_rewrite);
1576
1577                 // Search
1578                 $search_structure = $this->get_search_permastruct();
1579                 $search_rewrite = $this->generate_rewrite_rules($search_structure, EP_SEARCH);
1580                 $search_rewrite = apply_filters('search_rewrite_rules', $search_rewrite);
1581
1582                 // Authors
1583                 $author_rewrite = $this->generate_rewrite_rules($this->get_author_permastruct(), EP_AUTHORS);
1584                 $author_rewrite = apply_filters('author_rewrite_rules', $author_rewrite);
1585
1586                 // Pages
1587                 $page_rewrite = $this->page_rewrite_rules();
1588                 $page_rewrite = apply_filters('page_rewrite_rules', $page_rewrite);
1589
1590                 // Extra permastructs
1591                 foreach ( $this->extra_permastructs as $permastructname => $struct ) {
1592                         if ( is_array( $struct ) ) {
1593                                 if ( count( $struct ) == 2 )
1594                                         $rules = $this->generate_rewrite_rules( $struct[0], $struct[1] );
1595                                 else
1596                                         $rules = $this->generate_rewrite_rules( $struct['struct'], $struct['ep_mask'], $struct['paged'], $struct['feed'], $struct['forcomments'], $struct['walk_dirs'], $struct['endpoints'] );
1597                         } else {
1598                                 $rules = $this->generate_rewrite_rules( $struct );
1599                         }
1600
1601                         $rules = apply_filters($permastructname . '_rewrite_rules', $rules);
1602                         if ( 'post_tag' == $permastructname )
1603                                 $rules = apply_filters('tag_rewrite_rules', $rules);
1604
1605                         $this->extra_rules_top = array_merge($this->extra_rules_top, $rules);
1606                 }
1607
1608                 // Put them together.
1609                 if ( $this->use_verbose_page_rules )
1610                         $this->rules = array_merge($this->extra_rules_top, $robots_rewrite, $deprecated_files, $registration_pages, $root_rewrite, $comments_rewrite, $search_rewrite,  $author_rewrite, $date_rewrite, $page_rewrite, $post_rewrite, $this->extra_rules);
1611                 else
1612                         $this->rules = array_merge($this->extra_rules_top, $robots_rewrite, $deprecated_files, $registration_pages, $root_rewrite, $comments_rewrite, $search_rewrite,  $author_rewrite, $date_rewrite, $post_rewrite, $page_rewrite, $this->extra_rules);
1613
1614                 do_action_ref_array('generate_rewrite_rules', array(&$this));
1615                 $this->rules = apply_filters('rewrite_rules_array', $this->rules);
1616
1617                 return $this->rules;
1618         }
1619
1620         /**
1621          * Retrieve the rewrite rules.
1622          *
1623          * The difference between this method and {@link
1624          * WP_Rewrite::rewrite_rules()} is that this method stores the rewrite rules
1625          * in the 'rewrite_rules' option and retrieves it. This prevents having to
1626          * process all of the permalinks to get the rewrite rules in the form of
1627          * caching.
1628          *
1629          * @since 1.5.0
1630          * @access public
1631          *
1632          * @return array Rewrite rules.
1633          */
1634         function wp_rewrite_rules() {
1635                 $this->rules = get_option('rewrite_rules');
1636                 if ( empty($this->rules) ) {
1637                         $this->matches = 'matches';
1638                         $this->rewrite_rules();
1639                         update_option('rewrite_rules', $this->rules);
1640                 }
1641
1642                 return $this->rules;
1643         }
1644
1645         /**
1646          * Retrieve mod_rewrite formatted rewrite rules to write to .htaccess.
1647          *
1648          * Does not actually write to the .htaccess file, but creates the rules for
1649          * the process that will.
1650          *
1651          * Will add the non_wp_rules property rules to the .htaccess file before
1652          * the WordPress rewrite rules one.
1653          *
1654          * @since 1.5.0
1655          * @access public
1656          *
1657          * @return string
1658          */
1659         function mod_rewrite_rules() {
1660                 if ( ! $this->using_permalinks() )
1661                         return '';
1662
1663                 $site_root = parse_url( site_url() );
1664                 if ( isset( $site_root['path'] ) )
1665                         $site_root = trailingslashit($site_root['path']);
1666
1667                 $home_root = parse_url(home_url());
1668                 if ( isset( $home_root['path'] ) )
1669                         $home_root = trailingslashit($home_root['path']);
1670                 else
1671                         $home_root = '/';
1672
1673                 $rules = "<IfModule mod_rewrite.c>\n";
1674                 $rules .= "RewriteEngine On\n";
1675                 $rules .= "RewriteBase $home_root\n";
1676                 $rules .= "RewriteRule ^index\.php$ - [L]\n"; // Prevent -f checks on index.php.
1677
1678                 //add in the rules that don't redirect to WP's index.php (and thus shouldn't be handled by WP at all)
1679                 foreach ( (array) $this->non_wp_rules as $match => $query) {
1680                         // Apache 1.3 does not support the reluctant (non-greedy) modifier.
1681                         $match = str_replace('.+?', '.+', $match);
1682
1683                         // If the match is unanchored and greedy, prepend rewrite conditions
1684                         // to avoid infinite redirects and eclipsing of real files.
1685                         //if ($match == '(.+)/?$' || $match == '([^/]+)/?$' ) {
1686                                 //nada.
1687                         //}
1688
1689                         $rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n";
1690                 }
1691
1692                 if ( $this->use_verbose_rules ) {
1693                         $this->matches = '';
1694                         $rewrite = $this->rewrite_rules();
1695                         $num_rules = count($rewrite);
1696                         $rules .= "RewriteCond %{REQUEST_FILENAME} -f [OR]\n" .
1697                                 "RewriteCond %{REQUEST_FILENAME} -d\n" .
1698                                 "RewriteRule ^.*$ - [S=$num_rules]\n";
1699
1700                         foreach ( (array) $rewrite as $match => $query) {
1701                                 // Apache 1.3 does not support the reluctant (non-greedy) modifier.
1702                                 $match = str_replace('.+?', '.+', $match);
1703
1704                                 // If the match is unanchored and greedy, prepend rewrite conditions
1705                                 // to avoid infinite redirects and eclipsing of real files.
1706                                 //if ($match == '(.+)/?$' || $match == '([^/]+)/?$' ) {
1707                                         //nada.
1708                                 //}
1709
1710                                 if ( strpos($query, $this->index) !== false )
1711                                         $rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n";
1712                                 else
1713                                         $rules .= 'RewriteRule ^' . $match . ' ' . $site_root . $query . " [QSA,L]\n";
1714                         }
1715                 } else {
1716                         $rules .= "RewriteCond %{REQUEST_FILENAME} !-f\n" .
1717                                 "RewriteCond %{REQUEST_FILENAME} !-d\n" .
1718                                 "RewriteRule . {$home_root}{$this->index} [L]\n";
1719                 }
1720
1721                 $rules .= "</IfModule>\n";
1722
1723                 $rules = apply_filters('mod_rewrite_rules', $rules);
1724                 $rules = apply_filters('rewrite_rules', $rules);  // Deprecated
1725
1726                 return $rules;
1727         }
1728
1729         /**
1730          * Retrieve IIS7 URL Rewrite formatted rewrite rules to write to web.config file.
1731          *
1732          * Does not actually write to the web.config file, but creates the rules for
1733          * the process that will.
1734          *
1735          * @since 2.8.0
1736          * @access public
1737          *
1738          * @return string
1739          */
1740         function iis7_url_rewrite_rules( $add_parent_tags = false ) {
1741
1742                 if ( ! $this->using_permalinks() )
1743                         return '';
1744                 $rules = '';
1745                 if ( $add_parent_tags ) {
1746                         $rules .= '<configuration>
1747         <system.webServer>
1748                 <rewrite>
1749                         <rules>';
1750                 }
1751
1752                 $rules .= '
1753                         <rule name="wordpress" patternSyntax="Wildcard">
1754                                 <match url="*" />
1755                                         <conditions>
1756                                                 <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
1757                                                 <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
1758                                         </conditions>
1759                                 <action type="Rewrite" url="index.php" />
1760                         </rule>';
1761
1762                 if ( $add_parent_tags ) {
1763                         $rules .= '
1764                         </rules>
1765                 </rewrite>
1766         </system.webServer>
1767 </configuration>';
1768                 }
1769
1770                 $rules = apply_filters('iis7_url_rewrite_rules', $rules);
1771
1772                 return $rules;
1773         }
1774
1775         /**
1776          * Add a straight rewrite rule.
1777          *
1778          * Any value in the $after parameter that isn't 'bottom' will be placed at
1779          * the top of the rules.
1780          *
1781          * @since 2.1.0
1782          * @access public
1783          *
1784          * @param string $regex Regular expression to match against request.
1785          * @param string $redirect URL regex redirects to when regex matches request.
1786          * @param string $after Optional, default is bottom. Location to place rule.
1787          */
1788         function add_rule($regex, $redirect, $after = 'bottom') {
1789                 //get everything up to the first ?
1790                 $index = (strpos($redirect, '?') == false ? strlen($redirect) : strpos($redirect, '?'));
1791                 $front = substr($redirect, 0, $index);
1792                 if ( $front != $this->index ) { //it doesn't redirect to WP's index.php
1793                         $this->add_external_rule($regex, $redirect);
1794                 } else {
1795                         if ( 'bottom' == $after)
1796                                 $this->extra_rules = array_merge($this->extra_rules, array($regex => $redirect));
1797                         else
1798                                 $this->extra_rules_top = array_merge($this->extra_rules_top, array($regex => $redirect));
1799                         //$this->extra_rules[$regex] = $redirect;
1800                 }
1801         }
1802
1803         /**
1804          * Add a rule that doesn't redirect to index.php.
1805          *
1806          * Can redirect to any place.
1807          *
1808          * @since 2.1.0
1809          * @access public
1810          *
1811          * @param string $regex Regular expression to match against request.
1812          * @param string $redirect URL regex redirects to when regex matches request.
1813          */
1814         function add_external_rule($regex, $redirect) {
1815                 $this->non_wp_rules[$regex] = $redirect;
1816         }
1817
1818         /**
1819          * Add an endpoint, like /trackback/.
1820          *
1821          * See {@link add_rewrite_endpoint()} for full documentation.
1822          *
1823          * @see add_rewrite_endpoint()
1824          * @since 2.1.0
1825          * @access public
1826          * @uses WP::add_query_var()
1827          *
1828          * @param string $name Name of the endpoint.
1829          * @param int $places Endpoint mask describing the places the endpoint should be added.
1830          */
1831         function add_endpoint($name, $places) {
1832                 global $wp;
1833                 $this->endpoints[] = array ( $places, $name );
1834                 $wp->add_query_var($name);
1835         }
1836
1837         /**
1838          * Add a new permalink structure.
1839          *
1840          * A permalink structure (permastruct) is an abstract definition of a set of rewrite rules; it
1841          * is an easy way of expressing a set of regular expressions that rewrite to a set of query strings.
1842          * The new permastruct is added to the {@link WP_Rewrite::$extra_permastructs} array. When the
1843          * rewrite rules are built by {@link WP_Rewrite::rewrite_rules()} all of these extra permastructs
1844          * are passed to {@link WP_Rewrite::generate_rewrite_rules()} which transforms them into the
1845          * regular expressions that many love to hate.
1846          *
1847          * The $args parameter gives you control over how {@link WP_Rewrite::generate_rewrite_rules()}
1848          * works on the new permastruct.
1849          *
1850          * @since 2.5.0
1851          * @access public
1852          *
1853          * @param string $name Name for permalink structure.
1854          * @param string $struct Permalink structure (e.g. category/%category%)
1855          * @param array $args Optional configuration for building the rules from the permalink structure:
1856          *     - with_front (bool) - Should the structure be prepended with WP_Rewrite::$front? Default is true.
1857          *     - ep_mask (int) - Endpoint mask defining what endpoints are added to the structure. Default is EP_NONE.
1858          *     - paged (bool) - Should archive pagination rules be added for the structure? Default is true.
1859          *     - feed (bool) - Should feed rewrite rules be added for the structure? Default is true.
1860          *     - forcomments (bool) - Should the feed rules be a query for a comments feed? Default is false.
1861          *     - walk_dirs (bool) - Should the 'directories' making up the structure be walked over and rewrite
1862          *                          rules built for each in turn? Default is true.
1863          *     - endpoints (bool) - Should endpoints be applied to the generated rewrite rules? Default is true.
1864          */
1865         function add_permastruct( $name, $struct, $args = array() ) {
1866                 // backwards compatibility for the old parameters: $with_front and $ep_mask
1867                 if ( ! is_array( $args ) )
1868                         $args = array( 'with_front' => $args );
1869                 if ( func_num_args() == 4 )
1870                         $args['ep_mask'] = func_get_arg( 3 );
1871
1872                 $defaults = array(
1873                         'with_front' => true,
1874                         'ep_mask' => EP_NONE,
1875                         'paged' => true,
1876                         'feed' => true,
1877                         'forcomments' => false,
1878                         'walk_dirs' => true,
1879                         'endpoints' => true,
1880                 );
1881                 $args = array_intersect_key( $args, $defaults );
1882                 $args = wp_parse_args( $args, $defaults );
1883
1884                 if ( $args['with_front'] )
1885                         $struct = $this->front . $struct;
1886                 else
1887                         $struct = $this->root . $struct;
1888                 $args['struct'] = $struct;
1889
1890                 $this->extra_permastructs[ $name ] = $args;
1891         }
1892
1893         /**
1894          * Remove rewrite rules and then recreate rewrite rules.
1895          *
1896          * Calls {@link WP_Rewrite::wp_rewrite_rules()} after removing the
1897          * 'rewrite_rules' option. If the function named 'save_mod_rewrite_rules'
1898          * exists, it will be called.
1899          *
1900          * @since 2.0.1
1901          * @access public
1902          * @param bool $hard Whether to update .htaccess (hard flush) or just update rewrite_rules option (soft flush). Default is true (hard).
1903          */
1904         function flush_rules($hard = true) {
1905                 delete_option('rewrite_rules');
1906                 $this->wp_rewrite_rules();
1907                 /**
1908                  * Filter whether a "hard" rewrite rule flush should be performed when requested.
1909                  *
1910                  * A "hard" flush updates .htaccess (Apache) or web.config (IIS).
1911                  *
1912                  * @since 3.7.0
1913                  * @param bool $hard Defaults to true.
1914                  */
1915                 if ( ! $hard || ! apply_filters( 'flush_rewrite_rules_hard', true ) )
1916                         return;
1917                 if ( function_exists( 'save_mod_rewrite_rules' ) )
1918                         save_mod_rewrite_rules();
1919                 if ( function_exists( 'iis7_save_url_rewrite_rules' ) )
1920                         iis7_save_url_rewrite_rules();
1921         }
1922
1923         /**
1924          * Sets up the object's properties.
1925          *
1926          * The 'use_verbose_page_rules' object property will be set to true if the
1927          * permalink structure begins with one of the following: '%postname%', '%category%',
1928          * '%tag%', or '%author%'.
1929          *
1930          * @since 1.5.0
1931          * @access public
1932          */
1933         function init() {
1934                 $this->extra_rules = $this->non_wp_rules = $this->endpoints = array();
1935                 $this->permalink_structure = get_option('permalink_structure');
1936                 $this->front = substr($this->permalink_structure, 0, strpos($this->permalink_structure, '%'));
1937                 $this->root = '';
1938                 if ( $this->using_index_permalinks() )
1939                         $this->root = $this->index . '/';
1940                 unset($this->author_structure);
1941                 unset($this->date_structure);
1942                 unset($this->page_structure);
1943                 unset($this->search_structure);
1944                 unset($this->feed_structure);
1945                 unset($this->comment_feed_structure);
1946                 $this->use_trailing_slashes = ( '/' == substr($this->permalink_structure, -1, 1) );
1947
1948                 // Enable generic rules for pages if permalink structure doesn't begin with a wildcard.
1949                 if ( preg_match("/^[^%]*%(?:postname|category|tag|author)%/", $this->permalink_structure) )
1950                          $this->use_verbose_page_rules = true;
1951                 else
1952                         $this->use_verbose_page_rules = false;
1953         }
1954
1955         /**
1956          * Set the main permalink structure for the blog.
1957          *
1958          * Will update the 'permalink_structure' option, if there is a difference
1959          * between the current permalink structure and the parameter value. Calls
1960          * {@link WP_Rewrite::init()} after the option is updated.
1961          *
1962          * Fires the 'permalink_structure_changed' action once the init call has
1963          * processed passing the old and new values
1964          *
1965          * @since 1.5.0
1966          * @access public
1967          *
1968          * @param string $permalink_structure Permalink structure.
1969          */
1970         function set_permalink_structure($permalink_structure) {
1971                 if ( $permalink_structure != $this->permalink_structure ) {
1972                         $old_permalink_structure = $this->permalink_structure;
1973                         update_option('permalink_structure', $permalink_structure);
1974                         $this->init();
1975                         do_action('permalink_structure_changed', $old_permalink_structure, $permalink_structure);
1976                 }
1977         }
1978
1979         /**
1980          * Set the category base for the category permalink.
1981          *
1982          * Will update the 'category_base' option, if there is a difference between
1983          * the current category base and the parameter value. Calls
1984          * {@link WP_Rewrite::init()} after the option is updated.
1985          *
1986          * @since 1.5.0
1987          * @access public
1988          *
1989          * @param string $category_base Category permalink structure base.
1990          */
1991         function set_category_base($category_base) {
1992                 if ( $category_base != get_option('category_base') ) {
1993                         update_option('category_base', $category_base);
1994                         $this->init();
1995                 }
1996         }
1997
1998         /**
1999          * Set the tag base for the tag permalink.
2000          *
2001          * Will update the 'tag_base' option, if there is a difference between the
2002          * current tag base and the parameter value. Calls
2003          * {@link WP_Rewrite::init()} after the option is updated.
2004          *
2005          * @since 2.3.0
2006          * @access public
2007          *
2008          * @param string $tag_base Tag permalink structure base.
2009          */
2010         function set_tag_base( $tag_base ) {
2011                 if ( $tag_base != get_option( 'tag_base') ) {
2012                         update_option( 'tag_base', $tag_base );
2013                         $this->init();
2014                 }
2015         }
2016
2017         /**
2018          * Constructor - Calls init(), which runs setup.
2019          *
2020          * @since 1.5.0
2021          * @access public
2022          *
2023          * @return WP_Rewrite
2024          */
2025         function __construct() {
2026                 $this->init();
2027         }
2028 }