v2.0.0.8
Publisium
- <?php
-
- declare(strict_types=1);
-
- require_once __DIR__ . '/language.php';
-
- final class BlockEditor
- {
- private const ALLOWED_TYPES = [
- 'paragraph',
- 'heading2',
- 'heading3',
- 'image',
- 'video',
- 'quote',
- 'list',
- 'code',
- 'table',
- 'checklist',
- 'callout',
- 'separator',
- 'embed',
- 'contact_form',
- ];
-
- public const HOME_SYSTEM_TYPES = [
- 'home_featured',
- 'home_articles',
- ];
-
- public static function sanitize(string $rawJson, bool $allowContactForm = false): string
- {
- return json_encode(['blocks' => self::cleanBlocks($rawJson, $allowContactForm, [])], JSON_UNESCAPED_UNICODE);
- }
-
- public static function sanitizeHomepage(string $rawJson): string
- {
- $blocks = self::cleanBlocks($rawJson, true, self::HOME_SYSTEM_TYPES);
- $presentTypes = array_column($blocks, 'type');
-
- foreach (self::HOME_SYSTEM_TYPES as $systemType) {
- if (!in_array($systemType, $presentTypes, true)) {
- $blocks[] = ['id' => 'sys_' . $systemType, 'type' => $systemType, 'data' => []];
- }
- }
-
- return json_encode(['blocks' => $blocks], JSON_UNESCAPED_UNICODE);
- }
-
- public static function homepageBlocks(array $settings): array
- {
- $decoded = json_decode(self::sanitizeHomepage((string) ($settings['homepage_blocks'] ?? '')), true);
-
- return is_array($decoded['blocks'] ?? null) ? $decoded['blocks'] : [];
- }
-
- private static function cleanBlocks(string $rawJson, bool $allowContactForm, array $systemTypes): array
- {
- $decoded = json_decode($rawJson, true);
-
- if (!is_array($decoded) || !isset($decoded['blocks']) || !is_array($decoded['blocks'])) {
- return [];
- }
-
- $cleanBlocks = [];
- $hasContactForm = false;
- $seenSystemTypes = [];
-
- foreach ($decoded['blocks'] as $block) {
- if (!is_array($block) || !isset($block['type']) || !is_string($block['type'])) {
- continue;
- }
-
- if (in_array($block['type'], $systemTypes, true)) {
- if (isset($seenSystemTypes[$block['type']])) {
- continue;
- }
- $seenSystemTypes[$block['type']] = true;
- $cleanBlocks[] = ['id' => 'sys_' . $block['type'], 'type' => $block['type'], 'data' => []];
- continue;
- }
-
- if (!in_array($block['type'], self::ALLOWED_TYPES, true)) {
- continue;
- }
-
- if ($block['type'] === 'contact_form') {
- if (!$allowContactForm || $hasContactForm) {
- continue;
- }
- $hasContactForm = true;
- }
-
- $data = is_array($block['data'] ?? null) ? $block['data'] : [];
-
- $cleanBlocks[] = [
- 'id' => is_string($block['id'] ?? null) ? substr($block['id'], 0, 40) : bin2hex(random_bytes(8)),
- 'type' => $block['type'],
- 'data' => self::sanitizeBlockData($block['type'], $data),
- ];
- }
-
- return $cleanBlocks;
- }
-
- private static function sanitizeBlockData(string $type, array $data): array
- {
- return match ($type) {
- 'paragraph', 'quote' => [
- 'text' => self::cleanHtml((string) ($data['text'] ?? '')),
- ],
- 'heading2', 'heading3' => [
- 'text' => strip_tags((string) ($data['text'] ?? '')),
- ],
- 'image' => [
- 'src' => self::cleanUrl((string) ($data['src'] ?? '')),
- 'alt' => strip_tags((string) ($data['alt'] ?? '')),
- 'caption' => strip_tags((string) ($data['caption'] ?? '')),
- ],
- 'video' => [
- 'src' => self::cleanUrl((string) ($data['src'] ?? '')),
- 'caption' => strip_tags((string) ($data['caption'] ?? '')),
- ],
- 'list' => [
- 'style' => in_array($data['style'] ?? 'unordered', ['ordered', 'unordered'], true) ? $data['style'] : 'unordered',
- 'items' => array_map(
- static fn($item) => strip_tags((string) $item),
- is_array($data['items'] ?? null) ? $data['items'] : []
- ),
- ],
- 'code' => [
- 'language' => preg_replace('/[^a-zA-Z0-9_+-]/', '', (string) ($data['language'] ?? 'text')),
- 'code' => (string) ($data['code'] ?? ''),
- ],
- 'table' => [
- 'rows' => self::sanitizeTableRows(is_array($data['rows'] ?? null) ? $data['rows'] : []),
- ],
- 'checklist' => [
- 'items' => self::sanitizeChecklistItems(is_array($data['items'] ?? null) ? $data['items'] : []),
- ],
- 'callout' => [
- 'style' => in_array($data['style'] ?? 'info', ['info', 'warning', 'success', 'danger'], true) ? $data['style'] : 'info',
- 'text' => strip_tags((string) ($data['text'] ?? '')),
- ],
- 'embed' => [
- 'url' => self::cleanUrl((string) ($data['url'] ?? '')),
- ],
- 'separator', 'contact_form' => [],
- default => [],
- };
- }
-
- private static function sanitizeTableRows(array $rows): array
- {
- $clean = [];
- foreach ($rows as $row) {
- if (!is_array($row)) {
- continue;
- }
- $clean[] = array_map(static fn($cell) => strip_tags((string) $cell), $row);
- }
-
- return $clean;
- }
-
- private static function sanitizeChecklistItems(array $items): array
- {
- $clean = [];
- foreach ($items as $item) {
- if (!is_array($item)) {
- continue;
- }
- $clean[] = [
- 'text' => strip_tags((string) ($item['text'] ?? '')),
- 'checked' => (bool) ($item['checked'] ?? false),
- ];
- }
-
- return $clean;
- }
-
- private static function cleanUrl(string $url): string
- {
- $url = trim($url);
- if ($url === '') {
- return '';
- }
-
- if (str_starts_with($url, 'https://') || str_starts_with($url, 'http://')) {
- return filter_var($url, FILTER_SANITIZE_URL) ?: '';
- }
-
- if (preg_match('#^[a-zA-Z][a-zA-Z0-9+.-]*:#', $url) === 1) {
- return '';
- }
-
- if (str_starts_with($url, '//')) {
- return '';
- }
-
- $url = ltrim($url, '/');
-
- return filter_var($url, FILTER_SANITIZE_URL) ?: '';
- }
-
- private static function cleanHtml(string $text): string
- {
- if (trim($text) === '') {
- return '';
- }
-
- if (!class_exists(\DOMDocument::class)) {
- return strip_tags($text, '<b><strong><i><em><a><br><u><s><code><ul><ol><li>');
- }
-
- $allowedTags = ['b', 'strong', 'i', 'em', 'u', 's', 'code', 'a', 'span', 'br', 'ul', 'ol', 'li'];
- $allowedColors = '/^#[0-9a-fA-F]{3}([0-9a-fA-F]{3})?$/';
-
- $wrapped = '<?xml encoding="utf-8"?><div>' . $text . '</div>';
-
- $previous = libxml_use_internal_errors(true);
- $dom = new \DOMDocument();
- $dom->loadHTML($wrapped, LIBXML_NOERROR | LIBXML_NOWARNING | LIBXML_NOBLANKS);
- libxml_clear_errors();
- libxml_use_internal_errors($previous);
-
- $root = $dom->getElementsByTagName('div')->item(0);
- if ($root === null) {
- return '';
- }
-
- self::sanitizeNode($dom, $root, $allowedTags, $allowedColors);
-
- $html = '';
- foreach (iterator_to_array($root->childNodes) as $child) {
- $html .= $dom->saveHTML($child);
- }
-
- return self::decodeTextEntities($html);
- }
-
- private static function decodeTextEntities(string $html): string
- {
- return (string) preg_replace_callback('/&(#[0-9]+|#x[0-9a-fA-F]+|[a-zA-Z][a-zA-Z0-9]*);/', static function (array $match): string {
- $char = html_entity_decode($match[0], ENT_QUOTES | ENT_HTML5, 'UTF-8');
- if ($char === $match[0] || $char === "\u{00A0}" || mb_strlen($char, 'UTF-8') !== 1 || ord($char[0]) < 128) {
- return $match[0];
- }
-
- return $char;
- }, $html);
- }
-
- private static function sanitizeNode(\DOMDocument $dom, \DOMNode $node, array $allowedTags, string $allowedColors): void
- {
- $children = iterator_to_array($node->childNodes);
-
- foreach ($children as $child) {
- if ($child instanceof \DOMText) {
- continue;
- }
-
- if (!$child instanceof \DOMElement) {
- $node->removeChild($child);
- continue;
- }
-
- $tag = strtolower($child->tagName);
- $parentTag = $node instanceof \DOMElement ? strtolower($node->tagName) : '';
- $misplacedItem = $tag === 'li' && !in_array($parentTag, ['ul', 'ol'], true);
-
- if ($misplacedItem || !in_array($tag, $allowedTags, true)) {
- $previousSibling = $child->previousSibling;
- if (in_array($tag, ['div', 'p', 'li'], true) && $previousSibling !== null
- && !($previousSibling instanceof \DOMElement && in_array(strtolower($previousSibling->tagName), ['br', 'ul', 'ol'], true))) {
- $node->insertBefore($dom->createElement('br'), $child);
- }
- while ($child->firstChild) {
- $node->insertBefore($child->firstChild, $child);
- }
- $node->removeChild($child);
- self::sanitizeNode($dom, $node, $allowedTags, $allowedColors);
- return;
- }
-
- self::sanitizeAttributes($child, $tag, $allowedColors);
- self::sanitizeNode($dom, $child, $allowedTags, $allowedColors);
- }
- }
-
- private static function sanitizeAttributes(\DOMElement $element, string $tag, string $allowedColors): void
- {
- $keep = [];
-
- if ($tag === 'a') {
- $href = self::cleanUrl((string) $element->getAttribute('href'));
- if ($href !== '') {
- $keep['href'] = $href;
- if ($element->getAttribute('target') === '_blank') {
- $keep['target'] = '_blank';
- $keep['rel'] = 'noopener noreferrer';
- }
- }
- }
-
- if ($tag === 'span') {
- $color = self::extractColor((string) $element->getAttribute('style'), $allowedColors);
- if ($color !== '') {
- $keep['style'] = 'color:' . $color;
- }
- }
-
- foreach (iterator_to_array($element->attributes ?? []) as $attribute) {
- $element->removeAttribute($attribute->name);
- }
-
- foreach ($keep as $name => $value) {
- $element->setAttribute($name, $value);
- }
- }
-
- private static function extractColor(string $style, string $allowedColors): string
- {
- if (preg_match('/color\s*:\s*(#[0-9a-fA-F]{3,6})/', $style, $matches) !== 1) {
- return '';
- }
-
- $color = $matches[1];
-
- return preg_match($allowedColors, $color) === 1 ? $color : '';
- }
-
- public static function readingTimeMinutes(string $blocksJson): int
- {
- $decoded = json_decode($blocksJson, true);
- if (!is_array($decoded) || !isset($decoded['blocks'])) {
- return 1;
- }
-
- $wordCount = 0;
- foreach ($decoded['blocks'] as $block) {
- $wordCount += self::blockWordCount(is_array($block) ? $block : []);
- }
-
- return max(1, (int) ceil($wordCount / 200));
- }
-
- private static function blockWordCount(array $block): int
- {
- $type = $block['type'] ?? '';
- $data = is_array($block['data'] ?? null) ? $block['data'] : [];
-
- if ($type === 'table') {
- $cells = [];
- foreach ($data['rows'] ?? [] as $row) {
- foreach (is_array($row) ? $row : [] as $cell) {
- $cells[] = (string) $cell;
- }
- }
- $text = implode(' ', $cells);
- } else {
- $text = match ($type) {
- 'paragraph', 'quote', 'heading2', 'heading3', 'callout' => strip_tags((string) ($data['text'] ?? '')),
- 'list' => implode(' ', array_map('strval', $data['items'] ?? [])),
- 'checklist' => implode(' ', array_map(static fn($item) => (string) ($item['text'] ?? ''), $data['items'] ?? [])),
- default => '',
- };
- }
-
- $text = trim($text);
- if ($text === '') {
- return 0;
- }
-
- return count(preg_split('/\s+/', $text));
- }
-
- public static function render(string $blocksJson): string
- {
- $decoded = json_decode($blocksJson, true);
- if (!is_array($decoded) || !isset($decoded['blocks'])) {
- return '';
- }
-
- $html = '';
- foreach ($decoded['blocks'] as $block) {
- $html .= self::renderBlock($block);
- }
-
- return $html;
- }
-
- // Renders the blocks and puts $insertHtml halfway through (only when there are at least 3 blocks).
- public static function renderWithMiddle(string $blocksJson, string $insertHtml): string
- {
- $decoded = json_decode($blocksJson, true);
- if (!is_array($decoded) || !isset($decoded['blocks']) || !is_array($decoded['blocks'])) {
- return '';
- }
-
- $parts = [];
- foreach ($decoded['blocks'] as $block) {
- $blockHtml = self::renderBlock(is_array($block) ? $block : []);
- if ($blockHtml !== '') {
- $parts[] = $blockHtml;
- }
- }
-
- if ($insertHtml !== '' && count($parts) >= 3) {
- array_splice($parts, intdiv(count($parts), 2), 0, [$insertHtml]);
- }
-
- return implode('', $parts);
- }
-
- private static function renderBlock(array $block): string
- {
- $type = $block['type'] ?? '';
- $data = $block['data'] ?? [];
-
- return match ($type) {
- 'paragraph' => self::renderParagraph((string) ($data['text'] ?? '')),
- 'quote' => '<blockquote>' . ($data['text'] ?? '') . '</blockquote>',
- 'heading2' => '<h2>' . htmlspecialchars((string) ($data['text'] ?? '')) . '</h2>',
- 'heading3' => '<h3>' . htmlspecialchars((string) ($data['text'] ?? '')) . '</h3>',
- 'image' => '<figure><img src="' . htmlspecialchars((string) ($data['src'] ?? '')) . '" alt="' . htmlspecialchars((string) ($data['alt'] ?? '')) . '">' .
- (($data['caption'] ?? '') !== '' ? '<figcaption>' . htmlspecialchars((string) $data['caption']) . '</figcaption>' : '') . '</figure>',
- 'video' => '<figure>' . self::renderVideo((string) ($data['src'] ?? '')) .
- (($data['caption'] ?? '') !== '' ? '<figcaption>' . htmlspecialchars((string) $data['caption']) . '</figcaption>' : '') . '</figure>',
- 'list' => self::renderList($data),
- 'code' => self::renderCode($data),
- 'table' => self::renderTable($data),
- 'checklist' => self::renderChecklist($data),
- 'callout' => '<div class="callout callout-' . htmlspecialchars((string) ($data['style'] ?? 'info')) . '">' .
- htmlspecialchars((string) ($data['text'] ?? '')) . '</div>',
- 'embed' => self::renderEmbed((string) ($data['url'] ?? '')),
- 'separator' => '<hr>',
- 'contact_form' => self::renderContactForm(),
- default => '',
- };
- }
-
- private static function renderVideo(string $src): string
- {
- $embed = self::embedInfo($src);
- if ($embed !== null) {
- return self::embedFrame($embed);
- }
-
- return '<video controls playsinline preload="metadata" src="' . htmlspecialchars($src) . '"></video>';
- }
-
- private static function renderEmbed(string $url): string
- {
- $embed = self::embedInfo($url) ?? ['src' => $url, 'kind' => 'wide'];
-
- return self::embedFrame($embed);
- }
-
- private static function embedFrame(array $embed): string
- {
- return '<div class="embed-wrapper embed-' . htmlspecialchars($embed['kind']) . '"><iframe src="' . htmlspecialchars($embed['src']) . '" loading="lazy" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen referrerpolicy="strict-origin-when-cross-origin"></iframe></div>';
- }
-
- public static function embedInfo(string $url): ?array
- {
- $url = trim($url);
- if (!preg_match('#^https?://#i', $url)) {
- return null;
- }
- $host = strtolower((string) parse_url($url, PHP_URL_HOST));
- $host = preg_replace('/^(www\.|m\.|mobile\.)/', '', $host);
- $path = (string) parse_url($url, PHP_URL_PATH);
- parse_str((string) parse_url($url, PHP_URL_QUERY), $query);
-
- if (in_array($host, ['youtube.com', 'youtube-nocookie.com', 'music.youtube.com'], true)) {
- $id = '';
- if (isset($query['v'])) {
- $id = (string) $query['v'];
- } elseif (preg_match('#^/(?:embed|shorts|live|v)/([\w-]{6,})#', $path, $m)) {
- $id = $m[1];
- }
- if ($id !== '' && preg_match('/^[\w-]+$/', $id)) {
- return ['src' => 'https://www.youtube-nocookie.com/embed/' . $id, 'kind' => str_contains($path, '/shorts/') ? 'tall' : 'wide'];
- }
- return null;
- }
- if ($host === 'youtu.be' && preg_match('#^/([\w-]{6,})#', $path, $m)) {
- return ['src' => 'https://www.youtube-nocookie.com/embed/' . $m[1], 'kind' => 'wide'];
- }
- if (in_array($host, ['vimeo.com', 'player.vimeo.com'], true) && preg_match('#/(\d+)#', $path, $m)) {
- return ['src' => 'https://player.vimeo.com/video/' . $m[1], 'kind' => 'wide'];
- }
- if (in_array($host, ['x.com', 'twitter.com'], true) && preg_match('#/status(?:es)?/(\d+)#', $path, $m)) {
- return ['src' => 'https://platform.twitter.com/embed/Tweet.html?id=' . $m[1] . '&dnt=true', 'kind' => 'post'];
- }
- if (in_array($host, ['facebook.com', 'fb.watch', 'web.facebook.com'], true)) {
- $isVideo = $host === 'fb.watch' || preg_match('#/(videos|watch|reel|share/v|share/r)#', $path . '?' . http_build_query($query));
- $plugin = $isVideo ? 'video.php' : 'post.php';
- return ['src' => 'https://www.facebook.com/plugins/' . $plugin . '?show_text=false&href=' . rawurlencode($url), 'kind' => $isVideo && !str_contains($path, '/reel') ? 'wide' : 'post'];
- }
- if ($host === 'instagram.com' && preg_match('#^/(p|reel|reels|tv)/([\w-]+)#', $path, $m)) {
- return ['src' => 'https://www.instagram.com/' . ($m[1] === 'reels' ? 'reel' : $m[1]) . '/' . $m[2] . '/embed', 'kind' => 'tall'];
- }
- if ($host === 'tiktok.com' && preg_match('#/video/(\d+)#', $path, $m)) {
- return ['src' => 'https://www.tiktok.com/embed/v2/' . $m[1], 'kind' => 'tall'];
- }
- if (in_array($host, ['dailymotion.com', 'dai.ly'], true) && preg_match('#^/(?:video/)?([a-zA-Z0-9]+)#', $path, $m)) {
- return ['src' => 'https://www.dailymotion.com/embed/video/' . $m[1], 'kind' => 'wide'];
- }
- if ($host === 'twitch.tv' && preg_match('#^/videos/(\d+)#', $path, $m)) {
- return ['src' => 'https://player.twitch.tv/?video=' . $m[1] . '&parent=' . rawurlencode((string) ($_SERVER['HTTP_HOST'] ?? 'localhost')), 'kind' => 'wide'];
- }
- if ($host === 'open.spotify.com' && preg_match('#^/(track|album|playlist|episode|show)/(\w+)#', $path, $m)) {
- return ['src' => 'https://open.spotify.com/embed/' . $m[1] . '/' . $m[2], 'kind' => 'audio'];
- }
- if ($host === 'soundcloud.com') {
- return ['src' => 'https://w.soundcloud.com/player/?url=' . rawurlencode($url), 'kind' => 'audio'];
- }
- if ($host === 'streamable.com' && preg_match('#^/(?:e/)?(\w+)#', $path, $m)) {
- return ['src' => 'https://streamable.com/e/' . $m[1], 'kind' => 'wide'];
- }
-
- return null;
- }
-
- private static function renderContactForm(): string
- {
- require_once __DIR__ . '/contact.php';
-
- return ContactForm::renderBlock();
- }
-
- private static function renderCode(array $data): string
- {
- $language = preg_replace('/[^a-z0-9+#-]/', '', strtolower((string) ($data['language'] ?? 'text'))) ?: 'text';
- $copyLabel = htmlspecialchars(Language::get('code_copy', 'Copy'), ENT_QUOTES);
- $copiedLabel = htmlspecialchars(Language::get('code_copied', 'Copied'), ENT_QUOTES);
-
- return '<div class="code-block">' .
- '<button type="button" class="code-copy" data-label="' . $copyLabel . '" data-copied="' . $copiedLabel . '">' . $copyLabel . '</button>' .
- '<pre><code class="language-' . $language . '">' . htmlspecialchars((string) ($data['code'] ?? '')) . '</code></pre>' .
- '</div>';
- }
-
- private static function renderParagraph(string $html): string
- {
- if (stripos($html, '<ul') === false && stripos($html, '<ol') === false) {
- return '<p>' . $html . '</p>';
- }
-
- if (!class_exists(\DOMDocument::class)) {
- return '<div class="paragraph-group">' . $html . '</div>';
- }
-
- $previous = libxml_use_internal_errors(true);
- $dom = new \DOMDocument();
- $dom->loadHTML('<?xml encoding="utf-8"?><div>' . $html . '</div>', LIBXML_NOERROR | LIBXML_NOWARNING);
- libxml_clear_errors();
- libxml_use_internal_errors($previous);
-
- $root = $dom->getElementsByTagName('div')->item(0);
- if ($root === null) {
- return '<p>' . $html . '</p>';
- }
-
- $parts = [];
- $buffer = '';
- $flush = static function () use (&$buffer, &$parts): void {
- $trimmed = preg_replace('#^(\s|<br\s*/?>)+|(\s|<br\s*/?>)+$#i', '', $buffer);
- if ($trimmed !== null && trim(strip_tags($trimmed)) !== '') {
- $parts[] = '<p>' . $trimmed . '</p>';
- }
- $buffer = '';
- };
-
- foreach (iterator_to_array($root->childNodes) as $child) {
- $outer = (string) $dom->saveHTML($child);
- if ($child instanceof \DOMElement && in_array(strtolower($child->tagName), ['ul', 'ol'], true)) {
- $flush();
- $parts[] = $outer;
- continue;
- }
- $buffer .= $outer;
- }
- $flush();
-
- return self::decodeTextEntities(implode('', $parts));
- }
-
- private static function renderList(array $data): string
- {
- $tag = ($data['style'] ?? 'unordered') === 'ordered' ? 'ol' : 'ul';
- $items = '';
- foreach ($data['items'] ?? [] as $item) {
- if (trim((string) $item) === '') {
- continue;
- }
- $items .= '<li>' . htmlspecialchars((string) $item) . '</li>';
- }
- return $items === '' ? '' : '<' . $tag . '>' . $items . '</' . $tag . '>';
- }
-
- private static function renderTable(array $data): string
- {
- $rows = '';
- foreach ($data['rows'] ?? [] as $row) {
- $cells = '';
- foreach ($row as $cell) {
- $cells .= '<td>' . htmlspecialchars((string) $cell) . '</td>';
- }
- $rows .= '<tr>' . $cells . '</tr>';
- }
- return '<table><tbody>' . $rows . '</tbody></table>';
- }
-
- private static function renderChecklist(array $data): string
- {
- $items = '';
- foreach ($data['items'] ?? [] as $item) {
- $checked = !empty($item['checked']) ? 'checked disabled' : 'disabled';
- $items .= '<li><input type="checkbox" ' . $checked . '> ' . htmlspecialchars((string) ($item['text'] ?? '')) . '</li>';
- }
- return '<ul class="checklist">' . $items . '</ul>';
- }
- }
-