]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/rewrite.php
Wordpress 2.3.2-scripts
[autoinstalls/wordpress.git] / wp-includes / rewrite.php
1 <?php
2
3 /* WP_Rewrite API
4 *******************************************************************************/
5
6 //Add a straight rewrite rule
7 function add_rewrite_rule($regex, $redirect, $after = 'bottom') {
8         global $wp_rewrite;
9         $wp_rewrite->add_rule($regex, $redirect, $after);
10 }
11
12 //Add a new tag (like %postname%)
13 //warning: you must call this on init or earlier, otherwise the query var addition stuff won't work
14 function add_rewrite_tag($tagname, $regex) {
15         //validation
16         if (strlen($tagname) < 3 || $tagname{0} != '%' || $tagname{strlen($tagname)-1} != '%') {
17                 return;
18         }
19
20         $qv = trim($tagname, '%');
21
22         global $wp_rewrite, $wp;
23         $wp->add_query_var($qv);
24         $wp_rewrite->add_rewrite_tag($tagname, $regex, $qv . '=');
25 }
26
27 //Add a new feed type like /atom1/
28 function add_feed($feedname, $function) {
29         global $wp_rewrite;
30         if (!in_array($feedname, $wp_rewrite->feeds)) { //override the file if it is
31                 $wp_rewrite->feeds[] = $feedname;
32         }
33         $hook = 'do_feed_' . $feedname;
34         remove_action($hook, $function, 10, 1);
35         add_action($hook, $function, 10, 1);
36         return $hook;
37 }
38
39 define('EP_PERMALINK',  1   );
40 define('EP_ATTACHMENT', 2   );
41 define('EP_DATE',       4   );
42 define('EP_YEAR',       8   );
43 define('EP_MONTH',      16  );
44 define('EP_DAY',        32  );
45 define('EP_ROOT',       64  );
46 define('EP_COMMENTS',   128 );
47 define('EP_SEARCH',     256 );
48 define('EP_CATEGORIES', 512 );
49 define('EP_TAGS', 1024 );
50 define('EP_AUTHORS',    2048);
51 define('EP_PAGES',      4096);
52 //pseudo-places
53 define('EP_NONE',       0  );
54 define('EP_ALL',        8191);
55
56 //and an endpoint, like /trackback/
57 function add_rewrite_endpoint($name, $places) {
58         global $wp_rewrite;
59         $wp_rewrite->add_endpoint($name, $places);
60 }
61
62 // examine a url (supposedly from this blog) and try to
63 // determine the post ID it represents.
64 function url_to_postid($url) {
65         global $wp_rewrite;
66
67         $url = apply_filters('url_to_postid', $url);
68
69         // First, check to see if there is a 'p=N' or 'page_id=N' to match against
70         preg_match('#[?&](p|page_id)=(\d+)#', $url, $values);
71         $id = intval($values[2]);
72         if ( $id ) return $id;
73
74         // Check to see if we are using rewrite rules
75         $rewrite = $wp_rewrite->wp_rewrite_rules();
76
77         // Not using rewrite rules, and 'p=N' and 'page_id=N' methods failed, so we're out of options
78         if ( empty($rewrite) )
79                 return 0;
80
81         // $url cleanup by Mark Jaquith
82         // This fixes things like #anchors, ?query=strings, missing 'www.',
83         // added 'www.', or added 'index.php/' that will mess up our WP_Query
84         // and return a false negative
85
86         // Get rid of the #anchor
87         $url_split = explode('#', $url);
88         $url = $url_split[0];
89
90         // Get rid of URL ?query=string
91         $url_split = explode('?', $url);
92         $url = $url_split[0];
93
94         // Add 'www.' if it is absent and should be there
95         if ( false !== strpos(get_option('home'), '://www.') && false === strpos($url, '://www.') )
96                 $url = str_replace('://', '://www.', $url);
97
98         // Strip 'www.' if it is present and shouldn't be
99         if ( false === strpos(get_option('home'), '://www.') )
100                 $url = str_replace('://www.', '://', $url);
101
102         // Strip 'index.php/' if we're not using path info permalinks
103         if ( !$wp_rewrite->using_index_permalinks() )
104                 $url = str_replace('index.php/', '', $url);
105
106         if ( false !== strpos($url, get_option('home')) ) {
107                 // Chop off http://domain.com
108                 $url = str_replace(get_option('home'), '', $url);
109         } else {
110                 // Chop off /path/to/blog
111                 $home_path = parse_url(get_option('home'));
112                 $home_path = $home_path['path'];
113                 $url = str_replace($home_path, '', $url);
114         }
115
116         // Trim leading and lagging slashes
117         $url = trim($url, '/');
118
119         $request = $url;
120
121         // Done with cleanup
122
123         // Look for matches.
124         $request_match = $request;
125         foreach ($rewrite as $match => $query) {
126                 // If the requesting file is the anchor of the match, prepend it
127                 // to the path info.
128                 if ( (! empty($url)) && (strpos($match, $url) === 0) ) {
129                         $request_match = $url . '/' . $request;
130                 }
131
132                 if ( preg_match("!^$match!", $request_match, $matches) ) {
133                         // Got a match.
134                         // Trim the query of everything up to the '?'.
135                         $query = preg_replace("!^.+\?!", '', $query);
136
137                         // Substitute the substring matches into the query.
138                         eval("\$query = \"$query\";");
139                         // Filter out non-public query vars
140                         global $wp;
141                         parse_str($query, $query_vars);
142                         $query = array();
143                         foreach ( $query_vars as $key => $value ) {
144                                 if ( in_array($key, $wp->public_query_vars) )
145                                         $query[$key] = $value;
146                         }
147                         // Do the query
148                         $query = new WP_Query($query);
149                         if ( $query->is_single || $query->is_page )
150                                 return $query->post->ID;
151                         else
152                                 return 0;
153                 }
154         }
155         return 0;
156 }
157
158 /* WP_Rewrite class
159 *******************************************************************************/
160
161 class WP_Rewrite {
162         var $permalink_structure;
163         var $use_trailing_slashes;
164         var $category_base;
165         var $tag_base;
166         var $category_structure;
167         var $tag_structure;
168         var $author_base = 'author';
169         var $author_structure;
170         var $date_structure;
171         var $page_structure;
172         var $search_base = 'search';
173         var $search_structure;
174         var $comments_base = 'comments';
175         var $feed_base = 'feed';
176         var $comments_feed_structure;
177         var $feed_structure;
178         var $front;
179         var $root = '';
180         var $index = 'index.php';
181         var $matches = '';
182         var $rules;
183         var $extra_rules = array(); //those not generated by the class, see add_rewrite_rule()
184         var $extra_rules_top = array(); //those not generated by the class, see add_rewrite_rule()
185         var $non_wp_rules = array(); //rules that don't redirect to WP's index.php
186         var $endpoints;
187         var $use_verbose_rules = false;
188         var $rewritecode =
189                 array(
190                                         '%year%',
191                                         '%monthnum%',
192                                         '%day%',
193                                         '%hour%',
194                                         '%minute%',
195                                         '%second%',
196                                         '%postname%',
197                                         '%post_id%',
198                                         '%category%',
199                                         '%tag%',
200                                         '%author%',
201                                         '%pagename%',
202                                         '%search%'
203                                         );
204
205         var $rewritereplace =
206                 array(
207                                         '([0-9]{4})',
208                                         '([0-9]{1,2})',
209                                         '([0-9]{1,2})',
210                                         '([0-9]{1,2})',
211                                         '([0-9]{1,2})',
212                                         '([0-9]{1,2})',
213                                         '([^/]+)',
214                                         '([0-9]+)',
215                                         '(.+?)',
216                                         '(.+?)',
217                                         '([^/]+)',
218                                         '([^/]+)',
219                                         '(.+)'
220                                         );
221
222         var $queryreplace =
223                 array (
224                                         'year=',
225                                         'monthnum=',
226                                         'day=',
227                                         'hour=',
228                                         'minute=',
229                                         'second=',
230                                         'name=',
231                                         'p=',
232                                         'category_name=',
233                                         'tag=',
234                                         'author_name=',
235                                         'pagename=',
236                                         's='
237                                         );
238
239         var $feeds = array ( 'feed', 'rdf', 'rss', 'rss2', 'atom' );
240
241         function using_permalinks() {
242                 if (empty($this->permalink_structure))
243                         return false;
244                 else
245                         return true;
246         }
247
248         function using_index_permalinks() {
249                 if (empty($this->permalink_structure)) {
250                         return false;
251                 }
252
253                 // If the index is not in the permalink, we're using mod_rewrite.
254                 if (preg_match('#^/*' . $this->index . '#', $this->permalink_structure)) {
255                         return true;
256                 }
257
258                 return false;
259         }
260
261         function using_mod_rewrite_permalinks() {
262                 if ( $this->using_permalinks() && ! $this->using_index_permalinks())
263                         return true;
264                 else
265                         return false;
266         }
267
268         function preg_index($number) {
269                 $match_prefix = '$';
270                 $match_suffix = '';
271
272                 if (! empty($this->matches)) {
273                         $match_prefix = '$' . $this->matches . '[';
274                         $match_suffix = ']';
275                 }
276
277                 return "$match_prefix$number$match_suffix";
278         }
279
280         function page_rewrite_rules() {
281                 $uris = get_option('page_uris');
282                 $attachment_uris = get_option('page_attachment_uris');
283
284                 $rewrite_rules = array();
285                 $page_structure = $this->get_page_permastruct();
286                 if( is_array( $attachment_uris ) ) {
287                         foreach ($attachment_uris as $uri => $pagename) {
288                                 $this->add_rewrite_tag('%pagename%', "($uri)", 'attachment=');
289                                 $rewrite_rules = array_merge($rewrite_rules, $this->generate_rewrite_rules($page_structure, EP_PAGES));
290                         }
291                 }
292                 if( is_array( $uris ) ) {
293                         foreach ($uris as $uri => $pagename) {
294                                 $this->add_rewrite_tag('%pagename%', "($uri)", 'pagename=');
295                                 $rewrite_rules = array_merge($rewrite_rules, $this->generate_rewrite_rules($page_structure, EP_PAGES));
296                         }
297                 }
298
299                 return $rewrite_rules;
300         }
301
302         function get_date_permastruct() {
303                 if (isset($this->date_structure)) {
304                         return $this->date_structure;
305                 }
306
307                 if (empty($this->permalink_structure)) {
308                         $this->date_structure = '';
309                         return false;
310                 }
311
312                 // The date permalink must have year, month, and day separated by slashes.
313                 $endians = array('%year%/%monthnum%/%day%', '%day%/%monthnum%/%year%', '%monthnum%/%day%/%year%');
314
315                 $this->date_structure = '';
316                 $date_endian = '';
317
318                 foreach ($endians as $endian) {
319                         if (false !== strpos($this->permalink_structure, $endian)) {
320                                 $date_endian= $endian;
321                                 break;
322                         }
323                 }
324
325                 if ( empty($date_endian) )
326                         $date_endian = '%year%/%monthnum%/%day%';
327
328                 // Do not allow the date tags and %post_id% to overlap in the permalink
329                 // structure. If they do, move the date tags to $front/date/.
330                 $front = $this->front;
331                 preg_match_all('/%.+?%/', $this->permalink_structure, $tokens);
332                 $tok_index = 1;
333                 foreach ($tokens[0] as $token) {
334                         if ( ($token == '%post_id%') && ($tok_index <= 3) ) {
335                                 $front = $front . 'date/';
336                                 break;
337                         }
338                         $tok_index++;
339                 }
340
341                 $this->date_structure = $front . $date_endian;
342
343                 return $this->date_structure;
344         }
345
346         function get_year_permastruct() {
347                 $structure = $this->get_date_permastruct($this->permalink_structure);
348
349                 if (empty($structure)) {
350                         return false;
351                 }
352
353                 $structure = str_replace('%monthnum%', '', $structure);
354                 $structure = str_replace('%day%', '', $structure);
355
356                 $structure = preg_replace('#/+#', '/', $structure);
357
358                 return $structure;
359         }
360
361         function get_month_permastruct() {
362                 $structure = $this->get_date_permastruct($this->permalink_structure);
363
364                 if (empty($structure)) {
365                         return false;
366                 }
367
368                 $structure = str_replace('%day%', '', $structure);
369
370                 $structure = preg_replace('#/+#', '/', $structure);
371
372                 return $structure;
373         }
374
375         function get_day_permastruct() {
376                 return $this->get_date_permastruct($this->permalink_structure);
377         }
378
379         function get_category_permastruct() {
380                 if (isset($this->category_structure)) {
381                         return $this->category_structure;
382                 }
383
384                 if (empty($this->permalink_structure)) {
385                         $this->category_structure = '';
386                         return false;
387                 }
388
389                 if (empty($this->category_base))
390                         $this->category_structure = $this->front . 'category/';
391                 else
392                         $this->category_structure = $this->category_base . '/';
393
394                 $this->category_structure .= '%category%';
395
396                 return $this->category_structure;
397         }
398
399         function get_tag_permastruct() {
400                 if (isset($this->tag_structure)) {
401                         return $this->tag_structure;
402                 }
403
404                 if (empty($this->permalink_structure)) {
405                         $this->tag_structure = '';
406                         return false;
407                 }
408
409                 if (empty($this->tag_base))
410                         $this->tag_structure = $this->front . 'tag/';
411                 else
412                         $this->tag_structure = $this->tag_base . '/';
413
414                 $this->tag_structure .= '%tag%';
415
416                 return $this->tag_structure;
417         }
418
419         function get_author_permastruct() {
420                 if (isset($this->author_structure)) {
421                         return $this->author_structure;
422                 }
423
424                 if (empty($this->permalink_structure)) {
425                         $this->author_structure = '';
426                         return false;
427                 }
428
429                 $this->author_structure = $this->front . $this->author_base . '/%author%';
430
431                 return $this->author_structure;
432         }
433
434         function get_search_permastruct() {
435                 if (isset($this->search_structure)) {
436                         return $this->search_structure;
437                 }
438
439                 if (empty($this->permalink_structure)) {
440                         $this->search_structure = '';
441                         return false;
442                 }
443
444                 $this->search_structure = $this->root . $this->search_base . '/%search%';
445
446                 return $this->search_structure;
447         }
448
449         function get_page_permastruct() {
450                 if (isset($this->page_structure)) {
451                         return $this->page_structure;
452                 }
453
454                 if (empty($this->permalink_structure)) {
455                         $this->page_structure = '';
456                         return false;
457                 }
458
459                 $this->page_structure = $this->root . '%pagename%';
460
461                 return $this->page_structure;
462         }
463
464         function get_feed_permastruct() {
465                 if (isset($this->feed_structure)) {
466                         return $this->feed_structure;
467                 }
468
469                 if (empty($this->permalink_structure)) {
470                         $this->feed_structure = '';
471                         return false;
472                 }
473
474                 $this->feed_structure = $this->root . $this->feed_base . '/%feed%';
475
476                 return $this->feed_structure;
477         }
478
479         function get_comment_feed_permastruct() {
480                 if (isset($this->comment_feed_structure)) {
481                         return $this->comment_feed_structure;
482                 }
483
484                 if (empty($this->permalink_structure)) {
485                         $this->comment_feed_structure = '';
486                         return false;
487                 }
488
489                 $this->comment_feed_structure = $this->root . $this->comments_base . '/' . $this->feed_base . '/%feed%';
490
491                 return $this->comment_feed_structure;
492         }
493
494         function add_rewrite_tag($tag, $pattern, $query) {
495                 // If the tag already exists, replace the existing pattern and query for
496                 // that tag, otherwise add the new tag, pattern, and query to the end of
497                 // the arrays.
498                 $position = array_search($tag, $this->rewritecode);
499                 if (FALSE !== $position && NULL !== $position) {
500                         $this->rewritereplace[$position] = $pattern;
501                         $this->queryreplace[$position] = $query;
502                 } else {
503                         $this->rewritecode[] = $tag;
504                         $this->rewritereplace[] = $pattern;
505                         $this->queryreplace[] = $query;
506                 }
507         }
508
509         //the main WP_Rewrite function. generate the rules from permalink structure
510         function generate_rewrite_rules($permalink_structure, $ep_mask = EP_NONE, $paged = true, $feed = true, $forcomments = false, $walk_dirs = true, $endpoints = true) {
511                 //build a regex to match the feed section of URLs, something like (feed|atom|rss|rss2)/?
512                 $feedregex2 = '';
513                 foreach ($this->feeds as $feed_name) {
514                         $feedregex2 .= $feed_name . '|';
515                 }
516                 $feedregex2 = '(' . trim($feedregex2, '|') .  ')/?$';
517                 //$feedregex is identical but with /feed/ added on as well, so URLs like <permalink>/feed/atom
518                 //and <permalink>/atom are both possible
519                 $feedregex = $this->feed_base  . '/' . $feedregex2;
520
521                 //build a regex to match the trackback and page/xx parts of URLs
522                 $trackbackregex = 'trackback/?$';
523                 $pageregex = 'page/?([0-9]{1,})/?$';
524
525                 //build up an array of endpoint regexes to append => queries to append
526                 if ($endpoints) {
527                         $ep_query_append = array ();
528                         foreach ($this->endpoints as $endpoint) {
529                                 //match everything after the endpoint name, but allow for nothing to appear there
530                                 $epmatch = $endpoint[1] . '(/(.*))?/?$';
531                                 //this will be appended on to the rest of the query for each dir
532                                 $epquery = '&' . $endpoint[1] . '=';
533                                 $ep_query_append[$epmatch] = array ( $endpoint[0], $epquery );
534                         }
535                 }
536
537                 //get everything up to the first rewrite tag
538                 $front = substr($permalink_structure, 0, strpos($permalink_structure, '%'));
539                 //build an array of the tags (note that said array ends up being in $tokens[0])
540                 preg_match_all('/%.+?%/', $permalink_structure, $tokens);
541
542                 $num_tokens = count($tokens[0]);
543
544                 $index = $this->index; //probably 'index.php'
545                 $feedindex = $index;
546                 $trackbackindex = $index;
547                 //build a list from the rewritecode and queryreplace arrays, that will look something like
548                 //tagname=$matches[i] where i is the current $i
549                 for ($i = 0; $i < $num_tokens; ++$i) {
550                         if (0 < $i) {
551                                 $queries[$i] = $queries[$i - 1] . '&';
552                         }
553
554                         $query_token = str_replace($this->rewritecode, $this->queryreplace, $tokens[0][$i]) . $this->preg_index($i+1);
555                         $queries[$i] .= $query_token;
556                 }
557
558                 //get the structure, minus any cruft (stuff that isn't tags) at the front
559                 $structure = $permalink_structure;
560                 if ($front != '/') {
561                         $structure = str_replace($front, '', $structure);
562                 }
563                 //create a list of dirs to walk over, making rewrite rules for each level
564                 //so for example, a $structure of /%year%/%month%/%postname% would create
565                 //rewrite rules for /%year%/, /%year%/%month%/ and /%year%/%month%/%postname%
566                 $structure = trim($structure, '/');
567                 if ($walk_dirs) {
568                         $dirs = explode('/', $structure);
569                 } else {
570                         $dirs[] = $structure;
571                 }
572                 $num_dirs = count($dirs);
573
574                 //strip slashes from the front of $front
575                 $front = preg_replace('|^/+|', '', $front);
576
577                 //the main workhorse loop
578                 $post_rewrite = array();
579                 $struct = $front;
580                 for ($j = 0; $j < $num_dirs; ++$j) {
581                         //get the struct for this dir, and trim slashes off the front
582                         $struct .= $dirs[$j] . '/'; //accumulate. see comment near explode('/', $structure) above
583                         $struct = ltrim($struct, '/');
584                         //replace tags with regexes
585                         $match = str_replace($this->rewritecode, $this->rewritereplace, $struct);
586                         //make a list of tags, and store how many there are in $num_toks
587                         $num_toks = preg_match_all('/%.+?%/', $struct, $toks);
588                         //get the 'tagname=$matches[i]'
589                         $query = $queries[$num_toks - 1];
590
591                         //set up $ep_mask_specific which is used to match more specific URL types
592                         switch ($dirs[$j]) {
593                                 case '%year%': $ep_mask_specific = EP_YEAR; break;
594                                 case '%monthnum%': $ep_mask_specific = EP_MONTH; break;
595                                 case '%day%': $ep_mask_specific = EP_DAY; break;
596                         }
597
598                         //create query for /page/xx
599                         $pagematch = $match . $pageregex;
600                         $pagequery = $index . '?' . $query . '&paged=' . $this->preg_index($num_toks + 1);
601
602                         //create query for /feed/(feed|atom|rss|rss2|rdf)
603                         $feedmatch = $match . $feedregex;
604                         $feedquery = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1);
605
606                         //create query for /(feed|atom|rss|rss2|rdf) (see comment near creation of $feedregex)
607                         $feedmatch2 = $match . $feedregex2;
608                         $feedquery2 = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1);
609
610                         //if asked to, turn the feed queries into comment feed ones
611                         if ($forcomments) {
612                                 $feedquery .= '&withcomments=1';
613                                 $feedquery2 .= '&withcomments=1';
614                         }
615
616                         //start creating the array of rewrites for this dir
617                         $rewrite = array();
618                         if ($feed) //...adding on /feed/ regexes => queries
619                                 $rewrite = array($feedmatch => $feedquery, $feedmatch2 => $feedquery2);
620                         if ($paged) //...and /page/xx ones
621                                 $rewrite = array_merge($rewrite, array($pagematch => $pagequery));
622
623                         //do endpoints
624                         if ($endpoints) {
625                                 foreach ($ep_query_append as $regex => $ep) {
626                                         //add the endpoints on if the mask fits
627                                         if ($ep[0] & $ep_mask || $ep[0] & $ep_mask_specific) {
628                                                 $rewrite[$match . $regex] = $index . '?' . $query . $ep[1] . $this->preg_index($num_toks + 2);
629                                         }
630                                 }
631                         }
632
633                         //if we've got some tags in this dir
634                         if ($num_toks) {
635                                 $post = false;
636                                 $page = false;
637
638                                 //check to see if this dir is permalink-level: i.e. the structure specifies an
639                                 //individual post. Do this by checking it contains at least one of 1) post name,
640                                 //2) post ID, 3) page name, 4) timestamp (year, month, day, hour, second and
641                                 //minute all present). Set these flags now as we need them for the endpoints.
642                                 if (strpos($struct, '%postname%') !== false || strpos($struct, '%post_id%') !== false
643                                                 || strpos($struct, '%pagename%') !== false
644                                                 || (strpos($struct, '%year%') !== false && strpos($struct, '%monthnum%') !== false && strpos($struct, '%day%') !== false && strpos($struct, '%hour%') !== false && strpos($struct, '%minute%') !== false && strpos($struct, '%second%') !== false)) {
645                                         $post = true;
646                                         if (strpos($struct, '%pagename%') !== false)
647                                                 $page = true;
648                                 }
649
650                                 //if we're creating rules for a permalink, do all the endpoints like attachments etc
651                                 if ($post) {
652                                         $post = true;
653                                         //create query and regex for trackback
654                                         $trackbackmatch = $match . $trackbackregex;
655                                         $trackbackquery = $trackbackindex . '?' . $query . '&tb=1';
656                                         //trim slashes from the end of the regex for this dir
657                                         $match = rtrim($match, '/');
658                                         //get rid of brackets
659                                         $submatchbase = str_replace(array('(',')'),'',$match);
660
661                                         //add a rule for at attachments, which take the form of <permalink>/some-text
662                                         $sub1 = $submatchbase . '/([^/]+)/';
663                                         $sub1tb = $sub1 . $trackbackregex; //add trackback regex <permalink>/trackback/...
664                                         $sub1feed = $sub1 . $feedregex; //and <permalink>/feed/(atom|...)
665                                         $sub1feed2 = $sub1 . $feedregex2; //and <permalink>/(feed|atom...)
666                                         //add an ? as we don't have to match that last slash, and finally a $ so we
667                                         //match to the end of the URL
668
669                                         //add another rule to match attachments in the explicit form:
670                                         //<permalink>/attachment/some-text
671                                         $sub2 = $submatchbase . '/attachment/([^/]+)/';
672                                         $sub2tb = $sub2 . $trackbackregex; //and add trackbacks <permalink>/attachment/trackback
673                                         $sub2feed = $sub2 . $feedregex;    //feeds, <permalink>/attachment/feed/(atom|...)
674                                         $sub2feed2 = $sub2 . $feedregex2;  //and feeds again on to this <permalink>/attachment/(feed|atom...)
675
676                                         //create queries for these extra tag-ons we've just dealt with
677                                         $subquery = $index . '?attachment=' . $this->preg_index(1);
678                                         $subtbquery = $subquery . '&tb=1';
679                                         $subfeedquery = $subquery . '&feed=' . $this->preg_index(2);
680
681                                         //do endpoints for attachments
682                                         if ($endpoint) { foreach ($ep_query_append as $regex => $ep) {
683                                                 if ($ep[0] & EP_ATTACHMENT) {
684                                                         $rewrite[$sub1 . $regex] = $subquery . '?' . $ep[1] . $this->preg_index(2);
685                                                         $rewrite[$sub2 . $regex] = $subquery . '?' . $ep[1] . $this->preg_index(2);
686                                                 }
687                                         } }
688
689                                         //now we've finished with endpoints, finish off the $sub1 and $sub2 matches
690                                         $sub1 .= '?$';
691                                         $sub2 .= '?$';
692
693                                         //allow URLs like <permalink>/2 for <permalink>/page/2
694                                         $match = $match . '(/[0-9]+)?/?$';
695                                         $query = $index . '?' . $query . '&page=' . $this->preg_index($num_toks + 1);
696                                 } else { //not matching a permalink so this is a lot simpler
697                                         //close the match and finalise the query
698                                         $match .= '?$';
699                                         $query = $index . '?' . $query;
700                                 }
701
702                                 //create the final array for this dir by joining the $rewrite array (which currently
703                                 //only contains rules/queries for trackback, pages etc) to the main regex/query for
704                                 //this dir
705                                 $rewrite = array_merge($rewrite, array($match => $query));
706
707                                 //if we're matching a permalink, add those extras (attachments etc) on
708                                 if ($post) {
709                                         //add trackback
710                                         $rewrite = array_merge(array($trackbackmatch => $trackbackquery), $rewrite);
711
712                                         //add regexes/queries for attachments, attachment trackbacks and so on
713                                         if ( ! $page ) //require <permalink>/attachment/stuff form for pages because of confusion with subpages
714                                                 $rewrite = array_merge($rewrite, array($sub1 => $subquery, $sub1tb => $subtbquery, $sub1feed => $subfeedquery, $sub1feed2 => $subfeedquery));
715                                         $rewrite = array_merge($rewrite, array($sub2 => $subquery, $sub2tb => $subtbquery, $sub2feed => $subfeedquery, $sub2feed2 => $subfeedquery));
716                                 }
717                         } //if($num_toks)
718                         //add the rules for this dir to the accumulating $post_rewrite
719                         $post_rewrite = array_merge($rewrite, $post_rewrite);
720                 } //foreach ($dir)
721                 return $post_rewrite; //the finished rules. phew!
722         }
723
724         function generate_rewrite_rule($permalink_structure, $walk_dirs = false) {
725                 return $this->generate_rewrite_rules($permalink_structure, EP_NONE, false, false, false, $walk_dirs);
726         }
727
728         /* rewrite_rules
729          * Construct rewrite matches and queries from permalink structure.
730          * Returns an associate array of matches and queries.
731          */
732         function rewrite_rules() {
733                 $rewrite = array();
734
735                 if (empty($this->permalink_structure)) {
736                         return $rewrite;
737                 }
738
739                 // robots.txt
740                 $robots_rewrite = array('robots.txt$' => $this->index . '?robots=1');
741
742                 //Default Feed rules - These are require to allow for the direct access files to work with permalink structure starting with %category%
743                 $default_feeds = array( 'wp-atom.php$'  =>      $this->index .'?feed=atom',
744                                                                 'wp-rdf.php$'   =>      $this->index .'?feed=rdf',
745                                                                 'wp-rss.php$'   =>      $this->index .'?feed=rss',
746                                                                 'wp-rss2.php$'  =>      $this->index .'?feed=rss2',
747                                                                 'wp-feed.php$'  =>      $this->index .'?feed=feed',
748                                                                 'wp-commentsrss2.php$'  =>      $this->index . '?feed=rss2&withcomments=1');
749
750                 // Post
751                 $post_rewrite = $this->generate_rewrite_rules($this->permalink_structure, EP_PERMALINK);
752                 $post_rewrite = apply_filters('post_rewrite_rules', $post_rewrite);
753
754                 // Date
755                 $date_rewrite = $this->generate_rewrite_rules($this->get_date_permastruct(), EP_DATE);
756                 $date_rewrite = apply_filters('date_rewrite_rules', $date_rewrite);
757
758                 // Root
759                 $root_rewrite = $this->generate_rewrite_rules($this->root . '/', EP_ROOT);
760                 $root_rewrite = apply_filters('root_rewrite_rules', $root_rewrite);
761
762                 // Comments
763                 $comments_rewrite = $this->generate_rewrite_rules($this->root . $this->comments_base, EP_COMMENTS, true, true, true, false);
764                 $comments_rewrite = apply_filters('comments_rewrite_rules', $comments_rewrite);
765
766                 // Search
767                 $search_structure = $this->get_search_permastruct();
768                 $search_rewrite = $this->generate_rewrite_rules($search_structure, EP_SEARCH);
769                 $search_rewrite = apply_filters('search_rewrite_rules', $search_rewrite);
770
771                 // Categories
772                 $category_rewrite = $this->generate_rewrite_rules($this->get_category_permastruct(), EP_CATEGORIES);
773                 $category_rewrite = apply_filters('category_rewrite_rules', $category_rewrite);
774
775                 // Tags
776                 $tag_rewrite = $this->generate_rewrite_rules($this->get_tag_permastruct(), EP_TAGS);
777                 $tag_rewrite = apply_filters('tag_rewrite_rules', $tag_rewrite);
778
779                 // Authors
780                 $author_rewrite = $this->generate_rewrite_rules($this->get_author_permastruct(), EP_AUTHORS);
781                 $author_rewrite = apply_filters('author_rewrite_rules', $author_rewrite);
782
783                 // Pages
784                 $page_rewrite = $this->page_rewrite_rules();
785                 $page_rewrite = apply_filters('page_rewrite_rules', $page_rewrite);
786
787                 // Put them together.
788                 $this->rules = array_merge($this->extra_rules_top, $robots_rewrite, $default_feeds, $page_rewrite, $root_rewrite, $comments_rewrite, $search_rewrite, $category_rewrite, $tag_rewrite, $author_rewrite, $date_rewrite, $post_rewrite, $this->extra_rules);
789
790                 do_action_ref_array('generate_rewrite_rules', array(&$this));
791                 $this->rules = apply_filters('rewrite_rules_array', $this->rules);
792
793                 return $this->rules;
794         }
795
796         function wp_rewrite_rules() {
797                 $this->rules = get_option('rewrite_rules');
798                 if ( empty($this->rules) ) {
799                         $this->matches = 'matches';
800                         $this->rewrite_rules();
801                         update_option('rewrite_rules', $this->rules);
802                 }
803
804                 return $this->rules;
805         }
806
807         function mod_rewrite_rules() {
808                 if ( ! $this->using_permalinks()) {
809                         return '';
810                 }
811
812                 $site_root = parse_url(get_option('siteurl'));
813                 $site_root = trailingslashit($site_root['path']);
814
815                 $home_root = parse_url(get_option('home'));
816                 $home_root = trailingslashit($home_root['path']);
817
818                 $rules = "<IfModule mod_rewrite.c>\n";
819                 $rules .= "RewriteEngine On\n";
820                 $rules .= "RewriteBase $home_root\n";
821
822                 //add in the rules that don't redirect to WP's index.php (and thus shouldn't be handled by WP at all)
823                 foreach ($this->non_wp_rules as $match => $query) {
824                         // Apache 1.3 does not support the reluctant (non-greedy) modifier.
825                         $match = str_replace('.+?', '.+', $match);
826
827                         // If the match is unanchored and greedy, prepend rewrite conditions
828                         // to avoid infinite redirects and eclipsing of real files.
829                         if ($match == '(.+)/?$' || $match == '([^/]+)/?$' ) {
830                                 //nada.
831                         }
832
833                         $rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n";
834                 }
835
836                 if ($this->use_verbose_rules) {
837                         $this->matches = '';
838                         $rewrite = $this->rewrite_rules();
839                         $num_rules = count($rewrite);
840                         $rules .= "RewriteCond %{REQUEST_FILENAME} -f [OR]\n" .
841                                 "RewriteCond %{REQUEST_FILENAME} -d\n" .
842                                 "RewriteRule ^.*$ - [S=$num_rules]\n";
843
844                         foreach ($rewrite as $match => $query) {
845                                 // Apache 1.3 does not support the reluctant (non-greedy) modifier.
846                                 $match = str_replace('.+?', '.+', $match);
847
848                                 // If the match is unanchored and greedy, prepend rewrite conditions
849                                 // to avoid infinite redirects and eclipsing of real files.
850                                 if ($match == '(.+)/?$' || $match == '([^/]+)/?$' ) {
851                                         //nada.
852                                 }
853
854                                 if (strpos($query, $this->index) !== false) {
855                                         $rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n";
856                                 } else {
857                                         $rules .= 'RewriteRule ^' . $match . ' ' . $site_root . $query . " [QSA,L]\n";
858                                 }
859                         }
860                 } else {
861                         $rules .= "RewriteCond %{REQUEST_FILENAME} !-f\n" .
862                                 "RewriteCond %{REQUEST_FILENAME} !-d\n" .
863                                 "RewriteRule . {$home_root}{$this->index} [L]\n";
864                 }
865
866                 $rules .= "</IfModule>\n";
867
868                 $rules = apply_filters('mod_rewrite_rules', $rules);
869                 $rules = apply_filters('rewrite_rules', $rules);  // Deprecated
870
871                 return $rules;
872         }
873
874         //Add a straight rewrite rule
875         function add_rule($regex, $redirect, $after = 'bottom') {
876                 //get everything up to the first ?
877                 $index = (strpos($redirect, '?') == false ? strlen($redirect) : strpos($redirect, '?'));
878                 $front = substr($redirect, 0, $index);
879                 if ($front != $this->index) { //it doesn't redirect to WP's index.php
880                         $this->add_external_rule($regex, $redirect);
881                 } else {
882                         if ( 'bottom' == $after)
883                                 $this->extra_rules = array_merge($this->extra_rules, array($regex => $redirect));
884                         else
885                                 $this->extra_rules_top = array_merge($this->extra_rules_top, array($regex => $redirect));
886                         //$this->extra_rules[$regex] = $redirect;
887                 }
888         }
889
890         //add a rule that doesn't redirect to index.php
891         function add_external_rule($regex, $redirect) {
892                 $this->non_wp_rules[$regex] = $redirect;
893         }
894
895         //add an endpoint, like /trackback/, to be inserted after certain URL types (specified in $places)
896         function add_endpoint($name, $places) {
897                 global $wp;
898                 $this->endpoints[] = array ( $places, $name );
899                 $wp->add_query_var($name);
900         }
901
902         function flush_rules() {
903                 generate_page_uri_index();
904                 delete_option('rewrite_rules');
905                 $this->wp_rewrite_rules();
906                 if ( function_exists('save_mod_rewrite_rules') )
907                         save_mod_rewrite_rules();
908         }
909
910         function init() {
911                 $this->extra_rules = $this->non_wp_rules = $this->endpoints = array();
912                 $this->permalink_structure = get_option('permalink_structure');
913                 $this->front = substr($this->permalink_structure, 0, strpos($this->permalink_structure, '%'));
914                 $this->root = '';
915                 if ($this->using_index_permalinks()) {
916                         $this->root = $this->index . '/';
917                 }
918                 $this->category_base = get_option( 'category_base' );
919                 $this->tag_base = get_option( 'tag_base' );
920                 unset($this->category_structure);
921                 unset($this->author_structure);
922                 unset($this->date_structure);
923                 unset($this->page_structure);
924                 unset($this->search_structure);
925                 unset($this->feed_structure);
926                 unset($this->comment_feed_structure);
927                 $this->use_trailing_slashes = ( substr($this->permalink_structure, -1, 1) == '/' ) ? true : false;
928         }
929
930         function set_permalink_structure($permalink_structure) {
931                 if ($permalink_structure != $this->permalink_structure) {
932                         update_option('permalink_structure', $permalink_structure);
933                         $this->init();
934                 }
935         }
936
937         function set_category_base($category_base) {
938                 if ($category_base != $this->category_base) {
939                         update_option('category_base', $category_base);
940                         $this->init();
941                 }
942         }
943
944         function set_tag_base( $tag_base ) {
945                 if ( $tag_base != $this->tag_base ) {
946                         update_option( 'tag_base', $tag_base );
947                         $this->init();
948                 }
949         }
950
951         function WP_Rewrite() {
952                 $this->init();
953         }
954 }
955
956 ?>