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

/wp-includes/rewrite.php

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

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