and
* the script is written to the site root, so browsers show a readable page instead of raw XML.
* Browsers are removing XSLT, so lines (ours or WordPress's) are dropped.
*
* Sitemaps:
* - Sitemaps get the same way (the SEO plugin's
* XSLT line is dropped) and main-sitemap.js is written to the site root.
* - /sitemap.xml can redirect to the sitemap index (sitemap_index.xml or wp-sitemap.xml).
*
* 404 page:
* Many sites redirect missing pages to the home page. For the exporter only, WordPress renders
* the theme's real 404 template before any such redirect can run.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class CFSP_Feeds {
const FEED_JS = 'rss-style.js';
const SITEMAP_JS = 'main-sitemap.js';
const XHTML = 'http://www.w3.org/1999/xhtml';
public static function init() {
add_action( 'template_redirect', array( __CLASS__, 'render_404' ), -1000 );
if ( CFSP_Settings::get( 'feed_no_footer' ) ) {
// Yoast SEO's "The post X appeared first on Y." line after every feed item.
add_filter( 'wpseo_include_rss_footer', '__return_false' );
}
}
/* ------------------------------------------------------------------ *
* 404 page
* ------------------------------------------------------------------ */
/** Exporter requests with ?cfsp_404=1 get the theme's 404 template with a 404 status. */
public static function render_404() {
if ( empty( $_GET['cfsp_404'] ) || ! CFSP_Related::is_export_request() ) { // phpcs:ignore WordPress.Security.NonceVerification
return;
}
global $wp_query;
$wp_query->set_404();
status_header( 404 );
nocache_headers();
$template = get_404_template();
if ( ! $template ) {
$template = get_index_template();
}
$template = apply_filters( 'template_include', $template ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedHooknameFound -- WordPress core filter, applied as core does.
if ( $template ) {
include $template;
exit;
}
}
/** Make sure an exported 404 page is marked noindex and doesn't claim to be another page. */
public static function proper_404( $html ) {
$html = preg_replace( '#]*\brel\s*=\s*["\']?canonical\b[^>]*>\s*#i', '', $html );
$html = preg_replace( '#]*\bproperty\s*=\s*["\']?og:url\b[^>]*>\s*#i', '', $html );
$html = preg_replace( '/([?&](?:amp;)?)cfsp_404=1/', '', $html );
if ( preg_match( '#]*\bname\s*=\s*["\']?robots\b[^>]*>#i', $html ) ) {
$html = preg_replace( '#(]*\bname\s*=\s*["\']?robots\b[^>]*\bcontent\s*=\s*)(["\'])[^"\']*\2#i', '$1$2noindex, follow$2', $html );
} else {
$html = preg_replace( '#
]*>#i', "$0\n", $html, 1 );
}
return $html;
}
/** Used only when the theme's 404 template can't be fetched. */
public static function fallback_404() {
$name = wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES );
$home = CFSP_Settings::url_base() . '/';
$btn = 'display:inline-block;padding:12px 18px;border-radius:8px;border:0;background:#111827;color:#fff;font:inherit;text-decoration:none;cursor:pointer';
return ''
. ''
. 'Page not found | ' . esc_html( $name ) . ''
. ''
. '
404
'
. '
Page not found
'
. '
The page you were looking for doesn\'t exist or has moved.
'
. ''
. 'Back to ' . esc_html( $name ) . '';
}
/* ------------------------------------------------------------------ *
* Feeds
* ------------------------------------------------------------------ */
/** "/feed/" => "/feed.xml", "/category/news/feed" => "/category/news/feed.xml"; null if not a feed. */
public static function feed_file( $rel ) {
if ( CFSP_Settings::get( 'feed_xml' ) && preg_match( '#^(.*/)feed/?$#', $rel, $m ) ) {
return $m[1] . 'feed.xml';
}
return null;
}
public static function is_feed_body( $body ) {
return (bool) preg_match( '#<(rss|feed|rdf:RDF)\b#i', substr( $body, 0, 2000 ) );
}
/** Path prefix of the static site ("" or "/sub"), for root files such as rss-style.js and /font/. */
private static function base_path() {
return rtrim( 'relative' === CFSP_Settings::get( 'url_mode' ) ? (string) CFSP_Settings::get( 'relative_path' ) : '', '/' );
}
/** Feeds: drop XSLT and add the rss-style.js script. */
public static function style( $xml ) {
$xml = self::strip_styling( $xml );
if ( ! CFSP_Settings::get( 'feed_style' ) ) {
return $xml;
}
// RSS allows namespaced extension elements inside ; Atom and RDF take them at the root.
$at = preg_match( '#]*>#i', $xml ) ? ']*>' : '<(?:feed|rdf:RDF)\b[^>]*>';
return self::add_script( $xml, $at, self::base_path() . '/' . self::FEED_JS );
}
public static function is_sitemap_body( $body ) {
return (bool) preg_match( '#<(urlset|sitemapindex)\b#i', substr( $body, 0, 3000 ) );
}
/**
* Sitemaps: drop XSLT and add main-sitemap.js. The src is relative, so it works in a subfolder
* too; sitemaps always live in the site root.
*/
public static function sitemap_style( $xml ) {
$xml = self::strip_styling( $xml );
if ( ! CFSP_Settings::get( 'sitemap_style' ) ) {
return $xml;
}
return self::add_script( $xml, '<(?:urlset|sitemapindex)\b[^>]*>', self::SITEMAP_JS );
}
/**
* Remove lines (browsers are removing XSLT and show a warning for it) and
* any page script a previous export added.
*/
private static function strip_styling( $xml ) {
$out = preg_replace( '#<\?xml-stylesheet\b.*?\?>\s*#is', '', $xml );
$out = null === $out ? $xml : $out;
$re = '#\s*#i';
$res = preg_replace( $re, '', $out );
return null === $res ? $out : $res;
}
/** Insert the page script right after the first tag matching $after (a regex body). */
private static function add_script( $xml, $after, $src ) {
$tag = trim(
wp_get_script_tag(
array(
'xmlns' => self::XHTML,
'src' => $src,
)
)
);
if ( ! preg_match( '#' . $after . '#i', $xml, $m, PREG_OFFSET_CAPTURE ) ) {
return $xml;
}
$pos = $m[0][1] + strlen( $m[0][0] );
return substr( $xml, 0, $pos ) . "\n\t" . $tag . substr( $xml, $pos );
}
/**
* In rewritten HTML/XML: drop tags for feeds that aren't exported
* (e.g. the comments feed), and point every remaining feed link at feed.xml.
*/
public static function convert_links( $content ) {
if ( ! CFSP_Settings::get( 'feed_xml' ) ) {
return $content;
}
$base = CFSP_Settings::url_base();
// Is this href one of our own feed addresses? Returns the source URL or null.
$own = function ( $href ) use ( $base ) {
$href = html_entity_decode( $href, ENT_QUOTES );
if ( '' !== $base && 0 === stripos( $href, $base ) ) {
$path = substr( $href, strlen( $base ) );
} elseif ( '' !== $href && '/' === $href[0] && ( ! isset( $href[1] ) || '/' !== $href[1] ) ) {
$path = $href;
} else {
return null;
}
$path = '' === $path ? '/' : $path;
return preg_match( '#(^|/)feed/?$#', $path ) ? CFSP_Settings::source_url() . ( '/' === $path[0] ? '' : '/' ) . $path : null;
};
// 1) Remove alternate links to feeds that won't exist on the static site.
$content = preg_replace_callback(
'#]*\balternate\b[^>]*>#i',
function ( $m ) use ( $own ) {
if ( ! preg_match( '#\bhref\s*=\s*(?:(["\'])(.*?)\1|([^\s>]+))#i', $m[0], $h ) ) {
return $m[0];
}
$source = $own( isset( $h[3] ) && '' !== $h[3] ? $h[3] : $h[2] );
if ( $source ) {
$url = CFSP_Exporter::normalize( $source );
if ( ! $url || CFSP_Exporter::is_excluded( $url ) ) {
return '';
}
}
return $m[0];
},
$content
);
// 2) Point feed links at feed.xml (quoted and unquoted href values).
$content = preg_replace_callback(
'#(\bhref\s*=\s*)(["\'])([^"\']*)\2#i',
function ( $m ) use ( $own ) {
return $own( $m[3] ) ? $m[1] . $m[2] . preg_replace( '#/feed/?$#', '/feed.xml', $m[3] ) . $m[2] : $m[0];
},
$content
);
return preg_replace_callback(
'#(\bhref\s*=\s*)([^\s"\'>]+)(?=[\s>])#i',
function ( $m ) use ( $own ) {
return $own( $m[2] ) ? $m[1] . preg_replace( '#/feed/?$#', '/feed.xml', $m[2] ) : $m[0];
},
$content
);
}
/**
* Write (or remove) rss-style.js and main-sitemap.js in the export root, with the site's font
* path and the optional extra CSS filled in. Old rss-style.xsl / main-sitemap.xsl files are left
* alone so feeds and sitemaps exported before this version keep working until re-exported.
*/
public static function build() {
$files = array(
self::FEED_JS => array( 'feed_style', 'feed_css' ),
self::SITEMAP_JS => array( 'sitemap_style', 'sitemap_css' ),
);
$flags = JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP;
foreach ( $files as $file => list( $on, $css_key ) ) {
if ( ! CFSP_Settings::get( $on ) ) {
CFSP_Exporter::delete_file( $file );
continue;
}
$js = (string) file_get_contents( CFSP_DIR . 'assets/' . $file );
$js = str_replace(
array( "'__CFSP_FONT_BASE__'", "'__CFSP_EXTRA_CSS__'" ),
array( wp_json_encode( self::base_path() . '/font/', $flags ), wp_json_encode( trim( (string) CFSP_Settings::get( $css_key ) ), $flags ) ),
$js
);
CFSP_Exporter::write_file( $file, $js );
}
}
/** The exported sitemap index /sitemap.xml should redirect to, or null. */
public static function sitemap_index() {
$dir = trailingslashit( CFSP_Settings::export_dir() );
foreach ( array( 'sitemap_index.xml', 'wp-sitemap.xml' ) as $index ) {
if ( is_file( $dir . $index ) ) {
return $index;
}
}
return null;
}
/** Redirect old feed addresses to feed.xml, and /sitemap.xml to the sitemap index. */
public static function redirect_lines() {
$lines = array();
if ( CFSP_Settings::get( 'feed_xml' ) && CFSP_Settings::crawler( 'feeds' ) ) {
$lines = array(
'/feed /feed.xml 301',
'/feed/ /feed.xml 301',
'/:a/feed /:a/feed.xml 301',
'/:a/feed/ /:a/feed.xml 301',
'/:a/:b/feed /:a/:b/feed.xml 301',
'/:a/:b/feed/ /:a/:b/feed.xml 301',
);
}
$index = CFSP_Settings::get( 'sitemap_redirect' ) ? self::sitemap_index() : null;
if ( $index ) {
$lines[] = '/sitemap.xml /' . $index . ' 301';
}
return $lines;
}
/** _headers rules so browsers run the page scripts (nosniff needs a JavaScript content type). */
public static function header_rules() {
$out = '';
if ( CFSP_Settings::get( 'feed_style' ) ) {
$out .= '/' . self::FEED_JS . "\n Content-Type: text/javascript; charset=utf-8\n";
}
if ( CFSP_Settings::get( 'sitemap_style' ) ) {
$out .= '/' . self::SITEMAP_JS . "\n Content-Type: text/javascript; charset=utf-8\n";
}
return $out;
}
}