Files
Nicolas Grekas 84982072c7 Fix XSS by adjusting is_safe annotation on HTML-emitting filters
The `html_to_markdown` filter emits plain Markdown text, so the
`is_safe` annotation is dropped entirely and autoescape now handles
its output according to the surrounding context.

The `markdown_to_html` and `inline_css` filters emit HTML, not text
safe in every escaping context, so `is_safe => ['all']` produced
unescaped HTML when their output was interpolated into a JS, CSS or
URL context. The annotation is now `is_safe => ['html']`.
2026-05-15 15:14:02 +02:00

52 lines
1.4 KiB
PHP

<?php
/*
* This file is part of Twig.
*
* (c) Fabien Potencier
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Twig\Extra\Markdown;
use League\HTMLToMarkdown\HtmlConverter;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;
final class MarkdownExtension extends AbstractExtension
{
public function getFilters(): array
{
return [
new TwigFilter('markdown_to_html', ['Twig\\Extra\\Markdown\\MarkdownRuntime', 'convert'], ['is_safe' => ['html']]),
new TwigFilter('html_to_markdown', [self::class, 'htmlToMarkdown']),
];
}
/**
* @internal
*/
public static function htmlToMarkdown(string $body, array $options = []): string
{
static $converters;
if (!class_exists(HtmlConverter::class)) {
throw new \LogicException('You cannot use the "html_to_markdown" filter as league/html-to-markdown is not installed; try running "composer require league/html-to-markdown".');
}
$options += [
'hard_break' => true,
'strip_tags' => true,
'remove_nodes' => 'head style',
];
if (!isset($converters[$key = serialize($options)])) {
$converters[$key] = new HtmlConverter($options);
}
return $converters[$key]->convert($body);
}
}