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
3 changes: 3 additions & 0 deletions readme.txt
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,9 @@ Yes, as an opt-in. With `add_filter( 'markdown_alternate_skip_noindexed', '__ret
== Changelog ==

= Unreleased =
* Fixed cover block images running into the first inner heading
* Omitted aria-hidden and data-URI images from Markdown
* Preserved iframe embeds as links instead of dropping their content
* Added Markdown versions of category and tag archives, and of WooCommerce product category, tag and brand archives
* Changed frontmatter links to terms of taxonomies that are not served to point to their HTML archive instead of a `.md` URL that returned 404
* Changed frontmatter links to terms to absolute URLs, like the links in the body
Expand Down
56 changes: 56 additions & 0 deletions src/Converter/EmbedConverter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
<?php // phpcs:ignore WordPress.Files.FileName -- PSR-4 class filename.
/**
* Link fallback for iframe embeds.
*
* @package MarkdownAlternate
*/

namespace MarkdownAlternate\Converter;

use League\HTMLToMarkdown\Converter\ConverterInterface;
use League\HTMLToMarkdown\ElementInterface;

/**
* Preserve an embed's destination without emitting executable iframe markup.
*/
class EmbedConverter implements ConverterInterface {

/**
* Convert an iframe to a link using its source and optional title.
*
* @param ElementInterface $element Iframe element.
* @return string Markdown link or an empty string without a usable source.
*/
public function convert( ElementInterface $element ): string {
$url = trim( html_entity_decode( $element->getAttribute( 'src' ), ENT_QUOTES | ENT_HTML5, 'UTF-8' ) );
if ( ! preg_match( '~^(?:https?://|/|\.\.?/)~i', $url ) || preg_match( '/[\x00-\x1f\x7f]/', $url ) ) {
return '';
}

// Encode characters that would terminate a Markdown link destination.
$url = str_replace(
array( ' ', '(', ')', '<', '>', '\\' ),
array( '%20', '%28', '%29', '%3C', '%3E', '%5C' ),
$url
);
$title = trim( (string) preg_replace( '/\s+/u', ' ', html_entity_decode( $element->getAttribute( 'title' ), ENT_QUOTES | ENT_HTML5, 'UTF-8' ) ) );
if ( '' === $title ) {
$title = $url;
}
$title = str_replace(
array( '\\', '[', ']', '*', '_', '`', '<', '>' ),
array( '\\\\', '\\[', '\\]', '\\*', '\\_', '\\`', '\\<', '\\>' ),
$title
);
return '[' . $title . '](' . $url . ")\n\n";
}

/**
* Tags converted by this fallback.
*
* @return string[] Supported tags.
*/
public function getSupportedTags(): array { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid -- Library interface.
return array( 'iframe' );
}
}
41 changes: 41 additions & 0 deletions src/Converter/ImageConverter.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php // phpcs:ignore WordPress.Files.FileName -- PSR-4 class filename.
/**
* Image conversion for visible content and WordPress cover blocks.
*
* @package MarkdownAlternate
*/

namespace MarkdownAlternate\Converter;

use League\HTMLToMarkdown\Converter\ImageConverter as BaseImageConverter;
use League\HTMLToMarkdown\ElementInterface;

