220 lines
9.2 KiB
PHP
220 lines
9.2 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', 'aria-label'], 'article' => [], 'audio' => ['src', 'controls', 'preload'], 'b' => [], 'blockquote' => [], 'br' => [],
|
|
'button' => ['aria-expanded', 'aria-controls', 'hidden'], 'caption' => [], 'code' => [], 'dd' => [], 'details' => [], 'div' => ['role', 'aria-label', 'tabindex'],
|
|
'dl' => [], 'dt' => [], 'em' => [], 'figure' => [], 'figcaption' => [], 'footer' => [],
|
|
'h1' => [], 'h2' => [], 'h3' => [], 'h4' => [], 'h5' => [], 'h6' => [], 'header' => [], 'hr' => [], 'i' => [],
|
|
'img' => ['src', 'alt', 'loading', 'width', 'height'], 'label' => ['for'],
|
|
'li' => [], 'nav' => ['aria-label'], 'ol' => [], 'p' => [], 'pre' => [], 'progress' => ['max', 'value'], 's' => [],
|
|
'section' => ['aria-labelledby'], '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) {
|
|
self::scopeIds($body, $anchorPrefix);
|
|
}
|
|
|
|
return self::bodyMarkup($body);
|
|
}
|
|
|
|
public static function sharedFragment(string $html, string $scope, string $account, ?string $path = 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::scopeIds($body, $scope);
|
|
if ($path !== null) {
|
|
foreach ($body->getElementsByTagName('nav') as $nav) {
|
|
if (!in_array('primary-nav', preg_split('/\s+/', $nav->getAttribute('class')), true)) {
|
|
continue;
|
|
}
|
|
foreach ($nav->getElementsByTagName('a') as $link) {
|
|
if ($link->getAttribute('href') === $path) {
|
|
$link->setAttribute('aria-current', 'page');
|
|
}
|
|
}
|
|
}
|
|
}
|
|
foreach (iterator_to_array($body->getElementsByTagName('a')) as $node) {
|
|
if (!in_array('studio-member-slot', preg_split('/\s+/', $node->getAttribute('class')), true)) {
|
|
continue;
|
|
}
|
|
if ($account !== '') {
|
|
$fragment = new DOMDocument('1.0', 'UTF-8');
|
|
$fragment->loadHTML('<!doctype html><html><head><meta charset="UTF-8"></head><body>' . $account . '</body></html>', LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NONET);
|
|
$replacement = $fragment->getElementsByTagName('a')->item(0);
|
|
$node->parentNode->replaceChild($document->importNode($replacement, true), $node);
|
|
} else {
|
|
$node->parentNode->removeChild($node);
|
|
}
|
|
}
|
|
|
|
return self::bodyMarkup($body);
|
|
}
|
|
|
|
private static function scopeIds(DOMElement $body, string $prefix): void
|
|
{
|
|
$ids = [];
|
|
foreach ($body->getElementsByTagName('*') as $element) {
|
|
$id = $element->getAttribute('id');
|
|
if ($id !== '') {
|
|
$ids[$id] = $prefix . '-' . $id;
|
|
$element->setAttribute('id', $ids[$id]);
|
|
}
|
|
}
|
|
foreach ($body->getElementsByTagName('*') as $element) {
|
|
$href = $element->getAttribute('href');
|
|
if (str_starts_with($href, '#') && isset($ids[substr($href, 1)])) {
|
|
$element->setAttribute('href', '#' . $ids[substr($href, 1)]);
|
|
}
|
|
foreach (['for', 'aria-labelledby', 'aria-controls'] as $attribute) {
|
|
if ($element->hasAttribute($attribute)) {
|
|
$tokens = preg_split('/\s+/', $element->getAttribute($attribute));
|
|
$element->setAttribute($attribute, implode(' ', array_map(static fn ($id) => $ids[$id] ?? $id, $tokens)));
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
private static function bodyMarkup(DOMElement $body): string
|
|
{
|
|
$output = '';
|
|
foreach ($body->childNodes as $child) {
|
|
$output .= $body->ownerDocument->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');
|
|
}
|
|
}
|
|
if ($element->tagName === 'button') {
|
|
$element->setAttribute('type', 'button');
|
|
}
|
|
self::sanitizeChildren($element);
|
|
}
|
|
}
|
|
}
|