Files
laysense.cn/app/Content/Html.php
T

161 lines
6.4 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Content;
use DOMDocument;
use DOMElement;
use DOMNode;
use League\CommonMark\GithubFlavoredMarkdownConverter;
use RuntimeException;
final class Html
{
public const ALIGNMENTS = ['left', 'center', 'right'];
private const TAGS = [
'a' => ['href', 'target', 'rel'], 'article' => [], 'audio' => ['src', 'controls', 'preload'], 'b' => [], 'blockquote' => [], 'br' => [],
'caption' => [], 'code' => [], 'dd' => [], 'details' => [], 'div' => ['role', 'aria-label', 'tabindex'],
'dl' => [], 'dt' => [], 'em' => [], 'h1' => [], 'h2' => [], 'h3' => [], 'h4' => [], 'h5' => [], 'h6' => [], 'hr' => [], 'i' => [],
'img' => ['src', 'alt', 'loading', 'width', 'height'], 'label' => ['for'],
'li' => [], 'ol' => [], 'p' => [], 'pre' => [], 'progress' => ['max', 'value'], 's' => [],
'small' => [], 'source' => ['src', 'type'], 'span' => [], 'strong' => [], 'summary' => [],
'table' => [], 'tbody' => [], 'td' => ['colspan', 'rowspan'], 'tfoot' => [],
'th' => ['scope', 'colspan', 'rowspan'], 'thead' => [], 'tr' => [], 'ul' => [],
'video' => ['src', 'controls', 'muted', 'playsinline', 'poster', 'preload'],
];
public static function url(string $value, bool $media = false): bool
{
if ($value === '' || preg_match('/[\x00-\x20\x7f\\\\]/', $value)) {
return false;
}
if (str_starts_with($value, '/')) {
return !str_starts_with($value, '//');
}
if (str_starts_with($value, '#')) {
return !$media && strlen($value) > 1;
}
$scheme = strtolower((string) parse_url($value, PHP_URL_SCHEME));
return in_array($scheme, $media ? ['https'] : ['https', 'http', 'mailto', 'tel'], true);
}
public static function markdown(string $text): string
{
static $converter;
$converter ??= new GithubFlavoredMarkdownConverter(['html_input' => 'strip', 'allow_unsafe_links' => false, 'max_nesting_level' => 30]);
$html = $converter->convert($text)->getContent();
return str_replace(['<h1>', '</h1>'], ['<h2>', '</h2>'], $html);
}
public static function articleBody(array $article): string
{
return $article['body_format'] === 'html' ? self::sanitize($article['body']) : self::markdown($article['body']);
}
public static function applyCanvasEdits(string $body, array $edits): string
{
if (!array_is_list($edits) || count($edits) > 512) {
throw new RuntimeException('正文增量无效。');
}
$size = strlen($body);
$cursor = 0;
$result = '';
foreach ($edits as $edit) {
if (!is_array($edit) || !array_is_list($edit) || count($edit) !== 3) {
throw new RuntimeException('正文增量无效。');
}
[$offset, $remove, $insert] = $edit;
if (!is_int($offset) || !is_int($remove) || !is_string($insert)
|| $offset < $cursor || $offset > $size || $remove < 0 || $remove > $size - $offset) {
throw new RuntimeException('正文增量无效。');
}
$result .= substr($body, $cursor, $offset - $cursor) . $insert;
$cursor = $offset + $remove;
if (strlen($result) > 300000) {
throw new RuntimeException('正文太长。');
}
}
$result .= substr($body, $cursor);
if (strlen($result) > 300000 || !mb_check_encoding($result, 'UTF-8')) {
throw new RuntimeException('正文太长或编码无效。');
}
return $result;
}
public static function sanitize(string $html, ?string $anchorPrefix = null): string
{
$document = new DOMDocument('1.0', 'UTF-8');
$document->loadHTML('<!DOCTYPE html><html><head><meta charset="UTF-8"></head><body>' . $html . '</body></html>', LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
$body = $document->getElementsByTagName('body')->item(0);
if (!$body) {
return '';
}
self::sanitizeChildren($body);
if ($anchorPrefix !== null) {
$ids = [];
foreach ($body->getElementsByTagName('*') as $element) {
$id = $element->getAttribute('id');
if ($id !== '') {
$ids[$id] = $anchorPrefix . '-' . $id;
$element->setAttribute('id', $ids[$id]);
}
}
foreach ($body->getElementsByTagName('a') as $link) {
$href = $link->getAttribute('href');
if (str_starts_with($href, '#') && isset($ids[substr($href, 1)])) {
$link->setAttribute('href', '#' . $ids[substr($href, 1)]);
}
}
}
$output = '';
foreach ($body->childNodes as $child) {
$output .= $document->saveHTML($child);
}
return trim($output);
}
private static function sanitizeChildren(DOMNode $parent): void
{
foreach (iterator_to_array($parent->childNodes) as $element) {
if ($element->nodeType === XML_COMMENT_NODE) {
$parent->removeChild($element);
continue;
}
if (!$element instanceof DOMElement) {
continue;
}
if (!array_key_exists($element->tagName, self::TAGS)) {
$parent->removeChild($element);
continue;
}
$allowed = [...self::TAGS[$element->tagName], 'class', 'id'];
foreach (iterator_to_array($element->attributes) as $attribute) {
$name = $attribute->name;
$value = $attribute->value;
if (!in_array($name, $allowed, true)
|| ($name === 'href' && !self::url($value))
|| (in_array($name, ['src', 'poster'], true) && !self::url($value, true))
|| ($name === 'target' && $value !== '_blank')
|| ($name === 'tabindex' && $value !== '0')) {
$element->removeAttribute($name);
}
}
if ($element->tagName === 'a') {
if ($element->getAttribute('target') === '_blank') {
$element->setAttribute('rel', 'noopener noreferrer');
} else {
$element->removeAttribute('rel');
}
}
self::sanitizeChildren($element);
}
}
}