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