You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

1955 lines
59 KiB

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