/**
* Omit decorative image payloads and keep cover backgrounds block-separated.
*/
class ImageConverter extends BaseImageConverter {

/**
* Convert a visible image while preserving the library's inline formatting.
*
* @param ElementInterface $element Image element.
* @return string Markdown image, or an empty string for an omitted image.
*/
public function convert( ElementInterface $element ): string {
if ( 0 === stripos( ltrim( $element->getAttribute( 'src' ) ), 'data:' ) ) {
return '';
}
for ( $ancestor = $element; null !== $ancestor; $ancestor = $ancestor->getParent() ) {
if ( 'true' === strtolower( trim( $ancestor->getAttribute( 'aria-hidden' ) ) ) ) {
return '';
}
}

$markdown = parent::convert( $element );
// Cover backgrounds precede a div of inner blocks without a wrapping paragraph.
if ( preg_match( '/(?:^|\s)wp-block-cover__image-background(?:\s|$)/', $element->getAttribute( 'class' ) ) ) {
$markdown .= "\n\n";
}
return $markdown;
}
}
4 changes: 3 additions & 1 deletion src/Converter/MarkdownConverter.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public function __construct() {
$this->converter = new HtmlConverter([
'header_style' => 'atx',
'strip_tags' => true,
'remove_nodes' => 'script style iframe',
'remove_nodes' => 'script style',
'hard_break' => false,
'list_item_style' => '-',
]);
Expand All @@ -49,6 +49,8 @@ public function __construct() {
// The library already ships table_pipe_escape and table_caption_side
// defaults for this converter — only the registration is missing.
$this->converter->getEnvironment()->addConverter( new TableConverter() );
$this->converter->getEnvironment()->addConverter( new ImageConverter() );
$this->converter->getEnvironment()->addConverter( new EmbedConverter() );
}

/**
Expand Down
2 changes: 1 addition & 1 deletion src/Output/ContentRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class ContentRenderer {
*
* @var int
*/
private const CACHE_SCHEMA = 1;
private const CACHE_SCHEMA = 2;

/**
* The HTML to Markdown converter.
Expand Down
80 changes: 80 additions & 0 deletions tests/conversion.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
<?php
/**
* WordPress block conversion regressions, loaded by tests/run.php.
*
* @package MarkdownAlternate
*/

use MarkdownAlternate\Converter\MarkdownConverter;
use MarkdownAlternate\Output\ContentRenderer;

$md_alt_tests['Cover images and inner headings remain separate blocks'] = static function () {
$html = '<div class="wp-block-cover"><img class="wp-block-cover__image-background" src="https://example.com/cover.jpg" alt="Cover"><div class="wp-block-cover__inner-container"><h1>Heading</h1></div></div>';
md_alt_assert_same( "![Cover](https://example.com/cover.jpg)\n\n# Heading", ( new MarkdownConverter() )->convert( $html ) );
};

$md_alt_tests['Visible inline images retain alt text, titles and inline spacing'] = static function () {
$html = '<p>Before <img src="https://example.com/icon.png" alt="Icon" title="A title"> after.</p><p><img src="/image.png" alt=""></p>';
md_alt_assert_same( "Before ![Icon](https://example.com/icon.png \"A title\") after.\n\n![](/image.png)", ( new MarkdownConverter() )->convert( $html ) );
};

$md_alt_tests['Images hidden on themselves or any ancestor are omitted without removing text'] = static function () {
$html = '<p>Keep <img aria-hidden="true" src="/hidden.png" alt="Hidden">text.</p><div aria-hidden="true">Keep this text<span><img aria-hidden="false" src="/ancestor.png" alt="Hidden by ancestor"></span></div><p><img aria-hidden="false" src="/visible.png" alt="Visible"></p>';
md_alt_assert_same( "Keep text.\n\nKeep this text\n\n![Visible](/visible.png)", ( new MarkdownConverter() )->convert( $html ) );
};

$md_alt_tests['Data URI images are omitted regardless of case or leading whitespace'] = static function () {
foreach ( array( 'data:image/png;base64,AAAA', ' DATA:image/svg+xml;base64,BBBB' ) as $src ) {
md_alt_assert_same( 'Text', ( new MarkdownConverter() )->convert( '<p>Text<img src="' . $src . '" alt="Inline bytes"></p>' ) );
}
};

$md_alt_tests['Iframe-only embed blocks retain a titled link and their caption'] = static function () {
$html = '<figure class="wp-block-embed"><div class="wp-block-embed__wrapper"><iframe src="https://example.com/embed/video" title="Video title"></iframe></div><figcaption>A caption</figcaption></figure>';
// Nested block wrappers may contribute additional blank lines.
$output = preg_replace( '/\n{3,}/', "\n\n", ( new MarkdownConverter() )->convert( $html ) );
md_alt_assert_same( "[Video title](https://example.com/embed/video)\n\nA caption", $output );
};

$md_alt_tests['Untitled embeds keep their URL and remain separated from surrounding text'] = static function () {
md_alt_assert_same( "Before\n\n[https://example.com/video?a=1&b=2](https://example.com/video?a=1&b=2)\n\nAfter", ( new MarkdownConverter() )->convert( '<p>Before</p><iframe src="https://example.com/video?a=1&amp;b=2"></iframe><p>After</p>' ) );
md_alt_assert_contains( '](/local/video)', ( new MarkdownConverter() )->convert( '<iframe src="/local/video" title="Local video"></iframe>' ) );
md_alt_assert_same( '[//example.com/video](//example.com/video)', ( new MarkdownConverter() )->convert( '<iframe src="//example.com/video"></iframe>' ) );
};

$md_alt_tests['Embed attributes cannot introduce executable links or raw HTML'] = static function () {
$converter = new MarkdownConverter();
foreach ( array( 'javascript:alert(1)', 'data:text/html,bad', 'file:///private/file', 'about:blank', 'vbscript:bad' ) as $src ) {
md_alt_assert_same( '', $converter->convert( '<iframe src="' . $src . '"></iframe>' ) );
}
md_alt_assert_same( '', $converter->convert( '<iframe srcdoc="&lt;script&gt;alert(1)&lt;/script&gt;"></iframe><script>alert(1)</script><style>bad</style>' ) );
$output = $converter->convert( '<iframe src="https://example.com/a(b) c" title="A [title] &lt;tag&gt;"></iframe>' );
md_alt_assert_same( '[A \\[title\\] \\<tag\\>](https://example.com/a%28b%29%20c)', $output );
};

$md_alt_tests['Image and iframe code examples remain literal code'] = static function () {
$html = '<pre><code>&lt;img src="data:image/png;base64,AAAA"&gt;\n&lt;iframe src="https://example.com/embed"&gt;&lt;/iframe&gt;</code></pre>';
$output = ( new MarkdownConverter() )->convert( $html );
md_alt_assert_contains( '<img src="data:image/png;base64,AAAA">', $output );
md_alt_assert_contains( '<iframe src="https://example.com/embed"></iframe>', $output );
};

$md_alt_tests['Previously cached conversion output regenerates after the renderer update'] = static function () {
$post = md_alt_test_fixture( 'ordinary' );
$post->post_content = '<iframe src="https://example.com/embed" title="Video"></iframe>';
set_transient(
'md_alt_cache_17',
array(
'markdown' => 'Old output without the embed',
'modified' => $post->post_modified,
'version' => '',
'schema' => 1,
),
DAY_IN_SECONDS
);
$renderer = new ContentRenderer();
$output = $renderer->render( $post );
md_alt_assert_contains( '[Video](https://example.com/embed)', $output );
md_alt_assert_same( $output, $renderer->render( $post ) );
md_alt_assert_same( 1, $GLOBALS['md_alt_test_state']['renders'] );
};
1 change: 1 addition & 0 deletions tests/run.php
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,7 @@ static function () {
};

require __DIR__ . '/security.php';
require __DIR__ . '/conversion.php';

$md_alt_failures = 0;
foreach ( $md_alt_tests as $md_alt_name => $md_alt_test ) {
Expand Down
Loading