[ Index ]

WordPress Source Cross Reference

title

Body

[close]

/wp-includes/ -> rewrite.php (source)

   1  <?php
   2  
   3  /* WP_Rewrite API
   4  *******************************************************************************/
   5  
   6  //Add a straight rewrite rule
   7  function add_rewrite_rule($regex, $redirect) {
   8      global $wp_rewrite;
   9      $wp_rewrite->add_rule($regex, $redirect);
  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_AUTHORS',    1024);
  50  define('EP_PAGES',      2048);
  51  //pseudo-places
  52  define('EP_NONE',       0  );
  53  define('EP_ALL',        255);
  54  
  55  //and an endpoint, like /trackback/
  56  function add_rewrite_endpoint($name, $places) {
  57      global $wp_rewrite;
  58      $wp_rewrite->add_endpoint($name, $places);
  59  }
  60  
  61  // examine a url (supposedly from this blog) and try to
  62  // determine the post ID it represents.
  63  function url_to_postid($url) {
  64      global $wp_rewrite;
  65  
  66      // First, check to see if there is a 'p=N' or 'page_id=N' to match against
  67      preg_match('#[?&](p|page_id)=(\d+)#', $url, $values);
  68      $id = intval($values[2]);
  69      if ( $id ) return $id;
  70  
  71      // Check to see if we are using rewrite rules
  72      $rewrite = $wp_rewrite->wp_rewrite_rules();
  73  
  74      // Not using rewrite rules, and 'p=N' and 'page_id=N' methods failed, so we're out of options
  75      if ( empty($rewrite) )
  76          return 0;
  77  
  78      // $url cleanup by Mark Jaquith
  79      // This fixes things like #anchors, ?query=strings, missing 'www.',
  80      // added 'www.', or added 'index.php/' that will mess up our WP_Query
  81      // and return a false negative
  82  
  83      // Get rid of the #anchor
  84      $url_split = explode('#', $url);
  85      $url = $url_split[0];
  86  
  87      // Get rid of URI ?query=string
  88      $url_split = explode('?', $url);
  89      $url = $url_split[0];
  90  
  91      // Add 'www.' if it is absent and should be there
  92      if ( false !== strpos(get_settings('home'), '://www.') && false === strpos($url, '://www.') )
  93          $url = str_replace('://', '://www.', $url);
  94  
  95      // Strip 'www.' if it is present and shouldn't be
  96      if ( false === strpos(get_settings('home'), '://www.') )
  97          $url = str_replace('://www.', '://', $url);
  98  
  99      // Strip 'index.php/' if we're not using path info permalinks
 100      if ( false === strpos($rewrite, 'index.php/') )
 101          $url = str_replace('index.php/', '', $url);
 102  
 103      if ( false !== strpos($url, get_settings('home')) ) {
 104          // Chop off http://domain.com
 105          $url = str_replace(get_settings('home'), '', $url);
 106      } else {
 107          // Chop off /path/to/blog
 108          $home_path = parse_url(get_settings('home'));
 109          $home_path = $home_path['path'];
 110          $url = str_replace($home_path, '', $url);
 111      }
 112  
 113      // Trim leading and lagging slashes
 114      $url = trim($url, '/');
 115  
 116      $request = $url;
 117  
 118      // Done with cleanup
 119  
 120      // Look for matches.
 121      $request_match = $request;
 122      foreach ($rewrite as $match => $query) {
 123          // If the requesting file is the anchor of the match, prepend it
 124          // to the path info.
 125          if ( (! empty($url)) && (strpos($match, $url) === 0) ) {
 126              $request_match = $url . '/' . $request;
 127          }
 128  
 129          if ( preg_match("!^$match!", $request_match, $matches) ) {
 130              // Got a match.
 131              // Trim the query of everything up to the '?'.
 132              $query = preg_replace("!^.+\?!", '', $query);
 133  
 134              // Substitute the substring matches into the query.
 135              eval("\$query = \"$query\";");
 136              $query = new WP_Query($query);
 137              if ( $query->is_single || $query->is_page )
 138                  return $query->post->ID;
 139              else
 140                  return 0;
 141          }
 142      }
 143      return 0;
 144  }
 145  
 146  /* WP_Rewrite class
 147  *******************************************************************************/
 148  
 149  class WP_Rewrite {
 150      var $permalink_structure;
 151      var $category_base;
 152      var $category_structure;
 153      var $author_base = 'author';
 154      var $author_structure;
 155      var $date_structure;
 156      var $page_structure;
 157      var $search_base = 'search';
 158      var $search_structure;
 159      var $comments_base = 'comments';
 160      var $feed_base = 'feed';
 161      var $comments_feed_structure;
 162      var $feed_structure;
 163      var $front;
 164      var $root = '';
 165      var $index = 'index.php';
 166      var $matches = '';
 167      var $rules;
 168      var $extra_rules; //those not generated by the class, see add_rewrite_rule()
 169      var $non_wp_rules; //rules that don't redirect to WP's index.php
 170      var $endpoints;
 171      var $use_verbose_rules = false;
 172      var $rewritecode = 
 173          array(
 174                      '%year%',
 175                      '%monthnum%',
 176                      '%day%',
 177                      '%hour%',
 178                      '%minute%',
 179                      '%second%',
 180                      '%postname%',
 181                      '%post_id%',
 182                      '%category%',
 183                      '%author%',
 184                      '%pagename%',
 185                      '%search%'
 186                      );
 187  
 188      var $rewritereplace = 
 189          array(
 190                      '([0-9]{4})',
 191                      '([0-9]{1,2})',
 192                      '([0-9]{1,2})',
 193                      '([0-9]{1,2})',
 194                      '([0-9]{1,2})',
 195                      '([0-9]{1,2})',
 196                      '([^/]+)',
 197                      '([0-9]+)',
 198                      '(.+?)',
 199                      '([^/]+)',
 200                      '([^/]+)',
 201                      '(.+)'
 202                      );
 203  
 204      var $queryreplace = 
 205          array (
 206                      'year=',
 207                      'monthnum=',
 208                      'day=',
 209                      'hour=',
 210                      'minute=',
 211                      'second=',
 212                      'name=',
 213                      'p=',
 214                      'category_name=',
 215                      'author_name=',
 216                      'pagename=',
 217                      's='
 218                      );
 219  
 220      var $feeds = array ( 'feed', 'rdf', 'rss', 'rss2', 'atom' );
 221      
 222  	function using_permalinks() {
 223          if (empty($this->permalink_structure))
 224              return false;
 225          else
 226              return true;
 227      }
 228  
 229  	function using_index_permalinks() {
 230          if (empty($this->permalink_structure)) {
 231              return false;
 232          }
 233  
 234          // If the index is not in the permalink, we're using mod_rewrite.
 235          if (preg_match('#^/*' . $this->index . '#', $this->permalink_structure)) {
 236              return true;
 237          }
 238      
 239          return false;
 240      }
 241  
 242      function using_mod_rewrite_permalinks() {
 243          if ( $this->using_permalinks() && ! $this->using_index_permalinks())
 244              return true;
 245          else
 246              return false;
 247      }
 248  
 249      function preg_index($number) {
 250          $match_prefix = '$';
 251          $match_suffix = '';
 252  
 253          if (! empty($this->matches)) {
 254              $match_prefix = '$' . $this->matches . '['; 
 255              $match_suffix = ']';
 256          }        
 257  
 258          return "$match_prefix$number$match_suffix";        
 259      }
 260  
 261      function page_rewrite_rules() {
 262          $uris = get_settings('page_uris');
 263          $attachment_uris = get_settings('page_attachment_uris');
 264  
 265          $rewrite_rules = array();
 266          $page_structure = $this->get_page_permastruct();
 267          if( is_array( $attachment_uris ) ) {
 268              foreach ($attachment_uris as $uri => $pagename) {
 269                  $this->add_rewrite_tag('%pagename%', "($uri)", 'attachment=');
 270                  $rewrite_rules = array_merge($rewrite_rules, $this->generate_rewrite_rules($page_structure, EP_PAGES));
 271              }
 272          }
 273          if( is_array( $uris ) ) {
 274              foreach ($uris as $uri => $pagename) {
 275                  $this->add_rewrite_tag('%pagename%', "($uri)", 'pagename=');
 276                  $rewrite_rules = array_merge($rewrite_rules, $this->generate_rewrite_rules($page_structure, EP_PAGES));
 277              }
 278          }
 279  
 280          return $rewrite_rules;
 281      }
 282  
 283      function get_date_permastruct() {
 284          if (isset($this->date_structure)) {
 285              return $this->date_structure;
 286          }
 287  
 288          if (empty($this->permalink_structure)) {
 289              $this->date_structure = '';
 290              return false;
 291          }
 292  
 293          // The date permalink must have year, month, and day separated by slashes.
 294          $endians = array('%year%/%monthnum%/%day%', '%day%/%monthnum%/%year%', '%monthnum%/%day%/%year%');
 295  
 296          $this->date_structure = '';
 297          $date_endian = '';
 298  
 299          foreach ($endians as $endian) {
 300              if (false !== strpos($this->permalink_structure, $endian)) {
 301                  $date_endian= $endian;
 302                  break;
 303              }
 304          } 
 305  
 306          if ( empty($date_endian) )
 307              $date_endian = '%year%/%monthnum%/%day%';
 308  
 309          // Do not allow the date tags and %post_id% to overlap in the permalink
 310          // structure. If they do, move the date tags to $front/date/.  
 311          $front = $this->front;
 312          preg_match_all('/%.+?%/', $this->permalink_structure, $tokens);
 313          $tok_index = 1;
 314          foreach ($tokens[0] as $token) {
 315              if ( ($token == '%post_id%') && ($tok_index <= 3) ) {
 316                  $front = $front . 'date/';
 317                  break;
 318              }
 319          }
 320  
 321          $this->date_structure = $front . $date_endian;
 322  
 323          return $this->date_structure;
 324      }
 325  
 326      function get_year_permastruct() {
 327          $structure = $this->get_date_permastruct($this->permalink_structure);
 328  
 329          if (empty($structure)) {
 330              return false;
 331          }
 332  
 333          $structure = str_replace('%monthnum%', '', $structure);
 334          $structure = str_replace('%day%', '', $structure);
 335  
 336          $structure = preg_replace('#/+#', '/', $structure);
 337  
 338          return $structure;
 339      }
 340  
 341      function get_month_permastruct() {
 342          $structure = $this->get_date_permastruct($this->permalink_structure);
 343  
 344          if (empty($structure)) {
 345              return false;
 346          }
 347  
 348          $structure = str_replace('%day%', '', $structure);
 349  
 350          $structure = preg_replace('#/+#', '/', $structure);
 351  
 352          return $structure;
 353      }
 354  
 355      function get_day_permastruct() {
 356          return $this->get_date_permastruct($this->permalink_structure);
 357      }
 358  
 359      function get_category_permastruct() {
 360          if (isset($this->category_structure)) {
 361              return $this->category_structure;
 362          }
 363  
 364          if (empty($this->permalink_structure)) {
 365              $this->category_structure = '';
 366              return false;
 367          }
 368  
 369          if (empty($this->category_base))
 370              $this->category_structure = $this->front . 'category/';
 371          else
 372              $this->category_structure = $this->category_base . '/';
 373  
 374          $this->category_structure .= '%category%';
 375  
 376          return $this->category_structure;
 377      }
 378  
 379      function get_author_permastruct() {
 380          if (isset($this->author_structure)) {
 381              return $this->author_structure;
 382          }
 383  
 384          if (empty($this->permalink_structure)) {
 385              $this->author_structure = '';
 386              return false;
 387          }
 388  
 389          $this->author_structure = $this->front . $this->author_base . '/%author%';
 390  
 391          return $this->author_structure;
 392      }
 393  
 394      function get_search_permastruct() {
 395          if (isset($this->search_structure)) {
 396              return $this->search_structure;
 397          }
 398  
 399          if (empty($this->permalink_structure)) {
 400              $this->search_structure = '';
 401              return false;
 402          }
 403  
 404          $this->search_structure = $this->root . $this->search_base . '/%search%';
 405  
 406          return $this->search_structure;
 407      }
 408  
 409      function get_page_permastruct() {
 410          if (isset($this->page_structure)) {
 411              return $this->page_structure;
 412          }
 413  
 414          if (empty($this->permalink_structure)) {
 415              $this->page_structure = '';
 416              return false;
 417          }
 418  
 419          $this->page_structure = $this->root . '%pagename%';
 420  
 421          return $this->page_structure;
 422      }
 423  
 424      function get_feed_permastruct() {
 425          if (isset($this->feed_structure)) {
 426              return $this->feed_structure;
 427          }
 428  
 429          if (empty($this->permalink_structure)) {
 430              $this->feed_structure = '';
 431              return false;
 432          }
 433  
 434          $this->feed_structure = $this->root . $this->feed_base . '/%feed%';
 435  
 436          return $this->feed_structure;
 437      }
 438  
 439      function get_comment_feed_permastruct() {
 440          if (isset($this->comment_feed_structure)) {
 441              return $this->comment_feed_structure;
 442          }
 443  
 444          if (empty($this->permalink_structure)) {
 445              $this->comment_feed_structure = '';
 446              return false;
 447          }
 448  
 449          $this->comment_feed_structure = $this->root . $this->comments_base . '/' . $this->feed_base . '/%feed%';
 450  
 451          return $this->comment_feed_structure;
 452      }
 453  
 454      function add_rewrite_tag($tag, $pattern, $query) {
 455          // If the tag already exists, replace the existing pattern and query for
 456          // that tag, otherwise add the new tag, pattern, and query to the end of
 457          // the arrays.
 458          $position = array_search($tag, $this->rewritecode);
 459          if (FALSE !== $position && NULL !== $position) {
 460              $this->rewritereplace[$position] = $pattern;
 461              $this->queryreplace[$position] = $query;
 462          } else {
 463              $this->rewritecode[] = $tag;
 464              $this->rewritereplace[] = $pattern;
 465              $this->queryreplace[] = $query;
 466          }
 467      }
 468  
 469      //the main WP_Rewrite function. generate the rules from permalink structure
 470      function generate_rewrite_rules($permalink_structure, $ep_mask = EP_NONE, $paged = true, $feed = true, $forcomments = false, $walk_dirs = true, $endpoints = true) {
 471          //build a regex to match the feed section of URLs, something like (feed|atom|rss|rss2)/?
 472          $feedregex2 = '';
 473          foreach ($this->feeds as $feed_name) {
 474              $feedregex2 .= $feed_name . '|';
 475          }
 476          $feedregex2 = '(' . trim($feedregex2, '|') .  ')/?$';
 477          //$feedregex is identical but with /feed/ added on as well, so URLs like <permalink>/feed/atom
 478          //and <permalink>/atom are both possible
 479          $feedregex = $this->feed_base  . '/' . $feedregex2;
 480  
 481          //build a regex to match the trackback and page/xx parts of URLs
 482          $trackbackregex = 'trackback/?$';
 483          $pageregex = 'page/?([0-9]{1,})/?$';
 484          
 485          //build up an array of endpoint regexes to append => queries to append
 486          if ($endpoints) {
 487              $ep_query_append = array ();
 488              foreach ($this->endpoints as $endpoint) { 
 489                  //match everything after the endpoint name, but allow for nothing to appear there
 490                  $epmatch = $endpoint[1] . '(/(.*))?/?$';
 491                  //this will be appended on to the rest of the query for each dir
 492                  $epquery = '&' . $endpoint[1] . '=';
 493                  $ep_query_append[$epmatch] = array ( $endpoint[0], $epquery );
 494              }
 495          }
 496  
 497          //get everything up to the first rewrite tag
 498          $front = substr($permalink_structure, 0, strpos($permalink_structure, '%'));
 499          //build an array of the tags (note that said array ends up being in $tokens[0])
 500          preg_match_all('/%.+?%/', $permalink_structure, $tokens);
 501  
 502          $num_tokens = count($tokens[0]);
 503  
 504          $index = $this->index; //probably 'index.php'
 505          $feedindex = $index;
 506          $trackbackindex = $index;
 507          //build a list from the rewritecode and queryreplace arrays, that will look something like
 508          //tagname=$matches[i] where i is the current $i
 509          for ($i = 0; $i < $num_tokens; ++$i) {
 510              if (0 < $i) {
 511                  $queries[$i] = $queries[$i - 1] . '&';
 512              }
 513               
 514              $query_token = str_replace($this->rewritecode, $this->queryreplace, $tokens[0][$i]) . $this->preg_index($i+1);
 515              $queries[$i] .= $query_token;
 516          }
 517  
 518          //get the structure, minus any cruft (stuff that isn't tags) at the front
 519          $structure = $permalink_structure;
 520          if ($front != '/') {
 521              $structure = str_replace($front, '', $structure);
 522          }
 523          //create a list of dirs to walk over, making rewrite rules for each level
 524          //so for example, a $structure of /%year%/%month%/%postname% would create
 525          //rewrite rules for /%year%/, /%year%/%month%/ and /%year%/%month%/%postname%
 526          $structure = trim($structure, '/');
 527          if ($walk_dirs) {
 528              $dirs = explode('/', $structure);
 529          } else {
 530              $dirs[] = $structure;
 531          }
 532          $num_dirs = count($dirs);
 533  
 534          //strip slashes from the front of $front
 535          $front = preg_replace('|^/+|', '', $front);
 536  
 537          //the main workhorse loop
 538          $post_rewrite = array();
 539          $struct = $front;
 540          for ($j = 0; $j < $num_dirs; ++$j) {
 541              //get the struct for this dir, and trim slashes off the front
 542              $struct .= $dirs[$j] . '/'; //accumulate. see comment near explode('/', $structure) above
 543              $struct = ltrim($struct, '/');
 544              //replace tags with regexes
 545              $match = str_replace($this->rewritecode, $this->rewritereplace, $struct);
 546              //make a list of tags, and store how many there are in $num_toks
 547              $num_toks = preg_match_all('/%.+?%/', $struct, $toks);
 548              //get the 'tagname=$matches[i]'
 549              $query = $queries[$num_toks - 1];
 550              
 551              //set up $ep_mask_specific which is used to match more specific URL types
 552              switch ($dirs[$j]) {
 553                  case '%year%': $ep_mask_specific = EP_YEAR; break;
 554                  case '%monthnum%': $ep_mask_specific = EP_MONTH; break;
 555                  case '%day%': $ep_mask_specific = EP_DAY; break;
 556              }
 557  
 558              //create query for /page/xx
 559              $pagematch = $match . $pageregex;
 560              $pagequery = $index . '?' . $query . '&paged=' . $this->preg_index($num_toks + 1);
 561  
 562              //create query for /feed/(feed|atom|rss|rss2|rdf)
 563              $feedmatch = $match . $feedregex;
 564              $feedquery = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1);
 565  
 566              //create query for /(feed|atom|rss|rss2|rdf) (see comment near creation of $feedregex)
 567              $feedmatch2 = $match . $feedregex2;
 568              $feedquery2 = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1);
 569  
 570              //if asked to, turn the feed queries into comment feed ones
 571              if ($forcomments) {
 572                  $feedquery .= '&withcomments=1';
 573                  $feedquery2 .= '&withcomments=1';
 574              }
 575  
 576              //start creating the array of rewrites for this dir
 577              $rewrite = array();
 578              if ($feed) //...adding on /feed/ regexes => queries
 579                  $rewrite = array($feedmatch => $feedquery, $feedmatch2 => $feedquery2);
 580              if ($paged) //...and /page/xx ones
 581                  $rewrite = array_merge($rewrite, array($pagematch => $pagequery));
 582              
 583              //if we've got some tags in this dir
 584              if ($num_toks) {
 585                  $post = false;
 586                  $page = false;
 587                  
 588                  //check to see if this dir is permalink-level: i.e. the structure specifies an 
 589                  //individual post. Do this by checking it contains at least one of 1) post name,
 590                  //2) post ID, 3) page name, 4) timestamp (year, month, day, hour, second and 
 591                  //minute all present). Set these flags now as we need them for the endpoints.
 592                  if (strstr($struct, '%postname%') || strstr($struct, '%post_id%')
 593                          || strstr($struct, '%pagename%')
 594                          || (strstr($struct, '%year%') &&  strstr($struct, '%monthnum%') && strstr($struct, '%day%') && strstr($struct, '%hour%') && strstr($struct, '%minute') && strstr($struct, '%second%'))) {
 595                      $post = true;
 596                      if  ( strstr($struct, '%pagename%') )
 597                          $page = true;
 598                  }
 599                  
 600                  //do endpoints
 601                  if ($endpoints) {
 602                      foreach ($ep_query_append as $regex => $ep) {
 603                          //add the endpoints on if the mask fits
 604                          if ($ep[0] & $ep_mask || $ep[0] & $ep_mask_specific) {
 605                              $rewrite[$match . $regex] = $index . '?' . $query . $ep[1] . $this->preg_index($num_toks + 2);
 606                          }
 607                      }
 608                  }
 609                  
 610                  //if we're creating rules for a permalink, do all the endpoints like attachments etc
 611                  if ($post) {
 612                      $post = true;
 613                      //create query and regex for trackback
 614                      $trackbackmatch = $match . $trackbackregex;
 615                      $trackbackquery = $trackbackindex . '?' . $query . '&tb=1';
 616                      //trim slashes from the end of the regex for this dir
 617                      $match = rtrim($match, '/');
 618                      //get rid of brackets
 619                      $submatchbase = str_replace(array('(',')'),'',$match);
 620                      
 621                      //add a rule for at attachments, which take the form of <permalink>/some-text
 622                      $sub1 = $submatchbase . '/([^/]+)/';
 623                      $sub1tb = $sub1 . $trackbackregex; //add trackback regex <permalink>/trackback/...
 624                      $sub1feed = $sub1 . $feedregex; //and <permalink>/feed/(atom|...)
 625                      $sub1feed2 = $sub1 . $feedregex2; //and <permalink>/(feed|atom...)
 626                      //add an ? as we don't have to match that last slash, and finally a $ so we
 627                      //match to the end of the URL
 628                      
 629                      //add another rule to match attachments in the explicit form:
 630                      //<permalink>/attachment/some-text
 631                      $sub2 = $submatchbase . '/attachment/([^/]+)/';
 632                      $sub2tb = $sub2 . $trackbackregex; //and add trackbacks <permalink>/attachment/trackback
 633                      $sub2feed = $sub2 . $feedregex;    //feeds, <permalink>/attachment/feed/(atom|...)
 634                      $sub2feed2 = $sub2 . $feedregex2;  //and feeds again on to this <permalink>/attachment/(feed|atom...)
 635                      
 636                      //create queries for these extra tag-ons we've just dealt with
 637                      $subquery = $index . '?attachment=' . $this->preg_index(1);
 638                      $subtbquery = $subquery . '&tb=1';
 639                      $subfeedquery = $subquery . '&feed=' . $this->preg_index(2);
 640                      
 641                      //do endpoints for attachments
 642                      if ($endpoint) { foreach ($ep_query_append as $regex => $ep) {
 643                          if ($ep[0] & EP_ATTACHMENT) {
 644                              $rewrite[$sub1 . $regex] = $subquery . '?' . $ep[1] . $this->preg_index(2);
 645                              $rewrite[$sub2 . $regex] = $subquery . '?' . $ep[1] . $this->preg_index(2);
 646                          }
 647                      } }
 648                      
 649                      //now we've finished with endpoints, finish off the $sub1 and $sub2 matches
 650                      $sub1 .= '?$';
 651                      $sub2 .= '?$';
 652                      
 653                      //allow URLs like <permalink>/2 for <permalink>/page/2
 654                      $match = $match . '(/[0-9]+)?/?$';
 655                      $query = $index . '?' . $query . '&page=' . $this->preg_index($num_toks + 1);
 656                  } else { //not matching a permalink so this is a lot simpler
 657                      //close the match and finalise the query
 658                      $match .= '?$';
 659                      $query = $index . '?' . $query;
 660                  }
 661                  
 662                  //create the final array for this dir by joining the $rewrite array (which currently
 663                  //only contains rules/queries for trackback, pages etc) to the main regex/query for
 664                  //this dir
 665                  $rewrite = array_merge($rewrite, array($match => $query));
 666  
 667                  //if we're matching a permalink, add those extras (attachments etc) on
 668                  if ($post) {
 669                      //add trackback
 670                      $rewrite = array_merge(array($trackbackmatch => $trackbackquery), $rewrite);
 671                      
 672                      //add regexes/queries for attachments, attachment trackbacks and so on
 673                      if ( ! $page ) //require <permalink>/attachment/stuff form for pages because of confusion with subpages
 674                          $rewrite = array_merge($rewrite, array($sub1 => $subquery, $sub1tb => $subtbquery, $sub1feed => $subfeedquery, $sub1feed2 => $subfeedquery));
 675                      $rewrite = array_merge($rewrite, array($sub2 => $subquery, $sub2tb => $subtbquery, $sub2feed => $subfeedquery, $sub2feed2 => $subfeedquery));
 676                  }
 677              } //if($num_toks)
 678              //add the rules for this dir to the accumulating $post_rewrite
 679              $post_rewrite = array_merge($rewrite, $post_rewrite);
 680          } //foreach ($dir)
 681          return $post_rewrite; //the finished rules. phew!
 682      }
 683  
 684      function generate_rewrite_rule($permalink_structure, $walk_dirs = false) {
 685          return $this->generate_rewrite_rules($permalink_structure, EP_NONE, false, false, false, $walk_dirs);
 686      }
 687  
 688      /* rewrite_rules
 689       * Construct rewrite matches and queries from permalink structure.
 690       * Returns an associate array of matches and queries.
 691       */
 692  	function rewrite_rules() {
 693          $rewrite = array();
 694  
 695          if (empty($this->permalink_structure)) {
 696              return $rewrite;
 697          }
 698  
 699          // robots.txt
 700          $robots_rewrite = array('robots.txt$' => $this->index . '?robots=1');
 701  
 702          // Post
 703          $post_rewrite = $this->generate_rewrite_rules($this->permalink_structure, EP_PERMALINK);
 704          $post_rewrite = apply_filters('post_rewrite_rules', $post_rewrite);
 705  
 706          // Date
 707          $date_rewrite = $this->generate_rewrite_rules($this->get_date_permastruct(), EP_DATE);
 708          $date_rewrite = apply_filters('date_rewrite_rules', $date_rewrite);
 709  
 710          // Root
 711          $root_rewrite = $this->generate_rewrite_rules($this->root . '/', EP_ROOT);
 712          $root_rewrite = apply_filters('root_rewrite_rules', $root_rewrite);
 713  
 714          // Comments
 715          $comments_rewrite = $this->generate_rewrite_rules($this->root . $this->comments_base, EP_COMMENTS, true, true, true, false);
 716          $comments_rewrite = apply_filters('comments_rewrite_rules', $comments_rewrite);
 717  
 718          // Search
 719          $search_structure = $this->get_search_permastruct();
 720          $search_rewrite = $this->generate_rewrite_rules($search_structure, EP_SEARCH);
 721          $search_rewrite = apply_filters('search_rewrite_rules', $search_rewrite);
 722  
 723          // Categories
 724          $category_rewrite = $this->generate_rewrite_rules($this->get_category_permastruct(), EP_CATEGORIES);
 725          $category_rewrite = apply_filters('category_rewrite_rules', $category_rewrite);
 726  
 727          // Authors
 728          $author_rewrite = $this->generate_rewrite_rules($this->get_author_permastruct(), EP_AUTHORS);
 729          $author_rewrite = apply_filters('author_rewrite_rules', $author_rewrite);
 730  
 731          // Pages
 732          $page_rewrite = $this->page_rewrite_rules();
 733          $page_rewrite = apply_filters('page_rewrite_rules', $page_rewrite);
 734  
 735          // Put them together.
 736          $this->rules = array_merge($robots_rewrite, $page_rewrite,