Files
plugi/extensions/plugi-ext-blog/admin/Classes/PostContentRenderer.php
T
deepDiverPaul 8ebed89e73 feat(ext-blog): Add syntax highlighting for code blocks
Added language-specific syntax highlighting support to the markdown editor and preview. New code-highlighter assets are registered for public pages and admin headers. The PostContentRenderer detects language identifiers in code fences to apply appropriate CSS classes for highlighting. Tests verify the highlighting works correctly and unsafe content is escaped properly.
2026-12-02 11:09:09 +01:00

186 lines
7.6 KiB
PHP

<?php
namespace Plugi\Extensions\Blog;
class PostContentRenderer
{
// shortcut: supports basic Markdown blocks and inline syntax; use a maintained parser if authors need advanced Markdown.
public function render(string $markdown): string
{
$blocks = [];
$paragraph = [];
$listType = null;
$listItems = [];
$quote = [];
$flush = function () use (&$blocks, &$paragraph, &$listType, &$listItems, &$quote): void {
if ($paragraph !== []) {
$blocks[] = '<p>' . nl2br($this->renderInline(implode("\n", $paragraph))) . '</p>';
$paragraph = [];
}
if ($listType !== null) {
$class = $listType === 'ul' ? 'list-disc' : 'list-decimal';
$items = array_map(fn(string $item): string => '<li>' . $this->renderInline($item) . '</li>', $listItems);
$blocks[] = '<' . $listType . ' class="' . $class . ' space-y-1 pl-6">' . implode('', $items) . '</' . $listType . '>';
$listType = null;
$listItems = [];
}
if ($quote !== []) {
$blocks[] = '<blockquote class="border-l-4 border-base-300 pl-4 text-base-content/80"><p>' . nl2br($this->renderInline(implode("\n", $quote))) . '</p></blockquote>';
$quote = [];
}
};
$fence = null;
$fenceLanguage = null;
$codeLines = [];
foreach (preg_split('/\R/', $markdown) ?: [] as $line) {
if ($fence !== null) {
if (preg_match('/^ {0,3}(`{3,}|~{3,})[ \t]*$/', $line, $matches)
&& $matches[1][0] === $fence[0]
&& strlen($matches[1]) >= strlen($fence)) {
$codeClass = $fenceLanguage === null ? '' : ' class="language-' . $fenceLanguage . '"';
$blocks[] = '<pre class="overflow-x-auto rounded-box bg-base-200 p-4"><code' . $codeClass . '>' . $this->escape(implode("\n", $codeLines)) . '</code></pre>';
$fence = null;
$fenceLanguage = null;
$codeLines = [];
continue;
}
$codeLines[] = $line;
continue;
}
if (preg_match('/^ {0,3}(`{3,}|~{3,})(.*)$/', $line, $matches)) {
$flush();
$fence = $matches[1];
$info = trim($matches[2]);
$fenceLanguage = preg_match('/^([A-Za-z0-9][A-Za-z0-9_+-]*)(?:[ \t]+|$)/', $info, $languageMatches)
? $languageMatches[1]
: null;
$codeLines = [];
continue;
}
if (trim($line) === '') {
$flush();
continue;
}
if (preg_match('/^ {0,3}(#{1,6})[ \t]+(.+?)[ \t]*#*[ \t]*$/', $line, $matches)) {
$flush();
$level = strlen($matches[1]);
$class = [
1 => 'text-3xl font-bold tracking-tight',
2 => 'text-2xl font-bold tracking-tight',
3 => 'text-xl font-semibold',
4 => 'text-lg font-semibold',
5 => 'text-base font-semibold',
6 => 'text-sm font-semibold',
][$level];
$blocks[] = '<h' . $level . ' class="' . $class . '">' . $this->renderInline($matches[2]) . '</h' . $level . '>';
continue;
}
if (preg_match('/^ {0,3}(?:(?:\*[ \t]*){3,}|(?:-[ \t]*){3,}|(?:_[ \t]*){3,})$/', $line)) {
$flush();
$blocks[] = '<hr class="my-6 border-base-300">';
continue;
}
if (preg_match('/^ {0,3}> ?(.*)$/', $line, $matches)) {
if ($paragraph !== [] || $listType !== null) {
$flush();
}
$quote[] = $matches[1];
continue;
}
if ($quote !== []) {
$flush();
}
if (preg_match('/^ {0,3}[-*+]\s+(.+)$/', $line, $matches)) {
$type = 'ul';
} elseif (preg_match('/^ {0,3}\d+[.)]\s+(.+)$/', $line, $matches)) {
$type = 'ol';
} else {
if ($listType !== null) {
$flush();
}
$paragraph[] = $line;
continue;
}
if ($paragraph !== []) {
$flush();
} elseif ($listType !== null && $listType !== $type) {
$flush();
}
$listType = $type;
$listItems[] = $matches[1];
}
$flush();
if ($fence !== null) {
$codeClass = $fenceLanguage === null ? '' : ' class="language-' . $fenceLanguage . '"';
$blocks[] = '<pre class="overflow-x-auto rounded-box bg-base-200 p-4"><code' . $codeClass . '>' . $this->escape(implode("\n", $codeLines)) . '</code></pre>';
}
return implode("\n", $blocks);
}
private function renderInline(string $text): string
{
$parts = preg_split('/(`[^`\r\n]+`|!\[[^\]\r\n]*\]\([^\s)\r\n]+\)|\[[^\]\r\n]+\]\([^\s)\r\n]+\)|\*\*[^*\r\n]+\*\*|__[^_\r\n]+__|\*[^*\r\n]+\*|_[^_\r\n]+_)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE) ?: [$text];
$html = '';
foreach ($parts as $part) {
if ($part === '') {
continue;
}
if ($part[0] === '`') {
$html .= '<code>' . $this->escape(substr($part, 1, -1)) . '</code>';
} elseif (preg_match('/^!\[([^\]]*)\]\(([^)]+)\)$/', $part, $matches)) {
$altText = html_entity_decode($matches[1], ENT_QUOTES | ENT_HTML5, 'UTF-8');
$html .= $this->isSafeImageUrl($matches[2])
? '<img src="' . $this->escape($matches[2]) . '" alt="' . $this->escape($altText) . '" class="max-w-full rounded-box">'
: $this->escape($altText);
} elseif (preg_match('/^\[([^\]]+)\]\(([^)]+)\)$/', $part, $matches)) {
$html .= $this->isSafeLink($matches[2])
? '<a class="link link-hover" href="' . $this->escape($matches[2]) . '">' . $this->renderInline($matches[1]) . '</a>'
: $this->renderInline($matches[1]);
} elseif (str_starts_with($part, '**') || str_starts_with($part, '__')) {
$html .= '<strong>' . $this->renderInline(substr($part, 2, -2)) . '</strong>';
} elseif ($part[0] === '*' || $part[0] === '_') {
$html .= '<em>' . $this->renderInline(substr($part, 1, -1)) . '</em>';
} else {
$html .= $this->escape($part);
}
}
return $html;
}
private function isSafeLink(string $url): bool
{
return $this->isSafeUrl($url, ['http', 'https', 'mailto']);
}
private function isSafeImageUrl(string $url): bool
{
return $this->isSafeUrl($url, ['http', 'https']);
}
private function isSafeUrl(string $url, array $allowedSchemes): bool
{
$decodedUrl = html_entity_decode($url, ENT_QUOTES | ENT_HTML5, 'UTF-8');
if ($decodedUrl === '' || preg_match('/[\x00-\x20\x7f]/', $decodedUrl)) {
return false;
}
if (preg_match('/^([a-z][a-z0-9+.-]*):/i', $decodedUrl, $matches)) {
return in_array(strtolower($matches[1]), $allowedSchemes, true);
}
return true;
}
private function escape(string $text): string
{
return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
}