= $q( 'text/html' );
}
/**
* Early template_redirect: stop canonical redirects for .md requests,
* send discovery headers for HTML responses.
*/
public static function early() {
if ( self::$mode ) {
remove_action( 'template_redirect', 'redirect_canonical' );
remove_action( 'template_redirect', 'wp_redirect_admin_locations', 1000 );
if ( ! defined( 'DONOTCACHEPAGE' ) ) {
define( 'DONOTCACHEPAGE', true ); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedConstantFound -- Never let a page cache store Markdown under an HTML key.
}
return;
}
if ( Aeoora_Settings::get( 'markdown', 'negotiation', false ) && is_singular() ) {
header( 'Vary: Accept', false );
}
if ( Aeoora_Settings::get( 'markdown', 'link_header', true ) && is_singular() && ! headers_sent() ) {
$post = get_queried_object();
if ( $post instanceof WP_Post && self::is_eligible( $post ) ) {
header( 'Link: <' . esc_url_raw( self::url( $post ) ) . '>; rel="alternate"; type="text/markdown"', false );
}
}
}
/**
* Serve Markdown at the end of template_redirect.
*/
public static function serve() {
if ( ! self::$mode ) {
return;
}
$md = null;
if ( is_404() ) {
self::send( "# 404\n\n" . __( 'Nothing was found at this address.', 'aeoora' ) . "\n", 404, home_url( '/' ) );
}
if ( is_singular() ) {
$post = get_queried_object();
if ( ! $post instanceof WP_Post || ! self::is_eligible( $post ) ) {
if ( 'accept' === self::$mode ) {
return; // Fall back to HTML silently.
}
self::send( "# 403\n\n" . __( 'A Markdown version of this page is not available.', 'aeoora' ) . "\n", 403, get_permalink( $post ) );
}
$md = self::for_post( $post, ! is_user_logged_in() );
self::send( $md, 200, get_permalink( $post ) );
}
if ( Aeoora_Settings::get( 'markdown', 'archives', true ) && ( is_home() || is_front_page() || is_archive() || is_search() ) ) {
if ( 'accept' === self::$mode ) {
return;
}
self::send( self::for_listing(), 200, self::current_html_url() );
}
if ( 'accept' !== self::$mode ) {
self::send( "# 404\n\n" . __( 'No Markdown version is available for this address.', 'aeoora' ) . "\n", 404, home_url( '/' ) );
}
}
/**
* Is the post eligible for a Markdown version?
*
* @param WP_Post $post Post.
* @return bool
*/
public static function is_eligible( $post ) {
$types = (array) Aeoora_Settings::get( 'markdown', 'post_types', array( 'post', 'page' ) );
if ( ! in_array( $post->post_type, $types, true ) ) {
return false;
}
return (bool) apply_filters( 'aeoora_markdown_eligible', Aeoora_Content::is_public( $post, 'markdown' ), $post );
}
/**
* Markdown URL of a post.
*
* @param WP_Post|int $post Post.
* @return string
*/
public static function url( $post ) {
$post = get_post( $post );
$permalink = get_permalink( $post );
if ( ! $permalink ) {
return '';
}
if ( ! get_option( 'permalink_structure' ) || false !== strpos( $permalink, '?' ) ) {
return add_query_arg( 'format', 'markdown', $permalink );
}
if ( 'page' === get_option( 'show_on_front' ) && (int) get_option( 'page_on_front' ) === (int) $post->ID ) {
return home_url( '/index.md' );
}
return untrailingslashit( $permalink ) . '.md';
}
/**
* in the head.
*/
public static function link_tag() {
if ( ! is_singular() ) {
return;
}
$post = get_queried_object();
if ( $post instanceof WP_Post && self::is_eligible( $post ) ) {
printf( '' . "\n", esc_attr__( 'Markdown version', 'aeoora' ), esc_url( self::url( $post ) ) );
}
}
/**
* Markdown document of a post (cached for anonymous builds).
*
* @param WP_Post $post Post.
* @param bool $use_cache Use / fill the cache.
* @return string
*/
public static function for_post( WP_Post $post, $use_cache = true ) {
$hash = self::cache_hash( $post );
if ( $use_cache ) {
$cached = Aeoora_Cache::get( 'md', (string) $post->ID );
if ( is_array( $cached ) && isset( $cached['h'], $cached['md'] ) && $cached['h'] === $hash ) {
return (string) $cached['md'];
}
}
$md = self::build_post( $post, $use_cache );
if ( $use_cache ) {
Aeoora_Cache::set(
'md',
(string) $post->ID,
array(
'h' => $hash,
'md' => $md,
),
12 * HOUR_IN_SECONDS
);
}
return $md;
}
/**
* Body only (no frontmatter), used by llms-full.txt. Cached like the
* document, so rebuilding llms-full.txt only renders changed pages.
*
* @param WP_Post $post Post.
* @param bool $use_cache Use / fill the cache (anonymous builds only).
* @return string
*/
public static function body( WP_Post $post, $use_cache = true ) {
$hash = $use_cache ? self::cache_hash( $post ) : '';
if ( $use_cache ) {
$cached = Aeoora_Cache::get( 'mdbody', (string) $post->ID );
if ( is_array( $cached ) && isset( $cached['h'], $cached['md'] ) && $cached['h'] === $hash ) {
return (string) $cached['md'];
}
}
$html = Aeoora_Content::render_html( $post );
$md = Aeoora_Html_To_Markdown::convert( $html, get_permalink( $post ) );
if ( $use_cache ) {
Aeoora_Cache::set(
'mdbody',
(string) $post->ID,
array(
'h' => $hash,
'md' => $md,
),
12 * HOUR_IN_SECONDS
);
}
return $md;
}
/**
* Fingerprint of everything a post's Markdown is built from. Includes the
* fields WooCommerce and SEO plugins update without touching the post's
* modified date (price, stock, rating, description), so those never go stale.
*
* @param WP_Post $post Post.
* @return string
*/
private static function cache_hash( WP_Post $post ) {
$meta = array();
foreach ( array( '_price', '_regular_price', '_sale_price', '_stock_status', '_stock', '_wc_average_rating', '_wc_review_count', '_thumbnail_id', '_aeoora_tldr', '_aeoora_faq' ) as $key ) {
$meta[] = get_post_meta( $post->ID, $key, false );
}
$meta[] = Aeoora_Seo::get_description( $post->ID );
return md5( $post->post_modified_gmt . '|' . AEOORA_VERSION . '|' . wp_json_encode( Aeoora_Settings::get( 'markdown' ) ) . '|' . wp_json_encode( $meta ) );
}
/**
* Build the Markdown document for a post.
*
* @param WP_Post $post Post.
* @param bool $use_cache Use the body cache.
* @return string
*/
private static function build_post( WP_Post $post, $use_cache = true ) {
$title = Aeoora_Util::one_line( get_the_title( $post ) );
$desc = Aeoora_Seo::get_description( $post->ID );
if ( '' === $desc ) {
$desc = $post->post_excerpt ? Aeoora_Util::trim_chars( $post->post_excerpt, 200 ) : '';
}
$out = '';
if ( Aeoora_Settings::get( 'markdown', 'frontmatter', true ) ) {
$out .= self::frontmatter( $post, $title, $desc );
}
$out .= '# ' . $title . "\n\n";
$tldr = trim( (string) get_post_meta( $post->ID, '_aeoora_tldr', true ) );
if ( '' !== $tldr ) {
$out .= '> **' . __( 'TL;DR', 'aeoora' ) . ':** ' . Aeoora_Util::one_line( $tldr ) . "\n\n";
} elseif ( '' !== $desc ) {
$out .= '> ' . $desc . "\n\n";
}
$body = self::body( $post, $use_cache );
// The page title is already the H1.
$body = preg_replace( '~^#\s+' . preg_quote( $title, '~' ) . '\s*\n~u', '', ltrim( $body ) );
$out .= trim( (string) $body ) . "\n";
$faq = Aeoora_Schema::get_faq( $post->ID );
if ( $faq && false === stripos( $body, $faq[0]['q'] ) ) {
$out .= "\n## " . __( 'Frequently asked questions', 'aeoora' ) . "\n";
foreach ( $faq as $item ) {
$out .= "\n### " . Aeoora_Util::one_line( $item['q'] ) . "\n\n" . trim( Aeoora_Html_To_Markdown::convert( wpautop( $item['a'] ) ) ) . "\n";
}
}
if ( 'product' === $post->post_type && function_exists( 'wc_get_product' ) ) {
$out .= self::product_facts( $post );
}
$out .= "\n---\n\n" . sprintf(
/* translators: 1: page URL, 2: site name. */
__( 'Source: %1$s · %2$s', 'aeoora' ),
get_permalink( $post ),
get_bloginfo( 'name' )
) . "\n";
return (string) apply_filters( 'aeoora_post_markdown', $out, $post );
}
/**
* YAML frontmatter.
*
* @param WP_Post $post Post.
* @param string $title Title.
* @param string $desc Description.
* @return string
*/
private static function frontmatter( WP_Post $post, $title, $desc ) {
$lines = array( '---' );
$lines[] = 'title: ' . Aeoora_Util::yaml( $title );
if ( '' !== $desc ) {
$lines[] = 'description: ' . Aeoora_Util::yaml( $desc );
}
$lines[] = 'url: ' . get_permalink( $post );
$lines[] = 'type: ' . $post->post_type;
$lines[] = 'published: ' . get_post_time( 'c', true, $post );
$lines[] = 'updated: ' . get_post_modified_time( 'c', true, $post );
$author = get_the_author_meta( 'display_name', $post->post_author );
if ( $author ) {
$lines[] = 'author: ' . Aeoora_Util::yaml( $author );
}
$lang = get_bloginfo( 'language' );
if ( $lang ) {
$lines[] = 'language: ' . $lang;
}
foreach ( array(
'category' => 'categories',
'post_tag' => 'tags',
) as $tax => $label ) {
if ( ! is_object_in_taxonomy( $post->post_type, $tax ) ) {
continue;
}
$terms = get_the_terms( $post, $tax );
if ( $terms && ! is_wp_error( $terms ) ) {
$lines[] = $label . ': [' . implode( ', ', array_map( array( 'Aeoora_Util', 'yaml' ), wp_list_pluck( $terms, 'name' ) ) ) . ']';
}
}
$thumb = get_the_post_thumbnail_url( $post, 'large' );
if ( $thumb ) {
$lines[] = 'image: ' . $thumb;
}
$lines[] = '---';
return implode( "\n", $lines ) . "\n\n";
}
/**
* WooCommerce product facts.
*
* @param WP_Post $post Post.
* @return string
*/
private static function product_facts( WP_Post $post ) {
$product = wc_get_product( $post->ID );
if ( ! $product ) {
return '';
}
$facts = array();
$price = $product->get_price();
if ( '' !== $price ) {
$facts[] = '- **' . __( 'Price', 'aeoora' ) . ':** ' . wp_strip_all_tags( wc_price( $price ) ) . ( function_exists( 'get_woocommerce_currency' ) ? ' (' . get_woocommerce_currency() . ')' : '' );
}
if ( $product->get_sku() ) {
$facts[] = '- **SKU:** ' . $product->get_sku();
}
$facts[] = '- **' . __( 'Availability', 'aeoora' ) . ':** ' . ( $product->is_in_stock() ? __( 'In stock', 'aeoora' ) : __( 'Out of stock', 'aeoora' ) );
if ( $product->get_review_count() ) {
$facts[] = '- **' . __( 'Rating', 'aeoora' ) . ':** ' . $product->get_average_rating() . '/5 (' . $product->get_review_count() . ')';
}
foreach ( $product->get_attributes() as $attr ) {
if ( is_object( $attr ) && method_exists( $attr, 'get_name' ) && $attr->get_visible() ) {
$facts[] = '- **' . wc_attribute_label( $attr->get_name() ) . ':** ' . implode( ', ', $attr->is_taxonomy() ? wc_get_product_terms( $post->ID, $attr->get_name(), array( 'fields' => 'names' ) ) : $attr->get_options() );
}
}
return "\n## " . __( 'Product details', 'aeoora' ) . "\n\n" . implode( "\n", $facts ) . "\n";
}
/**
* Markdown for the home page / archives / search.
*
* @return string
*/
private static function for_listing() {
global $wp_query;
if ( is_front_page() && is_home() ) {
$title = get_bloginfo( 'name' );
$desc = get_bloginfo( 'description' );
} elseif ( is_home() ) {
$title = get_the_title( (int) get_option( 'page_for_posts' ) );
$desc = '';
} elseif ( is_search() ) {
/* translators: %s: search query. */
$title = sprintf( __( 'Search results for “%s”', 'aeoora' ), get_search_query() );
$desc = '';
} else {
$title = wp_strip_all_tags( get_the_archive_title() );
$desc = wp_strip_all_tags( get_the_archive_description() );
}
$out = '# ' . Aeoora_Util::one_line( $title ) . "\n\n";
if ( $desc ) {
$out .= '> ' . Aeoora_Util::one_line( $desc ) . "\n\n";
}
if ( is_front_page() && Aeoora_Settings::get( 'llms', 'enabled', true ) ) {
/* translators: %s: llms.txt URL. */
$out .= sprintf( __( 'Site guide for language models: %s', 'aeoora' ), home_url( '/llms.txt' ) ) . "\n\n";
}
if ( ! empty( $wp_query->posts ) ) {
foreach ( $wp_query->posts as $p ) {
if ( ! Aeoora_Content::is_public( $p ) ) {
continue;
}
$excerpt = Aeoora_Seo::get_description( $p->ID );
if ( '' === $excerpt ) {
$excerpt = wp_trim_words( wp_strip_all_tags( $p->post_excerpt ? $p->post_excerpt : strip_shortcodes( $p->post_content ) ), 30, '…' );
}
$link = self::is_eligible( $p ) ? self::url( $p ) : get_permalink( $p );
$out .= '- [' . Aeoora_Util::one_line( get_the_title( $p ) ) . '](' . $link . ')' . ( $excerpt ? ': ' . Aeoora_Util::one_line( $excerpt ) : '' ) . "\n";
}
}
$next = get_next_posts_page_link();
if ( $next && $wp_query->max_num_pages > max( 1, (int) get_query_var( 'paged' ) ) ) {
$out .= "\n[" . __( 'Next page', 'aeoora' ) . '](' . add_query_arg( 'format', 'markdown', $next ) . ")\n";
}
return $out;
}
/**
* HTML URL of the current request.
*
* @return string
*/
private static function current_html_url() {
$uri = '' !== self::$stripped_uri ? self::$stripped_uri : Aeoora_Util::request_uri();
$path = (string) wp_parse_url( remove_query_arg( 'format', $uri ), PHP_URL_PATH );
return Aeoora_Util::origin() . ( '' !== $path ? $path : '/' );
}
/**
* Output a Markdown response and stop.
*
* @param string $md Markdown.
* @param int $status HTTP status.
* @param string $canonical Canonical HTML URL.
*/
private static function send( $md, $status, $canonical ) {
Aeoora_Tracker::set_resource( 'md' );
if ( ! headers_sent() ) {
status_header( $status );
header( 'Content-Type: text/markdown; charset=utf-8' );
header( 'X-Content-Type-Options: nosniff' );
header( 'X-Markdown-Tokens: ' . (int) ceil( mb_strlen( $md ) / 4 ) );
if ( $canonical ) {
header( 'Link: <' . esc_url_raw( $canonical ) . '>; rel="canonical"' );
}
if ( Aeoora_Settings::get( 'llms', 'enabled', true ) ) {
header( 'Link: <' . esc_url_raw( home_url( '/llms.txt' ) ) . '>; rel="describedby"', false );
}
header( 'X-Robots-Tag: noindex, follow' );
if ( 'accept' === self::$mode ) {
header( 'Vary: Accept' );
header( 'Cache-Control: private, max-age=300' );
} elseif ( is_user_logged_in() ) {
header( 'Cache-Control: private, no-store' );
} else {
header( 'Cache-Control: public, max-age=3600' );
}
}
echo $md; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- text/markdown body built from sanitized content.
exit;
}
/**
* Drop cached Markdown when a post changes.
*
* @param int $post_id Post ID.
* @param bool $render_cache Also drop the cached rendered page.
*/
public static function flush_post( $post_id, $render_cache = true ) {
$post_id = (int) $post_id;
if ( $post_id <= 0 || wp_is_post_revision( $post_id ) ) {
return;
}
Aeoora_Cache::delete( 'md', (string) $post_id );
Aeoora_Cache::delete( 'mdbody', (string) $post_id );
$url = $render_cache ? get_permalink( $post_id ) : '';
if ( $url ) {
Aeoora_Cache::delete( 'render', $url );
}
}
/**
* After WordPress parsed the stripped URI, put the real one back so other
* plugins (redirect managers, 404 loggers, audit logs) see /page.md.
*/
public static function restore_uri() {
if ( 'md' === self::$mode && '' !== self::$original_uri ) {
self::$stripped_uri = Aeoora_Util::request_uri();
$_SERVER['REQUEST_URI'] = self::$original_uri; // Sanitized in intercept() (esc_url_raw).
do_action( 'aeoora_markdown_request', self::$stripped_uri );
}
}
}