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