PageRenderTime 55ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/wp-includes/rewrite.php

https://gitlab.com/geyson/geyson
PHP | 2326 lines | 834 code | 264 blank | 1228 comment | 178 complexity | d23e5fda4cb1d1e8e041f697018916d0 MD5 | raw file
Possible License(s): LGPL-2.1, GPL-2.0

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

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