Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 20 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ add_filter( 'markdown_alternate_supported_post_types', function( $types ) {

### Adjust cache duration

Markdown output is cached using transients for 24 hours by default. You can change that with `markdown_alternate_cache_expiration`:
Eligible anonymous Markdown output is cached using transients for 24 hours by default. You can change that with `markdown_alternate_cache_expiration`:

```php
add_filter( 'markdown_alternate_cache_expiration', function( $seconds ) {
Expand Down Expand Up @@ -301,8 +301,17 @@ default value.
Return `false` from `markdown_alternate_cache_enabled` to bypass both transient
reads and writes. The filter receives the `WP_Post` as its second argument. HTTP
responses also send private, no-store headers and mark the page as uncacheable.
The WooCommerce integration disables this cache for products; posts and pages
still default to cached output.
Logged-in visitors, password-protected posts, and visitors carrying WordPress
post-password, WooCommerce session/cart, or Easy Digital Downloads cart cookies
always bypass shared caching. The filter cannot turn caching back on for them.
The WooCommerce integration also disables caching for all products. Other
anonymous requests still use the shared cache; use this filter for custom
sessions or other visitor-dependent output.

Markdown response handlers run at `template_redirect` priority 15, after the
default-priority access checks and canonical redirects. Explicit `.md` URLs
still skip canonical redirects; `?format=markdown` and Accept-negotiated requests
can be normalized first. Access checks on this hook must run before priority 15.

### Invalidate integration data

Expand All @@ -319,15 +328,20 @@ add_filter( 'markdown_alternate_cache_version', function( $version, $post ) {

Append your token to the existing value so multiple integrations can participate.
The token is stored with the cached document; it does not change the transient key.
Old cache entries without a version token are regenerated once. Cache duration
continues to use `markdown_alternate_cache_expiration`.
Old cache entries without the current cache schema are regenerated once, even
when an integration's version token still matches, so previously cached personal
output is not reused. Cache duration continues to use
`markdown_alternate_cache_expiration`.

### Run renderer regression tests

Run `php tests/run.php` after installing dependencies. These standalone tests use
WordPress API doubles and the real Markdown converter, and compare default output
with fixtures captured from `main` at commit `7afba03`. CI runs them on PHP 7.4–8.3;
they do not replace a full WordPress integration test.
they do not replace a full WordPress integration test. The suite also checks
visitor isolation, old-cache invalidation, private response headers, access-check
ordering, and canonical redirects. Router cases run in child PHP processes so
the real handlers can terminate their responses normally.

### Run WooCommerce integration tests

Expand Down
5 changes: 4 additions & 1 deletion readme.txt
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ Example:

= Is the output cached? =

Yes. Markdown output is cached using WordPress transients for 24 hours by default. The cache is automatically bypassed if the post has changed. Developers can adjust the cache duration with the `markdown_alternate_cache_expiration` filter.
Yes. Eligible anonymous Markdown output is cached using WordPress transients for 24 hours by default. Logged-in visitors, password-protected posts, and visitors with known session or cart cookies bypass shared caching and receive private, no-store responses. Old cache entries are regenerated after the cache-isolation fix. The cache is also regenerated if the post has changed. Developers can adjust the duration with `markdown_alternate_cache_expiration` and disable caching for custom visitor-dependent output with `markdown_alternate_cache_enabled`.

= What does the Markdown output include? =

Expand All @@ -108,6 +108,9 @@ Yes, as an opt-in. With `add_filter( 'markdown_alternate_skip_noindexed', '__ret
* Changed frontmatter links to terms to absolute URLs, like the links in the body
* Added product URL, modified date, GTIN, sale end date and ratings to WooCommerce product frontmatter
* Removed the post author from WooCommerce product frontmatter
* Prevented visitor-specific Markdown from entering shared caches and invalidated previously generated entries
* Moved Markdown response handlers after default-priority access checks and canonical redirects
* Added cache-isolation, response-header, and routing-order regression tests

= 1.2.0 =
* Added WooCommerce product metadata, formatted prices, short descriptions, visible attributes, and variations
Expand Down
72 changes: 72 additions & 0 deletions src/Output/CachePolicy.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php // phpcs:ignore WordPress.Files.FileName -- PSR-4 class filename.
/**
* Shared cache eligibility for rendered Markdown and HTTP responses.
*
* @package MarkdownAlternate
*/

namespace MarkdownAlternate\Output;

use WP_Post;

/**
* Keep visitor-specific output out of caches shared with other visitors.
*/
class CachePolicy {

/**
* Whether this request can use shared caches for a post.
*
* @param WP_Post $post The post being rendered.
* @return bool Whether shared caching is safe for this request.
*/
public static function is_enabled( WP_Post $post ): bool {
if ( ! self::is_public_request() || '' !== $post->post_password ) {
return false;
}

/**
* Filters whether otherwise eligible output can use shared caching.
*
* Disable for custom sessions or other visitor-dependent content.
* The HTTP router also uses this to send private, no-store headers.
* Logged-in visitors, password-protected posts and known session
* cookies always bypass caching, regardless of this filter.
*
* @since 1.2.0
*
* @param bool $enabled Whether output may be cached. Default true.
* @param WP_Post $post The post being rendered.
*/
return (bool) apply_filters( 'markdown_alternate_cache_enabled', true, $post );
}

/**
* Whether a post or archive request has no known visitor-specific state.
*
* @return bool Whether the request is eligible for shared caching.
*/
public static function is_public_request(): bool {
if ( is_user_logged_in() ) {
return false;
}

// Guest sessions can personalize ordinary posts and pages too.
$session_cookies = array(
'wp-postpass_',
'wp_woocommerce_session_',
'woocommerce_items_in_cart',
'woocommerce_cart_hash',
'edd_items_in_cart',
);
foreach ( array_keys( $_COOKIE ) as $name ) {
foreach ( $session_cookies as $prefix ) {
if ( 0 === strpos( (string) $name, $prefix ) ) {
return false;
}
}
}

return true;
}
}
24 changes: 11 additions & 13 deletions src/Output/ContentRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@
*/
class ContentRenderer {

/**
* Cache schema; older entries may contain another visitor's output.
*
* @var int
*/
private const CACHE_SCHEMA = 1;

/**
* The HTML to Markdown converter.
*
Expand All @@ -45,18 +52,7 @@ public function __construct() {
*/
public function render( WP_Post $post ): string {
$transient_key = 'md_alt_cache_' . $post->ID;
/**
* Filters whether rendered output can use shared caching.
*
* Disable for content whose output depends on the current customer.
* The HTTP router also uses this to send private, no-store headers.
*
* @since 1.2.0
*
* @param bool $enabled Whether output may be cached. Default true.
* @param WP_Post $post The post being rendered.
*/
$cache_enabled = (bool) apply_filters( 'markdown_alternate_cache_enabled', true, $post );
$cache_enabled = CachePolicy::is_enabled( $post );
$cached_data = $cache_enabled ? get_transient( $transient_key ) : false;

/**
Expand All @@ -74,7 +70,8 @@ public function render( WP_Post $post ): string {
$cache_version = (string) apply_filters( 'markdown_alternate_cache_version', '', $post );

if ( is_array( $cached_data )
&& isset( $cached_data['markdown'], $cached_data['modified'], $cached_data['version'] )
&& isset( $cached_data['markdown'], $cached_data['modified'], $cached_data['version'], $cached_data['schema'] )
&& self::CACHE_SCHEMA === $cached_data['schema']
&& $post->post_modified === $cached_data['modified']
&& $cache_version === $cached_data['version']
) {
Expand Down Expand Up @@ -149,6 +146,7 @@ public function render( WP_Post $post ): string {
set_transient(
$transient_key,
array(
'schema' => self::CACHE_SCHEMA,
'markdown' => $output,
'modified' => $post->post_modified,
'version' => $cache_version,
Expand Down
14 changes: 8 additions & 6 deletions src/Router/RewriteHandler.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
use WP_Term;
use MarkdownAlternate\Output\ContentRenderer;
use MarkdownAlternate\Output\TermRenderer;
use MarkdownAlternate\Output\CachePolicy;
use MarkdownAlternate\PostTypeSupport;
use MarkdownAlternate\TaxonomySupport;

Expand Down Expand Up @@ -52,10 +53,11 @@ public function register(): void {
add_action('parse_request', [$this, 'parse_markdown_url']);
// Prevent canonical redirect for .md URLs
add_filter('redirect_canonical', [$this, 'prevent_markdown_redirect'], 10, 2);
// Order: format parameter -> Accept negotiation -> markdown request (URL wins first)
add_action('template_redirect', [$this, 'handle_format_parameter'], 1);
add_action('template_redirect', [$this, 'handle_accept_negotiation'], 1);
add_action('template_redirect', [$this, 'handle_markdown_request'], 1);
// Run after default-priority access checks and canonical redirects.
// Keep format -> Accept -> .md ordering; explicit .md URLs win.
add_action( 'template_redirect', array( $this, 'handle_format_parameter' ), 15 );
add_action( 'template_redirect', array( $this, 'handle_accept_negotiation' ), 15 );
add_action( 'template_redirect', array( $this, 'handle_markdown_request' ), 15 );
}

/**
Expand Down Expand Up @@ -263,7 +265,7 @@ private function serve_term_response( WP_Term $term ): void {
* @param bool $enabled Whether output may be cached. Default true.
* @param WP_Term $term The term being served.
*/
if ( ! apply_filters( 'markdown_alternate_term_cache_enabled', true, $term ) ) {
if ( ! CachePolicy::is_public_request() || ! apply_filters( 'markdown_alternate_term_cache_enabled', true, $term ) ) {
nocache_headers();
header( 'Cache-Control: private, no-store, no-cache, must-revalidate, max-age=0' );
if ( ! defined( 'DONOTCACHEPAGE' ) ) {
Expand Down Expand Up @@ -342,7 +344,7 @@ private function serve_markdown_response(WP_Post $post): void {
}

// Keep customer-dependent output out of HTTP and WordPress page caches too.
if ( ! apply_filters( 'markdown_alternate_cache_enabled', true, $post ) ) {
if ( ! CachePolicy::is_enabled( $post ) ) {
nocache_headers();
header( 'Cache-Control: private, no-store, no-cache, must-revalidate, max-age=0' );
if ( ! defined( 'DONOTCACHEPAGE' ) ) {
Expand Down
21 changes: 21 additions & 0 deletions tests/bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ class WP_Post {
public $post_title = 'Post Title';
public $post_content = '<p>Hello <strong>world</strong>.</p>';
public $post_type = 'post';
public $post_password = '';
}

class WP_Term {
Expand All @@ -32,7 +33,9 @@ class WP_Error {}
define( 'DAY_IN_SECONDS', 86400 );

function md_alt_test_reset() {
$_COOKIE = array();
$GLOBALS['md_alt_test_state'] = array(
'logged_in' => false,
'filters' => array(),
'cache' => array(),
'expiration' => array(),
Expand All @@ -47,6 +50,24 @@ function md_alt_test_reset() {
);
}

function is_user_logged_in() {
return $GLOBALS['md_alt_test_state']['logged_in'];
}

function add_action( $tag, $callback, $priority = 10, $accepted_args = 1 ) {
add_filter( $tag, $callback, $priority, $accepted_args );
}

function do_action( $tag, ...$args ) {
$priorities = $GLOBALS['md_alt_test_state']['filters'][ $tag ] ?? array();
ksort( $priorities );
foreach ( $priorities as $callbacks ) {
foreach ( $callbacks as list( $callback, $accepted_args ) ) {
$callback( ...array_slice( $args, 0, $accepted_args ) );
}
}
}

function get_post( $post ) {
return $post instanceof WP_Post ? $post : ( $GLOBALS['md_alt_test_state']['posts'][ $post ] ?? null );
}
Expand Down
Loading
Loading