PageRenderTime 58ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/rewrite.php

https://bitbucket.org/aqge/deptandashboard
PHP | 1974 lines | 785 code | 227 blank | 962 comment | 142 complexity | 9200b2ed4d3ea671c27333a551ee56d1 MD5 | raw file
Possible License(s): AGPL-1.0, GPL-2.0, LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * WordPress Rewrite API
  4. *
  5. * @package WordPress
  6. * @subpackage Rewrite
  7. */
  8. /**
  9. * Add a straight rewrite rule.
  10. *
  11. * @see WP_Rewrite::add_rule() for long description.
  12. * @since 2.1.0
  13. *
  14. * @param string $regex Regular Expression to match request against.
  15. * @param string $redirect Page to redirect to.
  16. * @param string $after Optional, default is 'bottom'. Where to add rule, can also be 'top'.
  17. */
  18. function add_rewrite_rule($regex, $redirect, $after = 'bottom') {
  19. global $wp_rewrite;
  20. $wp_rewrite->add_rule($regex, $redirect, $after);
  21. }
  22. /**
  23. * Add a new tag (like %postname%).
  24. *
  25. * Warning: you must call this on init or earlier, otherwise the query var
  26. * addition stuff won't work.
  27. *
  28. * @since 2.1.0
  29. *
  30. * @param string $tagname
  31. * @param string $regex
  32. */
  33. function add_rewrite_tag($tagname, $regex) {
  34. //validation
  35. if ( strlen($tagname) < 3 || $tagname[0] != '%' || $tagname[strlen($tagname)-1] != '%' )
  36. return;
  37. $qv = trim($tagname, '%');
  38. global $wp_rewrite, $wp;
  39. $wp->add_query_var($qv);
  40. $wp_rewrite->add_rewrite_tag($tagname, $regex, $qv . '=');
  41. }
  42. /**
  43. * Add permalink structure.
  44. *
  45. * @see WP_Rewrite::add_permastruct()
  46. * @since 3.0.0
  47. *
  48. * @param string $name Name for permalink structure.
  49. * @param string $struct Permalink structure.
  50. * @param bool $with_front Prepend front base to permalink structure.
  51. */
  52. function add_permastruct( $name, $struct, $with_front = true, $ep_mask = EP_NONE ) {
  53. global $wp_rewrite;
  54. return $wp_rewrite->add_permastruct( $name, $struct, $with_front, $ep_mask );
  55. }
  56. /**
  57. * Add a new feed type like /atom1/.
  58. *
  59. * @since 2.1.0
  60. *
  61. * @param string $feedname
  62. * @param callback $function Callback to run on feed display.
  63. * @return string Feed action name.
  64. */
  65. function add_feed($feedname, $function) {
  66. global $wp_rewrite;
  67. if ( ! in_array($feedname, $wp_rewrite->feeds) ) //override the file if it is
  68. $wp_rewrite->feeds[] = $feedname;
  69. $hook = 'do_feed_' . $feedname;
  70. // Remove default function hook
  71. remove_action($hook, $hook, 10, 1);
  72. add_action($hook, $function, 10, 1);
  73. return $hook;
  74. }
  75. /**
  76. * Remove rewrite rules and then recreate rewrite rules.
  77. *
  78. * @see WP_Rewrite::flush_rules()
  79. * @since 3.0.0
  80. *
  81. * @param bool $hard Whether to update .htaccess (hard flush) or just update
  82. * rewrite_rules transient (soft flush). Default is true (hard).
  83. */
  84. function flush_rewrite_rules( $hard = true ) {
  85. global $wp_rewrite;
  86. $wp_rewrite->flush_rules( $hard );
  87. }
  88. //pseudo-places
  89. /**
  90. * Endpoint Mask for default, which is nothing.
  91. *
  92. * @since 2.1.0
  93. */
  94. define('EP_NONE', 0);
  95. /**
  96. * Endpoint Mask for Permalink.
  97. *
  98. * @since 2.1.0
  99. */
  100. define('EP_PERMALINK', 1);
  101. /**
  102. * Endpoint Mask for Attachment.
  103. *
  104. * @since 2.1.0
  105. */
  106. define('EP_ATTACHMENT', 2);
  107. /**
  108. * Endpoint Mask for date.
  109. *
  110. * @since 2.1.0
  111. */
  112. define('EP_DATE', 4);
  113. /**
  114. * Endpoint Mask for year
  115. *
  116. * @since 2.1.0
  117. */
  118. define('EP_YEAR', 8);
  119. /**
  120. * Endpoint Mask for month.
  121. *
  122. * @since 2.1.0
  123. */
  124. define('EP_MONTH', 16);
  125. /**
  126. * Endpoint Mask for day.
  127. *
  128. * @since 2.1.0
  129. */
  130. define('EP_DAY', 32);
  131. /**
  132. * Endpoint Mask for root.
  133. *
  134. * @since 2.1.0
  135. */
  136. define('EP_ROOT', 64);
  137. /**
  138. * Endpoint Mask for comments.
  139. *
  140. * @since 2.1.0
  141. */
  142. define('EP_COMMENTS', 128);
  143. /**
  144. * Endpoint Mask for searches.
  145. *
  146. * @since 2.1.0
  147. */
  148. define('EP_SEARCH', 256);
  149. /**
  150. * Endpoint Mask for categories.
  151. *
  152. * @since 2.1.0
  153. */
  154. define('EP_CATEGORIES', 512);
  155. /**
  156. * Endpoint Mask for tags.
  157. *
  158. * @since 2.3.0
  159. */
  160. define('EP_TAGS', 1024);
  161. /**
  162. * Endpoint Mask for authors.
  163. *
  164. * @since 2.1.0
  165. */
  166. define('EP_AUTHORS', 2048);
  167. /**
  168. * Endpoint Mask for pages.
  169. *
  170. * @since 2.1.0
  171. */
  172. define('EP_PAGES', 4096);
  173. /**
  174. * Endpoint Mask for everything.
  175. *
  176. * @since 2.1.0
  177. */
  178. define('EP_ALL', 8191);
  179. /**
  180. * Add an endpoint, like /trackback/.
  181. *
  182. * The endpoints are added to the end of the request. So a request matching
  183. * "/2008/10/14/my_post/myep/", the endpoint will be "/myep/".
  184. *
  185. * Be sure to flush the rewrite rules (wp_rewrite->flush_rules()) when your plugin gets
  186. * activated (register_activation_hook()) and deactivated (register_deactivation_hook())
  187. *
  188. * @since 2.1.0
  189. * @see WP_Rewrite::add_endpoint() Parameters and more description.
  190. * @uses $wp_rewrite
  191. *
  192. * @param unknown_type $name
  193. * @param unknown_type $places
  194. */
  195. function add_rewrite_endpoint($name, $places) {
  196. global $wp_rewrite;
  197. $wp_rewrite->add_endpoint($name, $places);
  198. }
  199. /**
  200. * Filter the URL base for taxonomies.
  201. *
  202. * To remove any manually prepended /index.php/.
  203. *
  204. * @access private
  205. * @since 2.6.0
  206. *
  207. * @param string $base The taxonomy base that we're going to filter
  208. * @return string
  209. */
  210. function _wp_filter_taxonomy_base( $base ) {
  211. if ( !empty( $base ) ) {
  212. $base = preg_replace( '|^/index\.php/|', '', $base );
  213. $base = trim( $base, '/' );
  214. }
  215. return $base;
  216. }
  217. /**
  218. * Examine a url and try to determine the post ID it represents.
  219. *
  220. * Checks are supposedly from the hosted site blog.
  221. *
  222. * @since 1.0.0
  223. *
  224. * @param string $url Permalink to check.
  225. * @return int Post ID, or 0 on failure.
  226. */
  227. function url_to_postid($url) {
  228. global $wp_rewrite;
  229. $url = apply_filters('url_to_postid', $url);
  230. // First, check to see if there is a 'p=N' or 'page_id=N' to match against
  231. if ( preg_match('#[?&](p|page_id|attachment_id)=(\d+)#', $url, $values) ) {
  232. $id = absint($values[2]);
  233. if ( $id )
  234. return $id;
  235. }
  236. // Check to see if we are using rewrite rules
  237. $rewrite = $wp_rewrite->wp_rewrite_rules();
  238. // Not using rewrite rules, and 'p=N' and 'page_id=N' methods failed, so we're out of options
  239. if ( empty($rewrite) )
  240. return 0;
  241. // Get rid of the #anchor
  242. $url_split = explode('#', $url);
  243. $url = $url_split[0];
  244. // Get rid of URL ?query=string
  245. $url_split = explode('?', $url);
  246. $url = $url_split[0];
  247. // Add 'www.' if it is absent and should be there
  248. if ( false !== strpos(home_url(), '://www.') && false === strpos($url, '://www.') )
  249. $url = str_replace('://', '://www.', $url);
  250. // Strip 'www.' if it is present and shouldn't be
  251. if ( false === strpos(home_url(), '://www.') )
  252. $url = str_replace('://www.', '://', $url);
  253. // Strip 'index.php/' if we're not using path info permalinks
  254. if ( !$wp_rewrite->using_index_permalinks() )
  255. $url = str_replace('index.php/', '', $url);
  256. if ( false !== strpos($url, home_url()) ) {
  257. // Chop off http://domain.com
  258. $url = str_replace(home_url(), '', $url);
  259. } else {
  260. // Chop off /path/to/blog
  261. $home_path = parse_url(home_url());
  262. $home_path = isset( $home_path['path'] ) ? $home_path['path'] : '' ;
  263. $url = str_replace($home_path, '', $url);
  264. }
  265. // Trim leading and lagging slashes
  266. $url = trim($url, '/');
  267. $request = $url;
  268. // Look for matches.
  269. $request_match = $request;
  270. foreach ( (array)$rewrite as $match => $query) {
  271. // If the requesting file is the anchor of the match, prepend it
  272. // to the path info.
  273. if ( !empty($url) && ($url != $request) && (strpos($match, $url) === 0) )
  274. $request_match = $url . '/' . $request;
  275. if ( preg_match("!^$match!", $request_match, $matches) ) {
  276. if ( $wp_rewrite->use_verbose_page_rules && preg_match( '/pagename=\$matches\[([0-9]+)\]/', $query, $varmatch ) ) {
  277. // this is a verbose page match, lets check to be sure about it
  278. if ( ! get_page_by_path( $matches[ $varmatch[1] ] ) )
  279. continue;
  280. }
  281. // Got a match.
  282. // Trim the query of everything up to the '?'.
  283. $query = preg_replace("!^.+\?!", '', $query);
  284. // Substitute the substring matches into the query.
  285. $query = addslashes(WP_MatchesMapRegex::apply($query, $matches));
  286. // Filter out non-public query vars
  287. global $wp;
  288. parse_str($query, $query_vars);
  289. $query = array();
  290. foreach ( (array) $query_vars as $key => $value ) {
  291. if ( in_array($key, $wp->public_query_vars) )
  292. $query[$key] = $value;
  293. }
  294. // Do the query
  295. $query = new WP_Query($query);
  296. if ( !empty($query->posts) && $query->is_singular )
  297. return $query->post->ID;
  298. else
  299. return 0;
  300. }
  301. }
  302. return 0;
  303. }
  304. /**
  305. * WordPress Rewrite Component.
  306. *
  307. * The WordPress Rewrite class writes the rewrite module rules to the .htaccess
  308. * file. It also handles parsing the request to get the correct setup for the
  309. * WordPress Query class.
  310. *
  311. * The Rewrite along with WP class function as a front controller for WordPress.
  312. * You can add rules to trigger your page view and processing using this
  313. * component. The full functionality of a front controller does not exist,
  314. * meaning you can't define how the template files load based on the rewrite
  315. * rules.
  316. *
  317. * @since 1.5.0
  318. */
  319. class WP_Rewrite {
  320. /**
  321. * Default permalink structure for WordPress.
  322. *
  323. * @since 1.5.0
  324. * @access private
  325. * @var string
  326. */
  327. var $permalink_structure;
  328. /**
  329. * Whether to add trailing slashes.
  330. *
  331. * @since 2.2.0
  332. * @access private
  333. * @var bool
  334. */
  335. var $use_trailing_slashes;
  336. /**
  337. * Permalink author request base ( example.com/author/authorname ).
  338. *
  339. * @since 1.5.0
  340. * @access private
  341. * @var string
  342. */
  343. var $author_base = 'author';
  344. /**
  345. * Permalink request structure for author pages.
  346. *
  347. * @since 1.5.0
  348. * @access private
  349. * @var string
  350. */
  351. var $author_structure;
  352. /**
  353. * Permalink request structure for dates.
  354. *
  355. * @since 1.5.0
  356. * @access private
  357. * @var string
  358. */
  359. var $date_structure;
  360. /**
  361. * Permalink request structure for pages.
  362. *
  363. * @since 1.5.0
  364. * @access private
  365. * @var string
  366. */
  367. var $page_structure;
  368. /**
  369. * Search permalink base ( example.com/search/query ).
  370. *
  371. * @since 1.5.0
  372. * @access private
  373. * @var string
  374. */
  375. var $search_base = 'search';
  376. /**
  377. * Permalink request structure for searches.
  378. *
  379. * @since 1.5.0
  380. * @access private
  381. * @var string
  382. */
  383. var $search_structure;
  384. /**
  385. * Comments permalink base.
  386. *
  387. * @since 1.5.0
  388. * @access private
  389. * @var string
  390. */
  391. var $comments_base = 'comments';
  392. /**
  393. * Pagination permalink base.
  394. *
  395. * @since 3.1.0
  396. * @access private
  397. * @var string
  398. */
  399. var $pagination_base = 'page';
  400. /**
  401. * Feed permalink base.
  402. *
  403. * @since 1.5.0
  404. * @access private
  405. * @var string
  406. */
  407. var $feed_base = 'feed';
  408. /**
  409. * Comments feed request structure permalink.
  410. *
  411. * @since 1.5.0
  412. * @access private
  413. * @var string
  414. */
  415. var $comments_feed_structure;
  416. /**
  417. * Feed request structure permalink.
  418. *
  419. * @since 1.5.0
  420. * @access private
  421. * @var string
  422. */
  423. var $feed_structure;
  424. /**
  425. * Front URL path.
  426. *
  427. * The difference between the root property is that WordPress might be
  428. * located at example/WordPress/index.php, if permalinks are turned off. The
  429. * WordPress/index.php will be the front portion. If permalinks are turned
  430. * on, this will most likely be empty or not set.
  431. *
  432. * @since 1.5.0
  433. * @access private
  434. * @var string
  435. */
  436. var $front;
  437. /**
  438. * Root URL path to WordPress (without domain).
  439. *
  440. * The difference between front property is that WordPress might be located
  441. * at example.com/WordPress/. The root is the 'WordPress/' portion.
  442. *
  443. * @since 1.5.0
  444. * @access private
  445. * @var string
  446. */
  447. var $root = '';
  448. /**
  449. * Permalink to the home page.
  450. *
  451. * @since 1.5.0
  452. * @access public
  453. * @var string
  454. */
  455. var $index = 'index.php';
  456. /**
  457. * Request match string.
  458. *
  459. * @since 1.5.0
  460. * @access private
  461. * @var string
  462. */
  463. var $matches = '';
  464. /**
  465. * Rewrite rules to match against the request to find the redirect or query.
  466. *
  467. * @since 1.5.0
  468. * @access private
  469. * @var array
  470. */
  471. var $rules;
  472. /**
  473. * Additional rules added external to the rewrite class.
  474. *
  475. * Those not generated by the class, see add_rewrite_rule().
  476. *
  477. * @since 2.1.0
  478. * @access private
  479. * @var array
  480. */
  481. var $extra_rules = array(); //
  482. /**
  483. * Additional rules that belong at the beginning to match first.
  484. *
  485. * Those not generated by the class, see add_rewrite_rule().
  486. *
  487. * @since 2.3.0
  488. * @access private
  489. * @var array
  490. */
  491. var $extra_rules_top = array(); //
  492. /**
  493. * Rules that don't redirect to WP's index.php.
  494. *
  495. * These rules are written to the mod_rewrite portion of the .htaccess.
  496. *
  497. * @since 2.1.0
  498. * @access private
  499. * @var array
  500. */
  501. var $non_wp_rules = array(); //
  502. /**
  503. * Extra permalink structures.
  504. *
  505. * @since 2.1.0
  506. * @access private
  507. * @var array
  508. */
  509. var $extra_permastructs = array();
  510. /**
  511. * Endpoints permalinks
  512. *
  513. * @since 2.1.0
  514. * @access private
  515. * @var array
  516. */
  517. var $endpoints;
  518. /**
  519. * Whether to write every mod_rewrite rule for WordPress.
  520. *
  521. * This is off by default, turning it on might print a lot of rewrite rules
  522. * to the .htaccess file.
  523. *
  524. * @since 2.0.0
  525. * @access public
  526. * @var bool
  527. */
  528. var $use_verbose_rules = false;
  529. /**
  530. * Whether to write every mod_rewrite rule for WordPress pages.
  531. *
  532. * @since 2.5.0
  533. * @access public
  534. * @var bool
  535. */
  536. var $use_verbose_page_rules = true;
  537. /**
  538. * Permalink structure search for preg_replace.
  539. *
  540. * @since 1.5.0
  541. * @access private
  542. * @var array
  543. */
  544. var $rewritecode =
  545. array(
  546. '%year%',
  547. '%monthnum%',
  548. '%day%',
  549. '%hour%',
  550. '%minute%',
  551. '%second%',
  552. '%postname%',
  553. '%post_id%',
  554. '%author%',
  555. '%pagename%',
  556. '%search%'
  557. );
  558. /**
  559. * Preg_replace values for the search, see {@link WP_Rewrite::$rewritecode}.
  560. *
  561. * @since 1.5.0
  562. * @access private
  563. * @var array
  564. */
  565. var $rewritereplace =
  566. array(
  567. '([0-9]{4})',
  568. '([0-9]{1,2})',
  569. '([0-9]{1,2})',
  570. '([0-9]{1,2})',
  571. '([0-9]{1,2})',
  572. '([0-9]{1,2})',
  573. '([^/]+)',
  574. '([0-9]+)',
  575. '([^/]+)',
  576. '([^/]+?)',
  577. '(.+)'
  578. );
  579. /**
  580. * Search for the query to look for replacing.
  581. *
  582. * @since 1.5.0
  583. * @access private
  584. * @var array
  585. */
  586. var $queryreplace =
  587. array (
  588. 'year=',
  589. 'monthnum=',
  590. 'day=',
  591. 'hour=',
  592. 'minute=',
  593. 'second=',
  594. 'name=',
  595. 'p=',
  596. 'author_name=',
  597. 'pagename=',
  598. 's='
  599. );
  600. /**
  601. * Supported default feeds.
  602. *
  603. * @since 1.5.0
  604. * @access private
  605. * @var array
  606. */
  607. var $feeds = array ( 'feed', 'rdf', 'rss', 'rss2', 'atom' );
  608. /**
  609. * Whether permalinks are being used.
  610. *
  611. * This can be either rewrite module or permalink in the HTTP query string.
  612. *
  613. * @since 1.5.0
  614. * @access public
  615. *
  616. * @return bool True, if permalinks are enabled.
  617. */
  618. function using_permalinks() {
  619. return ! empty($this->permalink_structure);
  620. }
  621. /**
  622. * Whether permalinks are being used and rewrite module is not enabled.
  623. *
  624. * Means that permalink links are enabled and index.php is in the URL.
  625. *
  626. * @since 1.5.0
  627. * @access public
  628. *
  629. * @return bool
  630. */
  631. function using_index_permalinks() {
  632. if ( empty($this->permalink_structure) )
  633. return false;
  634. // If the index is not in the permalink, we're using mod_rewrite.
  635. if ( preg_match('#^/*' . $this->index . '#', $this->permalink_structure) )
  636. return true;
  637. return false;
  638. }
  639. /**
  640. * Whether permalinks are being used and rewrite module is enabled.
  641. *
  642. * Using permalinks and index.php is not in the URL.
  643. *
  644. * @since 1.5.0
  645. * @access public
  646. *
  647. * @return bool
  648. */
  649. function using_mod_rewrite_permalinks() {
  650. if ( $this->using_permalinks() && ! $this->using_index_permalinks() )
  651. return true;
  652. else
  653. return false;
  654. }
  655. /**
  656. * Index for matches for usage in preg_*() functions.
  657. *
  658. * The format of the string is, with empty matches property value, '$NUM'.
  659. * The 'NUM' will be replaced with the value in the $number parameter. With
  660. * the matches property not empty, the value of the returned string will
  661. * contain that value of the matches property. The format then will be
  662. * '$MATCHES[NUM]', with MATCHES as the value in the property and NUM the
  663. * value of the $number parameter.
  664. *
  665. * @since 1.5.0
  666. * @access public
  667. *
  668. * @param int $number Index number.
  669. * @return string
  670. */
  671. function preg_index($number) {
  672. $match_prefix = '$';
  673. $match_suffix = '';
  674. if ( ! empty($this->matches) ) {
  675. $match_prefix = '$' . $this->matches . '[';
  676. $match_suffix = ']';
  677. }
  678. return "$match_prefix$number$match_suffix";
  679. }
  680. /**
  681. * Retrieve all page and attachments for pages URIs.
  682. *
  683. * The attachments are for those that have pages as parents and will be
  684. * retrieved.
  685. *
  686. * @since 2.5.0
  687. * @access public
  688. *
  689. * @return array Array of page URIs as first element and attachment URIs as second element.
  690. */
  691. function page_uri_index() {
  692. global $wpdb;
  693. //get pages in order of hierarchy, i.e. children after parents
  694. $posts = get_page_hierarchy( $wpdb->get_results("SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_type = 'page' AND post_status != 'auto-draft'") );
  695. // If we have no pages get out quick
  696. if ( !$posts )
  697. return array( array(), array() );
  698. //now reverse it, because we need parents after children for rewrite rules to work properly
  699. $posts = array_reverse($posts, true);
  700. $page_uris = array();
  701. $page_attachment_uris = array();
  702. foreach ( $posts as $id => $post ) {
  703. // URL => page name
  704. $uri = get_page_uri($id);
  705. $attachments = $wpdb->get_results( $wpdb->prepare( "SELECT ID, post_name, post_parent FROM $wpdb->posts WHERE post_type = 'attachment' AND post_parent = %d", $id ));
  706. if ( !empty($attachments) ) {
  707. foreach ( $attachments as $attachment ) {
  708. $attach_uri = get_page_uri($attachment->ID);
  709. $page_attachment_uris[$attach_uri] = $attachment->ID;
  710. }
  711. }
  712. $page_uris[$uri] = $id;
  713. }
  714. return array( $page_uris, $page_attachment_uris );
  715. }
  716. /**
  717. * Retrieve all of the rewrite rules for pages.
  718. *
  719. * If the 'use_verbose_page_rules' property is false, then there will only
  720. * be a single rewrite rule for pages for those matching '%pagename%'. With
  721. * the property set to true, the attachments and the pages will be added for
  722. * each individual attachment URI and page URI, respectively.
  723. *
  724. * @since 1.5.0
  725. * @access public
  726. *
  727. * @return array
  728. */
  729. function page_rewrite_rules() {
  730. $rewrite_rules = array();
  731. $page_structure = $this->get_page_permastruct();
  732. // the extra .? at the beginning prevents clashes with other regular expressions in the rules array
  733. $this->add_rewrite_tag('%pagename%', "(.?.+?)", 'pagename=');
  734. $rewrite_rules = array_merge($rewrite_rules, $this->generate_rewrite_rules($page_structure, EP_PAGES));
  735. return $rewrite_rules;
  736. }
  737. /**
  738. * Retrieve date permalink structure, with year, month, and day.
  739. *
  740. * The permalink structure for the date, if not set already depends on the
  741. * permalink structure. It can be one of three formats. The first is year,
  742. * month, day; the second is day, month, year; and the last format is month,
  743. * day, year. These are matched against the permalink structure for which
  744. * one is used. If none matches, then the default will be used, which is
  745. * year, month, day.
  746. *
  747. * Prevents post ID and date permalinks from overlapping. In the case of
  748. * post_id, the date permalink will be prepended with front permalink with
  749. * 'date/' before the actual permalink to form the complete date permalink
  750. * structure.
  751. *
  752. * @since 1.5.0
  753. * @access public
  754. *
  755. * @return bool|string False on no permalink structure. Date permalink structure.
  756. */
  757. function get_date_permastruct() {
  758. if ( isset($this->date_structure) )
  759. return $this->date_structure;
  760. if ( empty($this->permalink_structure) ) {
  761. $this->date_structure = '';
  762. return false;
  763. }
  764. // The date permalink must have year, month, and day separated by slashes.
  765. $endians = array('%year%/%monthnum%/%day%', '%day%/%monthnum%/%year%', '%monthnum%/%day%/%year%');
  766. $this->date_structure = '';
  767. $date_endian = '';
  768. foreach ( $endians as $endian ) {
  769. if ( false !== strpos($this->permalink_structure, $endian) ) {
  770. $date_endian= $endian;
  771. break;
  772. }
  773. }
  774. if ( empty($date_endian) )
  775. $date_endian = '%year%/%monthnum%/%day%';
  776. // Do not allow the date tags and %post_id% to overlap in the permalink
  777. // structure. If they do, move the date tags to $front/date/.
  778. $front = $this->front;
  779. preg_match_all('/%.+?%/', $this->permalink_structure, $tokens);
  780. $tok_index = 1;
  781. foreach ( (array) $tokens[0] as $token) {
  782. if ( '%post_id%' == $token && ($tok_index <= 3) ) {
  783. $front = $front . 'date/';
  784. break;
  785. }
  786. $tok_index++;
  787. }
  788. $this->date_structure = $front . $date_endian;
  789. return $this->date_structure;
  790. }
  791. /**
  792. * Retrieve the year permalink structure without month and day.
  793. *
  794. * Gets the date permalink structure and strips out the month and day
  795. * permalink structures.
  796. *
  797. * @since 1.5.0
  798. * @access public
  799. *
  800. * @return bool|string False on failure. Year structure on success.
  801. */
  802. function get_year_permastruct() {
  803. $structure = $this->get_date_permastruct($this->permalink_structure);
  804. if ( empty($structure) )
  805. return false;
  806. $structure = str_replace('%monthnum%', '', $structure);
  807. $structure = str_replace('%day%', '', $structure);
  808. $structure = preg_replace('#/+#', '/', $structure);
  809. return $structure;
  810. }
  811. /**
  812. * Retrieve the month permalink structure without day and with year.
  813. *
  814. * Gets the date permalink structure and strips out the day permalink
  815. * structures. Keeps the year permalink structure.
  816. *
  817. * @since 1.5.0
  818. * @access public
  819. *
  820. * @return bool|string False on failure. Year/Month structure on success.
  821. */
  822. function get_month_permastruct() {
  823. $structure = $this->get_date_permastruct($this->permalink_structure);
  824. if ( empty($structure) )
  825. return false;
  826. $structure = str_replace('%day%', '', $structure);
  827. $structure = preg_replace('#/+#', '/', $structure);
  828. return $structure;
  829. }
  830. /**
  831. * Retrieve the day permalink structure with month and year.
  832. *
  833. * Keeps date permalink structure with all year, month, and day.
  834. *
  835. * @since 1.5.0
  836. * @access public
  837. *
  838. * @return bool|string False on failure. Year/Month/Day structure on success.
  839. */
  840. function get_day_permastruct() {
  841. return $this->get_date_permastruct($this->permalink_structure);
  842. }
  843. /**
  844. * Retrieve the permalink structure for categories.
  845. *
  846. * If the category_base property has no value, then the category structure
  847. * will have the front property value, followed by 'category', and finally
  848. * '%category%'. If it does, then the root property will be used, along with
  849. * the category_base property value.
  850. *
  851. * @since 1.5.0
  852. * @access public
  853. *
  854. * @return bool|string False on failure. Category permalink structure.
  855. */
  856. function get_category_permastruct() {
  857. return $this->get_extra_permastruct('category');
  858. }
  859. /**
  860. * Retrieve the permalink structure for tags.
  861. *
  862. * If the tag_base property has no value, then the tag structure will have
  863. * the front property value, followed by 'tag', and finally '%tag%'. If it
  864. * does, then the root property will be used, along with the tag_base
  865. * property value.
  866. *
  867. * @since 2.3.0
  868. * @access public
  869. *
  870. * @return bool|string False on failure. Tag permalink structure.
  871. */
  872. function get_tag_permastruct() {
  873. return $this->get_extra_permastruct('post_tag');
  874. }
  875. /**
  876. * Retrieve extra permalink structure by name.
  877. *
  878. * @since 2.5.0
  879. * @access public
  880. *
  881. * @param string $name Permalink structure name.
  882. * @return string|bool False if not found. Permalink structure string.
  883. */
  884. function get_extra_permastruct($name) {
  885. if ( empty($this->permalink_structure) )
  886. return false;
  887. if ( isset($this->extra_permastructs[$name]) )
  888. return $this->extra_permastructs[$name][0];
  889. return false;
  890. }
  891. /**
  892. * Retrieve the author permalink structure.
  893. *
  894. * The permalink structure is front property, author base, and finally
  895. * '/%author%'. Will set the author_structure property and then return it
  896. * without attempting to set the value again.
  897. *
  898. * @since 1.5.0
  899. * @access public
  900. *
  901. * @return string|bool False if not found. Permalink structure string.
  902. */
  903. function get_author_permastruct() {
  904. if ( isset($this->author_structure) )
  905. return $this->author_structure;
  906. if ( empty($this->permalink_structure) ) {
  907. $this->author_structure = '';
  908. return false;
  909. }
  910. $this->author_structure = $this->front . $this->author_base . '/%author%';
  911. return $this->author_structure;
  912. }
  913. /**
  914. * Retrieve the search permalink structure.
  915. *
  916. * The permalink structure is root property, search base, and finally
  917. * '/%search%'. Will set the search_structure property and then return it
  918. * without attempting to set the value again.
  919. *
  920. * @since 1.5.0
  921. * @access public
  922. *
  923. * @return string|bool False if not found. Permalink structure string.
  924. */
  925. function get_search_permastruct() {
  926. if ( isset($this->search_structure) )
  927. return $this->search_structure;
  928. if ( empty($this->permalink_structure) ) {
  929. $this->search_structure = '';
  930. return false;
  931. }
  932. $this->search_structure = $this->root . $this->search_base . '/%search%';
  933. return $this->search_structure;
  934. }
  935. /**
  936. * Retrieve the page permalink structure.
  937. *
  938. * The permalink structure is root property, and '%pagename%'. Will set the
  939. * page_structure property and then return it without attempting to set the
  940. * value again.
  941. *
  942. * @since 1.5.0
  943. * @access public
  944. *
  945. * @return string|bool False if not found. Permalink structure string.
  946. */
  947. function get_page_permastruct() {
  948. if ( isset($this->page_structure) )
  949. return $this->page_structure;
  950. if (empty($this->permalink_structure)) {
  951. $this->page_structure = '';
  952. return false;
  953. }
  954. $this->page_structure = $this->root . '%pagename%';
  955. return $this->page_structure;
  956. }
  957. /**
  958. * Retrieve the feed permalink structure.
  959. *
  960. * The permalink structure is root property, feed base, and finally
  961. * '/%feed%'. Will set the feed_structure property and then return it
  962. * without attempting to set the value again.
  963. *
  964. * @since 1.5.0
  965. * @access public
  966. *
  967. * @return string|bool False if not found. Permalink structure string.
  968. */
  969. function get_feed_permastruct() {
  970. if ( isset($this->feed_structure) )
  971. return $this->feed_structure;
  972. if ( empty($this->permalink_structure) ) {
  973. $this->feed_structure = '';
  974. return false;
  975. }
  976. $this->feed_structure = $this->root . $this->feed_base . '/%feed%';
  977. return $this->feed_structure;
  978. }
  979. /**
  980. * Retrieve the comment feed permalink structure.
  981. *
  982. * The permalink structure is root property, comment base property, feed
  983. * base and finally '/%feed%'. Will set the comment_feed_structure property
  984. * and then return it without attempting to set the value again.
  985. *
  986. * @since 1.5.0
  987. * @access public
  988. *
  989. * @return string|bool False if not found. Permalink structure string.
  990. */
  991. function get_comment_feed_permastruct() {
  992. if ( isset($this->comment_feed_structure) )
  993. return $this->comment_feed_structure;
  994. if (empty($this->permalink_structure)) {
  995. $this->comment_feed_structure = '';
  996. return false;
  997. }
  998. $this->comment_feed_structure = $this->root . $this->comments_base . '/' . $this->feed_base . '/%feed%';
  999. return $this->comment_feed_structure;
  1000. }
  1001. /**
  1002. * Append or update tag, pattern, and query for replacement.
  1003. *
  1004. * If the tag already exists, replace the existing pattern and query for
  1005. * that tag, otherwise add the new tag, pattern, and query to the end of the
  1006. * arrays.
  1007. *
  1008. * @internal What is the purpose of this function again? Need to finish long
  1009. * description.
  1010. *
  1011. * @since 1.5.0
  1012. * @access public
  1013. *
  1014. * @param string $tag Append tag to rewritecode property array.
  1015. * @param string $pattern Append pattern to rewritereplace property array.
  1016. * @param string $query Append query to queryreplace property array.
  1017. */
  1018. function add_rewrite_tag($tag, $pattern, $query) {
  1019. $position = array_search($tag, $this->rewritecode);
  1020. if ( false !== $position && null !== $position ) {
  1021. $this->rewritereplace[$position] = $pattern;
  1022. $this->queryreplace[$position] = $query;
  1023. } else {
  1024. $this->rewritecode[] = $tag;
  1025. $this->rewritereplace[] = $pattern;
  1026. $this->queryreplace[] = $query;
  1027. }
  1028. }
  1029. /**
  1030. * Generate the rules from permalink structure.
  1031. *
  1032. * The main WP_Rewrite function for building the rewrite rule list. The
  1033. * contents of the function is a mix of black magic and regular expressions,
  1034. * so best just ignore the contents and move to the parameters.
  1035. *
  1036. * @since 1.5.0
  1037. * @access public
  1038. *
  1039. * @param string $permalink_structure The permalink structure.
  1040. * @param int $ep_mask Optional, default is EP_NONE. Endpoint constant, see EP_* constants.
  1041. * @param bool $paged Optional, default is true. Whether permalink request is paged.
  1042. * @param bool $feed Optional, default is true. Whether for feed.
  1043. * @param bool $forcomments Optional, default is false. Whether for comments.
  1044. * @param bool $walk_dirs Optional, default is true. Whether to create list of directories to walk over.
  1045. * @param bool $endpoints Optional, default is true. Whether endpoints are enabled.
  1046. * @return array Rewrite rule list.
  1047. */
  1048. function generate_rewrite_rules($permalink_structure, $ep_mask = EP_NONE, $paged = true, $feed = true, $forcomments = false, $walk_dirs = true, $endpoints = true) {
  1049. //build a regex to match the feed section of URLs, something like (feed|atom|rss|rss2)/?
  1050. $feedregex2 = '';
  1051. foreach ( (array) $this->feeds as $feed_name)
  1052. $feedregex2 .= $feed_name . '|';
  1053. $feedregex2 = '(' . trim($feedregex2, '|') . ')/?$';
  1054. //$feedregex is identical but with /feed/ added on as well, so URLs like <permalink>/feed/atom
  1055. //and <permalink>/atom are both possible
  1056. $feedregex = $this->feed_base . '/' . $feedregex2;
  1057. //build a regex to match the trackback and page/xx parts of URLs
  1058. $trackbackregex = 'trackback/?$';
  1059. $pageregex = $this->pagination_base . '/?([0-9]{1,})/?$';
  1060. $commentregex = 'comment-page-([0-9]{1,})/?$';
  1061. //build up an array of endpoint regexes to append => queries to append
  1062. if ( $endpoints ) {
  1063. $ep_query_append = array ();
  1064. foreach ( (array) $this->endpoints as $endpoint) {
  1065. //match everything after the endpoint name, but allow for nothing to appear there
  1066. $epmatch = $endpoint[1] . '(/(.*))?/?$';
  1067. //this will be appended on to the rest of the query for each dir
  1068. $epquery = '&' . $endpoint[1] . '=';
  1069. $ep_query_append[$epmatch] = array ( $endpoint[0], $epquery );
  1070. }
  1071. }
  1072. //get everything up to the first rewrite tag
  1073. $front = substr($permalink_structure, 0, strpos($permalink_structure, '%'));
  1074. //build an array of the tags (note that said array ends up being in $tokens[0])
  1075. preg_match_all('/%.+?%/', $permalink_structure, $tokens);
  1076. $num_tokens = count($tokens[0]);
  1077. $index = $this->index; //probably 'index.php'
  1078. $feedindex = $index;
  1079. $trackbackindex = $index;
  1080. //build a list from the rewritecode and queryreplace arrays, that will look something like
  1081. //tagname=$matches[i] where i is the current $i
  1082. for ( $i = 0; $i < $num_tokens; ++$i ) {
  1083. if ( 0 < $i )
  1084. $queries[$i] = $queries[$i - 1] . '&';
  1085. else
  1086. $queries[$i] = '';
  1087. $query_token = str_replace($this->rewritecode, $this->queryreplace, $tokens[0][$i]) . $this->preg_index($i+1);
  1088. $queries[$i] .= $query_token;
  1089. }
  1090. //get the structure, minus any cruft (stuff that isn't tags) at the front
  1091. $structure = $permalink_structure;
  1092. if ( $front != '/' )
  1093. $structure = str_replace($front, '', $structure);
  1094. //create a list of dirs to walk over, making rewrite rules for each level
  1095. //so for example, a $structure of /%year%/%month%/%postname% would create
  1096. //rewrite rules for /%year%/, /%year%/%month%/ and /%year%/%month%/%postname%
  1097. $structure = trim($structure, '/');
  1098. $dirs = $walk_dirs ? explode('/', $structure) : array( $structure );
  1099. $num_dirs = count($dirs);
  1100. //strip slashes from the front of $front
  1101. $front = preg_replace('|^/+|', '', $front);
  1102. //the main workhorse loop
  1103. $post_rewrite = array();
  1104. $struct = $front;
  1105. for ( $j = 0; $j < $num_dirs; ++$j ) {
  1106. //get the struct for this dir, and trim slashes off the front
  1107. $struct .= $dirs[$j] . '/'; //accumulate. see comment near explode('/', $structure) above
  1108. $struct = ltrim($struct, '/');
  1109. //replace tags with regexes
  1110. $match = str_replace($this->rewritecode, $this->rewritereplace, $struct);
  1111. //make a list of tags, and store how many there are in $num_toks
  1112. $num_toks = preg_match_all('/%.+?%/', $struct, $toks);
  1113. //get the 'tagname=$matches[i]'
  1114. $query = ( isset($queries) && is_array($queries) && !empty($num_toks) ) ? $queries[$num_toks - 1] : '';
  1115. //set up $ep_mask_specific which is used to match more specific URL types
  1116. switch ( $dirs[$j] ) {
  1117. case '%year%':
  1118. $ep_mask_specific = EP_YEAR;
  1119. break;
  1120. case '%monthnum%':
  1121. $ep_mask_specific = EP_MONTH;
  1122. break;
  1123. case '%day%':
  1124. $ep_mask_specific = EP_DAY;
  1125. break;
  1126. default:
  1127. $ep_mask_specific = EP_NONE;
  1128. }
  1129. //create query for /page/xx
  1130. $pagematch = $match . $pageregex;
  1131. $pagequery = $index . '?' . $query . '&paged=' . $this->preg_index($num_toks + 1);
  1132. //create query for /comment-page-xx
  1133. $commentmatch = $match . $commentregex;
  1134. $commentquery = $index . '?' . $query . '&cpage=' . $this->preg_index($num_toks + 1);
  1135. if ( get_option('page_on_front') ) {
  1136. //create query for Root /comment-page-xx
  1137. $rootcommentmatch = $match . $commentregex;
  1138. $rootcommentquery = $index . '?' . $query . '&page_id=' . get_option('page_on_front') . '&cpage=' . $this->preg_index($num_toks + 1);
  1139. }
  1140. //create query for /feed/(feed|atom|rss|rss2|rdf)
  1141. $feedmatch = $match . $feedregex;
  1142. $feedquery = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1);
  1143. //create query for /(feed|atom|rss|rss2|rdf) (see comment near creation of $feedregex)
  1144. $feedmatch2 = $match . $feedregex2;
  1145. $feedquery2 = $feedindex . '?' . $query . '&feed=' . $this->preg_index($num_toks + 1);
  1146. //if asked to, turn the feed queries into comment feed ones
  1147. if ( $forcomments ) {
  1148. $feedquery .= '&withcomments=1';
  1149. $feedquery2 .= '&withcomments=1';
  1150. }
  1151. //start creating the array of rewrites for this dir
  1152. $rewrite = array();
  1153. if ( $feed ) //...adding on /feed/ regexes => queries
  1154. $rewrite = array($feedmatch => $feedquery, $feedmatch2 => $feedquery2);
  1155. if ( $paged ) //...and /page/xx ones
  1156. $rewrite = array_merge($rewrite, array($pagematch => $pagequery));
  1157. //only on pages with comments add ../comment-page-xx/
  1158. if ( EP_PAGES & $ep_mask || EP_PERMALINK & $ep_mask )
  1159. $rewrite = array_merge($rewrite, array($commentmatch => $commentquery));
  1160. else if ( EP_ROOT & $ep_mask && get_option('page_on_front') )
  1161. $rewrite = array_merge($rewrite, array($rootcommentmatch => $rootcommentquery));
  1162. //do endpoints
  1163. if ( $endpoints ) {
  1164. foreach ( (array) $ep_query_append as $regex => $ep) {
  1165. //add the endpoints on if the mask fits
  1166. if ( $ep[0] & $ep_mask || $ep[0] & $ep_mask_specific )
  1167. $rewrite[$match . $regex] = $index . '?' . $query . $ep[1] . $this->preg_index($num_toks + 2);
  1168. }
  1169. }
  1170. //if we've got some tags in this dir
  1171. if ( $num_toks ) {
  1172. $post = false;
  1173. $page = false;
  1174. //check to see if this dir is permalink-level: i.e. the structure specifies an
  1175. //individual post. Do this by checking it contains at least one of 1) post name,
  1176. //2) post ID, 3) page name, 4) timestamp (year, month, day, hour, second and
  1177. //minute all present). Set these flags now as we need them for the endpoints.
  1178. if ( strpos($struct, '%postname%') !== false
  1179. || strpos($struct, '%post_id%') !== false
  1180. || strpos($struct, '%pagename%') !== false
  1181. || (strpos($struct, '%year%') !== false && strpos($struct, '%monthnum%') !== false && strpos($struct, '%day%') !== false && strpos($struct, '%hour%') !== false && strpos($struct, '%minute%') !== false && strpos($struct, '%second%') !== false)
  1182. ) {
  1183. $post = true;
  1184. if ( strpos($struct, '%pagename%') !== false )
  1185. $page = true;
  1186. }
  1187. if ( ! $post ) {
  1188. // For custom post types, we need to add on endpoints as well.
  1189. foreach ( get_post_types( array('_builtin' => false ) ) as $ptype ) {
  1190. if ( strpos($struct, "%$ptype%") !== false ) {
  1191. $post = true;
  1192. $page = is_post_type_hierarchical( $ptype ); // This is for page style attachment url's
  1193. break;
  1194. }
  1195. }
  1196. }
  1197. //if we're creating rules for a permalink, do all the endpoints like attachments etc
  1198. if ( $post ) {
  1199. //create query and regex for trackback
  1200. $trackbackmatch = $match . $trackbackregex;
  1201. $trackbackquery = $trackbackindex . '?' . $query . '&tb=1';
  1202. //trim slashes from the end of the regex for this dir
  1203. $match = rtrim($match, '/');
  1204. //get rid of brackets
  1205. $submatchbase = str_replace( array('(', ')'), '', $match);
  1206. //add a rule for at attachments, which take the form of <permalink>/some-text
  1207. $sub1 = $submatchbase . '/([^/]+)/';
  1208. $sub1tb = $sub1 . $trackbackregex; //add trackback regex <permalink>/trackback/...
  1209. $sub1feed = $sub1 . $feedregex; //and <permalink>/feed/(atom|...)
  1210. $sub1feed2 = $sub1 . $feedregex2; //and <permalink>/(feed|atom...)
  1211. $sub1comment = $sub1 . $commentregex; //and <permalink>/comment-page-xx
  1212. //add an ? as we don't have to match that last slash, and finally a $ so we
  1213. //match to the end of the URL
  1214. //add another rule to match attachments in the explicit form:
  1215. //<permalink>/attachment/some-text
  1216. $sub2 = $submatchbase . '/attachment/([^/]+)/';
  1217. $sub2tb = $sub2 . $trackbackregex; //and add trackbacks <permalink>/attachment/trackback
  1218. $sub2feed = $sub2 . $feedregex; //feeds, <permalink>/attachment/feed/(atom|...)
  1219. $sub2feed2 = $sub2 . $feedregex2; //and feeds again on to this <permalink>/attachment/(feed|atom...)
  1220. $sub2comment = $sub2 . $commentregex; //and <permalink>/comment-page-xx
  1221. //create queries for these extra tag-ons we've just dealt with
  1222. $subquery = $index . '?attachment=' . $this->preg_index(1);
  1223. $subtbquery = $subquery . '&tb=1';
  1224. $subfeedquery = $subquery . '&feed=' . $this->preg_index(2);
  1225. $subcommentquery = $subquery . '&cpage=' . $this->preg_index(2);
  1226. //do endpoints for attachments
  1227. if ( !empty($endpoints) ) {
  1228. foreach ( (array) $ep_query_append as $regex => $ep ) {
  1229. if ( $ep[0] & EP_ATTACHMENT ) {
  1230. $rewrite[$sub1 . $regex] = $subquery . $ep[1] . $this->preg_index(2);
  1231. $rewrite[$sub2 . $regex] = $subquery . $ep[1] . $this->preg_index(2);
  1232. }
  1233. }
  1234. }
  1235. //now we've finished with endpoints, finish off the $sub1 and $sub2 matches
  1236. $sub1 .= '?$';
  1237. $sub2 .= '?$';
  1238. //allow URLs like <permalink>/2 for <permalink>/page/2
  1239. $match = $match . '(/[0-9]+)?/?$';
  1240. $query = $index . '?' . $query . '&page=' . $this->preg_index($num_toks + 1);
  1241. } else { //not matching a permalink so this is a lot simpler
  1242. //close the match and finalise the query
  1243. $match .= '?$';
  1244. $query = $index . '?' . $query;
  1245. }
  1246. //create the final array for this dir by joining the $rewrite array (which currently
  1247. //only contains rules/queries for trackback, pages etc) to the main regex/query for
  1248. //this dir
  1249. $rewrite = array_merge($rewrite, array($match => $query));
  1250. //if we're matching a permalink, add those extras (attachments etc) on
  1251. if ( $post ) {
  1252. //add trackback
  1253. $rewrite = array_merge(array($trackbackmatch => $trackbackquery), $rewrite);
  1254. //add regexes/queries for attachments, attachment trackbacks and so on
  1255. if ( ! $page ) //require <permalink>/attachment/stuff form for pages because of confusion with subpages
  1256. $rewrite = array_merge($rewrite, array($sub1 => $subquery, $sub1tb => $subtbquery, $sub1feed => $subfeedquery, $sub1feed2 => $subfeedquery, $sub1comment => $subcommentquery));
  1257. $rewrite = array_merge(array($sub2 => $subquery, $sub2tb => $subtbquery, $sub2feed => $subfeedquery, $sub2feed2 => $subfeedquery, $sub2comment => $subcommentquery), $rewrite);
  1258. }
  1259. } //if($num_toks)
  1260. //add the rules for this dir to the accumulating $post_rewrite
  1261. $post_rewrite = array_merge($rewrite, $post_rewrite);
  1262. } //foreach ($dir)
  1263. return $post_rewrite; //the finished rules. phew!
  1264. }
  1265. /**
  1266. * Generate Rewrite rules with permalink structure and walking directory only.
  1267. *
  1268. * Shorten version of {@link WP_Rewrite::generate_rewrite_rules()} that
  1269. * allows for shorter list of parameters. See the method for longer
  1270. * description of what generating rewrite rules does.
  1271. *
  1272. * @uses WP_Rewrite::generate_rewrite_rules() See for long description and rest of parameters.
  1273. * @since 1.5.0
  1274. * @access public
  1275. *
  1276. * @param string $permalink_structure The permalink structure to generate rules.
  1277. * @param bool $walk_dirs Optional, default is false. Whether to create list of directories to walk over.
  1278. * @return array
  1279. */
  1280. function generate_rewrite_rule($permalink_structure, $walk_dirs = false) {
  1281. return $this->generate_rewrite_rules($permalink_structure, EP_NONE, false, false, false, $walk_dirs);
  1282. }
  1283. /**
  1284. * Construct rewrite matches and queries from permalink structure.
  1285. *
  1286. * Runs the action 'generate_rewrite_rules' with the parameter that is an
  1287. * reference to the current WP_Rewrite instance to further manipulate the
  1288. * permalink structures and rewrite rules. Runs the 'rewrite_rules_array'
  1289. * filter on the full rewrite rule array.
  1290. *
  1291. * There are two ways to manipulate the rewrite rules, one by hooking into
  1292. * the 'generate_rewrite_rules' action and gaining full control of the
  1293. * object or just manipulating the rewrite rule array before it is passed
  1294. * from the function.
  1295. *
  1296. * @since 1.5.0
  1297. * @access public
  1298. *
  1299. * @return array An associate array of matches and queries.
  1300. */
  1301. function rewrite_rules() {
  1302. $rewrite = array();
  1303. if ( empty($this->permalink_structure) )
  1304. return $rewrite;
  1305. // robots.txt -only if installed at the root
  1306. $home_path = parse_url( home_url() );
  1307. $robots_rewrite = ( empty( $home_path['path'] ) || '/' == $home_path['path'] ) ? array( 'robots\.txt$' => $this->index . '?robots=1' ) : array();
  1308. // Old feed files
  1309. $old_feed_files = array( '.*wp-(atom|rdf|rss|rss2|feed|commentsrss2)\.php$' => $this->index . '?feed=old' );
  1310. // Registration rules
  1311. $registration_pages = array();
  1312. if ( is_multisite() && is_main_site() ) {
  1313. $registration_pages['.*wp-signup.php$'] = $this->index . '?signup=true';
  1314. $registration_pages['.*wp-activate.php$'] = $this->index . '?activate=true';
  1315. }
  1316. // Post
  1317. $post_rewrite = $this->generate_rewrite_rules($this->permalink_structure, EP_PERMALINK);
  1318. $post_rewrite = apply_filters('post_rewrite_rules', $post_rewrite);
  1319. // Date
  1320. $date_rewrite = $this->generate_rewrite_rules($this->get_date_permastruct(), EP_DATE);
  1321. $date_rewrite = apply_filters('date_rewrite_rules', $date_rewrite);
  1322. // Root
  1323. $root_rewrite = $this->generate_rewrite_rules($this->root . '/', EP_ROOT);
  1324. $root_rewrite = apply_filters('root_rewrite_rules', $root_rewrite);
  1325. // Comments
  1326. $comments_rewrite = $this->generate_rewrite_rules($this->root . $this->comments_base, EP_COMMENTS, true, true, true, false);
  1327. $comments_rewrite = apply_filters('comments_rewrite_rules', $comments_rewrite);
  1328. // Search
  1329. $search_structure = $this->get_search_permastruct();
  1330. $search_rewrite = $this->generate_rewrite_rules($search_structure, EP_SEARCH);
  1331. $search_rewrite = apply_filters('search_rewrite_rules', $search_rewrite);
  1332. // Authors
  1333. $author_rewrite = $this->generate_rewrite_rules($this->get_author_permastruct(), EP_AUTHORS);
  1334. $author_rewrite = apply_filters('author_rewrite_rules', $author_rewrite);
  1335. // Pages
  1336. $page_rewrite = $this->page_rewrite_rules();
  1337. $page_rewrite = apply_filters('page_rewrite_rules', $page_rewrite);
  1338. // Extra permastructs
  1339. foreach ( $this->extra_permastructs as $permastructname => $permastruct ) {
  1340. if ( is_array($permastruct) )
  1341. $rules = $this->generate_rewrite_rules($permastruct[0], $permastruct[1]);
  1342. else
  1343. $rules = $this->generate_rewrite_rules($permastruct, EP_NONE);
  1344. $rules = apply_filters($permastructname . '_rewrite_rules', $rules);
  1345. if ( 'post_tag' == $permastructname )
  1346. $rules = apply_filters('tag_rewrite_rules', $rules);
  1347. $this->extra_rules_top = array_merge($this->extra_rules_top, $rules);
  1348. }
  1349. // Put them together.
  1350. if ( $this->use_verbose_page_rules )
  1351. $this->rules = array_merge($this->extra_rules_top, $robots_rewrite, $old_feed_files, $registration_pages, $root_rewrite, $comments_rewrite, $search_rewrite, $author_rewrite, $date_rewrite, $page_rewrite, $post_rewrite, $this->extra_rules);
  1352. else
  1353. $this->rules = array_merge($this->extra_rules_top, $robots_rewrite, $old_feed_files, $registration_pages, $root_rewrite, $comments_rewrite, $search_rewrite, $author_rewrite, $date_rewrite, $post_rewrite, $page_rewrite, $this->extra_rules);
  1354. do_action_ref_array('generate_rewrite_rules', array(&$this));
  1355. $this->rules = apply_filters('rewrite_rules_array', $this->rules);
  1356. return $this->rules;
  1357. }
  1358. /**
  1359. * Retrieve the rewrite rules.
  1360. *
  1361. * The difference between this method and {@link
  1362. * WP_Rewrite::rewrite_rules()} is that this method stores the rewrite rules
  1363. * in the 'rewrite_rules' option and retrieves it. This prevents having to
  1364. * process all of the permalinks to get the rewrite rules in the form of
  1365. * caching.
  1366. *
  1367. * @since 1.5.0
  1368. * @access public
  1369. *
  1370. * @return array Rewrite rules.
  1371. */
  1372. function wp_rewrite_rules() {
  1373. $this->rules = get_option('rewrite_rules');
  1374. if ( empty($this->rules) ) {
  1375. $this->matches = 'matches';
  1376. $this->rewrite_rules();
  1377. update_option('rewrite_rules', $this->rules);
  1378. }
  1379. return $this->rules;
  1380. }
  1381. /**
  1382. * Retrieve mod_rewrite formatted rewrite rules to write to .htaccess.
  1383. *
  1384. * Does not actually write to the .htaccess file, but creates the rules for
  1385. * the process that will.
  1386. *
  1387. * Will add the non_wp_rules property rules to the .htaccess file before
  1388. * the WordPress rewrite rules one.
  1389. *
  1390. * @since 1.5.0
  1391. * @access public
  1392. *
  1393. * @return string
  1394. */
  1395. function mod_rewrite_rules() {
  1396. if ( ! $this->using_permalinks() )
  1397. return '';
  1398. $site_root = parse_url(get_option('siteurl'));
  1399. if ( isset( $site_root['path'] ) )
  1400. $site_root = trailingslashit($site_root['path']);
  1401. $home_root = parse_url(home_url());
  1402. if ( isset( $home_root['path'] ) )
  1403. $home_root = trailingslashit($home_root['path']);
  1404. else
  1405. $home_root = '/';
  1406. $rules = "<IfModule mod_rewrite.c>\n";
  1407. $rules .= "RewriteEngine On\n";
  1408. $rules .= "RewriteBase $home_root\n";
  1409. $rules .= "RewriteRule ^index\.php$ - [L]\n"; // Prevent -f checks on index.php.
  1410. //add in the rules that don't redirect to WP's index.php (and thus shouldn't be handled by WP at all)
  1411. foreach ( (array) $this->non_wp_rules as $match => $query) {
  1412. // Apache 1.3 does not support the reluctant (non-greedy) modifier.
  1413. $match = str_replace('.+?', '.+', $match);
  1414. // If the match is unanchored and greedy, prepend rewrite conditions
  1415. // to avoid infinite redirects and eclipsing of real files.
  1416. //if ($match == '(.+)/?$' || $match == '([^/]+)/?$' ) {
  1417. //nada.
  1418. //}
  1419. $rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n";
  1420. }
  1421. if ( $this->use_verbose_rules ) {
  1422. $this->matches = '';
  1423. $rewrite = $this->rewrite_rules();
  1424. $num_rules = count($rewrite);
  1425. $rules .= "RewriteCond %{REQUEST_FILENAME} -f [OR]\n" .
  1426. "RewriteCond %{REQUEST_FILENAME} -d\n" .
  1427. "RewriteRule ^.*$ - [S=$num_rules]\n";
  1428. foreach ( (array) $rewrite as $match => $query) {
  1429. // Apache 1.3 does not support the reluctant (non-greedy) modifier.
  1430. $match = str_replace('.+?', '.+', $match);
  1431. // If the match is unanchored and greedy, prepend rewrite conditions
  1432. // to avoid infinite redirects and eclipsing of real files.
  1433. //if ($match == '(.+)/?$' || $match == '([^/]+)/?$' ) {
  1434. //nada.
  1435. //}
  1436. if ( strpos($query, $this->index) !== false )
  1437. $rules .= 'RewriteRule ^' . $match . ' ' . $home_root . $query . " [QSA,L]\n";
  1438. else
  1439. $rules .= 'RewriteRule ^' . $match . ' ' . $site_root . $query . " [QSA,L]\n";
  1440. }
  1441. } else {
  1442. $rules .= "RewriteCond %{REQUEST_FILENAME} !-f\n" .
  1443. "RewriteCond %{REQUEST_FILENAME} !-d\n" .
  1444. "RewriteRule . {$home_root}{$this->index} [L]\n";
  1445. }
  1446. $rules .= "</IfModule>\n";
  1447. $rules = apply_filters('mod_rewrite_rules', $rules);
  1448. $rules = apply_filters('rewrite_rules', $rules); // Deprecated
  1449. return $rules;
  1450. }
  1451. /**
  1452. * Retrieve IIS7 URL Rewrite formatted rewrite rules to write to web.config file.
  1453. *
  1454. * Does not actually write to the web.config file, but creates the rules for
  1455. * the process that will.
  1456. *
  1457. * @since 2.8.0
  1458. * @access public
  1459. *
  1460. * @return string
  1461. */
  1462. function iis7_url_rewrite_rules( $add_parent_tags = false ) {
  1463. if ( ! $this->using_permalinks() )
  1464. return '';
  1465. $rules = '';
  1466. if ( $add_parent_tags ) {
  1467. $rules .= '<configuration>
  1468. <system.webServer>
  1469. <rewrite>
  1470. <rules>';
  1471. }
  1472. if ( !is_multisite() ) {
  1473. $rules .= '
  1474. <rule name="wordpress" patternSyntax="Wildcard">
  1475. <match url="*" />
  1476. <conditions>
  1477. <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
  1478. <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
  1479. </conditions>
  1480. <action type="Rewrite" url="index.php" />
  1481. </rule>';
  1482. } else {
  1483. if (is_subdomain_install()) {
  1484. $rules .= '
  1485. <rule name="wordpress - Rule 1" stopProcessing="true">
  1486. <match url="^index\.php$" ignoreCase="false" />
  1487. <action type="None" />
  1488. </rule>
  1489. <rule name="wordpress - Rule 2" stopProcessing="true">
  1490. <match url="^files/(.+)" ignoreCase="false" />
  1491. <action type="Rewrite" url="wp-includes/ms-files.php?file={R:1}" appendQueryString="false" />
  1492. </rule>
  1493. <rule name="wordpress - Rule 3" stopProcessing="true">
  1494. <match url="^" ignoreCase="false" />
  1495. <conditions logicalGrouping="MatchAny">
  1496. <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" />
  1497. <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" />
  1498. </conditions>
  1499. <action type="None" />
  1500. </rule>
  1501. <rule name="wordpress - Rule 4" stopProcessing="true">
  1502. <match url="." ignoreCase="false" />
  1503. <action type="Rewrite" url="index.php" />
  1504. </rule>';
  1505. } else {
  1506. $rules .= '
  1507. <rule name="…

Large files files are truncated, but you can click here to view the full file